Skip to content
TypeScript

perf(mobile): composer, connections, add project and shared state compile with the React Compiler (#21137)

Julius Marmingef733638fff20
diff --git a/apps/mobile/src/components/ComposerContextAttachment.tsx b/apps/mobile/src/components/ComposerContextAttachment.tsx
index 40cb741deec..e766a35177e 100644
--- a/apps/mobile/src/components/ComposerContextAttachment.tsx
+++ b/apps/mobile/src/components/ComposerContextAttachment.tsx
@@ -1,8 +1,10 @@
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import { AsyncResult } from "effect/reactivity";
import * as Dialog from "./ui/Dialog";
import type { ComposerContextRecord, EnvironmentId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { Image } from "expo-image";
-import { useEffect, useId, useMemo, useState } from "react";
+import { useEffect, useId, useState } from "react";
import type { DraftComposerAttachment } from "../lib/composerImages";
import { composerAttachmentInlineUri, isFileBackedComposerAttachment } from "../lib/composerImages";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
@@ -20,14 +22,11 @@ export function ComposerContextAttachment(props: {
}) {
const { record, attachment } = props;
const shareSourceIdentifier = useId();
- const resource = useMemo(
- () => ({
- _tag: "attachment" as const,
- attachmentId: record.attachmentId,
- fileName: record.name,
- }),
- [record.attachmentId, record.name],
- );
+ const resource = {
+ _tag: "attachment" as const,
+ attachmentId: record.attachmentId,
+ fileName: record.name,
+ };
const local = attachment?.fileUri
? (attachment as DraftComposerAttachment & { fileUri: string })
: undefined;
@@ -64,31 +63,33 @@ export function ComposerContextAttachment(props: {
if (sharing) return;
setSharing(true);
const controller = new AbortController();
- try {
+ const result = await settlePromise(async () => {
if (local) {
const preview = await loadLocalAttachmentPreview(local, controller.signal);
- try {
- await preview?.share(controller.signal, shareSourceIdentifier);
- } finally {
- preview?.dispose();
- }
- } else {
- const url = await refresh();
- if (!url) throw new Error("Reconnect to the environment and try again.");
- await downloadAndShareAttachment({
- url,
- attachment: record,
- signal: controller.signal,
- sourceIdentifier: shareSourceIdentifier,
- });
+ if (!preview) return;
+ const shared = await settlePromise(() =>
+ preview.share(controller.signal, shareSourceIdentifier),
+ );
+ preview.dispose();
+ if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
+ return;
}
- } catch (cause) {
+ const url = await refresh();
+ if (!url) throw new Error("Reconnect to the environment and try again.");
+ await downloadAndShareAttachment({
+ url,
+ attachment: record,
+ signal: controller.signal,
+ sourceIdentifier: shareSourceIdentifier,
+ });
+ });
+ setSharing(false);
+ if (AsyncResult.isFailure(result)) {
+ const cause = squashAtomCommandFailure(result);
Dialog.alert(
"Could not open attachment",
cause instanceof Error ? cause.message : "Try again.",
);
- } finally {
- setSharing(false);
}
};
return (
diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx
index 1cda78bbd93..a49fa6ef391 100644
--- a/apps/mobile/src/components/ComposerEditor.tsx
+++ b/apps/mobile/src/components/ComposerEditor.tsx
@@ -2,8 +2,9 @@ import * as Dialog from "./ui/Dialog";
import { ComposerContextId } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/reactivity";
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { useNavigation } from "@react-navigation/native";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import type { EnvironmentId } from "@t3tools/contracts";
import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
@@ -54,7 +55,7 @@ export function ComposerEditor({
const preferredEnterBehavior = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.composerEnterBehavior
: undefined;
- const contextHistory = useMemo(() => createComposerDraftContextHistory(), [draftKey]);
+ const contextHistory = createComposerDraftContextHistory();
useEffect(() => () => contextHistory.dispose(), [contextHistory]);
const changeText = (text: string) => {
const restored = contextHistory.restore(
@@ -87,7 +88,7 @@ export function ComposerEditor({
importRef.current = controller;
setImporting(true);
setComposerContextImporting(draftKey, true);
- try {
+ const settled = await settlePromise(async () => {
const retained = getComposerDraftAfterSelection(draftKey, insertion);
const result = await importComposerContextClipboard(
clipboard,
@@ -111,41 +112,36 @@ export function ComposerEditor({
"Some attachments could not be copied",
"Reconnect to the source environment and copy them again. References without their files are marked unavailable.",
);
- } catch (error) {
- if (!controller.signal.aborted)
- Dialog.alert(
- "Could not paste context",
- error instanceof Error ? error.message : "Try copying again.",
- );
- } finally {
- setComposerContextImporting(draftKey, false);
- importRef.current = null;
- setImporting(false);
+ });
+ setComposerContextImporting(draftKey, false);
+ importRef.current = null;
+ setImporting(false);
+ if (AsyncResult.isFailure(settled) && !controller.signal.aborted) {
+ const error = squashAtomCommandFailure(settled);
+ Dialog.alert(
+ "Could not paste context",
+ error instanceof Error ? error.message : "Try copying again.",
+ );
}
};
- const clipboardFragment = useMemo(
- () =>
- environmentId && draft.context
- ? encodeComposerContextFragment({
- version: 1,
- source: { environmentId },
- records: draft.context.records.map((record) => {
- if (!("attachmentId" in record)) return record;
- const attachment = draft.attachments.find(
- (entry) => entry.id === record.attachmentId,
- );
- return {
- ...record,
- attachmentId:
- attachment?.uploadEnvironmentId === environmentId
- ? (attachment.uploadedAttachmentId ?? record.attachmentId)
- : record.attachmentId,
- };
- }),
- })
- : "",
- [environmentId, draft.context, draft.attachments],
- );
+ const clipboardFragment =
+ environmentId && draft.context
+ ? encodeComposerContextFragment({
+ version: 1,
+ source: { environmentId },
+ records: draft.context.records.map((record) => {
+ if (!("attachmentId" in record)) return record;
+ const attachment = draft.attachments.find((entry) => entry.id === record.attachmentId);
+ return {
+ ...record,
+ attachmentId:
+ attachment?.uploadEnvironmentId === environmentId
+ ? (attachment.uploadedAttachmentId ?? record.attachmentId)
+ : record.attachmentId,
+ };
+ }),
+ })
+ : "";
const navigation = useNavigation();
const selectedReference = selected
? collectComposerContextReferences(selected.source)[0]
diff --git a/apps/mobile/src/components/VideoPreviewModal.ios.tsx b/apps/mobile/src/components/VideoPreviewModal.ios.tsx
index 14afdc5882a..2c95bdca396 100644
--- a/apps/mobile/src/components/VideoPreviewModal.ios.tsx
+++ b/apps/mobile/src/components/VideoPreviewModal.ios.tsx
@@ -1,6 +1,8 @@
import * as Dialog from "./ui/Dialog";
import { useIsFocused } from "@react-navigation/native";
import { requireNativeModule } from "expo";
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import { AsyncResult } from "effect/reactivity";
import { useEffect, useEffectEvent, useId, useState } from "react";
import { Keyboard } from "react-native";
@@ -76,20 +78,23 @@ function NativeVideoPreview(props: {
? await loadLocalAttachmentPreview(localAttachment, controller.signal)
: null;
if (localAttachment !== null && !file) return;
- try {
- if (controller.signal.aborted) return;
- ready = true;
- await NativeControls.presentVideo(
+ if (controller.signal.aborted) {
+ file?.dispose();
+ return;
+ }
+ ready = true;
+ const presented = await settlePromise(() =>
+ NativeControls.presentVideo(
file?.uri ?? playbackUrl!,
name,
source.sourceIdentifier ?? "",
identifier,
- );
- if (!controller.signal.aborted) onRequestClose();
- } finally {
- // Native completion follows dismissal, so local playback keeps its file lease.
- file?.dispose();
- }
+ ),
+ );
+ // Native completion follows dismissal, so local playback keeps its file lease.
+ file?.dispose();
+ if (AsyncResult.isFailure(presented)) throw squashAtomCommandFailure(presented);
+ if (!controller.signal.aborted) onRequestClose();
})().catch((error: unknown) => {
if (controller.signal.aborted) return;
// AVKit gives no retry, so re-mint now; the cached URL may simply have expired.
diff --git a/apps/mobile/src/components/VideoPreviewModal.tsx b/apps/mobile/src/components/VideoPreviewModal.tsx
index bfeacb79779..053bf104517 100644
--- a/apps/mobile/src/components/VideoPreviewModal.tsx
+++ b/apps/mobile/src/components/VideoPreviewModal.tsx
@@ -1,6 +1,6 @@
import { useIsFocused } from "@react-navigation/native";
import { videoMimeType } from "@t3tools/shared/video";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useEffectEvent, useState } from "react";
import { Keyboard, Modal, Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -60,14 +60,15 @@ function useLocalPlayback(source: LocalVideoPreviewSource): PlaybackState {
const [error, setError] = useState<string | null>(null);
// Only a different file needs a new lease; a metadata update on the same
// draft must not dispose the file Android is still playing.
- const attachmentRef = useRef(attachment);
- attachmentRef.current = attachment;
+ const loadAttachment = useEffectEvent((signal: AbortSignal) =>
+ loadLocalAttachmentPreview(attachment, signal),
+ );
const { id: attachmentId, fileUri } = attachment;
useEffect(() => {
setUri(null);
setError(null);
const controller = new AbortController();
- const loading = loadLocalAttachmentPreview(attachmentRef.current, controller.signal);
+ const loading = loadAttachment(controller.signal);
void loading.then(
(file) => {
if (file === null) return;
diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
index 638116844c1..e98120e8263 100644
--- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
+++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
@@ -12,7 +12,7 @@ import {
} from "@react-navigation/native";
import type { EnvironmentId } from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { Linking, Pressable, StyleSheet, View } from "react-native";
import Svg, { Defs, RadialGradient, Rect, Stop } from "react-native-svg";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -95,19 +95,19 @@ export function ConnectionsNewRouteScreen({
}
}, [pairingConnectionError]);
- const handleHostChange = useCallback((value: string) => {
+ const handleHostChange = (value: string) => {
setHostInput(value);
setPendingConnectionError(null);
- }, []);
+ };
- const handleCodeChange = useCallback((value: string) => {
+ const handleCodeChange = (value: string) => {
setCodeInput(value);
setPendingConnectionError(null);
- }, []);
+ };
useEffect(() => () => setPendingConnectionError(null), []);
- const handleScanPress = useCallback(async () => {
+ const handleScanPress = async () => {
const permission = await requestCameraPermission();
if (permission.granted) {
setScanComplete(false);
@@ -122,68 +122,59 @@ export function ConnectionsNewRouteScreen({
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
);
- }, [requestCameraPermission]);
+ };
- const handleQrScan = useCallback(
- ({ data }: { readonly data: string }) => {
- if (scannerLocked) {
- return;
- }
+ const handleQrScan = ({ data }: { readonly data: string }) => {
+ if (scannerLocked) {
+ return;
+ }
- setScannerLocked(true);
+ setScannerLocked(true);
- try {
- const pairingUrl = extractPairingUrlFromQrPayload(data);
- const { host, code } = parsePairingUrl(pairingUrl);
- setHostInput(host);
- setCodeInput(code);
- onChangeConnectionPairingUrl(pairingUrl);
- setScanComplete(true);
+ try {
+ const pairingUrl = extractPairingUrlFromQrPayload(data);
+ const { host, code } = parsePairingUrl(pairingUrl);
+ setHostInput(host);
+ setCodeInput(code);
+ onChangeConnectionPairingUrl(pairingUrl);
+ setScanComplete(true);
+ setScannerLocked(false);
+ } catch (error) {
+ void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
+ Dialog.alert(
+ "Invalid QR code",
+ error instanceof Error ? error.message : "Scanned QR code was not recognized.",
+ );
+ setTimeout(() => {
setScannerLocked(false);
- } catch (error) {
- void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
- Dialog.alert(
- "Invalid QR code",
- error instanceof Error ? error.message : "Scanned QR code was not recognized.",
- );
- setTimeout(() => {
- setScannerLocked(false);
- }, 600);
- }
- },
- [onChangeConnectionPairingUrl, scannerLocked],
- );
+ }, 600);
+ }
+ };
- const connectAndClose = useCallback(
- async (pairingUrl: string) => {
- setIsSubmitting(true);
- onChangeConnectionPairingUrl(pairingUrl);
- try {
- const result = await onConnectPress(pairingUrl, params.routeFor);
- void Haptics.notificationAsync(
- AsyncResult.isSuccess(result)
- ? Haptics.NotificationFeedbackType.Success
- : Haptics.NotificationFeedbackType.Error,
- );
- if (AsyncResult.isSuccess(result)) {
- // Return to whatever opened the sheet. Replacing it with Home would
- // nest Home inside any sheet still below it.
- if (!navigation.canGoBack()) {
- navigation.dispatch(StackActions.replace("Home"));
- } else {
- navigation.goBack();
- }
- }
- } finally {
- setIsSubmitting(false);
+ const connectAndClose = async (pairingUrl: string) => {
+ setIsSubmitting(true);
+ onChangeConnectionPairingUrl(pairingUrl);
+ const result = await onConnectPress(pairingUrl, params.routeFor);
+ setIsSubmitting(false);
+ void Haptics.notificationAsync(
+ AsyncResult.isSuccess(result)
+ ? Haptics.NotificationFeedbackType.Success
+ : Haptics.NotificationFeedbackType.Error,
+ );
+ if (AsyncResult.isSuccess(result)) {
+ // Return to whatever opened the sheet. Replacing it with Home would
+ // nest Home inside any sheet still below it.
+ if (!navigation.canGoBack()) {
+ navigation.dispatch(StackActions.replace("Home"));
+ } else {
+ navigation.goBack();
}
- },
- [navigation, onChangeConnectionPairingUrl, onConnectPress, params.routeFor],
- );
+ }
+ };
- const handleSubmit = useCallback(async () => {
+ const handleSubmit = async () => {
await connectAndClose(buildPairingUrl(hostInput, codeInput));
- }, [codeInput, connectAndClose, hostInput]);
+ };
useEffect(() => {
if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx
index 849c112dc70..eb05271e89e 100644
--- a/apps/mobile/src/features/projects/AddProjectScreen.tsx
+++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx
@@ -56,7 +56,7 @@ import {
} from "@t3tools/contracts";
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
import { SymbolView } from "../../components/ui/AppSymbol";
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useEffect, useRef, useState, type ReactNode } from "react";
import { Platform, Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import * as Arr from "effect/Array";
@@ -315,61 +315,48 @@ function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirecto
});
const [browseNavigation] = useState(createBrowseNavigationCoordinator);
const [isBrowseNavigating, setIsBrowseNavigating] = useState(false);
- const setPathInput = useCallback(
- (path: string) => {
- browseNavigation.invalidate();
+ const setPathInput = (path: string) => {
+ browseNavigation.invalidate();
+ setIsBrowseNavigating(false);
+ commitPathInput(path);
+ };
+ const navigateToBrowsePath = async (input: {
+ readonly browseDirectoryPath: string;
+ readonly selectedDirectoryName?: string;
+ }) => {
+ const selectedDirectoryPath = input.selectedDirectoryName
+ ? appendBrowsePathSegment(input.browseDirectoryPath, input.selectedDirectoryName)
+ : input.browseDirectoryPath;
+ const nextPathInput =
+ pinnedDirectoryName && input.selectedDirectoryName
+ ? getCloneDestinationBrowsePath({
+ browseDirectoryPath: input.browseDirectoryPath,
+ selectedDirectoryName: input.selectedDirectoryName,
+ cloneDirectoryName: pinnedDirectoryName,
+ caseSensitive: clonePathCaseSensitive,
+ })
+ : getCloneDestinationPath(selectedDirectoryPath, pinnedDirectoryName);
+ setIsBrowseNavigating(true);
+ const committed = await browseNavigation.run(
+ async () => {
+ if (
+ environment &&
+ readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) &&
+ canPreloadBrowsePath(environmentRuntime?.connectionState)
+ ) {
+ await loadBrowsePath({
+ environmentId: environment.environmentId,
+ input: { partialPath: selectedDirectoryPath },
+ });
+ }
+ },
+ () => commitPathInput(nextPathInput),
+ );
+ if (committed) {
setIsBrowseNavigating(false);
- commitPathInput(path);
- },
- [browseNavigation],
- );
- const navigateToBrowsePath = useCallback(
- async (input: {
- readonly browseDirectoryPath: string;
- readonly selectedDirectoryName?: string;
- }) => {
- const selectedDirectoryPath = input.selectedDirectoryName
- ? appendBrowsePathSegment(input.browseDirectoryPath, input.selectedDirectoryName)
- : input.browseDirectoryPath;
- const nextPathInput =
- pinnedDirectoryName && input.selectedDirectoryName
- ? getCloneDestinationBrowsePath({
- browseDirectoryPath: input.browseDirectoryPath,
- selectedDirectoryName: input.selectedDirectoryName,
- cloneDirectoryName: pinnedDirectoryName,
- caseSensitive: clonePathCaseSensitive,
- })
- : getCloneDestinationPath(selectedDirectoryPath, pinnedDirectoryName);
- setIsBrowseNavigating(true);
- const committed = await browseNavigation.run(
- async () => {
- if (
- environment &&
- readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) &&
- canPreloadBrowsePath(environmentRuntime?.connectionState)
- ) {
- await loadBrowsePath({
- environmentId: environment.environmentId,
- input: { partialPath: selectedDirectoryPath },
- });
- }
- },
- () => commitPathInput(nextPathInput),
- );
- if (committed) {
- setIsBrowseNavigating(false);
- }
- return committed;
- },
- [
- browseNavigation,
- clonePathCaseSensitive,
- environment,
- environmentRuntime?.connectionState,
- loadBrowsePath,
- pinnedDirectoryName,
- ],
- );
+ }
+ return committed;
+ };
useEffect(() => {
if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
@@ -398,7 +385,7 @@ function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
const { savedConnectionsById } = useSavedRemoteConnections();
const { connectedEnvironments } = useRemoteConnectionStatus();
- return useMemo<ReadonlyArray<EnvironmentOption>>(() => {
+ return ((): ReadonlyArray<EnvironmentOption> => {
const runtimeByEnvironmentId = new Map(
connectedEnvironments.map((environment) => [environment.environmentId, environment] as const),
);
@@ -422,7 +409,7 @@ function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
options.filter((environment) => canCreateProjectInEnvironment(environment.connectionState)),
environmentOptionOrder,
);
- }, [connectedEnvironments, savedConnectionsById, serverConfigByEnvironmentId]);
+ })();
}
function useSelectedEnvironment(): {
@@ -544,10 +531,7 @@ export function AddProjectSourceScreen() {
input: {},
}),
);
- const readiness = useMemo(
- () => buildAddProjectRemoteSourceReadiness(discoveryState.data),
- [discoveryState.data],
- );
+ const readiness = buildAddProjectRemoteSourceReadiness(discoveryState.data);
return (
<AddProjectShell title="Add project">
@@ -706,58 +690,26 @@ function useCreateProject(environment: EnvironmentOption | null) {
const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
const projects = useProjects();
- return useCallback(
- async (workspaceRoot: string) => {
- if (
- !environment ||
- !canCreateProjectInEnvironment(environment.connectionState) ||
- !readEnvironmentScope(environment.environmentId, AuthOrchestrationOperateScope)
- ) {
- Dialog.alert(
- "Project not added",
- `This connection cannot add projects right now. Any existing files remain at ${workspaceRoot}.`,
- );
- return;
- }
-
- const existing = findExistingAddProject({
- projects,
- environmentId: environment.environmentId,
- path: workspaceRoot,
- });
- if (existing) {
- Dialog.alert("Project already exists", existing.title);
- navigation.dispatch(
- CommonActions.reset({
- index: 0,
- routes: [
- {
- name: "NewTaskDraft",
- params: {
- environmentId: existing.environmentId,
- projectId: existing.id,
- title: existing.title,
- },
- },
- ],
- }),
- );
- return;
- }
+ return async (workspaceRoot: string) => {
+ if (
+ !environment ||
+ !canCreateProjectInEnvironment(environment.connectionState) ||
+ !readEnvironmentScope(environment.environmentId, AuthOrchestrationOperateScope)
+ ) {
+ Dialog.alert(
+ "Project not added",
+ `This connection cannot add projects right now. Any existing files remain at ${workspaceRoot}.`,
+ );
+ return;
+ }
- const projectId = ProjectId.make(uuidv4());
- const command = buildProjectCreateCommand({
- commandId: CommandId.make(uuidv4()),
- projectId,
- workspaceRoot,
- });
- const result = await createProject({
- environmentId: environment.environmentId,
- input: command,
- });
- if (AsyncResult.isFailure(result)) {
- return result;
- }
+ const existing = findExistingAddProject({
+ projects,
+ environmentId: environment.environmentId,
+ path: workspaceRoot,
+ });
+ if (existing) {
+ Dialog.alert("Project already exists", existing.title);
navigation.dispatch(
CommonActions.reset({
index: 0,
@@ -765,18 +717,47 @@ function useCreateProject(environment: EnvironmentOption | null) {
{
name: "NewTaskDraft",
params: {
- environmentId: environment.environmentId,
- projectId,
- title: inferProjectTitleFromPath(workspaceRoot),
+ environmentId: existing.environmentId,
+ projectId: existing.id,
+ title: existing.title,
},
},
],
}),
);
+ return;
+ }
+
+ const projectId = ProjectId.make(uuidv4());
+ const command = buildProjectCreateCommand({
+ commandId: CommandId.make(uuidv4()),
+ projectId,
+ workspaceRoot,
+ });
+ const result = await createProject({
+ environmentId: environment.environmentId,
+ input: command,
+ });
+ if (AsyncResult.isFailure(result)) {
return result;
- },
- [createProject, environment, projects, navigation],
- );
+ }
+ navigation.dispatch(
+ CommonActions.reset({
+ index: 0,
+ routes: [
+ {
+ name: "NewTaskDraft",
+ params: {
+ environmentId: environment.environmentId,
+ projectId,
+ title: inferProjectTitleFromPath(workspaceRoot),
+ },
+ },
+ ],
+ }),
+ );
+ return result;
+ };
}
function useEnvironmentFromParam(
@@ -801,7 +782,7 @@ export function AddProjectRepositoryScreen(props: {
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
- const lookupRepository = useCallback(async () => {
+ const lookupRepository = async () => {
if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
setError(null);
setIsSubmitting(true);
@@ -843,7 +824,7 @@ export function AddProjectRepositoryScreen(props: {
);
}
setIsSubmitting(false);
- }, [environment, isSubmitting, lookupRepositoryQuery, repositoryInput, navigation, source]);
+ };
return (
<AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
@@ -888,14 +869,9 @@ function FolderBrowser(props: {
}) => Promise<boolean>;
readonly pinnedDirectoryName?: string;
}) {
- const browsePath = useMemo(
- () => getFilesystemBrowsePath(props.pathInput, props.environment.platform),
- [props.environment.platform, props.pathInput],
- );
- const browseInput = useMemo(
- () => (browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null),
- [browsePath.directoryPath],
- );
+ const browsePath = getFilesystemBrowsePath(props.pathInput, props.environment.platform);
+ const browseInput =
+ browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null;
const fileAccessSession = useEnvironmentQuery(
environmentSession.sessionStateAtom(props.environment.environmentId),
);
@@ -920,9 +896,9 @@ function FolderBrowser(props: {
? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
: browsePath.filterQuery === pinnedDirectoryName;
const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
- const { visibleEntries: visibleBrowseEntries } = useMemo(
- () => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browseFilterQuery),
- [browseFilterQuery, browseState.data?.entries],
+ const { visibleEntries: visibleBrowseEntries } = filterFilesystemBrowseEntries(
+ browseState.data?.entries ?? [],
+ browseFilterQuery,
);
return (
@@ -1065,59 +1041,58 @@ export function AddProjectNewScreen(props: { readonly environmentId?: string | s
submittingRef.current = true;
setError(null);
setIsSubmitting(true);
- try {
- const result = await createNew({
+ const result = await createNew({
+ environmentId: environment.environmentId,
+ input: { name: trimmedName },
+ });
+ if (AsyncResult.isFailure(result)) {
+ submittingRef.current = false;
+ setIsSubmitting(false);
+ setError(errorMessage(Cause.squash(result.cause)));
+ return;
+ }
+ const { projectId, workspaceRoot, commitError } = result.value;
+ if (commitError !== undefined) {
+ Dialog.alert("Created without a first commit", commitError);
+ }
+ if (publishes && publishTarget !== null) {
+ void publishRepository({
environmentId: environment.environmentId,
- input: { name: trimmedName },
+ input: {
+ cwd: workspaceRoot,
+ provider: publishTarget.definition.kind,
+ repository: getNewProjectRepository(publishTarget, workspaceRoot),
+ visibility: "private",
+ },
+ }).then((publishResult) => {
+ if (AsyncResult.isFailure(publishResult)) {
+ Dialog.alert(
+ `Could not create the ${publishTarget.definition.label} repository`,
+ errorMessage(Cause.squash(publishResult.cause)),
+ );
+ }
});
- if (AsyncResult.isFailure(result)) {
- setError(errorMessage(Cause.squash(result.cause)));
- return;
- }
- const { projectId, workspaceRoot, commitError } = result.value;
- if (commitError !== undefined) {
- Dialog.alert("Created without a first commit", commitError);
- }
- if (publishes && publishTarget !== null) {
- void publishRepository({
- environmentId: environment.environmentId,
- input: {
- cwd: workspaceRoot,
- provider: publishTarget.definition.kind,
- repository: getNewProjectRepository(publishTarget, workspaceRoot),
- visibility: "private",
- },
- }).then((publishResult) => {
- if (AsyncResult.isFailure(publishResult)) {
- Dialog.alert(
- `Could not create the ${publishTarget.definition.label} repository`,
- errorMessage(Cause.squash(publishResult.cause)),
- );
- }
- });
- }
- // The draft screen resolves its project from the client store, so it
- // must not open before the create event has arrived.
- const project = await waitForProject(
- { environmentId: environment.environmentId, projectId },
- 15_000,
+ }
+ // The draft screen resolves its project from the client store, so it
+ // must not open before the create event has arrived.
+ const project = await waitForProject(
+ { environmentId: environment.environmentId, projectId },
+ 15_000,
+ );
+ submittingRef.current = false;
+ setIsSubmitting(false);
+ if (project === null) {
+ setName("");
+ setError(
+ "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
);
- if (project === null) {
- setName("");
- setError(
- "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
- );
- return;
- }
- openNewTaskDraft(navigation, {
- environmentId: environment.environmentId,
- projectId,
- title: trimmedName,
- });
- } finally {
- submittingRef.current = false;
- setIsSubmitting(false);
+ return;
}
+ openNewTaskDraft(navigation, {
+ environmentId: environment.environmentId,
+ projectId,
+ title: trimmedName,
+ });
};
return (
@@ -1251,7 +1226,7 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
- const submitPath = useCallback(async () => {
+ const submitPath = async () => {
if (!environment || isBrowseNavigating || isSubmitting) return;
setError(null);
const resolved = resolveAddProjectPath({
@@ -1270,7 +1245,7 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st
setError(errorMessage(Cause.squash(result.cause)));
}
setIsSubmitting(false);
- }, [createProject, environment, isBrowseNavigating, isSubmitting, pathInput]);
+ };
return (
<AddProjectShell title="Local folder">
@@ -1337,7 +1312,7 @@ export function AddProjectDestinationScreen(props: {
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
- const submitPath = useCallback(async () => {
+ const submitPath = async () => {
if (
!environment ||
!readEnvironmentScope(environment.environmentId, AuthSourceControlWriteScope) ||
@@ -1421,18 +1396,7 @@ export function AddProjectDestinationScreen(props: {
}
}
setIsSubmitting(false);
- }, [
- cloneRepository,
- createProject,
- environment,
- isBrowseNavigating,
- isSubmitting,
- navigation,
- pathInput,
- prompt,
- remoteUrl,
- startProjectClone,
- ]);
+ };
return (
<AddProjectShell title="Clone destination">
diff --git a/apps/mobile/src/lib/attachmentDocument.ts b/apps/mobile/src/lib/attachmentDocument.ts
index 37a0a9a2009..282147cfab7 100644
--- a/apps/mobile/src/lib/attachmentDocument.ts
+++ b/apps/mobile/src/lib/attachmentDocument.ts
@@ -1,3 +1,5 @@
+import { AsyncResult } from "effect/reactivity";
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import * as Dialog from "../components/ui/Dialog";
import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
import type { EnvironmentId } from "@t3tools/contracts";
@@ -5,7 +7,7 @@ import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
import { fetch } from "expo/fetch";
import { File } from "expo-file-system";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import type { FileBackedComposerAttachment } from "./composerImages";
import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
@@ -33,25 +35,19 @@ export function useAttachmentDocument(input: {
const delimiter = filePreviewDelimiter(input);
const shareController = useRef<AbortController | null>(null);
useEffect(() => () => shareController.current?.abort(), []);
- const resource = useMemo(
- () => ({
- _tag: "attachment" as const,
- attachmentId: input.attachmentId,
- fileName: input.name,
- mimeType: input.mimeType,
- disposition: "inline" as const,
- }),
- [input.attachmentId, input.name, input.mimeType],
- );
+ const resource = {
+ _tag: "attachment" as const,
+ attachmentId: input.attachmentId,
+ fileName: input.name,
+ mimeType: input.mimeType,
+ disposition: "inline" as const,
+ };
const environmentId = input.attachment ? null : input.environmentId;
const refresh = useRefreshAssetUrl(environmentId, resource);
const [localUri, setLocalUri] = useState<string | null>(null);
const [remoteUri, setRemoteUri] = useState<string | null>(null);
const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
- const table = useMemo(
- () => (content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null),
- [content, delimiter],
- );
+ const table = content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null;
const [error, setError] = useState<string | null>(null);
const [contentError, setContentError] = useState<string | null>(null);
const textReadUrl = useRef<{ uri: string; authorizedAt: number } | null>(null);
@@ -170,18 +166,19 @@ export function useAttachmentDocument(input: {
attachment: { name: input.name, mimeType: input.mimeType },
signal: controller.signal,
};
- try {
+ const result = await settlePromise(async () => {
if (isLocalUri(uri)) await shareLocalAttachment({ ...request, uri });
else await downloadAndShareAttachment({ ...request, url: (await refresh()) ?? uri });
- } catch (cause) {
- if (controller.signal.aborted) return;
+ });
+ if (shareController.current === controller) shareController.current = null;
+ if (controller.signal.aborted) return;
+ setSharing(false);
+ if (AsyncResult.isFailure(result)) {
+ const cause = squashAtomCommandFailure(result);
Dialog.alert(
"Could not share file",
cause instanceof Error ? cause.message : "Please try again.",
);
- } finally {
- if (shareController.current === controller) shareController.current = null;
- if (!controller.signal.aborted) setSharing(false);
}
};
return {
diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.ts
index 2e50626ac36..e0a0bb12e9e 100644
--- a/apps/mobile/src/reactCompilerCoverage.test.ts
+++ b/apps/mobile/src/reactCompilerCoverage.test.ts
@@ -17,17 +17,10 @@ const metroConfig: Promise<{ transformer: { babelTransformerPath: string } }> =
// delete its entry (and its manual useMemo/useCallback/memo) in the same change.
const KNOWN_BAILOUTS: Record<string, string> = {
"src/components/ComposerAttachmentStrip.tsx": "unsupported syntax",
- "src/components/ComposerContextAttachment.tsx":
- "throw inside try, try without catch, try/finally",
- "src/components/ComposerEditor.tsx": "try/finally",
- "src/components/VideoPreviewModal.ios.tsx": "try without catch",
- "src/components/VideoPreviewModal.tsx": "ref read during render",
"src/components/ui/AndroidAnchoredMenu.tsx": "ref read during render",
"src/components/ui/Menu.tsx": "ref read during render",
- "src/features/connection/ConnectionsNewRouteScreen.tsx": "try without catch",
"src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
"src/features/home/thread-swipe-actions.tsx": "ref read during render",
- "src/features/projects/AddProjectScreen.tsx": "try without catch",
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
"src/features/threads/NewTaskContextPickerScreens.tsx":
"manual memo not preserved, try without catch",
@@ -53,16 +46,11 @@ const KNOWN_BAILOUTS: Record<string, string> = {
"src/features/threads/use-thread-list-v2-shelf-preferences.ts": "ref read during render",
"src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
"src/features/voice-input/useVoiceInputController.ts": "ref read during render",
- "src/lib/attachmentDocument.ts": "try/finally",
"src/native/StackHeader.tsx": "ref read during render",
"src/native/T3ComposerEditor.ios.tsx": "ref read during render",
"src/native/T3ComposerEditor.native.tsx": "ref read during render",
- "src/state/composer-attachment-uploads.ts": "try without catch",
- "src/state/mediaActions.ts": "try without catch",
- "src/state/queries.ts": "manual memo not preserved",
"src/state/use-thread-composer-state.ts": "try without catch",
"src/state/use-thread-selection.ts": "ref read during render",
- "src/state/use-vcs-action-state.ts": "manual memo not preserved",
};
// Caller flags Metro passes for an iOS release bundle. supportsReactCompiler is
diff --git a/apps/mobile/src/state/composer-attachment-uploads.test.ts b/apps/mobile/src/state/composer-attachment-uploads.test.ts
index e288c40ec2d..226aeb95a7e 100644
--- a/apps/mobile/src/state/composer-attachment-uploads.test.ts
+++ b/apps/mobile/src/state/composer-attachment-uploads.test.ts
@@ -135,7 +135,10 @@ vi.mock("./attachments", () => ({
attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove },
}));
vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } }));
-vi.mock("@t3tools/client-runtime/state/runtime", () => ({
+vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
+ // The worker settles uploads with the real settlePromise and squashAtomCommandFailure;
+ // only the RPC transport is substituted.
+ ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
createEnvironmentRpcCommand: () => Symbol("rpc-command"),
executeAtomQuery: async (
_registry: unknown,
@@ -164,7 +167,6 @@ vi.mock("@t3tools/client-runtime/state/runtime", () => ({
}
throw new Error("Unexpected RPC command");
},
- squashAtomCommandFailure: (result: { error: unknown }) => result.error,
}));
vi.mock("./use-thread-outbox", async () => {
const { Atom } = await import("effect/reactivity");
diff --git a/apps/mobile/src/state/composer-attachment-uploads.ts b/apps/mobile/src/state/composer-attachment-uploads.ts
index b607be905d0..5f00e08e96d 100644
--- a/apps/mobile/src/state/composer-attachment-uploads.ts
+++ b/apps/mobile/src/state/composer-attachment-uploads.ts
@@ -1,6 +1,7 @@
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { useAtomValue } from "@effect/atom-react";
import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
-import { Atom } from "effect/reactivity";
+import { Atom, AsyncResult } from "effect/reactivity";
import { useEffect, useRef } from "react";
import { prepareTurnAttachments } from "../lib/attachmentUpload";
@@ -73,8 +74,8 @@ export function useComposerAttachmentUploadWorker() {
const release = isFileBackedComposerAttachment(attachment)
? retainComposerAttachmentFileForPreview(attachment)
: undefined;
- try {
- const result = await prepareTurnAttachments({
+ const prepared = await settlePromise(() =>
+ prepareTurnAttachments({
environmentId,
attachments: [attachment],
supportsImageUploads: true,
@@ -104,11 +105,12 @@ export function useComposerAttachmentUploadWorker() {
});
return "persisted";
},
- });
- return result.status === "ready";
- } finally {
- release?.();
- }
+ }),
+ );
+ release?.();
+ // The upload queue owns retry and failure reporting, so a failed upload rethrows to it.
+ if (AsyncResult.isFailure(prepared)) throw squashAtomCommandFailure(prepared);
+ return prepared.value.status === "ready";
},
});
queueRef.current = queue;
diff --git a/apps/mobile/src/state/mediaActions.ts b/apps/mobile/src/state/mediaActions.ts
index 6eae7311cec..a0a9a678205 100644
--- a/apps/mobile/src/state/mediaActions.ts
+++ b/apps/mobile/src/state/mediaActions.ts
@@ -1,3 +1,4 @@
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import * as Dialog from "../components/ui/Dialog";
import type { MediaActionsSource } from "../lib/mediaActionsSource";
import { useNavigation } from "@react-navigation/native";
@@ -62,11 +63,11 @@ export function useMediaActions(source: MediaActionsSource | undefined, onOpenFi
if ("attachment" in source) {
const preview = await loadLocalAttachmentPreview(source.attachment, request.signal);
if (!preview) return;
- try {
- await preview.share(request.signal, source.sourceIdentifier);
- } finally {
- preview.dispose();
- }
+ const shared = await settlePromise(() =>
+ preview.share(request.signal, source.sourceIdentifier),
+ );
+ preview.dispose();
+ if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
return;
}
const uri = "uri" in source ? normalizeNativeMarkdownUrl(source.uri) : await refresh();
diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts
index ca91f165737..2f64e6f164a 100644
--- a/apps/mobile/src/state/queries.ts
+++ b/apps/mobile/src/state/queries.ts
@@ -10,7 +10,6 @@ import type {
EnvironmentId,
OrchestrationV2ProjectedTurnItem,
ProjectId,
- ThreadId,
ThreadPullRequestLink,
VcsListRefsResult,
VcsRef,
@@ -25,7 +24,7 @@ import * as Cause from "effect/Cause";
import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/reactivity";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useEffect, useState } from "react";
import { appAtomRegistry } from "./atom-registry";
import { orchestrationEnvironment } from "./orchestration";
@@ -89,13 +88,10 @@ export function useComposerPullRequestSearch(input: {
query: string | null;
}) {
const query = useDebouncedValue(input.query, 180);
- const linked = useMemo(
- () =>
- input.projectId === null
- ? []
- : composerPullRequestsFromLinks(input.threadPullRequests ?? [], input.projectId),
- [input.projectId, input.threadPullRequests],
- );
+ const linked =
+ input.projectId === null
+ ? []
+ : composerPullRequestsFromLinks(input.threadPullRequests ?? [], input.projectId);
const ready =
query === input.query &&
query !== null &&
@@ -129,7 +125,7 @@ export function useComposerPullRequestSearch(input: {
})
: null,
);
- const entries = useMemo(() => {
+ const entries = (() => {
if (!ready) return [];
if (numeric) {
return filterComposerPullRequestMatches({
@@ -155,7 +151,7 @@ export function useComposerPullRequestSearch(input: {
return [...unique.values()]
.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
.slice(0, 20);
- }, [ready, exact.data, list.data, linked, input.projectId, input.repository, numeric, query]);
+ })();
return {
entries,
isPending: input.query !== null && (query !== input.query || list.isPending || exact.isPending),
@@ -174,10 +170,8 @@ export function useThreadSearch(
const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS);
const canSearch = environmentIds.length > 0 && normalizedQuery.length >= 2;
const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null;
- const searchKey = useMemo(
- () => (settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery)),
- [environmentIds, settledQuery],
- );
+ const searchKey =
+ settledQuery === null ? null : makeThreadSearchKey(environmentIds, settledQuery);
const result = useAtomValue(
searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearchResultsAtom(searchKey),
);
@@ -222,29 +216,22 @@ export function usePaginatedBranches(target: VcsRefTarget) {
cursors: INITIAL_BRANCH_CURSORS,
});
const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
- const pageAtoms = useMemo(
- () =>
- target.environmentId !== null && target.cwd !== null
- ? cursors.map((cursor) =>
- vcsEnvironment.listRefs({
- environmentId: target.environmentId!,
- input: {
- cwd: target.cwd!,
- ...(query.length > 0 ? { query } : {}),
- ...(cursor === undefined ? {} : { cursor }),
- limit: VCS_REF_LIST_LIMIT,
- },
- }),
- )
- : [],
- [cursors, query, target.cwd, target.environmentId],
- );
- const pagesAtom = useMemo(
- () =>
- Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
- Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
- ),
- [pageAtoms, targetKey],
+ const pageAtoms =
+ target.environmentId !== null && target.cwd !== null
+ ? cursors.map((cursor) =>
+ vcsEnvironment.listRefs({
+ environmentId: target.environmentId!,
+ input: {
+ cwd: target.cwd!,
+ ...(query.length > 0 ? { query } : {}),
+ ...(cursor === undefined ? {} : { cursor }),
+ limit: VCS_REF_LIST_LIMIT,
+ },
+ }),
+ )
+ : [];
+ const pagesAtom = Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
+ Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
);
const results = useAtomValue(pagesAtom);
const values = results.flatMap((result) => {
@@ -284,14 +271,14 @@ export function usePaginatedBranches(target: VcsRefTarget) {
: "Failed to load refs.";
})()
: null;
- const refresh = useCallback(() => {
+ const refresh = () => {
const firstPage = pageAtoms[0];
setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
if (firstPage !== undefined) {
appAtomRegistry.refresh(firstPage);
}
- }, [pageAtoms, targetKey]);
- const loadNext = useCallback(() => {
+ };
+ const loadNext = () => {
if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
return;
}
@@ -302,7 +289,7 @@ export function usePaginatedBranches(target: VcsRefTarget) {
? { targetKey, cursors: currentCursors }
: { targetKey, cursors: [...currentCursors, data.nextCursor!] };
});
- }, [data?.nextCursor, targetKey]);
+ };
return {
data,
@@ -316,14 +303,11 @@ export function usePaginatedBranches(target: VcsRefTarget) {
}
export function useComposerPathSearch(target: ComposerPathSearchTarget) {
- const normalizedTarget = useMemo(
- () => ({
- environmentId: target.environmentId,
- cwd: target.cwd,
- query: normalizeComposerPathSearchQuery(target.query),
- }),
- [target.cwd, target.environmentId, target.query],
- );
+ const normalizedTarget = {
+ environmentId: target.environmentId,
+ cwd: target.cwd,
+ query: normalizeComposerPathSearchQuery(target.query),
+ };
const debouncedTarget = useDebouncedValue(normalizedTarget, COMPOSER_PATH_SEARCH_DEBOUNCE_MS);
const fileAccessSession = useEnvironmentQuery(
debouncedTarget.environmentId === null
@@ -372,16 +356,7 @@ export function useComposerPathSearch(target: ComposerPathSearchTarget) {
}
export function useCheckpointDiff(target: CheckpointDiffTarget) {
- const targets = useMemo(
- () => buildCheckpointDiffTargets(target),
- [
- target.environmentId,
- target.fromTurnCount,
- target.ignoreWhitespace,
- target.threadId,
- target.toTurnCount,
- ],
- );
+ const targets = buildCheckpointDiffTargets(target);
const fullThread = useEnvironmentQuery(
targets.fullThread === null
? null
diff --git a/apps/mobile/src/state/use-vcs-action-state.ts b/apps/mobile/src/state/use-vcs-action-state.ts
index 318d38cd198..4124a40d450 100644
--- a/apps/mobile/src/state/use-vcs-action-state.ts
+++ b/apps/mobile/src/state/use-vcs-action-state.ts
@@ -1,7 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import { type VcsActionState, type VcsActionTarget } from "@t3tools/client-runtime/state/vcs";
import { Atom } from "effect/reactivity";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import { appAtomRegistry } from "./atom-registry";
import { vcsActionManager } from "./vcs";
@@ -67,9 +67,9 @@ const EMPTY_PROGRESS: GitActionProgress = {
description: null,
};
-function formatElapsedSeconds(ms: number | null): string | null {
+function formatElapsedSeconds(ms: number | null, nowMs: number): string | null {
if (ms === null) return null;
- const elapsed = Math.max(0, Math.floor((Date.now() - ms) / 1000));
+ const elapsed = Math.max(0, Math.floor((nowMs - ms) / 1000));
if (elapsed < 2) return null;
return `Running for ${elapsed}s`;
}
@@ -78,34 +78,20 @@ export function useGitActionProgress(target: VcsActionTarget): GitActionProgress
const actionState = useVcsActionState(target);
const { result } = useGitActionResultNotification();
- const [, forceUpdate] = useState(0);
- const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
-
- const startElapsedTimer = useCallback(() => {
- if (intervalRef.current) return;
- intervalRef.current = setInterval(() => forceUpdate((n) => n + 1), 1000);
- }, []);
-
- const stopElapsedTimer = useCallback(() => {
- if (intervalRef.current) {
- clearInterval(intervalRef.current);
- intervalRef.current = null;
- }
- }, []);
-
+ // The clock is state the interval advances: a render-time Date.now() would be
+ // cached on the start timestamp by the compiler and the label would freeze.
+ const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
- if (actionState.isRunning) {
- startElapsedTimer();
- } else {
- stopElapsedTimer();
- }
- return stopElapsedTimer;
- }, [actionState.isRunning, startElapsedTimer, stopElapsedTimer]);
+ if (!actionState.isRunning) return;
+ setNowMs(Date.now());
+ const interval = setInterval(() => setNowMs(Date.now()), 1000);
+ return () => clearInterval(interval);
+ }, [actionState.isRunning]);
if (actionState.isRunning) {
const description =
actionState.lastOutputLine ??
- formatElapsedSeconds(actionState.hookStartedAtMs ?? actionState.phaseStartedAtMs);
+ formatElapsedSeconds(actionState.hookStartedAtMs ?? actionState.phaseStartedAtMs, nowMs);
return {
phase: "running",
label: actionState.currentLabel,