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 : "Default model for new threads. Projects can override it."
152 }
153 status={
154 unavailable || mixedModel || modelSource === "project"
155 ? undefined
156 : settings.defaultModelSelection === null
157 ? "Automatic"
158 : undefined
159 }
160 resetAction={
161 settings.defaultModelSelection !== null ? (
162 <SettingResetButton label="default model" onClick={() => setModel(null)} />
163 ) : null
164 }
165 control={
166 selection && activeEntry ? (
167 <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
168 <ProviderModelPicker
169 environmentId={representative?.environmentId ?? null}
170 activeInstanceId={selection.instanceId}
171 model={selection.model}
172 lockedProvider={null}
173 instanceEntries={entries}
174 modelOptionsByInstance={modelOptions}
175 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
176 {...(mixedModel ? { triggerLabel: "Mixed" } : {})}
177 getModelDisabledReason={modelDisabledReason}
178 onOpenProviderSetup={(instanceId) => {
179 if (representative)
180 void navigate({
181 to: "/settings/providers",
182 search: { environmentId: representative.environmentId, instanceId },
183 });
184 }}
185 onInstanceModelChange={(instanceId, model) =>
186 setModel(createModelSelection(instanceId, model))
187 }
188 />
189 {!mixedModel ? (
190 <TraitsPicker
191 provider={activeEntry.driverKind}
192 models={activeEntry.models}
193 model={selection.model}
194 modelOptions={selection.options ?? []}
195 allowPromptInjectedEffort={false}
196 planModeEnabled={settings.planModeEnabled}
197 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
198 onModelOptionsChange={(options) =>
199 setModel(createModelSelection(selection.instanceId, selection.model, options))
200 }
201 />
202 ) : null}
203 </div>
204 ) : (
205 <span className="text-sm text-muted-foreground">No providers available</span>
206 )
207 }
208 />
209 );
210 const workspaceRow = (
211 <SettingsRow
212 serverScoped
213 settingKeys={["defaultThreadEnvMode"]}
214 mixed={mixedWorkspace}
215 id={searchableSetting("new-threads").id}
216 title="Workspace"
217 description={
218 isProjectScope
219 ? "Where new threads in this project start."
220 : "Where new threads start. Projects and their t3.json can override it."
221 }
222 resetAction={
223 !isProjectScope && settings.defaultThreadEnvMode !== null ? (
224 <SettingResetButton
225 label="default workspace"
226 onClick={() => updateSettings({ defaultThreadEnvMode: null })}
227 />
228 ) : null
229 }
230 control={
231 <Select
232 value={mixedWorkspace ? null : (effective?.defaultThreadEnvMode ?? null)}
233 onValueChange={(value) => {
234 if (value === "local" || value === "worktree")
235 updateSettings({ defaultThreadEnvMode: value });
236 }}
237 >
238 <SelectTrigger size="sm" aria-label="Default workspace">
239 <SelectValue>
240 {(value: string | null) =>
241 value === "local" || value === "worktree"
242 ? resolveEnvModeLabel(value)
243 : unavailable
244 ? "Unavailable"
245 : "Mixed"
246 }
247 </SelectValue>
248 </SelectTrigger>
249 <SelectPopup align="end" alignItemWithTrigger={false}>
250 <SelectItem value="local">{resolveEnvModeLabel("local")}</SelectItem>
251 <SelectItem value="worktree">{resolveEnvModeLabel("worktree")}</SelectItem>
252 </SelectPopup>
253 </Select>
254 }
255 />
256 );
257
258 return (
259 <SettingsSection
260 id={category === "source-control" ? "source-control-defaults" : "project-defaults"}
261 title={category === "source-control" ? "Repositories" : "New threads"}
262 >
263 {category === "project" ? (
264 <>
265 {modelRow}
266 {workspaceRow}
267 </>
268 ) : category === "general" ? (
269 <>
270 {modelRow}
271 <SettingsRow
272 serverScoped
273 settingKeys={["defaultRuntimeMode"]}
274 mixed={mixedPermissions}
275 {...searchableSetting("default-permissions")}
276 description={
277 isProjectScope
278 ? "Permissions for new threads in this project."
279 : "Default permissions for new threads. Projects can override them."
280 }
281 resetAction={
282 settings.defaultRuntimeMode !== DEFAULT_SERVER_SETTINGS.defaultRuntimeMode ? (
283 <SettingResetButton
284 label="default permissions"
285 onClick={() =>
286 updateSettings({
287 defaultRuntimeMode: DEFAULT_SERVER_SETTINGS.defaultRuntimeMode,
288 })
289 }
290 />
291 ) : null
292 }
293 control={
294 <Select
295 value={mixedPermissions ? null : settings.defaultRuntimeMode}
296 onValueChange={(value) => {
297 if (value) updateSettings({ defaultRuntimeMode: value });
298 }}
299 >
300 <SelectTrigger size="sm" aria-label="Default permissions">
301 {!mixedPermissions && (
302 <PermissionIcon className="size-3.5 shrink-0 text-muted-foreground" />
303 )}
304 <SelectValue>
305 {mixedPermissions
306 ? "Mixed"
307 : runtimeModeConfig[settings.defaultRuntimeMode].label}
308 </SelectValue>
309 </SelectTrigger>
310 <SelectPopup align="end" alignItemWithTrigger={false}>
311 {runtimeModeOptions.map((mode) => {
312 const option = runtimeModeConfig[mode];
313 const Icon = option.icon;
314 return (
315 <SelectItem key={mode} value={mode} className="min-w-64">
316 <div className="grid gap-0.5">
317 <span className="inline-flex items-center gap-1.5 font-medium">
318 <Icon className="size-3.5 shrink-0 text-muted-foreground" />
319 {option.label}
320 </span>
321 <span className="text-xs leading-4 text-muted-foreground">
322 {option.description}
323 </span>
324 </div>
325 </SelectItem>
326 );
327 })}
328 </SelectPopup>
329 </Select>
330 }
331 />
332 {workspaceRow}
333 <SettingsRow
334 serverScoped
335 settingKeys={["worktreeSubmodules"]}
336 mixed={mixedSubmodules}
337 {...searchableSetting("worktree-submodules")}
338 description={
339 isProjectScope
340 ? "How new worktrees in this project populate git submodules."
341 : "How new worktrees populate git submodules. Projects and their t3.json can override it."
342 }
343 resetAction={
344 !isProjectScope && settings.worktreeSubmodules !== null ? (
345 <SettingResetButton
346 label="worktree submodules"
347 onClick={() => updateSettings({ worktreeSubmodules: null })}
348 />
349 ) : null
350 }
351 control={
352 <Select
353 value={mixedSubmodules ? null : (effective?.worktreeSubmodules ?? null)}
354 onValueChange={(value) => {
355 if (isWorktreeSubmodules(value)) updateSettings({ worktreeSubmodules: value });
356 }}
357 >
358 <SelectTrigger size="sm" aria-label="Worktree submodules">
359 <SelectValue>
360 {(value: string | null) =>
361 isWorktreeSubmodules(value)
362 ? WORKTREE_SUBMODULES_LABELS[value]
363 : unavailable
364 ? "Unavailable"
365 : "Mixed"
366 }
367 </SelectValue>
368 </SelectTrigger>
369 <SelectPopup align="end" alignItemWithTrigger={false}>
370 {WORKTREE_SUBMODULES_OPTIONS.map((option) => (
371 <SelectItem key={option} value={option}>
372 {WORKTREE_SUBMODULES_LABELS[option]}
373 </SelectItem>
374 ))}
375 </SelectPopup>
376 </Select>
377 }
378 />
379 </>
380 ) : (
381 <>
382 <SettingsRow
383 serverScoped
384 settingKeys={["defaultAutoPull"]}
385 mixed={mixedAutoPull}
386 id="automatic-pull"
387 title="Automatically pull"
388 description={
389 isProjectScope
390 ? "Keeps this project's default branch current when the checkout has no local changes or commits."
391 : "Keeps the default branch current when the checkout has no local changes or commits. Projects can override it."
392 }
393 resetAction={
394 settings.defaultAutoPull ? (
395 <SettingResetButton
396 label="default automatic pull"
397 tooltip="Reset automatic pull to off"
398 onClick={() => updateSettings({ defaultAutoPull: false })}
399 />
400 ) : null
401 }
402 control={
403 <Switch
404 aria-label="Default automatic pull"
405 mixed={mixedAutoPull}
406 checked={mixedAutoPull ? false : settings.defaultAutoPull}
407 onCheckedChange={(enabled) => updateSettings({ defaultAutoPull: enabled })}
408 />
409 }
410 />
411 <SettingsRow
412 serverScoped
413 settingKeys={["removeAgentCreditsOnMerge"]}
414 mixed={mixedAgentCredits}
415 {...searchableSetting("remove-agent-credits-on-merge")}
416 description="Remove recognized agent credit lines from GitHub merge and squash messages, keeping human co-authors. Includes auto-merge. Excludes merge queues, stack merges, and existing commits."
417 resetAction={
418 settings.removeAgentCreditsOnMerge ? (
419 <SettingResetButton
420 label="agent credit removal"
421 tooltip="Keep agent credits"
422 onClick={() => updateSettings({ removeAgentCreditsOnMerge: false })}
423 />
424 ) : null
425 }
426 control={
427 <Switch
428 aria-label="Remove agent credits when merging"
429 mixed={mixedAgentCredits}
430 checked={mixedAgentCredits ? false : settings.removeAgentCreditsOnMerge}
431 onCheckedChange={(enabled) =>
432 updateSettings({ removeAgentCreditsOnMerge: enabled })
433 }
434 />
435 }
436 />
437 <SettingsRow
438 serverScoped
439 settingKeys={["pullRequestMergeMethod"]}
440 mixed={mixedMergeMethod}
441 {...searchableSetting("pull-request-merge-method")}
442 description={
443 isProjectScope
444 ? "Pull requests in this project start with this method."
445 : "Pull requests start with this method. Last selected reuses whatever you chose most recently on this device."
446 }
447 resetAction={
448 settings.pullRequestMergeMethod !== null ? (
449 <SettingResetButton
450 label="default merge method"
451 tooltip="Reset to last selected"
452 onClick={() => updateSettings({ pullRequestMergeMethod: null })}
453 />
454 ) : null
455 }
456 control={
457 <Select
458 value={mixedMergeMethod ? null : (settings.pullRequestMergeMethod ?? "last")}
459 onValueChange={(value) => {
460 if (value === "last") updateSettings({ pullRequestMergeMethod: null });
461 else if (value === "merge" || value === "squash" || value === "rebase")
462 updateSettings({ pullRequestMergeMethod: value });
463 }}
464 >
465 <SelectTrigger size="sm" aria-label="Default pull request merge method">
466 <SelectValue>
467 {(value: string | null) =>
468 value === "merge" || value === "squash" || value === "rebase"
469 ? PULL_REQUEST_MERGE_METHOD_LABELS[value]
470 : value === "last"
471 ? "Last selected"
472 : "Mixed"
473 }
474 </SelectValue>
475 </SelectTrigger>
476 <SelectPopup align="end" alignItemWithTrigger={false}>
477 <SelectItem value="last">Last selected</SelectItem>
478 <SelectItem value="merge">{PULL_REQUEST_MERGE_METHOD_LABELS.merge}</SelectItem>
479 <SelectItem value="squash">{PULL_REQUEST_MERGE_METHOD_LABELS.squash}</SelectItem>
480 <SelectItem value="rebase">{PULL_REQUEST_MERGE_METHOD_LABELS.rebase}</SelectItem>
481 </SelectPopup>
482 </Select>
483 }
484 />
485 </>
486 )}
487 </SettingsSection>
488 );
489}