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