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

new-task-flow-provider.tsx

1,246 lines46.0 KB

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