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