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