Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
3import { useEnvironmentPresentation } from "../../state/presentation";
4import { environmentSession } from "../../state/session";
5import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
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 { resolveNewThreadEnvMode, 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}`;
131}
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;
144}
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;
163}
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 readonly canChooseWorkspace: boolean;
172 readonly selectedBranchName: string | null;
173 readonly selectedWorktreePath: string | null;
174 readonly startFromOrigin: boolean;
175 readonly pullRequestReference: string | undefined;
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 readonly isScratchDraft: boolean;
198 readonly modelOptions: ReadonlyArray<ModelOption>;
199 readonly selectedModel: ModelSelection | null;
200 readonly selectedModelOption: ModelOption | null;
201 readonly selectedProviderStatus: ServerProvider | null;
202 readonly providerGroups: ReadonlyArray<ProviderGroup>;
203 readonly filteredBranches: ReadonlyArray<VcsRef>;
204 readonly reset: () => void;
205 readonly setProject: (project: EnvironmentProject) => void;
206 /**
207 * Binds the composer to an existing new-task draft (a row in the thread
208 * list). Returns false when the draft is gone, so the caller can fall back
209 * to a fresh one.
210 */
211 readonly openDraft: (draftKey: string) => boolean;
212 readonly selectEnvironment: (environmentId: EnvironmentId) => void;
213 readonly switchEnvironment: (environmentId: EnvironmentId) => Promise<boolean>;
214 readonly switchingToEnvironmentId: EnvironmentId | null;
215 readonly setSelectedModelKey: (
216 key: string | null,
217 options?: ReadonlyArray<ProviderOptionSelection>,
218 ) => void;
219 readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
220 readonly selectBranch: (branch: VcsRef) => void;
221 readonly setStartFromOrigin: (value: boolean) => void;
222 readonly beginEditingPendingTask: (messageId: string) => boolean;
223 readonly finishEditingPendingTask: () => void;
224 readonly cancelEditingPendingTask: () => void;
225 readonly buildPendingTaskMessage: (
226 metadata: TurnCommandMetadata,
227 options?: {
228 readonly currentCheckoutBranch?: string | null;
229 },
230 ) => QueuedThreadMessage | null;
231 readonly setPrompt: (value: string) => void;
232 readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => void;
233 /** Appends draft attachments; returns how many the live cap rejected. */
234 readonly appendAttachments: (
235 attachments: ReadonlyArray<DraftComposerAttachment>,
236 insertion?: ComposerDraftInsertion,
237 ) => number;
238 readonly removeAttachment: (imageId: string) => void;
239 readonly clearAttachments: () => void;
240 readonly setSubmitting: (value: boolean) => void;
241 readonly setBranchQuery: (value: string) => void;
242 readonly loadBranches: () => void;
243 readonly loadMoreBranches: () => void;
244 readonly setRuntimeMode: (value: RuntimeMode) => void;
245 readonly setInteractionMode: (value: ProviderInteractionMode) => void;
246 readonly setSelectedModelOptions: (
247 value: ReadonlyArray<ProviderOptionSelection> | undefined,
248 ) => void;
249 readonly setExpandedProvider: (value: string | null) => void;
250};
251
252const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null);
253
254export function NewTaskFlowProvider(props: React.PropsWithChildren) {
255 const projects = useProjects();
256 const threads = useThreadShells();
257 const { savedConnectionsById } = useSavedRemoteConnections();
258 const groupingSettings = useMobileProjectGroupingSettings();
259 const { enabled: legacyPlanModeEnabled, loaded: planModePreferenceLoaded } =
260 useLegacyPlanModeState();
261
262 const projectScopes = useMemo(
263 () =>
264 sortHomeProjectScopes({
265 scopes: buildHomeProjectScopes({
266 projects,
267 environmentId: null,
268 projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
269 }),
270 threads,
271 pendingTasks: [],
272 projectSortOrder: "updated_at",
273 }),
274 [groupingSettings.sidebarProjectGroupingMode, projects, threads],
275 );
276
277 const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
278 null,
279 );
280 const selectedEnvironmentId =
281 selectedEnvironmentIdOverride !== null &&
282 projects.some((project) => project.environmentId === selectedEnvironmentIdOverride)
283 ? selectedEnvironmentIdOverride
284 : (projects[0]?.environmentId ?? null);
285 const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
286 const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
287 const [submitting, setSubmitting] = useState(false);
288 const [branchQuery, setBranchQuery] = useState("");
289 const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
290 const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
291 const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
292 // Mirrors `editingPendingTask` synchronously so the unmount flush cannot act
293 // on a task whose editing session already ended this render.
294 const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
295 const editingRevisionRef = useRef(Promise.resolve(0));
296
297 const reset = useCallback(() => {
298 setSelectedEnvironmentId(null);
299 setSelectedProjectKey(null);
300 setActiveDraftKey(null);
301 setSubmitting(false);
302 setBranchQuery("");
303 setExpandedProvider(null);
304 pendingLocalBranchSyncDraftKeysRef.current.clear();
305 const editing = editingPendingTaskRef.current;
306 editingPendingTaskRef.current = null;
307 setEditingPendingTask(null);
308 if (editing) {
309 if (activeEditingMessageId === editing.messageId) {
310 activeEditingMessageId = null;
311 }
312 releaseEditingQueuedMessage(editing.messageId);
313 }
314 }, []);
315
316 const projectsForEnvironment = useMemo(
317 () =>
318 pipe(
319 projects,
320 Arr.filter((project) => project.environmentId === selectedEnvironmentId),
321 ),
322 [projects, selectedEnvironmentId],
323 );
324
325 const editingPendingProject = useMemo<EnvironmentProject | null>(() => {
326 const creation = editingPendingTask?.creation;
327 if (!editingPendingTask || !creation) {
328 return null;
329 }
330 return {
331 environmentId: editingPendingTask.environmentId,
332 id: creation.projectId,
333 title: creation.projectTitle ?? "Unknown project",
334 workspaceRoot: creation.projectCwd ?? "",
335 repositoryIdentity: null,
336 defaultModelSelection: editingPendingTask.modelSelection ?? null,
337 scripts: [],
338 createdAt: editingPendingTask.createdAt,
339 updatedAt: editingPendingTask.createdAt,
340 };
341 }, [editingPendingTask]);
342
343 const selectedProject =
344 projectsForEnvironment.find(
345 (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
346 ) ??
347 // While editing a queued task whose project shell is absent, keep the task
348 // pinned to its own project — falling through to an arbitrary first
349 // project would silently retarget it (and its reused turn identifiers).
350 (editingPendingProject !== null &&
351 selectedProjectKey ===
352 scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id)
353 ? editingPendingProject
354 : (projectsForEnvironment[0] ?? null));
355
356 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
357 selectedProject?.environmentId ?? null,
358 );
359 const isScratchDraft =
360 selectedProject !== null &&
361 isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot);
362 const serverConfigs = useServerConfigs();
363 const { connectedEnvironments } = useRemoteConnectionStatus();
364 const scratchEnvironments = useMemo(
365 () =>
366 connectedEnvironments.filter(
367 (environment) =>
368 availableScratchWorkspaceRoot(
369 environment.connectionState,
370 serverConfigs.get(environment.environmentId),
371 ) !== null,
372 ),
373 [connectedEnvironments, serverConfigs],
374 );
375
376 const selectedRepositoryKey = selectedProject?.repositoryIdentity
377 ? repositoryGroupingKeyOf(selectedProject.repositoryIdentity)
378 : null;
379 // `|| null` (not `??`): a pending-task placeholder project can have an empty
380 // workspaceRoot, and an "" basename would reject every real host below.
381 const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
382 const selectedProjectTitle = selectedProject?.title ?? null;
383 const environments = useMemo(() => {
384 if (isScratchDraft) {
385 return scratchEnvironments.map((environment) => ({
386 environmentId: environment.environmentId,
387 environmentLabel: environment.environmentLabel,
388 }));
389 }
390 const seen = new Set<EnvironmentId>();
391 const result: Array<{
392 readonly environmentId: EnvironmentId;
393 readonly environmentLabel: string;
394 }> = [];
395 const hostsSelectedRepository = (project: EnvironmentProject) => {
396 if (selectedRepositoryKey === null && selectedWorkspaceBasename === null) {
397 return true;
398 }
399 const projectKey = project.repositoryIdentity
400 ? repositoryGroupingKeyOf(project.repositoryIdentity)
401 : null;
402 if (selectedRepositoryKey !== null && projectKey !== null) {
403 return projectKey === selectedRepositoryKey;
404 }
405 return (
406 project.workspaceRoot.split("/").at(-1) === selectedWorkspaceBasename ||
407 (selectedProjectTitle !== null && project.title === selectedProjectTitle)
408 );
409 };
410 for (const project of projects) {
411 if (!hostsSelectedRepository(project)) {
412 continue;
413 }
414 if (seen.has(project.environmentId)) {
415 continue;
416 }
417 const environment = savedConnectionsById[project.environmentId];
418 if (!environment) {
419 continue;
420 }
421 seen.add(project.environmentId);
422 result.push({
423 environmentId: project.environmentId,
424 environmentLabel: environment.environmentLabel,
425 });
426 }
427 return result;
428 }, [
429 isScratchDraft,
430 projects,
431 savedConnectionsById,
432 scratchEnvironments,
433 selectedRepositoryKey,
434 selectedWorkspaceBasename,
435 selectedProjectTitle,
436 ]);
437
438 const selectedProjectDraftKey = editingPendingTask
439 ? pendingTaskDraftKey(editingPendingTask.messageId)
440 : selectedProject
441 ? activeDraftKey
442 : null;
443 useEffect(() => {
444 if (activeDraftKey !== null || editingPendingTask !== null || selectedProject === null) {
445 return;
446 }
447 setActiveDraftKey(
448 createNewTaskDraft({
449 environmentId: selectedProject.environmentId,
450 projectId: selectedProject.id,
451 }),
452 );
453 }, [activeDraftKey, editingPendingTask, selectedProject]);
454 const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
455 const prompt = selectedProjectDraft.text;
456 const attachments = selectedProjectDraft.attachments;
457 const fileAccessSession = useEnvironmentQuery(
458 selectedProject !== null && selectedProject.workspaceRoot !== ""
459 ? environmentSession.sessionStateAtom(selectedProject.environmentId)
460 : null,
461 );
462 const fileEnvironment = useEnvironmentPresentation(selectedProject?.environmentId ?? null);
463 const fileAccess = resolveFilesystemReadAccess({
464 isCatalogReady: fileEnvironment.isReady,
465 connection: fileEnvironment.presentation?.connection ?? null,
466 session: fileAccessSession.data,
467 sessionError: fileAccessSession.error,
468 });
469 const { canReadFiles } = fileAccess;
470 const fileAccessPending =
471 selectedProject !== null && selectedProject.workspaceRoot !== "" && fileAccess.isPending;
472 const t3ProjectFileQuery = useEnvironmentQuery(
473 canReadFiles && selectedProject !== null && selectedProject.workspaceRoot !== ""
474 ? projectEnvironment.readFile({
475 environmentId: selectedProject.environmentId,
476 input: { cwd: selectedProject.workspaceRoot, relativePath: T3_PROJECT_FILE_NAME },
477 })
478 : null,
479 );
480 const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
481 const t3ProjectFile = useMemo(
482 () =>
483 t3ProjectFileData === null || t3ProjectFileData.truncated
484 ? null
485 : parseT3ProjectFile(t3ProjectFileData.contents),
486 [t3ProjectFileData],
487 );
488 const projectSettings = useMemo(
489 () =>
490 resolveProjectSettings(
491 selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
492 selectedProject?.id ?? null,
493 selectedProject,
494 t3ProjectFile,
495 ),
496 [selectedEnvironmentServerConfig?.settings, selectedProject, t3ProjectFile],
497 );
498 const canChooseWorkspace = !isScratchDraft;
499 const selectedProjectHasThreads =
500 selectedProject !== null &&
501 threads.some(
502 (thread) =>
503 thread.environmentId === selectedProject.environmentId &&
504 thread.projectId === selectedProject.id,
505 );
506 const defaultWorkspaceMode: WorkspaceMode = canChooseWorkspace
507 ? resolveNewThreadEnvMode({
508 projectSettings,
509 workspaceRoot: selectedProject?.workspaceRoot ?? null,
510 newProjectsRoot: selectedEnvironmentServerConfig?.newProjectsRoot,
511 projectHasThreads: selectedProjectHasThreads,
512 })
513 : "local";
514 // While the file read is pending and nothing above it decided, the
515 // resolved default is provisional. Nothing may write it into the draft
516 // during that window (the auto-branch effect does), or the frozen interim
517 // value beats the t3.json default once it loads.
518 const defaultWorkspaceModeSettled =
519 selectedProjectDraft.workspaceSelection?.mode !== undefined ||
520 projectSettings.sources.defaultThreadEnvMode !== "environment" ||
521 (!t3ProjectFileQuery.isPending && !fileAccessPending);
522 const workspaceMode = canChooseWorkspace
523 ? (selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode)
524 : "local";
525 const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
526 const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
527 // Keep the user's explicit choice separate from the resolved display value:
528 // only the explicit flag is ever written back to the draft, so the resolved
529 // value keeps tracking the server setting when the config loads late.
530 const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
531 const startFromOrigin =
532 draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin;
533 const defaultRuntimeMode = editingPendingTask
534 ? (editingPendingTask.runtimeMode ?? DEFAULT_RUNTIME_MODE)
535 : projectSettings.settings.defaultRuntimeMode;
536 const runtimeMode = selectedProjectDraft.runtimeMode ?? defaultRuntimeMode;
537
538 // Antigravity keeps unavailable selections so sign-out or a catalog change
539 // cannot switch the user's model.
540 const draftModelSelection = resolveSelectableModelSelection(
541 selectedEnvironmentServerConfig,
542 selectedProjectDraft.modelSelection ?? null,
543 selectedProject?.id ?? null,
544 );
545 const projectDefaultModelSelection = resolveDefaultableModelSelection(
546 selectedEnvironmentServerConfig,
547 projectSettings.settings.defaultModelSelection,
548 selectedProject?.id ?? null,
549 );
550 const storedStickyModelSelection = useStickyComposerModelSelection();
551 const stickyModelSelection = resolveDefaultableModelSelection(
552 selectedEnvironmentServerConfig,
553 storedStickyModelSelection,
554 selectedProject?.id ?? null,
555 );
556 const modelOptions = useMemo(
557 () =>
558 buildModelOptions(
559 selectedEnvironmentServerConfig,
560 draftModelSelection ?? projectDefaultModelSelection ?? stickyModelSelection,
561 undefined,
562 selectedProject?.id ?? null,
563 ),
564 [
565 selectedEnvironmentServerConfig,
566 draftModelSelection,
567 projectDefaultModelSelection,
568 stickyModelSelection,
569 selectedProject?.id,
570 ],
571 );
572
573 const selectedModel = resolveNewTaskModelSelection({
574 draftSelection: draftModelSelection,
575 projectDefaultSelection: projectDefaultModelSelection,
576 stickySelection: stickyModelSelection,
577 modelOptions,
578 });
579 const selectedModelKey = selectedModel
580 ? `${selectedModel.instanceId}:${selectedModel.model}`
581 : null;
582
583 const selectedModelOption =
584 modelOptions.find(
585 (option) =>
586 selectedModel &&
587 option.selection.instanceId === selectedModel.instanceId &&
588 option.selection.model === selectedModel.model,
589 ) ?? null;
590 const selectedProviderStatus = useMemo(
591 () =>
592 selectedEnvironmentServerConfig?.providers.find(
593 (provider) => provider.instanceId === selectedModel?.instanceId,
594 ) ?? null,
595 [selectedEnvironmentServerConfig, selectedModel?.instanceId],
596 );
597 const planModeEnabled =
598 legacyPlanModeEnabled && selectedProviderStatus?.showInteractionModeToggle !== false;
599 const interactionMode = planModeEnabled
600 ? (selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE)
601 : DEFAULT_PROVIDER_INTERACTION_MODE;
602 const setSelectedModelKey = useCallback(
603 // Options ride along in the same write: a follow-up setSelectedModelOptions
604 // call would rebuild the selection from the stale pre-switch model.
605 (key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => {
606 if (!key || !selectedProjectDraftKey) {
607 return;
608 }
609 const option = modelOptions.find((candidate) => candidate.key === key);
610 if (!option) {
611 return;
612 }
613 const selection = withRememberedModelOptions(
614 options ? { ...option.selection, options } : option.selection,
615 );
616 const provider = selectedEnvironmentServerConfig?.providers.find(
617 (candidate) => candidate.instanceId === selection.instanceId,
618 );
619 updateComposerDraftSettings(selectedProjectDraftKey, {
620 modelSelection: selection,
621 ...(provider?.showInteractionModeToggle === false
622 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
623 : {}),
624 });
625 setStickyComposerModelSelection(selection);
626 },
627 [modelOptions, selectedEnvironmentServerConfig, selectedProjectDraftKey],
628 );
629 const setSelectedModelOptions = useCallback(
630 (options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
631 if (!selectedModel || !selectedProjectDraftKey) {
632 return;
633 }
634 rememberModelOptions(selectedModel.instanceId, selectedModel.model, options ?? []);
635 const nextSelection: ModelSelection = options
636 ? { ...selectedModel, options }
637 : {
638 instanceId: selectedModel.instanceId,
639 model: selectedModel.model,
640 };
641 updateComposerDraftSettings(selectedProjectDraftKey, {
642 modelSelection: nextSelection,
643 });
644 setStickyComposerModelSelection(nextSelection);
645 },
646 [selectedModel, selectedProjectDraftKey],
647 );
648
649 const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
650 const setPrompt = useCallback(
651 (value: string) => {
652 if (!selectedProjectDraftKey) {
653 return;
654 }
655 setComposerDraftText(selectedProjectDraftKey, value);
656 },
657 [selectedProjectDraftKey],
658 );
659 const replaceAttachments = useCallback(
660 (nextAttachments: ReadonlyArray<DraftComposerAttachment>) => {
661 if (!selectedProjectDraftKey) {
662 return;
663 }
664 replaceComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
665 },
666 [selectedProjectDraftKey],
667 );
668 const appendAttachments = useCallback(
669 (
670 nextAttachments: ReadonlyArray<DraftComposerAttachment>,
671 insertion?: ComposerDraftInsertion,
672 ): number => {
673 if (!selectedProjectDraftKey) {
674 return 0;
675 }
676 return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments, {
677 appendReference: true,
678 insertion,
679 });
680 },
681 [selectedProjectDraftKey],
682 );
683 const removeAttachment = useCallback(
684 (imageId: string) => {
685 if (!selectedProjectDraftKey) {
686 return;
687 }
688 removeComposerDraftAttachment(selectedProjectDraftKey, imageId);
689 },
690 [selectedProjectDraftKey],
691 );
692 const clearAttachments = useCallback(() => {
693 if (!selectedProjectDraftKey) {
694 return;
695 }
696 replaceComposerDraftAttachments(selectedProjectDraftKey, []);
697 }, [selectedProjectDraftKey]);
698 const branchSearchQuery = sanitizeNewRefName(branchQuery);
699 const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
700 const branchTarget = useMemo(
701 () => ({
702 environmentId: selectedProject?.environmentId ?? null,
703 cwd: selectedProject?.workspaceRoot || null,
704 query: debouncedBranchQuery,
705 }),
706 [debouncedBranchQuery, selectedProject?.environmentId, selectedProject?.workspaceRoot],
707 );
708 const branchState = usePaginatedBranches(branchTarget);
709 const branchSearchIsDebouncing = branchSearchQuery !== debouncedBranchQuery;
710 const branchesLoading =
711 branchSearchIsDebouncing || (branchState.isPending && branchState.data === null);
712 const branchesFetchingNextPage = branchState.isFetchingNextPage;
713 const hasMoreBranches =
714 branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;
715 const allBranchRefs = branchState.refs;
716 const availableBranches = useMemo(
717 () =>
718 pipe(
719 allBranchRefs,
720 Arr.filter((branch) => !branch.isRemote),
721 ),
722 [allBranchRefs],
723 );
724 const projectGitStatus = useEnvironmentQuery(
725 branchTarget.environmentId !== null && branchTarget.cwd !== null
726 ? vcsEnvironment.status({
727 environmentId: branchTarget.environmentId,
728 input: { cwd: branchTarget.cwd },
729 })
730 : null,
731 );
732 const currentCheckoutBranchName = projectGitStatus.data?.refName ?? null;
733
734 const filteredBranches = useMemo(
735 () => filterNewTaskBranches(allBranchRefs, branchQuery),
736 [allBranchRefs, branchQuery],
737 );
738
739 const carryDraftContentTo = useCallback(
740 (project: EnvironmentProject) => {
741 const target = { environmentId: project.environmentId, projectId: project.id };
742 if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
743 retargetNewTaskDraft(activeDraftKey, target);
744 } else if (!editingPendingTaskRef.current) {
745 setActiveDraftKey(createNewTaskDraft(target));
746 }
747 },
748 [activeDraftKey],
749 );
750
751 const setProject = useCallback(
752 (project: EnvironmentProject) => {
753 carryDraftContentTo(project);
754 setSelectedEnvironmentId(project.environmentId);
755 setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
756 },
757 [carryDraftContentTo],
758 );
759
760 const openDraft = useCallback(
761 (draftKey: string): boolean => {
762 const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
763 const stamp = draft?.project;
764 if (!isNewTaskDraftKey(draftKey) || !stamp) {
765 return false;
766 }
767 // The stamped project must be loaded: selectedProject falls back to
768 // the environment's first project otherwise, and the draft would be
769 // sent somewhere the user never chose.
770 const projectLoaded = projects.some(
771 (project) =>
772 project.environmentId === stamp.environmentId && project.id === stamp.projectId,
773 );
774 if (!projectLoaded) {
775 return false;
776 }
777 setActiveDraftKey(draftKey);
778 setSelectedEnvironmentId(stamp.environmentId);
779 setSelectedProjectKey(scopedProjectKey(stamp.environmentId, stamp.projectId));
780 return true;
781 },
782 [projects],
783 );
784
785 const selectEnvironment = useCallback(
786 (environmentId: EnvironmentId) => {
787 const match = resolveEnvironmentProjectMatch(
788 projects.filter((project) => project.environmentId === environmentId),
789 selectedProject,
790 );
791 if (match) {
792 carryDraftContentTo(match);
793 }
794 setSelectedEnvironmentId(environmentId);
795 setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
796 },
797 [projects, selectedProject, carryDraftContentTo],
798 );
799
800 const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
801 const [switchingToEnvironmentId, setSwitchingToEnvironmentId] = useState<EnvironmentId | null>(
802 null,
803 );
804 const latestSwitchRef = useRef<object | null>(null);
805 const switchEnvironment = useCallback(
806 async (environmentId: EnvironmentId): Promise<boolean> => {
807 if (environmentId === selectedEnvironmentId) {
808 latestSwitchRef.current = null;
809 setSwitchingToEnvironmentId(null);
810 return true;
811 }
812 if (!isScratchDraft) {
813 selectEnvironment(environmentId);
814 return true;
815 }
816 const request = {};
817 latestSwitchRef.current = request;
818 setSwitchingToEnvironmentId(environmentId);
819 try {
820 const result = await openScratch({ environmentId, input: {} });
821 if (latestSwitchRef.current !== request) return false;
822 if (result._tag === "Success") {
823 setProject(result.value);
824 return true;
825 }
826 if (!isAtomCommandInterrupted(result)) {
827 const error = squashAtomCommandFailure(result);
828 Dialog.alert(
829 "Could not switch machine",
830 error instanceof Error
831 ? error.message
832 : "The folder for threads without a project could not be created.",
833 );
834 }
835 return false;
836 } finally {
837 if (latestSwitchRef.current === request) {
838 latestSwitchRef.current = null;
839 setSwitchingToEnvironmentId(null);
840 }
841 }
842 },
843 [isScratchDraft, openScratch, selectEnvironment, selectedEnvironmentId, setProject],
844 );
845
846 const setWorkspaceMode = useCallback(
847 (mode: WorkspaceMode) => {
848 if (!selectedProjectDraftKey) {
849 return;
850 }
851 if (!selectedProject) {
852 return;
853 }
854 const localSelection = resolveNewTaskLocalWorkspaceSelection({
855 branches: availableBranches,
856 projectCwd: selectedProject.workspaceRoot,
857 });
858 if (mode === "local" && localSelection.awaitsCurrentBranch) {
859 pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
860 } else {
861 pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
862 }
863 updateComposerDraftSettings(selectedProjectDraftKey, {
864 workspaceSelection: {
865 mode,
866 branch: mode === "local" ? localSelection.branch : selectedBranchName,
867 worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
868 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
869 },
870 });
871 },
872 [
873 availableBranches,
874 draftStartFromOrigin,
875 selectedBranchName,
876 selectedProject,
877 selectedProjectDraftKey,
878 selectedWorktreePath,
879 ],
880 );
881
882 useEffect(() => {
883 if (
884 workspaceMode !== "local" ||
885 !selectedProject ||
886 !selectedProjectDraftKey ||
887 !pendingLocalBranchSyncDraftKeysRef.current.has(selectedProjectDraftKey)
888 ) {
889 return;
890 }
891 const localSelection = resolveNewTaskLocalWorkspaceSelection({
892 branches: availableBranches,
893 projectCwd: selectedProject.workspaceRoot,
894 });
895 if (localSelection.awaitsCurrentBranch) {
896 return;
897 }
898
899 pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
900 updateComposerDraftSettings(selectedProjectDraftKey, {
901 workspaceSelection: {
902 mode: "local",
903 branch: localSelection.branch,
904 worktreePath: localSelection.worktreePath,
905 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
906 },
907 });
908 }, [
909 availableBranches,
910 draftStartFromOrigin,
911 selectedProject,
912 selectedProjectDraftKey,
913 workspaceMode,
914 ]);
915
916 const selectBranch = useCallback(
917 (branch: VcsRef) => {
918 if (!selectedProject || !selectedProjectDraftKey) {
919 return;
920 }
921 pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
922 updateComposerDraftSettings(selectedProjectDraftKey, {
923 workspaceSelection: {
924 mode: workspaceMode,
925 branch: branch.name,
926 worktreePath: resolveNewTaskBranchWorktreePath({
927 workspaceMode,
928 projectCwd: selectedProject.workspaceRoot,
929 branchWorktreePath: branch.worktreePath,
930 }),
931 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
932 },
933 });
934 },
935 [draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
936 );
937
938 const setStartFromOrigin = useCallback(
939 (value: boolean) => {
940 if (!selectedProjectDraftKey) {
941 return;
942 }
943 updateComposerDraftSettings(selectedProjectDraftKey, {
944 workspaceSelection: {
945 mode: workspaceMode,
946 branch: selectedBranchName,
947 worktreePath: selectedWorktreePath,
948 startFromOrigin: value,
949 },
950 });
951 },
952 [selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, workspaceMode],
953 );
954
955 const refreshBranches = branchState.refresh;
956 const loadMoreBranches = branchState.loadNext;
957 const loadBranches = useCallback(() => {
958 if (!selectedProject) {
959 return;
960 }
961 setPendingConnectionError(null);
962 refreshBranches();
963 }, [refreshBranches, selectedProject]);
964
965 useEffect(() => {
966 if (
967 !selectedProjectDraftKey ||
968 !defaultWorkspaceModeSettled ||
969 workspaceMode !== "worktree" ||
970 selectedBranchName !== null
971 ) {
972 return;
973 }
974 // The draft screen writes a thread's branch and worktree into the draft in
975 // the same commit this effect runs, so the rendered selection above can be
976 // stale. Re-read the draft before replacing it.
977 const live = getComposerDraftSnapshot(selectedProjectDraftKey).workspaceSelection;
978 if (live && (live.mode !== "worktree" || live.branch !== null)) {
979 return;
980 }
981 // The default may only exist as origin/<default> (isRemote), which
982 // availableBranches filters out — search the unfiltered refs for it.
983 const preferredBranch =
984 allBranchRefs.find((branch) => branch.isDefault) ??
985 availableBranches.find((branch) => branch.current) ??
986 null;
987 if (preferredBranch) {
988 selectBranch(preferredBranch);
989 }
990 }, [
991 allBranchRefs,
992 availableBranches,
993 defaultWorkspaceModeSettled,
994 selectBranch,
995 selectedBranchName,
996 selectedProjectDraftKey,
997 workspaceMode,
998 ]);
999
1000 const setRuntimeMode = useCallback(
1001 (value: RuntimeMode) => {
1002 if (selectedProjectDraftKey) {
1003 updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
1004 }
1005 },
1006 [selectedProjectDraftKey],
1007 );
1008 const setInteractionMode = useCallback(
1009 (value: ProviderInteractionMode) => {
1010 if (selectedProjectDraftKey) {
1011 updateComposerDraftSettings(selectedProjectDraftKey, {
1012 interactionMode: resolveProviderInteractionMode(selectedProviderStatus, value),
1013 });
1014 }
1015 },
1016 [selectedProjectDraftKey, selectedProviderStatus],
1017 );
1018
1019 const beginEditingPendingTask = useCallback((messageId: string): boolean => {
1020 const message = findQueuedPendingTask(messageId);
1021 if (!message?.creation) {
1022 return false;
1023 }
1024 const draftKey = pendingTaskDraftKey(message.messageId);
1025 if (isComposerDraftEmpty(getComposerDraftSnapshot(draftKey))) {
1026 setComposerDraftText(draftKey, message.text);
1027 setComposerDraftContext(draftKey, message.context);
1028 replaceComposerDraftAttachments(draftKey, message.attachments);
1029 updateComposerDraftSettings(draftKey, {
1030 modelSelection: message.modelSelection,
1031 runtimeMode: message.runtimeMode,
1032 interactionMode: message.interactionMode,
1033 workspaceSelection: {
1034 mode: message.creation.workspaceMode,
1035 branch: message.creation.branch,
1036 worktreePath: message.creation.worktreePath,
1037 startFromOrigin: message.creation.startFromOrigin ?? false,
1038 pullRequestReference: message.creation.pullRequestReference,
1039 },
1040 });
1041 }
1042 setSelectedEnvironmentId(message.environmentId);
1043 setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId));
1044 activeEditingMessageId = message.messageId;
1045 editingPendingTaskRef.current = message;
1046 editingRevisionRef.current = capturePendingTaskEditorWriteBaseline(message.messageId);
1047 setEditingPendingTask(message);
1048 holdEditingQueuedMessage(message.messageId);
1049 return true;
1050 }, []);
1051
1052 const buildPendingTaskMessage = useCallback(
1053 (
1054 metadata: TurnCommandMetadata,
1055 options?: { readonly currentCheckoutBranch?: string | null },
1056 ): QueuedThreadMessage | null => {
1057 if (!selectedProject || !selectedProjectDraftKey) {
1058 return null;
1059 }
1060 const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
1061 const text = draft.text.trim();
1062 const draftModelSelection =
1063 resolveSelectableModelSelection(
1064 selectedEnvironmentServerConfig,
1065 draft.modelSelection ?? null,
1066 selectedProject.id,
1067 ) ?? selectedModel;
1068 if ((text.length === 0 && draft.attachments.length === 0) || !draftModelSelection) {
1069 return null;
1070 }
1071 const workspaceSelection = canChooseWorkspace ? draft.workspaceSelection : undefined;
1072 const mode = workspaceSelection?.mode ?? workspaceMode;
1073 // When the selection is the stand-in built from the queued snapshot,
1074 // persist the original (possibly absent) snapshot values — the
1075 // stand-in's placeholder title/workspaceRoot must never be written back
1076 // as if they were real project metadata.
1077 const usingPendingSnapshot = selectedProject === editingPendingProject;
1078 const projectTitle = usingPendingSnapshot
1079 ? editingPendingTask?.creation?.projectTitle
1080 : selectedProject.title;
1081 const projectCwd = usingPendingSnapshot
1082 ? editingPendingTask?.creation?.projectCwd
1083 : selectedProject.workspaceRoot;
1084 return {
1085 environmentId: selectedProject.environmentId,
1086 threadId: ThreadId.make(metadata.threadId),
1087 messageId: MessageId.make(metadata.messageId),
1088 commandId: CommandId.make(metadata.commandId),
1089 text,
1090 attachments: draft.attachments,
1091 context: draft.context,
1092 modelSelection: draftModelSelection,
1093 runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
1094 interactionMode: resolvePendingTaskInteractionMode({
1095 preferenceLoaded: planModePreferenceLoaded,
1096 planModeEnabled: legacyPlanModeEnabled,
1097 draftInteractionMode: draft.interactionMode,
1098 queuedInteractionMode: editingPendingTask?.interactionMode,
1099 provider: selectedEnvironmentServerConfig?.providers.find(
1100 (candidate) => candidate.instanceId === draftModelSelection.instanceId,
1101 ),
1102 }),
1103 creation: {
1104 projectId: selectedProject.id,
1105 ...(projectTitle !== undefined ? { projectTitle } : {}),
1106 ...(projectCwd !== undefined ? { projectCwd } : {}),
1107 workspaceMode: mode,
1108 ...(mode === "worktree" && workspaceSelection?.pullRequestReference
1109 ? { pullRequestReference: workspaceSelection.pullRequestReference }
1110 : {}),
1111 // An explicit picker choice wins. Otherwise only a task sending now
1112 // records the current checkout: a queued local task drains days
1113 // later against whatever is checked out then, so a queue-time
1114 // guess would pin a stale label to a thread that ran somewhere else.
1115 branch: resolveProjectThreadCreationBranch({
1116 workspaceMode: mode,
1117 selectedBranch: workspaceSelection?.branch ?? null,
1118 currentCheckoutBranch: options?.currentCheckoutBranch ?? null,
1119 }),
1120 worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
1121 ...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
1122 ? { startFromOrigin: true }
1123 : {}),
1124 },
1125 createdAt: metadata.createdAt,
1126 };
1127 },
1128 [
1129 canChooseWorkspace,
1130 defaultRuntimeMode,
1131 editingPendingProject,
1132 editingPendingTask,
1133 selectedEnvironmentServerConfig,
1134 selectedModel,
1135 selectedProject,
1136 selectedProjectDraftKey,
1137 legacyPlanModeEnabled,
1138 planModePreferenceLoaded,
1139 startFromOrigin,
1140 workspaceMode,
1141 ],
1142 );
1143
1144 const finishEditingPendingTask = useCallback(() => {
1145 const editing = editingPendingTaskRef.current;
1146 editingPendingTaskRef.current = null;
1147 if (editing) {
1148 if (activeEditingMessageId === editing.messageId) {
1149 activeEditingMessageId = null;
1150 }
1151 clearComposerDraft(pendingTaskDraftKey(editing.messageId));
1152 releaseEditingQueuedMessage(editing.messageId);
1153 scheduleUnusedComposerAttachmentCleanup(editing.attachments);
1154 }
1155 setEditingPendingTask(null);
1156 }, []);
1157
1158 // If the queued task disappears mid-edit (deleted from the list, or
1159 // delivered), end the editing session immediately without saving — a later
1160 // flush must not resurrect it, and the composer should fall back to the
1161 // regular per-project draft.
1162 const queuedMessagesByThreadKey = useThreadOutboxMessages();
1163 useEffect(() => {
1164 const editing = editingPendingTaskRef.current;
1165 if (!editing) {
1166 return;
1167 }
1168 const stillQueued = flattenQueuedThreadMessages(queuedMessagesByThreadKey).some(
1169 (candidate) => candidate.messageId === editing.messageId,
1170 );
1171 if (!stillQueued) {
1172 finishEditingPendingTask();
1173 }
1174 }, [finishEditingPendingTask, queuedMessagesByThreadKey]);
1175
1176 const editingFlushRef = useRef<(() => void) | null>(null);
1177 useEffect(() => {
1178 editingFlushRef.current = () => {
1179 const editing = editingPendingTaskRef.current;
1180 if (!editing) {
1181 return;
1182 }
1183 editingPendingTaskRef.current = null;
1184 setEditingPendingTask(null);
1185 if (activeEditingMessageId === editing.messageId) {
1186 activeEditingMessageId = null;
1187 }
1188
1189 const message = buildPendingTaskMessage({
1190 threadId: editing.threadId,
1191 commandId: editing.commandId,
1192 messageId: editing.messageId,
1193 createdAt: editing.createdAt,
1194 });
1195
1196 if (!message) {
1197 // The edits are currently unsendable (e.g. the prompt was cleared).
1198 // Keep both the draft and the drain lock: the stale queued payload
1199 // must not auto-send content the user just removed, and reopening the
1200 // task resumes from the saved draft.
1201 return;
1202 }
1203
1204 // The write handoff lets a reopened editor follow this editor's pending
1205 // save. Its CAS still rejects unrelated queue edits, deletes, and
1206 // deliveries, so the flush cannot resurrect or overwrite them.
1207 void flushPendingTaskEditorWrite({
1208 message,
1209 baseline: editingRevisionRef.current,
1210 draftKey: pendingTaskDraftKey(editing.messageId),
1211 })
1212 .then((savedDraftStillCurrent) => {
1213 if (activeEditingMessageId === editing.messageId) {
1214 return;
1215 }
1216 if (!savedDraftStillCurrent) {
1217 return;
1218 }
1219 clearComposerDraft(pendingTaskDraftKey(editing.messageId));
1220 releaseEditingQueuedMessage(editing.messageId);
1221 scheduleUnusedComposerAttachmentCleanup(editing.attachments);
1222 })
1223 .catch((error) => {
1224 // Keep the drain lock and the draft: delivering the stale payload
1225 // would silently drop the newer edits. Reopening the task retries.
1226 console.warn("[new-task] failed to save edited pending task", error);
1227 });
1228 };
1229 }, [buildPendingTaskMessage]);
1230 const cancelEditingPendingTask = useCallback(() => {
1231 editingFlushRef.current?.();
1232 }, []);
1233 useEffect(
1234 () => () => {
1235 editingFlushRef.current?.();
1236 },
1237 [],
1238 );
1239
1240 const value = useMemo<NewTaskFlowContextValue>(
1241 () => ({
1242 projectScopes,
1243 selectedEnvironmentId,
1244 selectedProjectKey,
1245 selectedModelKey,
1246 workspaceMode,
1247 canChooseWorkspace,
1248 selectedBranchName,
1249 selectedWorktreePath,
1250 startFromOrigin,
1251 draftKey: selectedProjectDraftKey,
1252 pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
1253 editingPendingTask,
1254 prompt,
1255 attachments,
1256 submitting,
1257 branchQuery,
1258 branchesLoading,
1259 branchesError: branchState.error,
1260 branchesFetchingNextPage,
1261 hasMoreBranches,
1262 availableBranches,
1263 currentCheckoutBranchName,
1264 runtimeMode,
1265 interactionMode,
1266 planModeEnabled,
1267 expandedProvider,
1268 environments,
1269 selectedProject,
1270 isScratchDraft,
1271 modelOptions,
1272 selectedModel,
1273 selectedModelOption,
1274 selectedProviderStatus,
1275 providerGroups,
1276 filteredBranches,
1277 reset,
1278 setProject,
1279 openDraft,
1280 selectEnvironment,
1281 switchEnvironment,
1282 switchingToEnvironmentId,
1283 setSelectedModelKey,
1284 setWorkspaceMode,
1285 selectBranch,
1286 setStartFromOrigin,
1287 beginEditingPendingTask,
1288 finishEditingPendingTask,
1289 cancelEditingPendingTask,
1290 buildPendingTaskMessage,
1291 setPrompt,
1292 replaceAttachments,
1293 appendAttachments,
1294 removeAttachment,
1295 clearAttachments,
1296 setSubmitting,
1297 setBranchQuery,
1298 loadBranches,
1299 loadMoreBranches,
1300 setRuntimeMode,
1301 setInteractionMode,
1302 setSelectedModelOptions,
1303 setExpandedProvider,
1304 }),
1305 [
1306 attachments,
1307 availableBranches,
1308 beginEditingPendingTask,
1309 branchQuery,
1310 branchesLoading,
1311 branchState.error,
1312 branchesFetchingNextPage,
1313 buildPendingTaskMessage,
1314 cancelEditingPendingTask,
1315 currentCheckoutBranchName,
1316 editingPendingTask,
1317 environments,
1318 expandedProvider,
1319 filteredBranches,
1320 finishEditingPendingTask,
1321 interactionMode,
1322 isScratchDraft,
1323 planModeEnabled,
1324 loadBranches,
1325 loadMoreBranches,
1326 projectScopes,
1327 modelOptions,
1328 prompt,
1329 providerGroups,
1330 replaceAttachments,
1331 reset,
1332 runtimeMode,
1333 selectedBranchName,
1334 hasMoreBranches,
1335 selectedEnvironmentId,
1336 selectedModel,
1337 selectedModelKey,
1338 selectedModelOption,
1339 selectedProjectDraftKey,
1340 selectedProviderStatus,
1341 setSelectedModelOptions,
1342 selectedProject,
1343 selectedProjectDraft.workspaceSelection?.pullRequestReference,
1344 selectedProjectKey,
1345 selectedWorktreePath,
1346 setProject,
1347 openDraft,
1348 selectBranch,
1349 selectEnvironment,
1350 switchEnvironment,
1351 switchingToEnvironmentId,
1352 setInteractionMode,
1353 setPrompt,
1354 setRuntimeMode,
1355 setSelectedModelKey,
1356 setStartFromOrigin,
1357 setWorkspaceMode,
1358 startFromOrigin,
1359 submitting,
1360 workspaceMode,
1361 canChooseWorkspace,
1362 appendAttachments,
1363 clearAttachments,
1364 removeAttachment,
1365 ],
1366 );
1367
1368 return <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>;
1369}
1370
1371export function useNewTaskFlow() {
1372 const value = React.use(NewTaskFlowContext);
1373 if (value === null) {
1374 throw new Error("useNewTaskFlow must be used within NewTaskFlowProvider.");
1375 }
1376 return value;
1377}