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

new-task-flow-provider.tsx

1,425 lines52.8 KB

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