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