@devries-cameron20 / t3code-1 / commits / cf84fc7772
Fork 0

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

perf(mobile): thread composer, route screen and queue control compile with the React Compiler (#21142)

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

Julius Marminge committed Oct 18, 2026 at 14:33 UTC cf84fc7772b02cb90f953f37c01aee99e01d7a42
5 files changed +747 -998
apps/mobile/src/features/threads/ThreadComposer.tsx
+104 -164
@@ -2,6 +2,8 @@ import * as Dialog from "../../components/ui/Dialog";
2 import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
3 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
4 import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
5 +import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6 +import { AsyncResult } from "effect/reactivity";
7 import { useAtomValue } from "@effect/atom-react";
8 import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
9 import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste";
@@ -24,16 +26,7 @@ import {
26 } from "@t3tools/shared/usageLimits";
27 import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
28 import type { ReactNode } from "react";
27 -import {
28 - memo,
29 - useCallback,
30 - useEffect,
31 - useLayoutEffect,
32 - useMemo,
33 - useRef,
34 - useState,
35 - type RefObject,
36 -} from "react";
29 +import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
30 import { Keyboard, Platform, Pressable, View, type ViewStyle } from "react-native";
31 import { composerImageGallery } from "../../lib/composerImageGallery";
32 import { filePreviewGallery } from "../../lib/filePreviewGallery";
@@ -332,7 +325,7 @@ export function ComposerSurface(props: {
325 );
326 }
327
335 -export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
328 +export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) {
329 const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
330 const { themeVariables: materialTheme } = useAppearancePreferences();
331 const composerPanel = materialTheme["--color-composer-panel"];
@@ -361,10 +354,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
354 props.draftMessage.trim().length > 0 ||
355 props.draftAttachments.length > 0 ||
356 (queuedEdit?.existingAttachments.length ?? 0) > 0;
364 - const stripAttachments = useMemo(
365 - () => composerStripAttachments(props.draftAttachments),
366 - [props.draftAttachments],
367 - );
357 + const stripAttachments = composerStripAttachments(props.draftAttachments);
358 const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
359
360 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
@@ -394,14 +384,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
384 currentModelSelection,
385 props.selectedThread.projectId,
386 );
397 - const selectedProviderStatus = useMemo(() => {
387 + const selectedProviderStatus = (() => {
388 if (!props.serverConfig) return null;
389 return (
390 props.serverConfig.providers.find(
391 (p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
392 ) ?? null
393 );
404 - }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
394 + })();
395 const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
396 const composerDraftKey = props.draftKey ?? composerOwnerKey;
397 const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
@@ -424,7 +414,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
414 props.serverConfig?.providers ?? [],
415 props.serverConfig?.usageLimitSources ?? [],
416 );
427 - const openUsageLimits = useCallback(() => {
417 + const openUsageLimits = () => {
418 const report = collectProviderUsageLimits(
419 currentModelSelection.instanceId,
420 props.serverConfig?.providers ?? [],
@@ -436,7 +426,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
426 Dialog.alert("Usage limits unavailable", "This provider does not currently report limits.");
427 }
428 return report !== null;
439 - }, [currentModelSelection.instanceId, onShowUsageLimits, props.serverConfig]);
429 + };
430
431 const composerMenu = useComposerCommandMenu({
432 draftMessage: props.draftMessage,
@@ -504,22 +494,19 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
494 onExpandedChange?.(isExpanded);
495 }, [isExpanded, onExpandedChange]);
496
507 - const onPressPreview = useCallback(
508 - (source: FilePreviewSource) => {
509 - wasExpandedBeforePreviewRef.current = isFocused;
510 - setPreviewVideo(null);
511 - setPreviewFile(
512 - (current) =>
513 - current ?? {
514 - ...source,
515 - gallery: filePreviewGallery(source, composerImageGallery(props.draftAttachments)),
516 - },
517 - );
518 - },
519 - [isFocused, props.draftAttachments],
520 - );
497 + const onPressPreview = (source: FilePreviewSource) => {
498 + wasExpandedBeforePreviewRef.current = isFocused;
499 + setPreviewVideo(null);
500 + setPreviewFile(
501 + (current) =>
502 + current ?? {
503 + ...source,
504 + gallery: filePreviewGallery(source, composerImageGallery(props.draftAttachments)),
505 + },
506 + );
507 + };
508
522 - const closePreview = useCallback(() => {
509 + const closePreview = () => {
510 setPreviewFile(null);
511 setPreviewVideo(null);
512 if (wasExpandedBeforePreviewRef.current) {
@@ -527,151 +514,106 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
514 if (navigation.isFocused()) inputRef.current?.focus();
515 }, 100);
516 }
530 - }, [inputRef, navigation]);
517 + };
518
532 - const onPressVideo = useCallback(
533 - (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
534 - wasExpandedBeforePreviewRef.current = isFocused;
535 - setPreviewFile(null);
536 - setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
537 - },
538 - [isFocused],
539 - );
519 + const onPressVideo = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
520 + wasExpandedBeforePreviewRef.current = isFocused;
521 + setPreviewFile(null);
522 + setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
523 + };
524
525 const onEditorFocusChange = props.onEditorFocusChange;
542 - const handleFocus = useCallback(() => {
526 + const handleFocus = () => {
527 setIsFocused(true);
528 onExpandedChange?.(true);
529 onEditorFocusChange?.(true);
546 - }, [onEditorFocusChange, onExpandedChange]);
530 + };
531
548 - const handleBlur = useCallback(() => {
532 + const handleBlur = () => {
533 setIsFocused(false);
534 if (!settingsSheetPresentation.keepsComposerExpanded) {
535 onExpandedChange?.(false);
536 }
537 onEditorFocusChange?.(false);
554 - }, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.keepsComposerExpanded]);
555 - const handleSend = useCallback(
556 - async (followUp?: ActiveTurnComposerAction) => {
557 - if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
558 - if (
559 - usageLimitsOffered &&
560 - isUsageLimitsCommand(props.draftMessage) &&
561 - props.draftAttachments.length === 0
562 - ) {
563 - if (openUsageLimits()) onChangeDraftMessage("");
564 - return;
565 - }
566 - const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
567 - if (inFlightThreadIdsRef.current.has(threadKey)) return;
568 - inFlightThreadIdsRef.current.add(threadKey);
569 - try {
570 - const messageId = await onSendMessage(followUp);
571 - if (messageId === null) {
572 - return;
573 - }
574 - // Armed after the send so its preference read and native Activity start don't contend
575 - // with the queued-message feedback on the tap frame.
576 - armAgentAwarenessLiveActivityForLocalWork({
577 - environmentId: props.environmentId,
578 - threadTitle: props.selectedThread.title,
579 - projectTitle: props.environmentLabel ?? "T3 Code",
580 - });
581 - } finally {
582 - inFlightThreadIdsRef.current.delete(threadKey);
583 - }
584 - },
585 - [
586 - props.draftMessage,
587 - props.draftAttachments.length,
588 - onChangeDraftMessage,
589 - openUsageLimits,
590 - usageLimitsOffered,
591 - onSendMessage,
592 - props.environmentId,
593 - props.environmentLabel,
594 - props.selectedThread.id,
595 - props.selectedThread.title,
596 - voiceInput.blocksSubmission,
597 - ],
598 - );
538 + };
539 + const handleSend = async (followUp?: ActiveTurnComposerAction) => {
540 + if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
541 + if (
542 + usageLimitsOffered &&
543 + isUsageLimitsCommand(props.draftMessage) &&
544 + props.draftAttachments.length === 0
545 + ) {
546 + if (openUsageLimits()) onChangeDraftMessage("");
547 + return;
548 + }
549 + const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
550 + if (inFlightThreadIdsRef.current.has(threadKey)) return;
551 + inFlightThreadIdsRef.current.add(threadKey);
552 + const sent = await settlePromise(() => onSendMessage(followUp));
553 + inFlightThreadIdsRef.current.delete(threadKey);
554 + if (AsyncResult.isFailure(sent)) {
555 + // The composer state already surfaces send errors; only the lock needed releasing.
556 + console.error("[composer] send failed", squashAtomCommandFailure(sent));
557 + return;
558 + }
559 + if (sent.value === null) return;
560 + // Armed after the send so its preference read and native Activity start don't contend
561 + // with the queued-message feedback on the tap frame.
562 + armAgentAwarenessLiveActivityForLocalWork({
563 + environmentId: props.environmentId,
564 + threadTitle: props.selectedThread.title,
565 + projectTitle: props.environmentLabel ?? "T3 Code",
566 + });
567 + };
568
569 const lockedProviderInstanceId = props.canSwitchProvider
570 ? undefined
571 : currentModelSelection.instanceId;
603 - const modelOptions = useMemo(
604 - () =>
605 - buildModelOptions(
606 - props.serverConfig,
607 - currentModelSelection,
608 - lockedProviderInstanceId,
609 - props.selectedThread.projectId,
610 - ),
611 - [
612 - props.serverConfig,
613 - currentModelSelection,
614 - lockedProviderInstanceId,
615 - props.selectedThread.projectId,
616 - ],
572 + const modelOptions = buildModelOptions(
573 + props.serverConfig,
574 + currentModelSelection,
575 + lockedProviderInstanceId,
576 + props.selectedThread.projectId,
577 );
618 - const threadProviderGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
578 + const threadProviderGroups = groupByProvider(modelOptions);
579 const currentModelOption =
580 modelOptions.find(
581 (option) =>
582 option.selection.instanceId === currentModelSelection.instanceId &&
583 option.selection.model === currentModelSelection.model,
584 ) ?? null;
625 - const providerOptionDescriptors = useMemo(
626 - () =>
627 - resolveProviderOptionDescriptors({
628 - capabilities: currentModelOption?.capabilities,
629 - selections: currentModelSelection.options,
630 - }),
631 - [currentModelOption?.capabilities, currentModelSelection.options],
632 - );
585 + const providerOptionDescriptors = resolveProviderOptionDescriptors({
586 + capabilities: currentModelOption?.capabilities,
587 + selections: currentModelSelection.options,
588 + });
589 const settingsOwnerId = composerOwnerKey;
634 - const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
635 - () => ({
636 - ownerId: settingsOwnerId,
637 - environmentId: props.environmentId,
638 - projectId: props.selectedThread.projectId,
639 - providerInstanceId: currentModelSelection.instanceId,
640 - ...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {}),
641 - providerGroups: threadProviderGroups,
642 - selectedModel: currentModelSelection,
643 - reportedModelSelection: props.reportedModelSelection,
644 - onSelectModel: (option) =>
645 - props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),
646 - optionDescriptors: providerOptionDescriptors,
647 - onUpdateOptionSelections: (options) => {
648 - rememberModelOptions(
649 - currentModelSelection.instanceId,
650 - currentModelSelection.model,
651 - options ?? [],
652 - );
653 - props.onUpdateModelSelection({ ...currentModelSelection, options });
654 - },
655 - runtimeMode: currentRuntimeMode,
656 - onUpdateRuntimeMode: props.onUpdateRuntimeMode,
657 - }),
658 - [
659 - currentModelSelection,
660 - props.reportedModelSelection,
661 - currentRuntimeMode,
662 - props.onUpdateModelSelection,
663 - props.onUpdateRuntimeMode,
664 - providerOptionDescriptors,
665 - settingsOwnerId,
666 - lockedProviderInstanceId,
667 - threadProviderGroups,
668 - props.selectedThread.projectId,
669 - ],
670 - );
671 - const openSettings = useCallback(() => {
590 + const settingsRouteSession = {
591 + ownerId: settingsOwnerId,
592 + environmentId: props.environmentId,
593 + projectId: props.selectedThread.projectId,
594 + providerInstanceId: currentModelSelection.instanceId,
595 + ...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {}),
596 + providerGroups: threadProviderGroups,
597 + selectedModel: currentModelSelection,
598 + reportedModelSelection: props.reportedModelSelection,
599 + onSelectModel: (option) =>
600 + props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),
601 + optionDescriptors: providerOptionDescriptors,
602 + onUpdateOptionSelections: (options) => {
603 + rememberModelOptions(
604 + currentModelSelection.instanceId,
605 + currentModelSelection.model,
606 + options ?? [],
607 + );
608 + props.onUpdateModelSelection({ ...currentModelSelection, options });
609 + },
610 + runtimeMode: currentRuntimeMode,
611 + onUpdateRuntimeMode: props.onUpdateRuntimeMode,
612 + } satisfies ExistingThreadSettingsRouteSession;
613 + const openSettings = () => {
614 settingsRoutePresentation.present(settingsRouteSession);
615 settingsSheetPresentation.open();
674 - }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
616 + };
617
618 useEffect(() => {
619 if (settingsSheetPresentation.isActive) {
@@ -688,17 +630,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
630 navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
631 }, [navigation, settingsSheetPresentation.isVisible]);
632
691 - useFocusEffect(
692 - useCallback(() => {
693 - if (!settingsRoutePresentedRef.current) {
694 - return;
695 - }
633 + useFocusEffect(() => {
634 + if (!settingsRoutePresentedRef.current) {
635 + return;
636 + }
637
697 - settingsRoutePresentedRef.current = false;
698 - settingsSheetPresentation.onDismissed();
699 - settingsRoutePresentation.clear(settingsOwnerId);
700 - }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
701 - );
638 + settingsRoutePresentedRef.current = false;
639 + settingsSheetPresentation.onDismissed();
640 + settingsRoutePresentation.clear(settingsOwnerId);
641 + });
642
643 useEffect(
644 () =>
@@ -1140,4 +1080,4 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
1080 <FilePreviewModal source={previewFile} onRequestClose={closePreview} />
1081 </Animated.View>
1082 );
1143 -});
1083 +};
apps/mobile/src/features/threads/ThreadQueueControl.tsx
+33 -45
@@ -4,7 +4,7 @@ import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/co
4 import { Atom } from "effect/reactivity";
5 import { Image } from "expo-image";
6 import * as Haptics from "expo-haptics";
7 -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
7 +import { useEffect, useEffectEvent, useRef, useState } from "react";
8 import { Animated, Platform, Pressable, ScrollView, View } from "react-native";
9 import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
10 import ReanimatedSwipeable, {
@@ -113,12 +113,9 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
113 busyRef.current = true;
114 setBusyRunId(runId);
115 void Haptics.selectionAsync();
116 - try {
117 - await reorder({ ...target, input: { threadId: target.threadId, runId, beforeRunId } });
118 - } finally {
119 - busyRef.current = false;
120 - setBusyRunId(null);
121 - }
116 + await reorder({ ...target, input: { threadId: target.threadId, runId, beforeRunId } });
117 + busyRef.current = false;
118 + setBusyRunId(null);
119 };
120
121 const act = async (runId: RunId, action: QueueAction) => {
@@ -150,23 +147,20 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
147 busyRef.current = true;
148 setBusyRunId(runId);
149 void Haptics.selectionAsync();
153 - try {
154 - if (action === "remove") {
155 - await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
156 - } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
157 - await promote({
158 - ...target,
159 - input: {
160 - threadId: target.threadId,
161 - queuedRunId: runId,
162 - targetRunId: workflow.activeRun.id,
163 - },
164 - });
165 - }
166 - } finally {
167 - busyRef.current = false;
168 - setBusyRunId(null);
150 + if (action === "remove") {
151 + await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
152 + } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
153 + await promote({
154 + ...target,
155 + input: {
156 + threadId: target.threadId,
157 + queuedRunId: runId,
158 + targetRunId: workflow.activeRun.id,
159 + },
160 + });
161 }
162 + busyRef.current = false;
163 + setBusyRunId(null);
164 };
165
166 const canReorder = workflow?.canReorder === true && queuedRuns.length > 1;
@@ -203,12 +197,9 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
197 if (busyRef.current) return;
198 busyRef.current = true;
199 setResuming(true);
206 - try {
207 - await resume({ ...target, input: { threadId: target.threadId } });
208 - } finally {
209 - busyRef.current = false;
210 - setResuming(false);
211 - }
200 + await resume({ ...target, input: { threadId: target.threadId } });
201 + busyRef.current = false;
202 + setResuming(false);
203 }}
204 />
205 </View>
@@ -596,22 +587,19 @@ function QueueDragHandle(props: {
587 onMove: (y: number) => void;
588 onEnd: (y: number, success: boolean) => void;
589 }) {
599 - const latest = useRef(props);
600 - useLayoutEffect(() => {
601 - latest.current = props;
602 - });
603 - const gesture = useMemo(
604 - () =>
605 - Gesture.Pan()
606 - .enabled(!props.disabled)
607 - .minDistance(0)
608 - .shouldCancelWhenOutside(false)
609 - .runOnJS(true)
610 - .onStart(() => latest.current.onStart())
611 - .onUpdate((event) => latest.current.onMove(event.translationY))
612 - .onFinalize((event, success) => latest.current.onEnd(event.translationY, success)),
613 - [props.disabled],
614 - );
590 + // Gesture callbacks fire outside render, so effect events read the latest
591 + // props without rebuilding the gesture.
592 + const onStart = useEffectEvent(() => props.onStart());
593 + const onMove = useEffectEvent((y: number) => props.onMove(y));
594 + const onEnd = useEffectEvent((y: number, success: boolean) => props.onEnd(y, success));
595 + const gesture = Gesture.Pan()
596 + .enabled(!props.disabled)
597 + .minDistance(0)
598 + .shouldCancelWhenOutside(false)
599 + .runOnJS(true)
600 + .onStart(() => onStart())
601 + .onUpdate((event) => onMove(event.translationY))
602 + .onFinalize((event, success) => onEnd(event.translationY, success));
603 return (
604 <GestureDetector gesture={gesture}>
605 <View
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+223 -313
@@ -11,7 +11,7 @@ import {
11 useNavigation,
12 type StaticScreenProps,
13 } from "@react-navigation/native";
14 -import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
14 +import { useEffect, useRef, useState, type ReactNode } from "react";
15 import * as Option from "effect/Option";
16 import {
17 AuthOrchestrationOperateScope,
@@ -294,7 +294,7 @@ function ThreadRouteContent(
294 label: "load earlier thread history",
295 reportFailure: false,
296 });
297 - const historyControls = useMemo(() => {
297 + const historyControls = (() => {
298 const history = selectedThreadDetailState.history;
299 if (!selectedThread) {
300 return undefined;
@@ -313,7 +313,7 @@ function ThreadRouteContent(
313 });
314 },
315 };
316 - }, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]);
316 + })();
317 const navigation = useNavigation();
318 const openPullRequest = useOpenPullRequest();
319 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
@@ -321,7 +321,7 @@ function ThreadRouteContent(
321 const mergeBackRun =
322 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
323 const mergeBackBusyRef = useRef(false);
324 - const handleMergeBack = useCallback(async () => {
324 + const handleMergeBack = async () => {
325 if (
326 mergeBackBusyRef.current ||
327 !selectedThread ||
@@ -331,25 +331,22 @@ function ThreadRouteContent(
331 return;
332 }
333 mergeBackBusyRef.current = true;
334 - try {
335 - const result = await mergeBack({
336 - environmentId: selectedThread.environmentId,
337 - input: {
338 - sourceThreadId: selectedThread.id,
339 - targetThreadId: mergeBackTargetThreadId,
340 - runId: mergeBackRun.id,
341 - creationSource: "mobile",
342 - },
343 - });
344 - if (result._tag !== "Success") return;
345 - navigation.navigate("Thread", {
346 - environmentId: selectedThread.environmentId,
347 - threadId: mergeBackTargetThreadId,
348 - });
349 - } finally {
350 - mergeBackBusyRef.current = false;
351 - }
352 - }, [mergeBack, mergeBackRun, mergeBackTargetThreadId, navigation, selectedThread]);
334 + const result = await mergeBack({
335 + environmentId: selectedThread.environmentId,
336 + input: {
337 + sourceThreadId: selectedThread.id,
338 + targetThreadId: mergeBackTargetThreadId,
339 + runId: mergeBackRun.id,
340 + creationSource: "mobile",
341 + },
342 + });
343 + mergeBackBusyRef.current = false;
344 + if (result._tag !== "Success") return;
345 + navigation.navigate("Thread", {
346 + environmentId: selectedThread.environmentId,
347 + threadId: mergeBackTargetThreadId,
348 + });
349 + };
350 const params = props.route.params;
351 const environmentIdRaw = firstRouteParam(params.environmentId);
352 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
@@ -402,31 +399,25 @@ function ThreadRouteContent(
399 });
400 }, [props.renderInspector, routeThreadIdentity]);
401
405 - useFocusEffect(
406 - useCallback(() => {
407 - return () => {
408 - if (props.renderInspector === undefined) {
409 - setInspectorSelection(null);
410 - }
411 - };
412 - }, [props.renderInspector]),
413 - );
402 + useFocusEffect(() => {
403 + return () => {
404 + if (props.renderInspector === undefined) {
405 + setInspectorSelection(null);
406 + }
407 + };
408 + });
409 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
410 const routeConnectionState =
411 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
412 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
418 - const selectedThreadWithDraftSettings = useMemo(
419 - () =>
420 - selectedThread
421 - ? {
422 - ...selectedThread,
423 - modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
424 - runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
425 - interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
426 - }
427 - : null,
428 - [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
429 - );
413 + const selectedThreadWithDraftSettings = selectedThread
414 + ? {
415 + ...selectedThread,
416 + modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
417 + runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
418 + interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
419 + }
420 + : null;
421
422 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
423 const headerSubtitle = [
@@ -447,32 +438,25 @@ function ThreadRouteContent(
438 environmentId: selectedThread?.environmentId ?? null,
439 threadId: selectedThread?.id ?? null,
440 });
450 - const terminalMenuSessions = useMemo(
451 - () =>
452 - buildTerminalMenuSessions({
453 - knownSessions: knownTerminalSessions ?? [],
454 - workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
455 - }),
456 - [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
457 - );
441 + const terminalMenuSessions = buildTerminalMenuSessions({
442 + knownSessions: knownTerminalSessions ?? [],
443 + workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
444 + });
445 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
459 - const handleReconnectEnvironment = useCallback(() => {
446 + const handleReconnectEnvironment = () => {
447 if (!environmentId) {
448 return;
449 }
450 onReconnectEnvironment(environmentId);
464 - }, [environmentId, onReconnectEnvironment]);
451 + };
452
466 - const gitActionProgressTarget = useMemo(
467 - () => ({
468 - environmentId: selectedThread?.environmentId ?? null,
469 - cwd: selectedThreadCwd,
470 - }),
471 - [selectedThread?.environmentId, selectedThreadCwd],
472 - );
453 + const gitActionProgressTarget = {
454 + environmentId: selectedThread?.environmentId ?? null,
455 + cwd: selectedThreadCwd,
456 + };
457 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
458
475 - const handleOpenGitInspector = useCallback(() => {
459 + const handleOpenGitInspector = () => {
460 if (!fileInspector.supported) {
461 if (selectedThread === null) {
462 return;
@@ -485,8 +469,8 @@ function ThreadRouteContent(
469 }
470 setInspectorSelection({ routeThreadIdentity, mode: "git" });
471 showAuxiliaryPane("inspector");
488 - }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
489 - const handleOpenFilesInspector = useCallback(() => {
472 + };
473 + const handleOpenFilesInspector = () => {
474 if (selectedThread === null || selectedThreadCwd === null) {
475 return;
476 }
@@ -502,115 +486,67 @@ function ThreadRouteContent(
486 mode: props.renderInspector === undefined ? "files" : "route",
487 });
488 showAuxiliaryPane("inspector");
505 - }, [
506 - fileInspector.supported,
507 - navigation,
508 - props.renderInspector,
509 - routeThreadIdentity,
510 - selectedThread,
511 - selectedThreadCwd,
512 - showAuxiliaryPane,
513 - ]);
514 - const inspectorToggleActionRef = useRef({
515 - inspectorMode,
516 - openFilesInspector: handleOpenFilesInspector,
517 - toggleAuxiliaryPane,
518 - });
519 - inspectorToggleActionRef.current = {
520 - inspectorMode,
521 - openFilesInspector: handleOpenFilesInspector,
522 - toggleAuxiliaryPane,
489 };
524 - const handleToggleInspector = useCallback(() => {
525 - const action = inspectorToggleActionRef.current;
526 - if (action.inspectorMode === null) {
527 - action.openFilesInspector();
490 + const handleToggleInspector = () => {
491 + if (inspectorMode === null) {
492 + handleOpenFilesInspector();
493 return;
494 }
530 - action.toggleAuxiliaryPane();
531 - }, []);
532 - const handleSelectInspectorFile = useCallback(
533 - (path: string) => {
534 - if (selectedThread === null) {
535 - return;
536 - }
537 - const params = {
538 - environmentId: String(selectedThread.environmentId),
539 - threadId: String(selectedThread.id),
540 - path: path.split("/").filter((segment) => segment.length > 0),
541 - };
542 - if (fileInspector.supported) {
543 - navigation.navigate("ThreadFile", params);
544 - return;
545 - }
495 + toggleAuxiliaryPane();
496 + };
497 + const handleSelectInspectorFile = (path: string) => {
498 + if (selectedThread === null) {
499 + return;
500 + }
501 + const params = {
502 + environmentId: String(selectedThread.environmentId),
503 + threadId: String(selectedThread.id),
504 + path: path.split("/").filter((segment) => segment.length > 0),
505 + };
506 + if (fileInspector.supported) {
507 navigation.navigate("ThreadFile", params);
547 - },
548 - [fileInspector.supported, navigation, selectedThread],
549 - );
508 + return;
509 + }
510 + navigation.navigate("ThreadFile", params);
511 + };
512 const safeAreaInsets = useSafeAreaInsets();
513 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
552 - const GitInspector = useCallback(
553 - () => (
554 - <GitOverviewSheet
514 + const GitInspector = () => (
515 + <GitOverviewSheet
516 + headerInset={inspectorHeaderInset}
517 + presentation="inspector"
518 + route={{ params: props.route.params }}
519 + />
520 + );
521 + const FilesInspector = () =>
522 + selectedThread !== null && selectedThreadCwd !== null ? (
523 + <ThreadFileNavigatorPane
524 + cwd={selectedThreadCwd}
525 + environmentId={selectedThread.environmentId}
526 headerInset={inspectorHeaderInset}
556 - presentation="inspector"
557 - route={{ params: props.route.params }}
527 + projectName={selectedThreadProject?.title ?? "Files"}
528 + selectedPath={null}
529 + onSelectFile={handleSelectInspectorFile}
530 />
559 - ),
560 - [inspectorHeaderInset, props.route.params],
561 - );
562 - const FilesInspector = useCallback(
563 - () =>
564 - selectedThread !== null && selectedThreadCwd !== null ? (
565 - <ThreadFileNavigatorPane
566 - cwd={selectedThreadCwd}
567 - environmentId={selectedThread.environmentId}
568 - headerInset={inspectorHeaderInset}
569 - projectName={selectedThreadProject?.title ?? "Files"}
570 - selectedPath={null}
571 - onSelectFile={handleSelectInspectorFile}
572 - />
573 - ) : null,
574 - [
575 - handleSelectInspectorFile,
576 - inspectorHeaderInset,
577 - selectedThread,
578 - selectedThreadCwd,
579 - selectedThreadProject?.title,
580 - ],
581 - );
582 - const RouteInspector = useCallback(
583 - () => props.renderInspector?.(inspectorHeaderInset),
584 - [inspectorHeaderInset, props.renderInspector],
585 - );
586 - const renderInspectorStack = useCallback(
587 - () =>
588 - inspectorMode === null ? null : (
589 - <ThreadInspectorContentStack
590 - renderFiles={FilesInspector}
591 - renderGit={GitInspector}
592 - mode={inspectorMode}
593 - resetKeys={[routeThreadIdentity, selectedThreadCwd]}
594 - renderRoute={props.renderInspector ? RouteInspector : undefined}
595 - />
596 - ),
597 - [
598 - FilesInspector,
599 - GitInspector,
600 - RouteInspector,
601 - inspectorMode,
602 - props.renderInspector,
603 - routeThreadIdentity,
604 - selectedThreadCwd,
605 - ],
606 - );
531 + ) : null;
532 + const RouteInspector = () => props.renderInspector?.(inspectorHeaderInset);
533 + const renderInspectorStack = () =>
534 + inspectorMode === null ? null : (
535 + <ThreadInspectorContentStack
536 + renderFiles={FilesInspector}
537 + renderGit={GitInspector}
538 + mode={inspectorMode}
539 + resetKeys={[routeThreadIdentity, selectedThreadCwd]}
540 + renderRoute={props.renderInspector ? RouteInspector : undefined}
541 + />
542 + );
543 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
544 useRegisterWorkspaceInspector(activeInspectorRenderer);
545
610 - const handleOpenConnectionEditor = useCallback(() => {
546 + const handleOpenConnectionEditor = () => {
547 void navigation.navigate("Connections");
612 - }, [navigation]);
613 - const handleStopThread = useCallback(() => {
548 + };
549 + const handleStopThread = () => {
550 if (
551 !selectedThread ||
552 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
@@ -625,35 +561,32 @@ function ThreadRouteContent(
561 runId: composer.interruptibleRunId,
562 },
563 });
628 - }, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
564 + };
565
630 - const handleOpenTerminal = useCallback(
631 - (nextTerminalId?: string | null) => {
632 - terminalDebugLog("terminal-menu:open-existing", {
633 - terminalId: nextTerminalId ?? null,
634 - hasThread: Boolean(selectedThread),
635 - hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
636 - });
566 + const handleOpenTerminal = (nextTerminalId?: string | null) => {
567 + terminalDebugLog("terminal-menu:open-existing", {
568 + terminalId: nextTerminalId ?? null,
569 + hasThread: Boolean(selectedThread),
570 + hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
571 + });
572
638 - if (
639 - !selectedThread ||
640 - !selectedThreadProject?.workspaceRoot ||
641 - (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
642 - !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
643 - ) {
644 - return;
645 - }
573 + if (
574 + !selectedThread ||
575 + !selectedThreadProject?.workspaceRoot ||
576 + (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
577 + !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
578 + ) {
579 + return;
580 + }
581
647 - void navigation.navigate("ThreadTerminal", {
648 - environmentId: String(selectedThread.environmentId),
649 - threadId: String(selectedThread.id),
650 - ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
651 - });
652 - },
653 - [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
654 - );
582 + void navigation.navigate("ThreadTerminal", {
583 + environmentId: String(selectedThread.environmentId),
584 + threadId: String(selectedThread.id),
585 + ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
586 + });
587 + };
588
656 - const handleOpenNewTerminal = useCallback(() => {
589 + const handleOpenNewTerminal = () => {
590 terminalDebugLog("terminal-menu:open-new", {
591 hasThread: Boolean(selectedThread),
592 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
@@ -680,92 +613,76 @@ function ThreadRouteContent(
613 threadId: String(selectedThread.id),
614 terminalId: nextId,
615 });
683 - }, [
684 - knownTerminalSessions,
685 - navigation,
686 - selectedThread,
687 - selectedThreadProject?.workspaceRoot,
688 - terminalMenuSessions,
689 - ]);
616 + };
617 +
618 + const handleRunProjectScript = async (script: ProjectScript) => {
619 + terminalDebugLog("project-script:press", {
620 + scriptId: script.id,
621 + command: script.command,
622 + hasThread: Boolean(selectedThread),
623 + hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
624 + });
625
691 - const handleRunProjectScript = useCallback(
692 - async (script: ProjectScript) => {
693 - terminalDebugLog("project-script:press", {
626 + if (
627 + !selectedThread ||
628 + !selectedThreadProject?.workspaceRoot ||
629 + !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
630 + ) {
631 + terminalDebugLog("project-script:abort", {
632 scriptId: script.id,
695 - command: script.command,
696 - hasThread: Boolean(selectedThread),
697 - hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
633 + reason: "no-thread-workspace-or-terminal-access",
634 });
635 + return;
636 + }
637
700 - if (
701 - !selectedThread ||
702 - !selectedThreadProject?.workspaceRoot ||
703 - !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
704 - ) {
705 - terminalDebugLog("project-script:abort", {
706 - scriptId: script.id,
707 - reason: "no-thread-workspace-or-terminal-access",
708 - });
709 - return;
710 - }
711 -
712 - const targetTerminalId = resolveProjectScriptTerminalId({
713 - existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
714 - ...(knownTerminalSessions === null ||
715 - !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
716 - ? { uniqueSuffix: uuidv4() }
717 - : {}),
718 - hasRunningTerminal: terminalMenuSessions.some(
719 - (session) => session.status === "running" || session.status === "starting",
720 - ),
721 - });
722 - const preferredWorktreePath = resolvePreferredThreadWorktreePath({
723 - threadShellWorktreePath: selectedThread.worktreePath ?? null,
724 - threadDetailWorktreePath: selectedThreadDetailWorktreePath,
725 - });
726 - const cwd = projectScriptCwd({
727 - project: { cwd: selectedThreadProject.workspaceRoot },
728 - worktreePath: preferredWorktreePath,
729 - });
730 - const env = projectScriptRuntimeEnv({
731 - project: { cwd: selectedThreadProject.workspaceRoot },
732 - worktreePath: preferredWorktreePath,
733 - });
734 - stagePendingTerminalLaunch({
735 - target: {
736 - environmentId: selectedThread.environmentId,
737 - threadId: selectedThread.id,
738 - terminalId: targetTerminalId,
739 - },
740 - launch: {
741 - cwd,
742 - worktreePath: preferredWorktreePath,
743 - env,
744 - initialInput: `${script.command}\r`,
745 - },
746 - });
747 - terminalDebugLog("project-script:staged", {
748 - scriptId: script.id,
638 + const targetTerminalId = resolveProjectScriptTerminalId({
639 + existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
640 + ...(knownTerminalSessions === null ||
641 + !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
642 + ? { uniqueSuffix: uuidv4() }
643 + : {}),
644 + hasRunningTerminal: terminalMenuSessions.some(
645 + (session) => session.status === "running" || session.status === "starting",
646 + ),
647 + });
648 + const preferredWorktreePath = resolvePreferredThreadWorktreePath({
649 + threadShellWorktreePath: selectedThread.worktreePath ?? null,
650 + threadDetailWorktreePath: selectedThreadDetailWorktreePath,
651 + });
652 + const cwd = projectScriptCwd({
653 + project: { cwd: selectedThreadProject.workspaceRoot },
654 + worktreePath: preferredWorktreePath,
655 + });
656 + const env = projectScriptRuntimeEnv({
657 + project: { cwd: selectedThreadProject.workspaceRoot },
658 + worktreePath: preferredWorktreePath,
659 + });
660 + stagePendingTerminalLaunch({
661 + target: {
662 + environmentId: selectedThread.environmentId,
663 + threadId: selectedThread.id,
664 terminalId: targetTerminalId,
665 + },
666 + launch: {
667 cwd,
668 worktreePath: preferredWorktreePath,
752 - });
669 + env,
670 + initialInput: `${script.command}\r`,
671 + },
672 + });
673 + terminalDebugLog("project-script:staged", {
674 + scriptId: script.id,
675 + terminalId: targetTerminalId,
676 + cwd,
677 + worktreePath: preferredWorktreePath,
678 + });
679
754 - void navigation.navigate("ThreadTerminal", {
755 - environmentId: String(selectedThread.environmentId),
756 - threadId: String(selectedThread.id),
757 - terminalId: targetTerminalId,
758 - });
759 - },
760 - [
761 - navigation,
762 - selectedThread,
763 - selectedThreadDetailWorktreePath,
764 - selectedThreadProject,
765 - terminalMenuSessions,
766 - knownTerminalSessions,
767 - ],
768 - );
680 + void navigation.navigate("ThreadTerminal", {
681 + environmentId: String(selectedThread.environmentId),
682 + threadId: String(selectedThread.id),
683 + terminalId: targetTerminalId,
684 + });
685 + };
686 const threadGitControlProps = {
687 environmentId: environmentIdRaw ?? "",
688 threadId: threadId ?? "",
@@ -804,7 +721,7 @@ function ThreadRouteContent(
721 onPull: gitActions.onPullSelectedThreadBranch,
722 onRunAction: gitActions.onRunSelectedThreadGitAction,
723 };
807 - const handleEditFailedCreation = useCallback(async () => {
724 + const handleEditFailedCreation = async () => {
725 const creation = selectedThreadCreation?.message;
726 if (!creation?.creation || routeThreadIdentity === null) {
727 return;
@@ -833,7 +750,7 @@ function ThreadRouteContent(
750 },
751 }),
752 );
836 - }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
753 + };
754 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
755 const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({
756 environmentId: selectedThread?.environmentId ?? null,
@@ -857,66 +774,59 @@ function ThreadRouteContent(
774 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
775 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
776 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
860 - const handleCancelWorktreeSetup = useCallback(() => {
777 + const handleCancelWorktreeSetup = () => {
778 if (!selectedThread) return;
779 void cancelWorktreeSetup({
780 environmentId: selectedThread.environmentId,
781 input: { threadId: selectedThread.id },
782 });
866 - }, [cancelWorktreeSetup, selectedThread]);
783 + };
784 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
785 const localResendBusy = useRef(false);
786 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
870 - const handleWorkLocally = useCallback(async () => {
787 + const handleWorkLocally = async () => {
788 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
789 return;
790 localResendBusy.current = true;
874 - try {
875 - const result = await cancelWorktreeSetup({
876 - environmentId: selectedThread.environmentId,
877 - input: { threadId: selectedThread.id },
878 - });
879 - if (result._tag !== "Success" || !result.value.cancelled) return;
880 - // V2 accepts the launch before setup runs, so cancellation never rejects
881 - // the original outbox delivery. Reuse the server-owned prompt and uploads.
882 - const metadata = makeTurnCommandMetadata();
883 - const launched = await startLocalThread({
884 - environmentId: selectedThread.environmentId,
885 - input: buildProjectThreadStartTurnInput({
886 - ...metadata,
887 - projectId: selectedThread.projectId,
888 - projectCwd: selectedThreadProject.workspaceRoot,
889 - text: setupMessage.text,
890 - ...(setupMessage.context ? { context: setupMessage.context } : {}),
891 - uploadedAttachments: setupMessage.attachments,
892 - modelSelection: selectedThread.modelSelection,
893 - runtimeMode: selectedThread.runtimeMode,
894 - interactionMode: selectedThread.interactionMode,
895 - workspaceMode: "local",
896 - branch: null,
897 - worktreePath: null,
898 - startFromOrigin: false,
899 - worktreeBranchName: "",
900 - }),
901 - });
902 - if (launched._tag !== "Success") return;
903 - navigation.dispatch(
904 - StackActions.replace("Thread", {
905 - environmentId: String(selectedThread.environmentId),
906 - threadId: metadata.threadId,
907 - }),
908 - );
909 - } finally {
791 + const result = await cancelWorktreeSetup({
792 + environmentId: selectedThread.environmentId,
793 + input: { threadId: selectedThread.id },
794 + });
795 + if (result._tag !== "Success" || !result.value.cancelled) {
796 localResendBusy.current = false;
797 + return;
798 }
912 - }, [
913 - cancelWorktreeSetup,
914 - navigation,
915 - selectedThread,
916 - selectedThreadProject,
917 - setupMessage,
918 - startLocalThread,
919 - ]);
799 + // V2 accepts the launch before setup runs, so cancellation never rejects
800 + // the original outbox delivery. Reuse the server-owned prompt and uploads.
801 + const metadata = makeTurnCommandMetadata();
802 + const launched = await startLocalThread({
803 + environmentId: selectedThread.environmentId,
804 + input: buildProjectThreadStartTurnInput({
805 + ...metadata,
806 + projectId: selectedThread.projectId,
807 + projectCwd: selectedThreadProject.workspaceRoot,
808 + text: setupMessage.text,
809 + ...(setupMessage.context ? { context: setupMessage.context } : {}),
810 + uploadedAttachments: setupMessage.attachments,
811 + modelSelection: selectedThread.modelSelection,
812 + runtimeMode: selectedThread.runtimeMode,
813 + interactionMode: selectedThread.interactionMode,
814 + workspaceMode: "local",
815 + branch: null,
816 + worktreePath: null,
817 + startFromOrigin: false,
818 + worktreeBranchName: "",
819 + }),
820 + });
821 + localResendBusy.current = false;
822 + if (launched._tag !== "Success") return;
823 + navigation.dispatch(
824 + StackActions.replace("Thread", {
825 + environmentId: String(selectedThread.environmentId),
826 + threadId: metadata.threadId,
827 + }),
828 + );
829 + };
830 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
831 if (selectedThreadCreation === null) {
832 return awaitingBootstrapTurn
apps/mobile/src/reactCompilerCoverage.test.ts
-4
@@ -24,19 +24,15 @@ const KNOWN_BAILOUTS: Record<string, string> = {
24 "src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
25 "src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
26 "src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
27 - "src/features/threads/ThreadComposer.tsx": "try without catch",
27 "src/features/threads/ThreadDetailScreen.tsx": "mutates a frozen value",
28 "src/features/threads/ThreadFeed.tsx": "ref read during render, throw inside try, try/finally",
29 "src/features/threads/ThreadNavigationSidebar.tsx": "ref read during render",
31 - "src/features/threads/ThreadQueueControl.tsx": "ref read during render, try without catch",
32 - "src/features/threads/ThreadRouteScreen.tsx": "try without catch",
30 "src/features/threads/use-thread-list-v2-shelf-preferences.ts": "ref read during render",
31 "src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
32 "src/features/voice-input/useVoiceInputController.ts": "ref read during render",
33 "src/native/StackHeader.tsx": "ref read during render",
34 "src/native/T3ComposerEditor.ios.tsx": "ref read during render",
35 "src/native/T3ComposerEditor.native.tsx": "ref read during render",
39 - "src/state/use-thread-composer-state.ts": "try without catch",
36 "src/state/use-thread-selection.ts": "ref read during render",
37 };
38
apps/mobile/src/state/use-thread-composer-state.ts
+387 -472
@@ -12,7 +12,7 @@ import {
12 deriveThreadRuntime,
13 threadRuntimeHasInterruptibleRun,
14 } from "@t3tools/client-runtime/state/thread-execution";
15 -import { useCallback, useEffect, useMemo, useRef, useState } from "react";
15 +import { useEffect, useRef, useState } from "react";
16
17 import {
18 CommandId,
@@ -89,6 +89,7 @@ import {
89 } from "@t3tools/client-runtime/state/composer-dispatch";
90 import { Atom } from "effect/reactivity";
91 import { AsyncResult } from "effect/reactivity";
92 +import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
93 import { prepareTurnAttachments } from "../lib/attachmentUpload";
94 import { DEFAULT_FOLLOW_UP_BEHAVIOR } from "../lib/followUpBehavior";
95 import { mobilePreferencesAtom } from "./preferences";
@@ -204,19 +205,16 @@ export function useThreadComposerState() {
205 threadKey: null,
206 names: new Set(),
207 });
207 - const reservePastedTextFileName = useCallback(
208 - (threadKey: string, existingNames: ReadonlyArray<string>) => {
209 - if (pastedTextFileNamesRef.current.threadKey !== threadKey) {
210 - pastedTextFileNamesRef.current = { threadKey, names: new Set() };
211 - }
212 - const names = pastedTextFileNamesRef.current.names;
213 - for (const name of existingNames) names.add(name);
214 - const nextName = nextPastedTextFileName([...names]);
215 - names.add(nextName);
216 - return nextName;
217 - },
218 - [],
219 - );
208 + const reservePastedTextFileName = (threadKey: string, existingNames: ReadonlyArray<string>) => {
209 + if (pastedTextFileNamesRef.current.threadKey !== threadKey) {
210 + pastedTextFileNamesRef.current = { threadKey, names: new Set() };
211 + }
212 + const names = pastedTextFileNamesRef.current.names;
213 + for (const name of existingNames) names.add(name);
214 + const nextName = nextPastedTextFileName([...names]);
215 + names.add(nextName);
216 + return nextName;
217 + };
218
219 useEffect(() => {
220 ensureComposerDraftsLoaded();
@@ -225,29 +223,21 @@ export function useThreadComposerState() {
223 const selectedThreadKey = selectedThreadShell
224 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
225 : null;
228 - const selectedThreadQueuedMessages = useMemo(
229 - () =>
230 - selectedThreadKey
231 - ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
232 - (message) => message.creation === undefined,
233 - )
234 - : [],
235 - [queuedMessagesByThreadKey, selectedThreadKey],
236 - );
237 - const feedbackSubmissions = useMemo(
238 - () => (selectedThreadKey ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? []) : []),
239 - [feedbackSubmissionsByThreadKey, selectedThreadKey],
240 - );
241 - const dismissFeedback = useCallback(
242 - (id: MessageId) => {
243 - if (!selectedThreadKey) return;
244 - setFeedbackSubmissionsByThreadKey((current) => ({
245 - ...current,
246 - [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
247 - }));
248 - },
249 - [selectedThreadKey],
250 - );
226 + const selectedThreadQueuedMessages = selectedThreadKey
227 + ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
228 + (message) => message.creation === undefined,
229 + )
230 + : [];
231 + const feedbackSubmissions = selectedThreadKey
232 + ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? [])
233 + : [];
234 + const dismissFeedback = (id: MessageId) => {
235 + if (!selectedThreadKey) return;
236 + setFeedbackSubmissionsByThreadKey((current) => ({
237 + ...current,
238 + [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
239 + }));
240 + };
241 const selectedThreadMessages = selectedThreadProjection?.projection.messages;
242 const selectedThreadAttempts = selectedThreadProjection?.projection.attempts;
243 const selectedThreadNodes = selectedThreadProjection?.projection.nodes;
@@ -256,7 +246,7 @@ export function useThreadComposerState() {
246 // detail is usually present but empty during a worktree checkout, so this
247 // cannot be an either/or with the loaded messages.
248 const pendingCreationMessage = selectedThreadCreation?.message ?? null;
259 - const selectedThreadFeed = useMemo(() => {
249 + const selectedThreadFeed = (() => {
250 const pendingCreation =
251 pendingCreationMessage !== null &&
252 !selectedThreadMessages?.some((message) => message.id === pendingCreationMessage.messageId)
@@ -276,16 +266,7 @@ export function useThreadComposerState() {
266 return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>
267 entry.pendingMessage ? { ...entry, acknowledged: true } : entry,
268 );
279 - }, [
280 - selectedThreadMessages,
281 - selectedThreadAttempts,
282 - selectedThreadNodes,
283 - selectedThreadVisibleTurnItems,
284 - pendingCreationMessage,
285 - selectedThreadKey,
286 - selectedThreadQueuedMessages,
287 - acknowledgedMessages,
288 - ]);
269 + })();
270 useEffect(() => {
271 const echoedIds = new Set(selectedThreadMessages?.map((message) => message.id));
272 if (acknowledgedMessages.some((message) => echoedIds.has(message.messageId))) {
@@ -321,14 +302,10 @@ export function useThreadComposerState() {
302 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
303 const selectedThread = selectedThreadShell;
304 const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
324 - const pendingHandoff = useMemo(
325 - () =>
326 - resolvePendingHandoff(
327 - selectedThreadProjection?.projection,
328 - modelSelection,
329 - selectedEnvironmentRuntime?.serverConfig?.providers ?? [],
330 - ),
331 - [modelSelection, selectedThreadProjection, selectedEnvironmentRuntime?.serverConfig?.providers],
305 + const pendingHandoff = resolvePendingHandoff(
306 + selectedThreadProjection?.projection,
307 + modelSelection,
308 + selectedEnvironmentRuntime?.serverConfig?.providers ?? [],
309 );
310 const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
311 const selectedProvider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
@@ -340,30 +317,18 @@ export function useThreadComposerState() {
317 selectedDraft?.interactionMode ?? selectedThread.interactionMode,
318 )
319 : null;
343 - const canSwitchThreadProvider = useMemo(
344 - () =>
345 - threadAllowsProviderSwitch({
346 - thread: selectedThreadShell,
347 - projection: selectedThreadProjection?.projection,
348 - }),
349 - [selectedThreadProjection, selectedThreadShell],
350 - );
351 - const selectedThreadRuntime = useMemo(
352 - () =>
353 - selectedThreadProjection
354 - ? deriveThreadRuntime(selectedThreadProjection.projection)
355 - : (selectedThreadShell?.runtime ?? null),
356 - [selectedThreadProjection, selectedThreadShell?.runtime],
357 - );
358 - const selectedThreadActivityRun = useMemo(
359 - () =>
360 - selectedThreadProjection
361 - ? deriveThreadActivityRun(selectedThreadProjection.projection)
362 - : (selectedThreadShell?.latestRun ?? null),
363 - [selectedThreadProjection, selectedThreadShell?.latestRun],
364 - );
365 -
366 - const isCompacting = useMemo(() => {
320 + const canSwitchThreadProvider = threadAllowsProviderSwitch({
321 + thread: selectedThreadShell,
322 + projection: selectedThreadProjection?.projection,
323 + });
324 + const selectedThreadRuntime = selectedThreadProjection
325 + ? deriveThreadRuntime(selectedThreadProjection.projection)
326 + : (selectedThreadShell?.runtime ?? null);
327 + const selectedThreadActivityRun = selectedThreadProjection
328 + ? deriveThreadActivityRun(selectedThreadProjection.projection)
329 + : (selectedThreadShell?.latestRun ?? null);
330 +
331 + const isCompacting = (() => {
332 const queuedCompact = selectedThreadQueuedMessages.some(
333 (message) =>
334 message.messageId === dispatchingQueuedMessageId &&
@@ -387,23 +352,14 @@ export function useThreadComposerState() {
352 item.type === "compaction" &&
353 (item.status === "completed" || item.status === "failed"),
354 );
390 - }, [
391 - dispatchingQueuedMessageId,
392 - selectedThreadQueuedMessages,
393 - selectedThreadRuntime,
394 - selectedThreadVisibleTurnItems,
395 - ]);
355 + })();
356 // A compacting turn cannot take steering input, so follow-ups queue meanwhile.
357 const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !isCompacting;
358
399 - const runlessWorkStartedAt = useMemo(
400 - () =>
401 - selectedThreadProjection
402 - ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
403 - : null,
404 - [selectedThreadProjection],
405 - );
406 - const activeWorkStartedAt = useMemo(() => {
359 + const runlessWorkStartedAt = selectedThreadProjection
360 + ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
361 + : null;
362 + const activeWorkStartedAt = (() => {
363 if (!selectedThreadShell) {
364 return null;
365 }
@@ -413,16 +369,12 @@ export function useThreadComposerState() {
369 runtime: selectedThreadRuntime,
370 }) ?? runlessWorkStartedAt
371 );
416 - }, [selectedThreadActivityRun, runlessWorkStartedAt, selectedThreadRuntime, selectedThreadShell]);
372 + })();
373 const runlessWorkActive = runlessWorkStartedAt !== null;
374
419 - const providerSubagentStatus = useMemo(
420 - () =>
421 - selectedThreadProjection
422 - ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
423 - : null,
424 - [selectedThreadProjection],
425 - );
375 + const providerSubagentStatus = selectedThreadProjection
376 + ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
377 + : null;
378
379 const selectedThreadRuns = selectedThreadProjection?.projection.runs;
380 const editedRunId = queuedRunEdit?.runId ?? null;
@@ -463,20 +415,17 @@ export function useThreadComposerState() {
415 ? (selectedThreadRuntime?.activeRunId ?? null)
416 : null;
417
466 - const cancelQueuedRunEdit = useCallback(() => {
418 + const cancelQueuedRunEdit = () => {
419 if (selectedThreadKey === null || savingQueuedEditRef.current) return;
420 endQueuedRunEdit(selectedThreadKey);
469 - }, [selectedThreadKey]);
421 + };
422
471 - const onRemoveQueuedEditAttachment = useCallback(
472 - (attachmentId: string) => {
473 - if (selectedThreadKey === null) return;
474 - removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
475 - },
476 - [selectedThreadKey],
477 - );
423 + const onRemoveQueuedEditAttachment = (attachmentId: string) => {
424 + if (selectedThreadKey === null) return;
425 + removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
426 + };
427
479 - const saveQueuedRunEdit = useCallback(async () => {
428 + const saveQueuedRunEdit = async () => {
429 const thread = selectedThreadShell;
430 if (!thread || savingQueuedEditRef.current) return;
431 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
@@ -501,257 +450,252 @@ export function useThreadComposerState() {
450 }
451 savingQueuedEditRef.current = true;
452 setIsSavingQueuedEdit(true);
504 - try {
505 - const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
506 - const prepared = await prepareTurnAttachments({
453 + const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
454 + const prepared = await settlePromise(() =>
455 + prepareTurnAttachments({
456 environmentId: thread.environmentId,
457 attachments: draft.attachments,
458 supportsImageUploads: capabilities?.attachmentUploads === true,
510 - });
511 - if (prepared.status !== "ready") return;
512 - const payload = resolveQueuedEditPayload({
513 - edit,
514 - draftContext: draft.context,
515 - draftAttachments: draft.attachments,
516 - uploaded: prepared.attachments,
517 - });
518 - const result = await editQueuedRun({
519 - environmentId: thread.environmentId,
520 - input: {
521 - threadId: thread.id,
522 - runId: edit.runId,
523 - text,
524 - edit: {
525 - messageId: edit.messageId,
526 - attachments: payload.attachments,
527 - ...(payload.context ? { context: payload.context } : {}),
528 - },
529 - },
530 - });
531 - if (result._tag !== "Success") {
532 - Dialog.alert(
533 - "Could not save the queued message",
534 - "It may have already started. Your edit is still in the composer.",
535 - );
536 - return;
537 - }
538 - endQueuedRunEdit(threadKey, { deferAttachmentCleanup: true });
539 - scheduleUnusedComposerAttachmentCleanup(draft.attachments);
540 - } finally {
459 + }),
460 + );
461 + if (AsyncResult.isFailure(prepared)) {
462 savingQueuedEditRef.current = false;
463 setIsSavingQueuedEdit(false);
464 + const error = squashAtomCommandFailure(prepared);
465 + Dialog.alert(
466 + "Could not save the queued message",
467 + error instanceof Error ? error.message : "Your edit is still in the composer.",
468 + );
469 + return;
470 }
544 - }, [editQueuedRun, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
471 + if (prepared.value.status !== "ready") {
472 + savingQueuedEditRef.current = false;
473 + setIsSavingQueuedEdit(false);
474 + return;
475 + }
476 + const payload = resolveQueuedEditPayload({
477 + edit,
478 + draftContext: draft.context,
479 + draftAttachments: draft.attachments,
480 + uploaded: prepared.value.attachments,
481 + });
482 + const result = await editQueuedRun({
483 + environmentId: thread.environmentId,
484 + input: {
485 + threadId: thread.id,
486 + runId: edit.runId,
487 + text,
488 + edit: {
489 + messageId: edit.messageId,
490 + attachments: payload.attachments,
491 + ...(payload.context ? { context: payload.context } : {}),
492 + },
493 + },
494 + });
495 + savingQueuedEditRef.current = false;
496 + setIsSavingQueuedEdit(false);
497 + if (result._tag !== "Success") {
498 + Dialog.alert(
499 + "Could not save the queued message",
500 + "It may have already started. Your edit is still in the composer.",
501 + );
502 + return;
503 + }
504 + endQueuedRunEdit(threadKey, { deferAttachmentCleanup: true });
505 + scheduleUnusedComposerAttachmentCleanup(draft.attachments);
506 + };
507
546 - const onSendMessage = useCallback(
547 - async (followUpOverride?: ActiveTurnComposerAction) => {
548 - if (
549 - selectedThreadShell &&
550 - selectedEnvironmentRuntime?.connectionState === "connected" &&
551 - !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
552 - )
553 - return null;
554 - if (!selectedThreadShell) {
555 - return null;
556 - }
557 - // The server has not created this thread yet. Queuing a follow-up against
558 - // its id would strand the message: if the creation is rejected the thread
559 - // never appears and the drain drops the orphan. The composer disables its
560 - if (selectedThreadCreation !== null) {
561 - return null;
562 - }
508 + const onSendMessage = async (followUpOverride?: ActiveTurnComposerAction) => {
509 + if (
510 + selectedThreadShell &&
511 + selectedEnvironmentRuntime?.connectionState === "connected" &&
512 + !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
513 + )
514 + return null;
515 + if (!selectedThreadShell) {
516 + return null;
517 + }
518 + // The server has not created this thread yet. Queuing a follow-up against
519 + // its id would strand the message: if the creation is rejected the thread
520 + // never appears and the drain drops the orphan. The composer disables its
521 + if (selectedThreadCreation !== null) {
522 + return null;
523 + }
524
564 - const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
565 - if (getQueuedRunEdit(editKey) !== null) {
566 - await saveQueuedRunEdit();
567 - return null;
568 - }
525 + const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
526 + if (getQueuedRunEdit(editKey) !== null) {
527 + await saveQueuedRunEdit();
528 + return null;
529 + }
530
570 - const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
571 - const draft = getComposerDraftSnapshot(threadKey);
572 - if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
573 - const thread = selectedThreadShell;
574 - const text = draft.text.trim();
575 - const attachments = draft.attachments;
576 - if (
577 - composerAttachmentUploadBlockReason({
578 - environmentId: selectedThreadShell.environmentId,
579 - attachments,
580 - connected: selectedEnvironmentRuntime?.connectionState === "connected",
581 - serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
582 - states: appAtomRegistry.get(composerAttachmentUploadsAtom),
583 - }) !== null
584 - )
585 - return null;
586 - if (text.length === 0 && attachments.length === 0) {
587 - return null;
588 - }
589 - // A send-failure restore appends with allowOverflow so it never drops the
590 - // user's files, which can leave the draft over the cap. Sending it anyway
591 - // would enqueue a message that outbox recovery rejects forever, so block
592 - // here until the user removes attachments.
593 - if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
594 - Dialog.alert(
595 - "Too many attachments",
596 - `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
597 - );
598 - return null;
599 - }
531 + const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
532 + const draft = getComposerDraftSnapshot(threadKey);
533 + if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
534 + const thread = selectedThreadShell;
535 + const text = draft.text.trim();
536 + const attachments = draft.attachments;
537 + if (
538 + composerAttachmentUploadBlockReason({
539 + environmentId: selectedThreadShell.environmentId,
540 + attachments,
541 + connected: selectedEnvironmentRuntime?.connectionState === "connected",
542 + serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
543 + states: appAtomRegistry.get(composerAttachmentUploadsAtom),
544 + }) !== null
545 + )
546 + return null;
547 + if (text.length === 0 && attachments.length === 0) {
548 + return null;
549 + }
550 + // A send-failure restore appends with allowOverflow so it never drops the
551 + // user's files, which can leave the draft over the cap. Sending it anyway
552 + // would enqueue a message that outbox recovery rejects forever, so block
553 + // here until the user removes attachments.
554 + if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
555 + Dialog.alert(
556 + "Too many attachments",
557 + `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
558 + );
559 + return null;
560 + }
561
601 - const contextBlockReason = composerContextSendBlockReason(draft.context);
602 - if (contextBlockReason) {
603 - Dialog.alert("Too much context", contextBlockReason);
604 - return null;
605 - }
562 + const contextBlockReason = composerContextSendBlockReason(draft.context);
563 + if (contextBlockReason) {
564 + Dialog.alert("Too much context", contextBlockReason);
565 + return null;
566 + }
567
607 - const modelSelection = draft.modelSelection ?? thread.modelSelection;
608 - const serverConfig = selectedEnvironmentRuntime?.serverConfig;
609 - if (
610 - selectedEnvironmentRuntime?.connectionState === "connected" &&
611 - isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
612 - ) {
613 - const { title, detail } = describeUnavailableModelSelection(
614 - serverConfig,
615 - modelSelection,
616 - thread.projectId,
617 - );
618 - Dialog.alert(title, detail);
619 - return null;
620 - }
621 - const provider = serverConfig?.providers.find(
622 - (entry) => entry.instanceId === modelSelection.instanceId,
568 + const modelSelection = draft.modelSelection ?? thread.modelSelection;
569 + const serverConfig = selectedEnvironmentRuntime?.serverConfig;
570 + if (
571 + selectedEnvironmentRuntime?.connectionState === "connected" &&
572 + isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
573 + ) {
574 + const { title, detail } = describeUnavailableModelSelection(
575 + serverConfig,
576 + modelSelection,
577 + thread.projectId,
578 );
624 - const feedbackCommand =
625 - attachments.length === 0 && provider?.driver === "codex"
626 - ? parseCodexFeedbackCommand(text)
627 - : null;
628 - if (feedbackCommand) {
629 - if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
630 - return null;
631 - if (thread.activeProviderThreadId === null) {
632 - Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
633 - return null;
634 - }
635 - const metadata = makeQueuedMessageMetadata();
636 - await submitCodexFeedback({
637 - submission: {
638 - id: MessageId.make(metadata.messageId),
639 - command: text,
640 - createdAt: metadata.createdAt,
641 - },
642 - clearDraft: () => clearComposerDraftContent(threadKey),
643 - onUpdate: (submission) => {
644 - setFeedbackSubmissionsByThreadKey((current) => {
645 - const existing = current[threadKey] ?? [];
646 - const found = existing.some((entry) => entry.id === submission.id);
647 - return {
648 - ...current,
649 - [threadKey]: found
650 - ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
651 - : [...existing, submission],
652 - };
653 - });
654 - },
655 - upload: () =>
656 - uploadThreadFeedback({
657 - environmentId: thread.environmentId,
658 - input: { threadId: thread.id, ...feedbackCommand },
659 - }),
660 - });
579 + Dialog.alert(title, detail);
580 + return null;
581 + }
582 + const provider = serverConfig?.providers.find(
583 + (entry) => entry.instanceId === modelSelection.instanceId,
584 + );
585 + const feedbackCommand =
586 + attachments.length === 0 && provider?.driver === "codex"
587 + ? parseCodexFeedbackCommand(text)
588 + : null;
589 + if (feedbackCommand) {
590 + if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
591 + return null;
592 + if (thread.activeProviderThreadId === null) {
593 + Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
594 return null;
595 }
663 -
664 - // Resolved here rather than at drain time: the outbox can deliver minutes
665 - // later, and the choice belongs to the moment the user pressed send.
666 - // Steering travels as "auto" so a turn that ends in the meantime degrades
667 - // to a queued run on the server instead of failing the delivery and
668 - // bouncing the message back into the draft.
669 - const followUpAction = resolveComposerDispatchMode({
670 - running: activeThreadBusy && canSteerActiveTurn,
671 - alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
672 - activeTurnDefault: followUpBehavior,
673 - });
674 - const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
675 - (status) => status === "preparing" || status === "starting",
676 - );
677 - const followUpDispatchMode = setupRunning
678 - ? "queue"
679 - : followUpAction === "auto"
680 - ? null
681 - : followUpAction === "queue"
682 - ? "queue"
683 - : "auto";
684 -
596 const metadata = makeQueuedMessageMetadata();
686 - const messageId = MessageId.make(metadata.messageId);
687 - clearThreadComposerError(threadKey);
688 - const enqueuePromise = enqueueThreadOutboxMessage({
689 - environmentId: selectedThreadShell.environmentId,
690 - threadId: selectedThreadShell.id,
691 - messageId,
692 - commandId: CommandId.make(metadata.commandId),
693 - text,
694 - attachments,
695 - context: draft.context,
696 - modelSelection,
697 - runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
698 - interactionMode: resolveProviderInteractionMode(
699 - provider,
700 - draft.interactionMode ?? thread.interactionMode,
701 - ),
702 - ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
703 - createdAt: metadata.createdAt,
704 - });
705 - clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
706 - enqueuePromise.then(
707 - () => scheduleUnusedComposerAttachmentCleanup(attachments),
708 - (error: unknown) => {
709 - // Restore text via merge (idempotent) but attachments via the uncapped
710 - // append: the merge path slots existing attachments first and truncates
711 - // at the send limit, which would silently drop this message's images if
712 - // the user attached new ones while the write was in flight.
713 - void mergeComposerDraftContent(threadKey, {
714 - text,
715 - context: draft.context,
716 - attachments: [],
597 + await submitCodexFeedback({
598 + submission: {
599 + id: MessageId.make(metadata.messageId),
600 + command: text,
601 + createdAt: metadata.createdAt,
602 + },
603 + clearDraft: () => clearComposerDraftContent(threadKey),
604 + onUpdate: (submission) => {
605 + setFeedbackSubmissionsByThreadKey((current) => {
606 + const existing = current[threadKey] ?? [];
607 + const found = existing.some((entry) => entry.id === submission.id);
608 + return {
609 + ...current,
610 + [threadKey]: found
611 + ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
612 + : [...existing, submission],
613 + };
614 });
718 - appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
719 - setThreadComposerError(
720 - threadKey,
721 - error instanceof Error ? error.message : "Failed to save the queued message.",
722 - );
615 },
724 - );
725 - return messageId;
726 - },
727 - [
728 - activeThreadBusy,
729 - canSteerActiveTurn,
730 - followUpBehavior,
731 - saveQueuedRunEdit,
732 - selectedEnvironmentRuntime?.connectionState,
733 - selectedEnvironmentRuntime?.serverConfig,
734 - selectedThreadActivityRun?.status,
735 - selectedThreadCreation,
736 - selectedThreadRuntime?.status,
737 - selectedThreadShell,
738 - uploadThreadFeedback,
739 - ],
740 - );
616 + upload: () =>
617 + uploadThreadFeedback({
618 + environmentId: thread.environmentId,
619 + input: { threadId: thread.id, ...feedbackCommand },
620 + }),
621 + });
622 + return null;
623 + }
624
742 - const onChangeDraftMessage = useCallback(
743 - (value: string) => {
744 - if (!selectedThreadShell) {
745 - return;
746 - }
625 + // Resolved here rather than at drain time: the outbox can deliver minutes
626 + // later, and the choice belongs to the moment the user pressed send.
627 + // Steering travels as "auto" so a turn that ends in the meantime degrades
628 + // to a queued run on the server instead of failing the delivery and
629 + // bouncing the message back into the draft.
630 + const followUpAction = resolveComposerDispatchMode({
631 + running: activeThreadBusy && canSteerActiveTurn,
632 + alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
633 + activeTurnDefault: followUpBehavior,
634 + });
635 + const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
636 + (status) => status === "preparing" || status === "starting",
637 + );
638 + const followUpDispatchMode = setupRunning
639 + ? "queue"
640 + : followUpAction === "auto"
641 + ? null
642 + : followUpAction === "queue"
643 + ? "queue"
644 + : "auto";
645 +
646 + const metadata = makeQueuedMessageMetadata();
647 + const messageId = MessageId.make(metadata.messageId);
648 + clearThreadComposerError(threadKey);
649 + const enqueuePromise = enqueueThreadOutboxMessage({
650 + environmentId: selectedThreadShell.environmentId,
651 + threadId: selectedThreadShell.id,
652 + messageId,
653 + commandId: CommandId.make(metadata.commandId),
654 + text,
655 + attachments,
656 + context: draft.context,
657 + modelSelection,
658 + runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
659 + interactionMode: resolveProviderInteractionMode(
660 + provider,
661 + draft.interactionMode ?? thread.interactionMode,
662 + ),
663 + ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
664 + createdAt: metadata.createdAt,
665 + });
666 + clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
667 + enqueuePromise.then(
668 + () => scheduleUnusedComposerAttachmentCleanup(attachments),
669 + (error: unknown) => {
670 + // Restore text via merge (idempotent) but attachments via the uncapped
671 + // append: the merge path slots existing attachments first and truncates
672 + // at the send limit, which would silently drop this message's images if
673 + // the user attached new ones while the write was in flight.
674 + void mergeComposerDraftContent(threadKey, {
675 + text,
676 + context: draft.context,
677 + attachments: [],
678 + });
679 + appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
680 + setThreadComposerError(
681 + threadKey,
682 + error instanceof Error ? error.message : "Failed to save the queued message.",
683 + );
684 + },
685 + );
686 + return messageId;
687 + };
688
748 - const threadKey = activeComposerDraftKey(selectedThreadShell);
749 - setComposerDraftText(threadKey, value);
750 - },
751 - [selectedThreadShell],
752 - );
689 + const onChangeDraftMessage = (value: string) => {
690 + if (!selectedThreadShell) {
691 + return;
692 + }
693 +
694 + const threadKey = activeComposerDraftKey(selectedThreadShell);
695 + setComposerDraftText(threadKey, value);
696 + };
697
754 - const onPickDraftMedia = useCallback(async () => {
698 + const onPickDraftMedia = async () => {
699 if (!selectedThreadShell) {
700 return;
701 }
@@ -779,9 +723,9 @@ export function useThreadComposerState() {
723 if (problems.length > 0) {
724 Dialog.alert("Could not attach photo or video", problems.join("\n\n"));
725 }
782 - }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
726 + };
727
784 - const onPickDraftFiles = useCallback(async () => {
728 + const onPickDraftFiles = async () => {
729 if (!selectedThreadShell) {
730 return;
731 }
@@ -812,9 +756,9 @@ export function useThreadComposerState() {
756 if (problems.length > 0) {
757 Dialog.alert("Could not attach file", problems.join("\n\n"));
758 }
815 - }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
759 + };
760
817 - const onPasteIntoDraft = useCallback(async () => {
761 + const onPasteIntoDraft = async () => {
762 if (!selectedThreadShell) {
763 return;
764 }
@@ -901,144 +845,115 @@ export function useThreadComposerState() {
845 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
846 );
847 }
904 - }, [
905 - composerDrafts,
906 - reservePastedTextFileName,
907 - selectedEnvironmentRuntime?.serverConfig,
908 - selectedThreadShell,
909 - ]);
848 + };
849
911 - const onNativePasteImages = useCallback(
912 - async (uris: ReadonlyArray<string>) => {
913 - if (!selectedThreadShell || uris.length === 0) {
914 - return;
915 - }
850 + const onNativePasteImages = async (uris: ReadonlyArray<string>) => {
851 + if (!selectedThreadShell || uris.length === 0) {
852 + return;
853 + }
854
917 - const threadKey = activeComposerDraftKey(selectedThreadShell);
918 - const insertion = captureComposerDraftInsertion(threadKey);
919 - try {
920 - const images = await convertPastedImagesToAttachments({
921 - uris,
922 - existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
923 - });
924 - if (images.length > 0) {
925 - appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
926 - }
927 - } catch (error) {
928 - console.error("[native paste] error converting images", {
929 - environmentId: selectedThreadShell.environmentId,
930 - threadId: selectedThreadShell.id,
931 - uriCount: uris.length,
932 - ...safeErrorLogAttributes(error),
933 - });
855 + const threadKey = activeComposerDraftKey(selectedThreadShell);
856 + const insertion = captureComposerDraftInsertion(threadKey);
857 + try {
858 + const images = await convertPastedImagesToAttachments({
859 + uris,
860 + existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
861 + });
862 + if (images.length > 0) {
863 + appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
864 }
935 - },
936 - [composerDrafts, selectedThreadShell],
937 - );
865 + } catch (error) {
866 + console.error("[native paste] error converting images", {
867 + environmentId: selectedThreadShell.environmentId,
868 + threadId: selectedThreadShell.id,
869 + uriCount: uris.length,
870 + ...safeErrorLogAttributes(error),
871 + });
872 + }
873 + };
874
939 - const onNativePasteText = useCallback(
940 - async (paste: ComposerTextPaste) => {
941 - if (!selectedThreadShell) return;
942 - const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
943 - const advertisedMax =
944 - capabilities?.attachmentUploads === true
945 - ? capabilities.fileAttachments?.maxUploadBytes
946 - : undefined;
947 - if (advertisedMax === undefined) return;
875 + const onNativePasteText = async (paste: ComposerTextPaste) => {
876 + if (!selectedThreadShell) return;
877 + const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
878 + const advertisedMax =
879 + capabilities?.attachmentUploads === true
880 + ? capabilities.fileAttachments?.maxUploadBytes
881 + : undefined;
882 + if (advertisedMax === undefined) return;
883
949 - const threadKey = activeComposerDraftKey(selectedThreadShell);
950 - const insertion = { text: paste.value, ...paste.selection };
951 - const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
952 - try {
953 - const attachment = await createPastedTextComposerAttachment({
954 - text: paste.text,
955 - name: reservePastedTextFileName(
956 - threadKey,
957 - currentAttachments.map((item) => item.name),
958 - ),
959 - maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
960 - });
961 - const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
962 - appendReference: true,
963 - insertion,
964 - });
965 - if (rejectedCount > 0) {
966 - await removePersistedComposerAttachmentFile(attachment.fileUri);
967 - setPendingConnectionError(
968 - `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
969 - );
970 - }
971 - } catch (error) {
884 + const threadKey = activeComposerDraftKey(selectedThreadShell);
885 + const insertion = { text: paste.value, ...paste.selection };
886 + const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
887 + try {
888 + const attachment = await createPastedTextComposerAttachment({
889 + text: paste.text,
890 + name: reservePastedTextFileName(
891 + threadKey,
892 + currentAttachments.map((item) => item.name),
893 + ),
894 + maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
895 + });
896 + const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
897 + appendReference: true,
898 + insertion,
899 + });
900 + if (rejectedCount > 0) {
901 + await removePersistedComposerAttachmentFile(attachment.fileUri);
902 setPendingConnectionError(
973 - error instanceof Error ? error.message : "Could not attach pasted text.",
903 + `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
904 );
905 }
976 - },
977 - [
978 - composerDrafts,
979 - reservePastedTextFileName,
980 - selectedEnvironmentRuntime?.serverConfig,
981 - selectedThreadShell,
982 - ],
983 - );
906 + } catch (error) {
907 + setPendingConnectionError(
908 + error instanceof Error ? error.message : "Could not attach pasted text.",
909 + );
910 + }
911 + };
912
985 - const onRemoveDraftImage = useCallback(
986 - (imageId: string) => {
987 - if (!selectedThreadShell) {
988 - return;
989 - }
913 + const onRemoveDraftImage = (imageId: string) => {
914 + if (!selectedThreadShell) {
915 + return;
916 + }
917
991 - const threadKey = activeComposerDraftKey(selectedThreadShell);
992 - removeComposerDraftAttachment(threadKey, imageId);
993 - },
994 - [selectedThreadShell],
995 - );
918 + const threadKey = activeComposerDraftKey(selectedThreadShell);
919 + removeComposerDraftAttachment(threadKey, imageId);
920 + };
921
997 - const onUpdateModelSelection = useCallback(
998 - (value: ModelSelection) => {
999 - if (!selectedThreadKey) {
1000 - return;
1001 - }
1002 - const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
1003 - (candidate) => candidate.instanceId === value.instanceId,
1004 - );
1005 - updateComposerDraftSettings(selectedThreadKey, {
1006 - modelSelection: value,
1007 - ...(provider?.showInteractionModeToggle === false
1008 - ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
1009 - : {}),
1010 - });
1011 - },
1012 - [selectedEnvironmentRuntime?.serverConfig, selectedThreadKey],
1013 - );
922 + const onUpdateModelSelection = (value: ModelSelection) => {
923 + if (!selectedThreadKey) {
924 + return;
925 + }
926 + const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
927 + (candidate) => candidate.instanceId === value.instanceId,
928 + );
929 + updateComposerDraftSettings(selectedThreadKey, {
930 + modelSelection: value,
931 + ...(provider?.showInteractionModeToggle === false
932 + ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
933 + : {}),
934 + });
935 + };
936
1015 - const onUpdateRuntimeMode = useCallback(
1016 - (value: RuntimeMode) => {
1017 - if (!selectedThreadKey) {
1018 - return;
1019 - }
1020 - updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
1021 - },
1022 - [selectedThreadKey],
1023 - );
937 + const onUpdateRuntimeMode = (value: RuntimeMode) => {
938 + if (!selectedThreadKey) {
939 + return;
940 + }
941 + updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
942 + };
943
1025 - const onUpdateInteractionMode = useCallback(
1026 - (value: ProviderInteractionMode) => {
1027 - if (!selectedThreadKey) {
1028 - return;
1029 - }
1030 - const modelSelection =
1031 - getComposerDraftSnapshot(selectedThreadKey).modelSelection ??
1032 - selectedThread?.modelSelection;
1033 - const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
1034 - (candidate) => candidate.instanceId === modelSelection?.instanceId,
1035 - );
1036 - updateComposerDraftSettings(selectedThreadKey, {
1037 - interactionMode: resolveProviderInteractionMode(provider, value),
1038 - });
1039 - },
1040 - [selectedEnvironmentRuntime?.serverConfig, selectedThread?.modelSelection, selectedThreadKey],
1041 - );
944 + const onUpdateInteractionMode = (value: ProviderInteractionMode) => {
945 + if (!selectedThreadKey) {
946 + return;
947 + }
948 + const modelSelection =
949 + getComposerDraftSnapshot(selectedThreadKey).modelSelection ?? selectedThread?.modelSelection;
950 + const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
951 + (candidate) => candidate.instanceId === modelSelection?.instanceId,
952 + );
953 + updateComposerDraftSettings(selectedThreadKey, {
954 + interactionMode: resolveProviderInteractionMode(provider, value),
955 + });
956 + };
957
958 return {
959 feedbackSubmissions,