Skip to content
TypeScript

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

Julius Marmingecf84fc7772b0
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index a693803e4f1..fb55cea4b1f 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -2,6 +2,8 @@ import * as Dialog from "../../components/ui/Dialog";
import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import { AsyncResult } from "effect/reactivity";
import { useAtomValue } from "@effect/atom-react";
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
import { pastedTextDisposition, replaceTextSelection } from "@t3tools/client-runtime/text-paste";
@@ -24,16 +26,7 @@ import {
} from "@t3tools/shared/usageLimits";
import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
import type { ReactNode } from "react";
-import {
- memo,
- useCallback,
- useEffect,
- useLayoutEffect,
- useMemo,
- useRef,
- useState,
- type RefObject,
-} from "react";
+import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { Keyboard, Platform, Pressable, View, type ViewStyle } from "react-native";
import { composerImageGallery } from "../../lib/composerImageGallery";
import { filePreviewGallery } from "../../lib/filePreviewGallery";
@@ -332,7 +325,7 @@ export function ComposerSurface(props: {
);
}
-export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
+export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps) {
const project = useProject(scopeProjectRef(props.environmentId, props.selectedThread.projectId));
const { themeVariables: materialTheme } = useAppearancePreferences();
const composerPanel = materialTheme["--color-composer-panel"];
@@ -361,10 +354,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
props.draftMessage.trim().length > 0 ||
props.draftAttachments.length > 0 ||
(queuedEdit?.existingAttachments.length ?? 0) > 0;
- const stripAttachments = useMemo(
- () => composerStripAttachments(props.draftAttachments),
- [props.draftAttachments],
- );
+ const stripAttachments = composerStripAttachments(props.draftAttachments);
const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
@@ -394,14 +384,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
currentModelSelection,
props.selectedThread.projectId,
);
- const selectedProviderStatus = useMemo(() => {
+ const selectedProviderStatus = (() => {
if (!props.serverConfig) return null;
return (
props.serverConfig.providers.find(
(p) => p.instanceId === props.selectedThread.modelSelection.instanceId,
) ?? null
);
- }, [props.serverConfig, props.selectedThread.modelSelection.instanceId]);
+ })();
const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerDraftKey = props.draftKey ?? composerOwnerKey;
const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
@@ -424,7 +414,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
props.serverConfig?.providers ?? [],
props.serverConfig?.usageLimitSources ?? [],
);
- const openUsageLimits = useCallback(() => {
+ const openUsageLimits = () => {
const report = collectProviderUsageLimits(
currentModelSelection.instanceId,
props.serverConfig?.providers ?? [],
@@ -436,7 +426,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
Dialog.alert("Usage limits unavailable", "This provider does not currently report limits.");
}
return report !== null;
- }, [currentModelSelection.instanceId, onShowUsageLimits, props.serverConfig]);
+ };
const composerMenu = useComposerCommandMenu({
draftMessage: props.draftMessage,
@@ -504,22 +494,19 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onExpandedChange?.(isExpanded);
}, [isExpanded, onExpandedChange]);
- const onPressPreview = useCallback(
- (source: FilePreviewSource) => {
- wasExpandedBeforePreviewRef.current = isFocused;
- setPreviewVideo(null);
- setPreviewFile(
- (current) =>
- current ?? {
- ...source,
- gallery: filePreviewGallery(source, composerImageGallery(props.draftAttachments)),
- },
- );
- },
- [isFocused, props.draftAttachments],
- );
+ const onPressPreview = (source: FilePreviewSource) => {
+ wasExpandedBeforePreviewRef.current = isFocused;
+ setPreviewVideo(null);
+ setPreviewFile(
+ (current) =>
+ current ?? {
+ ...source,
+ gallery: filePreviewGallery(source, composerImageGallery(props.draftAttachments)),
+ },
+ );
+ };
- const closePreview = useCallback(() => {
+ const closePreview = () => {
setPreviewFile(null);
setPreviewVideo(null);
if (wasExpandedBeforePreviewRef.current) {
@@ -527,151 +514,106 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
if (navigation.isFocused()) inputRef.current?.focus();
}, 100);
}
- }, [inputRef, navigation]);
+ };
- const onPressVideo = useCallback(
- (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
- wasExpandedBeforePreviewRef.current = isFocused;
- setPreviewFile(null);
- setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
- },
- [isFocused],
- );
+ const onPressVideo = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
+ wasExpandedBeforePreviewRef.current = isFocused;
+ setPreviewFile(null);
+ setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
+ };
const onEditorFocusChange = props.onEditorFocusChange;
- const handleFocus = useCallback(() => {
+ const handleFocus = () => {
setIsFocused(true);
onExpandedChange?.(true);
onEditorFocusChange?.(true);
- }, [onEditorFocusChange, onExpandedChange]);
+ };
- const handleBlur = useCallback(() => {
+ const handleBlur = () => {
setIsFocused(false);
if (!settingsSheetPresentation.keepsComposerExpanded) {
onExpandedChange?.(false);
}
onEditorFocusChange?.(false);
- }, [onEditorFocusChange, onExpandedChange, settingsSheetPresentation.keepsComposerExpanded]);
- const handleSend = useCallback(
- async (followUp?: ActiveTurnComposerAction) => {
- if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
- if (
- usageLimitsOffered &&
- isUsageLimitsCommand(props.draftMessage) &&
- props.draftAttachments.length === 0
- ) {
- if (openUsageLimits()) onChangeDraftMessage("");
- return;
- }
- const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
- if (inFlightThreadIdsRef.current.has(threadKey)) return;
- inFlightThreadIdsRef.current.add(threadKey);
- try {
- const messageId = await onSendMessage(followUp);
- if (messageId === null) {
- return;
- }
- // Armed after the send so its preference read and native Activity start don't contend
- // with the queued-message feedback on the tap frame.
- armAgentAwarenessLiveActivityForLocalWork({
- environmentId: props.environmentId,
- threadTitle: props.selectedThread.title,
- projectTitle: props.environmentLabel ?? "T3 Code",
- });
- } finally {
- inFlightThreadIdsRef.current.delete(threadKey);
- }
- },
- [
- props.draftMessage,
- props.draftAttachments.length,
- onChangeDraftMessage,
- openUsageLimits,
- usageLimitsOffered,
- onSendMessage,
- props.environmentId,
- props.environmentLabel,
- props.selectedThread.id,
- props.selectedThread.title,
- voiceInput.blocksSubmission,
- ],
- );
+ };
+ const handleSend = async (followUp?: ActiveTurnComposerAction) => {
+ if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
+ if (
+ usageLimitsOffered &&
+ isUsageLimitsCommand(props.draftMessage) &&
+ props.draftAttachments.length === 0
+ ) {
+ if (openUsageLimits()) onChangeDraftMessage("");
+ return;
+ }
+ const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
+ if (inFlightThreadIdsRef.current.has(threadKey)) return;
+ inFlightThreadIdsRef.current.add(threadKey);
+ const sent = await settlePromise(() => onSendMessage(followUp));
+ inFlightThreadIdsRef.current.delete(threadKey);
+ if (AsyncResult.isFailure(sent)) {
+ // The composer state already surfaces send errors; only the lock needed releasing.
+ console.error("[composer] send failed", squashAtomCommandFailure(sent));
+ return;
+ }
+ if (sent.value === null) return;
+ // Armed after the send so its preference read and native Activity start don't contend
+ // with the queued-message feedback on the tap frame.
+ armAgentAwarenessLiveActivityForLocalWork({
+ environmentId: props.environmentId,
+ threadTitle: props.selectedThread.title,
+ projectTitle: props.environmentLabel ?? "T3 Code",
+ });
+ };
const lockedProviderInstanceId = props.canSwitchProvider
? undefined
: currentModelSelection.instanceId;
- const modelOptions = useMemo(
- () =>
- buildModelOptions(
- props.serverConfig,
- currentModelSelection,
- lockedProviderInstanceId,
- props.selectedThread.projectId,
- ),
- [
- props.serverConfig,
- currentModelSelection,
- lockedProviderInstanceId,
- props.selectedThread.projectId,
- ],
+ const modelOptions = buildModelOptions(
+ props.serverConfig,
+ currentModelSelection,
+ lockedProviderInstanceId,
+ props.selectedThread.projectId,
);
- const threadProviderGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
+ const threadProviderGroups = groupByProvider(modelOptions);
const currentModelOption =
modelOptions.find(
(option) =>
option.selection.instanceId === currentModelSelection.instanceId &&
option.selection.model === currentModelSelection.model,
) ?? null;
- const providerOptionDescriptors = useMemo(
- () =>
- resolveProviderOptionDescriptors({
- capabilities: currentModelOption?.capabilities,
- selections: currentModelSelection.options,
- }),
- [currentModelOption?.capabilities, currentModelSelection.options],
- );
+ const providerOptionDescriptors = resolveProviderOptionDescriptors({
+ capabilities: currentModelOption?.capabilities,
+ selections: currentModelSelection.options,
+ });
const settingsOwnerId = composerOwnerKey;
- const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
- () => ({
- ownerId: settingsOwnerId,
- environmentId: props.environmentId,
- projectId: props.selectedThread.projectId,
- providerInstanceId: currentModelSelection.instanceId,
- ...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {}),
- providerGroups: threadProviderGroups,
- selectedModel: currentModelSelection,
- reportedModelSelection: props.reportedModelSelection,
- onSelectModel: (option) =>
- props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),
- optionDescriptors: providerOptionDescriptors,
- onUpdateOptionSelections: (options) => {
- rememberModelOptions(
- currentModelSelection.instanceId,
- currentModelSelection.model,
- options ?? [],
- );
- props.onUpdateModelSelection({ ...currentModelSelection, options });
- },
- runtimeMode: currentRuntimeMode,
- onUpdateRuntimeMode: props.onUpdateRuntimeMode,
- }),
- [
- currentModelSelection,
- props.reportedModelSelection,
- currentRuntimeMode,
- props.onUpdateModelSelection,
- props.onUpdateRuntimeMode,
- providerOptionDescriptors,
- settingsOwnerId,
- lockedProviderInstanceId,
- threadProviderGroups,
- props.selectedThread.projectId,
- ],
- );
- const openSettings = useCallback(() => {
+ const settingsRouteSession = {
+ ownerId: settingsOwnerId,
+ environmentId: props.environmentId,
+ projectId: props.selectedThread.projectId,
+ providerInstanceId: currentModelSelection.instanceId,
+ ...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {}),
+ providerGroups: threadProviderGroups,
+ selectedModel: currentModelSelection,
+ reportedModelSelection: props.reportedModelSelection,
+ onSelectModel: (option) =>
+ props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),
+ optionDescriptors: providerOptionDescriptors,
+ onUpdateOptionSelections: (options) => {
+ rememberModelOptions(
+ currentModelSelection.instanceId,
+ currentModelSelection.model,
+ options ?? [],
+ );
+ props.onUpdateModelSelection({ ...currentModelSelection, options });
+ },
+ runtimeMode: currentRuntimeMode,
+ onUpdateRuntimeMode: props.onUpdateRuntimeMode,
+ } satisfies ExistingThreadSettingsRouteSession;
+ const openSettings = () => {
settingsRoutePresentation.present(settingsRouteSession);
settingsSheetPresentation.open();
- }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
+ };
useEffect(() => {
if (settingsSheetPresentation.isActive) {
@@ -688,17 +630,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
}, [navigation, settingsSheetPresentation.isVisible]);
- useFocusEffect(
- useCallback(() => {
- if (!settingsRoutePresentedRef.current) {
- return;
- }
+ useFocusEffect(() => {
+ if (!settingsRoutePresentedRef.current) {
+ return;
+ }
- settingsRoutePresentedRef.current = false;
- settingsSheetPresentation.onDismissed();
- settingsRoutePresentation.clear(settingsOwnerId);
- }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
- );
+ settingsRoutePresentedRef.current = false;
+ settingsSheetPresentation.onDismissed();
+ settingsRoutePresentation.clear(settingsOwnerId);
+ });
useEffect(
() =>
@@ -1140,4 +1080,4 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
<FilePreviewModal source={previewFile} onRequestClose={closePreview} />
</Animated.View>
);
-});
+};
diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
index b6187d2cae4..20e5b2f2e9a 100644
--- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx
+++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
@@ -4,7 +4,7 @@ import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/co
import { Atom } from "effect/reactivity";
import { Image } from "expo-image";
import * as Haptics from "expo-haptics";
-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useEffectEvent, useRef, useState } from "react";
import { Animated, Platform, Pressable, ScrollView, View } from "react-native";
import { Gesture, GestureDetector, GestureHandlerRootView } from "react-native-gesture-handler";
import ReanimatedSwipeable, {
@@ -113,12 +113,9 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
busyRef.current = true;
setBusyRunId(runId);
void Haptics.selectionAsync();
- try {
- await reorder({ ...target, input: { threadId: target.threadId, runId, beforeRunId } });
- } finally {
- busyRef.current = false;
- setBusyRunId(null);
- }
+ await reorder({ ...target, input: { threadId: target.threadId, runId, beforeRunId } });
+ busyRef.current = false;
+ setBusyRunId(null);
};
const act = async (runId: RunId, action: QueueAction) => {
@@ -150,23 +147,20 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
busyRef.current = true;
setBusyRunId(runId);
void Haptics.selectionAsync();
- try {
- if (action === "remove") {
- await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
- } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
- await promote({
- ...target,
- input: {
- threadId: target.threadId,
- queuedRunId: runId,
- targetRunId: workflow.activeRun.id,
- },
- });
- }
- } finally {
- busyRef.current = false;
- setBusyRunId(null);
+ if (action === "remove") {
+ await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
+ } else if (workflow?.activeRun && workflow.canPromoteToSteer) {
+ await promote({
+ ...target,
+ input: {
+ threadId: target.threadId,
+ queuedRunId: runId,
+ targetRunId: workflow.activeRun.id,
+ },
+ });
}
+ busyRef.current = false;
+ setBusyRunId(null);
};
const canReorder = workflow?.canReorder === true && queuedRuns.length > 1;
@@ -203,12 +197,9 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
if (busyRef.current) return;
busyRef.current = true;
setResuming(true);
- try {
- await resume({ ...target, input: { threadId: target.threadId } });
- } finally {
- busyRef.current = false;
- setResuming(false);
- }
+ await resume({ ...target, input: { threadId: target.threadId } });
+ busyRef.current = false;
+ setResuming(false);
}}
/>
</View>
@@ -596,22 +587,19 @@ function QueueDragHandle(props: {
onMove: (y: number) => void;
onEnd: (y: number, success: boolean) => void;
}) {
- const latest = useRef(props);
- useLayoutEffect(() => {
- latest.current = props;
- });
- const gesture = useMemo(
- () =>
- Gesture.Pan()
- .enabled(!props.disabled)
- .minDistance(0)
- .shouldCancelWhenOutside(false)
- .runOnJS(true)
- .onStart(() => latest.current.onStart())
- .onUpdate((event) => latest.current.onMove(event.translationY))
- .onFinalize((event, success) => latest.current.onEnd(event.translationY, success)),
- [props.disabled],
- );
+ // Gesture callbacks fire outside render, so effect events read the latest
+ // props without rebuilding the gesture.
+ const onStart = useEffectEvent(() => props.onStart());
+ const onMove = useEffectEvent((y: number) => props.onMove(y));
+ const onEnd = useEffectEvent((y: number, success: boolean) => props.onEnd(y, success));
+ const gesture = Gesture.Pan()
+ .enabled(!props.disabled)
+ .minDistance(0)
+ .shouldCancelWhenOutside(false)
+ .runOnJS(true)
+ .onStart(() => onStart())
+ .onUpdate((event) => onMove(event.translationY))
+ .onFinalize((event, success) => onEnd(event.translationY, success));
return (
<GestureDetector gesture={gesture}>
<View
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 690973578fd..ce91de47907 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -11,7 +11,7 @@ import {
useNavigation,
type StaticScreenProps,
} from "@react-navigation/native";
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useEffect, useRef, useState, type ReactNode } from "react";
import * as Option from "effect/Option";
import {
AuthOrchestrationOperateScope,
@@ -294,7 +294,7 @@ function ThreadRouteContent(
label: "load earlier thread history",
reportFailure: false,
});
- const historyControls = useMemo(() => {
+ const historyControls = (() => {
const history = selectedThreadDetailState.history;
if (!selectedThread) {
return undefined;
@@ -313,7 +313,7 @@ function ThreadRouteContent(
});
},
};
- }, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]);
+ })();
const navigation = useNavigation();
const openPullRequest = useOpenPullRequest();
const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
@@ -321,7 +321,7 @@ function ThreadRouteContent(
const mergeBackRun =
selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
const mergeBackBusyRef = useRef(false);
- const handleMergeBack = useCallback(async () => {
+ const handleMergeBack = async () => {
if (
mergeBackBusyRef.current ||
!selectedThread ||
@@ -331,25 +331,22 @@ function ThreadRouteContent(
return;
}
mergeBackBusyRef.current = true;
- try {
- const result = await mergeBack({
- environmentId: selectedThread.environmentId,
- input: {
- sourceThreadId: selectedThread.id,
- targetThreadId: mergeBackTargetThreadId,
- runId: mergeBackRun.id,
- creationSource: "mobile",
- },
- });
- if (result._tag !== "Success") return;
- navigation.navigate("Thread", {
- environmentId: selectedThread.environmentId,
- threadId: mergeBackTargetThreadId,
- });
- } finally {
- mergeBackBusyRef.current = false;
- }
- }, [mergeBack, mergeBackRun, mergeBackTargetThreadId, navigation, selectedThread]);
+ const result = await mergeBack({
+ environmentId: selectedThread.environmentId,
+ input: {
+ sourceThreadId: selectedThread.id,
+ targetThreadId: mergeBackTargetThreadId,
+ runId: mergeBackRun.id,
+ creationSource: "mobile",
+ },
+ });
+ mergeBackBusyRef.current = false;
+ if (result._tag !== "Success") return;
+ navigation.navigate("Thread", {
+ environmentId: selectedThread.environmentId,
+ threadId: mergeBackTargetThreadId,
+ });
+ };
const params = props.route.params;
const environmentIdRaw = firstRouteParam(params.environmentId);
const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
@@ -402,31 +399,25 @@ function ThreadRouteContent(
});
}, [props.renderInspector, routeThreadIdentity]);
- useFocusEffect(
- useCallback(() => {
- return () => {
- if (props.renderInspector === undefined) {
- setInspectorSelection(null);
- }
- };
- }, [props.renderInspector]),
- );
+ useFocusEffect(() => {
+ return () => {
+ if (props.renderInspector === undefined) {
+ setInspectorSelection(null);
+ }
+ };
+ });
const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
- const selectedThreadWithDraftSettings = useMemo(
- () =>
- selectedThread
- ? {
- ...selectedThread,
- modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
- runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
- interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
- }
- : null,
- [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
- );
+ const selectedThreadWithDraftSettings = selectedThread
+ ? {
+ ...selectedThread,
+ modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
+ runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
+ interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
+ }
+ : null;
const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
const headerSubtitle = [
@@ -447,32 +438,25 @@ function ThreadRouteContent(
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
});
- const terminalMenuSessions = useMemo(
- () =>
- buildTerminalMenuSessions({
- knownSessions: knownTerminalSessions ?? [],
- workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
- }),
- [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
- );
+ const terminalMenuSessions = buildTerminalMenuSessions({
+ knownSessions: knownTerminalSessions ?? [],
+ workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
+ });
const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
- const handleReconnectEnvironment = useCallback(() => {
+ const handleReconnectEnvironment = () => {
if (!environmentId) {
return;
}
onReconnectEnvironment(environmentId);
- }, [environmentId, onReconnectEnvironment]);
+ };
- const gitActionProgressTarget = useMemo(
- () => ({
- environmentId: selectedThread?.environmentId ?? null,
- cwd: selectedThreadCwd,
- }),
- [selectedThread?.environmentId, selectedThreadCwd],
- );
+ const gitActionProgressTarget = {
+ environmentId: selectedThread?.environmentId ?? null,
+ cwd: selectedThreadCwd,
+ };
const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
- const handleOpenGitInspector = useCallback(() => {
+ const handleOpenGitInspector = () => {
if (!fileInspector.supported) {
if (selectedThread === null) {
return;
@@ -485,8 +469,8 @@ function ThreadRouteContent(
}
setInspectorSelection({ routeThreadIdentity, mode: "git" });
showAuxiliaryPane("inspector");
- }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
- const handleOpenFilesInspector = useCallback(() => {
+ };
+ const handleOpenFilesInspector = () => {
if (selectedThread === null || selectedThreadCwd === null) {
return;
}
@@ -502,115 +486,67 @@ function ThreadRouteContent(
mode: props.renderInspector === undefined ? "files" : "route",
});
showAuxiliaryPane("inspector");
- }, [
- fileInspector.supported,
- navigation,
- props.renderInspector,
- routeThreadIdentity,
- selectedThread,
- selectedThreadCwd,
- showAuxiliaryPane,
- ]);
- const inspectorToggleActionRef = useRef({
- inspectorMode,
- openFilesInspector: handleOpenFilesInspector,
- toggleAuxiliaryPane,
- });
- inspectorToggleActionRef.current = {
- inspectorMode,
- openFilesInspector: handleOpenFilesInspector,
- toggleAuxiliaryPane,
};
- const handleToggleInspector = useCallback(() => {
- const action = inspectorToggleActionRef.current;
- if (action.inspectorMode === null) {
- action.openFilesInspector();
+ const handleToggleInspector = () => {
+ if (inspectorMode === null) {
+ handleOpenFilesInspector();
return;
}
- action.toggleAuxiliaryPane();
- }, []);
- const handleSelectInspectorFile = useCallback(
- (path: string) => {
- if (selectedThread === null) {
- return;
- }
- const params = {
- environmentId: String(selectedThread.environmentId),
- threadId: String(selectedThread.id),
- path: path.split("/").filter((segment) => segment.length > 0),
- };
- if (fileInspector.supported) {
- navigation.navigate("ThreadFile", params);
- return;
- }
+ toggleAuxiliaryPane();
+ };
+ const handleSelectInspectorFile = (path: string) => {
+ if (selectedThread === null) {
+ return;
+ }
+ const params = {
+ environmentId: String(selectedThread.environmentId),
+ threadId: String(selectedThread.id),
+ path: path.split("/").filter((segment) => segment.length > 0),
+ };
+ if (fileInspector.supported) {
navigation.navigate("ThreadFile", params);
- },
- [fileInspector.supported, navigation, selectedThread],
- );
+ return;
+ }
+ navigation.navigate("ThreadFile", params);
+ };
const safeAreaInsets = useSafeAreaInsets();
const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
- const GitInspector = useCallback(
- () => (
- <GitOverviewSheet
+ const GitInspector = () => (
+ <GitOverviewSheet
+ headerInset={inspectorHeaderInset}
+ presentation="inspector"
+ route={{ params: props.route.params }}
+ />
+ );
+ const FilesInspector = () =>
+ selectedThread !== null && selectedThreadCwd !== null ? (
+ <ThreadFileNavigatorPane
+ cwd={selectedThreadCwd}
+ environmentId={selectedThread.environmentId}
headerInset={inspectorHeaderInset}
- presentation="inspector"
- route={{ params: props.route.params }}
+ projectName={selectedThreadProject?.title ?? "Files"}
+ selectedPath={null}
+ onSelectFile={handleSelectInspectorFile}
/>
- ),
- [inspectorHeaderInset, props.route.params],
- );
- const FilesInspector = useCallback(
- () =>
- selectedThread !== null && selectedThreadCwd !== null ? (
- <ThreadFileNavigatorPane
- cwd={selectedThreadCwd}
- environmentId={selectedThread.environmentId}
- headerInset={inspectorHeaderInset}
- projectName={selectedThreadProject?.title ?? "Files"}
- selectedPath={null}
- onSelectFile={handleSelectInspectorFile}
- />
- ) : null,
- [
- handleSelectInspectorFile,
- inspectorHeaderInset,
- selectedThread,
- selectedThreadCwd,
- selectedThreadProject?.title,
- ],
- );
- const RouteInspector = useCallback(
- () => props.renderInspector?.(inspectorHeaderInset),
- [inspectorHeaderInset, props.renderInspector],
- );
- const renderInspectorStack = useCallback(
- () =>
- inspectorMode === null ? null : (
- <ThreadInspectorContentStack
- renderFiles={FilesInspector}
- renderGit={GitInspector}
- mode={inspectorMode}
- resetKeys={[routeThreadIdentity, selectedThreadCwd]}
- renderRoute={props.renderInspector ? RouteInspector : undefined}
- />
- ),
- [
- FilesInspector,
- GitInspector,
- RouteInspector,
- inspectorMode,
- props.renderInspector,
- routeThreadIdentity,
- selectedThreadCwd,
- ],
- );
+ ) : null;
+ const RouteInspector = () => props.renderInspector?.(inspectorHeaderInset);
+ const renderInspectorStack = () =>
+ inspectorMode === null ? null : (
+ <ThreadInspectorContentStack
+ renderFiles={FilesInspector}
+ renderGit={GitInspector}
+ mode={inspectorMode}
+ resetKeys={[routeThreadIdentity, selectedThreadCwd]}
+ renderRoute={props.renderInspector ? RouteInspector : undefined}
+ />
+ );
const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
useRegisterWorkspaceInspector(activeInspectorRenderer);
- const handleOpenConnectionEditor = useCallback(() => {
+ const handleOpenConnectionEditor = () => {
void navigation.navigate("Connections");
- }, [navigation]);
- const handleStopThread = useCallback(() => {
+ };
+ const handleStopThread = () => {
if (
!selectedThread ||
!readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
@@ -625,35 +561,32 @@ function ThreadRouteContent(
runId: composer.interruptibleRunId,
},
});
- }, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
+ };
- const handleOpenTerminal = useCallback(
- (nextTerminalId?: string | null) => {
- terminalDebugLog("terminal-menu:open-existing", {
- terminalId: nextTerminalId ?? null,
- hasThread: Boolean(selectedThread),
- hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
- });
+ const handleOpenTerminal = (nextTerminalId?: string | null) => {
+ terminalDebugLog("terminal-menu:open-existing", {
+ terminalId: nextTerminalId ?? null,
+ hasThread: Boolean(selectedThread),
+ hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
+ });
- if (
- !selectedThread ||
- !selectedThreadProject?.workspaceRoot ||
- (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
- !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
- ) {
- return;
- }
+ if (
+ !selectedThread ||
+ !selectedThreadProject?.workspaceRoot ||
+ (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
+ ) {
+ return;
+ }
- void navigation.navigate("ThreadTerminal", {
- environmentId: String(selectedThread.environmentId),
- threadId: String(selectedThread.id),
- ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
- });
- },
- [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
- );
+ void navigation.navigate("ThreadTerminal", {
+ environmentId: String(selectedThread.environmentId),
+ threadId: String(selectedThread.id),
+ ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
+ });
+ };
- const handleOpenNewTerminal = useCallback(() => {
+ const handleOpenNewTerminal = () => {
terminalDebugLog("terminal-menu:open-new", {
hasThread: Boolean(selectedThread),
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
@@ -680,92 +613,76 @@ function ThreadRouteContent(
threadId: String(selectedThread.id),
terminalId: nextId,
});
- }, [
- knownTerminalSessions,
- navigation,
- selectedThread,
- selectedThreadProject?.workspaceRoot,
- terminalMenuSessions,
- ]);
+ };
+
+ const handleRunProjectScript = async (script: ProjectScript) => {
+ terminalDebugLog("project-script:press", {
+ scriptId: script.id,
+ command: script.command,
+ hasThread: Boolean(selectedThread),
+ hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
+ });
- const handleRunProjectScript = useCallback(
- async (script: ProjectScript) => {
- terminalDebugLog("project-script:press", {
+ if (
+ !selectedThread ||
+ !selectedThreadProject?.workspaceRoot ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
+ ) {
+ terminalDebugLog("project-script:abort", {
scriptId: script.id,
- command: script.command,
- hasThread: Boolean(selectedThread),
- hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
+ reason: "no-thread-workspace-or-terminal-access",
});
+ return;
+ }
- if (
- !selectedThread ||
- !selectedThreadProject?.workspaceRoot ||
- !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
- ) {
- terminalDebugLog("project-script:abort", {
- scriptId: script.id,
- reason: "no-thread-workspace-or-terminal-access",
- });
- return;
- }
-
- const targetTerminalId = resolveProjectScriptTerminalId({
- existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
- ...(knownTerminalSessions === null ||
- !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
- ? { uniqueSuffix: uuidv4() }
- : {}),
- hasRunningTerminal: terminalMenuSessions.some(
- (session) => session.status === "running" || session.status === "starting",
- ),
- });
- const preferredWorktreePath = resolvePreferredThreadWorktreePath({
- threadShellWorktreePath: selectedThread.worktreePath ?? null,
- threadDetailWorktreePath: selectedThreadDetailWorktreePath,
- });
- const cwd = projectScriptCwd({
- project: { cwd: selectedThreadProject.workspaceRoot },
- worktreePath: preferredWorktreePath,
- });
- const env = projectScriptRuntimeEnv({
- project: { cwd: selectedThreadProject.workspaceRoot },
- worktreePath: preferredWorktreePath,
- });
- stagePendingTerminalLaunch({
- target: {
- environmentId: selectedThread.environmentId,
- threadId: selectedThread.id,
- terminalId: targetTerminalId,
- },
- launch: {
- cwd,
- worktreePath: preferredWorktreePath,
- env,
- initialInput: `${script.command}\r`,
- },
- });
- terminalDebugLog("project-script:staged", {
- scriptId: script.id,
+ const targetTerminalId = resolveProjectScriptTerminalId({
+ existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
+ ...(knownTerminalSessions === null ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
+ ? { uniqueSuffix: uuidv4() }
+ : {}),
+ hasRunningTerminal: terminalMenuSessions.some(
+ (session) => session.status === "running" || session.status === "starting",
+ ),
+ });
+ const preferredWorktreePath = resolvePreferredThreadWorktreePath({
+ threadShellWorktreePath: selectedThread.worktreePath ?? null,
+ threadDetailWorktreePath: selectedThreadDetailWorktreePath,
+ });
+ const cwd = projectScriptCwd({
+ project: { cwd: selectedThreadProject.workspaceRoot },
+ worktreePath: preferredWorktreePath,
+ });
+ const env = projectScriptRuntimeEnv({
+ project: { cwd: selectedThreadProject.workspaceRoot },
+ worktreePath: preferredWorktreePath,
+ });
+ stagePendingTerminalLaunch({
+ target: {
+ environmentId: selectedThread.environmentId,
+ threadId: selectedThread.id,
terminalId: targetTerminalId,
+ },
+ launch: {
cwd,
worktreePath: preferredWorktreePath,
- });
+ env,
+ initialInput: `${script.command}\r`,
+ },
+ });
+ terminalDebugLog("project-script:staged", {
+ scriptId: script.id,
+ terminalId: targetTerminalId,
+ cwd,
+ worktreePath: preferredWorktreePath,
+ });
- void navigation.navigate("ThreadTerminal", {
- environmentId: String(selectedThread.environmentId),
- threadId: String(selectedThread.id),
- terminalId: targetTerminalId,
- });
- },
- [
- navigation,
- selectedThread,
- selectedThreadDetailWorktreePath,
- selectedThreadProject,
- terminalMenuSessions,
- knownTerminalSessions,
- ],
- );
+ void navigation.navigate("ThreadTerminal", {
+ environmentId: String(selectedThread.environmentId),
+ threadId: String(selectedThread.id),
+ terminalId: targetTerminalId,
+ });
+ };
const threadGitControlProps = {
environmentId: environmentIdRaw ?? "",
threadId: threadId ?? "",
@@ -804,7 +721,7 @@ function ThreadRouteContent(
onPull: gitActions.onPullSelectedThreadBranch,
onRunAction: gitActions.onRunSelectedThreadGitAction,
};
- const handleEditFailedCreation = useCallback(async () => {
+ const handleEditFailedCreation = async () => {
const creation = selectedThreadCreation?.message;
if (!creation?.creation || routeThreadIdentity === null) {
return;
@@ -833,7 +750,7 @@ function ThreadRouteContent(
},
}),
);
- }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
+ };
const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({
environmentId: selectedThread?.environmentId ?? null,
@@ -857,66 +774,59 @@ function ThreadRouteContent(
? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
: (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
- const handleCancelWorktreeSetup = useCallback(() => {
+ const handleCancelWorktreeSetup = () => {
if (!selectedThread) return;
void cancelWorktreeSetup({
environmentId: selectedThread.environmentId,
input: { threadId: selectedThread.id },
});
- }, [cancelWorktreeSetup, selectedThread]);
+ };
const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
const localResendBusy = useRef(false);
const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
- const handleWorkLocally = useCallback(async () => {
+ const handleWorkLocally = async () => {
if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
return;
localResendBusy.current = true;
- try {
- const result = await cancelWorktreeSetup({
- environmentId: selectedThread.environmentId,
- input: { threadId: selectedThread.id },
- });
- if (result._tag !== "Success" || !result.value.cancelled) return;
- // V2 accepts the launch before setup runs, so cancellation never rejects
- // the original outbox delivery. Reuse the server-owned prompt and uploads.
- const metadata = makeTurnCommandMetadata();
- const launched = await startLocalThread({
- environmentId: selectedThread.environmentId,
- input: buildProjectThreadStartTurnInput({
- ...metadata,
- projectId: selectedThread.projectId,
- projectCwd: selectedThreadProject.workspaceRoot,
- text: setupMessage.text,
- ...(setupMessage.context ? { context: setupMessage.context } : {}),
- uploadedAttachments: setupMessage.attachments,
- modelSelection: selectedThread.modelSelection,
- runtimeMode: selectedThread.runtimeMode,
- interactionMode: selectedThread.interactionMode,
- workspaceMode: "local",
- branch: null,
- worktreePath: null,
- startFromOrigin: false,
- worktreeBranchName: "",
- }),
- });
- if (launched._tag !== "Success") return;
- navigation.dispatch(
- StackActions.replace("Thread", {
- environmentId: String(selectedThread.environmentId),
- threadId: metadata.threadId,
- }),
- );
- } finally {
+ const result = await cancelWorktreeSetup({
+ environmentId: selectedThread.environmentId,
+ input: { threadId: selectedThread.id },
+ });
+ if (result._tag !== "Success" || !result.value.cancelled) {
localResendBusy.current = false;
+ return;
}
- }, [
- cancelWorktreeSetup,
- navigation,
- selectedThread,
- selectedThreadProject,
- setupMessage,
- startLocalThread,
- ]);
+ // V2 accepts the launch before setup runs, so cancellation never rejects
+ // the original outbox delivery. Reuse the server-owned prompt and uploads.
+ const metadata = makeTurnCommandMetadata();
+ const launched = await startLocalThread({
+ environmentId: selectedThread.environmentId,
+ input: buildProjectThreadStartTurnInput({
+ ...metadata,
+ projectId: selectedThread.projectId,
+ projectCwd: selectedThreadProject.workspaceRoot,
+ text: setupMessage.text,
+ ...(setupMessage.context ? { context: setupMessage.context } : {}),
+ uploadedAttachments: setupMessage.attachments,
+ modelSelection: selectedThread.modelSelection,
+ runtimeMode: selectedThread.runtimeMode,
+ interactionMode: selectedThread.interactionMode,
+ workspaceMode: "local",
+ branch: null,
+ worktreePath: null,
+ startFromOrigin: false,
+ worktreeBranchName: "",
+ }),
+ });
+ localResendBusy.current = false;
+ if (launched._tag !== "Success") return;
+ navigation.dispatch(
+ StackActions.replace("Thread", {
+ environmentId: String(selectedThread.environmentId),
+ threadId: metadata.threadId,
+ }),
+ );
+ };
const creationState = ((): ThreadDetailScreenProps["creationState"] => {
if (selectedThreadCreation === null) {
return awaitingBootstrapTurn
diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.ts
index a815f82da71..92cec59f18c 100644
--- a/apps/mobile/src/reactCompilerCoverage.test.ts
+++ b/apps/mobile/src/reactCompilerCoverage.test.ts
@@ -24,19 +24,15 @@ const KNOWN_BAILOUTS: Record<string, string> = {
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
"src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
"src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
- "src/features/threads/ThreadComposer.tsx": "try without catch",
"src/features/threads/ThreadDetailScreen.tsx": "mutates a frozen value",
"src/features/threads/ThreadFeed.tsx": "ref read during render, throw inside try, try/finally",
"src/features/threads/ThreadNavigationSidebar.tsx": "ref read during render",
- "src/features/threads/ThreadQueueControl.tsx": "ref read during render, try without catch",
- "src/features/threads/ThreadRouteScreen.tsx": "try without catch",
"src/features/threads/use-thread-list-v2-shelf-preferences.ts": "ref read during render",
"src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
"src/features/voice-input/useVoiceInputController.ts": "ref read during render",
"src/native/StackHeader.tsx": "ref read during render",
"src/native/T3ComposerEditor.ios.tsx": "ref read during render",
"src/native/T3ComposerEditor.native.tsx": "ref read during render",
- "src/state/use-thread-composer-state.ts": "try without catch",
"src/state/use-thread-selection.ts": "ref read during render",
};
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index d0866906f43..8e3aec88050 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -12,7 +12,7 @@ import {
deriveThreadRuntime,
threadRuntimeHasInterruptibleRun,
} from "@t3tools/client-runtime/state/thread-execution";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import {
CommandId,
@@ -89,6 +89,7 @@ import {
} from "@t3tools/client-runtime/state/composer-dispatch";
import { Atom } from "effect/reactivity";
import { AsyncResult } from "effect/reactivity";
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { prepareTurnAttachments } from "../lib/attachmentUpload";
import { DEFAULT_FOLLOW_UP_BEHAVIOR } from "../lib/followUpBehavior";
import { mobilePreferencesAtom } from "./preferences";
@@ -204,19 +205,16 @@ export function useThreadComposerState() {
threadKey: null,
names: new Set(),
});
- const reservePastedTextFileName = useCallback(
- (threadKey: string, existingNames: ReadonlyArray<string>) => {
- if (pastedTextFileNamesRef.current.threadKey !== threadKey) {
- pastedTextFileNamesRef.current = { threadKey, names: new Set() };
- }
- const names = pastedTextFileNamesRef.current.names;
- for (const name of existingNames) names.add(name);
- const nextName = nextPastedTextFileName([...names]);
- names.add(nextName);
- return nextName;
- },
- [],
- );
+ const reservePastedTextFileName = (threadKey: string, existingNames: ReadonlyArray<string>) => {
+ if (pastedTextFileNamesRef.current.threadKey !== threadKey) {
+ pastedTextFileNamesRef.current = { threadKey, names: new Set() };
+ }
+ const names = pastedTextFileNamesRef.current.names;
+ for (const name of existingNames) names.add(name);
+ const nextName = nextPastedTextFileName([...names]);
+ names.add(nextName);
+ return nextName;
+ };
useEffect(() => {
ensureComposerDraftsLoaded();
@@ -225,29 +223,21 @@ export function useThreadComposerState() {
const selectedThreadKey = selectedThreadShell
? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
: null;
- const selectedThreadQueuedMessages = useMemo(
- () =>
- selectedThreadKey
- ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
- (message) => message.creation === undefined,
- )
- : [],
- [queuedMessagesByThreadKey, selectedThreadKey],
- );
- const feedbackSubmissions = useMemo(
- () => (selectedThreadKey ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? []) : []),
- [feedbackSubmissionsByThreadKey, selectedThreadKey],
- );
- const dismissFeedback = useCallback(
- (id: MessageId) => {
- if (!selectedThreadKey) return;
- setFeedbackSubmissionsByThreadKey((current) => ({
- ...current,
- [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
- }));
- },
- [selectedThreadKey],
- );
+ const selectedThreadQueuedMessages = selectedThreadKey
+ ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
+ (message) => message.creation === undefined,
+ )
+ : [];
+ const feedbackSubmissions = selectedThreadKey
+ ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? [])
+ : [];
+ const dismissFeedback = (id: MessageId) => {
+ if (!selectedThreadKey) return;
+ setFeedbackSubmissionsByThreadKey((current) => ({
+ ...current,
+ [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
+ }));
+ };
const selectedThreadMessages = selectedThreadProjection?.projection.messages;
const selectedThreadAttempts = selectedThreadProjection?.projection.attempts;
const selectedThreadNodes = selectedThreadProjection?.projection.nodes;
@@ -256,7 +246,7 @@ export function useThreadComposerState() {
// detail is usually present but empty during a worktree checkout, so this
// cannot be an either/or with the loaded messages.
const pendingCreationMessage = selectedThreadCreation?.message ?? null;
- const selectedThreadFeed = useMemo(() => {
+ const selectedThreadFeed = (() => {
const pendingCreation =
pendingCreationMessage !== null &&
!selectedThreadMessages?.some((message) => message.id === pendingCreationMessage.messageId)
@@ -276,16 +266,7 @@ export function useThreadComposerState() {
return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>
entry.pendingMessage ? { ...entry, acknowledged: true } : entry,
);
- }, [
- selectedThreadMessages,
- selectedThreadAttempts,
- selectedThreadNodes,
- selectedThreadVisibleTurnItems,
- pendingCreationMessage,
- selectedThreadKey,
- selectedThreadQueuedMessages,
- acknowledgedMessages,
- ]);
+ })();
useEffect(() => {
const echoedIds = new Set(selectedThreadMessages?.map((message) => message.id));
if (acknowledgedMessages.some((message) => echoedIds.has(message.messageId))) {
@@ -321,14 +302,10 @@ export function useThreadComposerState() {
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
const selectedThread = selectedThreadShell;
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
- const pendingHandoff = useMemo(
- () =>
- resolvePendingHandoff(
- selectedThreadProjection?.projection,
- modelSelection,
- selectedEnvironmentRuntime?.serverConfig?.providers ?? [],
- ),
- [modelSelection, selectedThreadProjection, selectedEnvironmentRuntime?.serverConfig?.providers],
+ const pendingHandoff = resolvePendingHandoff(
+ selectedThreadProjection?.projection,
+ modelSelection,
+ selectedEnvironmentRuntime?.serverConfig?.providers ?? [],
);
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
const selectedProvider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
@@ -340,30 +317,18 @@ export function useThreadComposerState() {
selectedDraft?.interactionMode ?? selectedThread.interactionMode,
)
: null;
- const canSwitchThreadProvider = useMemo(
- () =>
- threadAllowsProviderSwitch({
- thread: selectedThreadShell,
- projection: selectedThreadProjection?.projection,
- }),
- [selectedThreadProjection, selectedThreadShell],
- );
- const selectedThreadRuntime = useMemo(
- () =>
- selectedThreadProjection
- ? deriveThreadRuntime(selectedThreadProjection.projection)
- : (selectedThreadShell?.runtime ?? null),
- [selectedThreadProjection, selectedThreadShell?.runtime],
- );
- const selectedThreadActivityRun = useMemo(
- () =>
- selectedThreadProjection
- ? deriveThreadActivityRun(selectedThreadProjection.projection)
- : (selectedThreadShell?.latestRun ?? null),
- [selectedThreadProjection, selectedThreadShell?.latestRun],
- );
-
- const isCompacting = useMemo(() => {
+ const canSwitchThreadProvider = threadAllowsProviderSwitch({
+ thread: selectedThreadShell,
+ projection: selectedThreadProjection?.projection,
+ });
+ const selectedThreadRuntime = selectedThreadProjection
+ ? deriveThreadRuntime(selectedThreadProjection.projection)
+ : (selectedThreadShell?.runtime ?? null);
+ const selectedThreadActivityRun = selectedThreadProjection
+ ? deriveThreadActivityRun(selectedThreadProjection.projection)
+ : (selectedThreadShell?.latestRun ?? null);
+
+ const isCompacting = (() => {
const queuedCompact = selectedThreadQueuedMessages.some(
(message) =>
message.messageId === dispatchingQueuedMessageId &&
@@ -387,23 +352,14 @@ export function useThreadComposerState() {
item.type === "compaction" &&
(item.status === "completed" || item.status === "failed"),
);
- }, [
- dispatchingQueuedMessageId,
- selectedThreadQueuedMessages,
- selectedThreadRuntime,
- selectedThreadVisibleTurnItems,
- ]);
+ })();
// A compacting turn cannot take steering input, so follow-ups queue meanwhile.
const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !isCompacting;
- const runlessWorkStartedAt = useMemo(
- () =>
- selectedThreadProjection
- ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
- : null,
- [selectedThreadProjection],
- );
- const activeWorkStartedAt = useMemo(() => {
+ const runlessWorkStartedAt = selectedThreadProjection
+ ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
+ : null;
+ const activeWorkStartedAt = (() => {
if (!selectedThreadShell) {
return null;
}
@@ -413,16 +369,12 @@ export function useThreadComposerState() {
runtime: selectedThreadRuntime,
}) ?? runlessWorkStartedAt
);
- }, [selectedThreadActivityRun, runlessWorkStartedAt, selectedThreadRuntime, selectedThreadShell]);
+ })();
const runlessWorkActive = runlessWorkStartedAt !== null;
- const providerSubagentStatus = useMemo(
- () =>
- selectedThreadProjection
- ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
- : null,
- [selectedThreadProjection],
- );
+ const providerSubagentStatus = selectedThreadProjection
+ ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
+ : null;
const selectedThreadRuns = selectedThreadProjection?.projection.runs;
const editedRunId = queuedRunEdit?.runId ?? null;
@@ -463,20 +415,17 @@ export function useThreadComposerState() {
? (selectedThreadRuntime?.activeRunId ?? null)
: null;
- const cancelQueuedRunEdit = useCallback(() => {
+ const cancelQueuedRunEdit = () => {
if (selectedThreadKey === null || savingQueuedEditRef.current) return;
endQueuedRunEdit(selectedThreadKey);
- }, [selectedThreadKey]);
+ };
- const onRemoveQueuedEditAttachment = useCallback(
- (attachmentId: string) => {
- if (selectedThreadKey === null) return;
- removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
- },
- [selectedThreadKey],
- );
+ const onRemoveQueuedEditAttachment = (attachmentId: string) => {
+ if (selectedThreadKey === null) return;
+ removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
+ };
- const saveQueuedRunEdit = useCallback(async () => {
+ const saveQueuedRunEdit = async () => {
const thread = selectedThreadShell;
if (!thread || savingQueuedEditRef.current) return;
const threadKey = scopedThreadKey(thread.environmentId, thread.id);
@@ -501,257 +450,252 @@ export function useThreadComposerState() {
}
savingQueuedEditRef.current = true;
setIsSavingQueuedEdit(true);
- try {
- const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
- const prepared = await prepareTurnAttachments({
+ const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
+ const prepared = await settlePromise(() =>
+ prepareTurnAttachments({
environmentId: thread.environmentId,
attachments: draft.attachments,
supportsImageUploads: capabilities?.attachmentUploads === true,
- });
- if (prepared.status !== "ready") return;
- const payload = resolveQueuedEditPayload({
- edit,
- draftContext: draft.context,
- draftAttachments: draft.attachments,
- uploaded: prepared.attachments,
- });
- const result = await editQueuedRun({
- environmentId: thread.environmentId,
- input: {
- threadId: thread.id,
- runId: edit.runId,
- text,
- edit: {
- messageId: edit.messageId,
- attachments: payload.attachments,
- ...(payload.context ? { context: payload.context } : {}),
- },
- },
- });
- if (result._tag !== "Success") {
- Dialog.alert(
- "Could not save the queued message",
- "It may have already started. Your edit is still in the composer.",
- );
- return;
- }
- endQueuedRunEdit(threadKey, { deferAttachmentCleanup: true });
- scheduleUnusedComposerAttachmentCleanup(draft.attachments);
- } finally {
+ }),
+ );
+ if (AsyncResult.isFailure(prepared)) {
savingQueuedEditRef.current = false;
setIsSavingQueuedEdit(false);
+ const error = squashAtomCommandFailure(prepared);
+ Dialog.alert(
+ "Could not save the queued message",
+ error instanceof Error ? error.message : "Your edit is still in the composer.",
+ );
+ return;
}
- }, [editQueuedRun, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
+ if (prepared.value.status !== "ready") {
+ savingQueuedEditRef.current = false;
+ setIsSavingQueuedEdit(false);
+ return;
+ }
+ const payload = resolveQueuedEditPayload({
+ edit,
+ draftContext: draft.context,
+ draftAttachments: draft.attachments,
+ uploaded: prepared.value.attachments,
+ });
+ const result = await editQueuedRun({
+ environmentId: thread.environmentId,
+ input: {
+ threadId: thread.id,
+ runId: edit.runId,
+ text,
+ edit: {
+ messageId: edit.messageId,
+ attachments: payload.attachments,
+ ...(payload.context ? { context: payload.context } : {}),
+ },
+ },
+ });
+ savingQueuedEditRef.current = false;
+ setIsSavingQueuedEdit(false);
+ if (result._tag !== "Success") {
+ Dialog.alert(
+ "Could not save the queued message",
+ "It may have already started. Your edit is still in the composer.",
+ );
+ return;
+ }
+ endQueuedRunEdit(threadKey, { deferAttachmentCleanup: true });
+ scheduleUnusedComposerAttachmentCleanup(draft.attachments);
+ };
- const onSendMessage = useCallback(
- async (followUpOverride?: ActiveTurnComposerAction) => {
- if (
- selectedThreadShell &&
- selectedEnvironmentRuntime?.connectionState === "connected" &&
- !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
- )
- return null;
- if (!selectedThreadShell) {
- return null;
- }
- // The server has not created this thread yet. Queuing a follow-up against
- // its id would strand the message: if the creation is rejected the thread
- // never appears and the drain drops the orphan. The composer disables its
- if (selectedThreadCreation !== null) {
- return null;
- }
+ const onSendMessage = async (followUpOverride?: ActiveTurnComposerAction) => {
+ if (
+ selectedThreadShell &&
+ selectedEnvironmentRuntime?.connectionState === "connected" &&
+ !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
+ )
+ return null;
+ if (!selectedThreadShell) {
+ return null;
+ }
+ // The server has not created this thread yet. Queuing a follow-up against
+ // its id would strand the message: if the creation is rejected the thread
+ // never appears and the drain drops the orphan. The composer disables its
+ if (selectedThreadCreation !== null) {
+ return null;
+ }
- const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
- if (getQueuedRunEdit(editKey) !== null) {
- await saveQueuedRunEdit();
- return null;
- }
+ const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
+ if (getQueuedRunEdit(editKey) !== null) {
+ await saveQueuedRunEdit();
+ return null;
+ }
- const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
- const draft = getComposerDraftSnapshot(threadKey);
- if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
- const thread = selectedThreadShell;
- const text = draft.text.trim();
- const attachments = draft.attachments;
- if (
- composerAttachmentUploadBlockReason({
- environmentId: selectedThreadShell.environmentId,
- attachments,
- connected: selectedEnvironmentRuntime?.connectionState === "connected",
- serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
- states: appAtomRegistry.get(composerAttachmentUploadsAtom),
- }) !== null
- )
- return null;
- if (text.length === 0 && attachments.length === 0) {
- return null;
- }
- // A send-failure restore appends with allowOverflow so it never drops the
- // user's files, which can leave the draft over the cap. Sending it anyway
- // would enqueue a message that outbox recovery rejects forever, so block
- // here until the user removes attachments.
- if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
- Dialog.alert(
- "Too many attachments",
- `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
- );
- return null;
- }
+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
+ const draft = getComposerDraftSnapshot(threadKey);
+ if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
+ const thread = selectedThreadShell;
+ const text = draft.text.trim();
+ const attachments = draft.attachments;
+ if (
+ composerAttachmentUploadBlockReason({
+ environmentId: selectedThreadShell.environmentId,
+ attachments,
+ connected: selectedEnvironmentRuntime?.connectionState === "connected",
+ serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
+ states: appAtomRegistry.get(composerAttachmentUploadsAtom),
+ }) !== null
+ )
+ return null;
+ if (text.length === 0 && attachments.length === 0) {
+ return null;
+ }
+ // A send-failure restore appends with allowOverflow so it never drops the
+ // user's files, which can leave the draft over the cap. Sending it anyway
+ // would enqueue a message that outbox recovery rejects forever, so block
+ // here until the user removes attachments.
+ if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
+ Dialog.alert(
+ "Too many attachments",
+ `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
+ );
+ return null;
+ }
- const contextBlockReason = composerContextSendBlockReason(draft.context);
- if (contextBlockReason) {
- Dialog.alert("Too much context", contextBlockReason);
- return null;
- }
+ const contextBlockReason = composerContextSendBlockReason(draft.context);
+ if (contextBlockReason) {
+ Dialog.alert("Too much context", contextBlockReason);
+ return null;
+ }
- const modelSelection = draft.modelSelection ?? thread.modelSelection;
- const serverConfig = selectedEnvironmentRuntime?.serverConfig;
- if (
- selectedEnvironmentRuntime?.connectionState === "connected" &&
- isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
- ) {
- const { title, detail } = describeUnavailableModelSelection(
- serverConfig,
- modelSelection,
- thread.projectId,
- );
- Dialog.alert(title, detail);
- return null;
- }
- const provider = serverConfig?.providers.find(
- (entry) => entry.instanceId === modelSelection.instanceId,
+ const modelSelection = draft.modelSelection ?? thread.modelSelection;
+ const serverConfig = selectedEnvironmentRuntime?.serverConfig;
+ if (
+ selectedEnvironmentRuntime?.connectionState === "connected" &&
+ isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
+ ) {
+ const { title, detail } = describeUnavailableModelSelection(
+ serverConfig,
+ modelSelection,
+ thread.projectId,
);
- const feedbackCommand =
- attachments.length === 0 && provider?.driver === "codex"
- ? parseCodexFeedbackCommand(text)
- : null;
- if (feedbackCommand) {
- if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
- return null;
- if (thread.activeProviderThreadId === null) {
- Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
- return null;
- }
- const metadata = makeQueuedMessageMetadata();
- await submitCodexFeedback({
- submission: {
- id: MessageId.make(metadata.messageId),
- command: text,
- createdAt: metadata.createdAt,
- },
- clearDraft: () => clearComposerDraftContent(threadKey),
- onUpdate: (submission) => {
- setFeedbackSubmissionsByThreadKey((current) => {
- const existing = current[threadKey] ?? [];
- const found = existing.some((entry) => entry.id === submission.id);
- return {
- ...current,
- [threadKey]: found
- ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
- : [...existing, submission],
- };
- });
- },
- upload: () =>
- uploadThreadFeedback({
- environmentId: thread.environmentId,
- input: { threadId: thread.id, ...feedbackCommand },
- }),
- });
+ Dialog.alert(title, detail);
+ return null;
+ }
+ const provider = serverConfig?.providers.find(
+ (entry) => entry.instanceId === modelSelection.instanceId,
+ );
+ const feedbackCommand =
+ attachments.length === 0 && provider?.driver === "codex"
+ ? parseCodexFeedbackCommand(text)
+ : null;
+ if (feedbackCommand) {
+ if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
+ return null;
+ if (thread.activeProviderThreadId === null) {
+ Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
return null;
}
-
- // Resolved here rather than at drain time: the outbox can deliver minutes
- // later, and the choice belongs to the moment the user pressed send.
- // Steering travels as "auto" so a turn that ends in the meantime degrades
- // to a queued run on the server instead of failing the delivery and
- // bouncing the message back into the draft.
- const followUpAction = resolveComposerDispatchMode({
- running: activeThreadBusy && canSteerActiveTurn,
- alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
- activeTurnDefault: followUpBehavior,
- });
- const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
- (status) => status === "preparing" || status === "starting",
- );
- const followUpDispatchMode = setupRunning
- ? "queue"
- : followUpAction === "auto"
- ? null
- : followUpAction === "queue"
- ? "queue"
- : "auto";
-
const metadata = makeQueuedMessageMetadata();
- const messageId = MessageId.make(metadata.messageId);
- clearThreadComposerError(threadKey);
- const enqueuePromise = enqueueThreadOutboxMessage({
- environmentId: selectedThreadShell.environmentId,
- threadId: selectedThreadShell.id,
- messageId,
- commandId: CommandId.make(metadata.commandId),
- text,
- attachments,
- context: draft.context,
- modelSelection,
- runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
- interactionMode: resolveProviderInteractionMode(
- provider,
- draft.interactionMode ?? thread.interactionMode,
- ),
- ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
- createdAt: metadata.createdAt,
- });
- clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
- enqueuePromise.then(
- () => scheduleUnusedComposerAttachmentCleanup(attachments),
- (error: unknown) => {
- // Restore text via merge (idempotent) but attachments via the uncapped
- // append: the merge path slots existing attachments first and truncates
- // at the send limit, which would silently drop this message's images if
- // the user attached new ones while the write was in flight.
- void mergeComposerDraftContent(threadKey, {
- text,
- context: draft.context,
- attachments: [],
+ await submitCodexFeedback({
+ submission: {
+ id: MessageId.make(metadata.messageId),
+ command: text,
+ createdAt: metadata.createdAt,
+ },
+ clearDraft: () => clearComposerDraftContent(threadKey),
+ onUpdate: (submission) => {
+ setFeedbackSubmissionsByThreadKey((current) => {
+ const existing = current[threadKey] ?? [];
+ const found = existing.some((entry) => entry.id === submission.id);
+ return {
+ ...current,
+ [threadKey]: found
+ ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
+ : [...existing, submission],
+ };
});
- appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
- setThreadComposerError(
- threadKey,
- error instanceof Error ? error.message : "Failed to save the queued message.",
- );
},
- );
- return messageId;
- },
- [
- activeThreadBusy,
- canSteerActiveTurn,
- followUpBehavior,
- saveQueuedRunEdit,
- selectedEnvironmentRuntime?.connectionState,
- selectedEnvironmentRuntime?.serverConfig,
- selectedThreadActivityRun?.status,
- selectedThreadCreation,
- selectedThreadRuntime?.status,
- selectedThreadShell,
- uploadThreadFeedback,
- ],
- );
+ upload: () =>
+ uploadThreadFeedback({
+ environmentId: thread.environmentId,
+ input: { threadId: thread.id, ...feedbackCommand },
+ }),
+ });
+ return null;
+ }
- const onChangeDraftMessage = useCallback(
- (value: string) => {
- if (!selectedThreadShell) {
- return;
- }
+ // Resolved here rather than at drain time: the outbox can deliver minutes
+ // later, and the choice belongs to the moment the user pressed send.
+ // Steering travels as "auto" so a turn that ends in the meantime degrades
+ // to a queued run on the server instead of failing the delivery and
+ // bouncing the message back into the draft.
+ const followUpAction = resolveComposerDispatchMode({
+ running: activeThreadBusy && canSteerActiveTurn,
+ alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
+ activeTurnDefault: followUpBehavior,
+ });
+ const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
+ (status) => status === "preparing" || status === "starting",
+ );
+ const followUpDispatchMode = setupRunning
+ ? "queue"
+ : followUpAction === "auto"
+ ? null
+ : followUpAction === "queue"
+ ? "queue"
+ : "auto";
+
+ const metadata = makeQueuedMessageMetadata();
+ const messageId = MessageId.make(metadata.messageId);
+ clearThreadComposerError(threadKey);
+ const enqueuePromise = enqueueThreadOutboxMessage({
+ environmentId: selectedThreadShell.environmentId,
+ threadId: selectedThreadShell.id,
+ messageId,
+ commandId: CommandId.make(metadata.commandId),
+ text,
+ attachments,
+ context: draft.context,
+ modelSelection,
+ runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
+ interactionMode: resolveProviderInteractionMode(
+ provider,
+ draft.interactionMode ?? thread.interactionMode,
+ ),
+ ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
+ createdAt: metadata.createdAt,
+ });
+ clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
+ enqueuePromise.then(
+ () => scheduleUnusedComposerAttachmentCleanup(attachments),
+ (error: unknown) => {
+ // Restore text via merge (idempotent) but attachments via the uncapped
+ // append: the merge path slots existing attachments first and truncates
+ // at the send limit, which would silently drop this message's images if
+ // the user attached new ones while the write was in flight.
+ void mergeComposerDraftContent(threadKey, {
+ text,
+ context: draft.context,
+ attachments: [],
+ });
+ appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
+ setThreadComposerError(
+ threadKey,
+ error instanceof Error ? error.message : "Failed to save the queued message.",
+ );
+ },
+ );
+ return messageId;
+ };
- const threadKey = activeComposerDraftKey(selectedThreadShell);
- setComposerDraftText(threadKey, value);
- },
- [selectedThreadShell],
- );
+ const onChangeDraftMessage = (value: string) => {
+ if (!selectedThreadShell) {
+ return;
+ }
+
+ const threadKey = activeComposerDraftKey(selectedThreadShell);
+ setComposerDraftText(threadKey, value);
+ };
- const onPickDraftMedia = useCallback(async () => {
+ const onPickDraftMedia = async () => {
if (!selectedThreadShell) {
return;
}
@@ -779,9 +723,9 @@ export function useThreadComposerState() {
if (problems.length > 0) {
Dialog.alert("Could not attach photo or video", problems.join("\n\n"));
}
- }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
+ };
- const onPickDraftFiles = useCallback(async () => {
+ const onPickDraftFiles = async () => {
if (!selectedThreadShell) {
return;
}
@@ -812,9 +756,9 @@ export function useThreadComposerState() {
if (problems.length > 0) {
Dialog.alert("Could not attach file", problems.join("\n\n"));
}
- }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
+ };
- const onPasteIntoDraft = useCallback(async () => {
+ const onPasteIntoDraft = async () => {
if (!selectedThreadShell) {
return;
}
@@ -901,144 +845,115 @@ export function useThreadComposerState() {
`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
);
}
- }, [
- composerDrafts,
- reservePastedTextFileName,
- selectedEnvironmentRuntime?.serverConfig,
- selectedThreadShell,
- ]);
+ };
- const onNativePasteImages = useCallback(
- async (uris: ReadonlyArray<string>) => {
- if (!selectedThreadShell || uris.length === 0) {
- return;
- }
+ const onNativePasteImages = async (uris: ReadonlyArray<string>) => {
+ if (!selectedThreadShell || uris.length === 0) {
+ return;
+ }
- const threadKey = activeComposerDraftKey(selectedThreadShell);
- const insertion = captureComposerDraftInsertion(threadKey);
- try {
- const images = await convertPastedImagesToAttachments({
- uris,
- existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
- });
- if (images.length > 0) {
- appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
- }
- } catch (error) {
- console.error("[native paste] error converting images", {
- environmentId: selectedThreadShell.environmentId,
- threadId: selectedThreadShell.id,
- uriCount: uris.length,
- ...safeErrorLogAttributes(error),
- });
+ const threadKey = activeComposerDraftKey(selectedThreadShell);
+ const insertion = captureComposerDraftInsertion(threadKey);
+ try {
+ const images = await convertPastedImagesToAttachments({
+ uris,
+ existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
+ });
+ if (images.length > 0) {
+ appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
}
- },
- [composerDrafts, selectedThreadShell],
- );
+ } catch (error) {
+ console.error("[native paste] error converting images", {
+ environmentId: selectedThreadShell.environmentId,
+ threadId: selectedThreadShell.id,
+ uriCount: uris.length,
+ ...safeErrorLogAttributes(error),
+ });
+ }
+ };
- const onNativePasteText = useCallback(
- async (paste: ComposerTextPaste) => {
- if (!selectedThreadShell) return;
- const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
- const advertisedMax =
- capabilities?.attachmentUploads === true
- ? capabilities.fileAttachments?.maxUploadBytes
- : undefined;
- if (advertisedMax === undefined) return;
+ const onNativePasteText = async (paste: ComposerTextPaste) => {
+ if (!selectedThreadShell) return;
+ const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
+ const advertisedMax =
+ capabilities?.attachmentUploads === true
+ ? capabilities.fileAttachments?.maxUploadBytes
+ : undefined;
+ if (advertisedMax === undefined) return;
- const threadKey = activeComposerDraftKey(selectedThreadShell);
- const insertion = { text: paste.value, ...paste.selection };
- const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
- try {
- const attachment = await createPastedTextComposerAttachment({
- text: paste.text,
- name: reservePastedTextFileName(
- threadKey,
- currentAttachments.map((item) => item.name),
- ),
- maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
- });
- const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
- appendReference: true,
- insertion,
- });
- if (rejectedCount > 0) {
- await removePersistedComposerAttachmentFile(attachment.fileUri);
- setPendingConnectionError(
- `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
- );
- }
- } catch (error) {
+ const threadKey = activeComposerDraftKey(selectedThreadShell);
+ const insertion = { text: paste.value, ...paste.selection };
+ const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
+ try {
+ const attachment = await createPastedTextComposerAttachment({
+ text: paste.text,
+ name: reservePastedTextFileName(
+ threadKey,
+ currentAttachments.map((item) => item.name),
+ ),
+ maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
+ });
+ const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
+ appendReference: true,
+ insertion,
+ });
+ if (rejectedCount > 0) {
+ await removePersistedComposerAttachmentFile(attachment.fileUri);
setPendingConnectionError(
- error instanceof Error ? error.message : "Could not attach pasted text.",
+ `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
);
}
- },
- [
- composerDrafts,
- reservePastedTextFileName,
- selectedEnvironmentRuntime?.serverConfig,
- selectedThreadShell,
- ],
- );
+ } catch (error) {
+ setPendingConnectionError(
+ error instanceof Error ? error.message : "Could not attach pasted text.",
+ );
+ }
+ };
- const onRemoveDraftImage = useCallback(
- (imageId: string) => {
- if (!selectedThreadShell) {
- return;
- }
+ const onRemoveDraftImage = (imageId: string) => {
+ if (!selectedThreadShell) {
+ return;
+ }
- const threadKey = activeComposerDraftKey(selectedThreadShell);
- removeComposerDraftAttachment(threadKey, imageId);
- },
- [selectedThreadShell],
- );
+ const threadKey = activeComposerDraftKey(selectedThreadShell);
+ removeComposerDraftAttachment(threadKey, imageId);
+ };
- const onUpdateModelSelection = useCallback(
- (value: ModelSelection) => {
- if (!selectedThreadKey) {
- return;
- }
- const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
- (candidate) => candidate.instanceId === value.instanceId,
- );
- updateComposerDraftSettings(selectedThreadKey, {
- modelSelection: value,
- ...(provider?.showInteractionModeToggle === false
- ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
- : {}),
- });
- },
- [selectedEnvironmentRuntime?.serverConfig, selectedThreadKey],
- );
+ const onUpdateModelSelection = (value: ModelSelection) => {
+ if (!selectedThreadKey) {
+ return;
+ }
+ const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
+ (candidate) => candidate.instanceId === value.instanceId,
+ );
+ updateComposerDraftSettings(selectedThreadKey, {
+ modelSelection: value,
+ ...(provider?.showInteractionModeToggle === false
+ ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
+ : {}),
+ });
+ };
- const onUpdateRuntimeMode = useCallback(
- (value: RuntimeMode) => {
- if (!selectedThreadKey) {
- return;
- }
- updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
- },
- [selectedThreadKey],
- );
+ const onUpdateRuntimeMode = (value: RuntimeMode) => {
+ if (!selectedThreadKey) {
+ return;
+ }
+ updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
+ };
- const onUpdateInteractionMode = useCallback(
- (value: ProviderInteractionMode) => {
- if (!selectedThreadKey) {
- return;
- }
- const modelSelection =
- getComposerDraftSnapshot(selectedThreadKey).modelSelection ??
- selectedThread?.modelSelection;
- const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
- (candidate) => candidate.instanceId === modelSelection?.instanceId,
- );
- updateComposerDraftSettings(selectedThreadKey, {
- interactionMode: resolveProviderInteractionMode(provider, value),
- });
- },
- [selectedEnvironmentRuntime?.serverConfig, selectedThread?.modelSelection, selectedThreadKey],
- );
+ const onUpdateInteractionMode = (value: ProviderInteractionMode) => {
+ if (!selectedThreadKey) {
+ return;
+ }
+ const modelSelection =
+ getComposerDraftSnapshot(selectedThreadKey).modelSelection ?? selectedThread?.modelSelection;
+ const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
+ (candidate) => candidate.instanceId === modelSelection?.instanceId,
+ );
+ updateComposerDraftSettings(selectedThreadKey, {
+ interactionMode: resolveProviderInteractionMode(provider, value),
+ });
+ };
return {
feedbackSubmissions,