cherry-studio/src/main/services/AppUpdater.ts
亢奋猫 1c7b7a1a55
feat: add code tools (#9043)
* feat: add code tools

* feat(CodeToolsService): add CLI executable management and installation check

- Introduced methods to determine the CLI executable name based on the tool.
- Added functionality to check if a package is installed and create the necessary bin directory if it doesn't exist.
- Enhanced the run method to handle installation and execution of CLI tools based on their installation status.
- Updated terminal command handling for different operating systems with improved comments and error messages.

* feat(ipService): implement IP address country detection and npm registry URL selection

- Added a new module for IP address country detection using the ipinfo.io API.
- Implemented functions to check if the user is in China and to return the appropriate npm registry URL based on the user's location.
- Updated AppUpdater and CodeToolsService to utilize the new ipService functions for improved user experience based on geographical location.
- Enhanced error handling and logging for better debugging and user feedback.

* feat: remember cli model

* feat(CodeToolsService): update options for auto-update functionality

- Refactored the options parameter in CodeToolsService to replace checkUpdate and forceUpdate with autoUpdateToLatest.
- Updated logic to handle automatic updates when the CLI tool is already installed.
- Modified related UI components to reflect the new auto-update option.
- Added corresponding translations for the new feature in multiple languages.

* feat(CodeToolsService): enhance CLI tool launch with debugging support

- Added detailed logging for CLI tool launch process, including environment variables and options.
- Implemented a temporary batch file for Windows to facilitate debugging and command execution.
- Improved error handling and cleanup for the temporary batch file after execution.
- Updated terminal command handling to use the new batch file for safer execution.

* refactor(CodeToolsService): simplify command execution output

- Removed display of environment variable settings during command execution in the CLI tool.
- Updated comments for clarity on the command execution process.

* feat(CodePage): add model filtering logic for provider selection

- Introduced a modelPredicate function to filter out embedding, rerank, and text-to-image models from the available providers.
- Updated the ModelSelector component to utilize the new predicate for improved model selection experience.

* refactor(CodeToolsService): improve logging and cleanup for CLI tool execution

- Updated logging to display only the keys of environment variables during CLI tool launch for better clarity.
- Introduced a variable to store the path of the temporary batch file for Windows.
- Enhanced cleanup logic to remove the temporary batch file after execution, improving resource management.

* feat(Router): replace CodePage with CodeToolsPage and add new page for code tools

- Updated Router to import and route to the new CodeToolsPage instead of the old CodePage.
- Introduced CodeToolsPage component, which provides a user interface for selecting CLI tools and models, managing directories, and launching code tools with enhanced functionality.

* refactor(CodeToolsService): improve temporary file management and cleanup

- Removed unused variable for Windows batch file path.
- Added a cleanup task to delete the temporary batch file after 10 seconds to enhance resource management.
- Updated logging to ensure clarity during the execution of CLI tools.

* refactor(CodeToolsService): streamline environment variable handling for CLI tool execution

- Introduced a utility function to remove proxy-related environment variables before launching terminal processes.
- Updated logging to display only the relevant environment variable keys, enhancing clarity during execution.

* refactor(MCPService, CodeToolsService): unify proxy environment variable handling

- Replaced custom proxy removal logic with a shared utility function `removeEnvProxy` to streamline environment variable management across services.
- Updated logging to reflect changes in environment variable handling during CLI tool execution.
2025-08-12 11:54:38 +08:00

282 lines
9.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { loggerService } from '@logger'
import { isWin } from '@main/constant'
import { getIpCountry } from '@main/utils/ipService'
import { locales } from '@main/utils/locales'
import { generateUserAgent } from '@main/utils/systemInfo'
import { FeedUrl, UpgradeChannel } from '@shared/config/constant'
import { IpcChannel } from '@shared/IpcChannel'
import { CancellationToken, UpdateInfo } from 'builder-util-runtime'
import { app, BrowserWindow, dialog } from 'electron'
import { AppUpdater as _AppUpdater, autoUpdater, Logger, NsisUpdater, UpdateCheckResult } from 'electron-updater'
import path from 'path'
import icon from '../../../build/icon.png?asset'
import { configManager } from './ConfigManager'
const logger = loggerService.withContext('AppUpdater')
export default class AppUpdater {
autoUpdater: _AppUpdater = autoUpdater
private releaseInfo: UpdateInfo | undefined
private cancellationToken: CancellationToken = new CancellationToken()
private updateCheckResult: UpdateCheckResult | null = null
constructor(mainWindow: BrowserWindow) {
autoUpdater.logger = logger as Logger
autoUpdater.forceDevUpdateConfig = !app.isPackaged
autoUpdater.autoDownload = configManager.getAutoUpdate()
autoUpdater.autoInstallOnAppQuit = configManager.getAutoUpdate()
autoUpdater.requestHeaders = {
...autoUpdater.requestHeaders,
'User-Agent': generateUserAgent()
}
autoUpdater.on('error', (error) => {
logger.error('update error', error as Error)
mainWindow.webContents.send(IpcChannel.UpdateError, error)
})
autoUpdater.on('update-available', (releaseInfo: UpdateInfo) => {
logger.info('update available', releaseInfo)
mainWindow.webContents.send(IpcChannel.UpdateAvailable, releaseInfo)
})
// 检测到不需要更新时
autoUpdater.on('update-not-available', () => {
if (configManager.getTestPlan() && this.autoUpdater.channel !== UpgradeChannel.LATEST) {
logger.info('test plan is enabled, but update is not available, do not send update not available event')
// will not send update not available event, because will check for updates with latest channel
return
}
mainWindow.webContents.send(IpcChannel.UpdateNotAvailable)
})
// 更新下载进度
autoUpdater.on('download-progress', (progress) => {
mainWindow.webContents.send(IpcChannel.DownloadProgress, progress)
})
// 当需要更新的内容下载完成后
autoUpdater.on('update-downloaded', (releaseInfo: UpdateInfo) => {
mainWindow.webContents.send(IpcChannel.UpdateDownloaded, releaseInfo)
this.releaseInfo = releaseInfo
logger.info('update downloaded', releaseInfo)
})
if (isWin) {
;(autoUpdater as NsisUpdater).installDirectory = path.dirname(app.getPath('exe'))
}
this.autoUpdater = autoUpdater
}
private async _getPreReleaseVersionFromGithub(channel: UpgradeChannel) {
try {
logger.info(`get pre release version from github: ${channel}`)
const responses = await fetch('https://api.github.com/repos/CherryHQ/cherry-studio/releases?per_page=8', {
headers: {
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
'Accept-Language': 'en-US,en;q=0.9'
}
})
const data = (await responses.json()) as GithubReleaseInfo[]
const release: GithubReleaseInfo | undefined = data.find((item: GithubReleaseInfo) => {
return item.prerelease && item.tag_name.includes(`-${channel}.`)
})
if (!release) {
return null
}
logger.info(`prerelease url is ${release.tag_name}, set channel to ${channel}`)
return `https://github.com/CherryHQ/cherry-studio/releases/download/${release.tag_name}`
} catch (error) {
logger.error('Failed to get latest not draft version from github:', error as Error)
return null
}
}
public setAutoUpdate(isActive: boolean) {
autoUpdater.autoDownload = isActive
autoUpdater.autoInstallOnAppQuit = isActive
}
private _getChannelByVersion(version: string) {
if (version.includes(`-${UpgradeChannel.BETA}.`)) {
return UpgradeChannel.BETA
}
if (version.includes(`-${UpgradeChannel.RC}.`)) {
return UpgradeChannel.RC
}
return UpgradeChannel.LATEST
}
private _getTestChannel() {
const currentChannel = this._getChannelByVersion(app.getVersion())
const savedChannel = configManager.getTestChannel()
if (currentChannel === UpgradeChannel.LATEST) {
return savedChannel || UpgradeChannel.RC
}
if (savedChannel === currentChannel) {
return savedChannel
}
// if the upgrade channel is not equal to the current channel, use the latest channel
return UpgradeChannel.LATEST
}
private _setChannel(channel: UpgradeChannel, feedUrl: string) {
this.autoUpdater.channel = channel
this.autoUpdater.setFeedURL(feedUrl)
// disable downgrade after change the channel
this.autoUpdater.allowDowngrade = false
// github and gitcode don't support multiple range download
this.autoUpdater.disableDifferentialDownload = true
}
private async _setFeedUrl() {
const testPlan = configManager.getTestPlan()
if (testPlan) {
const channel = this._getTestChannel()
if (channel === UpgradeChannel.LATEST) {
this._setChannel(UpgradeChannel.LATEST, FeedUrl.GITHUB_LATEST)
return
}
const preReleaseUrl = await this._getPreReleaseVersionFromGithub(channel)
if (preReleaseUrl) {
logger.info(`prerelease url is ${preReleaseUrl}, set channel to ${channel}`)
this._setChannel(channel, preReleaseUrl)
return
}
// if no prerelease url, use github latest to avoid error
this._setChannel(UpgradeChannel.LATEST, FeedUrl.GITHUB_LATEST)
return
}
this._setChannel(UpgradeChannel.LATEST, FeedUrl.PRODUCTION)
const ipCountry = await getIpCountry()
logger.info(`ipCountry is ${ipCountry}, set channel to ${UpgradeChannel.LATEST}`)
if (ipCountry.toLowerCase() !== 'cn') {
this._setChannel(UpgradeChannel.LATEST, FeedUrl.GITHUB_LATEST)
}
}
public cancelDownload() {
this.cancellationToken.cancel()
this.cancellationToken = new CancellationToken()
if (this.autoUpdater.autoDownload) {
this.updateCheckResult?.cancellationToken?.cancel()
}
}
public async checkForUpdates() {
if (isWin && 'PORTABLE_EXECUTABLE_DIR' in process.env) {
return {
currentVersion: app.getVersion(),
updateInfo: null
}
}
try {
await this._setFeedUrl()
this.updateCheckResult = await this.autoUpdater.checkForUpdates()
logger.info(
`update check result: ${this.updateCheckResult?.isUpdateAvailable}, channel: ${this.autoUpdater.channel}, currentVersion: ${this.autoUpdater.currentVersion}`
)
// if the update is not available, and the test plan is enabled, set the feed url to the github latest
if (
!this.updateCheckResult?.isUpdateAvailable &&
configManager.getTestPlan() &&
this.autoUpdater.channel !== UpgradeChannel.LATEST
) {
logger.info('test plan is enabled, but update is not available, set channel to latest')
this._setChannel(UpgradeChannel.LATEST, FeedUrl.GITHUB_LATEST)
this.updateCheckResult = await this.autoUpdater.checkForUpdates()
}
if (this.updateCheckResult?.isUpdateAvailable && !this.autoUpdater.autoDownload) {
// 如果 autoDownload 为 false则需要再调用下面的函数触发下
// do not use await, because it will block the return of this function
logger.info('downloadUpdate manual by check for updates', this.cancellationToken)
this.autoUpdater.downloadUpdate(this.cancellationToken)
}
return {
currentVersion: this.autoUpdater.currentVersion,
updateInfo: this.updateCheckResult?.isUpdateAvailable ? this.updateCheckResult?.updateInfo : null
}
} catch (error) {
logger.error('Failed to check for update:', error as Error)
return {
currentVersion: app.getVersion(),
updateInfo: null
}
}
}
public async showUpdateDialog(mainWindow: BrowserWindow) {
if (!this.releaseInfo) {
return
}
const locale = locales[configManager.getLanguage()]
const { update: updateLocale } = locale.translation
let detail = this.formatReleaseNotes(this.releaseInfo.releaseNotes)
if (detail === '') {
detail = updateLocale.noReleaseNotes
}
dialog
.showMessageBox({
type: 'info',
title: updateLocale.title,
icon,
message: updateLocale.message.replace('{{version}}', this.releaseInfo.version),
detail,
buttons: [updateLocale.later, updateLocale.install],
defaultId: 1,
cancelId: 0
})
.then(({ response }) => {
if (response === 1) {
app.isQuitting = true
setImmediate(() => autoUpdater.quitAndInstall())
} else {
mainWindow.webContents.send(IpcChannel.UpdateDownloadedCancelled)
}
})
}
private formatReleaseNotes(releaseNotes: string | ReleaseNoteInfo[] | null | undefined): string {
if (!releaseNotes) {
return ''
}
if (typeof releaseNotes === 'string') {
return releaseNotes
}
return releaseNotes.map((note) => note.note).join('\n')
}
}
interface GithubReleaseInfo {
draft: boolean
prerelease: boolean
tag_name: string
}
interface ReleaseNoteInfo {
readonly version: string
readonly note: string | null
}