The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 03:00 UTC
perf(mobile): composer, connections, add project and shared state compile with the React Compiler (#21137)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 18, 2026 at 14:33 UTC
f733638fff201b0cbbf4e72bff42b8bf727e1e8f
13 files changed
+375
-466
apps/mobile/src/components/ComposerContextAttachment.tsx
+28
-27
@@ -1,8 +1,10 @@
1
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2
+import { AsyncResult } from "effect/reactivity";
3
import * as Dialog from "./ui/Dialog";
4
import type { ComposerContextRecord, EnvironmentId } from "@t3tools/contracts";
5
import { Pressable, View } from "react-native";
6
import { Image } from "expo-image";
5
-import { useEffect, useId, useMemo, useState } from "react";
7
+import { useEffect, useId, useState } from "react";
8
import type { DraftComposerAttachment } from "../lib/composerImages";
9
import { composerAttachmentInlineUri, isFileBackedComposerAttachment } from "../lib/composerImages";
10
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
@@ -20,14 +22,11 @@ export function ComposerContextAttachment(props: {
22
}) {
23
const { record, attachment } = props;
24
const shareSourceIdentifier = useId();
23
- const resource = useMemo(
24
- () => ({
25
- _tag: "attachment" as const,
26
- attachmentId: record.attachmentId,
27
- fileName: record.name,
28
- }),
29
- [record.attachmentId, record.name],
30
- );
25
+ const resource = {
26
+ _tag: "attachment" as const,
27
+ attachmentId: record.attachmentId,
28
+ fileName: record.name,
29
+ };
30
const local = attachment?.fileUri
31
? (attachment as DraftComposerAttachment & { fileUri: string })
32
: undefined;
@@ -64,31 +63,33 @@ export function ComposerContextAttachment(props: {
63
if (sharing) return;
64
setSharing(true);
65
const controller = new AbortController();
67
- try {
66
+ const result = await settlePromise(async () => {
67
if (local) {
68
const preview = await loadLocalAttachmentPreview(local, controller.signal);
70
- try {
71
- await preview?.share(controller.signal, shareSourceIdentifier);
72
- } finally {
73
- preview?.dispose();
74
- }
75
- } else {
76
- const url = await refresh();
77
- if (!url) throw new Error("Reconnect to the environment and try again.");
78
- await downloadAndShareAttachment({
79
- url,
80
- attachment: record,
81
- signal: controller.signal,
82
- sourceIdentifier: shareSourceIdentifier,
83
- });
69
+ if (!preview) return;
70
+ const shared = await settlePromise(() =>
71
+ preview.share(controller.signal, shareSourceIdentifier),
72
+ );
73
+ preview.dispose();
74
+ if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
75
+ return;
76
}
85
- } catch (cause) {
77
+ const url = await refresh();
78
+ if (!url) throw new Error("Reconnect to the environment and try again.");
79
+ await downloadAndShareAttachment({
80
+ url,
81
+ attachment: record,
82
+ signal: controller.signal,
83
+ sourceIdentifier: shareSourceIdentifier,
84
+ });
85
+ });
86
+ setSharing(false);
87
+ if (AsyncResult.isFailure(result)) {
88
+ const cause = squashAtomCommandFailure(result);
89
Dialog.alert(
90
"Could not open attachment",
91
cause instanceof Error ? cause.message : "Try again.",
92
);
90
- } finally {
91
- setSharing(false);
93
}
94
};
95
return (
apps/mobile/src/components/ComposerEditor.tsx
+32
-36
@@ -2,8 +2,9 @@ import * as Dialog from "./ui/Dialog";
2
import { ComposerContextId } from "@t3tools/contracts";
3
import { useAtomValue } from "@effect/atom-react";
4
import { AsyncResult } from "effect/reactivity";
5
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6
import { useNavigation } from "@react-navigation/native";
6
-import { useEffect, useMemo, useRef, useState } from "react";
7
+import { useEffect, useRef, useState } from "react";
8
import type { EnvironmentId } from "@t3tools/contracts";
9
import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
10
import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
@@ -54,7 +55,7 @@ export function ComposerEditor({
55
const preferredEnterBehavior = AsyncResult.isSuccess(preferencesResult)
56
? preferencesResult.value.composerEnterBehavior
57
: undefined;
57
- const contextHistory = useMemo(() => createComposerDraftContextHistory(), [draftKey]);
58
+ const contextHistory = createComposerDraftContextHistory();
59
useEffect(() => () => contextHistory.dispose(), [contextHistory]);
60
const changeText = (text: string) => {
61
const restored = contextHistory.restore(
@@ -87,7 +88,7 @@ export function ComposerEditor({
88
importRef.current = controller;
89
setImporting(true);
90
setComposerContextImporting(draftKey, true);
90
- try {
91
+ const settled = await settlePromise(async () => {
92
const retained = getComposerDraftAfterSelection(draftKey, insertion);
93
const result = await importComposerContextClipboard(
94
clipboard,
@@ -111,41 +112,36 @@ export function ComposerEditor({
112
"Some attachments could not be copied",
113
"Reconnect to the source environment and copy them again. References without their files are marked unavailable.",
114
);
114
- } catch (error) {
115
- if (!controller.signal.aborted)
116
- Dialog.alert(
117
- "Could not paste context",
118
- error instanceof Error ? error.message : "Try copying again.",
119
- );
120
- } finally {
121
- setComposerContextImporting(draftKey, false);
122
- importRef.current = null;
123
- setImporting(false);
115
+ });
116
+ setComposerContextImporting(draftKey, false);
117
+ importRef.current = null;
118
+ setImporting(false);
119
+ if (AsyncResult.isFailure(settled) && !controller.signal.aborted) {
120
+ const error = squashAtomCommandFailure(settled);
121
+ Dialog.alert(
122
+ "Could not paste context",
123
+ error instanceof Error ? error.message : "Try copying again.",
124
+ );
125
}
126
};
126
- const clipboardFragment = useMemo(
127
- () =>
128
- environmentId && draft.context
129
- ? encodeComposerContextFragment({
130
- version: 1,
131
- source: { environmentId },
132
- records: draft.context.records.map((record) => {
133
- if (!("attachmentId" in record)) return record;
134
- const attachment = draft.attachments.find(
135
- (entry) => entry.id === record.attachmentId,
136
- );
137
- return {
138
- ...record,
139
- attachmentId:
140
- attachment?.uploadEnvironmentId === environmentId
141
- ? (attachment.uploadedAttachmentId ?? record.attachmentId)
142
- : record.attachmentId,
143
- };
144
- }),
145
- })
146
- : "",
147
- [environmentId, draft.context, draft.attachments],
148
- );
127
+ const clipboardFragment =
128
+ environmentId && draft.context
129
+ ? encodeComposerContextFragment({
130
+ version: 1,
131
+ source: { environmentId },
132
+ records: draft.context.records.map((record) => {
133
+ if (!("attachmentId" in record)) return record;
134
+ const attachment = draft.attachments.find((entry) => entry.id === record.attachmentId);
135
+ return {
136
+ ...record,
137
+ attachmentId:
138
+ attachment?.uploadEnvironmentId === environmentId
139
+ ? (attachment.uploadedAttachmentId ?? record.attachmentId)
140
+ : record.attachmentId,
141
+ };
142
+ }),
143
+ })
144
+ : "";
145
const navigation = useNavigation();
146
const selectedReference = selected
147
? collectComposerContextReferences(selected.source)[0]
apps/mobile/src/components/VideoPreviewModal.ios.tsx
+15
-10
@@ -1,6 +1,8 @@
1
import * as Dialog from "./ui/Dialog";
2
import { useIsFocused } from "@react-navigation/native";
3
import { requireNativeModule } from "expo";
4
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5
+import { AsyncResult } from "effect/reactivity";
6
import { useEffect, useEffectEvent, useId, useState } from "react";
7
import { Keyboard } from "react-native";
8
@@ -76,20 +78,23 @@ function NativeVideoPreview(props: {
78
? await loadLocalAttachmentPreview(localAttachment, controller.signal)
79
: null;
80
if (localAttachment !== null && !file) return;
79
- try {
80
- if (controller.signal.aborted) return;
81
- ready = true;
82
- await NativeControls.presentVideo(
81
+ if (controller.signal.aborted) {
82
+ file?.dispose();
83
+ return;
84
+ }
85
+ ready = true;
86
+ const presented = await settlePromise(() =>
87
+ NativeControls.presentVideo(
88
file?.uri ?? playbackUrl!,
89
name,
90
source.sourceIdentifier ?? "",
91
identifier,
87
- );
88
- if (!controller.signal.aborted) onRequestClose();
89
- } finally {
90
- // Native completion follows dismissal, so local playback keeps its file lease.
91
- file?.dispose();
92
- }
92
+ ),
93
+ );
94
+ // Native completion follows dismissal, so local playback keeps its file lease.
95
+ file?.dispose();
96
+ if (AsyncResult.isFailure(presented)) throw squashAtomCommandFailure(presented);
97
+ if (!controller.signal.aborted) onRequestClose();
98
})().catch((error: unknown) => {
99
if (controller.signal.aborted) return;
100
// AVKit gives no retry, so re-mint now; the cached URL may simply have expired.
apps/mobile/src/components/VideoPreviewModal.tsx
+5
-4
@@ -1,6 +1,6 @@
1
import { useIsFocused } from "@react-navigation/native";
2
import { videoMimeType } from "@t3tools/shared/video";
3
-import { useEffect, useRef, useState } from "react";
3
+import { useEffect, useEffectEvent, useState } from "react";
4
import { Keyboard, Modal, Pressable, View } from "react-native";
5
import { useSafeAreaInsets } from "react-native-safe-area-context";
6
@@ -60,14 +60,15 @@ function useLocalPlayback(source: LocalVideoPreviewSource): PlaybackState {
60
const [error, setError] = useState<string | null>(null);
61
// Only a different file needs a new lease; a metadata update on the same
62
// draft must not dispose the file Android is still playing.
63
- const attachmentRef = useRef(attachment);
64
- attachmentRef.current = attachment;
63
+ const loadAttachment = useEffectEvent((signal: AbortSignal) =>
64
+ loadLocalAttachmentPreview(attachment, signal),
65
+ );
66
const { id: attachmentId, fileUri } = attachment;
67
useEffect(() => {
68
setUri(null);
69
setError(null);
70
const controller = new AbortController();
70
- const loading = loadLocalAttachmentPreview(attachmentRef.current, controller.signal);
71
+ const loading = loadAttachment(controller.signal);
72
void loading.then(
73
(file) => {
74
if (file === null) return;
apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
+51
-60
@@ -12,7 +12,7 @@ import {
12
} from "@react-navigation/native";
13
import type { EnvironmentId } from "@t3tools/contracts";
14
import { AsyncResult } from "effect/reactivity";
15
-import { useCallback, useEffect, useRef, useState } from "react";
15
+import { useEffect, useRef, useState } from "react";
16
import { Linking, Pressable, StyleSheet, View } from "react-native";
17
import Svg, { Defs, RadialGradient, Rect, Stop } from "react-native-svg";
18
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -95,19 +95,19 @@ export function ConnectionsNewRouteScreen({
95
}
96
}, [pairingConnectionError]);
97
98
- const handleHostChange = useCallback((value: string) => {
98
+ const handleHostChange = (value: string) => {
99
setHostInput(value);
100
setPendingConnectionError(null);
101
- }, []);
101
+ };
102
103
- const handleCodeChange = useCallback((value: string) => {
103
+ const handleCodeChange = (value: string) => {
104
setCodeInput(value);
105
setPendingConnectionError(null);
106
- }, []);
106
+ };
107
108
useEffect(() => () => setPendingConnectionError(null), []);
109
110
- const handleScanPress = useCallback(async () => {
110
+ const handleScanPress = async () => {
111
const permission = await requestCameraPermission();
112
if (permission.granted) {
113
setScanComplete(false);
@@ -122,68 +122,59 @@ export function ConnectionsNewRouteScreen({
122
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
123
],
124
);
125
- }, [requestCameraPermission]);
125
+ };
126
127
- const handleQrScan = useCallback(
128
- ({ data }: { readonly data: string }) => {
129
- if (scannerLocked) {
130
- return;
131
- }
127
+ const handleQrScan = ({ data }: { readonly data: string }) => {
128
+ if (scannerLocked) {
129
+ return;
130
+ }
131
133
- setScannerLocked(true);
132
+ setScannerLocked(true);
133
135
- try {
136
- const pairingUrl = extractPairingUrlFromQrPayload(data);
137
- const { host, code } = parsePairingUrl(pairingUrl);
138
- setHostInput(host);
139
- setCodeInput(code);
140
- onChangeConnectionPairingUrl(pairingUrl);
141
- setScanComplete(true);
134
+ try {
135
+ const pairingUrl = extractPairingUrlFromQrPayload(data);
136
+ const { host, code } = parsePairingUrl(pairingUrl);
137
+ setHostInput(host);
138
+ setCodeInput(code);
139
+ onChangeConnectionPairingUrl(pairingUrl);
140
+ setScanComplete(true);
141
+ setScannerLocked(false);
142
+ } catch (error) {
143
+ void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
144
+ Dialog.alert(
145
+ "Invalid QR code",
146
+ error instanceof Error ? error.message : "Scanned QR code was not recognized.",
147
+ );
148
+ setTimeout(() => {
149
setScannerLocked(false);
143
- } catch (error) {
144
- void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
145
- Dialog.alert(
146
- "Invalid QR code",
147
- error instanceof Error ? error.message : "Scanned QR code was not recognized.",
148
- );
149
- setTimeout(() => {
150
- setScannerLocked(false);
151
- }, 600);
152
- }
153
- },
154
- [onChangeConnectionPairingUrl, scannerLocked],
155
- );
150
+ }, 600);
151
+ }
152
+ };
153
157
- const connectAndClose = useCallback(
158
- async (pairingUrl: string) => {
159
- setIsSubmitting(true);
160
- onChangeConnectionPairingUrl(pairingUrl);
161
- try {
162
- const result = await onConnectPress(pairingUrl, params.routeFor);
163
- void Haptics.notificationAsync(
164
- AsyncResult.isSuccess(result)
165
- ? Haptics.NotificationFeedbackType.Success
166
- : Haptics.NotificationFeedbackType.Error,
167
- );
168
- if (AsyncResult.isSuccess(result)) {
169
- // Return to whatever opened the sheet. Replacing it with Home would
170
- // nest Home inside any sheet still below it.
171
- if (!navigation.canGoBack()) {
172
- navigation.dispatch(StackActions.replace("Home"));
173
- } else {
174
- navigation.goBack();
175
- }
176
- }
177
- } finally {
178
- setIsSubmitting(false);
154
+ const connectAndClose = async (pairingUrl: string) => {
155
+ setIsSubmitting(true);
156
+ onChangeConnectionPairingUrl(pairingUrl);
157
+ const result = await onConnectPress(pairingUrl, params.routeFor);
158
+ setIsSubmitting(false);
159
+ void Haptics.notificationAsync(
160
+ AsyncResult.isSuccess(result)
161
+ ? Haptics.NotificationFeedbackType.Success
162
+ : Haptics.NotificationFeedbackType.Error,
163
+ );
164
+ if (AsyncResult.isSuccess(result)) {
165
+ // Return to whatever opened the sheet. Replacing it with Home would
166
+ // nest Home inside any sheet still below it.
167
+ if (!navigation.canGoBack()) {
168
+ navigation.dispatch(StackActions.replace("Home"));
169
+ } else {
170
+ navigation.goBack();
171
}
180
- },
181
- [navigation, onChangeConnectionPairingUrl, onConnectPress, params.routeFor],
182
- );
172
+ }
173
+ };
174
184
- const handleSubmit = useCallback(async () => {
175
+ const handleSubmit = async () => {
176
await connectAndClose(buildPairingUrl(hostInput, codeInput));
186
- }, [codeInput, connectAndClose, hostInput]);
177
+ };
178
179
useEffect(() => {
180
if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
apps/mobile/src/features/projects/AddProjectScreen.tsx
+159
-195
@@ -56,7 +56,7 @@ import {
56
} from "@t3tools/contracts";
57
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
58
import { SymbolView } from "../../components/ui/AppSymbol";
59
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
59
+import { useEffect, useRef, useState, type ReactNode } from "react";
60
import { Platform, Pressable, View } from "react-native";
61
import { useSafeAreaInsets } from "react-native-safe-area-context";
62
import * as Arr from "effect/Array";
@@ -315,61 +315,48 @@ function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirecto
315
});
316
const [browseNavigation] = useState(createBrowseNavigationCoordinator);
317
const [isBrowseNavigating, setIsBrowseNavigating] = useState(false);
318
- const setPathInput = useCallback(
319
- (path: string) => {
320
- browseNavigation.invalidate();
318
+ const setPathInput = (path: string) => {
319
+ browseNavigation.invalidate();
320
+ setIsBrowseNavigating(false);
321
+ commitPathInput(path);
322
+ };
323
+ const navigateToBrowsePath = async (input: {
324
+ readonly browseDirectoryPath: string;
325
+ readonly selectedDirectoryName?: string;
326
+ }) => {
327
+ const selectedDirectoryPath = input.selectedDirectoryName
328
+ ? appendBrowsePathSegment(input.browseDirectoryPath, input.selectedDirectoryName)
329
+ : input.browseDirectoryPath;
330
+ const nextPathInput =
331
+ pinnedDirectoryName && input.selectedDirectoryName
332
+ ? getCloneDestinationBrowsePath({
333
+ browseDirectoryPath: input.browseDirectoryPath,
334
+ selectedDirectoryName: input.selectedDirectoryName,
335
+ cloneDirectoryName: pinnedDirectoryName,
336
+ caseSensitive: clonePathCaseSensitive,
337
+ })
338
+ : getCloneDestinationPath(selectedDirectoryPath, pinnedDirectoryName);
339
+ setIsBrowseNavigating(true);
340
+ const committed = await browseNavigation.run(
341
+ async () => {
342
+ if (
343
+ environment &&
344
+ readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) &&
345
+ canPreloadBrowsePath(environmentRuntime?.connectionState)
346
+ ) {
347
+ await loadBrowsePath({
348
+ environmentId: environment.environmentId,
349
+ input: { partialPath: selectedDirectoryPath },
350
+ });
351
+ }
352
+ },
353
+ () => commitPathInput(nextPathInput),
354
+ );
355
+ if (committed) {
356
setIsBrowseNavigating(false);
322
- commitPathInput(path);
323
- },
324
- [browseNavigation],
325
- );
326
- const navigateToBrowsePath = useCallback(
327
- async (input: {
328
- readonly browseDirectoryPath: string;
329
- readonly selectedDirectoryName?: string;
330
- }) => {
331
- const selectedDirectoryPath = input.selectedDirectoryName
332
- ? appendBrowsePathSegment(input.browseDirectoryPath, input.selectedDirectoryName)
333
- : input.browseDirectoryPath;
334
- const nextPathInput =
335
- pinnedDirectoryName && input.selectedDirectoryName
336
- ? getCloneDestinationBrowsePath({
337
- browseDirectoryPath: input.browseDirectoryPath,
338
- selectedDirectoryName: input.selectedDirectoryName,
339
- cloneDirectoryName: pinnedDirectoryName,
340
- caseSensitive: clonePathCaseSensitive,
341
- })
342
- : getCloneDestinationPath(selectedDirectoryPath, pinnedDirectoryName);
343
- setIsBrowseNavigating(true);
344
- const committed = await browseNavigation.run(
345
- async () => {
346
- if (
347
- environment &&
348
- readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) &&
349
- canPreloadBrowsePath(environmentRuntime?.connectionState)
350
- ) {
351
- await loadBrowsePath({
352
- environmentId: environment.environmentId,
353
- input: { partialPath: selectedDirectoryPath },
354
- });
355
- }
356
- },
357
- () => commitPathInput(nextPathInput),
358
- );
359
- if (committed) {
360
- setIsBrowseNavigating(false);
361
- }
362
- return committed;
363
- },
364
- [
365
- browseNavigation,
366
- clonePathCaseSensitive,
367
- environment,
368
- environmentRuntime?.connectionState,
369
- loadBrowsePath,
370
- pinnedDirectoryName,
371
- ],
372
- );
357
+ }
358
+ return committed;
359
+ };
360
361
useEffect(() => {
362
if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
@@ -398,7 +385,7 @@ function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
385
const { savedConnectionsById } = useSavedRemoteConnections();
386
const { connectedEnvironments } = useRemoteConnectionStatus();
387
401
- return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
388
+ return ((): ReadonlyArray<EnvironmentOption> => {
389
const runtimeByEnvironmentId = new Map(
390
connectedEnvironments.map((environment) => [environment.environmentId, environment] as const),
391
);
@@ -422,7 +409,7 @@ function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
409
options.filter((environment) => canCreateProjectInEnvironment(environment.connectionState)),
410
environmentOptionOrder,
411
);
425
- }, [connectedEnvironments, savedConnectionsById, serverConfigByEnvironmentId]);
412
+ })();
413
}
414
415
function useSelectedEnvironment(): {
@@ -544,10 +531,7 @@ export function AddProjectSourceScreen() {
531
input: {},
532
}),
533
);
547
- const readiness = useMemo(
548
- () => buildAddProjectRemoteSourceReadiness(discoveryState.data),
549
- [discoveryState.data],
550
- );
534
+ const readiness = buildAddProjectRemoteSourceReadiness(discoveryState.data);
535
536
return (
537
<AddProjectShell title="Add project">
@@ -706,58 +690,26 @@ function useCreateProject(environment: EnvironmentOption | null) {
690
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
691
const projects = useProjects();
692
709
- return useCallback(
710
- async (workspaceRoot: string) => {
711
- if (
712
- !environment ||
713
- !canCreateProjectInEnvironment(environment.connectionState) ||
714
- !readEnvironmentScope(environment.environmentId, AuthOrchestrationOperateScope)
715
- ) {
716
- Dialog.alert(
717
- "Project not added",
718
- `This connection cannot add projects right now. Any existing files remain at ${workspaceRoot}.`,
719
- );
720
- return;
721
- }
722
-
723
- const existing = findExistingAddProject({
724
- projects,
725
- environmentId: environment.environmentId,
726
- path: workspaceRoot,
727
- });
728
- if (existing) {
729
- Dialog.alert("Project already exists", existing.title);
730
- navigation.dispatch(
731
- CommonActions.reset({
732
- index: 0,
733
- routes: [
734
- {
735
- name: "NewTaskDraft",
736
- params: {
737
- environmentId: existing.environmentId,
738
- projectId: existing.id,
739
- title: existing.title,
740
- },
741
- },
742
- ],
743
- }),
744
- );
745
- return;
746
- }
693
+ return async (workspaceRoot: string) => {
694
+ if (
695
+ !environment ||
696
+ !canCreateProjectInEnvironment(environment.connectionState) ||
697
+ !readEnvironmentScope(environment.environmentId, AuthOrchestrationOperateScope)
698
+ ) {
699
+ Dialog.alert(
700
+ "Project not added",
701
+ `This connection cannot add projects right now. Any existing files remain at ${workspaceRoot}.`,
702
+ );
703
+ return;
704
+ }
705
748
- const projectId = ProjectId.make(uuidv4());
749
- const command = buildProjectCreateCommand({
750
- commandId: CommandId.make(uuidv4()),
751
- projectId,
752
- workspaceRoot,
753
- });
754
- const result = await createProject({
755
- environmentId: environment.environmentId,
756
- input: command,
757
- });
758
- if (AsyncResult.isFailure(result)) {
759
- return result;
760
- }
706
+ const existing = findExistingAddProject({
707
+ projects,
708
+ environmentId: environment.environmentId,
709
+ path: workspaceRoot,
710
+ });
711
+ if (existing) {
712
+ Dialog.alert("Project already exists", existing.title);
713
navigation.dispatch(
714
CommonActions.reset({
715
index: 0,
@@ -765,18 +717,47 @@ function useCreateProject(environment: EnvironmentOption | null) {
717
{
718
name: "NewTaskDraft",
719
params: {
768
- environmentId: environment.environmentId,
769
- projectId,
770
- title: inferProjectTitleFromPath(workspaceRoot),
720
+ environmentId: existing.environmentId,
721
+ projectId: existing.id,
722
+ title: existing.title,
723
},
724
},
725
],
726
}),
727
);
728
+ return;
729
+ }
730
+
731
+ const projectId = ProjectId.make(uuidv4());
732
+ const command = buildProjectCreateCommand({
733
+ commandId: CommandId.make(uuidv4()),
734
+ projectId,
735
+ workspaceRoot,
736
+ });
737
+ const result = await createProject({
738
+ environmentId: environment.environmentId,
739
+ input: command,
740
+ });
741
+ if (AsyncResult.isFailure(result)) {
742
return result;
777
- },
778
- [createProject, environment, projects, navigation],
779
- );
743
+ }
744
+ navigation.dispatch(
745
+ CommonActions.reset({
746
+ index: 0,
747
+ routes: [
748
+ {
749
+ name: "NewTaskDraft",
750
+ params: {
751
+ environmentId: environment.environmentId,
752
+ projectId,
753
+ title: inferProjectTitleFromPath(workspaceRoot),
754
+ },
755
+ },
756
+ ],
757
+ }),
758
+ );
759
+ return result;
760
+ };
761
}
762
763
function useEnvironmentFromParam(
@@ -801,7 +782,7 @@ export function AddProjectRepositoryScreen(props: {
782
const [isSubmitting, setIsSubmitting] = useState(false);
783
const [error, setError] = useState<string | null>(null);
784
804
- const lookupRepository = useCallback(async () => {
785
+ const lookupRepository = async () => {
786
if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
787
setError(null);
788
setIsSubmitting(true);
@@ -843,7 +824,7 @@ export function AddProjectRepositoryScreen(props: {
824
);
825
}
826
setIsSubmitting(false);
846
- }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
827
+ };
828
829
return (
830
<AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
@@ -888,14 +869,9 @@ function FolderBrowser(props: {
869
}) => Promise<boolean>;
870
readonly pinnedDirectoryName?: string;
871
}) {
891
- const browsePath = useMemo(
892
- () => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
893
- [props.environment.platform, props.pathInput],
894
- );
895
- const browseInput = useMemo(
896
- () => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
897
- [browsePath.directoryPath],
898
- );
872
+ const browsePath = getFilesystemBrowsePath(props.pathInput, props.environment.platform);
873
+ const browseInput =
874
+ browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null;
875
const fileAccessSession = useEnvironmentQuery(
876
environmentSession.sessionStateAtom(props.environment.environmentId),
877
);
@@ -920,9 +896,9 @@ function FolderBrowser(props: {
896
? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
897
: browsePath.filterQuery === pinnedDirectoryName;
898
const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
923
- const { visibleEntries: visibleBrowseEntries } = useMemo(
924
- () => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browseFilterQuery),
925
- [browseFilterQuery, browseState.data?.entries],
899
+ const { visibleEntries: visibleBrowseEntries } = filterFilesystemBrowseEntries(
900
+ browseState.data?.entries ?? [],
901
+ browseFilterQuery,
902
);
903
904
return (
@@ -1065,59 +1041,58 @@ export function AddProjectNewScreen(props: { readonly environmentId?: string | s
1041
submittingRef.current = true;
1042
setError(null);
1043
setIsSubmitting(true);
1068
- try {
1069
- const result = await createNew({
1044
+ const result = await createNew({
1045
+ environmentId: environment.environmentId,
1046
+ input: { name: trimmedName },
1047
+ });
1048
+ if (AsyncResult.isFailure(result)) {
1049
+ submittingRef.current = false;
1050
+ setIsSubmitting(false);
1051
+ setError(errorMessage(Cause.squash(result.cause)));
1052
+ return;
1053
+ }
1054
+ const { projectId, workspaceRoot, commitError } = result.value;
1055
+ if (commitError !== undefined) {
1056
+ Dialog.alert("Created without a first commit", commitError);
1057
+ }
1058
+ if (publishes && publishTarget !== null) {
1059
+ void publishRepository({
1060
environmentId: environment.environmentId,
1071
- input: { name: trimmedName },
1061
+ input: {
1062
+ cwd: workspaceRoot,
1063
+ provider: publishTarget.definition.kind,
1064
+ repository: getNewProjectRepository(publishTarget, workspaceRoot),
1065
+ visibility: "private",
1066
+ },
1067
+ }).then((publishResult) => {
1068
+ if (AsyncResult.isFailure(publishResult)) {
1069
+ Dialog.alert(
1070
+ `Could not create the ${publishTarget.definition.label} repository`,
1071
+ errorMessage(Cause.squash(publishResult.cause)),
1072
+ );
1073
+ }
1074
});
1073
- if (AsyncResult.isFailure(result)) {
1074
- setError(errorMessage(Cause.squash(result.cause)));
1075
- return;
1076
- }
1077
- const { projectId, workspaceRoot, commitError } = result.value;
1078
- if (commitError !== undefined) {
1079
- Dialog.alert("Created without a first commit", commitError);
1080
- }
1081
- if (publishes && publishTarget !== null) {
1082
- void publishRepository({
1083
- environmentId: environment.environmentId,
1084
- input: {
1085
- cwd: workspaceRoot,
1086
- provider: publishTarget.definition.kind,
1087
- repository: getNewProjectRepository(publishTarget, workspaceRoot),
1088
- visibility: "private",
1089
- },
1090
- }).then((publishResult) => {
1091
- if (AsyncResult.isFailure(publishResult)) {
1092
- Dialog.alert(
1093
- `Could not create the ${publishTarget.definition.label} repository`,
1094
- errorMessage(Cause.squash(publishResult.cause)),
1095
- );
1096
- }
1097
- });
1098
- }
1099
- // The draft screen resolves its project from the client store, so it
1100
- // must not open before the create event has arrived.
1101
- const project = await waitForProject(
1102
- { environmentId: environment.environmentId, projectId },
1103
- 15_000,
1075
+ }
1076
+ // The draft screen resolves its project from the client store, so it
1077
+ // must not open before the create event has arrived.
1078
+ const project = await waitForProject(
1079
+ { environmentId: environment.environmentId, projectId },
1080
+ 15_000,
1081
+ );
1082
+ submittingRef.current = false;
1083
+ setIsSubmitting(false);
1084
+ if (project === null) {
1085
+ setName("");
1086
+ setError(
1087
+ "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
1088
);
1105
- if (project === null) {
1106
- setName("");
1107
- setError(
1108
- "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
1109
- );
1110
- return;
1111
- }
1112
- openNewTaskDraft(navigation, {
1113
- environmentId: environment.environmentId,
1114
- projectId,
1115
- title: trimmedName,
1116
- });
1117
- } finally {
1118
- submittingRef.current = false;
1119
- setIsSubmitting(false);
1089
+ return;
1090
}
1091
+ openNewTaskDraft(navigation, {
1092
+ environmentId: environment.environmentId,
1093
+ projectId,
1094
+ title: trimmedName,
1095
+ });
1096
};
1097
1098
return (
@@ -1251,7 +1226,7 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
1226
const [isSubmitting, setIsSubmitting] = useState(false);
1227
const [error, setError] = useState<string | null>(null);
1228
1254
- const submitPath = useCallback(async () => {
1229
+ const submitPath = async () => {
1230
if (!environment || isBrowseNavigating || isSubmitting) return;
1231
setError(null);
1232
const resolved = resolveAddProjectPath({
@@ -1270,7 +1245,7 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
1245
setError(errorMessage(Cause.squash(result.cause)));
1246
}
1247
setIsSubmitting(false);
1273
- }, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
1248
+ };
1249
1250
return (
1251
<AddProjectShell title="Local folder">
@@ -1337,7 +1312,7 @@ export function AddProjectDestinationScreen(props: {
1312
const [isSubmitting, setIsSubmitting] = useState(false);
1313
const [error, setError] = useState<string | null>(null);
1314
1340
- const submitPath = useCallback(async () => {
1315
+ const submitPath = async () => {
1316
if (
1317
!environment ||
1318
!readEnvironmentScope(environment.environmentId, AuthSourceControlWriteScope) ||
@@ -1421,18 +1396,7 @@ export function AddProjectDestinationScreen(props: {
1396
}
1397
}
1398
setIsSubmitting(false);
1424
- }, [
1425
- cloneRepository,
1426
- createProject,
1427
- environment,
1428
- isBrowseNavigating,
1429
- isSubmitting,
1430
- navigation,
1431
- pathInput,
1432
- prompt,
1433
- remoteUrl,
1434
- startProjectClone,
1435
- ]);
1399
+ };
1400
1401
return (
1402
<AddProjectShell title="Clone destination">
apps/mobile/src/lib/attachmentDocument.ts
+18
-21
@@ -1,3 +1,5 @@
1
+import { AsyncResult } from "effect/reactivity";
2
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3
import * as Dialog from "../components/ui/Dialog";
4
import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
5
import type { EnvironmentId } from "@t3tools/contracts";
@@ -5,7 +7,7 @@ import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
7
import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
8
import { fetch } from "expo/fetch";
9
import { File } from "expo-file-system";
8
-import { useEffect, useMemo, useRef, useState } from "react";
10
+import { useEffect, useRef, useState } from "react";
11
12
import type { FileBackedComposerAttachment } from "./composerImages";
13
import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
@@ -33,25 +35,19 @@ export function useAttachmentDocument(input: {
35
const delimiter = filePreviewDelimiter(input);
36
const shareController = useRef<AbortController | null>(null);
37
useEffect(() => () => shareController.current?.abort(), []);
36
- const resource = useMemo(
37
- () => ({
38
- _tag: "attachment" as const,
39
- attachmentId: input.attachmentId,
40
- fileName: input.name,
41
- mimeType: input.mimeType,
42
- disposition: "inline" as const,
43
- }),
44
- [input.attachmentId, input.name, input.mimeType],
45
- );
38
+ const resource = {
39
+ _tag: "attachment" as const,
40
+ attachmentId: input.attachmentId,
41
+ fileName: input.name,
42
+ mimeType: input.mimeType,
43
+ disposition: "inline" as const,
44
+ };
45
const environmentId = input.attachment ? null : input.environmentId;
46
const refresh = useRefreshAssetUrl(environmentId, resource);
47
const [localUri, setLocalUri] = useState<string | null>(null);
48
const [remoteUri, setRemoteUri] = useState<string | null>(null);
49
const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
51
- const table = useMemo(
52
- () => (content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null),
53
- [content, delimiter],
54
- );
50
+ const table = content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null;
51
const [error, setError] = useState<string | null>(null);
52
const [contentError, setContentError] = useState<string | null>(null);
53
const textReadUrl = useRef<{ uri: string; authorizedAt: number } | null>(null);
@@ -170,18 +166,19 @@ export function useAttachmentDocument(input: {
166
attachment: { name: input.name, mimeType: input.mimeType },
167
signal: controller.signal,
168
};
173
- try {
169
+ const result = await settlePromise(async () => {
170
if (isLocalUri(uri)) await shareLocalAttachment({ ...request, uri });
171
else await downloadAndShareAttachment({ ...request, url: (await refresh()) ?? uri });
176
- } catch (cause) {
177
- if (controller.signal.aborted) return;
172
+ });
173
+ if (shareController.current === controller) shareController.current = null;
174
+ if (controller.signal.aborted) return;
175
+ setSharing(false);
176
+ if (AsyncResult.isFailure(result)) {
177
+ const cause = squashAtomCommandFailure(result);
178
Dialog.alert(
179
"Could not share file",
180
cause instanceof Error ? cause.message : "Please try again.",
181
);
182
- } finally {
183
- if (shareController.current === controller) shareController.current = null;
184
- if (!controller.signal.aborted) setSharing(false);
182
}
183
};
184
return {
apps/mobile/src/reactCompilerCoverage.test.ts
-12
@@ -17,17 +17,10 @@ const metroConfig: Promise<{ transformer: { babelTransformerPath: string } }> =
17
// delete its entry (and its manual useMemo/useCallback/memo) in the same change.
18
const KNOWN_BAILOUTS: Record<string, string> = {
19
"src/components/ComposerAttachmentStrip.tsx": "unsupported syntax",
20
- "src/components/ComposerContextAttachment.tsx":
21
- "throw inside try, try without catch, try/finally",
22
- "src/components/ComposerEditor.tsx": "try/finally",
23
- "src/components/VideoPreviewModal.ios.tsx": "try without catch",
24
- "src/components/VideoPreviewModal.tsx": "ref read during render",
20
"src/components/ui/AndroidAnchoredMenu.tsx": "ref read during render",
21
"src/components/ui/Menu.tsx": "ref read during render",
27
- "src/features/connection/ConnectionsNewRouteScreen.tsx": "try without catch",
22
"src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
23
"src/features/home/thread-swipe-actions.tsx": "ref read during render",
30
- "src/features/projects/AddProjectScreen.tsx": "try without catch",
24
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
25
"src/features/threads/NewTaskContextPickerScreens.tsx":
26
"manual memo not preserved, try without catch",
@@ -53,16 +46,11 @@ const KNOWN_BAILOUTS: Record<string, string> = {
46
"src/features/threads/use-thread-list-v2-shelf-preferences.ts": "ref read during render",
47
"src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
48
"src/features/voice-input/useVoiceInputController.ts": "ref read during render",
56
- "src/lib/attachmentDocument.ts": "try/finally",
49
"src/native/StackHeader.tsx": "ref read during render",
50
"src/native/T3ComposerEditor.ios.tsx": "ref read during render",
51
"src/native/T3ComposerEditor.native.tsx": "ref read during render",
60
- "src/state/composer-attachment-uploads.ts": "try without catch",
61
- "src/state/mediaActions.ts": "try without catch",
62
- "src/state/queries.ts": "manual memo not preserved",
52
"src/state/use-thread-composer-state.ts": "try without catch",
53
"src/state/use-thread-selection.ts": "ref read during render",
65
- "src/state/use-vcs-action-state.ts": "manual memo not preserved",
54
};
55
56
// Caller flags Metro passes for an iOS release bundle. supportsReactCompiler is
apps/mobile/src/state/composer-attachment-uploads.test.ts
+4
-2
@@ -135,7 +135,10 @@ vi.mock("./attachments", () => ({
135
attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove },
136
}));
137
vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } }));
138
-vi.mock("@t3tools/client-runtime/state/runtime", () => ({
138
+vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
139
+ // The worker settles uploads with the real settlePromise and squashAtomCommandFailure;
140
+ // only the RPC transport is substituted.
141
+ ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
142
createEnvironmentRpcCommand: () => Symbol("rpc-command"),
143
executeAtomQuery: async (
144
_registry: unknown,
@@ -164,7 +167,6 @@ vi.mock("@t3tools/client-runtime/state/runtime", () => ({
167
}
168
throw new Error("Unexpected RPC command");
169
},
167
- squashAtomCommandFailure: (result: { error: unknown }) => result.error,
170
}));
171
vi.mock("./use-thread-outbox", async () => {
172
const { Atom } = await import("effect/reactivity");
apps/mobile/src/state/composer-attachment-uploads.ts
+10
-8
@@ -1,6 +1,7 @@
1
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2
import { useAtomValue } from "@effect/atom-react";
3
import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
3
-import { Atom } from "effect/reactivity";
4
+import { Atom, AsyncResult } from "effect/reactivity";
5
import { useEffect, useRef } from "react";
6
7
import { prepareTurnAttachments } from "../lib/attachmentUpload";
@@ -73,8 +74,8 @@ export function useComposerAttachmentUploadWorker() {
74
const release = isFileBackedComposerAttachment(attachment)
75
? retainComposerAttachmentFileForPreview(attachment)
76
: undefined;
76
- try {
77
- const result = await prepareTurnAttachments({
77
+ const prepared = await settlePromise(() =>
78
+ prepareTurnAttachments({
79
environmentId,
80
attachments: [attachment],
81
supportsImageUploads: true,
@@ -104,11 +105,12 @@ export function useComposerAttachmentUploadWorker() {
105
});
106
return "persisted";
107
},
107
- });
108
- return result.status === "ready";
109
- } finally {
110
- release?.();
111
- }
108
+ }),
109
+ );
110
+ release?.();
111
+ // The upload queue owns retry and failure reporting, so a failed upload rethrows to it.
112
+ if (AsyncResult.isFailure(prepared)) throw squashAtomCommandFailure(prepared);
113
+ return prepared.value.status === "ready";
114
},
115
});
116
queueRef.current = queue;
apps/mobile/src/state/mediaActions.ts
+6
-5
@@ -1,3 +1,4 @@
1
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2
import * as Dialog from "../components/ui/Dialog";
3
import type { MediaActionsSource } from "../lib/mediaActionsSource";
4
import { useNavigation } from "@react-navigation/native";
@@ -62,11 +63,11 @@ export function useMediaActions(source: MediaActionsSource | undefined, onOpenFi
63
if ("attachment" in source) {
64
const preview = await loadLocalAttachmentPreview(source.attachment, request.signal);
65
if (!preview) return;
65
- try {
66
- await preview.share(request.signal, source.sourceIdentifier);
67
- } finally {
68
- preview.dispose();
69
- }
66
+ const shared = await settlePromise(() =>
67
+ preview.share(request.signal, source.sourceIdentifier),
68
+ );
69
+ preview.dispose();
70
+ if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
71
return;
72
}
73
const uri = "uri" in source ? normalizeNativeMarkdownUrl(source.uri) : await refresh();
apps/mobile/src/state/queries.ts
+35
-60
@@ -10,7 +10,6 @@ import type {
10
EnvironmentId,
11
OrchestrationV2ProjectedTurnItem,
12
ProjectId,
13
- ThreadId,
13
ThreadPullRequestLink,
14
VcsListRefsResult,
15
VcsRef,
@@ -25,7 +24,7 @@ import * as Cause from "effect/Cause";
24
import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
25
import * as Option from "effect/Option";
26
import { AsyncResult, Atom } from "effect/reactivity";
28
-import { useCallback, useEffect, useMemo, useState } from "react";
27
+import { useEffect, useState } from "react";
28
29
import { appAtomRegistry } from "./atom-registry";
30
import { orchestrationEnvironment } from "./orchestration";
@@ -89,13 +88,10 @@ export function useComposerPullRequestSearch(input: {
88
query: string | null;
89
}) {
90
const query = useDebouncedValue(input.query, 180);
92
- const linked = useMemo(
93
- () =>
94
- input.projectId === null
95
- ? []
96
- : composerPullRequestsFromLinks(input.threadPullRequests ?? [], input.projectId),
97
- [input.projectId, input.threadPullRequests],
98
- );
91
+ const linked =
92
+ input.projectId === null
93
+ ? []
94
+ : composerPullRequestsFromLinks(input.threadPullRequests ?? [], input.projectId);
95
const ready =
96
query === input.query &&
97
query !== null &&
@@ -129,7 +125,7 @@ export function useComposerPullRequestSearch(input: {
125
})
126
: null,
127
);
132
- const entries = useMemo(() => {
128
+ const entries = (() => {
129
if (!ready) return [];
130
if (numeric) {
131
return filterComposerPullRequestMatches({
@@ -155,7 +151,7 @@ export function useComposerPullRequestSearch(input: {
151
return [...unique.values()]
152
.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
153
.slice(0, 20);
158
- }, [ready, exact.data, list.data, linked, input.projectId, input.repository, numeric, query]);
154
+ })();
155
return {
156
entries,
157
isPending: input.query !== null && (query !== input.query || list.isPending || exact.isPending),
@@ -174,10 +170,8 @@ export function useThreadSearch(
170
const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
171
const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
172
const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
177
- const searchKey = useMemo(
178
- () => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)),
179
- [environmentIds, settledQuery],
180
- );
173
+ const searchKey =
174
+ settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery);
175
const result = useAtomValue(
176
searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
177
);
@@ -222,29 +216,22 @@ export function usePaginatedBranches(target: VcsRefTarget) {
216
cursors: INITIAL_BRANCH_CURSORS,
217
});
218
const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
225
- const pageAtoms = useMemo(
226
- () =>
227
- target.environmentId !== null && target.cwd !== null
228
- ? cursors.map((cursor) =>
229
- vcsEnvironment.listRefs({
230
- environmentId: target.environmentId!,
231
- input: {
232
- cwd: target.cwd!,
233
- ...(query.length > 0 ? { query } : {}),
234
- ...(cursor === undefined ? {} : { cursor }),
235
- limit: VCS_REF_LIST_LIMIT,
236
- },
237
- }),
238
- )
239
- : [],
240
- [cursors, query, target.cwd, target.environmentId],
241
- );
242
- const pagesAtom = useMemo(
243
- () =>
244
- Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
245
- Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
246
- ),
247
- [pageAtoms, targetKey],
219
+ const pageAtoms =
220
+ target.environmentId !== null && target.cwd !== null
221
+ ? cursors.map((cursor) =>
222
+ vcsEnvironment.listRefs({
223
+ environmentId: target.environmentId!,
224
+ input: {
225
+ cwd: target.cwd!,
226
+ ...(query.length > 0 ? { query } : {}),
227
+ ...(cursor === undefined ? {} : { cursor }),
228
+ limit: VCS_REF_LIST_LIMIT,
229
+ },
230
+ }),
231
+ )
232
+ : [];
233
+ const pagesAtom = Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
234
+ Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
235
);
236
const results = useAtomValue(pagesAtom);
237
const values = results.flatMap((result) => {
@@ -284,14 +271,14 @@ export function usePaginatedBranches(target: VcsRefTarget) {
271
: "Failed to load refs.";
272
})()
273
: null;
287
- const refresh = useCallback(() => {
274
+ const refresh = () => {
275
const firstPage = pageAtoms[0];
276
setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
277
if (firstPage !== undefined) {
278
appAtomRegistry.refresh(firstPage);
279
}
293
- }, [pageAtoms, targetKey]);
294
- const loadNext = useCallback(() => {
280
+ };
281
+ const loadNext = () => {
282
if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
283
return;
284
}
@@ -302,7 +289,7 @@ export function usePaginatedBranches(target: VcsRefTarget) {
289
? { targetKey, cursors: currentCursors }
290
: { targetKey, cursors: [...currentCursors, data.nextCursor!] };
291
});
305
- }, [data?.nextCursor, targetKey]);
292
+ };
293
294
return {
295
data,
@@ -316,14 +303,11 @@ export function usePaginatedBranches(target: VcsRefTarget) {
303
}
304
305
export function useComposerPathSearch(target: ComposerPathSearchTarget) {
319
- const normalizedTarget = useMemo(
320
- () => ({
321
- environmentId: target.environmentId,
322
- cwd: target.cwd,
323
- query: normalizeComposerPathSearchQuery(target.query),
324
- }),
325
- [target.cwd, target.environmentId, target.query],
326
- );
306
+ const normalizedTarget = {
307
+ environmentId: target.environmentId,
308
+ cwd: target.cwd,
309
+ query: normalizeComposerPathSearchQuery(target.query),
310
+ };
311
const debouncedTarget = useDebouncedValue(normalizedTarget, COMPOSER_PATH_SEARCH_DEBOUNCE_MS);
312
const fileAccessSession = useEnvironmentQuery(
313
debouncedTarget.environmentId === null
@@ -372,16 +356,7 @@ export function useComposerPathSearch(target: ComposerPathSearchTarget) {
356
}
357
358
export function useCheckpointDiff(target: CheckpointDiffTarget) {
375
- const targets = useMemo(
376
- () => buildCheckpointDiffTargets(target),
377
- [
378
- target.environmentId,
379
- target.fromTurnCount,
380
- target.ignoreWhitespace,
381
- target.threadId,
382
- target.toTurnCount,
383
- ],
384
- );
359
+ const targets = buildCheckpointDiffTargets(target);
360
const fullThread = useEnvironmentQuery(
361
targets.fullThread === null
362
? null
apps/mobile/src/state/use-vcs-action-state.ts
+12
-26
@@ -1,7 +1,7 @@
1
import { useAtomValue } from "@effect/atom-react";
2
import { type VcsActionState, type VcsActionTarget } from "@t3tools/client-runtime/state/vcs";
3
import { Atom } from "effect/reactivity";
4
-import { useCallback, useEffect, useRef, useState } from "react";
4
+import { useEffect, useState } from "react";
5
6
import { appAtomRegistry } from "./atom-registry";
7
import { vcsActionManager } from "./vcs";
@@ -67,9 +67,9 @@ const EMPTY_PROGRESS: GitActionProgress = {
67
description: null,
68
};
69
70
-function formatElapsedSeconds(ms: number | null): string | null {
70
+function formatElapsedSeconds(ms: number | null, nowMs: number): string | null {
71
if (ms === null) return null;
72
- const elapsed = Math.max(0, Math.floor((Date.now() - ms) / 1000));
72
+ const elapsed = Math.max(0, Math.floor((nowMs - ms) / 1000));
73
if (elapsed < 2) return null;
74
return `Running for ${elapsed}s`;
75
}
@@ -78,34 +78,20 @@ export function useGitActionProgress(target: VcsActionTarget): GitActionProgress
78
const actionState = useVcsActionState(target);
79
const { result } = useGitActionResultNotification();
80
81
- const [, forceUpdate] = useState(0);
82
- const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
83
-
84
- const startElapsedTimer = useCallback(() => {
85
- if (intervalRef.current) return;
86
- intervalRef.current = setInterval(() => forceUpdate((n) => n + 1), 1000);
87
- }, []);
88
-
89
- const stopElapsedTimer = useCallback(() => {
90
- if (intervalRef.current) {
91
- clearInterval(intervalRef.current);
92
- intervalRef.current = null;
93
- }
94
- }, []);
95
-
81
+ // The clock is state the interval advances: a render-time Date.now() would be
82
+ // cached on the start timestamp by the compiler and the label would freeze.
83
+ const [nowMs, setNowMs] = useState(() => Date.now());
84
useEffect(() => {
97
- if (actionState.isRunning) {
98
- startElapsedTimer();
99
- } else {
100
- stopElapsedTimer();
101
- }
102
- return stopElapsedTimer;
103
- }, [actionState.isRunning, startElapsedTimer, stopElapsedTimer]);
85
+ if (!actionState.isRunning) return;
86
+ setNowMs(Date.now());
87
+ const interval = setInterval(() => setNowMs(Date.now()), 1000);
88
+ return () => clearInterval(interval);
89
+ }, [actionState.isRunning]);
90
91
if (actionState.isRunning) {
92
const description =
93
actionState.lastOutputLine ??
108
- formatElapsedSeconds(actionState.hookStartedAtMs ?? actionState.phaseStartedAtMs);
94
+ formatElapsedSeconds(actionState.hookStartedAtMs ?? actionState.phaseStartedAtMs, nowMs);
95
return {
96
phase: "running",
97
label: actionState.currentLabel,