The best way to control Claude Code, Codex and more from any computer or phone
perf(mobile): new task flow, git sheets, thread settings and work log compile with the React Compiler (#21141)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 18, 2026 at 14:33 UTC
8528d64109b2ca9d6301e46850b244186bcdf9f0
13 files changed
+1488
-2000
apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
+71
-92
@@ -13,7 +13,7 @@ import {
13
} from "@t3tools/client-runtime/state/runtime";
14
import * as Haptics from "expo-haptics";
15
import { useNavigation } from "@react-navigation/native";
16
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
16
+import { useEffect, useRef, useState, type ReactNode } from "react";
17
import { Platform, Pressable, ScrollView, TextInput, View } from "react-native";
18
import { useSafeAreaInsets } from "react-native-safe-area-context";
19
@@ -155,7 +155,7 @@ function BranchSelectionRow(props: {
155
readonly onSelect: (branch: VcsRef) => void;
156
readonly selected: boolean;
157
}) {
158
- const onPress = useCallback(() => props.onSelect(props.branch), [props.branch, props.onSelect]);
158
+ const onPress = () => props.onSelect(props.branch);
159
160
return (
161
<View
@@ -290,67 +290,58 @@ export function NewTaskBranchPickerRouteScreen() {
290
[navigation],
291
);
292
293
- const selectBranch = useCallback(
294
- async (branch: VcsRef) => {
295
- const needsCheckout = shouldCheckoutNewTaskBranch({
296
- branchIsCurrent: branch.current,
297
- branchWorktreePath: branch.worktreePath,
298
- workspaceMode: flow.workspaceMode,
299
- });
300
- if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
301
- return;
302
- }
303
- selectingBranchNameRef.current = branch.name;
304
- void Haptics.selectionAsync();
305
-
306
- try {
307
- if (!flow.selectedProject) return;
308
- setSwitchingBranchName(branch.name);
309
- const result = await checkoutNewTaskBranch({
310
- branch,
311
- project: flow.selectedProject,
312
- workspaceMode: flow.workspaceMode,
313
- switchRef,
314
- });
315
- if (result._tag === "Failure") {
316
- if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
317
- const error = squashAtomCommandFailure(result);
318
- Dialog.alert(
319
- "Could not switch branch",
320
- error instanceof Error ? error.message : "The branch could not be checked out.",
321
- );
322
- }
323
- return;
324
- }
293
+ const selectBranch = async (branch: VcsRef) => {
294
+ const needsCheckout = shouldCheckoutNewTaskBranch({
295
+ branchIsCurrent: branch.current,
296
+ branchWorktreePath: branch.worktreePath,
297
+ workspaceMode: flow.workspaceMode,
298
+ });
299
+ if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
300
+ return;
301
+ }
302
+ selectingBranchNameRef.current = branch.name;
303
+ void Haptics.selectionAsync();
304
326
- // The checkout has already changed the repository. Persist the matching
327
- // draft selection even if the native sheet was dismissed while the
328
- // command was in flight; only visible-screen work is focus-gated below.
329
- flow.selectBranch(result.value);
330
- if (!mountedRef.current || !navigation.isFocused()) {
331
- return;
332
- }
333
- flow.setBranchQuery("");
334
- allowSelectionNavigationRef.current = true;
335
- navigation.goBack();
336
- } finally {
337
- selectingBranchNameRef.current = null;
338
- allowSelectionNavigationRef.current = false;
339
- if (mountedRef.current) {
340
- setSwitchingBranchName(null);
341
- }
342
- }
343
- },
344
- [
345
- canWriteSourceControl,
346
- flow.selectBranch,
347
- flow.selectedProject,
348
- flow.setBranchQuery,
349
- flow.workspaceMode,
350
- navigation,
305
+ const project = flow.selectedProject;
306
+ if (!project) {
307
+ selectingBranchNameRef.current = null;
308
+ return;
309
+ }
310
+ setSwitchingBranchName(branch.name);
311
+ const result = await checkoutNewTaskBranch({
312
+ branch,
313
+ project,
314
+ workspaceMode: flow.workspaceMode,
315
switchRef,
352
- ],
353
- );
316
+ });
317
+ if (mountedRef.current) setSwitchingBranchName(null);
318
+ if (result._tag === "Failure") {
319
+ selectingBranchNameRef.current = null;
320
+ if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
321
+ const error = squashAtomCommandFailure(result);
322
+ Dialog.alert(
323
+ "Could not switch branch",
324
+ error instanceof Error ? error.message : "The branch could not be checked out.",
325
+ );
326
+ }
327
+ return;
328
+ }
329
+
330
+ // The checkout has already changed the repository. Persist the matching
331
+ // draft selection even if the native sheet was dismissed while the
332
+ // command was in flight; only visible-screen work is focus-gated below.
333
+ flow.selectBranch(result.value);
334
+ if (!mountedRef.current || !navigation.isFocused()) {
335
+ selectingBranchNameRef.current = null;
336
+ return;
337
+ }
338
+ flow.setBranchQuery("");
339
+ // beforeRemove blocks dismissal while a switch is in flight; this one is ours.
340
+ allowSelectionNavigationRef.current = true;
341
+ navigation.goBack();
342
+ allowSelectionNavigationRef.current = false;
343
+ selectingBranchNameRef.current = null;
344
+ };
345
346
return (
347
<BranchPickerScreen
@@ -413,38 +404,26 @@ export function BranchPickerScreen(props: {
404
props.branches.find((branch) => branch.current)?.name ??
405
props.branches.find((branch) => branch.isDefault)?.name ??
406
null;
416
- const branchListContentStyle = useMemo(
417
- () => ({
418
- paddingBottom: usesNativeMailSearchToolbar
419
- ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
420
- : Platform.OS === "ios"
421
- ? 16
422
- : Math.max(insets.bottom, 16) + 16,
423
- paddingHorizontal: 16,
424
- paddingTop: 16,
425
- }),
426
- [insets.bottom, usesNativeMailSearchToolbar],
427
- );
407
+ const branchListContentStyle = {
408
+ paddingBottom: usesNativeMailSearchToolbar
409
+ ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
410
+ : Platform.OS === "ios"
411
+ ? 16
412
+ : Math.max(insets.bottom, 16) + 16,
413
+ paddingHorizontal: 16,
414
+ paddingTop: 16,
415
+ };
416
429
- const renderBranch = useCallback(
430
- ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
431
- <BranchSelectionRow
432
- badge={branchBadgeLabel({ branch: item, project: props.project })}
433
- branch={item}
434
- disabled={props.selectionDisabled ?? false}
435
- isFirst={index === 0}
436
- isLast={index === props.branches.length - 1}
437
- onSelect={props.onSelect}
438
- selected={selectedBranchName === item.name}
439
- />
440
- ),
441
- [
442
- props.branches.length,
443
- props.project,
444
- props.onSelect,
445
- selectedBranchName,
446
- props.selectionDisabled,
447
- ],
417
+ const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
418
+ <BranchSelectionRow
419
+ badge={branchBadgeLabel({ branch: item, project: props.project })}
420
+ branch={item}
421
+ disabled={props.selectionDisabled ?? false}
422
+ isFirst={index === 0}
423
+ isLast={index === props.branches.length - 1}
424
+ onSelect={props.onSelect}
425
+ selected={selectedBranchName === item.name}
426
+ />
427
);
428
429
const branchListHeader = props.worktree ? (
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+148
-168
@@ -3,6 +3,7 @@ import * as Dialog from "../../components/ui/Dialog";
3
import { useAtomValue } from "@effect/atom-react";
4
import * as Cause from "effect/Cause";
5
import { AsyncResult } from "effect/reactivity";
6
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
7
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
8
import {
9
nextPastedTextFileName,
@@ -18,7 +19,7 @@ import {
19
usePreventRemove,
20
type NavigationAction,
21
} from "@react-navigation/native";
21
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
22
+import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
23
import { Platform, Pressable, ScrollView, View } from "react-native";
24
import {
25
KeyboardController,
@@ -211,7 +212,7 @@ export function NewTaskDraftScreen(props: {
212
const controlsBottomPadding = Math.max(insets.bottom, 10);
213
const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);
214
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
214
- const selectedProjectLabel = useMemo(() => {
215
+ const selectedProjectLabel = (() => {
216
if (!selectedProject) return null;
217
const scope = projectScopes.find((candidate) =>
218
candidate.projectRefs.some(
@@ -221,7 +222,7 @@ export function NewTaskDraftScreen(props: {
222
),
223
);
224
return scope?.title ?? selectedProject.title;
224
- }, [projectScopes, selectedProject]);
225
+ })();
226
const { connectedEnvironments } = useRemoteConnectionStatus();
227
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
228
selectedProject?.environmentId ?? null,
@@ -319,23 +320,17 @@ export function NewTaskDraftScreen(props: {
320
const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
321
const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
322
const wasFocusedBeforePreviewRef = useRef(false);
322
- const openVideoPreview = useCallback(
323
- (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
324
- wasFocusedBeforePreviewRef.current = isComposerFocused;
325
- setPreviewFile(null);
326
- setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
327
- },
328
- [isComposerFocused],
329
- );
330
- const openFilePreview = useCallback(
331
- (source: FilePreviewSource) => {
332
- wasFocusedBeforePreviewRef.current = isComposerFocused;
333
- setPreviewVideo(null);
334
- setPreviewFile((current) => current ?? source);
335
- },
336
- [isComposerFocused],
337
- );
338
- const closeMediaPreview = useCallback(() => {
323
+ const openVideoPreview = (attachment: DraftComposerFileAttachment, sourceIdentifier: string) => {
324
+ wasFocusedBeforePreviewRef.current = isComposerFocused;
325
+ setPreviewFile(null);
326
+ setPreviewVideo((current) => current ?? { type: "local", attachment, sourceIdentifier });
327
+ };
328
+ const openFilePreview = (source: FilePreviewSource) => {
329
+ wasFocusedBeforePreviewRef.current = isComposerFocused;
330
+ setPreviewVideo(null);
331
+ setPreviewFile((current) => current ?? source);
332
+ };
333
+ const closeMediaPreview = () => {
334
setPreviewVideo(null);
335
setPreviewFile(null);
336
if (wasFocusedBeforePreviewRef.current) {
@@ -343,7 +338,7 @@ export function NewTaskDraftScreen(props: {
338
if (navigation.isFocused()) promptInputRef.current?.focus();
339
}, 100);
340
}
346
- }, [navigation]);
341
+ };
342
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
343
editorRef: promptInputRef,
344
isEditorFocused: isComposerFocused,
@@ -371,16 +366,14 @@ export function NewTaskDraftScreen(props: {
366
settingsRoutePresentedRef.current = true;
367
navigation.dispatch(StackActions.push("ThreadSettings"));
368
}, [navigation, settingsSheetPresentation.isVisible]);
374
- useFocusEffect(
375
- useCallback(() => {
376
- if (!settingsRoutePresentedRef.current) {
377
- return;
378
- }
369
+ useFocusEffect(() => {
370
+ if (!settingsRoutePresentedRef.current) {
371
+ return;
372
+ }
373
380
- settingsRoutePresentedRef.current = false;
381
- settingsSheetPresentation.onDismissed();
382
- }, [settingsSheetPresentation.onDismissed]),
383
- );
374
+ settingsRoutePresentedRef.current = false;
375
+ settingsSheetPresentation.onDismissed();
376
+ });
377
useEffect(
378
() =>
379
// UIKit's completion callback for the sheet dismissal, surfaced by the
@@ -410,17 +403,25 @@ export function NewTaskDraftScreen(props: {
403
draftKey: null,
404
names: new Set(),
405
});
406
+ // The share import resumes after awaits; this reads the screen's current
407
+ // draft and share at that point without re-running the import effect.
408
+ const isCurrentShareImport = useEffectEvent(
409
+ (draftKey: string, shareId: string) =>
410
+ flow.draftKey === draftKey && props.incomingShareId === shareId,
411
+ );
412
+ // Pasted-text attachments finish in an event handler, where an effect event
413
+ // cannot be called and the provider's draft key has no store to read.
414
const latestDraftKeyRef = useRef(flow.draftKey);
414
- const latestIncomingShareIdRef = useRef(props.incomingShareId);
415
- latestDraftKeyRef.current = flow.draftKey;
416
- latestIncomingShareIdRef.current = props.incomingShareId;
415
+ useLayoutEffect(() => {
416
+ latestDraftKeyRef.current = flow.draftKey;
417
+ });
418
const isImportingShare = importingShareKey !== null;
419
const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
420
// The share this screen already moved into its draft. Sending clears the
421
// draft (and its importedShareIds receipt) a frame before the screen leaves,
422
// and the inbox entry is long gone by then; without this the re-render in
423
// between reads as "shared content vanished" and alerts on every send.
423
- const consumedIncomingShareIdRef = useRef<string | null>(null);
424
+ const [consumedIncomingShareId, setConsumedIncomingShareId] = useState<string | null>(null);
425
const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
426
const requestedInitialProjectAvailable = Boolean(
427
props.initialProjectRef?.environmentId &&
@@ -447,22 +448,13 @@ export function NewTaskDraftScreen(props: {
448
const isComposerInteractionLocked =
449
isIncomingShareTransferPending || flow.submitting || isImportingContext;
450
const { environments, selectedEnvironmentId, switchEnvironment, switchingToEnvironmentId } = flow;
450
- const cycleEnvironment = useCallback(() => {
451
+ const cycleEnvironment = () => {
452
if (isComposerInteractionLocked) return true;
453
const next = nextEnvironmentId(environments, switchingToEnvironmentId ?? selectedEnvironmentId);
454
if (next !== null) void switchEnvironment(next);
455
return true;
455
- }, [
456
- environments,
457
- isComposerInteractionLocked,
458
- selectedEnvironmentId,
459
- switchEnvironment,
460
- switchingToEnvironmentId,
461
- ]);
462
- const cycleEnvironmentCommands = useMemo(
463
- () => (environments.length > 1 ? (["cycleHost"] as const) : []),
464
- [environments.length],
465
- );
456
+ };
457
+ const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : [];
458
useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);
459
const offersUsageLimits =
460
flow.selectedProviderStatus !== null &&
@@ -475,10 +467,7 @@ export function NewTaskDraftScreen(props: {
467
(flow.workspaceMode === "worktree"
468
? selectedProject?.workspaceRoot
469
: (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
478
- const stripAttachments = useMemo(
479
- () => composerStripAttachments(flow.attachments),
480
- [flow.attachments],
481
- );
470
+ const stripAttachments = composerStripAttachments(flow.attachments);
471
const composerMenu = useComposerCommandMenu({
472
draftMessage: flow.prompt,
473
ownerKey: flow.draftKey,
@@ -529,7 +518,7 @@ export function NewTaskDraftScreen(props: {
518
}, [navigation, preventRemove, submitNavigationAction]);
519
const hasImportedIncomingShare = Boolean(
520
props.incomingShareId &&
532
- (consumedIncomingShareIdRef.current === props.incomingShareId ||
521
+ (consumedIncomingShareId === props.incomingShareId ||
522
(flow.draftKey &&
523
getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId))),
524
);
@@ -812,8 +801,7 @@ export function NewTaskDraftScreen(props: {
801
if (
802
!shareImportMountedRef.current ||
803
activeShareImportTokenRef.current !== importToken ||
815
- latestDraftKeyRef.current !== draftKey ||
816
- latestIncomingShareIdRef.current !== shareId
804
+ !isCurrentShareImport(draftKey, shareId)
805
) {
806
return;
807
}
@@ -835,8 +823,7 @@ export function NewTaskDraftScreen(props: {
823
if (
824
!shareImportMountedRef.current ||
825
activeShareImportTokenRef.current !== importToken ||
838
- latestDraftKeyRef.current !== draftKey ||
839
- latestIncomingShareIdRef.current !== shareId
826
+ !isCurrentShareImport(draftKey, shareId)
827
) {
828
// The durable reservation makes an interrupted transfer resume only
829
// in this project instead of copying into a second project draft.
@@ -844,7 +831,7 @@ export function NewTaskDraftScreen(props: {
831
}
832
await consumeShare(shareId);
833
didConsumeShare = true;
847
- consumedIncomingShareIdRef.current = shareId;
834
+ setConsumedIncomingShareId(shareId);
835
// The consumed inbox draft was the last owner of files that never made
836
// it into the composer draft (unsupported server, oversize, limit
837
// skips). Release them before any early return: an unmount or a
@@ -1067,124 +1054,118 @@ export function NewTaskDraftScreen(props: {
1054
}
1055
}
1056
1070
- const handleNativePasteImages = useCallback(
1071
- async (uris: ReadonlyArray<string>) => {
1072
- try {
1073
- const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
1074
- const images = await convertPastedImagesToAttachments({
1075
- uris,
1076
- existingCount:
1077
- flow.draftKey && insertion
1078
- ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
1079
- : flow.attachments.length,
1080
- });
1081
- if (images.length > 0) {
1082
- flow.appendAttachments(images, insertion);
1083
- }
1084
- } catch (error) {
1085
- console.error("[native paste] error converting images", error);
1086
- }
1087
- },
1088
- [flow],
1089
- );
1057
+ const handleNativePasteImages = async (uris: ReadonlyArray<string>) => {
1058
+ const insertion = flow.draftKey ? captureComposerDraftInsertion(flow.draftKey) : undefined;
1059
+ const existingCount =
1060
+ flow.draftKey && insertion
1061
+ ? countComposerDraftAttachmentsAfterSelection(flow.draftKey, insertion)
1062
+ : flow.attachments.length;
1063
+ const converted = await settlePromise(() =>
1064
+ convertPastedImagesToAttachments({ uris, existingCount }),
1065
+ );
1066
+ if (AsyncResult.isFailure(converted)) {
1067
+ console.error("[native paste] error converting images", squashAtomCommandFailure(converted));
1068
+ return;
1069
+ }
1070
+ if (converted.value.length > 0) flow.appendAttachments(converted.value, insertion);
1071
+ };
1072
1091
- const handleNativePasteText = useCallback(
1092
- async (paste: ComposerTextPaste) => {
1093
- const draftKey = flow.draftKey;
1094
- if (!draftKey) return;
1095
- const insertion = { text: paste.value, ...paste.selection };
1096
- const insertPaste = () => {
1097
- const insertion = replaceTextSelection({
1098
- value: paste.value,
1099
- selection: paste.selection,
1100
- text: paste.text,
1101
- });
1102
- const selection = { start: insertion.cursor, end: insertion.cursor };
1103
- flow.setPrompt(insertion.value);
1104
- composerMenu.onSelectionChange(selection);
1105
- };
1106
- const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;
1107
- const advertisedMax =
1108
- capabilities?.attachmentUploads === true
1109
- ? capabilities.fileAttachments?.maxUploadBytes
1110
- : undefined;
1111
- const maxBytes =
1112
- advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
1113
- const wouldExceedInputLimit =
1114
- paste.value.length -
1115
- Math.max(0, paste.selection.end - paste.selection.start) +
1116
- paste.text.length >
1117
- PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
1118
- const canAttach =
1119
- maxBytes !== null &&
1120
- countComposerDraftAttachmentsAfterSelection(draftKey, insertion) <
1121
- PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
1122
- new TextEncoder().encode(paste.text).byteLength <= maxBytes;
1123
- if (
1124
- pastedTextDisposition({
1125
- text: paste.text,
1126
- wouldExceedInputLimit,
1127
- canAttach: true,
1128
- }) === "attachment"
1129
- ) {
1130
- if (canAttach && maxBytes !== null) {
1131
- pendingPastedTextAttachmentCountRef.current += 1;
1132
- setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
1133
- try {
1134
- if (pastedTextFileNamesRef.current.draftKey !== draftKey) {
1135
- pastedTextFileNamesRef.current = { draftKey, names: new Set() };
1136
- }
1137
- const reservedNames = pastedTextFileNamesRef.current.names;
1138
- for (const attachment of flow.attachments) reservedNames.add(attachment.name);
1139
- const name = nextPastedTextFileName([...reservedNames]);
1140
- reservedNames.add(name);
1141
- const attachment = await createPastedTextComposerAttachment({
1142
- text: paste.text,
1143
- name,
1144
- maxBytes,
1145
- });
1146
- if (latestDraftKeyRef.current !== draftKey) {
1147
- await removePersistedComposerAttachmentFile(attachment.fileUri);
1148
- return;
1149
- }
1150
- if (flow.appendAttachments([attachment], insertion) > 0) {
1151
- await removePersistedComposerAttachmentFile(attachment.fileUri);
1152
- Dialog.alert(
1153
- "Could not attach pasted text",
1154
- `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
1155
- );
1156
- }
1157
- } catch (error) {
1073
+ const handleNativePasteText = async (paste: ComposerTextPaste) => {
1074
+ const draftKey = flow.draftKey;
1075
+ if (!draftKey) return;
1076
+ const insertion = { text: paste.value, ...paste.selection };
1077
+ const insertPaste = () => {
1078
+ const insertion = replaceTextSelection({
1079
+ value: paste.value,
1080
+ selection: paste.selection,
1081
+ text: paste.text,
1082
+ });
1083
+ const selection = { start: insertion.cursor, end: insertion.cursor };
1084
+ flow.setPrompt(insertion.value);
1085
+ composerMenu.onSelectionChange(selection);
1086
+ };
1087
+ const capabilities = selectedEnvironmentServerConfig?.environment.capabilities;
1088
+ const advertisedMax =
1089
+ capabilities?.attachmentUploads === true
1090
+ ? capabilities.fileAttachments?.maxUploadBytes
1091
+ : undefined;
1092
+ const maxBytes =
1093
+ advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
1094
+ const wouldExceedInputLimit =
1095
+ paste.value.length -
1096
+ Math.max(0, paste.selection.end - paste.selection.start) +
1097
+ paste.text.length >
1098
+ PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
1099
+ const canAttach =
1100
+ maxBytes !== null &&
1101
+ countComposerDraftAttachmentsAfterSelection(draftKey, insertion) <
1102
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
1103
+ new TextEncoder().encode(paste.text).byteLength <= maxBytes;
1104
+ if (
1105
+ pastedTextDisposition({
1106
+ text: paste.text,
1107
+ wouldExceedInputLimit,
1108
+ canAttach: true,
1109
+ }) === "attachment"
1110
+ ) {
1111
+ if (canAttach && maxBytes !== null) {
1112
+ pendingPastedTextAttachmentCountRef.current += 1;
1113
+ setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
1114
+ const attached = await settlePromise(async () => {
1115
+ if (pastedTextFileNamesRef.current.draftKey !== draftKey) {
1116
+ pastedTextFileNamesRef.current = { draftKey, names: new Set() };
1117
+ }
1118
+ const reservedNames = pastedTextFileNamesRef.current.names;
1119
+ for (const attachment of flow.attachments) reservedNames.add(attachment.name);
1120
+ const name = nextPastedTextFileName([...reservedNames]);
1121
+ reservedNames.add(name);
1122
+ const attachment = await createPastedTextComposerAttachment({
1123
+ text: paste.text,
1124
+ name,
1125
+ maxBytes,
1126
+ });
1127
+ if (latestDraftKeyRef.current !== draftKey) {
1128
+ await removePersistedComposerAttachmentFile(attachment.fileUri);
1129
+ return;
1130
+ }
1131
+ if (flow.appendAttachments([attachment], insertion) > 0) {
1132
+ await removePersistedComposerAttachmentFile(attachment.fileUri);
1133
Dialog.alert(
1134
"Could not attach pasted text",
1160
- error instanceof Error ? error.message : "Try again.",
1161
- );
1162
- } finally {
1163
- pendingPastedTextAttachmentCountRef.current = Math.max(
1164
- 0,
1165
- pendingPastedTextAttachmentCountRef.current - 1,
1135
+ `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
1136
);
1167
- setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
1137
}
1169
- } else if (!wouldExceedInputLimit) {
1170
- insertPaste();
1171
- } else {
1138
+ });
1139
+ pendingPastedTextAttachmentCountRef.current = Math.max(
1140
+ 0,
1141
+ pendingPastedTextAttachmentCountRef.current - 1,
1142
+ );
1143
+ setPendingPastedTextAttachmentCount(pendingPastedTextAttachmentCountRef.current);
1144
+ if (AsyncResult.isFailure(attached)) {
1145
+ const error = squashAtomCommandFailure(attached);
1146
Dialog.alert(
1173
- wouldExceedInputLimit
1174
- ? "Pasted text is too large for this message"
1175
- : "Could not attach pasted text",
1176
- wouldExceedInputLimit
1177
- ? "Remove some text or an attachment, then paste again."
1178
- : "Remove an attachment or use a smaller paste, then try again.",
1147
+ "Could not attach pasted text",
1148
+ error instanceof Error ? error.message : "Try again.",
1149
);
1150
}
1151
return;
1152
+ } else if (!wouldExceedInputLimit) {
1153
+ insertPaste();
1154
+ } else {
1155
+ Dialog.alert(
1156
+ wouldExceedInputLimit
1157
+ ? "Pasted text is too large for this message"
1158
+ : "Could not attach pasted text",
1159
+ wouldExceedInputLimit
1160
+ ? "Remove some text or an attachment, then paste again."
1161
+ : "Remove an attachment or use a smaller paste, then try again.",
1162
+ );
1163
}
1164
+ return;
1165
+ }
1166
1184
- insertPaste();
1185
- },
1186
- [composerMenu, flow, selectedEnvironmentServerConfig],
1187
- );
1167
+ insertPaste();
1168
+ };
1169
1170
async function handleStart(): Promise<void> {
1171
if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
@@ -1300,16 +1281,15 @@ export function NewTaskDraftScreen(props: {
1281
// Persist before clearing the draft or leaving its editor. This only waits
1282
// for the local outbox write; server and worktree setup run on the thread.
1283
flow.setSubmitting(true);
1303
- try {
1304
- await enqueueThreadOutboxMessage(message);
1305
- } catch (error) {
1284
+ const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
1285
+ flow.setSubmitting(false);
1286
+ if (AsyncResult.isFailure(queued)) {
1287
+ const error = squashAtomCommandFailure(queued);
1288
Dialog.alert(
1289
"Could not queue task",
1290
error instanceof Error ? error.message : "The task could not be saved to the outbox.",
1291
);
1292
return;
1311
- } finally {
1312
- flow.setSubmitting(false);
1293
}
1294
const draftSnapshot = getComposerDraftSnapshot(draftKey);
1295
if (editingPendingTask) {
apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+15
-16
@@ -237,24 +237,23 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
237
if (!scratchEnvironment || scratchStartInFlightRef.current) return;
238
const environmentId = scratchEnvironment.environmentId;
239
scratchStartInFlightRef.current = true;
240
- try {
241
- const result = await openScratch({ environmentId, input: {} });
242
- if (result._tag === "Failure") {
243
- if (!isAtomCommandInterrupted(result)) {
244
- const error = squashAtomCommandFailure(result);
245
- Dialog.alert(
246
- "Could not start without a project",
247
- error instanceof Error
248
- ? error.message
249
- : "The folder for threads without a project could not be created.",
250
- );
251
- }
252
- return;
253
- }
254
- await selectProject(result.value);
255
- } finally {
240
+ const result = await openScratch({ environmentId, input: {} });
241
+ if (result._tag === "Failure") {
242
scratchStartInFlightRef.current = false;
243
+ if (!isAtomCommandInterrupted(result)) {
244
+ const error = squashAtomCommandFailure(result);
245
+ Dialog.alert(
246
+ "Could not start without a project",
247
+ error instanceof Error
248
+ ? error.message
249
+ : "The folder for threads without a project could not be created.",
250
+ );
251
+ }
252
+ return;
253
}
254
+ // selectProject handles its own failures, so this never throws.
255
+ await selectProject(result.value);
256
+ scratchStartInFlightRef.current = false;
257
}
258
259
useEffect(() => {
apps/mobile/src/features/threads/QuestionAttachments.tsx
+7
-4
@@ -1,3 +1,5 @@
1
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2
+import { AsyncResult } from "effect/reactivity";
3
import * as Dialog from "../../components/ui/Dialog";
4
import { TextInputWrapper } from "expo-paste-input";
5
import { AppTextInput as TextInput } from "../../components/ui/AppText";
@@ -134,7 +136,7 @@ export function QuestionAttachments(props: {
136
const pick = async (kind: "media" | "files") => {
137
const scope = pickerScope.current;
138
changeQuestionAttachmentPreparation(key, 1);
137
- try {
139
+ const picked = await settlePromise(async () => {
140
const existingCount = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0;
141
const result =
142
kind === "files"
@@ -158,10 +160,11 @@ export function QuestionAttachments(props: {
160
const rejected = append(key, picked);
161
if (result.error || rejected > 0)
162
Dialog.alert("Could not attach file", result.error ?? "Too many attachments.");
161
- } catch (error) {
163
+ });
164
+ changeQuestionAttachmentPreparation(key, -1);
165
+ if (AsyncResult.isFailure(picked)) {
166
+ const error = squashAtomCommandFailure(picked);
167
Dialog.alert("Could not attach file", error instanceof Error ? error.message : "Try again.");
163
- } finally {
164
- changeQuestionAttachmentPreparation(key, -1);
168
}
169
};
170
return (
apps/mobile/src/features/threads/ThreadGitControls.tsx
+169
-213
@@ -18,7 +18,6 @@ import {
18
} from "@t3tools/client-runtime/state/vcs";
19
import { useNavigation } from "@react-navigation/native";
20
21
-import { useCallback, useMemo } from "react";
21
import { useEnvironmentScope } from "../../state/session";
22
import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
23
import {
@@ -130,7 +129,7 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
129
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
130
const isDefaultRef = gitStatus?.isDefaultRef ?? false;
131
133
- const quickAction = useMemo(() => {
132
+ const quickAction = (() => {
133
if (!isRepo) {
134
return {
135
label: "Git unavailable",
@@ -147,7 +146,7 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
146
hint: "This connection cannot change source control.",
147
}
148
: action;
150
- }, [busy, canWriteSourceControl, gitStatus, hasPrimaryRemote, isDefaultRef, isRepo]);
149
+ })();
150
151
const quickActionHint = quickAction.disabled
152
? (quickAction.hint ?? "This action is unavailable.")
@@ -164,7 +163,7 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
163
return "arrow.up.right.circle";
164
})();
165
167
- const openExistingPr = useCallback(async () => {
166
+ const openExistingPr = async () => {
167
const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
168
if (!prUrl) {
169
Dialog.alert("No open PR", "This branch does not have an open pull request.");
@@ -173,51 +172,38 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
172
if (!(await openPullRequest(prUrl))) {
173
Dialog.alert("Unable to open PR", "The pull request could not be opened.");
174
}
176
- }, [gitStatus, openPullRequest]);
177
-
178
- const runActionWithPrompt = useCallback(
179
- async (input: GitActionRequestInput) => {
180
- if (!canWriteSourceControl) return;
181
- const confirmableAction =
182
- input.action === "push" ||
183
- input.action === "create_pr" ||
184
- input.action === "commit_push" ||
185
- input.action === "commit_push_pr"
186
- ? input.action
187
- : null;
188
- const branchName = gitStatus?.refName;
189
- if (
190
- branchName &&
191
- confirmableAction &&
192
- !input.featureBranch &&
193
- requiresDefaultBranchConfirmation(input.action, isDefaultRef)
194
- ) {
195
- navigation.navigate("GitConfirm", {
196
- environmentId: String(environmentId),
197
- threadId: String(threadId),
198
- confirmAction: confirmableAction,
199
- branchName,
200
- includesCommit: String(
201
- input.action === "commit_push" || input.action === "commit_push_pr",
202
- ),
203
- });
204
- return;
205
- }
206
-
207
- await onRunAction(input);
208
- },
209
- [
210
- canWriteSourceControl,
211
- environmentId,
212
- gitStatus,
213
- isDefaultRef,
214
- onRunAction,
215
- navigation,
216
- threadId,
217
- ],
218
- );
175
+ };
176
+
177
+ const runActionWithPrompt = async (input: GitActionRequestInput) => {
178
+ if (!canWriteSourceControl) return;
179
+ const confirmableAction =
180
+ input.action === "push" ||
181
+ input.action === "create_pr" ||
182
+ input.action === "commit_push" ||
183
+ input.action === "commit_push_pr"
184
+ ? input.action
185
+ : null;
186
+ const branchName = gitStatus?.refName;
187
+ if (
188
+ branchName &&
189
+ confirmableAction &&
190
+ !input.featureBranch &&
191
+ requiresDefaultBranchConfirmation(input.action, isDefaultRef)
192
+ ) {
193
+ navigation.navigate("GitConfirm", {
194
+ environmentId: String(environmentId),
195
+ threadId: String(threadId),
196
+ confirmAction: confirmableAction,
197
+ branchName,
198
+ includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"),
199
+ });
200
+ return;
201
+ }
202
+
203
+ await onRunAction(input);
204
+ };
205
220
- const runQuickAction = useCallback(async () => {
206
+ const runQuickAction = async () => {
207
if (quickAction.disabled) return;
208
if (quickAction.kind === "open_pr") {
209
await openExistingPr();
@@ -230,9 +216,9 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
216
if (quickAction.kind === "run_action" && quickAction.action) {
217
await runActionWithPrompt({ action: quickAction.action });
218
}
233
- }, [onPull, openExistingPr, quickAction, runActionWithPrompt]);
219
+ };
220
235
- const openFiles = useCallback(() => {
221
+ const openFiles = () => {
222
if (props.onOpenFilesInspector) {
223
props.onOpenFilesInspector();
224
return;
@@ -241,16 +227,16 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
227
environmentId: String(environmentId),
228
threadId: String(threadId),
229
});
244
- }, [environmentId, props.onOpenFilesInspector, navigation, threadId]);
230
+ };
231
246
- const openReview = useCallback(() => {
232
+ const openReview = () => {
233
navigation.navigate("ThreadReview", {
234
environmentId: EnvironmentId.make(String(environmentId)),
235
threadId: ThreadId.make(String(threadId)),
236
});
251
- }, [environmentId, navigation, threadId]);
237
+ };
238
253
- const openGitInspector = useCallback(() => {
239
+ const openGitInspector = () => {
240
if (props.onOpenGitInspector) {
241
props.onOpenGitInspector();
242
return;
@@ -259,7 +245,7 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
245
environmentId: String(environmentId),
246
threadId: String(threadId),
247
});
262
- }, [environmentId, props.onOpenGitInspector, navigation, threadId]);
248
+ };
249
250
return {
251
currentBranchLabel,
@@ -277,176 +263,146 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) {
263
function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGitHeaderActionItems {
264
const model = useThreadGitControlModel(props);
265
280
- return useMemo(
281
- () => ({
282
- terminal: {
283
- accessibilityLabel: "Open terminal",
284
- disabled: !props.canOpenTerminal,
285
- icon: { name: "terminal", type: "sfSymbol" },
286
- identifier: "thread-right-terminal",
287
- label: "Terminal",
288
- menu: {
289
- items: [
290
- ...props.projectScripts.map((script) => ({
291
- description: script.command,
292
- disabled: !props.canOperateTerminal,
293
- icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const },
294
- label: projectScriptMenuLabel(script),
295
- onPress: () => void props.onRunProjectScript(script),
296
- type: "action" as const,
297
- })),
298
- ...(props.projectScripts.length === 0
299
- ? [
300
- {
301
- description: "This project has no saved scripts yet",
302
- disabled: true,
303
- icon: { name: "play", type: "sfSymbol" as const },
304
- label: "No project scripts",
305
- onPress: () => {},
306
- type: "action" as const,
307
- },
308
- ]
309
- : []),
310
- ...props.terminalSessions.map((session) => ({
311
- description: [
312
- getTerminalStatusLabel({
313
- status: session.status,
314
- hasRunningSubprocess: session.hasRunningSubprocess,
315
- }),
316
- basename(session.cwd),
266
+ return {
267
+ terminal: {
268
+ accessibilityLabel: "Open terminal",
269
+ disabled: !props.canOpenTerminal,
270
+ icon: { name: "terminal", type: "sfSymbol" },
271
+ identifier: "thread-right-terminal",
272
+ label: "Terminal",
273
+ menu: {
274
+ items: [
275
+ ...props.projectScripts.map((script) => ({
276
+ description: script.command,
277
+ disabled: !props.canOperateTerminal,
278
+ icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const },
279
+ label: projectScriptMenuLabel(script),
280
+ onPress: () => void props.onRunProjectScript(script),
281
+ type: "action" as const,
282
+ })),
283
+ ...(props.projectScripts.length === 0
284
+ ? [
285
+ {
286
+ description: "This project has no saved scripts yet",
287
+ disabled: true,
288
+ icon: { name: "play", type: "sfSymbol" as const },
289
+ label: "No project scripts",
290
+ onPress: () => {},
291
+ type: "action" as const,
292
+ },
293
]
318
- .filter(Boolean)
319
- .join(" · "),
320
- icon: { name: "terminal", type: "sfSymbol" as const },
321
- label: session.displayLabel,
322
- onPress: () => props.onOpenTerminal(session.terminalId),
323
- type: "action" as const,
324
- })),
325
- {
326
- description: "Start another shell for this thread",
327
- disabled: !props.canOperateTerminal,
328
- icon: { name: "plus", type: "sfSymbol" },
329
- label: "Open new terminal",
330
- onPress: props.onOpenNewTerminal,
331
- type: "action",
332
- },
333
- ],
334
- title: "Terminal",
335
- },
336
- sharesBackground: true,
337
- type: "menu",
338
- variant: "plain",
339
- },
340
- files: {
341
- accessibilityLabel: "Open files",
342
- disabled: !props.canOpenFiles,
343
- icon: { name: "folder", type: "sfSymbol" },
344
- identifier: "thread-right-files",
345
- label: "Files",
346
- onPress: model.openFiles,
347
- sharesBackground: true,
348
- type: "button",
349
- variant: "plain",
294
+ : []),
295
+ ...props.terminalSessions.map((session) => ({
296
+ description: [
297
+ getTerminalStatusLabel({
298
+ status: session.status,
299
+ hasRunningSubprocess: session.hasRunningSubprocess,
300
+ }),
301
+ basename(session.cwd),
302
+ ]
303
+ .filter(Boolean)
304
+ .join(" · "),
305
+ icon: { name: "terminal", type: "sfSymbol" as const },
306
+ label: session.displayLabel,
307
+ onPress: () => props.onOpenTerminal(session.terminalId),
308
+ type: "action" as const,
309
+ })),
310
+ {
311
+ description: "Start another shell for this thread",
312
+ disabled: !props.canOperateTerminal,
313
+ icon: { name: "plus", type: "sfSymbol" },
314
+ label: "Open new terminal",
315
+ onPress: props.onOpenNewTerminal,
316
+ type: "action",
317
+ },
318
+ ],
319
+ title: "Terminal",
320
},
351
- git: {
352
- accessibilityLabel: "Git actions",
353
- icon: { name: "point.topleft.down.curvedto.point.bottomright.up", type: "sfSymbol" },
354
- identifier: "thread-right-git",
355
- label: "Git",
356
- menu: {
357
- items: [
358
- {
359
- description: compactMenuStatus(props.gitStatus),
360
- disabled: true,
361
- icon: {
362
- name: "point.topleft.down.curvedto.point.bottomright.up",
363
- type: "sfSymbol",
364
- },
365
- label: compactMenuBranchLabel(model.currentBranchLabel),
366
- onPress: (): void => {},
367
- type: "action",
368
- },
369
- {
370
- description: model.quickActionHint ?? undefined,
371
- disabled: model.quickAction.disabled,
372
- icon: { name: model.quickActionIcon, type: "sfSymbol" },
373
- label: model.quickAction.label,
374
- onPress: (): void => void model.runQuickAction(),
375
- type: "action",
376
- },
377
- {
378
- description: "Turn diffs and worktree changes",
379
- disabled: !model.isRepo,
380
- icon: { name: "text.bubble", type: "sfSymbol" },
381
- label: "Review changes",
382
- onPress: model.openReview,
383
- type: "action",
384
- },
385
- ...(props.onMergeBack
386
- ? [
387
- {
388
- description: "Bring this thread's latest turn into its source",
389
- icon: { name: PullRequestGlyph.merged, type: "sfSymbol" as const },
390
- label: "Merge back to source",
391
- onPress: props.onMergeBack,
392
- type: "action" as const,
393
- },
394
- ]
395
- : []),
396
- {
397
- description: "Commit, files, branches",
398
- icon: { name: "ellipsis", type: "sfSymbol" },
399
- label: "More",
400
- onPress: model.openGitInspector,
401
- type: "action",
321
+ sharesBackground: true,
322
+ type: "menu",
323
+ variant: "plain",
324
+ },
325
+ files: {
326
+ accessibilityLabel: "Open files",
327
+ disabled: !props.canOpenFiles,
328
+ icon: { name: "folder", type: "sfSymbol" },
329
+ identifier: "thread-right-files",
330
+ label: "Files",
331
+ onPress: model.openFiles,
332
+ sharesBackground: true,
333
+ type: "button",
334
+ variant: "plain",
335
+ },
336
+ git: {
337
+ accessibilityLabel: "Git actions",
338
+ icon: { name: "point.topleft.down.curvedto.point.bottomright.up", type: "sfSymbol" },
339
+ identifier: "thread-right-git",
340
+ label: "Git",
341
+ menu: {
342
+ items: [
343
+ {
344
+ description: compactMenuStatus(props.gitStatus),
345
+ disabled: true,
346
+ icon: {
347
+ name: "point.topleft.down.curvedto.point.bottomright.up",
348
+ type: "sfSymbol",
349
},
403
- ],
404
- title: "Git",
405
- },
406
- sharesBackground: true,
407
- type: "menu",
408
- variant: "plain",
350
+ label: compactMenuBranchLabel(model.currentBranchLabel),
351
+ onPress: (): void => {},
352
+ type: "action",
353
+ },
354
+ {
355
+ description: model.quickActionHint ?? undefined,
356
+ disabled: model.quickAction.disabled,
357
+ icon: { name: model.quickActionIcon, type: "sfSymbol" },
358
+ label: model.quickAction.label,
359
+ onPress: (): void => void model.runQuickAction(),
360
+ type: "action",
361
+ },
362
+ {
363
+ description: "Turn diffs and worktree changes",
364
+ disabled: !model.isRepo,
365
+ icon: { name: "text.bubble", type: "sfSymbol" },
366
+ label: "Review changes",
367
+ onPress: model.openReview,
368
+ type: "action",
369
+ },
370
+ ...(props.onMergeBack
371
+ ? [
372
+ {
373
+ description: "Bring this thread's latest turn into its source",
374
+ icon: { name: PullRequestGlyph.merged, type: "sfSymbol" as const },
375
+ label: "Merge back to source",
376
+ onPress: props.onMergeBack,
377
+ type: "action" as const,
378
+ },
379
+ ]
380
+ : []),
381
+ {
382
+ description: "Commit, files, branches",
383
+ icon: { name: "ellipsis", type: "sfSymbol" },
384
+ label: "More",
385
+ onPress: model.openGitInspector,
386
+ type: "action",
387
+ },
388
+ ],
389
+ title: "Git",
390
},
410
- }),
411
- [
412
- model.currentBranchLabel,
413
- model.isRepo,
414
- model.openFiles,
415
- model.openGitInspector,
416
- model.openReview,
417
- model.quickAction.disabled,
418
- model.quickAction.label,
419
- model.quickActionHint,
420
- model.quickActionIcon,
421
- model.runQuickAction,
422
- props.canOpenFiles,
423
- props.canOpenTerminal,
424
- props.canOperateTerminal,
425
- props.gitStatus,
426
- props.onMergeBack,
427
- props.onOpenNewTerminal,
428
- props.onOpenTerminal,
429
- props.onRunProjectScript,
430
- props.projectScripts,
431
- props.terminalSessions,
432
- ],
433
- );
391
+ sharesBackground: true,
392
+ type: "menu",
393
+ variant: "plain",
394
+ },
395
+ };
396
}
397
398
export function useThreadGitRightHeaderItems(props: ThreadGitControlsProps): HeaderItems {
399
const actionItems = useThreadGitHeaderActionItems(props);
438
- return useMemo(
439
- () => [actionItems.git, actionItems.files, actionItems.terminal] as HeaderItems,
440
- [actionItems],
441
- );
400
+ return [actionItems.git, actionItems.files, actionItems.terminal] as HeaderItems;
401
}
402
403
export function useThreadGitCenterHeaderItems(props: ThreadGitControlsProps): HeaderItems {
404
const actionItems = useThreadGitHeaderActionItems(props);
446
- return useMemo(
447
- () => [actionItems.files, actionItems.git, actionItems.terminal] as HeaderItems,
448
- [actionItems],
449
- );
405
+ return [actionItems.files, actionItems.git, actionItems.terminal] as HeaderItems;
406
}
407
408
export function ThreadGitControls(props: ThreadGitControlsProps) {
apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
+369
-504
@@ -28,16 +28,7 @@ import { useNavigation, useRoute, type RouteProp } from "@react-navigation/nativ
28
import { type NativeStackNavigationProp } from "@react-navigation/native-stack";
29
import * as Haptics from "expo-haptics";
30
import { AsyncResult } from "effect/reactivity";
31
-import {
32
- createContext,
33
- use,
34
- useCallback,
35
- useEffect,
36
- useMemo,
37
- useRef,
38
- useState,
39
- type ReactNode,
40
-} from "react";
31
+import { createContext, use, useEffect, useRef, useState, type ReactNode } from "react";
32
import { Platform, Pressable, RefreshControl, ScrollView, TextInput, View } from "react-native";
33
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
34
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -264,13 +255,13 @@ const ExistingThreadSettingsRouteContext =
255
256
export function ExistingThreadSettingsRouteProvider(props: { readonly children: ReactNode }) {
257
const [session, setSession] = useState<ExistingThreadSettingsRouteSession | null>(null);
267
- const present = useCallback((nextSession: ExistingThreadSettingsRouteSession) => {
258
+ const present = (nextSession: ExistingThreadSettingsRouteSession) => {
259
setSession(nextSession);
269
- }, []);
270
- const clear = useCallback((ownerId: string) => {
260
+ };
261
+ const clear = (ownerId: string) => {
262
setSession((current) => (current?.ownerId === ownerId ? null : current));
272
- }, []);
273
- const value = useMemo(() => ({ session, present, clear }), [clear, present, session]);
263
+ };
264
+ const value = { session, present, clear };
265
266
return (
267
<ExistingThreadSettingsRouteContext.Provider value={value}>
@@ -339,28 +330,18 @@ function ThreadSettingsSessionProvider(
330
new Map<string, { favorite: boolean; settings: ServerSettings; pending: boolean }>(),
331
);
332
const [pendingHiddenKeys, setPendingHiddenKeys] = useState<ReadonlySet<string>>(() => new Set());
342
- const providerGroups = useMemo(
343
- () =>
344
- manageHidden && config
345
- ? groupByProvider(
346
- buildModelOptions(
347
- config,
348
- props.selectedModel,
349
- props.lockedProviderInstanceId,
350
- props.projectId,
351
- true,
352
- ),
353
- )
354
- : props.providerGroups,
355
- [
356
- config,
357
- manageHidden,
358
- props.providerGroups,
359
- props.selectedModel,
360
- props.lockedProviderInstanceId,
361
- props.projectId,
362
- ],
363
- );
333
+ const providerGroups =
334
+ manageHidden && config
335
+ ? groupByProvider(
336
+ buildModelOptions(
337
+ config,
338
+ props.selectedModel,
339
+ props.lockedProviderInstanceId,
340
+ props.projectId,
341
+ true,
342
+ ),
343
+ )
344
+ : props.providerGroups;
345
const legacyFavorites = AsyncResult.isSuccess(preferences)
346
? (preferences.value.modelFavorites ?? EMPTY_MODEL_FAVORITES)
347
: EMPTY_MODEL_FAVORITES;
@@ -375,114 +356,98 @@ function ThreadSettingsSessionProvider(
356
const patch = modelPreferencesMigrationPatch(settings, { favorites: legacyFavorites });
357
if (patch) void saveSettings({ environmentId: props.environmentId, input: { patch } });
358
}, [legacyFavorites, preferences, props.environmentId, saveSettings, settings]);
378
- const favoriteKeys = useMemo(
379
- () =>
380
- new Set(
381
- modelFavorites.map((favorite) => modelFavoriteKey(favorite.provider, favorite.model)),
382
- ),
383
- [modelFavorites],
359
+ const favoriteKeys = new Set(
360
+ modelFavorites.map((favorite) => modelFavoriteKey(favorite.provider, favorite.model)),
361
);
385
- const toggleFavorite = useCallback(
386
- async (option: ModelOption) => {
387
- if (!favoritesLoaded || !props.environmentId) return;
388
- const currentSettings = registry
389
- .get(environmentServerConfigsAtom)
390
- .get(props.environmentId)?.settings;
391
- if (!currentSettings) return;
392
- const favorites = resolveModelPreferences(currentSettings, {
393
- favorites: legacyFavorites,
394
- }).favorites;
395
- const key = JSON.stringify([
396
- props.environmentId,
397
- option.selection.instanceId,
398
- option.selection.model,
399
- ]);
400
- const previous = pendingFavorites.current.get(key);
401
- const previousFavorite =
402
- previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
403
- ? previous.favorite
404
- : favorites.some(
405
- (favorite) =>
406
- favorite.provider === option.selection.instanceId &&
407
- favorite.model === option.selection.model,
408
- );
409
- const pending = { favorite: !previousFavorite, settings: currentSettings, pending: true };
410
- pendingFavorites.current.set(key, pending);
411
- void Haptics.selectionAsync();
412
- try {
413
- const result = await saveSettings({
414
- environmentId: props.environmentId,
415
- input: {
416
- patch: {
417
- setModelFavorites: [
418
- {
419
- provider: option.selection.instanceId,
420
- model: option.selection.model,
421
- favorite: pending.favorite,
422
- },
423
- ],
424
- ...(currentSettings.favorites === null
425
- ? { migrateModelPreferences: { favorites } }
426
- : {}),
362
+ const toggleFavorite = async (option: ModelOption) => {
363
+ const environmentId = props.environmentId;
364
+ if (!favoritesLoaded || !environmentId) return;
365
+ const currentSettings = registry.get(environmentServerConfigsAtom).get(environmentId)?.settings;
366
+ if (!currentSettings) return;
367
+ const favorites = resolveModelPreferences(currentSettings, {
368
+ favorites: legacyFavorites,
369
+ }).favorites;
370
+ const key = JSON.stringify([
371
+ environmentId,
372
+ option.selection.instanceId,
373
+ option.selection.model,
374
+ ]);
375
+ const previous = pendingFavorites.current.get(key);
376
+ const previousFavorite =
377
+ previous && (previous.pending || previous.settings.favorites === currentSettings.favorites)
378
+ ? previous.favorite
379
+ : favorites.some(
380
+ (favorite) =>
381
+ favorite.provider === option.selection.instanceId &&
382
+ favorite.model === option.selection.model,
383
+ );
384
+ const pending = { favorite: !previousFavorite, settings: currentSettings, pending: true };
385
+ pendingFavorites.current.set(key, pending);
386
+ void Haptics.selectionAsync();
387
+ const result = await saveSettings({
388
+ environmentId: environmentId,
389
+ input: {
390
+ patch: {
391
+ setModelFavorites: [
392
+ {
393
+ provider: option.selection.instanceId,
394
+ model: option.selection.model,
395
+ favorite: pending.favorite,
396
},
428
- },
429
- });
430
- if (
431
- AsyncResult.isSuccess(result) &&
432
- registry.get(environmentServerConfigsAtom).get(props.environmentId)?.settings
433
- .favorites === currentSettings.favorites
434
- ) {
435
- pending.pending = false;
436
- }
437
- } finally {
438
- if (pending.pending && pendingFavorites.current.get(key) === pending) {
439
- if (
440
- previous &&
441
- !previous.pending &&
442
- registry.get(environmentServerConfigsAtom).get(props.environmentId)?.settings
443
- .favorites === previous.settings.favorites
444
- ) {
445
- pendingFavorites.current.set(key, previous);
446
- } else {
447
- pendingFavorites.current.delete(key);
448
- }
449
- }
450
- }
451
- },
452
- [favoritesLoaded, legacyFavorites, props.environmentId, registry, saveSettings],
453
- );
454
- const toggleHidden = useCallback(
455
- (option: ModelOption) => {
397
+ ],
398
+ ...(currentSettings.favorites === null ? { migrateModelPreferences: { favorites } } : {}),
399
+ },
400
+ },
401
+ });
402
+ if (
403
+ AsyncResult.isSuccess(result) &&
404
+ registry.get(environmentServerConfigsAtom).get(environmentId)?.settings.favorites ===
405
+ currentSettings.favorites
406
+ ) {
407
+ pending.pending = false;
408
+ }
409
+ if (pending.pending && pendingFavorites.current.get(key) === pending) {
410
if (
457
- !settings ||
458
- !props.environmentId ||
459
- !option.canHide ||
460
- pendingHidden.current.has(option.key)
461
- )
462
- return;
463
- pendingHidden.current.add(option.key);
464
- setPendingHiddenKeys(new Set(pendingHidden.current));
465
- void Haptics.selectionAsync();
466
- void saveSettings({
467
- environmentId: props.environmentId,
468
- input: {
469
- patch: {
470
- setModelsHidden: [
471
- {
472
- provider: option.selection.instanceId,
473
- model: option.selection.model,
474
- hidden: !option.isHidden,
475
- },
476
- ],
477
- },
411
+ previous &&
412
+ !previous.pending &&
413
+ registry.get(environmentServerConfigsAtom).get(environmentId)?.settings.favorites ===
414
+ previous.settings.favorites
415
+ ) {
416
+ pendingFavorites.current.set(key, previous);
417
+ } else {
418
+ pendingFavorites.current.delete(key);
419
+ }
420
+ }
421
+ };
422
+ const toggleHidden = (option: ModelOption) => {
423
+ if (
424
+ !settings ||
425
+ !props.environmentId ||
426
+ !option.canHide ||
427
+ pendingHidden.current.has(option.key)
428
+ )
429
+ return;
430
+ pendingHidden.current.add(option.key);
431
+ setPendingHiddenKeys(new Set(pendingHidden.current));
432
+ void Haptics.selectionAsync();
433
+ void saveSettings({
434
+ environmentId: props.environmentId,
435
+ input: {
436
+ patch: {
437
+ setModelsHidden: [
438
+ {
439
+ provider: option.selection.instanceId,
440
+ model: option.selection.model,
441
+ hidden: !option.isHidden,
442
+ },
443
+ ],
444
},
479
- }).then(() => {
480
- pendingHidden.current.delete(option.key);
481
- setPendingHiddenKeys(new Set(pendingHidden.current));
482
- });
483
- },
484
- [props.environmentId, saveSettings, settings],
485
- );
445
+ },
446
+ }).then(() => {
447
+ pendingHidden.current.delete(option.key);
448
+ setPendingHiddenKeys(new Set(pendingHidden.current));
449
+ });
450
+ };
451
const [showLegacyToggle, setShowLegacyToggle] = useState(false);
452
const [providerFilter, setProviderFilter] = useState<string | null>(null);
453
const [searchQuery, setSearchQuery] = useState("");
@@ -491,36 +456,24 @@ function ThreadSettingsSessionProvider(
456
);
457
const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);
458
494
- const isApplied = useCallback(
495
- (option: ModelOption) =>
496
- option.selection.instanceId === props.selectedModel?.instanceId &&
497
- option.selection.model === props.selectedModel.model,
498
- [props.selectedModel],
499
- );
500
- const isDisplayed = useCallback(
501
- (option: ModelOption) => (pendingModel ? option.key === pendingModel.key : isApplied(option)),
502
- [isApplied, pendingModel],
503
- );
504
-
505
- const displayedDescriptors = useMemo(
506
- () =>
507
- pendingModel
508
- ? pendingModel.capabilities
509
- ? getProviderOptionDescriptors({
510
- caps: pendingModel.capabilities,
511
- selections: pendingModel.selection.options,
512
- })
513
- : []
514
- : props.optionDescriptors,
515
- [pendingModel, props.optionDescriptors],
516
- );
517
- const displayedModel = useMemo(
518
- () =>
519
- pendingModel ??
520
- props.providerGroups.flatMap((group) => group.models).find((option) => isApplied(option)) ??
521
- null,
522
- [isApplied, pendingModel, props.providerGroups],
523
- );
459
+ const isApplied = (option: ModelOption) =>
460
+ option.selection.instanceId === props.selectedModel?.instanceId &&
461
+ option.selection.model === props.selectedModel.model;
462
+ const isDisplayed = (option: ModelOption) =>
463
+ pendingModel ? option.key === pendingModel.key : isApplied(option);
464
+
465
+ const displayedDescriptors = pendingModel
466
+ ? pendingModel.capabilities
467
+ ? getProviderOptionDescriptors({
468
+ caps: pendingModel.capabilities,
469
+ selections: pendingModel.selection.options,
470
+ })
471
+ : []
472
+ : props.optionDescriptors;
473
+ const displayedModel =
474
+ pendingModel ??
475
+ props.providerGroups.flatMap((group) => group.models).find((option) => isApplied(option)) ??
476
+ null;
477
const runtimeModeChoices = runtimeModeChoicesForSupportedModes(
478
displayedModel?.supportedRuntimeModes,
479
);
@@ -529,11 +482,10 @@ function ThreadSettingsSessionProvider(
482
runtimeModeChoices,
483
);
484
532
- const hasLegacyModels = useMemo(
533
- () => props.providerGroups.some((group) => group.models.some((model) => model.isLegacy)),
534
- [props.providerGroups],
485
+ const hasLegacyModels = props.providerGroups.some((group) =>
486
+ group.models.some((model) => model.isLegacy),
487
);
536
- const commitPendingModel = useCallback(() => {
488
+ const commitPendingModel = () => {
489
if (pendingModel) {
490
if (!canCommitPendingModel(pendingModel, props.providerGroups)) {
491
Dialog.alert(
@@ -546,28 +498,25 @@ function ThreadSettingsSessionProvider(
498
props.onSelectModel(pendingModel);
499
}
500
return true;
549
- }, [pendingModel, props.onSelectModel, props.providerGroups]);
501
+ };
502
551
- const applyOptionChange = useCallback(
552
- (id: string, value: string | boolean) => {
553
- const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
554
- if (!next) {
555
- return;
556
- }
557
- if (pendingModel) {
558
- rememberModelOptions(pendingModel.selection.instanceId, pendingModel.selection.model, next);
559
- setPendingModel({
560
- ...pendingModel,
561
- selection: { ...pendingModel.selection, options: next },
562
- });
563
- } else {
564
- props.onUpdateOptionSelections(next);
565
- }
566
- },
567
- [displayedDescriptors, pendingModel, props.onUpdateOptionSelections],
568
- );
503
+ const applyOptionChange = (id: string, value: string | boolean) => {
504
+ const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
505
+ if (!next) {
506
+ return;
507
+ }
508
+ if (pendingModel) {
509
+ rememberModelOptions(pendingModel.selection.instanceId, pendingModel.selection.model, next);
510
+ setPendingModel({
511
+ ...pendingModel,
512
+ selection: { ...pendingModel.selection, options: next },
513
+ });
514
+ } else {
515
+ props.onUpdateOptionSelections(next);
516
+ }
517
+ };
518
570
- const toggleProvider = useCallback((providerKey: string) => {
519
+ const toggleProvider = (providerKey: string) => {
520
setProviderExpansionOverrides((current) => {
521
const next = new Set(current);
522
if (!next.delete(providerKey)) {
@@ -575,86 +524,52 @@ function ThreadSettingsSessionProvider(
524
}
525
return next;
526
});
578
- }, []);
579
-
580
- const pressModel = useCallback(
581
- (option: ModelOption) => {
582
- void Haptics.selectionAsync();
583
- setPendingModel((current) =>
584
- pendingModelAfterPress({
585
- current,
586
- pressed: option,
587
- pressedIsApplied: isApplied(option),
588
- }),
589
- );
590
- },
591
- [isApplied],
592
- );
593
-
594
- const value = useMemo<ThreadSettingsSessionValue>(
595
- () => ({
596
- environmentId: props.environmentId,
597
- providerInstanceId: props.providerInstanceId,
598
- providerGroups,
599
- manageHidden,
600
- setManageHidden,
601
- toggleHidden,
602
- pendingHiddenKeys,
603
- runtimeMode: compatibleRuntimeMode,
604
- runtimeModeChoices,
605
- onUpdateRuntimeMode: props.onUpdateRuntimeMode,
606
- displayedDescriptors,
607
- displayedModelSelection: pendingModel?.selection ?? props.selectedModel,
608
- reportedModelSelection: pendingModel ? null : (props.reportedModelSelection ?? null),
609
- favoriteKeys,
610
- favoritesLoaded,
611
- providerExpansionOverrides,
612
- hasLegacyModels,
613
- pendingModel,
614
- providerFilter,
615
- searchQuery,
616
- showLegacy: showLegacyToggle,
617
- applyOptionChange,
618
- commitPendingModel,
619
- isApplied,
620
- isDisplayed,
621
- pressModel,
622
- setProviderFilter,
623
- setSearchQuery,
624
- setShowLegacy: setShowLegacyToggle,
625
- toggleProvider,
626
- toggleFavorite,
627
- }),
628
- [
629
- applyOptionChange,
630
- commitPendingModel,
631
- compatibleRuntimeMode,
632
- displayedDescriptors,
633
- favoriteKeys,
634
- favoritesLoaded,
635
- providerExpansionOverrides,
636
- hasLegacyModels,
637
- isApplied,
638
- isDisplayed,
639
- props.environmentId,
640
- props.selectedModel,
641
- props.reportedModelSelection,
642
- props.providerInstanceId,
643
- pendingModel,
644
- pressModel,
645
- providerFilter,
646
- props.onUpdateRuntimeMode,
647
- providerGroups,
648
- manageHidden,
649
- toggleHidden,
650
- pendingHiddenKeys,
651
- runtimeModeChoices,
652
- searchQuery,
653
- showLegacyToggle,
654
- toggleProvider,
655
- toggleFavorite,
656
- ],
657
- );
527
+ };
528
+
529
+ const pressModel = (option: ModelOption) => {
530
+ void Haptics.selectionAsync();
531
+ setPendingModel((current) =>
532
+ pendingModelAfterPress({
533
+ current,
534
+ pressed: option,
535
+ pressedIsApplied: isApplied(option),
536
+ }),
537
+ );
538
+ };
539
+
540
+ const value = {
541
+ environmentId: props.environmentId,
542
+ providerInstanceId: props.providerInstanceId,
543
+ providerGroups,
544
+ manageHidden,
545
+ setManageHidden,
546
+ toggleHidden,
547
+ pendingHiddenKeys,
548
+ runtimeMode: compatibleRuntimeMode,
549
+ runtimeModeChoices,
550
+ onUpdateRuntimeMode: props.onUpdateRuntimeMode,
551
+ displayedDescriptors,
552
+ displayedModelSelection: pendingModel?.selection ?? props.selectedModel,
553
+ reportedModelSelection: pendingModel ? null : (props.reportedModelSelection ?? null),
554
+ favoriteKeys,
555
+ favoritesLoaded,
556
+ providerExpansionOverrides,
557
+ hasLegacyModels,
558
+ pendingModel,
559
+ providerFilter,
560
+ searchQuery,
561
+ showLegacy: showLegacyToggle,
562
+ applyOptionChange,
563
+ commitPendingModel,
564
+ isApplied,
565
+ isDisplayed,
566
+ pressModel,
567
+ setProviderFilter,
568
+ setSearchQuery,
569
+ setShowLegacy: setShowLegacyToggle,
570
+ toggleProvider,
571
+ toggleFavorite,
572
+ } satisfies ThreadSettingsSessionValue;
573
574
return (
575
<ThreadSettingsSessionContext.Provider value={value}>
@@ -715,10 +630,7 @@ function ThreadSettingsModelListRow(props: {
630
readonly isLast: boolean;
631
}) {
632
const session = useThreadSettingsSession();
718
- const onPress = useCallback(
719
- () => session.pressModel(props.option),
720
- [props.option, session.pressModel],
721
- );
633
+ const onPress = () => session.pressModel(props.option);
634
635
return (
636
<ModelRow
@@ -744,10 +656,7 @@ function ThreadSettingsProviderListHeader(props: {
656
readonly provider: ThreadSettingsProviderCatalog;
657
}) {
658
const session = useThreadSettingsSession();
747
- const onToggle = useCallback(
748
- () => session.toggleProvider(props.provider.key),
749
- [props.provider.key, session.toggleProvider],
750
- );
659
+ const onToggle = () => session.toggleProvider(props.provider.key);
660
661
return (
662
<ProviderHeader
@@ -762,106 +671,90 @@ function ThreadSettingsProviderListHeader(props: {
671
);
672
}
673
765
-function useThreadSettingsCatalogItems(
674
+function buildThreadSettingsCatalogItems(
675
session: ThreadSettingsSessionValue,
676
): ReadonlyArray<ThreadSettingsCatalogItem> {
768
- return useMemo(
769
- () =>
770
- session.providerGroups.flatMap((group) => {
771
- if (
772
- session.providerFilter !== null &&
773
- session.providerFilter !== FAVORITES_PROVIDER_FILTER &&
774
- group.providerKey !== session.providerFilter
775
- ) {
776
- return [];
777
- }
778
- const driver = group.models[0]?.providerDriver ?? group.providerKey;
779
- const catalogModels =
780
- session.manageHidden ||
781
- session.showLegacy ||
782
- session.providerFilter === FAVORITES_PROVIDER_FILTER
783
- ? group.models
784
- : group.models.filter(
785
- (model) =>
786
- !model.isLegacy ||
787
- session.isDisplayed(model) ||
788
- session.favoriteKeys.has(model.key),
789
- );
790
- const visibleModels = favoritesFirst(
791
- catalogModels.filter(
677
+ return session.providerGroups.flatMap((group) => {
678
+ if (
679
+ session.providerFilter !== null &&
680
+ session.providerFilter !== FAVORITES_PROVIDER_FILTER &&
681
+ group.providerKey !== session.providerFilter
682
+ ) {
683
+ return [];
684
+ }
685
+ const driver = group.models[0]?.providerDriver ?? group.providerKey;
686
+ const catalogModels =
687
+ session.manageHidden ||
688
+ session.showLegacy ||
689
+ session.providerFilter === FAVORITES_PROVIDER_FILTER
690
+ ? group.models
691
+ : group.models.filter(
692
(model) =>
793
- (session.providerFilter !== FAVORITES_PROVIDER_FILTER ||
794
- session.favoriteKeys.has(model.key)) &&
795
- modelMatchesCatalogQuery({
796
- model,
797
- providerLabel: group.providerLabel,
798
- query: session.searchQuery,
799
- }),
800
- ),
801
- session.favoriteKeys,
802
- );
803
- const updateRequiredNotice =
804
- group.updateRequired && session.providerFilter !== FAVORITES_PROVIDER_FILTER
805
- ? formatProviderUpdateRequiredNotice(group.updateRequired, session.searchQuery)
806
- : null;
807
- if (visibleModels.length === 0 && !updateRequiredNotice) {
808
- return [];
809
- }
810
- const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
811
- const containsAppliedSelection = group.models.some(session.isApplied);
812
- const isNarrowed = session.providerFilter !== null || session.searchQuery.trim().length > 0;
813
- const collapsible = !isNarrowed;
814
- const collapsed = providerSectionIsCollapsed({
815
- defaultExpanded: isPrimary || containsAppliedSelection,
816
- hasExpansionOverride: session.providerExpansionOverrides.has(group.providerKey),
817
- isNarrowed,
818
- });
819
- const provider: ThreadSettingsProviderCatalog = {
820
- key: group.providerKey,
821
- driver,
822
- iconUrl: group.models[0]?.providerIconUrl,
823
- label: group.providerLabel,
824
- collapsible,
825
- collapsed,
826
- modelCount: visibleModels.length,
827
- models: collapsed ? [] : visibleModels,
828
- };
829
- return [
830
- {
831
- kind: "provider" as const,
832
- key: `provider:${group.providerKey}`,
833
- provider,
834
- },
835
- ...provider.models.map((option, index) => ({
836
- kind: "model" as const,
837
- key: `model:${option.key}`,
838
- option,
839
- isFirst: index === 0,
840
- isLast: index === provider.models.length - 1,
841
- })),
842
- ...(!collapsed && updateRequiredNotice
843
- ? [
844
- {
845
- kind: "notice" as const,
846
- key: `notice:${group.providerKey}`,
847
- text: updateRequiredNotice,
848
- },
849
- ]
850
- : []),
851
- ];
852
- }),
853
- [
854
- session.isApplied,
855
- session.isDisplayed,
693
+ !model.isLegacy || session.isDisplayed(model) || session.favoriteKeys.has(model.key),
694
+ );
695
+ const visibleModels = favoritesFirst(
696
+ catalogModels.filter(
697
+ (model) =>
698
+ (session.providerFilter !== FAVORITES_PROVIDER_FILTER ||
699
+ session.favoriteKeys.has(model.key)) &&
700
+ modelMatchesCatalogQuery({
701
+ model,
702
+ providerLabel: group.providerLabel,
703
+ query: session.searchQuery,
704
+ }),
705
+ ),
706
session.favoriteKeys,
857
- session.providerExpansionOverrides,
858
- session.providerFilter,
859
- session.providerGroups,
860
- session.searchQuery,
861
- session.showLegacy,
862
- session.manageHidden,
863
- ],
864
- );
707
+ );
708
+ const updateRequiredNotice =
709
+ group.updateRequired && session.providerFilter !== FAVORITES_PROVIDER_FILTER
710
+ ? formatProviderUpdateRequiredNotice(group.updateRequired, session.searchQuery)
711
+ : null;
712
+ if (visibleModels.length === 0 && !updateRequiredNotice) {
713
+ return [];
714
+ }
715
+ const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
716
+ const containsAppliedSelection = group.models.some(session.isApplied);
717
+ const isNarrowed = session.providerFilter !== null || session.searchQuery.trim().length > 0;
718
+ const collapsible = !isNarrowed;
719
+ const collapsed = providerSectionIsCollapsed({
720
+ defaultExpanded: isPrimary || containsAppliedSelection,
721
+ hasExpansionOverride: session.providerExpansionOverrides.has(group.providerKey),
722
+ isNarrowed,
723
+ });
724
+ const provider: ThreadSettingsProviderCatalog = {
725
+ key: group.providerKey,
726
+ driver,
727
+ iconUrl: group.models[0]?.providerIconUrl,
728
+ label: group.providerLabel,
729
+ collapsible,
730
+ collapsed,
731
+ modelCount: visibleModels.length,
732
+ models: collapsed ? [] : visibleModels,
733
+ };
734
+ return [
735
+ {
736
+ kind: "provider" as const,
737
+ key: `provider:${group.providerKey}`,
738
+ provider,
739
+ },
740
+ ...provider.models.map((option, index) => ({
741
+ kind: "model" as const,
742
+ key: `model:${option.key}`,
743
+ option,
744
+ isFirst: index === 0,
745
+ isLast: index === provider.models.length - 1,
746
+ })),
747
+ ...(!collapsed && updateRequiredNotice
748
+ ? [
749
+ {
750
+ kind: "notice" as const,
751
+ key: `notice:${group.providerKey}`,
752
+ text: updateRequiredNotice,
753
+ },
754
+ ]
755
+ : []),
756
+ ];
757
+ });
758
}
759
760
function ThreadSettingsOptionsItem(props: {
@@ -968,12 +861,9 @@ function ThreadSettingsMainContent(props: {
861
const refreshProvidersCommand = useAtomCommand(serverEnvironment.refreshProviders, {
862
reportFailure: false,
863
});
971
- const refreshProviderCatalog = useMemo(
972
- () => createProviderCatalogRefreshRunner(refreshProvidersCommand),
973
- [refreshProvidersCommand],
974
- );
864
+ const refreshProviderCatalog = createProviderCatalogRefreshRunner(refreshProvidersCommand);
865
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
976
- const refreshProviders = useCallback(() => {
866
+ const refreshProviders = () => {
867
if (!session.environmentId || isRefreshingProviders) return;
868
setIsRefreshingProviders(true);
869
void refreshProviderCatalog(session.environmentId).then((result) => {
@@ -981,75 +871,63 @@ function ThreadSettingsMainContent(props: {
871
const error = providerCatalogRefreshError(result);
872
if (error) Dialog.alert("Could not refresh models", error);
873
});
984
- }, [isRefreshingProviders, refreshProviderCatalog, session.environmentId]);
985
- const catalogItems = useThreadSettingsCatalogItems(session);
874
+ };
875
const [animationsReady, setAnimationsReady] = useState(false);
876
+ const catalogItems = buildThreadSettingsCatalogItems(session);
877
const hasActiveCatalogFilter =
878
session.providerFilter !== null || session.searchQuery.trim().length > 0;
989
- const listItems = useMemo<ReadonlyArray<ThreadSettingsCatalogItem>>(
990
- () => [
991
- ...(catalogItems.length === 0 ? ([{ kind: "empty", key: "empty" }] as const) : catalogItems),
992
- { kind: "options", key: "options" },
993
- ],
994
- [catalogItems],
995
- );
996
- const renderCatalogItem = useCallback(
997
- (itemProps: LegendListRenderItemProps<ThreadSettingsCatalogItem>) => {
998
- const item = itemProps.item;
999
- let content: ReactNode;
1000
-
1001
- if (item.kind === "provider") {
1002
- content = <ThreadSettingsProviderListHeader provider={item.provider} />;
1003
- } else if (item.kind === "model") {
1004
- content = (
1005
- <ThreadSettingsModelListRow
1006
- isFirst={item.isFirst}
1007
- isLast={item.isLast}
1008
- option={item.option}
1009
- />
1010
- );
1011
- } else if (item.kind === "notice") {
1012
- content = <Text className="mx-8 mt-2 text-xs text-foreground-muted">{item.text}</Text>;
1013
- } else if (item.kind === "empty") {
1014
- content = (
1015
- <View className="items-center px-8 py-14">
1016
- <Text className="text-center text-sm text-foreground-muted">
1017
- {session.providerFilter === FAVORITES_PROVIDER_FILTER &&
1018
- session.searchQuery.trim().length === 0
1019
- ? "No favorite models"
1020
- : hasActiveCatalogFilter
1021
- ? "No matching models"
1022
- : "No available models"}
1023
- </Text>
1024
- </View>
1025
- );
1026
- } else {
1027
- content = (
1028
- <ThreadSettingsOptionsItem
1029
- animationsReady={animationsReady}
1030
- onOpenSubmenu={props.onOpenSubmenu}
1031
- />
1032
- );
1033
- }
1034
-
1035
- return (
1036
- <Animated.View
1037
- key={item.key}
1038
- entering={animationsReady ? THREAD_SETTINGS_CATALOG_ENTER_TRANSITION : undefined}
1039
- exiting={animationsReady ? THREAD_SETTINGS_CATALOG_EXIT_TRANSITION : undefined}
1040
- >
1041
- {content}
1042
- </Animated.View>
879
+ const listItems = [
880
+ ...(catalogItems.length === 0 ? ([{ kind: "empty", key: "empty" }] as const) : catalogItems),
881
+ { kind: "options", key: "options" },
882
+ ] satisfies ReadonlyArray<ThreadSettingsCatalogItem>;
883
+ const renderCatalogItem = (itemProps: LegendListRenderItemProps<ThreadSettingsCatalogItem>) => {
884
+ const item = itemProps.item;
885
+ let content: ReactNode;
886
+
887
+ if (item.kind === "provider") {
888
+ content = <ThreadSettingsProviderListHeader provider={item.provider} />;
889
+ } else if (item.kind === "model") {
890
+ content = (
891
+ <ThreadSettingsModelListRow
892
+ isFirst={item.isFirst}
893
+ isLast={item.isLast}
894
+ option={item.option}
895
+ />
896
);
1044
- },
1045
- [
1046
- animationsReady,
1047
- hasActiveCatalogFilter,
1048
- props.onOpenSubmenu,
1049
- session.providerFilter,
1050
- session.searchQuery,
1051
- ],
1052
- );
897
+ } else if (item.kind === "notice") {
898
+ content = <Text className="mx-8 mt-2 text-xs text-foreground-muted">{item.text}</Text>;
899
+ } else if (item.kind === "empty") {
900
+ content = (
901
+ <View className="items-center px-8 py-14">
902
+ <Text className="text-center text-sm text-foreground-muted">
903
+ {session.providerFilter === FAVORITES_PROVIDER_FILTER &&
904
+ session.searchQuery.trim().length === 0
905
+ ? "No favorite models"
906
+ : hasActiveCatalogFilter
907
+ ? "No matching models"
908
+ : "No available models"}
909
+ </Text>
910
+ </View>
911
+ );
912
+ } else {
913
+ content = (
914
+ <ThreadSettingsOptionsItem
915
+ animationsReady={animationsReady}
916
+ onOpenSubmenu={props.onOpenSubmenu}
917
+ />
918
+ );
919
+ }
920
+
921
+ return (
922
+ <Animated.View
923
+ key={item.key}
924
+ entering={animationsReady ? THREAD_SETTINGS_CATALOG_ENTER_TRANSITION : undefined}
925
+ exiting={animationsReady ? THREAD_SETTINGS_CATALOG_EXIT_TRANSITION : undefined}
926
+ >
927
+ {content}
928
+ </Animated.View>
929
+ );
930
+ };
931
932
return (
933
<AnimatedLegendList
@@ -1243,50 +1121,44 @@ function ThreadSettingsModelsScreen() {
1121
const navigation = useNavigation<NativeStackNavigationProp<ThreadSettingsPickerStackParams>>();
1122
const usesNativeMailSearchToolbar = useNativeMailSearchToolbar();
1123
const hasCustomCatalogFilter = session.providerFilter !== null || session.showLegacy;
1246
- const commitAndClose = useCallback(() => {
1124
+ const commitAndClose = () => {
1125
if (!session.commitPendingModel()) return;
1126
presentation.onClose();
1249
- }, [presentation, session]);
1250
- const providerFilters = useMemo(
1251
- () => [
1252
- { id: "all-providers", title: "All providers", value: null },
1253
- { id: "favorites", title: "Favorites", value: FAVORITES_PROVIDER_FILTER },
1254
- ...session.providerGroups.map((group) => ({
1255
- id: `provider:${group.providerKey}`,
1256
- title: group.providerLabel,
1257
- value: group.providerKey,
1258
- })),
1127
+ };
1128
+ const providerFilters = [
1129
+ { id: "all-providers", title: "All providers", value: null },
1130
+ { id: "favorites", title: "Favorites", value: FAVORITES_PROVIDER_FILTER },
1131
+ ...session.providerGroups.map((group) => ({
1132
+ id: `provider:${group.providerKey}`,
1133
+ title: group.providerLabel,
1134
+ value: group.providerKey,
1135
+ })),
1136
+ ];
1137
+ const filterMenu = {
1138
+ title: "Model filters",
1139
+ items: [
1140
+ {
1141
+ type: "submenu" as const,
1142
+ title: "Provider",
1143
+ items: providerFilters.map((filter) => ({
1144
+ type: "action" as const,
1145
+ title: filter.title,
1146
+ state: session.providerFilter === filter.value ? ("on" as const) : ("off" as const),
1147
+ onPress: () => session.setProviderFilter(filter.value),
1148
+ })),
1149
+ },
1150
+ ...(session.hasLegacyModels
1151
+ ? [
1152
+ {
1153
+ type: "action" as const,
1154
+ title: "Show legacy models",
1155
+ state: session.showLegacy ? ("on" as const) : ("off" as const),
1156
+ onPress: () => session.setShowLegacy(!session.showLegacy),
1157
+ },
1158
+ ]
1159
+ : []),
1160
],
1260
- [session.providerGroups],
1261
- );
1262
- const filterMenu = useMemo(
1263
- () => ({
1264
- title: "Model filters",
1265
- items: [
1266
- {
1267
- type: "submenu" as const,
1268
- title: "Provider",
1269
- items: providerFilters.map((filter) => ({
1270
- type: "action" as const,
1271
- title: filter.title,
1272
- state: session.providerFilter === filter.value ? ("on" as const) : ("off" as const),
1273
- onPress: () => session.setProviderFilter(filter.value),
1274
- })),
1275
- },
1276
- ...(session.hasLegacyModels
1277
- ? [
1278
- {
1279
- type: "action" as const,
1280
- title: "Show legacy models",
1281
- state: session.showLegacy ? ("on" as const) : ("off" as const),
1282
- onPress: () => session.setShowLegacy(!session.showLegacy),
1283
- },
1284
- ]
1285
- : []),
1286
- ],
1287
- }),
1288
- [providerFilters, session],
1289
- );
1161
+ };
1162
1163
return (
1164
<>
@@ -1486,12 +1358,9 @@ function ThreadSettingsPickerNavigator(props: ThreadSettingsPickerPresentation)
1358
const theme = useUniwindTheme();
1359
const solidSheetBackground = theme["--color-sheet-solid"];
1360
const foreground = theme["--color-foreground"];
1489
- const presentation = useMemo(
1490
- () => ({
1491
- onClose: props.onClose,
1492
- }),
1493
- [props.onClose],
1494
- );
1361
+ const presentation = {
1362
+ onClose: props.onClose,
1363
+ };
1364
1365
return (
1366
<ThreadSettingsPickerPresentationContext.Provider value={presentation}>
@@ -1570,14 +1439,10 @@ export function ExistingThreadSettingsRouteScreen() {
1439
export function NewTaskThreadSettingsRouteScreen() {
1440
const flow = useNewTaskFlow();
1441
const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>();
1573
- const optionDescriptors = useMemo(
1574
- () =>
1575
- resolveProviderOptionDescriptors({
1576
- capabilities: flow.selectedModelOption?.capabilities,
1577
- selections: flow.selectedModel?.options,
1578
- }),
1579
- [flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
1580
- );
1442
+ const optionDescriptors = resolveProviderOptionDescriptors({
1443
+ capabilities: flow.selectedModelOption?.capabilities,
1444
+ selections: flow.selectedModel?.options,
1445
+ });
1446
1447
return (
1448
<ThreadSettingsPickerScreen
apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx
+35
-17
@@ -1,8 +1,9 @@
1
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2
+import { AsyncResult } from "effect/reactivity";
3
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4
import type { EnvironmentId } from "@t3tools/contracts";
5
import * as DateTime from "effect/DateTime";
5
-import { useState } from "react";
6
+import { useEffect, useState } from "react";
7
import { Pressable, View } from "react-native";
8
import { AppText as Text } from "../../components/ui/AppText";
9
import { threadEnvironment } from "../../state/threads";
@@ -22,6 +23,25 @@ export function UsageLimitRecoveryCard({
23
const canSchedule =
24
resetAt !== null &&
25
Date.parse(resetAt) > Date.parse(thread.latestRun?.completedAt ?? thread.updatedAt);
26
+ // Whether the reset already passed is state a timer flips at resetAt: the
27
+ // compiler caches render output on its inputs, so reading the clock during
28
+ // render would leave the snooze button enabled after the reset.
29
+ const resetAtMs = resetAt === null ? null : Date.parse(resetAt);
30
+ const [resetPassedFor, setResetPassedFor] = useState<number | null>(null);
31
+ const resetPassed = resetAtMs !== null && resetPassedFor === resetAtMs;
32
+ useEffect(() => {
33
+ if (resetAtMs === null || Number.isNaN(resetAtMs)) return;
34
+ const flip = () => setResetPassedFor(resetAtMs);
35
+ const delay = resetAtMs - Date.now();
36
+ if (delay <= 0) {
37
+ flip();
38
+ return;
39
+ }
40
+ // Beyond setTimeout's 32-bit range the card re-renders long before then.
41
+ if (delay > 2_147_483_647) return;
42
+ const timer = setTimeout(flip, delay);
43
+ return () => clearTimeout(timer);
44
+ }, [resetAtMs]);
45
const runId = thread.latestRun?.runId;
46
const recovery = thread.limitRecovery;
47
const scheduled =
@@ -47,23 +67,21 @@ export function UsageLimitRecoveryCard({
67
}
68
setPending(true);
69
setError(null);
50
- try {
51
- const result = await updateMetadata({
52
- environmentId,
53
- input: {
54
- threadId: thread.id,
55
- limitRecovery: {
56
- runId,
57
- resetAt,
58
- ...(action === "resume" ? { autoResume: !scheduled } : { snooze: !snoozed }),
59
- },
70
+ const result = await updateMetadata({
71
+ environmentId,
72
+ input: {
73
+ threadId: thread.id,
74
+ limitRecovery: {
75
+ runId,
76
+ resetAt,
77
+ ...(action === "resume" ? { autoResume: !scheduled } : { snooze: !snoozed }),
78
},
61
- });
62
- if (result._tag === "Failure") throw squashAtomCommandFailure(result);
63
- } catch (cause) {
79
+ },
80
+ });
81
+ setPending(false);
82
+ if (AsyncResult.isFailure(result)) {
83
+ const cause = squashAtomCommandFailure(result);
84
setError(cause instanceof Error ? cause.message : "Could not change limit recovery.");
65
- } finally {
66
- setPending(false);
85
}
86
}
87
return (
@@ -87,7 +105,7 @@ export function UsageLimitRecoveryCard({
105
</Pressable>
106
<Pressable
107
accessibilityRole="button"
90
- disabled={pending || (!snoozed && Date.parse(resetAt!) <= Date.now())}
108
+ disabled={pending || (!snoozed && resetPassed)}
109
onPress={() => void toggle("snooze")}
110
className="self-start rounded-lg bg-subtle px-3 py-2 active:opacity-70"
111
>
apps/mobile/src/features/threads/git/GitCommitSheet.tsx
+12
-23
@@ -1,5 +1,5 @@
1
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
2
-import { useCallback, useState } from "react";
2
+import { useState } from "react";
3
import { Platform, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
4
import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
5
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -57,28 +57,17 @@ export function GitCommitSheet(_props: GitCommitSheetProps) {
57
const selectedDeletions = selectedFiles.reduce((sum, file) => sum + file.deletions, 0);
58
const selectedFilePreview = selectedFiles.slice(0, 3);
59
60
- const runCommitAction = useCallback(
61
- async (featureBranch: boolean) => {
62
- if (!canWriteSourceControl || (featureBranch && !canChangeThreadBranch)) return;
63
- const commitMessage = dialogCommitMessage.trim();
64
- navigation.goBack();
65
- await gitActions.onRunSelectedThreadGitAction({
66
- action: "commit",
67
- featureBranch,
68
- ...(commitMessage ? { commitMessage } : {}),
69
- ...(!allSelected ? { filePaths: selectedFiles.map((file) => file.path) } : {}),
70
- });
71
- },
72
- [
73
- allSelected,
74
- canWriteSourceControl,
75
- canChangeThreadBranch,
76
- dialogCommitMessage,
77
- gitActions,
78
- navigation,
79
- selectedFiles,
80
- ],
81
- );
60
+ const runCommitAction = async (featureBranch: boolean) => {
61
+ if (!canWriteSourceControl || (featureBranch && !canChangeThreadBranch)) return;
62
+ const commitMessage = dialogCommitMessage.trim();
63
+ navigation.goBack();
64
+ await gitActions.onRunSelectedThreadGitAction({
65
+ action: "commit",
66
+ featureBranch,
67
+ ...(commitMessage ? { commitMessage } : {}),
68
+ ...(!allSelected ? { filePaths: selectedFiles.map((file) => file.path) } : {}),
69
+ });
70
+ };
71
72
return (
73
<View
apps/mobile/src/features/threads/git/GitOverviewSheet.tsx
+92
-129
@@ -14,7 +14,7 @@ import {
14
type StaticScreenProps,
15
} from "@react-navigation/native";
16
import { SymbolView } from "../../../components/ui/AppSymbol";
17
-import { useCallback, useEffect, useMemo, useState } from "react";
17
+import { useEffect, useState } from "react";
18
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
19
20
import { ScreenStack } from "react-native-screens";
@@ -112,32 +112,25 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {
112
const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
113
const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
114
115
- const menuItems = useMemo(
116
- () => (isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : []),
117
- [busy, gitStatus.data, hasPrimaryRemote, isRepo],
118
- );
115
+ const menuItems = isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : [];
116
120
- const sheetMenuItems = useMemo(
121
- () =>
122
- menuItems.map((item) => ({
123
- item: {
124
- ...item,
125
- disabled: item.disabled || (!canWriteSourceControl && item.kind !== "open_pr"),
126
- },
127
- disabledReason:
128
- !canWriteSourceControl && item.kind !== "open_pr"
129
- ? "This connection cannot change source control."
130
- : getGitActionDisabledReason({
131
- item,
132
- gitStatus: gitStatus.data,
133
- isBusy: busy,
134
- hasOriginRemote: hasPrimaryRemote,
135
- }),
136
- })),
137
- [busy, canWriteSourceControl, gitStatus.data, hasPrimaryRemote, menuItems],
138
- );
117
+ const sheetMenuItems = menuItems.map((item) => ({
118
+ item: {
119
+ ...item,
120
+ disabled: item.disabled || (!canWriteSourceControl && item.kind !== "open_pr"),
121
+ },
122
+ disabledReason:
123
+ !canWriteSourceControl && item.kind !== "open_pr"
124
+ ? "This connection cannot change source control."
125
+ : getGitActionDisabledReason({
126
+ item,
127
+ gitStatus: gitStatus.data,
128
+ isBusy: busy,
129
+ hasOriginRemote: hasPrimaryRemote,
130
+ }),
131
+ }));
132
140
- const openExistingPr = useCallback(async () => {
133
+ const openExistingPr = async () => {
134
const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
135
if (!prUrl) {
136
Dialog.alert("No open PR", "This branch does not have an open pull request.");
@@ -146,122 +139,92 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {
139
if (!(await openPullRequest(prUrl))) {
140
Dialog.alert("Unable to open PR", "The pull request could not be opened.");
141
}
149
- }, [gitStatus.data, openPullRequest]);
142
+ };
143
151
- const runActionWithPrompt = useCallback(
152
- async (input: GitActionRequestInput) => {
153
- if (!canWriteSourceControl) return;
154
- const confirmableAction =
155
- input.action === "push" ||
156
- input.action === "create_pr" ||
157
- input.action === "commit_push" ||
158
- input.action === "commit_push_pr"
159
- ? input.action
160
- : null;
161
- const branchName = gitStatus.data?.refName;
162
- if (
163
- branchName &&
164
- confirmableAction &&
165
- !input.featureBranch &&
166
- requiresDefaultBranchConfirmation(input.action, isDefaultRef)
167
- ) {
168
- navigation.navigate("GitConfirm", {
169
- environmentId: String(environmentId),
170
- threadId: String(threadId),
171
- confirmAction: confirmableAction,
172
- branchName,
173
- includesCommit: String(
174
- input.action === "commit_push" || input.action === "commit_push_pr",
175
- ),
176
- });
177
- return;
178
- }
144
+ const runActionWithPrompt = async (input: GitActionRequestInput) => {
145
+ if (!canWriteSourceControl) return;
146
+ const confirmableAction =
147
+ input.action === "push" ||
148
+ input.action === "create_pr" ||
149
+ input.action === "commit_push" ||
150
+ input.action === "commit_push_pr"
151
+ ? input.action
152
+ : null;
153
+ const branchName = gitStatus.data?.refName;
154
+ if (
155
+ branchName &&
156
+ confirmableAction &&
157
+ !input.featureBranch &&
158
+ requiresDefaultBranchConfirmation(input.action, isDefaultRef)
159
+ ) {
160
+ navigation.navigate("GitConfirm", {
161
+ environmentId: String(environmentId),
162
+ threadId: String(threadId),
163
+ confirmAction: confirmableAction,
164
+ branchName,
165
+ includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"),
166
+ });
167
+ return;
168
+ }
169
180
- if (!isInspector) {
181
- navigation.goBack();
182
- }
183
- await gitActions.onRunSelectedThreadGitAction(input);
184
- },
185
- [
186
- canWriteSourceControl,
187
- environmentId,
188
- gitActions,
189
- gitStatus.data,
190
- isDefaultRef,
191
- isInspector,
192
- navigation,
193
- threadId,
194
- ],
195
- );
170
+ if (!isInspector) {
171
+ navigation.goBack();
172
+ }
173
+ await gitActions.onRunSelectedThreadGitAction(input);
174
+ };
175
197
- const onPressMenuItem = useCallback(
198
- async (item: (typeof menuItems)[number]) => {
199
- if (item.disabled) return;
200
- if (item.kind === "open_pr") {
201
- await openExistingPr();
202
- return;
203
- }
204
- if (!canWriteSourceControl) return;
205
- if (item.dialogAction === "commit") {
206
- navigation.navigate("GitCommit", {
207
- environmentId: String(environmentId),
208
- threadId: String(threadId),
209
- });
210
- return;
211
- }
212
- if (item.dialogAction === "push") {
213
- await runActionWithPrompt({ action: "push" });
214
- return;
215
- }
216
- if (item.dialogAction === "create_pr") {
217
- await runActionWithPrompt({ action: "create_pr" });
218
- }
219
- },
220
- [
221
- canWriteSourceControl,
222
- environmentId,
223
- openExistingPr,
224
- navigation,
225
- runActionWithPrompt,
226
- threadId,
227
- ],
228
- );
176
+ const onPressMenuItem = async (item: (typeof menuItems)[number]) => {
177
+ if (item.disabled) return;
178
+ if (item.kind === "open_pr") {
179
+ await openExistingPr();
180
+ return;
181
+ }
182
+ if (!canWriteSourceControl) return;
183
+ if (item.dialogAction === "commit") {
184
+ navigation.navigate("GitCommit", {
185
+ environmentId: String(environmentId),
186
+ threadId: String(threadId),
187
+ });
188
+ return;
189
+ }
190
+ if (item.dialogAction === "push") {
191
+ await runActionWithPrompt({ action: "push" });
192
+ return;
193
+ }
194
+ if (item.dialogAction === "create_pr") {
195
+ await runActionWithPrompt({ action: "create_pr" });
196
+ }
197
+ };
198
230
- const rowStatusDetail = useCallback(
231
- (item: (typeof menuItems)[number]): string | undefined => {
232
- const status = gitStatus.data;
233
- if (status == null) {
234
- return undefined;
235
- }
236
- if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
237
- const fileCount = status.workingTree?.files.length ?? 0;
238
- return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
239
- }
240
- if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
241
- const ahead = status.aheadCount ?? 0;
242
- return `${ahead} commit${ahead === 1 ? "" : "s"} ahead`;
243
- }
244
- if (item.kind === "open_pr" && status.pr?.number != null) {
245
- return `PR #${status.pr.number} ${status.pr.state ?? "open"}`;
246
- }
199
+ const rowStatusDetail = (item: (typeof menuItems)[number]): string | undefined => {
200
+ const status = gitStatus.data;
201
+ if (status == null) {
202
return undefined;
248
- },
249
- [gitStatus.data, menuItems],
250
- );
203
+ }
204
+ if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
205
+ const fileCount = status.workingTree?.files.length ?? 0;
206
+ return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
207
+ }
208
+ if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
209
+ const ahead = status.aheadCount ?? 0;
210
+ return `${ahead} commit${ahead === 1 ? "" : "s"} ahead`;
211
+ }
212
+ if (item.kind === "open_pr" && status.pr?.number != null) {
213
+ return `PR #${status.pr.number} ${status.pr.state ?? "open"}`;
214
+ }
215
+ return undefined;
216
+ };
217
218
const behindCount = gitStatus.data?.behindCount ?? 0;
219
220
// Tying RefreshControl to the query's isPending flag left the spinner stuck
221
// (the status query reports pending during quiet background refreshes too).
222
const [isRefreshing, setIsRefreshing] = useState(false);
257
- const handleRefresh = useCallback(async () => {
223
+ const handleRefresh = async () => {
224
setIsRefreshing(true);
259
- try {
260
- await gitActions.refreshSelectedThreadGitStatus();
261
- } finally {
262
- setIsRefreshing(false);
263
- }
264
- }, [gitActions]);
225
+ await gitActions.refreshSelectedThreadGitStatus();
226
+ setIsRefreshing(false);
227
+ };
228
229
const content = (
230
<ScrollView
apps/mobile/src/features/threads/new-task-flow-provider.tsx
+417
-606
@@ -2,7 +2,7 @@ import * as Dialog from "../../components/ui/Dialog";
2
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
3
import { useEnvironmentPresentation } from "../../state/presentation";
4
import { environmentSession } from "../../state/session";
5
-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
+import React, { useEffect, useRef, useState } from "react";
6
7
import type {
8
EnvironmentId,
@@ -259,20 +259,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
259
const { enabled: legacyPlanModeEnabled, loaded: planModePreferenceLoaded } =
260
useLegacyPlanModeState();
261
262
- const projectScopes = useMemo(
263
- () =>
264
- sortHomeProjectScopes({
265
- scopes: buildHomeProjectScopes({
266
- projects,
267
- environmentId: null,
268
- projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
269
- }),
270
- threads,
271
- pendingTasks: [],
272
- projectSortOrder: "updated_at",
273
- }),
274
- [groupingSettings.sidebarProjectGroupingMode, projects, threads],
275
- );
262
+ const projectScopes = sortHomeProjectScopes({
263
+ scopes: buildHomeProjectScopes({
264
+ projects,
265
+ environmentId: null,
266
+ projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
267
+ }),
268
+ threads,
269
+ pendingTasks: [],
270
+ projectSortOrder: "updated_at",
271
+ });
272
273
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
274
null,
@@ -294,7 +290,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
290
const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
291
const editingRevisionRef = useRef(Promise.resolve(0));
292
297
- const reset = useCallback(() => {
293
+ const reset = () => {
294
setSelectedEnvironmentId(null);
295
setSelectedProjectKey(null);
296
setActiveDraftKey(null);
@@ -311,18 +307,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
307
}
308
releaseEditingQueuedMessage(editing.messageId);
309
}
314
- }, []);
310
+ };
311
316
- const projectsForEnvironment = useMemo(
317
- () =>
318
- pipe(
319
- projects,
320
- Arr.filter((project) => project.environmentId === selectedEnvironmentId),
321
- ),
322
- [projects, selectedEnvironmentId],
312
+ const projectsForEnvironment = pipe(
313
+ projects,
314
+ Arr.filter((project) => project.environmentId === selectedEnvironmentId),
315
);
316
325
- const editingPendingProject = useMemo<EnvironmentProject | null>(() => {
317
+ const editingPendingProject = ((): EnvironmentProject | null => {
318
const creation = editingPendingTask?.creation;
319
if (!editingPendingTask || !creation) {
320
return null;
@@ -338,7 +330,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
330
createdAt: editingPendingTask.createdAt,
331
updatedAt: editingPendingTask.createdAt,
332
};
341
- }, [editingPendingTask]);
333
+ })();
334
335
const selectedProject =
336
projectsForEnvironment.find(
@@ -361,16 +353,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
353
isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot);
354
const serverConfigs = useServerConfigs();
355
const { connectedEnvironments } = useRemoteConnectionStatus();
364
- const scratchEnvironments = useMemo(
365
- () =>
366
- connectedEnvironments.filter(
367
- (environment) =>
368
- availableScratchWorkspaceRoot(
369
- environment.connectionState,
370
- serverConfigs.get(environment.environmentId),
371
- ) !== null,
372
- ),
373
- [connectedEnvironments, serverConfigs],
356
+ const scratchEnvironments = connectedEnvironments.filter(
357
+ (environment) =>
358
+ availableScratchWorkspaceRoot(
359
+ environment.connectionState,
360
+ serverConfigs.get(environment.environmentId),
361
+ ) !== null,
362
);
363
364
const selectedRepositoryKey = selectedProject?.repositoryIdentity
@@ -380,7 +368,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
368
// workspaceRoot, and an "" basename would reject every real host below.
369
const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
370
const selectedProjectTitle = selectedProject?.title ?? null;
383
- const environments = useMemo(() => {
371
+ const environments = (() => {
372
if (isScratchDraft) {
373
return scratchEnvironments.map((environment) => ({
374
environmentId: environment.environmentId,
@@ -425,15 +413,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
413
});
414
}
415
return result;
428
- }, [
429
- isScratchDraft,
430
- projects,
431
- savedConnectionsById,
432
- scratchEnvironments,
433
- selectedRepositoryKey,
434
- selectedWorkspaceBasename,
435
- selectedProjectTitle,
436
- ]);
416
+ })();
417
418
const selectedProjectDraftKey = editingPendingTask
419
? pendingTaskDraftKey(editingPendingTask.messageId)
@@ -478,22 +458,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
458
: null,
459
);
460
const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
481
- const t3ProjectFile = useMemo(
482
- () =>
483
- t3ProjectFileData === null || t3ProjectFileData.truncated
484
- ? null
485
- : parseT3ProjectFile(t3ProjectFileData.contents),
486
- [t3ProjectFileData],
487
- );
488
- const projectSettings = useMemo(
489
- () =>
490
- resolveProjectSettings(
491
- selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
492
- selectedProject?.id ?? null,
493
- selectedProject,
494
- t3ProjectFile,
495
- ),
496
- [selectedEnvironmentServerConfig?.settings, selectedProject, t3ProjectFile],
461
+ const t3ProjectFile =
462
+ t3ProjectFileData === null || t3ProjectFileData.truncated
463
+ ? null
464
+ : parseT3ProjectFile(t3ProjectFileData.contents);
465
+ const projectSettings = resolveProjectSettings(
466
+ selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
467
+ selectedProject?.id ?? null,
468
+ selectedProject,
469
+ t3ProjectFile,
470
);
471
const canChooseWorkspace = !isScratchDraft;
472
const selectedProjectHasThreads =
@@ -553,21 +526,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
526
storedStickyModelSelection,
527
selectedProject?.id ?? null,
528
);
556
- const modelOptions = useMemo(
557
- () =>
558
- buildModelOptions(
559
- selectedEnvironmentServerConfig,
560
- draftModelSelection ?? projectDefaultModelSelection ?? stickyModelSelection,
561
- undefined,
562
- selectedProject?.id ?? null,
563
- ),
564
- [
565
- selectedEnvironmentServerConfig,
566
- draftModelSelection,
567
- projectDefaultModelSelection,
568
- stickyModelSelection,
569
- selectedProject?.id,
570
- ],
529
+ const modelOptions = buildModelOptions(
530
+ selectedEnvironmentServerConfig,
531
+ draftModelSelection ?? projectDefaultModelSelection ?? stickyModelSelection,
532
+ undefined,
533
+ selectedProject?.id ?? null,
534
);
535
536
const selectedModel = resolveNewTaskModelSelection({
@@ -587,124 +550,101 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
550
option.selection.instanceId === selectedModel.instanceId &&
551
option.selection.model === selectedModel.model,
552
) ?? null;
590
- const selectedProviderStatus = useMemo(
591
- () =>
592
- selectedEnvironmentServerConfig?.providers.find(
593
- (provider) => provider.instanceId === selectedModel?.instanceId,
594
- ) ?? null,
595
- [selectedEnvironmentServerConfig, selectedModel?.instanceId],
596
- );
553
+ const selectedProviderStatus =
554
+ selectedEnvironmentServerConfig?.providers.find(
555
+ (provider) => provider.instanceId === selectedModel?.instanceId,
556
+ ) ?? null;
557
const planModeEnabled =
558
legacyPlanModeEnabled && selectedProviderStatus?.showInteractionModeToggle !== false;
559
const interactionMode = planModeEnabled
560
? (selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE)
561
: DEFAULT_PROVIDER_INTERACTION_MODE;
602
- const setSelectedModelKey = useCallback(
603
- // Options ride along in the same write: a follow-up setSelectedModelOptions
604
- // call would rebuild the selection from the stale pre-switch model.
605
- (key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => {
606
- if (!key || !selectedProjectDraftKey) {
607
- return;
608
- }
609
- const option = modelOptions.find((candidate) => candidate.key === key);
610
- if (!option) {
611
- return;
612
- }
613
- const selection = withRememberedModelOptions(
614
- options ? { ...option.selection, options } : option.selection,
615
- );
616
- const provider = selectedEnvironmentServerConfig?.providers.find(
617
- (candidate) => candidate.instanceId === selection.instanceId,
618
- );
619
- updateComposerDraftSettings(selectedProjectDraftKey, {
620
- modelSelection: selection,
621
- ...(provider?.showInteractionModeToggle === false
622
- ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
623
- : {}),
624
- });
625
- setStickyComposerModelSelection(selection);
626
- },
627
- [modelOptions, selectedEnvironmentServerConfig, selectedProjectDraftKey],
628
- );
629
- const setSelectedModelOptions = useCallback(
630
- (options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
631
- if (!selectedModel || !selectedProjectDraftKey) {
632
- return;
633
- }
634
- rememberModelOptions(selectedModel.instanceId, selectedModel.model, options ?? []);
635
- const nextSelection: ModelSelection = options
636
- ? { ...selectedModel, options }
637
- : {
638
- instanceId: selectedModel.instanceId,
639
- model: selectedModel.model,
640
- };
641
- updateComposerDraftSettings(selectedProjectDraftKey, {
642
- modelSelection: nextSelection,
643
- });
644
- setStickyComposerModelSelection(nextSelection);
645
- },
646
- [selectedModel, selectedProjectDraftKey],
647
- );
562
+ const setSelectedModelKey = (
563
+ key: string | null,
564
+ options?: ReadonlyArray<ProviderOptionSelection>,
565
+ ) => {
566
+ if (!key || !selectedProjectDraftKey) {
567
+ return;
568
+ }
569
+ const option = modelOptions.find((candidate) => candidate.key === key);
570
+ if (!option) {
571
+ return;
572
+ }
573
+ const selection = withRememberedModelOptions(
574
+ options ? { ...option.selection, options } : option.selection,
575
+ );
576
+ const provider = selectedEnvironmentServerConfig?.providers.find(
577
+ (candidate) => candidate.instanceId === selection.instanceId,
578
+ );
579
+ updateComposerDraftSettings(selectedProjectDraftKey, {
580
+ modelSelection: selection,
581
+ ...(provider?.showInteractionModeToggle === false
582
+ ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
583
+ : {}),
584
+ });
585
+ setStickyComposerModelSelection(selection);
586
+ };
587
+ const setSelectedModelOptions = (options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
588
+ if (!selectedModel || !selectedProjectDraftKey) {
589
+ return;
590
+ }
591
+ rememberModelOptions(selectedModel.instanceId, selectedModel.model, options ?? []);
592
+ const nextSelection: ModelSelection = options
593
+ ? { ...selectedModel, options }
594
+ : {
595
+ instanceId: selectedModel.instanceId,
596
+ model: selectedModel.model,
597
+ };
598
+ updateComposerDraftSettings(selectedProjectDraftKey, {
599
+ modelSelection: nextSelection,
600
+ });
601
+ setStickyComposerModelSelection(nextSelection);
602
+ };
603
649
- const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
650
- const setPrompt = useCallback(
651
- (value: string) => {
652
- if (!selectedProjectDraftKey) {
653
- return;
654
- }
655
- setComposerDraftText(selectedProjectDraftKey, value);
656
- },
657
- [selectedProjectDraftKey],
658
- );
659
- const replaceAttachments = useCallback(
660
- (nextAttachments: ReadonlyArray<DraftComposerAttachment>) => {
661
- if (!selectedProjectDraftKey) {
662
- return;
663
- }
664
- replaceComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
665
- },
666
- [selectedProjectDraftKey],
667
- );
668
- const appendAttachments = useCallback(
669
- (
670
- nextAttachments: ReadonlyArray<DraftComposerAttachment>,
671
- insertion?: ComposerDraftInsertion,
672
- ): number => {
673
- if (!selectedProjectDraftKey) {
674
- return 0;
675
- }
676
- return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments, {
677
- appendReference: true,
678
- insertion,
679
- });
680
- },
681
- [selectedProjectDraftKey],
682
- );
683
- const removeAttachment = useCallback(
684
- (imageId: string) => {
685
- if (!selectedProjectDraftKey) {
686
- return;
687
- }
688
- removeComposerDraftAttachment(selectedProjectDraftKey, imageId);
689
- },
690
- [selectedProjectDraftKey],
691
- );
692
- const clearAttachments = useCallback(() => {
604
+ const providerGroups = groupByProvider(modelOptions);
605
+ const setPrompt = (value: string) => {
606
+ if (!selectedProjectDraftKey) {
607
+ return;
608
+ }
609
+ setComposerDraftText(selectedProjectDraftKey, value);
610
+ };
611
+ const replaceAttachments = (nextAttachments: ReadonlyArray<DraftComposerAttachment>) => {
612
+ if (!selectedProjectDraftKey) {
613
+ return;
614
+ }
615
+ replaceComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
616
+ };
617
+ const appendAttachments = (
618
+ nextAttachments: ReadonlyArray<DraftComposerAttachment>,
619
+ insertion?: ComposerDraftInsertion,
620
+ ): number => {
621
+ if (!selectedProjectDraftKey) {
622
+ return 0;
623
+ }
624
+ return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments, {
625
+ appendReference: true,
626
+ insertion,
627
+ });
628
+ };
629
+ const removeAttachment = (imageId: string) => {
630
+ if (!selectedProjectDraftKey) {
631
+ return;
632
+ }
633
+ removeComposerDraftAttachment(selectedProjectDraftKey, imageId);
634
+ };
635
+ const clearAttachments = () => {
636
if (!selectedProjectDraftKey) {
637
return;
638
}
639
replaceComposerDraftAttachments(selectedProjectDraftKey, []);
697
- }, [selectedProjectDraftKey]);
640
+ };
641
const branchSearchQuery = sanitizeNewRefName(branchQuery);
642
const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
700
- const branchTarget = useMemo(
701
- () => ({
702
- environmentId: selectedProject?.environmentId ?? null,
703
- cwd: selectedProject?.workspaceRoot || null,
704
- query: debouncedBranchQuery,
705
- }),
706
- [debouncedBranchQuery, selectedProject?.environmentId, selectedProject?.workspaceRoot],
707
- );
643
+ const branchTarget = {
644
+ environmentId: selectedProject?.environmentId ?? null,
645
+ cwd: selectedProject?.workspaceRoot || null,
646
+ query: debouncedBranchQuery,
647
+ };
648
const branchState = usePaginatedBranches(branchTarget);
649
const branchSearchIsDebouncing = branchSearchQuery !== debouncedBranchQuery;
650
const branchesLoading =
@@ -713,13 +653,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
653
const hasMoreBranches =
654
branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;
655
const allBranchRefs = branchState.refs;
716
- const availableBranches = useMemo(
717
- () =>
718
- pipe(
719
- allBranchRefs,
720
- Arr.filter((branch) => !branch.isRemote),
721
- ),
722
- [allBranchRefs],
656
+ const availableBranches = pipe(
657
+ allBranchRefs,
658
+ Arr.filter((branch) => !branch.isRemote),
659
);
660
const projectGitStatus = useEnvironmentQuery(
661
branchTarget.environmentId !== null && branchTarget.cwd !== null
@@ -731,153 +667,119 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
667
);
668
const currentCheckoutBranchName = projectGitStatus.data?.refName ?? null;
669
734
- const filteredBranches = useMemo(
735
- () => filterNewTaskBranches(allBranchRefs, branchQuery),
736
- [allBranchRefs, branchQuery],
737
- );
670
+ const filteredBranches = filterNewTaskBranches(allBranchRefs, branchQuery);
671
739
- const carryDraftContentTo = useCallback(
740
- (project: EnvironmentProject) => {
741
- const target = { environmentId: project.environmentId, projectId: project.id };
742
- if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
743
- retargetNewTaskDraft(activeDraftKey, target);
744
- } else if (!editingPendingTaskRef.current) {
745
- setActiveDraftKey(createNewTaskDraft(target));
746
- }
747
- },
748
- [activeDraftKey],
749
- );
672
+ const carryDraftContentTo = (project: EnvironmentProject) => {
673
+ const target = { environmentId: project.environmentId, projectId: project.id };
674
+ if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
675
+ retargetNewTaskDraft(activeDraftKey, target);
676
+ } else if (!editingPendingTaskRef.current) {
677
+ setActiveDraftKey(createNewTaskDraft(target));
678
+ }
679
+ };
680
751
- const setProject = useCallback(
752
- (project: EnvironmentProject) => {
753
- carryDraftContentTo(project);
754
- setSelectedEnvironmentId(project.environmentId);
755
- setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
756
- },
757
- [carryDraftContentTo],
758
- );
681
+ const setProject = (project: EnvironmentProject) => {
682
+ carryDraftContentTo(project);
683
+ setSelectedEnvironmentId(project.environmentId);
684
+ setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
685
+ };
686
760
- const openDraft = useCallback(
761
- (draftKey: string): boolean => {
762
- const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
763
- const stamp = draft?.project;
764
- if (!isNewTaskDraftKey(draftKey) || !stamp) {
765
- return false;
766
- }
767
- // The stamped project must be loaded: selectedProject falls back to
768
- // the environment's first project otherwise, and the draft would be
769
- // sent somewhere the user never chose.
770
- const projectLoaded = projects.some(
771
- (project) =>
772
- project.environmentId === stamp.environmentId && project.id === stamp.projectId,
773
- );
774
- if (!projectLoaded) {
775
- return false;
776
- }
777
- setActiveDraftKey(draftKey);
778
- setSelectedEnvironmentId(stamp.environmentId);
779
- setSelectedProjectKey(scopedProjectKey(stamp.environmentId, stamp.projectId));
780
- return true;
781
- },
782
- [projects],
783
- );
687
+ const openDraft = (draftKey: string): boolean => {
688
+ const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
689
+ const stamp = draft?.project;
690
+ if (!isNewTaskDraftKey(draftKey) || !stamp) {
691
+ return false;
692
+ }
693
+ // The stamped project must be loaded: selectedProject falls back to
694
+ // the environment's first project otherwise, and the draft would be
695
+ // sent somewhere the user never chose.
696
+ const projectLoaded = projects.some(
697
+ (project) => project.environmentId === stamp.environmentId && project.id === stamp.projectId,
698
+ );
699
+ if (!projectLoaded) {
700
+ return false;
701
+ }
702
+ setActiveDraftKey(draftKey);
703
+ setSelectedEnvironmentId(stamp.environmentId);
704
+ setSelectedProjectKey(scopedProjectKey(stamp.environmentId, stamp.projectId));
705
+ return true;
706
+ };
707
785
- const selectEnvironment = useCallback(
786
- (environmentId: EnvironmentId) => {
787
- const match = resolveEnvironmentProjectMatch(
788
- projects.filter((project) => project.environmentId === environmentId),
789
- selectedProject,
790
- );
791
- if (match) {
792
- carryDraftContentTo(match);
793
- }
794
- setSelectedEnvironmentId(environmentId);
795
- setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
796
- },
797
- [projects, selectedProject, carryDraftContentTo],
798
- );
708
+ const selectEnvironment = (environmentId: EnvironmentId) => {
709
+ const match = resolveEnvironmentProjectMatch(
710
+ projects.filter((project) => project.environmentId === environmentId),
711
+ selectedProject,
712
+ );
713
+ if (match) {
714
+ carryDraftContentTo(match);
715
+ }
716
+ setSelectedEnvironmentId(environmentId);
717
+ setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
718
+ };
719
720
const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
721
const [switchingToEnvironmentId, setSwitchingToEnvironmentId] = useState<EnvironmentId | null>(
722
null,
723
);
724
const latestSwitchRef = useRef<object | null>(null);
805
- const switchEnvironment = useCallback(
806
- async (environmentId: EnvironmentId): Promise<boolean> => {
807
- if (environmentId === selectedEnvironmentId) {
808
- latestSwitchRef.current = null;
809
- setSwitchingToEnvironmentId(null);
810
- return true;
811
- }
812
- if (!isScratchDraft) {
813
- selectEnvironment(environmentId);
814
- return true;
815
- }
816
- const request = {};
817
- latestSwitchRef.current = request;
818
- setSwitchingToEnvironmentId(environmentId);
819
- try {
820
- const result = await openScratch({ environmentId, input: {} });
821
- if (latestSwitchRef.current !== request) return false;
822
- if (result._tag === "Success") {
823
- setProject(result.value);
824
- return true;
825
- }
826
- if (!isAtomCommandInterrupted(result)) {
827
- const error = squashAtomCommandFailure(result);
828
- Dialog.alert(
829
- "Could not switch machine",
830
- error instanceof Error
831
- ? error.message
832
- : "The folder for threads without a project could not be created.",
833
- );
834
- }
835
- return false;
836
- } finally {
837
- if (latestSwitchRef.current === request) {
838
- latestSwitchRef.current = null;
839
- setSwitchingToEnvironmentId(null);
840
- }
841
- }
842
- },
843
- [isScratchDraft, openScratch, selectEnvironment, selectedEnvironmentId, setProject],
844
- );
725
+ const switchEnvironment = async (environmentId: EnvironmentId): Promise<boolean> => {
726
+ if (environmentId === selectedEnvironmentId) {
727
+ latestSwitchRef.current = null;
728
+ setSwitchingToEnvironmentId(null);
729
+ return true;
730
+ }
731
+ if (!isScratchDraft) {
732
+ selectEnvironment(environmentId);
733
+ return true;
734
+ }
735
+ const request = {};
736
+ latestSwitchRef.current = request;
737
+ setSwitchingToEnvironmentId(environmentId);
738
+ const result = await openScratch({ environmentId, input: {} });
739
+ if (latestSwitchRef.current !== request) return false;
740
+ latestSwitchRef.current = null;
741
+ setSwitchingToEnvironmentId(null);
742
+ if (result._tag === "Success") {
743
+ setProject(result.value);
744
+ return true;
745
+ }
746
+ if (!isAtomCommandInterrupted(result)) {
747
+ const error = squashAtomCommandFailure(result);
748
+ Dialog.alert(
749
+ "Could not switch machine",
750
+ error instanceof Error
751
+ ? error.message
752
+ : "The folder for threads without a project could not be created.",
753
+ );
754
+ }
755
+ return false;
756
+ };
757
846
- const setWorkspaceMode = useCallback(
847
- (mode: WorkspaceMode) => {
848
- if (!selectedProjectDraftKey) {
849
- return;
850
- }
851
- if (!selectedProject) {
852
- return;
853
- }
854
- const localSelection = resolveNewTaskLocalWorkspaceSelection({
855
- branches: availableBranches,
856
- projectCwd: selectedProject.workspaceRoot,
857
- });
858
- if (mode === "local" && localSelection.awaitsCurrentBranch) {
859
- pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
860
- } else {
861
- pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
862
- }
863
- updateComposerDraftSettings(selectedProjectDraftKey, {
864
- workspaceSelection: {
865
- mode,
866
- branch: mode === "local" ? localSelection.branch : selectedBranchName,
867
- worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
868
- ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
869
- },
870
- });
871
- },
872
- [
873
- availableBranches,
874
- draftStartFromOrigin,
875
- selectedBranchName,
876
- selectedProject,
877
- selectedProjectDraftKey,
878
- selectedWorktreePath,
879
- ],
880
- );
758
+ const setWorkspaceMode = (mode: WorkspaceMode) => {
759
+ if (!selectedProjectDraftKey) {
760
+ return;
761
+ }
762
+ if (!selectedProject) {
763
+ return;
764
+ }
765
+ const localSelection = resolveNewTaskLocalWorkspaceSelection({
766
+ branches: availableBranches,
767
+ projectCwd: selectedProject.workspaceRoot,
768
+ });
769
+ if (mode === "local" && localSelection.awaitsCurrentBranch) {
770
+ pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
771
+ } else {
772
+ pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
773
+ }
774
+ updateComposerDraftSettings(selectedProjectDraftKey, {
775
+ workspaceSelection: {
776
+ mode,
777
+ branch: mode === "local" ? localSelection.branch : selectedBranchName,
778
+ worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
779
+ ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
780
+ },
781
+ });
782
+ };
783
784
useEffect(() => {
785
if (
@@ -913,54 +815,48 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
815
workspaceMode,
816
]);
817
916
- const selectBranch = useCallback(
917
- (branch: VcsRef) => {
918
- if (!selectedProject || !selectedProjectDraftKey) {
919
- return;
920
- }
921
- pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
922
- updateComposerDraftSettings(selectedProjectDraftKey, {
923
- workspaceSelection: {
924
- mode: workspaceMode,
925
- branch: branch.name,
926
- worktreePath: resolveNewTaskBranchWorktreePath({
927
- workspaceMode,
928
- projectCwd: selectedProject.workspaceRoot,
929
- branchWorktreePath: branch.worktreePath,
930
- }),
931
- ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
932
- },
933
- });
934
- },
935
- [draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
936
- );
818
+ const selectBranch = (branch: VcsRef) => {
819
+ if (!selectedProject || !selectedProjectDraftKey) {
820
+ return;
821
+ }
822
+ pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
823
+ updateComposerDraftSettings(selectedProjectDraftKey, {
824
+ workspaceSelection: {
825
+ mode: workspaceMode,
826
+ branch: branch.name,
827
+ worktreePath: resolveNewTaskBranchWorktreePath({
828
+ workspaceMode,
829
+ projectCwd: selectedProject.workspaceRoot,
830
+ branchWorktreePath: branch.worktreePath,
831
+ }),
832
+ ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
833
+ },
834
+ });
835
+ };
836
938
- const setStartFromOrigin = useCallback(
939
- (value: boolean) => {
940
- if (!selectedProjectDraftKey) {
941
- return;
942
- }
943
- updateComposerDraftSettings(selectedProjectDraftKey, {
944
- workspaceSelection: {
945
- mode: workspaceMode,
946
- branch: selectedBranchName,
947
- worktreePath: selectedWorktreePath,
948
- startFromOrigin: value,
949
- },
950
- });
951
- },
952
- [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, workspaceMode],
953
- );
837
+ const setStartFromOrigin = (value: boolean) => {
838
+ if (!selectedProjectDraftKey) {
839
+ return;
840
+ }
841
+ updateComposerDraftSettings(selectedProjectDraftKey, {
842
+ workspaceSelection: {
843
+ mode: workspaceMode,
844
+ branch: selectedBranchName,
845
+ worktreePath: selectedWorktreePath,
846
+ startFromOrigin: value,
847
+ },
848
+ });
849
+ };
850
851
const refreshBranches = branchState.refresh;
852
const loadMoreBranches = branchState.loadNext;
957
- const loadBranches = useCallback(() => {
853
+ const loadBranches = () => {
854
if (!selectedProject) {
855
return;
856
}
857
setPendingConnectionError(null);
858
refreshBranches();
963
- }, [refreshBranches, selectedProject]);
859
+ };
860
861
useEffect(() => {
862
if (
@@ -997,26 +893,20 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
893
workspaceMode,
894
]);
895
1000
- const setRuntimeMode = useCallback(
1001
- (value: RuntimeMode) => {
1002
- if (selectedProjectDraftKey) {
1003
- updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
1004
- }
1005
- },
1006
- [selectedProjectDraftKey],
1007
- );
1008
- const setInteractionMode = useCallback(
1009
- (value: ProviderInteractionMode) => {
1010
- if (selectedProjectDraftKey) {
1011
- updateComposerDraftSettings(selectedProjectDraftKey, {
1012
- interactionMode: resolveProviderInteractionMode(selectedProviderStatus, value),
1013
- });
1014
- }
1015
- },
1016
- [selectedProjectDraftKey, selectedProviderStatus],
1017
- );
896
+ const setRuntimeMode = (value: RuntimeMode) => {
897
+ if (selectedProjectDraftKey) {
898
+ updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
899
+ }
900
+ };
901
+ const setInteractionMode = (value: ProviderInteractionMode) => {
902
+ if (selectedProjectDraftKey) {
903
+ updateComposerDraftSettings(selectedProjectDraftKey, {
904
+ interactionMode: resolveProviderInteractionMode(selectedProviderStatus, value),
905
+ });
906
+ }
907
+ };
908
1019
- const beginEditingPendingTask = useCallback((messageId: string): boolean => {
909
+ const beginEditingPendingTask = (messageId: string): boolean => {
910
const message = findQueuedPendingTask(messageId);
911
if (!message?.creation) {
912
return false;
@@ -1047,101 +937,85 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
937
setEditingPendingTask(message);
938
holdEditingQueuedMessage(message.messageId);
939
return true;
1050
- }, []);
940
+ };
941
1052
- const buildPendingTaskMessage = useCallback(
1053
- (
1054
- metadata: TurnCommandMetadata,
1055
- options?: { readonly currentCheckoutBranch?: string | null },
1056
- ): QueuedThreadMessage | null => {
1057
- if (!selectedProject || !selectedProjectDraftKey) {
1058
- return null;
1059
- }
1060
- const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
1061
- const text = draft.text.trim();
1062
- const draftModelSelection =
1063
- resolveSelectableModelSelection(
1064
- selectedEnvironmentServerConfig,
1065
- draft.modelSelection ?? null,
1066
- selectedProject.id,
1067
- ) ?? selectedModel;
1068
- if ((text.length === 0 && draft.attachments.length === 0) || !draftModelSelection) {
1069
- return null;
1070
- }
1071
- const workspaceSelection = canChooseWorkspace ? draft.workspaceSelection : undefined;
1072
- const mode = workspaceSelection?.mode ?? workspaceMode;
1073
- // When the selection is the stand-in built from the queued snapshot,
1074
- // persist the original (possibly absent) snapshot values — the
1075
- // stand-in's placeholder title/workspaceRoot must never be written back
1076
- // as if they were real project metadata.
1077
- const usingPendingSnapshot = selectedProject === editingPendingProject;
1078
- const projectTitle = usingPendingSnapshot
1079
- ? editingPendingTask?.creation?.projectTitle
1080
- : selectedProject.title;
1081
- const projectCwd = usingPendingSnapshot
1082
- ? editingPendingTask?.creation?.projectCwd
1083
- : selectedProject.workspaceRoot;
1084
- return {
1085
- environmentId: selectedProject.environmentId,
1086
- threadId: ThreadId.make(metadata.threadId),
1087
- messageId: MessageId.make(metadata.messageId),
1088
- commandId: CommandId.make(metadata.commandId),
1089
- text,
1090
- attachments: draft.attachments,
1091
- context: draft.context,
1092
- modelSelection: draftModelSelection,
1093
- runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
1094
- interactionMode: resolvePendingTaskInteractionMode({
1095
- preferenceLoaded: planModePreferenceLoaded,
1096
- planModeEnabled: legacyPlanModeEnabled,
1097
- draftInteractionMode: draft.interactionMode,
1098
- queuedInteractionMode: editingPendingTask?.interactionMode,
1099
- provider: selectedEnvironmentServerConfig?.providers.find(
1100
- (candidate) => candidate.instanceId === draftModelSelection.instanceId,
1101
- ),
1102
- }),
1103
- creation: {
1104
- projectId: selectedProject.id,
1105
- ...(projectTitle !== undefined ? { projectTitle } : {}),
1106
- ...(projectCwd !== undefined ? { projectCwd } : {}),
942
+ const buildPendingTaskMessage = (
943
+ metadata: TurnCommandMetadata,
944
+ options?: { readonly currentCheckoutBranch?: string | null },
945
+ ): QueuedThreadMessage | null => {
946
+ if (!selectedProject || !selectedProjectDraftKey) {
947
+ return null;
948
+ }
949
+ const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
950
+ const text = draft.text.trim();
951
+ const draftModelSelection =
952
+ resolveSelectableModelSelection(
953
+ selectedEnvironmentServerConfig,
954
+ draft.modelSelection ?? null,
955
+ selectedProject.id,
956
+ ) ?? selectedModel;
957
+ if ((text.length === 0 && draft.attachments.length === 0) || !draftModelSelection) {
958
+ return null;
959
+ }
960
+ const workspaceSelection = canChooseWorkspace ? draft.workspaceSelection : undefined;
961
+ const mode = workspaceSelection?.mode ?? workspaceMode;
962
+ // When the selection is the stand-in built from the queued snapshot,
963
+ // persist the original (possibly absent) snapshot values — the
964
+ // stand-in's placeholder title/workspaceRoot must never be written back
965
+ // as if they were real project metadata.
966
+ const usingPendingSnapshot = selectedProject === editingPendingProject;
967
+ const projectTitle = usingPendingSnapshot
968
+ ? editingPendingTask?.creation?.projectTitle
969
+ : selectedProject.title;
970
+ const projectCwd = usingPendingSnapshot
971
+ ? editingPendingTask?.creation?.projectCwd
972
+ : selectedProject.workspaceRoot;
973
+ return {
974
+ environmentId: selectedProject.environmentId,
975
+ threadId: ThreadId.make(metadata.threadId),
976
+ messageId: MessageId.make(metadata.messageId),
977
+ commandId: CommandId.make(metadata.commandId),
978
+ text,
979
+ attachments: draft.attachments,
980
+ context: draft.context,
981
+ modelSelection: draftModelSelection,
982
+ runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
983
+ interactionMode: resolvePendingTaskInteractionMode({
984
+ preferenceLoaded: planModePreferenceLoaded,
985
+ planModeEnabled: legacyPlanModeEnabled,
986
+ draftInteractionMode: draft.interactionMode,
987
+ queuedInteractionMode: editingPendingTask?.interactionMode,
988
+ provider: selectedEnvironmentServerConfig?.providers.find(
989
+ (candidate) => candidate.instanceId === draftModelSelection.instanceId,
990
+ ),
991
+ }),
992
+ creation: {
993
+ projectId: selectedProject.id,
994
+ ...(projectTitle !== undefined ? { projectTitle } : {}),
995
+ ...(projectCwd !== undefined ? { projectCwd } : {}),
996
+ workspaceMode: mode,
997
+ ...(mode === "worktree" && workspaceSelection?.pullRequestReference
998
+ ? { pullRequestReference: workspaceSelection.pullRequestReference }
999
+ : {}),
1000
+ // An explicit picker choice wins. Otherwise only a task sending now
1001
+ // records the current checkout: a queued local task drains days
1002
+ // later against whatever is checked out then, so a queue-time
1003
+ // guess would pin a stale label to a thread that ran somewhere else.
1004
+ branch: resolveProjectThreadCreationBranch({
1005
workspaceMode: mode,
1108
- ...(mode === "worktree" && workspaceSelection?.pullRequestReference
1109
- ? { pullRequestReference: workspaceSelection.pullRequestReference }
1110
- : {}),
1111
- // An explicit picker choice wins. Otherwise only a task sending now
1112
- // records the current checkout: a queued local task drains days
1113
- // later against whatever is checked out then, so a queue-time
1114
- // guess would pin a stale label to a thread that ran somewhere else.
1115
- branch: resolveProjectThreadCreationBranch({
1116
- workspaceMode: mode,
1117
- selectedBranch: workspaceSelection?.branch ?? null,
1118
- currentCheckoutBranch: options?.currentCheckoutBranch ?? null,
1119
- }),
1120
- worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
1121
- ...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
1122
- ? { startFromOrigin: true }
1123
- : {}),
1124
- },
1125
- createdAt: metadata.createdAt,
1126
- };
1127
- },
1128
- [
1129
- canChooseWorkspace,
1130
- defaultRuntimeMode,
1131
- editingPendingProject,
1132
- editingPendingTask,
1133
- selectedEnvironmentServerConfig,
1134
- selectedModel,
1135
- selectedProject,
1136
- selectedProjectDraftKey,
1137
- legacyPlanModeEnabled,
1138
- planModePreferenceLoaded,
1139
- startFromOrigin,
1140
- workspaceMode,
1141
- ],
1142
- );
1006
+ selectedBranch: workspaceSelection?.branch ?? null,
1007
+ currentCheckoutBranch: options?.currentCheckoutBranch ?? null,
1008
+ }),
1009
+ worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
1010
+ ...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
1011
+ ? { startFromOrigin: true }
1012
+ : {}),
1013
+ },
1014
+ createdAt: metadata.createdAt,
1015
+ };
1016
+ };
1017
1144
- const finishEditingPendingTask = useCallback(() => {
1018
+ const finishEditingPendingTask = () => {
1019
const editing = editingPendingTaskRef.current;
1020
editingPendingTaskRef.current = null;
1021
if (editing) {
@@ -1153,7 +1027,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
1027
scheduleUnusedComposerAttachmentCleanup(editing.attachments);
1028
}
1029
setEditingPendingTask(null);
1156
- }, []);
1030
+ };
1031
1032
// If the queued task disappears mid-edit (deleted from the list, or
1033
// delivered), end the editing session immediately without saving — a later
@@ -1227,9 +1101,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
1101
});
1102
};
1103
}, [buildPendingTaskMessage]);
1230
- const cancelEditingPendingTask = useCallback(() => {
1104
+ const cancelEditingPendingTask = () => {
1105
editingFlushRef.current?.();
1232
- }, []);
1106
+ };
1107
useEffect(
1108
() => () => {
1109
editingFlushRef.current?.();
@@ -1237,133 +1111,70 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
1111
[],
1112
);
1113
1240
- const value = useMemo<NewTaskFlowContextValue>(
1241
- () => ({
1242
- projectScopes,
1243
- selectedEnvironmentId,
1244
- selectedProjectKey,
1245
- selectedModelKey,
1246
- workspaceMode,
1247
- canChooseWorkspace,
1248
- selectedBranchName,
1249
- selectedWorktreePath,
1250
- startFromOrigin,
1251
- draftKey: selectedProjectDraftKey,
1252
- pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
1253
- editingPendingTask,
1254
- prompt,
1255
- attachments,
1256
- submitting,
1257
- branchQuery,
1258
- branchesLoading,
1259
- branchesError: branchState.error,
1260
- branchesFetchingNextPage,
1261
- hasMoreBranches,
1262
- availableBranches,
1263
- currentCheckoutBranchName,
1264
- runtimeMode,
1265
- interactionMode,
1266
- planModeEnabled,
1267
- expandedProvider,
1268
- environments,
1269
- selectedProject,
1270
- isScratchDraft,
1271
- modelOptions,
1272
- selectedModel,
1273
- selectedModelOption,
1274
- selectedProviderStatus,
1275
- providerGroups,
1276
- filteredBranches,
1277
- reset,
1278
- setProject,
1279
- openDraft,
1280
- selectEnvironment,
1281
- switchEnvironment,
1282
- switchingToEnvironmentId,
1283
- setSelectedModelKey,
1284
- setWorkspaceMode,
1285
- selectBranch,
1286
- setStartFromOrigin,
1287
- beginEditingPendingTask,
1288
- finishEditingPendingTask,
1289
- cancelEditingPendingTask,
1290
- buildPendingTaskMessage,
1291
- setPrompt,
1292
- replaceAttachments,
1293
- appendAttachments,
1294
- removeAttachment,
1295
- clearAttachments,
1296
- setSubmitting,
1297
- setBranchQuery,
1298
- loadBranches,
1299
- loadMoreBranches,
1300
- setRuntimeMode,
1301
- setInteractionMode,
1302
- setSelectedModelOptions,
1303
- setExpandedProvider,
1304
- }),
1305
- [
1306
- attachments,
1307
- availableBranches,
1308
- beginEditingPendingTask,
1309
- branchQuery,
1310
- branchesLoading,
1311
- branchState.error,
1312
- branchesFetchingNextPage,
1313
- buildPendingTaskMessage,
1314
- cancelEditingPendingTask,
1315
- currentCheckoutBranchName,
1316
- editingPendingTask,
1317
- environments,
1318
- expandedProvider,
1319
- filteredBranches,
1320
- finishEditingPendingTask,
1321
- interactionMode,
1322
- isScratchDraft,
1323
- planModeEnabled,
1324
- loadBranches,
1325
- loadMoreBranches,
1326
- projectScopes,
1327
- modelOptions,
1328
- prompt,
1329
- providerGroups,
1330
- replaceAttachments,
1331
- reset,
1332
- runtimeMode,
1333
- selectedBranchName,
1334
- hasMoreBranches,
1335
- selectedEnvironmentId,
1336
- selectedModel,
1337
- selectedModelKey,
1338
- selectedModelOption,
1339
- selectedProjectDraftKey,
1340
- selectedProviderStatus,
1341
- setSelectedModelOptions,
1342
- selectedProject,
1343
- selectedProjectDraft.workspaceSelection?.pullRequestReference,
1344
- selectedProjectKey,
1345
- selectedWorktreePath,
1346
- setProject,
1347
- openDraft,
1348
- selectBranch,
1349
- selectEnvironment,
1350
- switchEnvironment,
1351
- switchingToEnvironmentId,
1352
- setInteractionMode,
1353
- setPrompt,
1354
- setRuntimeMode,
1355
- setSelectedModelKey,
1356
- setStartFromOrigin,
1357
- setWorkspaceMode,
1358
- startFromOrigin,
1359
- submitting,
1360
- workspaceMode,
1361
- canChooseWorkspace,
1362
- appendAttachments,
1363
- clearAttachments,
1364
- removeAttachment,
1365
- ],
1366
- );
1114
+ const value = {
1115
+ projectScopes,
1116
+ selectedEnvironmentId,
1117
+ selectedProjectKey,
1118
+ selectedModelKey,
1119
+ workspaceMode,
1120
+ canChooseWorkspace,
1121
+ selectedBranchName,
1122
+ selectedWorktreePath,
1123
+ startFromOrigin,
1124
+ draftKey: selectedProjectDraftKey,
1125
+ pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
1126
+ editingPendingTask,
1127
+ prompt,
1128
+ attachments,
1129
+ submitting,
1130
+ branchQuery,
1131
+ branchesLoading,
1132
+ branchesError: branchState.error,
1133
+ branchesFetchingNextPage,
1134
+ hasMoreBranches,
1135
+ availableBranches,
1136
+ currentCheckoutBranchName,
1137
+ runtimeMode,
1138
+ interactionMode,
1139
+ planModeEnabled,
1140
+ expandedProvider,
1141
+ environments,
1142
+ selectedProject,
1143
+ isScratchDraft,
1144
+ modelOptions,
1145
+ selectedModel,
1146
+ selectedModelOption,
1147
+ selectedProviderStatus,
1148
+ providerGroups,
1149
+ filteredBranches,
1150
+ reset,
1151
+ setProject,
1152
+ openDraft,
1153
+ selectEnvironment,
1154
+ switchEnvironment,
1155
+ switchingToEnvironmentId,
1156
+ setSelectedModelKey,
1157
+ setWorkspaceMode,
1158
+ selectBranch,
1159
+ setStartFromOrigin,
1160
+ beginEditingPendingTask,
1161
+ finishEditingPendingTask,
1162
+ cancelEditingPendingTask,
1163
+ buildPendingTaskMessage,
1164
+ setPrompt,
1165
+ replaceAttachments,
1166
+ appendAttachments,
1167
+ removeAttachment,
1168
+ clearAttachments,
1169
+ setSubmitting,
1170
+ setBranchQuery,
1171
+ loadBranches,
1172
+ loadMoreBranches,
1173
+ setRuntimeMode,
1174
+ setInteractionMode,
1175
+ setSelectedModelOptions,
1176
+ setExpandedProvider,
1177
+ } satisfies NewTaskFlowContextValue;
1178
1179
return <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>;
1180
}
apps/mobile/src/features/threads/thread-work-log.tsx
+69
-96
@@ -21,12 +21,9 @@ import type { LegendListRef } from "@legendapp/list/react-native";
21
import { AnimatedLegendList } from "@legendapp/list/reanimated";
22
import { StackActions, useIsFocused, useNavigation } from "@react-navigation/native";
23
import {
24
- memo,
25
- useCallback,
24
useEffect,
25
useId,
26
useLayoutEffect,
29
- useMemo,
27
useRef,
28
useState,
29
type ComponentProps,
@@ -493,37 +490,22 @@ interface ThreadWorkLogProps {
490
}
491
492
export function ThreadWorkLog(props: ThreadWorkLogProps) {
496
- const renderRow = useCallback(
497
- (row: ThreadFeedActivity) => (
498
- <ThreadWorkLogRow
499
- key={row.id}
500
- row={row}
501
- anchorKey={props.anchorKey}
502
- copied={props.copiedRowId === row.id}
503
- expanded={props.expandedRows[row.id] ?? false}
504
- environmentId={props.environmentId}
505
- iconSubtleColor={props.iconSubtleColor}
506
- onCopyRow={props.onCopyRow}
507
- onToggleRow={props.onToggleRow}
508
- renderImage={props.renderImage}
509
- renderReasoning={props.renderReasoning}
510
- onPressPreview={props.onPressPreview}
511
- themeAppearance={props.themeAppearance}
512
- />
513
- ),
514
- [
515
- props.anchorKey,
516
- props.copiedRowId,
517
- props.expandedRows,
518
- props.environmentId,
519
- props.iconSubtleColor,
520
- props.onCopyRow,
521
- props.onToggleRow,
522
- props.renderImage,
523
- props.renderReasoning,
524
- props.onPressPreview,
525
- props.themeAppearance,
526
- ],
493
+ const renderRow = (row: ThreadFeedActivity) => (
494
+ <ThreadWorkLogRow
495
+ key={row.id}
496
+ row={row}
497
+ anchorKey={props.anchorKey}
498
+ copied={props.copiedRowId === row.id}
499
+ expanded={props.expandedRows[row.id] ?? false}
500
+ environmentId={props.environmentId}
501
+ iconSubtleColor={props.iconSubtleColor}
502
+ onCopyRow={props.onCopyRow}
503
+ onToggleRow={props.onToggleRow}
504
+ renderImage={props.renderImage}
505
+ renderReasoning={props.renderReasoning}
506
+ onPressPreview={props.onPressPreview}
507
+ themeAppearance={props.themeAppearance}
508
+ />
509
);
510
511
if (props.activities.length === 0) {
@@ -608,7 +590,7 @@ function ThreadWorkGroupList(props: {
590
);
591
const height = Math.min(contentHeight, WORK_GROUP_MAX_HEIGHT);
592
const scrollOffset = useSharedValue(initialPosition?.scrollOffset ?? 0);
611
- const sharedValues = useMemo(() => ({ scrollOffset }), [scrollOffset]);
593
+ const sharedValues = { scrollOffset };
594
595
const topFadeStyle = useAnimatedStyle(() => ({
596
opacity: Math.min(1, Math.max(0, scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT),
@@ -619,7 +601,7 @@ function ThreadWorkGroupList(props: {
601
Math.max(0, contentHeight - height - scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT,
602
),
603
}));
622
- const rememberPosition = useCallback(() => {
604
+ const rememberPosition = () => {
605
if (!loadedRef.current) return;
606
const state = listRef.current?.getState();
607
const position = state && resolveWorkGroupScrollAnchor(state);
@@ -628,8 +610,8 @@ function ThreadWorkGroupList(props: {
610
...position,
611
contentHeight: state.contentLength,
612
});
631
- }, [props.groupId, props.scrollPositions]);
632
- const finishPendingAppend = useCallback(() => {
613
+ };
614
+ const finishPendingAppend = () => {
615
const targetHeight = pendingAppendHeightRef.current;
616
const state = listRef.current?.getState();
617
if (
@@ -641,45 +623,42 @@ function ThreadWorkGroupList(props: {
623
pendingAppendHeightRef.current = null;
624
void listRef.current?.scrollToEnd({ animated: false });
625
}
644
- }, []);
645
- const onContentSizeChange = useCallback(
646
- (nextHeight: number) => {
647
- const previous = previousContent.current;
648
- const detailsChanged = previous.expandedRows !== props.expandedRows;
649
- const followAppend =
650
- loadedRef.current &&
651
- shouldFollowThreadWorkGroupAppend({
652
- previousRows: previous.rows,
653
- rows: props.activities,
654
- previousContentHeight: previous.height,
655
- contentHeight: nextHeight,
656
- viewportHeight: Math.min(previous.height, WORK_GROUP_MAX_HEIGHT),
657
- scrollOffset: scrollOffset.value,
658
- detailsChanged,
659
- userScrolling: userScrollingRef.current,
660
- });
661
- previousContent.current = {
626
+ };
627
+ const onContentSizeChange = (nextHeight: number) => {
628
+ const previous = previousContent.current;
629
+ const detailsChanged = previous.expandedRows !== props.expandedRows;
630
+ const followAppend =
631
+ loadedRef.current &&
632
+ shouldFollowThreadWorkGroupAppend({
633
+ previousRows: previous.rows,
634
rows: props.activities,
663
- height: nextHeight,
664
- expandedRows: props.expandedRows,
665
- };
666
- setMeasuredContent((current) =>
667
- current.height === nextHeight && current.rowCount === props.activities.length
668
- ? current
669
- : { height: nextHeight, rowCount: props.activities.length },
670
- );
671
- if (followAppend) {
672
- pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
673
- } else if (detailsChanged || userScrollingRef.current || previous.rows !== props.activities) {
674
- pendingAppendHeightRef.current = null;
675
- } else if (pendingAppendHeightRef.current !== null) {
676
- pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
677
- }
678
- finishPendingAppend();
679
- rememberPosition();
680
- },
681
- [props.activities, props.expandedRows, scrollOffset, finishPendingAppend, rememberPosition],
682
- );
635
+ previousContentHeight: previous.height,
636
+ contentHeight: nextHeight,
637
+ viewportHeight: Math.min(previous.height, WORK_GROUP_MAX_HEIGHT),
638
+ scrollOffset: scrollOffset.value,
639
+ detailsChanged,
640
+ userScrolling: userScrollingRef.current,
641
+ });
642
+ previousContent.current = {
643
+ rows: props.activities,
644
+ height: nextHeight,
645
+ expandedRows: props.expandedRows,
646
+ };
647
+ setMeasuredContent((current) =>
648
+ current.height === nextHeight && current.rowCount === props.activities.length
649
+ ? current
650
+ : { height: nextHeight, rowCount: props.activities.length },
651
+ );
652
+ if (followAppend) {
653
+ pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
654
+ } else if (detailsChanged || userScrollingRef.current || previous.rows !== props.activities) {
655
+ pendingAppendHeightRef.current = null;
656
+ } else if (pendingAppendHeightRef.current !== null) {
657
+ pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
658
+ }
659
+ finishPendingAppend();
660
+ rememberPosition();
661
+ };
662
// The native ScrollView reports its content size a frame or more after
663
// LegendList has laid the rows out, so a detail toggle rendered the group
664
// at its old height while the rows below already moved. Read the size
@@ -689,7 +668,7 @@ function ThreadWorkGroupList(props: {
668
useLayoutEffect(() => {
669
onContentSizeChangeRef.current = onContentSizeChange;
670
}, [onContentSizeChange]);
692
- const subscribeToContentSize = useCallback((list: LegendListRef | null) => {
671
+ const subscribeToContentSize = (list: LegendListRef | null) => {
672
listRef.current = list;
673
if (!list) return;
674
const unsubscribe = list.getState().listen("totalSize", () => {
@@ -697,21 +676,15 @@ function ThreadWorkGroupList(props: {
676
});
677
onContentSizeChangeRef.current(list.getState().contentLength);
678
return unsubscribe;
700
- }, []);
701
- const getFixedItemSize = useCallback(
702
- (row: ThreadFeedActivity, index: number) =>
703
- props.expandedRows[row.id] || props.rowSizing.fixedRowHeight === undefined
704
- ? undefined
705
- : props.rowSizing.fixedRowHeight + (index < props.activities.length - 1 ? WORK_ROW_GAP : 0),
706
- [props.activities.length, props.expandedRows, props.rowSizing.fixedRowHeight],
707
- );
708
- const renderItem = useCallback(
709
- ({ item, index }: { item: ThreadFeedActivity; index: number }) => (
710
- <View className={index < props.activities.length - 1 ? "pb-px" : undefined}>
711
- {props.renderRow(item)}
712
- </View>
713
- ),
714
- [props.activities.length, props.renderRow],
679
+ };
680
+ const getFixedItemSize = (row: ThreadFeedActivity, index: number) =>
681
+ props.expandedRows[row.id] || props.rowSizing.fixedRowHeight === undefined
682
+ ? undefined
683
+ : props.rowSizing.fixedRowHeight + (index < props.activities.length - 1 ? WORK_ROW_GAP : 0);
684
+ const renderItem = ({ item, index }: { item: ThreadFeedActivity; index: number }) => (
685
+ <View className={index < props.activities.length - 1 ? "pb-px" : undefined}>
686
+ {props.renderRow(item)}
687
+ </View>
688
);
689
690
return (
@@ -877,7 +850,7 @@ function ReplCodeText({
850
);
851
}
852
880
-const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
853
+const ThreadWorkLogRow = function ThreadWorkLogRow(
854
props: Omit<
855
ThreadWorkLogProps,
856
| "continuesWorkLog"
@@ -1293,7 +1266,7 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
1266
) : null}
1267
</Animated.View>
1268
);
1296
-});
1269
+};
1270
1271
export function ThreadWorkGroupToggle(props: {
1272
readonly environmentId: EnvironmentId;
@@ -1389,7 +1362,7 @@ export function ThreadWorkGroupToggle(props: {
1362
);
1363
}
1364
1392
-export const ThreadAgentSpawnCard = memo(function ThreadAgentSpawnCard(props: {
1365
+export const ThreadAgentSpawnCard = function ThreadAgentSpawnCard(props: {
1366
readonly summary: AgentSpawnSummary;
1367
readonly expanded: boolean;
1368
readonly iconSubtleColor: ColorValue;
@@ -1498,7 +1471,7 @@ export const ThreadAgentSpawnCard = memo(function ThreadAgentSpawnCard(props: {
1471
</Pressable>
1472
</Animated.View>
1473
);
1501
-});
1474
+};
1475
1476
export function ThreadThinkingRow(props: {
1477
readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
apps/mobile/src/features/threads/use-composer-command-menu.ts
+84
-119
@@ -45,7 +45,7 @@ import {
45
resolveProviderSkillsForCwd,
46
resolveProviderSlashCommandsForCwd,
47
} from "@t3tools/client-runtime/providerSkills";
48
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
48
+import { useEffect, useRef, useState } from "react";
49
50
import type { ComposerEditorSelection } from "../../components/ComposerEditor";
51
import { serverEnvironment } from "../../state/server";
@@ -206,9 +206,9 @@ export function useComposerCommandMenu({
206
}) {
207
const [selection, setSelection] = useState(() => composerSelectionAtEnd(draftMessage));
208
const previousOwnerKeyRef = useRef(ownerKey);
209
- const onSelectionChange = useCallback((nextSelection: ComposerEditorSelection) => {
209
+ const onSelectionChange = (nextSelection: ComposerEditorSelection) => {
210
setSelection(nextSelection);
211
- }, []);
211
+ };
212
useEffect(() => {
213
const inserted = ownerKey ? readComposerDraftSelection(ownerKey, draftMessage) : null;
214
if (inserted) {
@@ -233,11 +233,9 @@ export function useComposerCommandMenu({
233
setSelection(composerSelectionAtEnd(draftMessage));
234
}, [draftMessage, ownerKey]);
235
236
- const skills = useMemo(
237
- () =>
238
- selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd) : [],
239
- [projectCwd, selectedProviderStatus],
240
- );
236
+ const skills = selectedProviderStatus
237
+ ? resolveProviderSkillsForCwd(selectedProviderStatus, projectCwd)
238
+ : [];
239
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
240
reportFailure: false,
241
});
@@ -334,12 +332,12 @@ export function useComposerCommandMenu({
332
workspaceRefreshRetry,
333
]);
334
337
- const trigger = useMemo(() => {
335
+ const trigger = (() => {
336
if (!enabled || selection.start !== selection.end) {
337
return null;
338
}
339
return detectComposerTrigger(draftMessage, selection.end);
342
- }, [draftMessage, enabled, selection]);
340
+ })();
341
const pathSearch = useComposerPathSearch({
342
environmentId,
343
cwd: trigger?.kind === "path" ? projectCwd : null,
@@ -353,7 +351,7 @@ export function useComposerCommandMenu({
351
query: trigger?.kind === "pull-request" ? trigger.query : null,
352
});
353
356
- const items = useMemo<ComposerCommandItem[]>(() => {
354
+ const items = ((): ComposerCommandItem[] => {
355
if (!trigger) return [];
356
357
if (trigger.kind === "pull-request") {
@@ -521,132 +519,99 @@ export function useComposerCommandMenu({
519
}
520
521
return [];
524
- }, [
525
- currentThreadId,
526
- environmentId,
527
- threadShells,
528
- hasThread,
529
- hasCompactableConversation,
530
- onUpdateInteractionMode,
531
- pathSearch.entries,
532
- pullRequestSearch.entries,
533
- projectCwd,
534
- selectedProviderStatus,
535
- skills,
536
- trigger,
537
- offersUsageLimits,
538
- ]);
522
+ })();
523
540
- const onSelect = useCallback(
541
- (item: ComposerCommandItem) => {
542
- if (!trigger) return;
543
- if (item.type === "thread") {
544
- if (!ownerKey || trigger.kind !== "path") return;
545
- const shell = threadShells.find(
546
- (candidate) =>
547
- candidate.environmentId === item.thread.environmentId &&
548
- candidate.id === item.thread.threadId,
549
- );
550
- if (!shell) return;
551
- const record = threadComposerContext(item.thread, shell.title);
552
- const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? [];
553
- const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId);
554
- if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) {
555
- Dialog.alert(
556
- "Too many context items",
557
- "Remove some context from the draft and try again.",
558
- );
559
- return;
560
- }
561
- const result = replaceTextRange(
562
- draftMessage,
563
- trigger.rangeStart,
564
- trigger.rangeEnd,
565
- `${formatComposerContextReference(record)} `,
566
- );
567
- onChangeDraftMessage(result.text);
568
- if (!alreadyAttached) {
569
- const draft = getComposerDraftSnapshot(ownerKey);
570
- setComposerDraftContext(ownerKey, {
571
- version: 1,
572
- records: [...(draft.context?.records ?? []), record],
573
- });
574
- }
575
- setSelection({ start: result.cursor, end: result.cursor });
524
+ const onSelect = (item: ComposerCommandItem) => {
525
+ if (!trigger) return;
526
+ if (item.type === "thread") {
527
+ if (!ownerKey || trigger.kind !== "path") return;
528
+ const shell = threadShells.find(
529
+ (candidate) =>
530
+ candidate.environmentId === item.thread.environmentId &&
531
+ candidate.id === item.thread.threadId,
532
+ );
533
+ if (!shell) return;
534
+ const record = threadComposerContext(item.thread, shell.title);
535
+ const existing = getComposerDraftSnapshot(ownerKey).context?.records ?? [];
536
+ const alreadyAttached = existing.some((entry) => entry.contextId === record.contextId);
537
+ if (!alreadyAttached && existing.length >= COMPOSER_CONTEXT_MAX_RECORDS) {
538
+ Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
539
return;
540
}
578
- if (item.type === "pull-request") {
579
- if (
580
- !ownerKey ||
581
- trigger.kind !== "pull-request" ||
582
- !items.some((candidate) => candidate.id === item.id)
583
- )
584
- return;
585
- const record = pullRequestComposerContext(item.pullRequest, uuidv4());
586
- if (
587
- (getComposerDraftSnapshot(ownerKey).context?.records.length ?? 0) >=
588
- COMPOSER_CONTEXT_MAX_RECORDS
589
- ) {
590
- Dialog.alert(
591
- "Too many context items",
592
- "Remove some context from the draft and try again.",
593
- );
594
- return;
595
- }
596
- const result = replaceTextRange(
597
- draftMessage,
598
- trigger.rangeStart,
599
- trigger.rangeEnd,
600
- `${formatComposerContextReference(record)} `,
601
- );
602
- onChangeDraftMessage(result.text);
541
+ const result = replaceTextRange(
542
+ draftMessage,
543
+ trigger.rangeStart,
544
+ trigger.rangeEnd,
545
+ `${formatComposerContextReference(record)} `,
546
+ );
547
+ onChangeDraftMessage(result.text);
548
+ if (!alreadyAttached) {
549
const draft = getComposerDraftSnapshot(ownerKey);
550
setComposerDraftContext(ownerKey, {
551
version: 1,
552
records: [...(draft.context?.records ?? []), record],
553
});
608
- setSelection({ start: result.cursor, end: result.cursor });
609
- return;
554
}
611
-
555
+ setSelection({ start: result.cursor, end: result.cursor });
556
+ return;
557
+ }
558
+ if (item.type === "pull-request") {
559
if (
613
- item.type === "provider-slash-command" &&
614
- item.command.name === USAGE_LIMITS_COMMAND.name &&
615
- onUsageLimits
560
+ !ownerKey ||
561
+ trigger.kind !== "pull-request" ||
562
+ !items.some((candidate) => candidate.id === item.id)
563
+ )
564
+ return;
565
+ const record = pullRequestComposerContext(item.pullRequest, uuidv4());
566
+ if (
567
+ (getComposerDraftSnapshot(ownerKey).context?.records.length ?? 0) >=
568
+ COMPOSER_CONTEXT_MAX_RECORDS
569
) {
617
- const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
618
- setSelection({ start: cleared.cursor, end: cleared.cursor });
619
- onChangeDraftMessage(cleared.text);
620
- onUsageLimits();
570
+ Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
571
return;
572
}
623
-
624
- const result = resolveComposerCommandSelection({
573
+ const result = replaceTextRange(
574
draftMessage,
626
- trigger,
627
- item,
628
- allowInteractionMode:
629
- onUpdateInteractionMode !== undefined &&
630
- selectedProviderStatus?.showInteractionModeToggle !== false,
575
+ trigger.rangeStart,
576
+ trigger.rangeEnd,
577
+ `${formatComposerContextReference(record)} `,
578
+ );
579
+ onChangeDraftMessage(result.text);
580
+ const draft = getComposerDraftSnapshot(ownerKey);
581
+ setComposerDraftContext(ownerKey, {
582
+ version: 1,
583
+ records: [...(draft.context?.records ?? []), record],
584
});
585
setSelection({ start: result.cursor, end: result.cursor });
633
- onChangeDraftMessage(result.text);
634
- if (result.interactionMode !== null) {
635
- onUpdateInteractionMode?.(result.interactionMode);
636
- }
637
- },
638
- [
586
+ return;
587
+ }
588
+
589
+ if (
590
+ item.type === "provider-slash-command" &&
591
+ item.command.name === USAGE_LIMITS_COMMAND.name &&
592
+ onUsageLimits
593
+ ) {
594
+ const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
595
+ setSelection({ start: cleared.cursor, end: cleared.cursor });
596
+ onChangeDraftMessage(cleared.text);
597
+ onUsageLimits();
598
+ return;
599
+ }
600
+
601
+ const result = resolveComposerCommandSelection({
602
draftMessage,
640
- ownerKey,
641
- items,
642
- onChangeDraftMessage,
643
- onUpdateInteractionMode,
644
- onUsageLimits,
645
- selectedProviderStatus?.showInteractionModeToggle,
646
- threadShells,
603
trigger,
648
- ],
649
- );
604
+ item,
605
+ allowInteractionMode:
606
+ onUpdateInteractionMode !== undefined &&
607
+ selectedProviderStatus?.showInteractionModeToggle !== false,
608
+ });
609
+ setSelection({ start: result.cursor, end: result.cursor });
610
+ onChangeDraftMessage(result.text);
611
+ if (result.interactionMode !== null) {
612
+ onUpdateInteractionMode?.(result.interactionMode);
613
+ }
614
+ };
615
616
return {
617
selection,
apps/mobile/src/reactCompilerCoverage.test.ts
-13
@@ -22,27 +22,14 @@ const KNOWN_BAILOUTS: Record<string, string> = {
22
"src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
23
"src/features/home/thread-swipe-actions.tsx": "ref read during render",
24
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
25
- "src/features/threads/NewTaskContextPickerScreens.tsx":
26
- "manual memo not preserved, try without catch",
27
- "src/features/threads/NewTaskDraftScreen.tsx": "try/finally",
28
- "src/features/threads/NewTaskRouteScreen.tsx": "try without catch",
25
"src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
30
- "src/features/threads/QuestionAttachments.tsx": "try/finally",
26
"src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
27
"src/features/threads/ThreadComposer.tsx": "try without catch",
28
"src/features/threads/ThreadDetailScreen.tsx": "mutates a frozen value",
29
"src/features/threads/ThreadFeed.tsx": "ref read during render, throw inside try, try/finally",
35
- "src/features/threads/ThreadGitControls.tsx": "manual memo not preserved",
30
"src/features/threads/ThreadNavigationSidebar.tsx": "ref read during render",
31
"src/features/threads/ThreadQueueControl.tsx": "ref read during render, try without catch",
32
"src/features/threads/ThreadRouteScreen.tsx": "try without catch",
39
- "src/features/threads/ThreadSettingsSheet.tsx": "manual memo not preserved, try without catch",
40
- "src/features/threads/UsageLimitRecoveryCard.tsx": "throw inside try, try/finally",
41
- "src/features/threads/git/GitCommitSheet.tsx": "manual memo not preserved",
42
- "src/features/threads/git/GitOverviewSheet.tsx": "try without catch",
43
- "src/features/threads/new-task-flow-provider.tsx": "try without catch",
44
- "src/features/threads/thread-work-log.tsx": "manual memo not preserved",
45
- "src/features/threads/use-composer-command-menu.ts": "manual memo not preserved",
33
"src/features/threads/use-thread-list-v2-shelf-preferences.ts": "ref read during render",
34
"src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
35
"src/features/voice-input/useVoiceInputController.ts": "ref read during render",