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