@devries-cameron20 / t3code-1 / commits / 0623d09aee
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

refactor(mobile): drop the unreachable pending-task editor from new-task drafts (#25684)

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

Julius Marminge committed Oct 26, 2026 at 17:09 UTC 0623d09aeed210c77b6b149359f630983d90fe05
9 files changed +36 -676
apps/mobile/src/Stack.tsx
+2 -11
@@ -500,16 +500,11 @@ function RootStackLayout(props: {
500 );
501 const draftRoute = props.state.routes.findLast((route) => route.name === "Thread");
502 const draftParams = (
503 - draftRoute?.params as
504 - | { draft?: { draftId?: string | string[]; pendingTaskId?: string | string[] } }
505 - | undefined
503 + draftRoute?.params as { draft?: { draftId?: string | string[] } } | undefined
504 )?.draft;
505 const routeDraftId = Array.isArray(draftParams?.draftId)
506 ? draftParams.draftId[0]
507 : draftParams?.draftId;
510 - const routePendingTaskId = Array.isArray(draftParams?.pendingTaskId)
511 - ? draftParams.pendingTaskId[0]
512 - : draftParams?.pendingTaskId;
508 useAgentNotificationNavigation(workspaceLocation.pathname);
509 useConnectOnboardingNavigation();
510 useAppShortcuts(props.state);
@@ -531,11 +526,7 @@ function RootStackLayout(props: {
526 }, [navigation, pendingShare, props.state]);
527
528 return (
534 - <NewTaskFlowProvider
535 - active={isDraftThreadRoute(draftRoute)}
536 - routeDraftId={routeDraftId}
537 - routePendingTaskId={routePendingTaskId}
538 - >
529 + <NewTaskFlowProvider active={isDraftThreadRoute(draftRoute)} routeDraftId={routeDraftId}>
530 <HardwareKeyboardCommandProvider pathname={pathname}>
531 <ShowcaseCaptureCoordinator pathname={pathname} />
532 <SettingsEnvironmentFilterProvider open={settingsOpen}>
apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
+1 -5
@@ -40,9 +40,6 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
40 // oxlint-disable-next-line react/set-state-in-effect -- Draft reset runs once before first paint; initialized gates the screen until then.
41 setInitialized(true);
42 }, [reset]);
43 - const pendingTaskId = Array.isArray(params.pendingTaskId)
44 - ? params.pendingTaskId[0]
45 - : params.pendingTaskId;
43 const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
44 const projects = useProjects();
45 const { state: catalogState } = useWorkspaceState();
@@ -75,7 +72,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
72 );
73 const environmentId = project?.environmentId;
74 const workspaceRoot = project?.workspaceRoot;
78 - const needsPreparation = Boolean(initialProjectRef.branch && !pendingTaskId && !draftId);
75 + const needsPreparation = Boolean(initialProjectRef.branch && !draftId);
76
77 const [pendingCheckouts, setPendingCheckouts] = useState(0);
78 const checkoutTail = useRef(Promise.resolve());
@@ -200,7 +197,6 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
197 ? params.incomingShareId[0]
198 : params.incomingShareId
199 }
203 - pendingTaskId={pendingTaskId}
200 draftId={draftId}
201 />
202 )}
apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+14 -52
@@ -150,7 +150,6 @@ export function NewTaskDraftScreen(props: {
150 readonly worktreePath?: string | null;
151 readonly cloning?: boolean;
152 };
153 - readonly pendingTaskId?: string;
153 readonly draftId?: string;
154 readonly incomingShareId?: string;
155 }) {
@@ -386,11 +385,11 @@ export function NewTaskDraftScreen(props: {
385 };
386 }, []);
387
389 - const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask, openDraft } = flow;
388 + const { openDraft } = flow;
389 // Cold launches load drafts and projects separately; wait for hydration and retry while shells load.
390 const attemptedDraftIdRef = useRef<string | null>(null);
391 useEffect(() => {
393 - if (!props.draftId || props.pendingTaskId) {
392 + if (!props.draftId) {
393 return;
394 }
395 const draftId = props.draftId;
@@ -415,34 +414,12 @@ export function NewTaskDraftScreen(props: {
414 return () => {
415 cancelled = true;
416 };
418 - }, [navigation, openDraft, projects, props.draftId, props.pendingTaskId]);
419 -
420 - const attemptedPendingTaskIdRef = useRef<string | null>(null);
421 - useEffect(() => {
422 - if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
423 - return;
424 - }
425 - if (attemptedPendingTaskIdRef.current === props.pendingTaskId) {
426 - return;
427 - }
428 - attemptedPendingTaskIdRef.current = props.pendingTaskId;
429 - if (!beginEditingPendingTask(props.pendingTaskId)) {
430 - navigation.dispatch(CommonActions.navigate("NewTaskProject"));
431 - }
432 - }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
433 -
434 - useEffect(() => {
435 - if (!props.pendingTaskId) return;
436 - return () => {
437 - attemptedPendingTaskIdRef.current = null;
438 - cancelEditingPendingTask();
439 - };
440 - }, [props.pendingTaskId, cancelEditingPendingTask]);
417 + }, [navigation, openDraft, projects, props.draftId]);
418
419 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
420
421 useEffect(() => {
445 - if (props.pendingTaskId || props.draftId) {
422 + if (props.draftId) {
423 return;
424 }
425 if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
@@ -516,9 +493,8 @@ export function NewTaskDraftScreen(props: {
493 projects,
494 flow.draftKey,
495 props.initialProjectRef,
519 - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening a draft from a share, pending task, or draft id re-resolves its project.
496 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening a draft from a share or draft id re-resolves its project.
497 props.incomingShareId,
521 - props.pendingTaskId,
498 props.draftId,
499 navigation,
500 selectedProject,
@@ -901,17 +877,7 @@ export function NewTaskDraftScreen(props: {
877 return null;
878 }
879
904 - const editingPendingTask = flow.editingPendingTask;
905 -
906 - const metadata = editingPendingTask
907 - ? {
908 - threadId: editingPendingTask.threadId,
909 - commandId: editingPendingTask.commandId,
910 - messageId: editingPendingTask.messageId,
911 - createdAt: editingPendingTask.createdAt,
912 - }
913 - : creationMetadata;
914 - const message = flow.buildPendingTaskMessage(metadata, {
880 + const message = flow.buildPendingTaskMessage(creationMetadata, {
881 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
882 });
883 if (!message) {
@@ -939,17 +905,13 @@ export function NewTaskDraftScreen(props: {
905 // would otherwise resurrect this draft.
906 abortComposerDraftOperations(draftKey);
907 const draftSnapshot = getComposerDraftSnapshot(draftKey);
942 - if (editingPendingTask) {
943 - flow.finishEditingPendingTask();
944 - } else {
945 - // The queued message owns the attachments now, so the sweep is deferred
946 - // until the write confirms it.
947 - clearComposerDraftContent(draftKey, {
948 - clearModelSelection: true,
949 - clearWorkspaceSelection: true,
950 - deferAttachmentCleanup: true,
951 - });
952 - }
908 + // The queued message owns the attachments now, so the sweep is deferred
909 + // until the write confirms it.
910 + clearComposerDraftContent(draftKey, {
911 + clearModelSelection: true,
912 + clearWorkspaceSelection: true,
913 + deferAttachmentCleanup: true,
914 + });
915 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
916 return message.messageId;
917 }
@@ -1146,7 +1108,7 @@ export function NewTaskDraftScreen(props: {
1108 const thread = draftThreadShell({
1109 environmentId: selectedProject.environmentId,
1110 projectId: selectedProject.id,
1149 - threadId: ThreadId.make(flow.editingPendingTask?.threadId ?? creationMetadata.threadId),
1111 + threadId: ThreadId.make(creationMetadata.threadId),
1112 modelSelection: flow.selectedModel,
1113 runtimeMode: flow.runtimeMode,
1114 interactionMode: flow.interactionMode,
apps/mobile/src/features/threads/new-task-flow-provider.tsx
+16 -241
@@ -17,7 +17,6 @@ import type {
17 import {
18 CommandId,
19 DEFAULT_PROVIDER_INTERACTION_MODE,
20 - DEFAULT_RUNTIME_MODE,
20 DEFAULT_SERVER_SETTINGS,
21 MessageId,
22 repositoryGroupingKeyOf,
@@ -54,43 +53,26 @@ import { useAtomCommand } from "../../state/use-atom-command";
53 import {
54 appendComposerDraftAttachments,
55 type ComposerDraftInsertion,
57 - clearComposerDraft,
56 composerDraftsAtom,
57 createNewTaskDraft,
58 getComposerDraftSnapshot,
61 - isComposerDraftEmpty,
59 isNewTaskDraftKey,
60 removeComposerDraftAttachment,
61 replaceComposerDraftAttachments,
62 retargetNewTaskDraft,
66 - scheduleUnusedComposerAttachmentCleanup,
63 setComposerDraftText,
68 - setComposerDraftContext,
64 setStickyComposerModelSelection,
65 updateComposerDraftSettings,
66 useComposerDraft,
67 useStickyComposerModelSelection,
68 } from "../../state/use-composer-drafts";
74 -import {
75 - capturePendingTaskEditorWriteBaseline,
76 - flushPendingTaskEditorWrite,
77 -} from "../../state/pending-task-editor-writes";
69 import {
70 rememberModelOptions,
71 withRememberedModelOptions,
72 } from "../../state/use-model-option-memory";
73 import { useBranches, usePaginatedBranches } from "../../state/queries";
74 import { vcsEnvironment } from "../../state/vcs";
84 -import {
85 - flattenQueuedThreadMessages,
86 - threadOutboxManager,
87 - type QueuedThreadMessage,
88 -} from "../../state/thread-outbox";
89 -import {
90 - holdEditingQueuedMessage,
91 - releaseEditingQueuedMessage,
92 - useThreadOutboxMessages,
93 -} from "../../state/use-thread-outbox";
75 +import { type QueuedThreadMessage } from "../../state/thread-outbox";
76 import {
77 setPendingConnectionError,
78 useRemoteConnectionStatus,
@@ -126,20 +108,6 @@ import { useOlderSettledCount } from "../../state/olderSettledShelf";
108
109 type WorkspaceMode = "local" | "worktree";
110
129 -function pendingTaskDraftKey(messageId: string): string {
130 - return `pending-task:${messageId}`;
131 -}
132 -
133 -// Track ownership across providers so old unmount flushes cannot drop newer drafts or drain locks.
134 -let activeEditingMessageId: string | null = null;
135 -
136 -function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null {
137 - const message = flattenQueuedThreadMessages(
138 - appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
139 - ).find((candidate) => candidate.messageId === messageId);
140 - return message?.creation !== undefined ? message : null;
141 -}
142 -
111 export function branchBadgeLabel(input: {
112 readonly branch: VcsRef;
113 readonly project: EnvironmentProject | null;
@@ -174,7 +142,6 @@ type NewTaskFlowContextValue = {
142 readonly startFromOrigin: boolean;
143 readonly pullRequestReference: string | undefined;
144 readonly draftKey: string | null;
177 - readonly editingPendingTask: QueuedThreadMessage | null;
145 readonly prompt: string;
146 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
147 readonly submitting: boolean;
@@ -210,9 +177,6 @@ type NewTaskFlowContextValue = {
177 readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
178 readonly selectBranch: (branch: VcsRef) => void;
179 readonly setStartFromOrigin: (value: boolean) => void;
213 - readonly beginEditingPendingTask: (messageId: string) => boolean;
214 - readonly finishEditingPendingTask: () => void;
215 - readonly cancelEditingPendingTask: () => void;
180 readonly buildPendingTaskMessage: (
181 metadata: TurnCommandMetadata,
182 options?: {
@@ -244,15 +208,13 @@ export function NewTaskFlowProvider(
208 props: React.PropsWithChildren<{
209 active?: boolean;
210 routeDraftId?: string;
247 - routePendingTaskId?: string;
211 }>,
212 ) {
213 const projects = useProjects();
214 const threads = useThreadShells();
215 const { savedConnectionsById } = useSavedRemoteConnections();
216 const groupingSettings = useMobileProjectGroupingSettings();
254 - const { enabled: legacyPlanModeEnabled, loaded: planModePreferenceLoaded } =
255 - useLegacyPlanModeState();
217 + const { enabled: legacyPlanModeEnabled } = useLegacyPlanModeState();
218
219 const projectScopes = sortHomeProjectScopes({
220 scopes: buildHomeProjectScopes({
@@ -277,11 +239,7 @@ export function NewTaskFlowProvider(
239 const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
240 const [submitting, setSubmitting] = useState(false);
241 const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
280 - const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
242 const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
282 - // Mirror edit state synchronously so unmount flush cannot save a session ended this render.
283 - const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
284 - const editingRevisionRef = useRef(Promise.resolve(0));
243
244 const reset = useCallback(() => {
245 setSelectedEnvironmentId(null);
@@ -290,15 +248,6 @@ export function NewTaskFlowProvider(
248 setSubmitting(false);
249 setExpandedProvider(null);
250 pendingLocalBranchSyncDraftKeysRef.current.clear();
293 - const editing = editingPendingTaskRef.current;
294 - editingPendingTaskRef.current = null;
295 - setEditingPendingTask(null);
296 - if (editing) {
297 - if (activeEditingMessageId === editing.messageId) {
298 - activeEditingMessageId = null;
299 - }
300 - releaseEditingQueuedMessage(editing.messageId);
301 - }
251 }, []);
252
253 const projectsForEnvironment = pipe(
@@ -306,34 +255,12 @@ export function NewTaskFlowProvider(
255 Arr.filter((project) => project.environmentId === selectedEnvironmentId),
256 );
257
309 - const editingPendingProject = ((): EnvironmentProject | null => {
310 - const creation = editingPendingTask?.creation;
311 - if (!editingPendingTask || !creation) {
312 - return null;
313 - }
314 - return {
315 - environmentId: editingPendingTask.environmentId,
316 - id: creation.projectId,
317 - title: creation.projectTitle ?? "Unknown project",
318 - workspaceRoot: creation.projectCwd ?? "",
319 - repositoryIdentity: null,
320 - defaultModelSelection: editingPendingTask.modelSelection ?? null,
321 - scripts: [],
322 - createdAt: editingPendingTask.createdAt,
323 - updatedAt: editingPendingTask.createdAt,
324 - };
325 - })();
326 -
258 const selectedProject =
259 projectsForEnvironment.find(
260 (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
261 ) ??
331 - // Pin queued edits to their original project when its shell is missing; fallback would silently retarget them.
332 - (editingPendingProject !== null &&
333 - selectedProjectKey ===
334 - scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id)
335 - ? editingPendingProject
336 - : (projectsForEnvironment[0] ?? null));
262 + projectsForEnvironment[0] ??
263 + null;
264
265 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
266 selectedProject?.environmentId ?? null,
@@ -404,18 +331,9 @@ export function NewTaskFlowProvider(
331 return result;
332 })();
333
407 - const selectedProjectDraftKey = editingPendingTask
408 - ? pendingTaskDraftKey(editingPendingTask.messageId)
409 - : selectedProject
410 - ? activeDraftKey
411 - : null;
334 + const selectedProjectDraftKey = selectedProject ? activeDraftKey : null;
335 useEffect(() => {
413 - if (
414 - props.active === false ||
415 - activeDraftKey !== null ||
416 - editingPendingTask !== null ||
417 - selectedProject === null
418 - ) {
336 + if (props.active === false || activeDraftKey !== null || selectedProject === null) {
337 return;
338 }
339 // oxlint-disable-next-line react/set-state-in-effect -- Creates the persistent draft once the project selection is ready; the key must exist before the composer mounts.
@@ -425,19 +343,15 @@ export function NewTaskFlowProvider(
343 projectId: selectedProject.id,
344 }),
345 );
428 - }, [activeDraftKey, editingPendingTask, selectedProject, props.active]);
346 + }, [activeDraftKey, selectedProject, props.active]);
347 const activePendingKey =
348 props.active === false
349 ? null
432 - : props.routePendingTaskId
433 - ? `pending-task:${props.routePendingTaskId}`
434 - : props.routeDraftId
435 - ? `draft-task:${props.routeDraftId}`
436 - : editingPendingTask
437 - ? `pending-task:${editingPendingTask.messageId}`
438 - : selectedProjectDraftKey
439 - ? `draft-task:${selectedProjectDraftKey}`
440 - : null;
350 + : props.routeDraftId
351 + ? `draft-task:${props.routeDraftId}`
352 + : selectedProjectDraftKey
353 + ? `draft-task:${selectedProjectDraftKey}`
354 + : null;
355 const activeNewTask = React.useMemo(
356 () => (props.active === false ? null : { pendingKey: activePendingKey }),
357 [props.active, activePendingKey],
@@ -537,9 +451,7 @@ export function NewTaskFlowProvider(
451 const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
452 const startFromOrigin =
453 isGitRepo && (draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin);
540 - const defaultRuntimeMode = editingPendingTask
541 - ? (editingPendingTask.runtimeMode ?? DEFAULT_RUNTIME_MODE)
542 - : projectSettings.settings.defaultRuntimeMode;
454 + const defaultRuntimeMode = projectSettings.settings.defaultRuntimeMode;
455 const runtimeMode = selectedProjectDraft.runtimeMode ?? defaultRuntimeMode;
456
457 // Antigravity keeps unavailable selections so sign-out or a catalog change
@@ -687,7 +599,7 @@ export function NewTaskFlowProvider(
599 const target = { environmentId: project.environmentId, projectId: project.id };
600 if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
601 retargetNewTaskDraft(activeDraftKey, target);
690 - } else if (!editingPendingTaskRef.current) {
602 + } else {
603 setActiveDraftKey(createNewTaskDraft(target));
604 }
605 };
@@ -914,39 +826,6 @@ export function NewTaskFlowProvider(
826 }
827 };
828
917 - const beginEditingPendingTask = (messageId: string): boolean => {
918 - const message = findQueuedPendingTask(messageId);
919 - if (!message?.creation) {
920 - return false;
921 - }
922 - const draftKey = pendingTaskDraftKey(message.messageId);
923 - if (isComposerDraftEmpty(getComposerDraftSnapshot(draftKey))) {
924 - setComposerDraftText(draftKey, message.text);
925 - setComposerDraftContext(draftKey, message.context);
926 - replaceComposerDraftAttachments(draftKey, message.attachments);
927 - updateComposerDraftSettings(draftKey, {
928 - modelSelection: message.modelSelection,
929 - runtimeMode: message.runtimeMode,
930 - interactionMode: message.interactionMode,
931 - workspaceSelection: {
932 - mode: message.creation.workspaceMode,
933 - branch: message.creation.branch,
934 - worktreePath: message.creation.worktreePath,
935 - startFromOrigin: message.creation.startFromOrigin ?? false,
936 - pullRequestReference: message.creation.pullRequestReference,
937 - },
938 - });
939 - }
940 - setSelectedEnvironmentId(message.environmentId);
941 - setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId));
942 - activeEditingMessageId = message.messageId;
943 - editingPendingTaskRef.current = message;
944 - editingRevisionRef.current = capturePendingTaskEditorWriteBaseline(message.messageId);
945 - setEditingPendingTask(message);
946 - holdEditingQueuedMessage(message.messageId);
947 - return true;
948 - };
949 -
829 const buildPendingTaskMessage = (
830 metadata: TurnCommandMetadata,
831 options?: { readonly currentCheckoutBranch?: string | null },
@@ -980,17 +859,6 @@ export function NewTaskFlowProvider(
859 isGitRepo,
860 });
861 const mode = workspaceSelection.mode;
983 - // When the selection is the stand-in built from the queued snapshot,
984 - // persist the original (possibly absent) snapshot values — the
985 - // stand-in's placeholder title/workspaceRoot must never be written back
986 - // as if they were real project metadata.
987 - const usingPendingSnapshot = selectedProject === editingPendingProject;
988 - const projectTitle = usingPendingSnapshot
989 - ? editingPendingTask?.creation?.projectTitle
990 - : selectedProject.title;
991 - const projectCwd = usingPendingSnapshot
992 - ? editingPendingTask?.creation?.projectCwd
993 - : selectedProject.workspaceRoot;
862 return {
863 environmentId: selectedProject.environmentId,
864 threadId: ThreadId.make(metadata.threadId),
@@ -1002,18 +870,16 @@ export function NewTaskFlowProvider(
870 modelSelection: draftModelSelection,
871 runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
872 interactionMode: resolvePendingTaskInteractionMode({
1005 - preferenceLoaded: planModePreferenceLoaded,
873 planModeEnabled: legacyPlanModeEnabled,
874 draftInteractionMode: draft.interactionMode,
1008 - queuedInteractionMode: editingPendingTask?.interactionMode,
875 provider: selectedEnvironmentServerConfig?.providers.find(
876 (candidate) => candidate.instanceId === draftModelSelection.instanceId,
877 ),
878 }),
879 creation: {
880 projectId: selectedProject.id,
1015 - ...(projectTitle !== undefined ? { projectTitle } : {}),
1016 - ...(projectCwd !== undefined ? { projectCwd } : {}),
881 + projectTitle: selectedProject.title,
882 + projectCwd: selectedProject.workspaceRoot,
883 workspaceMode: mode,
884 ...(mode === "worktree" && workspaceSelection?.pullRequestReference
885 ? { pullRequestReference: workspaceSelection.pullRequestReference }
@@ -1033,93 +899,6 @@ export function NewTaskFlowProvider(
899 };
900 };
901
1036 - const finishEditingPendingTask = () => {
1037 - const editing = editingPendingTaskRef.current;
1038 - editingPendingTaskRef.current = null;
1039 - if (editing) {
1040 - if (activeEditingMessageId === editing.messageId) {
1041 - activeEditingMessageId = null;
1042 - }
1043 - clearComposerDraft(pendingTaskDraftKey(editing.messageId));
1044 - releaseEditingQueuedMessage(editing.messageId);
1045 - scheduleUnusedComposerAttachmentCleanup(editing.attachments);
1046 - }
1047 - setEditingPendingTask(null);
1048 - };
1049 -
1050 - // End editing without saving if the queued task disappears; a later flush must not resurrect it.
1051 - const queuedMessagesByThreadKey = useThreadOutboxMessages();
1052 - useEffect(() => {
1053 - const editing = editingPendingTaskRef.current;
1054 - if (!editing) {
1055 - return;
1056 - }
1057 - const stillQueued = flattenQueuedThreadMessages(queuedMessagesByThreadKey).some(
1058 - (candidate) => candidate.messageId === editing.messageId,
1059 - );
1060 - if (!stillQueued) {
1061 - finishEditingPendingTask();
1062 - }
1063 - }, [finishEditingPendingTask, queuedMessagesByThreadKey]);
1064 -
1065 - const editingFlushRef = useRef<(() => void) | null>(null);
1066 - useEffect(() => {
1067 - editingFlushRef.current = () => {
1068 - const editing = editingPendingTaskRef.current;
1069 - if (!editing) {
1070 - return;
1071 - }
1072 - editingPendingTaskRef.current = null;
1073 - setEditingPendingTask(null);
1074 - if (activeEditingMessageId === editing.messageId) {
1075 - activeEditingMessageId = null;
1076 - }
1077 -
1078 - const message = buildPendingTaskMessage({
1079 - threadId: editing.threadId,
1080 - commandId: editing.commandId,
1081 - messageId: editing.messageId,
1082 - createdAt: editing.createdAt,
1083 - });
1084 -
1085 - if (!message) {
1086 - // Keep unsendable edits and the drain lock so removed content cannot auto-send from a stale payload.
1087 - return;
1088 - }
1089 -
1090 - // Hand off pending saves to reopened editors; CAS still rejects unrelated edits, deletes and deliveries.
1091 - void flushPendingTaskEditorWrite({
1092 - message,
1093 - baseline: editingRevisionRef.current,
1094 - draftKey: pendingTaskDraftKey(editing.messageId),
1095 - })
1096 - .then((savedDraftStillCurrent) => {
1097 - if (activeEditingMessageId === editing.messageId) {
1098 - return;
1099 - }
1100 - if (!savedDraftStillCurrent) {
1101 - return;
1102 - }
1103 - clearComposerDraft(pendingTaskDraftKey(editing.messageId));
1104 - releaseEditingQueuedMessage(editing.messageId);
1105 - scheduleUnusedComposerAttachmentCleanup(editing.attachments);
1106 - })
1107 - .catch((error) => {
1108 - // Keep the draft and drain lock on failure so stale payloads cannot discard edits; reopening retries.
1109 - console.warn("[new-task] failed to save edited pending task", error);
1110 - });
1111 - };
1112 - }, [buildPendingTaskMessage]);
1113 - const cancelEditingPendingTask = () => {
1114 - editingFlushRef.current?.();
1115 - };
1116 - useEffect(
1117 - () => () => {
1118 - editingFlushRef.current?.();
1119 - },
1120 - [],
1121 - );
1122 -
902 const value = {
903 activeNewTask,
904 projectScopes,
@@ -1135,7 +914,6 @@ export function NewTaskFlowProvider(
914 startFromOrigin,
915 draftKey: selectedProjectDraftKey,
916 pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
1138 - editingPendingTask,
917 prompt,
918 attachments,
919 submitting,
@@ -1164,9 +942,6 @@ export function NewTaskFlowProvider(
942 setWorkspaceMode,
943 selectBranch,
944 setStartFromOrigin,
1167 - beginEditingPendingTask,
1168 - finishEditingPendingTask,
1169 - cancelEditingPendingTask,
945 buildPendingTaskMessage,
946 setPrompt,
947 replaceAttachments,
apps/mobile/src/features/threads/thread-route-state.ts
-2
@@ -6,7 +6,6 @@ export type NewTaskDraftRouteParams = {
6 readonly worktreePath?: string | null;
7 readonly title?: string | string[];
8 readonly cloning?: string | string[];
9 - readonly pendingTaskId?: string | string[];
9 readonly draftId?: string | string[];
10 readonly incomingShareId?: string | string[];
11 };
@@ -32,7 +31,6 @@ export function draftRouteIdentity(draft: NewTaskDraftRouteParams): string {
31 const first = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value);
32 return JSON.stringify([
33 draft.requestId,
35 - first(draft.pendingTaskId),
34 first(draft.draftId),
35 first(draft.environmentId),
36 first(draft.projectId),
apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts
+1 -2
@@ -4,7 +4,7 @@ import { AsyncResult } from "effect/reactivity";
4 import { mobilePreferencesAtom } from "../../state/preferences";
5 import { resolveLegacyPlanModeEnabled } from "../../state/legacy-plan-mode";
6
7 -export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly loaded: boolean } {
7 +export function useLegacyPlanModeState(): { readonly enabled: boolean } {
8 const preferences = useAtomValue(mobilePreferencesAtom);
9 const loaded = AsyncResult.isSuccess(preferences);
10 return {
@@ -12,6 +12,5 @@ export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly
12 loaded,
13 preference: loaded ? preferences.value.planModeEnabled : undefined,
14 }),
15 - loaded,
15 };
16 }
apps/mobile/src/state/legacy-plan-mode.ts
+2 -10
@@ -23,20 +23,12 @@ export function resolveLegacyPlanModeEnabled(input: {
23 }
24
25 export function resolvePendingTaskInteractionMode(input: {
26 - readonly preferenceLoaded: boolean;
26 readonly planModeEnabled: boolean;
27 readonly draftInteractionMode: ProviderInteractionMode | undefined;
29 - readonly queuedInteractionMode: ProviderInteractionMode | undefined;
28 readonly provider?: InteractionModeProvider | null;
29 }): ProviderInteractionMode {
32 - if (input.provider?.showInteractionModeToggle === false) {
30 + if (input.provider?.showInteractionModeToggle === false || !input.planModeEnabled) {
31 return DEFAULT_PROVIDER_INTERACTION_MODE;
32 }
35 - if (input.planModeEnabled) {
36 - return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
37 - }
38 - if (!input.preferenceLoaded) {
39 - return input.queuedInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
40 - }
41 - return DEFAULT_PROVIDER_INTERACTION_MODE;
33 + return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
34 }
apps/mobile/src/state/pending-task-editor-writes.test.ts deleted
-272
@@ -1,272 +0,0 @@
1 -import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
2 -import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 -
4 -import type { QueuedThreadMessage } from "./thread-outbox-model";
5 -
6 -const harness = vi.hoisted(() => ({
7 - manager: null as unknown as ReturnType<
8 - typeof import("./thread-outbox-manager").createThreadOutboxManager
9 - >,
10 - writeGates: [] as Array<{
11 - readonly promise: Promise<void>;
12 - readonly started: (message: QueuedThreadMessage) => void;
13 - }>,
14 -}));
15 -
16 -vi.mock("./thread-outbox", async () => {
17 - const { createThreadOutboxManager } = await import("./thread-outbox-manager");
18 - const { appAtomRegistry } = await import("./atom-registry");
19 - harness.manager = createThreadOutboxManager({
20 - registry: appAtomRegistry,
21 - storage: {
22 - load: async () => ({ messages: [], errors: [] }),
23 - write: async (message) => {
24 - const pending = harness.writeGates.shift();
25 - if (pending) {
26 - pending.started(message);
27 - await pending.promise;
28 - }
29 - },
30 - remove: async () => undefined,
31 - },
32 - });
33 - const manager = harness.manager;
34 - return {
35 - threadOutboxManager: manager,
36 - flushThreadOutbox: async () => undefined,
37 - threadOutboxRevision: (messageId: QueuedThreadMessage["messageId"]) =>
38 - manager.revisionOf(messageId),
39 - updateThreadOutboxMessage: (message: QueuedThreadMessage, expectedRevision?: number) =>
40 - manager.update(message, expectedRevision),
41 - };
42 -});
43 -
44 -import { appAtomRegistry } from "./atom-registry";
45 -import {
46 - capturePendingTaskEditorWriteBaseline,
47 - flushPendingTaskEditorWrite,
48 -} from "./pending-task-editor-writes";
49 -import {
50 - composerDraftsAtom,
51 - getComposerDraftSnapshot,
52 - type ComposerDraft,
53 -} from "./use-composer-drafts";
54 -
55 -function queuedMessage(messageId: string, text: string): QueuedThreadMessage {
56 - return {
57 - environmentId: EnvironmentId.make("environment-1"),
58 - threadId: ThreadId.make("thread-1"),
59 - messageId: MessageId.make(messageId),
60 - commandId: CommandId.make(`command-${messageId}`),
61 - text,
62 - attachments: [],
63 - createdAt: "2026-08-28T12:00:00.000Z",
64 - };
65 -}
66 -
67 -function draft(text: string): ComposerDraft {
68 - return {
69 - text,
70 - attachments: [],
71 - runtimeMode: "full-access",
72 - };
73 -}
74 -
75 -function setDraft(draftKey: string, value: ComposerDraft): void {
76 - appAtomRegistry.set(composerDraftsAtom, { [draftKey]: value });
77 -}
78 -
79 -function queuedMessageText(messageId: QueuedThreadMessage["messageId"]): string | null {
80 - const messages = Object.values(
81 - appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom),
82 - ).flat();
83 - return messages.find((message) => message.messageId === messageId)?.text ?? null;
84 -}
85 -
86 -function blockNextWrite() {
87 - let resolveWrite!: () => void;
88 - let rejectWrite!: (error: Error) => void;
89 - let markStarted!: (message: QueuedThreadMessage) => void;
90 - const promise = new Promise<void>((resolve, reject) => {
91 - resolveWrite = resolve;
92 - rejectWrite = reject;
93 - });
94 - const started = new Promise<QueuedThreadMessage>((resolve) => {
95 - markStarted = resolve;
96 - });
97 - harness.writeGates.push({ promise, started: markStarted });
98 - return {
99 - started,
100 - resolve: resolveWrite,
101 - reject: rejectWrite,
102 - };
103 -}
104 -
105 -beforeEach(() => {
106 - harness.writeGates.length = 0;
107 - appAtomRegistry.set(harness.manager.queuedMessagesByThreadKeyAtom, {});
108 - appAtomRegistry.set(composerDraftsAtom, {});
109 -});
110 -
111 -describe("pending task editor writes", () => {
112 - it("chains a reopened editor that closes before the previous save finishes", async () => {
113 - const original = queuedMessage("message-close-before-save", "original");
114 - const firstEdit = queuedMessage("message-close-before-save", "first edit");
115 - const secondEdit = queuedMessage("message-close-before-save", "second edit");
116 - const draftKey = "pending-task:message-close-before-save";
117 - await harness.manager.enqueue(original);
118 -
119 - setDraft(draftKey, draft(firstEdit.text));
120 - const firstBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
121 - const firstWriteGate = blockNextWrite();
122 - const firstSave = flushPendingTaskEditorWrite({
123 - message: firstEdit,
124 - baseline: firstBaseline,
125 - draftKey,
126 - });
127 - await firstWriteGate.started;
128 -
129 - const secondBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
130 - setDraft(draftKey, draft(secondEdit.text));
131 - const secondWriteGate = blockNextWrite();
132 - const secondSave = flushPendingTaskEditorWrite({
133 - message: secondEdit,
134 - baseline: secondBaseline,
135 - draftKey,
136 - });
137 -
138 - firstWriteGate.resolve();
139 - await expect(firstSave).resolves.toBe(false);
140 - await expect(secondWriteGate.started).resolves.toMatchObject({ text: secondEdit.text });
141 - secondWriteGate.resolve();
142 -
143 - await expect(secondSave).resolves.toBe(true);
144 - expect(queuedMessageText(original.messageId)).toBe(secondEdit.text);
145 - });
146 -
147 - it("keeps a captured predecessor after that predecessor finishes", async () => {
148 - const original = queuedMessage("message-finished-predecessor", "original");
149 - const firstEdit = queuedMessage("message-finished-predecessor", "first edit");
150 - const secondEdit = queuedMessage("message-finished-predecessor", "second edit");
151 - const draftKey = "pending-task:message-finished-predecessor";
152 - await harness.manager.enqueue(original);
153 -
154 - setDraft(draftKey, draft(firstEdit.text));
155 - const firstWriteGate = blockNextWrite();
156 - const firstSave = flushPendingTaskEditorWrite({
157 - message: firstEdit,
158 - baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
159 - draftKey,
160 - });
161 - await firstWriteGate.started;
162 - const secondBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
163 -
164 - firstWriteGate.resolve();
165 - await expect(firstSave).resolves.toBe(true);
166 -
167 - setDraft(draftKey, draft(secondEdit.text));
168 - const secondWriteGate = blockNextWrite();
169 - const secondSave = flushPendingTaskEditorWrite({
170 - message: secondEdit,
171 - baseline: secondBaseline,
172 - draftKey,
173 - });
174 - await secondWriteGate.started;
175 - secondWriteGate.resolve();
176 -
177 - await expect(secondSave).resolves.toBe(true);
178 - expect(queuedMessageText(original.messageId)).toBe(secondEdit.text);
179 - });
180 -
181 - it("keeps the handed-off revision when the middle editor write fails", async () => {
182 - const original = queuedMessage("message-middle-failure", "original");
183 - const firstEdit = queuedMessage("message-middle-failure", "first edit");
184 - const failedEdit = queuedMessage("message-middle-failure", "failed edit");
185 - const finalEdit = queuedMessage("message-middle-failure", "final edit");
186 - const draftKey = "pending-task:message-middle-failure";
187 - await harness.manager.enqueue(original);
188 -
189 - setDraft(draftKey, draft(firstEdit.text));
190 - const firstWriteGate = blockNextWrite();
191 - const firstSave = flushPendingTaskEditorWrite({
192 - message: firstEdit,
193 - baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
194 - draftKey,
195 - });
196 - await firstWriteGate.started;
197 -
198 - const failedBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
199 - setDraft(draftKey, draft(failedEdit.text));
200 - const failedWriteGate = blockNextWrite();
201 - const failedSave = flushPendingTaskEditorWrite({
202 - message: failedEdit,
203 - baseline: failedBaseline,
204 - draftKey,
205 - });
206 -
207 - const finalBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
208 - setDraft(draftKey, draft(finalEdit.text));
209 - const finalWriteGate = blockNextWrite();
210 - const finalSave = flushPendingTaskEditorWrite({
211 - message: finalEdit,
212 - baseline: finalBaseline,
213 - draftKey,
214 - });
215 -
216 - firstWriteGate.resolve();
217 - await expect(firstSave).resolves.toBe(false);
218 - await failedWriteGate.started;
219 - failedWriteGate.reject(new Error("disk full"));
220 - await expect(failedSave).rejects.toMatchObject({ _tag: "ThreadOutboxManagerError" });
221 - await finalWriteGate.started;
222 - finalWriteGate.resolve();
223 -
224 - await expect(finalSave).resolves.toBe(true);
225 - expect(queuedMessageText(original.messageId)).toBe(finalEdit.text);
226 - });
227 -
228 - it("does not overwrite an unrelated update accepted after capture", async () => {
229 - const original = queuedMessage("message-unrelated-update", "original");
230 - const editorEdit = queuedMessage("message-unrelated-update", "editor edit");
231 - const unrelatedEdit = queuedMessage("message-unrelated-update", "unrelated edit");
232 - const draftKey = "pending-task:message-unrelated-update";
233 - await harness.manager.enqueue(original);
234 -
235 - const editorBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
236 - const revision = harness.manager.revisionOf(original.messageId);
237 - await expect(harness.manager.update(unrelatedEdit, revision)).resolves.toBe(true);
238 - setDraft(draftKey, draft(editorEdit.text));
239 -
240 - await expect(
241 - flushPendingTaskEditorWrite({
242 - message: editorEdit,
243 - baseline: editorBaseline,
244 - draftKey,
245 - }),
246 - ).resolves.toBe(false);
247 - expect(queuedMessageText(original.messageId)).toBe(unrelatedEdit.text);
248 - });
249 -
250 - it("does not permit cleanup after a newer editor makes the draft unsendable", async () => {
251 - const original = queuedMessage("message-unsendable-draft", "original");
252 - const editorEdit = queuedMessage("message-unsendable-draft", "saved edit");
253 - const draftKey = "pending-task:message-unsendable-draft";
254 - await harness.manager.enqueue(original);
255 -
256 - setDraft(draftKey, draft(editorEdit.text));
257 - const writeGate = blockNextWrite();
258 - const save = flushPendingTaskEditorWrite({
259 - message: editorEdit,
260 - baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
261 - draftKey,
262 - });
263 - await writeGate.started;
264 -
265 - setDraft(draftKey, draft(""));
266 - writeGate.resolve();
267 -
268 - await expect(save).resolves.toBe(false);
269 - expect(getComposerDraftSnapshot(draftKey).text).toBe("");
270 - expect(queuedMessageText(original.messageId)).toBe(editorEdit.text);
271 - });
272 -});
apps/mobile/src/state/pending-task-editor-writes.ts deleted
-81
@@ -1,81 +0,0 @@
1 -import type { QueuedThreadMessage } from "./thread-outbox";
2 -import { threadOutboxRevision, updateThreadOutboxMessage } from "./thread-outbox";
3 -import { getComposerDraftSnapshot, sameComposerDraftState } from "./use-composer-drafts";
4 -
5 -type PendingTaskEditorWriteResult =
6 - | {
7 - readonly status: "complete";
8 - readonly updated: boolean;
9 - readonly nextRevision: number;
10 - }
11 - | {
12 - readonly status: "failed";
13 - readonly error: unknown;
14 - readonly nextRevision: number;
15 - };
16 -
17 -const pendingWrites = new Map<
18 - QueuedThreadMessage["messageId"],
19 - Promise<PendingTaskEditorWriteResult>
20 ->();
21 -
22 -/** Captures the editor revision and predecessor save; the promise survives clearing its map entry. */
23 -export function capturePendingTaskEditorWriteBaseline(
24 - messageId: QueuedThreadMessage["messageId"],
25 -): Promise<number> {
26 - const capturedRevision = threadOutboxRevision(messageId);
27 - const predecessor = pendingWrites.get(messageId);
28 - if (!predecessor) {
29 - return Promise.resolve(capturedRevision);
30 - }
31 - return predecessor.then(
32 - ({ nextRevision }) => Math.max(capturedRevision, nextRevision),
33 - () => capturedRevision,
34 - );
35 -}
36 -
37 -export function flushPendingTaskEditorWrite(input: {
38 - readonly message: QueuedThreadMessage;
39 - readonly baseline: Promise<number>;
40 - readonly draftKey: string;
41 -}): Promise<boolean> {
42 - const { message } = input;
43 - const draftSnapshot = getComposerDraftSnapshot(input.draftKey);
44 - const write = input.baseline.then(
45 - async (expectedRevision): Promise<PendingTaskEditorWriteResult> => {
46 - try {
47 - const updated = await updateThreadOutboxMessage(message, expectedRevision);
48 - return {
49 - status: "complete",
50 - updated,
51 - nextRevision: expectedRevision + (updated ? 1 : 0),
52 - };
53 - } catch (error) {
54 - // Failed writes do not advance the outbox; hand their expected revision to later editor saves.
55 - return {
56 - status: "failed",
57 - error,
58 - nextRevision: expectedRevision,
59 - };
60 - }
61 - },
62 - );
63 -
64 - pendingWrites.set(message.messageId, write);
65 - const removeWrite = (): void => {
66 - if (pendingWrites.get(message.messageId) === write) {
67 - pendingWrites.delete(message.messageId);
68 - }
69 - };
70 - void write.then(removeWrite, removeWrite);
71 -
72 - return write.then((result) => {
73 - if (result.status === "failed") {
74 - throw result.error;
75 - }
76 - return (
77 - result.updated &&
78 - sameComposerDraftState(draftSnapshot, getComposerDraftSnapshot(input.draftKey))
79 - );
80 - });
81 -}