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

new-task-flow-provider.tsx

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