Skip to content
TypeScript

perf(mobile): new task flow, git sheets, thread settings and work log compile with the React Compiler (#21141)

Julius Marminge8528d64109b2
diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
index c0c3d24113b..54b9e17da4a 100644
--- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
+++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
@@ -13,7 +13,7 @@ import {
} from "@t3tools/client-runtime/state/runtime";
import * as Haptics from "expo-haptics";
import { useNavigation } from "@react-navigation/native";
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useEffect, useRef, useState, type ReactNode } from "react";
import { Platform, Pressable, ScrollView, TextInput, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -155,7 +155,7 @@ function BranchSelectionRow(props: {
readonly onSelect: (branch: VcsRef) => void;
readonly selected: boolean;
}) {
- const onPress = useCallback(() => props.onSelect(props.branch), [props.branch, props.onSelect]);
+ const onPress = () => props.onSelect(props.branch);
return (
<View
@@ -290,67 +290,58 @@ export function NewTaskBranchPickerRouteScreen() {
[navigation],
);
- const selectBranch = useCallback(
- async (branch: VcsRef) => {
- const needsCheckout = shouldCheckoutNewTaskBranch({
- branchIsCurrent: branch.current,
- branchWorktreePath: branch.worktreePath,
- workspaceMode: flow.workspaceMode,
- });
- if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
- return;
- }
- selectingBranchNameRef.current = branch.name;
- void Haptics.selectionAsync();
-
- try {
- if (!flow.selectedProject) return;
- setSwitchingBranchName(branch.name);
- const result = await checkoutNewTaskBranch({
- branch,
- project: flow.selectedProject,
- workspaceMode: flow.workspaceMode,
- switchRef,
- });
- if (result._tag === "Failure") {
- if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
- Dialog.alert(
- "Could not switch branch",
- error instanceof Error ? error.message : "The branch could not be checked out.",
- );
- }
- return;
- }
+ const selectBranch = async (branch: VcsRef) => {
+ const needsCheckout = shouldCheckoutNewTaskBranch({
+ branchIsCurrent: branch.current,
+ branchWorktreePath: branch.worktreePath,
+ workspaceMode: flow.workspaceMode,
+ });
+ if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
+ return;
+ }
+ selectingBranchNameRef.current = branch.name;
+ void Haptics.selectionAsync();
- // The checkout has already changed the repository. Persist the matching
- // draft selection even if the native sheet was dismissed while the
- // command was in flight; only visible-screen work is focus-gated below.
- flow.selectBranch(result.value);
- if (!mountedRef.current || !navigation.isFocused()) {
- return;
- }
- flow.setBranchQuery("");
- allowSelectionNavigationRef.current = true;
- navigation.goBack();
- } finally {
- selectingBranchNameRef.current = null;
- allowSelectionNavigationRef.current = false;
- if (mountedRef.current) {
- setSwitchingBranchName(null);
- }
- }
- },
- [
- canWriteSourceControl,
- flow.selectBranch,
- flow.selectedProject,
- flow.setBranchQuery,
- flow.workspaceMode,
- navigation,
+ const project = flow.selectedProject;
+ if (!project) {
+ selectingBranchNameRef.current = null;
+ return;
+ }
+ setSwitchingBranchName(branch.name);
+ const result = await checkoutNewTaskBranch({
+ branch,
+ project,
+ workspaceMode: flow.workspaceMode,
switchRef,
- ],
- );
+ });
+ if (mountedRef.current) setSwitchingBranchName(null);
+ if (result._tag === "Failure") {
+ selectingBranchNameRef.current = null;
+ if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ Dialog.alert(
+ "Could not switch branch",
+ error instanceof Error ? error.message : "The branch could not be checked out.",
+ );
+ }
+ return;
+ }
+
+ // The checkout has already changed the repository. Persist the matching
+ // draft selection even if the native sheet was dismissed while the
+ // command was in flight; only visible-screen work is focus-gated below.
+ flow.selectBranch(result.value);
+ if (!mountedRef.current || !navigation.isFocused()) {
+ selectingBranchNameRef.current = null;
+ return;
+ }
+ flow.setBranchQuery("");
+ // beforeRemove blocks dismissal while a switch is in flight; this one is ours.
+ allowSelectionNavigationRef.current = true;
+ navigation.goBack();
+ allowSelectionNavigationRef.current = false;
+ selectingBranchNameRef.current = null;
+ };
return (
<BranchPickerScreen
@@ -413,38 +404,26 @@ export function BranchPickerScreen(props: {
props.branches.find((branch) => branch.current)?.name ??
props.branches.find((branch) => branch.isDefault)?.name ??
null;
- const branchListContentStyle = useMemo(
- () => ({
- paddingBottom: usesNativeMailSearchToolbar
- ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
- : Platform.OS === "ios"
- ? 16
- : Math.max(insets.bottom, 16) + 16,
- paddingHorizontal: 16,
- paddingTop: 16,
- }),
- [insets.bottom, usesNativeMailSearchToolbar],
- );
+ const branchListContentStyle = {
+ paddingBottom: usesNativeMailSearchToolbar
+ ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
+ : Platform.OS === "ios"
+ ? 16
+ : Math.max(insets.bottom, 16) + 16,
+ paddingHorizontal: 16,
+ paddingTop: 16,
+ };
- const renderBranch = useCallback(
- ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
- <BranchSelectionRow
- badge={branchBadgeLabel({ branch: item, project: props.project })}
- branch={item}
- disabled={props.selectionDisabled ?? false}
- isFirst={index === 0}
- isLast={index === props.branches.length - 1}
- onSelect={props.onSelect}
- selected={selectedBranchName === item.name}
- />
- ),
- [
- props.branches.length,
- props.project,
- props.onSelect,
- selectedBranchName,
- props.selectionDisabled,
- ],
+ const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
+ <BranchSelectionRow
+ badge={branchBadgeLabel({ branch: item, project: props.project })}
+ branch={item}
+ disabled={props.selectionDisabled ?? false}
+ isFirst={index === 0}
+ isLast={index === props.branches.length - 1}
+ onSelect={props.onSelect}
+ selected={selectedBranchName === item.name}
+ />
);
const branchListHeader = props.worktree ? (
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
index 02a20015435..7f31caeee92 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
@@ -3,6 +3,7 @@ import * as Dialog from "../../components/ui/Dialog";
import { useAtomValue } from "@effect/atom-react";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
import {
nextPastedTextFileName,
@@ -18,7 +19,7 @@ import {
usePreventRemove,
type NavigationAction,
} from "@react-navigation/native";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
import { Platform, Pressable, ScrollView, View } from "react-native";
import {
KeyboardController,
@@ -211,7 +212,7 @@ export function NewTaskDraftScreen(props: {
const controlsBottomPadding = Math.max(insets.bottom, 10);
const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
- const selectedProjectLabel = useMemo(() => {
+ const selectedProjectLabel = (() => {
if (!selectedProject) return null;
const scope = projectScopes.find((candidate) =>
candidate.projectRefs.some(
@@ -221,7 +222,7 @@ export function NewTaskDraftScreen(props: {
),
);
return scope?.title ?? selectedProject.title;
- }, [projectScopes, selectedProject]);
+ })();
const { connectedEnvironments } = useRemoteConnectionStatus();
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
@@ -319,23 +320,17 @@ export function NewTaskDraftScreen(props: {
const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
const wasFocusedBeforePreviewRef = useRef(false);
- const openVideoPreview = useCallback(
- (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
- wasFocusedBeforePreviewRef.current = isComposerFocused;
- setPreviewFile(null);
- setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
- },
- [isComposerFocused],
- );
- const openFilePreview = useCallback(
- (source: FilePreviewSource) => {
- wasFocusedBeforePreviewRef.current = isComposerFocused;
- setPreviewVideo(null);
- setPreviewFile((current) => current ?? source);
- },
- [isComposerFocused],
- );
- const closeMediaPreview = useCallback(() => {
+ const openVideoPreview = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
+ wasFocusedBeforePreviewRef.current = isComposerFocused;
+ setPreviewFile(null);
+ setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
+ };
+ const openFilePreview = (source: FilePreviewSource) => {
+ wasFocusedBeforePreviewRef.current = isComposerFocused;
+ setPreviewVideo(null);
+ setPreviewFile((current) => current ?? source);
+ };
+ const closeMediaPreview = () => {
setPreviewVideo(null);
setPreviewFile(null);
if (wasFocusedBeforePreviewRef.current) {
@@ -343,7 +338,7 @@ export function NewTaskDraftScreen(props: {
if (navigation.isFocused()) promptInputRef.current?.focus();
}, 100);
}
- }, [navigation]);
+ };
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: promptInputRef,
isEditorFocused: isComposerFocused,
@@ -371,16 +366,14 @@ export function NewTaskDraftScreen(props: {
settingsRoutePresentedRef.current = true;
navigation.dispatch(StackActions.push("ThreadSettings"));
}, [navigation, settingsSheetPresentation.isVisible]);
- useFocusEffect(
- useCallback(() => {
- if (!settingsRoutePresentedRef.current) {
- return;
- }
+ useFocusEffect(() => {
+ if (!settingsRoutePresentedRef.current) {
+ return;
+ }
- settingsRoutePresentedRef.current = false;
- settingsSheetPresentation.onDismissed();
- }, [settingsSheetPresentation.onDismissed]),
- );
+ settingsRoutePresentedRef.current = false;
+ settingsSheetPresentation.onDismissed();
+ });
useEffect(
() =>
// UIKit's completion callback for the sheet dismissal, surfaced by the
@@ -410,17 +403,25 @@ export function NewTaskDraftScreen(props: {
draftKey: null,
names: new Set(),
});
+ // The share import resumes after awaits; this reads the screen's current
+ // draft and share at that point without re-running the import effect.
+ const isCurrentShareImport = useEffectEvent(
+ (draftKey: string, shareId: string) =>
+ flow.draftKey === draftKey && props.incomingShareId === shareId,
+ );
+ // Pasted-text attachments finish in an event handler, where an effect event
+ // cannot be called and the provider's draft key has no store to read.
const latestDraftKeyRef = useRef(flow.draftKey);
- const latestIncomingShareIdRef = useRef(props.incomingShareId);
- latestDraftKeyRef.current = flow.draftKey;
- latestIncomingShareIdRef.current = props.incomingShareId;
+ useLayoutEffect(() => {
+ latestDraftKeyRef.current = flow.draftKey;
+ });
const isImportingShare = importingShareKey !== null;
const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
// The share this screen already moved into its draft. Sending clears the
// draft (and its importedShareIds receipt) a frame before the screen leaves,
// and the inbox entry is long gone by then; without this the re-render in
// between reads as "shared content vanished" and alerts on every send.
- const consumedIncomingShareIdRef = useRef<string | null>(null);
+ const [consumedIncomingShareId, setConsumedIncomingShareId] = useState<string | null>(null);
const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
const requestedInitialProjectAvailable = Boolean(
props.initialProjectRef?.environmentId &&
@@ -447,22 +448,13 @@ export function NewTaskDraftScreen(props: {
const isComposerInteractionLocked =
isIncomingShareTransferPending || flow.submitting || isImportingContext;
const { environments, selectedEnvironmentId, switchEnvironment, switchingToEnvironmentId } = flow;
- const cycleEnvironment = useCallback(() => {
+ const cycleEnvironment = () => {
if (isComposerInteractionLocked) return true;
const next = nextEnvironmentId(environments, switchingToEnvironmentId ?? selectedEnvironmentId);
if (next !== null) void switchEnvironment(next);
return true;
- }, [
- environments,
- isComposerInteractionLocked,
- selectedEnvironmentId,
- switchEnvironment,
- switchingToEnvironmentId,
- ]);
- const cycleEnvironmentCommands = useMemo(
- () => (environments.length > 1 ? (["cycleHost"] as const) : []),
- [environments.length],
- );
+ };
+ const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : [];
useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);
const offersUsageLimits =
flow.selectedProviderStatus !== null &&
@@ -475,10 +467,7 @@ export function NewTaskDraftScreen(props: {
(flow.workspaceMode === "worktree"
? selectedProject?.workspaceRoot
: (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
- const stripAttachments = useMemo(
- () => composerStripAttachments(flow.attachments),
- [flow.attachments],
- );
+ const stripAttachments = composerStripAttachments(flow.attachments);
const composerMenu = useComposerCommandMenu({
draftMessage: flow.prompt,
ownerKey: flow.draftKey,
@@ -529,7 +518,7 @@ export function NewTaskDraftScreen(props: {
}, [navigation, preventRemove, submitNavigationAction]);
const hasImportedIncomingShare = Boolean(
props.incomingShareId &&
- (consumedIncomingShareIdRef.current === props.incomingShareId ||
+ (consumedIncomingShareId === props.incomingShareId ||
(flow.draftKey &&
getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId))),
);
@@ -812,8 +801,7 @@ export function NewTaskDraftScreen(props: {
if (
!shareImportMountedRef.current ||
activeShareImportTokenRef.current !== importToken ||
- latestDraftKeyRef.current !== draftKey ||
- latestIncomingShareIdRef.current !== shareId
+ !isCurrentShareImport(draftKey, shareId)
) {
return;
}
@@ -835,8 +823,7 @@ export function NewTaskDraftScreen(props: {
if (
!shareImportMountedRef.current ||
activeShareImportTokenRef.current !== importToken ||
- latestDraftKeyRef.current !== draftKey ||
- latestIncomingShareIdRef.current !== shareId
+ !isCurrentShareImport(draftKey, shareId)
) {
// The durable reservation makes an interrupted transfer resume only
// in this project instead of copying into a second project draft.
@@ -844,7 +831,7 @@ export function NewTaskDraftScreen(props: {
}
await consumeShare(shareId);
didConsumeShare = true;
- consumedIncomingShareIdRef.current = shareId;
+ setConsumedIncomingShareId(shareId);
// The consumed inbox draft was the last owner of files that never made
// it into the composer draft (unsupported server, oversize, limit
// skips). Release them before any early return: an unmount or a
@@ -1067,124 +1054,118 @@ export function NewTaskDraftScreen(props: {
}
}
- const handleNativePasteImages = useCallback(
- async (uris: ReadonlyArray<string>) => {
- try {
- const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
- const images = await convertPastedImagesToAttachments({
- uris,
- existingCount:
- flow.draftKey && insertion
- ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
- : flow.attachments.length,
- });
- if (images.length > 0) {
- flow.appendAttachments(images, insertion);
- }
- } catch (error) {
- console.error("[native paste] error converting images", error);
- }
- },
- [flow],
- );
+ const handleNativePasteImages = async (uris: ReadonlyArray<string>) => {
+ const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
+ const existingCount =
+ flow.draftKey && insertion
+ ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
+ : flow.attachments.length;
+ const converted = await settlePromise(() =>
+ convertPastedImagesToAttachments({ uris, existingCount }),
+ );
+ if (AsyncResult.isFailure(converted)) {
+ console.error("[native paste] error converting images", squashAtomCommandFailure(converted));
+ return;
+ }
+ if (converted.value.length > 0) flow.appendAttachments(converted.value, insertion);
+ };
- const handleNativePasteText = useCallback(
- async (paste: ComposerTextPaste) => {
- const draftKey = flow.draftKey;
- if (!draftKey) return;
- const insertion = { text: paste.value, ...paste.selection };
- const insertPaste = () => {
- const insertion = replaceTextSelection({
- value: paste.value,
- selection: paste.selection,
- text: paste.text,
- });
- const selection = { start: insertion.cursor, end: insertion.cursor };
- flow.setPrompt(insertion.value);
- composerMenu.onSelectionChange(selection);
- };
- const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;
- const advertisedMax =
- capabilities?.attachmentUploads === true
- ? capabilities.fileAttachments?.maxUploadBytes
- : undefined;
- const maxBytes =
- advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
- const wouldExceedInputLimit =
- paste.value.length -
- Math.max(0, paste.selection.end - paste.selection.start) +
- paste.text.length >
- PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
- const canAttach =
- maxBytes !== null &&
- countComposerDraftAttachmentsAfterSelection(draftKey, insertion) <
- PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
- new TextEncoder().encode(paste.text).byteLength <= maxBytes;
- if (
- pastedTextDisposition({
- text: paste.text,
- wouldExceedInputLimit,
- canAttach: true,
- }) === "attachment"
- ) {
- if (canAttach && maxBytes !== null) {
- pendingPastedTextAttachmentCountRef.current += 1;
- setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
- try {
- if (pastedTextFileNamesRef.current.draftKey !== draftKey) {
- pastedTextFileNamesRef.current = { draftKey, names: new Set() };
- }
- const reservedNames = pastedTextFileNamesRef.current.names;
- for (const attachment of flow.attachments) reservedNames.add(attachment.name);
- const name = nextPastedTextFileName([...reservedNames]);
- reservedNames.add(name);
- const attachment = await createPastedTextComposerAttachment({
- text: paste.text,
- name,
- maxBytes,
- });
- if (latestDraftKeyRef.current !== draftKey) {
- await removePersistedComposerAttachmentFile(attachment.fileUri);
- return;
- }
- if (flow.appendAttachments([attachment], insertion) > 0) {
- await removePersistedComposerAttachmentFile(attachment.fileUri);
- Dialog.alert(
- "Could not attach pasted text",
- `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
- );
- }
- } catch (error) {
+ const handleNativePasteText = async (paste: ComposerTextPaste) => {
+ const draftKey = flow.draftKey;
+ if (!draftKey) return;
+ const insertion = { text: paste.value, ...paste.selection };
+ const insertPaste = () => {
+ const insertion = replaceTextSelection({
+ value: paste.value,
+ selection: paste.selection,
+ text: paste.text,
+ });
+ const selection = { start: insertion.cursor, end: insertion.cursor };
+ flow.setPrompt(insertion.value);
+ composerMenu.onSelectionChange(selection);
+ };
+ const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;
+ const advertisedMax =
+ capabilities?.attachmentUploads === true
+ ? capabilities.fileAttachments?.maxUploadBytes
+ : undefined;
+ const maxBytes =
+ advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
+ const wouldExceedInputLimit =
+ paste.value.length -
+ Math.max(0, paste.selection.end - paste.selection.start) +
+ paste.text.length >
+ PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
+ const canAttach =
+ maxBytes !== null &&
+ countComposerDraftAttachmentsAfterSelection(draftKey, insertion) <
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
+ new TextEncoder().encode(paste.text).byteLength <= maxBytes;
+ if (
+ pastedTextDisposition({
+ text: paste.text,
+ wouldExceedInputLimit,
+ canAttach: true,
+ }) === "attachment"
+ ) {
+ if (canAttach && maxBytes !== null) {
+ pendingPastedTextAttachmentCountRef.current += 1;
+ setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
+ const attached = await settlePromise(async () => {
+ if (pastedTextFileNamesRef.current.draftKey !== draftKey) {
+ pastedTextFileNamesRef.current = { draftKey, names: new Set() };
+ }
+ const reservedNames = pastedTextFileNamesRef.current.names;
+ for (const attachment of flow.attachments) reservedNames.add(attachment.name);
+ const name = nextPastedTextFileName([...reservedNames]);
+ reservedNames.add(name);
+ const attachment = await createPastedTextComposerAttachment({
+ text: paste.text,
+ name,
+ maxBytes,
+ });
+ if (latestDraftKeyRef.current !== draftKey) {
+ await removePersistedComposerAttachmentFile(attachment.fileUri);
+ return;
+ }
+ if (flow.appendAttachments([attachment], insertion) > 0) {
+ await removePersistedComposerAttachmentFile(attachment.fileUri);
Dialog.alert(
"Could not attach pasted text",
- error instanceof Error ? error.message : "Try again.",
- );
- } finally {
- pendingPastedTextAttachmentCountRef.current = Math.max(
- 0,
- pendingPastedTextAttachmentCountRef.current - 1,
+ `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
);
- setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
}
- } else if (!wouldExceedInputLimit) {
- insertPaste();
- } else {
+ });
+ pendingPastedTextAttachmentCountRef.current = Math.max(
+ 0,
+ pendingPastedTextAttachmentCountRef.current - 1,
+ );
+ setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
+ if (AsyncResult.isFailure(attached)) {
+ const error = squashAtomCommandFailure(attached);
Dialog.alert(
- wouldExceedInputLimit
- ? "Pasted text is too large for this message"
- : "Could not attach pasted text",
- wouldExceedInputLimit
- ? "Remove some text or an attachment, then paste again."
- : "Remove an attachment or use a smaller paste, then try again.",
+ "Could not attach pasted text",
+ error instanceof Error ? error.message : "Try again.",
);
}
return;
+ } else if (!wouldExceedInputLimit) {
+ insertPaste();
+ } else {
+ Dialog.alert(
+ wouldExceedInputLimit
+ ? "Pasted text is too large for this message"
+ : "Could not attach pasted text",
+ wouldExceedInputLimit
+ ? "Remove some text or an attachment, then paste again."
+ : "Remove an attachment or use a smaller paste, then try again.",
+ );
}
+ return;
+ }
- insertPaste();
- },
- [composerMenu, flow, selectedEnvironmentServerConfig],
- );
+ insertPaste();
+ };
async function handleStart(): Promise<void> {
if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
@@ -1300,16 +1281,15 @@ export function NewTaskDraftScreen(props: {
// Persist before clearing the draft or leaving its editor. This only waits
// for the local outbox write; server and worktree setup run on the thread.
flow.setSubmitting(true);
- try {
- await enqueueThreadOutboxMessage(message);
- } catch (error) {
+ const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
+ flow.setSubmitting(false);
+ if (AsyncResult.isFailure(queued)) {
+ const error = squashAtomCommandFailure(queued);
Dialog.alert(
"Could not queue task",
error instanceof Error ? error.message : "The task could not be saved to the outbox.",
);
return;
- } finally {
- flow.setSubmitting(false);
}
const draftSnapshot = getComposerDraftSnapshot(draftKey);
if (editingPendingTask) {
diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
index 2b28553b496..ff539280c11 100644
--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
@@ -237,24 +237,23 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
if (!scratchEnvironment || scratchStartInFlightRef.current) return;
const environmentId = scratchEnvironment.environmentId;
scratchStartInFlightRef.current = true;
- try {
- const result = await openScratch({ environmentId, input: {} });
- if (result._tag === "Failure") {
- if (!isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
- Dialog.alert(
- "Could not start without a project",
- error instanceof Error
- ? error.message
- : "The folder for threads without a project could not be created.",
- );
- }
- return;
- }
- await selectProject(result.value);
- } finally {
+ const result = await openScratch({ environmentId, input: {} });
+ if (result._tag === "Failure") {
scratchStartInFlightRef.current = false;
+ if (!isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ Dialog.alert(
+ "Could not start without a project",
+ error instanceof Error
+ ? error.message
+ : "The folder for threads without a project could not be created.",
+ );
+ }
+ return;
}
+ // selectProject handles its own failures, so this never throws.
+ await selectProject(result.value);
+ scratchStartInFlightRef.current = false;
}
useEffect(() => {
diff --git a/apps/mobile/src/features/threads/QuestionAttachments.tsx b/apps/mobile/src/features/threads/QuestionAttachments.tsx
index 91469aec24e..3b4449d3aff 100644
--- a/apps/mobile/src/features/threads/QuestionAttachments.tsx
+++ b/apps/mobile/src/features/threads/QuestionAttachments.tsx
@@ -1,3 +1,5 @@
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import { AsyncResult } from "effect/reactivity";
import * as Dialog from "../../components/ui/Dialog";
import { TextInputWrapper } from "expo-paste-input";
import { AppTextInput as TextInput } from "../../components/ui/AppText";
@@ -134,7 +136,7 @@ export function QuestionAttachments(props: {
const pick = async (kind: "media" | "files") => {
const scope = pickerScope.current;
changeQuestionAttachmentPreparation(key, 1);
- try {
+ const picked = await settlePromise(async () => {
const existingCount = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0;
const result =
kind === "files"
@@ -158,10 +160,11 @@ export function QuestionAttachments(props: {
const rejected = append(key, picked);
if (result.error || rejected > 0)
Dialog.alert("Could not attach file", result.error ?? "Too many attachments.");
- } catch (error) {
+ });
+ changeQuestionAttachmentPreparation(key, -1);
+ if (AsyncResult.isFailure(picked)) {
+ const error = squashAtomCommandFailure(picked);
Dialog.alert("Could not attach file", error instanceof Error ? error.message : "Try again.");
- } finally {
- changeQuestionAttachmentPreparation(key, -1);
}
};
return (
diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx
index e0c83f6a4d1..c7cf8a61e30 100644
--- a/apps/mobile/src/features/threads/ThreadGitControls.tsx
+++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx
@@ -18,7 +18,6 @@ import {
} from "@t3tools/client-runtime/state/vcs";
import { useNavigation } from "@react-navigation/native";
-import { useCallback, useMemo } from "react";
import { useEnvironmentScope } from "../../state/session";
import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
import {
@@ -130,7 +129,7 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
const isDefaultRef = gitStatus?.isDefaultRef ?? false;
- const quickAction = useMemo(() => {
+ const quickAction = (() => {
if (!isRepo) {
return {
label: "Git unavailable",
@@ -147,7 +146,7 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
hint: "This connection cannot change source control.",
}
: action;
- }, [busy, canWriteSourceControl, gitStatus, hasPrimaryRemote, isDefaultRef, isRepo]);
+ })();
const quickActionHint = quickAction.disabled
? (quickAction.hint ?? "This action is unavailable.")
@@ -164,7 +163,7 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
return "arrow.up.right.circle";
})();
- const openExistingPr = useCallback(async () => {
+ const openExistingPr = async () => {
const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
if (!prUrl) {
Dialog.alert("No open PR", "This branch does not have an open pull request.");
@@ -173,51 +172,38 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
if (!(await openPullRequest(prUrl))) {
Dialog.alert("Unable to open PR", "The pull request could not be opened.");
}
- }, [gitStatus, openPullRequest]);
-
- const runActionWithPrompt = useCallback(
- async (input: GitActionRequestInput) => {
- if (!canWriteSourceControl) return;
- const confirmableAction =
- input.action === "push" ||
- input.action === "create_pr" ||
- input.action === "commit_push" ||
- input.action === "commit_push_pr"
- ? input.action
- : null;
- const branchName = gitStatus?.refName;
- if (
- branchName &&
- confirmableAction &&
- !input.featureBranch &&
- requiresDefaultBranchConfirmation(input.action, isDefaultRef)
- ) {
- navigation.navigate("GitConfirm", {
- environmentId: String(environmentId),
- threadId: String(threadId),
- confirmAction: confirmableAction,
- branchName,
- includesCommit: String(
- input.action === "commit_push" || input.action === "commit_push_pr",
- ),
- });
- return;
- }
-
- await onRunAction(input);
- },
- [
- canWriteSourceControl,
- environmentId,
- gitStatus,
- isDefaultRef,
- onRunAction,
- navigation,
- threadId,
- ],
- );
+ };
+
+ const runActionWithPrompt = async (input: GitActionRequestInput) => {
+ if (!canWriteSourceControl) return;
+ const confirmableAction =
+ input.action === "push" ||
+ input.action === "create_pr" ||
+ input.action === "commit_push" ||
+ input.action === "commit_push_pr"
+ ? input.action
+ : null;
+ const branchName = gitStatus?.refName;
+ if (
+ branchName &&
+ confirmableAction &&
+ !input.featureBranch &&
+ requiresDefaultBranchConfirmation(input.action, isDefaultRef)
+ ) {
+ navigation.navigate("GitConfirm", {
+ environmentId: String(environmentId),
+ threadId: String(threadId),
+ confirmAction: confirmableAction,
+ branchName,
+ includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"),
+ });
+ return;
+ }
+
+ await onRunAction(input);
+ };
- const runQuickAction = useCallback(async () => {
+ const runQuickAction = async () => {
if (quickAction.disabled) return;
if (quickAction.kind === "open_pr") {
await openExistingPr();
@@ -230,9 +216,9 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
if (quickAction.kind === "run_action" && quickAction.action) {
await runActionWithPrompt({ action: quickAction.action });
}
- }, [onPull, openExistingPr, quickAction, runActionWithPrompt]);
+ };
- const openFiles = useCallback(() => {
+ const openFiles = () => {
if (props.onOpenFilesInspector) {
props.onOpenFilesInspector();
return;
@@ -241,16 +227,16 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
environmentId: String(environmentId),
threadId: String(threadId),
});
- }, [environmentId, props.onOpenFilesInspector, navigation, threadId]);
+ };
- const openReview = useCallback(() => {
+ const openReview = () => {
navigation.navigate("ThreadReview", {
environmentId: EnvironmentId.make(String(environmentId)),
threadId: ThreadId.make(String(threadId)),
});
- }, [environmentId, navigation, threadId]);
+ };
- const openGitInspector = useCallback(() => {
+ const openGitInspector = () => {
if (props.onOpenGitInspector) {
props.onOpenGitInspector();
return;
@@ -259,7 +245,7 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
environmentId: String(environmentId),
threadId: String(threadId),
});
- }, [environmentId, props.onOpenGitInspector, navigation, threadId]);
+ };
return {
currentBranchLabel,
@@ -277,176 +263,146 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGitHeaderActionItems {
const model = useThreadGitControlModel(props);
- return useMemo(
- () => ({
- terminal: {
- accessibilityLabel: "Open terminal",
- disabled: !props.canOpenTerminal,
- icon: { name: "terminal", type: "sfSymbol" },
- identifier: "thread-right-terminal",
- label: "Terminal",
- menu: {
- items: [
- ...props.projectScripts.map((script) => ({
- description: script.command,
- disabled: !props.canOperateTerminal,
- icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const },
- label: projectScriptMenuLabel(script),
- onPress: () => void props.onRunProjectScript(script),
- type: "action" as const,
- })),
- ...(props.projectScripts.length === 0
- ? [
- {
- description: "This project has no saved scripts yet",
- disabled: true,
- icon: { name: "play", type: "sfSymbol" as const },
- label: "No project scripts",
- onPress: () => {},
- type: "action" as const,
- },
- ]
- : []),
- ...props.terminalSessions.map((session) => ({
- description: [
- getTerminalStatusLabel({
- status: session.status,
- hasRunningSubprocess: session.hasRunningSubprocess,
- }),
- basename(session.cwd),
+ return {
+ terminal: {
+ accessibilityLabel: "Open terminal",
+ disabled: !props.canOpenTerminal,
+ icon: { name: "terminal", type: "sfSymbol" },
+ identifier: "thread-right-terminal",
+ label: "Terminal",
+ menu: {
+ items: [
+ ...props.projectScripts.map((script) => ({
+ description: script.command,
+ disabled: !props.canOperateTerminal,
+ icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const },
+ label: projectScriptMenuLabel(script),
+ onPress: () => void props.onRunProjectScript(script),
+ type: "action" as const,
+ })),
+ ...(props.projectScripts.length === 0
+ ? [
+ {
+ description: "This project has no saved scripts yet",
+ disabled: true,
+ icon: { name: "play", type: "sfSymbol" as const },
+ label: "No project scripts",
+ onPress: () => {},
+ type: "action" as const,
+ },
]
- .filter(Boolean)
- .join(" · "),
- icon: { name: "terminal", type: "sfSymbol" as const },
- label: session.displayLabel,
- onPress: () => props.onOpenTerminal(session.terminalId),
- type: "action" as const,
- })),
- {
- description: "Start another shell for this thread",
- disabled: !props.canOperateTerminal,
- icon: { name: "plus", type: "sfSymbol" },
- label: "Open new terminal",
- onPress: props.onOpenNewTerminal,
- type: "action",
- },
- ],
- title: "Terminal",
- },
- sharesBackground: true,
- type: "menu",
- variant: "plain",
- },
- files: {
- accessibilityLabel: "Open files",
- disabled: !props.canOpenFiles,
- icon: { name: "folder", type: "sfSymbol" },
- identifier: "thread-right-files",
- label: "Files",
- onPress: model.openFiles,
- sharesBackground: true,
- type: "button",
- variant: "plain",
+ : []),
+ ...props.terminalSessions.map((session) => ({
+ description: [
+ getTerminalStatusLabel({
+ status: session.status,
+ hasRunningSubprocess: session.hasRunningSubprocess,
+ }),
+ basename(session.cwd),
+ ]
+ .filter(Boolean)
+ .join(" · "),
+ icon: { name: "terminal", type: "sfSymbol" as const },
+ label: session.displayLabel,
+ onPress: () => props.onOpenTerminal(session.terminalId),
+ type: "action" as const,
+ })),
+ {
+ description: "Start another shell for this thread",
+ disabled: !props.canOperateTerminal,
+ icon: { name: "plus", type: "sfSymbol" },
+ label: "Open new terminal",
+ onPress: props.onOpenNewTerminal,
+ type: "action",
+ },
+ ],
+ title: "Terminal",
},
- git: {
- accessibilityLabel: "Git actions",
- icon: { name: "point.topleft.down.curvedto.point.bottomright.up", type: "sfSymbol" },
- identifier: "thread-right-git",
- label: "Git",
- menu: {
- items: [
- {
- description: compactMenuStatus(props.gitStatus),
- disabled: true,
- icon: {
- name: "point.topleft.down.curvedto.point.bottomright.up",
- type: "sfSymbol",
- },
- label: compactMenuBranchLabel(model.currentBranchLabel),
- onPress: (): void => {},
- type: "action",
- },
- {
- description: model.quickActionHint ?? undefined,
- disabled: model.quickAction.disabled,
- icon: { name: model.quickActionIcon, type: "sfSymbol" },
- label: model.quickAction.label,
- onPress: (): void => void model.runQuickAction(),
- type: "action",
- },
- {
- description: "Turn diffs and worktree changes",
- disabled: !model.isRepo,
- icon: { name: "text.bubble", type: "sfSymbol" },
- label: "Review changes",
- onPress: model.openReview,
- type: "action",
- },
- ...(props.onMergeBack
- ? [
- {
- description: "Bring this thread's latest turn into its source",
- icon: { name: PullRequestGlyph.merged, type: "sfSymbol" as const },
- label: "Merge back to source",
- onPress: props.onMergeBack,
- type: "action" as const,
- },
- ]
- : []),
- {
- description: "Commit, files, branches",
- icon: { name: "ellipsis", type: "sfSymbol" },
- label: "More",
- onPress: model.openGitInspector,
- type: "action",
+ sharesBackground: true,
+ type: "menu",
+ variant: "plain",
+ },
+ files: {
+ accessibilityLabel: "Open files",
+ disabled: !props.canOpenFiles,
+ icon: { name: "folder", type: "sfSymbol" },
+ identifier: "thread-right-files",
+ label: "Files",
+ onPress: model.openFiles,
+ sharesBackground: true,
+ type: "button",
+ variant: "plain",
+ },
+ git: {
+ accessibilityLabel: "Git actions",
+ icon: { name: "point.topleft.down.curvedto.point.bottomright.up", type: "sfSymbol" },
+ identifier: "thread-right-git",
+ label: "Git",
+ menu: {
+ items: [
+ {
+ description: compactMenuStatus(props.gitStatus),
+ disabled: true,
+ icon: {
+ name: "point.topleft.down.curvedto.point.bottomright.up",
+ type: "sfSymbol",
},
- ],
- title: "Git",
- },
- sharesBackground: true,
- type: "menu",
- variant: "plain",
+ label: compactMenuBranchLabel(model.currentBranchLabel),
+ onPress: (): void => {},
+ type: "action",
+ },
+ {
+ description: model.quickActionHint ?? undefined,
+ disabled: model.quickAction.disabled,
+ icon: { name: model.quickActionIcon, type: "sfSymbol" },
+ label: model.quickAction.label,
+ onPress: (): void => void model.runQuickAction(),
+ type: "action",
+ },
+ {
+ description: "Turn diffs and worktree changes",
+ disabled: !model.isRepo,
+ icon: { name: "text.bubble", type: "sfSymbol" },
+ label: "Review changes",
+ onPress: model.openReview,
+ type: "action",
+ },
+ ...(props.onMergeBack
+ ? [
+ {
+ description: "Bring this thread's latest turn into its source",
+ icon: { name: PullRequestGlyph.merged, type: "sfSymbol" as const },
+ label: "Merge back to source",
+ onPress: props.onMergeBack,
+ type: "action" as const,
+ },
+ ]
+ : []),
+ {
+ description: "Commit, files, branches",
+ icon: { name: "ellipsis", type: "sfSymbol" },
+ label: "More",
+ onPress: model.openGitInspector,
+ type: "action",
+ },
+ ],
+ title: "Git",
},
- }),
- [
- model.currentBranchLabel,
- model.isRepo,
- model.openFiles,
- model.openGitInspector,
- model.openReview,
- model.quickAction.disabled,
- model.quickAction.label,
- model.quickActionHint,
- model.quickActionIcon,
- model.runQuickAction,
- props.canOpenFiles,
- props.canOpenTerminal,
- props.canOperateTerminal,
- props.gitStatus,
- props.onMergeBack,
- props.onOpenNewTerminal,
- props.onOpenTerminal,
- props.onRunProjectScript,
- props.projectScripts,
- props.terminalSessions,
- ],
- );
+ sharesBackground: true,
+ type: "menu",
+ variant: "plain",
+ },
+ };
}
export function useThreadGitRightHeaderItems(props: ThreadGitControlsProps): HeaderItems {
const actionItems = useThreadGitHeaderActionItems(props);
- return useMemo(
- () => [actionItems.git, actionItems.files, actionItems.terminal] as HeaderItems,
- [actionItems],
- );
+ return [actionItems.git, actionItems.files, actionItems.terminal] as HeaderItems;
}
export function useThreadGitCenterHeaderItems(props: ThreadGitControlsProps): HeaderItems {
const actionItems = useThreadGitHeaderActionItems(props);
- return useMemo(
- () => [actionItems.files, actionItems.git, actionItems.terminal] as HeaderItems,
- [actionItems],
- );
+ return [actionItems.files, actionItems.git, actionItems.terminal] as HeaderItems;
}
export function ThreadGitControls(props: ThreadGitControlsProps) {
diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
index 5583008c017..28cd3f00d96 100644
--- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
+++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
@@ -28,16 +28,7 @@ import { useNavigation, useRoute, type RouteProp } from "@react-navigation/nativ
import { type NativeStackNavigationProp } from "@react-navigation/native-stack";
import * as Haptics from "expo-haptics";
import { AsyncResult } from "effect/reactivity";
-import {
- createContext,
- use,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
- type ReactNode,
-} from "react";
+import { createContext, use, useEffect, useRef, useState, type ReactNode } from "react";
import { Platform, Pressable, RefreshControl, ScrollView, TextInput, View } from "react-native";
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -264,13 +255,13 @@ const ExistingThreadSettingsRouteContext =
export function ExistingThreadSettingsRouteProvider(props: { readonly children: ReactNode }) {
const [session, setSession] = useState<ExistingThreadSettingsRouteSession | null>(null);
- const present = useCallback((nextSession: ExistingThreadSettingsRouteSession) => {
+ const present = (nextSession: ExistingThreadSettingsRouteSession) => {
setSession(nextSession);
- }, []);
- const clear = useCallback((ownerId: string) => {
+ };
+ const clear = (ownerId: string) => {
setSession((current) => (current?.ownerId === ownerId ? null : current));
- }, []);
- const value = useMemo(() => ({ session, present, clear }), [clear, present, session]);
+ };
+ const value = { session, present, clear };
return (
<ExistingThreadSettingsRouteContext.Provider value={value}>
@@ -339,28 +330,18 @@ function ThreadSettingsSessionProvider(
new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(),
);
const [pendingHiddenKeys, setPendingHiddenKeys] = useState<ReadonlySet<string>>(() => new Set());
- const providerGroups = useMemo(
- () =>
- manageHidden && config
- ? groupByProvider(
- buildModelOptions(
- config,
- props.selectedModel,
- props.lockedProviderInstanceId,
- props.projectId,
- true,
- ),
- )
- : props.providerGroups,
- [
- config,
- manageHidden,
- props.providerGroups,
- props.selectedModel,
- props.lockedProviderInstanceId,
- props.projectId,
- ],
- );
+ const providerGroups =
+ manageHidden && config
+ ? groupByProvider(
+ buildModelOptions(
+ config,
+ props.selectedModel,
+ props.lockedProviderInstanceId,
+ props.projectId,
+ true,
+ ),
+ )
+ : props.providerGroups;
const legacyFavorites = AsyncResult.isSuccess(preferences)
? (preferences.value.modelFavorites ?? EMPTY_MODEL_FAVORITES)
: EMPTY_MODEL_FAVORITES;
@@ -375,114 +356,98 @@ function ThreadSettingsSessionProvider(
const patch = modelPreferencesMigrationPatch(settings, { favorites: legacyFavorites });
if (patch) void saveSettings({ environmentId: props.environmentId, input: { patch } });
}, [legacyFavorites, preferences, props.environmentId, saveSettings, settings]);
- const favoriteKeys = useMemo(
- () =>
- new Set(
- modelFavorites.map((favorite) => modelFavoriteKey(favorite.provider, favorite.model)),
- ),
- [modelFavorites],
+ const favoriteKeys = new Set(
+ modelFavorites.map((favorite) => modelFavoriteKey(favorite.provider, favorite.model)),
);
- const toggleFavorite = useCallback(
- async (option: ModelOption) => {
- if (!favoritesLoaded || !props.environmentId) return;
- const currentSettings = registry
- .get(environmentServerConfigsAtom)
- .get(props.environmentId)?.settings;
- if (!currentSettings) return;
- const favorites = resolveModelPreferences(currentSettings, {
- favorites: legacyFavorites,
- }).favorites;
- const key = JSON.stringify([
- props.environmentId,
- option.selection.instanceId,
- option.selection.model,
- ]);
- const previous = pendingFavorites.current.get(key);
- const previousFavorite =
- previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
- ? previous.favorite
- : favorites.some(
- (favorite) =>
- favorite.provider === option.selection.instanceId &&
- favorite.model === option.selection.model,
- );
- const pending = { favorite: !previousFavorite, settings: currentSettings, pending: true };
- pendingFavorites.current.set(key, pending);
- void Haptics.selectionAsync();
- try {
- const result = await saveSettings({
- environmentId: props.environmentId,
- input: {
- patch: {
- setModelFavorites: [
- {
- provider: option.selection.instanceId,
- model: option.selection.model,
- favorite: pending.favorite,
- },
- ],
- ...(currentSettings.favorites === null
- ? { migrateModelPreferences: { favorites } }
- : {}),
+ const toggleFavorite = async (option: ModelOption) => {
+ const environmentId = props.environmentId;
+ if (!favoritesLoaded || !environmentId) return;
+ const currentSettings = registry.get(environmentServerConfigsAtom).get(environmentId)?.settings;
+ if (!currentSettings) return;
+ const favorites = resolveModelPreferences(currentSettings, {
+ favorites: legacyFavorites,
+ }).favorites;
+ const key = JSON.stringify([
+ environmentId,
+ option.selection.instanceId,
+ option.selection.model,
+ ]);
+ const previous = pendingFavorites.current.get(key);
+ const previousFavorite =
+ previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
+ ? previous.favorite
+ : favorites.some(
+ (favorite) =>
+ favorite.provider === option.selection.instanceId &&
+ favorite.model === option.selection.model,
+ );
+ const pending = { favorite: !previousFavorite, settings: currentSettings, pending: true };
+ pendingFavorites.current.set(key, pending);
+ void Haptics.selectionAsync();
+ const result = await saveSettings({
+ environmentId: environmentId,
+ input: {
+ patch: {
+ setModelFavorites: [
+ {
+ provider: option.selection.instanceId,
+ model: option.selection.model,
+ favorite: pending.favorite,
},
- },
- });
- if (
- AsyncResult.isSuccess(result) &&
- registry.get(environmentServerConfigsAtom).get(props.environmentId)?.settings
- .favorites === currentSettings.favorites
- ) {
- pending.pending = false;
- }
- } finally {
- if (pending.pending && pendingFavorites.current.get(key) === pending) {
- if (
- previous &&
- !previous.pending &&
- registry.get(environmentServerConfigsAtom).get(props.environmentId)?.settings
- .favorites === previous.settings.favorites
- ) {
- pendingFavorites.current.set(key, previous);
- } else {
- pendingFavorites.current.delete(key);
- }
- }
- }
- },
- [favoritesLoaded, legacyFavorites, props.environmentId, registry, saveSettings],
- );
- const toggleHidden = useCallback(
- (option: ModelOption) => {
+ ],
+ ...(currentSettings.favorites === null ? { migrateModelPreferences: { favorites } } : {}),
+ },
+ },
+ });
+ if (
+ AsyncResult.isSuccess(result) &&
+ registry.get(environmentServerConfigsAtom).get(environmentId)?.settings.favorites ===
+ currentSettings.favorites
+ ) {
+ pending.pending = false;
+ }
+ if (pending.pending && pendingFavorites.current.get(key) === pending) {
if (
- !settings ||
- !props.environmentId ||
- !option.canHide ||
- pendingHidden.current.has(option.key)
- )
- return;
- pendingHidden.current.add(option.key);
- setPendingHiddenKeys(new Set(pendingHidden.current));
- void Haptics.selectionAsync();
- void saveSettings({
- environmentId: props.environmentId,
- input: {
- patch: {
- setModelsHidden: [
- {
- provider: option.selection.instanceId,
- model: option.selection.model,
- hidden: !option.isHidden,
- },
- ],
- },
+ previous &&
+ !previous.pending &&
+ registry.get(environmentServerConfigsAtom).get(environmentId)?.settings.favorites ===
+ previous.settings.favorites
+ ) {
+ pendingFavorites.current.set(key, previous);
+ } else {
+ pendingFavorites.current.delete(key);
+ }
+ }
+ };
+ const toggleHidden = (option: ModelOption) => {
+ if (
+ !settings ||
+ !props.environmentId ||
+ !option.canHide ||
+ pendingHidden.current.has(option.key)
+ )
+ return;
+ pendingHidden.current.add(option.key);
+ setPendingHiddenKeys(new Set(pendingHidden.current));
+ void Haptics.selectionAsync();
+ void saveSettings({
+ environmentId: props.environmentId,
+ input: {
+ patch: {
+ setModelsHidden: [
+ {
+ provider: option.selection.instanceId,
+ model: option.selection.model,
+ hidden: !option.isHidden,
+ },
+ ],
},
- }).then(() => {
- pendingHidden.current.delete(option.key);
- setPendingHiddenKeys(new Set(pendingHidden.current));
- });
- },
- [props.environmentId, saveSettings, settings],
- );
+ },
+ }).then(() => {
+ pendingHidden.current.delete(option.key);
+ setPendingHiddenKeys(new Set(pendingHidden.current));
+ });
+ };
const [showLegacyToggle, setShowLegacyToggle] = useState(false);
const [providerFilter, setProviderFilter] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState("");
@@ -491,36 +456,24 @@ function ThreadSettingsSessionProvider(
);
const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);
- const isApplied = useCallback(
- (option: ModelOption) =>
- option.selection.instanceId === props.selectedModel?.instanceId &&
- option.selection.model === props.selectedModel.model,
- [props.selectedModel],
- );
- const isDisplayed = useCallback(
- (option: ModelOption) => (pendingModel ? option.key === pendingModel.key : isApplied(option)),
- [isApplied, pendingModel],
- );
-
- const displayedDescriptors = useMemo(
- () =>
- pendingModel
- ? pendingModel.capabilities
- ? getProviderOptionDescriptors({
- caps: pendingModel.capabilities,
- selections: pendingModel.selection.options,
- })
- : []
- : props.optionDescriptors,
- [pendingModel, props.optionDescriptors],
- );
- const displayedModel = useMemo(
- () =>
- pendingModel ??
- props.providerGroups.flatMap((group) => group.models).find((option) => isApplied(option)) ??
- null,
- [isApplied, pendingModel, props.providerGroups],
- );
+ const isApplied = (option: ModelOption) =>
+ option.selection.instanceId === props.selectedModel?.instanceId &&
+ option.selection.model === props.selectedModel.model;
+ const isDisplayed = (option: ModelOption) =>
+ pendingModel ? option.key === pendingModel.key : isApplied(option);
+
+ const displayedDescriptors = pendingModel
+ ? pendingModel.capabilities
+ ? getProviderOptionDescriptors({
+ caps: pendingModel.capabilities,
+ selections: pendingModel.selection.options,
+ })
+ : []
+ : props.optionDescriptors;
+ const displayedModel =
+ pendingModel ??
+ props.providerGroups.flatMap((group) => group.models).find((option) => isApplied(option)) ??
+ null;
const runtimeModeChoices = runtimeModeChoicesForSupportedModes(
displayedModel?.supportedRuntimeModes,
);
@@ -529,11 +482,10 @@ function ThreadSettingsSessionProvider(
runtimeModeChoices,
);
- const hasLegacyModels = useMemo(
- () => props.providerGroups.some((group) => group.models.some((model) => model.isLegacy)),
- [props.providerGroups],
+ const hasLegacyModels = props.providerGroups.some((group) =>
+ group.models.some((model) => model.isLegacy),
);
- const commitPendingModel = useCallback(() => {
+ const commitPendingModel = () => {
if (pendingModel) {
if (!canCommitPendingModel(pendingModel, props.providerGroups)) {
Dialog.alert(
@@ -546,28 +498,25 @@ function ThreadSettingsSessionProvider(
props.onSelectModel(pendingModel);
}
return true;
- }, [pendingModel, props.onSelectModel, props.providerGroups]);
+ };
- const applyOptionChange = useCallback(
- (id: string, value: string | boolean) => {
- const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
- if (!next) {
- return;
- }
- if (pendingModel) {
- rememberModelOptions(pendingModel.selection.instanceId, pendingModel.selection.model, next);
- setPendingModel({
- ...pendingModel,
- selection: { ...pendingModel.selection, options: next },
- });
- } else {
- props.onUpdateOptionSelections(next);
- }
- },
- [displayedDescriptors, pendingModel, props.onUpdateOptionSelections],
- );
+ const applyOptionChange = (id: string, value: string | boolean) => {
+ const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
+ if (!next) {
+ return;
+ }
+ if (pendingModel) {
+ rememberModelOptions(pendingModel.selection.instanceId, pendingModel.selection.model, next);
+ setPendingModel({
+ ...pendingModel,
+ selection: { ...pendingModel.selection, options: next },
+ });
+ } else {
+ props.onUpdateOptionSelections(next);
+ }
+ };
- const toggleProvider = useCallback((providerKey: string) => {
+ const toggleProvider = (providerKey: string) => {
setProviderExpansionOverrides((current) => {
const next = new Set(current);
if (!next.delete(providerKey)) {
@@ -575,86 +524,52 @@ function ThreadSettingsSessionProvider(
}
return next;
});
- }, []);
-
- const pressModel = useCallback(
- (option: ModelOption) => {
- void Haptics.selectionAsync();
- setPendingModel((current) =>
- pendingModelAfterPress({
- current,
- pressed: option,
- pressedIsApplied: isApplied(option),
- }),
- );
- },
- [isApplied],
- );
-
- const value = useMemo<ThreadSettingsSessionValue>(
- () => ({
- environmentId: props.environmentId,
- providerInstanceId: props.providerInstanceId,
- providerGroups,
- manageHidden,
- setManageHidden,
- toggleHidden,
- pendingHiddenKeys,
- runtimeMode: compatibleRuntimeMode,
- runtimeModeChoices,
- onUpdateRuntimeMode: props.onUpdateRuntimeMode,
- displayedDescriptors,
- displayedModelSelection: pendingModel?.selection ?? props.selectedModel,
- reportedModelSelection: pendingModel ? null : (props.reportedModelSelection ?? null),
- favoriteKeys,
- favoritesLoaded,
- providerExpansionOverrides,
- hasLegacyModels,
- pendingModel,
- providerFilter,
- searchQuery,
- showLegacy: showLegacyToggle,
- applyOptionChange,
- commitPendingModel,
- isApplied,
- isDisplayed,
- pressModel,
- setProviderFilter,
- setSearchQuery,
- setShowLegacy: setShowLegacyToggle,
- toggleProvider,
- toggleFavorite,
- }),
- [
- applyOptionChange,
- commitPendingModel,
- compatibleRuntimeMode,
- displayedDescriptors,
- favoriteKeys,
- favoritesLoaded,
- providerExpansionOverrides,
- hasLegacyModels,
- isApplied,
- isDisplayed,
- props.environmentId,
- props.selectedModel,
- props.reportedModelSelection,
- props.providerInstanceId,
- pendingModel,
- pressModel,
- providerFilter,
- props.onUpdateRuntimeMode,
- providerGroups,
- manageHidden,
- toggleHidden,
- pendingHiddenKeys,
- runtimeModeChoices,
- searchQuery,
- showLegacyToggle,
- toggleProvider,
- toggleFavorite,
- ],
- );
+ };
+
+ const pressModel = (option: ModelOption) => {
+ void Haptics.selectionAsync();
+ setPendingModel((current) =>
+ pendingModelAfterPress({
+ current,
+ pressed: option,
+ pressedIsApplied: isApplied(option),
+ }),
+ );
+ };
+
+ const value = {
+ environmentId: props.environmentId,
+ providerInstanceId: props.providerInstanceId,
+ providerGroups,
+ manageHidden,
+ setManageHidden,
+ toggleHidden,
+ pendingHiddenKeys,
+ runtimeMode: compatibleRuntimeMode,
+ runtimeModeChoices,
+ onUpdateRuntimeMode: props.onUpdateRuntimeMode,
+ displayedDescriptors,
+ displayedModelSelection: pendingModel?.selection ?? props.selectedModel,
+ reportedModelSelection: pendingModel ? null : (props.reportedModelSelection ?? null),
+ favoriteKeys,
+ favoritesLoaded,
+ providerExpansionOverrides,
+ hasLegacyModels,
+ pendingModel,
+ providerFilter,
+ searchQuery,
+ showLegacy: showLegacyToggle,
+ applyOptionChange,
+ commitPendingModel,
+ isApplied,
+ isDisplayed,
+ pressModel,
+ setProviderFilter,
+ setSearchQuery,
+ setShowLegacy: setShowLegacyToggle,
+ toggleProvider,
+ toggleFavorite,
+ } satisfies ThreadSettingsSessionValue;
return (
<ThreadSettingsSessionContext.Provider value={value}>
@@ -715,10 +630,7 @@ function ThreadSettingsModelListRow(props: {
readonly isLast: boolean;
}) {
const session = useThreadSettingsSession();
- const onPress = useCallback(
- () => session.pressModel(props.option),
- [props.option, session.pressModel],
- );
+ const onPress = () => session.pressModel(props.option);
return (
<ModelRow
@@ -744,10 +656,7 @@ function ThreadSettingsProviderListHeader(props: {
readonly provider: ThreadSettingsProviderCatalog;
}) {
const session = useThreadSettingsSession();
- const onToggle = useCallback(
- () => session.toggleProvider(props.provider.key),
- [props.provider.key, session.toggleProvider],
- );
+ const onToggle = () => session.toggleProvider(props.provider.key);
return (
<ProviderHeader
@@ -762,106 +671,90 @@ function ThreadSettingsProviderListHeader(props: {
);
}
-function useThreadSettingsCatalogItems(
+function buildThreadSettingsCatalogItems(
session: ThreadSettingsSessionValue,
): ReadonlyArray<ThreadSettingsCatalogItem> {
- return useMemo(
- () =>
- session.providerGroups.flatMap((group) => {
- if (
- session.providerFilter !== null &&
- session.providerFilter !== FAVORITES_PROVIDER_FILTER &&
- group.providerKey !== session.providerFilter
- ) {
- return [];
- }
- const driver = group.models[0]?.providerDriver ?? group.providerKey;
- const catalogModels =
- session.manageHidden ||
- session.showLegacy ||
- session.providerFilter === FAVORITES_PROVIDER_FILTER
- ? group.models
- : group.models.filter(
- (model) =>
- !model.isLegacy ||
- session.isDisplayed(model) ||
- session.favoriteKeys.has(model.key),
- );
- const visibleModels = favoritesFirst(
- catalogModels.filter(
+ return session.providerGroups.flatMap((group) => {
+ if (
+ session.providerFilter !== null &&
+ session.providerFilter !== FAVORITES_PROVIDER_FILTER &&
+ group.providerKey !== session.providerFilter
+ ) {
+ return [];
+ }
+ const driver = group.models[0]?.providerDriver ?? group.providerKey;
+ const catalogModels =
+ session.manageHidden ||
+ session.showLegacy ||
+ session.providerFilter === FAVORITES_PROVIDER_FILTER
+ ? group.models
+ : group.models.filter(
(model) =>
- (session.providerFilter !== FAVORITES_PROVIDER_FILTER ||
- session.favoriteKeys.has(model.key)) &&
- modelMatchesCatalogQuery({
- model,
- providerLabel: group.providerLabel,
- query: session.searchQuery,
- }),
- ),
- session.favoriteKeys,
- );
- const updateRequiredNotice =
- group.updateRequired && session.providerFilter !== FAVORITES_PROVIDER_FILTER
- ? formatProviderUpdateRequiredNotice(group.updateRequired, session.searchQuery)
- : null;
- if (visibleModels.length === 0 && !updateRequiredNotice) {
- return [];
- }
- const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
- const containsAppliedSelection = group.models.some(session.isApplied);
- const isNarrowed = session.providerFilter !== null || session.searchQuery.trim().length > 0;
- const collapsible = !isNarrowed;
- const collapsed = providerSectionIsCollapsed({
- defaultExpanded: isPrimary || containsAppliedSelection,
- hasExpansionOverride: session.providerExpansionOverrides.has(group.providerKey),
- isNarrowed,
- });
- const provider: ThreadSettingsProviderCatalog = {
- key: group.providerKey,
- driver,
- iconUrl: group.models[0]?.providerIconUrl,
- label: group.providerLabel,
- collapsible,
- collapsed,
- modelCount: visibleModels.length,
- models: collapsed ? [] : visibleModels,
- };
- return [
- {
- kind: "provider" as const,
- key: `provider:${group.providerKey}`,
- provider,
- },
- ...provider.models.map((option, index) => ({
- kind: "model" as const,
- key: `model:${option.key}`,
- option,
- isFirst: index === 0,
- isLast: index === provider.models.length - 1,
- })),
- ...(!collapsed && updateRequiredNotice
- ? [
- {
- kind: "notice" as const,
- key: `notice:${group.providerKey}`,
- text: updateRequiredNotice,
- },
- ]
- : []),
- ];
- }),
- [
- session.isApplied,
- session.isDisplayed,
+ !model.isLegacy || session.isDisplayed(model) || session.favoriteKeys.has(model.key),
+ );
+ const visibleModels = favoritesFirst(
+ catalogModels.filter(
+ (model) =>
+ (session.providerFilter !== FAVORITES_PROVIDER_FILTER ||
+ session.favoriteKeys.has(model.key)) &&
+ modelMatchesCatalogQuery({
+ model,
+ providerLabel: group.providerLabel,
+ query: session.searchQuery,
+ }),
+ ),
session.favoriteKeys,
- session.providerExpansionOverrides,
- session.providerFilter,
- session.providerGroups,
- session.searchQuery,
- session.showLegacy,
- session.manageHidden,
- ],
- );
+ );
+ const updateRequiredNotice =
+ group.updateRequired && session.providerFilter !== FAVORITES_PROVIDER_FILTER
+ ? formatProviderUpdateRequiredNotice(group.updateRequired, session.searchQuery)
+ : null;
+ if (visibleModels.length === 0 && !updateRequiredNotice) {
+ return [];
+ }
+ const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
+ const containsAppliedSelection = group.models.some(session.isApplied);
+ const isNarrowed = session.providerFilter !== null || session.searchQuery.trim().length > 0;
+ const collapsible = !isNarrowed;
+ const collapsed = providerSectionIsCollapsed({
+ defaultExpanded: isPrimary || containsAppliedSelection,
+ hasExpansionOverride: session.providerExpansionOverrides.has(group.providerKey),
+ isNarrowed,
+ });
+ const provider: ThreadSettingsProviderCatalog = {
+ key: group.providerKey,
+ driver,
+ iconUrl: group.models[0]?.providerIconUrl,
+ label: group.providerLabel,
+ collapsible,
+ collapsed,
+ modelCount: visibleModels.length,
+ models: collapsed ? [] : visibleModels,
+ };
+ return [
+ {
+ kind: "provider" as const,
+ key: `provider:${group.providerKey}`,
+ provider,
+ },
+ ...provider.models.map((option, index) => ({
+ kind: "model" as const,
+ key: `model:${option.key}`,
+ option,
+ isFirst: index === 0,
+ isLast: index === provider.models.length - 1,
+ })),
+ ...(!collapsed && updateRequiredNotice
+ ? [
+ {
+ kind: "notice" as const,
+ key: `notice:${group.providerKey}`,
+ text: updateRequiredNotice,
+ },
+ ]
+ : []),
+ ];
+ });
}
function ThreadSettingsOptionsItem(props: {
@@ -968,12 +861,9 @@ function ThreadSettingsMainContent(props: {
const refreshProvidersCommand = useAtomCommand(serverEnvironment.refreshProviders, {
reportFailure: false,
});
- const refreshProviderCatalog = useMemo(
- () => createProviderCatalogRefreshRunner(refreshProvidersCommand),
- [refreshProvidersCommand],
- );
+ const refreshProviderCatalog = createProviderCatalogRefreshRunner(refreshProvidersCommand);
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
- const refreshProviders = useCallback(() => {
+ const refreshProviders = () => {
if (!session.environmentId || isRefreshingProviders) return;
setIsRefreshingProviders(true);
void refreshProviderCatalog(session.environmentId).then((result) => {
@@ -981,75 +871,63 @@ function ThreadSettingsMainContent(props: {
const error = providerCatalogRefreshError(result);
if (error) Dialog.alert("Could not refresh models", error);
});
- }, [isRefreshingProviders, refreshProviderCatalog, session.environmentId]);
- const catalogItems = useThreadSettingsCatalogItems(session);
+ };
const [animationsReady, setAnimationsReady] = useState(false);
+ const catalogItems = buildThreadSettingsCatalogItems(session);
const hasActiveCatalogFilter =
session.providerFilter !== null || session.searchQuery.trim().length > 0;
- const listItems = useMemo<ReadonlyArray<ThreadSettingsCatalogItem>>(
- () => [
- ...(catalogItems.length === 0 ? ([{ kind: "empty", key: "empty" }] as const) : catalogItems),
- { kind: "options", key: "options" },
- ],
- [catalogItems],
- );
- const renderCatalogItem = useCallback(
- (itemProps: LegendListRenderItemProps<ThreadSettingsCatalogItem>) => {
- const item = itemProps.item;
- let content: ReactNode;
-
- if (item.kind === "provider") {
- content = <ThreadSettingsProviderListHeader provider={item.provider} />;
- } else if (item.kind === "model") {
- content = (
- <ThreadSettingsModelListRow
- isFirst={item.isFirst}
- isLast={item.isLast}
- option={item.option}
- />
- );
- } else if (item.kind === "notice") {
- content = <Text className="mx-8 mt-2 text-xs text-foreground-muted">{item.text}</Text>;
- } else if (item.kind === "empty") {
- content = (
- <View className="items-center px-8 py-14">
- <Text className="text-center text-sm text-foreground-muted">
- {session.providerFilter === FAVORITES_PROVIDER_FILTER &&
- session.searchQuery.trim().length === 0
- ? "No favorite models"
- : hasActiveCatalogFilter
- ? "No matching models"
- : "No available models"}
- </Text>
- </View>
- );
- } else {
- content = (
- <ThreadSettingsOptionsItem
- animationsReady={animationsReady}
- onOpenSubmenu={props.onOpenSubmenu}
- />
- );
- }
-
- return (
- <Animated.View
- key={item.key}
- entering={animationsReady ? THREAD_SETTINGS_CATALOG_ENTER_TRANSITION : undefined}
- exiting={animationsReady ? THREAD_SETTINGS_CATALOG_EXIT_TRANSITION : undefined}
- >
- {content}
- </Animated.View>
+ const listItems = [
+ ...(catalogItems.length === 0 ? ([{ kind: "empty", key: "empty" }] as const) : catalogItems),
+ { kind: "options", key: "options" },
+ ] satisfies ReadonlyArray<ThreadSettingsCatalogItem>;
+ const renderCatalogItem = (itemProps: LegendListRenderItemProps<ThreadSettingsCatalogItem>) => {
+ const item = itemProps.item;
+ let content: ReactNode;
+
+ if (item.kind === "provider") {
+ content = <ThreadSettingsProviderListHeader provider={item.provider} />;
+ } else if (item.kind === "model") {
+ content = (
+ <ThreadSettingsModelListRow
+ isFirst={item.isFirst}
+ isLast={item.isLast}
+ option={item.option}
+ />
);
- },
- [
- animationsReady,
- hasActiveCatalogFilter,
- props.onOpenSubmenu,
- session.providerFilter,
- session.searchQuery,
- ],
- );
+ } else if (item.kind === "notice") {
+ content = <Text className="mx-8 mt-2 text-xs text-foreground-muted">{item.text}</Text>;
+ } else if (item.kind === "empty") {
+ content = (
+ <View className="items-center px-8 py-14">
+ <Text className="text-center text-sm text-foreground-muted">
+ {session.providerFilter === FAVORITES_PROVIDER_FILTER &&
+ session.searchQuery.trim().length === 0
+ ? "No favorite models"
+ : hasActiveCatalogFilter
+ ? "No matching models"
+ : "No available models"}
+ </Text>
+ </View>
+ );
+ } else {
+ content = (
+ <ThreadSettingsOptionsItem
+ animationsReady={animationsReady}
+ onOpenSubmenu={props.onOpenSubmenu}
+ />
+ );
+ }
+
+ return (
+ <Animated.View
+ key={item.key}
+ entering={animationsReady ? THREAD_SETTINGS_CATALOG_ENTER_TRANSITION : undefined}
+ exiting={animationsReady ? THREAD_SETTINGS_CATALOG_EXIT_TRANSITION : undefined}
+ >
+ {content}
+ </Animated.View>
+ );
+ };
return (
<AnimatedLegendList
@@ -1243,50 +1121,44 @@ function ThreadSettingsModelsScreen() {
const navigation = useNavigation<NativeStackNavigationProp<ThreadSettingsPickerStackParams>>();
const usesNativeMailSearchToolbar = useNativeMailSearchToolbar();
const hasCustomCatalogFilter = session.providerFilter !== null || session.showLegacy;
- const commitAndClose = useCallback(() => {
+ const commitAndClose = () => {
if (!session.commitPendingModel()) return;
presentation.onClose();
- }, [presentation, session]);
- const providerFilters = useMemo(
- () => [
- { id: "all-providers", title: "All providers", value: null },
- { id: "favorites", title: "Favorites", value: FAVORITES_PROVIDER_FILTER },
- ...session.providerGroups.map((group) => ({
- id: `provider:${group.providerKey}`,
- title: group.providerLabel,
- value: group.providerKey,
- })),
+ };
+ const providerFilters = [
+ { id: "all-providers", title: "All providers", value: null },
+ { id: "favorites", title: "Favorites", value: FAVORITES_PROVIDER_FILTER },
+ ...session.providerGroups.map((group) => ({
+ id: `provider:${group.providerKey}`,
+ title: group.providerLabel,
+ value: group.providerKey,
+ })),
+ ];
+ const filterMenu = {
+ title: "Model filters",
+ items: [
+ {
+ type: "submenu" as const,
+ title: "Provider",
+ items: providerFilters.map((filter) => ({
+ type: "action" as const,
+ title: filter.title,
+ state: session.providerFilter === filter.value ? ("on" as const) : ("off" as const),
+ onPress: () => session.setProviderFilter(filter.value),
+ })),
+ },
+ ...(session.hasLegacyModels
+ ? [
+ {
+ type: "action" as const,
+ title: "Show legacy models",
+ state: session.showLegacy ? ("on" as const) : ("off" as const),
+ onPress: () => session.setShowLegacy(!session.showLegacy),
+ },
+ ]
+ : []),
],
- [session.providerGroups],
- );
- const filterMenu = useMemo(
- () => ({
- title: "Model filters",
- items: [
- {
- type: "submenu" as const,
- title: "Provider",
- items: providerFilters.map((filter) => ({
- type: "action" as const,
- title: filter.title,
- state: session.providerFilter === filter.value ? ("on" as const) : ("off" as const),
- onPress: () => session.setProviderFilter(filter.value),
- })),
- },
- ...(session.hasLegacyModels
- ? [
- {
- type: "action" as const,
- title: "Show legacy models",
- state: session.showLegacy ? ("on" as const) : ("off" as const),
- onPress: () => session.setShowLegacy(!session.showLegacy),
- },
- ]
- : []),
- ],
- }),
- [providerFilters, session],
- );
+ };
return (
<>
@@ -1486,12 +1358,9 @@ function ThreadSettingsPickerNavigator(props: ThreadSettingsPickerPresentation)
const theme = useUniwindTheme();
const solidSheetBackground = theme["--color-sheet-solid"];
const foreground = theme["--color-foreground"];
- const presentation = useMemo(
- () => ({
- onClose: props.onClose,
- }),
- [props.onClose],
- );
+ const presentation = {
+ onClose: props.onClose,
+ };
return (
<ThreadSettingsPickerPresentationContext.Provider value={presentation}>
@@ -1570,14 +1439,10 @@ export function ExistingThreadSettingsRouteScreen() {
export function NewTaskThreadSettingsRouteScreen() {
const flow = useNewTaskFlow();
const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>();
- const optionDescriptors = useMemo(
- () =>
- resolveProviderOptionDescriptors({
- capabilities: flow.selectedModelOption?.capabilities,
- selections: flow.selectedModel?.options,
- }),
- [flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
- );
+ const optionDescriptors = resolveProviderOptionDescriptors({
+ capabilities: flow.selectedModelOption?.capabilities,
+ selections: flow.selectedModel?.options,
+ });
return (
<ThreadSettingsPickerScreen
diff --git a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx
index 4f9316e3f58..61bdd3597d1 100644
--- a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx
+++ b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx
@@ -1,8 +1,9 @@
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import { AsyncResult } from "effect/reactivity";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/ui/AppText";
import { threadEnvironment } from "../../state/threads";
@@ -22,6 +23,25 @@ export function UsageLimitRecoveryCard({
const canSchedule =
resetAt !== null &&
Date.parse(resetAt) > Date.parse(thread.latestRun?.completedAt ?? thread.updatedAt);
+ // Whether the reset already passed is state a timer flips at resetAt: the
+ // compiler caches render output on its inputs, so reading the clock during
+ // render would leave the snooze button enabled after the reset.
+ const resetAtMs = resetAt === null ? null : Date.parse(resetAt);
+ const [resetPassedFor, setResetPassedFor] = useState<number | null>(null);
+ const resetPassed = resetAtMs !== null && resetPassedFor === resetAtMs;
+ useEffect(() => {
+ if (resetAtMs === null || Number.isNaN(resetAtMs)) return;
+ const flip = () => setResetPassedFor(resetAtMs);
+ const delay = resetAtMs - Date.now();
+ if (delay <= 0) {
+ flip();
+ return;
+ }
+ // Beyond setTimeout's 32-bit range the card re-renders long before then.
+ if (delay > 2_147_483_647) return;
+ const timer = setTimeout(flip, delay);
+ return () => clearTimeout(timer);
+ }, [resetAtMs]);
const runId = thread.latestRun?.runId;
const recovery = thread.limitRecovery;
const scheduled =
@@ -47,23 +67,21 @@ export function UsageLimitRecoveryCard({
}
setPending(true);
setError(null);
- try {
- const result = await updateMetadata({
- environmentId,
- input: {
- threadId: thread.id,
- limitRecovery: {
- runId,
- resetAt,
- ...(action === "resume" ? { autoResume: !scheduled } : { snooze: !snoozed }),
- },
+ const result = await updateMetadata({
+ environmentId,
+ input: {
+ threadId: thread.id,
+ limitRecovery: {
+ runId,
+ resetAt,
+ ...(action === "resume" ? { autoResume: !scheduled } : { snooze: !snoozed }),
},
- });
- if (result._tag === "Failure") throw squashAtomCommandFailure(result);
- } catch (cause) {
+ },
+ });
+ setPending(false);
+ if (AsyncResult.isFailure(result)) {
+ const cause = squashAtomCommandFailure(result);
setError(cause instanceof Error ? cause.message : "Could not change limit recovery.");
- } finally {
- setPending(false);
}
}
return (
@@ -87,7 +105,7 @@ export function UsageLimitRecoveryCard({
</Pressable>
<Pressable
accessibilityRole="button"
- disabled={pending || (!snoozed && Date.parse(resetAt!) <= Date.now())}
+ disabled={pending || (!snoozed && resetPassed)}
onPress={() => void toggle("snooze")}
className="self-start rounded-lg bg-subtle px-3 py-2 active:opacity-70"
>
diff --git a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
index 77a196928a6..d0cf3c345f0 100644
--- a/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
+++ b/apps/mobile/src/features/threads/git/GitCommitSheet.tsx
@@ -1,5 +1,5 @@
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
-import { useCallback, useState } from "react";
+import { useState } from "react";
import { Platform, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -57,28 +57,17 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
const selectedDeletions = selectedFiles.reduce((sum, file) => sum + file.deletions, 0);
const selectedFilePreview = selectedFiles.slice(0, 3);
- const runCommitAction = useCallback(
- async (featureBranch: boolean) => {
- if (!canWriteSourceControl || (featureBranch && !canChangeThreadBranch)) return;
- const commitMessage = dialogCommitMessage.trim();
- navigation.goBack();
- await gitActions.onRunSelectedThreadGitAction({
- action: "commit",
- featureBranch,
- ...(commitMessage ? { commitMessage } : {}),
- ...(!allSelected ? { filePaths: selectedFiles.map((file) => file.path) } : {}),
- });
- },
- [
- allSelected,
- canWriteSourceControl,
- canChangeThreadBranch,
- dialogCommitMessage,
- gitActions,
- navigation,
- selectedFiles,
- ],
- );
+ const runCommitAction = async (featureBranch: boolean) => {
+ if (!canWriteSourceControl || (featureBranch && !canChangeThreadBranch)) return;
+ const commitMessage = dialogCommitMessage.trim();
+ navigation.goBack();
+ await gitActions.onRunSelectedThreadGitAction({
+ action: "commit",
+ featureBranch,
+ ...(commitMessage ? { commitMessage } : {}),
+ ...(!allSelected ? { filePaths: selectedFiles.map((file) => file.path) } : {}),
+ });
+ };
return (
<View
diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
index ba590576cf3..6e131d12dd9 100644
--- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
+++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
@@ -14,7 +14,7 @@ import {
type StaticScreenProps,
} from "@react-navigation/native";
import { SymbolView } from "../../../components/ui/AppSymbol";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useEffect, useState } from "react";
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
import { ScreenStack } from "react-native-screens";
@@ -112,32 +112,25 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {
const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
- const menuItems = useMemo(
- () => (isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : []),
- [busy, gitStatus.data, hasPrimaryRemote, isRepo],
- );
+ const menuItems = isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : [];
- const sheetMenuItems = useMemo(
- () =>
- menuItems.map((item) => ({
- item: {
- ...item,
- disabled: item.disabled || (!canWriteSourceControl && item.kind !== "open_pr"),
- },
- disabledReason:
- !canWriteSourceControl && item.kind !== "open_pr"
- ? "This connection cannot change source control."
- : getGitActionDisabledReason({
- item,
- gitStatus: gitStatus.data,
- isBusy: busy,
- hasOriginRemote: hasPrimaryRemote,
- }),
- })),
- [busy, canWriteSourceControl, gitStatus.data, hasPrimaryRemote, menuItems],
- );
+ const sheetMenuItems = menuItems.map((item) => ({
+ item: {
+ ...item,
+ disabled: item.disabled || (!canWriteSourceControl && item.kind !== "open_pr"),
+ },
+ disabledReason:
+ !canWriteSourceControl && item.kind !== "open_pr"
+ ? "This connection cannot change source control."
+ : getGitActionDisabledReason({
+ item,
+ gitStatus: gitStatus.data,
+ isBusy: busy,
+ hasOriginRemote: hasPrimaryRemote,
+ }),
+ }));
- const openExistingPr = useCallback(async () => {
+ const openExistingPr = async () => {
const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
if (!prUrl) {
Dialog.alert("No open PR", "This branch does not have an open pull request.");
@@ -146,122 +139,92 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {
if (!(await openPullRequest(prUrl))) {
Dialog.alert("Unable to open PR", "The pull request could not be opened.");
}
- }, [gitStatus.data, openPullRequest]);
+ };
- const runActionWithPrompt = useCallback(
- async (input: GitActionRequestInput) => {
- if (!canWriteSourceControl) return;
- const confirmableAction =
- input.action === "push" ||
- input.action === "create_pr" ||
- input.action === "commit_push" ||
- input.action === "commit_push_pr"
- ? input.action
- : null;
- const branchName = gitStatus.data?.refName;
- if (
- branchName &&
- confirmableAction &&
- !input.featureBranch &&
- requiresDefaultBranchConfirmation(input.action, isDefaultRef)
- ) {
- navigation.navigate("GitConfirm", {
- environmentId: String(environmentId),
- threadId: String(threadId),
- confirmAction: confirmableAction,
- branchName,
- includesCommit: String(
- input.action === "commit_push" || input.action === "commit_push_pr",
- ),
- });
- return;
- }
+ const runActionWithPrompt = async (input: GitActionRequestInput) => {
+ if (!canWriteSourceControl) return;
+ const confirmableAction =
+ input.action === "push" ||
+ input.action === "create_pr" ||
+ input.action === "commit_push" ||
+ input.action === "commit_push_pr"
+ ? input.action
+ : null;
+ const branchName = gitStatus.data?.refName;
+ if (
+ branchName &&
+ confirmableAction &&
+ !input.featureBranch &&
+ requiresDefaultBranchConfirmation(input.action, isDefaultRef)
+ ) {
+ navigation.navigate("GitConfirm", {
+ environmentId: String(environmentId),
+ threadId: String(threadId),
+ confirmAction: confirmableAction,
+ branchName,
+ includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"),
+ });
+ return;
+ }
- if (!isInspector) {
- navigation.goBack();
- }
- await gitActions.onRunSelectedThreadGitAction(input);
- },
- [
- canWriteSourceControl,
- environmentId,
- gitActions,
- gitStatus.data,
- isDefaultRef,
- isInspector,
- navigation,
- threadId,
- ],
- );
+ if (!isInspector) {
+ navigation.goBack();
+ }
+ await gitActions.onRunSelectedThreadGitAction(input);
+ };
- const onPressMenuItem = useCallback(
- async (item: (typeof menuItems)[number]) => {
- if (item.disabled) return;
- if (item.kind === "open_pr") {
- await openExistingPr();
- return;
- }
- if (!canWriteSourceControl) return;
- if (item.dialogAction === "commit") {
- navigation.navigate("GitCommit", {
- environmentId: String(environmentId),
- threadId: String(threadId),
- });
- return;
- }
- if (item.dialogAction === "push") {
- await runActionWithPrompt({ action: "push" });
- return;
- }
- if (item.dialogAction === "create_pr") {
- await runActionWithPrompt({ action: "create_pr" });
- }
- },
- [
- canWriteSourceControl,
- environmentId,
- openExistingPr,
- navigation,
- runActionWithPrompt,
- threadId,
- ],
- );
+ const onPressMenuItem = async (item: (typeof menuItems)[number]) => {
+ if (item.disabled) return;
+ if (item.kind === "open_pr") {
+ await openExistingPr();
+ return;
+ }
+ if (!canWriteSourceControl) return;
+ if (item.dialogAction === "commit") {
+ navigation.navigate("GitCommit", {
+ environmentId: String(environmentId),
+ threadId: String(threadId),
+ });
+ return;
+ }
+ if (item.dialogAction === "push") {
+ await runActionWithPrompt({ action: "push" });
+ return;
+ }
+ if (item.dialogAction === "create_pr") {
+ await runActionWithPrompt({ action: "create_pr" });
+ }
+ };
- const rowStatusDetail = useCallback(
- (item: (typeof menuItems)[number]): string | undefined => {
- const status = gitStatus.data;
- if (status == null) {
- return undefined;
- }
- if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
- const fileCount = status.workingTree?.files.length ?? 0;
- return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
- }
- if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
- const ahead = status.aheadCount ?? 0;
- return `${ahead} commit${ahead === 1 ? "" : "s"} ahead`;
- }
- if (item.kind === "open_pr" && status.pr?.number != null) {
- return `PR #${status.pr.number} ${status.pr.state ?? "open"}`;
- }
+ const rowStatusDetail = (item: (typeof menuItems)[number]): string | undefined => {
+ const status = gitStatus.data;
+ if (status == null) {
return undefined;
- },
- [gitStatus.data, menuItems],
- );
+ }
+ if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
+ const fileCount = status.workingTree?.files.length ?? 0;
+ return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
+ }
+ if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
+ const ahead = status.aheadCount ?? 0;
+ return `${ahead} commit${ahead === 1 ? "" : "s"} ahead`;
+ }
+ if (item.kind === "open_pr" && status.pr?.number != null) {
+ return `PR #${status.pr.number} ${status.pr.state ?? "open"}`;
+ }
+ return undefined;
+ };
const behindCount = gitStatus.data?.behindCount ?? 0;
// Tying RefreshControl to the query's isPending flag left the spinner stuck
// (the status query reports pending during quiet background refreshes too).
const [isRefreshing, setIsRefreshing] = useState(false);
- const handleRefresh = useCallback(async () => {
+ const handleRefresh = async () => {
setIsRefreshing(true);
- try {
- await gitActions.refreshSelectedThreadGitStatus();
- } finally {
- setIsRefreshing(false);
- }
- }, [gitActions]);
+ await gitActions.refreshSelectedThreadGitStatus();
+ setIsRefreshing(false);
+ };
const content = (
<ScrollView
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
index 9680052592b..1da765bc775 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -2,7 +2,7 @@ import * as Dialog from "../../components/ui/Dialog";
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
import { useEnvironmentPresentation } from "../../state/presentation";
import { environmentSession } from "../../state/session";
-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import React, { useEffect, useRef, useState } from "react";
import type {
EnvironmentId,
@@ -259,20 +259,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const { enabled: legacyPlanModeEnabled, loaded: planModePreferenceLoaded } =
useLegacyPlanModeState();
- const projectScopes = useMemo(
- () =>
- sortHomeProjectScopes({
- scopes: buildHomeProjectScopes({
- projects,
- environmentId: null,
- projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
- }),
- threads,
- pendingTasks: [],
- projectSortOrder: "updated_at",
- }),
- [groupingSettings.sidebarProjectGroupingMode, projects, threads],
- );
+ const projectScopes = sortHomeProjectScopes({
+ scopes: buildHomeProjectScopes({
+ projects,
+ environmentId: null,
+ projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
+ }),
+ threads,
+ pendingTasks: [],
+ projectSortOrder: "updated_at",
+ });
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
null,
@@ -294,7 +290,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
const editingRevisionRef = useRef(Promise.resolve(0));
- const reset = useCallback(() => {
+ const reset = () => {
setSelectedEnvironmentId(null);
setSelectedProjectKey(null);
setActiveDraftKey(null);
@@ -311,18 +307,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}
releaseEditingQueuedMessage(editing.messageId);
}
- }, []);
+ };
- const projectsForEnvironment = useMemo(
- () =>
- pipe(
- projects,
- Arr.filter((project) => project.environmentId === selectedEnvironmentId),
- ),
- [projects, selectedEnvironmentId],
+ const projectsForEnvironment = pipe(
+ projects,
+ Arr.filter((project) => project.environmentId === selectedEnvironmentId),
);
- const editingPendingProject = useMemo<EnvironmentProject | null>(() => {
+ const editingPendingProject = ((): EnvironmentProject | null => {
const creation = editingPendingTask?.creation;
if (!editingPendingTask || !creation) {
return null;
@@ -338,7 +330,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
createdAt: editingPendingTask.createdAt,
updatedAt: editingPendingTask.createdAt,
};
- }, [editingPendingTask]);
+ })();
const selectedProject =
projectsForEnvironment.find(
@@ -361,16 +353,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot);
const serverConfigs = useServerConfigs();
const { connectedEnvironments } = useRemoteConnectionStatus();
- const scratchEnvironments = useMemo(
- () =>
- connectedEnvironments.filter(
- (environment) =>
- availableScratchWorkspaceRoot(
- environment.connectionState,
- serverConfigs.get(environment.environmentId),
- ) !== null,
- ),
- [connectedEnvironments, serverConfigs],
+ const scratchEnvironments = connectedEnvironments.filter(
+ (environment) =>
+ availableScratchWorkspaceRoot(
+ environment.connectionState,
+ serverConfigs.get(environment.environmentId),
+ ) !== null,
);
const selectedRepositoryKey = selectedProject?.repositoryIdentity
@@ -380,7 +368,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
// workspaceRoot, and an "" basename would reject every real host below.
const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
const selectedProjectTitle = selectedProject?.title ?? null;
- const environments = useMemo(() => {
+ const environments = (() => {
if (isScratchDraft) {
return scratchEnvironments.map((environment) => ({
environmentId: environment.environmentId,
@@ -425,15 +413,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
});
}
return result;
- }, [
- isScratchDraft,
- projects,
- savedConnectionsById,
- scratchEnvironments,
- selectedRepositoryKey,
- selectedWorkspaceBasename,
- selectedProjectTitle,
- ]);
+ })();
const selectedProjectDraftKey = editingPendingTask
? pendingTaskDraftKey(editingPendingTask.messageId)
@@ -478,22 +458,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
: null,
);
const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
- const t3ProjectFile = useMemo(
- () =>
- t3ProjectFileData === null || t3ProjectFileData.truncated
- ? null
- : parseT3ProjectFile(t3ProjectFileData.contents),
- [t3ProjectFileData],
- );
- const projectSettings = useMemo(
- () =>
- resolveProjectSettings(
- selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
- selectedProject?.id ?? null,
- selectedProject,
- t3ProjectFile,
- ),
- [selectedEnvironmentServerConfig?.settings, selectedProject, t3ProjectFile],
+ const t3ProjectFile =
+ t3ProjectFileData === null || t3ProjectFileData.truncated
+ ? null
+ : parseT3ProjectFile(t3ProjectFileData.contents);
+ const projectSettings = resolveProjectSettings(
+ selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
+ selectedProject?.id ?? null,
+ selectedProject,
+ t3ProjectFile,
);
const canChooseWorkspace = !isScratchDraft;
const selectedProjectHasThreads =
@@ -553,21 +526,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
storedStickyModelSelection,
selectedProject?.id ?? null,
);
- const modelOptions = useMemo(
- () =>
- buildModelOptions(
- selectedEnvironmentServerConfig,
- draftModelSelection ?? projectDefaultModelSelection ?? stickyModelSelection,
- undefined,
- selectedProject?.id ?? null,
- ),
- [
- selectedEnvironmentServerConfig,
- draftModelSelection,
- projectDefaultModelSelection,
- stickyModelSelection,
- selectedProject?.id,
- ],
+ const modelOptions = buildModelOptions(
+ selectedEnvironmentServerConfig,
+ draftModelSelection ?? projectDefaultModelSelection ?? stickyModelSelection,
+ undefined,
+ selectedProject?.id ?? null,
);
const selectedModel = resolveNewTaskModelSelection({
@@ -587,124 +550,101 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
option.selection.instanceId === selectedModel.instanceId &&
option.selection.model === selectedModel.model,
) ?? null;
- const selectedProviderStatus = useMemo(
- () =>
- selectedEnvironmentServerConfig?.providers.find(
- (provider) => provider.instanceId === selectedModel?.instanceId,
- ) ?? null,
- [selectedEnvironmentServerConfig, selectedModel?.instanceId],
- );
+ const selectedProviderStatus =
+ selectedEnvironmentServerConfig?.providers.find(
+ (provider) => provider.instanceId === selectedModel?.instanceId,
+ ) ?? null;
const planModeEnabled =
legacyPlanModeEnabled && selectedProviderStatus?.showInteractionModeToggle !== false;
const interactionMode = planModeEnabled
? (selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE)
: DEFAULT_PROVIDER_INTERACTION_MODE;
- const setSelectedModelKey = useCallback(
- // Options ride along in the same write: a follow-up setSelectedModelOptions
- // call would rebuild the selection from the stale pre-switch model.
- (key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => {
- if (!key || !selectedProjectDraftKey) {
- return;
- }
- const option = modelOptions.find((candidate) => candidate.key === key);
- if (!option) {
- return;
- }
- const selection = withRememberedModelOptions(
- options ? { ...option.selection, options } : option.selection,
- );
- const provider = selectedEnvironmentServerConfig?.providers.find(
- (candidate) => candidate.instanceId === selection.instanceId,
- );
- updateComposerDraftSettings(selectedProjectDraftKey, {
- modelSelection: selection,
- ...(provider?.showInteractionModeToggle === false
- ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
- : {}),
- });
- setStickyComposerModelSelection(selection);
- },
- [modelOptions, selectedEnvironmentServerConfig, selectedProjectDraftKey],
- );
- const setSelectedModelOptions = useCallback(
- (options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
- if (!selectedModel || !selectedProjectDraftKey) {
- return;
- }
- rememberModelOptions(selectedModel.instanceId, selectedModel.model, options ?? []);
- const nextSelection: ModelSelection = options
- ? { ...selectedModel, options }
- : {
- instanceId: selectedModel.instanceId,
- model: selectedModel.model,
- };
- updateComposerDraftSettings(selectedProjectDraftKey, {
- modelSelection: nextSelection,
- });
- setStickyComposerModelSelection(nextSelection);
- },
- [selectedModel, selectedProjectDraftKey],
- );
+ const setSelectedModelKey = (
+ key: string | null,
+ options?: ReadonlyArray<ProviderOptionSelection>,
+ ) => {
+ if (!key || !selectedProjectDraftKey) {
+ return;
+ }
+ const option = modelOptions.find((candidate) => candidate.key === key);
+ if (!option) {
+ return;
+ }
+ const selection = withRememberedModelOptions(
+ options ? { ...option.selection, options } : option.selection,
+ );
+ const provider = selectedEnvironmentServerConfig?.providers.find(
+ (candidate) => candidate.instanceId === selection.instanceId,
+ );
+ updateComposerDraftSettings(selectedProjectDraftKey, {
+ modelSelection: selection,
+ ...(provider?.showInteractionModeToggle === false
+ ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
+ : {}),
+ });
+ setStickyComposerModelSelection(selection);
+ };
+ const setSelectedModelOptions = (options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
+ if (!selectedModel || !selectedProjectDraftKey) {
+ return;
+ }
+ rememberModelOptions(selectedModel.instanceId, selectedModel.model, options ?? []);
+ const nextSelection: ModelSelection = options
+ ? { ...selectedModel, options }
+ : {
+ instanceId: selectedModel.instanceId,
+ model: selectedModel.model,
+ };
+ updateComposerDraftSettings(selectedProjectDraftKey, {
+ modelSelection: nextSelection,
+ });
+ setStickyComposerModelSelection(nextSelection);
+ };
- const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
- const setPrompt = useCallback(
- (value: string) => {
- if (!selectedProjectDraftKey) {
- return;
- }
- setComposerDraftText(selectedProjectDraftKey, value);
- },
- [selectedProjectDraftKey],
- );
- const replaceAttachments = useCallback(
- (nextAttachments: ReadonlyArray<DraftComposerAttachment>) => {
- if (!selectedProjectDraftKey) {
- return;
- }
- replaceComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
- },
- [selectedProjectDraftKey],
- );
- const appendAttachments = useCallback(
- (
- nextAttachments: ReadonlyArray<DraftComposerAttachment>,
- insertion?: ComposerDraftInsertion,
- ): number => {
- if (!selectedProjectDraftKey) {
- return 0;
- }
- return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments, {
- appendReference: true,
- insertion,
- });
- },
- [selectedProjectDraftKey],
- );
- const removeAttachment = useCallback(
- (imageId: string) => {
- if (!selectedProjectDraftKey) {
- return;
- }
- removeComposerDraftAttachment(selectedProjectDraftKey, imageId);
- },
- [selectedProjectDraftKey],
- );
- const clearAttachments = useCallback(() => {
+ const providerGroups = groupByProvider(modelOptions);
+ const setPrompt = (value: string) => {
+ if (!selectedProjectDraftKey) {
+ return;
+ }
+ setComposerDraftText(selectedProjectDraftKey, value);
+ };
+ const replaceAttachments = (nextAttachments: ReadonlyArray<DraftComposerAttachment>) => {
+ if (!selectedProjectDraftKey) {
+ return;
+ }
+ replaceComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
+ };
+ const appendAttachments = (
+ nextAttachments: ReadonlyArray<DraftComposerAttachment>,
+ insertion?: ComposerDraftInsertion,
+ ): number => {
+ if (!selectedProjectDraftKey) {
+ return 0;
+ }
+ return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments, {
+ appendReference: true,
+ insertion,
+ });
+ };
+ const removeAttachment = (imageId: string) => {
+ if (!selectedProjectDraftKey) {
+ return;
+ }
+ removeComposerDraftAttachment(selectedProjectDraftKey, imageId);
+ };
+ const clearAttachments = () => {
if (!selectedProjectDraftKey) {
return;
}
replaceComposerDraftAttachments(selectedProjectDraftKey, []);
- }, [selectedProjectDraftKey]);
+ };
const branchSearchQuery = sanitizeNewRefName(branchQuery);
const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
- const branchTarget = useMemo(
- () => ({
- environmentId: selectedProject?.environmentId ?? null,
- cwd: selectedProject?.workspaceRoot || null,
- query: debouncedBranchQuery,
- }),
- [debouncedBranchQuery, selectedProject?.environmentId, selectedProject?.workspaceRoot],
- );
+ const branchTarget = {
+ environmentId: selectedProject?.environmentId ?? null,
+ cwd: selectedProject?.workspaceRoot || null,
+ query: debouncedBranchQuery,
+ };
const branchState = usePaginatedBranches(branchTarget);
const branchSearchIsDebouncing = branchSearchQuery !== debouncedBranchQuery;
const branchesLoading =
@@ -713,13 +653,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const hasMoreBranches =
branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;
const allBranchRefs = branchState.refs;
- const availableBranches = useMemo(
- () =>
- pipe(
- allBranchRefs,
- Arr.filter((branch) => !branch.isRemote),
- ),
- [allBranchRefs],
+ const availableBranches = pipe(
+ allBranchRefs,
+ Arr.filter((branch) => !branch.isRemote),
);
const projectGitStatus = useEnvironmentQuery(
branchTarget.environmentId !== null && branchTarget.cwd !== null
@@ -731,153 +667,119 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const currentCheckoutBranchName = projectGitStatus.data?.refName ?? null;
- const filteredBranches = useMemo(
- () => filterNewTaskBranches(allBranchRefs, branchQuery),
- [allBranchRefs, branchQuery],
- );
+ const filteredBranches = filterNewTaskBranches(allBranchRefs, branchQuery);
- const carryDraftContentTo = useCallback(
- (project: EnvironmentProject) => {
- const target = { environmentId: project.environmentId, projectId: project.id };
- if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
- retargetNewTaskDraft(activeDraftKey, target);
- } else if (!editingPendingTaskRef.current) {
- setActiveDraftKey(createNewTaskDraft(target));
- }
- },
- [activeDraftKey],
- );
+ const carryDraftContentTo = (project: EnvironmentProject) => {
+ const target = { environmentId: project.environmentId, projectId: project.id };
+ if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
+ retargetNewTaskDraft(activeDraftKey, target);
+ } else if (!editingPendingTaskRef.current) {
+ setActiveDraftKey(createNewTaskDraft(target));
+ }
+ };
- const setProject = useCallback(
- (project: EnvironmentProject) => {
- carryDraftContentTo(project);
- setSelectedEnvironmentId(project.environmentId);
- setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
- },
- [carryDraftContentTo],
- );
+ const setProject = (project: EnvironmentProject) => {
+ carryDraftContentTo(project);
+ setSelectedEnvironmentId(project.environmentId);
+ setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
+ };
- const openDraft = useCallback(
- (draftKey: string): boolean => {
- const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
- const stamp = draft?.project;
- if (!isNewTaskDraftKey(draftKey) || !stamp) {
- return false;
- }
- // The stamped project must be loaded: selectedProject falls back to
- // the environment's first project otherwise, and the draft would be
- // sent somewhere the user never chose.
- const projectLoaded = projects.some(
- (project) =>
- project.environmentId === stamp.environmentId && project.id === stamp.projectId,
- );
- if (!projectLoaded) {
- return false;
- }
- setActiveDraftKey(draftKey);
- setSelectedEnvironmentId(stamp.environmentId);
- setSelectedProjectKey(scopedProjectKey(stamp.environmentId, stamp.projectId));
- return true;
- },
- [projects],
- );
+ const openDraft = (draftKey: string): boolean => {
+ const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
+ const stamp = draft?.project;
+ if (!isNewTaskDraftKey(draftKey) || !stamp) {
+ return false;
+ }
+ // The stamped project must be loaded: selectedProject falls back to
+ // the environment's first project otherwise, and the draft would be
+ // sent somewhere the user never chose.
+ const projectLoaded = projects.some(
+ (project) => project.environmentId === stamp.environmentId && project.id === stamp.projectId,
+ );
+ if (!projectLoaded) {
+ return false;
+ }
+ setActiveDraftKey(draftKey);
+ setSelectedEnvironmentId(stamp.environmentId);
+ setSelectedProjectKey(scopedProjectKey(stamp.environmentId, stamp.projectId));
+ return true;
+ };
- const selectEnvironment = useCallback(
- (environmentId: EnvironmentId) => {
- const match = resolveEnvironmentProjectMatch(
- projects.filter((project) => project.environmentId === environmentId),
- selectedProject,
- );
- if (match) {
- carryDraftContentTo(match);
- }
- setSelectedEnvironmentId(environmentId);
- setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
- },
- [projects, selectedProject, carryDraftContentTo],
- );
+ const selectEnvironment = (environmentId: EnvironmentId) => {
+ const match = resolveEnvironmentProjectMatch(
+ projects.filter((project) => project.environmentId === environmentId),
+ selectedProject,
+ );
+ if (match) {
+ carryDraftContentTo(match);
+ }
+ setSelectedEnvironmentId(environmentId);
+ setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
+ };
const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
const [switchingToEnvironmentId, setSwitchingToEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const latestSwitchRef = useRef<object | null>(null);
- const switchEnvironment = useCallback(
- async (environmentId: EnvironmentId): Promise<boolean> => {
- if (environmentId === selectedEnvironmentId) {
- latestSwitchRef.current = null;
- setSwitchingToEnvironmentId(null);
- return true;
- }
- if (!isScratchDraft) {
- selectEnvironment(environmentId);
- return true;
- }
- const request = {};
- latestSwitchRef.current = request;
- setSwitchingToEnvironmentId(environmentId);
- try {
- const result = await openScratch({ environmentId, input: {} });
- if (latestSwitchRef.current !== request) return false;
- if (result._tag === "Success") {
- setProject(result.value);
- return true;
- }
- if (!isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
- Dialog.alert(
- "Could not switch machine",
- error instanceof Error
- ? error.message
- : "The folder for threads without a project could not be created.",
- );
- }
- return false;
- } finally {
- if (latestSwitchRef.current === request) {
- latestSwitchRef.current = null;
- setSwitchingToEnvironmentId(null);
- }
- }
- },
- [isScratchDraft, openScratch, selectEnvironment, selectedEnvironmentId, setProject],
- );
+ const switchEnvironment = async (environmentId: EnvironmentId): Promise<boolean> => {
+ if (environmentId === selectedEnvironmentId) {
+ latestSwitchRef.current = null;
+ setSwitchingToEnvironmentId(null);
+ return true;
+ }
+ if (!isScratchDraft) {
+ selectEnvironment(environmentId);
+ return true;
+ }
+ const request = {};
+ latestSwitchRef.current = request;
+ setSwitchingToEnvironmentId(environmentId);
+ const result = await openScratch({ environmentId, input: {} });
+ if (latestSwitchRef.current !== request) return false;
+ latestSwitchRef.current = null;
+ setSwitchingToEnvironmentId(null);
+ if (result._tag === "Success") {
+ setProject(result.value);
+ return true;
+ }
+ if (!isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ Dialog.alert(
+ "Could not switch machine",
+ error instanceof Error
+ ? error.message
+ : "The folder for threads without a project could not be created.",
+ );
+ }
+ return false;
+ };
- const setWorkspaceMode = useCallback(
- (mode: WorkspaceMode) => {
- if (!selectedProjectDraftKey) {
- return;
- }
- if (!selectedProject) {
- return;
- }
- const localSelection = resolveNewTaskLocalWorkspaceSelection({
- branches: availableBranches,
- projectCwd: selectedProject.workspaceRoot,
- });
- if (mode === "local" && localSelection.awaitsCurrentBranch) {
- pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
- } else {
- pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
- }
- updateComposerDraftSettings(selectedProjectDraftKey, {
- workspaceSelection: {
- mode,
- branch: mode === "local" ? localSelection.branch : selectedBranchName,
- worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
- ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
- },
- });
- },
- [
- availableBranches,
- draftStartFromOrigin,
- selectedBranchName,
- selectedProject,
- selectedProjectDraftKey,
- selectedWorktreePath,
- ],
- );
+ const setWorkspaceMode = (mode: WorkspaceMode) => {
+ if (!selectedProjectDraftKey) {
+ return;
+ }
+ if (!selectedProject) {
+ return;
+ }
+ const localSelection = resolveNewTaskLocalWorkspaceSelection({
+ branches: availableBranches,
+ projectCwd: selectedProject.workspaceRoot,
+ });
+ if (mode === "local" && localSelection.awaitsCurrentBranch) {
+ pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
+ } else {
+ pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
+ }
+ updateComposerDraftSettings(selectedProjectDraftKey, {
+ workspaceSelection: {
+ mode,
+ branch: mode === "local" ? localSelection.branch : selectedBranchName,
+ worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
+ ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
+ },
+ });
+ };
useEffect(() => {
if (
@@ -913,54 +815,48 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode,
]);
- const selectBranch = useCallback(
- (branch: VcsRef) => {
- if (!selectedProject || !selectedProjectDraftKey) {
- return;
- }
- pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
- updateComposerDraftSettings(selectedProjectDraftKey, {
- workspaceSelection: {
- mode: workspaceMode,
- branch: branch.name,
- worktreePath: resolveNewTaskBranchWorktreePath({
- workspaceMode,
- projectCwd: selectedProject.workspaceRoot,
- branchWorktreePath: branch.worktreePath,
- }),
- ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
- },
- });
- },
- [draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
- );
+ const selectBranch = (branch: VcsRef) => {
+ if (!selectedProject || !selectedProjectDraftKey) {
+ return;
+ }
+ pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
+ updateComposerDraftSettings(selectedProjectDraftKey, {
+ workspaceSelection: {
+ mode: workspaceMode,
+ branch: branch.name,
+ worktreePath: resolveNewTaskBranchWorktreePath({
+ workspaceMode,
+ projectCwd: selectedProject.workspaceRoot,
+ branchWorktreePath: branch.worktreePath,
+ }),
+ ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
+ },
+ });
+ };
- const setStartFromOrigin = useCallback(
- (value: boolean) => {
- if (!selectedProjectDraftKey) {
- return;
- }
- updateComposerDraftSettings(selectedProjectDraftKey, {
- workspaceSelection: {
- mode: workspaceMode,
- branch: selectedBranchName,
- worktreePath: selectedWorktreePath,
- startFromOrigin: value,
- },
- });
- },
- [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, workspaceMode],
- );
+ const setStartFromOrigin = (value: boolean) => {
+ if (!selectedProjectDraftKey) {
+ return;
+ }
+ updateComposerDraftSettings(selectedProjectDraftKey, {
+ workspaceSelection: {
+ mode: workspaceMode,
+ branch: selectedBranchName,
+ worktreePath: selectedWorktreePath,
+ startFromOrigin: value,
+ },
+ });
+ };
const refreshBranches = branchState.refresh;
const loadMoreBranches = branchState.loadNext;
- const loadBranches = useCallback(() => {
+ const loadBranches = () => {
if (!selectedProject) {
return;
}
setPendingConnectionError(null);
refreshBranches();
- }, [refreshBranches, selectedProject]);
+ };
useEffect(() => {
if (
@@ -997,26 +893,20 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode,
]);
- const setRuntimeMode = useCallback(
- (value: RuntimeMode) => {
- if (selectedProjectDraftKey) {
- updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
- }
- },
- [selectedProjectDraftKey],
- );
- const setInteractionMode = useCallback(
- (value: ProviderInteractionMode) => {
- if (selectedProjectDraftKey) {
- updateComposerDraftSettings(selectedProjectDraftKey, {
- interactionMode: resolveProviderInteractionMode(selectedProviderStatus, value),
- });
- }
- },
- [selectedProjectDraftKey, selectedProviderStatus],
- );
+ const setRuntimeMode = (value: RuntimeMode) => {
+ if (selectedProjectDraftKey) {
+ updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
+ }
+ };
+ const setInteractionMode = (value: ProviderInteractionMode) => {
+ if (selectedProjectDraftKey) {
+ updateComposerDraftSettings(selectedProjectDraftKey, {
+ interactionMode: resolveProviderInteractionMode(selectedProviderStatus, value),
+ });
+ }
+ };
- const beginEditingPendingTask = useCallback((messageId: string): boolean => {
+ const beginEditingPendingTask = (messageId: string): boolean => {
const message = findQueuedPendingTask(messageId);
if (!message?.creation) {
return false;
@@ -1047,101 +937,85 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setEditingPendingTask(message);
holdEditingQueuedMessage(message.messageId);
return true;
- }, []);
+ };
- const buildPendingTaskMessage = useCallback(
- (
- metadata: TurnCommandMetadata,
- options?: { readonly currentCheckoutBranch?: string | null },
- ): QueuedThreadMessage | null => {
- if (!selectedProject || !selectedProjectDraftKey) {
- return null;
- }
- const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
- const text = draft.text.trim();
- const draftModelSelection =
- resolveSelectableModelSelection(
- selectedEnvironmentServerConfig,
- draft.modelSelection ?? null,
- selectedProject.id,
- ) ?? selectedModel;
- if ((text.length === 0 && draft.attachments.length === 0) || !draftModelSelection) {
- return null;
- }
- const workspaceSelection = canChooseWorkspace ? draft.workspaceSelection : undefined;
- const mode = workspaceSelection?.mode ?? workspaceMode;
- // When the selection is the stand-in built from the queued snapshot,
- // persist the original (possibly absent) snapshot values — the
- // stand-in's placeholder title/workspaceRoot must never be written back
- // as if they were real project metadata.
- const usingPendingSnapshot = selectedProject === editingPendingProject;
- const projectTitle = usingPendingSnapshot
- ? editingPendingTask?.creation?.projectTitle
- : selectedProject.title;
- const projectCwd = usingPendingSnapshot
- ? editingPendingTask?.creation?.projectCwd
- : selectedProject.workspaceRoot;
- return {
- environmentId: selectedProject.environmentId,
- threadId: ThreadId.make(metadata.threadId),
- messageId: MessageId.make(metadata.messageId),
- commandId: CommandId.make(metadata.commandId),
- text,
- attachments: draft.attachments,
- context: draft.context,
- modelSelection: draftModelSelection,
- runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
- interactionMode: resolvePendingTaskInteractionMode({
- preferenceLoaded: planModePreferenceLoaded,
- planModeEnabled: legacyPlanModeEnabled,
- draftInteractionMode: draft.interactionMode,
- queuedInteractionMode: editingPendingTask?.interactionMode,
- provider: selectedEnvironmentServerConfig?.providers.find(
- (candidate) => candidate.instanceId === draftModelSelection.instanceId,
- ),
- }),
- creation: {
- projectId: selectedProject.id,
- ...(projectTitle !== undefined ? { projectTitle } : {}),
- ...(projectCwd !== undefined ? { projectCwd } : {}),
+ const buildPendingTaskMessage = (
+ metadata: TurnCommandMetadata,
+ options?: { readonly currentCheckoutBranch?: string | null },
+ ): QueuedThreadMessage | null => {
+ if (!selectedProject || !selectedProjectDraftKey) {
+ return null;
+ }
+ const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
+ const text = draft.text.trim();
+ const draftModelSelection =
+ resolveSelectableModelSelection(
+ selectedEnvironmentServerConfig,
+ draft.modelSelection ?? null,
+ selectedProject.id,
+ ) ?? selectedModel;
+ if ((text.length === 0 && draft.attachments.length === 0) || !draftModelSelection) {
+ return null;
+ }
+ const workspaceSelection = canChooseWorkspace ? draft.workspaceSelection : undefined;
+ const mode = workspaceSelection?.mode ?? workspaceMode;
+ // When the selection is the stand-in built from the queued snapshot,
+ // persist the original (possibly absent) snapshot values — the
+ // stand-in's placeholder title/workspaceRoot must never be written back
+ // as if they were real project metadata.
+ const usingPendingSnapshot = selectedProject === editingPendingProject;
+ const projectTitle = usingPendingSnapshot
+ ? editingPendingTask?.creation?.projectTitle
+ : selectedProject.title;
+ const projectCwd = usingPendingSnapshot
+ ? editingPendingTask?.creation?.projectCwd
+ : selectedProject.workspaceRoot;
+ return {
+ environmentId: selectedProject.environmentId,
+ threadId: ThreadId.make(metadata.threadId),
+ messageId: MessageId.make(metadata.messageId),
+ commandId: CommandId.make(metadata.commandId),
+ text,
+ attachments: draft.attachments,
+ context: draft.context,
+ modelSelection: draftModelSelection,
+ runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
+ interactionMode: resolvePendingTaskInteractionMode({
+ preferenceLoaded: planModePreferenceLoaded,
+ planModeEnabled: legacyPlanModeEnabled,
+ draftInteractionMode: draft.interactionMode,
+ queuedInteractionMode: editingPendingTask?.interactionMode,
+ provider: selectedEnvironmentServerConfig?.providers.find(
+ (candidate) => candidate.instanceId === draftModelSelection.instanceId,
+ ),
+ }),
+ creation: {
+ projectId: selectedProject.id,
+ ...(projectTitle !== undefined ? { projectTitle } : {}),
+ ...(projectCwd !== undefined ? { projectCwd } : {}),
+ workspaceMode: mode,
+ ...(mode === "worktree" && workspaceSelection?.pullRequestReference
+ ? { pullRequestReference: workspaceSelection.pullRequestReference }
+ : {}),
+ // An explicit picker choice wins. Otherwise only a task sending now
+ // records the current checkout: a queued local task drains days
+ // later against whatever is checked out then, so a queue-time
+ // guess would pin a stale label to a thread that ran somewhere else.
+ branch: resolveProjectThreadCreationBranch({
workspaceMode: mode,
- ...(mode === "worktree" && workspaceSelection?.pullRequestReference
- ? { pullRequestReference: workspaceSelection.pullRequestReference }
- : {}),
- // An explicit picker choice wins. Otherwise only a task sending now
- // records the current checkout: a queued local task drains days
- // later against whatever is checked out then, so a queue-time
- // guess would pin a stale label to a thread that ran somewhere else.
- branch: resolveProjectThreadCreationBranch({
- workspaceMode: mode,
- selectedBranch: workspaceSelection?.branch ?? null,
- currentCheckoutBranch: options?.currentCheckoutBranch ?? null,
- }),
- worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
- ...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
- ? { startFromOrigin: true }
- : {}),
- },
- createdAt: metadata.createdAt,
- };
- },
- [
- canChooseWorkspace,
- defaultRuntimeMode,
- editingPendingProject,
- editingPendingTask,
- selectedEnvironmentServerConfig,
- selectedModel,
- selectedProject,
- selectedProjectDraftKey,
- legacyPlanModeEnabled,
- planModePreferenceLoaded,
- startFromOrigin,
- workspaceMode,
- ],
- );
+ selectedBranch: workspaceSelection?.branch ?? null,
+ currentCheckoutBranch: options?.currentCheckoutBranch ?? null,
+ }),
+ worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
+ ...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
+ ? { startFromOrigin: true }
+ : {}),
+ },
+ createdAt: metadata.createdAt,
+ };
+ };
- const finishEditingPendingTask = useCallback(() => {
+ const finishEditingPendingTask = () => {
const editing = editingPendingTaskRef.current;
editingPendingTaskRef.current = null;
if (editing) {
@@ -1153,7 +1027,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
scheduleUnusedComposerAttachmentCleanup(editing.attachments);
}
setEditingPendingTask(null);
- }, []);
+ };
// If the queued task disappears mid-edit (deleted from the list, or
// delivered), end the editing session immediately without saving — a later
@@ -1227,9 +1101,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
});
};
}, [buildPendingTaskMessage]);
- const cancelEditingPendingTask = useCallback(() => {
+ const cancelEditingPendingTask = () => {
editingFlushRef.current?.();
- }, []);
+ };
useEffect(
() => () => {
editingFlushRef.current?.();
@@ -1237,133 +1111,70 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[],
);
- const value = useMemo<NewTaskFlowContextValue>(
- () => ({
- projectScopes,
- selectedEnvironmentId,
- selectedProjectKey,
- selectedModelKey,
- workspaceMode,
- canChooseWorkspace,
- selectedBranchName,
- selectedWorktreePath,
- startFromOrigin,
- draftKey: selectedProjectDraftKey,
- pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
- editingPendingTask,
- prompt,
- attachments,
- submitting,
- branchQuery,
- branchesLoading,
- branchesError: branchState.error,
- branchesFetchingNextPage,
- hasMoreBranches,
- availableBranches,
- currentCheckoutBranchName,
- runtimeMode,
- interactionMode,
- planModeEnabled,
- expandedProvider,
- environments,
- selectedProject,
- isScratchDraft,
- modelOptions,
- selectedModel,
- selectedModelOption,
- selectedProviderStatus,
- providerGroups,
- filteredBranches,
- reset,
- setProject,
- openDraft,
- selectEnvironment,
- switchEnvironment,
- switchingToEnvironmentId,
- setSelectedModelKey,
- setWorkspaceMode,
- selectBranch,
- setStartFromOrigin,
- beginEditingPendingTask,
- finishEditingPendingTask,
- cancelEditingPendingTask,
- buildPendingTaskMessage,
- setPrompt,
- replaceAttachments,
- appendAttachments,
- removeAttachment,
- clearAttachments,
- setSubmitting,
- setBranchQuery,
- loadBranches,
- loadMoreBranches,
- setRuntimeMode,
- setInteractionMode,
- setSelectedModelOptions,
- setExpandedProvider,
- }),
- [
- attachments,
- availableBranches,
- beginEditingPendingTask,
- branchQuery,
- branchesLoading,
- branchState.error,
- branchesFetchingNextPage,
- buildPendingTaskMessage,
- cancelEditingPendingTask,
- currentCheckoutBranchName,
- editingPendingTask,
- environments,
- expandedProvider,
- filteredBranches,
- finishEditingPendingTask,
- interactionMode,
- isScratchDraft,
- planModeEnabled,
- loadBranches,
- loadMoreBranches,
- projectScopes,
- modelOptions,
- prompt,
- providerGroups,
- replaceAttachments,
- reset,
- runtimeMode,
- selectedBranchName,
- hasMoreBranches,
- selectedEnvironmentId,
- selectedModel,
- selectedModelKey,
- selectedModelOption,
- selectedProjectDraftKey,
- selectedProviderStatus,
- setSelectedModelOptions,
- selectedProject,
- selectedProjectDraft.workspaceSelection?.pullRequestReference,
- selectedProjectKey,
- selectedWorktreePath,
- setProject,
- openDraft,
- selectBranch,
- selectEnvironment,
- switchEnvironment,
- switchingToEnvironmentId,
- setInteractionMode,
- setPrompt,
- setRuntimeMode,
- setSelectedModelKey,
- setStartFromOrigin,
- setWorkspaceMode,
- startFromOrigin,
- submitting,
- workspaceMode,
- canChooseWorkspace,
- appendAttachments,
- clearAttachments,
- removeAttachment,
- ],
- );
+ const value = {
+ projectScopes,
+ selectedEnvironmentId,
+ selectedProjectKey,
+ selectedModelKey,
+ workspaceMode,
+ canChooseWorkspace,
+ selectedBranchName,
+ selectedWorktreePath,
+ startFromOrigin,
+ draftKey: selectedProjectDraftKey,
+ pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
+ editingPendingTask,
+ prompt,
+ attachments,
+ submitting,
+ branchQuery,
+ branchesLoading,
+ branchesError: branchState.error,
+ branchesFetchingNextPage,
+ hasMoreBranches,
+ availableBranches,
+ currentCheckoutBranchName,
+ runtimeMode,
+ interactionMode,
+ planModeEnabled,
+ expandedProvider,
+ environments,
+ selectedProject,
+ isScratchDraft,
+ modelOptions,
+ selectedModel,
+ selectedModelOption,
+ selectedProviderStatus,
+ providerGroups,
+ filteredBranches,
+ reset,
+ setProject,
+ openDraft,
+ selectEnvironment,
+ switchEnvironment,
+ switchingToEnvironmentId,
+ setSelectedModelKey,
+ setWorkspaceMode,
+ selectBranch,
+ setStartFromOrigin,
+ beginEditingPendingTask,
+ finishEditingPendingTask,
+ cancelEditingPendingTask,
+ buildPendingTaskMessage,
+ setPrompt,
+ replaceAttachments,
+ appendAttachments,
+ removeAttachment,
+ clearAttachments,
+ setSubmitting,
+ setBranchQuery,
+ loadBranches,
+ loadMoreBranches,
+ setRuntimeMode,
+ setInteractionMode,
+ setSelectedModelOptions,
+ setExpandedProvider,
+ } satisfies NewTaskFlowContextValue;
return <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>;
}
diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx
index 925928a342a..b6d28c41dc7 100644
--- a/apps/mobile/src/features/threads/thread-work-log.tsx
+++ b/apps/mobile/src/features/threads/thread-work-log.tsx
@@ -21,12 +21,9 @@ import type { LegendListRef } from "@legendapp/list/react-native";
import { AnimatedLegendList } from "@legendapp/list/reanimated";
import { StackActions, useIsFocused, useNavigation } from "@react-navigation/native";
import {
- memo,
- useCallback,
useEffect,
useId,
useLayoutEffect,
- useMemo,
useRef,
useState,
type ComponentProps,
@@ -493,37 +490,22 @@ interface ThreadWorkLogProps {
}
export function ThreadWorkLog(props: ThreadWorkLogProps) {
- const renderRow = useCallback(
- (row: ThreadFeedActivity) => (
- <ThreadWorkLogRow
- key={row.id}
- row={row}
- anchorKey={props.anchorKey}
- copied={props.copiedRowId === row.id}
- expanded={props.expandedRows[row.id] ?? false}
- environmentId={props.environmentId}
- iconSubtleColor={props.iconSubtleColor}
- onCopyRow={props.onCopyRow}
- onToggleRow={props.onToggleRow}
- renderImage={props.renderImage}
- renderReasoning={props.renderReasoning}
- onPressPreview={props.onPressPreview}
- themeAppearance={props.themeAppearance}
- />
- ),
- [
- props.anchorKey,
- props.copiedRowId,
- props.expandedRows,
- props.environmentId,
- props.iconSubtleColor,
- props.onCopyRow,
- props.onToggleRow,
- props.renderImage,
- props.renderReasoning,
- props.onPressPreview,
- props.themeAppearance,
- ],
+ const renderRow = (row: ThreadFeedActivity) => (
+ <ThreadWorkLogRow
+ key={row.id}
+ row={row}
+ anchorKey={props.anchorKey}
+ copied={props.copiedRowId === row.id}
+ expanded={props.expandedRows[row.id] ?? false}
+ environmentId={props.environmentId}
+ iconSubtleColor={props.iconSubtleColor}
+ onCopyRow={props.onCopyRow}
+ onToggleRow={props.onToggleRow}
+ renderImage={props.renderImage}
+ renderReasoning={props.renderReasoning}
+ onPressPreview={props.onPressPreview}
+ themeAppearance={props.themeAppearance}
+ />
);
if (props.activities.length === 0) {
@@ -608,7 +590,7 @@ function ThreadWorkGroupList(props: {
);
const height = Math.min(contentHeight, WORK_GROUP_MAX_HEIGHT);
const scrollOffset = useSharedValue(initialPosition?.scrollOffset ?? 0);
- const sharedValues = useMemo(() => ({ scrollOffset }), [scrollOffset]);
+ const sharedValues = { scrollOffset };
const topFadeStyle = useAnimatedStyle(() => ({
opacity: Math.min(1, Math.max(0, scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT),
@@ -619,7 +601,7 @@ function ThreadWorkGroupList(props: {
Math.max(0, contentHeight - height - scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT,
),
}));
- const rememberPosition = useCallback(() => {
+ const rememberPosition = () => {
if (!loadedRef.current) return;
const state = listRef.current?.getState();
const position = state && resolveWorkGroupScrollAnchor(state);
@@ -628,8 +610,8 @@ function ThreadWorkGroupList(props: {
...position,
contentHeight: state.contentLength,
});
- }, [props.groupId, props.scrollPositions]);
- const finishPendingAppend = useCallback(() => {
+ };
+ const finishPendingAppend = () => {
const targetHeight = pendingAppendHeightRef.current;
const state = listRef.current?.getState();
if (
@@ -641,45 +623,42 @@ function ThreadWorkGroupList(props: {
pendingAppendHeightRef.current = null;
void listRef.current?.scrollToEnd({ animated: false });
}
- }, []);
- const onContentSizeChange = useCallback(
- (nextHeight: number) => {
- const previous = previousContent.current;
- const detailsChanged = previous.expandedRows !== props.expandedRows;
- const followAppend =
- loadedRef.current &&
- shouldFollowThreadWorkGroupAppend({
- previousRows: previous.rows,
- rows: props.activities,
- previousContentHeight: previous.height,
- contentHeight: nextHeight,
- viewportHeight: Math.min(previous.height, WORK_GROUP_MAX_HEIGHT),
- scrollOffset: scrollOffset.value,
- detailsChanged,
- userScrolling: userScrollingRef.current,
- });
- previousContent.current = {
+ };
+ const onContentSizeChange = (nextHeight: number) => {
+ const previous = previousContent.current;
+ const detailsChanged = previous.expandedRows !== props.expandedRows;
+ const followAppend =
+ loadedRef.current &&
+ shouldFollowThreadWorkGroupAppend({
+ previousRows: previous.rows,
rows: props.activities,
- height: nextHeight,
- expandedRows: props.expandedRows,
- };
- setMeasuredContent((current) =>
- current.height === nextHeight && current.rowCount === props.activities.length
- ? current
- : { height: nextHeight, rowCount: props.activities.length },
- );
- if (followAppend) {
- pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
- } else if (detailsChanged || userScrollingRef.current || previous.rows !== props.activities) {
- pendingAppendHeightRef.current = null;
- } else if (pendingAppendHeightRef.current !== null) {
- pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
- }
- finishPendingAppend();
- rememberPosition();
- },
- [props.activities, props.expandedRows, scrollOffset, finishPendingAppend, rememberPosition],
- );
+ previousContentHeight: previous.height,
+ contentHeight: nextHeight,
+ viewportHeight: Math.min(previous.height, WORK_GROUP_MAX_HEIGHT),
+ scrollOffset: scrollOffset.value,
+ detailsChanged,
+ userScrolling: userScrollingRef.current,
+ });
+ previousContent.current = {
+ rows: props.activities,
+ height: nextHeight,
+ expandedRows: props.expandedRows,
+ };
+ setMeasuredContent((current) =>
+ current.height === nextHeight && current.rowCount === props.activities.length
+ ? current
+ : { height: nextHeight, rowCount: props.activities.length },
+ );
+ if (followAppend) {
+ pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
+ } else if (detailsChanged || userScrollingRef.current || previous.rows !== props.activities) {
+ pendingAppendHeightRef.current = null;
+ } else if (pendingAppendHeightRef.current !== null) {
+ pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
+ }
+ finishPendingAppend();
+ rememberPosition();
+ };
// The native ScrollView reports its content size a frame or more after
// LegendList has laid the rows out, so a detail toggle rendered the group
// at its old height while the rows below already moved. Read the size
@@ -689,7 +668,7 @@ function ThreadWorkGroupList(props: {
useLayoutEffect(() => {
onContentSizeChangeRef.current = onContentSizeChange;
}, [onContentSizeChange]);
- const subscribeToContentSize = useCallback((list: LegendListRef | null) => {
+ const subscribeToContentSize = (list: LegendListRef | null) => {
listRef.current = list;
if (!list) return;
const unsubscribe = list.getState().listen("totalSize", () => {
@@ -697,21 +676,15 @@ function ThreadWorkGroupList(props: {
});
onContentSizeChangeRef.current(list.getState().contentLength);
return unsubscribe;
- }, []);
- const getFixedItemSize = useCallback(
- (row: ThreadFeedActivity, index: number) =>
- props.expandedRows[row.id] || props.rowSizing.fixedRowHeight === undefined
- ? undefined
- : props.rowSizing.fixedRowHeight + (index < props.activities.length - 1 ? WORK_ROW_GAP : 0),
- [props.activities.length, props.expandedRows, props.rowSizing.fixedRowHeight],
- );
- const renderItem = useCallback(
- ({ item, index }: { item: ThreadFeedActivity; index: number }) => (
- <View className={index < props.activities.length - 1 ? "pb-px" : undefined}>
- {props.renderRow(item)}
- </View>
- ),
- [props.activities.length, props.renderRow],
+ };
+ const getFixedItemSize = (row: ThreadFeedActivity, index: number) =>
+ props.expandedRows[row.id] || props.rowSizing.fixedRowHeight === undefined
+ ? undefined
+ : props.rowSizing.fixedRowHeight + (index < props.activities.length - 1 ? WORK_ROW_GAP : 0);
+ const renderItem = ({ item, index }: { item: ThreadFeedActivity; index: number }) => (
+ <View className={index < props.activities.length - 1 ? "pb-px" : undefined}>
+ {props.renderRow(item)}
+ </View>
);
return (
@@ -877,7 +850,7 @@ function ReplCodeText({
);
}
-const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
+const ThreadWorkLogRow = function ThreadWorkLogRow(
props: Omit<
ThreadWorkLogProps,
| "continuesWorkLog"
@@ -1293,7 +1266,7 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
) : null}
</Animated.View>
);
-});
+};
export function ThreadWorkGroupToggle(props: {
readonly environmentId: EnvironmentId;
@@ -1389,7 +1362,7 @@ export function ThreadWorkGroupToggle(props: {
);
}
-export const ThreadAgentSpawnCard = memo(function ThreadAgentSpawnCard(props: {
+export const ThreadAgentSpawnCard = function ThreadAgentSpawnCard(props: {
readonly summary: AgentSpawnSummary;
readonly expanded: boolean;
readonly iconSubtleColor: ColorValue;
@@ -1498,7 +1471,7 @@ export const ThreadAgentSpawnCard = memo(function ThreadAgentSpawnCard(props: {
</Pressable>
</Animated.View>
);
-});
+};
export function ThreadThinkingRow(props: {
readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts
index d320c9ce0dd..67e560b8eaa 100644
--- a/apps/mobile/src/features/threads/use-composer-command-menu.ts
+++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts
@@ -45,7 +45,7 @@ import {
resolveProviderSkillsForCwd,
resolveProviderSlashCommandsForCwd,
} from "@t3tools/client-runtime/providerSkills";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import type { ComposerEditorSelection } from "../../components/ComposerEditor";
import { serverEnvironment } from "../../state/server";
@@ -206,9 +206,9 @@ export function useComposerCommandMenu({
}) {
const [selection, setSelection] = useState(() => composerSelectionAtEnd(draftMessage));
const previousOwnerKeyRef = useRef(ownerKey);
- const onSelectionChange = useCallback((nextSelection: ComposerEditorSelection) => {
+ const onSelectionChange = (nextSelection: ComposerEditorSelection) => {
setSelection(nextSelection);
- }, []);
+ };
useEffect(() => {
const inserted = ownerKey ? readComposerDraftSelection(ownerKey, draftMessage) : null;
if (inserted) {
@@ -233,11 +233,9 @@ export function useComposerCommandMenu({
setSelection(composerSelectionAtEnd(draftMessage));
}, [draftMessage, ownerKey]);
- const skills = useMemo(
- () =>
- selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd) : [],
- [projectCwd, selectedProviderStatus],
- );
+ const skills = selectedProviderStatus
+ ? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd)
+ : [];
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
reportFailure: false,
});
@@ -334,12 +332,12 @@ export function useComposerCommandMenu({
workspaceRefreshRetry,
]);
- const trigger = useMemo(() => {
+ const trigger = (() => {
if (!enabled || selection.start !== selection.end) {
return null;
}
return detectComposerTrigger(draftMessage, selection.end);
- }, [draftMessage, enabled, selection]);
+ })();
const pathSearch = useComposerPathSearch({
environmentId,
cwd: trigger?.kind === "path" ? projectCwd : null,
@@ -353,7 +351,7 @@ export function useComposerCommandMenu({
query: trigger?.kind === "pull-request" ? trigger.query : null,
});
- const items = useMemo<ComposerCommandItem[]>(() => {
+ const items = ((): ComposerCommandItem[] => {
if (!trigger) return [];
if (trigger.kind === "pull-request") {
@@ -521,132 +519,99 @@ export function useComposerCommandMenu({
}
return [];
- }, [
- currentThreadId,
- environmentId,
- threadShells,
- hasThread,
- hasCompactableConversation,
- onUpdateInteractionMode,
- pathSearch.entries,
- pullRequestSearch.entries,
- projectCwd,
- selectedProviderStatus,
- skills,
- trigger,
- offersUsageLimits,
- ]);
+ })();
- const onSelect = useCallback(
- (item: ComposerCommandItem) => {
- if (!trigger) return;
- if (item.type === "thread") {
- if (!ownerKey || trigger.kind !== "path") return;
- const shell = threadShells.find(
- (candidate) =>
- candidate.environmentId === item.thread.environmentId &&
- candidate.id === item.thread.threadId,
- );
- if (!shell) return;
- const record = threadComposerContext(item.thread, shell.title);
- const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? [];
- const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId);
- if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) {
- Dialog.alert(
- "Too many context items",
- "Remove some context from the draft and try again.",
- );
- return;
- }
- const result = replaceTextRange(
- draftMessage,
- trigger.rangeStart,
- trigger.rangeEnd,
- `${formatComposerContextReference(record)} `,
- );
- onChangeDraftMessage(result.text);
- if (!alreadyAttached) {
- const draft = getComposerDraftSnapshot(ownerKey);
- setComposerDraftContext(ownerKey, {
- version: 1,
- records: [...(draft.context?.records ?? []), record],
- });
- }
- setSelection({ start: result.cursor, end: result.cursor });
+ const onSelect = (item: ComposerCommandItem) => {
+ if (!trigger) return;
+ if (item.type === "thread") {
+ if (!ownerKey || trigger.kind !== "path") return;
+ const shell = threadShells.find(
+ (candidate) =>
+ candidate.environmentId === item.thread.environmentId &&
+ candidate.id === item.thread.threadId,
+ );
+ if (!shell) return;
+ const record = threadComposerContext(item.thread, shell.title);
+ const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? [];
+ const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId);
+ if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) {
+ Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
return;
}
- if (item.type === "pull-request") {
- if (
- !ownerKey ||
- trigger.kind !== "pull-request" ||
- !items.some((candidate) => candidate.id === item.id)
- )
- return;
- const record = pullRequestComposerContext(item.pullRequest, uuidv4());
- if (
- (getComposerDraftSnapshot(ownerKey).context?.records.length ?? 0) >=
- COMPOSER_CONTEXT_MAX_RECORDS
- ) {
- Dialog.alert(
- "Too many context items",
- "Remove some context from the draft and try again.",
- );
- return;
- }
- const result = replaceTextRange(
- draftMessage,
- trigger.rangeStart,
- trigger.rangeEnd,
- `${formatComposerContextReference(record)} `,
- );
- onChangeDraftMessage(result.text);
+ const result = replaceTextRange(
+ draftMessage,
+ trigger.rangeStart,
+ trigger.rangeEnd,
+ `${formatComposerContextReference(record)} `,
+ );
+ onChangeDraftMessage(result.text);
+ if (!alreadyAttached) {
const draft = getComposerDraftSnapshot(ownerKey);
setComposerDraftContext(ownerKey, {
version: 1,
records: [...(draft.context?.records ?? []), record],
});
- setSelection({ start: result.cursor, end: result.cursor });
- return;
}
-
+ setSelection({ start: result.cursor, end: result.cursor });
+ return;
+ }
+ if (item.type === "pull-request") {
if (
- item.type === "provider-slash-command" &&
- item.command.name === USAGE_LIMITS_COMMAND.name &&
- onUsageLimits
+ !ownerKey ||
+ trigger.kind !== "pull-request" ||
+ !items.some((candidate) => candidate.id === item.id)
+ )
+ return;
+ const record = pullRequestComposerContext(item.pullRequest, uuidv4());
+ if (
+ (getComposerDraftSnapshot(ownerKey).context?.records.length ?? 0) >=
+ COMPOSER_CONTEXT_MAX_RECORDS
) {
- const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
- setSelection({ start: cleared.cursor, end: cleared.cursor });
- onChangeDraftMessage(cleared.text);
- onUsageLimits();
+ Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
return;
}
-
- const result = resolveComposerCommandSelection({
+ const result = replaceTextRange(
draftMessage,
- trigger,
- item,
- allowInteractionMode:
- onUpdateInteractionMode !== undefined &&
- selectedProviderStatus?.showInteractionModeToggle !== false,
+ trigger.rangeStart,
+ trigger.rangeEnd,
+ `${formatComposerContextReference(record)} `,
+ );
+ onChangeDraftMessage(result.text);
+ const draft = getComposerDraftSnapshot(ownerKey);
+ setComposerDraftContext(ownerKey, {
+ version: 1,
+ records: [...(draft.context?.records ?? []), record],
});
setSelection({ start: result.cursor, end: result.cursor });
- onChangeDraftMessage(result.text);
- if (result.interactionMode !== null) {
- onUpdateInteractionMode?.(result.interactionMode);
- }
- },
- [
+ return;
+ }
+
+ if (
+ item.type === "provider-slash-command" &&
+ item.command.name === USAGE_LIMITS_COMMAND.name &&
+ onUsageLimits
+ ) {
+ const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
+ setSelection({ start: cleared.cursor, end: cleared.cursor });
+ onChangeDraftMessage(cleared.text);
+ onUsageLimits();
+ return;
+ }
+
+ const result = resolveComposerCommandSelection({
draftMessage,
- ownerKey,
- items,
- onChangeDraftMessage,
- onUpdateInteractionMode,
- onUsageLimits,
- selectedProviderStatus?.showInteractionModeToggle,
- threadShells,
trigger,
- ],
- );
+ item,
+ allowInteractionMode:
+ onUpdateInteractionMode !== undefined &&
+ selectedProviderStatus?.showInteractionModeToggle !== false,
+ });
+ setSelection({ start: result.cursor, end: result.cursor });
+ onChangeDraftMessage(result.text);
+ if (result.interactionMode !== null) {
+ onUpdateInteractionMode?.(result.interactionMode);
+ }
+ };
return {
selection,
diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.ts
index e0a0bb12e9e..a815f82da71 100644
--- a/apps/mobile/src/reactCompilerCoverage.test.ts
+++ b/apps/mobile/src/reactCompilerCoverage.test.ts
@@ -22,27 +22,14 @@ const KNOWN_BAILOUTS: Record<string, string> = {
"src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
"src/features/home/thread-swipe-actions.tsx": "ref read during render",
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
- "src/features/threads/NewTaskContextPickerScreens.tsx":
- "manual memo not preserved, try without catch",
- "src/features/threads/NewTaskDraftScreen.tsx": "try/finally",
- "src/features/threads/NewTaskRouteScreen.tsx": "try without catch",
"src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
- "src/features/threads/QuestionAttachments.tsx": "try/finally",
"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/ThreadGitControls.tsx": "manual memo not preserved",
"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/ThreadSettingsSheet.tsx": "manual memo not preserved, try without catch",
- "src/features/threads/UsageLimitRecoveryCard.tsx": "throw inside try, try/finally",
- "src/features/threads/git/GitCommitSheet.tsx": "manual memo not preserved",
- "src/features/threads/git/GitOverviewSheet.tsx": "try without catch",
- "src/features/threads/new-task-flow-provider.tsx": "try without catch",
- "src/features/threads/thread-work-log.tsx": "manual memo not preserved",
- "src/features/threads/use-composer-command-menu.ts": "manual memo not preserved",
"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",