From 68d6be0e627d9fe6a7c6e333b3028dda4a97f786 Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Sun, 27 Sep 2026 18:38:52 -0300 Subject: [PATCH 1/4] feat(web): add project-scoped provider profiles - Let projects select provider profiles to focus model pickers on chosen instances - Keep out-of-profile providers reachable and expose profile settings across web and mobile --- .../SettingsServerControlsRouteScreen.tsx | 54 +- .../threads/new-task-flow-provider.tsx | 14 +- apps/mobile/src/lib/modelOptions.test.ts | 27 + apps/mobile/src/lib/modelOptions.ts | 6 + apps/web/src/components/ChatView.tsx | 17 +- .../src/components/ProviderProfileChip.tsx | 25 + .../automations/AutomationsPage.tsx | 18 +- apps/web/src/components/chat/ChatComposer.tsx | 15 +- .../chat/ModelPickerContent.test.ts | 53 ++ .../components/chat/ModelPickerContent.tsx | 97 +++- .../components/chat/ModelPickerSidebar.tsx | 81 ++- .../components/chat/ProviderModelPicker.tsx | 26 +- .../settings/ProjectDefaultsSettings.tsx | 104 +++- .../settings/ProviderInstanceCard.tsx | 27 + .../ProviderProfilesSettings.logic.test.ts | 76 +++ .../ProviderProfilesSettings.logic.ts | 74 +++ .../settings/ProviderProfilesSettings.tsx | 461 ++++++++++++++++++ .../settings/ProviderSettingsPanel.tsx | 21 +- .../settings/SettingInheritance.tsx | 42 +- .../src/components/settings/settingsSearch.ts | 14 + apps/web/src/providerInstances.ts | 16 + docs/user/project-settings.md | 16 + packages/contracts/src/settings.ts | 37 ++ packages/shared/src/projectSettings.test.ts | 99 ++++ packages/shared/src/projectSettings.ts | 53 +- packages/shared/src/serverSettings.ts | 7 + 26 files changed, 1442 insertions(+), 38 deletions(-) create mode 100644 apps/web/src/components/ProviderProfileChip.tsx create mode 100644 apps/web/src/components/settings/ProviderProfilesSettings.logic.test.ts create mode 100644 apps/web/src/components/settings/ProviderProfilesSettings.logic.ts create mode 100644 apps/web/src/components/settings/ProviderProfilesSettings.tsx diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 9368cb94b907e..7e16afd1607fa 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -11,6 +11,7 @@ import { type WorktreeSubmodules, PROJECT_SCOPED_SERVER_SETTING_KEYS, type ProjectScopedServerSettingKey, + type ProviderProfileId, } from "@t3tools/contracts"; import { useRef, useState, type ComponentProps } from "react"; import { Alert, Platform, Pressable, View } from "react-native"; @@ -46,7 +47,12 @@ const PAGE_TITLES: Record = { }; const PAGE_PROJECT_KEYS: Record = { - "new-threads": ["defaultThreadEnvMode", "worktreeSubmodules", "defaultRuntimeMode"], + "new-threads": [ + "providerProfileId", + "defaultThreadEnvMode", + "worktreeSubmodules", + "defaultRuntimeMode", + ], "source-control": ["defaultAutoPull", "newWorktreesStartFromOrigin"], "agent-behavior": ["responseStreamingMode", "enableAgentBrowserAccess"], maintenance: ["continueThreadsAfterServerUpdate"], @@ -208,6 +214,16 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { (target) => target.environment.serverConfig.environment.capabilities.threadRestartContinuation === true, ); + // Profiles are per environment; list every one the selection knows by id. + const profileChoices = [ + ...new Map( + displayTargets.flatMap((target) => + Object.entries(target.settings.providerProfiles).map( + ([id, profile]) => [id, profile] as const, + ), + ), + ), + ]; const disabledFor = (key: string) => disabled || (projectSelected && @@ -250,6 +266,42 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { ) : null} {props.page === "new-threads" ? ( <> + {profileChoices.length > 0 ? ( + + ) : null + } + > + {[ + ...profileChoices.map(([id, profile]) => ({ + id: id as ProviderProfileId, + label: profile.name, + description: `${profile.instanceIds.length} provider${profile.instanceIds.length === 1 ? "" : "s"}`, + })), + { + id: null, + label: "No profile", + description: "Offer every provider in the model picker.", + }, + ].map((choice, index) => ( + 0} + disabled={disabledFor("providerProfileId")} + onPress={() => write({ providerProfileId: choice.id })} + /> + ))} + + ) : null} resolveProviderProfile(projectSettings.settings), + [projectSettings.settings], + ); const storedStickyModelSelection = useStickyComposerModelSelection(); + // The last app-wide pick only carries over when the project's profile has it. const stickyModelSelection = resolveDefaultableModelSelection( selectedEnvironmentServerConfig, - storedStickyModelSelection, + storedStickyModelSelection && + (!providerProfile || providerProfile.instanceIdSet.has(storedStickyModelSelection.instanceId)) + ? storedStickyModelSelection + : null, ); const modelOptions = useMemo( () => buildModelOptions( selectedEnvironmentServerConfig, draftModelSelection ?? projectDefaultModelSelection ?? stickyModelSelection, + providerProfile, ), [ selectedEnvironmentServerConfig, draftModelSelection, projectDefaultModelSelection, stickyModelSelection, + providerProfile, ], ); diff --git a/apps/mobile/src/lib/modelOptions.test.ts b/apps/mobile/src/lib/modelOptions.test.ts index 98896b990ec4a..f83d68043a813 100644 --- a/apps/mobile/src/lib/modelOptions.test.ts +++ b/apps/mobile/src/lib/modelOptions.test.ts @@ -408,4 +408,31 @@ describe("mobile model options", () => { }), ).toBeNull(); }); + + it("offers only the provider profile's instances plus an outside current pick", () => { + const provider = (instanceId: string) => ({ + instanceId, + driver: "claudeAgent", + displayName: instanceId, + enabled: true, + installed: true, + auth: { status: "authenticated" }, + models: [{ slug: "opus", name: "Opus", isCustom: false, capabilities: null }], + }); + const config = { + providers: [provider("cc-a"), provider("cc-b")], + } as unknown as ServerConfig; + const profile = { instanceIdSet: new Set(["cc-a"]) }; + + expect(buildModelOptions(config, null, profile).map((option) => option.key)).toEqual([ + "cc-a:opus", + ]); + expect( + buildModelOptions( + config, + { instanceId: ProviderInstanceId.make("cc-b"), model: "opus" }, + profile, + ).map((option) => option.key), + ).toEqual(["cc-a:opus", "cc-b:opus"]); + }); }); diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.ts index 4e82957331412..6aeaa8c907fd7 100644 --- a/apps/mobile/src/lib/modelOptions.ts +++ b/apps/mobile/src/lib/modelOptions.ts @@ -147,14 +147,20 @@ export function resolveNewTaskModelSelection(input: { ); } +/** + * With a provider profile, only its instances are offered; the fallback + * selection is still listed so a pick outside the profile stays visible. + */ export function buildModelOptions( config: T3ServerConfig | null | undefined, fallbackModelSelection: ModelSelection | null, + providerProfile?: { readonly instanceIdSet: ReadonlySet } | null, ): ReadonlyArray { const options = new Map(); for (const provider of config?.providers ?? []) { if ( + (providerProfile && !providerProfile.instanceIdSet.has(provider.instanceId)) || !provider.enabled || !provider.installed || provider.auth.status === "unauthenticated" || diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 949821ac3ae76..35d50325557cd 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -75,7 +75,7 @@ import { projectScriptRuntimeEnv, resolveProjectScripts, } from "@t3tools/shared/projectScripts"; -import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { resolveProjectSettings, resolveProviderProfile } from "@t3tools/shared/projectSettings"; import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl"; import { truncate } from "@t3tools/shared/String"; import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference"; @@ -259,6 +259,7 @@ import { applyProviderInstanceSettings, deriveProviderInstanceEntries, NO_PROVIDER_MODEL_SELECTION, + leadWithProviderProfile, sortProviderInstanceEntries, } from "../providerInstances"; import { @@ -2277,6 +2278,10 @@ export default function ChatView(props: ChatViewProps) { runProjectCloneAction, ]); const activeProjectDefaultModelSelection = activeProjectSettings.settings.defaultModelSelection; + const activeProviderProfile = useMemo( + () => resolveProviderProfile(activeProjectSettings.settings), + [activeProjectSettings.settings], + ); const handleNewThreadInActiveProject = useCallback(() => { startNewThreadForProject(activeProjectRef, handleNewThread); }, [activeProjectRef, handleNewThread]); @@ -2871,10 +2876,13 @@ export default function ChatView(props: ChatViewProps) { ]); const providerInstanceEntries = useMemo( () => - sortProviderInstanceEntries( - applyProviderInstanceSettings(deriveProviderInstanceEntries(providerStatuses), settings), + leadWithProviderProfile( + sortProviderInstanceEntries( + applyProviderInstanceSettings(deriveProviderInstanceEntries(providerStatuses), settings), + ), + activeProviderProfile, ), - [providerStatuses, settings], + [activeProviderProfile, providerStatuses, settings], ); const { selectedProviderEntry, requestedDriverKind } = useMemo( () => @@ -10098,6 +10106,7 @@ export default function ChatView(props: ChatViewProps) { providerStatuses={providerStatuses as ServerProvider[]} providerCatalogKnown={serverConfig !== null} activeProjectDefaultModelSelection={activeProjectDefaultModelSelection} + activeProviderProfile={activeProviderProfile} activeThreadModelSelection={activeThread?.modelSelection} activeContextWindow={activeContextWindow} compactThreadUnavailable={compactThreadUnavailable} diff --git a/apps/web/src/components/ProviderProfileChip.tsx b/apps/web/src/components/ProviderProfileChip.tsx new file mode 100644 index 0000000000000..86c95224cd753 --- /dev/null +++ b/apps/web/src/components/ProviderProfileChip.tsx @@ -0,0 +1,25 @@ +import type { CSSProperties } from "react"; + +import { Badge } from "./ui/badge"; + +/** A provider profile's name tinted with its color, for pickers and settings rows. */ +export function ProviderProfileChip({ + name, + color, + size = "default", +}: { + name: string; + color?: string | undefined; + size?: "sm" | "default"; +}) { + return ( + + + {name} + + ); +} diff --git a/apps/web/src/components/automations/AutomationsPage.tsx b/apps/web/src/components/automations/AutomationsPage.tsx index 80f9ca0c94b98..4678e1e443ddc 100644 --- a/apps/web/src/components/automations/AutomationsPage.tsx +++ b/apps/web/src/components/automations/AutomationsPage.tsx @@ -15,6 +15,7 @@ import { isValidAutomationCronExpression, resolveEnvironmentMachineKind, } from "@t3tools/contracts"; +import { resolveProjectSettings, resolveProviderProfile } from "@t3tools/shared/projectSettings"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { @@ -48,6 +49,7 @@ import { applyProviderInstanceSettings, deriveProviderInstanceEntries, resolveDefaultProviderModelSelection, + leadWithProviderProfile, sortProviderInstanceEntries, } from "../../providerInstances"; import { @@ -710,6 +712,7 @@ function AutomationEditor({ {environmentId ? ( @@ -1245,6 +1248,7 @@ function ProjectPicker({ /** Instructions and the model that runs them, which also decides the skills "$" offers. */ function AutomationInstructions({ environmentId, + projectId, cwd, prompt, onPromptChange, @@ -1252,6 +1256,7 @@ function AutomationInstructions({ onModelSelectionChange, }: { environmentId: EnvironmentId; + projectId: ProjectId | null; cwd: string | null; prompt: string; onPromptChange: (prompt: string) => void; @@ -1261,13 +1266,19 @@ function AutomationInstructions({ const environment = useEnvironment(environmentId); const settings = useEnvironmentSettings(environmentId); const providers = environment?.serverConfig?.providers ?? EMPTY_SERVER_PROVIDERS; + // Runs resolve the project's default model the same way on the server. + const projectSettings = resolveProjectSettings(settings, projectId).settings; + const providerProfile = resolveProviderProfile(projectSettings); // Until the user picks one, `modelSelection` stays null and runs follow the default model. const selection = resolveDefaultProviderModelSelection( providers, - modelSelection ?? settings.defaultModelSelection, + modelSelection ?? projectSettings.defaultModelSelection, ); - const entries = sortProviderInstanceEntries( - applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings), + const entries = leadWithProviderProfile( + sortProviderInstanceEntries( + applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings), + ), + providerProfile, ); const modelOptions = getCustomModelOptionsByInstance( settings, @@ -1295,6 +1306,7 @@ function AutomationInstructions({ model={selection.model} lockedProvider={null} instanceEntries={entries} + providerProfile={providerProfile} modelOptionsByInstance={modelOptions} onInstanceModelChange={(instanceId, model) => onModelSelectionChange(createModelSelection(instanceId, model)) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 75a4054e77a13..f53e0c6dbd2b7 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -52,6 +52,7 @@ import { import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; import { folderDropTarget, resolveDroppedFolderPath } from "./folderDrop"; import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; +import type { ResolvedProviderProfile } from "@t3tools/shared/projectSettings"; import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; import { memo, @@ -951,6 +952,7 @@ import { applyProviderInstanceSettings, deriveProviderInstanceEntries, NO_PROVIDER_MODEL_SELECTION, + leadWithProviderProfile, sortProviderInstanceEntries, type ProviderInstanceEntry, } from "../../providerInstances"; @@ -1403,6 +1405,8 @@ export interface ChatComposerProps { /** False until the environment's server config has arrived at least once. */ providerCatalogKnown: boolean; activeProjectDefaultModelSelection: ModelSelection | null | undefined; + /** The active project's provider profile; the model picker leads with it. */ + activeProviderProfile: ResolvedProviderProfile | null; activeThreadModelSelection: ModelSelection | null | undefined; // Context window @@ -1532,6 +1536,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) providerStatuses, providerCatalogKnown, activeProjectDefaultModelSelection, + activeProviderProfile, activeThreadModelSelection, activeContextWindow, compactThreadUnavailable, @@ -1872,10 +1877,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // sorted default-first per driver kind for a stable picker order. const providerInstanceEntries = useMemo>( () => - sortProviderInstanceEntries( - applyProviderInstanceSettings(deriveProviderInstanceEntries(providerStatuses), settings), + leadWithProviderProfile( + sortProviderInstanceEntries( + applyProviderInstanceSettings(deriveProviderInstanceEntries(providerStatuses), settings), + ), + activeProviderProfile, ), - [providerStatuses, settings], + [activeProviderProfile, providerStatuses, settings], ); const selectedProviderByThreadId = composerDraft.activeProvider ?? null; const { @@ -5116,6 +5124,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) lockedProvider={lockedProvider} lockedContinuationGroupKey={lockedContinuationGroupKey} instanceEntries={providerInstanceEntries} + providerProfile={activeProviderProfile} keybindings={keybindings} modelOptionsByInstance={modelOptionsByInstance} size={composerControlsInStrip ? "xs" : "sm"} diff --git a/apps/web/src/components/chat/ModelPickerContent.test.ts b/apps/web/src/components/chat/ModelPickerContent.test.ts index 50db51bfa068c..3425ce20288ae 100644 --- a/apps/web/src/components/chat/ModelPickerContent.test.ts +++ b/apps/web/src/components/chat/ModelPickerContent.test.ts @@ -9,6 +9,7 @@ import { describe, expect, it } from "vite-plus/test"; import { deriveProviderInstanceEntries } from "../../providerInstances"; import { adjacentModelPickerProvider, + partitionModelPickerProfileEntries, resolveModelPickerSelectedModel, shouldIncludeModelPickerOption, shouldOfferModelPickerSetup, @@ -285,3 +286,55 @@ describe("adjacentModelPickerProvider", () => { ).toBe(claude.instanceId); }); }); + +describe("partitionModelPickerProfileEntries", () => { + const entries = ["cc_a", "codex_a", "cc_b", "codex_b"].map((id) => ({ + ...entry("ready", "codex"), + instanceId: ProviderInstanceId.make(id), + })); + const ids = (list: ReadonlyArray<{ instanceId: string }>) => list.map((item) => item.instanceId); + const profile = { + name: "Acme", + instanceIdSet: new Set([ProviderInstanceId.make("codex_a"), ProviderInstanceId.make("cc_a")]), + }; + + it("lists only the profile's instances until others are revealed", () => { + const hidden = partitionModelPickerProfileEntries({ + entries, + profile, + showOthers: false, + activeInstanceId: ProviderInstanceId.make("cc_a"), + }); + expect(ids(hidden.entries)).toEqual(["cc_a", "codex_a"]); + expect([...hidden.outsideInstanceIds]).toEqual(["cc_b", "codex_b"]); + + const shown = partitionModelPickerProfileEntries({ + entries, + profile, + showOthers: true, + activeInstanceId: ProviderInstanceId.make("cc_a"), + }); + expect(ids(shown.entries)).toEqual(["cc_a", "codex_a", "cc_b", "codex_b"]); + }); + + it("keeps an active instance outside the profile reachable", () => { + const result = partitionModelPickerProfileEntries({ + entries, + profile, + showOthers: false, + activeInstanceId: ProviderInstanceId.make("codex_b"), + }); + expect(ids(result.entries)).toEqual(["cc_a", "codex_a", "codex_b"]); + }); + + it("changes nothing without a profile", () => { + const result = partitionModelPickerProfileEntries({ + entries, + profile: null, + showOthers: false, + activeInstanceId: ProviderInstanceId.make("cc_b"), + }); + expect(result.entries).toBe(entries); + expect(result.outsideInstanceIds.size).toBe(0); + }); +}); diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 57a04b1a2f24a..3742dd677d229 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -8,8 +8,9 @@ import { resolveSelectableModel } from "@t3tools/shared/model"; import { useAtomValue } from "@effect/atom-react"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react"; -import { ChevronRightIcon } from "lucide-react"; +import { ChevronRightIcon, TriangleAlertIcon } from "lucide-react"; import { ModelListRow } from "./ModelListRow"; +import { ProviderProfileChip } from "../ProviderProfileChip"; import { ModelPickerSidebar } from "./ModelPickerSidebar"; import { getProviderStatusMessage, hasProviderSetup } from "./ProviderStatusBanner"; import { @@ -147,6 +148,44 @@ function ModelListSeparator() { return
; } +/** The subset of a resolved provider profile the picker needs. */ +export type ModelPickerProviderProfile = { + readonly name: string; + readonly color?: string | undefined; + readonly instanceIdSet: ReadonlySet; +}; + +/** + * Split entries by the project's provider profile. In-profile entries come + * first; the rest are listed only while revealed, except the active instance, + * which stays reachable so a thread already outside its profile still shows + * where it runs. + */ +export function partitionModelPickerProfileEntries(input: { + entries: ReadonlyArray; + profile: ModelPickerProviderProfile | null | undefined; + showOthers: boolean; + activeInstanceId: ProviderInstanceId; +}): { + entries: ReadonlyArray; + outsideInstanceIds: ReadonlySet; +} { + const { profile } = input; + if (!profile) return { entries: input.entries, outsideInstanceIds: new Set() }; + const inside: ProviderInstanceEntry[] = []; + const outside: ProviderInstanceEntry[] = []; + const outsideInstanceIds = new Set(); + for (const entry of input.entries) { + if (profile.instanceIdSet.has(entry.instanceId)) { + inside.push(entry); + continue; + } + outsideInstanceIds.add(entry.instanceId); + if (input.showOthers || entry.instanceId === input.activeInstanceId) outside.push(entry); + } + return { entries: [...inside, ...outside], outsideInstanceIds }; +} + export const ModelPickerContent = memo(function ModelPickerContent(props: { /** The instance currently selected in the composer (combobox "value"). */ activeInstanceId: ProviderInstanceId; @@ -181,15 +220,30 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void; getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null; onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void; + /** The project's provider profile; instances outside it start hidden. */ + providerProfile?: ModelPickerProviderProfile | null; }) { + const [showOtherProfiles, setShowOtherProfiles] = useState(false); + // Hidden instances drop out of every derived list below (rail, favorites, + // search) because they are absent from `instanceEntries`. + const profilePartition = useMemo( + () => + partitionModelPickerProfileEntries({ + entries: props.instanceEntries, + profile: props.providerProfile, + showOthers: showOtherProfiles, + activeInstanceId: props.activeInstanceId, + }), + [props.activeInstanceId, props.instanceEntries, props.providerProfile, showOtherProfiles], + ); const { keybindings: providedKeybindings, modelOptionsByInstance, - instanceEntries, getModelDisabledReason, onInstanceModelChange, onToggleModel, } = props; + const instanceEntries = profilePartition.entries; const [searchQuery, setSearchQuery] = useState(""); const [showTopScrollFade, setShowTopScrollFade] = useState(false); const [showBottomScrollFade, setShowBottomScrollFade] = useState(false); @@ -822,6 +876,26 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { onFocusSearch={focusSearchInput} instanceEntries={sidebarInstanceEntries} showFavorites + {...(props.providerProfile + ? { + profile: { + name: props.providerProfile.name, + outsideInstanceIds: profilePartition.outsideInstanceIds, + showingOthers: showOtherProfiles, + onToggleOthers: () => { + if ( + showOtherProfiles && + selectedInstanceId !== "favorites" && + selectedInstanceId !== props.activeInstanceId && + profilePartition.outsideInstanceIds.has(selectedInstanceId) + ) { + setSelectedInstanceId(props.activeInstanceId); + } + setShowOtherProfiles((shown) => !shown); + }, + }, + } + : {})} {...(selectableUnavailableInstanceIds ? { selectableUnavailableInstanceIds } : {})} {...(lockedDisabledInstanceIds ? { @@ -938,6 +1012,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { onMouseDown={(e) => e.stopPropagation()} onTouchStart={(e) => e.stopPropagation()} /> + {props.providerProfile && + !isSearching && + selectedInstanceId !== "favorites" && + profilePartition.outsideInstanceIds.has(selectedInstanceId) ? ( +

+ + Not in the {props.providerProfile.name} profile. Threads use this provider's own + credentials and MCP servers. +

+ ) : null} {/* Model list */}
@@ -1048,6 +1132,15 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { ) : ( No models found )} + {props.providerProfile ? ( +
+ +
+ ) : null}
diff --git a/apps/web/src/components/chat/ModelPickerSidebar.tsx b/apps/web/src/components/chat/ModelPickerSidebar.tsx index d043c053a0738..6275568170605 100644 --- a/apps/web/src/components/chat/ModelPickerSidebar.tsx +++ b/apps/web/src/components/chat/ModelPickerSidebar.tsx @@ -1,7 +1,7 @@ import { Toolbar } from "@base-ui/react/toolbar"; import { type ProviderInstanceId } from "@t3tools/contracts"; import { memo, useLayoutEffect, useRef, useState } from "react"; -import { SparklesIcon, StarIcon } from "lucide-react"; +import { EyeIcon, EyeOffIcon, SparklesIcon, StarIcon } from "lucide-react"; import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; @@ -64,6 +64,17 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { * instances are never flagged — the user just made them). */ newBadgeInstanceIds?: ReadonlySet; + /** + * The project's provider profile. Entries outside it render dimmed after a + * toggle that reveals or hides them; callers drop hidden entries from + * `instanceEntries` themselves. + */ + profile?: { + readonly name: string; + readonly outsideInstanceIds: ReadonlySet; + readonly showingOthers: boolean; + readonly onToggleOthers: () => void; + }; }) { const handleSelect = (instanceId: ProviderInstanceId | "favorites") => { props.onSelectInstance(instanceId); @@ -148,7 +159,13 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { ) : null} {/* Instance buttons (one per configured instance — built-in + custom) */} - {props.instanceEntries.map((entry) => { + {props.instanceEntries.map((entry, index) => { + const profile = props.profile; + const isOutsideProfile = profile?.outsideInstanceIds.has(entry.instanceId) ?? false; + const startsOutsideGroup = + isOutsideProfile && + (index === 0 || + !profile?.outsideInstanceIds.has(props.instanceEntries[index - 1]!.instanceId)); const isUnavailable = !isProviderInstancePickerReady(entry); const isContextDisabled = props.disabledInstanceIds?.has(entry.instanceId) ?? false; const unavailableSelectionIsReachable = @@ -164,15 +181,18 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { ? describeUnavailableInstance(entry) : isContextDisabled ? (props.getDisabledInstanceTooltip?.(entry) ?? entry.displayName) - : showNewBadge - ? `${entry.displayName} — New` - : entry.displayName; + : isOutsideProfile + ? `${entry.displayName} — Not in ${props.profile?.name}` + : showNewBadge + ? `${entry.displayName} — New` + : entry.displayName; const button = ( !isDisabled && handleSelect(entry.instanceId)} @@ -226,7 +246,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { button ); - return ( + const item = (
); + return startsOutsideGroup ? ( +
+ + ) : ( + item + ); })} + {props.profile && props.profile.outsideInstanceIds.size > 0 ? ( + + ) : null}
); }); + +function OtherProfilesToggle(props: { + profile: NonNullable[0]["profile"]>; +}) { + const label = props.profile.showingOthers + ? `Hide providers outside ${props.profile.name}` + : `Show providers outside ${props.profile.name}`; + return ( +
+ + + {props.profile.showingOthers ? ( + + ) : ( + + )} + + } + /> + + {label} + + +
+ ); +} diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index fbc1789653783..ba2f6c347d4a5 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -9,7 +9,11 @@ import { Badge } from "../ui/badge"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; -import { ModelPickerContent, resolveModelPickerSelectedModel } from "./ModelPickerContent"; +import { + ModelPickerContent, + type ModelPickerProviderProfile, + resolveModelPickerSelectedModel, +} from "./ModelPickerContent"; import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; import { ModelEsque, @@ -55,6 +59,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void; getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null; onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void; + /** The project's provider profile; the picker leads with its instances. */ + providerProfile?: ModelPickerProviderProfile | null; }) { const composerFloatingLayerProps = useComposerMenuProps(); const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false); @@ -92,6 +98,10 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { : triggerTitle; const showInstanceBadge = activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries); + const outsideProfile = + props.providerProfile != null && + activeEntry !== null && + !props.providerProfile.instanceIdSet.has(activeEntry.instanceId); const setIsMenuOpen = (open: boolean) => { props.onOpenChange?.(open); @@ -272,6 +282,19 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { Unavailable + ) : outsideProfile && !selectedEntries && props.triggerLabel === undefined ? ( + + + Outside profile + + } + /> + + {`${activeEntry?.displayName} is not in the ${props.providerProfile?.name} profile`} + + ) : null} + ) : ( +
+ {profiles.map((profile) => ( + + ))} +
+ ) + } + /> + ) : null}
{setup ? {setup} : null} diff --git a/apps/web/src/components/settings/ProviderProfilesSettings.logic.test.ts b/apps/web/src/components/settings/ProviderProfilesSettings.logic.test.ts new file mode 100644 index 0000000000000..e292468074ef9 --- /dev/null +++ b/apps/web/src/components/settings/ProviderProfilesSettings.logic.test.ts @@ -0,0 +1,76 @@ +import { + DEFAULT_SERVER_SETTINGS, + ProjectId, + ProviderProfileId, + type ServerSettings, +} from "@t3tools/contracts"; +import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; +import { describe, expect, it } from "vite-plus/test"; + +import { + buildDeleteProviderProfilePatch, + providerProfileIdFromName, + resolveProjectProviderProfileId, +} from "./ProviderProfilesSettings.logic"; + +const acme = ProviderProfileId.make("acme"); +const globex = ProviderProfileId.make("globex"); +const optedIn = ProjectId.make("opted-in"); +const optedOut = ProjectId.make("opted-out"); +const other = ProjectId.make("other"); +const inheriting = ProjectId.make("inheriting"); + +const settings: ServerSettings = { + ...DEFAULT_SERVER_SETTINGS, + providerProfileId: acme, + providerProfiles: { + [acme]: { name: "Acme", instanceIds: [], defaultModelSelection: null }, + [globex]: { name: "Globex", instanceIds: [], defaultModelSelection: null }, + }, + projectSettingsOverrides: { + [optedIn]: { providerProfileId: acme, defaultRuntimeMode: "approval-required" }, + [optedOut]: { providerProfileId: null }, + [other]: { providerProfileId: globex }, + }, +}; + +describe("providerProfileIdFromName", () => { + it("slugs the name and avoids existing ids", () => { + expect(providerProfileIdFromName(" Acme Corp! ", {})).toBe("acme-corp"); + expect(providerProfileIdFromName("Acme", { acme: {}, "acme-2": {} })).toBe("acme-3"); + expect(providerProfileIdFromName("Café", {})).toBe("cafe"); + expect(providerProfileIdFromName("!!!", {})).toBe("profile"); + }); +}); + +describe("buildDeleteProviderProfilePatch", () => { + it("removes the profile along with the environment default and overrides that select it", () => { + const next = applyServerSettingsPatch( + settings, + buildDeleteProviderProfilePatch(settings, acme), + ); + expect(Object.keys(next.providerProfiles)).toEqual([globex]); + expect(next.providerProfileId).toBeNull(); + expect(next.projectSettingsOverrides).toEqual({ + [optedIn]: { defaultRuntimeMode: "approval-required" }, + [optedOut]: { providerProfileId: null }, + [other]: { providerProfileId: globex }, + }); + }); + + it("leaves an unrelated environment default alone", () => { + const patch = buildDeleteProviderProfilePatch(settings, globex); + expect(patch).not.toHaveProperty("providerProfileId"); + expect(applyServerSettingsPatch(settings, patch).projectSettingsOverrides).not.toHaveProperty( + other, + ); + }); +}); + +describe("resolveProjectProviderProfileId", () => { + it("prefers the project's override, including an explicit opt-out", () => { + expect(resolveProjectProviderProfileId(settings, other)).toBe(globex); + expect(resolveProjectProviderProfileId(settings, optedOut)).toBeNull(); + expect(resolveProjectProviderProfileId(settings, inheriting)).toBe(acme); + }); +}); diff --git a/apps/web/src/components/settings/ProviderProfilesSettings.logic.ts b/apps/web/src/components/settings/ProviderProfilesSettings.logic.ts new file mode 100644 index 0000000000000..75088c276890b --- /dev/null +++ b/apps/web/src/components/settings/ProviderProfilesSettings.logic.ts @@ -0,0 +1,74 @@ +import { + type ProjectId, + type ProjectSettingsOverrides, + ProviderProfileId, + type ServerSettings, + type ServerSettingsPatch, +} from "@t3tools/contracts"; +import { clearProjectSettingsOverrides } from "@t3tools/shared/projectSettings"; + +export const PROVIDER_PROFILE_COLORS = [ + "#ea580c", + "#2563eb", + "#16a34a", + "#9333ea", + "#db2777", + "#0891b2", +] as const; + +/** A readable id derived from the name, suffixed until it is unused in `existing`. */ +export function providerProfileIdFromName( + name: string, + existing: Readonly>, +): ProviderProfileId { + const base = + name + .toLowerCase() + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") || "profile"; + let candidate = base; + for (let suffix = 2; Object.hasOwn(existing, candidate); suffix += 1) { + candidate = `${base}-${suffix}`; + } + return ProviderProfileId.make(candidate); +} + +/** + * Removes a profile and every reference to it in one write: the environment + * default and project overrides that select it fall back to their inherited + * value instead of silently pointing at nothing. + */ +export function buildDeleteProviderProfilePatch( + settings: Pick, + id: ProviderProfileId, +): ServerSettingsPatch { + const overrides: Record = {}; + for (const [projectId, entry] of Object.entries(settings.projectSettingsOverrides) as [ + ProjectId, + ProjectSettingsOverrides, + ][]) { + if (entry.providerProfileId === id) { + overrides[projectId] = clearProjectSettingsOverrides(settings, projectId, [ + "providerProfileId", + ]); + } + } + return { + providerProfiles: { [id]: null }, + ...(settings.providerProfileId === id ? { providerProfileId: null } : {}), + ...(Object.keys(overrides).length > 0 ? { projectSettingsOverrides: overrides } : {}), + }; +} + +/** The profile a project uses: its own override, including an explicit "no profile", else the environment's. */ +export function resolveProjectProviderProfileId( + settings: Pick, + projectId: ProjectId, +): ProviderProfileId | null { + const entry = settings.projectSettingsOverrides[projectId]; + return entry !== undefined && Object.hasOwn(entry, "providerProfileId") + ? (entry.providerProfileId ?? null) + : settings.providerProfileId; +} diff --git a/apps/web/src/components/settings/ProviderProfilesSettings.tsx b/apps/web/src/components/settings/ProviderProfilesSettings.tsx new file mode 100644 index 0000000000000..fe7c6e7db10ec --- /dev/null +++ b/apps/web/src/components/settings/ProviderProfilesSettings.tsx @@ -0,0 +1,461 @@ +import { + type EnvironmentId, + type ModelSelection, + type ProviderInstanceId, + type ProviderProfile, + type ProviderProfileId, + type ServerProvider, + type UnifiedSettings, +} from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; +import { PencilIcon, PlusIcon } from "lucide-react"; +import { useMemo, useState } from "react"; + +import { useUpdateEnvironmentSettings } from "../../hooks/useSettings"; +import { cn } from "../../lib/utils"; +import { getCustomModelOptionsByInstance } from "../../modelSelection"; +import { + applyProviderInstanceSettings, + deriveProviderInstanceEntries, + type ProviderInstanceEntry, + resolveDefaultProviderModelSelection, + sortProviderInstanceEntries, +} from "../../providerInstances"; +import { useProjects } from "../../state/entities"; +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; +import { ProviderModelPicker } from "../chat/ProviderModelPicker"; +import { ProviderProfileChip } from "../ProviderProfileChip"; +import { Button, InlineButton } from "../ui/button"; +import { Checkbox } from "../ui/checkbox"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Input } from "../ui/input"; +import { Label } from "../ui/label"; +import { + buildDeleteProviderProfilePatch, + PROVIDER_PROFILE_COLORS, + providerProfileIdFromName, + resolveProjectProviderProfileId, +} from "./ProviderProfilesSettings.logic"; +import { searchableSetting } from "./settingsSearch"; +import { SETTINGS_PICKER_TRIGGER_CLASSNAME, SettingsRow, SettingsSection } from "./settingsLayout"; + +/** Provider instance entries for an environment, in settings order. */ +export function useProviderInstanceEntries( + providers: ReadonlyArray, + settings: Pick, +): ReadonlyArray { + return useMemo( + () => + sortProviderInstanceEntries( + applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings), + ), + [providers, settings], + ); +} + +/** A profile's member instances as icon and name; ids of removed instances are skipped. */ +export function ProviderProfileInstances({ + instanceIds, + entries, +}: { + instanceIds: ReadonlyArray; + entries: ReadonlyArray; +}) { + const members = entries.filter((entry) => instanceIds.includes(entry.instanceId)); + if (members.length === 0) return No providers; + return ( + + {members.map((entry) => ( + + + {entry.displayName} + + ))} + + ); +} + +export function describeProfileModel( + selection: ModelSelection | null, + entries: ReadonlyArray, +): string { + if (selection === null) return "Automatic"; + const entry = entries.find((candidate) => candidate.instanceId === selection.instanceId); + if (!entry) return selection.model; + const model = entry.models.find((candidate) => candidate.slug === selection.model); + return `${entry.displayName} · ${model?.name ?? selection.model}`; +} + +interface EditingProfile { + readonly id: ProviderProfileId | null; + readonly profile: ProviderProfile; +} + +/** + * Profiles group this environment's provider instances, usually one per + * company or client. Projects pick a profile in their settings. + */ +export function ProviderProfilesSettings({ + environmentId, + settings, + providers, + readOnly, +}: { + readonly environmentId: EnvironmentId; + readonly settings: UnifiedSettings; + readonly providers: ReadonlyArray; + readonly readOnly: boolean; +}) { + const updateSettings = useUpdateEnvironmentSettings(environmentId); + const entries = useProviderInstanceEntries(providers, settings); + const allProjects = useProjects(); + const [editing, setEditing] = useState(null); + const profiles = Object.entries(settings.providerProfiles) as [ + ProviderProfileId, + ProviderProfile, + ][]; + const projectsByProfile = useMemo(() => { + const byProfile = new Map(); + for (const project of allProjects) { + if (project.environmentId !== environmentId) continue; + const id = resolveProjectProviderProfileId(settings, project.id); + if (id !== null) byProfile.set(id, [...(byProfile.get(id) ?? []), project.title]); + } + return byProfile; + }, [allProjects, environmentId, settings]); + + const startNew = () => + setEditing({ + id: null, + profile: { + name: "", + color: + PROVIDER_PROFILE_COLORS[profiles.length % PROVIDER_PROFILE_COLORS.length] ?? + PROVIDER_PROFILE_COLORS[0], + instanceIds: [], + defaultModelSelection: null, + }, + }); + + return ( + <> + + + New profile + + ) + } + > + {profiles.length === 0 ? ( + + ) : ( + profiles.map(([id, profile]) => { + const projects = projectsByProfile.get(id) ?? []; + return ( + + + + {projects.length === 0 + ? "No projects" + : `${projects.length} ${projects.length === 1 ? "project" : "projects"}: ${projects.join(", ")}`} + + + } + description={`Default model: ${describeProfileModel(profile.defaultModelSelection, entries)}`} + status={ + + } + control={ + readOnly ? null : ( + + ) + } + /> + ); + }) + )} + + {editing && !readOnly ? ( + setEditing(null)} + onSave={(profile) => { + const id = + editing.id ?? providerProfileIdFromName(profile.name, settings.providerProfiles); + updateSettings({ providerProfiles: { [id]: profile } }); + setEditing(null); + }} + onDelete={ + editing.id + ? () => { + if (editing.id) + updateSettings(buildDeleteProviderProfilePatch(settings, editing.id)); + setEditing(null); + } + : undefined + } + /> + ) : null} + + ); +} + +function ProviderProfileEditorDialog({ + initial, + entries, + settings, + providers, + usedBy, + onClose, + onSave, + onDelete, +}: { + readonly initial: EditingProfile; + readonly entries: ReadonlyArray; + readonly settings: UnifiedSettings; + readonly providers: ReadonlyArray; + readonly usedBy: number; + readonly onClose: () => void; + readonly onSave: (profile: ProviderProfile) => void; + readonly onDelete: (() => void) | undefined; +}) { + const [draft, setDraft] = useState(initial.profile); + const [confirmingDelete, setConfirmingDelete] = useState(false); + const chosen = new Set(draft.instanceIds); + const chosenEntries = entries.filter((entry) => chosen.has(entry.instanceId)); + const selection = resolveDefaultProviderModelSelection( + providers.filter((provider) => chosen.has(provider.instanceId)), + draft.defaultModelSelection, + ); + const modelOptions = getCustomModelOptionsByInstance( + settings, + providers, + selection?.instanceId, + selection?.model, + ); + const name = draft.name.trim(); + // Deleting clears references to the profile, so its projects inherit the + // environment's profile, or every provider when that was this one. + const fallbackProfile = + settings.providerProfileId !== null && settings.providerProfileId !== initial.id + ? settings.providerProfiles[settings.providerProfileId] + : undefined; + const deleteFallback = fallbackProfile ? `the ${fallbackProfile.name} profile` : "all providers"; + + const toggleInstance = (instanceId: ProviderInstanceId, checked: boolean) => { + const instanceIds = checked + ? [...draft.instanceIds, instanceId] + : draft.instanceIds.filter((id) => id !== instanceId); + setDraft({ + ...draft, + instanceIds, + defaultModelSelection: + draft.defaultModelSelection && instanceIds.includes(draft.defaultModelSelection.instanceId) + ? draft.defaultModelSelection + : null, + }); + }; + + return ( + !open && onClose()}> + + + {initial.id ? `Edit ${initial.profile.name}` : "New profile"} + + A profile is the set of providers a project may use, usually one per company or client. + + + +
{ + event.preventDefault(); + if (name && draft.instanceIds.length > 0) onSave({ ...draft, name }); + }} + > +
+ +
+ setDraft({ ...draft, name: event.target.value })} + /> +
+ {PROVIDER_PROFILE_COLORS.map((color) => ( +
+
+
+ +
+ Providers + {entries.length === 0 ? ( + No providers on this device. + ) : ( +
+ {entries.map((entry) => ( + + ))} +
+ )} +
+ +
+
+ Default model + {draft.defaultModelSelection ? ( + setDraft({ ...draft, defaultModelSelection: null })} + > + Use automatic + + ) : null} +
+ {selection && chosenEntries.length > 0 ? ( +
+ + setDraft({ + ...draft, + defaultModelSelection: createModelSelection(instanceId, model), + }) + } + /> +
+ ) : ( + + Choose providers to pick a default model. + + )} + + New threads in the profile's projects start on this model unless a project sets its + own. + +
+
+
+ + {onDelete ? ( + confirmingDelete ? ( +
+ + + {usedBy > 0 + ? `${usedBy} ${usedBy === 1 ? "project switches" : "projects switch"} to ${deleteFallback}.` + : "No projects use it."} + +
+ ) : ( + + ) + ) : null} + + +
+
+
+ ); +} diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx index 6722969075a1d..3431a553a20fe 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx @@ -82,6 +82,7 @@ import { stackedThreadToast, toastManager } from "../ui/toast"; import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog"; import { ExpandableText } from "./ExpandableText"; import { ProviderInstanceCard } from "./ProviderInstanceCard"; +import { ProviderProfilesSettings } from "./ProviderProfilesSettings"; import { UsageProviderSettings } from "./UsageProviderSettings"; import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection"; import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta"; @@ -336,7 +337,8 @@ function ProviderSettingsPanelContent(target: ProviderSettingsTarget) { if ( !target.scoped && (searchTargetId === searchableSetting("provider-health-check-interval").id || - searchTargetId === searchableSetting("usage-providers").id) && + searchTargetId === searchableSetting("usage-providers").id || + searchTargetId === searchableSetting("provider-profiles").id) && !selectedEnvironmentCanRenderSettings && searchableEnvironmentId !== undefined ) { @@ -904,6 +906,11 @@ export function EnvironmentProviderSettings({ }); }; + const profiles = Object.entries(settings.providerProfiles).map(([id, profile]) => ({ + id, + ...profile, + })); + const renderProviderInstance = (row: InstanceRow, mode: "list" | "editor") => { const driverOption = getDriverOption(row.driver); const liveProvider = serverProviders.find( @@ -935,6 +942,11 @@ export function EnvironmentProviderSettings({ selected={mode === "list" && selectedRow?.instanceId === row.instanceId} onSelect={mode === "list" ? () => setSelectedInstanceId(row.instanceId) : undefined} readOnly={readOnly} + profiles={ + mode === "editor" && profiles.length > 0 + ? profiles.filter((profile) => profile.instanceIds.includes(row.instanceId)) + : undefined + } setup={ mode === "editor" && row.driver === "antigravity" ? ( + + = { custom: "Custom instructions", }; -/** Human labels for the values the chain can show; falls back to a type summary. */ -function formatValue(key: keyof ServerSettings, value: unknown): string { +/** + * Human labels for the values the chain can show; falls back to a type + * summary. `settings` is the environment the value lives on, to name its + * profiles. + */ +function formatValue( + key: keyof ServerSettings, + value: unknown, + settings?: Pick, +): string { if (value === null || value === undefined) { return key === "pullRequestMergeMethod" ? "Last selected" @@ -45,11 +54,13 @@ function formatValue(key: keyof ServerSettings, value: unknown): string { ? "Never" : key === "defaultModelSelection" ? "Automatic" - : key === "sourceControlWriterModelSelection" - ? "Text generation model" - : key === "defaultThreadEnvMode" || key === "worktreeSubmodules" - ? "Inherit" - : "Not set"; + : key === "providerProfileId" + ? "No profile" + : key === "sourceControlWriterModelSelection" + ? "Text generation model" + : key === "defaultThreadEnvMode" || key === "worktreeSubmodules" + ? "Inherit" + : "Not set"; } if (typeof value === "boolean") return value ? "On" : "Off"; if (typeof value === "number") { @@ -64,6 +75,10 @@ function formatValue(key: keyof ServerSettings, value: unknown): string { if (key === "worktreeSubmodules" && value in WORKTREE_SUBMODULES_LABELS) { return WORKTREE_SUBMODULES_LABELS[value as WorktreeSubmodules]; } + if (key === "providerProfileId") { + // A deleted profile resolves to no profile. + return settings?.providerProfiles[value as ProviderProfileId]?.name ?? "No profile"; + } if (key === "pullRequestMergeMethod" && value in PULL_REQUEST_MERGE_METHOD_LABELS) { return PULL_REQUEST_MERGE_METHOD_LABELS[ value as keyof typeof PULL_REQUEST_MERGE_METHOD_LABELS @@ -102,7 +117,10 @@ export function settingInheritanceLayers( layers.push({ key: "project", label: "Project", - value: source === "project" ? formatValue(key, target.settings[key]) : "Inherits", + value: + source === "project" + ? formatValue(key, target.settings[key], environmentSettings) + : "Inherits", effective: source === "project", set: source === "project", }); @@ -110,7 +128,7 @@ export function settingInheritanceLayers( layers.push({ key: "environment", label: target.label, - value: environmentSet ? formatValue(key, environmentValue) : "Inherits", + value: environmentSet ? formatValue(key, environmentValue, environmentSettings) : "Inherits", effective: source === "environment" && environmentSet, set: environmentSet, }); @@ -301,7 +319,11 @@ export function SettingInheritance({ {isProjectScopedSettingKey(key) - ? formatValue(key, overrides[project.projectId]?.[key]) + ? formatValue( + key, + overrides[project.projectId]?.[key], + environment.serverConfig.settings, + ) : null} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index e812bb82bbc87..3a04897284c07 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -167,6 +167,13 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/projects", searchTerms: ["name icon emoji image checkout remove delete"], }, + { + id: "provider-profile", + title: "Provider profile", + to: "/settings/general", + scope: "project-defaults", + searchTerms: ["providers company client account model picker new thread"], + }, { id: "default-model", title: "Default model", @@ -615,6 +622,13 @@ export const SETTINGS_SEARCH_ITEMS = [ ], providerSettingsOnly: true, }, + { + id: "provider-profiles", + title: "Provider profiles", + to: "/settings/providers", + searchTerms: ["group providers company client account project default model new profile"], + providerSettingsOnly: true, + }, { id: "cursor-keychain-usage", title: "Cursor account usage", diff --git a/apps/web/src/providerInstances.ts b/apps/web/src/providerInstances.ts index 88ea8a2572403..9140e97bdb513 100644 --- a/apps/web/src/providerInstances.ts +++ b/apps/web/src/providerInstances.ts @@ -210,6 +210,22 @@ export function sortProviderInstanceEntries( return sorted; } +/** + * Move a provider profile's instances to the front, keeping relative order. + * Composer fallbacks pick the first selectable entry, so a project with a + * profile falls back inside it. + */ +export function leadWithProviderProfile( + entries: ReadonlyArray, + profile: { readonly instanceIdSet: ReadonlySet } | null, +): ReadonlyArray { + if (!profile) return entries; + return [ + ...entries.filter((entry) => profile.instanceIdSet.has(entry.instanceId)), + ...entries.filter((entry) => !profile.instanceIdSet.has(entry.instanceId)), + ]; +} + /** * Look up a single instance entry by exact `instanceId`. Missing snapshots * are not inferred from driver kind in UI routing code. diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index b32c5a53f0ef7..e21d8b8ecd1b7 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -62,6 +62,22 @@ itself, or **Skip** to leave them for a setup script. It resolves in the same or workspace default: a `"worktreeSubmodules"` value in the `t3.json` of the branch being checked out applies when the project and environment are both on **Inherit**. +## Provider profiles + +If you keep separate provider instances per company or client, such as a Claude and a Codex +instance for each with their own accounts and MCP servers, group them into profiles in +**Settings → Providers**. Each profile names its instances and can set a default model. + +Pick a profile with **Provider profile** in **Settings → General**, with a project selected to +assign it to that project, or with no project to set the environment default. That project's +model picker then lists only the profile's instances, and new threads start on the profile's +default model unless the project sets its own. **No profile** offers every instance. On mobile, the +same choice is on the **New threads** server settings page. + +The eye button at the bottom of the picker's provider rail reveals instances outside the profile. +Models picked from them are marked **Outside profile** because they run with that instance's +credentials and MCP servers. Existing threads keep their provider. + ## Storage cleanup Use **Manage worktrees** in **Settings → Storage** to choose a project and checkout, then create a diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7d9910ba2901a..8c64175acfacb 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1038,8 +1038,30 @@ export const WorktreeCleanup = Schema.NullOr( ); export type WorktreeCleanup = typeof WorktreeCleanup.Type; +export const ProviderProfileId = TrimmedNonEmptyString.pipe(Schema.brand("ProviderProfileId")); +export type ProviderProfileId = typeof ProviderProfileId.Type; + +/** + * A named set of provider instances, usually one per company or client. A + * project assigned to a profile only offers these instances in the model + * picker, and new threads start on the profile's default model. Ids of + * instances that no longer exist are ignored, not removed. + */ +export const ProviderProfile = Schema.Struct({ + name: TrimmedNonEmptyString, + color: Schema.optionalKey(TrimmedNonEmptyString), + instanceIds: Schema.Array(ProviderInstanceId).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + ), + defaultModelSelection: Schema.NullOr(ModelSelection).pipe( + Schema.withDecodingDefault(Effect.succeed(null)), + ), +}); +export type ProviderProfile = typeof ProviderProfile.Type; + export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [ "worktreeCleanup", + "providerProfileId", "defaultModelSelection", "defaultRuntimeMode", "defaultThreadEnvMode", @@ -1068,6 +1090,7 @@ export type ProjectScopedServerSettingKey = (typeof PROJECT_SCOPED_SERVER_SETTIN */ export const ProjectSettingsOverrides = Schema.Struct({ worktreeCleanup: Schema.optionalKey(WorktreeCleanup), + providerProfileId: Schema.optionalKey(Schema.NullOr(ProviderProfileId)), defaultModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)), defaultRuntimeMode: Schema.optionalKey(RuntimeMode), defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode), @@ -1103,6 +1126,7 @@ const NULLABLE_PROJECT_SETTINGS_OVERRIDES: ReadonlySet([ + "providerProfileId", "defaultModelSelection", "sourceControlWriterModelSelection", "pullRequestMergeMethod", @@ -1168,6 +1192,13 @@ export const ServerSettings = Schema.Struct({ defaultModelSelection: Schema.NullOr(ModelSelection).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), + /** The profile projects use unless they override it; `null` offers every provider. */ + providerProfileId: Schema.NullOr(ProviderProfileId).pipe( + Schema.withDecodingDefault(Effect.succeed(null)), + ), + providerProfiles: Schema.Record(ProviderProfileId, ProviderProfile).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), defaultRuntimeMode: RuntimeMode.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE)), ), @@ -1536,6 +1567,12 @@ export const ServerSettingsPatch = Schema.Struct({ Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)), ), defaultModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)), + providerProfileId: Schema.optionalKey(Schema.NullOr(ProviderProfileId)), + // Per-entry like `usageLimitSources`: each entry replaces one profile and + // `null` removes it. + providerProfiles: Schema.optionalKey( + Schema.Record(ProviderProfileId, Schema.NullOr(ProviderProfile)), + ), defaultRuntimeMode: Schema.optionalKey(RuntimeMode), /** * Per-project entry replacement: each entry replaces that project's whole diff --git a/packages/shared/src/projectSettings.test.ts b/packages/shared/src/projectSettings.test.ts index f59156530aa5b..b39f0dad5f3bb 100644 --- a/packages/shared/src/projectSettings.test.ts +++ b/packages/shared/src/projectSettings.test.ts @@ -2,7 +2,11 @@ import { DEFAULT_SERVER_SETTINGS, PROJECT_SCOPED_SERVER_SETTING_KEYS, ProjectId, + type ProjectSettingsOverrides, + ProviderDriverKind, ProviderInstanceId, + ProviderProfileId, + type ServerSettings, } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { createModelSelection } from "./model.ts"; @@ -11,6 +15,7 @@ import { hasProjectSettingsOverrides, resolveProjectFileBackedSetting, resolveProjectSettings, + resolveProviderProfile, resolveWorktreeCleanup, withProjectSettingsOverrides, } from "./projectSettings.ts"; @@ -366,3 +371,97 @@ describe("resolveWorktreeCleanup", () => { ).toBe(8); }); }); + +describe("provider profiles", () => { + const ccA = ProviderInstanceId.make("cc-a"); + const codexA = ProviderInstanceId.make("codex-a"); + const ccB = ProviderInstanceId.make("cc-b"); + const acme = ProviderProfileId.make("acme"); + const base: ServerSettings = { + ...DEFAULT_SERVER_SETTINGS, + providerInstances: { + [ccA]: { driver: ProviderDriverKind.make("claudeAgent") }, + [codexA]: { driver: ProviderDriverKind.make("codex") }, + [ccB]: { driver: ProviderDriverKind.make("claudeAgent") }, + }, + defaultModelSelection: createModelSelection(ccB, "sonnet"), + providerProfiles: { + [acme]: { + name: "Acme", + instanceIds: [ccA, codexA], + defaultModelSelection: createModelSelection(ccA, "opus"), + }, + }, + }; + const withProjectProfile = (overrides: ProjectSettingsOverrides): ServerSettings => ({ + ...base, + projectSettingsOverrides: { [projectId]: overrides }, + }); + + it("starts new threads on the project profile's default model", () => { + const resolved = resolveProjectSettings( + withProjectProfile({ providerProfileId: acme }), + projectId, + ); + expect(resolved.settings.defaultModelSelection).toEqual(createModelSelection(ccA, "opus")); + expect(resolveProviderProfile(resolved.settings)?.instanceIdSet.has(codexA)).toBe(true); + expect( + resolveProjectSettings(withProjectProfile({ providerProfileId: acme }), otherProjectId) + .settings.defaultModelSelection, + ).toEqual(createModelSelection(ccB, "sonnet")); + }); + + it("drops an inherited default outside the profile when the profile has none", () => { + const settings = { + ...withProjectProfile({ providerProfileId: acme }), + providerProfiles: { + [acme]: { name: "Acme", instanceIds: [ccA], defaultModelSelection: null }, + }, + }; + expect(resolveProjectSettings(settings, projectId).settings.defaultModelSelection).toBeNull(); + }); + + it("keeps a project's explicit model even outside its profile", () => { + const explicit = createModelSelection(ccB, "haiku"); + const resolved = resolveProjectSettings( + withProjectProfile({ providerProfileId: acme, defaultModelSelection: explicit }), + projectId, + ); + expect(resolved.settings.defaultModelSelection).toEqual(explicit); + }); + + it("applies the environment profile and lets a project opt out with null", () => { + const settings = { ...base, providerProfileId: acme }; + expect(resolveProjectSettings(settings, projectId).settings.defaultModelSelection).toEqual( + createModelSelection(ccA, "opus"), + ); + const optedOut = resolveProjectSettings( + { ...settings, projectSettingsOverrides: { [projectId]: { providerProfileId: null } } }, + projectId, + ); + expect(resolveProviderProfile(optedOut.settings)).toBeNull(); + expect(optedOut.settings.defaultModelSelection).toEqual(createModelSelection(ccB, "sonnet")); + }); + + it("treats a deleted profile as no profile", () => { + const settings = withProjectProfile({ providerProfileId: ProviderProfileId.make("gone") }); + const resolved = resolveProjectSettings(settings, projectId); + expect(resolveProviderProfile(resolved.settings)).toBeNull(); + expect(resolved.settings.defaultModelSelection).toEqual(createModelSelection(ccB, "sonnet")); + }); + + it("upserts and removes profiles per entry", () => { + const globex = ProviderProfileId.make("globex"); + const added = applyServerSettingsPatch(base, { + providerProfiles: { + [globex]: { name: "Globex", instanceIds: [ccB], defaultModelSelection: null }, + }, + }); + expect(Object.keys(added.providerProfiles)).toEqual([acme, globex]); + const removed = applyServerSettingsPatch(added, { providerProfiles: { [acme]: null } }); + expect(Object.keys(removed.providerProfiles)).toEqual([globex]); + expect(applyServerSettingsPatch(removed, { providerProfileId: globex }).providerProfileId).toBe( + globex, + ); + }); +}); diff --git a/packages/shared/src/projectSettings.ts b/packages/shared/src/projectSettings.ts index f99dacbbb69df..71e4be9ed625b 100644 --- a/packages/shared/src/projectSettings.ts +++ b/packages/shared/src/projectSettings.ts @@ -6,6 +6,9 @@ import { type ProjectId, type ProjectScopedServerSettingKey, type ProjectSettingsOverrides, + type ProviderInstanceId, + type ProviderProfile, + type ProviderProfileId, type ResolvedServerSettings, type ServerSettings, type T3ProjectFile, @@ -95,7 +98,9 @@ export function resolveProjectSettings( project?: LegacyProjectSettingsFields | null, projectFile?: T3ProjectFile | null, ): ResolvedProjectSettings { - const resolved = resolveProjectOverrides(settings, projectId, project); + const resolved = applyProviderProfileDefaultModel( + resolveProjectOverrides(settings, projectId, project), + ); return projectFile === undefined ? resolved : applyProjectFile(resolved, projectFile); } @@ -188,6 +193,52 @@ function resolveProjectOverrides( return { settings: effective as ServerSettings, sources, overrides }; } +export interface ResolvedProviderProfile extends ProviderProfile { + readonly id: ProviderProfileId; + /** The profile's instance ids as a set, for membership checks in pickers. */ + readonly instanceIdSet: ReadonlySet; +} + +/** + * The profile selected by already-resolved settings (see + * `resolveProjectSettings`), or null when every provider is offered. A + * dangling id, left behind by a deleted profile, also means no profile. + */ +export function resolveProviderProfile( + settings: Pick, +): ResolvedProviderProfile | null { + const id = settings.providerProfileId; + const profile = id === null ? undefined : settings.providerProfiles[id]; + if (id === null || profile === undefined) return null; + return { ...profile, id, instanceIdSet: new Set(profile.instanceIds) }; +} + +/** + * A profile replaces the inherited new-thread model: its own default when it + * has one, otherwise the environment default only if the profile includes + * that provider. A project's explicit model override always wins. + */ +function applyProviderProfileDefaultModel( + resolved: ResolvedProjectSettings, +): ResolvedProjectSettings { + if (resolved.sources.defaultModelSelection === "project") return resolved; + const profile = resolveProviderProfile(resolved.settings); + if (profile === null) return resolved; + const inherited = resolved.settings.defaultModelSelection; + const profileDefault = profile.defaultModelSelection; + const next = + profileDefault !== null && + profile.instanceIdSet.has(profileDefault.instanceId) && + isModelSelectionProviderEnabled(resolved.settings, profileDefault) + ? profileDefault + : inherited !== null && profile.instanceIdSet.has(inherited.instanceId) + ? inherited + : null; + return next === inherited + ? resolved + : { ...resolved, settings: { ...resolved.settings, defaultModelSelection: next } }; +} + /** Replace the project's entry, dropping it entirely when nothing is overridden. */ export function withProjectSettingsOverrides( settings: Pick, diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index ab6ceefeaf64b..8f10006737e9f 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -277,6 +277,7 @@ export function applyServerSettingsPatch( // Merged per entry below; its `null` removals must not reach deepMerge. usageLimitSources: usageLimitSourcesPatch, usagePriceOverrides: usagePriceOverridesPatch, + providerProfiles: providerProfilesPatch, // Entry replacement: deepMerge would keep keys the client meant to clear. projectSettingsOverrides: projectSettingsOverridesPatch, // Already translated into `projectSettingsOverrides` above; the legacy @@ -372,6 +373,12 @@ export function applyServerSettingsPatch( ...(patch.defaultModelSelection !== undefined ? { defaultModelSelection: patch.defaultModelSelection } : {}), + ...(patch.providerProfileId !== undefined + ? { providerProfileId: patch.providerProfileId } + : {}), + ...(providerProfilesPatch !== undefined + ? { providerProfiles: mergeSettingsEntries(current.providerProfiles, providerProfilesPatch) } + : {}), ...(patch.defaultProjectScripts !== undefined ? { defaultProjectScripts: patch.defaultProjectScripts } : {}), From 68acf6f7d3ec75788e89d8659cd994ed5f387c8b Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Sun, 27 Sep 2026 20:05:23 -0300 Subject: [PATCH 2/4] fix: keep provider profiles from leaking other accounts - New drafts drop carried and sticky model seeds outside the target project's profile; explicit picks still stand. - Automations with no model resolve inside the project's profile on the server and in the editor instead of falling back to the environment default. - Multi-environment settings only offer profiles every selected environment defines, on web and mobile. - Profile picker values are prefixed so a profile named "None" no longer collides with the opt-out. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../SettingsServerControlsRouteScreen.tsx | 28 ++++----- .../src/automation/AutomationService.test.ts | 61 ++++++++++++++++++- .../src/automation/AutomationService.ts | 21 ++++++- .../automations/AutomationsPage.tsx | 31 ++++++++-- .../src/components/chat/DraftHeroHeadline.tsx | 13 ++-- .../settings/ProjectDefaultsSettings.tsx | 56 ++++++++++------- .../ProviderProfilesSettings.logic.test.ts | 18 ++++++ .../ProviderProfilesSettings.logic.ts | 20 ++++++ apps/web/src/composerDraftStore.test.ts | 14 +++++ apps/web/src/composerDraftStore.ts | 27 ++++++-- apps/web/src/hooks/useHandleNewThread.ts | 8 ++- apps/web/src/lib/chatThreadActions.test.ts | 29 +++++++++ apps/web/src/lib/chatThreadActions.ts | 18 ++++-- packages/shared/src/projectSettings.test.ts | 51 ++++++++++++++++ packages/shared/src/projectSettings.ts | 42 +++++++++++++ 15 files changed, 375 insertions(+), 62 deletions(-) diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 7e16afd1607fa..a900c257686b5 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -13,6 +13,7 @@ import { type ProjectScopedServerSettingKey, type ProviderProfileId, } from "@t3tools/contracts"; +import { commonProviderProfiles } from "@t3tools/shared/projectSettings"; import { useRef, useState, type ComponentProps } from "react"; import { Alert, Platform, Pressable, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -214,16 +215,12 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { (target) => target.environment.serverConfig.environment.capabilities.threadRestartContinuation === true, ); - // Profiles are per environment; list every one the selection knows by id. - const profileChoices = [ - ...new Map( - displayTargets.flatMap((target) => - Object.entries(target.settings.providerProfiles).map( - ([id, profile]) => [id, profile] as const, - ), - ), - ), - ]; + // Profiles are per environment: offer only those every write target + // defines, so one choice never saves an id some environment lacks. + const profileChoices = commonProviderProfiles(targets.map((target) => target.settings)); + const anyTargetHasProfiles = targets.some( + (target) => Object.keys(target.settings.providerProfiles).length > 0, + ); const disabledFor = (key: string) => disabled || (projectSelected && @@ -266,7 +263,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { ) : null} {props.page === "new-threads" ? ( <> - {profileChoices.length > 0 ? ( + {anyTargetHasProfiles ? ( {[ ...profileChoices.map(([id, profile]) => ({ - id: id as ProviderProfileId, + id: id as ProviderProfileId | null, label: profile.name, description: `${profile.instanceIds.length} provider${profile.instanceIds.length === 1 ? "" : "s"}`, })), { id: null, label: "No profile", - description: "Offer every provider in the model picker.", + description: + profileChoices.length === 0 + ? "The selected environments share no profile. Filter to one environment to pick one of its profiles." + : "Offer every provider in the model picker.", }, ].map((choice, index) => ( >; readonly project: OrchestrationProjectShell | null; + readonly settings?: Parameters[0]; + readonly providers?: ReadonlyArray; }) => AutomationService.layer.pipe( Layer.provide( @@ -72,7 +79,8 @@ const makeLayer = (input: { Layer.mock(GitWorkflowService)({}), Layer.mock(ProjectSetupScriptRunner)({}), Layer.mock(GitHubCli)({}), - ServerSettingsService.layerTest(), + Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed(input.providers ?? []) }), + ServerSettingsService.layerTest(input.settings), ServerConfig.layerTest(process.cwd(), input.stateDir), ), ), @@ -88,13 +96,14 @@ const withService = ( readonly commands: Ref.Ref>; }, ) => Effect.Effect, + environment: Pick[0], "settings" | "providers"> = {}, ) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-automations-" }); const commands = yield* Ref.make>([]); const service = yield* AutomationService.AutomationService.pipe( - Effect.provide(makeLayer({ stateDir, commands, project })), + Effect.provide(makeLayer({ stateDir, commands, project, ...environment })), ); return yield* body(service, { stateDir, commands }); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); @@ -169,4 +178,52 @@ describe("AutomationService", () => { }), ), ); + + it.effect( + "an automation on a profiled project runs inside the profile, not on the environment default", + () => { + const acmeClaude = ProviderInstanceId.make("cc_a"); + const otherClaude = ProviderInstanceId.make("cc_b"); + const acme = ProviderProfileId.make("acme"); + const provider = (instanceId: ProviderInstanceId) => + ({ + instanceId, + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + status: "ready", + auth: { status: "authenticated" }, + models: [{ slug: "opus", name: "Opus", isCustom: false, isDefault: true }], + }) as unknown as ServerProvider; + const settings: Partial = { + providerInstances: { + [acmeClaude]: { driver: ProviderDriverKind.make("claudeAgent") }, + [otherClaude]: { driver: ProviderDriverKind.make("claudeAgent") }, + }, + // The environment default belongs to another profile's account. + defaultModelSelection: { instanceId: otherClaude, model: "opus" }, + providerProfiles: { + [acme]: { name: "Acme", instanceIds: [acmeClaude], defaultModelSelection: null }, + }, + projectSettingsOverrides: { [PROJECT_ID]: { providerProfileId: acme } }, + }; + return withService( + PROJECT, + (service, { commands }) => + Effect.gen(function* () { + const created = yield* service.create({ ...CONFIG, modelSelection: null }); + const run = yield* service.runNow(created.id); + assert.strictEqual(run.error, null); + const turn = (yield* Ref.get(commands)).find( + (command) => command.type === "thread.turn.start", + ); + assert.deepStrictEqual(turn?.type === "thread.turn.start" && turn.modelSelection, { + instanceId: acmeClaude, + model: "opus", + }); + }), + { settings, providers: [provider(otherClaude), provider(acmeClaude)] }, + ); + }, + ); }); diff --git a/apps/server/src/automation/AutomationService.ts b/apps/server/src/automation/AutomationService.ts index e2d732dc106bb..acc3f061c3c04 100644 --- a/apps/server/src/automation/AutomationService.ts +++ b/apps/server/src/automation/AutomationService.ts @@ -29,7 +29,11 @@ import { latestTriggerAt, } from "@t3tools/shared/automationSchedule"; import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git"; -import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { + resolveProjectSettings, + resolveProviderProfile, + resolveProviderProfileFallbackModelSelection, +} from "@t3tools/shared/projectSettings"; import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; @@ -56,6 +60,7 @@ import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEng import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { ThreadDeletionReactor } from "../orchestration/Services/ThreadDeletionReactor.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; +import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts"; import { forkParked } from "../serverActivation.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as GitHubCli from "../sourceControl/GitHubCli.ts"; @@ -145,6 +150,7 @@ const make = Effect.gen(function* () { const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; const settingsService = yield* ServerSettings.ServerSettingsService; const gitHubCli = yield* GitHubCli.GitHubCli; + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; const filePath = path.join(config.stateDir, "automations.json"); // Captured so writes from RPC handlers and the scheduler fiber need no extra services. @@ -294,10 +300,19 @@ const make = Effect.gen(function* () { return yield* failWith("The automation's project no longer exists."); } const settings = yield* settingsService.getSettings; + const projectSettings = resolveProjectSettings(settings, project.id, project).settings; + const providerProfile = resolveProviderProfile(projectSettings); + // With a profile, a missing default resolves inside it; the environment + // default may belong to another profile's account. const modelSelection = automation.modelSelection ?? - resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ?? - settings.defaultModelSelection; + projectSettings.defaultModelSelection ?? + (providerProfile + ? resolveProviderProfileFallbackModelSelection( + providerProfile, + yield* providerRegistry.getProviders, + ) + : settings.defaultModelSelection); if (!modelSelection) { return yield* failWith("Choose a model for this automation."); } diff --git a/apps/web/src/components/automations/AutomationsPage.tsx b/apps/web/src/components/automations/AutomationsPage.tsx index 4678e1e443ddc..ba7b1f0232d91 100644 --- a/apps/web/src/components/automations/AutomationsPage.tsx +++ b/apps/web/src/components/automations/AutomationsPage.tsx @@ -15,7 +15,11 @@ import { isValidAutomationCronExpression, resolveEnvironmentMachineKind, } from "@t3tools/contracts"; -import { resolveProjectSettings, resolveProviderProfile } from "@t3tools/shared/projectSettings"; +import { + resolveProjectSettings, + resolveProviderProfile, + resolveProviderProfileFallbackModelSelection, +} from "@t3tools/shared/projectSettings"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { @@ -1269,11 +1273,26 @@ function AutomationInstructions({ // Runs resolve the project's default model the same way on the server. const projectSettings = resolveProjectSettings(settings, projectId).settings; const providerProfile = resolveProviderProfile(projectSettings); - // Until the user picks one, `modelSelection` stays null and runs follow the default model. - const selection = resolveDefaultProviderModelSelection( - providers, - modelSelection ?? projectSettings.defaultModelSelection, - ); + // Until the user picks one, `modelSelection` stays null and runs follow the + // default model, resolved inside the project's profile like the server does. + const selection = + modelSelection === null && providerProfile + ? projectSettings.defaultModelSelection + ? resolveDefaultProviderModelSelection( + // A project may pin a model outside its profile; an unavailable + // default still only falls back inside the profile. + providers.filter( + (provider) => + providerProfile.instanceIdSet.has(provider.instanceId) || + provider.instanceId === projectSettings.defaultModelSelection?.instanceId, + ), + projectSettings.defaultModelSelection, + ) + : resolveProviderProfileFallbackModelSelection(providerProfile, providers) + : resolveDefaultProviderModelSelection( + providers, + modelSelection ?? projectSettings.defaultModelSelection, + ); const entries = leadWithProviderProfile( sortProviderInstanceEntries( applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings), diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx index ea4741b80664a..8ab42c2656bd7 100644 --- a/apps/web/src/components/chat/DraftHeroHeadline.tsx +++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx @@ -30,7 +30,7 @@ import { } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { InlineButton } from "../ui/button"; -import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { resolveProjectSettings, resolveProviderProfile } from "@t3tools/shared/projectSettings"; interface DraftHeroHeadlineProps { readonly draftId: DraftId | null; @@ -175,13 +175,18 @@ export function DraftHeroHeadline({ draftId, ); if (!hasExplicitComposerModelSelection(currentDraft)) { - applyStickyState(draftId); const environmentSettings = environments.find( (environment) => environment.environmentId === project.environmentId, )?.serverConfig?.settings; - const defaultModelSelection = environmentSettings + const projectSettings = environmentSettings ? resolveProjectSettings(environmentSettings, project.id, project).settings - .defaultModelSelection + : null; + applyStickyState( + draftId, + projectSettings ? resolveProviderProfile(projectSettings) : null, + ); + const defaultModelSelection = projectSettings + ? projectSettings.defaultModelSelection : project.defaultModelSelection; if (defaultModelSelection) { setModelSelection(draftId, defaultModelSelection, { diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx index 6fbce4ad0de56..1605bb594c0ba 100644 --- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx +++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx @@ -2,11 +2,14 @@ import { DEFAULT_SERVER_SETTINGS, type ModelSelection, type ProviderInstanceId, - ProviderProfileId, type WorktreeSubmodules, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; -import { resolveProjectSettings, resolveProviderProfile } from "@t3tools/shared/projectSettings"; +import { + commonProviderProfiles, + resolveProjectSettings, + resolveProviderProfile, +} from "@t3tools/shared/projectSettings"; import { useNavigate } from "@tanstack/react-router"; import { getCustomModelOptionsByInstance } from "../../modelSelection"; @@ -30,6 +33,11 @@ import { toastManager } from "../ui/toast"; import { Switch } from "../ui/switch"; import type { ProjectSettingsCategory } from "./ProjectSettingsPanel"; import { ProviderProfileInstances } from "./ProviderProfilesSettings"; +import { + decodeProviderProfileValue, + encodeProviderProfileValue, + NO_PROVIDER_PROFILE_VALUE, +} from "./ProviderProfilesSettings.logic"; import { searchableSetting } from "./settingsSearch"; import { useSettingsScope } from "./SettingsScopeContext"; import { @@ -79,7 +87,13 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting const mixedModel = useScopedSettingsMixed(["defaultModelSelection"]); const mixedProfile = useScopedSettingsMixed(["providerProfileId"]); const profile = resolveProviderProfile(settings); - const profiles = Object.entries(settings.providerProfiles); + // Offer only profiles every target defines, so a multi-environment write + // never saves an id some environment lacks. + const profileTargets = targets.length > 0 ? targets.map((entry) => entry.settings) : [settings]; + const profiles = commonProviderProfiles(profileTargets); + const anyTargetHasProfiles = profileTargets.some( + (entry) => Object.keys(entry.providerProfiles).length > 0, + ); const mixedPermissions = useScopedSettingsMixed(["defaultRuntimeMode"]); const PermissionIcon = runtimeModeConfig[settings.defaultRuntimeMode].icon; const mixedWorkspace = useScopedSettingsMixed(["defaultThreadEnvMode"]); @@ -153,11 +167,13 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting mixed={mixedProfile} {...searchableSetting("provider-profile")} description={ - profiles.length === 0 && settings.providerProfileId === null + !anyTargetHasProfiles && settings.providerProfileId === null ? "Profiles limit a project to a set of providers, such as one per client. Create one in provider settings." - : isProjectScope - ? "This project only offers the profile's providers in the model picker, and new threads start on its default model." - : "Projects only offer this profile's providers in the model picker, and new threads start on its default model." + : profiles.length === 0 && anyTargetHasProfiles + ? "The selected environments share no profile. Choose one environment to pick one of its profiles." + : isProjectScope + ? "This project only offers the profile's providers in the model picker, and new threads start on its default model." + : "Projects only offer this profile's providers in the model picker, and new threads start on its default model." } status={ profile && !mixedProfile ? ( @@ -174,34 +190,30 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting ) : null } control={ - profiles.length === 0 && settings.providerProfileId === null ? ( + !anyTargetHasProfiles && settings.providerProfileId === null ? ( ) : ( ) diff --git a/apps/web/src/components/settings/ProviderProfilesSettings.logic.test.ts b/apps/web/src/components/settings/ProviderProfilesSettings.logic.test.ts index e292468074ef9..8a60999b65ede 100644 --- a/apps/web/src/components/settings/ProviderProfilesSettings.logic.test.ts +++ b/apps/web/src/components/settings/ProviderProfilesSettings.logic.test.ts @@ -9,6 +9,9 @@ import { describe, expect, it } from "vite-plus/test"; import { buildDeleteProviderProfilePatch, + decodeProviderProfileValue, + encodeProviderProfileValue, + NO_PROVIDER_PROFILE_VALUE, providerProfileIdFromName, resolveProjectProviderProfileId, } from "./ProviderProfilesSettings.logic"; @@ -74,3 +77,18 @@ describe("resolveProjectProviderProfileId", () => { expect(resolveProjectProviderProfileId(settings, inheriting)).toBe(acme); }); }); + +describe("provider profile select values", () => { + it("keeps a profile named None distinct from the opt-out", () => { + const noneProfile = providerProfileIdFromName("None", {}); + expect(noneProfile).toBe("none"); + const value = encodeProviderProfileValue(noneProfile); + expect(value).not.toBe(NO_PROVIDER_PROFILE_VALUE); + expect(decodeProviderProfileValue(value)).toBe(noneProfile); + expect(decodeProviderProfileValue(encodeProviderProfileValue(null))).toBeNull(); + // Ids are slugs, so even one spelled like the opt-out value stays a profile. + const lookalike = providerProfileIdFromName("No profile", {}); + expect(decodeProviderProfileValue(encodeProviderProfileValue(lookalike))).toBe(lookalike); + expect(decodeProviderProfileValue("none")).toBeUndefined(); + }); +}); diff --git a/apps/web/src/components/settings/ProviderProfilesSettings.logic.ts b/apps/web/src/components/settings/ProviderProfilesSettings.logic.ts index 75088c276890b..50678853332da 100644 --- a/apps/web/src/components/settings/ProviderProfilesSettings.logic.ts +++ b/apps/web/src/components/settings/ProviderProfilesSettings.logic.ts @@ -72,3 +72,23 @@ export function resolveProjectProviderProfileId( ? (entry.providerProfileId ?? null) : settings.providerProfileId; } + +/** + * Select values for the profile picker. Profile ids are user-derived slugs + * (a profile named "None" gets id `none`), so they are prefixed to never + * collide with the opt-out value. + */ +export const NO_PROVIDER_PROFILE_VALUE = "no-profile"; +const PROFILE_VALUE_PREFIX = "profile:"; + +export function encodeProviderProfileValue(id: ProviderProfileId | null): string { + return id === null ? NO_PROVIDER_PROFILE_VALUE : `${PROFILE_VALUE_PREFIX}${id}`; +} + +/** `null` is the opt-out; `undefined` is a value this picker never produces. */ +export function decodeProviderProfileValue(value: string): ProviderProfileId | null | undefined { + if (value === NO_PROVIDER_PROFILE_VALUE) return null; + return value.startsWith(PROFILE_VALUE_PREFIX) + ? ProviderProfileId.make(value.slice(PROFILE_VALUE_PREFIX.length)) + : undefined; +} diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index 92672348f97eb..2590ece6c46de 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -2415,6 +2415,20 @@ describe("composerDraftStore sticky composer settings", () => { }); }); + it("only seeds sticky selections inside the target project's provider profile", () => { + const store = useComposerDraftStore.getState(); + const draftId = DraftId.make("draft-profile-sticky-seed"); + + store.setStickyModelSelection(modelSelection(CODEX_DRIVER, "gpt-5.5")); + store.setStickyModelSelection(modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6")); + // The last app-wide pick was Claude, which this project's profile excludes. + store.applyStickyState(draftId, { instanceIdSet: new Set([CODEX_INSTANCE]) }); + + const draft = draftByKey(draftId); + expect(draft?.activeProvider).toBeNull(); + expect(Object.keys(draft?.modelSelectionByProvider ?? {})).toEqual([CODEX_INSTANCE]); + }); + it("clears a non-explicit stale model when there is no sticky state", () => { const store = useComposerDraftStore.getState(); const draftId = DraftId.make("draft-stale-without-sticky"); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index ce2c51fe52478..b69006566af7c 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -594,7 +594,15 @@ interface ComposerDraftStoreState { | null | undefined, ) => void; - applyStickyState: (threadRef: ComposerThreadTarget) => void; + /** + * Seed a draft from the last app-wide pick. With a provider profile, only + * sticky selections on its instances carry over, so a project never + * inherits another profile's account implicitly. + */ + applyStickyState: ( + threadRef: ComposerThreadTarget, + providerProfile?: { readonly instanceIdSet: ReadonlySet } | null, + ) => void; setProviderModelOptions: ( threadRef: ComposerThreadTarget, provider: ProviderDriverKind, @@ -2947,14 +2955,25 @@ const composerDraftStore = create()( }; }); }, - applyStickyState: (threadRef) => { + applyStickyState: (threadRef, providerProfile) => { const threadKey = resolveComposerDraftKey(get(), threadRef) ?? ""; if (threadKey.length === 0) { return; } set((state) => { - const stickyMap = state.stickyModelSelectionByProvider; - const stickyActiveProvider = state.stickyActiveProvider; + const inProfile = (instanceId: ProviderInstanceId) => + !providerProfile || providerProfile.instanceIdSet.has(instanceId); + const stickyMap = providerProfile + ? Object.fromEntries( + Object.entries(state.stickyModelSelectionByProvider).filter(([instanceId]) => + inProfile(instanceId as ProviderInstanceId), + ), + ) + : state.stickyModelSelectionByProvider; + const stickyActiveProvider = + state.stickyActiveProvider && inProfile(state.stickyActiveProvider) + ? state.stickyActiveProvider + : null; const existing = state.draftsByThreadKey[threadKey]; const base = existing ?? createEmptyThreadDraft(); const nextMap = compactModelSelectionByProvider(stickyMap); diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 327f180800088..2f2b1ab81b130 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -22,7 +22,7 @@ import { getProjectOrderKey, selectProjectGroupingSettings, } from "../logicalProject"; -import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { resolveProjectSettings, resolveProviderProfile } from "@t3tools/shared/projectSettings"; import { readProjects, readThreadShell, useProjects, useThread } from "../state/entities"; import { hasExplicitComposerModelSelection, @@ -136,6 +136,7 @@ export function useNewThreadHandler() { project, ); const projectDefaultModelSelection = projectSettings.settings.defaultModelSelection; + const providerProfile = resolveProviderProfile(projectSettings.settings); const defaultRuntimeMode = projectSettings.settings.defaultRuntimeMode; const resolveModelSelectionOverride = (destinationDraftId: DraftId) => resolveNewThreadModelSelectionOverride({ @@ -144,6 +145,7 @@ export function useNewThreadHandler() { carrySourceDraftId: currentRouteTarget?.kind === "draft" ? currentRouteTarget.draftId : null, destinationDraftId, + providerProfile, }); // The shared resolver owns the priority order. The t3.json read is // skipped entirely when a higher-priority source decides, and its @@ -276,7 +278,7 @@ export function useNewThreadHandler() { const storedDraft = getComposerDraft(emptyStoredDraftThread.draftId); const storedDraftHasExplicitModelPick = hasExplicitComposerModelSelection(storedDraft); if (!storedDraftHasExplicitModelPick) { - applyStickyState(emptyStoredDraftThread.draftId); + applyStickyState(emptyStoredDraftThread.draftId, providerProfile); const modelSelectionOverride = resolveModelSelectionOverride( emptyStoredDraftThread.draftId, ); @@ -415,7 +417,7 @@ export function useNewThreadHandler() { runtimeMode: defaultRuntimeMode, ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}), }); - applyStickyState(draftId); + applyStickyState(draftId, providerProfile); const modelSelectionOverride = resolveModelSelectionOverride(draftId); if (modelSelectionOverride) { // Project defaults and carried selections both outrank global sticky diff --git a/apps/web/src/lib/chatThreadActions.test.ts b/apps/web/src/lib/chatThreadActions.test.ts index c145404a74e2d..653fca5cc3981 100644 --- a/apps/web/src/lib/chatThreadActions.test.ts +++ b/apps/web/src/lib/chatThreadActions.test.ts @@ -76,6 +76,35 @@ describe("chatThreadActions", () => { ).toEqual(CARRIED_SELECTION); }); + it("drops a carried outside provider when a new thread starts in a profiled project", () => { + // The viewed thread in another project runs on an instance the target + // project's profile does not include. + const outsideSelection: ModelSelection = { + instanceId: ProviderInstanceId.make("cc_b"), + model: "opus", + }; + const providerProfile = { instanceIdSet: new Set([ProviderInstanceId.make("cc_a")]) }; + expect( + resolveNewThreadModelSelectionOverride({ + projectDefaultSelection: null, + carrySelection: outsideSelection, + carrySourceDraftId: "draft-other-project", + destinationDraftId: "draft-b", + providerProfile, + }), + ).toBeNull(); + const insideSelection = { ...outsideSelection, instanceId: ProviderInstanceId.make("cc_a") }; + expect( + resolveNewThreadModelSelectionOverride({ + projectDefaultSelection: null, + carrySelection: insideSelection, + carrySourceDraftId: "draft-other-project", + destinationDraftId: "draft-b", + providerProfile, + }), + ).toEqual(insideSelection); + }); + it("keeps the project default above any carried selection", () => { expect( resolveNewThreadModelSelectionOverride({ diff --git a/apps/web/src/lib/chatThreadActions.ts b/apps/web/src/lib/chatThreadActions.ts index c14a26d03d1c0..870c362d4dccc 100644 --- a/apps/web/src/lib/chatThreadActions.ts +++ b/apps/web/src/lib/chatThreadActions.ts @@ -3,6 +3,7 @@ import type { EnvironmentId, ModelSelection, ProjectId, + ProviderInstanceId, ScopedProjectRef, } from "@t3tools/contracts"; import type { ComposerThreadDraftState, DraftThreadEnvMode } from "../composerDraftStore"; @@ -44,16 +45,25 @@ export function resolveNewDraftStartFromOrigin(input: { return input.envMode === "worktree" && input.newWorktreesStartFromOrigin; } +/** + * The model a new draft starts on: the project default, else the selection + * carried from the thread being viewed. A carried selection outside the + * destination project's provider profile is dropped, so switching projects + * never moves work onto another profile's account implicitly. + */ export function resolveNewThreadModelSelectionOverride(input: { readonly projectDefaultSelection: ModelSelection | null; readonly carrySelection: ModelSelection | null; readonly carrySourceDraftId: string | null; readonly destinationDraftId: string; + readonly providerProfile?: { readonly instanceIdSet: ReadonlySet } | null; }): ModelSelection | null { - return ( - input.projectDefaultSelection ?? - (input.carrySourceDraftId === input.destinationDraftId ? null : input.carrySelection) - ); + if (input.projectDefaultSelection) return input.projectDefaultSelection; + if (input.carrySourceDraftId === input.destinationDraftId || !input.carrySelection) return null; + return input.providerProfile && + !input.providerProfile.instanceIdSet.has(input.carrySelection.instanceId) + ? null + : input.carrySelection; } export function hasExplicitComposerModelSelection( diff --git a/packages/shared/src/projectSettings.test.ts b/packages/shared/src/projectSettings.test.ts index b39f0dad5f3bb..aee4e41e72510 100644 --- a/packages/shared/src/projectSettings.test.ts +++ b/packages/shared/src/projectSettings.test.ts @@ -6,16 +6,19 @@ import { ProviderDriverKind, ProviderInstanceId, ProviderProfileId, + type ServerProvider, type ServerSettings, } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { createModelSelection } from "./model.ts"; import { clearProjectSettingsOverrides, + commonProviderProfiles, hasProjectSettingsOverrides, resolveProjectFileBackedSetting, resolveProjectSettings, resolveProviderProfile, + resolveProviderProfileFallbackModelSelection, resolveWorktreeCleanup, withProjectSettingsOverrides, } from "./projectSettings.ts"; @@ -450,6 +453,54 @@ describe("provider profiles", () => { expect(resolved.settings.defaultModelSelection).toEqual(createModelSelection(ccB, "sonnet")); }); + it("falls back to a ready profile instance, never one outside the profile", () => { + const provider = ( + instanceId: ProviderInstanceId, + status: ServerProvider["status"], + enabled = true, + ) => + ({ + instanceId, + enabled, + status, + models: [ + { slug: "custom", isCustom: true }, + { slug: "haiku", isCustom: false }, + { slug: "opus", isCustom: false, isDefault: true }, + ], + }) as unknown as ServerProvider; + const profile = { instanceIds: [ccA, codexA] }; + + expect( + resolveProviderProfileFallbackModelSelection(profile, [ + provider(ccB, "ready"), + provider(ccA, "warning"), + provider(codexA, "ready"), + ]), + ).toEqual(createModelSelection(codexA, "opus")); + expect( + resolveProviderProfileFallbackModelSelection(profile, [ + provider(ccB, "ready"), + provider(ccA, "error"), + provider(codexA, "ready", false), + ]), + ).toBeNull(); + }); + + it("only offers profiles every selected environment defines", () => { + const globex = ProviderProfileId.make("globex"); + const onlyAcme = { providerProfiles: base.providerProfiles }; + const both = { + providerProfiles: { + ...base.providerProfiles, + [globex]: { name: "Globex", instanceIds: [ccB], defaultModelSelection: null }, + }, + }; + expect(commonProviderProfiles([both, onlyAcme]).map(([id]) => id)).toEqual([acme]); + expect(commonProviderProfiles([both]).map(([id]) => id)).toEqual([acme, globex]); + expect(commonProviderProfiles([both, { providerProfiles: {} }])).toEqual([]); + }); + it("upserts and removes profiles per entry", () => { const globex = ProviderProfileId.make("globex"); const added = applyServerSettingsPatch(base, { diff --git a/packages/shared/src/projectSettings.ts b/packages/shared/src/projectSettings.ts index 71e4be9ed625b..3890f6114c413 100644 --- a/packages/shared/src/projectSettings.ts +++ b/packages/shared/src/projectSettings.ts @@ -1,4 +1,5 @@ import { + isProviderAvailable, type ModelSelection, PROJECT_FILE_BACKED_SETTINGS, PROJECT_SCOPED_SERVER_SETTING_KEYS, @@ -10,6 +11,7 @@ import { type ProviderProfile, type ProviderProfileId, type ResolvedServerSettings, + type ServerProvider, type ServerSettings, type T3ProjectFile, type ThreadEnvMode, @@ -213,6 +215,46 @@ export function resolveProviderProfile( return { ...profile, id, instanceIdSet: new Set(profile.instanceIds) }; } +/** + * Profiles a multi-target settings edit can assign: those every target + * defines under the same id. Profiles are per environment, so writing an id + * a target lacks would silently mean "no profile" there. Names come from the + * first target. + */ +export function commonProviderProfiles( + targets: ReadonlyArray>, +): ReadonlyArray { + const [first, ...rest] = targets; + if (!first) return []; + return ( + Object.entries(first.providerProfiles) as Array<[ProviderProfileId, ProviderProfile]> + ).filter(([id]) => rest.every((target) => target.providerProfiles[id] !== undefined)); +} + +/** + * The model to use when a profile applies but nothing picked one: the default + * model of the profile's first ready instance, else its first one that is not + * failing. Never a provider outside the profile, so a run cannot fall back to + * another account. Null when no profile instance can start. + */ +export function resolveProviderProfileFallbackModelSelection( + profile: Pick, + providers: ReadonlyArray, +): ModelSelection | null { + const candidates = profile.instanceIds.flatMap((instanceId) => { + const provider = providers.find((candidate) => candidate.instanceId === instanceId); + return provider?.enabled && isProviderAvailable(provider) ? [provider] : []; + }); + const provider = + candidates.find((candidate) => candidate.status === "ready") ?? + candidates.find((candidate) => candidate.status !== "error"); + const model = + provider?.models.find((candidate) => candidate.isDefault && !candidate.isCustom) ?? + provider?.models.find((candidate) => !candidate.isCustom) ?? + provider?.models[0]; + return provider && model ? { instanceId: provider.instanceId, model: model.slug } : null; +} + /** * A profile replaces the inherited new-thread model: its own default when it * has one, otherwise the environment default only if the profile includes From 3af26f20227ee4d022b801795572e1dce700e1ca Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Sun, 27 Sep 2026 20:38:50 -0300 Subject: [PATCH 3/4] fix(web): unexport file-local provider profile helpers knip's unused-export check failed on two helpers only used inside ProviderProfilesSettings.tsx. Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/web/src/components/settings/ProviderProfilesSettings.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/settings/ProviderProfilesSettings.tsx b/apps/web/src/components/settings/ProviderProfilesSettings.tsx index fe7c6e7db10ec..97e7580cbd846 100644 --- a/apps/web/src/components/settings/ProviderProfilesSettings.tsx +++ b/apps/web/src/components/settings/ProviderProfilesSettings.tsx @@ -48,7 +48,7 @@ import { searchableSetting } from "./settingsSearch"; import { SETTINGS_PICKER_TRIGGER_CLASSNAME, SettingsRow, SettingsSection } from "./settingsLayout"; /** Provider instance entries for an environment, in settings order. */ -export function useProviderInstanceEntries( +function useProviderInstanceEntries( providers: ReadonlyArray, settings: Pick, ): ReadonlyArray { @@ -91,7 +91,7 @@ export function ProviderProfileInstances({ ); } -export function describeProfileModel( +function describeProfileModel( selection: ModelSelection | null, entries: ReadonlyArray, ): string { From 8b0a98c264ccc16ea23a3b329d0319bfad910716 Mon Sep 17 00:00:00 2001 From: Donald Silveira Date: Sun, 27 Sep 2026 20:40:11 -0300 Subject: [PATCH 4/4] test(web): stub resolveProviderProfile in the new-thread hook mock The hook now resolves the target project's provider profile, and the module mock lacked that export, failing 18 tests. Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/web/src/hooks/useHandleNewThread.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.ts index 3a29155bda6d9..6d852db156865 100644 --- a/apps/web/src/hooks/useHandleNewThread.test.ts +++ b/apps/web/src/hooks/useHandleNewThread.test.ts @@ -98,6 +98,8 @@ vi.mock("@t3tools/contracts", () => ({ DEFAULT_SERVER_SETTINGS: {}, })); vi.mock("@t3tools/shared/projectSettings", () => ({ + // These tests configure no provider profiles. + resolveProviderProfile: () => null, // Environment settings pass through; the tests set project fields on the // project record, which the hook still honors until the server folds them. // With a file argument the env mode resolves like the real chain.