Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectDefaultsSettings.tsx

495 lines20.7 KB

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