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

new-task-flow-provider.tsx

1,188 lines43.4 KB

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