The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { ActiveNewTaskContext } from "../../state/active-new-task"; |
| 2 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { msg, useMessages } from "gt-react-native"; |
| 4 | import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; |
| 5 | import { useNowMinuteMs } from "../../lib/clock"; |
| 6 | import { m, type MessageResolver } from "../../i18n/messages"; |
| 7 | import * as Dialog from "../../components/ui/Dialog"; |
| 8 | import React, { useRef, useState } from "react"; |
| 9 | |
| 10 | import type { |
| 11 | EnvironmentId, |
| 12 | ModelSelection, |
| 13 | ProviderOptionSelection, |
| 14 | RuntimeMode, |
| 15 | ServerProvider, |
| 16 | } from "@t3tools/contracts"; |
| 17 | import { |
| 18 | CommandId, |
| 19 | DEFAULT_PROVIDER_INTERACTION_MODE, |
| 20 | MessageId, |
| 21 | repositoryGroupingKeyOf, |
| 22 | ThreadId, |
| 23 | } from "@t3tools/contracts"; |
| 24 | import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences"; |
| 25 | import { isTriagePrompt, replaceTriagePlaybookLink } from "@t3tools/shared/triagePrompt"; |
| 26 | import * as Arr from "effect/Array"; |
| 27 | import { pipe } from "effect/Function"; |
| 28 | |
| 29 | import { useProjects, useServerConfigs, useThreadShells } from "../../state/entities"; |
| 30 | import type { TurnCommandMetadata } from "../../lib/commandMetadata"; |
| 31 | import type { DraftComposerAttachment } from "../../lib/composerImages"; |
| 32 | import type { ModelOption, ProviderGroup } from "../../lib/modelOptions"; |
| 33 | import { |
| 34 | buildModelOptions, |
| 35 | groupByProvider, |
| 36 | resolveDefaultableModelSelection, |
| 37 | resolveNewTaskModelSelection, |
| 38 | resolveSelectableModelSelection, |
| 39 | serverConfigForCwd, |
| 40 | } from "../../lib/modelOptions"; |
| 41 | import { scopedProjectKey } from "../../lib/scopedEntities"; |
| 42 | import { useAtomValue } from "@effect/atom-react"; |
| 43 | import { appAtomRegistry } from "../../state/atom-registry"; |
| 44 | import { projectEnvironment } from "../../state/projects"; |
| 45 | import { useLinkedEnvironments } from "../../state/peerLinks"; |
| 46 | import { useEnvironmentQuery } from "../../state/query"; |
| 47 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 48 | import { |
| 49 | appendComposerDraftAttachments, |
| 50 | type ComposerDraftInsertion, |
| 51 | type ComposerDraftWorkspaceSelection, |
| 52 | composerDraftsLoadedAtom, |
| 53 | createNewTaskDraft, |
| 54 | getComposerDraftSnapshot, |
| 55 | isNewTaskDraftKey, |
| 56 | removeComposerDraftAttachment, |
| 57 | replaceComposerDraftAttachments, |
| 58 | retargetNewTaskDraft, |
| 59 | setComposerDraftText, |
| 60 | setStickyComposerModelSelection, |
| 61 | updateComposerDraftSettings, |
| 62 | useComposerDraft, |
| 63 | useStickyComposerModelSelection, |
| 64 | } from "../../state/use-composer-drafts"; |
| 65 | import { |
| 66 | rememberModelOptions, |
| 67 | withRememberedModelOptions, |
| 68 | } from "../../state/use-model-option-memory"; |
| 69 | import { useBranches, usePaginatedBranches } from "../../state/queries"; |
| 70 | import { vcsEnvironment } from "../../state/vcs"; |
| 71 | import { type QueuedThreadMessage } from "../../state/thread-outbox"; |
| 72 | import { |
| 73 | setPendingConnectionError, |
| 74 | useRemoteConnectionStatus, |
| 75 | useSavedRemoteConnections, |
| 76 | } from "../../state/use-remote-environment-registry"; |
| 77 | import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects"; |
| 78 | import { |
| 79 | isAtomCommandInterrupted, |
| 80 | squashAtomCommandFailure, |
| 81 | } from "@t3tools/client-runtime/state/runtime"; |
| 82 | import { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; |
| 83 | import { type VcsRef } from "@t3tools/client-runtime/state/vcs"; |
| 84 | import { |
| 85 | buildHomeProjectScopes, |
| 86 | sortHomeProjectScopes, |
| 87 | type HomeProjectScope, |
| 88 | } from "../home/homeThreadList"; |
| 89 | import { useMobileProjectGroupingSettings } from "../../state/project-grouping"; |
| 90 | import { |
| 91 | resolveNewTaskDraftWorkspace, |
| 92 | resolveNewTaskBranchWorktreePath, |
| 93 | resolveNewTaskLocalWorkspaceSelection, |
| 94 | } from "./new-task-context-presentation"; |
| 95 | import { isSameRepository, resolveEnvironmentProjectMatch } from "./new-task-project-selection"; |
| 96 | import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults"; |
| 97 | import { resolveNewThreadRuntimeMode } from "./thread-settings-options"; |
| 98 | import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation"; |
| 99 | import { |
| 100 | INACTIVE_FLOW_KEY, |
| 101 | type NewTaskFlowState, |
| 102 | newTaskFlowStateAtom, |
| 103 | readNewTaskFlowState, |
| 104 | resolveRouteDraft, |
| 105 | type RouteDraftResolution, |
| 106 | stampedEnvironmentProjectsLoading, |
| 107 | updateNewTaskFlowState, |
| 108 | } from "./new-task-flow-state"; |
| 109 | import { usePrepareTriage } from "../triage/usePrepareTriage"; |
| 110 | import { useEnvironmentShellReadiness } from "../../state/shell"; |
| 111 | import { useConnectionsReady, useWorkspaceEnvironments } from "../../state/workspace"; |
| 112 | |
| 113 | type WorkspaceMode = "local" | "worktree"; |
| 114 | |
| 115 | export function branchBadgeLabel( |
| 116 | input: { |
| 117 | readonly branch: VcsRef; |
| 118 | readonly project: EnvironmentProject | null; |
| 119 | }, |
| 120 | resolve: MessageResolver = m, |
| 121 | ): string | null { |
| 122 | if (input.branch.current) { |
| 123 | return resolve(msg("current", { $context: "branch badge, the checked-out branch" })); |
| 124 | } |
| 125 | if (input.branch.worktreePath && input.branch.worktreePath !== input.project?.workspaceRoot) { |
| 126 | return resolve(msg("worktree", { $context: "branch badge, checked out in another worktree" })); |
| 127 | } |
| 128 | if (input.branch.isRemote) { |
| 129 | return resolve(msg("remote", { $context: "branch badge, a remote-tracking branch" })); |
| 130 | } |
| 131 | if (input.branch.isDefault) { |
| 132 | return resolve(msg("default", { $context: "branch badge, the repository default branch" })); |
| 133 | } |
| 134 | return null; |
| 135 | } |
| 136 | |
| 137 | type NewTaskFlowContextValue = { |
| 138 | readonly activeNewTask: { readonly pendingKey: string | null } | null; |
| 139 | readonly projectScopes: ReadonlyArray<HomeProjectScope>; |
| 140 | readonly selectedEnvironmentId: EnvironmentId | null; |
| 141 | readonly selectedProjectKey: string | null; |
| 142 | readonly selectedModelKey: string | null; |
| 143 | readonly workspaceMode: WorkspaceMode; |
| 144 | readonly isGitRepo: boolean; |
| 145 | readonly isGitRepoKnown: boolean; |
| 146 | readonly canChooseWorkspace: boolean; |
| 147 | readonly selectedBranchName: string | null; |
| 148 | readonly selectedWorktreePath: string | null; |
| 149 | /** Where the draft's agent will run: the selected worktree, else the project root. */ |
| 150 | readonly workspaceCwd: string | null; |
| 151 | readonly resolveWorkspaceSelection: ( |
| 152 | selection: ComposerDraftWorkspaceSelection | undefined, |
| 153 | ) => ComposerDraftWorkspaceSelection; |
| 154 | readonly startFromOrigin: boolean; |
| 155 | readonly pullRequestReference: string | undefined; |
| 156 | readonly draftKey: string | null; |
| 157 | readonly prompt: string; |
| 158 | readonly attachments: ReadonlyArray<DraftComposerAttachment>; |
| 159 | readonly submitting: boolean; |
| 160 | readonly branchesLoading: boolean; |
| 161 | readonly availableBranches: ReadonlyArray<VcsRef>; |
| 162 | readonly currentCheckoutBranchName: string | null; |
| 163 | readonly runtimeMode: RuntimeMode; |
| 164 | readonly expandedProvider: string | null; |
| 165 | readonly environments: ReadonlyArray<{ |
| 166 | readonly environmentId: EnvironmentId; |
| 167 | readonly environmentLabel: string; |
| 168 | }>; |
| 169 | readonly selectedProject: EnvironmentProject | null; |
| 170 | /** The machines the selected project's environment links to, whose threads it can read. */ |
| 171 | readonly linkedEnvironments: ReadonlyMap<EnvironmentId, string>; |
| 172 | readonly isScratchDraft: boolean; |
| 173 | readonly modelOptions: ReadonlyArray<ModelOption>; |
| 174 | readonly selectedModel: ModelSelection | null; |
| 175 | readonly selectedModelOption: ModelOption | null; |
| 176 | readonly selectedProviderStatus: ServerProvider | null; |
| 177 | readonly providerGroups: ReadonlyArray<ProviderGroup>; |
| 178 | readonly setProject: (project: EnvironmentProject) => void; |
| 179 | /** The flow's project, read when a continuation resumes after an await. */ |
| 180 | readonly getSelectedProjectKey: () => string | null; |
| 181 | /** |
| 182 | * The route this flow serves when its draft cannot open: the draft is gone |
| 183 | * (`missing`) or only its project is (`pickProject`). Only the topmost draft |
| 184 | * route is served, so a screen compares `draftId` with its own draft id. |
| 185 | */ |
| 186 | readonly unopenableRouteDraft: { |
| 187 | readonly draftId: string; |
| 188 | readonly kind: "missing" | "pickProject"; |
| 189 | } | null; |
| 190 | readonly selectEnvironment: (environmentId: EnvironmentId) => void; |
| 191 | readonly switchEnvironment: (environmentId: EnvironmentId) => Promise<boolean>; |
| 192 | readonly switchingToEnvironmentId: EnvironmentId | null; |
| 193 | readonly setSelectedModelKey: ( |
| 194 | key: string | null, |
| 195 | options?: ReadonlyArray<ProviderOptionSelection>, |
| 196 | ) => void; |
| 197 | readonly setWorkspaceMode: (mode: WorkspaceMode) => void; |
| 198 | readonly selectBranch: (branch: VcsRef) => void; |
| 199 | readonly setStartFromOrigin: (value: boolean) => void; |
| 200 | readonly buildPendingTaskMessage: ( |
| 201 | metadata: TurnCommandMetadata, |
| 202 | options?: { |
| 203 | readonly currentCheckoutBranch?: string | null; |
| 204 | }, |
| 205 | ) => QueuedThreadMessage | null; |
| 206 | readonly setPrompt: (value: string) => void; |
| 207 | readonly replaceAttachments: (attachments: ReadonlyArray<DraftComposerAttachment>) => void; |
| 208 | /** Appends draft attachments; returns how many the live cap rejected. */ |
| 209 | readonly appendAttachments: ( |
| 210 | attachments: ReadonlyArray<DraftComposerAttachment>, |
| 211 | insertion?: ComposerDraftInsertion, |
| 212 | ) => number; |
| 213 | readonly removeAttachment: (imageId: string) => void; |
| 214 | readonly clearAttachments: () => void; |
| 215 | readonly setSubmitting: (value: boolean) => void; |
| 216 | readonly loadBranches: () => void; |
| 217 | readonly setRuntimeMode: (value: RuntimeMode) => void; |
| 218 | readonly setSelectedModelOptions: ( |
| 219 | value: ReadonlyArray<ProviderOptionSelection> | undefined, |
| 220 | ) => void; |
| 221 | readonly setExpandedProvider: (value: string | null) => void; |
| 222 | }; |
| 223 | |
| 224 | const NewTaskFlowContext = React.createContext<NewTaskFlowContextValue | null>(null); |
| 225 | |
| 226 | export function NewTaskFlowProvider( |
| 227 | props: React.PropsWithChildren<{ |
| 228 | active?: boolean; |
| 229 | /** Identifies the draft route this flow serves; a new key starts a fresh flow. */ |
| 230 | flowKey?: string; |
| 231 | routeDraftId?: string; |
| 232 | }>, |
| 233 | ) { |
| 234 | const projects = useProjects(); |
| 235 | const messages = useMessages(); |
| 236 | const threads = useThreadShells(); |
| 237 | const { savedConnectionsById } = useSavedRemoteConnections(); |
| 238 | const groupingSettings = useMobileProjectGroupingSettings(); |
| 239 | |
| 240 | const projectScopes = sortHomeProjectScopes({ |
| 241 | scopes: buildHomeProjectScopes( |
| 242 | { |
| 243 | projects, |
| 244 | environmentId: null, |
| 245 | projectGroupingMode: groupingSettings.sidebarProjectGroupingMode, |
| 246 | }, |
| 247 | messages, |
| 248 | ), |
| 249 | threads, |
| 250 | pendingTasks: [], |
| 251 | projectSortOrder: "updated_at", |
| 252 | }); |
| 253 | |
| 254 | const flowKey = props.flowKey ?? INACTIVE_FLOW_KEY; |
| 255 | const storedFlowState = useAtomValue(newTaskFlowStateAtom(flowKey)); |
| 256 | const draftsLoaded = useAtomValue(composerDraftsLoadedAtom); |
| 257 | // A draft route opened from a list row, a deep link, or restored state binds |
| 258 | // its draft here until the flow's first write stores the binding. |
| 259 | const routeDraft = useComposerDraft( |
| 260 | storedFlowState.draftKey === null ? (props.routeDraftId ?? null) : null, |
| 261 | ); |
| 262 | // Readiness of the environment the route's draft is stamped to; another |
| 263 | // environment's projects loading first says nothing about it. |
| 264 | const stampedEnvironmentId = routeDraft.project?.environmentId ?? null; |
| 265 | const connectionsReady = useConnectionsReady(); |
| 266 | const stampedEnvironmentConnection = |
| 267 | useWorkspaceEnvironments().find( |
| 268 | (environment) => environment.environmentId === stampedEnvironmentId, |
| 269 | )?.connectionState ?? null; |
| 270 | const stampedEnvironmentShell = useEnvironmentShellReadiness(stampedEnvironmentId); |
| 271 | const stampedEnvironmentLoading = stampedEnvironmentProjectsLoading({ |
| 272 | connectionsReady, |
| 273 | connectionState: stampedEnvironmentConnection, |
| 274 | shellCacheRead: stampedEnvironmentShell.cacheRead, |
| 275 | shellStatus: stampedEnvironmentShell.status, |
| 276 | shellHasError: stampedEnvironmentShell.hasError, |
| 277 | }); |
| 278 | const resolveRoute = ( |
| 279 | flow: NewTaskFlowState, |
| 280 | loaded: boolean, |
| 281 | stamp: Parameters<typeof resolveRouteDraft>[0]["stamp"], |
| 282 | ): RouteDraftResolution => |
| 283 | resolveRouteDraft({ |
| 284 | flow, |
| 285 | routeDraftId: props.routeDraftId, |
| 286 | draftsLoaded: loaded, |
| 287 | stamp, |
| 288 | projects, |
| 289 | stampedEnvironmentLoading, |
| 290 | }); |
| 291 | const routeDraftResolution = resolveRoute(storedFlowState, draftsLoaded, routeDraft.project); |
| 292 | const flowState = |
| 293 | routeDraftResolution.kind === "open" ? routeDraftResolution.flow : storedFlowState; |
| 294 | const { |
| 295 | environmentId: selectedEnvironmentIdOverride, |
| 296 | projectKey: selectedProjectKey, |
| 297 | draftKey: activeDraftKey, |
| 298 | submitting, |
| 299 | expandedProvider, |
| 300 | } = flowState; |
| 301 | // Continuations read the flow at use time, with the route's draft applied. |
| 302 | const readFlow = (): NewTaskFlowState => { |
| 303 | const stored = readNewTaskFlowState(flowKey); |
| 304 | const resolution = resolveRoute( |
| 305 | stored, |
| 306 | appAtomRegistry.get(composerDraftsLoadedAtom), |
| 307 | props.routeDraftId === undefined |
| 308 | ? undefined |
| 309 | : getComposerDraftSnapshot(props.routeDraftId).project, |
| 310 | ); |
| 311 | return resolution.kind === "open" ? resolution.flow : stored; |
| 312 | }; |
| 313 | // Every flow write stores the route's draft binding along with it, so the |
| 314 | // binding outlives the draft's project stamp (submit clears it). |
| 315 | const updateFlow = (patch: Partial<NewTaskFlowState>) => |
| 316 | updateNewTaskFlowState(flowKey, { ...readFlow(), ...patch }); |
| 317 | // A draft's project stamp is the selection: picking a project writes it, and uploads and |
| 318 | // the send read it, so the screen cannot show one project while the draft holds another. |
| 319 | const draftStamp = useComposerDraft(activeDraftKey).project; |
| 320 | const stampedProject = |
| 321 | draftStamp === undefined |
| 322 | ? undefined |
| 323 | : projects.find( |
| 324 | (project) => |
| 325 | project.environmentId === draftStamp.environmentId && |
| 326 | project.id === draftStamp.projectId, |
| 327 | ); |
| 328 | const selectedEnvironmentId = |
| 329 | stampedProject?.environmentId ?? |
| 330 | (selectedEnvironmentIdOverride !== null && |
| 331 | projects.some((project) => project.environmentId === selectedEnvironmentIdOverride) |
| 332 | ? selectedEnvironmentIdOverride |
| 333 | : (projects[0]?.environmentId ?? null)); |
| 334 | const projectsForEnvironment = pipe( |
| 335 | projects, |
| 336 | Arr.filter((project) => project.environmentId === selectedEnvironmentId), |
| 337 | ); |
| 338 | |
| 339 | // A route draft still waiting for its environment has no project yet: the |
| 340 | // fallback would show, and could send to, another environment's project. |
| 341 | const selectedProject = |
| 342 | routeDraftResolution.kind === "pending" |
| 343 | ? null |
| 344 | : (stampedProject ?? |
| 345 | projectsForEnvironment.find( |
| 346 | (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey, |
| 347 | ) ?? |
| 348 | projectsForEnvironment[0] ?? |
| 349 | null); |
| 350 | |
| 351 | const linkedEnvironments = useLinkedEnvironments(selectedProject?.environmentId ?? null); |
| 352 | const storedStickyModelSelection = useStickyComposerModelSelection(); |
| 353 | const modelSelectionNow = useNowMinuteMs(); |
| 354 | const projectDefaults = useNewTaskProjectDefaults(selectedProject); |
| 355 | const isScratchDraft = projectDefaults.isScratch; |
| 356 | const serverConfigs = useServerConfigs(); |
| 357 | const { connectedEnvironments } = useRemoteConnectionStatus(); |
| 358 | const selectedProjectDraftKey = selectedProject ? activeDraftKey : null; |
| 359 | const activePendingKey = |
| 360 | props.active === false |
| 361 | ? null |
| 362 | : props.routeDraftId |
| 363 | ? `draft-task:${props.routeDraftId}` |
| 364 | : selectedProjectDraftKey |
| 365 | ? `draft-task:${selectedProjectDraftKey}` |
| 366 | : null; |
| 367 | const activeNewTask = props.active === false ? null : { pendingKey: activePendingKey }; |
| 368 | const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey); |
| 369 | const prompt = selectedProjectDraft.text; |
| 370 | const attachments = selectedProjectDraft.attachments; |
| 371 | const projectGitStatus = useEnvironmentQuery( |
| 372 | props.active !== false && selectedProject !== null && selectedProject.workspaceRoot !== "" |
| 373 | ? vcsEnvironment.status({ |
| 374 | environmentId: selectedProject.environmentId, |
| 375 | input: { cwd: selectedProject.workspaceRoot }, |
| 376 | }) |
| 377 | : null, |
| 378 | ); |
| 379 | const currentCheckoutBranchName = projectGitStatus.data?.refName ?? null; |
| 380 | // The unfiltered ref list also provides repository capability while offline. |
| 381 | const projectBranches = useBranches({ |
| 382 | environmentId: selectedProject?.environmentId ?? null, |
| 383 | cwd: selectedProject?.workspaceRoot || null, |
| 384 | }); |
| 385 | const knownIsGitRepo = projectGitStatus.data?.isRepo ?? projectBranches.data?.isRepo ?? null; |
| 386 | const isGitRepo = knownIsGitRepo ?? true; |
| 387 | const projectSettings = projectDefaults.projectSettings; |
| 388 | const canChooseWorkspace = !isScratchDraft; |
| 389 | const defaultWorkspaceMode: WorkspaceMode = projectDefaults.defaultWorkspaceMode; |
| 390 | const branchState = usePaginatedBranches({ |
| 391 | environmentId: selectedProject?.environmentId ?? null, |
| 392 | cwd: selectedProject?.workspaceRoot || null, |
| 393 | }); |
| 394 | const branchesLoading = branchState.isPending && branchState.data === null; |
| 395 | const allBranchRefs = branchState.refs; |
| 396 | const availableBranches = pipe( |
| 397 | allBranchRefs, |
| 398 | Arr.filter((branch) => !branch.isRemote), |
| 399 | ); |
| 400 | |
| 401 | const resolveWorkspaceSelection = (selection: ComposerDraftWorkspaceSelection | undefined) => |
| 402 | resolveNewTaskDraftWorkspace({ |
| 403 | selection, |
| 404 | canChooseWorkspace, |
| 405 | defaultMode: defaultWorkspaceMode, |
| 406 | defaultModeSettled: projectDefaults.defaultWorkspaceModeSettled, |
| 407 | isGitRepo, |
| 408 | branches: allBranchRefs, |
| 409 | projectCwd: selectedProject?.workspaceRoot ?? null, |
| 410 | }); |
| 411 | const workspaceSelection = resolveWorkspaceSelection(selectedProjectDraft.workspaceSelection); |
| 412 | const workspaceMode = workspaceSelection.mode; |
| 413 | const selectedBranchName = workspaceSelection.branch; |
| 414 | const selectedWorktreePath = workspaceSelection.worktreePath; |
| 415 | // A new worktree does not exist yet, so the project root stands in for it. |
| 416 | const workspaceCwd = |
| 417 | (workspaceMode === "worktree" |
| 418 | ? selectedProject?.workspaceRoot |
| 419 | : (selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null; |
| 420 | const selectedEnvironmentServerConfig = serverConfigForCwd( |
| 421 | projectDefaults.serverConfig, |
| 422 | workspaceCwd, |
| 423 | ); |
| 424 | // Keep the user's explicit choice separate from the resolved display value: |
| 425 | // only the explicit flag is ever written back to the draft, so the resolved |
| 426 | // value keeps tracking the server setting when the config loads late. |
| 427 | const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin; |
| 428 | const startFromOrigin = |
| 429 | isGitRepo && (draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin); |
| 430 | const defaultRuntimeMode = projectSettings.settings.defaultRuntimeMode; |
| 431 | const managedPolicy = selectedEnvironmentServerConfig?.managedPolicy; |
| 432 | const runtimeMode = resolveNewThreadRuntimeMode( |
| 433 | selectedProjectDraft.runtimeMode, |
| 434 | defaultRuntimeMode, |
| 435 | managedPolicy, |
| 436 | ); |
| 437 | |
| 438 | // Antigravity keeps unavailable selections so sign-out or a catalog change |
| 439 | // cannot switch the user's model. |
| 440 | const draftModelSelection = resolveSelectableModelSelection( |
| 441 | selectedEnvironmentServerConfig, |
| 442 | selectedProjectDraft.modelSelection ?? null, |
| 443 | selectedProject?.id ?? null, |
| 444 | ); |
| 445 | const projectDefaultModelSelection = resolveDefaultableModelSelection( |
| 446 | selectedEnvironmentServerConfig, |
| 447 | projectSettings.settings.defaultModelSelection, |
| 448 | selectedProject?.id ?? null, |
| 449 | ); |
| 450 | const stickyModelSelection = resolveDefaultableModelSelection( |
| 451 | selectedEnvironmentServerConfig, |
| 452 | storedStickyModelSelection, |
| 453 | selectedProject?.id ?? null, |
| 454 | ); |
| 455 | const modelOptions = buildModelOptions( |
| 456 | selectedEnvironmentServerConfig, |
| 457 | draftModelSelection ?? projectDefaultModelSelection ?? stickyModelSelection, |
| 458 | undefined, |
| 459 | selectedProject?.id ?? null, |
| 460 | ); |
| 461 | |
| 462 | const selectedDefaultModel = resolveNewTaskModelSelection({ |
| 463 | draftSelection: draftModelSelection, |
| 464 | projectDefaultSelection: projectDefaultModelSelection, |
| 465 | stickySelection: stickyModelSelection, |
| 466 | modelOptions, |
| 467 | }); |
| 468 | const selectedModel = resolveNewThreadModelSelection({ |
| 469 | defaultSelection: selectedDefaultModel, |
| 470 | explicitSelection: |
| 471 | draftModelSelection ?? (projectDefaultModelSelection ? null : stickyModelSelection), |
| 472 | fallbackSelection: selectedEnvironmentServerConfig?.settings.fallbackModelSelection ?? null, |
| 473 | providers: selectedEnvironmentServerConfig?.providers ?? [], |
| 474 | ...(selectedEnvironmentServerConfig |
| 475 | ? { settings: selectedEnvironmentServerConfig.settings } |
| 476 | : {}), |
| 477 | projectId: selectedProject?.id ?? null, |
| 478 | now: modelSelectionNow, |
| 479 | }).selection; |
| 480 | const selectedModelKey = selectedModel |
| 481 | ? `${selectedModel.instanceId}:${selectedModel.model}` |
| 482 | : null; |
| 483 | |
| 484 | const selectedModelOption = |
| 485 | modelOptions.find( |
| 486 | (option) => |
| 487 | selectedModel && |
| 488 | option.selection.instanceId === selectedModel.instanceId && |
| 489 | option.selection.model === selectedModel.model, |
| 490 | ) ?? null; |
| 491 | const selectedProviderStatus = |
| 492 | selectedEnvironmentServerConfig?.providers.find( |
| 493 | (provider) => provider.instanceId === selectedModel?.instanceId, |
| 494 | ) ?? null; |
| 495 | const setSelectedModelKey = ( |
| 496 | key: string | null, |
| 497 | options?: ReadonlyArray<ProviderOptionSelection>, |
| 498 | ) => { |
| 499 | if (!key || !selectedProjectDraftKey) { |
| 500 | return; |
| 501 | } |
| 502 | const option = modelOptions.find((candidate) => candidate.key === key); |
| 503 | if (!option) { |
| 504 | return; |
| 505 | } |
| 506 | const selection = withRememberedModelOptions( |
| 507 | options ? { ...option.selection, options } : option.selection, |
| 508 | ); |
| 509 | updateComposerDraftSettings(selectedProjectDraftKey, { modelSelection: selection }); |
| 510 | setStickyComposerModelSelection(selection); |
| 511 | }; |
| 512 | const setSelectedModelOptions = (options: ReadonlyArray<ProviderOptionSelection> | undefined) => { |
| 513 | if (!selectedModel || !selectedProjectDraftKey) { |
| 514 | return; |
| 515 | } |
| 516 | rememberModelOptions(selectedModel.instanceId, selectedModel.model, options ?? []); |
| 517 | const nextSelection: ModelSelection = options |
| 518 | ? { ...selectedModel, options } |
| 519 | : { |
| 520 | instanceId: selectedModel.instanceId, |
| 521 | model: selectedModel.model, |
| 522 | }; |
| 523 | updateComposerDraftSettings(selectedProjectDraftKey, { |
| 524 | modelSelection: nextSelection, |
| 525 | }); |
| 526 | setStickyComposerModelSelection(nextSelection); |
| 527 | }; |
| 528 | |
| 529 | const providerGroups = groupByProvider(modelOptions); |
| 530 | const setPrompt = (value: string) => { |
| 531 | if (!selectedProjectDraftKey) { |
| 532 | return; |
| 533 | } |
| 534 | setComposerDraftText(selectedProjectDraftKey, value); |
| 535 | }; |
| 536 | const replaceAttachments = (nextAttachments: ReadonlyArray<DraftComposerAttachment>) => { |
| 537 | if (!selectedProjectDraftKey) { |
| 538 | return; |
| 539 | } |
| 540 | replaceComposerDraftAttachments(selectedProjectDraftKey, nextAttachments); |
| 541 | }; |
| 542 | const appendAttachments = ( |
| 543 | nextAttachments: ReadonlyArray<DraftComposerAttachment>, |
| 544 | insertion?: ComposerDraftInsertion, |
| 545 | ): number => { |
| 546 | if (!selectedProjectDraftKey) { |
| 547 | return 0; |
| 548 | } |
| 549 | return appendComposerDraftAttachments(selectedProjectDraftKey, nextAttachments, { |
| 550 | appendReference: true, |
| 551 | insertion, |
| 552 | }); |
| 553 | }; |
| 554 | const removeAttachment = (imageId: string) => { |
| 555 | if (!selectedProjectDraftKey) { |
| 556 | return; |
| 557 | } |
| 558 | removeComposerDraftAttachment(selectedProjectDraftKey, imageId); |
| 559 | }; |
| 560 | const clearAttachments = () => { |
| 561 | if (!selectedProjectDraftKey) { |
| 562 | return; |
| 563 | } |
| 564 | replaceComposerDraftAttachments(selectedProjectDraftKey, []); |
| 565 | }; |
| 566 | |
| 567 | const carryDraftContentTo = ( |
| 568 | project: EnvironmentProject, |
| 569 | options?: Parameters<typeof retargetNewTaskDraft>[2], |
| 570 | ): string => { |
| 571 | const target = { environmentId: project.environmentId, projectId: project.id }; |
| 572 | const current = readFlow().draftKey; |
| 573 | if (current !== null && isNewTaskDraftKey(current)) { |
| 574 | retargetNewTaskDraft(current, target, options); |
| 575 | return current; |
| 576 | } |
| 577 | return createNewTaskDraft(target); |
| 578 | }; |
| 579 | |
| 580 | const setProject = (project: EnvironmentProject) => { |
| 581 | updateFlow({ |
| 582 | draftKey: carryDraftContentTo(project), |
| 583 | environmentId: project.environmentId, |
| 584 | projectKey: scopedProjectKey(project.environmentId, project.id), |
| 585 | }); |
| 586 | }; |
| 587 | |
| 588 | const selectEnvironment = (environmentId: EnvironmentId) => { |
| 589 | const match = resolveEnvironmentProjectMatch( |
| 590 | projects.filter((project) => project.environmentId === environmentId), |
| 591 | selectedProject, |
| 592 | ); |
| 593 | updateFlow({ |
| 594 | // A name or title match may be another repository, which must not receive the PR checkout. |
| 595 | draftKey: match |
| 596 | ? carryDraftContentTo(match, { |
| 597 | keepPullRequestWorkspace: isSameRepository(match, selectedProject), |
| 598 | }) |
| 599 | : readFlow().draftKey, |
| 600 | environmentId, |
| 601 | projectKey: match ? scopedProjectKey(match.environmentId, match.id) : null, |
| 602 | }); |
| 603 | }; |
| 604 | |
| 605 | const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false }); |
| 606 | const prepareTriage = usePrepareTriage(); |
| 607 | const [switchingToEnvironmentId, setSwitchingToEnvironmentId] = useState<EnvironmentId | null>( |
| 608 | null, |
| 609 | ); |
| 610 | const latestSwitchRef = useRef<object | null>(null); |
| 611 | const switchEnvironment = async (environmentId: EnvironmentId): Promise<boolean> => { |
| 612 | if (environmentId === selectedEnvironmentId) { |
| 613 | latestSwitchRef.current = null; |
| 614 | setSwitchingToEnvironmentId(null); |
| 615 | return true; |
| 616 | } |
| 617 | if (!isScratchDraft) { |
| 618 | selectEnvironment(environmentId); |
| 619 | return true; |
| 620 | } |
| 621 | const request = {}; |
| 622 | latestSwitchRef.current = request; |
| 623 | setSwitchingToEnvironmentId(environmentId); |
| 624 | // A triage draft takes its session along: the playbook and context files |
| 625 | // exist only on the machine that prepared them. |
| 626 | const { draftKey, projectKey } = readFlow(); |
| 627 | const triage = |
| 628 | draftKey !== null && isTriagePrompt(getComposerDraftSnapshot(draftKey).text) |
| 629 | ? await prepareTriage(environmentId) |
| 630 | : null; |
| 631 | const result = |
| 632 | triage?._tag === "Failure" ? triage : await openScratch({ environmentId, input: {} }); |
| 633 | if (latestSwitchRef.current !== request) return false; |
| 634 | latestSwitchRef.current = null; |
| 635 | setSwitchingToEnvironmentId(null); |
| 636 | // A project picked while this waited stands. |
| 637 | if (readFlow().projectKey !== projectKey) return false; |
| 638 | if (result._tag === "Success") { |
| 639 | if (triage?._tag === "Success" && draftKey !== null && readFlow().draftKey === draftKey) { |
| 640 | // Read now, so text typed while the machine prepared the session is kept. |
| 641 | const text = getComposerDraftSnapshot(draftKey).text; |
| 642 | const nextText = replaceTriagePlaybookLink(text, triage.value.prompt); |
| 643 | if (nextText !== text) setComposerDraftText(draftKey, nextText); |
| 644 | } |
| 645 | setProject(result.value); |
| 646 | return true; |
| 647 | } |
| 648 | if (!isAtomCommandInterrupted(result)) { |
| 649 | const error = squashAtomCommandFailure(result); |
| 650 | Dialog.alert( |
| 651 | m(msg("Could not switch machine")), |
| 652 | errorDisplayMessage(error, m) ?? |
| 653 | (triage?._tag === "Failure" |
| 654 | ? m(msg("The server could not prepare triage.")) |
| 655 | : m(msg("The folder for threads without a project could not be created."))), |
| 656 | ); |
| 657 | } |
| 658 | return false; |
| 659 | }; |
| 660 | |
| 661 | const setWorkspaceMode = (mode: WorkspaceMode) => { |
| 662 | if (!selectedProjectDraftKey) { |
| 663 | return; |
| 664 | } |
| 665 | if (!selectedProject) { |
| 666 | return; |
| 667 | } |
| 668 | const localSelection = resolveNewTaskLocalWorkspaceSelection({ |
| 669 | branches: availableBranches, |
| 670 | projectCwd: selectedProject.workspaceRoot, |
| 671 | }); |
| 672 | updateComposerDraftSettings(selectedProjectDraftKey, { |
| 673 | workspaceSelection: { |
| 674 | mode, |
| 675 | branch: mode === "local" ? localSelection.branch : selectedBranchName, |
| 676 | worktreePath: mode === "local" ? localSelection.worktreePath : selectedWorktreePath, |
| 677 | ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}), |
| 678 | // Refs have not named the current branch yet; the selection follows it. |
| 679 | ...(mode === "local" && localSelection.awaitsCurrentBranch |
| 680 | ? { followsCurrentCheckout: true } |
| 681 | : {}), |
| 682 | }, |
| 683 | }); |
| 684 | }; |
| 685 | |
| 686 | const selectBranch = (branch: VcsRef) => { |
| 687 | if (!selectedProject || !selectedProjectDraftKey) { |
| 688 | return; |
| 689 | } |
| 690 | updateComposerDraftSettings(selectedProjectDraftKey, { |
| 691 | workspaceSelection: { |
| 692 | mode: workspaceMode, |
| 693 | branch: branch.name, |
| 694 | worktreePath: resolveNewTaskBranchWorktreePath({ |
| 695 | workspaceMode, |
| 696 | projectCwd: selectedProject.workspaceRoot, |
| 697 | branchWorktreePath: branch.worktreePath, |
| 698 | }), |
| 699 | ...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}), |
| 700 | }, |
| 701 | }); |
| 702 | }; |
| 703 | |
| 704 | const setStartFromOrigin = (value: boolean) => { |
| 705 | if (!selectedProjectDraftKey) { |
| 706 | return; |
| 707 | } |
| 708 | updateComposerDraftSettings(selectedProjectDraftKey, { |
| 709 | workspaceSelection: { |
| 710 | mode: workspaceMode, |
| 711 | branch: selectedBranchName, |
| 712 | worktreePath: selectedWorktreePath, |
| 713 | startFromOrigin: value, |
| 714 | ...(selectedBranchName === null && workspaceSelection.followsCurrentCheckout |
| 715 | ? { followsCurrentCheckout: true } |
| 716 | : {}), |
| 717 | }, |
| 718 | }); |
| 719 | }; |
| 720 | |
| 721 | const refreshBranches = branchState.refresh; |
| 722 | const loadBranches = () => { |
| 723 | if (!selectedProject) { |
| 724 | return; |
| 725 | } |
| 726 | setPendingConnectionError(null); |
| 727 | refreshBranches(); |
| 728 | }; |
| 729 | |
| 730 | const setRuntimeMode = (value: RuntimeMode) => { |
| 731 | if (selectedProjectDraftKey) { |
| 732 | updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value }); |
| 733 | } |
| 734 | }; |
| 735 | |
| 736 | const buildPendingTaskMessage = ( |
| 737 | metadata: TurnCommandMetadata, |
| 738 | options?: { readonly currentCheckoutBranch?: string | null }, |
| 739 | ): QueuedThreadMessage | null => { |
| 740 | if (!selectedProject || !selectedProjectDraftKey) { |
| 741 | return null; |
| 742 | } |
| 743 | const draft = getComposerDraftSnapshot(selectedProjectDraftKey); |
| 744 | const text = draft.text.trim(); |
| 745 | const draftModelSelection = |
| 746 | resolveSelectableModelSelection( |
| 747 | selectedEnvironmentServerConfig, |
| 748 | draft.modelSelection ?? null, |
| 749 | selectedProject.id, |
| 750 | ) ?? selectedModel; |
| 751 | if ((text.length === 0 && draft.attachments.length === 0) || !draftModelSelection) { |
| 752 | return null; |
| 753 | } |
| 754 | if ( |
| 755 | threadContextsOutsideEnvironment({ |
| 756 | text: draft.text, |
| 757 | records: draft.context?.records ?? [], |
| 758 | environmentId: selectedProject.environmentId, |
| 759 | linkedEnvironments, |
| 760 | }).length > 0 |
| 761 | ) { |
| 762 | return null; |
| 763 | } |
| 764 | const workspaceSelection = resolveWorkspaceSelection(draft.workspaceSelection); |
| 765 | const mode = workspaceSelection.mode; |
| 766 | return { |
| 767 | environmentId: selectedProject.environmentId, |
| 768 | threadId: ThreadId.make(metadata.threadId), |
| 769 | messageId: MessageId.make(metadata.messageId), |
| 770 | commandId: CommandId.make(metadata.commandId), |
| 771 | text, |
| 772 | attachments: draft.attachments, |
| 773 | context: draft.context, |
| 774 | modelSelection: draftModelSelection, |
| 775 | runtimeMode: resolveNewThreadRuntimeMode( |
| 776 | draft.runtimeMode, |
| 777 | defaultRuntimeMode, |
| 778 | managedPolicy, |
| 779 | ), |
| 780 | interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, |
| 781 | creation: { |
| 782 | projectId: selectedProject.id, |
| 783 | projectTitle: selectedProject.title, |
| 784 | projectCwd: selectedProject.workspaceRoot, |
| 785 | workspaceMode: mode, |
| 786 | ...(mode === "worktree" && workspaceSelection?.pullRequestReference |
| 787 | ? { pullRequestReference: workspaceSelection.pullRequestReference } |
| 788 | : {}), |
| 789 | // Queued local tasks use drain-time checkout; snapshot branches only for immediate sends or explicit choices. |
| 790 | branch: resolveProjectThreadCreationBranch({ |
| 791 | workspaceMode: mode, |
| 792 | selectedBranch: workspaceSelection?.branch ?? null, |
| 793 | currentCheckoutBranch: options?.currentCheckoutBranch ?? null, |
| 794 | }), |
| 795 | worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null), |
| 796 | ...((workspaceSelection?.startFromOrigin ?? startFromOrigin) |
| 797 | ? { startFromOrigin: true } |
| 798 | : {}), |
| 799 | }, |
| 800 | createdAt: metadata.createdAt, |
| 801 | }; |
| 802 | }; |
| 803 | |
| 804 | const scratchEnvironments = connectedEnvironments.filter( |
| 805 | (environment) => |
| 806 | availableScratchWorkspaceRoot( |
| 807 | environment.connectionState, |
| 808 | serverConfigs.get(environment.environmentId), |
| 809 | ) !== null, |
| 810 | ); |
| 811 | |
| 812 | const selectedRepositoryKey = selectedProject?.repositoryIdentity |
| 813 | ? repositoryGroupingKeyOf(selectedProject.repositoryIdentity) |
| 814 | : null; |
| 815 | // Use || null: placeholder workspaceRoot can be empty, and an empty basename rejects real hosts. |
| 816 | const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null; |
| 817 | const selectedProjectTitle = selectedProject?.title ?? null; |
| 818 | const environments = (() => { |
| 819 | if (isScratchDraft) { |
| 820 | return scratchEnvironments.map((environment) => ({ |
| 821 | environmentId: environment.environmentId, |
| 822 | environmentLabel: environment.environmentLabel, |
| 823 | })); |
| 824 | } |
| 825 | const seen = new Set<EnvironmentId>(); |
| 826 | const result: Array<{ |
| 827 | readonly environmentId: EnvironmentId; |
| 828 | readonly environmentLabel: string; |
| 829 | }> = []; |
| 830 | const hostsSelectedRepository = (project: EnvironmentProject) => { |
| 831 | if (selectedRepositoryKey === null && selectedWorkspaceBasename === null) { |
| 832 | return true; |
| 833 | } |
| 834 | const projectKey = project.repositoryIdentity |
| 835 | ? repositoryGroupingKeyOf(project.repositoryIdentity) |
| 836 | : null; |
| 837 | if (selectedRepositoryKey !== null && projectKey !== null) { |
| 838 | return projectKey === selectedRepositoryKey; |
| 839 | } |
| 840 | return ( |
| 841 | project.workspaceRoot.split("/").at(-1) === selectedWorkspaceBasename || |
| 842 | (selectedProjectTitle !== null && project.title === selectedProjectTitle) |
| 843 | ); |
| 844 | }; |
| 845 | for (const project of projects) { |
| 846 | if (!hostsSelectedRepository(project)) { |
| 847 | continue; |
| 848 | } |
| 849 | if (seen.has(project.environmentId)) { |
| 850 | continue; |
| 851 | } |
| 852 | const environment = savedConnectionsById[project.environmentId]; |
| 853 | if (!environment) { |
| 854 | continue; |
| 855 | } |
| 856 | seen.add(project.environmentId); |
| 857 | result.push({ |
| 858 | environmentId: project.environmentId, |
| 859 | environmentLabel: environment.environmentLabel, |
| 860 | }); |
| 861 | } |
| 862 | return result; |
| 863 | })(); |
| 864 | |
| 865 | const value = { |
| 866 | activeNewTask, |
| 867 | projectScopes, |
| 868 | selectedEnvironmentId, |
| 869 | selectedProjectKey, |
| 870 | selectedModelKey, |
| 871 | workspaceMode, |
| 872 | isGitRepo, |
| 873 | isGitRepoKnown: knownIsGitRepo !== null, |
| 874 | canChooseWorkspace, |
| 875 | selectedBranchName, |
| 876 | selectedWorktreePath, |
| 877 | workspaceCwd, |
| 878 | resolveWorkspaceSelection, |
| 879 | startFromOrigin, |
| 880 | draftKey: selectedProjectDraftKey, |
| 881 | pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference, |
| 882 | prompt, |
| 883 | attachments, |
| 884 | submitting, |
| 885 | branchesLoading, |
| 886 | availableBranches, |
| 887 | currentCheckoutBranchName, |
| 888 | runtimeMode, |
| 889 | expandedProvider, |
| 890 | environments, |
| 891 | selectedProject, |
| 892 | linkedEnvironments, |
| 893 | isScratchDraft, |
| 894 | modelOptions, |
| 895 | selectedModel, |
| 896 | selectedModelOption, |
| 897 | selectedProviderStatus, |
| 898 | providerGroups, |
| 899 | setProject, |
| 900 | getSelectedProjectKey: () => readFlow().projectKey, |
| 901 | unopenableRouteDraft: |
| 902 | props.routeDraftId !== undefined && |
| 903 | (routeDraftResolution.kind === "missing" || routeDraftResolution.kind === "pickProject") |
| 904 | ? { draftId: props.routeDraftId, kind: routeDraftResolution.kind } |
| 905 | : null, |
| 906 | selectEnvironment, |
| 907 | switchEnvironment, |
| 908 | switchingToEnvironmentId, |
| 909 | setSelectedModelKey, |
| 910 | setWorkspaceMode, |
| 911 | selectBranch, |
| 912 | setStartFromOrigin, |
| 913 | buildPendingTaskMessage, |
| 914 | setPrompt, |
| 915 | replaceAttachments, |
| 916 | appendAttachments, |
| 917 | removeAttachment, |
| 918 | clearAttachments, |
| 919 | setSubmitting: (value: boolean) => { |
| 920 | // A send takes the draft as it is, so a machine switch still waiting is dropped. |
| 921 | if (value) { |
| 922 | latestSwitchRef.current = null; |
| 923 | setSwitchingToEnvironmentId(null); |
| 924 | } |
| 925 | updateFlow({ submitting: value }); |
| 926 | }, |
| 927 | loadBranches, |
| 928 | setRuntimeMode, |
| 929 | setSelectedModelOptions, |
| 930 | setExpandedProvider: (value: string | null) => updateFlow({ expandedProvider: value }), |
| 931 | } satisfies NewTaskFlowContextValue; |
| 932 | |
| 933 | return ( |
| 934 | <ActiveNewTaskContext value={activeNewTask}> |
| 935 | <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider> |
| 936 | </ActiveNewTaskContext> |
| 937 | ); |
| 938 | } |
| 939 | |
| 940 | export function useNewTaskFlow() { |
| 941 | const value = React.use(NewTaskFlowContext); |
| 942 | if (value === null) { |
| 943 | throw new Error("useNewTaskFlow must be used within NewTaskFlowProvider."); |
| 944 | } |
| 945 | return value; |
| 946 | } |