Skip to content

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

feat(model-config): support configurable text editors

YunYouJun36cc431b13be
diff --git a/packages/dsh-tauri-model-config/README.md b/packages/dsh-tauri-model-config/README.md
index 38f5b5f2..d42fb2d0 100644
--- a/packages/dsh-tauri-model-config/README.md
+++ b/packages/dsh-tauri-model-config/README.md
@@ -1,6 +1,6 @@
# dsh-tauri-model-config
-内置插件:接管 DSH 的「模型」设置页,在官方页面的基础上补齐官方不支持的配置项(上下文、图片输入、思考模式),并让模型上限可以从提供方端点直接读取。
+本仓库维护的内置扩展,并非 DeepSeek 官方插件:接管 DSH 的「模型」设置页,在官方页面的基础上补齐官方不支持的配置项(上下文、图片输入、思考模式),并让模型上限可以从提供方端点直接读取。
## 为什么是 fork
@@ -15,11 +15,13 @@
同步上游时的步骤:以同一 tag 重新取源 → 覆盖 `src/client/models/` 中未被本地改动的文件 → 重放上述改动。
+编辑器选择位于独立的 `src/client/components/config-editor.tsx`,模型页面只负责挂载入口;偏好存储和跨平台启动逻辑在本插件宿主端。当前仅服务模型配置文件,无需拆成独立插件或桌面全局能力。若上游提供统一编辑器接口或出现跨插件复用需求,再评估迁移;插件内隔离仍需配合模型页面 fork 的上游同步维护。
+
## 新增能力
| 位置 | 能力 |
| --- | --- |
-| 面板标题右侧(`.zGbnIq_title`) | **打开配置文件**:用系统默认程序打开 `$DSH_HOME/settings.yaml`;文件尚未创建时改为打开它所在目录 |
+| 面板标题右侧(`.zGbnIq_title`) | **文本编辑器**:下拉菜单默认跟随系统,可选择 VS Code、Cursor 或自定义编辑器;预设点选即保存,自定义路径确认后保存。**打开配置文件**:使用所选编辑器打开 `$DSH_HOME/settings.yaml`;文件尚未创建时改为打开它所在目录 |
| 单个模型行(`.zGbnIq_modelRow`) | **获取配置**:仅在该条目只有 `id`/`name`/`description` 时出现,按 `id` 从提供方端点读取该模型的上下文与输出上限 |
| 模型目录标题(`.zGbnIq_modelCatalogHeading`) | 追加 `flex: 1`(按钮集中到右侧),并在右侧加入 **自动配置所有模型**;pi-ai 提供方与官方 DeepSeek 模型目录都有这个入口 |
| 单个模型高级区(`.zGbnIq_modelAdvanced`) | **图片输入** 开关 → `input` 声明;**思考模式** 开关 → `reasoningEfforts` 声明,打开后可按档位勾选;**关闭 Developer 角色** 开关 → `compat` 声明(仅路由显式声明 `openai-completions` 时出现) |
@@ -28,6 +30,8 @@
高级区首行横跨整个栅格:左半边是两个容量输入(彼此等宽,整组按内容宽度),右半边是三个开关(开关组吃掉剩余宽度)——开关按内容宽度排布、不做拉伸,容器带 4px 左外边距,行内与开关组内的间距都是 6px;档位勾选仍独占下一行。高级区自身去掉上游那 4px 左右内边距,首行因此与上面的模型行同宽、同起止。
+VS Code 和 Cursor 菜单图标随插件内嵌,以 CSS background / mask 显示,无运行时外部请求。图形分别来自 [VS Code 官方品牌资源](https://code.visualstudio.com/brand) 和 [Cursor 官方品牌资源](https://cursor.com/brand)。
+
## 配置从哪里来
三条通道,先直连再回退(前两条与参考实现 `dsh-llm-capabilities` 的顺序一致):
@@ -71,7 +75,8 @@
| --- | --- | --- |
| GET | `/api/desktop/dsh-tauri-model-config/endpoint/models` | 读取提供方端点的 `/models` 清单并归一化容量 |
| GET | `/api/desktop/dsh-tauri-model-config/presets` | 取模型能力表(`force=true` 忽略缓存有效期) |
-| POST | `/api/desktop/dsh-tauri-model-config/config/open` | 用系统默认程序打开模型配置文件 |
+| GET / PUT | `/api/desktop/dsh-tauri-model-config/config/editor` | 读取 / 保存文本编辑器偏好 |
+| POST | `/api/desktop/dsh-tauri-model-config/config/open` | 用所选编辑器打开模型配置文件,未设置时跟随系统 |
已接入 `genapi.config.ts`,客户端 `apis/` 为生成产物。
@@ -116,6 +121,7 @@ compat:
## 已知约束
- 模型配置文件按 `$DSH_HOME`(非空白)→ `~/.dsh` 解析后取 `settings.yaml`,与官方 `resolveDshHome` 及桌面壳一致;如果 profile 的 `cordis.yml` 为 `settings-file` 配了自定义 `path`,这里无法感知。
+- 编辑器设置仅作用于本插件模型页面的“打开配置文件”;偏好保存于 `$DSH_HOME/dsh-tauri-model-config/editor.json`,不修改系统文件关联。自定义编辑器在 macOS 上支持应用名称、`.app` 路径或可执行文件路径;Windows 使用 `.exe` 完整路径;Linux 支持可执行程序名称或路径。无需引号,不支持附加参数。编辑器启动失败会显示错误,不自动切换应用。
- 文件不存在时打开的是它所在的目录,而不是替用户创建一个空文档。
- 图片能力既不在官方发现通道的返回里,也没有跨厂商的端点字段:它来自模型能力表,表里没有的靠家族规则。两者都是社区口径的近似值,用户随时可以在高级区改;单行「获取配置」也不会覆盖手写值。
- 能力表需要一次网络请求(约 2.6 MB 的原始数据集,压成 72 KB 落盘,一天内不再请求)。离线且从未下载过时,只剩家族规则能补图片/思考,容量仍由端点清单提供。
diff --git a/packages/dsh-tauri-model-config/package.json b/packages/dsh-tauri-model-config/package.json
index 6df316a7..af8ec272 100644
--- a/packages/dsh-tauri-model-config/package.json
+++ b/packages/dsh-tauri-model-config/package.json
@@ -69,7 +69,8 @@
},
"dependencies": {
"dsh-tauri": "workspace:*",
- "dsh-tauri-ui": "workspace:*"
+ "dsh-tauri-ui": "workspace:*",
+ "react-if-lite": "catalog:runtime"
},
"devDependencies": {
"@deepseek-ai/cordis": "catalog:dsh",
diff --git a/packages/dsh-tauri-model-config/src/client/apis/index.ts b/packages/dsh-tauri-model-config/src/client/apis/index.ts
index 49346fe8..b3967fea 100644
--- a/packages/dsh-tauri-model-config/src/client/apis/index.ts
+++ b/packages/dsh-tauri-model-config/src/client/apis/index.ts
@@ -10,6 +10,16 @@ import type * as Types from "./index.type";
export const baseURL = "/api/desktop/dsh-tauri-model-config";
+/** @method get */
+export function getConfigEditor(options?: FetchOptions) {
+ return ofetch<Types.EditorPreferenceResponse>("/config/editor", { baseURL, method: "get", ...options });
+}
+
+/** @method put */
+export function putConfigEditor(body: Types.EditorPreferenceBody, options?: FetchOptions) {
+ return ofetch<Types.EditorPreferenceResponse>("/config/editor", { baseURL, method: "put", body, ...options });
+}
+
/** @method post */
export function postConfigOpen(options?: FetchOptions) {
return ofetch<Types.OpenModelsConfigResponse>("/config/open", { baseURL, method: "post", ...options });
diff --git a/packages/dsh-tauri-model-config/src/client/apis/index.type.ts b/packages/dsh-tauri-model-config/src/client/apis/index.type.ts
index 07bdeeb7..2c815750 100644
--- a/packages/dsh-tauri-model-config/src/client/apis/index.type.ts
+++ b/packages/dsh-tauri-model-config/src/client/apis/index.type.ts
@@ -1,3 +1,11 @@
+export type EditorPreferenceResponse = {
+ preference?: EditorPreference;
+ error?: string;
+};
+export type EditorPreference = {
+ editor: "vscode" | "cursor" | "system" | "custom";
+ command: string;
+};
export type OpenModelsConfigResponse = {
ok?: boolean;
path?: string;
@@ -27,6 +35,9 @@ export type PresetsResponse = {
error?: string;
};
+export interface EditorPreferenceBody {
+ preference: EditorPreference;
+}
export interface GetEndpointModelsQuery {
ns?: string;
profilePath?: string;
diff --git a/packages/dsh-tauri-model-config/src/client/components/config-editor.cssr.ts b/packages/dsh-tauri-model-config/src/client/components/config-editor.cssr.ts
new file mode 100644
index 00000000..552a7612
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/client/components/config-editor.cssr.ts
@@ -0,0 +1,28 @@
+import { cssr } from 'dsh-tauri-ui/client'
+
+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-editor__trigger', {
+ gap: '5px',
+ whiteSpace: 'nowrap',
+ }),
+ c('.dshp-model-config-editor__icon', {
+ display: 'inline-block',
+ flex: 'none',
+ width: '16px',
+ height: '16px',
+ }),
+ c('.dshp-model-config-editor__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-editor__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-model-config/src/client/components/config-editor.tsx b/packages/dsh-tauri-model-config/src/client/components/config-editor.tsx
new file mode 100644
index 00000000..cba60926
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/client/components/config-editor.tsx
@@ -0,0 +1,150 @@
+import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives'
+import type { EditorPreference } from '../../shared/editor.types'
+import type { en } from '../models/locales'
+import { Button, IconChevronDownOutline14, Menu, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
+import { useMountStyle } from 'dsh-tauri-ui/client'
+import { useState } from 'react'
+import { If } from 'react-if-lite'
+import { modelStyles as styles } from '../models/styles'
+import { loadEditor, saveEditor } from '../service/editor'
+import { withDetail } from '../service/model-config.utils'
+import { configEditorStyle } from './config-editor.cssr'
+
+export function ConfigEditor({ t }: { t: (key: keyof typeof en) => string }) {
+ useMountStyle(configEditorStyle, 'dshp-model-config-editor')
+ const [menuOpen, setMenuOpen] = useState(false)
+ const [customOpen, setCustomOpen] = useState(false)
+ const [preference, setPreference] = useState<EditorPreference>()
+ const [command, setCommand] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [failure, setFailure] = useState<string>()
+ const items: MenuEntry[] = [
+ { id: 'system', label: t('editorSystem'), icon: <span className="dshp-model-config-editor__icon dshp-model-config-editor__icon--system" aria-hidden="true" /> },
+ { id: 'vscode', label: t('editorVSCode'), icon: <span className="dshp-model-config-editor__icon dshp-model-config-editor__icon--vscode" aria-hidden="true" /> },
+ { id: 'cursor', label: t('editorCursor'), icon: <span className="dshp-model-config-editor__icon dshp-model-config-editor__icon--cursor" aria-hidden="true" /> },
+ { id: 'separator', type: 'separator' },
+ { id: 'custom', label: t('editorCustom'), icon: <span className="dshp-model-config-editor__icon dshp-model-config-editor__icon--custom" aria-hidden="true" /> },
+ ]
+
+ async function openMenu() {
+ if (busy)
+ return
+ if (menuOpen) {
+ setMenuOpen(false)
+ return
+ }
+ setBusy(true)
+ setFailure(undefined)
+ try {
+ setPreference(await loadEditor())
+ setMenuOpen(true)
+ }
+ catch (error) {
+ setFailure(withDetail(t('editorLoadFailed'), String(error)))
+ }
+ finally {
+ setBusy(false)
+ }
+ }
+
+ function closeDialog() {
+ if (busy)
+ return
+ setCustomOpen(false)
+ setFailure(undefined)
+ }
+
+ async function save(next: EditorPreference) {
+ if (busy)
+ return
+ setBusy(true)
+ setFailure(undefined)
+ const result = await saveEditor(next)
+ setBusy(false)
+ if (result.ok) {
+ setPreference(next)
+ setCustomOpen(false)
+ }
+ else {
+ setFailure(withDetail(t('editorSaveFailed'), result.error ?? ''))
+ }
+ }
+
+ function selectEditor(editor: string) {
+ if (!preference || busy)
+ return
+ setMenuOpen(false)
+ if (editor === 'custom') {
+ setCommand(preference.command)
+ setCustomOpen(true)
+ }
+ else if (editor === 'vscode' || editor === 'cursor' || editor === 'system') {
+ void save({ ...preference, editor })
+ }
+ }
+
+ return (
+ <>
+ <Menu
+ open={menuOpen}
+ align="end"
+ autoFocus
+ items={items}
+ selectedId={preference?.editor}
+ onSelect={selectEditor}
+ onClose={() => setMenuOpen(false)}
+ anchor={(
+ <button
+ type="button"
+ className={`${styles.linkButton} dshp-model-config-editor__trigger`}
+ onClick={() => { void openMenu() }}
+ disabled={busy}
+ aria-haspopup="menu"
+ aria-expanded={menuOpen}
+ aria-busy={busy}
+ >
+ {t('textEditor')}
+ <IconChevronDownOutline14 aria-hidden="true" />
+ </button>
+ )}
+ />
+ <Modal
+ open={customOpen || failure !== undefined}
+ onClose={closeDialog}
+ title={customOpen ? t('editorCustom') : t('textEditor')}
+ closeLabel={t('close')}
+ description={t('textEditorHint')}
+ className={styles.fetchDialog}
+ footer={(
+ <>
+ <Button variant="outline" disabled={busy} onClick={closeDialog}>{customOpen ? t('cancel') : t('close')}</Button>
+ <If cond={customOpen}>
+ <Button disabled={busy || !command.trim()} onClick={() => { void save({ editor: 'custom', command: command.trim() }) }}>
+ {t('apply')}
+ </Button>
+ </If>
+ </>
+ )}
+ >
+ <div className={styles.editor}>
+ <If cond={customOpen}>
+ <label className={styles.field}>
+ <span className={styles.fieldLabel}>{t('editorCommand')}</span>
+ <input
+ className={styles.input}
+ value={command}
+ disabled={busy}
+ placeholder={t('editorCommandPlaceholder')}
+ onChange={event => setCommand(event.target.value)}
+ />
+ <span className={styles.advancedHint}>{t('editorCommandHint')}</span>
+ </label>
+ </If>
+ <If cond={failure !== undefined}>
+ <p className={styles.error} role="alert">{failure}</p>
+ </If>
+ </div>
+ </Modal>
+ </>
+ )
+}
diff --git a/packages/dsh-tauri-model-config/src/client/models/ModelsSection.tsx b/packages/dsh-tauri-model-config/src/client/models/ModelsSection.tsx
index 1d2c1145..012f87ac 100644
--- a/packages/dsh-tauri-model-config/src/client/models/ModelsSection.tsx
+++ b/packages/dsh-tauri-model-config/src/client/models/ModelsSection.tsx
@@ -10,6 +10,7 @@ import type {} from './slot-contract.ts'
import type { ModelsSettingsStore, ProviderRow } from './store.ts'
import { Button, IconPlusOutline16, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
import { useEffect, useState } from 'react'
+import { ConfigEditor } from '../components/config-editor'
import { withDetail, withPath } from '../service/model-config.utils.ts'
import { ensurePresets } from '../service/presets.ts'
import { CustomProviderCard } from './CustomProviderCard.tsx'
@@ -262,14 +263,17 @@ function Loaded({ injected, renderSlot }: { injected: ModelsSectionFace, renderS
<div className={styles.section}>
<div className={styles.titleRow}>
<h2 className={styles.title}>{t('title')}</h2>
- <button
- type="button"
- className={styles.linkButton}
- title={t('openConfigFileHint')}
- onClick={openConfigFile}
- >
- {t('openConfigFile')}
- </button>
+ <div className={styles.rowActions}>
+ <ConfigEditor t={t} />
+ <button
+ type="button"
+ className={styles.linkButton}
+ title={t('openConfigFileHint')}
+ onClick={openConfigFile}
+ >
+ {t('openConfigFile')}
+ </button>
+ </div>
</div>
<p className={styles.intro}>{t('intro')}</p>
{configOpen === undefined
diff --git a/packages/dsh-tauri-model-config/src/client/models/locales.ts b/packages/dsh-tauri-model-config/src/client/models/locales.ts
index 25430a22..73831e11 100644
--- a/packages/dsh-tauri-model-config/src/client/models/locales.ts
+++ b/packages/dsh-tauri-model-config/src/client/models/locales.ts
@@ -103,7 +103,18 @@ export const en = {
openConfigFileHint: 'Open the settings file that holds every model definition',
openConfigFileLanded: 'Opened {path}',
openConfigFileDirectory: 'The config file does not exist yet; opened {path} instead',
- openConfigFileFailed: 'Could not open the config file: {detail}',
+ openConfigFileFailed: 'Could not open the config file. Check that your editor is installed, or change it in Text editor: {detail}',
+ textEditor: 'Text editor',
+ textEditorHint: 'This preference applies only to opening config files in the Models page.',
+ editorVSCode: 'VS Code',
+ editorCursor: 'Cursor',
+ editorSystem: 'System default (recommended)',
+ editorCustom: 'Custom editor',
+ editorCommand: 'Application name or executable path',
+ editorCommandPlaceholder: 'App name or executable path',
+ editorCommandHint: 'On macOS, enter an app name or .app path. On Windows, use the full .exe path. On Linux, use an executable name or path. Do not add quotes or arguments.',
+ editorLoadFailed: 'Could not load the editor preference: {detail}',
+ editorSaveFailed: 'Could not save the editor preference: {detail}',
imageInput: 'Image input',
imageInputHint: 'Declare whether this model accepts image content',
thinkingMode: 'Thinking mode',
@@ -229,7 +240,18 @@ export const zh: { [Key in keyof typeof en]: string } = {
openConfigFileHint: '打开承载全部模型定义的设置文件',
openConfigFileLanded: '已打开 {path}',
openConfigFileDirectory: '配置文件尚未创建,已改为打开 {path}',
- openConfigFileFailed: '无法打开配置文件:{detail}',
+ openConfigFileFailed: '无法打开配置文件,请确认编辑器已安装,或在“文本编辑器”中更换:{detail}',
+ textEditor: '文本编辑器',
+ textEditorHint: '此设置仅用于模型页面的“打开配置文件”。',
+ editorVSCode: 'VS Code',
+ editorCursor: 'Cursor',
+ editorSystem: '系统默认(推荐)',
+ editorCustom: '自定义编辑器',
+ editorCommand: '应用名称或可执行文件路径',
+ editorCommandPlaceholder: '应用名称、.app 路径或可执行文件路径',
+ editorCommandHint: 'macOS 可填写应用名称或 .app 路径;Windows 请填写 .exe 完整路径;Linux 可填写程序名称或路径。无需引号,请勿附加启动参数。',
+ editorLoadFailed: '无法读取编辑器设置:{detail}',
+ editorSaveFailed: '无法保存编辑器设置:{detail}',
imageInput: '图片输入',
imageInputHint: '声明该模型是否接受图片内容',
thinkingMode: '思考模式',
diff --git a/packages/dsh-tauri-model-config/src/client/service/editor.ts b/packages/dsh-tauri-model-config/src/client/service/editor.ts
new file mode 100644
index 00000000..19eb0a9c
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/client/service/editor.ts
@@ -0,0 +1,23 @@
+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-model-config/src/client/service/model-config.ts b/packages/dsh-tauri-model-config/src/client/service/model-config.ts
index 9c921df3..1336532a 100644
--- a/packages/dsh-tauri-model-config/src/client/service/model-config.ts
+++ b/packages/dsh-tauri-model-config/src/client/service/model-config.ts
@@ -71,10 +71,9 @@ export async function loadModelCapacities(
}
}
-/** 让宿主用系统默认程序打开 `$DSH_HOME/settings.yaml`(模型配置所在的设置文档)。 */
export async function openConfigFile(): Promise<ConfigFileOpen> {
try {
- const response = await postConfigOpen()
+ const response = await postConfigOpen({ ignoreResponseError: true })
if (response.error !== undefined)
return { ok: false, error: response.error }
return { ok: true, path: response.path ?? '', opened: response.opened ?? 'file' }
diff --git a/packages/dsh-tauri-model-config/src/host/routes/config/editor/get.ts b/packages/dsh-tauri-model-config/src/host/routes/config/editor/get.ts
new file mode 100644
index 00000000..38e4745d
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/host/routes/config/editor/get.ts
@@ -0,0 +1,14 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { EditorPreferenceResponse } from '../../index.types'
+import { defineEventHandler } from 'dsh-tauri'
+import { configFile } from '../../../service/config-file'
+
+export default defineEventHandler<EventHandlerRequest, Promise<EditorPreferenceResponse>>(async (event) => {
+ try {
+ return { preference: await configFile.load() }
+ }
+ catch (error) {
+ event.res.status = 500
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+})
diff --git a/packages/dsh-tauri-model-config/src/host/routes/config/editor/put.ts b/packages/dsh-tauri-model-config/src/host/routes/config/editor/put.ts
new file mode 100644
index 00000000..a8a579af
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/host/routes/config/editor/put.ts
@@ -0,0 +1,25 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { EditorPreference } from '../../../../shared/editor.types'
+import type { EditorPreferenceBody, EditorPreferenceResponse } from '../../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { parseEditorPreference } from '../../../../shared/editor'
+import { configFile } from '../../../service/config-file'
+
+export default defineEventHandler<EventHandlerRequest, Promise<EditorPreferenceResponse>>(async (event) => {
+ let preference: EditorPreference
+ try {
+ const body = await readBody<EditorPreferenceBody>(event, { type: 'json' })
+ preference = parseEditorPreference(body?.preference)
+ }
+ catch (error) {
+ event.res.status = 400
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+ try {
+ return { preference: await configFile.save(preference) }
+ }
+ catch (error) {
+ event.res.status = 500
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+})
diff --git a/packages/dsh-tauri-model-config/src/host/routes/index.ts b/packages/dsh-tauri-model-config/src/host/routes/index.ts
index 2d1a5741..f1bb8215 100644
--- a/packages/dsh-tauri-model-config/src/host/routes/index.ts
+++ b/packages/dsh-tauri-model-config/src/host/routes/index.ts
@@ -1,9 +1,13 @@
import { defineRoutes } from 'dsh-tauri'
+import getEditor from './config/editor/get'
+import putEditor from './config/editor/put'
import openConfig from './config/open/post'
import endpointModels from './endpoint/models/get'
import presets from './presets/get'
export const routes = defineRoutes((disposer) => {
+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/config/editor' }, getEditor)
+ disposer.put({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/config/editor' }, putEditor)
disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/endpoint/models' }, endpointModels)
disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/presets' }, presets)
disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-model-config/config/open' }, openConfig)
diff --git a/packages/dsh-tauri-model-config/src/host/routes/index.types.ts b/packages/dsh-tauri-model-config/src/host/routes/index.types.ts
index 1fee6dfc..684db961 100644
--- a/packages/dsh-tauri-model-config/src/host/routes/index.types.ts
+++ b/packages/dsh-tauri-model-config/src/host/routes/index.types.ts
@@ -1,3 +1,14 @@
+import type { EditorPreference } from '../../shared/editor.types'
+
+export interface EditorPreferenceBody {
+ preference: EditorPreference
+}
+
+export interface EditorPreferenceResponse {
+ preference?: EditorPreference
+ error?: string
+}
+
export type HostContext = any
/** 一条归一化后的端点模型条目;缺席字段表示端点没有披露。 */
diff --git a/packages/dsh-tauri-model-config/src/host/service/config-file.test.ts b/packages/dsh-tauri-model-config/src/host/service/config-file.test.ts
new file mode 100644
index 00000000..fd85ee96
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/host/service/config-file.test.ts
@@ -0,0 +1,76 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { openDirectory } 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('dsh-tauri', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('dsh-tauri')>()
+ return { ...actual, openDirectory: vi.fn() }
+})
+vi.mock('./config-file.utils', () => ({ openInEditor: vi.fn() }))
+
+describe('config file editor preference', () => {
+ let home: string
+
+ beforeEach(async () => {
+ home = await mkdtemp(join(tmpdir(), 'dsh-editor-'))
+ vi.stubEnv('DSH_HOME', home)
+ vi.mocked(openInEditor).mockResolvedValue(undefined)
+ })
+
+ afterEach(async () => {
+ vi.unstubAllEnvs()
+ vi.clearAllMocks()
+ 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('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-model-config', '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(openDirectory).not.toHaveBeenCalled()
+ })
+
+ it('opens and reports 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()
+ })
+})
diff --git a/packages/dsh-tauri-model-config/src/host/service/config-file.ts b/packages/dsh-tauri-model-config/src/host/service/config-file.ts
index e8c7c0bf..971d6243 100644
--- a/packages/dsh-tauri-model-config/src/host/service/config-file.ts
+++ b/packages/dsh-tauri-model-config/src/host/service/config-file.ts
@@ -1,46 +1,58 @@
-import { statSync } from 'node:fs'
-import { dirname } from 'node:path'
-import { defineService, openDirectory, openUrl } from 'dsh-tauri'
+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 { resolveSettingsFilePath } from '../utils/paths'
-
-export type ConfigOpenResult
- = | { ok: true, path: string, opened: 'file' | 'directory' }
- | { ok: false, path: string, error: string }
-
-function isFile(path: string): boolean {
- try {
- return statSync(path).isFile()
- }
- catch {
- return false
- }
-}
+import { openInEditor } from './config-file.utils'
export const configFile = defineService({
- /** 模型配置所在的 DSH 设置文档路径(`$DSH_HOME/settings.yaml`)。 */
- resolvePath(): string {
- return resolveSettingsFilePath()
+ async load(): Promise<EditorPreference> {
+ try {
+ return parseEditorPreference(JSON.parse(await readFile(preferencePath(), 'utf8')))
+ }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ return { editor: 'system', command: '' }
+ throw error
+ }
+ },
+
+ async save(preference: EditorPreference): Promise<EditorPreference> {
+ const normalized = parseEditorPreference(preference)
+ await writeAtomic(preferencePath(), JSON.stringify(normalized))
+ return normalized
},
- /**
- * 用系统默认程序打开模型配置文件。
- *
- * 文档尚未落盘时退而打开它所在的目录:`settings.yaml` 只在第一次写入时创建,
- * 空手打开一个不存在的路径在任何平台上都只会静默失败。
- * @returns 实际打开的路径与目标类型,或宿主侧自己的失败文案。
- */
async open(): Promise<ConfigOpenResult> {
const path = resolveSettingsFilePath()
try {
- const servesFile = isFile(path)
+ const servesFile = await isFile(path)
if (servesFile)
- await openUrl(path)
+ await openInEditor(path, await configFile.load())
else
await openDirectory(dirname(path))
- return { ok: true, path, opened: servesFile ? 'file' : 'directory' }
+ return { ok: true, path: servesFile ? path : dirname(path), opened: servesFile ? 'file' : 'directory' }
}
catch (error) {
return { ok: false, path, error: error instanceof Error ? error.message : String(error) }
}
},
})
+
+function preferencePath(): string {
+ return join(dirname(resolveSettingsFilePath()), PLUGIN_ID, 'editor.json')
+}
+
+async function isFile(path: string): Promise<boolean> {
+ try {
+ return (await stat(path)).isFile()
+ }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ return false
+ throw error
+ }
+}
diff --git a/packages/dsh-tauri-model-config/src/host/service/config-file.types.ts b/packages/dsh-tauri-model-config/src/host/service/config-file.types.ts
new file mode 100644
index 00000000..dcea8d97
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/host/service/config-file.types.ts
@@ -0,0 +1,3 @@
+export type ConfigOpenResult
+ = | { ok: true, path: string, opened: 'file' | 'directory' }
+ | { ok: false, path: string, error: string }
diff --git a/packages/dsh-tauri-model-config/src/host/service/config-file.utils.test.ts b/packages/dsh-tauri-model-config/src/host/service/config-file.utils.test.ts
new file mode 100644
index 00000000..5cceae25
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/host/service/config-file.utils.test.ts
@@ -0,0 +1,94 @@
+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-model-config/src/host/service/config-file.utils.ts b/packages/dsh-tauri-model-config/src/host/service/config-file.utils.ts
new file mode 100644
index 00000000..c420ae0c
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/host/service/config-file.utils.ts
@@ -0,0 +1,50 @@
+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
+}
diff --git a/packages/dsh-tauri-model-config/src/shared/editor.ts b/packages/dsh-tauri-model-config/src/shared/editor.ts
new file mode 100644
index 00000000..7610ceb1
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/shared/editor.ts
@@ -0,0 +1,14 @@
+import type { EditorPreference } from './editor.types'
+
+export function parseEditorPreference(value: unknown): EditorPreference {
+ if (typeof value !== 'object' || value === null)
+ throw new Error('EDITOR_INVALID')
+ const { editor, command } = value as Partial<EditorPreference>
+ if (editor !== 'vscode' && editor !== 'cursor' && editor !== 'system' && editor !== 'custom')
+ throw new Error('EDITOR_INVALID')
+ if (typeof command !== 'string' || /[\r\n\0]/.test(command))
+ throw new Error('EDITOR_INVALID')
+ if (editor === 'custom' && !command.trim())
+ throw new Error('EDITOR_COMMAND_REQUIRED')
+ return { editor, command: command.trim() }
+}
diff --git a/packages/dsh-tauri-model-config/src/shared/editor.types.ts b/packages/dsh-tauri-model-config/src/shared/editor.types.ts
new file mode 100644
index 00000000..4e44380f
--- /dev/null
+++ b/packages/dsh-tauri-model-config/src/shared/editor.types.ts
@@ -0,0 +1,4 @@
+export interface EditorPreference {
+ editor: 'vscode' | 'cursor' | 'system' | 'custom'
+ command: string
+}
diff --git a/packages/dsh-tauri-model-config/tsdown.config.ts b/packages/dsh-tauri-model-config/tsdown.config.ts
index 3efc8343..b889e553 100644
--- a/packages/dsh-tauri-model-config/tsdown.config.ts
+++ b/packages/dsh-tauri-model-config/tsdown.config.ts
@@ -3,5 +3,6 @@ import { defineDshConfig } from '../dsh-tauri-tsdown/src/index.ts'
export default defineDshConfig({
client: {
dts: true,
+ noExternal: ['react-if-lite'],
},
})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6c93b439..8818580e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -662,6 +662,9 @@ importers:
dsh-tauri-ui:
specifier: workspace:*
version: link:../dsh-tauri-ui
+ react-if-lite:
+ specifier: catalog:runtime
+ version: 0.1.0([email protected])
devDependencies:
'@deepseek-ai/cordis':
specifier: catalog:dsh