Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

new-task-flow-provider.tsx

1,407 lines51.9 KB

1import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
2import { Alert } from "react-native";
3​
4import type {
5 EnvironmentId,
6 ModelSelection,
7 ProjectReadFileResult,
8 ProviderInteractionMode,
9 ProviderOptionSelection,
10 RuntimeMode,
11 ServerProvider,
12} from "@t3tools/contracts";
13import {
14 CommandId,
15 DEFAULT_PROVIDER_INTERACTION_MODE,
16 DEFAULT_RUNTIME_MODE,
17 DEFAULT_SERVER_SETTINGS,
18 MessageId,
19 repositoryGroupingKeyOf,
20 T3_PROJECT_FILE_NAME,
21 ThreadId,
22} from "@t3tools/contracts";
23import { sanitizeNewRefName } from "@t3tools/shared/git";
24import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
25import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
26import * as Arr from "effect/Array";
27import { pipe } from "effect/Function";
28​
29import {
30 useEnvironmentServerConfig,
31 useProjects,
32 useServerConfigs,
33 useThreadShells,
34} from "../../state/entities";
35import type { TurnCommandMetadata } from "../../lib/commandMetadata";
36import type { DraftComposerAttachment } from "../../lib/composerImages";
37import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
38import {
39 buildModelOptions,
40 groupByProvider,
41 resolveDefaultableModelSelection,
42 resolveNewTaskModelSelection,
43 resolveSelectableModelSelection,
44} from "../../lib/modelOptions";
45import { scopedProjectKey } from "../../lib/scopedEntities";
46import { appAtomRegistry } from "../../state/atom-registry";
47import { projectEnvironment } from "../../state/projects";
48import { useEnvironmentQuery } from "../../state/query";
49import { useAtomCommand } from "../../state/use-atom-command";
50import {
51 appendComposerDraftAttachments,
52 type ComposerDraftInsertion,
53 clearComposerDraft,
54 composerDraftsAtom,
55 createNewTaskDraft,
56 getComposerDraftSnapshot,
57 isComposerDraftEmpty,
58 isNewTaskDraftKey,
59 removeComposerDraftAttachment,
60 replaceComposerDraftAttachments,
61 retargetNewTaskDraft,
62 scheduleUnusedComposerAttachmentCleanup,
63 setComposerDraftText,
64 setComposerDraftContext,
65 setStickyComposerModelSelection,
66 updateComposerDraftSettings,
67 useComposerDraft,
68 useStickyComposerModelSelection,
69} from "../../state/use-composer-drafts";
70import {
71 capturePendingTaskEditorWriteBaseline,
72 flushPendingTaskEditorWrite,
73} from "../../state/pending-task-editor-writes";
74import {
75 rememberModelOptions,
76 withRememberedModelOptions,
77} from "../../state/use-model-option-memory";
78import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
79import { vcsEnvironment } from "../../state/vcs";
80import {
81 flattenQueuedThreadMessages,
82 threadOutboxManager,
83 type QueuedThreadMessage,
84} from "../../state/thread-outbox";
85import {
86 holdEditingQueuedMessage,
87 releaseEditingQueuedMessage,
88 useThreadOutboxMessages,
89} from "../../state/use-thread-outbox";
90import {
91 setPendingConnectionError,
92 useRemoteConnectionStatus,
93 useSavedRemoteConnections,
94} from "../../state/use-remote-environment-registry";
95import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
96import {
97 isAtomCommandInterrupted,
98 squashAtomCommandFailure,
99} from "@t3tools/client-runtime/state/runtime";
100import { isScratchProject } from "@t3tools/client-runtime/state/projects";
101import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
102import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
103import {
104 buildHomeProjectScopes,
105 sortHomeProjectScopes,
106 type HomeProjectScope,
107} from "../home/homeThreadList";
108import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
109import {
110 resolvePendingTaskInteractionMode,
111 resolveProviderInteractionMode,
112} from "../../state/legacy-plan-mode";
113import { useLegacyPlanModeState } from "./use-legacy-plan-mode-enabled";
114import {
115 filterNewTaskBranches,
116 resolveNewTaskBranchWorktreePath,
117 resolveNewTaskLocalWorkspaceSelection,
118} from "./new-task-context-presentation";
119import { resolveEnvironmentProjectMatch } from "./new-task-project-selection";
120import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
121​
122type WorkspaceMode = "local" | "worktree";
123​
124const BRANCH_SEARCH_DEBOUNCE_MS = 150;
125​
126function pendingTaskDraftKey(messageId: string): string {
127 return `pending-task:${messageId}`;
129​
130// The message id owned by the currently active editing session, tracked
131// across provider instances. An in-flight flush from a dismissed session
132// consults it so it never drops the draft or releases the drain lock out from
133// under a newer session editing the same task.
134let activeEditingMessageId: string | null = null;
135​
136function 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;
142​
143export function branchBadgeLabel(input: {
144 readonly branch: VcsRef;
145 readonly project: EnvironmentProject | null;
146}): string | null {
147 if (input.branch.current) {
148 return "current";
149 }
150 if (input.branch.worktreePath && input.branch.worktreePath !== input.project?.workspaceRoot) {
151 return "worktree";
152 }
153 if (input.branch.isRemote) {
154 return "remote";
155 }
156 if (input.branch.isDefault) {
157 return "default";
158 }
159 return null;
161​
162type NewTaskFlowContextValue = {
163 readonly projectScopes: ReadonlyArray<HomeProjectScope>;
164 readonly selectedEnvironmentId: EnvironmentId | null;
165 readonly selectedProjectKey: string | null;
166 readonly selectedModelKey: string | null;
167 readonly workspaceMode: WorkspaceMode;
168 /** False for threads without a project: their folder has no branch or worktree. */
169 readonly canChooseWorkspace: boolean;
170 readonly selectedBranchName: string | null;
171 readonly selectedWorktreePath: string | null;
172 readonly startFromOrigin: boolean;
173 readonly draftKey: string | null;
174 readonly editingPendingTask: QueuedThreadMessage | null;
175 readonly prompt: string;
176 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
177 readonly submitting: boolean;
178 readonly branchQuery: string;
179 readonly branchesLoading: boolean;
180 readonly branchesError: string | null;
181 readonly branchesFetchingNextPage: boolean;
182 readonly hasMoreBranches: boolean;
183 readonly availableBranches: ReadonlyArray<VcsRef>;
184 readonly currentCheckoutBranchName: string | null;
185 readonly runtimeMode: RuntimeMode;
186 readonly interactionMode: ProviderInteractionMode;
187 readonly planModeEnabled: boolean;
188 readonly expandedProvider: string | null;
189 readonly environments: ReadonlyArray<{
190 readonly environmentId: EnvironmentId;
191 readonly environmentLabel: string;
192 }>;
193 readonly selectedProject: EnvironmentProject | null;
194 /** True when the draft is a thread without a project (its machine's Scratch project). */
195 readonly isScratchDraft: boolean;
196 readonly modelOptions: ReadonlyArray<ModelOption>;
197 readonly selectedModel: ModelSelection | null;
198 readonly selectedModelOption: ModelOption | null;
199 readonly selectedProviderStatus: ServerProvider | null;
200 readonly providerGroups: ReadonlyArray<ProviderGroup>;
201 readonly filteredBranches: ReadonlyArray<VcsRef>;
202 readonly reset: () => void;
203 readonly setProject: (project: EnvironmentProject) => void;
204 /**
205 * Binds the composer to an existing new-task draft (a row in the thread
206 * list). Returns false when the draft is gone, so the caller can fall back
207 * to a fresh one.
208 */
209 readonly openDraft: (draftKey: string) => boolean;
210 readonly selectEnvironment: (environmentId: EnvironmentId) => void;
211 /**
212 * Moves the draft to another machine. A draft without a project resolves to
213 * that machine's "No project" folder first, creating it when needed.
214 */
215 readonly switchEnvironment: (environmentId: EnvironmentId) => Promise<boolean>;
216 /** The machine a switch in progress is heading to. */
217 readonly switchingToEnvironmentId: EnvironmentId | null;
218 readonly setSelectedModelKey: (
219 key: string | null,
220 options?: ReadonlyArray<ProviderOptionSelection>,
221 ) => void;
222 readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
223 readonly selectBranch: (branch: VcsRef) => void;
224 readonly setStartFromOrigin: (value: boolean) => void;
225 readonly beginEditingPendingTask: (messageId: string) => boolean;
226 readonly finishEditingPendingTask: () => void;
227 readonly cancelEditingPendingTask: () => void;
228 readonly buildPendingTaskMessage: (
229 metadata: TurnCommandMetadata,
230 options?: {
231 /** The live checkout, recorded as a local task's branch when it sends now. */
232 readonly currentCheckoutBranch?: string | null;
233 },
234 ) => QueuedThreadMessage | null;
235 readonly setPrompt: (value: string) => void;
236 readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => void;
237 /** Appends draft attachments; returns how many the live cap rejected. */
238 readonly appendAttachments: (
239 attachments: ReadonlyArray<DraftComposerAttachment>,
240 insertion?: ComposerDraftInsertion,
241 ) => number;
242 readonly removeAttachment: (imageId: string) => void;
243 readonly clearAttachments: () => void;
244 readonly setSubmitting: (value: boolean) => void;
245 readonly setBranchQuery: (value: string) => void;
246 readonly loadBranches: () => void;
247 readonly loadMoreBranches: () => void;
248 readonly setRuntimeMode: (value: RuntimeMode) => void;
249 readonly setInteractionMode: (value: ProviderInteractionMode) => void;
250 readonly setSelectedModelOptions: (
251 value: ReadonlyArray<ProviderOptionSelection> | undefined,
252 ) => void;
253 readonly setExpandedProvider: (value: string | null) => void;
254};
255​
256const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null);
257​
258export function NewTaskFlowProvider(props: React.PropsWithChildren) {
259 const projects = useProjects();
260 const threads = useThreadShells();
261 const { savedConnectionsById } = useSavedRemoteConnections();
262 const groupingSettings = useMobileProjectGroupingSettings();
263 const { enabled: legacyPlanModeEnabled, loaded: planModePreferenceLoaded } =
264 useLegacyPlanModeState();
265​
266 const projectScopes = useMemo(
267 () =>
268 sortHomeProjectScopes({
269 scopes: buildHomeProjectScopes({
270 projects,
271 environmentId: null,
272 projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
273 }),
274 threads,
275 pendingTasks: [],
276 projectSortOrder: "updated_at",
277 }),
278 [groupingSettings.sidebarProjectGroupingMode, projects, threads],
279 );
280​
281 const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
282 null,
283 );
284 const selectedEnvironmentId =
285 selectedEnvironmentIdOverride !== null &&
286 projects.some((project) => project.environmentId === selectedEnvironmentIdOverride)
287 ? selectedEnvironmentIdOverride
288 : (projects[0]?.environmentId ?? null);
289 const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
290 // The new-task draft the composer is bound to. Null until a project is
291 // chosen; each New Task entry mints its own, so a project can hold several.
292 const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
293 const [submitting, setSubmitting] = useState(false);
294 const [branchQuery, setBranchQuery] = useState("");
295 const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
296 const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
297 const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
298 // Mirrors `editingPendingTask` synchronously so the unmount flush cannot act
299 // on a task whose editing session already ended this render.
300 const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
301 // Outbox revision this editor session may write after its predecessor save.
302 // Unrelated accepted writes still beat the dismissed session's CAS.
303 const editingRevisionRef = useRef(Promise.resolve(0));
304​
305 const reset = useCallback(() => {
306 setSelectedEnvironmentId(null);
307 setSelectedProjectKey(null);
308 setActiveDraftKey(null);
309 setSubmitting(false);
310 setBranchQuery("");
311 setExpandedProvider(null);
312 pendingLocalBranchSyncDraftKeysRef.current.clear();
313 const editing = editingPendingTaskRef.current;
314 editingPendingTaskRef.current = null;
315 setEditingPendingTask(null);
316 if (editing) {
317 if (activeEditingMessageId === editing.messageId) {
318 activeEditingMessageId = null;
319 }
320 releaseEditingQueuedMessage(editing.messageId);
321 }
322 }, []);
323​
324 const projectsForEnvironment = useMemo(
325 () =>
326 pipe(
327 projects,
328 Arr.filter((project) => project.environmentId === selectedEnvironmentId),
329 ),
330 [projects, selectedEnvironmentId],
331 );
332​
333 // Stand-in for the edited task's project while its shell is not loaded
334 // (environment offline / still synchronizing), built from the metadata
335 // snapshotted at enqueue time.
336 const editingPendingProject = useMemo<EnvironmentProject | null>(() => {
337 const creation = editingPendingTask?.creation;
338 if (!editingPendingTask || !creation) {
339 return null;
340 }
341 return {
342 environmentId: editingPendingTask.environmentId,
343 id: creation.projectId,
344 title: creation.projectTitle ?? "Unknown project",
345 // Deliberately empty when the snapshot has no cwd — downstream consumers
346 // (branch queries, worktree bootstrap) must skip it, not receive a
347 // fabricated path.
348 workspaceRoot: creation.projectCwd ?? "",
349 repositoryIdentity: null,
350 defaultModelSelection: editingPendingTask.modelSelection ?? null,
351 scripts: [],
352 createdAt: editingPendingTask.createdAt,
353 updatedAt: editingPendingTask.createdAt,
354 };
355 }, [editingPendingTask]);
356​
357 const selectedProject =
358 projectsForEnvironment.find(
359 (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
360 ) ??
361 // While editing a queued task whose project shell is absent, keep the task
362 // pinned to its own project — falling through to an arbitrary first
363 // project would silently retarget it (and its reused turn identifiers).
364 (editingPendingProject !== null &&
365 selectedProjectKey ===
366 scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id)
367 ? editingPendingProject
368 : (projectsForEnvironment[0] ?? null));
369​
370 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
371 selectedProject?.environmentId ?? null,
372 );
373 const isScratchDraft =
374 selectedProject !== null &&
375 isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot);
376 const serverConfigs = useServerConfigs();
377 const { connectedEnvironments } = useRemoteConnectionStatus();
378 // A thread without a project can move to any connected machine that offers
379 // one; its Scratch project there is created on the switch if it is missing.
380 const scratchEnvironments = useMemo(
381 () =>
382 connectedEnvironments.filter(
383 (environment) =>
384 availableScratchWorkspaceRoot(
385 environment.connectionState,
386 serverConfigs.get(environment.environmentId),
387 ) !== null,
388 ),
389 [connectedEnvironments, serverConfigs],
390 );
391​
392 // Only offer machines that actually host the currently selected repository, so
393 // switching computers moves the same repo across machines instead of jumping to
394 // whatever unrelated project happens to be first on the other machine. Repository
395 // identity is the primary signal; projects that haven't reported one yet (still
396 // indexing) fall back to workspace basename / title so a valid host isn't hidden.
397 const selectedRepositoryKey = selectedProject?.repositoryIdentity
398 ? repositoryGroupingKeyOf(selectedProject.repositoryIdentity)
399 : null;
400 // `|| null` (not `??`): a pending-task placeholder project can have an empty
401 // workspaceRoot, and an "" basename would reject every real host below.
402 const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
403 const selectedProjectTitle = selectedProject?.title ?? null;
404 const environments = useMemo(() => {
405 if (isScratchDraft) {
406 return scratchEnvironments.map((environment) => ({
407 environmentId: environment.environmentId,
408 environmentLabel: environment.environmentLabel,
409 }));
410 }
411 const seen = new Set<EnvironmentId>();
412 const result: Array<{
413 readonly environmentId: EnvironmentId;
414 readonly environmentLabel: string;
415 }> = [];
416 const hostsSelectedRepository = (project: EnvironmentProject) => {
417 if (selectedRepositoryKey === null && selectedWorkspaceBasename === null) {
418 return true;
419 }
420 const projectKey = project.repositoryIdentity
421 ? repositoryGroupingKeyOf(project.repositoryIdentity)
422 : null;
423 if (selectedRepositoryKey !== null && projectKey !== null) {
424 return projectKey === selectedRepositoryKey;
425 }
426 return (
427 project.workspaceRoot.split("/").at(-1) === selectedWorkspaceBasename ||
428 (selectedProjectTitle !== null && project.title === selectedProjectTitle)
429 );
430 };
431 for (const project of projects) {
432 if (!hostsSelectedRepository(project)) {
433 continue;
434 }
435 if (seen.has(project.environmentId)) {
436 continue;
437 }
438 const environment = savedConnectionsById[project.environmentId];
439 if (!environment) {
440 continue;
441 }
442 seen.add(project.environmentId);
443 result.push({
444 environmentId: project.environmentId,
445 environmentLabel: environment.environmentLabel,
446 });
447 }
448 return result;
449 }, [
450 isScratchDraft,
451 projects,
452 savedConnectionsById,
453 scratchEnvironments,
454 selectedRepositoryKey,
455 selectedWorkspaceBasename,
456 selectedProjectTitle,
457 ]);
458​
459 // While a queued pending task is being edited its draft lives under a key
460 // scoped to the queued message, so new-task drafts stay intact.
461 const selectedProjectDraftKey = editingPendingTask
462 ? pendingTaskDraftKey(editingPendingTask.messageId)
463 : selectedProject
464 ? activeDraftKey
465 : null;
466 // selectedProject can resolve without setProject ever running (the
467 // environment's first project is the fallback, and the draft screen skips
468 // setProject when the route's project already matches it). The composer
469 // still needs a draft to write into, so bind one the moment a project is
470 // in view and nothing else owns the key.
471 useEffect(() => {
472 if (activeDraftKey !== null || editingPendingTask !== null || selectedProject === null) {
473 return;
474 }
475 setActiveDraftKey(
476 createNewTaskDraft({
477 environmentId: selectedProject.environmentId,
478 projectId: selectedProject.id,
479 }),
480 );
481 }, [activeDraftKey, editingPendingTask, selectedProject]);
482 const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
483 const prompt = selectedProjectDraft.text;
484 const attachments = selectedProjectDraft.attachments;
485 // Default mode until the user picks one explicitly — same resolution web
486 // uses for new draft threads: per-project setting, then the repo's
487 // checked-in t3.json, then the server's configured default.
488 const t3ProjectFileQuery = useEnvironmentQuery(
489 selectedProject !== null && selectedProject.workspaceRoot !== ""
490 ? projectEnvironment.readFile({
491 environmentId: selectedProject.environmentId,
492 input: { cwd: selectedProject.workspaceRoot, relativePath: T3_PROJECT_FILE_NAME },
493 })
494 : null,
495 );
496 const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
497 const t3ProjectFile = useMemo(
498 () =>
499 t3ProjectFileData === null || t3ProjectFileData.truncated
500 ? null
501 : parseT3ProjectFile(t3ProjectFileData.contents),
502 [t3ProjectFileData],
503 );
504 // Environment settings with the project's overrides and its t3.json
505 // applied; the aggregate's own legacy fields still count until the server
506 // folds them.
507 const projectSettings = useMemo(
508 () =>
509 resolveProjectSettings(
510 selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
511 selectedProject?.id ?? null,
512 selectedProject,
513 t3ProjectFile,
514 ),
515 [selectedEnvironmentServerConfig?.settings, selectedProject, t3ProjectFile],
516 );
517 // A thread without a project runs in a plain folder, so worktree mode
518 // would leave it unsendable: it is always local and offers no choice.
519 const canChooseWorkspace = !isScratchDraft;
520 const defaultWorkspaceMode: WorkspaceMode = canChooseWorkspace
521 ? projectSettings.settings.defaultThreadEnvMode
522 : "local";
523 // While the file read is pending and nothing above it decided, the
524 // resolved default is provisional. Nothing may write it into the draft
525 // during that window (the auto-branch effect does), or the frozen interim
526 // value beats the t3.json default once it loads.
527 const defaultWorkspaceModeSettled =
528 selectedProjectDraft.workspaceSelection?.mode !== undefined ||
529 projectSettings.sources.defaultThreadEnvMode !== "environment" ||
530 !t3ProjectFileQuery.isPending;
531 const workspaceMode = canChooseWorkspace
532 ? (selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode)
533 : "local";
534 const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
535 const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
536 // Keep the user's explicit choice separate from the resolved display value:
537 // only the explicit flag is ever written back to the draft, so the resolved
538 // value keeps tracking the server setting when the config loads late.
539 const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
540 const startFromOrigin =
541 draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin;
542 const defaultRuntimeMode = editingPendingTask
543 ? (editingPendingTask.runtimeMode ?? DEFAULT_RUNTIME_MODE)
544 : projectSettings.settings.defaultRuntimeMode;
545 const runtimeMode = selectedProjectDraft.runtimeMode ?? defaultRuntimeMode;
546​
547 // Antigravity keeps unavailable selections so sign-out or a catalog change
548 // cannot switch the user's model. Other providers retain their fallback
549 // rules. Implicit defaults also exclude legacy models for those providers.
550 const draftModelSelection = resolveSelectableModelSelection(
551 selectedEnvironmentServerConfig,
552 selectedProjectDraft.modelSelection ?? null,
553 );
554 const projectDefaultModelSelection = resolveDefaultableModelSelection(
555 selectedEnvironmentServerConfig,
556 projectSettings.settings.defaultModelSelection,
557 );
558 const storedStickyModelSelection = useStickyComposerModelSelection();
559 const stickyModelSelection = resolveDefaultableModelSelection(
560 selectedEnvironmentServerConfig,
561 storedStickyModelSelection,
562 );
563 const modelOptions = useMemo(
564 () =>
565 buildModelOptions(
566 selectedEnvironmentServerConfig,
567 draftModelSelection ?? projectDefaultModelSelection ?? stickyModelSelection,
568 ),
569 [
570 selectedEnvironmentServerConfig,
571 draftModelSelection,
572 projectDefaultModelSelection,
573 stickyModelSelection,
574 ],
575 );
576​
577 // An unsent draft keeps its explicit pick. Fresh drafts resolve the project
578 // default before the last manual app-wide selection and provider default.
579 const selectedModel = resolveNewTaskModelSelection({
580 draftSelection: draftModelSelection,
581 projectDefaultSelection: projectDefaultModelSelection,
582 stickySelection: stickyModelSelection,
583 modelOptions,
584 });
585 const selectedModelKey = selectedModel
586 ? `${selectedModel.instanceId}:${selectedModel.model}`
587 : null;
588​
589 const selectedModelOption =
590 modelOptions.find(
591 (option) =>
592 selectedModel &&
593 option.selection.instanceId === selectedModel.instanceId &&
594 option.selection.model === selectedModel.model,
595 ) ?? null;
596 const selectedProviderStatus = useMemo(
597 () =>
598 selectedEnvironmentServerConfig?.providers.find(
599 (provider) => provider.instanceId === selectedModel?.instanceId,
600 ) ?? null,
601 [selectedEnvironmentServerConfig, selectedModel?.instanceId],
602 );
603 const planModeEnabled =
604 legacyPlanModeEnabled && selectedProviderStatus?.showInteractionModeToggle !== false;
605 const interactionMode = planModeEnabled
606 ? (selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE)
607 : DEFAULT_PROVIDER_INTERACTION_MODE;
608 const setSelectedModelKey = useCallback(
609 // Options ride along in the same write: a follow-up setSelectedModelOptions
610 // call would rebuild the selection from the stale pre-switch model.
611 (key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => {
612 if (!key || !selectedProjectDraftKey) {
613 return;
614 }
615 const option = modelOptions.find((candidate) => candidate.key === key);
616 if (!option) {
617 return;
618 }
619 const selection = withRememberedModelOptions(
620 options ? { ...option.selection, options } : option.selection,
621 );
622 const provider = selectedEnvironmentServerConfig?.providers.find(
623 (candidate) => candidate.instanceId === selection.instanceId,
624 );
625 updateComposerDraftSettings(selectedProjectDraftKey, {
626 modelSelection: selection,
627 ...(provider?.showInteractionModeToggle === false
628 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
629 : {}),
630 });
631 setStickyComposerModelSelection(selection);
632 },
633 [modelOptions, selectedEnvironmentServerConfig, selectedProjectDraftKey],
634 );
635 const setSelectedModelOptions = useCallback(
636 (options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
637 if (!selectedModel || !selectedProjectDraftKey) {
638 return;
639 }
640 rememberModelOptions(selectedModel.instanceId, selectedModel.model, options ?? []);
641 const nextSelection: ModelSelection = options
642 ? { ...selectedModel, options }
643 : {
644 instanceId: selectedModel.instanceId,
645 model: selectedModel.model,
646 };
647 updateComposerDraftSettings(selectedProjectDraftKey, {
648 modelSelection: nextSelection,
649 });
650 setStickyComposerModelSelection(nextSelection);
651 },
652 [selectedModel, selectedProjectDraftKey],
653 );
654​
655 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
656 const setPrompt = useCallback(
657 (value: string) => {
658 if (!selectedProjectDraftKey) {
659 return;
660 }
661 setComposerDraftText(selectedProjectDraftKey, value);
662 },
663 [selectedProjectDraftKey],
664 );
665 const replaceAttachments = useCallback(
666 (nextAttachments: ReadonlyArray<DraftComposerAttachment>) => {
667 if (!selectedProjectDraftKey) {
668 return;
669 }
670 replaceComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
671 },
672 [selectedProjectDraftKey],
673 );
674 // Returns how many attachments the live cap rejected so the caller can
675 // tell the user (a concurrent add can fill the draft mid-pick).
676 const appendAttachments = useCallback(
677 (
678 nextAttachments: ReadonlyArray<DraftComposerAttachment>,
679 insertion?: ComposerDraftInsertion,
680 ): number => {
681 if (!selectedProjectDraftKey) {
682 return 0;
683 }
684 return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments, {
685 appendReference: true,
686 insertion,
687 });
688 },
689 [selectedProjectDraftKey],
690 );
691 const removeAttachment = useCallback(
692 (imageId: string) => {
693 if (!selectedProjectDraftKey) {
694 return;
695 }
696 removeComposerDraftAttachment(selectedProjectDraftKey, imageId);
697 },
698 [selectedProjectDraftKey],
699 );
700 const clearAttachments = useCallback(() => {
701 if (!selectedProjectDraftKey) {
702 return;
703 }
704 replaceComposerDraftAttachments(selectedProjectDraftKey, []);
705 }, [selectedProjectDraftKey]);
706 const branchSearchQuery = sanitizeNewRefName(branchQuery);
707 const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
708 const branchTarget = useMemo(
709 () => ({
710 environmentId: selectedProject?.environmentId ?? null,
711 // `|| null` also skips the stand-in project's empty workspaceRoot.
712 cwd: selectedProject?.workspaceRoot || null,
713 query: debouncedBranchQuery,
714 }),
715 [debouncedBranchQuery, selectedProject?.environmentId, selectedProject?.workspaceRoot],
716 );
717 const branchState = usePaginatedBranches(branchTarget);
718 const branchSearchIsDebouncing = branchSearchQuery !== debouncedBranchQuery;
719 const branchesLoading =
720 branchSearchIsDebouncing || (branchState.isPending && branchState.data === null);
721 const branchesFetchingNextPage = branchState.isFetchingNextPage;
722 const hasMoreBranches =
723 branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;
724 const allBranchRefs = branchState.refs;
725 const availableBranches = useMemo(
726 () =>
727 pipe(
728 allBranchRefs,
729 Arr.filter((branch) => !branch.isRemote),
730 ),
731 [allBranchRefs],
732 );
733 // The ref actually checked out in the project root, serialized onto new
734 // local threads. It comes from the live status stream rather than listRefs'
735 // `current` flag, which is served from a cache that can lag an out-of-band
736 // `git switch` by minutes — and from the same value the PR badge compares
737 // against. Detached HEAD and non-repository projects report no ref, so this
738 // stays null instead of fabricating a branch. The status family is
739 // deduplicated per (environmentId, cwd) with the thread rows.
740 const projectGitStatus = useEnvironmentQuery(
741 branchTarget.environmentId !== null && branchTarget.cwd !== null
742 ? vcsEnvironment.status({
743 environmentId: branchTarget.environmentId,
744 input: { cwd: branchTarget.cwd },
745 })
746 : null,
747 );
748 const currentCheckoutBranchName = projectGitStatus.data?.refName ?? null;
749​
750 const filteredBranches = useMemo(
751 () => filterNewTaskBranches(allBranchRefs, branchQuery),
752 [allBranchRefs, branchQuery],
753 );
754​
755 // The composer's draft follows the project it will be sent to: switching
756 // mid-compose keeps the same draft and moves it, so typed text follows the
757 // user. A pending-task edit owns its own key and is untouched here.
758 const carryDraftContentTo = useCallback(
759 (project: EnvironmentProject) => {
760 const target = { environmentId: project.environmentId, projectId: project.id };
761 if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
762 retargetNewTaskDraft(activeDraftKey, target);
763 } else if (!editingPendingTaskRef.current) {
764 setActiveDraftKey(createNewTaskDraft(target));
765 }
766 },
767 [activeDraftKey],
768 );
769​
770 const setProject = useCallback(
771 (project: EnvironmentProject) => {
772 carryDraftContentTo(project);
773 setSelectedEnvironmentId(project.environmentId);
774 setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
775 },
776 [carryDraftContentTo],
777 );
778​
779 const openDraft = useCallback(
780 (draftKey: string): boolean => {
781 const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
782 const stamp = draft?.project;
783 if (!isNewTaskDraftKey(draftKey) || !stamp) {
784 return false;
785 }
786 // The stamped project must be loaded: selectedProject falls back to
787 // the environment's first project otherwise, and the draft would be
788 // sent somewhere the user never chose.
789 const projectLoaded = projects.some(
790 (project) =>
791 project.environmentId === stamp.environmentId && project.id === stamp.projectId,
792 );
793 if (!projectLoaded) {
794 return false;
795 }
796 setActiveDraftKey(draftKey);
797 setSelectedEnvironmentId(stamp.environmentId);
798 setSelectedProjectKey(scopedProjectKey(stamp.environmentId, stamp.projectId));
799 return true;
800 },
801 [projects],
802 );
803​
804 const selectEnvironment = useCallback(
805 (environmentId: EnvironmentId) => {
806 const match = resolveEnvironmentProjectMatch(
807 projects.filter((project) => project.environmentId === environmentId),
808 selectedProject,
809 );
810 if (match) {
811 carryDraftContentTo(match);
812 }
813 setSelectedEnvironmentId(environmentId);
814 setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
815 },
816 [projects, selectedProject, carryDraftContentTo],
817 );
818​
819 const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
820 const [switchingToEnvironmentId, setSwitchingToEnvironmentId] = useState<EnvironmentId | null>(
821 null,
822 );
823 // The latest switch wins: a slower, earlier one must not retarget the draft.
824 const latestSwitchRef = useRef<object | null>(null);
825 const switchEnvironment = useCallback(
826 async (environmentId: EnvironmentId): Promise<boolean> => {
827 if (environmentId === selectedEnvironmentId) {
828 latestSwitchRef.current = null;
829 setSwitchingToEnvironmentId(null);
830 return true;
831 }
832 if (!isScratchDraft) {
833 selectEnvironment(environmentId);
834 return true;
835 }
836 const request = {};
837 latestSwitchRef.current = request;
838 setSwitchingToEnvironmentId(environmentId);
839 try {
840 const result = await openScratch({ environmentId, input: {} });
841 if (latestSwitchRef.current !== request) return false;
842 if (result._tag === "Success") {
843 setProject(result.value);
844 return true;
845 }
846 if (!isAtomCommandInterrupted(result)) {
847 const error = squashAtomCommandFailure(result);
848 Alert.alert(
849 "Could not switch machine",
850 error instanceof Error
851 ? error.message
852 : "The folder for threads without a project could not be created.",
853 );
854 }
855 return false;
856 } finally {
857 if (latestSwitchRef.current === request) {
858 latestSwitchRef.current = null;
859 setSwitchingToEnvironmentId(null);
860 }
861 }
862 },
863 [isScratchDraft, openScratch, selectEnvironment, selectedEnvironmentId, setProject],
864 );
865​
866 const setWorkspaceMode = useCallback(
867 (mode: WorkspaceMode) => {
868 if (!selectedProjectDraftKey) {
869 return;
870 }
871 if (!selectedProject) {
872 return;
873 }
874 const localSelection = resolveNewTaskLocalWorkspaceSelection({
875 branches: availableBranches,
876 projectCwd: selectedProject.workspaceRoot,
877 });
878 if (mode === "local" && localSelection.awaitsCurrentBranch) {
879 pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
880 } else {
881 pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
882 }
883 updateComposerDraftSettings(selectedProjectDraftKey, {
884 workspaceSelection: {
885 mode,
886 branch: mode === "local" ? localSelection.branch : selectedBranchName,
887 worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
888 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
889 },
890 });
891 },
892 [
893 availableBranches,
894 draftStartFromOrigin,
895 selectedBranchName,
896 selectedProject,
897 selectedProjectDraftKey,
898 selectedWorktreePath,
899 ],
900 );
901​
902 useEffect(() => {
903 if (
904 workspaceMode !== "local" ||
905 !selectedProject ||
906 !selectedProjectDraftKey ||
907 !pendingLocalBranchSyncDraftKeysRef.current.has(selectedProjectDraftKey)
908 ) {
909 return;
910 }
911 const localSelection = resolveNewTaskLocalWorkspaceSelection({
912 branches: availableBranches,
913 projectCwd: selectedProject.workspaceRoot,
914 });
915 if (localSelection.awaitsCurrentBranch) {
916 return;
917 }
918​
919 pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
920 updateComposerDraftSettings(selectedProjectDraftKey, {
921 workspaceSelection: {
922 mode: "local",
923 branch: localSelection.branch,
924 worktreePath: localSelection.worktreePath,
925 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
926 },
927 });
928 }, [
929 availableBranches,
930 draftStartFromOrigin,
931 selectedProject,
932 selectedProjectDraftKey,
933 workspaceMode,
934 ]);
935​
936 const selectBranch = useCallback(
937 (branch: VcsRef) => {
938 if (!selectedProject || !selectedProjectDraftKey) {
939 return;
940 }
941 pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
942 updateComposerDraftSettings(selectedProjectDraftKey, {
943 workspaceSelection: {
944 mode: workspaceMode,
945 branch: branch.name,
946 worktreePath: resolveNewTaskBranchWorktreePath({
947 workspaceMode,
948 projectCwd: selectedProject.workspaceRoot,
949 branchWorktreePath: branch.worktreePath,
950 }),
951 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
952 },
953 });
954 },
955 [draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
956 );
957​
958 const setStartFromOrigin = useCallback(
959 (value: boolean) => {
960 if (!selectedProjectDraftKey) {
961 return;
962 }
963 updateComposerDraftSettings(selectedProjectDraftKey, {
964 workspaceSelection: {
965 mode: workspaceMode,
966 branch: selectedBranchName,
967 worktreePath: selectedWorktreePath,
968 startFromOrigin: value,
969 },
970 });
971 },
972 [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, workspaceMode],
973 );
974​
975 const refreshBranches = branchState.refresh;
976 const loadMoreBranches = branchState.loadNext;
977 const loadBranches = useCallback(() => {
978 if (!selectedProject) {
979 return;
980 }
981 setPendingConnectionError(null);
982 refreshBranches();
983 }, [refreshBranches, selectedProject]);
984​
985 useEffect(() => {
986 if (
987 !selectedProjectDraftKey ||
988 !defaultWorkspaceModeSettled ||
989 workspaceMode !== "worktree" ||
990 selectedBranchName !== null
991 ) {
992 return;
993 }
994 // The draft screen writes a thread's branch and worktree into the draft in
995 // the same commit this effect runs, so the rendered selection above can be
996 // stale. Re-read the draft before replacing it.
997 const live = getComposerDraftSnapshot(selectedProjectDraftKey).workspaceSelection;
998 if (live && (live.mode !== "worktree" || live.branch !== null)) {
999 return;
1001 // The default may only exist as origin/<default> (isRemote), which
1002 // availableBranches filters out — search the unfiltered refs for it.
1003 const preferredBranch =
1004 allBranchRefs.find((branch) => branch.isDefault) ??
1005 availableBranches.find((branch) => branch.current) ??
1006 null;
1007 if (preferredBranch) {
1008 selectBranch(preferredBranch);
1010 }, [
1011 allBranchRefs,
1012 availableBranches,
1013 defaultWorkspaceModeSettled,
1014 selectBranch,
1015 selectedBranchName,
1016 selectedProjectDraftKey,
1017 workspaceMode,
1018 ]);
1019​
1020 const setRuntimeMode = useCallback(
1021 (value: RuntimeMode) => {
1022 if (selectedProjectDraftKey) {
1023 updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
1025 },
1026 [selectedProjectDraftKey],
1027 );
1028 const setInteractionMode = useCallback(
1029 (value: ProviderInteractionMode) => {
1030 if (selectedProjectDraftKey) {
1031 updateComposerDraftSettings(selectedProjectDraftKey, {
1032 interactionMode: resolveProviderInteractionMode(selectedProviderStatus, value),
1033 });
1035 },
1036 [selectedProjectDraftKey, selectedProviderStatus],
1037 );
1038​
1039 const beginEditingPendingTask = useCallback((messageId: string): boolean => {
1040 const message = findQueuedPendingTask(messageId);
1041 if (!message?.creation) {
1042 return false;
1044 const draftKey = pendingTaskDraftKey(message.messageId);
1045 // Only hydrate a fresh editing draft; reopening mid-edit keeps newer edits.
1046 if (isComposerDraftEmpty(getComposerDraftSnapshot(draftKey))) {
1047 setComposerDraftText(draftKey, message.text);
1048 setComposerDraftContext(draftKey, message.context);
1049 replaceComposerDraftAttachments(draftKey, message.attachments);
1050 updateComposerDraftSettings(draftKey, {
1051 modelSelection: message.modelSelection,
1052 runtimeMode: message.runtimeMode,
1053 interactionMode: message.interactionMode,
1054 workspaceSelection: {
1055 mode: message.creation.workspaceMode,
1056 branch: message.creation.branch,
1057 worktreePath: message.creation.worktreePath,
1058 startFromOrigin: message.creation.startFromOrigin ?? false,
1059 },
1060 });
1062 setSelectedEnvironmentId(message.environmentId);
1063 setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId));
1064 activeEditingMessageId = message.messageId;
1065 editingPendingTaskRef.current = message;
1066 editingRevisionRef.current = capturePendingTaskEditorWriteBaseline(message.messageId);
1067 setEditingPendingTask(message);
1068 // Hold the outbox drain off this task while it is open in the editor.
1069 holdEditingQueuedMessage(message.messageId);
1070 return true;
1071 }, []);
1072​
1073 const buildPendingTaskMessage = useCallback(
1075 metadata: TurnCommandMetadata,
1076 options?: { readonly currentCheckoutBranch?: string | null },
1077 ): QueuedThreadMessage | null => {
1078 if (!selectedProject || !selectedProjectDraftKey) {
1079 return null;
1081 const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
1082 const text = draft.text.trim();
1083 // Use the displayed selection rules without substituting an unavailable
1084 // Antigravity model while the task is queued.
1085 const draftModelSelection =
1086 resolveSelectableModelSelection(
1087 selectedEnvironmentServerConfig,
1088 draft.modelSelection ?? null,
1089 ) ?? selectedModel;
1090 if (text.length === 0 || !draftModelSelection) {
1091 return null;
1093 // A saved choice from before the project went no-project must not
1094 // survive: those threads always run locally in their own folder.
1095 const workspaceSelection = canChooseWorkspace ? draft.workspaceSelection : undefined;
1096 // Fall back to the resolved mode (server default) so queued tasks drain
1097 // with the same mode the composer displayed.
1098 const mode = workspaceSelection?.mode ?? workspaceMode;
1099 // When the selection is the stand-in built from the queued snapshot,
1100 // persist the original (possibly absent) snapshot values — the
1101 // stand-in's placeholder title/workspaceRoot must never be written back
1102 // as if they were real project metadata.
1103 const usingPendingSnapshot = selectedProject === editingPendingProject;
1104 const projectTitle = usingPendingSnapshot
1105 ? editingPendingTask?.creation?.projectTitle
1106 : selectedProject.title;
1107 const projectCwd = usingPendingSnapshot
1108 ? editingPendingTask?.creation?.projectCwd
1109 : selectedProject.workspaceRoot;
1110 return {
1111 environmentId: selectedProject.environmentId,
1112 threadId: ThreadId.make(metadata.threadId),
1113 messageId: MessageId.make(metadata.messageId),
1114 commandId: CommandId.make(metadata.commandId),
1115 text,
1116 attachments: draft.attachments,
1117 context: draft.context,
1118 modelSelection: draftModelSelection,
1119 runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
1120 interactionMode: resolvePendingTaskInteractionMode({
1121 preferenceLoaded: planModePreferenceLoaded,
1122 planModeEnabled: legacyPlanModeEnabled,
1123 draftInteractionMode: draft.interactionMode,
1124 queuedInteractionMode: editingPendingTask?.interactionMode,
1125 provider: selectedEnvironmentServerConfig?.providers.find(
1126 (candidate) => candidate.instanceId === draftModelSelection.instanceId,
1127 ),
1128 }),
1129 creation: {
1130 projectId: selectedProject.id,
1131 ...(projectTitle !== undefined ? { projectTitle } : {}),
1132 ...(projectCwd !== undefined ? { projectCwd } : {}),
1133 workspaceMode: mode,
1134 // An explicit picker choice wins. Otherwise only a task sending now
1135 // records the current checkout: a queued local task drains days
1136 // later against whatever is checked out then, so a queue-time
1137 // guess would pin a stale label to a thread that ran somewhere else.
1138 branch: resolveProjectThreadCreationBranch({
1139 workspaceMode: mode,
1140 selectedBranch: workspaceSelection?.branch ?? null,
1141 currentCheckoutBranch: options?.currentCheckoutBranch ?? null,
1142 }),
1143 worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
1144 // The draft only carries the flag when the user touched it; fall
1145 // back to the resolved default (server settings) so queued tasks
1146 // drain with the same origin mode the composer displayed.
1147 ...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
1148 ? { startFromOrigin: true }
1149 : {}),
1150 },
1151 createdAt: metadata.createdAt,
1152 };
1153 },
1155 canChooseWorkspace,
1156 defaultRuntimeMode,
1157 editingPendingProject,
1158 editingPendingTask,
1159 selectedEnvironmentServerConfig,
1160 selectedModel,
1161 selectedProject,
1162 selectedProjectDraftKey,
1163 legacyPlanModeEnabled,
1164 planModePreferenceLoaded,
1165 startFromOrigin,
1166 workspaceMode,
1167 ],
1168 );
1169​
1170 const finishEditingPendingTask = useCallback(() => {
1171 const editing = editingPendingTaskRef.current;
1172 editingPendingTaskRef.current = null;
1173 if (editing) {
1174 if (activeEditingMessageId === editing.messageId) {
1175 activeEditingMessageId = null;
1177 clearComposerDraft(pendingTaskDraftKey(editing.messageId));
1178 releaseEditingQueuedMessage(editing.messageId);
1179 scheduleUnusedComposerAttachmentCleanup(editing.attachments);
1181 setEditingPendingTask(null);
1182 }, []);
1183​
1184 // If the queued task disappears mid-edit (deleted from the list, or
1185 // delivered), end the editing session immediately without saving — a later
1186 // flush must not resurrect it, and the composer should fall back to the
1187 // regular per-project draft.
1188 const queuedMessagesByThreadKey = useThreadOutboxMessages();
1189 useEffect(() => {
1190 const editing = editingPendingTaskRef.current;
1191 if (!editing) {
1192 return;
1194 const stillQueued = flattenQueuedThreadMessages(queuedMessagesByThreadKey).some(
1195 (candidate) => candidate.messageId === editing.messageId,
1196 );
1197 if (!stillQueued) {
1198 finishEditingPendingTask();
1200 }, [finishEditingPendingTask, queuedMessagesByThreadKey]);
1201​
1202 // Leaving the flow mid-edit (sheet dismissed or draft screen popped) saves
1203 // the current edits back into the queued task so nothing typed here is lost.
1204 const editingFlushRef = useRef<(() => void) | null>(null);
1205 useEffect(() => {
1206 editingFlushRef.current = () => {
1207 const editing = editingPendingTaskRef.current;
1208 if (!editing) {
1209 return;
1211 editingPendingTaskRef.current = null;
1212 setEditingPendingTask(null);
1213 if (activeEditingMessageId === editing.messageId) {
1214 activeEditingMessageId = null;
1216​
1217 const message = buildPendingTaskMessage({
1218 threadId: editing.threadId,
1219 commandId: editing.commandId,
1220 messageId: editing.messageId,
1221 createdAt: editing.createdAt,
1222 });
1223​
1224 if (!message) {
1225 // The edits are currently unsendable (e.g. the prompt was cleared).
1226 // Keep both the draft and the drain lock: the stale queued payload
1227 // must not auto-send content the user just removed, and reopening the
1228 // task resumes from the saved draft.
1229 return;
1231​
1232 // The write handoff lets a reopened editor follow this editor's pending
1233 // save. Its CAS still rejects unrelated queue edits, deletes, and
1234 // deliveries, so the flush cannot resurrect or overwrite them.
1235 void flushPendingTaskEditorWrite({
1236 message,
1237 baseline: editingRevisionRef.current,
1238 draftKey: pendingTaskDraftKey(editing.messageId),
1239 })
1240 .then((savedDraftStillCurrent) => {
1241 // If this task was reopened (possibly in a fresh provider) while
1242 // the save was in flight, that session owns the draft and the lock.
1243 if (activeEditingMessageId === editing.messageId) {
1244 return;
1246 if (!savedDraftStillCurrent) {
1247 // A newer queue write won the CAS, or a newer editor changed this
1248 // draft. Keep the draft and drain lock so reopening can retry it.
1249 return;
1251 clearComposerDraft(pendingTaskDraftKey(editing.messageId));
1252 releaseEditingQueuedMessage(editing.messageId);
1253 scheduleUnusedComposerAttachmentCleanup(editing.attachments);
1254 })
1255 .catch((error) => {
1256 // Keep the drain lock and the draft: delivering the stale payload
1257 // would silently drop the newer edits. Reopening the task retries.
1258 console.warn("[new-task] failed to save edited pending task", error);
1259 });
1260 };
1261 }, [buildPendingTaskMessage]);
1262 const cancelEditingPendingTask = useCallback(() => {
1263 editingFlushRef.current?.();
1264 }, []);
1265 useEffect(
1266 () => () => {
1267 editingFlushRef.current?.();
1268 },
1269 [],
1270 );
1271​
1272 const value = useMemo<NewTaskFlowContextValue>(
1273 () => ({
1274 projectScopes,
1275 selectedEnvironmentId,
1276 selectedProjectKey,
1277 selectedModelKey,
1278 workspaceMode,
1279 canChooseWorkspace,
1280 selectedBranchName,
1281 selectedWorktreePath,
1282 startFromOrigin,
1283 draftKey: selectedProjectDraftKey,
1284 editingPendingTask,
1285 prompt,
1286 attachments,
1287 submitting,
1288 branchQuery,
1289 branchesLoading,
1290 branchesError: branchState.error,
1291 branchesFetchingNextPage,
1292 hasMoreBranches,
1293 availableBranches,
1294 currentCheckoutBranchName,
1295 runtimeMode,
1296 interactionMode,
1297 planModeEnabled,
1298 expandedProvider,
1299 environments,
1300 selectedProject,
1301 isScratchDraft,
1302 modelOptions,
1303 selectedModel,
1304 selectedModelOption,
1305 selectedProviderStatus,
1306 providerGroups,
1307 filteredBranches,
1308 reset,
1309 setProject,
1310 openDraft,
1311 selectEnvironment,
1312 switchEnvironment,
1313 switchingToEnvironmentId,
1314 setSelectedModelKey,
1315 setWorkspaceMode,
1316 selectBranch,
1317 setStartFromOrigin,
1318 beginEditingPendingTask,
1319 finishEditingPendingTask,
1320 cancelEditingPendingTask,
1321 buildPendingTaskMessage,
1322 setPrompt,
1323 replaceAttachments,
1324 appendAttachments,
1325 removeAttachment,
1326 clearAttachments,
1327 setSubmitting,
1328 setBranchQuery,
1329 loadBranches,
1330 loadMoreBranches,
1331 setRuntimeMode,
1332 setInteractionMode,
1333 setSelectedModelOptions,
1334 setExpandedProvider,
1335 }),
1337 attachments,
1338 availableBranches,
1339 beginEditingPendingTask,
1340 branchQuery,
1341 branchesLoading,
1342 branchState.error,
1343 branchesFetchingNextPage,
1344 buildPendingTaskMessage,
1345 cancelEditingPendingTask,
1346 currentCheckoutBranchName,
1347 editingPendingTask,
1348 environments,
1349 expandedProvider,
1350 filteredBranches,
1351 finishEditingPendingTask,
1352 interactionMode,
1353 isScratchDraft,
1354 planModeEnabled,
1355 loadBranches,
1356 loadMoreBranches,
1357 projectScopes,
1358 modelOptions,
1359 prompt,
1360 providerGroups,
1361 replaceAttachments,
1362 reset,
1363 runtimeMode,
1364 selectedBranchName,
1365 hasMoreBranches,
1366 selectedEnvironmentId,
1367 selectedModel,
1368 selectedModelKey,
1369 selectedModelOption,
1370 selectedProjectDraftKey,
1371 selectedProviderStatus,
1372 setSelectedModelOptions,
1373 selectedProject,
1374 selectedProjectKey,
1375 selectedWorktreePath,
1376 setProject,
1377 openDraft,
1378 selectBranch,
1379 selectEnvironment,
1380 switchEnvironment,
1381 switchingToEnvironmentId,
1382 setInteractionMode,
1383 setPrompt,
1384 setRuntimeMode,
1385 setSelectedModelKey,
1386 setStartFromOrigin,
1387 setWorkspaceMode,
1388 startFromOrigin,
1389 submitting,
1390 workspaceMode,
1391 canChooseWorkspace,
1392 appendAttachments,
1393 clearAttachments,
1394 removeAttachment,
1395 ],
1396 );
1397​
1398 return <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>;
1400​
1401export function useNewTaskFlow() {
1402 const value = React.use(NewTaskFlowContext);
1403 if (value === null) {
1404 throw new Error("useNewTaskFlow must be used within NewTaskFlowProvider.");
1406 return value;