Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat: allow toggling built-in plugins with risk confirmation (#836)

Mao Mrbcf3fb7edda5
diff --git a/src-tauri/src/service/plugin/disable.rs b/src-tauri/src/service/plugin/disable.rs
index 298a0e49..7a582d2f 100644
--- a/src-tauri/src/service/plugin/disable.rs
+++ b/src-tauri/src/service/plugin/disable.rs
@@ -221,6 +221,28 @@ fn now_seconds_string() -> String {
.unwrap_or_default()
}
+pub(crate) fn preserve_disabled_bundles(profile: &Path) -> Result<(), String> {
+ let disabled = load_disabled(profile);
+ if disabled.is_empty() {
+ return Ok(());
+ }
+ let path = profile.join("package.json");
+ let raw = fs::read_to_string(&path).map_err(|e| format!("DISABLE_READ_MANIFEST: {e}"))?;
+ let mut manifest: serde_json::Value =
+ serde_json::from_str(&raw).map_err(|e| format!("DISABLE_PARSE_MANIFEST: {e}"))?;
+ let before = manifest.clone();
+ for id in disabled.keys() {
+ remove_bundle(&mut manifest, id);
+ }
+ if manifest != before {
+ let rendered = serde_json::to_string_pretty(&manifest)
+ .map_err(|e| format!("DISABLE_RENDER_MANIFEST: {e}"))?;
+ fs::write(&path, format!("{rendered}\n"))
+ .map_err(|e| format!("DISABLE_WRITE_MANIFEST: {e}"))?;
+ }
+ Ok(())
+}
+
/// 回滚禁用清单到操作前的状态。
///
/// 当 manifest 写入失败时,把已加入禁用清单的条目移除,使两个持久化文件
@@ -424,6 +446,43 @@ mod tests {
serde_json::from_str(&content).unwrap()
}
+ #[test]
+ fn preserve_disabled_bundles_keeps_builtin_disabled_after_install() {
+ let profile = build_profile("preserve-builtin", "builtin");
+ let mut manifest = read_manifest(&profile);
+ manifest["dependencies"]["dsh-tauri-pet"] = serde_json::json!("link:/bundled/pet");
+ manifest["dsh"]["profile"]["bundles"]
+ .as_array_mut()
+ .unwrap()
+ .push(serde_json::json!("dsh-tauri-pet"));
+ fs::write(
+ profile.join("package.json"),
+ serde_json::to_string(&manifest).unwrap(),
+ )
+ .unwrap();
+ disable_plugin_at(&profile, "dsh-tauri-pet").unwrap();
+ fs::write(
+ profile.join("package.json"),
+ serde_json::to_string(&manifest).unwrap(),
+ )
+ .unwrap();
+ preserve_disabled_bundles(&profile).unwrap();
+ let preserved = read_manifest(&profile);
+ assert_eq!(preserved["dependencies"], manifest["dependencies"]);
+ assert_eq!(
+ preserved["dsh"]["profile"]["bundles"],
+ serde_json::json!(["dsh-better-sidebar", "dshmarket", "@deepseek-ai/dsh-base"])
+ );
+ assert!(load_disabled(&profile).contains_key("dsh-tauri-pet"));
+ enable_plugin_at(&profile, "dsh-tauri-pet", false).unwrap();
+ assert!(!load_disabled(&profile).contains_key("dsh-tauri-pet"));
+ assert!(read_manifest(&profile)["dsh"]["profile"]["bundles"]
+ .as_array()
+ .unwrap()
+ .contains(&serde_json::json!("dsh-tauri-pet")));
+ fs::remove_dir_all(profile).unwrap();
+ }
+
#[test]
fn disable_removes_from_bundles_only() {
let profile = build_profile("bundles-only", "a");
diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rs
index 08c2bc34..8b1bafd7 100644
--- a/src-tauri/src/service/plugin/install/mod.rs
+++ b/src-tauri/src/service/plugin/install/mod.rs
@@ -569,6 +569,8 @@ async fn install_with_cancel(
));
}
+ super::disable::preserve_disabled_bundles(&profile_dir(app_handle))?;
+
// 告知用户安装阶段结束;随后的服务重启由前端 continueAfterPreinstall 负责
let _ = window.emit(
PREINSTALL_LOG_EVENT,
diff --git a/src-tauri/src/service/plugin/internal/mod.rs b/src-tauri/src/service/plugin/internal/mod.rs
index 175053e2..9fd2f2db 100644
--- a/src-tauri/src/service/plugin/internal/mod.rs
+++ b/src-tauri/src/service/plugin/internal/mod.rs
@@ -291,6 +291,9 @@ fn ensure_fingerprint(app_handle: &AppHandle, internal: &[PreinstallPluginInfo])
std::fs::read(profile.join("package.json"))
.unwrap_or_default()
.hash(&mut hasher);
+ std::fs::read(profile.join("disabled-plugins.json"))
+ .unwrap_or_default()
+ .hash(&mut hasher);
std::fs::read(profile.join("cordis.yml"))
.unwrap_or_default()
.hash(&mut hasher);
@@ -357,6 +360,7 @@ pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {
"PROFILE_NOT_WRITABLE",
)?;
+ super::disable::preserve_disabled_bundles(&profile_dir(app_handle))?;
repair_loader_state(app_handle)?;
let outcome =
receive_current_or_next_flight(|| subscribe_or_start(app_handle, &internal)).await;
@@ -688,7 +692,11 @@ async fn ensure_inner(
// 本分支要「直接卸载」的孤儿内置插件(安装包名):其捆绑目录已不存在且仍以
// `link:`/`file:` 本地依赖形式安装在 profile 里。见下方 bundle 缺失分支的说明。
let mut orphans: Vec<String> = Vec::new();
+ let disabled = super::disable::load_disabled(&profile);
for preset in internal {
+ if disabled.contains_key(&preset.id) || disabled.contains_key(installed_name(preset)) {
+ continue;
+ }
let Some(bundled) = bundled_plugin_dir(app_handle, &preset.id) else {
// 未找到内置插件目录:release 说明构建期 build:plugins 未打包(发布
// 缺陷,由 build:plugins 响亮失败);debug 自动发现 packages/* 中非私有
@@ -1031,6 +1039,7 @@ fn materialize_internal_links(
});
}
materialize_links(profile, &links)?;
+ super::disable::preserve_disabled_bundles(profile)?;
// pnpm 失败路径已为这些 id 记过安装错误;兜底成功后必须清掉,否则插件面板
// 会继续显示「安装失败」而实际上插件已就绪(与 verify 的成功路径一致)。
for (id, _, _) in need {
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index fb342914..51b58e74 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -277,6 +277,8 @@
"plugins.hold_no_target": "No installable target version: the plugin's source is pinned, or npm reports no newer release. Reopen the panel to refresh the version list and try again.",
"plugins.authorize_failed": "Authorisation failed",
"plugins.disable": "Disable",
+ "plugins.disable_builtin_confirm_title": "Disable built-in plugin",
+ "plugins.disable_builtin_confirm_desc": "Disabling the built-in plugin {{name}} may cause the desktop shell or related features to malfunction. Confirm disabling?",
"plugins.enable": "Enable",
"plugins.disabled_badge": "Disabled",
"plugins.patch_disabled_badge": "Disabled · Config Override",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 80bf7a90..0e466326 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -277,6 +277,8 @@
"plugins.hold_no_target": "没有可安装的目标版本:插件来源被钉死,或 npm 上没有更新的版本。重新打开插件面板刷新版本列表后再试。",
"plugins.authorize_failed": "授权失败",
"plugins.disable": "禁用",
+ "plugins.disable_builtin_confirm_title": "禁用内置插件",
+ "plugins.disable_builtin_confirm_desc": "禁用内置插件 {{name}} 可能导致桌面壳或相关功能异常。是否确认禁用?",
"plugins.enable": "启用",
"plugins.disabled_badge": "已禁用",
"plugins.patch_disabled_badge": "已禁用 · 配置覆盖",
diff --git a/src/ui/config/plugin.test.tsx b/src/ui/config/plugin.test.tsx
new file mode 100644
index 00000000..e9f3dc90
--- /dev/null
+++ b/src/ui/config/plugin.test.tsx
@@ -0,0 +1,129 @@
+// @vitest-environment jsdom
+import type { ReactNode } from 'react'
+import type { Plugin } from '@/store/modules/plugins'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ConfigPlugin } from './plugin'
+
+const { manager, openDialog } = vi.hoisted(() => ({
+ manager: { installed: [] as Plugin[], processes: [], loading: false, error: '', disable: vi.fn(), enable: vi.fn() },
+ openDialog: vi.fn(),
+}))
+
+vi.mock('@/hooks/use-plugins-manager', () => ({ useDshPluginsManager: () => manager }))
+vi.mock('@overlastic/react', () => ({ useOverlay: () => [null, openDialog] }))
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))
+vi.mock('@tanstack/react-query', () => ({ useQueryClient: () => ({}), useMutation: () => ({}) }))
+vi.mock('@/store', () => ({ store: { preinstall: { open: vi.fn(), installing: false } } }))
+vi.mock('@/utils/toast', () => ({ toast: vi.fn() }))
+vi.mock('@/components/modal', () => ({ Modal: () => null }))
+vi.mock('@/components/item', () => ({ Item: ({ left, right }: { left: ReactNode, right: ReactNode }) => (
+ <div>
+ {left}
+ {right}
+ </div>
+) }))
+vi.mock('@/components/ellipsis', () => ({ Ellipsis: ({ children }: { children: ReactNode }) => <span>{children}</span> }))
+vi.mock('@/components/panel', () => ({ Panel: { Header: () => null, Loadable: ({ children }: { children: ReactNode }) => <div>{children}</div> } }))
+vi.mock('@heroui/react', () => ({
+ Chip: ({ children, onClick }: { children: ReactNode, onClick?: () => void }) => <button type="button" onClick={onClick}>{children}</button>,
+ Button: ({ children, onPress }: { children: ReactNode, onPress?: () => void }) => <button type="button" onClick={onPress}>{children}</button>,
+ Input: () => null,
+ Label: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+ Spinner: () => null,
+ Switch: () => null,
+ Tooltip: () => null,
+}))
+
+function plugin(overrides: Partial<Plugin> = {}): Plugin {
+ return {
+ id: 'dsh-tauri-pet',
+ name: 'Desktop Pet',
+ internal: true,
+ disabled: false,
+ patchDisabled: false,
+ version: '1.0.0',
+ description: '',
+ repoUrl: '',
+ bundled: true,
+ recommended: false,
+ fix: false,
+ hasSnapshot: false,
+ error: null,
+ latest: null,
+ updateAvailable: false,
+ incompatible: false,
+ latestIncompatible: false,
+ ...overrides,
+ }
+}
+
+function showBuiltIn() {
+ render(<ConfigPlugin />)
+ fireEvent.click(screen.getByRole('button', { name: 'plugins.builtin_title' }))
+}
+
+beforeEach(() => {
+ manager.installed = [plugin()]
+ manager.disable.mockReset().mockResolvedValue(undefined)
+ manager.enable.mockReset().mockResolvedValue(undefined)
+ openDialog.mockReset()
+})
+
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+describe('built-in plugin toggles', () => {
+ it('waits for risk confirmation before disabling a built-in plugin', async () => {
+ let confirm: () => void = () => {}
+ openDialog.mockImplementation(() => new Promise<void>((resolve) => {
+ confirm = resolve
+ }))
+ showBuiltIn()
+ fireEvent.click(screen.getByRole('button', { name: 'plugins.disable' }))
+ expect(openDialog).toHaveBeenCalledWith(expect.objectContaining({
+ status: 'warning',
+ title: 'plugins.disable_builtin_confirm_title',
+ confirmText: 'plugins.disable',
+ }))
+ expect(manager.disable).not.toHaveBeenCalled()
+ await act(async () => confirm())
+ expect(manager.disable).toHaveBeenCalledExactlyOnceWith('dsh-tauri-pet')
+ })
+
+ it('does not disable when the risk dialog is cancelled', async () => {
+ openDialog.mockRejectedValue(new Error('cancelled'))
+ showBuiltIn()
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'plugins.disable' })))
+ expect(openDialog).toHaveBeenCalledTimes(1)
+ expect(manager.disable).not.toHaveBeenCalled()
+ })
+
+ it('enables a desktop-disabled built-in without showing a disable action', async () => {
+ manager.installed = [plugin({ disabled: true })]
+ showBuiltIn()
+ expect(screen.queryByRole('button', { name: 'plugins.disable' })).toBeNull()
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'plugins.enable' })))
+ expect(manager.enable).toHaveBeenCalledExactlyOnceWith('dsh-tauri-pet', { clearConfigOverride: false })
+ expect(openDialog).not.toHaveBeenCalled()
+ })
+
+ it('keeps explicit confirmation for enabling a config-disabled built-in', async () => {
+ manager.installed = [plugin({ patchDisabled: true })]
+ openDialog.mockResolvedValue(undefined)
+ showBuiltIn()
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'plugins.enable' })))
+ expect(openDialog).toHaveBeenCalledWith(expect.objectContaining({ title: 'plugins.enable_override_confirm_title' }))
+ expect(manager.enable).toHaveBeenCalledExactlyOnceWith('dsh-tauri-pet', { clearConfigOverride: true })
+ })
+
+ it('keeps non-built-in disabling direct', async () => {
+ manager.installed = [plugin({ internal: false })]
+ render(<ConfigPlugin />)
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'plugins.disable' })))
+ expect(manager.disable).toHaveBeenCalledExactlyOnceWith('dsh-tauri-pet')
+ expect(openDialog).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/ui/config/plugin.tsx b/src/ui/config/plugin.tsx
index 14b68e6d..060f09b7 100644
--- a/src/ui/config/plugin.tsx
+++ b/src/ui/config/plugin.tsx
@@ -68,7 +68,6 @@ export function ConfigPlugin() {
const internalPlugins = plugins.filter(plugin => plugin.internal)
const managedPlugins = plugins.filter(plugin => !plugin.internal)
- /** 「内置插件」分组是否展开:默认折叠,内置插件由启动自愈维护,不作为常规可管理项 */
const [showInternal, toggleShowInternal] = useToggle()
/** 高级选项:默认关闭,快照(创建/还原/删除)属于低频维护操作,不常驻每行 */
const [advanced, toggleAdvanced] = useToggle()
@@ -227,6 +226,23 @@ export function ConfigPlugin() {
}
async function onDisable(id: string) {
+ if (rowBusy(id))
+ return
+ const plugin = plugins.find(p => p.id === id)
+ if (plugin?.internal) {
+ try {
+ await openDialog({
+ status: 'warning',
+ title: t('plugins.disable_builtin_confirm_title'),
+ description: <p>{t('plugins.disable_builtin_confirm_desc', { name: plugin.name })}</p>,
+ confirmText: t('plugins.disable'),
+ })
+ }
+ catch (e) {
+ silence(e, 'plugin disable: dialog cancelled')
+ return
+ }
+ }
await runAction(id, 'disable', () => manager.disable(id))
}
@@ -453,9 +469,7 @@ export function ConfigPlugin() {
</span>
</Chip>
</If>
- {/* 启用入口:配置覆盖禁用(含内置插件)或桌面禁用清单 → 可启用。
- 配置覆盖禁用时点击会先弹确认框,确认后管理器透传 clearConfigOverride */}
- <If cond={plugin.patchDisabled || (!plugin.internal && plugin.disabled)}>
+ <If cond={plugin.patchDisabled || plugin.disabled}>
<Chip
className={actionChip({ busy: rowBusy(plugin.id) })}
variant="primary"
@@ -469,7 +483,7 @@ export function ConfigPlugin() {
</span>
</Chip>
</If>
- <If cond={!plugin.internal && !plugin.patchDisabled && !plugin.disabled}>
+ <If cond={!plugin.patchDisabled && !plugin.disabled}>
<Chip
className={actionChip({ busy: rowBusy(plugin.id) })}
size="sm"
diff --git a/test/plugin-disable.test.ts b/test/plugin-disable.test.ts
index 724af158..9aa3cddc 100644
--- a/test/plugin-disable.test.ts
+++ b/test/plugin-disable.test.ts
@@ -34,15 +34,14 @@ describe('plugin disable/enable frontend contract', () => {
expect(source).toContain('\'update\' | \'remove\' | \'disable\' | \'enable\'')
})
- it('config-plugin.tsx does NOT open a confirmation dialog for disable (reversible action)', () => {
+ it('config-plugin.tsx confirms before disabling a built-in plugin', () => {
const source = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')
- // onDisable must not call openDialog — the disable handler is a direct action,
- // unlike onRemove which confirms via openDialog. We assert the onDisable block
- // contains no openDialog invocation.
const onDisableMatch = source.match(/async function onDisable[\s\S]*?\n {2}\}/)
expect(onDisableMatch).not.toBeNull()
- expect(onDisableMatch![0]).not.toContain('openDialog')
+ expect(onDisableMatch![0]).toContain('if (plugin?.internal)')
+ expect(onDisableMatch![0]).toContain('await openDialog')
+ expect(onDisableMatch![0]).toContain('plugins.disable_builtin_confirm_desc')
})
it('the plugin manager owns the single plugin list query and update probe', () => {
diff --git a/test/plugin-uninstall.test.ts b/test/plugin-uninstall.test.ts
index ee07fd19..7479b907 100644
--- a/test/plugin-uninstall.test.ts
+++ b/test/plugin-uninstall.test.ts
@@ -59,10 +59,10 @@ describe('configPlugin preset chip', () => {
expect(source).toContain('plugins.builtin')
})
- it('withholds uninstall/disable/snapshot from internal plugins', () => {
+ it('allows internal toggles while withholding uninstall/snapshot', () => {
const source = readFileSync(new URL('../src/ui/config/plugin.tsx', import.meta.url), 'utf8')
- expect(source, '禁用入口排除内置插件').toContain('cond={!plugin.internal && !plugin.patchDisabled && !plugin.disabled}')
- expect(source, '启用入口排除内置插件的桌面禁用态').toContain('cond={plugin.patchDisabled || (!plugin.internal && plugin.disabled)}')
+ expect(source, '禁用入口包含内置插件').toContain('cond={!plugin.patchDisabled && !plugin.disabled}')
+ expect(source, '启用入口包含内置插件的桌面禁用态').toContain('cond={plugin.patchDisabled || plugin.disabled}')
expect(source, '快照入口由 !plugin.internal 守卫').toContain('<If cond={!plugin.internal}>')
})