Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 type ModelSelection,
4 type ProviderInstanceId,
5 type WorktreeSubmodules,
6} from "@t3tools/contracts";
7import { createModelSelection } from "@t3tools/shared/model";
8import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
9import { useNavigate } from "@tanstack/react-router";
10
11import { mergeEnvironmentSettings } from "../../hooks/useSettings";
12import {
13 getCustomModelOptionsByInstance,
14 resolveEffectiveDefaultModelSelection,
15} from "../../modelSelection";
16import {
17 applyProviderInstanceSettings,
18 deriveProviderInstanceEntries,
19 resolveDefaultProviderModelSelection,
20 sortProviderInstanceEntries,
21} from "../../providerInstances";
22import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
23import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
24import { resolveEnvModeLabel, WORKTREE_SUBMODULES_LABELS } from "../BranchToolbar.logic";
25import { ProviderModelPicker } from "../chat/ProviderModelPicker";
26import { runtimeModeConfig, runtimeModeOptions } from "../chat/runtimeModeConfig";
27import { PULL_REQUEST_MERGE_METHOD_LABELS } from "../pullRequest/pullRequestDetail.logic";
28import { TraitsPicker } from "../chat/TraitsPicker";
29import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
30import { toastManager } from "../ui/toast";
31import { Switch } from "../ui/switch";
32import type { ProjectSettingsCategory } from "./ProjectSettingsPanel";
33import { searchableSetting } from "./settingsSearch";
34import { useSettingsScope } from "./SettingsScopeContext";
35import {
36 SETTINGS_PICKER_TRIGGER_CLASSNAME,
37 SettingResetButton,
38 SettingsRow,
39 SettingsSection,
40} from "./settingsLayout";
41import {
42 useScopedSettings,
43 useScopedSettingsMixed,
44 useScopedSettingSource,
45 useUpdateScopedSettings,
46} from "./useScopedSettings";
47
48const WORKTREE_SUBMODULES_OPTIONS = ["recursive", "top-level", "none"] as const;
49function isWorktreeSubmodules(value: string | null): value is WorktreeSubmodules {
50 return value !== null && (WORKTREE_SUBMODULES_OPTIONS as readonly string[]).includes(value);
51}
52
53export function ProjectDefaultsSettings({ category }: { category: ProjectSettingsCategory }) {
54 const { scope, target, targets, connectedEnvironments } = useSettingsScope();
55 const settings = useScopedSettings();
56 const updateSettings = useUpdateScopedSettings();
57 const navigate = useNavigate();
58 const { environments } = useEnvironments();
59 const providersByEnvironment = useEnvironmentProviders();
60 const representative = target
61 ? environments.find((environment) => environment.environmentId === target.environmentId)
62 : undefined;
63 const providers =
64 (representative?.serverConfig
65 ? providersByEnvironment.get(representative.environmentId)
66 : undefined) ?? EMPTY_SERVER_PROVIDERS;
67 const storedSelection = resolveDefaultProviderModelSelection(
68 providers,
69 settings.defaultModelSelection,
70 );
71 const selection = storedSelection
72 ? resolveEffectiveDefaultModelSelection(settings, providers, storedSelection)
73 : null;
74 const entries = sortProviderInstanceEntries(
75 applyProviderInstanceSettings(
76 deriveProviderInstanceEntries(providers),
77 settings,
78 target?.projectId ?? null,
79 ),
80 );
81 const modelOptions = getCustomModelOptionsByInstance(
82 settings,
83 providers,
84 selection?.instanceId,
85 selection?.model,
86 );
87 const activeEntry = entries.find((entry) => entry.instanceId === selection?.instanceId);
88 const mixedModel = useScopedSettingsMixed(["defaultModelSelection"]);
89 const mixedPermissions = useScopedSettingsMixed(["defaultRuntimeMode"]);
90 const PermissionIcon = runtimeModeConfig[settings.defaultRuntimeMode].icon;
91 const mixedWorkspace = useScopedSettingsMixed(["defaultThreadEnvMode"]);
92 const mixedSubmodules = useScopedSettingsMixed(["worktreeSubmodules"]);
93 const mixedAutoPull = useScopedSettingsMixed(["defaultAutoPull"]);
94 const mixedAgentCredits = useScopedSettingsMixed(["removeAgentCreditsOnMerge"]);
95 const mixedMergeMethod = useScopedSettingsMixed(["pullRequestMergeMethod"]);
96 const modelSource = useScopedSettingSource(["defaultModelSelection"]);
97 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
98 const unavailable = connectedEnvironments.length === 0;
99 const effective = target
100 ? resolveProjectSettings(target.settings, null, null, null).settings
101 : null;
102
103 function modelDisabledReason(instanceId: ProviderInstanceId, model: string): string | null {
104 const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
105 for (const candidate of targets) {
106 const environment = environments.find(
107 (entry) => entry.environmentId === candidate.environmentId,
108 );
109 const providers = providersByEnvironment.get(candidate.environmentId);
110 if (!environment?.serverConfig || !providers) continue;
111 const entry = applyProviderInstanceSettings(
112 deriveProviderInstanceEntries(providers),
113 candidate.settings,
114 candidate.projectId,
115 ).find((option) => option.instanceId === instanceId);
116 const options = getCustomModelOptionsByInstance(
117 mergeEnvironmentSettings(candidate.settings, settings),
118 providers,
119 ).get(instanceId);
120 if (
121 !entry?.enabled ||
122 !entry.isAvailable ||
123 entry.driverKind !== sourceEntry?.driverKind ||
124 !options?.some((option) => option.slug === model && !option.isUnavailable)
125 ) {
126 return `This model is unavailable on ${environment?.label ?? "a selected environment"}. Select that environment to choose its model separately.`;
127 }
128 }
129 return null;
130 }
131
132 const setModel = (value: ModelSelection | null) => {
133 const reason = value ? modelDisabledReason(value.instanceId, value.model) : null;
134 if (reason) {
135 toastManager.add({ type: "error", title: "Default model not saved", description: reason });
136 return;
137 }
138 updateSettings({ defaultModelSelection: value });
139 };
140
141 const modelRow = (
142 <SettingsRow
143 serverScoped
144 settingKeys={["defaultModelSelection"]}
145 mixed={mixedModel}
146 id="default-model"
147 title="Model"
148 description={
149 isProjectScope
150 ? "Model for new threads in this project."
151 : !unavailable &&
152 !mixedModel &&
153 modelSource !== "project" &&
154 settings.defaultModelSelection === null
155 ? "Default model for new threads, selected automatically. Projects can override it."
156 : "Default model for new threads. Projects can override it."
157 }
158 resetAction={
159 settings.defaultModelSelection !== null ? (
160 <SettingResetButton label="default model" onClick={() => setModel(null)} />
161 ) : null
162 }
163 control={
164 selection && activeEntry ? (
165 <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
166 <ProviderModelPicker
167 environmentId={representative?.environmentId ?? null}
168 activeInstanceId={selection.instanceId}
169 model={selection.model}
170 lockedProvider={null}
171 instanceEntries={entries}
172 modelOptionsByInstance={modelOptions}
173 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
174 {...(mixedModel ? { triggerLabel: "Mixed" } : {})}
175 getModelDisabledReason={modelDisabledReason}
176 onOpenProviderSetup={(instanceId) => {
177 if (representative)
178 void navigate({
179 to: "/settings/providers",
180 search: { environmentId: representative.environmentId, instanceId },
181 });
182 }}
183 onInstanceModelChange={(instanceId, model) =>
184 setModel(createModelSelection(instanceId, model))
185 }
186 />
187 {!mixedModel ? (
188 <TraitsPicker
189 provider={activeEntry.driverKind}
190 models={activeEntry.models}
191 model={selection.model}
192 modelOptions={selection.options ?? []}
193 allowPromptInjectedEffort={false}
194 planModeEnabled={settings.planModeEnabled}
195 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
196 onModelOptionsChange={(options) =>
197 setModel(createModelSelection(selection.instanceId, selection.model, options))
198 }
199 />
200 ) : null}
201 </div>
202 ) : (
203 <span className="text-sm text-muted-foreground">No providers available</span>
204 )
205 }
206 />
207 );
208 const workspaceRow = (
209 <SettingsRow
210 serverScoped
211 settingKeys={["defaultThreadEnvMode"]}
212 mixed={mixedWorkspace}
213 id={searchableSetting("new-threads").id}
214 title="Workspace"
215 description={
216 isProjectScope
217 ? "Where new threads in this project start."
218 : "Where new threads start. Projects and their t3.json can override it."
219 }
220 resetAction={
221 !isProjectScope && settings.defaultThreadEnvMode !== null ? (
222 <SettingResetButton
223 label="default workspace"
224 onClick={() => updateSettings({ defaultThreadEnvMode: null })}
225 />
226 ) : null
227 }
228 control={
229 <Select
230 value={mixedWorkspace ? null : (effective?.defaultThreadEnvMode ?? null)}
231 onValueChange={(value) => {
232 if (value === "local" || value === "worktree")
233 updateSettings({ defaultThreadEnvMode: value });
234 }}
235 >
236 <SelectTrigger size="sm" aria-label="Default workspace">
237 <SelectValue>
238 {(value: string | null) =>
239 value === "local" || value === "worktree"
240 ? resolveEnvModeLabel(value)
241 : unavailable
242 ? "Unavailable"
243 : "Mixed"
244 }
245 </SelectValue>
246 </SelectTrigger>
247 <SelectPopup align="end" alignItemWithTrigger={false}>
248 <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
249 <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
250 </SelectPopup>
251 </Select>
252 }
253 />
254 );
255
256 return (
257 <SettingsSection
258 id={category === "source-control" ? "source-control-defaults" : "project-defaults"}
259 title={category === "source-control" ? "Repositories" : "New threads"}
260 >
261 {category === "project" ? (
262 <>
263 {modelRow}
264 {workspaceRow}
265 </>
266 ) : category === "general" ? (
267 <>
268 {modelRow}
269 <SettingsRow
270 serverScoped
271 settingKeys={["defaultRuntimeMode"]}
272 mixed={mixedPermissions}
273 {...searchableSetting("default-permissions")}
274 description={
275 isProjectScope
276 ? "Permissions for new threads in this project."
277 : "Default permissions for new threads. Projects can override them."
278 }
279 resetAction={
280 settings.defaultRuntimeMode !== DEFAULT_SERVER_SETTINGS.defaultRuntimeMode ? (
281 <SettingResetButton
282 label="default permissions"
283 onClick={() =>
284 updateSettings({
285 defaultRuntimeMode: DEFAULT_SERVER_SETTINGS.defaultRuntimeMode,
286 })
287 }
288 />
289 ) : null
290 }
291 control={
292 <Select
293 value={mixedPermissions ? null : settings.defaultRuntimeMode}
294 onValueChange={(value) => {
295 if (value) updateSettings({ defaultRuntimeMode: value });
296 }}
297 >
298 <SelectTrigger size="sm" aria-label="Default permissions">
299 {!mixedPermissions && (
300 <PermissionIcon className="size-3.5 shrink-0 text-muted-foreground" />
301 )}
302 <SelectValue>
303 {mixedPermissions
304 ? "Mixed"
305 : runtimeModeConfig[settings.defaultRuntimeMode].label}
306 </SelectValue>
307 </SelectTrigger>
308 <SelectPopup align="end" alignItemWithTrigger={false}>
309 {runtimeModeOptions.map((mode) => {
310 const option = runtimeModeConfig[mode];
311 const Icon = option.icon;
312 return (
313 <SelectItem key={mode} value={mode} className="min-w-64">
314 <div className="grid gap-0.5">
315 <span className="inline-flex items-center gap-1.5 font-medium">
316 <Icon className="size-3.5 shrink-0 text-muted-foreground" />
317 {option.label}
318 </span>
319 <span className="text-xs leading-4 text-muted-foreground">
320 {option.description}
321 </span>
322 </div>
323 </SelectItem>
324 );
325 })}
326 </SelectPopup>
327 </Select>
328 }
329 />
330 {workspaceRow}
331 <SettingsRow
332 serverScoped
333 settingKeys={["worktreeSubmodules"]}
334 mixed={mixedSubmodules}
335 {...searchableSetting("worktree-submodules")}
336 description={
337 isProjectScope
338 ? "How new worktrees in this project populate git submodules."
339 : "How new worktrees populate git submodules. Projects and their t3.json can override it."
340 }
341 resetAction={
342 !isProjectScope && settings.worktreeSubmodules !== null ? (
343 <SettingResetButton
344 label="worktree submodules"
345 onClick={() => updateSettings({ worktreeSubmodules: null })}
346 />
347 ) : null
348 }
349 control={
350 <Select
351 value={mixedSubmodules ? null : (effective?.worktreeSubmodules ?? null)}
352 onValueChange={(value) => {
353 if (isWorktreeSubmodules(value)) updateSettings({ worktreeSubmodules: value });
354 }}
355 >
356 <SelectTrigger size="sm" aria-label="Worktree submodules">
357 <SelectValue>
358 {(value: string | null) =>
359 isWorktreeSubmodules(value)
360 ? WORKTREE_SUBMODULES_LABELS[value]
361 : unavailable
362 ? "Unavailable"
363 : "Mixed"
364 }
365 </SelectValue>
366 </SelectTrigger>
367 <SelectPopup align="end" alignItemWithTrigger={false}>
368 {WORKTREE_SUBMODULES_OPTIONS.map((option) => (
369 <SelectItem key={option} value={option}>
370 {WORKTREE_SUBMODULES_LABELS[option]}
371 </SelectItem>
372 ))}
373 </SelectPopup>
374 </Select>
375 }
376 />
377 </>
378 ) : (
379 <>
380 <SettingsRow
381 serverScoped
382 settingKeys={["defaultAutoPull"]}
383 mixed={mixedAutoPull}
384 id="automatic-pull"
385 title="Automatically pull"
386 description={
387 isProjectScope
388 ? "Keeps this project's default branch current when the checkout has no local changes or commits."
389 : "Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
390 }
391 resetAction={
392 settings.defaultAutoPull ? (
393 <SettingResetButton
394 label="default automatic pull"
395 tooltip="Reset automatic pull to off"
396 onClick={() => updateSettings({ defaultAutoPull: false })}
397 />
398 ) : null
399 }
400 control={
401 <Switch
402 aria-label="Default automatic pull"
403 mixed={mixedAutoPull}
404 checked={mixedAutoPull ? false : settings.defaultAutoPull}
405 onCheckedChange={(enabled) => updateSettings({ defaultAutoPull: enabled })}
406 />
407 }
408 />
409 <SettingsRow
410 serverScoped
411 settingKeys={["removeAgentCreditsOnMerge"]}
412 mixed={mixedAgentCredits}
413 {...searchableSetting("remove-agent-credits-on-merge")}
414 description="Remove recognized agent credit lines from merge and squash messages on hosts that support it, keeping human co-authors. Includes auto-merge. Excludes merge queues, stack merges, and existing commits."
415 resetAction={
416 settings.removeAgentCreditsOnMerge ? (
417 <SettingResetButton
418 label="agent credit removal"
419 tooltip="Keep agent credits"
420 onClick={() => updateSettings({ removeAgentCreditsOnMerge: false })}
421 />
422 ) : null
423 }
424 control={
425 <Switch
426 aria-label="Remove agent credits when merging"
427 mixed={mixedAgentCredits}
428 checked={mixedAgentCredits ? false : settings.removeAgentCreditsOnMerge}
429 onCheckedChange={(enabled) =>
430 updateSettings({ removeAgentCreditsOnMerge: enabled })
431 }
432 />
433 }
434 />
435 <SettingsRow
436 serverScoped
437 settingKeys={["pullRequestMergeMethod"]}
438 mixed={mixedMergeMethod}
439 {...searchableSetting("pull-request-merge-method")}
440 description={
441 isProjectScope
442 ? "Pull requests in this project start with this method."
443 : "Pull requests start with this method. Last selected reuses whatever you chose most recently on this device."
444 }
445 resetAction={
446 settings.pullRequestMergeMethod !== null ? (
447 <SettingResetButton
448 label="default merge method"
449 tooltip="Reset to last selected"
450 onClick={() => updateSettings({ pullRequestMergeMethod: null })}
451 />
452 ) : null
453 }
454 control={
455 <Select
456 value={mixedMergeMethod ? null : (settings.pullRequestMergeMethod ?? "last")}
457 onValueChange={(value) => {
458 if (value === "last") updateSettings({ pullRequestMergeMethod: null });
459 else if (value === "merge" || value === "squash" || value === "rebase")
460 updateSettings({ pullRequestMergeMethod: value });
461 }}
462 >
463 <SelectTrigger size="sm" aria-label="Default pull request merge method">
464 <SelectValue>
465 {(value: string | null) =>
466 value === "merge" || value === "squash" || value === "rebase"
467 ? PULL_REQUEST_MERGE_METHOD_LABELS[value]
468 : value === "last"
469 ? "Last selected"
470 : "Mixed"
471 }
472 </SelectValue>
473 </SelectTrigger>
474 <SelectPopup align="end" alignItemWithTrigger={false}>
475 <SelectItem value="last">Last selected</SelectItem>
476 <SelectItem value="merge">{PULL_REQUEST_MERGE_METHOD_LABELS.merge}</SelectItem>
477 <SelectItem value="squash">{PULL_REQUEST_MERGE_METHOD_LABELS.squash}</SelectItem>
478 <SelectItem value="rebase">{PULL_REQUEST_MERGE_METHOD_LABELS.rebase}</SelectItem>
479 </SelectPopup>
480 </Select>
481 }
482 />
483 </>
484 )}
485 </SettingsSection>
486 );
487}