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