DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(model-extras): 清理废弃编辑器配置代码,简化组件实现
hairyfce1f650f1e47
diff --git a/packages/dsh-tauri-ui/src/client/service/editor.ts b/packages/dsh-tauri-ui/src/client/service/editor.tsdeleted file mode 100644index 19eb0a9c..00000000--- a/packages/dsh-tauri-ui/src/client/service/editor.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { EditorPreference } from '../../shared/editor.types'-import { parseEditorPreference } from '../../shared/editor'-import { getConfigEditor, putConfigEditor } from '../apis'--export async function loadEditor(): Promise<EditorPreference> {- const response = await getConfigEditor({ ignoreResponseError: true })- if (response.error)- throw new Error(response.error)- return parseEditorPreference(response.preference)-}--export async function saveEditor(preference: EditorPreference): Promise<{ ok: boolean, error?: string }> {- try {- const response = await putConfigEditor({ preference: parseEditorPreference(preference) }, { ignoreResponseError: true })- if (response.error)- return { ok: false, error: response.error }- parseEditorPreference(response.preference)- return { ok: true }- }- catch (error) {- return { ok: false, error: error instanceof Error ? error.message : String(error) }- }-}diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/auto-config-all-button.tsx b/packages/dsh-tauri-ui/src/client/ui/model-extras/auto-config-all-button.tsxindex e9b8b16a..72da2f6d 100644--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/auto-config-all-button.tsx+++ b/packages/dsh-tauri-ui/src/client/ui/model-extras/auto-config-all-button.tsx@@ -1,27 +1,25 @@import type { ReactElement } from 'react'import type { AutoConfigAllButtonProps } from './auto-config-all-button.types'-import { useMountStyle } from '../../hooks/use-mount-style'-import modelExtrasStyle, { MODEL_EXTRAS_STYLE_ID } from './model-extras.cssr'+import { Action } from '../../components/action'+import { Text } from '../../components/text'import { useModelConfigFetch } from './use-model-config-fetch'export function AutoConfigAllButton({ t, models, probe, operations, disabled, onApply }: AutoConfigAllButtonProps): ReactElement {- useMountStyle(modelExtrasStyle, MODEL_EXTRAS_STYLE_ID)const { busy, failure, notice, run } = useModelConfigFetch({ t, models, probe, operations, onApply })return (<>- <button- type="button"- className="dshp-model-extras__link"+ <Action+ variant="link"disabled={disabled === true || busy || models.length === 0}title={t('autoConfigureModelsHint')}aria-busy={busy}onClick={() => run()}>{busy ? t('fetchingConfig') : t('autoConfigureModels')}- </button>- {failure === undefined ? null : <p className="dshp-model-extras__notice dshp-model-extras__notice--failed" role="alert">{failure}</p>}- {notice === undefined ? null : <p className="dshp-model-extras__notice dshp-model-extras__notice--done">{notice}</p>}+ </Action>+ {failure === undefined ? null : <Text tone="error" className="flex-[1_1_100%] min-w-0 [overflow-wrap:anywhere]" role="alert">{failure}</Text>}+ {notice === undefined ? null : <Text tone="success" className="flex-[1_1_100%] min-w-0 [overflow-wrap:anywhere]">{notice}</Text>}</>)}diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/config-editor.cssr.ts b/packages/dsh-tauri-ui/src/client/ui/model-extras/config-editor.cssr.tsdeleted file mode 100644index cb7683a6..00000000--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/config-editor.cssr.ts+++ /dev/null@@ -1,30 +0,0 @@-import { cssr } from '../../utils/cssr'--export const MODEL_CONFIG_TOOLBAR_STYLE_ID = 'dsh-tauri-ui-model-config-toolbar-styles'--const { c } = cssr-const vscode = '<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg"><mask id="mask0" mask-type="alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="100" height="100"><path fill-rule="evenodd" clip-rule="evenodd" d="M70.9119 99.3171C72.4869 99.9307 74.2828 99.8914 75.8725 99.1264L96.4608 89.2197C98.6242 88.1787 100 85.9892 100 83.5872V16.4133C100 14.0113 98.6243 11.8218 96.4609 10.7808L75.8725 0.873756C73.7862 -0.130129 71.3446 0.11576 69.5135 1.44695C69.252 1.63711 69.0028 1.84943 68.769 2.08341L29.3551 38.0415L12.1872 25.0096C10.589 23.7965 8.35363 23.8959 6.86933 25.2461L1.36303 30.2549C-0.452552 31.9064 -0.454633 34.7627 1.35853 36.417L16.2471 50.0001L1.35853 63.5832C-0.454633 65.2374 -0.452552 68.0938 1.36303 69.7453L6.86933 74.7541C8.35363 76.1043 10.589 76.2037 12.1872 74.9905L29.3551 61.9587L68.769 97.9167C69.3925 98.5406 70.1246 99.0104 70.9119 99.3171ZM75.0152 27.2989L45.1091 50.0001L75.0152 72.7012V27.2989Z" fill="white"/></mask><g mask="url(#mask0)"><path d="M96.4614 10.7962L75.8569 0.875542C73.4719 -0.272773 70.6217 0.211611 68.75 2.08333L1.29858 63.5832C-0.515693 65.2373 -0.513607 68.0937 1.30308 69.7452L6.81272 74.754C8.29793 76.1042 10.5347 76.2036 12.1338 74.9905L93.3609 13.3699C96.086 11.3026 100 13.2462 100 16.6667V16.4275C100 14.0265 98.6246 11.8378 96.4614 10.7962Z" fill="#0065A9"/><g filter="url(#filter0_d)"><path d="M96.4614 89.2038L75.8569 99.1245C73.4719 100.273 70.6217 99.7884 68.75 97.9167L1.29858 36.4169C-0.515693 34.7627 -0.513607 31.9063 1.30308 30.2548L6.81272 25.246C8.29793 23.8958 10.5347 23.7964 12.1338 25.0095L93.3609 86.6301C96.086 88.6974 100 86.7538 100 83.3334V83.5726C100 85.9735 98.6246 88.1622 96.4614 89.2038Z" fill="#007ACC"/></g><g filter="url(#filter1_d)"><path d="M75.8578 99.1263C73.4721 100.274 70.6219 99.7885 68.75 97.9166C71.0564 100.223 75 98.5895 75 95.3278V4.67213C75 1.41039 71.0564 -0.223106 68.75 2.08329C70.6219 0.211402 73.4721 -0.273666 75.8578 0.873633L96.4587 10.7807C98.6234 11.8217 100 14.0112 100 16.4132V83.5871C100 85.9891 98.6234 88.1786 96.4586 89.2196L75.8578 99.1263Z" fill="#1F9CF0"/></g><g style="mix-blend-mode:overlay" opacity="0.25"><path fill-rule="evenodd" clip-rule="evenodd" d="M70.8511 99.3171C72.4261 99.9306 74.2221 99.8913 75.8117 99.1264L96.4 89.2197C98.5634 88.1787 99.9392 85.9892 99.9392 83.5871V16.4133C99.9392 14.0112 98.5635 11.8217 96.4001 10.7807L75.8117 0.873695C73.7255 -0.13019 71.2838 0.115699 69.4527 1.44688C69.1912 1.63705 68.942 1.84937 68.7082 2.08335L29.2943 38.0414L12.1264 25.0096C10.5283 23.7964 8.29285 23.8959 6.80855 25.246L1.30225 30.2548C-0.513334 31.9064 -0.515415 34.7627 1.29775 36.4169L16.1863 50L1.29775 63.5832C-0.515415 65.2374 -0.513334 68.0937 1.30225 69.7452L6.80855 74.754C8.29285 76.1042 10.5283 76.2036 12.1264 74.9905L29.2943 61.9586L68.7082 97.9167C69.3317 98.5405 70.0638 99.0104 70.8511 99.3171ZM74.9544 27.2989L45.0483 50L74.9544 72.7012V27.2989Z" fill="url(#paint0_linear)"/></g></g><defs><filter id="filter0_d" x="-8.39411" y="15.8291" width="116.727" height="92.2456" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset/><feGaussianBlur stdDeviation="4.16667"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend mode="overlay" in2="BackgroundImageFix" result="effect1_dropShadow"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/></filter><filter id="filter1_d" x="60.4167" y="-8.07558" width="47.9167" height="116.151" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/><feOffset/><feGaussianBlur stdDeviation="4.16667"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend mode="overlay" in2="BackgroundImageFix" result="effect1_dropShadow"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/></filter><linearGradient id="paint0_linear" x1="49.9392" y1="0.257812" x2="49.9392" y2="99.7423" gradientUnits="userSpaceOnUse"><stop stop-color="white"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient></defs></svg>'-const cursor = '<svg id="Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs><style>\n .st0 {\n fill: #26251e;\n }\n </style></defs><path class="st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"/></svg>'-const system = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="13" rx="2"/><path d="M8 21h8m-4-4v4"/></svg>'-const custom = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="m15 5 4 4M4 20l5-1L21 7a2.8 2.8 0 0 0-4-4L5 15l-1 5Z"/></svg>'--export const configEditorStyle = c([- c('.dshp-model-config-toolbar__trigger', {- gap: '5px',- whiteSpace: 'nowrap',- }),- c('.dshp-model-config-toolbar__icon', {- display: 'inline-block',- flex: 'none',- width: '16px',- height: '16px',- }),- c('.dshp-model-config-toolbar__icon--vscode', {- background: `url("data:image/svg+xml,${encodeURIComponent(vscode)}") center / contain no-repeat`,- }),- ...Object.entries({ system, cursor, custom }).map(([name, svg]) => c(`.dshp-model-config-toolbar__icon--${name}`, {- backgroundColor: 'currentColor',- mask: `url("data:image/svg+xml,${encodeURIComponent(svg)}") center / contain no-repeat`,- WebkitMask: `url("data:image/svg+xml,${encodeURIComponent(svg)}") center / contain no-repeat`,- })),-])diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.cssr.ts b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.cssr.tsdeleted file mode 100644index 58f7868d..00000000--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.cssr.ts+++ /dev/null@@ -1,73 +0,0 @@-import { styles as sharedStyles } from '../../constants/theme'-import { cssr } from '../../utils/cssr'--export const MODEL_COMPAT_FIELDS_STYLE_ID = 'dsh-tauri-ui-model-compat-fields-styles'--const { c } = cssr-const { secondary, tertiary, borderL3, brand, focusRing } = sharedStyles--export default c([- c('.dshp-model-compat', {- order: '1',- display: 'flex',- gap: '16px',- minWidth: '0',- margin: '0',- padding: '0',- border: 'none',- }),- c('.dshp-model-compat__field', {- display: 'flex',- flexDirection: 'column',- gap: '4px',- minWidth: '0',- }),- c('.dshp-model-compat__label', {- padding: '0',- color: tertiary,- fontSize: '12px',- lineHeight: '18px',- }),- c('.dshp-model-compat__switch', {- display: 'flex',- alignItems: 'center',- height: '32px',- }),- c('.dshp-model-compat__levels', {- order: '3',- gridColumn: '1 / -1',- display: 'flex',- flexDirection: 'column',- gap: '4px',- }),- c('.dshp-model-compat__chips', {- display: 'flex',- flexWrap: 'wrap',- gap: '6px',- }),- c('.dshp-model-compat__chip', {- display: 'inline-flex',- alignItems: 'center',- gap: '4px',- height: '24px',- padding: '0 8px',- border: `0.5px solid ${borderL3}`,- borderRadius: '6px',- fontSize: '12px',- lineHeight: '18px',- color: secondary,- cursor: 'pointer',- }, [- c('&:has(input:disabled)', {- opacity: '0.6',- cursor: 'default',- }),- c('input', {- width: '12px',- height: '12px',- margin: '0',- accentColor: brand,- }),- c('input:focus-visible', focusRing),- ]),-])diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.test.tsx b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.test.tsxindex 15f68c10..1e5f2ccf 100644--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.test.tsx+++ b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.test.tsx@@ -71,11 +71,11 @@ function switches(html: string): SwitchState[] {}function fieldLabels(html: string): string[] {- return [...html.matchAll(/<span class="dshp-model-compat__label"([^>]*)>([^<]*)<\/span>/g)].map(match => match[2] ?? '')+ return [...html.matchAll(/<span data-slot="model-compat-label"[^>]*>([^<]*)<\/span>/g)].map(match => match[1] ?? '')}function chips(html: string): { checked: boolean, disabled: boolean, level: string }[] {- return [...html.matchAll(/<label class="dshp-model-compat__chip"><input type="checkbox"([^>]*)>([a-z]+)<\/label>/g)]+ return [...html.matchAll(/<label data-slot="model-compat-chip"[^>]*><input type="checkbox"([^>]*)>([a-z]+)<\/label>/g)].map(match => ({checked: (match[1] ?? '').includes('checked'),disabled: (match[1] ?? '').includes('disabled'),diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.tsx b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.tsxindex e48655b6..37bd2e9f 100644--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.tsx+++ b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.tsx@@ -1,7 +1,6 @@import type { ReactElement } from 'react'-import type { ModelCompatFieldsProps } from './model-compat-fields.types'+import type { Translate } from './types'import { Switch } from '@deepseek-ai/dsh-client-ui-primitives'-import { useMountStyle } from '../../hooks/use-mount-style'import {declaredThinkingLevels,enableThinking,@@ -12,7 +11,22 @@ import {thinkingEffortsOf,toggleThinkingLevel,} from '../../service/model-compat'-import modelCompatFieldsStyle, { MODEL_COMPAT_FIELDS_STYLE_ID } from './model-compat-fields.cssr'++/** 字段名、开关位、思考等级胶囊三段的公共排版。 */+const FIELD = 'flex flex-col gap-[4px] min-w-0'+const LABEL = 'p-0 text-tertiary text-[12px] leading-[18px]'+const SWITCH_ROW = 'flex items-center h-[32px]'+const CHIP = 'inline-flex items-center gap-[4px] h-[24px] px-[8px] border-[0.5px] border-border-l3 rounded-[6px] text-[12px] leading-[18px] text-secondary cursor-pointer [&:has(input:disabled)]:opacity-60 [&:has(input:disabled)]:cursor-default [&_input]:w-[12px] [&_input]:h-[12px] [&_input]:m-0 [&_input]:accent-brand [&_input:focus-visible]:shadow-focus-ring'++export interface ModelCompatFieldsProps {+ t: Translate+ model: Record<string, unknown>+ index: number+ /** 协议是 chat completions 时才渲染「关闭 Developer 角色」开关,由调用方按自己的路由判断。 */+ templateCompat: boolean+ onPatch: (patch: Record<string, unknown>) => void+ disabled?: boolean | undefined+}export function ModelCompatFields({t,@@ -22,14 +36,13 @@ export function ModelCompatFields({onPatch,disabled,}: ModelCompatFieldsProps): ReactElement {- useMountStyle(modelCompatFieldsStyle, MODEL_COMPAT_FIELDS_STYLE_ID)const position = index + 1return (<>- <div className="dshp-model-compat">- <div className="dshp-model-compat__field">- <span className="dshp-model-compat__label" title={t('thinkingModeHint')}>{t('thinkingMode')}</span>- <div className="dshp-model-compat__switch">+ <div className="order-[1] flex gap-[16px] min-w-0 m-0 p-0 border-none">+ <div className={FIELD}>+ <span data-slot="model-compat-label" className={LABEL} title={t('thinkingModeHint')}>{t('thinkingMode')}</span>+ <div className={SWITCH_ROW}><Switchchecked={supportsThinking(model)}disabled={disabled}@@ -41,9 +54,9 @@ export function ModelCompatFields({</div>{templateCompat? (- <div className="dshp-model-compat__field">- <span className="dshp-model-compat__label" title={t('developerRoleHint')}>{t('developerRole')}</span>- <div className="dshp-model-compat__switch">+ <div className={FIELD}>+ <span data-slot="model-compat-label" className={LABEL} title={t('developerRoleHint')}>{t('developerRole')}</span>+ <div className={SWITCH_ROW}><Switchchecked={supportsTemplateThinking(model)}disabled={disabled}@@ -58,11 +71,11 @@ export function ModelCompatFields({</div>{supportsThinking(model)? (- <div className="dshp-model-compat__levels" role="group" aria-label={`${t('thinkingLevels')} ${String(position)}`}>- <span className="dshp-model-compat__label">{t('thinkingLevels')}</span>- <div className="dshp-model-compat__chips">+ <div className="order-[3] col-span-full flex flex-col gap-[4px]" role="group" aria-label={`${t('thinkingLevels')} ${String(position)}`}>+ <span data-slot="model-compat-label" className={LABEL}>{t('thinkingLevels')}</span>+ <div className="flex flex-wrap gap-[6px]">{THINKING_LEVELS.map(level => (- <label key={level} className="dshp-model-compat__chip">+ <label key={level} data-slot="model-compat-chip" className={CHIP}><inputtype="checkbox"checked={declaredThinkingLevels(model).includes(level)}diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.types.ts b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.types.tsdeleted file mode 100644index 2178976c..00000000--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-compat-fields.types.ts+++ /dev/null@@ -1,11 +0,0 @@-import type { Translate } from './types'--export interface ModelCompatFieldsProps {- t: Translate- model: Record<string, unknown>- index: number- /** 协议是 chat completions 时才渲染「关闭 Developer 角色」开关,由调用方按自己的路由判断。 */- templateCompat: boolean- onPatch: (patch: Record<string, unknown>) => void- disabled?: boolean | undefined-}diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-config-toolbar.tsx b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-config-toolbar.tsxindex a911b382..38956c29 100644--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-config-toolbar.tsx+++ b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-config-toolbar.tsx@@ -1,184 +1,52 @@-import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives'import type { ReactElement } from 'react'-import type { ModelConfigToolbarProps } from './model-config-toolbar.types'-import { Button, Menu, Modal } from '@deepseek-ai/dsh-client-ui-primitives'-import { useState } from 'react'-import { ChevronDown } from '../../components/icons'-import { useMountStyle } from '../../hooks/use-mount-style'-import { loadEditor, saveEditor } from '../../service/editor'-import { withDetail } from '../../service/model-config.utils'-import { configEditorStyle, MODEL_CONFIG_TOOLBAR_STYLE_ID } from './config-editor.cssr'-import modelExtrasStyle, { MODEL_EXTRAS_STYLE_ID } from './model-extras.cssr'+import type { Translate } from './types'+import { Action } from '../../components/action'++export type ModelDraft = Record<string, unknown>++export interface ModelProbeTarget {+ settingsNs: string+ profilePath: readonly string[]+ provider?: string+ baseURL?: string+ api?: string+ apiKey?: string+}-const SEPARATOR: MenuEntry = { id: 'separator', type: 'separator' }+export interface ModelConfigToolbarProps {+ t: Translate+ onOpenConfig?: () => void+ openConfigLabel?: string+ openConfigHint?: string+ disabled?: boolean+}+/**+ * 模型页工具条:只保留「打开配置文件」。+ * 文本编辑器选择器已删除——官方 `dsh-client-ui-open-in-app` 已独占「用哪个应用打开」这件事+ * (自带应用目录与记忆选择,且不对外 provide 客户端服务),本包不再重复实现。+ */export function ModelConfigToolbar({t,- editor,- onEditorChange,onOpenConfig,openConfigLabel,openConfigHint,disabled,}: ModelConfigToolbarProps): ReactElement {- useMountStyle(modelExtrasStyle, MODEL_EXTRAS_STYLE_ID)- useMountStyle(configEditorStyle, MODEL_CONFIG_TOOLBAR_STYLE_ID)- const [menuOpen, setMenuOpen] = useState(false)- const [customOpen, setCustomOpen] = useState(false)- const [loaded, setLoaded] = useState(editor)- const [command, setCommand] = useState('')- const [busy, setBusy] = useState(false)- const [failure, setFailure] = useState<string>()- const current = editor ?? loaded- const locked = disabled === true || busy-- const items: MenuEntry[] = [- { id: 'system', label: t('editorSystem'), icon: <span className="dshp-model-config-toolbar__icon dshp-model-config-toolbar__icon--system" aria-hidden="true" /> },- { id: 'vscode', label: t('editorVSCode'), icon: <span className="dshp-model-config-toolbar__icon dshp-model-config-toolbar__icon--vscode" aria-hidden="true" /> },- { id: 'cursor', label: t('editorCursor'), icon: <span className="dshp-model-config-toolbar__icon dshp-model-config-toolbar__icon--cursor" aria-hidden="true" /> },- SEPARATOR,- { id: 'custom', label: t('editorCustom'), icon: <span className="dshp-model-config-toolbar__icon dshp-model-config-toolbar__icon--custom" aria-hidden="true" /> },- ]-- async function openMenu(): Promise<void> {- if (locked)- return- if (menuOpen) {- setMenuOpen(false)- return- }- if (current !== undefined) {- setMenuOpen(true)- return- }- setBusy(true)- setFailure(undefined)- try {- setLoaded(await loadEditor())- setMenuOpen(true)- }- catch (error) {- setFailure(withDetail(t('editorLoadFailed'), String(error)))- }- finally {- setBusy(false)- }- }-- function closeDialog(): void {- if (busy)- return- setCustomOpen(false)- setFailure(undefined)- }-- async function save(next: NonNullable<typeof current>): Promise<void> {- if (busy)- return- setBusy(true)- setFailure(undefined)- const result = await saveEditor(next)- setBusy(false)- if (result.ok) {- if (editor === undefined)- setLoaded(next)- onEditorChange?.(next)- setCustomOpen(false)- }- else {- setFailure(withDetail(t('editorSaveFailed'), result.error ?? ''))- }- }-- function selectEditor(id: string): void {- if (current === undefined || busy)- return- setMenuOpen(false)- if (id === 'custom') {- setCommand(current.command)- setCustomOpen(true)- return- }- if (id === 'vscode' || id === 'cursor' || id === 'system')- void save({ ...current, editor: id })- }-return (- <div className="dshp-model-extras__row">- <Menu- open={menuOpen}- align="end"- autoFocus- items={items}- selectedId={current?.editor}- onSelect={selectEditor}- onClose={() => setMenuOpen(false)}- anchor={(- <button- type="button"- className="dshp-model-extras__link dshp-model-config-toolbar__trigger"- onClick={() => { void openMenu() }}- disabled={locked}- aria-haspopup="menu"- aria-expanded={menuOpen}- aria-busy={busy}- >- {t('textEditor')}- <ChevronDown aria-hidden="true" />- </button>- )}- />+ <div className="flex items-center flex-wrap gap-[8px] min-w-0">{onOpenConfig === undefined? null: (- <button- type="button"- className="dshp-model-extras__link"- disabled={locked}+ <Action+ variant="link"+ disabled={disabled}title={openConfigHint}onClick={onOpenConfig}>{openConfigLabel ?? t('openConfigFile')}- </button>+ </Action>)}- <Modal- open={customOpen || failure !== undefined}- onClose={closeDialog}- title={customOpen ? t('editorCustom') : t('textEditor')}- closeLabel={t('close')}- description={t('textEditorHint')}- footer={(- <>- <Button variant="outline" disabled={busy} onClick={closeDialog}>{customOpen ? t('cancel') : t('close')}</Button>- {customOpen- ? (- <Button disabled={busy || !command.trim()} onClick={() => { void save({ editor: 'custom', command: command.trim() }) }}>- {t('apply')}- </Button>- )- : null}- </>- )}- >- <div className="dshp-model-extras__dialog-field">- {customOpen- ? (- <label className="dshp-model-extras__dialog-field">- <span className="dshp-model-extras__dialog-label">{t('editorCommand')}</span>- <input- className="dshp-model-extras__input"- value={command}- disabled={busy}- placeholder={t('editorCommandPlaceholder')}- onChange={event => setCommand(event.target.value)}- />- <span className="dshp-model-extras__dialog-hint">{t('editorCommandHint')}</span>- </label>- )- : null}- {failure === undefined ? null : <p className="dshp-model-extras__dialog-error" role="alert">{failure}</p>}- </div>- </Modal></div>)}diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-config-toolbar.types.ts b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-config-toolbar.types.tsdeleted file mode 100644index bd5e4306..00000000--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-config-toolbar.types.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { EditorPreference } from '../../../shared/editor.types'-import type { Translate } from './types'--export type ModelDraft = Record<string, unknown>--export interface ModelProbeTarget {- settingsNs: string- profilePath: readonly string[]- provider?: string- baseURL?: string- api?: string- apiKey?: string-}--export interface ModelConfigToolbarProps {- t: Translate- editor?: EditorPreference- onEditorChange?: (next: EditorPreference) => void- onOpenConfig?: () => void- openConfigLabel?: string- openConfigHint?: string- disabled?: boolean-}diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-extras.cssr.ts b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-extras.cssr.tsdeleted file mode 100644index 40112a1a..00000000--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-extras.cssr.ts+++ /dev/null@@ -1,100 +0,0 @@-import { styles as sharedStyles } from '../../constants/theme'-import { cssr } from '../../utils/cssr'--export const MODEL_EXTRAS_STYLE_ID = 'dsh-tauri-ui-model-extras-styles'--const { c } = cssr-const { primary, secondary, tertiary, error, success, hover, borderL4, layer1, focusRing } = sharedStyles--export default c([- c('.dshp-model-extras__row', {- display: 'flex',- alignItems: 'center',- flexWrap: 'wrap',- gap: '8px',- minWidth: '0',- }),- c('.dshp-model-extras__link', {- boxSizing: 'border-box',- display: 'inline-flex',- alignItems: 'center',- gap: '5px',- height: '28px',- padding: '0 10px',- border: 'none',- borderRadius: '14px',- background: 'transparent',- color: tertiary,- cursor: 'pointer',- font: 'inherit',- fontSize: '12px',- lineHeight: '18px',- whiteSpace: 'nowrap',- }, [- c('&:hover:not(:disabled)', {- background: hover,- color: secondary,- }),- c('&:focus-visible', focusRing),- c('&:disabled', {- cursor: 'not-allowed',- opacity: '0.5',- }),- c('&[aria-expanded=\'true\']', {- color: secondary,- }),- ]),- c('.dshp-model-extras__notice', {- flex: '1 1 100%',- minWidth: '0',- margin: '0',- fontSize: '12px',- lineHeight: '18px',- color: tertiary,- overflowWrap: 'anywhere',- }, [- c('&.dshp-model-extras__notice--failed', { color: error }),- c('&.dshp-model-extras__notice--done', { color: success }),- ]),- c('.dshp-model-extras__dialog-field', {- display: 'flex',- flexDirection: 'column',- gap: '6px',- }),- c('.dshp-model-extras__dialog-label', {- fontSize: '12px',- lineHeight: '18px',- color: secondary,- }),- c('.dshp-model-extras__input', {- boxSizing: 'border-box',- width: '100%',- height: '32px',- padding: '0 10px',- border: `0.5px solid ${borderL4}`,- borderRadius: '8px',- background: layer1,- color: primary,- font: 'inherit',- fontSize: '14px',- lineHeight: '22px',- outline: 'none',- }, [- c('&:focus-visible', focusRing),- c('&:disabled', {- cursor: 'not-allowed',- opacity: '0.5',- }),- ]),- c('.dshp-model-extras__dialog-hint', {- fontSize: '12px',- lineHeight: '18px',- color: tertiary,- }),- c('.dshp-model-extras__dialog-error', {- margin: '0',- fontSize: '13px',- lineHeight: '20px',- color: error,- }),-])diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-extras.test.tsx b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-extras.test.tsxindex 784499cf..07974184 100644--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-extras.test.tsx+++ b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-extras.test.tsx@@ -12,7 +12,8 @@ const mocks = vi.hoisted(() => ({ofetch: vi.fn(),}))-vi.mock('dsh-tauri/client', () => ({+vi.mock('dsh-tauri/client', async () => ({+ ...await import('tailwind-variants'),ofetch: mocks.ofetch,defineLocale: (_namespace: string, dicts: { zh: Record<string, string>, en: Record<string, string> }) => {mocks.dicts = dicts@@ -130,24 +131,18 @@ describe('autoConfigAllButton', () => {const html = renderToStaticMarkup(<AutoConfigAllButton t={t} models={[{ id: 'm' }]} probe={{ settingsNs: 'ns', profilePath: [] }} />,)- expect(html).not.toContain('disabled')+ expect(html).not.toContain('disabled=""')})})describe('modelConfigToolbar', () => {- it('renders the editor trigger and the open-config action', () => {- const html = renderToStaticMarkup(- <ModelConfigToolbar t={t} onOpenConfig={vi.fn()} editor={{ editor: 'system', command: '' }} />,- )- expect(html).toContain('Text editor')+ it('renders the open-config action', () => {+ const html = renderToStaticMarkup(<ModelConfigToolbar t={t} onOpenConfig={vi.fn()} />)expect(html).toContain('Open config file')- expect(html).toContain('dshp-model-config-toolbar__trigger')})it('omits the open-config action when the caller owns it elsewhere', () => {- const html = renderToStaticMarkup(- <ModelConfigToolbar t={t} editor={{ editor: 'vscode', command: '' }} />,- )+ const html = renderToStaticMarkup(<ModelConfigToolbar t={t} />)expect(html).not.toContain('Open config file')})})diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-fetch-config-button.tsx b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-fetch-config-button.tsxindex 27cffd61..a59cd21f 100644--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/model-fetch-config-button.tsx+++ b/packages/dsh-tauri-ui/src/client/ui/model-extras/model-fetch-config-button.tsx@@ -1,8 +1,8 @@import type { ReactElement } from 'react'import type { ModelFetchConfigButtonProps } from './model-fetch-config-button.types'-import { useMountStyle } from '../../hooks/use-mount-style'+import { Action } from '../../components/action'+import { Text } from '../../components/text'import { hasModelConfig } from '../../service/model-config.utils'-import modelExtrasStyle, { MODEL_EXTRAS_STYLE_ID } from './model-extras.cssr'import { useModelConfigFetch } from './use-model-config-fetch'export function ModelFetchConfigButton({@@ -14,25 +14,23 @@ export function ModelFetchConfigButton({disabled,onApply,}: ModelFetchConfigButtonProps): ReactElement | null {- useMountStyle(modelExtrasStyle, MODEL_EXTRAS_STYLE_ID)const { busy, failure, run } = useModelConfigFetch({ t, models, probe, operations, onApply })const row = models.find(model => model.id === modelId)if (row !== undefined && hasModelConfig(row))return nullreturn (- <div className="dshp-model-extras__row">- <button- type="button"- className="dshp-model-extras__link"+ <div className="flex items-center flex-wrap gap-[8px] min-w-0">+ <Action+ variant="link"disabled={disabled === true || busy}title={t('fetchModelConfigHint')}aria-busy={busy}onClick={() => run([modelId])}>{busy ? t('fetchingConfig') : t('fetchModelConfig')}- </button>- {failure === undefined ? null : <p className="dshp-model-extras__notice dshp-model-extras__notice--failed" role="alert">{failure}</p>}+ </Action>+ {failure === undefined ? null : <Text tone="error" className="flex-[1_1_100%] min-w-0 [overflow-wrap:anywhere]" role="alert">{failure}</Text>}</div>)}diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/translate.ts b/packages/dsh-tauri-ui/src/client/ui/model-extras/translate.tsindex 31ebdf31..46fa665e 100644--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/translate.ts+++ b/packages/dsh-tauri-ui/src/client/ui/model-extras/translate.ts@@ -3,17 +3,6 @@ import { locale } from '../../locales'export const MODEL_EXTRAS_KEYS = ['apply',- 'textEditor',- 'textEditorHint',- 'editorSystem',- 'editorVSCode',- 'editorCursor',- 'editorCustom',- 'editorCommand',- 'editorCommandPlaceholder',- 'editorCommandHint',- 'editorLoadFailed',- 'editorSaveFailed','openConfigFile','openConfigFileHint','openConfigFileLanded',diff --git a/packages/dsh-tauri-ui/src/client/ui/model-extras/use-model-config-fetch.ts b/packages/dsh-tauri-ui/src/client/ui/model-extras/use-model-config-fetch.tsindex 2453c802..c288eeab 100644--- a/packages/dsh-tauri-ui/src/client/ui/model-extras/use-model-config-fetch.ts+++ b/packages/dsh-tauri-ui/src/client/ui/model-extras/use-model-config-fetch.ts@@ -1,5 +1,5 @@import type { ModelDiscoveryChannel } from '../../service/model-config'-import type { ModelDraft, ModelProbeTarget } from './model-config-toolbar.types'+import type { ModelDraft, ModelProbeTarget } from './model-config-toolbar'import type { Translate } from './types'import { useCallback, useState } from 'react'import { loadModelCapacities } from '../../service/model-config'diff --git a/packages/dsh-tauri-ui/src/host/service/config-file.test.ts b/packages/dsh-tauri-ui/src/host/service/config-file.test.tsindex e5401f20..7872be00 100644--- a/packages/dsh-tauri-ui/src/host/service/config-file.test.ts+++ b/packages/dsh-tauri-ui/src/host/service/config-file.test.ts@@ -1,28 +1,21 @@-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { openDirectory, writeAtomic } from 'dsh-tauri'+import { openDirectory, openUrl } from 'dsh-tauri'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { configFile } from './config-file'-import { openInEditor } from './config-file.utils'-vi.mock('node:fs/promises', async (importOriginal) => {- const actual = await importOriginal<typeof import('node:fs/promises')>()- return { ...actual, readFile: vi.fn(actual.readFile) }-})vi.mock('dsh-tauri', async (importOriginal) => {const actual = await importOriginal<typeof import('dsh-tauri')>()- return { ...actual, openDirectory: vi.fn(), writeAtomic: vi.fn(actual.writeAtomic) }+ return { ...actual, openDirectory: vi.fn(), openUrl: vi.fn() }})-vi.mock('./config-file.utils', () => ({ openInEditor: vi.fn() }))-describe('config file editor preference', () => {+describe('config file open', () => {let home: stringbeforeEach(async () => {- home = await mkdtemp(join(tmpdir(), 'dsh-editor-'))+ home = await mkdtemp(join(tmpdir(), 'dsh-config-open-'))vi.stubEnv('DSH_HOME', home)- vi.mocked(openInEditor).mockResolvedValue(undefined)})afterEach(async () => {@@ -31,105 +24,29 @@ describe('config file editor preference', () => {await rm(home, { recursive: true, force: true })})- it('keeps the system default for existing users without a preference', async () => {- await writeFile(join(home, 'settings.yaml'), 'models: {}\n')- expect(await configFile.load()).toEqual({ editor: 'system', command: '' })- expect(await configFile.open()).toEqual({ ok: true, path: join(home, 'settings.yaml'), opened: 'file' })- expect(openInEditor).toHaveBeenCalledWith(join(home, 'settings.yaml'), { editor: 'system', command: '' })- })-- it.each([- ['malformed JSON', '{'],- ['invalid shape', 'null'],- ['unknown editor', '{"editor":"unknown","command":""}'],- ['empty custom command', '{"editor":"custom","command":" "}'],- ])('recovers from %s and allows saving a new preference', async (_, content) => {- const path = join(home, 'dsh-tauri-ui', 'editor.json')- await mkdir(join(home, 'dsh-tauri-ui'))- await writeFile(path, content)+ it('opens the settings file with the system default', async () => {await writeFile(join(home, 'settings.yaml'), 'models: {}\n')-- expect(await configFile.load()).toEqual({ editor: 'system', command: '' })expect(await configFile.open()).toEqual({ ok: true, path: join(home, 'settings.yaml'), opened: 'file' })- expect(openInEditor).toHaveBeenCalledWith(join(home, 'settings.yaml'), { editor: 'system', command: '' })- expect(await readFile(path, 'utf8')).toBe(content)-- await configFile.save({ editor: 'vscode', command: '' })- expect(await configFile.load()).toEqual({ editor: 'vscode', command: '' })- })-- it.each(['EACCES', 'EIO'])('reports %s instead of falling back to the system editor', async (code) => {- await writeFile(join(home, 'settings.yaml'), 'models: {}\n')- const error = Object.assign(new Error(code), { code })- vi.mocked(readFile).mockRejectedValueOnce(error)- await expect(configFile.load()).rejects.toBe(error)-- vi.mocked(readFile).mockRejectedValueOnce(error)- expect(await configFile.open()).toEqual({ ok: false, path: join(home, 'settings.yaml'), error: code })- expect(openInEditor).not.toHaveBeenCalled()- expect(openDirectory).not.toHaveBeenCalled()- })-- it('persists a custom editor and uses it on the next open', async () => {- await writeFile(join(home, 'settings.yaml'), 'models: {}\n')- await configFile.save({ editor: 'custom', command: ' /Applications/My Editor.app ' })- const preference = { editor: 'custom', command: '/Applications/My Editor.app' }- expect(JSON.parse(await readFile(join(home, 'dsh-tauri-ui', 'editor.json'), 'utf8'))).toEqual(preference)- expect(await configFile.load()).toEqual(preference)- await configFile.open()- expect(openInEditor).toHaveBeenCalledWith(join(home, 'settings.yaml'), preference)- await configFile.save({ editor: 'system', command: '' })- expect(await configFile.load()).toEqual({ editor: 'system', command: '' })- })-- it('rejects an empty custom editor without replacing the saved preference', async () => {- await configFile.save({ editor: 'vscode', command: '' })- await expect(configFile.save({ editor: 'custom', command: ' ' })).rejects.toThrow('EDITOR_COMMAND_REQUIRED')- expect(await configFile.load()).toEqual({ editor: 'vscode', command: '' })- })-- it('persists and opens with the Cursor preset', async () => {- await writeFile(join(home, 'settings.yaml'), 'models: {}\n')- const preference = { editor: 'cursor', command: '' } as const- await configFile.save(preference)- expect(await configFile.load()).toEqual(preference)- await configFile.open()- expect(openInEditor).toHaveBeenCalledWith(join(home, 'settings.yaml'), preference)- })-- it('reports launcher failure instead of silently opening a different app', async () => {- await writeFile(join(home, 'settings.yaml'), 'models: {}\n')- vi.mocked(openInEditor).mockRejectedValueOnce(new Error('Editor not found'))- expect(await configFile.open()).toEqual({ ok: false, path: join(home, 'settings.yaml'), error: 'Editor not found' })+ expect(openUrl).toHaveBeenCalledWith(join(home, 'settings.yaml'))expect(openDirectory).not.toHaveBeenCalled()})- it('opens and reports the containing directory when settings do not exist', async () => {+ it('opens the containing directory when settings do not exist', async () => {expect(await configFile.open()).toEqual({ ok: true, path: home, opened: 'directory' })expect(openDirectory).toHaveBeenCalledWith(home)- expect(openInEditor).not.toHaveBeenCalled()+ expect(openUrl).not.toHaveBeenCalled()})it('treats a directory named settings.yaml as no settings file and opens the containing directory', async () => {await mkdir(join(home, 'settings.yaml'))-expect(await configFile.open()).toEqual({ ok: true, path: home, opened: 'directory' })expect(openDirectory).toHaveBeenCalledWith(home)- expect(openInEditor).not.toHaveBeenCalled()})- it('surfaces an atomic write failure without replacing the stored preference', async () => {- const path = join(home, 'dsh-tauri-ui', 'editor.json')- await configFile.save({ editor: 'vscode', command: '' })-- const failure = Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' })- vi.mocked(writeAtomic).mockRejectedValueOnce(failure)-- await expect(configFile.save({ editor: 'cursor', command: '' })).rejects.toBe(failure)- expect(writeAtomic).toHaveBeenCalledTimes(2)- const [target, serialized] = vi.mocked(writeAtomic).mock.calls[1]!- expect(target).toBe(path)- expect(JSON.parse(String(serialized))).toEqual({ editor: 'cursor', command: '' })- expect(await configFile.load()).toEqual({ editor: 'vscode', command: '' })+ it('reports launcher failure instead of silently opening a different app', async () => {+ await writeFile(join(home, 'settings.yaml'), 'models: {}\n')+ vi.mocked(openUrl).mockRejectedValueOnce(new Error('No default application'))+ expect(await configFile.open()).toEqual({ ok: false, path: join(home, 'settings.yaml'), error: 'No default application' })+ expect(openDirectory).not.toHaveBeenCalled()})})diff --git a/packages/dsh-tauri-ui/src/host/service/config-file.ts b/packages/dsh-tauri-ui/src/host/service/config-file.tsindex 173ec049..69eb6b8e 100644--- a/packages/dsh-tauri-ui/src/host/service/config-file.ts+++ b/packages/dsh-tauri-ui/src/host/service/config-file.ts@@ -1,44 +1,17 @@-import type { EditorPreference } from '../../shared/editor.types'import type { ConfigOpenResult } from './config-file.types'-import { readFile, stat } from 'node:fs/promises'-import { dirname, join } from 'node:path'-import { defineService, openDirectory, writeAtomic } from 'dsh-tauri'-import { PLUGIN_ID } from '../../shared/constants'-import { parseEditorPreference } from '../../shared/editor'+import { stat } from 'node:fs/promises'+import { dirname } from 'node:path'+import { defineService, openDirectory, openUrl } from 'dsh-tauri'import { resolveSettingsFilePath } from '../utils/paths'-import { openInEditor } from './config-file.utils'+/** 设置文件:存在就用系统默认应用打开,未创建则退到所在目录(编辑器选择交给官方 open-in-app)。 */export const configFile = defineService({- async load(): Promise<EditorPreference> {- let content: string- try {- content = await readFile(preferencePath(), 'utf8')- }- catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT')- return { editor: 'system', command: '' }- throw error- }- try {- return parseEditorPreference(JSON.parse(content))- }- catch {- return { editor: 'system', command: '' }- }- },-- async save(preference: EditorPreference): Promise<EditorPreference> {- const normalized = parseEditorPreference(preference)- await writeAtomic(preferencePath(), JSON.stringify(normalized))- return normalized- },-async open(): Promise<ConfigOpenResult> {const path = resolveSettingsFilePath()try {const servesFile = await isFile(path)if (servesFile)- await openInEditor(path, await configFile.load())+ await openUrl(path)elseawait openDirectory(dirname(path))return { ok: true, path: servesFile ? path : dirname(path), opened: servesFile ? 'file' : 'directory' }@@ -49,10 +22,6 @@ export const configFile = defineService({},})-function preferencePath(): string {- return join(dirname(resolveSettingsFilePath()), PLUGIN_ID, 'editor.json')-}-async function isFile(path: string): Promise<boolean> {try {return (await stat(path)).isFile()diff --git a/packages/dsh-tauri-ui/src/host/service/config-file.utils.test.ts b/packages/dsh-tauri-ui/src/host/service/config-file.utils.test.tsdeleted file mode 100644index 5cceae25..00000000--- a/packages/dsh-tauri-ui/src/host/service/config-file.utils.test.ts+++ /dev/null@@ -1,94 +0,0 @@-import { execFile } from 'node:child_process'-import { existsSync } from 'node:fs'-import { openUrl, spawnDetached } from 'dsh-tauri'-import { beforeEach, describe, expect, it, vi } from 'vitest'-import { openInEditor } from './config-file.utils'--const runtime = vi.hoisted(() => ({ platform: 'darwin', env: {} as NodeJS.ProcessEnv }))-vi.mock('node:process', () => ({ default: runtime }))-vi.mock('node:fs', () => ({ existsSync: vi.fn() }))-vi.mock('node:child_process', () => ({- execFile: vi.fn((_command, _args, _options, callback) => callback(null, '', '')),-}))-vi.mock('dsh-tauri', () => ({ openUrl: vi.fn(), spawnDetached: vi.fn() }))--describe('opening files in an editor', () => {- beforeEach(() => {- vi.clearAllMocks()- runtime.platform = 'darwin'- runtime.env = {}- vi.mocked(existsSync).mockReturnValue(false)- })-- it('uses the existing system association when requested', async () => {- await openInEditor('/tmp/settings.yaml', { editor: 'system', command: '' })- expect(openUrl).toHaveBeenCalledWith('/tmp/settings.yaml')- expect(execFile).not.toHaveBeenCalled()- expect(spawnDetached).not.toHaveBeenCalled()- })-- it('opens VS Code on macOS without depending on the code CLI', async () => {- await openInEditor('/tmp/my config/settings.yaml', { editor: 'vscode', command: '' })- expect(execFile).toHaveBeenCalledWith('/usr/bin/open', ['-a', 'Visual Studio Code', '/tmp/my config/settings.yaml'], { timeout: 10_000 }, expect.any(Function))- })-- it('opens Cursor on macOS without depending on its CLI', async () => {- await openInEditor('/tmp/settings.yaml', { editor: 'cursor', command: '' })- expect(execFile).toHaveBeenCalledWith('/usr/bin/open', ['-a', 'Cursor', '/tmp/settings.yaml'], { timeout: 10_000 }, expect.any(Function))- })-- it('passes custom application and file paths as literal arguments', async () => {- const path = '/tmp/settings $(touch injected).yaml'- await openInEditor(path, { editor: 'custom', command: '/Applications/My Editor.app' })- expect(execFile).toHaveBeenCalledWith('/usr/bin/open', ['-a', '/Applications/My Editor.app', path], { timeout: 10_000 }, expect.any(Function))- })-- it('propagates a failed macOS open command', async () => {- vi.mocked(execFile).mockImplementationOnce((_command: any, _args: any, _options: any, callback: any): any => callback(new Error('Unable to find application')))- await expect(openInEditor('/tmp/settings.yaml', { editor: 'vscode', command: '' })).rejects.toThrow('Unable to find application')- })-- it('finds a Windows user installation without launching a cmd shim', async () => {- runtime.platform = 'win32'- runtime.env = { LOCALAPPDATA: 'C:\\Users\\Test User\\AppData\\Local' }- const exe = 'C:\\Users\\Test User\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe'- vi.mocked(existsSync).mockImplementation(path => path === exe)- await openInEditor('C:\\My Config\\settings.yaml', { editor: 'vscode', command: '' })- expect(spawnDetached).toHaveBeenCalledWith(exe, ['C:\\My Config\\settings.yaml'])- })-- it('finds a portable Windows installation from its bin entry in PATH', async () => {- runtime.platform = 'win32'- runtime.env = { PATH: 'D:\\Tools\\VS Code\\bin' }- vi.mocked(existsSync).mockImplementation(path => path === 'D:\\Tools\\VS Code\\Code.exe')- await openInEditor('C:\\settings.yaml', { editor: 'vscode', command: '' })- expect(spawnDetached).toHaveBeenCalledWith('D:\\Tools\\VS Code\\Code.exe', ['C:\\settings.yaml'])- })-- it('finds a Windows Cursor user installation', async () => {- runtime.platform = 'win32'- runtime.env = { LOCALAPPDATA: 'C:\\Users\\Test User\\AppData\\Local' }- const exe = 'C:\\Users\\Test User\\AppData\\Local\\Programs\\Cursor\\Cursor.exe'- vi.mocked(existsSync).mockImplementation(path => path === exe)- await openInEditor('C:\\My Config\\settings.yaml', { editor: 'cursor', command: '' })- expect(spawnDetached).toHaveBeenCalledWith(exe, ['C:\\My Config\\settings.yaml'])- })-- it('launches the code executable on Linux', async () => {- runtime.platform = 'linux'- await openInEditor('/tmp/settings.yaml', { editor: 'vscode', command: '' })- expect(spawnDetached).toHaveBeenCalledWith('code', ['/tmp/settings.yaml'])- })-- it('launches the cursor executable on Linux', async () => {- runtime.platform = 'linux'- await openInEditor('/tmp/settings.yaml', { editor: 'cursor', command: '' })- expect(spawnDetached).toHaveBeenCalledWith('cursor', ['/tmp/settings.yaml'])- })-- it('launches a custom executable without shell evaluation', async () => {- runtime.platform = 'linux'- await openInEditor('/tmp/settings.yaml', { editor: 'custom', command: '/opt/My Editor/editor' })- expect(spawnDetached).toHaveBeenCalledWith('/opt/My Editor/editor', ['/tmp/settings.yaml'])- })-})diff --git a/packages/dsh-tauri-ui/src/host/service/config-file.utils.ts b/packages/dsh-tauri-ui/src/host/service/config-file.utils.tsdeleted file mode 100644index c420ae0c..00000000--- a/packages/dsh-tauri-ui/src/host/service/config-file.utils.ts+++ /dev/null@@ -1,50 +0,0 @@-import type { EditorPreference } from '../../shared/editor.types'-import { execFile } from 'node:child_process'-import { existsSync } from 'node:fs'-import { homedir } from 'node:os'-import { isAbsolute, join, win32 } from 'node:path'-import process from 'node:process'-import { promisify } from 'node:util'-import { openUrl, spawnDetached } from 'dsh-tauri'--const run = promisify(execFile)--export async function openInEditor(path: string, preference: EditorPreference): Promise<void> {- if (preference.editor === 'system') {- await openUrl(path)- return- }- let command = preference.command- if (preference.editor === 'vscode' || preference.editor === 'cursor') {- if (process.platform === 'darwin')- command = preference.editor === 'vscode' ? 'Visual Studio Code' : 'Cursor'- else if (process.platform === 'win32')- command = resolveWindowsEditor(preference.editor)- else- command = preference.editor === 'vscode' ? 'code' : 'cursor'- }- if (command.startsWith('~/'))- command = join(homedir(), command.slice(2))- if (process.platform === 'darwin' && (command.endsWith('.app') || !isAbsolute(command))) {- await run('/usr/bin/open', ['-a', command, path], { timeout: 10_000 })- return- }- await spawnDetached(command, [path])-}--function resolveWindowsEditor(editor: 'vscode' | 'cursor'): string {- const directoryName = editor === 'vscode' ? 'Microsoft VS Code' : 'Cursor'- const executable = editor === 'vscode' ? 'Code.exe' : 'Cursor.exe'- const candidates: string[] = []- if (process.env.LOCALAPPDATA)- candidates.push(win32.join(process.env.LOCALAPPDATA, 'Programs', directoryName, executable))- for (const root of [process.env.ProgramFiles, process.env['ProgramFiles(x86)']]) {- if (root)- candidates.push(win32.join(root, directoryName, executable))- }- for (const directory of (process.env.PATH ?? '').split(';').filter(Boolean)) {- candidates.push(win32.join(directory, executable))- candidates.push(win32.resolve(directory, '..', executable))- }- return candidates.find(candidate => existsSync(candidate)) ?? executable-}