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

new-task-flow-provider.tsx

1,141 lines42.0 KB

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