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

new-task-flow-provider.tsx

1,295 lines48.0 KB

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