The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; |
| 2 | import type { UnifiedSettings } from "@t3tools/contracts"; |
| 3 | import { useMessages } from "gt-react"; |
| 4 | import type { Dispatch } from "react"; |
| 5 | import type { ComposerThreadTarget, DraftSessionState } from "../../composerDraftStore"; |
| 6 | import { useStableCallback } from "../../hooks/useStableCallback"; |
| 7 | import { useApplyThreadModelPick } from "./useApplyThreadModelPick"; |
| 8 | import { |
| 9 | type EnvironmentId, |
| 10 | type ModelSelection, |
| 11 | ProviderInstanceId, |
| 12 | type ServerProvider, |
| 13 | type ThreadId, |
| 14 | RuntimeMode, |
| 15 | } from "@t3tools/contracts"; |
| 16 | import type { deriveThreadStructureRuntime } from "@t3tools/client-runtime/state/thread-execution"; |
| 17 | import { scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 18 | import { type SetStateAction } from "react"; |
| 19 | import { useNavigate } from "@tanstack/react-router"; |
| 20 | import { toastManager } from "../ui/toast"; |
| 21 | import { resolveAppModelSelectionForInstance } from "../../modelSelection"; |
| 22 | import { |
| 23 | draftModelSelectionApplies, |
| 24 | resolveNewDraftStartFromOrigin, |
| 25 | threadHasStarted, |
| 26 | } from "../../lib/chatThreadActions"; |
| 27 | import { |
| 28 | type DraftThreadEnvMode, |
| 29 | isSameModel, |
| 30 | useComposerDraftStore, |
| 31 | } from "../../composerDraftStore"; |
| 32 | import { |
| 33 | getStartedThreadModelChangeBlockReason, |
| 34 | deriveLockedProvider, |
| 35 | makeModelDisabledReason, |
| 36 | } from "../ChatView.logic"; |
| 37 | interface ComposerSelectionInput { |
| 38 | readonly environmentId: EnvironmentId; |
| 39 | readonly composerDraftTarget: ComposerThreadTarget; |
| 40 | readonly draftThread: DraftSessionState | null; |
| 41 | readonly activeThread: EnvironmentThreadShell | undefined; |
| 42 | readonly activeRuntime: ReturnType<typeof deriveThreadStructureRuntime>; |
| 43 | readonly activeProjectSettings: { |
| 44 | readonly settings: { readonly newWorktreesStartFromOrigin: boolean }; |
| 45 | }; |
| 46 | readonly settings: UnifiedSettings; |
| 47 | readonly providerStatuses: ReadonlyArray<ServerProvider>; |
| 48 | readonly lockedProvider: ReturnType<typeof deriveLockedProvider>; |
| 49 | readonly supportsProviderSwitchingViaHandoff: boolean; |
| 50 | readonly multipleModelSelections: ReadonlyArray<ModelSelection> | null; |
| 51 | readonly runtimeMode: RuntimeMode; |
| 52 | readonly isLocalDraftThread: boolean; |
| 53 | readonly canOverrideServerThreadEnvMode: boolean; |
| 54 | readonly setPendingServerThreadEnvModeEntry: Dispatch< |
| 55 | SetStateAction<{ readonly threadId: ThreadId; readonly mode: DraftThreadEnvMode } | null> |
| 56 | >; |
| 57 | readonly setPendingServerThreadStartFromOriginByThreadId: Dispatch< |
| 58 | SetStateAction<Record<string, boolean>> |
| 59 | >; |
| 60 | readonly scheduleComposerFocus: () => void; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * The composer's choices for the next turn: provider and model, runtime mode, |
| 65 | * and where a new thread runs (local or a new worktree, from the remote's tip or not). |
| 66 | */ |
| 67 | export function useComposerSelection(input: ComposerSelectionInput) { |
| 68 | const { |
| 69 | environmentId, |
| 70 | composerDraftTarget, |
| 71 | draftThread, |
| 72 | activeThread, |
| 73 | activeRuntime, |
| 74 | activeProjectSettings, |
| 75 | settings, |
| 76 | providerStatuses, |
| 77 | lockedProvider, |
| 78 | supportsProviderSwitchingViaHandoff, |
| 79 | multipleModelSelections, |
| 80 | runtimeMode, |
| 81 | isLocalDraftThread, |
| 82 | canOverrideServerThreadEnvMode, |
| 83 | setPendingServerThreadEnvModeEntry, |
| 84 | setPendingServerThreadStartFromOriginByThreadId, |
| 85 | scheduleComposerFocus, |
| 86 | } = input; |
| 87 | const messages = useMessages(); |
| 88 | const navigate = useNavigate(); |
| 89 | const setStickyComposerModelSelection = useComposerDraftStore( |
| 90 | (store) => store.setStickyModelSelection, |
| 91 | ); |
| 92 | const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection); |
| 93 | const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode); |
| 94 | const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); |
| 95 | const applyThreadModelPick = useApplyThreadModelPick(); |
| 96 | |
| 97 | const handleRuntimeModeChange = (mode: RuntimeMode) => { |
| 98 | if (mode === runtimeMode) return; |
| 99 | setComposerDraftRuntimeMode(composerDraftTarget, mode); |
| 100 | if (isLocalDraftThread) { |
| 101 | setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); |
| 102 | } |
| 103 | scheduleComposerFocus(); |
| 104 | }; |
| 105 | const handleRuntimeModeChangeStable = useStableCallback(handleRuntimeModeChange); |
| 106 | |
| 107 | const openProviderSetup = (instanceId: ProviderInstanceId) => { |
| 108 | void navigate({ |
| 109 | to: "/settings/providers", |
| 110 | search: { environmentId, instanceId }, |
| 111 | }); |
| 112 | }; |
| 113 | const openProviderSetupStable = useStableCallback(openProviderSetup); |
| 114 | |
| 115 | // Keyed on the fields it reads: the thread and runtime objects change with |
| 116 | // every streamed event, and a new function re-renders the whole model picker. |
| 117 | const hasStartedSession = activeRuntime !== null; |
| 118 | const runtimeProviderInstanceId = activeRuntime?.providerInstanceId ?? null; |
| 119 | const currentModelSelection = activeThread?.modelSelection ?? null; |
| 120 | const getModelDisabledReason = makeModelDisabledReason( |
| 121 | currentModelSelection |
| 122 | ? { |
| 123 | hasStartedSession, |
| 124 | supportsProviderSwitchingViaHandoff, |
| 125 | currentModelSelection, |
| 126 | currentProviderInstanceId: runtimeProviderInstanceId, |
| 127 | } |
| 128 | : null, |
| 129 | messages, |
| 130 | ); |
| 131 | |
| 132 | const onProviderModelSelect = ( |
| 133 | instanceId: ProviderInstanceId, |
| 134 | model: string, |
| 135 | options?: { focusComposer?: boolean }, |
| 136 | ) => { |
| 137 | if (!activeThread) return; |
| 138 | const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId); |
| 139 | const resolvedDriverKind = entry?.driver ?? null; |
| 140 | if ( |
| 141 | !supportsProviderSwitchingViaHandoff && |
| 142 | lockedProvider !== null && |
| 143 | resolvedDriverKind !== null && |
| 144 | resolvedDriverKind !== lockedProvider |
| 145 | ) { |
| 146 | if (options?.focusComposer !== false) scheduleComposerFocus(); |
| 147 | return; |
| 148 | } |
| 149 | if ( |
| 150 | !supportsProviderSwitchingViaHandoff && |
| 151 | lockedProvider !== null && |
| 152 | activeRuntime?.providerInstanceId |
| 153 | ) { |
| 154 | const currentEntry = providerStatuses.find( |
| 155 | (snapshot) => snapshot.instanceId === activeRuntime.providerInstanceId, |
| 156 | ); |
| 157 | if ( |
| 158 | currentEntry?.continuation?.groupKey && |
| 159 | entry?.continuation?.groupKey && |
| 160 | currentEntry.continuation.groupKey !== entry.continuation.groupKey |
| 161 | ) { |
| 162 | if (options?.focusComposer !== false) scheduleComposerFocus(); |
| 163 | return; |
| 164 | } |
| 165 | } |
| 166 | // The picker lists an unavailable model only as the active selection, so re-picking keeps it. |
| 167 | const resolvedModel = resolveAppModelSelectionForInstance( |
| 168 | instanceId, |
| 169 | settings, |
| 170 | providerStatuses, |
| 171 | model, |
| 172 | { preserveUnavailableSelection: true }, |
| 173 | ); |
| 174 | const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id); |
| 175 | const storedDraft = useComposerDraftStore.getState().getComposerDraft(threadRef); |
| 176 | const draft = draftModelSelectionApplies(storedDraft, threadHasStarted(activeThread)) |
| 177 | ? storedDraft |
| 178 | : null; |
| 179 | const shownInstanceId = |
| 180 | draft?.activeProvider ?? |
| 181 | activeRuntime?.providerInstanceId ?? |
| 182 | activeThread.modelSelection.instanceId; |
| 183 | const shownSelection = |
| 184 | draft?.modelSelectionByProvider[shownInstanceId] ?? activeThread.modelSelection; |
| 185 | if ( |
| 186 | !resolvedModel || |
| 187 | (instanceId === shownInstanceId && |
| 188 | shownSelection.instanceId === instanceId && |
| 189 | shownSelection.model === resolvedModel) |
| 190 | ) { |
| 191 | // Re-picking the shown model keeps its options and saves it again if that save failed. |
| 192 | if (resolvedModel && !isLocalDraftThread) applyThreadModelPick(threadRef); |
| 193 | if (options?.focusComposer !== false) scheduleComposerFocus(); |
| 194 | return; |
| 195 | } |
| 196 | const rememberedOptions = |
| 197 | useComposerDraftStore.getState().stickyOptionsByModelByProvider[instanceId]?.[resolvedModel]; |
| 198 | const threadSelection = activeThread.modelSelection; |
| 199 | // This pick replaces the stored options, so the thread's own model carries them over. |
| 200 | const pickOptions = |
| 201 | rememberedOptions !== undefined && rememberedOptions.length > 0 |
| 202 | ? rememberedOptions |
| 203 | : threadSelection.instanceId === instanceId && |
| 204 | entry !== undefined && |
| 205 | isSameModel( |
| 206 | { providers: providerStatuses, selectedProvider: entry.driver, settings }, |
| 207 | threadSelection, |
| 208 | { instanceId, model: resolvedModel }, |
| 209 | ) |
| 210 | ? threadSelection.options |
| 211 | : undefined; |
| 212 | const nextModelSelection: ModelSelection = |
| 213 | pickOptions !== undefined && pickOptions.length > 0 |
| 214 | ? { instanceId, model: resolvedModel, options: [...pickOptions] } |
| 215 | : { instanceId, model: resolvedModel }; |
| 216 | const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({ |
| 217 | hasStartedSession: activeRuntime !== null, |
| 218 | supportsProviderSwitchingViaHandoff, |
| 219 | currentModelSelection: activeThread.modelSelection, |
| 220 | currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null, |
| 221 | nextModelSelection, |
| 222 | }); |
| 223 | if (modelChangeBlockReason) { |
| 224 | toastManager.add({ |
| 225 | type: "warning", |
| 226 | title: modelChangeBlockReason.title, |
| 227 | description: modelChangeBlockReason.description, |
| 228 | }); |
| 229 | if (options?.focusComposer !== false) scheduleComposerFocus(); |
| 230 | return; |
| 231 | } |
| 232 | setComposerDraftModelSelection(threadRef, nextModelSelection, { |
| 233 | explicit: true, |
| 234 | replaceOptions: true, |
| 235 | }); |
| 236 | setStickyComposerModelSelection(nextModelSelection); |
| 237 | if (!isLocalDraftThread) applyThreadModelPick(threadRef); |
| 238 | if (options?.focusComposer !== false) scheduleComposerFocus(); |
| 239 | }; |
| 240 | const onProviderModelSelectStable = useStableCallback(onProviderModelSelect); |
| 241 | const onEnvModeChange = (mode: DraftThreadEnvMode) => { |
| 242 | if (multipleModelSelections !== null) return; |
| 243 | if (canOverrideServerThreadEnvMode) { |
| 244 | if (activeThread) setPendingServerThreadEnvModeEntry({ threadId: activeThread.id, mode }); |
| 245 | scheduleComposerFocus(); |
| 246 | return; |
| 247 | } |
| 248 | if (isLocalDraftThread) { |
| 249 | setDraftThreadContext(composerDraftTarget, { |
| 250 | envMode: mode, |
| 251 | startFromOrigin: resolveNewDraftStartFromOrigin({ |
| 252 | envMode: mode, |
| 253 | newWorktreesStartFromOrigin: activeProjectSettings.settings.newWorktreesStartFromOrigin, |
| 254 | }), |
| 255 | ...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}), |
| 256 | }); |
| 257 | } |
| 258 | scheduleComposerFocus(); |
| 259 | }; |
| 260 | const onEnvModeChangeStable = useStableCallback(onEnvModeChange); |
| 261 | |
| 262 | // Reads only the id: the shell changes on every streamed event, and a new handler |
| 263 | // re-renders the branch toolbar and thread details panel with it. |
| 264 | const activeThreadId = activeThread?.id; |
| 265 | const onStartFromOriginChange = (nextStartFromOrigin: boolean) => { |
| 266 | if (canOverrideServerThreadEnvMode && activeThreadId !== undefined) { |
| 267 | setPendingServerThreadStartFromOriginByThreadId((current) => |
| 268 | current[activeThreadId] === nextStartFromOrigin |
| 269 | ? current |
| 270 | : { ...current, [activeThreadId]: nextStartFromOrigin }, |
| 271 | ); |
| 272 | return; |
| 273 | } |
| 274 | if (isLocalDraftThread) { |
| 275 | setDraftThreadContext(composerDraftTarget, { |
| 276 | startFromOrigin: nextStartFromOrigin, |
| 277 | }); |
| 278 | } |
| 279 | }; |
| 280 | return { |
| 281 | getModelDisabledReason, |
| 282 | handleRuntimeModeChangeStable, |
| 283 | onEnvModeChangeStable, |
| 284 | onProviderModelSelectStable, |
| 285 | onStartFromOriginChange, |
| 286 | openProviderSetupStable, |
| 287 | }; |
| 288 | } |