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

ProjectDefaultsSettings.tsx

459 lines19.1 KB

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