TypeScript
fix(mobile): queued edits end when their run starts, wherever you are (#25468)
Julius Marmingee5ea25d1292e
diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex 83d075f3489..ffc4b0bc8de 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -82,7 +82,6 @@ import {NewTaskEnvironmentPickerRouteScreen,} from "./features/threads/NewTaskContextPickerScreens";import {- ExistingThreadSettingsRouteProvider,ExistingThreadSettingsRouteScreen,NewTaskThreadSettingsRouteScreen,} from "./features/threads/ThreadSettingsSheet";@@ -550,20 +549,18 @@ function RootStackLayout(props: {<ThreadOutboxDrainWorker /><ShowcaseCaptureCoordinator pathname={pathname} /><SettingsEnvironmentFilterProvider open={settingsOpen}>- <ExistingThreadSettingsRouteProvider>- <WorkspaceConnectionStatusProvider>- <AndroidWorkspaceTabsProvider state={props.state}>- <AdaptiveWorkspaceLayout- pathname={workspaceLocation.pathname}- workspaceRouteKey={workspaceLocation.routeKey}- selectedPullRequestKey={selectedPullRequestKey(props.state)}- >- {props.children}- <HardwareKeyboardCommandOverlay />- </AdaptiveWorkspaceLayout>- </AndroidWorkspaceTabsProvider>- </WorkspaceConnectionStatusProvider>- </ExistingThreadSettingsRouteProvider>+ <WorkspaceConnectionStatusProvider>+ <AndroidWorkspaceTabsProvider state={props.state}>+ <AdaptiveWorkspaceLayout+ pathname={workspaceLocation.pathname}+ workspaceRouteKey={workspaceLocation.routeKey}+ selectedPullRequestKey={selectedPullRequestKey(props.state)}+ >+ {props.children}+ <HardwareKeyboardCommandOverlay />+ </AdaptiveWorkspaceLayout>+ </AndroidWorkspaceTabsProvider>+ </WorkspaceConnectionStatusProvider></SettingsEnvironmentFilterProvider></HardwareKeyboardCommandProvider></NewTaskFlowProvider>diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsxindex 8cac0b59cfd..923afb87a3a 100644--- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx+++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx@@ -3,10 +3,13 @@ import { composerImageGallery } from "../lib/composerImageGallery";import { SymbolView } from "./ui/AppSymbol";import { imageMimeType } from "@t3tools/shared/image";import { videoMimeType } from "@t3tools/shared/video";-import { useEffect, useMemo, useState } from "react";+import { useAtomValue } from "@effect/atom-react";+import { AsyncResult, Atom } from "effect/reactivity";+import { Paths } from "expo-file-system";import { Image, Pressable, ScrollView, View } from "react-native";import { AppText as Text } from "./ui/AppText";+import { MaterializedPreviewKey, materializedPreviewAtom } from "../lib/composerImagePreview";import { PierreEntryIcon } from "./PierreEntryIcon";import {isFileBackedComposerAttachment,@@ -93,65 +96,31 @@ export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailPr);}-const PREVIEW_CACHE_DIRECTORY = "t3-composer-previews";-/** Fabric re-parses URLs each layout; large data URLs can stall and abort commits. */const INLINE_PREVIEW_FALLBACK_MAX_CHARS = 256_000;-async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<string | null> {- const comma = dataUrl.indexOf(",");- if (comma < 0) return null;- const { Directory, File, Paths } = await import("expo-file-system");- const mimeType = /^data:([^;,]+)/.exec(dataUrl)?.[1] ?? "image/jpeg";- const extension = (mimeType.split("/")[1] ?? "jpg").replace("jpeg", "jpg");- const directory = new Directory(Paths.cache, PREVIEW_CACHE_DIRECTORY);- directory.create({ idempotent: true, intermediates: true });- const file = new File(directory, `${id}.${extension}`);- if (!file.exists) {- file.create();- await file.write(dataUrl.slice(comma + 1), { encoding: "base64" });- }- return file.uri;-}+const noMaterializedPreview = Atom.make(AsyncResult.initial<string | null>()).pipe(+ Atom.withLabel("composer-image-preview:none"),+);function useComposerImagePreviewUri(attachment: DraftComposerImageAttachment): string | null {- const { id, fileUri, previewUri } = attachment;- const [rebased, setRebased] = useState<{ fileUri: string; uri: string } | null>(null);- const [materialized, setMaterialized] = useState<{ id: string; uri: string | null } | null>(null);+ const { fileUri, previewUri } = attachment;const inlinePreview = fileUri === undefined && previewUri.startsWith("data:");- useEffect(() => {- if (fileUri === undefined) return;- let cancelled = false;- void (async () => {- const { Paths } = await import("expo-file-system");- const owned = resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri);- if (!cancelled && owned !== null && owned !== previewUri) setRebased({ fileUri, uri: owned });- })();- return () => {- cancelled = true;- };- }, [fileUri, previewUri]);- useEffect(() => {- if (!inlinePreview) return;- let cancelled = false;- void materializeDataUrlPreview(id, previewUri)- .then((uri) => {- if (!cancelled && uri !== null) setMaterialized({ id, uri });- })- .catch((error: unknown) => {- console.warn("[composer-attachments] could not cache an image preview", error);- if (!cancelled) setMaterialized({ id, uri: null });- });- return () => {- cancelled = true;- };- }, [id, inlinePreview, previewUri]);- if (fileUri !== undefined && rebased?.fileUri === fileUri) return rebased.uri;- if (fileUri !== undefined) return previewUri.startsWith("data:") ? fileUri : previewUri;+ const materialized = useAtomValue(+ inlinePreview+ ? materializedPreviewAtom(new MaterializedPreviewKey(attachment))+ : noMaterializedPreview,+ );+ if (fileUri !== undefined) {+ // Reinstalls move the app container, so a stored file URI may point at the old one.+ const owned = resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri);+ if (owned !== null) return owned;+ return previewUri.startsWith("data:") ? fileUri : previewUri;+ }if (inlinePreview) {- if (materialized?.id !== id) return null;+ if (!AsyncResult.isSuccess(materialized)) return null;return (- materialized.uri ??+ materialized.value ??(previewUri.length <= INLINE_PREVIEW_FALLBACK_MAX_CHARS ? previewUri : null));}@@ -280,15 +249,12 @@ function ComposerVideoAttachment(props: {const { attachment } = props;const sourceIdentifier = `draft:${attachment.id}`;const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };- const actionsSource = useMemo<MediaActionsSource>(- () => ({- name: attachment.name,- mimeType: videoMimeType(attachment) ?? attachment.mimeType,- sourceIdentifier,- attachment,- }),- [attachment, sourceIdentifier],- );+ const actionsSource: MediaActionsSource = {+ name: attachment.name,+ mimeType: videoMimeType(attachment) ?? attachment.mimeType,+ sourceIdentifier,+ attachment,+ };return (<VideoAttachmentTile@@ -304,7 +270,7 @@ function ComposerVideoAttachment(props: {}export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {- const gallery = useMemo(() => composerImageGallery(props.attachments), [props.attachments]);+ const gallery = composerImageGallery(props.attachments);const size = props.imageSize ?? 72;const radius = props.imageBorderRadius ?? 16;const removeButtonPlacement = props.removeButtonPlacement ?? "overlay";diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex 61d4e2decac..5efbf0a45cc 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -1246,10 +1246,6 @@ export function NewTaskDraftScreen(props: {onSendMessage={handleStart}onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}canSwitchThreadProvider- onUpdateThreadModelSelection={(selection) =>- flow.setSelectedModelKey(`${selection.instanceId}:${selection.model}`, selection.options)- }- onUpdateThreadRuntimeMode={flow.setRuntimeMode}onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}onRespondToApproval={async () => {}}onSelectUserInputOption={() => {}}diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsxindex 89edbd7a44a..42c4716410b 100644--- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx+++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx@@ -269,6 +269,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {</View>{question.allowCustomAnswer !== false ? (<QuestionAttachments+ key={`${props.pendingUserInput.requestId}:${question.id}`}requestId={props.pendingUserInput.requestId}question={question}questions={props.pendingUserInput.questions}diff --git a/apps/mobile/src/features/threads/QuestionAttachments.tsx b/apps/mobile/src/features/threads/QuestionAttachments.tsxindex a8bd433f024..c4d42c4fa0e 100644--- a/apps/mobile/src/features/threads/QuestionAttachments.tsx+++ b/apps/mobile/src/features/threads/QuestionAttachments.tsx@@ -45,27 +45,23 @@ export function QuestionAttachments(props: {const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);const configs = useServerConfigs();const drafts = useAtomValue(composerDraftsAtom);- const scopeKey = JSON.stringify([- selectedThread?.environmentId,- selectedThread?.id,- props.requestId,- props.question.id,- ]);- // Unmounted inputs never emit onBlur; explicitly release keyboard ownership.const focusedRef = useRef(false);const onInputFocusChange = props.onInputFocusChange;- const releaseFocus = useEffectEvent(() => {- if (focusedRef.current) onInputFocusChange?.(false);- });- useEffect(() => () => releaseFocus(), []);- const pickerScope = useRef<{ key: string; active: boolean } | null>(null);+ // The caller keys this component by request and question, so unmounting ends any open+ // picker's scope.+ const pickerScope = useRef<{ active: boolean }>({ active: false });useEffect(() => {- const scope = { key: scopeKey, active: true };+ const scope = { active: true };pickerScope.current = scope;return () => {scope.active = false;};- }, [scopeKey]);+ }, []);+ // Unmounted inputs never emit onBlur; explicitly release keyboard ownership.+ const releaseFocus = useEffectEvent(() => {+ if (focusedRef.current) onInputFocusChange?.(false);+ });+ useEffect(() => () => releaseFocus(), []);const append = (key: string,attachments: Parameters<typeof appendComposerDraftAttachments>[1],@@ -106,7 +102,7 @@ export function QuestionAttachments(props: {}).then(async (images) => {if (- scope?.active &&+ scope.active &&(appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0) {if (append(key, images) > 0)@@ -150,7 +146,7 @@ export function QuestionAttachments(props: {const picked = "files" in result ? result.files : result.attachments;// Resolution on another client clears the reservation while the picker is open.if (- !scope?.active ||+ !scope.active ||(appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) === 0) {await releaseUnusedComposerAttachmentFiles(picked);diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsxindex 9f94ecd2edc..1aa2ec2293e 100644--- a/apps/mobile/src/features/threads/ThreadComposer.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx@@ -18,7 +18,6 @@ import {type MessageId,type ModelSelection,type ProviderInteractionMode,- type RuntimeMode,type ServerConfig as T3ServerConfig,type UsageLimitsReport,} from "@t3tools/contracts";@@ -29,7 +28,14 @@ import {} from "@t3tools/shared/usageLimits";import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";import type { ReactNode } from "react";-import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";+import {+ useEffect,+ useEffectEvent,+ useLayoutEffect,+ useRef,+ useState,+ type RefObject,+} from "react";import { Keyboard, Platform, View, type ViewStyle } from "react-native";import { composerImageGallery } from "../../lib/composerImageGallery";import { filePreviewGallery } from "../../lib/filePreviewGallery";@@ -45,6 +51,7 @@ import Animated, {type LayoutAnimationFunction,ReduceMotion,useAnimatedStyle,+ useDerivedValue,useSharedValue,withTiming,} from "react-native-reanimated";@@ -81,15 +88,10 @@ import {composerStripAttachments,type DraftComposerFileAttachment,} from "../../lib/composerImages";-import {- buildModelOptions,- groupByProvider,- isModelSelectionUnavailable,-} from "../../lib/modelOptions";+import { buildModelOptions, isModelSelectionUnavailable } from "../../lib/modelOptions";import { useScaledTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole";import type { RemoteClientConnectionState } from "../../lib/connection";import { MOBILE_TYPOGRAPHY } from "../../lib/typography";-import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";import { Menu } from "../../components/ui/Menu";import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";import type { FollowUpBehavior } from "../../lib/followUpBehavior";@@ -111,14 +113,7 @@ import {} from "../voice-input/ComposerDictationControl";import { useVoiceInputController } from "../voice-input/useVoiceInputController";import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";-import {- rememberModelOptions,- withRememberedModelOptions,-} from "../../state/use-model-option-memory";-import {- type ExistingThreadSettingsRouteSession,- useExistingThreadSettingsRoutePresentation,-} from "./ThreadSettingsSheet";+import type { ExistingThreadSettingsRouteParams } from "./ThreadSettingsSheet";import {useThreadSettingsSheetPresentation,type NavigationWithFinishTransitioning,@@ -275,8 +270,6 @@ export interface ThreadComposerProps {) => Promise<MessageId | null>;readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;readonly canSwitchProvider: boolean;- readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;- readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;readonly onUpdateInteractionMode?: (interactionMode: ProviderInteractionMode) => void;readonly onHeightChange?: (height: number) => void;readonly onEditorFocusChange?: (focused: boolean) => void;@@ -382,18 +375,15 @@ export function ComposerSurface(props: {const colors = useUniwindTheme();const targetBorderRadius =typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0;- const animatedBorderRadius = useSharedValue(targetBorderRadius);const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android";- useLayoutEffect(() => {- animatedBorderRadius.set(- shouldAnimate- ? withTiming(targetBorderRadius, {- duration: COMPOSER_TRANSITION_DURATION_MS,- reduceMotion: ReduceMotion.System,- })- : targetBorderRadius,- );- }, [animatedBorderRadius, shouldAnimate, targetBorderRadius]);+ const animatedBorderRadius = useDerivedValue(() =>+ shouldAnimate+ ? withTiming(targetBorderRadius, {+ duration: COMPOSER_TRANSITION_DURATION_MS,+ reduceMotion: ReduceMotion.System,+ })+ : targetBorderRadius,+ );const borderCurve = props.style.borderCurve;const animatedShapeStyle = useAnimatedStyle(() => ({borderRadius: animatedBorderRadius.value,@@ -454,12 +444,25 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsconst pendingPastedTextAttachmentCountRef = useRef(0);const pendingNativeImagePasteCountRef = useRef(0);const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0);+ const settingsRoutePresentedRef = useRef(false);const settingsSheetPresentation = useThreadSettingsSheetPresentation({editorRef: inputRef,- isEditorFocused: isFocused,+ onPresent: () => {+ if (settingsRoutePresentedRef.current) return;+ settingsRoutePresentedRef.current = true;+ // The draft composer edits the new-task flow, which owns its own settings route.+ navigation.dispatch(+ props.isDraft+ ? StackActions.push("NewTaskThreadSettings")+ : StackActions.push("ThreadSettingsSheet", {+ environmentId: props.environmentId,+ threadId: props.selectedThread.id,+ draftKey: composerDraftKey,+ } satisfies ExistingThreadSettingsRouteParams),+ );+ },});- const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();- const settingsRoutePresentedRef = useRef(false);+ const disposeSettingsSheetPresentation = useEffectEvent(settingsSheetPresentation.dispose);const wasExpandedBeforePreviewRef = useRef(false);const inFlightThreadIdsRef = useRef(new Set<string>());@@ -505,7 +508,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps});const sendLabel = sendPresentation.label;const currentModelSelection = props.selectedThread.modelSelection;- const currentRuntimeMode = props.selectedThread.runtimeMode;const modelUnavailable =props.connectionState === "connected" &&isModelSelectionUnavailable(@@ -628,6 +630,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps!modelUnavailable;useEffect(() => () => setComposerEditing(false), [setComposerEditing]);+ // A pending sheet presentation or focus restore has no composer left to act on.+ useEffect(() => () => disposeSettingsSheetPresentation(), []);const onPressPreview = (source: FilePreviewSource) => {wasExpandedBeforePreviewRef.current = isFocused;@@ -660,12 +664,14 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropsconst onEditorFocusChange = props.onEditorFocusChange;const handleFocus = () => {setIsFocused(true);+ settingsSheetPresentation.onEditorFocusChange(true);onEditorFocusChange?.(true);setComposerEditing(true);};const handleBlur = () => {setIsFocused(false);+ settingsSheetPresentation.onEditorFocusChange(false);onEditorFocusChange?.(false);setComposerEditing(false);};@@ -721,65 +727,16 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropslockedProviderInstanceId,props.selectedThread.projectId,);- const threadProviderGroups = groupByProvider(modelOptions);const currentModelOption =modelOptions.find((option) =>option.selection.instanceId === currentModelSelection.instanceId &&option.selection.model === currentModelSelection.model,) ?? null;- const providerOptionDescriptors = resolveProviderOptionDescriptors({- capabilities: currentModelOption?.capabilities,- selections: currentModelSelection.options,- });- const settingsOwnerId = composerOwnerKey;- const settingsRouteSession = {- ownerId: settingsOwnerId,- environmentId: props.environmentId,- projectId: props.selectedThread.projectId,- providerInstanceId: currentModelSelection.instanceId,- ...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {}),- providerGroups: threadProviderGroups,- selectedModel: currentModelSelection,- prompt: draftMessage,- onPromptChange: (text) => setComposerDraftText(composerDraftKey, text),- reportedModelSelection: props.reportedModelSelection,- onSelectModel: (option) =>- props.onUpdateModelSelection(withRememberedModelOptions(option.selection)),- restoreSelection: withRememberedModelOptions,- optionDescriptors: providerOptionDescriptors,- onUpdateOptionSelections: (options) => {- rememberModelOptions(- currentModelSelection.instanceId,- currentModelSelection.model,- options ?? [],- );- props.onUpdateModelSelection({ ...currentModelSelection, options });- },- runtimeMode: currentRuntimeMode,- onUpdateRuntimeMode: props.onUpdateRuntimeMode,- } satisfies ExistingThreadSettingsRouteSession;const openSettings = () => {- settingsRoutePresentation.present(settingsRouteSession);settingsSheetPresentation.open();};- const { present: presentSettingsRoute } = settingsRoutePresentation;- useEffect(() => {- if (settingsSheetPresentation.isActive) {- presentSettingsRoute(settingsRouteSession);- }- }, [presentSettingsRoute, settingsRouteSession, settingsSheetPresentation.isActive]);-- useEffect(() => {- if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {- return;- }-- settingsRoutePresentedRef.current = true;- navigation.dispatch(StackActions.push("ThreadSettingsSheet"));- }, [navigation, settingsSheetPresentation.isVisible]);-useFocusEffect(() => {if (!settingsRoutePresentedRef.current) {return;@@ -787,7 +744,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerPropssettingsRoutePresentedRef.current = false;settingsSheetPresentation.onDismissed();- settingsRoutePresentation.clear(settingsOwnerId);});useEffect(diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 4ac5b75e72d..dbccc5d12b1 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -40,9 +40,7 @@ import { deriveBottomControlInsets, type NativeLayoutMetrics } from "../../lib/rimport type {EnvironmentId,MessageId,- ModelSelection,ProviderInteractionMode,- RuntimeMode,RuntimeRequestId,ScopedThreadRef,ServerConfig as T3ServerConfig,@@ -285,8 +283,6 @@ export interface ThreadDetailScreenProps {) => Promise<MessageId | null>;readonly onReconnectEnvironment: () => void;readonly canSwitchThreadProvider: boolean;- readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;- readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;readonly onUpdateThreadInteractionMode?: (interactionMode: ProviderInteractionMode) => void;readonly onRespondToApproval: ApprovalResponder;readonly onSelectUserInputOption: (@@ -1633,8 +1629,6 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {onSendMessage={handleSendMessage}onShowUsageLimits={showUsageLimits}canSwitchProvider={props.canSwitchThreadProvider}- onUpdateModelSelection={props.onUpdateThreadModelSelection}- onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}onUpdateInteractionMode={props.onUpdateThreadInteractionMode}onHeightChange={handleComposerHeightChange}onEditorFocusChange={handleOwnedInputFocusChange}diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsxindex e023408aee1..f2ce81db0b6 100644--- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx+++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx@@ -1,5 +1,6 @@import { type StaticScreenProps, useNavigation } from "@react-navigation/native";import { useAtomValue } from "@effect/atom-react";+import { makeQueuedRunsAtom } from "@t3tools/client-runtime/queued-run-edit";import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";import { Atom } from "effect/reactivity";import { Image } from "expo-image";@@ -48,6 +49,12 @@ const EMPTY_QUEUED_COUNT_ATOM = Atom.make(0).pipe(type QueueTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };type QueueAction = "steer" | "edit" | "up" | "down" | "remove";type QueueRowLayout = { readonly id: RunId; readonly y?: number; readonly height?: number };+type QueueDrag = {+ readonly runId: RunId;+ readonly order: string;+ beforeRunId: RunId | null | undefined;+ readonly rows: ReadonlyArray<QueueRowLayout>;+};export function useThreadQueueWorkflow(target: QueueTarget) {return useAtomValue(environmentThreadDetails.queueWorkflowAtom(target));@@ -75,29 +82,18 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {const [resuming, setResuming] = useState(false);const [busyRunId, setBusyRunId] = useState<RunId | null>(null);const busyRef = useRef(false);- const [draggedRunId, setDraggedRunId] = useState<RunId | null>(null);- const [previewBeforeRunId, setPreviewBeforeRunId] = useState<RunId | null | undefined>();- const [dragRows, setDragRows] = useState<ReadonlyArray<QueueRowLayout> | null>(null);+ const [dragState, setDragState] = useState<QueueDrag | null>(null);const rowLayouts = useRef(new Map<RunId, { y: number; height: number }>());- const drag = useRef<{- runId: RunId;- order: string;- beforeRunId: RunId | null | undefined;- rows: ReadonlyArray<QueueRowLayout>;- } | null>(null);+ const drag = useRef<QueueDrag | null>(null);const [translation] = useState(() => new Animated.Value(0));const queuedRuns = workflow?.queuedRuns ?? [];const order = queuedRuns.map(({ run }) => run.id).join(",");-- useEffect(() => {- if (drag.current && drag.current.order !== order) {- drag.current = null;- setDraggedRunId(null);- setPreviewBeforeRunId(undefined);- setDragRows(null);- translation.setValue(0);- }- }, [order, translation]);+ // A queue that changed under the drag (delivery, another client) ends it:+ // the gesture handlers ignore it from then on and its preview disappears.+ const visibleDrag = dragState?.order === order ? dragState : null;+ const draggedRunId = visibleDrag?.runId ?? null;+ const previewBeforeRunId = visibleDrag?.beforeRunId;+ const dragRows = visibleDrag?.rows ?? null;const hadQueuedRuns = useRef(queuedRuns.length > 0);useEffect(() => {@@ -133,13 +129,24 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {if (action === "edit") {const entry = queuedRuns[index]!;void Haptics.selectionAsync();- beginQueuedRunEdit(threadKey, {- runId,- messageId: entry.messageId,- originalText: entry.text,- existingAttachments: entry.attachments,- ...(entry.context ? { context: entry.context } : {}),- });+ beginQueuedRunEdit(+ threadKey,+ {+ runId,+ messageId: entry.messageId,+ originalText: entry.text,+ existingAttachments: entry.attachments,+ ...(entry.context ? { context: entry.context } : {}),+ },+ makeQueuedRunsAtom({+ threadId: target.threadId,+ snapshot: threadEnvironment.snapshotAtom(target.environmentId),+ detailStatus: environmentThreadDetails.statusAtom(target),+ runs: Atom.make(+ (get) => get(environmentThreadDetails.quietThreadAtom(target))?.projection.runs ?? null,+ ),+ }),+ );navigation.goBack();return;}@@ -261,9 +268,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {const beforeRunId = resolveQueueDragBeforeRunId(rows, run.id, 0);drag.current = { runId: run.id, order, beforeRunId, rows };translation.setValue(0);- setDragRows(rows);- setPreviewBeforeRunId(beforeRunId);- setDraggedRunId(run.id);+ setDragState({ ...drag.current });void Haptics.selectionAsync();}}onMove={(y) => {@@ -273,7 +278,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {const before = resolveQueueDragBeforeRunId(current.rows, run.id, y);if (current.beforeRunId !== before) {current.beforeRunId = before;- setPreviewBeforeRunId(before);+ setDragState({ ...current });}}}onEnd={(y, success) => {@@ -281,9 +286,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {const stop = () => {if (drag.current !== started) return;drag.current = null;- setDraggedRunId(null);- setPreviewBeforeRunId(undefined);- setDragRows(null);+ setDragState(null);translation.setValue(0);};if (!success || started?.order !== order || started.runId !== run.id) {@@ -314,7 +317,8 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {useNativeDriver: true,}).start();}- setPreviewBeforeRunId(before);+ started.beforeRunId = before;+ setDragState({ ...started });void move(run.id, before).finally(stop);}}/>diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsxindex 43a1462a655..87e57557eba 100644--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx@@ -1055,8 +1055,6 @@ function ThreadRouteContent(onSendMessage={composer.onSendMessage}onReconnectEnvironment={handleReconnectEnvironment}canSwitchThreadProvider={composer.canSwitchThreadProvider}- onUpdateThreadModelSelection={composer.onUpdateModelSelection}- onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}onRespondToApproval={requests.onRespondToApproval}onSelectUserInputOption={requests.onSelectUserInputOption}diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsxindex 030b317f41f..ac382d101b8 100644--- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx+++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx@@ -20,6 +20,7 @@ import type {ProviderOptionSelection,RuntimeMode,ServerSettings,+ ThreadId,} from "@t3tools/contracts";import type { LegendListRenderItemProps } from "@legendapp/list/react-native";import { RegistryContext, useAtomValue } from "@effect/atom-react";@@ -29,7 +30,12 @@ import {getProviderOptionCurrentValue,getProviderOptionDescriptors,} from "@t3tools/shared/model";-import { useNavigation, useRoute, type RouteProp } from "@react-navigation/native";+import {+ useNavigation,+ useRoute,+ type RouteProp,+ type StaticScreenProps,+} from "@react-navigation/native";import { type NativeStackNavigationProp } from "@react-navigation/native-stack";import * as Haptics from "expo-haptics";import { AsyncResult } from "effect/reactivity";@@ -72,6 +78,19 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";import { ChatGptSharingStatus } from "./ChatGptSharingStatus";import { environmentCatalog } from "../../connection/catalog";import { useEnvironmentQuery } from "../../state/query";+import { scopedThreadKey } from "../../lib/scopedEntities";+import { useThreadReportedModelSelection } from "../../state/entities";+import {+ setComposerDraftText,+ updateComposerDraftSettings,+ useComposerDraft,+ useComposerDraftSettings,+} from "../../state/use-composer-drafts";+import { useQuietThreadStructure } from "../../state/use-thread-detail";+import { activeComposerDraftKey, useQueuedRunEdit } from "../../state/queued-run-edit";+import { updateThreadDraftModelSelection } from "../../state/use-thread-composer-state";+import { useThreadSelection } from "../../state/use-thread-selection";+import { threadAllowsProviderSwitch } from "../../state/thread-provider-switching";import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server";import { mobilePreferencesAtom } from "../../state/preferences";import { useAtomCommand } from "../../state/use-atom-command";@@ -260,46 +279,13 @@ type ThreadSettingsSessionProps = {readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;};-export type ExistingThreadSettingsRouteSession = ThreadSettingsSessionProps & {- readonly ownerId: string;+/** The composer draft the sheet edits: the thread's own, or a queued message being edited. */+export type ExistingThreadSettingsRouteParams = {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+ readonly draftKey: string;};-type ExistingThreadSettingsRouteContextValue = {- readonly session: ExistingThreadSettingsRouteSession | null;- readonly present: (session: ExistingThreadSettingsRouteSession) => void;- readonly clear: (ownerId: string) => void;-};--const ExistingThreadSettingsRouteContext =- createContext<ExistingThreadSettingsRouteContextValue | null>(null);--export function ExistingThreadSettingsRouteProvider(props: { readonly children: ReactNode }) {- const [session, setSession] = useState<ExistingThreadSettingsRouteSession | null>(null);- const present = (nextSession: ExistingThreadSettingsRouteSession) => {- setSession(nextSession);- };- const clear = (ownerId: string) => {- setSession((current) => (current?.ownerId === ownerId ? null : current));- };- const value = { session, present, clear };-- return (- <ExistingThreadSettingsRouteContext.Provider value={value}>- {props.children}- </ExistingThreadSettingsRouteContext.Provider>- );-}--export function useExistingThreadSettingsRoutePresentation() {- const value = use(ExistingThreadSettingsRouteContext);- if (!value) {- throw new Error(- "useExistingThreadSettingsRoutePresentation must be used inside ExistingThreadSettingsRouteProvider.",- );- }- return value;-}-type ThreadSettingsSessionValue = {readonly environmentId: EnvironmentId | null;readonly providerInstanceId?: ProviderInstanceId;@@ -1504,26 +1490,76 @@ export function ThreadSettingsPickerScreen();}-export function ExistingThreadSettingsRouteScreen() {+export function ExistingThreadSettingsRouteScreen({+ route,+}: StaticScreenProps<ExistingThreadSettingsRouteParams>) {const navigation = useNavigation<NativeStackNavigationProp<Record<string, object | undefined>>>();- const presentation = useExistingThreadSettingsRoutePresentation();- const session = presentation.session;-- useEffect(() => {- if (session) {- return;- }-- navigation.goBack();- }, [navigation, session]);-- if (!session) {+ // Reads the same environmentId/threadId params as the Thread route beneath it.+ const { selectedThread, selectedThreadDetailRef, selectedEnvironmentRuntime } =+ useThreadSelection();+ // Streamed text would otherwise re-render the whole model picker on every delta.+ const structure = useQuietThreadStructure(selectedThreadDetailRef);+ const reportedModelSelection = useThreadReportedModelSelection(selectedThreadDetailRef);+ const threadKey = scopedThreadKey(route.params.environmentId, route.params.threadId);+ const draftSettings = useComposerDraftSettings(threadKey);+ const queuedRunEdit = useQueuedRunEdit(threadKey);+ // A queued edit can end while the sheet is open; the prompt then belongs to the thread's draft.+ const draftKey = activeComposerDraftKey(threadKey, route.params.draftKey, queuedRunEdit);+ const prompt = useComposerDraft(draftKey).text;++ if (!selectedThread) {return <View className="flex-1 bg-sheet" />;}- const { ownerId: _ownerId, ...settings } = session;+ const serverConfig = selectedEnvironmentRuntime?.serverConfig ?? null;+ const modelSelection = draftSettings.modelSelection ?? selectedThread.modelSelection;+ const lockedProviderInstanceId = threadAllowsProviderSwitch({+ thread: selectedThread,+ projection: structure?.projection,+ })+ ? undefined+ : modelSelection.instanceId;+ const modelOptions = buildModelOptions(+ serverConfig,+ modelSelection,+ lockedProviderInstanceId,+ selectedThread.projectId,+ );+ const currentModelOption =+ modelOptions.find(+ (option) =>+ option.selection.instanceId === modelSelection.instanceId &&+ option.selection.model === modelSelection.model,+ ) ?? null;+ const updateModelSelection = (selection: ModelSelection) =>+ updateThreadDraftModelSelection(threadKey, selection, serverConfig?.providers ?? []);- return <ThreadSettingsPickerScreen {...settings} onClose={() => navigation.goBack()} />;+ return (+ <ThreadSettingsPickerScreen+ environmentId={selectedThread.environmentId}+ projectId={selectedThread.projectId}+ providerInstanceId={modelSelection.instanceId}+ {...(lockedProviderInstanceId ? { lockedProviderInstanceId } : {})}+ providerGroups={groupByProvider(modelOptions)}+ selectedModel={modelSelection}+ prompt={prompt}+ onPromptChange={(text) => setComposerDraftText(draftKey, text)}+ reportedModelSelection={reportedModelSelection}+ onSelectModel={(option) => updateModelSelection(withRememberedModelOptions(option.selection))}+ restoreSelection={withRememberedModelOptions}+ optionDescriptors={resolveProviderOptionDescriptors({+ capabilities: currentModelOption?.capabilities,+ selections: modelSelection.options,+ })}+ onUpdateOptionSelections={(options) => {+ rememberModelOptions(modelSelection.instanceId, modelSelection.model, options ?? []);+ updateModelSelection({ ...modelSelection, options });+ }}+ runtimeMode={draftSettings.runtimeMode ?? selectedThread.runtimeMode}+ onUpdateRuntimeMode={(runtimeMode) => updateComposerDraftSettings(threadKey, { runtimeMode })}+ onClose={() => navigation.goBack()}+ />+ );}/** RNS owns nested sheet dismissal; Reasoning and Runtime remain ordinary pushes. */diff --git a/apps/mobile/src/features/threads/pending-thread-feed.test.ts b/apps/mobile/src/features/threads/pending-thread-feed.test.tsindex be82e4b6510..314dc1aa477 100644--- a/apps/mobile/src/features/threads/pending-thread-feed.test.ts+++ b/apps/mobile/src/features/threads/pending-thread-feed.test.ts@@ -8,7 +8,11 @@ import {ThreadId,} from "@t3tools/contracts";import type { QueuedThreadMessage } from "../../state/thread-outbox-model";-import { appendPendingThreadMessages, isCompactionCommandFeedEntry } from "./pending-thread-feed";+import {+ appendPendingThreadMessages,+ isCompactionCommandFeedEntry,+ selectPendingAcknowledgedMessages,+} from "./pending-thread-feed";const pending = (id: string): QueuedThreadMessage => ({environmentId: EnvironmentId.make("env"),@@ -109,4 +113,20 @@ describe("pending timeline messages", () => {expect(appendPendingThreadMessages([delivered], [delivered], [queued])).toEqual([delivered]);expect(appendPendingThreadMessages([], [delivered], [queued])).toEqual([]);});++ it("stops showing an acknowledged message once the projection holds it, even when the feed hides it", () => {+ // A rolled-back or cancelled queued run keeps its message in projection.messages+ // while its user_message item leaves the visible feed.+ const echoed = pending("rolled-back");+ const waiting = pending("waiting");+ const shown = selectPendingAcknowledgedMessages([echoed, waiting], {+ threadKey: "env:thread",+ queuedMessages: [],+ projectedMessages: [{ id: echoed.messageId }],+ });+ expect(shown).toEqual([waiting]);+ expect(appendPendingThreadMessages([], [], shown).map((entry) => entry.id)).toEqual([+ "waiting",+ ]);+ });});diff --git a/apps/mobile/src/features/threads/pending-thread-feed.ts b/apps/mobile/src/features/threads/pending-thread-feed.tsindex 820afb66a75..9eaf42dcee8 100644--- a/apps/mobile/src/features/threads/pending-thread-feed.ts+++ b/apps/mobile/src/features/threads/pending-thread-feed.ts@@ -4,6 +4,7 @@ import {type ThreadGuestShare,} from "@t3tools/contracts";import type { ThreadFeedEntry } from "../../lib/threadActivity";+import { scopedThreadKey } from "../../lib/scopedEntities";import type { QueuedThreadMessage } from "../../state/thread-outbox-model";/**@@ -23,6 +24,24 @@ export type PendingThreadFeedEntry = ThreadFeedEntry & {readonly acknowledged?: boolean;};+// An acknowledged row stops being pending once the projection holds its message,+// even when the feed hides that message (a rolled-back or cancelled run).+export function selectPendingAcknowledgedMessages(+ acknowledged: ReadonlyArray<QueuedThreadMessage>,+ thread: {+ readonly threadKey: string | null;+ readonly queuedMessages: ReadonlyArray<QueuedThreadMessage>;+ readonly projectedMessages: ReadonlyArray<{ readonly id: string }> | undefined;+ },+): ReadonlyArray<QueuedThreadMessage> {+ return acknowledged.filter(+ (message) =>+ scopedThreadKey(message.environmentId, message.threadId) === thread.threadKey &&+ !thread.queuedMessages.some((queued) => queued.messageId === message.messageId) &&+ !thread.projectedMessages?.some((projected) => projected.id === message.messageId),+ );+}+/** A row of the thread feed's list. */export type ThreadFeedRow = PendingThreadFeedEntry | GuestPendingFeedEntry;diff --git a/apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.ts b/apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.tsindex 57f72861387..2ea4d6c3755 100644--- a/apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.ts+++ b/apps/mobile/src/features/threads/use-thread-settings-sheet-presentation.ts@@ -1,4 +1,4 @@-import { useCallback, useEffect, useRef, useState, type RefObject } from "react";+import { useRef, useState, type RefObject } from "react";import { KeyboardController } from "react-native-keyboard-controller";import type { ComposerEditorHandle } from "../../components/ComposerEditor";@@ -18,41 +18,30 @@ const NATIVE_DISMISSAL_ECHO_WINDOW_MS = 150;/** Blur/focus costs two keyboard animations; inputView overrides also replay show when removed. */export function useThreadSettingsSheetPresentation(input: {readonly editorRef: RefObject<ComposerEditorHandle | null>;- readonly isEditorFocused: boolean;+ /** Runs on the frame the sheet becomes visible, after the keyboard started leaving. */+ readonly onPresent: () => void;}) {+ // Destructured so the compiler keys memoized handlers on the stable editor ref, not on+ // the fresh input object: the finishTransitioning listener re-subscribes on every change.+ const { editorRef, onPresent } = input;const [phase, setPhase] = useState<PresentationPhase>("closed");const isActiveRef = useRef(false);- const isMountedRef = useRef(true);- const isEditorFocusedRef = useRef(input.isEditorFocused);+ // Written by the editor's focus handlers; read when restoring focus after dismissal.+ const isEditorFocusedRef = useRef(false);const openingIdRef = useRef(0);const focusRestoreIdRef = useRef(0);const restoreFocusAfterDismissRef = useRef(false);const restorePendingRef = useRef(false);const lastStackTransitionFinishedAtRef = useRef(0);const dismissRestoreTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const clearDismissRestoreTimer = useCallback(() => {+ const clearDismissRestoreTimer = () => {if (dismissRestoreTimerRef.current !== null) {clearTimeout(dismissRestoreTimerRef.current);dismissRestoreTimerRef.current = null;}- }, []);-- useEffect(() => {- isEditorFocusedRef.current = input.isEditorFocused;- }, [input.isEditorFocused]);-- useEffect(() => {- isMountedRef.current = true;- return () => {- isMountedRef.current = false;- isActiveRef.current = false;- openingIdRef.current += 1;- focusRestoreIdRef.current += 1;- clearDismissRestoreTimer();- };- }, [clearDismissRestoreTimer]);+ };- const open = useCallback(() => {+ const open = () => {if (isActiveRef.current) {return;}@@ -62,7 +51,7 @@ export function useThreadSettingsSheetPresentation(input: {clearDismissRestoreTimer();restorePendingRef.current = false;restoreFocusAfterDismissRef.current =- phase === "restoring" || input.isEditorFocused || KeyboardController.isVisible();+ phase === "restoring" || isEditorFocusedRef.current || KeyboardController.isVisible();setPhase("opening");const openingId = openingIdRef.current + 1;@@ -70,24 +59,30 @@ export function useThreadSettingsSheetPresentation(input: {// Dismiss the keyboard before blur, then present next frame so native transitions overlap.void KeyboardController.dismiss({ animated: true });- input.editorRef.current?.blur();+ editorRef.current?.blur();requestAnimationFrame(() => {- if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {+ // A composer unmounted during the frame takes its editor with it; present nothing.+ if (+ !isActiveRef.current ||+ openingIdRef.current !== openingId ||+ editorRef.current === null+ ) {return;}setPhase("visible");+ onPresent();});- }, [clearDismissRestoreTimer, input.editorRef, input.isEditorFocused, phase]);+ };- const restoreEditorFocus = useCallback(() => {+ const restoreEditorFocus = () => {const focusRestoreId = focusRestoreIdRef.current + 1;focusRestoreIdRef.current = focusRestoreId;let attemptsRemaining = 20;// Retry focus restoration if UIKit briefly refuses first responder at the dismissal boundary.const restoreFocus = () => {- if (!isMountedRef.current || focusRestoreIdRef.current !== focusRestoreId) {+ if (focusRestoreIdRef.current !== focusRestoreId) {return;}if (isEditorFocusedRef.current || attemptsRemaining <= 0) {@@ -96,25 +91,25 @@ export function useThreadSettingsSheetPresentation(input: {}attemptsRemaining -= 1;- input.editorRef.current?.focus();+ editorRef.current?.focus();setTimeout(restoreFocus, 50);};requestAnimationFrame(restoreFocus);- }, [input.editorRef]);+ };- const runPendingDismissalRestore = useCallback(() => {+ const runPendingDismissalRestore = () => {if (!restorePendingRef.current) {return;}restorePendingRef.current = false;clearDismissRestoreTimer();- if (!isMountedRef.current || isActiveRef.current) {+ if (isActiveRef.current) {return;}restoreEditorFocus();- }, [clearDismissRestoreTimer, restoreEditorFocus]);+ };- const onDismissed = useCallback(() => {+ const onDismissed = () => {isActiveRef.current = false;if (!restoreFocusAfterDismissRef.current) {@@ -134,19 +129,35 @@ export function useThreadSettingsSheetPresentation(input: {dismissRestoreTimerRef.current = null;runPendingDismissalRestore();}, SHEET_DISMISSAL_KEYBOARD_OVERLAP_MS);- }, [clearDismissRestoreTimer, runPendingDismissalRestore]);+ };- const onStackTransitionsFinished = useCallback(() => {+ const onStackTransitionsFinished = () => {lastStackTransitionFinishedAtRef.current = Date.now();runPendingDismissalRestore();- }, [runPendingDismissalRestore]);+ };++ const onEditorFocusChange = (focused: boolean) => {+ isEditorFocusedRef.current = focused;+ };++ // Called when the composer unmounts: cancels a queued presentation frame, the+ // dismissal restore timer, and any focus-restore retries still in flight.+ const dispose = () => {+ isActiveRef.current = false;+ openingIdRef.current += 1;+ focusRestoreIdRef.current += 1;+ restorePendingRef.current = false;+ clearDismissRestoreTimer();+ };return {isActive: phase === "opening" || phase === "visible",keepsComposerExpanded: phase !== "closed",isVisible: phase === "visible",open,+ onEditorFocusChange,onDismissed,onStackTransitionsFinished,+ dispose,} as const;}diff --git a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsxindex cd7976232e6..8df3f538997 100644--- a/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx+++ b/apps/mobile/src/features/voice-input/ComposerDictationControl.tsx@@ -1,12 +1,12 @@import type { VoiceInputPhase, VoiceInputState } from "@t3tools/client-runtime/voice-input";-import { memo, useCallback, useLayoutEffect, useState, type ReactNode } from "react";+import { memo, useCallback, useState, type ReactNode } from "react";import { Linking, Pressable, Text as SystemText, View, type LayoutChangeEvent } from "react-native";import Animated, {Easing,ReduceMotion,useAnimatedStyle,+ useDerivedValue,useReducedMotion,- useSharedValue,withTiming,type EntryExitAnimationFunction,type SharedValue,@@ -88,10 +88,8 @@ export function ComposerDictationDraftContent(props: {readonly compact: boolean;readonly hidden: boolean;}) {- const rotation = useSharedValue(props.hidden ? 1 : 0);- useLayoutEffect(() => {- rotation.set(withTiming(props.hidden ? 1 : 0, TOOLBAR_FLIP_TIMING));- }, [props.hidden, rotation]);+ const hidden = props.hidden;+ const rotation = useDerivedValue(() => withTiming(hidden ? 1 : 0, TOOLBAR_FLIP_TIMING));const compact = props.compact;const animatedStyle = useAnimatedStyle(() => ({opacity: compact ? 1 - rotation.value : 1,@@ -261,11 +259,10 @@ function VoiceActionButton(props: {readonly variant?: "plain" | "primary";}) {const variant = props.variant ?? "plain";- const loadingVisibility = useSharedValue(props.loading ? 1 : 0);- useLayoutEffect(() => {- loadingVisibility.set(withTiming(props.loading ? 1 : 0, DICTATION_TIMING));- }, [loadingVisibility, props.loading]);- const primaryStyle = useAnimatedStyle(() => ({ opacity: 1 - loadingVisibility.value }));+ const loading = props.loading === true;+ const primaryStyle = useAnimatedStyle(() => ({+ opacity: withTiming(loading ? 0 : 1, DICTATION_TIMING),+ }));return (<Pressable@@ -320,15 +317,12 @@ export function ComposerDictationStatus(props: {readonly presentation: VoiceComposerPresentation;readonly onDismissError: () => void;}) {- const recordingVisibility = useSharedValue(props.phase === "recording" ? 1 : 0);- useLayoutEffect(() => {- recordingVisibility.set(withTiming(props.phase === "recording" ? 1 : 0, DICTATION_TIMING));- }, [props.phase, recordingVisibility]);+ const recording = props.phase === "recording";const waveformStyle = useAnimatedStyle(() => ({- opacity: recordingVisibility.value,+ opacity: withTiming(recording ? 1 : 0, DICTATION_TIMING),}));const labelStyle = useAnimatedStyle(() => ({- opacity: 1 - recordingVisibility.value,+ opacity: withTiming(recording ? 0 : 1, DICTATION_TIMING),}));if (!props.presentation.statusLabel) return null;diff --git a/apps/mobile/src/lib/composerImagePreview.test.ts b/apps/mobile/src/lib/composerImagePreview.test.tsnew file mode 100644index 00000000000..84bcc13bbf7--- /dev/null+++ b/apps/mobile/src/lib/composerImagePreview.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it, vi } from "vite-plus/test";++const mocks = vi.hoisted(() => ({+ files: new Set<string>(),+ write: vi.fn(async (_content: string, _options: unknown) => undefined),+}));++vi.mock("expo-file-system", () => ({+ Paths: { cache: "file:///cache" },+ Directory: class {+ constructor(+ readonly parent: string,+ readonly name: string,+ ) {}+ create() {}+ },+ File: class {+ uri: string;+ constructor(directory: { parent: string; name: string }, name: string) {+ this.uri = `${directory.parent}/${directory.name}/${name}`;+ }+ get exists() {+ return mocks.files.has(this.uri);+ }+ create() {+ mocks.files.add(this.uri);+ }+ delete() {+ mocks.files.delete(this.uri);+ }+ write(content: string, options: unknown) {+ return mocks.write(content, options);+ }+ async move(destination: { uri: string }) {+ mocks.files.delete(this.uri);+ mocks.files.add(destination.uri);+ this.uri = destination.uri;+ }+ },+}));++import type { EnvironmentId } from "@t3tools/contracts";+import { AsyncResult, AtomRegistry } from "effect/reactivity";++import type { DraftComposerImageAttachment } from "./composerImages";+import { MaterializedPreviewKey, materializedPreviewAtom } from "./composerImagePreview";++describe("materializedPreviewAtom", () => {+ it("keeps the materialized preview when the upload reference lands", async () => {+ const registry = AtomRegistry.make();+ const attachment: DraftComposerImageAttachment = {+ id: "image-1",+ type: "image",+ name: "photo.png",+ mimeType: "image/png",+ sizeBytes: 3,+ previewUri: "data:image/png;base64,AAAA",+ };+ const atom = materializedPreviewAtom(new MaterializedPreviewKey(attachment));+ const unmount = registry.mount(atom);+ await vi.waitFor(() => expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true));++ const uploaded = materializedPreviewAtom(+ new MaterializedPreviewKey({+ ...attachment,+ uploadedAttachmentId: "uploaded-1",+ uploadEnvironmentId: "env-1" as EnvironmentId,+ }),+ );++ expect(uploaded).toBe(atom);+ const result = registry.get(uploaded);+ expect(AsyncResult.isSuccess(result) && result.value).toBe(+ "file:///cache/t3-composer-previews/image-1.png",+ );+ expect(mocks.write).toHaveBeenCalledTimes(1);+ unmount();+ });++ it("writes the preview again after a failed write instead of reusing the partial file", async () => {+ const attachment: DraftComposerImageAttachment = {+ id: "image-failed",+ type: "image",+ name: "photo.png",+ mimeType: "image/png",+ sizeBytes: 3,+ previewUri: "data:image/png;base64,AAAA",+ };+ const materialize = async () => {+ const registry = AtomRegistry.make();+ const atom = materializedPreviewAtom(new MaterializedPreviewKey(attachment));+ const unmount = registry.mount(atom);+ await vi.waitFor(() => expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true));+ const result = registry.get(atom);+ unmount();+ return AsyncResult.isSuccess(result) ? result.value : undefined;+ };+ using _warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ mocks.write.mockClear();+ mocks.write.mockRejectedValueOnce(new Error("disk full"));++ expect(await materialize()).toBeNull();+ expect(await materialize()).toBe("file:///cache/t3-composer-previews/image-failed.png");+ expect(mocks.write).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/mobile/src/lib/composerImagePreview.ts b/apps/mobile/src/lib/composerImagePreview.tsnew file mode 100644index 00000000000..6e96acb7599--- /dev/null+++ b/apps/mobile/src/lib/composerImagePreview.ts@@ -0,0 +1,60 @@+import * as Effect from "effect/Effect";+import * as Equal from "effect/Equal";+import * as Hash from "effect/Hash";+import { Atom } from "effect/reactivity";++import type { DraftComposerImageAttachment } from "./composerImages";++const PREVIEW_CACHE_DIRECTORY = "t3-composer-previews";++async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<string | null> {+ const comma = dataUrl.indexOf(",");+ if (comma < 0) return null;+ const { Directory, File, Paths } = await import("expo-file-system");+ const mimeType = /^data:([^;,]+)/.exec(dataUrl)?.[1] ?? "image/jpeg";+ const extension = (mimeType.split("/")[1] ?? "jpg").replace("jpeg", "jpg");+ const directory = new Directory(Paths.cache, PREVIEW_CACHE_DIRECTORY);+ directory.create({ idempotent: true, intermediates: true });+ const file = new File(directory, `${id}.${extension}`);+ if (file.exists) return file.uri;+ // Write beside the cache entry and move it in, so a failed or interrupted write is never reused.+ const partial = new File(directory, `${id}.${extension}.partial`);+ if (partial.exists) partial.delete();+ partial.create();+ try {+ await partial.write(dataUrl.slice(comma + 1), { encoding: "base64" });+ } catch (error) {+ partial.delete();+ throw error;+ }+ await partial.move(file);+ return file.uri;+}++/**+ * Keyed by attachment id only: the cached file is named by id, and an upload+ * reference landing on the same draft must not restart materialization and+ * blank the preview. Hashing the id also avoids rehashing a multi-megabyte data URL.+ */+export class MaterializedPreviewKey implements Equal.Equal {+ constructor(readonly attachment: DraftComposerImageAttachment) {}+ [Equal.symbol](that: unknown): boolean {+ return that instanceof MaterializedPreviewKey && that.attachment.id === this.attachment.id;+ }+ [Hash.symbol](): number {+ return Hash.string(this.attachment.id);+ }+}++export const materializedPreviewAtom = Atom.family(({ attachment }: MaterializedPreviewKey) =>+ Atom.make(+ Effect.tryPromise(() => materializeDataUrlPreview(attachment.id, attachment.previewUri)).pipe(+ Effect.catch((error) =>+ Effect.sync(() => {+ console.warn("[composer-attachments] could not cache an image preview", error);+ return null;+ }),+ ),+ ),+ ).pipe(Atom.withLabel(`composer-image-preview:${attachment.id}`)),+);diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.tsindex c644fb09a4c..c862138ce58 100644--- a/apps/mobile/src/reactCompilerCoverage.test.ts+++ b/apps/mobile/src/reactCompilerCoverage.test.ts@@ -14,7 +14,6 @@ const metroConfig: Promise<{ transformer: { babelTransformerPath: string } }> =// Remove bailout entries and manual memoization when compilation starts; this check rejects stale entries.const KNOWN_BAILOUTS: Record<string, string> = {- "src/components/ComposerAttachmentStrip.tsx": "unsupported syntax","src/components/ui/Menu.tsx": "ref read during render","src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render","src/features/home/thread-swipe-actions.tsx": "ref read during render",diff --git a/apps/mobile/src/state/acknowledged-thread-messages.ts b/apps/mobile/src/state/acknowledged-thread-messages.tsindex d455c01cafc..ab9f26dd7d4 100644--- a/apps/mobile/src/state/acknowledged-thread-messages.ts+++ b/apps/mobile/src/state/acknowledged-thread-messages.ts@@ -1,16 +1,42 @@+import * as Option from "effect/Option";import { Atom } from "effect/reactivity";import { appAtomRegistry } from "./atom-registry";import type { QueuedThreadMessage } from "./thread-outbox-model";+import { environmentThreadDetails } from "./threads";// Keep acknowledged rows until their subscribed projection arrives; command receipts can precede messages.+// Render hides rows the projection has echoed, so dropping them here only frees memory.export const acknowledgedThreadMessagesAtom = Atom.make<ReadonlyArray<QueuedThreadMessage>>([],).pipe(Atom.keepAlive);-export function retainAcknowledgedThreadMessage(message: QueuedThreadMessage) {+// Peeks at a thread only when something already has it in the registry: reading+// it through the registry would open a snapshot load and a live stream of its own.+function isEchoedInMountedThread(message: QueuedThreadMessage): boolean {+ const threadAtom = environmentThreadDetails.threadAtom({+ environmentId: message.environmentId,+ threadId: message.threadId,+ });+ const node = appAtomRegistry.getNodes().get(threadAtom);+ if (node === undefined) return false;+ const loaded: Option.Option<Atom.Type<typeof threadAtom>> = node.valueOption();+ const thread = Option.getOrNull(loaded);+ return thread?.projection.messages.some((entry) => entry.id === message.messageId) ?? false;+}++function writeAcknowledgedThreadMessages(+ update: (current: ReadonlyArray<QueuedThreadMessage>) => ReadonlyArray<QueuedThreadMessage>,+) {const current = appAtomRegistry.get(acknowledgedThreadMessagesAtom);- appAtomRegistry.set(- acknowledgedThreadMessagesAtom,+ const next = update(current).filter((entry) => !isEchoedInMountedThread(entry));+ if (next.length === current.length && next.every((entry, index) => entry === current[index])) {+ return;+ }+ appAtomRegistry.set(acknowledgedThreadMessagesAtom, next);+}++export function retainAcknowledgedThreadMessage(message: QueuedThreadMessage) {+ writeAcknowledgedThreadMessages((current) =>current.some((entry) => entry.messageId === message.messageId)? current: [...current, message],@@ -18,9 +44,7 @@ export function retainAcknowledgedThreadMessage(message: QueuedThreadMessage) {}export function forgetAcknowledgedThreadMessage(message: QueuedThreadMessage) {- const current = appAtomRegistry.get(acknowledgedThreadMessagesAtom);- appAtomRegistry.set(- acknowledgedThreadMessagesAtom,+ writeAcknowledgedThreadMessages((current) =>current.filter((entry) => entry.messageId !== message.messageId),);}diff --git a/apps/mobile/src/state/queued-run-edit.test.ts b/apps/mobile/src/state/queued-run-edit.test.tsindex 9309b071355..361a743ac71 100644--- a/apps/mobile/src/state/queued-run-edit.test.ts+++ b/apps/mobile/src/state/queued-run-edit.test.ts@@ -1,4 +1,5 @@import { describe, expect, it } from "vite-plus/test";+import { Atom } from "effect/reactivity";import {ChatAttachmentId,ComposerContextId,@@ -8,7 +9,18 @@ import {type OrchestrationMessageContext,} from "@t3tools/contracts";-import { resolveQueuedEditPayload, type QueuedRunEdit } from "./queued-run-edit";+import { appAtomRegistry } from "./atom-registry";+import {+ activeComposerDraftKey,+ beginQueuedRunEdit,+ getQueuedRunEdit,+ queuedEditDraftKey,+ removeQueuedRunEditAttachment,+ resolveQueuedEditPayload,+ type QueuedRunEdit,+} from "./queued-run-edit";+import { threadComposerErrorsAtom } from "./thread-composer-error";+import { getComposerDraftSnapshot, setComposerDraftText } from "./use-composer-drafts";const image = (id: string): ChatAttachment => ({type: "image",@@ -80,3 +92,73 @@ describe("resolveQueuedEditPayload", () => {expect(payload.context?.records).toEqual([expect.objectContaining({ attachmentId: "kept" })]);});});++describe("beginQueuedRunEdit", () => {+ it("ends a changed edit when its run starts, without the thread's composer mounted", () => {+ const threadKey = "env-exit:thread-exit";+ const runId = RunId.make("run-1");+ const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([+ { id: runId, status: "queued" },+ ]);+ setComposerDraftText(threadKey, "other work");+ beginQueuedRunEdit(threadKey, edit([]), runs);+ setComposerDraftText(queuedEditDraftKey(threadKey, runId), "changed");++ appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);++ expect(getQueuedRunEdit(threadKey)).toBeNull();+ expect(getComposerDraftSnapshot(threadKey).text).toBe("other work");+ expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(+ "That message already started, so the edit was discarded.",+ );+ });++ it("reports a cleared edit as discarded when the run starts", () => {+ const threadKey = "env-exit:thread-cleared";+ const runId = RunId.make("run-1");+ const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([+ { id: runId, status: "queued" },+ ]);+ beginQueuedRunEdit(threadKey, edit([]), runs);+ setComposerDraftText(queuedEditDraftKey(threadKey, runId), "");++ appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);++ expect(getQueuedRunEdit(threadKey)).toBeNull();+ expect(getComposerDraftSnapshot(threadKey).text).toBe("");+ expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(+ "That message already started, so the edit was discarded.",+ );+ });++ it("treats a removed server attachment as a change when the run starts", () => {+ const threadKey = "env-exit:thread-removed";+ const runId = RunId.make("run-1");+ const runs = Atom.make<ReadonlyArray<{ readonly id: RunId; readonly status: string }> | null>([+ { id: runId, status: "queued" },+ ]);+ setComposerDraftText(threadKey, "other work");+ beginQueuedRunEdit(threadKey, edit([image("kept")]), runs);+ removeQueuedRunEditAttachment(threadKey, "kept");++ appAtomRegistry.set(runs, [{ id: runId, status: "running" }]);++ expect(getQueuedRunEdit(threadKey)).toBeNull();+ expect(appAtomRegistry.get(threadComposerErrorsAtom)[threadKey]?.message).toBe(+ "That message already started, so the edit was discarded.",+ );+ });+});++describe("activeComposerDraftKey", () => {+ const threadKey = "env:thread";+ const editKey = queuedEditDraftKey(threadKey, RunId.make("run-1"));++ it("keeps a queued edit's draft while that edit is open", () => {+ expect(activeComposerDraftKey(threadKey, editKey, edit([]))).toBe(editKey);+ });++ it("falls back to the thread's draft once the edit has ended", () => {+ expect(activeComposerDraftKey(threadKey, editKey, null)).toBe(threadKey);+ });+});diff --git a/apps/mobile/src/state/queued-run-edit.ts b/apps/mobile/src/state/queued-run-edit.tsindex 5e99d75ee85..dae52d9eb93 100644--- a/apps/mobile/src/state/queued-run-edit.ts+++ b/apps/mobile/src/state/queued-run-edit.ts@@ -5,15 +5,22 @@ import type {RunId,UploadChatAttachment,} from "@t3tools/contracts";-import { Atom } from "effect/reactivity";import { useAtomValue } from "@effect/atom-react";+import {+ makeQueuedRunEditStore,+ resolveQueuedEditExit,+ type QueuedRunsAtom,+} from "@t3tools/client-runtime/queued-run-edit";import { uploadedComposerContext } from "../lib/composerContext";import { appAtomRegistry } from "./atom-registry";import { abortComposerDraftOperations } from "./composerDraftOperations";import { queuedEditDraftKey } from "./queued-edit-draft-key";+import { setThreadComposerError } from "./thread-composer-error";import {clearComposerDraft,+ getComposerDraftSnapshot,+ mergeComposerDraftContent,setComposerDraftContext,setComposerDraftText,} from "./use-composer-drafts";@@ -24,38 +31,86 @@ export interface QueuedRunEdit {readonly originalText: string;readonly existingAttachments: ReadonlyArray<ChatAttachment>;readonly context?: OrchestrationMessageContext;+ /** Removing a server attachment changes the message even when the draft looks untouched. */+ readonly removedExistingAttachment?: true;}-export const queuedRunEditsAtom = Atom.make<Readonly<Record<string, QueuedRunEdit>>>({}).pipe(- Atom.keepAlive,- Atom.withLabel("mobile-queued-run-edits"),-);+const queuedRunEdits = makeQueuedRunEditStore<QueuedRunEdit>({+ registry: appAtomRegistry,+ label: "mobile-queued-run-edits",+});export { isQueuedEditDraftKey, queuedEditDraftKey } from "./queued-edit-draft-key";-export function getQueuedRunEdit(threadKey: string | null): QueuedRunEdit | null {- if (threadKey === null) return null;- return appAtomRegistry.get(queuedRunEditsAtom)[threadKey] ?? null;+export const getQueuedRunEdit = queuedRunEdits.get;++/**+ * The draft a sheet opened for `requestedKey` should edit now: a queued edit's+ * draft only while that edit is still open, else the thread's own draft.+ */+export function activeComposerDraftKey(+ threadKey: string,+ requestedKey: string,+ edit: QueuedRunEdit | null,+): string {+ if (requestedKey === threadKey) return threadKey;+ return edit !== null && queuedEditDraftKey(threadKey, edit.runId) === requestedKey+ ? requestedKey+ : threadKey;}export function useQueuedRunEdit(threadKey: string | null): QueuedRunEdit | null {- const edits = useAtomValue(queuedRunEditsAtom);+ const edits = useAtomValue(queuedRunEdits.atom);return threadKey === null ? null : (edits[threadKey] ?? null);}-function setQueuedRunEdit(threadKey: string, edit: QueuedRunEdit | null): void {- const current = appAtomRegistry.get(queuedRunEditsAtom);- if (edit === null) {- if (!current[threadKey]) return;- const next = { ...current };- delete next[threadKey];- appAtomRegistry.set(queuedRunEditsAtom, next);- return;+/**+ * The run started or was cancelled elsewhere. A changed edit goes back into+ * the thread's composer when that is empty; otherwise it is dropped. Either+ * way the thread says so, wherever the user is when it happens.+ */+function exitQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void {+ const editDraftKey = queuedEditDraftKey(threadKey, edit.runId);+ const editDraft = getComposerDraftSnapshot(editDraftKey);+ const threadDraft = getComposerDraftSnapshot(threadKey);+ const editRestorable = editDraft.text.trim().length > 0 || editDraft.attachments.length > 0;+ const recovery = resolveQueuedEditExit({+ editChanged:+ editDraft.text !== edit.originalText ||+ editDraft.attachments.length > 0 ||+ edit.removedExistingAttachment === true,+ // A cleared edit has nothing to put back, so it can only be discarded.+ threadDraftEmpty:+ editRestorable &&+ threadDraft.text.trim().length === 0 &&+ threadDraft.attachments.length === 0,+ });+ if (recovery === "kept") {+ // The merge publishes the draft before writing it, so a failed write only delays persistence to the next one.+ mergeComposerDraftContent(threadKey, {+ text: editDraft.text,+ attachments: editDraft.attachments,+ ...(editDraft.context ? { context: editDraft.context } : {}),+ }).catch((error: unknown) => {+ console.warn("[queued-run-edit] could not persist the recovered edit", error);+ });}- appAtomRegistry.set(queuedRunEditsAtom, { ...current, [threadKey]: edit });+ clearComposerDraft(editDraftKey, { deferAttachmentCleanup: recovery === "kept" });+ if (recovery === "clean") return;+ setThreadComposerError(+ threadKey,+ recovery === "kept"+ ? "That message already started. Your edit is back in the composer."+ : "That message already started, so the edit was discarded.",+ );}-export function beginQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void {+/** `runs` is the thread's runs; the edit ends when its run leaves the queue. */+export function beginQueuedRunEdit(+ threadKey: string,+ edit: QueuedRunEdit,+ runs: QueuedRunsAtom,+): void {const previous = getQueuedRunEdit(threadKey);if (previous !== null && previous.runId !== edit.runId) {clearComposerDraft(queuedEditDraftKey(threadKey, previous.runId));@@ -66,18 +121,17 @@ export function beginQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): voidclearComposerDraft(draftKey);setComposerDraftText(draftKey, edit.originalText);setComposerDraftContext(draftKey, edit.context);- setQueuedRunEdit(threadKey, edit);+ queuedRunEdits.begin(threadKey, edit, { runs, onRunLeftQueue: exitQueuedRunEdit });}export function removeQueuedRunEditAttachment(threadKey: string, attachmentId: string): void {- const edit = getQueuedRunEdit(threadKey);- if (edit === null) return;- setQueuedRunEdit(threadKey, {+ queuedRunEdits.update(threadKey, (edit) => ({...edit,+ removedExistingAttachment: true,existingAttachments: edit.existingAttachments.filter((attachment) => attachment.id !== attachmentId,),- });+ }));}export function endQueuedRunEdit(@@ -87,9 +141,15 @@ export function endQueuedRunEdit(const edit = getQueuedRunEdit(threadKey);if (edit === null) return;clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), options);- setQueuedRunEdit(threadKey, null);+ queuedRunEdits.end(threadKey);}+/**+ * Claims the open edit for a save; while it runs, the save's result decides the+ * edit's fate. Null when there is no edit or a save is already in flight.+ */+export const startQueuedRunEditSave = queuedRunEdits.startSave;+/** Attachments replace wholesale; resend kept server attachments with uploads in composer order. */export function resolveQueuedEditPayload(input: {readonly edit: QueuedRunEdit;diff --git a/apps/mobile/src/state/thread-provider-switching.ts b/apps/mobile/src/state/thread-provider-switching.tsindex 72d07ffddaa..50e4a668eb7 100644--- a/apps/mobile/src/state/thread-provider-switching.ts+++ b/apps/mobile/src/state/thread-provider-switching.ts@@ -1,6 +1,6 @@import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";import { threadSupportsProviderHandoff } from "@t3tools/client-runtime/state/thread-workflows";-import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";+import type { ThreadStructure } from "@t3tools/client-runtime/state/models";type ThreadStartMarkers = Pick<EnvironmentThreadShell,@@ -16,7 +16,7 @@ function threadShellHasStarted(thread: ThreadStartMarkers | null | undefined): bexport function threadAllowsProviderSwitch(input: {readonly thread: ThreadStartMarkers | null | undefined;- readonly projection: OrchestrationV2ThreadProjection | null | undefined;+ readonly projection: ThreadStructure | null | undefined;}): boolean {return input.projection != null? threadSupportsProviderHandoff(input.projection)diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.tsindex 5b86b886509..74206557b0a 100644--- a/apps/mobile/src/state/use-thread-composer-state.ts+++ b/apps/mobile/src/state/use-thread-composer-state.ts@@ -13,7 +13,7 @@ import {deriveThreadRuntime,threadRuntimeHasInterruptibleRun,} from "@t3tools/client-runtime/state/thread-execution";-import { useEffect, useRef, useState } from "react";+import { useRef, useState } from "react";import {CommandId,@@ -24,7 +24,7 @@ import {type EnvironmentId,type ModelSelection,type ProviderInteractionMode,- type RuntimeMode,+ type ServerProvider,type ThreadId,} from "@t3tools/contracts";import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";@@ -54,7 +54,10 @@ import type { DraftComposerImageAttachment } from "../lib/composerImages";import { scopedThreadKey } from "../lib/scopedEntities";import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity";import { acknowledgedThreadMessagesAtom } from "./acknowledged-thread-messages";-import { appendPendingThreadMessages } from "../features/threads/pending-thread-feed";+import {+ appendPendingThreadMessages,+ selectPendingAcknowledgedMessages,+} from "../features/threads/pending-thread-feed";import { threadAllowsProviderSwitch } from "./thread-provider-switching";import { appAtomRegistry } from "../state/atom-registry";import { pendingThreadCreationMessage } from "./pending-thread-creation";@@ -68,9 +71,9 @@ import {countComposerDraftAttachmentsAfterSelection,insertComposerDraftText,insertComposerDraftContext,+ clearComposerDraft,clearComposerDraftContent,composerContextImportsAtom,- ensureComposerDraftsLoaded,getComposerDraftSnapshot,mergeComposerDraftContent,removeComposerDraftAttachment,@@ -97,6 +100,7 @@ import {queuedEditDraftKey,removeQueuedRunEditAttachment,resolveQueuedEditPayload,+ startQueuedRunEditSave,useQueuedRunEdit,} from "./queued-run-edit";import { setPendingConnectionError } from "../state/use-remote-environment-registry";@@ -171,6 +175,21 @@ export function useThreadDraftForThread(input: {};}+/** A provider without the interaction-mode toggle runs in the default mode. */+export function updateThreadDraftModelSelection(+ threadKey: string,+ value: ModelSelection,+ providers: ReadonlyArray<ServerProvider>,+): void {+ const provider = providers.find((candidate) => candidate.instanceId === value.instanceId);+ updateComposerDraftSettings(threadKey, {+ modelSelection: value,+ ...(provider?.showInteractionModeToggle === false+ ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }+ : {}),+ });+}+export function useThreadComposerState() {const {selectedThread: selectedThreadShell,@@ -210,10 +229,6 @@ export function useThreadComposerState() {return nextName;};- useEffect(() => {- ensureComposerDraftsLoaded();- }, []);-const selectedThreadKey = selectedThreadShell? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id): null;@@ -259,27 +274,16 @@ export function useThreadComposerState() {checkpointSummaries,cache: feedCache,});- const pendingAcknowledgments = acknowledgedMessages.filter(- (message) =>- scopedThreadKey(message.environmentId, message.threadId) === selectedThreadKey &&- !selectedThreadQueuedMessages.some((queued) => queued.messageId === message.messageId),- );+ const pendingAcknowledgments = selectPendingAcknowledgedMessages(acknowledgedMessages, {+ threadKey: selectedThreadKey,+ queuedMessages: selectedThreadQueuedMessages,+ projectedMessages: selectedThreadMessages,+ });if (pendingAcknowledgments.length === 0) return feed;return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>entry.pendingMessage ? { ...entry, acknowledged: true } : entry,);})();- useEffect(() => {- const echoedIds = new Set(selectedThreadMessages?.map((message) => message.id));- if (acknowledgedMessages.some((message) => echoedIds.has(message.messageId))) {- appAtomRegistry.set(- acknowledgedThreadMessagesAtom,- appAtomRegistry- .get(acknowledgedThreadMessagesAtom)- .filter((message) => !echoedIds.has(message.messageId)),- );- }- }, [acknowledgedMessages, selectedThreadMessages]);const preferencesResult = useAtomValue(mobilePreferencesAtom);const followUpBehavior = AsyncResult.isSuccess(preferencesResult)@@ -392,40 +396,6 @@ export function useThreadComposerState() {? deriveProviderSubagentStatus(selectedThreadProjection.projection): null;- const selectedThreadRuns = selectedThreadProjection?.projection.runs;- const editedRunId = queuedRunEdit?.runId ?? null;- useEffect(() => {- if (selectedThreadKey === null || editedRunId === null || selectedThreadRuns === undefined) {- return;- }- if (savingQueuedEditRef.current) return;- const stillQueued = selectedThreadRuns.some(- (run) => run.id === editedRunId && run.status === "queued",- );- if (stillQueued) return;- const editDraftKey = queuedEditDraftKey(selectedThreadKey, editedRunId);- const editDraft = getComposerDraftSnapshot(editDraftKey);- const threadDraft = getComposerDraftSnapshot(selectedThreadKey);- const keepable =- editDraft.text.trim().length > 0 &&- threadDraft.text.trim().length === 0 &&- threadDraft.attachments.length === 0;- if (keepable) {- void mergeComposerDraftContent(selectedThreadKey, {- text: editDraft.text,- attachments: editDraft.attachments,- ...(editDraft.context ? { context: editDraft.context } : {}),- });- }- endQueuedRunEdit(selectedThreadKey, { deferAttachmentCleanup: keepable });- setThreadComposerError(- selectedThreadKey,- keepable- ? "That message already started. Your edit is back in the composer."- : "That message already started, so the edit was discarded.",- );- }, [editedRunId, selectedThreadKey, selectedThreadRuns]);-const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)? (selectedThreadRuntime?.activeRunId ?? null)@@ -463,6 +433,8 @@ export function useThreadComposerState() {);return;}+ const finishSave = startQueuedRunEditSave(threadKey);+ if (finishSave === null) return;savingQueuedEditRef.current = true;setIsSavingQueuedEdit(true);const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;@@ -476,6 +448,7 @@ export function useThreadComposerState() {if (AsyncResult.isFailure(prepared)) {savingQueuedEditRef.current = false;setIsSavingQueuedEdit(false);+ finishSave(false);const error = squashAtomCommandFailure(prepared);Dialog.alert("Could not save the queued message",@@ -486,6 +459,7 @@ export function useThreadComposerState() {if (prepared.value.status !== "ready") {savingQueuedEditRef.current = false;setIsSavingQueuedEdit(false);+ finishSave(false);return;}const payload = resolveQueuedEditPayload({@@ -510,13 +484,20 @@ export function useThreadComposerState() {savingQueuedEditRef.current = false;setIsSavingQueuedEdit(false);if (result._tag !== "Success") {+ // The run left the queue during the save; its exit already told the composer what happened.+ if (!finishSave(false)) return;Dialog.alert("Could not save the queued message","It may have already started. Your edit is still in the composer.",);return;}- endQueuedRunEdit(threadKey, { deferAttachmentCleanup: true });+ // False when the edit was cancelled or begun again meanwhile; its draft is the newer edit's.+ if (finishSave(true)) {+ clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), {+ deferAttachmentCleanup: true,+ });+ }scheduleUnusedComposerAttachmentCleanup(draft.attachments);};@@ -837,28 +818,6 @@ export function useThreadComposerState() {removeComposerDraftAttachment(threadKey, imageId);};- const onUpdateModelSelection = (value: ModelSelection) => {- if (!selectedThreadKey) {- return;- }- const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(- (candidate) => candidate.instanceId === value.instanceId,- );- updateComposerDraftSettings(selectedThreadKey, {- modelSelection: value,- ...(provider?.showInteractionModeToggle === false- ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }- : {}),- });- };-- const onUpdateRuntimeMode = (value: RuntimeMode) => {- if (!selectedThreadKey) {- return;- }- updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });- };-const onUpdateInteractionMode = (value: ProviderInteractionMode) => {if (!selectedThreadKey) {return;@@ -908,8 +867,6 @@ export function useThreadComposerState() {onNativePasteText,onRemoveDraftImage,onSendMessage,- onUpdateModelSelection,- onUpdateRuntimeMode,onUpdateInteractionMode,};}diff --git a/apps/mobile/src/state/use-thread-detail.ts b/apps/mobile/src/state/use-thread-detail.tsindex 3ef33e75add..ad684b3b6a6 100644--- a/apps/mobile/src/state/use-thread-detail.ts+++ b/apps/mobile/src/state/use-thread-detail.ts@@ -1,7 +1,13 @@import { useAtomValue } from "@effect/atom-react";import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";+import type { EnvironmentThreadStructure } from "@t3tools/client-runtime/state/models";import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";-import type { EnvironmentId, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts";+import type {+ EnvironmentId,+ OrchestrationV2ThreadProjection,+ ScopedThreadRef,+ ThreadId,+} from "@t3tools/contracts";import { Atom } from "effect/reactivity";import { environmentThreadDetails, useEnvironmentThread } from "./threads";@@ -10,6 +16,9 @@ import { useThreadSelection } from "./use-thread-selection";const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(Atom.withLabel("mobile-thread-projection:empty"),);+const EMPTY_THREAD_STRUCTURE_ATOM = Atom.make<EnvironmentThreadStructure | null>(null).pipe(+ Atom.withLabel("mobile-thread-structure:empty"),+);const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make<OrchestrationV2ThreadProjection["visibleTurnItems"]>(Object.freeze([])).pipe(Atom.withLabel("mobile-thread-visible-turn-items:empty"));@@ -42,6 +51,15 @@ export function useThreadProjection(target: ThreadDetailTarget): EnvironmentThre);}+/** Keeps its value through streamed text; runs, sessions, and item status still update. */+export function useQuietThreadStructure(+ ref: ScopedThreadRef | null,+): EnvironmentThreadStructure | null {+ return useAtomValue(+ ref === null ? EMPTY_THREAD_STRUCTURE_ATOM : environmentThreadDetails.quietThreadAtom(ref),+ );+}+export function useSelectedThreadProjection(): EnvironmentThread | null {const { selectedThreadDetailRef } = useThreadSelection();return useThreadProjection({diff --git a/apps/mobile/src/state/use-thread-outbox-drain.permissions.test.ts b/apps/mobile/src/state/use-thread-outbox-drain.permissions.test.tsindex 3bdab5f7a62..f199616d43c 100644--- a/apps/mobile/src/state/use-thread-outbox-drain.permissions.test.ts+++ b/apps/mobile/src/state/use-thread-outbox-drain.permissions.test.ts@@ -78,6 +78,7 @@ vi.mock("./threads", async () => {setInteractionMode: state.interaction,},environmentThreadShells: { threadShellsAtom: Atom.make([state.thread]) },+ environmentThreadDetails: { threadAtom: Atom.family((_key: unknown) => Atom.make(null)) },};});vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));diff --git a/apps/mobile/src/state/use-thread-outbox-drain.test.ts b/apps/mobile/src/state/use-thread-outbox-drain.test.tsindex f62686baf23..c4968d3e33e 100644--- a/apps/mobile/src/state/use-thread-outbox-drain.test.ts+++ b/apps/mobile/src/state/use-thread-outbox-drain.test.ts@@ -89,9 +89,13 @@ vi.mock("./server", async () => {vi.mock("./git", () => ({ gitEnvironment: {} }));-vi.mock("./threads", () => ({- threadEnvironment: {},-}));+vi.mock("./threads", async () => {+ const { Atom } = await import("effect/reactivity");+ return {+ threadEnvironment: {},+ environmentThreadDetails: { threadAtom: Atom.family((_key: unknown) => Atom.make(null)) },+ };+});vi.mock("./use-atom-command", () => ({useAtomCommand: () => async () => undefined,diff --git a/packages/client-runtime/src/queuedRunEdit.test.ts b/packages/client-runtime/src/queuedRunEdit.test.tsindex 24d2dc42402..6ecd2bc59cd 100644--- a/packages/client-runtime/src/queuedRunEdit.test.ts+++ b/packages/client-runtime/src/queuedRunEdit.test.ts@@ -81,10 +81,19 @@ describe("makeQueuedRunEditStore", () => {const finishSave = store.startSave("env:thread");registry.set(runs, []);expect(exits).toEqual([]);- expect(finishSave?.(false)).toBe(true);+ expect(finishSave?.(false)).toBe(false);expect(exits).toHaveLength(1);});+ it("reports the edit still open when a save fails while its run is queued", () => {+ const { store, exits, begin } = setup();+ begin();+ const finishSave = store.startSave("env:thread");+ expect(finishSave?.(false)).toBe(true);+ expect(exits).toEqual([]);+ expect(store.get("env:thread")).toEqual({ runId: RUN, text: "draft" });+ });+it("allows one save at a time and ends the edit when it succeeds", () => {const { registry, store, begin } = setup();begin();diff --git a/packages/client-runtime/src/queuedRunEdit.ts b/packages/client-runtime/src/queuedRunEdit.tsindex 5d9377b2638..d366a0d1f39 100644--- a/packages/client-runtime/src/queuedRunEdit.ts+++ b/packages/client-runtime/src/queuedRunEdit.ts@@ -69,10 +69,9 @@ interface ExitWatch<E> {}/**- * Settles a save started with `startSave`. Returns false, changing nothing,- * when the edit the save started from was ended or begun again meanwhile; the- * caller must then leave the edit's drafts alone. Otherwise success ends the- * edit and failure resumes its exit watch.+ * Settles a save from `startSave`. False, changing nothing, when the edit was+ * ended or begun again meanwhile. Success ends the edit; failure resumes its+ * exit watch and returns whether the edit survived it.*/export type FinishQueuedRunEditSave = (succeeded: boolean) => boolean;@@ -196,10 +195,10 @@ export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(optiif (succeeded) {stopWatch(threadKey);write(threadKey, null);- } else {- subscribe(threadKey, watch);+ return true;}- return true;+ subscribe(threadKey, watch);+ return watches.get(threadKey) === watch;};},};