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