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

new-task-flow-provider.tsx

960 lines34.3 KB

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