@devries-cameron20 / t3code Mirror · read-only / commits / e5ea25d129
Fork 0

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 22, 15:45 UTC

fix(mobile): queued edits end when their run starts, wherever you are (#25468)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 06:52 UTC e5ea25d1292e5342db8508bf48ded67b88b82b82
27 files changed +768 -461
apps/mobile/src/Stack.tsx
+12 -15
@@ -82,7 +82,6 @@ import {
82 NewTaskEnvironmentPickerRouteScreen,
83 } from "./features/threads/NewTaskContextPickerScreens";
84 import {
85 - ExistingThreadSettingsRouteProvider,
85 ExistingThreadSettingsRouteScreen,
86 NewTaskThreadSettingsRouteScreen,
87 } from "./features/threads/ThreadSettingsSheet";
@@ -550,20 +549,18 @@ function RootStackLayout(props: {
549 <ThreadOutboxDrainWorker />
550 <ShowcaseCaptureCoordinator pathname={pathname} />
551 <SettingsEnvironmentFilterProvider open={settingsOpen}>
553 - <ExistingThreadSettingsRouteProvider>
554 - <WorkspaceConnectionStatusProvider>
555 - <AndroidWorkspaceTabsProvider state={props.state}>
556 - <AdaptiveWorkspaceLayout
557 - pathname={workspaceLocation.pathname}
558 - workspaceRouteKey={workspaceLocation.routeKey}
559 - selectedPullRequestKey={selectedPullRequestKey(props.state)}
560 - >
561 - {props.children}
562 - <HardwareKeyboardCommandOverlay />
563 - </AdaptiveWorkspaceLayout>
564 - </AndroidWorkspaceTabsProvider>
565 - </WorkspaceConnectionStatusProvider>
566 - </ExistingThreadSettingsRouteProvider>
552 + <WorkspaceConnectionStatusProvider>
553 + <AndroidWorkspaceTabsProvider state={props.state}>
554 + <AdaptiveWorkspaceLayout
555 + pathname={workspaceLocation.pathname}
556 + workspaceRouteKey={workspaceLocation.routeKey}
557 + selectedPullRequestKey={selectedPullRequestKey(props.state)}
558 + >
559 + {props.children}
560 + <HardwareKeyboardCommandOverlay />
561 + </AdaptiveWorkspaceLayout>
562 + </AndroidWorkspaceTabsProvider>
563 + </WorkspaceConnectionStatusProvider>
564 </SettingsEnvironmentFilterProvider>
565 </HardwareKeyboardCommandProvider>
566 </NewTaskFlowProvider>
apps/mobile/src/components/ComposerAttachmentStrip.tsx
+28 -62
@@ -3,10 +3,13 @@ import { composerImageGallery } from "../lib/composerImageGallery";
3 import { SymbolView } from "./ui/AppSymbol";
4 import { imageMimeType } from "@t3tools/shared/image";
5 import { videoMimeType } from "@t3tools/shared/video";
6 -import { useEffect, useMemo, useState } from "react";
6 +import { useAtomValue } from "@effect/atom-react";
7 +import { AsyncResult, Atom } from "effect/reactivity";
8 +import { Paths } from "expo-file-system";
9 import { Image, Pressable, ScrollView, View } from "react-native";
10
11 import { AppText as Text } from "./ui/AppText";
12 +import { MaterializedPreviewKey, materializedPreviewAtom } from "../lib/composerImagePreview";
13 import { PierreEntryIcon } from "./PierreEntryIcon";
14 import {
15 isFileBackedComposerAttachment,
@@ -93,65 +96,31 @@ export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailPr
96 );
97 }
98
96 -const PREVIEW_CACHE_DIRECTORY = "t3-composer-previews";
97 -
99 /** Fabric re-parses URLs each layout; large data URLs can stall and abort commits. */
100 const INLINE_PREVIEW_FALLBACK_MAX_CHARS = 256_000;
101
101 -async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<string | null> {
102 - const comma = dataUrl.indexOf(",");
103 - if (comma < 0) return null;
104 - const { Directory, File, Paths } = await import("expo-file-system");
105 - const mimeType = /^data:([^;,]+)/.exec(dataUrl)?.[1] ?? "image/jpeg";
106 - const extension = (mimeType.split("/")[1] ?? "jpg").replace("jpeg", "jpg");
107 - const directory = new Directory(Paths.cache, PREVIEW_CACHE_DIRECTORY);
108 - directory.create({ idempotent: true, intermediates: true });
109 - const file = new File(directory, `${id}.${extension}`);
110 - if (!file.exists) {
111 - file.create();
112 - await file.write(dataUrl.slice(comma + 1), { encoding: "base64" });
113 - }
114 - return file.uri;
115 -}
102 +const noMaterializedPreview = Atom.make(AsyncResult.initial<string | null>()).pipe(
103 + Atom.withLabel("composer-image-preview:none"),
104 +);
105
106 function useComposerImagePreviewUri(attachment: DraftComposerImageAttachment): string | null {
118 - const { id, fileUri, previewUri } = attachment;
119 - const [rebased, setRebased] = useState<{ fileUri: string; uri: string } | null>(null);
120 - const [materialized, setMaterialized] = useState<{ id: string; uri: string | null } | null>(null);
107 + const { fileUri, previewUri } = attachment;
108 const inlinePreview = fileUri === undefined && previewUri.startsWith("data:");
122 - useEffect(() => {
123 - if (fileUri === undefined) return;
124 - let cancelled = false;
125 - void (async () => {
126 - const { Paths } = await import("expo-file-system");
127 - const owned = resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri);
128 - if (!cancelled && owned !== null && owned !== previewUri) setRebased({ fileUri, uri: owned });
129 - })();
130 - return () => {
131 - cancelled = true;
132 - };
133 - }, [fileUri, previewUri]);
134 - useEffect(() => {
135 - if (!inlinePreview) return;
136 - let cancelled = false;
137 - void materializeDataUrlPreview(id, previewUri)
138 - .then((uri) => {
139 - if (!cancelled && uri !== null) setMaterialized({ id, uri });
140 - })
141 - .catch((error: unknown) => {
142 - console.warn("[composer-attachments] could not cache an image preview", error);
143 - if (!cancelled) setMaterialized({ id, uri: null });
144 - });
145 - return () => {
146 - cancelled = true;
147 - };
148 - }, [id, inlinePreview, previewUri]);
149 - if (fileUri !== undefined && rebased?.fileUri === fileUri) return rebased.uri;
150 - if (fileUri !== undefined) return previewUri.startsWith("data:") ? fileUri : previewUri;
109 + const materialized = useAtomValue(
110 + inlinePreview
111 + ? materializedPreviewAtom(new MaterializedPreviewKey(attachment))
112 + : noMaterializedPreview,
113 + );
114 + if (fileUri !== undefined) {
115 + // Reinstalls move the app container, so a stored file URI may point at the old one.
116 + const owned = resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri);
117 + if (owned !== null) return owned;
118 + return previewUri.startsWith("data:") ? fileUri : previewUri;
119 + }
120 if (inlinePreview) {
152 - if (materialized?.id !== id) return null;
121 + if (!AsyncResult.isSuccess(materialized)) return null;
122 return (
154 - materialized.uri ??
123 + materialized.value ??
124 (previewUri.length <= INLINE_PREVIEW_FALLBACK_MAX_CHARS ? previewUri : null)
125 );
126 }
@@ -280,15 +249,12 @@ function ComposerVideoAttachment(props: {
249 const { attachment } = props;
250 const sourceIdentifier = `draft:${attachment.id}`;
251 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
283 - const actionsSource = useMemo<MediaActionsSource>(
284 - () => ({
285 - name: attachment.name,
286 - mimeType: videoMimeType(attachment) ?? attachment.mimeType,
287 - sourceIdentifier,
288 - attachment,
289 - }),
290 - [attachment, sourceIdentifier],
291 - );
252 + const actionsSource: MediaActionsSource = {
253 + name: attachment.name,
254 + mimeType: videoMimeType(attachment) ?? attachment.mimeType,
255 + sourceIdentifier,
256 + attachment,
257 + };
258
259 return (
260 <VideoAttachmentTile
@@ -304,7 +270,7 @@ function ComposerVideoAttachment(props: {
270 }
271
272 export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
307 - const gallery = useMemo(() => composerImageGallery(props.attachments), [props.attachments]);
273 + const gallery = composerImageGallery(props.attachments);
274 const size = props.imageSize ?? 72;
275 const radius = props.imageBorderRadius ?? 16;
276 const removeButtonPlacement = props.removeButtonPlacement ?? "overlay";
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
-4
@@ -1246,10 +1246,6 @@ export function NewTaskDraftScreen(props: {
1246 onSendMessage={handleStart}
1247 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
1248 canSwitchThreadProvider
1249 - onUpdateThreadModelSelection={(selection) =>
1250 - flow.setSelectedModelKey(`${selection.instanceId}:${selection.model}`, selection.options)
1251 - }
1252 - onUpdateThreadRuntimeMode={flow.setRuntimeMode}
1249 onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}
1250 onRespondToApproval={async () => {}}
1251 onSelectUserInputOption={() => {}}
apps/mobile/src/features/threads/PendingUserInputCard.tsx
+1
@@ -269,6 +269,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
269 </View>
270 {question.allowCustomAnswer !== false ? (
271 <QuestionAttachments
272 + key={`${props.pendingUserInput.requestId}:${question.id}`}
273 requestId={props.pendingUserInput.requestId}
274 question={question}
275 questions={props.pendingUserInput.questions}
apps/mobile/src/features/threads/QuestionAttachments.tsx
+12 -16
@@ -45,27 +45,23 @@ export function QuestionAttachments(props: {
45 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
46 const configs = useServerConfigs();
47 const drafts = useAtomValue(composerDraftsAtom);
48 - const scopeKey = JSON.stringify([
49 - selectedThread?.environmentId,
50 - selectedThread?.id,
51 - props.requestId,
52 - props.question.id,
53 - ]);
54 - // Unmounted inputs never emit onBlur; explicitly release keyboard ownership.
48 const focusedRef = useRef(false);
49 const onInputFocusChange = props.onInputFocusChange;
57 - const releaseFocus = useEffectEvent(() => {
58 - if (focusedRef.current) onInputFocusChange?.(false);
59 - });
60 - useEffect(() => () => releaseFocus(), []);
61 - const pickerScope = useRef<{ key: string; active: boolean } | null>(null);
50 + // The caller keys this component by request and question, so unmounting ends any open
51 + // picker's scope.
52 + const pickerScope = useRef<{ active: boolean }>({ active: false });
53 useEffect(() => {
63 - const scope = { key: scopeKey, active: true };
54 + const scope = { active: true };
55 pickerScope.current = scope;
56 return () => {
57 scope.active = false;
58 };
68 - }, [scopeKey]);
59 + }, []);
60 + // Unmounted inputs never emit onBlur; explicitly release keyboard ownership.
61 + const releaseFocus = useEffectEvent(() => {
62 + if (focusedRef.current) onInputFocusChange?.(false);
63 + });
64 + useEffect(() => () => releaseFocus(), []);
65 const append = (
66 key: string,
67 attachments: Parameters<typeof appendComposerDraftAttachments>[1],
@@ -106,7 +102,7 @@ export function QuestionAttachments(props: {
102 })
103 .then(async (images) => {
104 if (
109 - scope?.active &&
105 + scope.active &&
106 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0
107 ) {
108 if (append(key, images) > 0)
@@ -150,7 +146,7 @@ export function QuestionAttachments(props: {
146 const picked = "files" in result ? result.files : result.attachments;
147 // Resolution on another client clears the reservation while the picker is open.
148 if (
153 - !scope?.active ||
149 + !scope.active ||
150 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) === 0
151 ) {
152 await releaseUnusedComposerAttachmentFiles(picked);
apps/mobile/src/features/threads/ThreadComposer.tsx
+39 -83
@@ -18,7 +18,6 @@ import {
18 type MessageId,
19 type ModelSelection,
20 type ProviderInteractionMode,
21 - type RuntimeMode,
21 type ServerConfig as T3ServerConfig,
22 type UsageLimitsReport,
23 } from "@t3tools/contracts";
@@ -29,7 +28,14 @@ import {
28 } from "@t3tools/shared/usageLimits";
29 import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
30 import type { ReactNode } from "react";
32 -import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
31 +import {
32 + useEffect,
33 + useEffectEvent,
34 + useLayoutEffect,
35 + useRef,
36 + useState,
37 + type RefObject,
38 +} from "react";
39 import { Keyboard, Platform, View, type ViewStyle } from "react-native";
40 import { composerImageGallery } from "../../lib/composerImageGallery";
41 import { filePreviewGallery } from "../../lib/filePreviewGallery";
@@ -45,6 +51,7 @@ import Animated, {
51 type LayoutAnimationFunction,
52 ReduceMotion,
53 useAnimatedStyle,
54 + useDerivedValue,
55 useSharedValue,
56 withTiming,
57 } from "react-native-reanimated";
@@ -81,15 +88,10 @@ import {
88 composerStripAttachments,
89 type DraftComposerFileAttachment,
90 } from "../../lib/composerImages";
84 -import {
85 - buildModelOptions,
86 - groupByProvider,
87 - isModelSelectionUnavailable,
88 -} from "../../lib/modelOptions";
91 +import { buildModelOptions, isModelSelectionUnavailable } from "../../lib/modelOptions";
92 import { useScaledTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole";
93 import type { RemoteClientConnectionState } from "../../lib/connection";
94 import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
92 -import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
95 import { Menu } from "../../components/ui/Menu";
96 import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
97 import type { FollowUpBehavior } from "../../lib/followUpBehavior";
@@ -111,14 +113,7 @@ import {
113 } from "../voice-input/ComposerDictationControl";
114 import { useVoiceInputController } from "../voice-input/useVoiceInputController";
115 import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
114 -import {
115 - rememberModelOptions,
116 - withRememberedModelOptions,
117 -} from "../../state/use-model-option-memory";
118 -import {
119 - type ExistingThreadSettingsRouteSession,
120 - useExistingThreadSettingsRoutePresentation,
121 -} from "./ThreadSettingsSheet";
116 +import type { ExistingThreadSettingsRouteParams } from "./ThreadSettingsSheet";
117 import {
118 useThreadSettingsSheetPresentation,
119 type NavigationWithFinishTransitioning,
@@ -275,8 +270,6 @@ export interface ThreadComposerProps {
270 ) => Promise<MessageId | null>;
271 readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
272 readonly canSwitchProvider: boolean;
278 - readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
279 - readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
273 readonly onUpdateInteractionMode?: (interactionMode: ProviderInteractionMode) => void;
274 readonly onHeightChange?: (height: number) => void;
275 readonly onEditorFocusChange?: (focused: boolean) => void;
@@ -382,18 +375,15 @@ export function ComposerSurface(props: {
375 const colors = useUniwindTheme();
376 const targetBorderRadius =
377 typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;
385 - const animatedBorderRadius = useSharedValue(targetBorderRadius);
378 const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";
387 - useLayoutEffect(() => {
388 - animatedBorderRadius.set(
389 - shouldAnimate
390 - ? withTiming(targetBorderRadius, {
391 - duration: COMPOSER_TRANSITION_DURATION_MS,
392 - reduceMotion: ReduceMotion.System,
393 - })
394 - : targetBorderRadius,
395 - );
396 - }, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);
379 + const animatedBorderRadius = useDerivedValue(() =>
380 + shouldAnimate
381 + ? withTiming(targetBorderRadius, {
382 + duration: COMPOSER_TRANSITION_DURATION_MS,
383 + reduceMotion: ReduceMotion.System,
384 + })
385 + : targetBorderRadius,
386 + );
387 const borderCurve = props.style.borderCurve;
388 const animatedShapeStyle = useAnimatedStyle(() => ({
389 borderRadius: animatedBorderRadius.value,
@@ -454,12 +444,25 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
444 const pendingPastedTextAttachmentCountRef = useRef(0);
445 const pendingNativeImagePasteCountRef = useRef(0);
446 const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);
447 + const settingsRoutePresentedRef = useRef(false);
448 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
449 editorRef: inputRef,
459 - isEditorFocused: isFocused,
450 + onPresent: () => {
451 + if (settingsRoutePresentedRef.current) return;
452 + settingsRoutePresentedRef.current = true;
453 + // The draft composer edits the new-task flow, which owns its own settings route.
454 + navigation.dispatch(
455 + props.isDraft
456 + ? StackActions.push("NewTaskThreadSettings")
457 + : StackActions.push("ThreadSettingsSheet", {
458 + environmentId: props.environmentId,
459 + threadId: props.selectedThread.id,
460 + draftKey: composerDraftKey,
461 + } satisfies ExistingThreadSettingsRouteParams),
462 + );
463 + },
464 });
461 - const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
462 - const settingsRoutePresentedRef = useRef(false);
465 + const disposeSettingsSheetPresentation = useEffectEvent(settingsSheetPresentation.dispose);
466 const wasExpandedBeforePreviewRef = useRef(false);
467 const inFlightThreadIdsRef = useRef(new Set<string>());
468
@@ -505,7 +508,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
508 });
509 const sendLabel = sendPresentation.label;
510 const currentModelSelection = props.selectedThread.modelSelection;
508 - const currentRuntimeMode = props.selectedThread.runtimeMode;
511 const modelUnavailable =
512 props.connectionState === "connected" &&
513 isModelSelectionUnavailable(
@@ -628,6 +630,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
630 !modelUnavailable;
631
632 useEffect(() => () => setComposerEditing(false), [setComposerEditing]);
633 + // A pending sheet presentation or focus restore has no composer left to act on.
634 + useEffect(() => () => disposeSettingsSheetPresentation(), []);
635
636 const onPressPreview = (source: FilePreviewSource) => {
637 wasExpandedBeforePreviewRef.current = isFocused;
@@ -660,12 +664,14 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
664 const onEditorFocusChange = props.onEditorFocusChange;
665 const handleFocus = () => {
666 setIsFocused(true);
667 + settingsSheetPresentation.onEditorFocusChange(true);
668 onEditorFocusChange?.(true);
669 setComposerEditing(true);
670 };
671
672 const handleBlur = () => {
673 setIsFocused(false);
674 + settingsSheetPresentation.onEditorFocusChange(false);
675 onEditorFocusChange?.(false);
676 setComposerEditing(false);
677 };
@@ -721,65 +727,16 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
727 lockedProviderInstanceId,
728 props.selectedThread.projectId,
729 );
724 - const threadProviderGroups = groupByProvider(modelOptions);
730 const currentModelOption =
731 modelOptions.find(
732 (option) =>
733 option.selection.instanceId === currentModelSelection.instanceId &&
734 option.selection.model === currentModelSelection.model,
735 ) ?? null;
731 - const providerOptionDescriptors = resolveProviderOptionDescriptors({
732 - capabilities: currentModelOption?.capabilities,
733 - selections: currentModelSelection.options,
734 - });
735 - const settingsOwnerId = composerOwnerKey;
736 - const settingsRouteSession = {
737 - ownerId: settingsOwnerId,
738 - environmentId: props.environmentId,
739 - projectId: props.selectedThread.projectId,
740 - providerInstanceId: currentModelSelection.instanceId,
741 - ...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {}),
742 - providerGroups: threadProviderGroups,
743 - selectedModel: currentModelSelection,
744 - prompt: draftMessage,
745 - onPromptChange: (text) => setComposerDraftText(composerDraftKey, text),
746 - reportedModelSelection: props.reportedModelSelection,
747 - onSelectModel: (option) =>
748 - props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),
749 - restoreSelection: withRememberedModelOptions,
750 - optionDescriptors: providerOptionDescriptors,
751 - onUpdateOptionSelections: (options) => {
752 - rememberModelOptions(
753 - currentModelSelection.instanceId,
754 - currentModelSelection.model,
755 - options ?? [],
756 - );
757 - props.onUpdateModelSelection({ ...currentModelSelection, options });
758 - },
759 - runtimeMode: currentRuntimeMode,
760 - onUpdateRuntimeMode: props.onUpdateRuntimeMode,
761 - } satisfies ExistingThreadSettingsRouteSession;
736 const openSettings = () => {
763 - settingsRoutePresentation.present(settingsRouteSession);
737 settingsSheetPresentation.open();
738 };
739
767 - const { present: presentSettingsRoute } = settingsRoutePresentation;
768 - useEffect(() => {
769 - if (settingsSheetPresentation.isActive) {
770 - presentSettingsRoute(settingsRouteSession);
771 - }
772 - }, [presentSettingsRoute, settingsRouteSession, settingsSheetPresentation.isActive]);
773 -
774 - useEffect(() => {
775 - if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
776 - return;
777 - }
778 -
779 - settingsRoutePresentedRef.current = true;
780 - navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
781 - }, [navigation, settingsSheetPresentation.isVisible]);
782 -
740 useFocusEffect(() => {
741 if (!settingsRoutePresentedRef.current) {
742 return;
@@ -787,7 +744,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
744
745 settingsRoutePresentedRef.current = false;
746 settingsSheetPresentation.onDismissed();
790 - settingsRoutePresentation.clear(settingsOwnerId);
747 });
748
749 useEffect(
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
-6
@@ -40,9 +40,7 @@ import { deriveBottomControlInsets, type NativeLayoutMetrics } from "../../lib/r
40 import type {
41 EnvironmentId,
42 MessageId,
43 - ModelSelection,
43 ProviderInteractionMode,
45 - RuntimeMode,
44 RuntimeRequestId,
45 ScopedThreadRef,
46 ServerConfig as T3ServerConfig,
@@ -285,8 +283,6 @@ export interface ThreadDetailScreenProps {
283 ) => Promise<MessageId | null>;
284 readonly onReconnectEnvironment: () => void;
285 readonly canSwitchThreadProvider: boolean;
288 - readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
289 - readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
286 readonly onUpdateThreadInteractionMode?: (interactionMode: ProviderInteractionMode) => void;
287 readonly onRespondToApproval: ApprovalResponder;
288 readonly onSelectUserInputOption: (
@@ -1633,8 +1629,6 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
1629 onSendMessage={handleSendMessage}
1630 onShowUsageLimits={showUsageLimits}
1631 canSwitchProvider={props.canSwitchThreadProvider}
1636 - onUpdateModelSelection={props.onUpdateThreadModelSelection}
1637 - onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
1632 onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
1633 onHeightChange={handleComposerHeightChange}
1634 onEditorFocusChange={handleOwnedInputFocusChange}
apps/mobile/src/features/threads/ThreadQueueControl.tsx
+38 -34
@@ -1,5 +1,6 @@
1 import { type StaticScreenProps, useNavigation } from "@react-navigation/native";
2 import { useAtomValue } from "@effect/atom-react";
3 +import { makeQueuedRunsAtom } from "@t3tools/client-runtime/queued-run-edit";
4 import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
5 import { Atom } from "effect/reactivity";
6 import { Image } from "expo-image";
@@ -48,6 +49,12 @@ const EMPTY_QUEUED_COUNT_ATOM = Atom.make(0).pipe(
49 type QueueTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };
50 type QueueAction = "steer" | "edit" | "up" | "down" | "remove";
51 type QueueRowLayout = { readonly id: RunId; readonly y?: number; readonly height?: number };
52 +type QueueDrag = {
53 + readonly runId: RunId;
54 + readonly order: string;
55 + beforeRunId: RunId | null | undefined;
56 + readonly rows: ReadonlyArray<QueueRowLayout>;
57 +};
58
59 export function useThreadQueueWorkflow(target: QueueTarget) {
60 return useAtomValue(environmentThreadDetails.queueWorkflowAtom(target));
@@ -75,29 +82,18 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
82 const [resuming, setResuming] = useState(false);
83 const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
84 const busyRef = useRef(false);
78 - const [draggedRunId, setDraggedRunId] = useState<RunId | null>(null);
79 - const [previewBeforeRunId, setPreviewBeforeRunId] = useState<RunId | null | undefined>();
80 - const [dragRows, setDragRows] = useState<ReadonlyArray<QueueRowLayout> | null>(null);
85 + const [dragState, setDragState] = useState<QueueDrag | null>(null);
86 const rowLayouts = useRef(new Map<RunId, { y: number; height: number }>());
82 - const drag = useRef<{
83 - runId: RunId;
84 - order: string;
85 - beforeRunId: RunId | null | undefined;
86 - rows: ReadonlyArray<QueueRowLayout>;
87 - } | null>(null);
87 + const drag = useRef<QueueDrag | null>(null);
88 const [translation] = useState(() => new Animated.Value(0));
89 const queuedRuns = workflow?.queuedRuns ?? [];
90 const order = queuedRuns.map(({ run }) => run.id).join(",");
91 -
92 - useEffect(() => {
93 - if (drag.current && drag.current.order !== order) {
94 - drag.current = null;
95 - setDraggedRunId(null);
96 - setPreviewBeforeRunId(undefined);
97 - setDragRows(null);
98 - translation.setValue(0);
99 - }
100 - }, [order, translation]);
91 + // A queue that changed under the drag (delivery, another client) ends it:
92 + // the gesture handlers ignore it from then on and its preview disappears.
93 + const visibleDrag = dragState?.order === order ? dragState : null;
94 + const draggedRunId = visibleDrag?.runId ?? null;
95 + const previewBeforeRunId = visibleDrag?.beforeRunId;
96 + const dragRows = visibleDrag?.rows ?? null;
97
98 const hadQueuedRuns = useRef(queuedRuns.length > 0);
99 useEffect(() => {
@@ -133,13 +129,24 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
129 if (action === "edit") {
130 const entry = queuedRuns[index]!;
131 void Haptics.selectionAsync();
136 - beginQueuedRunEdit(threadKey, {
137 - runId,
138 - messageId: entry.messageId,
139 - originalText: entry.text,
140 - existingAttachments: entry.attachments,
141 - ...(entry.context ? { context: entry.context } : {}),
142 - });
132 + beginQueuedRunEdit(
133 + threadKey,
134 + {
135 + runId,
136 + messageId: entry.messageId,
137 + originalText: entry.text,
138 + existingAttachments: entry.attachments,
139 + ...(entry.context ? { context: entry.context } : {}),
140 + },
141 + makeQueuedRunsAtom({
142 + threadId: target.threadId,
143 + snapshot: threadEnvironment.snapshotAtom(target.environmentId),
144 + detailStatus: environmentThreadDetails.statusAtom(target),
145 + runs: Atom.make(
146 + (get) => get(environmentThreadDetails.quietThreadAtom(target))?.projection.runs ?? null,
147 + ),
148 + }),
149 + );
150 navigation.goBack();
151 return;
152 }
@@ -261,9 +268,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
268 const beforeRunId = resolveQueueDragBeforeRunId(rows, run.id, 0);
269 drag.current = { runId: run.id, order, beforeRunId, rows };
270 translation.setValue(0);
264 - setDragRows(rows);
265 - setPreviewBeforeRunId(beforeRunId);
266 - setDraggedRunId(run.id);
271 + setDragState({ ...drag.current });
272 void Haptics.selectionAsync();
273 }}
274 onMove={(y) => {
@@ -273,7 +278,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
278 const before = resolveQueueDragBeforeRunId(current.rows, run.id, y);
279 if (current.beforeRunId !== before) {
280 current.beforeRunId = before;
276 - setPreviewBeforeRunId(before);
281 + setDragState({ ...current });
282 }
283 }}
284 onEnd={(y, success) => {
@@ -281,9 +286,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
286 const stop = () => {
287 if (drag.current !== started) return;
288 drag.current = null;
284 - setDraggedRunId(null);
285 - setPreviewBeforeRunId(undefined);
286 - setDragRows(null);
289 + setDragState(null);
290 translation.setValue(0);
291 };
292 if (!success || started?.order !== order || started.runId !== run.id) {
@@ -314,7 +317,8 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
317 useNativeDriver: true,
318 }).start();
319 }
317 - setPreviewBeforeRunId(before);
320 + started.beforeRunId = before;
321 + setDragState({ ...started });
322 void move(run.id, before).finally(stop);
323 }}
324 />
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
-2
@@ -1055,8 +1055,6 @@ function ThreadRouteContent(
1055 onSendMessage={composer.onSendMessage}
1056 onReconnectEnvironment={handleReconnectEnvironment}
1057 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1058 - onUpdateThreadModelSelection={composer.onUpdateModelSelection}
1059 - onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
1058 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1059 onRespondToApproval={requests.onRespondToApproval}
1060 onSelectUserInputOption={requests.onSelectUserInputOption}
apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
+90 -54
@@ -20,6 +20,7 @@ import type {
20 ProviderOptionSelection,
21 RuntimeMode,
22 ServerSettings,
23 + ThreadId,
24 } from "@t3tools/contracts";
25 import type { LegendListRenderItemProps } from "@legendapp/list/react-native";
26 import { RegistryContext, useAtomValue } from "@effect/atom-react";
@@ -29,7 +30,12 @@ import {
30 getProviderOptionCurrentValue,
31 getProviderOptionDescriptors,
32 } from "@t3tools/shared/model";
32 -import { useNavigation, useRoute, type RouteProp } from "@react-navigation/native";
33 +import {
34 + useNavigation,
35 + useRoute,
36 + type RouteProp,
37 + type StaticScreenProps,
38 +} from "@react-navigation/native";
39 import { type NativeStackNavigationProp } from "@react-navigation/native-stack";
40 import * as Haptics from "expo-haptics";
41 import { AsyncResult } from "effect/reactivity";
@@ -72,6 +78,19 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
78 import { ChatGptSharingStatus } from "./ChatGptSharingStatus";
79 import { environmentCatalog } from "../../connection/catalog";
80 import { useEnvironmentQuery } from "../../state/query";
81 +import { scopedThreadKey } from "../../lib/scopedEntities";
82 +import { useThreadReportedModelSelection } from "../../state/entities";
83 +import {
84 + setComposerDraftText,
85 + updateComposerDraftSettings,
86 + useComposerDraft,
87 + useComposerDraftSettings,
88 +} from "../../state/use-composer-drafts";
89 +import { useQuietThreadStructure } from "../../state/use-thread-detail";
90 +import { activeComposerDraftKey, useQueuedRunEdit } from "../../state/queued-run-edit";
91 +import { updateThreadDraftModelSelection } from "../../state/use-thread-composer-state";
92 +import { useThreadSelection } from "../../state/use-thread-selection";
93 +import { threadAllowsProviderSwitch } from "../../state/thread-provider-switching";
94 import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server";
95 import { mobilePreferencesAtom } from "../../state/preferences";
96 import { useAtomCommand } from "../../state/use-atom-command";
@@ -260,46 +279,13 @@ type ThreadSettingsSessionProps = {
279 readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
280 };
281
263 -export type ExistingThreadSettingsRouteSession = ThreadSettingsSessionProps & {
264 - readonly ownerId: string;
282 +/** The composer draft the sheet edits: the thread's own, or a queued message being edited. */
283 +export type ExistingThreadSettingsRouteParams = {
284 + readonly environmentId: EnvironmentId;
285 + readonly threadId: ThreadId;
286 + readonly draftKey: string;
287 };
288
267 -type ExistingThreadSettingsRouteContextValue = {
268 - readonly session: ExistingThreadSettingsRouteSession | null;
269 - readonly present: (session: ExistingThreadSettingsRouteSession) => void;
270 - readonly clear: (ownerId: string) => void;
271 -};
272 -
273 -const ExistingThreadSettingsRouteContext =
274 - createContext<ExistingThreadSettingsRouteContextValue | null>(null);
275 -
276 -export function ExistingThreadSettingsRouteProvider(props: { readonly children: ReactNode }) {
277 - const [session, setSession] = useState<ExistingThreadSettingsRouteSession | null>(null);
278 - const present = (nextSession: ExistingThreadSettingsRouteSession) => {
279 - setSession(nextSession);
280 - };
281 - const clear = (ownerId: string) => {
282 - setSession((current) => (current?.ownerId === ownerId ? null : current));
283 - };
284 - const value = { session, present, clear };
285 -
286 - return (
287 - <ExistingThreadSettingsRouteContext.Provider value={value}>
288 - {props.children}
289 - </ExistingThreadSettingsRouteContext.Provider>
290 - );
291 -}
292 -
293 -export function useExistingThreadSettingsRoutePresentation() {
294 - const value = use(ExistingThreadSettingsRouteContext);
295 - if (!value) {
296 - throw new Error(
297 - "useExistingThreadSettingsRoutePresentation must be used inside ExistingThreadSettingsRouteProvider.",
298 - );
299 - }
300 - return value;
301 -}
302 -
289 type ThreadSettingsSessionValue = {
290 readonly environmentId: EnvironmentId | null;
291 readonly providerInstanceId?: ProviderInstanceId;
@@ -1504,26 +1490,76 @@ export function ThreadSettingsPickerScreen(
1490 );
1491 }
1492
1507 -export function ExistingThreadSettingsRouteScreen() {
1493 +export function ExistingThreadSettingsRouteScreen({
1494 + route,
1495 +}: StaticScreenProps<ExistingThreadSettingsRouteParams>) {
1496 const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>();
1509 - const presentation = useExistingThreadSettingsRoutePresentation();
1510 - const session = presentation.session;
1511 -
1512 - useEffect(() => {
1513 - if (session) {
1514 - return;
1515 - }
1516 -
1517 - navigation.goBack();
1518 - }, [navigation, session]);
1519 -
1520 - if (!session) {
1497 + // Reads the same environmentId/threadId params as the Thread route beneath it.
1498 + const { selectedThread, selectedThreadDetailRef, selectedEnvironmentRuntime } =
1499 + useThreadSelection();
1500 + // Streamed text would otherwise re-render the whole model picker on every delta.
1501 + const structure = useQuietThreadStructure(selectedThreadDetailRef);
1502 + const reportedModelSelection = useThreadReportedModelSelection(selectedThreadDetailRef);
1503 + const threadKey = scopedThreadKey(route.params.environmentId, route.params.threadId);
1504 + const draftSettings = useComposerDraftSettings(threadKey);
1505 + const queuedRunEdit = useQueuedRunEdit(threadKey);
1506 + // A queued edit can end while the sheet is open; the prompt then belongs to the thread's draft.
1507 + const draftKey = activeComposerDraftKey(threadKey, route.params.draftKey, queuedRunEdit);
1508 + const prompt = useComposerDraft(draftKey).text;
1509 +
1510 + if (!selectedThread) {
1511 return <View className="flex-1 bg-sheet" />;
1512 }
1513
1524 - const { ownerId: _ownerId, ...settings } = session;
1514 + const serverConfig = selectedEnvironmentRuntime?.serverConfig ?? null;
1515 + const modelSelection = draftSettings.modelSelection ?? selectedThread.modelSelection;
1516 + const lockedProviderInstanceId = threadAllowsProviderSwitch({
1517 + thread: selectedThread,
1518 + projection: structure?.projection,
1519 + })
1520 + ? undefined
1521 + : modelSelection.instanceId;
1522 + const modelOptions = buildModelOptions(
1523 + serverConfig,
1524 + modelSelection,
1525 + lockedProviderInstanceId,
1526 + selectedThread.projectId,
1527 + );
1528 + const currentModelOption =
1529 + modelOptions.find(
1530 + (option) =>
1531 + option.selection.instanceId === modelSelection.instanceId &&
1532 + option.selection.model === modelSelection.model,
1533 + ) ?? null;
1534 + const updateModelSelection = (selection: ModelSelection) =>
1535 + updateThreadDraftModelSelection(threadKey, selection, serverConfig?.providers ?? []);
1536
1526 - return <ThreadSettingsPickerScreen {...settings} onClose={() => navigation.goBack()} />;
1537 + return (
1538 + <ThreadSettingsPickerScreen
1539 + environmentId={selectedThread.environmentId}
1540 + projectId={selectedThread.projectId}
1541 + providerInstanceId={modelSelection.instanceId}
1542 + {...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {})}
1543 + providerGroups={groupByProvider(modelOptions)}
1544 + selectedModel={modelSelection}
1545 + prompt={prompt}
1546 + onPromptChange={(text) => setComposerDraftText(draftKey, text)}
1547 + reportedModelSelection={reportedModelSelection}
1548 + onSelectModel={(option) => updateModelSelection(withRememberedModelOptions(option.selection))}
1549 + restoreSelection={withRememberedModelOptions}
1550 + optionDescriptors={resolveProviderOptionDescriptors({
1551 + capabilities: currentModelOption?.capabilities,
1552 + selections: modelSelection.options,
1553 + })}
1554 + onUpdateOptionSelections={(options) => {
1555 + rememberModelOptions(modelSelection.instanceId, modelSelection.model, options ?? []);
1556 + updateModelSelection({ ...modelSelection, options });
1557 + }}
1558 + runtimeMode={draftSettings.runtimeMode ?? selectedThread.runtimeMode}
1559 + onUpdateRuntimeMode={(runtimeMode) => updateComposerDraftSettings(threadKey, { runtimeMode })}
1560 + onClose={() => navigation.goBack()}
1561 + />
1562 + );
1563 }
1564
1565 /** RNS owns nested sheet dismissal; Reasoning and Runtime remain ordinary pushes. */
apps/mobile/src/features/threads/pending-thread-feed.test.ts
+21 -1
@@ -8,7 +8,11 @@ import {
8 ThreadId,
9 } from "@t3tools/contracts";
10 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
11 -import { appendPendingThreadMessages, isCompactionCommandFeedEntry } from "./pending-thread-feed";
11 +import {
12 + appendPendingThreadMessages,
13 + isCompactionCommandFeedEntry,
14 + selectPendingAcknowledgedMessages,
15 +} from "./pending-thread-feed";
16
17 const pending = (id: string): QueuedThreadMessage => ({
18 environmentId: EnvironmentId.make("env"),
@@ -109,4 +113,20 @@ describe("pending timeline messages", () => {
113 expect(appendPendingThreadMessages([delivered], [delivered], [queued])).toEqual([delivered]);
114 expect(appendPendingThreadMessages([], [delivered], [queued])).toEqual([]);
115 });
116 +
117 + it("stops showing an acknowledged message once the projection holds it, even when the feed hides it", () => {
118 + // A rolled-back or cancelled queued run keeps its message in projection.messages
119 + // while its user_message item leaves the visible feed.
120 + const echoed = pending("rolled-back");
121 + const waiting = pending("waiting");
122 + const shown = selectPendingAcknowledgedMessages([echoed, waiting], {
123 + threadKey: "env:thread",
124 + queuedMessages: [],
125 + projectedMessages: [{ id: echoed.messageId }],
126 + });
127 + expect(shown).toEqual([waiting]);
128 + expect(appendPendingThreadMessages([], [], shown).map((entry) => entry.id)).toEqual([
129 + "waiting",
130 + ]);
131 + });
132 });
apps/mobile/src/features/threads/pending-thread-feed.ts
+19
@@ -4,6 +4,7 @@ import {
4 type ThreadGuestShare,
5 } from "@t3tools/contracts";
6 import type { ThreadFeedEntry } from "../../lib/threadActivity";
7 +import { scopedThreadKey } from "../../lib/scopedEntities";
8 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
9
10 /**
@@ -23,6 +24,24 @@ export type PendingThreadFeedEntry = ThreadFeedEntry & {
24 readonly acknowledged?: boolean;
25 };
26
27 +// An acknowledged row stops being pending once the projection holds its message,
28 +// even when the feed hides that message (a rolled-back or cancelled run).
29 +export function selectPendingAcknowledgedMessages(
30 + acknowledged: ReadonlyArray<QueuedThreadMessage>,
31 + thread: {
32 + readonly threadKey: string | null;
33 + readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;
34 + readonly projectedMessages: ReadonlyArray<{ readonly id: string }> | undefined;
35 + },
36 +): ReadonlyArray<QueuedThreadMessage> {
37 + return acknowledged.filter(
38 + (message) =>
39 + scopedThreadKey(message.environmentId, message.threadId) === thread.threadKey &&
40 + !thread.queuedMessages.some((queued) => queued.messageId === message.messageId) &&
41 + !thread.projectedMessages?.some((projected) => projected.id === message.messageId),
42 + );
43 +}
44 +
45 /** A row of the thread feed's list. */
46 export type ThreadFeedRow = PendingThreadFeedEntry | GuestPendingFeedEntry;
47
apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.ts
+48 -37
@@ -1,4 +1,4 @@
1 -import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
1 +import { useRef, useState, type RefObject } from "react";
2 import { KeyboardController } from "react-native-keyboard-controller";
3
4 import type { ComposerEditorHandle } from "../../components/ComposerEditor";
@@ -18,41 +18,30 @@ const NATIVE_DISMISSAL_ECHO_WINDOW_MS = 150;
18 /** Blur/focus costs two keyboard animations; inputView overrides also replay show when removed. */
19 export function useThreadSettingsSheetPresentation(input: {
20 readonly editorRef: RefObject<ComposerEditorHandle | null>;
21 - readonly isEditorFocused: boolean;
21 + /** Runs on the frame the sheet becomes visible, after the keyboard started leaving. */
22 + readonly onPresent: () => void;
23 }) {
24 + // Destructured so the compiler keys memoized handlers on the stable editor ref, not on
25 + // the fresh input object: the finishTransitioning listener re-subscribes on every change.
26 + const { editorRef, onPresent } = input;
27 const [phase, setPhase] = useState<PresentationPhase>("closed");
28 const isActiveRef = useRef(false);
25 - const isMountedRef = useRef(true);
26 - const isEditorFocusedRef = useRef(input.isEditorFocused);
29 + // Written by the editor's focus handlers; read when restoring focus after dismissal.
30 + const isEditorFocusedRef = useRef(false);
31 const openingIdRef = useRef(0);
32 const focusRestoreIdRef = useRef(0);
33 const restoreFocusAfterDismissRef = useRef(false);
34 const restorePendingRef = useRef(false);
35 const lastStackTransitionFinishedAtRef = useRef(0);
36 const dismissRestoreTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
33 - const clearDismissRestoreTimer = useCallback(() => {
37 + const clearDismissRestoreTimer = () => {
38 if (dismissRestoreTimerRef.current !== null) {
39 clearTimeout(dismissRestoreTimerRef.current);
40 dismissRestoreTimerRef.current = null;
41 }
38 - }, []);
39 -
40 - useEffect(() => {
41 - isEditorFocusedRef.current = input.isEditorFocused;
42 - }, [input.isEditorFocused]);
43 -
44 - useEffect(() => {
45 - isMountedRef.current = true;
46 - return () => {
47 - isMountedRef.current = false;
48 - isActiveRef.current = false;
49 - openingIdRef.current += 1;
50 - focusRestoreIdRef.current += 1;
51 - clearDismissRestoreTimer();
52 - };
53 - }, [clearDismissRestoreTimer]);
42 + };
43
55 - const open = useCallback(() => {
44 + const open = () => {
45 if (isActiveRef.current) {
46 return;
47 }
@@ -62,7 +51,7 @@ export function useThreadSettingsSheetPresentation(input: {
51 clearDismissRestoreTimer();
52 restorePendingRef.current = false;
53 restoreFocusAfterDismissRef.current =
65 - phase === "restoring" || input.isEditorFocused || KeyboardController.isVisible();
54 + phase === "restoring" || isEditorFocusedRef.current || KeyboardController.isVisible();
55 setPhase("opening");
56
57 const openingId = openingIdRef.current + 1;
@@ -70,24 +59,30 @@ export function useThreadSettingsSheetPresentation(input: {
59
60 // Dismiss the keyboard before blur, then present next frame so native transitions overlap.
61 void KeyboardController.dismiss({ animated: true });
73 - input.editorRef.current?.blur();
62 + editorRef.current?.blur();
63
64 requestAnimationFrame(() => {
76 - if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {
65 + // A composer unmounted during the frame takes its editor with it; present nothing.
66 + if (
67 + !isActiveRef.current ||
68 + openingIdRef.current !== openingId ||
69 + editorRef.current === null
70 + ) {
71 return;
72 }
73 setPhase("visible");
74 + onPresent();
75 });
81 - }, [clearDismissRestoreTimer, input.editorRef, input.isEditorFocused, phase]);
76 + };
77
83 - const restoreEditorFocus = useCallback(() => {
78 + const restoreEditorFocus = () => {
79 const focusRestoreId = focusRestoreIdRef.current + 1;
80 focusRestoreIdRef.current = focusRestoreId;
81 let attemptsRemaining = 20;
82
83 // Retry focus restoration if UIKit briefly refuses first responder at the dismissal boundary.
84 const restoreFocus = () => {
90 - if (!isMountedRef.current || focusRestoreIdRef.current !== focusRestoreId) {
85 + if (focusRestoreIdRef.current !== focusRestoreId) {
86 return;
87 }
88 if (isEditorFocusedRef.current || attemptsRemaining <= 0) {
@@ -96,25 +91,25 @@ export function useThreadSettingsSheetPresentation(input: {
91 }
92
93 attemptsRemaining -= 1;
99 - input.editorRef.current?.focus();
94 + editorRef.current?.focus();
95 setTimeout(restoreFocus, 50);
96 };
97 requestAnimationFrame(restoreFocus);
103 - }, [input.editorRef]);
98 + };
99
105 - const runPendingDismissalRestore = useCallback(() => {
100 + const runPendingDismissalRestore = () => {
101 if (!restorePendingRef.current) {
102 return;
103 }
104 restorePendingRef.current = false;
105 clearDismissRestoreTimer();
111 - if (!isMountedRef.current || isActiveRef.current) {
106 + if (isActiveRef.current) {
107 return;
108 }
109 restoreEditorFocus();
115 - }, [clearDismissRestoreTimer, restoreEditorFocus]);
110 + };
111
117 - const onDismissed = useCallback(() => {
112 + const onDismissed = () => {
113 isActiveRef.current = false;
114
115 if (!restoreFocusAfterDismissRef.current) {
@@ -134,19 +129,35 @@ export function useThreadSettingsSheetPresentation(input: {
129 dismissRestoreTimerRef.current = null;
130 runPendingDismissalRestore();
131 }, SHEET_DISMISSAL_KEYBOARD_OVERLAP_MS);
137 - }, [clearDismissRestoreTimer, runPendingDismissalRestore]);
132 + };
133
139 - const onStackTransitionsFinished = useCallback(() => {
134 + const onStackTransitionsFinished = () => {
135 lastStackTransitionFinishedAtRef.current = Date.now();
136 runPendingDismissalRestore();
142 - }, [runPendingDismissalRestore]);
137 + };
138 +
139 + const onEditorFocusChange = (focused: boolean) => {
140 + isEditorFocusedRef.current = focused;
141 + };
142 +
143 + // Called when the composer unmounts: cancels a queued presentation frame, the
144 + // dismissal restore timer, and any focus-restore retries still in flight.
145 + const dispose = () => {
146 + isActiveRef.current = false;
147 + openingIdRef.current += 1;
148 + focusRestoreIdRef.current += 1;
149 + restorePendingRef.current = false;
150 + clearDismissRestoreTimer();
151 + };
152
153 return {
154 isActive: phase === "opening" || phase === "visible",
155 keepsComposerExpanded: phase !== "closed",
156 isVisible: phase === "visible",
157 open,
158 + onEditorFocusChange,
159 onDismissed,
160 onStackTransitionsFinished,
161 + dispose,
162 } as const;
163 }
apps/mobile/src/features/voice-input/ComposerDictationControl.tsx
+11 -17
@@ -1,12 +1,12 @@
1 import type { VoiceInputPhase, VoiceInputState } from "@t3tools/client-runtime/voice-input";
2 -import { memo, useCallback, useLayoutEffect, useState, type ReactNode } from "react";
2 +import { memo, useCallback, useState, type ReactNode } from "react";
3 import { Linking, Pressable, Text as SystemText, View, type LayoutChangeEvent } from "react-native";
4 import Animated, {
5 Easing,
6 ReduceMotion,
7 useAnimatedStyle,
8 + useDerivedValue,
9 useReducedMotion,
9 - useSharedValue,
10 withTiming,
11 type EntryExitAnimationFunction,
12 type SharedValue,
@@ -88,10 +88,8 @@ export function ComposerDictationDraftContent(props: {
88 readonly compact: boolean;
89 readonly hidden: boolean;
90 }) {
91 - const rotation = useSharedValue(props.hidden ? 1 : 0);
92 - useLayoutEffect(() => {
93 - rotation.set(withTiming(props.hidden ? 1 : 0, TOOLBAR_FLIP_TIMING));
94 - }, [props.hidden, rotation]);
91 + const hidden = props.hidden;
92 + const rotation = useDerivedValue(() => withTiming(hidden ? 1 : 0, TOOLBAR_FLIP_TIMING));
93 const compact = props.compact;
94 const animatedStyle = useAnimatedStyle(() => ({
95 opacity: compact ? 1 - rotation.value : 1,
@@ -261,11 +259,10 @@ function VoiceActionButton(props: {
259 readonly variant?: "plain" | "primary";
260 }) {
261 const variant = props.variant ?? "plain";
264 - const loadingVisibility = useSharedValue(props.loading ? 1 : 0);
265 - useLayoutEffect(() => {
266 - loadingVisibility.set(withTiming(props.loading ? 1 : 0, DICTATION_TIMING));
267 - }, [loadingVisibility, props.loading]);
268 - const primaryStyle = useAnimatedStyle(() => ({ opacity: 1 - loadingVisibility.value }));
262 + const loading = props.loading === true;
263 + const primaryStyle = useAnimatedStyle(() => ({
264 + opacity: withTiming(loading ? 0 : 1, DICTATION_TIMING),
265 + }));
266
267 return (
268 <Pressable
@@ -320,15 +317,12 @@ export function ComposerDictationStatus(props: {
317 readonly presentation: VoiceComposerPresentation;
318 readonly onDismissError: () => void;
319 }) {
323 - const recordingVisibility = useSharedValue(props.phase === "recording" ? 1 : 0);
324 - useLayoutEffect(() => {
325 - recordingVisibility.set(withTiming(props.phase === "recording" ? 1 : 0, DICTATION_TIMING));
326 - }, [props.phase, recordingVisibility]);
320 + const recording = props.phase === "recording";
321 const waveformStyle = useAnimatedStyle(() => ({
328 - opacity: recordingVisibility.value,
322 + opacity: withTiming(recording ? 1 : 0, DICTATION_TIMING),
323 }));
324 const labelStyle = useAnimatedStyle(() => ({
331 - opacity: 1 - recordingVisibility.value,
325 + opacity: withTiming(recording ? 0 : 1, DICTATION_TIMING),
326 }));
327
328 if (!props.presentation.statusLabel) return null;
apps/mobile/src/lib/composerImagePreview.test.ts new
+106
@@ -0,0 +1,106 @@
1 +import { describe, expect, it, vi } from "vite-plus/test";
2 +
3 +const mocks = vi.hoisted(() => ({
4 + files: new Set<string>(),
5 + write: vi.fn(async (_content: string, _options: unknown) => undefined),
6 +}));
7 +
8 +vi.mock("expo-file-system", () => ({
9 + Paths: { cache: "file:///cache" },
10 + Directory: class {
11 + constructor(
12 + readonly parent: string,
13 + readonly name: string,
14 + ) {}
15 + create() {}
16 + },
17 + File: class {
18 + uri: string;
19 + constructor(directory: { parent: string; name: string }, name: string) {
20 + this.uri = `${directory.parent}/${directory.name}/${name}`;
21 + }
22 + get exists() {
23 + return mocks.files.has(this.uri);
24 + }
25 + create() {
26 + mocks.files.add(this.uri);
27 + }
28 + delete() {
29 + mocks.files.delete(this.uri);
30 + }
31 + write(content: string, options: unknown) {
32 + return mocks.write(content, options);
33 + }
34 + async move(destination: { uri: string }) {
35 + mocks.files.delete(this.uri);
36 + mocks.files.add(destination.uri);
37 + this.uri = destination.uri;
38 + }
39 + },
40 +}));
41 +
42 +import type { EnvironmentId } from "@t3tools/contracts";
43 +import { AsyncResult, AtomRegistry } from "effect/reactivity";
44 +
45 +import type { DraftComposerImageAttachment } from "./composerImages";
46 +import { MaterializedPreviewKey, materializedPreviewAtom } from "./composerImagePreview";
47 +
48 +describe("materializedPreviewAtom", () => {
49 + it("keeps the materialized preview when the upload reference lands", async () => {
50 + const registry = AtomRegistry.make();
51 + const attachment: DraftComposerImageAttachment = {
52 + id: "image-1",
53 + type: "image",
54 + name: "photo.png",
55 + mimeType: "image/png",
56 + sizeBytes: 3,
57 + previewUri: "data:image/png;base64,AAAA",
58 + };
59 + const atom = materializedPreviewAtom(new MaterializedPreviewKey(attachment));
60 + const unmount = registry.mount(atom);
61 + await vi.waitFor(() => expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true));
62 +
63 + const uploaded = materializedPreviewAtom(
64 + new MaterializedPreviewKey({
65 + ...attachment,
66 + uploadedAttachmentId: "uploaded-1",
67 + uploadEnvironmentId: "env-1" as EnvironmentId,
68 + }),
69 + );
70 +
71 + expect(uploaded).toBe(atom);
72 + const result = registry.get(uploaded);
73 + expect(AsyncResult.isSuccess(result) && result.value).toBe(
74 + "file:///cache/t3-composer-previews/image-1.png",
75 + );
76 + expect(mocks.write).toHaveBeenCalledTimes(1);
77 + unmount();
78 + });
79 +
80 + it("writes the preview again after a failed write instead of reusing the partial file", async () => {
81 + const attachment: DraftComposerImageAttachment = {
82 + id: "image-failed",
83 + type: "image",
84 + name: "photo.png",
85 + mimeType: "image/png",
86 + sizeBytes: 3,
87 + previewUri: "data:image/png;base64,AAAA",
88 + };
89 + const materialize = async () => {
90 + const registry = AtomRegistry.make();
91 + const atom = materializedPreviewAtom(new MaterializedPreviewKey(attachment));
92 + const unmount = registry.mount(atom);
93 + await vi.waitFor(() => expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true));
94 + const result = registry.get(atom);
95 + unmount();
96 + return AsyncResult.isSuccess(result) ? result.value : undefined;
97 + };
98 + using _warn = vi.spyOn(console, "warn").mockImplementation(() => {});
99 + mocks.write.mockClear();
100 + mocks.write.mockRejectedValueOnce(new Error("disk full"));
101 +
102 + expect(await materialize()).toBeNull();
103 + expect(await materialize()).toBe("file:///cache/t3-composer-previews/image-failed.png");
104 + expect(mocks.write).toHaveBeenCalledTimes(2);
105 + });
106 +});
apps/mobile/src/lib/composerImagePreview.ts new
+60
@@ -0,0 +1,60 @@
1 +import * as Effect from "effect/Effect";
2 +import * as Equal from "effect/Equal";
3 +import * as Hash from "effect/Hash";
4 +import { Atom } from "effect/reactivity";
5 +
6 +import type { DraftComposerImageAttachment } from "./composerImages";
7 +
8 +const PREVIEW_CACHE_DIRECTORY = "t3-composer-previews";
9 +
10 +async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<string | null> {
11 + const comma = dataUrl.indexOf(",");
12 + if (comma < 0) return null;
13 + const { Directory, File, Paths } = await import("expo-file-system");
14 + const mimeType = /^data:([^;,]+)/.exec(dataUrl)?.[1] ?? "image/jpeg";
15 + const extension = (mimeType.split("/")[1] ?? "jpg").replace("jpeg", "jpg");
16 + const directory = new Directory(Paths.cache, PREVIEW_CACHE_DIRECTORY);
17 + directory.create({ idempotent: true, intermediates: true });
18 + const file = new File(directory, `${id}.${extension}`);
19 + if (file.exists) return file.uri;
20 + // Write beside the cache entry and move it in, so a failed or interrupted write is never reused.
21 + const partial = new File(directory, `${id}.${extension}.partial`);
22 + if (partial.exists) partial.delete();
23 + partial.create();
24 + try {
25 + await partial.write(dataUrl.slice(comma + 1), { encoding: "base64" });
26 + } catch (error) {
27 + partial.delete();
28 + throw error;
29 + }
30 + await partial.move(file);
31 + return file.uri;
32 +}
33 +
34 +/**
35 + * Keyed by attachment id only: the cached file is named by id, and an upload
36 + * reference landing on the same draft must not restart materialization and
37 + * blank the preview. Hashing the id also avoids rehashing a multi-megabyte data URL.
38 + */
39 +export class MaterializedPreviewKey implements Equal.Equal {
40 + constructor(readonly attachment: DraftComposerImageAttachment) {}
41 + [Equal.symbol](that: unknown): boolean {
42 + return that instanceof MaterializedPreviewKey && that.attachment.id === this.attachment.id;
43 + }
44 + [Hash.symbol](): number {
45 + return Hash.string(this.attachment.id);
46 + }
47 +}
48 +
49 +export const materializedPreviewAtom = Atom.family(({ attachment }: MaterializedPreviewKey) =>
50 + Atom.make(
51 + Effect.tryPromise(() => materializeDataUrlPreview(attachment.id, attachment.previewUri)).pipe(
52 + Effect.catch((error) =>
53 + Effect.sync(() => {
54 + console.warn("[composer-attachments] could not cache an image preview", error);
55 + return null;
56 + }),
57 + ),
58 + ),
59 + ).pipe(Atom.withLabel(`composer-image-preview:${attachment.id}`)),
60 +);
apps/mobile/src/reactCompilerCoverage.test.ts
-1
@@ -14,7 +14,6 @@ const metroConfig: Promise<{ transformer: { babelTransformerPath: string } }> =
14
15 // Remove bailout entries and manual memoization when compilation starts; this check rejects stale entries.
16 const KNOWN_BAILOUTS: Record<string, string> = {
17 - "src/components/ComposerAttachmentStrip.tsx": "unsupported syntax",
17 "src/components/ui/Menu.tsx": "ref read during render",
18 "src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
19 "src/features/home/thread-swipe-actions.tsx": "ref read during render",
apps/mobile/src/state/acknowledged-thread-messages.ts
+30 -6
@@ -1,16 +1,42 @@
1 +import * as Option from "effect/Option";
2 import { Atom } from "effect/reactivity";
3 import { appAtomRegistry } from "./atom-registry";
4 import type { QueuedThreadMessage } from "./thread-outbox-model";
5 +import { environmentThreadDetails } from "./threads";
6
7 // Keep acknowledged rows until their subscribed projection arrives; command receipts can precede messages.
8 +// Render hides rows the projection has echoed, so dropping them here only frees memory.
9 export const acknowledgedThreadMessagesAtom = Atom.make<ReadonlyArray<QueuedThreadMessage>>(
10 [],
11 ).pipe(Atom.keepAlive);
12
10 -export function retainAcknowledgedThreadMessage(message: QueuedThreadMessage) {
13 +// Peeks at a thread only when something already has it in the registry: reading
14 +// it through the registry would open a snapshot load and a live stream of its own.
15 +function isEchoedInMountedThread(message: QueuedThreadMessage): boolean {
16 + const threadAtom = environmentThreadDetails.threadAtom({
17 + environmentId: message.environmentId,
18 + threadId: message.threadId,
19 + });
20 + const node = appAtomRegistry.getNodes().get(threadAtom);
21 + if (node === undefined) return false;
22 + const loaded: Option.Option<Atom.Type<typeof threadAtom>> = node.valueOption();
23 + const thread = Option.getOrNull(loaded);
24 + return thread?.projection.messages.some((entry) => entry.id === message.messageId) ?? false;
25 +}
26 +
27 +function writeAcknowledgedThreadMessages(
28 + update: (current: ReadonlyArray<QueuedThreadMessage>) => ReadonlyArray<QueuedThreadMessage>,
29 +) {
30 const current = appAtomRegistry.get(acknowledgedThreadMessagesAtom);
12 - appAtomRegistry.set(
13 - acknowledgedThreadMessagesAtom,
31 + const next = update(current).filter((entry) => !isEchoedInMountedThread(entry));
32 + if (next.length === current.length && next.every((entry, index) => entry === current[index])) {
33 + return;
34 + }
35 + appAtomRegistry.set(acknowledgedThreadMessagesAtom, next);
36 +}
37 +
38 +export function retainAcknowledgedThreadMessage(message: QueuedThreadMessage) {
39 + writeAcknowledgedThreadMessages((current) =>
40 current.some((entry) => entry.messageId === message.messageId)
41 ? current
42 : [...current, message],
@@ -18,9 +44,7 @@ export function retainAcknowledgedThreadMessage(message: QueuedThreadMessage) {
44 }
45
46 export function forgetAcknowledgedThreadMessage(message: QueuedThreadMessage) {
21 - const current = appAtomRegistry.get(acknowledgedThreadMessagesAtom);
22 - appAtomRegistry.set(
23 - acknowledgedThreadMessagesAtom,
47 + writeAcknowledgedThreadMessages((current) =>
48 current.filter((entry) => entry.messageId !== message.messageId),
49 );
50 }
apps/mobile/src/state/queued-run-edit.test.ts
+83 -1
@@ -1,4 +1,5 @@
1 import { describe, expect, it } from "vite-plus/test";
2 +import { Atom } from "effect/reactivity";
3 import {
4 ChatAttachmentId,
5 ComposerContextId,
@@ -8,7 +9,18 @@ import {
9 type OrchestrationMessageContext,
10 } from "@t3tools/contracts";
11
11 -import { resolveQueuedEditPayload, type QueuedRunEdit } from "./queued-run-edit";
12 +import { appAtomRegistry } from "./atom-registry";
13 +import {
14 + activeComposerDraftKey,
15 + beginQueuedRunEdit,
16 + getQueuedRunEdit,
17 + queuedEditDraftKey,
18 + removeQueuedRunEditAttachment,
19 + resolveQueuedEditPayload,
20 + type QueuedRunEdit,
21 +} from "./queued-run-edit";
22 +import { threadComposerErrorsAtom } from "./thread-composer-error";
23 +import { getComposerDraftSnapshot, setComposerDraftText } from "./use-composer-drafts";
24
25 const image = (id: string): ChatAttachment => ({
26 type: "image",
@@ -80,3 +92,73 @@ describe("resolveQueuedEditPayload", () => {
92 expect(payload.context?.records).toEqual([expect.objectContaining({ attachmentId: "kept" })]);
93 });
94 });
95 +
96 +describe("beginQueuedRunEdit", () => {
97 + it("ends a changed edit when its run starts, without the thread's composer mounted", () => {
98 + const threadKey = "env-exit:thread-exit";
99 + const runId = RunId.make("run-1");
100 + const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
101 + { id: runId, status: "queued" },
102 + ]);
103 + setComposerDraftText(threadKey, "other work");
104 + beginQueuedRunEdit(threadKey, edit([]), runs);
105 + setComposerDraftText(queuedEditDraftKey(threadKey, runId), "changed");
106 +
107 + appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
108 +
109 + expect(getQueuedRunEdit(threadKey)).toBeNull();
110 + expect(getComposerDraftSnapshot(threadKey).text).toBe("other work");
111 + expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
112 + "That message already started, so the edit was discarded.",
113 + );
114 + });
115 +
116 + it("reports a cleared edit as discarded when the run starts", () => {
117 + const threadKey = "env-exit:thread-cleared";
118 + const runId = RunId.make("run-1");
119 + const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
120 + { id: runId, status: "queued" },
121 + ]);
122 + beginQueuedRunEdit(threadKey, edit([]), runs);
123 + setComposerDraftText(queuedEditDraftKey(threadKey, runId), "");
124 +
125 + appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
126 +
127 + expect(getQueuedRunEdit(threadKey)).toBeNull();
128 + expect(getComposerDraftSnapshot(threadKey).text).toBe("");
129 + expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
130 + "That message already started, so the edit was discarded.",
131 + );
132 + });
133 +
134 + it("treats a removed server attachment as a change when the run starts", () => {
135 + const threadKey = "env-exit:thread-removed";
136 + const runId = RunId.make("run-1");
137 + const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([
138 + { id: runId, status: "queued" },
139 + ]);
140 + setComposerDraftText(threadKey, "other work");
141 + beginQueuedRunEdit(threadKey, edit([image("kept")]), runs);
142 + removeQueuedRunEditAttachment(threadKey, "kept");
143 +
144 + appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);
145 +
146 + expect(getQueuedRunEdit(threadKey)).toBeNull();
147 + expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(
148 + "That message already started, so the edit was discarded.",
149 + );
150 + });
151 +});
152 +
153 +describe("activeComposerDraftKey", () => {
154 + const threadKey = "env:thread";
155 + const editKey = queuedEditDraftKey(threadKey, RunId.make("run-1"));
156 +
157 + it("keeps a queued edit's draft while that edit is open", () => {
158 + expect(activeComposerDraftKey(threadKey, editKey, edit([]))).toBe(editKey);
159 + });
160 +
161 + it("falls back to the thread's draft once the edit has ended", () => {
162 + expect(activeComposerDraftKey(threadKey, editKey, null)).toBe(threadKey);
163 + });
164 +});
apps/mobile/src/state/queued-run-edit.ts
+85 -25
@@ -5,15 +5,22 @@ import type {
5 RunId,
6 UploadChatAttachment,
7 } from "@t3tools/contracts";
8 -import { Atom } from "effect/reactivity";
8 import { useAtomValue } from "@effect/atom-react";
9 +import {
10 + makeQueuedRunEditStore,
11 + resolveQueuedEditExit,
12 + type QueuedRunsAtom,
13 +} from "@t3tools/client-runtime/queued-run-edit";
14
15 import { uploadedComposerContext } from "../lib/composerContext";
16 import { appAtomRegistry } from "./atom-registry";
17 import { abortComposerDraftOperations } from "./composerDraftOperations";
18 import { queuedEditDraftKey } from "./queued-edit-draft-key";
19 +import { setThreadComposerError } from "./thread-composer-error";
20 import {
21 clearComposerDraft,
22 + getComposerDraftSnapshot,
23 + mergeComposerDraftContent,
24 setComposerDraftContext,
25 setComposerDraftText,
26 } from "./use-composer-drafts";
@@ -24,38 +31,86 @@ export interface QueuedRunEdit {
31 readonly originalText: string;
32 readonly existingAttachments: ReadonlyArray<ChatAttachment>;
33 readonly context?: OrchestrationMessageContext;
34 + /** Removing a server attachment changes the message even when the draft looks untouched. */
35 + readonly removedExistingAttachment?: true;
36 }
37
29 -export const queuedRunEditsAtom = Atom.make<Readonly<Record<string, QueuedRunEdit>>>({}).pipe(
30 - Atom.keepAlive,
31 - Atom.withLabel("mobile-queued-run-edits"),
32 -);
38 +const queuedRunEdits = makeQueuedRunEditStore<QueuedRunEdit>({
39 + registry: appAtomRegistry,
40 + label: "mobile-queued-run-edits",
41 +});
42
43 export { isQueuedEditDraftKey, queuedEditDraftKey } from "./queued-edit-draft-key";
44
36 -export function getQueuedRunEdit(threadKey: string | null): QueuedRunEdit | null {
37 - if (threadKey === null) return null;
38 - return appAtomRegistry.get(queuedRunEditsAtom)[threadKey] ?? null;
45 +export const getQueuedRunEdit = queuedRunEdits.get;
46 +
47 +/**
48 + * The draft a sheet opened for `requestedKey` should edit now: a queued edit's
49 + * draft only while that edit is still open, else the thread's own draft.
50 + */
51 +export function activeComposerDraftKey(
52 + threadKey: string,
53 + requestedKey: string,
54 + edit: QueuedRunEdit | null,
55 +): string {
56 + if (requestedKey === threadKey) return threadKey;
57 + return edit !== null && queuedEditDraftKey(threadKey, edit.runId) === requestedKey
58 + ? requestedKey
59 + : threadKey;
60 }
61
62 export function useQueuedRunEdit(threadKey: string | null): QueuedRunEdit | null {
42 - const edits = useAtomValue(queuedRunEditsAtom);
63 + const edits = useAtomValue(queuedRunEdits.atom);
64 return threadKey === null ? null : (edits[threadKey] ?? null);
65 }
66
46 -function setQueuedRunEdit(threadKey: string, edit: QueuedRunEdit | null): void {
47 - const current = appAtomRegistry.get(queuedRunEditsAtom);
48 - if (edit === null) {
49 - if (!current[threadKey]) return;
50 - const next = { ...current };
51 - delete next[threadKey];
52 - appAtomRegistry.set(queuedRunEditsAtom, next);
53 - return;
67 +/**
68 + * The run started or was cancelled elsewhere. A changed edit goes back into
69 + * the thread's composer when that is empty; otherwise it is dropped. Either
70 + * way the thread says so, wherever the user is when it happens.
71 + */
72 +function exitQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void {
73 + const editDraftKey = queuedEditDraftKey(threadKey, edit.runId);
74 + const editDraft = getComposerDraftSnapshot(editDraftKey);
75 + const threadDraft = getComposerDraftSnapshot(threadKey);
76 + const editRestorable = editDraft.text.trim().length > 0 || editDraft.attachments.length > 0;
77 + const recovery = resolveQueuedEditExit({
78 + editChanged:
79 + editDraft.text !== edit.originalText ||
80 + editDraft.attachments.length > 0 ||
81 + edit.removedExistingAttachment === true,
82 + // A cleared edit has nothing to put back, so it can only be discarded.
83 + threadDraftEmpty:
84 + editRestorable &&
85 + threadDraft.text.trim().length === 0 &&
86 + threadDraft.attachments.length === 0,
87 + });
88 + if (recovery === "kept") {
89 + // The merge publishes the draft before writing it, so a failed write only delays persistence to the next one.
90 + mergeComposerDraftContent(threadKey, {
91 + text: editDraft.text,
92 + attachments: editDraft.attachments,
93 + ...(editDraft.context ? { context: editDraft.context } : {}),
94 + }).catch((error: unknown) => {
95 + console.warn("[queued-run-edit] could not persist the recovered edit", error);
96 + });
97 }
55 - appAtomRegistry.set(queuedRunEditsAtom, { ...current, [threadKey]: edit });
98 + clearComposerDraft(editDraftKey, { deferAttachmentCleanup: recovery === "kept" });
99 + if (recovery === "clean") return;
100 + setThreadComposerError(
101 + threadKey,
102 + recovery === "kept"
103 + ? "That message already started. Your edit is back in the composer."
104 + : "That message already started, so the edit was discarded.",
105 + );
106 }
107
58 -export function beginQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void {
108 +/** `runs` is the thread's runs; the edit ends when its run leaves the queue. */
109 +export function beginQueuedRunEdit(
110 + threadKey: string,
111 + edit: QueuedRunEdit,
112 + runs: QueuedRunsAtom,
113 +): void {
114 const previous = getQueuedRunEdit(threadKey);
115 if (previous !== null && previous.runId !== edit.runId) {
116 clearComposerDraft(queuedEditDraftKey(threadKey, previous.runId));
@@ -66,18 +121,17 @@ export function beginQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void
121 clearComposerDraft(draftKey);
122 setComposerDraftText(draftKey, edit.originalText);
123 setComposerDraftContext(draftKey, edit.context);
69 - setQueuedRunEdit(threadKey, edit);
124 + queuedRunEdits.begin(threadKey, edit, { runs, onRunLeftQueue: exitQueuedRunEdit });
125 }
126
127 export function removeQueuedRunEditAttachment(threadKey: string, attachmentId: string): void {
73 - const edit = getQueuedRunEdit(threadKey);
74 - if (edit === null) return;
75 - setQueuedRunEdit(threadKey, {
128 + queuedRunEdits.update(threadKey, (edit) => ({
129 ...edit,
130 + removedExistingAttachment: true,
131 existingAttachments: edit.existingAttachments.filter(
132 (attachment) => attachment.id !== attachmentId,
133 ),
80 - });
134 + }));
135 }
136
137 export function endQueuedRunEdit(
@@ -87,9 +141,15 @@ export function endQueuedRunEdit(
141 const edit = getQueuedRunEdit(threadKey);
142 if (edit === null) return;
143 clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), options);
90 - setQueuedRunEdit(threadKey, null);
144 + queuedRunEdits.end(threadKey);
145 }
146
147 +/**
148 + * Claims the open edit for a save; while it runs, the save's result decides the
149 + * edit's fate. Null when there is no edit or a save is already in flight.
150 + */
151 +export const startQueuedRunEditSave = queuedRunEdits.startSave;
152 +
153 /** Attachments replace wholesale; resend kept server attachments with uploads in composer order. */
154 export function resolveQueuedEditPayload(input: {
155 readonly edit: QueuedRunEdit;
apps/mobile/src/state/thread-provider-switching.ts
+2 -2
@@ -1,6 +1,6 @@
1 import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2 import { threadSupportsProviderHandoff } from "@t3tools/client-runtime/state/thread-workflows";
3 -import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
3 +import type { ThreadStructure } from "@t3tools/client-runtime/state/models";
4
5 type ThreadStartMarkers = Pick<
6 EnvironmentThreadShell,
@@ -16,7 +16,7 @@ function threadShellHasStarted(thread: ThreadStartMarkers | null | undefined): b
16
17 export function threadAllowsProviderSwitch(input: {
18 readonly thread: ThreadStartMarkers | null | undefined;
19 - readonly projection: OrchestrationV2ThreadProjection | null | undefined;
19 + readonly projection: ThreadStructure | null | undefined;
20 }): boolean {
21 return input.projection != null
22 ? threadSupportsProviderHandoff(input.projection)
apps/mobile/src/state/use-thread-composer-state.ts
+40 -83
@@ -13,7 +13,7 @@ import {
13 deriveThreadRuntime,
14 threadRuntimeHasInterruptibleRun,
15 } from "@t3tools/client-runtime/state/thread-execution";
16 -import { useEffect, useRef, useState } from "react";
16 +import { useRef, useState } from "react";
17
18 import {
19 CommandId,
@@ -24,7 +24,7 @@ import {
24 type EnvironmentId,
25 type ModelSelection,
26 type ProviderInteractionMode,
27 - type RuntimeMode,
27 + type ServerProvider,
28 type ThreadId,
29 } from "@t3tools/contracts";
30 import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
@@ -54,7 +54,10 @@ import type { DraftComposerImageAttachment } from "../lib/composerImages";
54 import { scopedThreadKey } from "../lib/scopedEntities";
55 import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity";
56 import { acknowledgedThreadMessagesAtom } from "./acknowledged-thread-messages";
57 -import { appendPendingThreadMessages } from "../features/threads/pending-thread-feed";
57 +import {
58 + appendPendingThreadMessages,
59 + selectPendingAcknowledgedMessages,
60 +} from "../features/threads/pending-thread-feed";
61 import { threadAllowsProviderSwitch } from "./thread-provider-switching";
62 import { appAtomRegistry } from "../state/atom-registry";
63 import { pendingThreadCreationMessage } from "./pending-thread-creation";
@@ -68,9 +71,9 @@ import {
71 countComposerDraftAttachmentsAfterSelection,
72 insertComposerDraftText,
73 insertComposerDraftContext,
74 + clearComposerDraft,
75 clearComposerDraftContent,
76 composerContextImportsAtom,
73 - ensureComposerDraftsLoaded,
77 getComposerDraftSnapshot,
78 mergeComposerDraftContent,
79 removeComposerDraftAttachment,
@@ -97,6 +100,7 @@ import {
100 queuedEditDraftKey,
101 removeQueuedRunEditAttachment,
102 resolveQueuedEditPayload,
103 + startQueuedRunEditSave,
104 useQueuedRunEdit,
105 } from "./queued-run-edit";
106 import { setPendingConnectionError } from "../state/use-remote-environment-registry";
@@ -171,6 +175,21 @@ export function useThreadDraftForThread(input: {
175 };
176 }
177
178 +/** A provider without the interaction-mode toggle runs in the default mode. */
179 +export function updateThreadDraftModelSelection(
180 + threadKey: string,
181 + value: ModelSelection,
182 + providers: ReadonlyArray<ServerProvider>,
183 +): void {
184 + const provider = providers.find((candidate) => candidate.instanceId === value.instanceId);
185 + updateComposerDraftSettings(threadKey, {
186 + modelSelection: value,
187 + ...(provider?.showInteractionModeToggle === false
188 + ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
189 + : {}),
190 + });
191 +}
192 +
193 export function useThreadComposerState() {
194 const {
195 selectedThread: selectedThreadShell,
@@ -210,10 +229,6 @@ export function useThreadComposerState() {
229 return nextName;
230 };
231
213 - useEffect(() => {
214 - ensureComposerDraftsLoaded();
215 - }, []);
216 -
232 const selectedThreadKey = selectedThreadShell
233 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
234 : null;
@@ -259,27 +274,16 @@ export function useThreadComposerState() {
274 checkpointSummaries,
275 cache: feedCache,
276 });
262 - const pendingAcknowledgments = acknowledgedMessages.filter(
263 - (message) =>
264 - scopedThreadKey(message.environmentId, message.threadId) === selectedThreadKey &&
265 - !selectedThreadQueuedMessages.some((queued) => queued.messageId === message.messageId),
266 - );
277 + const pendingAcknowledgments = selectPendingAcknowledgedMessages(acknowledgedMessages, {
278 + threadKey: selectedThreadKey,
279 + queuedMessages: selectedThreadQueuedMessages,
280 + projectedMessages: selectedThreadMessages,
281 + });
282 if (pendingAcknowledgments.length === 0) return feed;
283 return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>
284 entry.pendingMessage ? { ...entry, acknowledged: true } : entry,
285 );
286 })();
272 - useEffect(() => {
273 - const echoedIds = new Set(selectedThreadMessages?.map((message) => message.id));
274 - if (acknowledgedMessages.some((message) => echoedIds.has(message.messageId))) {
275 - appAtomRegistry.set(
276 - acknowledgedThreadMessagesAtom,
277 - appAtomRegistry
278 - .get(acknowledgedThreadMessagesAtom)
279 - .filter((message) => !echoedIds.has(message.messageId)),
280 - );
281 - }
282 - }, [acknowledgedMessages, selectedThreadMessages]);
287
288 const preferencesResult = useAtomValue(mobilePreferencesAtom);
289 const followUpBehavior = AsyncResult.isSuccess(preferencesResult)
@@ -392,40 +396,6 @@ export function useThreadComposerState() {
396 ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
397 : null;
398
395 - const selectedThreadRuns = selectedThreadProjection?.projection.runs;
396 - const editedRunId = queuedRunEdit?.runId ?? null;
397 - useEffect(() => {
398 - if (selectedThreadKey === null || editedRunId === null || selectedThreadRuns === undefined) {
399 - return;
400 - }
401 - if (savingQueuedEditRef.current) return;
402 - const stillQueued = selectedThreadRuns.some(
403 - (run) => run.id === editedRunId && run.status === "queued",
404 - );
405 - if (stillQueued) return;
406 - const editDraftKey = queuedEditDraftKey(selectedThreadKey, editedRunId);
407 - const editDraft = getComposerDraftSnapshot(editDraftKey);
408 - const threadDraft = getComposerDraftSnapshot(selectedThreadKey);
409 - const keepable =
410 - editDraft.text.trim().length > 0 &&
411 - threadDraft.text.trim().length === 0 &&
412 - threadDraft.attachments.length === 0;
413 - if (keepable) {
414 - void mergeComposerDraftContent(selectedThreadKey, {
415 - text: editDraft.text,
416 - attachments: editDraft.attachments,
417 - ...(editDraft.context ? { context: editDraft.context } : {}),
418 - });
419 - }
420 - endQueuedRunEdit(selectedThreadKey, { deferAttachmentCleanup: keepable });
421 - setThreadComposerError(
422 - selectedThreadKey,
423 - keepable
424 - ? "That message already started. Your edit is back in the composer."
425 - : "That message already started, so the edit was discarded.",
426 - );
427 - }, [editedRunId, selectedThreadKey, selectedThreadRuns]);
428 -
399 const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
400 const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
401 ? (selectedThreadRuntime?.activeRunId ?? null)
@@ -463,6 +433,8 @@ export function useThreadComposerState() {
433 );
434 return;
435 }
436 + const finishSave = startQueuedRunEditSave(threadKey);
437 + if (finishSave === null) return;
438 savingQueuedEditRef.current = true;
439 setIsSavingQueuedEdit(true);
440 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
@@ -476,6 +448,7 @@ export function useThreadComposerState() {
448 if (AsyncResult.isFailure(prepared)) {
449 savingQueuedEditRef.current = false;
450 setIsSavingQueuedEdit(false);
451 + finishSave(false);
452 const error = squashAtomCommandFailure(prepared);
453 Dialog.alert(
454 "Could not save the queued message",
@@ -486,6 +459,7 @@ export function useThreadComposerState() {
459 if (prepared.value.status !== "ready") {
460 savingQueuedEditRef.current = false;
461 setIsSavingQueuedEdit(false);
462 + finishSave(false);
463 return;
464 }
465 const payload = resolveQueuedEditPayload({
@@ -510,13 +484,20 @@ export function useThreadComposerState() {
484 savingQueuedEditRef.current = false;
485 setIsSavingQueuedEdit(false);
486 if (result._tag !== "Success") {
487 + // The run left the queue during the save; its exit already told the composer what happened.
488 + if (!finishSave(false)) return;
489 Dialog.alert(
490 "Could not save the queued message",
491 "It may have already started. Your edit is still in the composer.",
492 );
493 return;
494 }
519 - endQueuedRunEdit(threadKey, { deferAttachmentCleanup: true });
495 + // False when the edit was cancelled or begun again meanwhile; its draft is the newer edit's.
496 + if (finishSave(true)) {
497 + clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), {
498 + deferAttachmentCleanup: true,
499 + });
500 + }
501 scheduleUnusedComposerAttachmentCleanup(draft.attachments);
502 };
503
@@ -837,28 +818,6 @@ export function useThreadComposerState() {
818 removeComposerDraftAttachment(threadKey, imageId);
819 };
820
840 - const onUpdateModelSelection = (value: ModelSelection) => {
841 - if (!selectedThreadKey) {
842 - return;
843 - }
844 - const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
845 - (candidate) => candidate.instanceId === value.instanceId,
846 - );
847 - updateComposerDraftSettings(selectedThreadKey, {
848 - modelSelection: value,
849 - ...(provider?.showInteractionModeToggle === false
850 - ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
851 - : {}),
852 - });
853 - };
854 -
855 - const onUpdateRuntimeMode = (value: RuntimeMode) => {
856 - if (!selectedThreadKey) {
857 - return;
858 - }
859 - updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
860 - };
861 -
821 const onUpdateInteractionMode = (value: ProviderInteractionMode) => {
822 if (!selectedThreadKey) {
823 return;
@@ -908,8 +867,6 @@ export function useThreadComposerState() {
867 onNativePasteText,
868 onRemoveDraftImage,
869 onSendMessage,
911 - onUpdateModelSelection,
912 - onUpdateRuntimeMode,
870 onUpdateInteractionMode,
871 };
872 }
apps/mobile/src/state/use-thread-detail.ts
+19 -1
@@ -1,7 +1,13 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
3 +import type { EnvironmentThreadStructure } from "@t3tools/client-runtime/state/models";
4 import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
4 -import type { EnvironmentId, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts";
5 +import type {
6 + EnvironmentId,
7 + OrchestrationV2ThreadProjection,
8 + ScopedThreadRef,
9 + ThreadId,
10 +} from "@t3tools/contracts";
11 import { Atom } from "effect/reactivity";
12
13 import { environmentThreadDetails, useEnvironmentThread } from "./threads";
@@ -10,6 +16,9 @@ import { useThreadSelection } from "./use-thread-selection";
16 const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
17 Atom.withLabel("mobile-thread-projection:empty"),
18 );
19 +const EMPTY_THREAD_STRUCTURE_ATOM = Atom.make<EnvironmentThreadStructure | null>(null).pipe(
20 + Atom.withLabel("mobile-thread-structure:empty"),
21 +);
22 const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make<
23 OrchestrationV2ThreadProjection["visibleTurnItems"]
24 >(Object.freeze([])).pipe(Atom.withLabel("mobile-thread-visible-turn-items:empty"));
@@ -42,6 +51,15 @@ export function useThreadProjection(target: ThreadDetailTarget): EnvironmentThre
51 );
52 }
53
54 +/** Keeps its value through streamed text; runs, sessions, and item status still update. */
55 +export function useQuietThreadStructure(
56 + ref: ScopedThreadRef | null,
57 +): EnvironmentThreadStructure | null {
58 + return useAtomValue(
59 + ref === null ? EMPTY_THREAD_STRUCTURE_ATOM : environmentThreadDetails.quietThreadAtom(ref),
60 + );
61 +}
62 +
63 export function useSelectedThreadProjection(): EnvironmentThread | null {
64 const { selectedThreadDetailRef } = useThreadSelection();
65 return useThreadProjection({
apps/mobile/src/state/use-thread-outbox-drain.permissions.test.ts
+1
@@ -78,6 +78,7 @@ vi.mock("./threads", async () => {
78 setInteractionMode: state.interaction,
79 },
80 environmentThreadShells: { threadShellsAtom: Atom.make([state.thread]) },
81 + environmentThreadDetails: { threadAtom: Atom.family((_key: unknown) => Atom.make(null)) },
82 };
83 });
84 vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));
apps/mobile/src/state/use-thread-outbox-drain.test.ts
+7 -3
@@ -89,9 +89,13 @@ vi.mock("./server", async () => {
89
90 vi.mock("./git", () => ({ gitEnvironment: {} }));
91
92 -vi.mock("./threads", () => ({
93 - threadEnvironment: {},
94 -}));
92 +vi.mock("./threads", async () => {
93 + const { Atom } = await import("effect/reactivity");
94 + return {
95 + threadEnvironment: {},
96 + environmentThreadDetails: { threadAtom: Atom.family((_key: unknown) => Atom.make(null)) },
97 + };
98 +});
99
100 vi.mock("./use-atom-command", () => ({
101 useAtomCommand: () => async () => undefined,
packages/client-runtime/src/queuedRunEdit.test.ts
+10 -1
@@ -81,10 +81,19 @@ describe("makeQueuedRunEditStore", () => {
81 const finishSave = store.startSave("env:thread");
82 registry.set(runs, []);
83 expect(exits).toEqual([]);
84 - expect(finishSave?.(false)).toBe(true);
84 + expect(finishSave?.(false)).toBe(false);
85 expect(exits).toHaveLength(1);
86 });
87
88 + it("reports the edit still open when a save fails while its run is queued", () => {
89 + const { store, exits, begin } = setup();
90 + begin();
91 + const finishSave = store.startSave("env:thread");
92 + expect(finishSave?.(false)).toBe(true);
93 + expect(exits).toEqual([]);
94 + expect(store.get("env:thread")).toEqual({ runId: RUN, text: "draft" });
95 + });
96 +
97 it("allows one save at a time and ends the edit when it succeeds", () => {
98 const { registry, store, begin } = setup();
99 begin();
packages/client-runtime/src/queuedRunEdit.ts
+6 -7
@@ -69,10 +69,9 @@ interface ExitWatch<E> {
69 }
70
71 /**
72 - * Settles a save started with `startSave`. Returns false, changing nothing,
73 - * when the edit the save started from was ended or begun again meanwhile; the
74 - * caller must then leave the edit's drafts alone. Otherwise success ends the
75 - * edit and failure resumes its exit watch.
72 + * Settles a save from `startSave`. False, changing nothing, when the edit was
73 + * ended or begun again meanwhile. Success ends the edit; failure resumes its
74 + * exit watch and returns whether the edit survived it.
75 */
76 export type FinishQueuedRunEditSave = (succeeded: boolean) => boolean;
77
@@ -196,10 +195,10 @@ export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(opti
195 if (succeeded) {
196 stopWatch(threadKey);
197 write(threadKey, null);
199 - } else {
200 - subscribe(threadKey, watch);
198 + return true;
199 }
202 - return true;
200 + subscribe(threadKey, watch);
201 + return watches.get(threadKey) === watch;
202 };
203 },
204 };