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

new-task-flow-provider.tsx

1,336 lines49.4 KB

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