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

new-task-flow-provider.tsx

1,228 lines44.3 KB

1import { ActiveNewTaskContext } from "../../state/active-new-task";
2import * as Dialog from "../../components/ui/Dialog";
3import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
4import { useEnvironmentPresentation } from "../../state/presentation";
5import { environmentSession } from "../../state/session";
6import React, { useCallback, useEffect, useRef, useState } from "react";
7​
8import type {
9 EnvironmentId,
10 ModelSelection,
11 ProjectReadFileResult,
12 ProviderInteractionMode,
13 ProviderOptionSelection,
14 RuntimeMode,
15 ServerProvider,
16} from "@t3tools/contracts";
17import {
18 CommandId,
19 DEFAULT_PROVIDER_INTERACTION_MODE,
20 DEFAULT_RUNTIME_MODE,
21 DEFAULT_SERVER_SETTINGS,
22 MessageId,
23 repositoryGroupingKeyOf,
24 T3_PROJECT_FILE_NAME,
25 ThreadId,
26} from "@t3tools/contracts";
27import { sanitizeNewRefName } from "@t3tools/shared/git";
28import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
29import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings";
30import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
31import * as Arr from "effect/Array";
32import { pipe } from "effect/Function";
33​
34import {
35 useEnvironmentServerConfig,
36 useProjects,
37 useServerConfigs,
38 useThreadShells,
39} from "../../state/entities";
40import type { TurnCommandMetadata } from "../../lib/commandMetadata";
41import type { DraftComposerAttachment } from "../../lib/composerImages";
42import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
43import {
44 buildModelOptions,
45 groupByProvider,
46 resolveDefaultableModelSelection,
47 resolveNewTaskModelSelection,
48 resolveSelectableModelSelection,
49} from "../../lib/modelOptions";
50import { scopedProjectKey } from "../../lib/scopedEntities";
51import { appAtomRegistry } from "../../state/atom-registry";
52import { projectEnvironment } from "../../state/projects";
53import { useEnvironmentQuery } from "../../state/query";
54import { useAtomCommand } from "../../state/use-atom-command";
55import {
56 appendComposerDraftAttachments,
57 type ComposerDraftInsertion,
58 clearComposerDraft,
59 composerDraftsAtom,
60 createNewTaskDraft,
61 getComposerDraftSnapshot,
62 isComposerDraftEmpty,
63 isNewTaskDraftKey,
64 removeComposerDraftAttachment,
65 replaceComposerDraftAttachments,
66 retargetNewTaskDraft,
67 scheduleUnusedComposerAttachmentCleanup,
68 setComposerDraftText,
69 setComposerDraftContext,
70 setStickyComposerModelSelection,
71 updateComposerDraftSettings,
72 useComposerDraft,
73 useStickyComposerModelSelection,
74} from "../../state/use-composer-drafts";
75import {
76 capturePendingTaskEditorWriteBaseline,
77 flushPendingTaskEditorWrite,
78} from "../../state/pending-task-editor-writes";
79import {
80 rememberModelOptions,
81 withRememberedModelOptions,
82} from "../../state/use-model-option-memory";
83import { useBranches, useDebouncedValue, usePaginatedBranches } from "../../state/queries";
84import { vcsEnvironment } from "../../state/vcs";
85import {
86 flattenQueuedThreadMessages,
87 threadOutboxManager,
88 type QueuedThreadMessage,
89} from "../../state/thread-outbox";
90import {
91 holdEditingQueuedMessage,
92 releaseEditingQueuedMessage,
93 useThreadOutboxMessages,
94} from "../../state/use-thread-outbox";
95import {
96 setPendingConnectionError,
97 useRemoteConnectionStatus,
98 useSavedRemoteConnections,
99} from "../../state/use-remote-environment-registry";
100import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
101import {
102 isAtomCommandInterrupted,
103 squashAtomCommandFailure,
104} from "@t3tools/client-runtime/state/runtime";
105import { isScratchProject } from "@t3tools/client-runtime/state/projects";
106import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
107import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
108import {
109 buildHomeProjectScopes,
110 sortHomeProjectScopes,
111 type HomeProjectScope,
112} from "../home/homeThreadList";
113import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
114import {
115 resolvePendingTaskInteractionMode,
116 resolveProviderInteractionMode,
117} from "../../state/legacy-plan-mode";
118import { useLegacyPlanModeState } from "./use-legacy-plan-mode-enabled";
119import {
120 filterNewTaskBranches,
121 resolveNewTaskBranchWorktreePath,
122 resolveNewTaskLocalWorkspaceSelection,
123 resolveNewTaskWorkspaceSelection,
124} from "./new-task-context-presentation";
125import { resolveEnvironmentProjectMatch } from "./new-task-project-selection";
126import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
127import { useOlderSettledCount } from "../../state/olderSettledShelf";
128​
129type WorkspaceMode = "local" | "worktree";
130​
131const BRANCH_SEARCH_DEBOUNCE_MS = 150;
132​
133function pendingTaskDraftKey(messageId: string): string {
134 return `pending-task:${messageId}`;
136​
137// Track ownership across providers so old unmount flushes cannot drop newer drafts or drain locks.
138let activeEditingMessageId: string | null = null;
139​
140function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null {
141 const message = flattenQueuedThreadMessages(
142 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
143 ).find((candidate) => candidate.messageId === messageId);
144 return message?.creation !== undefined ? message : null;
146​
147export function branchBadgeLabel(input: {
148 readonly branch: VcsRef;
149 readonly project: EnvironmentProject | null;
150}): string | null {
151 if (input.branch.current) {
152 return "current";
153 }
154 if (input.branch.worktreePath && input.branch.worktreePath !== input.project?.workspaceRoot) {
155 return "worktree";
156 }
157 if (input.branch.isRemote) {
158 return "remote";
159 }
160 if (input.branch.isDefault) {
161 return "default";
162 }
163 return null;
165​
166type NewTaskFlowContextValue = {
167 readonly activeNewTask: { readonly pendingKey: string | null } | null;
168 readonly projectScopes: ReadonlyArray<HomeProjectScope>;
169 readonly selectedEnvironmentId: EnvironmentId | null;
170 readonly selectedProjectKey: string | null;
171 readonly selectedModelKey: string | null;
172 readonly workspaceMode: WorkspaceMode;
173 readonly isGitRepo: boolean;
174 readonly isGitRepoKnown: boolean;
175 readonly canChooseWorkspace: boolean;
176 readonly selectedBranchName: string | null;
177 readonly selectedWorktreePath: string | null;
178 readonly startFromOrigin: boolean;
179 readonly pullRequestReference: string | undefined;
180 readonly draftKey: string | null;
181 readonly editingPendingTask: QueuedThreadMessage | null;
182 readonly prompt: string;
183 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
184 readonly submitting: boolean;
185 readonly branchQuery: string;
186 readonly branchesLoading: boolean;
187 readonly branchesError: string | null;
188 readonly branchesFetchingNextPage: boolean;
189 readonly hasMoreBranches: boolean;
190 readonly availableBranches: ReadonlyArray<VcsRef>;
191 readonly currentCheckoutBranchName: string | null;
192 readonly runtimeMode: RuntimeMode;
193 readonly interactionMode: ProviderInteractionMode;
194 readonly planModeEnabled: boolean;
195 readonly expandedProvider: string | null;
196 readonly environments: ReadonlyArray<{
197 readonly environmentId: EnvironmentId;
198 readonly environmentLabel: string;
199 }>;
200 readonly selectedProject: EnvironmentProject | null;
201 readonly isScratchDraft: boolean;
202 readonly modelOptions: ReadonlyArray<ModelOption>;
203 readonly selectedModel: ModelSelection | null;
204 readonly selectedModelOption: ModelOption | null;
205 readonly selectedProviderStatus: ServerProvider | null;
206 readonly providerGroups: ReadonlyArray<ProviderGroup>;
207 readonly filteredBranches: ReadonlyArray<VcsRef>;
208 readonly reset: () => void;
209 readonly setProject: (project: EnvironmentProject) => void;
210 /** Returns false if the existing draft is gone, allowing fallback to a fresh draft. */
211 readonly openDraft: (draftKey: string) => boolean;
212 readonly selectEnvironment: (environmentId: EnvironmentId) => void;
213 readonly switchEnvironment: (environmentId: EnvironmentId) => Promise<boolean>;
214 readonly switchingToEnvironmentId: EnvironmentId | null;
215 readonly setSelectedModelKey: (
216 key: string | null,
217 options?: ReadonlyArray<ProviderOptionSelection>,
218 ) => void;
219 readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
220 readonly selectBranch: (branch: VcsRef) => void;
221 readonly setStartFromOrigin: (value: boolean) => void;
222 readonly beginEditingPendingTask: (messageId: string) => boolean;
223 readonly finishEditingPendingTask: () => void;
224 readonly cancelEditingPendingTask: () => void;
225 readonly buildPendingTaskMessage: (
226 metadata: TurnCommandMetadata,
227 options?: {
228 readonly currentCheckoutBranch?: string | null;
229 },
230 ) => QueuedThreadMessage | null;
231 readonly setPrompt: (value: string) => void;
232 readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => void;
233 /** Appends draft attachments; returns how many the live cap rejected. */
234 readonly appendAttachments: (
235 attachments: ReadonlyArray<DraftComposerAttachment>,
236 insertion?: ComposerDraftInsertion,
237 ) => number;
238 readonly removeAttachment: (imageId: string) => void;
239 readonly clearAttachments: () => void;
240 readonly setSubmitting: (value: boolean) => void;
241 readonly setBranchQuery: (value: string) => void;
242 readonly loadBranches: () => void;
243 readonly loadMoreBranches: () => void;
244 readonly setRuntimeMode: (value: RuntimeMode) => void;
245 readonly setInteractionMode: (value: ProviderInteractionMode) => void;
246 readonly setSelectedModelOptions: (
247 value: ReadonlyArray<ProviderOptionSelection> | undefined,
248 ) => void;
249 readonly setExpandedProvider: (value: string | null) => void;
250};
251​
252const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null);
253​
254export function NewTaskFlowProvider(
255 props: React.PropsWithChildren<{
256 active?: boolean;
257 routeDraftId?: string;
258 routePendingTaskId?: string;
259 }>,
260) {
261 const projects = useProjects();
262 const threads = useThreadShells();
263 const { savedConnectionsById } = useSavedRemoteConnections();
264 const groupingSettings = useMobileProjectGroupingSettings();
265 const { enabled: legacyPlanModeEnabled, loaded: planModePreferenceLoaded } =
266 useLegacyPlanModeState();
267​
268 const projectScopes = sortHomeProjectScopes({
269 scopes: buildHomeProjectScopes({
270 projects,
271 environmentId: null,
272 projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
273 }),
274 threads,
275 pendingTasks: [],
276 projectSortOrder: "updated_at",
277 });
278​
279 const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
280 null,
281 );
282 const selectedEnvironmentId =
283 selectedEnvironmentIdOverride !== null &&
284 projects.some((project) => project.environmentId === selectedEnvironmentIdOverride)
285 ? selectedEnvironmentIdOverride
286 : (projects[0]?.environmentId ?? null);
287 const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
288 const [activeDraftKey, setActiveDraftKey] = useState<string | null>(null);
289 const [submitting, setSubmitting] = useState(false);
290 const [branchQuery, setBranchQuery] = useState("");
291 const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
292 const [editingPendingTask, setEditingPendingTask] = useState<QueuedThreadMessage | null>(null);
293 const pendingLocalBranchSyncDraftKeysRef = useRef(new Set<string>());
294 // Mirror edit state synchronously so unmount flush cannot save a session ended this render.
295 const editingPendingTaskRef = useRef<QueuedThreadMessage | null>(null);
296 const editingRevisionRef = useRef(Promise.resolve(0));
297​
298 const reset = useCallback(() => {
299 setSelectedEnvironmentId(null);
300 setSelectedProjectKey(null);
301 setActiveDraftKey(null);
302 setSubmitting(false);
303 setBranchQuery("");
304 setExpandedProvider(null);
305 pendingLocalBranchSyncDraftKeysRef.current.clear();
306 const editing = editingPendingTaskRef.current;
307 editingPendingTaskRef.current = null;
308 setEditingPendingTask(null);
309 if (editing) {
310 if (activeEditingMessageId === editing.messageId) {
311 activeEditingMessageId = null;
312 }
313 releaseEditingQueuedMessage(editing.messageId);
314 }
315 }, []);
316​
317 const projectsForEnvironment = pipe(
318 projects,
319 Arr.filter((project) => project.environmentId === selectedEnvironmentId),
320 );
321​
322 const editingPendingProject = ((): EnvironmentProject | null => {
323 const creation = editingPendingTask?.creation;
324 if (!editingPendingTask || !creation) {
325 return null;
326 }
327 return {
328 environmentId: editingPendingTask.environmentId,
329 id: creation.projectId,
330 title: creation.projectTitle ?? "Unknown project",
331 workspaceRoot: creation.projectCwd ?? "",
332 repositoryIdentity: null,
333 defaultModelSelection: editingPendingTask.modelSelection ?? null,
334 scripts: [],
335 createdAt: editingPendingTask.createdAt,
336 updatedAt: editingPendingTask.createdAt,
337 };
338 })();
339​
340 const selectedProject =
341 projectsForEnvironment.find(
342 (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
343 ) ??
344 // Pin queued edits to their original project when its shell is missing; fallback would silently retarget them.
345 (editingPendingProject !== null &&
346 selectedProjectKey ===
347 scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id)
348 ? editingPendingProject
349 : (projectsForEnvironment[0] ?? null));
350​
351 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
352 selectedProject?.environmentId ?? null,
353 );
354 const isScratchDraft =
355 selectedProject !== null &&
356 isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot);
357 const serverConfigs = useServerConfigs();
358 const { connectedEnvironments } = useRemoteConnectionStatus();
359 const scratchEnvironments = connectedEnvironments.filter(
360 (environment) =>
361 availableScratchWorkspaceRoot(
362 environment.connectionState,
363 serverConfigs.get(environment.environmentId),
364 ) !== null,
365 );
366​
367 const selectedRepositoryKey = selectedProject?.repositoryIdentity
368 ? repositoryGroupingKeyOf(selectedProject.repositoryIdentity)
369 : null;
370 // Use || null: placeholder workspaceRoot can be empty, and an empty basename rejects real hosts.
371 const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;
372 const selectedProjectTitle = selectedProject?.title ?? null;
373 const environments = (() => {
374 if (isScratchDraft) {
375 return scratchEnvironments.map((environment) => ({
376 environmentId: environment.environmentId,
377 environmentLabel: environment.environmentLabel,
378 }));
379 }
380 const seen = new Set<EnvironmentId>();
381 const result: Array<{
382 readonly environmentId: EnvironmentId;
383 readonly environmentLabel: string;
384 }> = [];
385 const hostsSelectedRepository = (project: EnvironmentProject) => {
386 if (selectedRepositoryKey === null && selectedWorkspaceBasename === null) {
387 return true;
388 }
389 const projectKey = project.repositoryIdentity
390 ? repositoryGroupingKeyOf(project.repositoryIdentity)
391 : null;
392 if (selectedRepositoryKey !== null && projectKey !== null) {
393 return projectKey === selectedRepositoryKey;
394 }
395 return (
396 project.workspaceRoot.split("/").at(-1) === selectedWorkspaceBasename ||
397 (selectedProjectTitle !== null && project.title === selectedProjectTitle)
398 );
399 };
400 for (const project of projects) {
401 if (!hostsSelectedRepository(project)) {
402 continue;
403 }
404 if (seen.has(project.environmentId)) {
405 continue;
406 }
407 const environment = savedConnectionsById[project.environmentId];
408 if (!environment) {
409 continue;
410 }
411 seen.add(project.environmentId);
412 result.push({
413 environmentId: project.environmentId,
414 environmentLabel: environment.environmentLabel,
415 });
416 }
417 return result;
418 })();
419​
420 const selectedProjectDraftKey = editingPendingTask
421 ? pendingTaskDraftKey(editingPendingTask.messageId)
422 : selectedProject
423 ? activeDraftKey
424 : null;
425 useEffect(() => {
426 if (
427 props.active === false ||
428 activeDraftKey !== null ||
429 editingPendingTask !== null ||
430 selectedProject === null
431 ) {
432 return;
433 }
434 setActiveDraftKey(
435 createNewTaskDraft({
436 environmentId: selectedProject.environmentId,
437 projectId: selectedProject.id,
438 }),
439 );
440 }, [activeDraftKey, editingPendingTask, selectedProject, props.active]);
441 const activePendingKey =
442 props.active === false
443 ? null
444 : props.routePendingTaskId
445 ? `pending-task:${props.routePendingTaskId}`
446 : props.routeDraftId
447 ? `draft-task:${props.routeDraftId}`
448 : editingPendingTask
449 ? `pending-task:${editingPendingTask.messageId}`
450 : selectedProjectDraftKey
451 ? `draft-task:${selectedProjectDraftKey}`
452 : null;
453 const activeNewTask = React.useMemo(
454 () => (props.active === false ? null : { pendingKey: activePendingKey }),
455 [props.active, activePendingKey],
456 );
457 const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
458 const prompt = selectedProjectDraft.text;
459 const attachments = selectedProjectDraft.attachments;
460 const projectGitStatus = useEnvironmentQuery(
461 selectedProject !== null && selectedProject.workspaceRoot !== ""
462 ? vcsEnvironment.status({
463 environmentId: selectedProject.environmentId,
464 input: { cwd: selectedProject.workspaceRoot },
465 })
466 : null,
467 );
468 const currentCheckoutBranchName = projectGitStatus.data?.refName ?? null;
469 // The unfiltered ref list also provides repository capability while offline.
470 const projectBranches = useBranches({
471 environmentId: selectedProject?.environmentId ?? null,
472 cwd: selectedProject?.workspaceRoot || null,
473 });
474 const knownIsGitRepo = projectGitStatus.data?.isRepo ?? projectBranches.data?.isRepo ?? null;
475 const isGitRepo = knownIsGitRepo ?? true;
476 const fileAccessSession = useEnvironmentQuery(
477 selectedProject !== null && selectedProject.workspaceRoot !== ""
478 ? environmentSession.sessionStateAtom(selectedProject.environmentId)
479 : null,
480 );
481 const fileEnvironment = useEnvironmentPresentation(selectedProject?.environmentId ?? null);
482 const fileAccess = resolveFilesystemReadAccess({
483 isCatalogReady: fileEnvironment.isReady,
484 connection: fileEnvironment.presentation?.connection ?? null,
485 session: fileAccessSession.data,
486 sessionError: fileAccessSession.error,
487 });
488 const { canReadFiles } = fileAccess;
489 const fileAccessPending =
490 selectedProject !== null && selectedProject.workspaceRoot !== "" && fileAccess.isPending;
491 const t3ProjectFileQuery = useEnvironmentQuery(
492 canReadFiles && selectedProject !== null && selectedProject.workspaceRoot !== ""
493 ? projectEnvironment.readFile({
494 environmentId: selectedProject.environmentId,
495 input: {
496 cwd: selectedProject.workspaceRoot,
497 relativePath: T3_PROJECT_FILE_NAME,
498 allowMissing: true,
499 },
500 })
501 : null,
502 );
503 const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
504 const t3ProjectFile =
505 t3ProjectFileData === null || t3ProjectFileData.exists === false || t3ProjectFileData.truncated
506 ? null
507 : parseT3ProjectFile(t3ProjectFileData.contents);
508 const projectSettings = resolveProjectSettings(
509 selectedEnvironmentServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
510 selectedProject?.id ?? null,
511 selectedProject,
512 t3ProjectFile,
513 );
514 const canChooseWorkspace = !isScratchDraft;
515 const selectedProjectOlderSettledCount = useOlderSettledCount(selectedProject);
516 const selectedProjectHasThreads =
517 selectedProject !== null &&
518 (selectedProjectOlderSettledCount > 0 ||
519 threads.some(
520 (thread) =>
521 thread.environmentId === selectedProject.environmentId &&
522 thread.projectId === selectedProject.id,
523 ));
524 const defaultWorkspaceMode: WorkspaceMode = canChooseWorkspace
525 ? resolveNewThreadEnvMode({
526 projectSettings,
527 workspaceRoot: selectedProject?.workspaceRoot ?? null,
528 newProjectsRoot: selectedEnvironmentServerConfig?.newProjectsRoot,
529 projectHasThreads: selectedProjectHasThreads,
530 })
531 : "local";
532 // Do not persist the provisional workspace default while t3.json is loading; it would override
533 // the file's eventual default.
534 const defaultWorkspaceModeSettled =
535 selectedProjectDraft.workspaceSelection?.mode !== undefined ||
536 projectSettings.sources.defaultThreadEnvMode !== "environment" ||
537 (!t3ProjectFileQuery.isPending && !fileAccessPending);
538 const workspaceSelection = resolveNewTaskWorkspaceSelection({
539 selection: canChooseWorkspace ? selectedProjectDraft.workspaceSelection : undefined,
540 fallback: { mode: defaultWorkspaceMode, branch: null, worktreePath: null },
541 isGitRepo,
542 });
543 const workspaceMode = workspaceSelection.mode;
544 const selectedBranchName = workspaceSelection.branch;
545 const selectedWorktreePath = workspaceSelection.worktreePath;
546 // Keep the user's explicit choice separate from the resolved display value:
547 // only the explicit flag is ever written back to the draft, so the resolved
548 // value keeps tracking the server setting when the config loads late.
549 const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
550 const startFromOrigin =
551 isGitRepo && (draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin);
552 const defaultRuntimeMode = editingPendingTask
553 ? (editingPendingTask.runtimeMode ?? DEFAULT_RUNTIME_MODE)
554 : projectSettings.settings.defaultRuntimeMode;
555 const runtimeMode = selectedProjectDraft.runtimeMode ?? defaultRuntimeMode;
556​
557 // Antigravity keeps unavailable selections so sign-out or a catalog change
558 // cannot switch the user's model.
559 const draftModelSelection = resolveSelectableModelSelection(
560 selectedEnvironmentServerConfig,
561 selectedProjectDraft.modelSelection ?? null,
562 selectedProject?.id ?? null,
563 );
564 const projectDefaultModelSelection = resolveDefaultableModelSelection(
565 selectedEnvironmentServerConfig,
566 projectSettings.settings.defaultModelSelection,
567 selectedProject?.id ?? null,
568 );
569 const storedStickyModelSelection = useStickyComposerModelSelection();
570 const stickyModelSelection = resolveDefaultableModelSelection(
571 selectedEnvironmentServerConfig,
572 storedStickyModelSelection,
573 selectedProject?.id ?? null,
574 );
575 const modelOptions = buildModelOptions(
576 selectedEnvironmentServerConfig,
577 draftModelSelection ?? projectDefaultModelSelection ?? stickyModelSelection,
578 undefined,
579 selectedProject?.id ?? null,
580 );
581​
582 const selectedModel = resolveNewTaskModelSelection({
583 draftSelection: draftModelSelection,
584 projectDefaultSelection: projectDefaultModelSelection,
585 stickySelection: stickyModelSelection,
586 modelOptions,
587 });
588 const selectedModelKey = selectedModel
589 ? `${selectedModel.instanceId}:${selectedModel.model}`
590 : null;
591​
592 const selectedModelOption =
593 modelOptions.find(
594 (option) =>
595 selectedModel &&
596 option.selection.instanceId === selectedModel.instanceId &&
597 option.selection.model === selectedModel.model,
598 ) ?? null;
599 const selectedProviderStatus =
600 selectedEnvironmentServerConfig?.providers.find(
601 (provider) => provider.instanceId === selectedModel?.instanceId,
602 ) ?? null;
603 const planModeEnabled =
604 legacyPlanModeEnabled && selectedProviderStatus?.showInteractionModeToggle !== false;
605 const interactionMode = planModeEnabled
606 ? (selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE)
607 : DEFAULT_PROVIDER_INTERACTION_MODE;
608 const setSelectedModelKey = (
609 key: string | null,
610 options?: ReadonlyArray<ProviderOptionSelection>,
611 ) => {
612 if (!key || !selectedProjectDraftKey) {
613 return;
614 }
615 const option = modelOptions.find((candidate) => candidate.key === key);
616 if (!option) {
617 return;
618 }
619 const selection = withRememberedModelOptions(
620 options ? { ...option.selection, options } : option.selection,
621 );
622 const provider = selectedEnvironmentServerConfig?.providers.find(
623 (candidate) => candidate.instanceId === selection.instanceId,
624 );
625 updateComposerDraftSettings(selectedProjectDraftKey, {
626 modelSelection: selection,
627 ...(provider?.showInteractionModeToggle === false
628 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
629 : {}),
630 });
631 setStickyComposerModelSelection(selection);
632 };
633 const setSelectedModelOptions = (options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
634 if (!selectedModel || !selectedProjectDraftKey) {
635 return;
636 }
637 rememberModelOptions(selectedModel.instanceId, selectedModel.model, options ?? []);
638 const nextSelection: ModelSelection = options
639 ? { ...selectedModel, options }
640 : {
641 instanceId: selectedModel.instanceId,
642 model: selectedModel.model,
643 };
644 updateComposerDraftSettings(selectedProjectDraftKey, {
645 modelSelection: nextSelection,
646 });
647 setStickyComposerModelSelection(nextSelection);
648 };
649​
650 const providerGroups = groupByProvider(modelOptions);
651 const setPrompt = (value: string) => {
652 if (!selectedProjectDraftKey) {
653 return;
654 }
655 setComposerDraftText(selectedProjectDraftKey, value);
656 };
657 const replaceAttachments = (nextAttachments: ReadonlyArray<DraftComposerAttachment>) => {
658 if (!selectedProjectDraftKey) {
659 return;
660 }
661 replaceComposerDraftAttachments(selectedProjectDraftKey, nextAttachments);
662 };
663 const appendAttachments = (
664 nextAttachments: ReadonlyArray<DraftComposerAttachment>,
665 insertion?: ComposerDraftInsertion,
666 ): number => {
667 if (!selectedProjectDraftKey) {
668 return 0;
669 }
670 return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments, {
671 appendReference: true,
672 insertion,
673 });
674 };
675 const removeAttachment = (imageId: string) => {
676 if (!selectedProjectDraftKey) {
677 return;
678 }
679 removeComposerDraftAttachment(selectedProjectDraftKey, imageId);
680 };
681 const clearAttachments = () => {
682 if (!selectedProjectDraftKey) {
683 return;
684 }
685 replaceComposerDraftAttachments(selectedProjectDraftKey, []);
686 };
687 const branchSearchQuery = sanitizeNewRefName(branchQuery);
688 const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
689 const branchTarget = {
690 environmentId: selectedProject?.environmentId ?? null,
691 cwd: selectedProject?.workspaceRoot || null,
692 query: debouncedBranchQuery,
693 };
694 const branchState = usePaginatedBranches(branchTarget);
695 const branchSearchIsDebouncing = branchSearchQuery !== debouncedBranchQuery;
696 const branchesLoading =
697 branchSearchIsDebouncing || (branchState.isPending && branchState.data === null);
698 const branchesFetchingNextPage = branchState.isFetchingNextPage;
699 const hasMoreBranches =
700 branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined;
701 const allBranchRefs = branchState.refs;
702 const availableBranches = pipe(
703 allBranchRefs,
704 Arr.filter((branch) => !branch.isRemote),
705 );
706​
707 const filteredBranches = filterNewTaskBranches(allBranchRefs, branchQuery);
708​
709 const carryDraftContentTo = (project: EnvironmentProject) => {
710 const target = { environmentId: project.environmentId, projectId: project.id };
711 if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) {
712 retargetNewTaskDraft(activeDraftKey, target);
713 } else if (!editingPendingTaskRef.current) {
714 setActiveDraftKey(createNewTaskDraft(target));
715 }
716 };
717​
718 const setProject = (project: EnvironmentProject) => {
719 carryDraftContentTo(project);
720 setSelectedEnvironmentId(project.environmentId);
721 setSelectedProjectKey(scopedProjectKey(project.environmentId, project.id));
722 };
723​
724 const openDraft = (draftKey: string): boolean => {
725 const draft = appAtomRegistry.get(composerDraftsAtom)[draftKey];
726 const stamp = draft?.project;
727 if (!isNewTaskDraftKey(draftKey) || !stamp) {
728 return false;
729 }
730 // Require the stamped project to load; selectedProject otherwise falls back and retargets the draft.
731 const projectLoaded = projects.some(
732 (project) => project.environmentId === stamp.environmentId && project.id === stamp.projectId,
733 );
734 if (!projectLoaded) {
735 return false;
736 }
737 setActiveDraftKey(draftKey);
738 setSelectedEnvironmentId(stamp.environmentId);
739 setSelectedProjectKey(scopedProjectKey(stamp.environmentId, stamp.projectId));
740 return true;
741 };
742​
743 const selectEnvironment = (environmentId: EnvironmentId) => {
744 const match = resolveEnvironmentProjectMatch(
745 projects.filter((project) => project.environmentId === environmentId),
746 selectedProject,
747 );
748 if (match) {
749 carryDraftContentTo(match);
750 }
751 setSelectedEnvironmentId(environmentId);
752 setSelectedProjectKey(match ? scopedProjectKey(match.environmentId, match.id) : null);
753 };
754​
755 const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
756 const [switchingToEnvironmentId, setSwitchingToEnvironmentId] = useState<EnvironmentId | null>(
757 null,
758 );
759 const latestSwitchRef = useRef<object | null>(null);
760 const switchEnvironment = async (environmentId: EnvironmentId): Promise<boolean> => {
761 if (environmentId === selectedEnvironmentId) {
762 latestSwitchRef.current = null;
763 setSwitchingToEnvironmentId(null);
764 return true;
765 }
766 if (!isScratchDraft) {
767 selectEnvironment(environmentId);
768 return true;
769 }
770 const request = {};
771 latestSwitchRef.current = request;
772 setSwitchingToEnvironmentId(environmentId);
773 const result = await openScratch({ environmentId, input: {} });
774 if (latestSwitchRef.current !== request) return false;
775 latestSwitchRef.current = null;
776 setSwitchingToEnvironmentId(null);
777 if (result._tag === "Success") {
778 setProject(result.value);
779 return true;
780 }
781 if (!isAtomCommandInterrupted(result)) {
782 const error = squashAtomCommandFailure(result);
783 Dialog.alert(
784 "Could not switch machine",
785 error instanceof Error
786 ? error.message
787 : "The folder for threads without a project could not be created.",
788 );
789 }
790 return false;
791 };
792​
793 const setWorkspaceMode = (mode: WorkspaceMode) => {
794 if (!selectedProjectDraftKey) {
795 return;
796 }
797 if (!selectedProject) {
798 return;
799 }
800 const localSelection = resolveNewTaskLocalWorkspaceSelection({
801 branches: availableBranches,
802 projectCwd: selectedProject.workspaceRoot,
803 });
804 if (mode === "local" && localSelection.awaitsCurrentBranch) {
805 pendingLocalBranchSyncDraftKeysRef.current.add(selectedProjectDraftKey);
806 } else {
807 pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
808 }
809 updateComposerDraftSettings(selectedProjectDraftKey, {
810 workspaceSelection: {
811 mode,
812 branch: mode === "local" ? localSelection.branch : selectedBranchName,
813 worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath,
814 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
815 },
816 });
817 };
818​
819 useEffect(() => {
820 if (
821 workspaceMode !== "local" ||
822 !selectedProject ||
823 !selectedProjectDraftKey ||
824 !pendingLocalBranchSyncDraftKeysRef.current.has(selectedProjectDraftKey)
825 ) {
826 return;
827 }
828 const localSelection = resolveNewTaskLocalWorkspaceSelection({
829 branches: availableBranches,
830 projectCwd: selectedProject.workspaceRoot,
831 });
832 if (localSelection.awaitsCurrentBranch) {
833 return;
834 }
835​
836 pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
837 updateComposerDraftSettings(selectedProjectDraftKey, {
838 workspaceSelection: {
839 mode: "local",
840 branch: localSelection.branch,
841 worktreePath: localSelection.worktreePath,
842 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
843 },
844 });
845 }, [
846 availableBranches,
847 draftStartFromOrigin,
848 selectedProject,
849 selectedProjectDraftKey,
850 workspaceMode,
851 ]);
852​
853 const selectBranch = (branch: VcsRef) => {
854 if (!selectedProject || !selectedProjectDraftKey) {
855 return;
856 }
857 pendingLocalBranchSyncDraftKeysRef.current.delete(selectedProjectDraftKey);
858 updateComposerDraftSettings(selectedProjectDraftKey, {
859 workspaceSelection: {
860 mode: workspaceMode,
861 branch: branch.name,
862 worktreePath: resolveNewTaskBranchWorktreePath({
863 workspaceMode,
864 projectCwd: selectedProject.workspaceRoot,
865 branchWorktreePath: branch.worktreePath,
866 }),
867 ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
868 },
869 });
870 };
871​
872 const setStartFromOrigin = (value: boolean) => {
873 if (!selectedProjectDraftKey) {
874 return;
875 }
876 updateComposerDraftSettings(selectedProjectDraftKey, {
877 workspaceSelection: {
878 mode: workspaceMode,
879 branch: selectedBranchName,
880 worktreePath: selectedWorktreePath,
881 startFromOrigin: value,
882 },
883 });
884 };
885​
886 const refreshBranches = branchState.refresh;
887 const loadMoreBranches = branchState.loadNext;
888 const loadBranches = () => {
889 if (!selectedProject) {
890 return;
891 }
892 setPendingConnectionError(null);
893 refreshBranches();
894 };
895​
896 useEffect(() => {
897 if (
898 !selectedProjectDraftKey ||
899 !defaultWorkspaceModeSettled ||
900 workspaceMode !== "worktree" ||
901 selectedBranchName !== null
902 ) {
903 return;
904 }
905 // Re-read before replacing: the draft screen can update workspace selection in this same commit.
906 const live = getComposerDraftSnapshot(selectedProjectDraftKey).workspaceSelection;
907 if (live && (live.mode !== "worktree" || live.branch !== null)) {
908 return;
909 }
910 // Search unfiltered refs: the default may exist only as origin/<default>, excluded by availableBranches.
911 const preferredBranch =
912 allBranchRefs.find((branch) => branch.isDefault) ??
913 availableBranches.find((branch) => branch.current) ??
914 null;
915 if (preferredBranch) {
916 selectBranch(preferredBranch);
917 }
918 }, [
919 allBranchRefs,
920 availableBranches,
921 defaultWorkspaceModeSettled,
922 selectBranch,
923 selectedBranchName,
924 selectedProjectDraftKey,
925 workspaceMode,
926 ]);
927​
928 const setRuntimeMode = (value: RuntimeMode) => {
929 if (selectedProjectDraftKey) {
930 updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
931 }
932 };
933 const setInteractionMode = (value: ProviderInteractionMode) => {
934 if (selectedProjectDraftKey) {
935 updateComposerDraftSettings(selectedProjectDraftKey, {
936 interactionMode: resolveProviderInteractionMode(selectedProviderStatus, value),
937 });
938 }
939 };
940​
941 const beginEditingPendingTask = (messageId: string): boolean => {
942 const message = findQueuedPendingTask(messageId);
943 if (!message?.creation) {
944 return false;
945 }
946 const draftKey = pendingTaskDraftKey(message.messageId);
947 if (isComposerDraftEmpty(getComposerDraftSnapshot(draftKey))) {
948 setComposerDraftText(draftKey, message.text);
949 setComposerDraftContext(draftKey, message.context);
950 replaceComposerDraftAttachments(draftKey, message.attachments);
951 updateComposerDraftSettings(draftKey, {
952 modelSelection: message.modelSelection,
953 runtimeMode: message.runtimeMode,
954 interactionMode: message.interactionMode,
955 workspaceSelection: {
956 mode: message.creation.workspaceMode,
957 branch: message.creation.branch,
958 worktreePath: message.creation.worktreePath,
959 startFromOrigin: message.creation.startFromOrigin ?? false,
960 pullRequestReference: message.creation.pullRequestReference,
961 },
962 });
963 }
964 setSelectedEnvironmentId(message.environmentId);
965 setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId));
966 activeEditingMessageId = message.messageId;
967 editingPendingTaskRef.current = message;
968 editingRevisionRef.current = capturePendingTaskEditorWriteBaseline(message.messageId);
969 setEditingPendingTask(message);
970 holdEditingQueuedMessage(message.messageId);
971 return true;
972 };
973​
974 const buildPendingTaskMessage = (
975 metadata: TurnCommandMetadata,
976 options?: { readonly currentCheckoutBranch?: string | null },
977 ): QueuedThreadMessage | null => {
978 if (!selectedProject || !selectedProjectDraftKey) {
979 return null;
980 }
981 const draft = getComposerDraftSnapshot(selectedProjectDraftKey);
982 const text = draft.text.trim();
983 const draftModelSelection =
984 resolveSelectableModelSelection(
985 selectedEnvironmentServerConfig,
986 draft.modelSelection ?? null,
987 selectedProject.id,
988 ) ?? selectedModel;
989 if ((text.length === 0 && draft.attachments.length === 0) || !draftModelSelection) {
990 return null;
991 }
992 if (
993 threadContextsOutsideEnvironment({
994 text: draft.text,
995 records: draft.context?.records ?? [],
996 environmentId: selectedProject.environmentId,
997 }).length > 0
998 ) {
999 return null;
1001 const workspaceSelection = resolveNewTaskWorkspaceSelection({
1002 selection: canChooseWorkspace ? draft.workspaceSelection : undefined,
1003 fallback: { mode: workspaceMode, branch: null, worktreePath: null },
1004 isGitRepo,
1005 });
1006 const mode = workspaceSelection.mode;
1007 // When the selection is the stand-in built from the queued snapshot,
1008 // persist the original (possibly absent) snapshot values — the
1009 // stand-in's placeholder title/workspaceRoot must never be written back
1010 // as if they were real project metadata.
1011 const usingPendingSnapshot = selectedProject === editingPendingProject;
1012 const projectTitle = usingPendingSnapshot
1013 ? editingPendingTask?.creation?.projectTitle
1014 : selectedProject.title;
1015 const projectCwd = usingPendingSnapshot
1016 ? editingPendingTask?.creation?.projectCwd
1017 : selectedProject.workspaceRoot;
1018 return {
1019 environmentId: selectedProject.environmentId,
1020 threadId: ThreadId.make(metadata.threadId),
1021 messageId: MessageId.make(metadata.messageId),
1022 commandId: CommandId.make(metadata.commandId),
1023 text,
1024 attachments: draft.attachments,
1025 context: draft.context,
1026 modelSelection: draftModelSelection,
1027 runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
1028 interactionMode: resolvePendingTaskInteractionMode({
1029 preferenceLoaded: planModePreferenceLoaded,
1030 planModeEnabled: legacyPlanModeEnabled,
1031 draftInteractionMode: draft.interactionMode,
1032 queuedInteractionMode: editingPendingTask?.interactionMode,
1033 provider: selectedEnvironmentServerConfig?.providers.find(
1034 (candidate) => candidate.instanceId === draftModelSelection.instanceId,
1035 ),
1036 }),
1037 creation: {
1038 projectId: selectedProject.id,
1039 ...(projectTitle !== undefined ? { projectTitle } : {}),
1040 ...(projectCwd !== undefined ? { projectCwd } : {}),
1041 workspaceMode: mode,
1042 ...(mode === "worktree" && workspaceSelection?.pullRequestReference
1043 ? { pullRequestReference: workspaceSelection.pullRequestReference }
1044 : {}),
1045 // Queued local tasks use drain-time checkout; snapshot branches only for immediate sends or explicit choices.
1046 branch: resolveProjectThreadCreationBranch({
1047 workspaceMode: mode,
1048 selectedBranch: workspaceSelection?.branch ?? null,
1049 currentCheckoutBranch: options?.currentCheckoutBranch ?? null,
1050 }),
1051 worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
1052 ...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
1053 ? { startFromOrigin: true }
1054 : {}),
1055 },
1056 createdAt: metadata.createdAt,
1057 };
1058 };
1059​
1060 const finishEditingPendingTask = () => {
1061 const editing = editingPendingTaskRef.current;
1062 editingPendingTaskRef.current = null;
1063 if (editing) {
1064 if (activeEditingMessageId === editing.messageId) {
1065 activeEditingMessageId = null;
1067 clearComposerDraft(pendingTaskDraftKey(editing.messageId));
1068 releaseEditingQueuedMessage(editing.messageId);
1069 scheduleUnusedComposerAttachmentCleanup(editing.attachments);
1071 setEditingPendingTask(null);
1072 };
1073​
1074 // End editing without saving if the queued task disappears; a later flush must not resurrect it.
1075 const queuedMessagesByThreadKey = useThreadOutboxMessages();
1076 useEffect(() => {
1077 const editing = editingPendingTaskRef.current;
1078 if (!editing) {
1079 return;
1081 const stillQueued = flattenQueuedThreadMessages(queuedMessagesByThreadKey).some(
1082 (candidate) => candidate.messageId === editing.messageId,
1083 );
1084 if (!stillQueued) {
1085 finishEditingPendingTask();
1087 }, [finishEditingPendingTask, queuedMessagesByThreadKey]);
1088​
1089 const editingFlushRef = useRef<(() => void) | null>(null);
1090 useEffect(() => {
1091 editingFlushRef.current = () => {
1092 const editing = editingPendingTaskRef.current;
1093 if (!editing) {
1094 return;
1096 editingPendingTaskRef.current = null;
1097 setEditingPendingTask(null);
1098 if (activeEditingMessageId === editing.messageId) {
1099 activeEditingMessageId = null;
1101​
1102 const message = buildPendingTaskMessage({
1103 threadId: editing.threadId,
1104 commandId: editing.commandId,
1105 messageId: editing.messageId,
1106 createdAt: editing.createdAt,
1107 });
1108​
1109 if (!message) {
1110 // Keep unsendable edits and the drain lock so removed content cannot auto-send from a stale payload.
1111 return;
1113​
1114 // Hand off pending saves to reopened editors; CAS still rejects unrelated edits, deletes and deliveries.
1115 void flushPendingTaskEditorWrite({
1116 message,
1117 baseline: editingRevisionRef.current,
1118 draftKey: pendingTaskDraftKey(editing.messageId),
1119 })
1120 .then((savedDraftStillCurrent) => {
1121 if (activeEditingMessageId === editing.messageId) {
1122 return;
1124 if (!savedDraftStillCurrent) {
1125 return;
1127 clearComposerDraft(pendingTaskDraftKey(editing.messageId));
1128 releaseEditingQueuedMessage(editing.messageId);
1129 scheduleUnusedComposerAttachmentCleanup(editing.attachments);
1130 })
1131 .catch((error) => {
1132 // Keep the draft and drain lock on failure so stale payloads cannot discard edits; reopening retries.
1133 console.warn("[new-task] failed to save edited pending task", error);
1134 });
1135 };
1136 }, [buildPendingTaskMessage]);
1137 const cancelEditingPendingTask = () => {
1138 editingFlushRef.current?.();
1139 };
1140 useEffect(
1141 () => () => {
1142 editingFlushRef.current?.();
1143 },
1144 [],
1145 );
1146​
1147 const value = {
1148 activeNewTask,
1149 projectScopes,
1150 selectedEnvironmentId,
1151 selectedProjectKey,
1152 selectedModelKey,
1153 workspaceMode,
1154 isGitRepo,
1155 isGitRepoKnown: knownIsGitRepo !== null,
1156 canChooseWorkspace,
1157 selectedBranchName,
1158 selectedWorktreePath,
1159 startFromOrigin,
1160 draftKey: selectedProjectDraftKey,
1161 pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference,
1162 editingPendingTask,
1163 prompt,
1164 attachments,
1165 submitting,
1166 branchQuery,
1167 branchesLoading,
1168 branchesError: branchState.error,
1169 branchesFetchingNextPage,
1170 hasMoreBranches,
1171 availableBranches,
1172 currentCheckoutBranchName,
1173 runtimeMode,
1174 interactionMode,
1175 planModeEnabled,
1176 expandedProvider,
1177 environments,
1178 selectedProject,
1179 isScratchDraft,
1180 modelOptions,
1181 selectedModel,
1182 selectedModelOption,
1183 selectedProviderStatus,
1184 providerGroups,
1185 filteredBranches,
1186 reset,
1187 setProject,
1188 openDraft,
1189 selectEnvironment,
1190 switchEnvironment,
1191 switchingToEnvironmentId,
1192 setSelectedModelKey,
1193 setWorkspaceMode,
1194 selectBranch,
1195 setStartFromOrigin,
1196 beginEditingPendingTask,
1197 finishEditingPendingTask,
1198 cancelEditingPendingTask,
1199 buildPendingTaskMessage,
1200 setPrompt,
1201 replaceAttachments,
1202 appendAttachments,
1203 removeAttachment,
1204 clearAttachments,
1205 setSubmitting,
1206 setBranchQuery,
1207 loadBranches,
1208 loadMoreBranches,
1209 setRuntimeMode,
1210 setInteractionMode,
1211 setSelectedModelOptions,
1212 setExpandedProvider,
1213 } satisfies NewTaskFlowContextValue;
1214​
1215 return (
1216 <ActiveNewTaskContext value={activeNewTask}>
1217 <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>
1218 </ActiveNewTaskContext>
1219 );
1221​
1222export function useNewTaskFlow() {
1223 const value = React.use(NewTaskFlowContext);
1224 if (value === null) {
1225 throw new Error("useNewTaskFlow must be used within NewTaskFlowProvider.");
1227 return value;