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