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

new-task-flow-provider.tsx

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