Skip to content
TypeScript

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

Julius Marminge0623d09aeed2
diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx
index fab1f307b04..1ea67736ab1 100644
--- a/apps/mobile/src/Stack.tsx
+++ b/apps/mobile/src/Stack.tsx
@@ -500,16 +500,11 @@ function RootStackLayout(props: {
);
const draftRoute = props.state.routes.findLast((route) => route.name === "Thread");
const draftParams = (
- draftRoute?.params as
- | { draft?: { draftId?: string | string[]; pendingTaskId?: string | string[] } }
- | undefined
+ draftRoute?.params as { draft?: { draftId?: string | string[] } } | undefined
)?.draft;
const routeDraftId = Array.isArray(draftParams?.draftId)
? draftParams.draftId[0]
: draftParams?.draftId;
- const routePendingTaskId = Array.isArray(draftParams?.pendingTaskId)
- ? draftParams.pendingTaskId[0]
- : draftParams?.pendingTaskId;
useAgentNotificationNavigation(workspaceLocation.pathname);
useConnectOnboardingNavigation();
useAppShortcuts(props.state);
@@ -531,11 +526,7 @@ function RootStackLayout(props: {
}, [navigation, pendingShare, props.state]);
return (
- <NewTaskFlowProvider
- active={isDraftThreadRoute(draftRoute)}
- routeDraftId={routeDraftId}
- routePendingTaskId={routePendingTaskId}
- >
+ <NewTaskFlowProvider active={isDraftThreadRoute(draftRoute)} routeDraftId={routeDraftId}>
<HardwareKeyboardCommandProvider pathname={pathname}>
<ShowcaseCaptureCoordinator pathname={pathname} />
<SettingsEnvironmentFilterProvider open={settingsOpen}>
diff --git a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
index 059f6ff2b12..73a43b7340d 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx
@@ -40,9 +40,6 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
// oxlint-disable-next-line react/set-state-in-effect -- Draft reset runs once before first paint; initialized gates the screen until then.
setInitialized(true);
}, [reset]);
- const pendingTaskId = Array.isArray(params.pendingTaskId)
- ? params.pendingTaskId[0]
- : params.pendingTaskId;
const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
const projects = useProjects();
const { state: catalogState } = useWorkspaceState();
@@ -75,7 +72,7 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
);
const environmentId = project?.environmentId;
const workspaceRoot = project?.workspaceRoot;
- const needsPreparation = Boolean(initialProjectRef.branch && !pendingTaskId && !draftId);
+ const needsPreparation = Boolean(initialProjectRef.branch && !draftId);
const [pendingCheckouts, setPendingCheckouts] = useState(0);
const checkoutTail = useRef(Promise.resolve());
@@ -200,7 +197,6 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraf
? params.incomingShareId[0]
: params.incomingShareId
}
- pendingTaskId={pendingTaskId}
draftId={draftId}
/>
)}
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
index 5efbf0a45cc..66a041c3f3f 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
@@ -150,7 +150,6 @@ export function NewTaskDraftScreen(props: {
readonly worktreePath?: string | null;
readonly cloning?: boolean;
};
- readonly pendingTaskId?: string;
readonly draftId?: string;
readonly incomingShareId?: string;
}) {
@@ -386,11 +385,11 @@ export function NewTaskDraftScreen(props: {
};
}, []);
- const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask, openDraft } = flow;
+ const { openDraft } = flow;
// Cold launches load drafts and projects separately; wait for hydration and retry while shells load.
const attemptedDraftIdRef = useRef<string | null>(null);
useEffect(() => {
- if (!props.draftId || props.pendingTaskId) {
+ if (!props.draftId) {
return;
}
const draftId = props.draftId;
@@ -415,34 +414,12 @@ export function NewTaskDraftScreen(props: {
return () => {
cancelled = true;
};
- }, [navigation, openDraft, projects, props.draftId, props.pendingTaskId]);
-
- const attemptedPendingTaskIdRef = useRef<string | null>(null);
- useEffect(() => {
- if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
- return;
- }
- if (attemptedPendingTaskIdRef.current === props.pendingTaskId) {
- return;
- }
- attemptedPendingTaskIdRef.current = props.pendingTaskId;
- if (!beginEditingPendingTask(props.pendingTaskId)) {
- navigation.dispatch(CommonActions.navigate("NewTaskProject"));
- }
- }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
-
- useEffect(() => {
- if (!props.pendingTaskId) return;
- return () => {
- attemptedPendingTaskIdRef.current = null;
- cancelEditingPendingTask();
- };
- }, [props.pendingTaskId, cancelEditingPendingTask]);
+ }, [navigation, openDraft, projects, props.draftId]);
const lastInitialProjectRefRef = useRef(props.initialProjectRef);
useEffect(() => {
- if (props.pendingTaskId || props.draftId) {
+ if (props.draftId) {
return;
}
if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
@@ -516,9 +493,8 @@ export function NewTaskDraftScreen(props: {
projects,
flow.draftKey,
props.initialProjectRef,
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening a draft from a share, pending task, or draft id re-resolves its project.
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening a draft from a share or draft id re-resolves its project.
props.incomingShareId,
- props.pendingTaskId,
props.draftId,
navigation,
selectedProject,
@@ -901,17 +877,7 @@ export function NewTaskDraftScreen(props: {
return null;
}
- const editingPendingTask = flow.editingPendingTask;
-
- const metadata = editingPendingTask
- ? {
- threadId: editingPendingTask.threadId,
- commandId: editingPendingTask.commandId,
- messageId: editingPendingTask.messageId,
- createdAt: editingPendingTask.createdAt,
- }
- : creationMetadata;
- const message = flow.buildPendingTaskMessage(metadata, {
+ const message = flow.buildPendingTaskMessage(creationMetadata, {
currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
});
if (!message) {
@@ -939,17 +905,13 @@ export function NewTaskDraftScreen(props: {
// would otherwise resurrect this draft.
abortComposerDraftOperations(draftKey);
const draftSnapshot = getComposerDraftSnapshot(draftKey);
- if (editingPendingTask) {
- flow.finishEditingPendingTask();
- } else {
- // The queued message owns the attachments now, so the sweep is deferred
- // until the write confirms it.
- clearComposerDraftContent(draftKey, {
- clearModelSelection: true,
- clearWorkspaceSelection: true,
- deferAttachmentCleanup: true,
- });
- }
+ // The queued message owns the attachments now, so the sweep is deferred
+ // until the write confirms it.
+ clearComposerDraftContent(draftKey, {
+ clearModelSelection: true,
+ clearWorkspaceSelection: true,
+ deferAttachmentCleanup: true,
+ });
scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
return message.messageId;
}
@@ -1146,7 +1108,7 @@ export function NewTaskDraftScreen(props: {
const thread = draftThreadShell({
environmentId: selectedProject.environmentId,
projectId: selectedProject.id,
- threadId: ThreadId.make(flow.editingPendingTask?.threadId ?? creationMetadata.threadId),
+ threadId: ThreadId.make(creationMetadata.threadId),
modelSelection: flow.selectedModel,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
index 43017bfc747..a7417328e65 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -17,7 +17,6 @@ import type {
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
- DEFAULT_RUNTIME_MODE,
DEFAULT_SERVER_SETTINGS,
MessageId,
repositoryGroupingKeyOf,
@@ -54,43 +53,26 @@ import { useAtomCommand } from "../../state/use-atom-command";
import {
appendComposerDraftAttachments,
type ComposerDraftInsertion,
- clearComposerDraft,
composerDraftsAtom,
createNewTaskDraft,
getComposerDraftSnapshot,
- isComposerDraftEmpty,
isNewTaskDraftKey,
removeComposerDraftAttachment,
replaceComposerDraftAttachments,
retargetNewTaskDraft,
- scheduleUnusedComposerAttachmentCleanup,
setComposerDraftText,
- setComposerDraftContext,
setStickyComposerModelSelection,
updateComposerDraftSettings,
useComposerDraft,
useStickyComposerModelSelection,
} from "../../state/use-composer-drafts";
-import {
- capturePendingTaskEditorWriteBaseline,
- flushPendingTaskEditorWrite,
-} from "../../state/pending-task-editor-writes";
import {
rememberModelOptions,
withRememberedModelOptions,
} from "../../state/use-model-option-memory";
import { useBranches, usePaginatedBranches } from "../../state/queries";
import { vcsEnvironment } from "../../state/vcs";
-import {
- flattenQueuedThreadMessages,
- threadOutboxManager,
- type QueuedThreadMessage,
-} from "../../state/thread-outbox";
-import {
- holdEditingQueuedMessage,
- releaseEditingQueuedMessage,
- useThreadOutboxMessages,
-} from "../../state/use-thread-outbox";
+import { type QueuedThreadMessage } from "../../state/thread-outbox";
import {
setPendingConnectionError,
useRemoteConnectionStatus,
@@ -126,20 +108,6 @@ import { useOlderSettledCount } from "../../state/olderSettledShelf";
type WorkspaceMode = "local" | "worktree";
-function pendingTaskDraftKey(messageId: string): string {
- return `pending-task:${messageId}`;
-}
-
-// Track ownership across providers so old unmount flushes cannot drop newer drafts or drain locks.
-let activeEditingMessageId: string | null = null;
-
-function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null {
- const message = flattenQueuedThreadMessages(
- appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
- ).find((candidate) => candidate.messageId === messageId);
- return message?.creation !== undefined ? message : null;
-}
-
export function branchBadgeLabel(input: {
readonly branch: VcsRef;
readonly project: EnvironmentProject | null;
@@ -174,7 +142,6 @@ type NewTaskFlowContextValue = {
readonly startFromOrigin: boolean;
readonly pullRequestReference: string | undefined;
readonly draftKey: string | null;
- readonly editingPendingTask: QueuedThreadMessage | null;
readonly prompt: string;
readonly attachments: ReadonlyArray<DraftComposerAttachment>;
readonly submitting: boolean;
@@ -210,9 +177,6 @@ type NewTaskFlowContextValue = {
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
readonly selectBranch: (branch: VcsRef) => void;
readonly setStartFromOrigin: (value: boolean) => void;
- readonly beginEditingPendingTask: (messageId: string) => boolean;
- readonly finishEditingPendingTask: () => void;
- readonly cancelEditingPendingTask: () => void;
readonly buildPendingTaskMessage: (
metadata: TurnCommandMetadata,
options?: {
@@ -244,15 +208,13 @@ export function NewTaskFlowProvider(
props: React.PropsWithChildren<{
active?: boolean;
routeDraftId?: string;
- routePendingTaskId?: string;
}>,
) {
const projects = useProjects();
const threads = useThreadShells();
const { savedConnectionsById } = useSavedRemoteConnections();
const groupingSettings = useMobileProjectGroupingSettings();
- const { enabled: legacyPlanModeEnabled, loaded: planModePreferenceLoaded } =
- useLegacyPlanModeState();
+ const { enabled: legacyPlanModeEnabled } = useLegacyPlanModeState();
const projectScopes = sortHomeProjectScopes({
scopes: buildHomeProjectScopes({
@@ -277,11 +239,7 @@ export function NewTaskFlowProvider(
const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
- const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
- // Mirror edit state synchronously so unmount flush cannot save a session ended this render.
- const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
- const editingRevisionRef = useRef(Promise.resolve(0));
const reset = useCallback(() => {
setSelectedEnvironmentId(null);
@@ -290,15 +248,6 @@ export function NewTaskFlowProvider(
setSubmitting(false);
setExpandedProvider(null);
pendingLocalBranchSyncDraftKeysRef.current.clear();
- const editing = editingPendingTaskRef.current;
- editingPendingTaskRef.current = null;
- setEditingPendingTask(null);
- if (editing) {
- if (activeEditingMessageId === editing.messageId) {
- activeEditingMessageId = null;
- }
- releaseEditingQueuedMessage(editing.messageId);
- }
}, []);
const projectsForEnvironment = pipe(
@@ -306,34 +255,12 @@ export function NewTaskFlowProvider(
Arr.filter((project) => project.environmentId === selectedEnvironmentId),
);
- const editingPendingProject = ((): EnvironmentProject | null => {
- const creation = editingPendingTask?.creation;
- if (!editingPendingTask || !creation) {
- return null;
- }
- return {
- environmentId: editingPendingTask.environmentId,
- id: creation.projectId,
- title: creation.projectTitle ?? "Unknown project",
- workspaceRoot: creation.projectCwd ?? "",
- repositoryIdentity: null,
- defaultModelSelection: editingPendingTask.modelSelection ?? null,
- scripts: [],
- createdAt: editingPendingTask.createdAt,
- updatedAt: editingPendingTask.createdAt,
- };
- })();
-
const selectedProject =
projectsForEnvironment.find(
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
) ??
- // Pin queued edits to their original project when its shell is missing; fallback would silently retarget them.
- (editingPendingProject !== null &&
- selectedProjectKey ===
- scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id)
- ? editingPendingProject
- : (projectsForEnvironment[0] ?? null));
+ projectsForEnvironment[0] ??
+ null;
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
@@ -404,18 +331,9 @@ export function NewTaskFlowProvider(
return result;
})();
- const selectedProjectDraftKey = editingPendingTask
- ? pendingTaskDraftKey(editingPendingTask.messageId)
- : selectedProject
- ? activeDraftKey
- : null;
+ const selectedProjectDraftKey = selectedProject ? activeDraftKey : null;
useEffect(() => {
- if (
- props.active === false ||
- activeDraftKey !== null ||
- editingPendingTask !== null ||
- selectedProject === null
- ) {
+ if (props.active === false || activeDraftKey !== null || selectedProject === null) {
return;
}
// 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(
projectId: selectedProject.id,
}),
);
- }, [activeDraftKey, editingPendingTask, selectedProject, props.active]);
+ }, [activeDraftKey, selectedProject, props.active]);
const activePendingKey =
props.active === false
? null
- : props.routePendingTaskId
- ? `pending-task:${props.routePendingTaskId}`
- : props.routeDraftId
- ? `draft-task:${props.routeDraftId}`
- : editingPendingTask
- ? `pending-task:${editingPendingTask.messageId}`
- : selectedProjectDraftKey
- ? `draft-task:${selectedProjectDraftKey}`
- : null;
+ : props.routeDraftId
+ ? `draft-task:${props.routeDraftId}`
+ : selectedProjectDraftKey
+ ? `draft-task:${selectedProjectDraftKey}`
+ : null;
const activeNewTask = React.useMemo(
() => (props.active === false ? null : { pendingKey: activePendingKey }),
[props.active, activePendingKey],
@@ -537,9 +451,7 @@ export function NewTaskFlowProvider(
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
const startFromOrigin =
isGitRepo && (draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin);
- const defaultRuntimeMode = editingPendingTask
- ? (editingPendingTask.runtimeMode ?? DEFAULT_RUNTIME_MODE)
- : projectSettings.settings.defaultRuntimeMode;
+ const defaultRuntimeMode = projectSettings.settings.defaultRuntimeMode;
const runtimeMode = selectedProjectDraft.runtimeMode ?? defaultRuntimeMode;
// Antigravity keeps unavailable selections so sign-out or a catalog change
@@ -687,7 +599,7 @@ export function NewTaskFlowProvider(
const target = { environmentId: project.environmentId, projectId: project.id };
if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
retargetNewTaskDraft(activeDraftKey, target);
- } else if (!editingPendingTaskRef.current) {
+ } else {
setActiveDraftKey(createNewTaskDraft(target));
}
};
@@ -914,39 +826,6 @@ export function NewTaskFlowProvider(
}
};
- const beginEditingPendingTask = (messageId: string): boolean => {
- const message = findQueuedPendingTask(messageId);
- if (!message?.creation) {
- return false;
- }
- const draftKey = pendingTaskDraftKey(message.messageId);
- if (isComposerDraftEmpty(getComposerDraftSnapshot(draftKey))) {
- setComposerDraftText(draftKey, message.text);
- setComposerDraftContext(draftKey, message.context);
- replaceComposerDraftAttachments(draftKey, message.attachments);
- updateComposerDraftSettings(draftKey, {
- modelSelection: message.modelSelection,
- runtimeMode: message.runtimeMode,
- interactionMode: message.interactionMode,
- workspaceSelection: {
- mode: message.creation.workspaceMode,
- branch: message.creation.branch,
- worktreePath: message.creation.worktreePath,
- startFromOrigin: message.creation.startFromOrigin ?? false,
- pullRequestReference: message.creation.pullRequestReference,
- },
- });
- }
- setSelectedEnvironmentId(message.environmentId);
- setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId));
- activeEditingMessageId = message.messageId;
- editingPendingTaskRef.current = message;
- editingRevisionRef.current = capturePendingTaskEditorWriteBaseline(message.messageId);
- setEditingPendingTask(message);
- holdEditingQueuedMessage(message.messageId);
- return true;
- };
-
const buildPendingTaskMessage = (
metadata: TurnCommandMetadata,
options?: { readonly currentCheckoutBranch?: string | null },
@@ -980,17 +859,6 @@ export function NewTaskFlowProvider(
isGitRepo,
});
const mode = workspaceSelection.mode;
- // When the selection is the stand-in built from the queued snapshot,
- // persist the original (possibly absent) snapshot values — the
- // stand-in's placeholder title/workspaceRoot must never be written back
- // as if they were real project metadata.
- const usingPendingSnapshot = selectedProject === editingPendingProject;
- const projectTitle = usingPendingSnapshot
- ? editingPendingTask?.creation?.projectTitle
- : selectedProject.title;
- const projectCwd = usingPendingSnapshot
- ? editingPendingTask?.creation?.projectCwd
- : selectedProject.workspaceRoot;
return {
environmentId: selectedProject.environmentId,
threadId: ThreadId.make(metadata.threadId),
@@ -1002,18 +870,16 @@ export function NewTaskFlowProvider(
modelSelection: draftModelSelection,
runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
interactionMode: resolvePendingTaskInteractionMode({
- preferenceLoaded: planModePreferenceLoaded,
planModeEnabled: legacyPlanModeEnabled,
draftInteractionMode: draft.interactionMode,
- queuedInteractionMode: editingPendingTask?.interactionMode,
provider: selectedEnvironmentServerConfig?.providers.find(
(candidate) => candidate.instanceId === draftModelSelection.instanceId,
),
}),
creation: {
projectId: selectedProject.id,
- ...(projectTitle !== undefined ? { projectTitle } : {}),
- ...(projectCwd !== undefined ? { projectCwd } : {}),
+ projectTitle: selectedProject.title,
+ projectCwd: selectedProject.workspaceRoot,
workspaceMode: mode,
...(mode === "worktree" && workspaceSelection?.pullRequestReference
? { pullRequestReference: workspaceSelection.pullRequestReference }
@@ -1033,93 +899,6 @@ export function NewTaskFlowProvider(
};
};
- const finishEditingPendingTask = () => {
- const editing = editingPendingTaskRef.current;
- editingPendingTaskRef.current = null;
- if (editing) {
- if (activeEditingMessageId === editing.messageId) {
- activeEditingMessageId = null;
- }
- clearComposerDraft(pendingTaskDraftKey(editing.messageId));
- releaseEditingQueuedMessage(editing.messageId);
- scheduleUnusedComposerAttachmentCleanup(editing.attachments);
- }
- setEditingPendingTask(null);
- };
-
- // End editing without saving if the queued task disappears; a later flush must not resurrect it.
- const queuedMessagesByThreadKey = useThreadOutboxMessages();
- useEffect(() => {
- const editing = editingPendingTaskRef.current;
- if (!editing) {
- return;
- }
- const stillQueued = flattenQueuedThreadMessages(queuedMessagesByThreadKey).some(
- (candidate) => candidate.messageId === editing.messageId,
- );
- if (!stillQueued) {
- finishEditingPendingTask();
- }
- }, [finishEditingPendingTask, queuedMessagesByThreadKey]);
-
- const editingFlushRef = useRef<(() => void) | null>(null);
- useEffect(() => {
- editingFlushRef.current = () => {
- const editing = editingPendingTaskRef.current;
- if (!editing) {
- return;
- }
- editingPendingTaskRef.current = null;
- setEditingPendingTask(null);
- if (activeEditingMessageId === editing.messageId) {
- activeEditingMessageId = null;
- }
-
- const message = buildPendingTaskMessage({
- threadId: editing.threadId,
- commandId: editing.commandId,
- messageId: editing.messageId,
- createdAt: editing.createdAt,
- });
-
- if (!message) {
- // Keep unsendable edits and the drain lock so removed content cannot auto-send from a stale payload.
- return;
- }
-
- // Hand off pending saves to reopened editors; CAS still rejects unrelated edits, deletes and deliveries.
- void flushPendingTaskEditorWrite({
- message,
- baseline: editingRevisionRef.current,
- draftKey: pendingTaskDraftKey(editing.messageId),
- })
- .then((savedDraftStillCurrent) => {
- if (activeEditingMessageId === editing.messageId) {
- return;
- }
- if (!savedDraftStillCurrent) {
- return;
- }
- clearComposerDraft(pendingTaskDraftKey(editing.messageId));
- releaseEditingQueuedMessage(editing.messageId);
- scheduleUnusedComposerAttachmentCleanup(editing.attachments);
- })
- .catch((error) => {
- // Keep the draft and drain lock on failure so stale payloads cannot discard edits; reopening retries.
- console.warn("[new-task] failed to save edited pending task", error);
- });
- };
- }, [buildPendingTaskMessage]);
- const cancelEditingPendingTask = () => {
- editingFlushRef.current?.();
- };
- useEffect(
- () => () => {
- editingFlushRef.current?.();
- },
- [],
- );
-
const value = {
activeNewTask,
projectScopes,
@@ -1135,7 +914,6 @@ export function NewTaskFlowProvider(
startFromOrigin,
draftKey: selectedProjectDraftKey,
pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
- editingPendingTask,
prompt,
attachments,
submitting,
@@ -1164,9 +942,6 @@ export function NewTaskFlowProvider(
setWorkspaceMode,
selectBranch,
setStartFromOrigin,
- beginEditingPendingTask,
- finishEditingPendingTask,
- cancelEditingPendingTask,
buildPendingTaskMessage,
setPrompt,
replaceAttachments,
diff --git a/apps/mobile/src/features/threads/thread-route-state.ts b/apps/mobile/src/features/threads/thread-route-state.ts
index c9a6ab6a3dd..e237d9bf699 100644
--- a/apps/mobile/src/features/threads/thread-route-state.ts
+++ b/apps/mobile/src/features/threads/thread-route-state.ts
@@ -6,7 +6,6 @@ export type NewTaskDraftRouteParams = {
readonly worktreePath?: string | null;
readonly title?: string | string[];
readonly cloning?: string | string[];
- readonly pendingTaskId?: string | string[];
readonly draftId?: string | string[];
readonly incomingShareId?: string | string[];
};
@@ -32,7 +31,6 @@ export function draftRouteIdentity(draft: NewTaskDraftRouteParams): string {
const first = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value);
return JSON.stringify([
draft.requestId,
- first(draft.pendingTaskId),
first(draft.draftId),
first(draft.environmentId),
first(draft.projectId),
diff --git a/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts b/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts
index 5f41874588b..694a34e632e 100644
--- a/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts
+++ b/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts
@@ -4,7 +4,7 @@ import { AsyncResult } from "effect/reactivity";
import { mobilePreferencesAtom } from "../../state/preferences";
import { resolveLegacyPlanModeEnabled } from "../../state/legacy-plan-mode";
-export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly loaded: boolean } {
+export function useLegacyPlanModeState(): { readonly enabled: boolean } {
const preferences = useAtomValue(mobilePreferencesAtom);
const loaded = AsyncResult.isSuccess(preferences);
return {
@@ -12,6 +12,5 @@ export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly
loaded,
preference: loaded ? preferences.value.planModeEnabled : undefined,
}),
- loaded,
};
}
diff --git a/apps/mobile/src/state/legacy-plan-mode.ts b/apps/mobile/src/state/legacy-plan-mode.ts
index d768d4dac35..f4ab2f8c681 100644
--- a/apps/mobile/src/state/legacy-plan-mode.ts
+++ b/apps/mobile/src/state/legacy-plan-mode.ts
@@ -23,20 +23,12 @@ export function resolveLegacyPlanModeEnabled(input: {
}
export function resolvePendingTaskInteractionMode(input: {
- readonly preferenceLoaded: boolean;
readonly planModeEnabled: boolean;
readonly draftInteractionMode: ProviderInteractionMode | undefined;
- readonly queuedInteractionMode: ProviderInteractionMode | undefined;
readonly provider?: InteractionModeProvider | null;
}): ProviderInteractionMode {
- if (input.provider?.showInteractionModeToggle === false) {
+ if (input.provider?.showInteractionModeToggle === false || !input.planModeEnabled) {
return DEFAULT_PROVIDER_INTERACTION_MODE;
}
- if (input.planModeEnabled) {
- return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
- }
- if (!input.preferenceLoaded) {
- return input.queuedInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
- }
- return DEFAULT_PROVIDER_INTERACTION_MODE;
+ return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
}
diff --git a/apps/mobile/src/state/pending-task-editor-writes.test.ts b/apps/mobile/src/state/pending-task-editor-writes.test.ts
deleted file mode 100644
index 8cdfc006a81..00000000000
--- a/apps/mobile/src/state/pending-task-editor-writes.test.ts
+++ /dev/null
@@ -1,272 +0,0 @@
-import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
-
-import type { QueuedThreadMessage } from "./thread-outbox-model";
-
-const harness = vi.hoisted(() => ({
- manager: null as unknown as ReturnType<
- typeof import("./thread-outbox-manager").createThreadOutboxManager
- >,
- writeGates: [] as Array<{
- readonly promise: Promise<void>;
- readonly started: (message: QueuedThreadMessage) => void;
- }>,
-}));
-
-vi.mock("./thread-outbox", async () => {
- const { createThreadOutboxManager } = await import("./thread-outbox-manager");
- const { appAtomRegistry } = await import("./atom-registry");
- harness.manager = createThreadOutboxManager({
- registry: appAtomRegistry,
- storage: {
- load: async () => ({ messages: [], errors: [] }),
- write: async (message) => {
- const pending = harness.writeGates.shift();
- if (pending) {
- pending.started(message);
- await pending.promise;
- }
- },
- remove: async () => undefined,
- },
- });
- const manager = harness.manager;
- return {
- threadOutboxManager: manager,
- flushThreadOutbox: async () => undefined,
- threadOutboxRevision: (messageId: QueuedThreadMessage["messageId"]) =>
- manager.revisionOf(messageId),
- updateThreadOutboxMessage: (message: QueuedThreadMessage, expectedRevision?: number) =>
- manager.update(message, expectedRevision),
- };
-});
-
-import { appAtomRegistry } from "./atom-registry";
-import {
- capturePendingTaskEditorWriteBaseline,
- flushPendingTaskEditorWrite,
-} from "./pending-task-editor-writes";
-import {
- composerDraftsAtom,
- getComposerDraftSnapshot,
- type ComposerDraft,
-} from "./use-composer-drafts";
-
-function queuedMessage(messageId: string, text: string): QueuedThreadMessage {
- return {
- environmentId: EnvironmentId.make("environment-1"),
- threadId: ThreadId.make("thread-1"),
- messageId: MessageId.make(messageId),
- commandId: CommandId.make(`command-${messageId}`),
- text,
- attachments: [],
- createdAt: "2026-08-28T12:00:00.000Z",
- };
-}
-
-function draft(text: string): ComposerDraft {
- return {
- text,
- attachments: [],
- runtimeMode: "full-access",
- };
-}
-
-function setDraft(draftKey: string, value: ComposerDraft): void {
- appAtomRegistry.set(composerDraftsAtom, { [draftKey]: value });
-}
-
-function queuedMessageText(messageId: QueuedThreadMessage["messageId"]): string | null {
- const messages = Object.values(
- appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom),
- ).flat();
- return messages.find((message) => message.messageId === messageId)?.text ?? null;
-}
-
-function blockNextWrite() {
- let resolveWrite!: () => void;
- let rejectWrite!: (error: Error) => void;
- let markStarted!: (message: QueuedThreadMessage) => void;
- const promise = new Promise<void>((resolve, reject) => {
- resolveWrite = resolve;
- rejectWrite = reject;
- });
- const started = new Promise<QueuedThreadMessage>((resolve) => {
- markStarted = resolve;
- });
- harness.writeGates.push({ promise, started: markStarted });
- return {
- started,
- resolve: resolveWrite,
- reject: rejectWrite,
- };
-}
-
-beforeEach(() => {
- harness.writeGates.length = 0;
- appAtomRegistry.set(harness.manager.queuedMessagesByThreadKeyAtom, {});
- appAtomRegistry.set(composerDraftsAtom, {});
-});
-
-describe("pending task editor writes", () => {
- it("chains a reopened editor that closes before the previous save finishes", async () => {
- const original = queuedMessage("message-close-before-save", "original");
- const firstEdit = queuedMessage("message-close-before-save", "first edit");
- const secondEdit = queuedMessage("message-close-before-save", "second edit");
- const draftKey = "pending-task:message-close-before-save";
- await harness.manager.enqueue(original);
-
- setDraft(draftKey, draft(firstEdit.text));
- const firstBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
- const firstWriteGate = blockNextWrite();
- const firstSave = flushPendingTaskEditorWrite({
- message: firstEdit,
- baseline: firstBaseline,
- draftKey,
- });
- await firstWriteGate.started;
-
- const secondBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
- setDraft(draftKey, draft(secondEdit.text));
- const secondWriteGate = blockNextWrite();
- const secondSave = flushPendingTaskEditorWrite({
- message: secondEdit,
- baseline: secondBaseline,
- draftKey,
- });
-
- firstWriteGate.resolve();
- await expect(firstSave).resolves.toBe(false);
- await expect(secondWriteGate.started).resolves.toMatchObject({ text: secondEdit.text });
- secondWriteGate.resolve();
-
- await expect(secondSave).resolves.toBe(true);
- expect(queuedMessageText(original.messageId)).toBe(secondEdit.text);
- });
-
- it("keeps a captured predecessor after that predecessor finishes", async () => {
- const original = queuedMessage("message-finished-predecessor", "original");
- const firstEdit = queuedMessage("message-finished-predecessor", "first edit");
- const secondEdit = queuedMessage("message-finished-predecessor", "second edit");
- const draftKey = "pending-task:message-finished-predecessor";
- await harness.manager.enqueue(original);
-
- setDraft(draftKey, draft(firstEdit.text));
- const firstWriteGate = blockNextWrite();
- const firstSave = flushPendingTaskEditorWrite({
- message: firstEdit,
- baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
- draftKey,
- });
- await firstWriteGate.started;
- const secondBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
-
- firstWriteGate.resolve();
- await expect(firstSave).resolves.toBe(true);
-
- setDraft(draftKey, draft(secondEdit.text));
- const secondWriteGate = blockNextWrite();
- const secondSave = flushPendingTaskEditorWrite({
- message: secondEdit,
- baseline: secondBaseline,
- draftKey,
- });
- await secondWriteGate.started;
- secondWriteGate.resolve();
-
- await expect(secondSave).resolves.toBe(true);
- expect(queuedMessageText(original.messageId)).toBe(secondEdit.text);
- });
-
- it("keeps the handed-off revision when the middle editor write fails", async () => {
- const original = queuedMessage("message-middle-failure", "original");
- const firstEdit = queuedMessage("message-middle-failure", "first edit");
- const failedEdit = queuedMessage("message-middle-failure", "failed edit");
- const finalEdit = queuedMessage("message-middle-failure", "final edit");
- const draftKey = "pending-task:message-middle-failure";
- await harness.manager.enqueue(original);
-
- setDraft(draftKey, draft(firstEdit.text));
- const firstWriteGate = blockNextWrite();
- const firstSave = flushPendingTaskEditorWrite({
- message: firstEdit,
- baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
- draftKey,
- });
- await firstWriteGate.started;
-
- const failedBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
- setDraft(draftKey, draft(failedEdit.text));
- const failedWriteGate = blockNextWrite();
- const failedSave = flushPendingTaskEditorWrite({
- message: failedEdit,
- baseline: failedBaseline,
- draftKey,
- });
-
- const finalBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
- setDraft(draftKey, draft(finalEdit.text));
- const finalWriteGate = blockNextWrite();
- const finalSave = flushPendingTaskEditorWrite({
- message: finalEdit,
- baseline: finalBaseline,
- draftKey,
- });
-
- firstWriteGate.resolve();
- await expect(firstSave).resolves.toBe(false);
- await failedWriteGate.started;
- failedWriteGate.reject(new Error("disk full"));
- await expect(failedSave).rejects.toMatchObject({ _tag: "ThreadOutboxManagerError" });
- await finalWriteGate.started;
- finalWriteGate.resolve();
-
- await expect(finalSave).resolves.toBe(true);
- expect(queuedMessageText(original.messageId)).toBe(finalEdit.text);
- });
-
- it("does not overwrite an unrelated update accepted after capture", async () => {
- const original = queuedMessage("message-unrelated-update", "original");
- const editorEdit = queuedMessage("message-unrelated-update", "editor edit");
- const unrelatedEdit = queuedMessage("message-unrelated-update", "unrelated edit");
- const draftKey = "pending-task:message-unrelated-update";
- await harness.manager.enqueue(original);
-
- const editorBaseline = capturePendingTaskEditorWriteBaseline(original.messageId);
- const revision = harness.manager.revisionOf(original.messageId);
- await expect(harness.manager.update(unrelatedEdit, revision)).resolves.toBe(true);
- setDraft(draftKey, draft(editorEdit.text));
-
- await expect(
- flushPendingTaskEditorWrite({
- message: editorEdit,
- baseline: editorBaseline,
- draftKey,
- }),
- ).resolves.toBe(false);
- expect(queuedMessageText(original.messageId)).toBe(unrelatedEdit.text);
- });
-
- it("does not permit cleanup after a newer editor makes the draft unsendable", async () => {
- const original = queuedMessage("message-unsendable-draft", "original");
- const editorEdit = queuedMessage("message-unsendable-draft", "saved edit");
- const draftKey = "pending-task:message-unsendable-draft";
- await harness.manager.enqueue(original);
-
- setDraft(draftKey, draft(editorEdit.text));
- const writeGate = blockNextWrite();
- const save = flushPendingTaskEditorWrite({
- message: editorEdit,
- baseline: capturePendingTaskEditorWriteBaseline(original.messageId),
- draftKey,
- });
- await writeGate.started;
-
- setDraft(draftKey, draft(""));
- writeGate.resolve();
-
- await expect(save).resolves.toBe(false);
- expect(getComposerDraftSnapshot(draftKey).text).toBe("");
- expect(queuedMessageText(original.messageId)).toBe(editorEdit.text);
- });
-});
diff --git a/apps/mobile/src/state/pending-task-editor-writes.ts b/apps/mobile/src/state/pending-task-editor-writes.ts
deleted file mode 100644
index 7fe61c30e4c..00000000000
--- a/apps/mobile/src/state/pending-task-editor-writes.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import type { QueuedThreadMessage } from "./thread-outbox";
-import { threadOutboxRevision, updateThreadOutboxMessage } from "./thread-outbox";
-import { getComposerDraftSnapshot, sameComposerDraftState } from "./use-composer-drafts";
-
-type PendingTaskEditorWriteResult =
- | {
- readonly status: "complete";
- readonly updated: boolean;
- readonly nextRevision: number;
- }
- | {
- readonly status: "failed";
- readonly error: unknown;
- readonly nextRevision: number;
- };
-
-const pendingWrites = new Map<
- QueuedThreadMessage["messageId"],
- Promise<PendingTaskEditorWriteResult>
->();
-
-/** Captures the editor revision and predecessor save; the promise survives clearing its map entry. */
-export function capturePendingTaskEditorWriteBaseline(
- messageId: QueuedThreadMessage["messageId"],
-): Promise<number> {
- const capturedRevision = threadOutboxRevision(messageId);
- const predecessor = pendingWrites.get(messageId);
- if (!predecessor) {
- return Promise.resolve(capturedRevision);
- }
- return predecessor.then(
- ({ nextRevision }) => Math.max(capturedRevision, nextRevision),
- () => capturedRevision,
- );
-}
-
-export function flushPendingTaskEditorWrite(input: {
- readonly message: QueuedThreadMessage;
- readonly baseline: Promise<number>;
- readonly draftKey: string;
-}): Promise<boolean> {
- const { message } = input;
- const draftSnapshot = getComposerDraftSnapshot(input.draftKey);
- const write = input.baseline.then(
- async (expectedRevision): Promise<PendingTaskEditorWriteResult> => {
- try {
- const updated = await updateThreadOutboxMessage(message, expectedRevision);
- return {
- status: "complete",
- updated,
- nextRevision: expectedRevision + (updated ? 1 : 0),
- };
- } catch (error) {
- // Failed writes do not advance the outbox; hand their expected revision to later editor saves.
- return {
- status: "failed",
- error,
- nextRevision: expectedRevision,
- };
- }
- },
- );
-
- pendingWrites.set(message.messageId, write);
- const removeWrite = (): void => {
- if (pendingWrites.get(message.messageId) === write) {
- pendingWrites.delete(message.messageId);
- }
- };
- void write.then(removeWrite, removeWrite);
-
- return write.then((result) => {
- if (result.status === "failed") {
- throw result.error;
- }
- return (
- result.updated &&
- sameComposerDraftState(draftSnapshot, getComposerDraftSnapshot(input.draftKey))
- );
- });
-}