DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(pet): external transparent pet window bridged via tauri invoke (#308)
hairyf6a13a7007c47
diff --git a/packages/dsh-tauri-bundle/package.json b/packages/dsh-tauri-bundle/package.jsonindex 70d2c472..ac12794e 100644--- a/packages/dsh-tauri-bundle/package.json+++ b/packages/dsh-tauri-bundle/package.json@@ -7,9 +7,10 @@"dsh-tauri-panel": "workspace:*","dsh-tauri-panel-extension": "workspace:*","dsh-tauri-panel-placeholder": "workspace:*",+ "dsh-tauri-pet": "workspace:*","dsh-tauri-rightclick": "workspace:*","dsh-tauri-session": "workspace:*","dsh-tauri-ui": "workspace:*","dsh-tauri-worktree": "workspace:*"}-}+}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/README.md b/packages/dsh-tauri-pet/README.mdnew file mode 100644index 00000000..b0133dce--- /dev/null+++ b/packages/dsh-tauri-pet/README.md@@ -0,0 +1,36 @@+# dsh-tauri-pet++DeepSeek Harness 桌宠插件:在 dsh 界面右下角提供一个自包含的桌宠浮控件,+开关外置透明桌宠窗口、显示/隐藏窗口、从候选中选择桌宠(Codex / Deepseek)。++桌宠窗口由桌面端(`src-tauri`)经 `pet.html` 渲染为一个**独立透明、置顶、无边框、+跳过任务栏**的 Webview(label `pet`),悬于普通窗口之上。本插件的所有命令都经+`dsh-tauri` 的 **invoke 桥**调用:iframe 内的 dsh 界面把 command 以 postMessage+上报到主 webview 监听器,由宿主调用 `@tauri-apps/api/core` 的 `invoke` 并把结果+回传。++## 能力++- **开关控制**:一键启用/停用桌宠(`set_pet_enabled`,同步外置窗口显示)。+- **设置新增选项**:显示/隐藏宠物窗口(`show_pet` / `hide_pet`)、从内置候选+ 选择桌宠(`set_active_pet`,可扩展 `.zip` 导入)。+- **设置页面**:展开的卡片即为「宠物」设置小页(右下角胶囊按钮 → 展开面板)。++## 桥协议++| command | 方向 | 说明 |+| --- | --- | --- |+| `get_pet_status` | r | 查询 enabled + active_pet |+| `set_pet_enabled` | rw | 启用/停用 |+| `set_active_pet` | rw | 选择桌宠 |+| `show_pet` / `hide_pet` | rw | 显示/隐藏窗口 |++客户端侧桥实现见 `packages/dsh-tauri/src/client/service/invoke.ts`(+`invokeBridgedTauri`);宿主监听器见 `src/hooks/use-iframe-invoke.ts`。++## 构建++```sh+pnpm --filter dsh-tauri-pet typecheck+pnpm --filter dsh-tauri-pet build+```\ No newline at end of filediff --git a/packages/dsh-tauri-pet/cordis.patch.yml b/packages/dsh-tauri-pet/cordis.patch.ymlnew file mode 100644index 00000000..7fb0cff9--- /dev/null+++ b/packages/dsh-tauri-pet/cordis.patch.yml@@ -0,0 +1,3 @@+- insert:+ - id: dsh-tauri-pet+ name: dsh-tauri-pet\ No newline at end of filediff --git a/packages/dsh-tauri-pet/package.json b/packages/dsh-tauri-pet/package.jsonnew file mode 100644index 00000000..d0242456--- /dev/null+++ b/packages/dsh-tauri-pet/package.json@@ -0,0 +1,73 @@+{+ "name": "dsh-tauri-pet",+ "type": "module",+ "version": "0.1.0",+ "description": "Desktop pet for DeepSeek Harness — toggle, pet selection and a transparent always-on-top window bridged through Tauri invoke.",+ "author": "Hairyf <[email protected]>",+ "license": "MIT",+ "homepage": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins#readme",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/dsh-tauri-desk/dsh-tauri-plugins.git"+ },+ "bugs": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/issues",+ "keywords": [+ "dsh",+ "plugin",+ "dsh-plugin",+ "pet",+ "tauri",+ "desktop",+ "deepseek-harness"+ ],+ "sideEffects": false,+ "exports": {+ ".": "./dist/index.js",+ "./client": "./dist/client.cjs",+ "./package.json": "./package.json"+ },+ "main": "./dist/index.js",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "files": [+ "README.md",+ "cordis.patch.yml",+ "dist"+ ],+ "dsh": {+ "client": {+ "inject": [+ "@deepseek-ai/dsh-client-ui-layout",+ "dsh-tauri"+ ],+ "external": [+ "dsh-tauri/client"+ ],+ "platform": "web"+ },+ "bundle": {+ "patch": "./cordis.patch.yml"+ }+ },+ "scripts": {+ "build": "tsdown",+ "dev": "tsdown --watch",+ "prepublishOnly": "nr build",+ "start": "tsx src/index.ts",+ "typecheck": "tsc"+ },+ "dependencies": {+ "dsh-tauri": "workspace:*"+ },+ "devDependencies": {+ "@deepseek-ai/dsh-client-store": "catalog:dsh",+ "@deepseek-ai/dsh-client-ui-layout": "catalog:dsh",+ "@deepseek-ai/dsh-client-ui-renderer": "catalog:dsh",+ "@deepseek-ai/dsh-client-ui-slots": "catalog:dsh",+ "@deepseek-ai/cordis": "catalog:dsh",+ "css-render": "catalog:ui",+ "dsh-tauri-tsdown": "workspace:*",+ "react": "catalog:runtime",+ "tsdown": "catalog:cli"+ }+}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/src/client/components/pet-control.tsx b/packages/dsh-tauri-pet/src/client/components/pet-control.tsxnew file mode 100644index 00000000..c3ebe4c8--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/components/pet-control.tsx@@ -0,0 +1,142 @@+/**+ * components/pet-control.tsx — 桌宠浮控件(注册进 shell.overlay 槽)。+ *+ * 单一自包含浮层(右下角胶囊按钮 + 展开的设置卡片),承担三项能力:+ * - 开关控制:一键启用/停用桌宠(set_pet_enabled,同步外置窗口);+ * - 设置新增选项:显示/隐藏宠物窗口(show_pet/hide_pet),并从内置候选+ * 选择桌宠(set_active_pet,可扩展 .zip 导入);+ * - 设置页面:展开的面板即为「宠物」设置小页。+ */+import { useEffect, useState } from 'react'+import type { CSSProperties, ReactNode } from 'react'+import type { PetStatus } from '../types'+import { DEFAULT_PETS } from '../constants'+import { text } from '../locales'+import { fetchPetStatus, hidePet, setActivePet, setPetEnabled, showPet } from '../service/pet'++/** 供应商 id(组件身份,不消费 bounds;注册站点类型由 slots 体系约束)。 */+type PetControlProps = Record<never, never>++export function PetControl(_props: PetControlProps) {+ const [status, setStatus] = useState<PetStatus | null>(null)+ const [open, setOpen] = useState(false)+ const [busy, setBusy] = useState(false)++ useEffect(() => {+ let cancelled = false+ void fetchPetStatus()+ .then((value) => {+ if (!cancelled)+ setStatus(value)+ })+ .catch((error) => {+ console.error('[dsh-tauri-pet] fetchPetStatus failed:', error)+ })+ return () => {+ cancelled = true+ }+ }, [])++ async function toggleEnabled() {+ if (busy || !status)+ return+ setBusy(true)+ try {+ const next = await setPetEnabled(!status.enabled)+ setStatus(next)+ }+ catch (error) {+ console.error('[dsh-tauri-pet] setPetEnabled failed:', error)+ }+ finally {+ setBusy(false)+ }+ }++ async function choose(id: string) {+ if (busy || !status || id === status.active_pet)+ return+ setBusy(true)+ try {+ const next = await setActivePet(id)+ setStatus(next)+ }+ catch (error) {+ console.error('[dsh-tauri-pet] setActivePet failed:', error)+ }+ finally {+ setBusy(false)+ }+ }++ async function show() {+ try {+ await showPet()+ }+ catch (error) {+ console.error('[dsh-tauri-pet] showPet failed:', error)+ }+ }++ async function hide() {+ try {+ await hidePet()+ }+ catch (error) {+ console.error('[dsh-tauri-pet] hidePet failed:', error)+ }+ }++ const enabled = Boolean(status?.enabled)++ return (+ <div className="dshpet-wrap">+ <IfPop open={open}>+ <div className="dshpet-pop" role="dialog" aria-label={text('selectPet')}>+ <div className="dshpet-row">+ <span>{text(enabled ? 'enabled' : 'disabled')}</span>+ <button className="dshpet-petBtn" type="button" disabled={busy} onClick={toggleEnabled}>+ {enabled ? text('disable') : text('enable')}+ </button>+ </div>+ <div className="dshpet-row">+ <span>{text('selectPet')}</span>+ <span className="dshpet-statusDot" style={dotStyle(enabled)} />+ </div>+ <div className="dshpet-row">+ {DEFAULT_PETS.map(pet => (+ <button+ key={pet.id}+ type="button"+ className={`dshpet-petBtn${status?.active_pet === pet.id ? ' dshpet-petBtnActive' : ''}`}+ onClick={() => choose(pet.id)}+ >+ {pet.id === 'codex' ? text('chooseCodex') : pet.label}+ </button>+ ))}+ </div>+ <div className="dshpet-row">+ <button className="dshpet-petBtn" type="button" onClick={show}>{text('show')}</button>+ <button className="dshpet-petBtn" type="button" onClick={hide}>{text('hide')}</button>+ </div>+ </div>+ </IfPop>++ <button className="dshpet-pill" type="button" onClick={() => setOpen(v => !v)}>+ <span className="dshpet-statusDot" style={dotStyle(enabled)} />+ <span>{text('name')} · {enabled ? text('enabled') : text('disabled')}</span>+ </button>+ </div>+ )+}++function dotStyle(enabled: boolean): CSSProperties {+ return { background: enabled ? '#3ddc84' : '#7a7f99' }+}++/** 极简条件渲染(避免引入 react-if-lite:无 children 声明、纯自包含)。 */+function IfPop(props: { open: boolean, children: ReactNode }) {+ if (!props.open)+ return null+ return <>{props.children}</>+}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/src/client/constants.ts b/packages/dsh-tauri-pet/src/client/constants.tsnew file mode 100644index 00000000..c2171a7d--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/constants.ts@@ -0,0 +1,36 @@+/**+ * constants.ts — dsh-tauri-pet 稳定标识:插件名、shell.overlay 控制组件 id、+ * locale 命名空间、与桌面端 invoke 桥对齐的 command 名。+ */++/** 插件名(npm 包名,宿主错误注册表与列表主键)。 */+export const PET_CLIENT_PLUGIN = 'dsh-tauri-pet'++/** 面板控件注册进 `shell.overlay`(list/root 槽,第三方通用浮层)的组件 id。 */+export const PET_CONTROL_SLOT_ID = 'dsh-tauri-pet-control'++/** 样式 effect id(css-render 卸载句柄)。 */+export const PET_STYLES_EFFECT = 'dsh-tauri-pet: styles'+/** 控件注册 effect id。 */+export const PET_CONTROL_EFFECT = 'dsh-tauri-pet: shell.overlay control'++/** 本插件文案命名空间(与 locale 注册键一致)。 */+export const PET_CLIENT_NS = 'dsh-tauri-pet'++// ── 桌面端 Tauri command(经 dsh-tauri invoke 桥调用)─────────────+/** 查询桌宠状态(enabled + active_pet)。 */+export const CMD_GET_PET_STATUS = 'get_pet_status'+/** 启用/停用桌宠。 */+export const CMD_SET_PET_ENABLED = 'set_pet_enabled'+/** 选择桌宠。 */+export const CMD_SET_ACTIVE_PET = 'set_active_pet'+/** 显示桌宠窗口(需已启用)。 */+export const CMD_SHOW_PET = 'show_pet'+/** 隐藏桌宠窗口(不改 enabled)。 */+export const CMD_HIDE_PET = 'hide_pet'++/** 内置可选桌宠列表(可导入 .zip 扩展)。 */+export const DEFAULT_PETS = [+ { id: 'codex', label: 'Codex' },+ { id: 'dsh', label: 'Deepseek' },+] as const\ No newline at end of filediff --git a/packages/dsh-tauri-pet/src/client/index.ts b/packages/dsh-tauri-pet/src/client/index.tsnew file mode 100644index 00000000..2600ecb1--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/index.ts@@ -0,0 +1,34 @@+/**+ * client/index.ts — dsh-tauri-pet 客户端插件体(browser half):桌宠浮控件。+ *+ * 能力(slot-shadow,零结构补丁,零新增运行时依赖):+ * 注册进 layout 声明的 `shell.overlay`(list/root 槽,第三方通用浮层)——+ * 右下角胶囊开关键 + 展开的「宠物」设置卡片:启用/停用、显示/隐藏、选择+ * 桌宠(Codex/Deepseek),全部经 dsh-tauri invoke 桥调用桌面端 Tauri 命令+ * (get_pet_status/set_pet_enabled/set_active_pet/show_pet/hide_pet)。+ *+ * 依赖:slots(注册点位)、locale(双语文案)。invoke 桥来自 dsh-tauri/client。+ */+import type { ClientContext } from 'dsh-tauri/client'+import { PET_CLIENT_PLUGIN } from './constants'+import { installLocale } from './locales'+import { mountPetStyles } from './styles'+import { installPetControl } from './register/control'++/** 插件显示名(诊断元数据)。 */+export const name = PET_CLIENT_PLUGIN++/** 需要的客户端服务:slots(注册 shell.overlay 浮层)、locale(双语文案)。 */+export const inject = ['slots', 'locale']++/**+ * 插件体:安装文案、样式,并注册桌宠浮控件到 shell.overlay。+ * @param ctx - 客户端根上下文(须已注入 slots/locale)。+ */+export function apply(ctx: ClientContext): void {+ ctx.effect(() => mountPetStyles(), 'dsh-tauri-pet: styles')++ installLocale(ctx)++ installPetControl(ctx)+}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/src/client/locales/index.ts b/packages/dsh-tauri-pet/src/client/locales/index.tsnew file mode 100644index 00000000..3f9ab17d--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/locales/index.ts@@ -0,0 +1,78 @@+/**+ * locales/index.ts — 本插件自有文案(桌宠开关、选择宠物、提示)。+ * 走 locale 服务的非类型化注册面(register(ns, locale, dict)),zh/en 双语齐备,+ * 语言自动跟随宿主 UI;`text()` 支持 `{name}` 插值。+ */+import type { ClientContext } from 'dsh-tauri/client'+import type { LocaleKey } from '../types'+import { PET_CLIENT_NS as NS } from '../constants'++export { PET_CLIENT_NS as NS } from '../constants'++/** zh 字典(键集合的权威)。 */+const DICT_ZH: Record<LocaleKey, string> = {+ name: '桌宠',+ enable: '启用',+ disable: '停用',+ enabled: '已启用',+ disabled: '已停用',+ selectPet: '选择宠物',+ show: '显示',+ hide: '隐藏',+ chooseCodex: 'Codex',+ import: '导入',+ pets: '宠物',+ petWindowHint: '桌宠会以独立透明窗口显示在桌面一角',+ enabledHint: '桌宠已启用,正在桌面显示',+ disabledHint: '桌宠未启用',+ loadFailed: '读取桌宠状态失败',+ setEnabledFailed: '切换桌宠状态失败',+ setPetFailed: '选择宠物失败',+}++/** en 字典,与 zh 键集完全一致。 */+const DICT_EN: Record<LocaleKey, string> = {+ name: 'Pet',+ enable: 'Enable',+ disable: 'Disable',+ enabled: 'Enabled',+ disabled: 'Disabled',+ selectPet: 'Select pet',+ show: 'Show',+ hide: 'Hide',+ chooseCodex: 'Codex',+ import: 'Import',+ pets: 'Pets',+ petWindowHint: 'The pet shows in a separate transparent window on the desktop',+ enabledHint: 'Pet enabled, showing on the desktop',+ disabledHint: 'Pet disabled',+ loadFailed: 'Failed to load pet status',+ setEnabledFailed: 'Failed to toggle pet status',+ setPetFailed: 'Failed to select pet',+}++/** 活跃语言 id(module 级缓存,apply 时初始化并由订阅推进)。 */+let activeLocale = 'en'++/**+ * 在 apply 里安装:注册双语字典,并桥接 locale 变更到 module 级缓存。+ * @param ctx - 客户端根上下文(须已注入 locale 服务)。+ */+export function installLocale(ctx: ClientContext): void {+ activeLocale = ctx.locale.getLocale().active+ ctx.locale.register(NS, 'zh', DICT_ZH)+ ctx.locale.register(NS, 'en', DICT_EN)+ ctx.locale.subscribe(() => {+ activeLocale = ctx.locale.getLocale().active+ })+}++/**+ * 按当前活跃语言取一条文案,并做 `{name}` 插值。+ * @param key - 文案键。+ * @param values - 插值表。+ */+export function text(key: LocaleKey, values: Record<string, string | number> = {}): string {+ const dict = activeLocale === 'en' ? DICT_EN : DICT_ZH+ return (dict[key] || DICT_EN[key] || key).replace(/\{(\w+)\}/g, (_, name: string) => String(values[name] ?? ''))+}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/src/client/register/control.ts b/packages/dsh-tauri-pet/src/client/register/control.tsnew file mode 100644index 00000000..8f728378--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/register/control.ts@@ -0,0 +1,26 @@+/**+ * register/control.ts — 桌宠浮控件注册:装入 layout 声明的 `shell.overlay` 槽。+ *+ * shell.overlay 是 list/root 槽(通用浮层,点击穿透——条目自行 opt-in 事件),+ * 以独立 id 并排在框架官方条目旁,不替换任何槽。等待槽声明后注册,+ * 卸载时随插件停用整体释放。+ */+import type { Context } from '@deepseek-ai/cordis'+// 拉入 dsh-client-ui-renderer 的 `declare module '@deepseek-ai/cordis'` 增广,+// 让 `ctx.slots`(SlotRegistry)获得类型(运行时由 UI renderer 提供)。+import type {} from '@deepseek-ai/dsh-client-ui-renderer'+import { PetControl } from '../components/pet-control'+import { PET_CONTROL_SLOT_ID } from '../constants'++export function installPetControl(ctx: Context): void {+ ctx.slots.inject('shell.overlay' as never, () =>+ ctx.slots.register(+ {+ name: 'shell.overlay',+ id: PET_CONTROL_SLOT_ID,+ order: 100,+ registrant: 'dsh-tauri-pet',+ } as never,+ PetControl as never,+ ))+}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/src/client/service/pet.ts b/packages/dsh-tauri-pet/src/client/service/pet.tsnew file mode 100644index 00000000..37eb245f--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/service/pet.ts@@ -0,0 +1,37 @@+/**+ * service/pet.ts — 桌宠 Tauri 命令的桥客户端。+ *+ * dsh 界面运行在 iframe 内,无 `__TAURI_INTERNALS__`,因此所有命令都经+ * `dsh-tauri/client` 的 `invokeBridgedTauri` 转发到宿主(主 webview)监听器,+ * 由宿主调用 `@tauri-apps/api/core` 的 `invoke` 并把结果回传(见桌面端+ * `src/hooks/use-iframe-invoke.ts`)。命令名与桌面端 bridge/pet.rs 的+ * `#[tauri::command]` 一一对应。+ */+import { invokeBridgedTauri } from 'dsh-tauri/client'+import type { PetStatus } from '../types'+import { CMD_GET_PET_STATUS, CMD_HIDE_PET, CMD_SET_ACTIVE_PET, CMD_SET_PET_ENABLED, CMD_SHOW_PET } from '../constants'++/** 查询桌宠当前状态(启用与否 + 当前选择)。 */+export function fetchPetStatus(): Promise<PetStatus> {+ return invokeBridgedTauri<PetStatus>(CMD_GET_PET_STATUS)+}++/** 启用/停用桌宠(同步外置窗口显示状态)。 */+export function setPetEnabled(enabled: boolean): Promise<PetStatus> {+ return invokeBridgedTauri<PetStatus>(CMD_SET_PET_ENABLED, { enabled })+}++/** 选择桌宠模型包。 */+export function setActivePet(id: string): Promise<PetStatus> {+ return invokeBridgedTauri<PetStatus>(CMD_SET_ACTIVE_PET, { id })+}++/** 显示桌宠窗口(需已启用)。 */+export function showPet(): Promise<void> {+ return invokeBridgedTauri<void>(CMD_SHOW_PET)+}++/** 隐藏桌宠窗口(不改 enabled)。 */+export function hidePet(): Promise<void> {+ return invokeBridgedTauri<void>(CMD_HIDE_PET)+}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/src/client/styles/index.ts b/packages/dsh-tauri-pet/src/client/styles/index.tsnew file mode 100644index 00000000..f31eb739--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/styles/index.ts@@ -0,0 +1,101 @@+/**+ * styles/index.ts — 桌宠浮控件的样式(css-render,apply() 的 effect 内 mount)。+ * 浮层固定在 dsh 画布右下角;开关/选择/显示/隐藏与「设置页」卡片一体。+ */+import { CssRender } from 'css-render'+import { PET_CLIENT_PLUGIN } from '../constants'++const CLS = {+ wrap: 'dshpet-wrap',+ pill: 'dshpet-pill',+ statusDot: 'dshpet-statusDot',+ pop: 'dshpet-pop',+ row: 'dshpet-row',+ petBtn: 'dshpet-petBtn',+ petBtnActive: 'dshpet-petBtnActive',+} as const++const cssr = CssRender()+const { c } = cssr++const style = c([+ c(`.${CLS.wrap}`, {+ position: 'fixed',+ right: '18px',+ bottom: '18px',+ zIndex: 2147483000,+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'flex-end',+ fontFamily: 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',+ }),+ c(`.${CLS.pill}`, {+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '6px 12px',+ borderRadius: '999px',+ border: '1px solid rgba(120,130,180,0.35)',+ background: 'rgba(24,28,56,0.72)',+ backdropFilter: 'blur(6px)',+ color: '#e7e9ff',+ fontSize: '12px',+ lineHeight: 1,+ cursor: 'pointer',+ boxShadow: '0 4px 14px rgba(0,0,0,0.25)',+ transition: 'background .16s ease, transform .1s ease',+ }),+ c(`.${CLS.pill}:hover`, {+ background: 'rgba(34,40,80,0.85)',+ }),+ c(`.${CLS.statusDot}`, {+ width: '9px',+ height: '9px',+ borderRadius: '50%',+ flex: 'none',+ }),+ c(`.${CLS.pop}`, {+ display: 'flex',+ flexDirection: 'column',+ gap: '6px',+ width: '220px',+ marginBottom: '8px',+ padding: '12px',+ borderRadius: '12px',+ border: '1px solid rgba(120,130,180,0.3)',+ background: 'rgba(24,28,56,0.9)',+ backdropFilter: 'blur(8px)',+ color: '#e7e9ff',+ fontSize: '12px',+ boxShadow: '0 8px 24px rgba(0,0,0,0.3)',+ }),+ c(`.${CLS.row}`, {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: '8px',+ }),+ c(`.${CLS.petBtn}`, {+ flex: 1,+ padding: '6px 8px',+ borderRadius: '8px',+ border: '1px solid rgba(120,130,180,0.3)',+ background: 'transparent',+ color: '#e7e9ff',+ fontSize: '12px',+ cursor: 'pointer',+ }),+ c(`.${CLS.petBtn}:hover`, {+ background: 'rgba(80,100,255,0.18)',+ }),+ c(`.${CLS.petBtnActive}`, {+ background: 'rgba(80,100,255,0.3)',+ borderColor: 'rgba(120,150,255,0.7)',+ }),+])++/** 挂载样式;返回卸载函数,供 apply() 的 effect 生命周期回收。 */+export function mountPetStyles(): () => void {+ style.mount({ id: `${PET_CLIENT_PLUGIN}-styles`, head: true })+ return () => style.unmount({ id: `${PET_CLIENT_PLUGIN}-styles` })+}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/src/client/types/index.ts b/packages/dsh-tauri-pet/src/client/types/index.tsnew file mode 100644index 00000000..6d6dd8b4--- /dev/null+++ b/packages/dsh-tauri-pet/src/client/types/index.ts@@ -0,0 +1,27 @@+/** types/index.ts — 本插件文案键集合(zh 字典为权威)与桌宠桥类型。 */++/** 桌宠当前状态(与桌面端 bridge/pet.rs 的 PetStatus 对齐)。 */+export interface PetStatus {+ enabled: boolean+ active_pet?: string | null+}++/** 文案键(locale 字典键集合的权威来源)。 */+export type LocaleKey+ = | 'name'+ | 'enable'+ | 'disable'+ | 'enabled'+ | 'disabled'+ | 'selectPet'+ | 'show'+ | 'hide'+ | 'chooseCodex'+ | 'import'+ | 'pets'+ | 'petWindowHint'+ | 'enabledHint'+ | 'disabledHint'+ | 'loadFailed'+ | 'setEnabledFailed'+ | 'setPetFailed'\ No newline at end of filediff --git a/packages/dsh-tauri-pet/src/index.ts b/packages/dsh-tauri-pet/src/index.tsnew file mode 100644index 00000000..6811670c--- /dev/null+++ b/packages/dsh-tauri-pet/src/index.ts@@ -0,0 +1,16 @@+/**+ * src/index.ts — dsh-tauri-pet 宿主侧(node half)。+ *+ * 桌宠能力全部在浏览器 half(shell.overlay 浮控件经 invoke 桥调用桌面端 Rust+ * 命令),宿主无需注册任何 Node 行为;loader 按行名导入包根时需要一个可挂载的+ * 插件入口,这里给一个空 apply。+ */++/** 插件名(诊断元数据)。 */+export const name = 'dsh-tauri-pet'++/** 需要的宿主服务(无,纯客户端能力)。 */+export const inject: string[] = []++/** 插件体:无宿主行为。 */+export function apply(): void {}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/tsconfig.json b/packages/dsh-tauri-pet/tsconfig.jsonnew file mode 100644index 00000000..73e40dcc--- /dev/null+++ b/packages/dsh-tauri-pet/tsconfig.json@@ -0,0 +1,4 @@+{+ "extends": "../../tsconfig.json",+ "include": ["src/**/*.ts", "src/**/*.tsx", "../../types/**/*.d.ts"]+}\ No newline at end of filediff --git a/packages/dsh-tauri-pet/tsdown.config.ts b/packages/dsh-tauri-pet/tsdown.config.tsnew file mode 100644index 00000000..daec4805--- /dev/null+++ b/packages/dsh-tauri-pet/tsdown.config.ts@@ -0,0 +1,3 @@+import { defineDshConfig } from 'dsh-tauri-tsdown'++export default defineDshConfig()\ No newline at end of filediff --git a/packages/dsh-tauri/src/client/constants/index.ts b/packages/dsh-tauri/src/client/constants/index.tsindex b48c65c1..b6415719 100644--- a/packages/dsh-tauri/src/client/constants/index.ts+++ b/packages/dsh-tauri/src/client/constants/index.ts@@ -4,6 +4,21 @@ export const SRC_HOST = 'dsh-desktop'/** iframe → 宿主事件的 source。 */export const SRC_BRIDGE = 'dsh-nav-bridge'+// ── dsh-tauri invoke 桥(iframe → 宿主 → invoke() → 回传)─────────────+// iframe 内的 dsh 界面 / 插件无法直接访问 `@tauri-apps/api`(`__TAURI_INTERNALS__`+// 只在顶层 webview)。本桥让客户端经 postMessage 把 command 上报到宿主(主+// webview)监听器,由宿主调用 Tauri `invoke` 并把结果回传给 iframe。+/** iframe → 宿主:invoke 请求的 source。 */+export const SRC_INVOKE = 'dsh-tauri-invoke'+/** 宿主 → iframe:invoke 应答的 source。 */+export const SRC_INVOKE_REPLY = 'dsh-desktop-invoke'+/** invoke 请求消息类型。 */+export const TYPE_INVOKE = 'dsh://tauri:invoke'+/** invoke 应答消息类型。 */+export const TYPE_INVOKE_REPLY = 'dsh://tauri:reply'+/** 单次 invoke 等待宿主应答的最长毫秒数(超时按失败处理)。 */+export const INVOKE_TIMEOUT_MS = 15000+/** 宿主命令类型。 */export const CMD_TOGGLE = 'dsh://sidebar:toggle'export const CMD_PREV = 'dsh://page:prev'diff --git a/packages/dsh-tauri/src/client/index.ts b/packages/dsh-tauri/src/client/index.tsindex 943e40b7..b2dadd8e 100644--- a/packages/dsh-tauri/src/client/index.ts+++ b/packages/dsh-tauri/src/client/index.ts@@ -23,6 +23,8 @@ export * from './storage'export * from './store'export type * from './types'+export { invokeBridgedTauri } from './service/invoke'+export type { ClientContext } from './types'export { compat, resolveStartSession } from './utils/compat'export { CssRender } from 'css-render'diff --git a/packages/dsh-tauri/src/client/service/invoke.ts b/packages/dsh-tauri/src/client/service/invoke.tsnew file mode 100644index 00000000..4a7a201e--- /dev/null+++ b/packages/dsh-tauri/src/client/service/invoke.ts@@ -0,0 +1,99 @@+/**+ * dsh-tauri invoke 桥(iframe 侧客户端)。+ *+ * iframe 内的 dsh 界面 / 插件没有 `__TAURI_INTERNALS__`(只有顶层 webview 有),+ * 因此无法直接 `import { invoke } from '@tauri-apps/api/core'`。本桥把这些调用+ * 经 postMessage 转发到宿主(主 webview)的监听器(见桌面端+ * `src/hooks/use-iframe-invoke.ts`),由宿主调用 Tauri `invoke` 并把结果回传。+ *+ * 协议(与宿主监听器逐字一致):+ * iframe → 宿主:{ source: 'dsh-tauri-invoke', type: 'dsh://tauri:invoke',+ * cmd, args, nonce }+ * 宿主 → iframe:{ source: 'dsh-desktop-invoke', type: 'dsh://tauri:reply',+ * nonce, ok, value | error }+ *+ * 可靠性:每条请求带唯一 nonce,应答按 nonce 精确匹配避免串线;等待超时+ * (INVOKE_TIMEOUT_MS)或局部失败统一 reject,并登记进宿主错误注册表便于排查。+ */+import { INVOKE_TIMEOUT_MS, PLUGIN_ID, SRC_INVOKE, SRC_INVOKE_REPLY, TYPE_INVOKE, TYPE_INVOKE_REPLY } from '../constants'+import type { InvokeBridgeRequest, InvokeBridgeReply } from '../types'++let nonceSeq = 0++/** 生成全局唯一的请求 nonce(`<pluginId>:<seq>`,进程内递增)。 */+function nextNonce(): string {+ nonceSeq += 1+ return `${PLUGIN_ID}:${nonceSeq}`+}++/**+ * 经宿主桥调用一个 Tauri command,返回其成功值;command 抛错或超时时 reject。+ *+ * @param cmd Tauri command 名(如 `get_pet_status`)+ * @param args command 参数对象(可选)+ * @typeParam T command 成功返回值的类型+ */+export function invokeBridgedTauri<T>(+ cmd: string,+ args?: Record<string, unknown>,+): Promise<T> {+ const nonce = nextNonce()++ return new Promise<T>((resolve, reject) => {+ let settled = false++ function onMessage(event: MessageEvent<unknown>): void {+ // 只接受宿主(顶层)直接发回的应答,且 nonce 必须命中本次请求+ if (event.source !== window.parent)+ return+ const data = event.data as InvokeBridgeReply | null+ if (!data || typeof data !== 'object' || data.source !== SRC_INVOKE_REPLY)+ return+ if (data.type !== TYPE_INVOKE_REPLY || data.nonce !== nonce)+ return+ settle(data)+ }++ function settle(reply: InvokeBridgeReply): void {+ if (settled)+ return+ settled = true+ window.removeEventListener('message', onMessage)+ if (reply.ok) {+ resolve(reply.value as T)+ }+ else {+ reject(new Error(reply.error || `NODE_NOT_ANSWERED: invoke ${cmd} rejected by host`))+ }+ }++ window.addEventListener('message', onMessage)+ // 超时保护:宿主未应答(监听器未挂载/iframe 非 dsh 环境等)时按失败处理+ const timer = setTimeout(() => {+ if (settled)+ return+ window.removeEventListener('message', onMessage)+ settled = true+ reject(new Error(`NODE_NOT_ANSWERED: invoke ${cmd} timed out`))+ }, INVOKE_TIMEOUT_MS)++ const request: InvokeBridgeRequest = {+ source: SRC_INVOKE,+ type: TYPE_INVOKE,+ cmd,+ args,+ nonce,+ }+ try {+ window.parent.postMessage(request, '*')+ }+ catch (error) {+ clearTimeout(timer)+ if (settled)+ return+ settled = true+ window.removeEventListener('message', onMessage)+ reject(error)+ }+ })+}\ No newline at end of filediff --git a/packages/dsh-tauri/src/client/types/bridge.ts b/packages/dsh-tauri/src/client/types/bridge.tsindex 56d38835..61c20950 100644--- a/packages/dsh-tauri/src/client/types/bridge.ts+++ b/packages/dsh-tauri/src/client/types/bridge.ts@@ -11,3 +11,27 @@ export interface Page {/** 记录动作(与宿主 `PluginError.action` 语义一致)。 */export type ErrorAction = 'runtime' | 'install' | 'update' | 'remove'++// ── dsh-tauri invoke 桥(iframe → 宿主 → invoke())────────────────+/** iframe → 宿主 的 invoke 请求(postMessage)。 */+export interface InvokeBridgeRequest {+ source: 'dsh-tauri-invoke'+ type: 'dsh://tauri:invoke'+ /** Tauri command 名。 */+ cmd: string+ /** command 参数对象。 */+ args?: Record<string, unknown>+ /** 一次请求的唯一标识,宿主原样回填用于匹配。 */+ nonce: string+}++/** 宿主 → iframe 的 invoke 应答(postMessage)。 */+export interface InvokeBridgeReply {+ source: 'dsh-desktop-invoke'+ type: 'dsh://tauri:reply'+ nonce: string+ /** true=成功(value 有效);false=失败(error 为 command 抛出的字符串)。 */+ ok: boolean+ value?: unknown+ error?: string+}diff --git a/pet.html b/pet.htmlnew file mode 100644index 00000000..b8a5dd41--- /dev/null+++ b/pet.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="zh-CN">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Deepseek Harness Pet</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/pet/main.tsx"></script>+ </body>+</html>\ No newline at end of filediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 57c06747..b36ccf12 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -415,6 +415,9 @@ importers:dsh-tauri-panel-placeholder:specifier: workspace:*version: link:../dsh-tauri-panel-placeholder+ dsh-tauri-pet:+ specifier: workspace:*+ version: link:../dsh-tauri-petdsh-tauri-rightclick:specifier: workspace:*version: link:../dsh-tauri-rightclick@@ -497,6 +500,40 @@ importers:specifier: catalog:cliversion: 0.17.4(@emnapi/[email protected])(@emnapi/[email protected])([email protected])([email protected])([email protected])([email protected])+ packages/dsh-tauri-pet:+ dependencies:+ dsh-tauri:+ specifier: workspace:*+ version: link:../dsh-tauri+ devDependencies:+ '@deepseek-ai/cordis':+ specifier: catalog:dsh+ version: 4.0.2(@deepseek-ai/[email protected])(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-client-store':+ specifier: catalog:dsh+ version: 0.1.2-alpha.3(@deepseek-ai/[email protected])(@types/[email protected])([email protected])+ '@deepseek-ai/dsh-client-ui-layout':+ specifier: catalog:dsh+ version: 0.1.2-alpha.3(@deepseek-ai/[email protected])+ '@deepseek-ai/dsh-client-ui-renderer':+ specifier: catalog:dsh+ version: 0.1.2-alpha.3(@deepseek-ai/[email protected])([email protected])+ '@deepseek-ai/dsh-client-ui-slots':+ specifier: catalog:dsh+ version: 0.1.2-alpha.3(@deepseek-ai/[email protected])+ css-render:+ specifier: catalog:ui+ version: 0.15.14+ dsh-tauri-tsdown:+ specifier: workspace:*+ version: link:../dsh-tauri-tsdown+ react:+ specifier: catalog:runtime+ version: 19.2.8+ tsdown:+ specifier: catalog:cli+ version: 0.17.4(@emnapi/[email protected])(@emnapi/[email protected])([email protected])([email protected])([email protected])([email protected])+packages/dsh-tauri-rightclick:dependencies:dsh-tauri:diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 0d5f50e6..ef2e9365 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -23,7 +23,8 @@ tauri-build = { version = "2", features = [] }tauri = { version = "2", features = ["tray-icon","image-png",- "devtools"+ "devtools",+ "macos-private-api"] }tauri-plugin-single-instance = "2"tauri-plugin-opener = "2"diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex f238ef74..0253b337 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -2,7 +2,7 @@"$schema": "../gen/schemas/desktop-schema.json","identifier": "default","description": "Capability for the main window and embedded Harness GUI. The remote Harness origin is restricted to loopback, while the shell validates every cross-origin postMessage before servicing bridge requests. The service port is NOT fixed: it defaults to 3080/3081 but is user-configurable and advances to the next free port when the default is occupied (service/workflow::find_available_port).",- "windows": ["main"],+ "windows": ["main", "pet"],"remote": {"urls": ["http://127.0.0.1:*"]},diff --git a/src-tauri/capabilities/desktop.json b/src-tauri/capabilities/desktop.jsonindex 5c839cd8..990629a7 100644--- a/src-tauri/capabilities/desktop.json+++ b/src-tauri/capabilities/desktop.json@@ -6,7 +6,8 @@"linux"],"windows": [- "main"+ "main",+ "pet"],"permissions": []}diff --git a/src-tauri/src/bridge/mod.rs b/src-tauri/src/bridge/mod.rsindex 16dd98ce..14493e58 100644--- a/src-tauri/src/bridge/mod.rs+++ b/src-tauri/src/bridge/mod.rs@@ -10,6 +10,7 @@ pub mod config;pub mod core;pub mod guard;pub mod lifecycle;+pub mod pet;pub mod plugin;pub mod profile;pub mod system_os;@@ -20,6 +21,7 @@ pub use clipboard::*;pub use config::*;pub use core::*;pub use lifecycle::*;+pub use pet::*;pub use plugin::*;pub use profile::*;pub use system_os::*;diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rsnew file mode 100644index 00000000..96ecb9fc--- /dev/null+++ b/src-tauri/src/bridge/pet.rs@@ -0,0 +1,87 @@+//! bridge/pet.rs — 桌宠(外置透明宠物窗口)的 Tauri 命令出口。+//!+//! 这些命令被 dsh 容器(iframe 内的 dsh 界面 / dsh-tauri-pet 插件)经+//! invoke 桥调用(见 `desktop::gravity`? 实际为壳层桥监听模块+//! `src/hooks/use-iframe-invoke.ts`,把 iframe 的 postMessage invoke 转发到+//! `@tauri-apps/api/core` 的 `invoke`)。所有状态读写统一落在+//! `config::setting`(持久化)与 `desktop::pet`(窗口)。错误遵循仓库约定:+//! `Result<_, String>`,Err 以大写协议前缀开头(如 `PET_WINDOW_*:`)。++use crate::config;+use crate::desktop::pet as pet_window;+use serde::{Deserialize, Serialize};+use tauri::{AppHandle, Manager};++/// 桌宠当前状态(设置页与插件读取)。+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct PetStatus {+ /// 桌宠是否启用(决定是否显示外置宠物窗口)。+ pub enabled: bool,+ /// 当前选中的桌宠模型包名;None/空 = 未选择(默认宠)。+ pub active_pet: Option<String>,+}++/// 查询桌宠当前状态(启用与否 + 当前选择的宠物模型)。+#[tauri::command]+pub fn get_pet_status(app: AppHandle) -> PetStatus {+ let setting = config::get_store_dat_setting(&app);+ PetStatus {+ enabled: setting.pet_enabled,+ active_pet: setting.active_pet.clone(),+ }+}++/// 启用/停用桌宠:改变设置并同步外置宠物窗口的显示状态。+#[tauri::command]+pub fn set_pet_enabled(app: AppHandle, enabled: bool) -> Result<PetStatus, String> {+ let updated = config::update_store_dat_setting(&app, |setting| {+ setting.pet_enabled = enabled;+ });++ // 无论启用还是停用都同步窗口(停用隐藏、启用创建+显示)。+ pet_window::sync_pet_window(&app);++ Ok(PetStatus {+ enabled: updated.pet_enabled,+ active_pet: updated.active_pet.clone(),+ })+}++/// 选择桌宠模型包(设置页「选择宠物」),并持久化 active_pet。+///+/// `id` 为模型包标志(`x.x.x.sprites/` 目录名或用户导入的 .zip 包名)。+#[tauri::command]+pub fn set_active_pet(app: AppHandle, id: String) -> Result<PetStatus, String> {+ let id = id.trim().to_string();+ if id.is_empty() {+ return Err("PET_ID_EMPTY: active pet id must not be empty".to_string());+ }+ let updated = config::update_store_dat_setting(&app, |setting| {+ setting.active_pet = Some(id);+ });++ Ok(PetStatus {+ enabled: updated.pet_enabled,+ active_pet: updated.active_pet.clone(),+ })+}++/// 显示桌宠窗口(仅当已启用时有效)。+#[tauri::command]+pub fn show_pet(app: AppHandle) -> Result<(), String> {+ if !config::get_store_dat_setting(&app).pet_enabled {+ return Err("PET_DISABLED: pet window is not enabled".to_string());+ }+ pet_window::sync_pet_window(&app);+ Ok(())+}++/// 隐藏桌宠窗口(不改动 pet_enabled 设置)。+#[tauri::command]+pub fn hide_pet(app: AppHandle) -> Result<(), String> {+ if let Some(window) = app.get_webview_window(pet_window::PET_WINDOW_LABEL) {+ let _ = window.hide();+ }+ Ok(())+}\ No newline at end of filediff --git a/src-tauri/src/config/constants.rs b/src-tauri/src/config/constants.rsindex df2e8035..769bcdd4 100644--- a/src-tauri/src/config/constants.rs+++ b/src-tauri/src/config/constants.rs@@ -89,6 +89,8 @@ pub const STORE_DAT_DEV_FILE: &str = ".store.dev.dat";pub const STORE_SETTING_KEY: &str = "setting";/// Store 中记录主窗口几何(位置/大小/最大化)的键pub const STORE_WINDOW_STATE_KEY: &str = "window_state";+/// Store 中记录桌宠(外置透明宠物窗口)几何(位置/大小)的键+pub const STORE_PET_WINDOW_STATE_KEY: &str = "pet_window_state";/// 健康检查超时pub const HEALTH_CHECK_TIMEOUT: Duration = Duration::from_secs(5);diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rsindex 506c2726..746f070f 100644--- a/src-tauri/src/config/setting.rs+++ b/src-tauri/src/config/setting.rs@@ -74,6 +74,13 @@ pub struct Setting {/// 备份是否包含凭据文件(`.credentials.yaml`)。#[serde(default)]pub backup_include_credentials: bool,+ /// 桌宠(外置透明宠物窗口)是否启用。+ #[serde(default)]+ pub pet_enabled: bool,+ /// 当前选中的桌宠模型包(`x.x.x.sprites/` 目录名或用户导入的 .zip 包名);+ /// `None` 或空串 = 尚未选择(沿用默认内置宠)。+ #[serde(default)]+ pub active_pet: Option<String>,}pub const ZOOM_FACTOR_MIN: f64 = 0.5;@@ -192,6 +199,8 @@ impl Default for Setting {auto_backup_on_change: false,backup_retention_count: default_backup_retention_count(),backup_include_credentials: false,+ pet_enabled: false,+ active_pet: None,}}}diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex e1a0767b..5521a65a 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -572,6 +572,11 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::read_clipboard_image,crate::desktop::notification::show_native_notification,crate::bridge::log_frontend,+ crate::bridge::get_pet_status,+ crate::bridge::set_pet_enabled,+ crate::bridge::set_active_pet,+ crate::bridge::show_pet,+ crate::bridge::hide_pet,]}@@ -584,6 +589,8 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {#[cfg(target_os = "macos")]install_macos_menu(&app_handle)?;tray(&app_handle)?;+ // 桌宠窗口:按「是否启用」设置惰性创建/显示(幂等)。+ crate::desktop::pet::init_pet_window(&app_handle);setup(app_handle.clone());Ok(())})@@ -648,10 +655,18 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {}// 移动/缩放主窗口时记录几何,重启后据此恢复(见 config::window_state)tauri::WindowEvent::Moved(_) => {- crate::config::save_geometry(window);+ if window.label() == crate::desktop::pet::PET_WINDOW_LABEL {+ crate::desktop::pet::save_pet_window_geometry(window);+ } else {+ crate::config::save_geometry(window);+ }}tauri::WindowEvent::Resized(_) => {- crate::config::save_geometry(window);+ if window.label() == crate::desktop::pet::PET_WINDOW_LABEL {+ crate::desktop::pet::save_pet_window_geometry(window);+ } else {+ crate::config::save_geometry(window);+ }#[cfg(target_os = "macos")]sync_macos_fullscreen_menu(window);// 退出全屏后补做全屏期间被推迟的 Accessory 切换diff --git a/src-tauri/src/desktop/mod.rs b/src-tauri/src/desktop/mod.rsindex 8848bb6f..1d69619e 100644--- a/src-tauri/src/desktop/mod.rs+++ b/src-tauri/src/desktop/mod.rs@@ -6,6 +6,7 @@ pub mod nav;pub mod notification;pub mod paste;pub mod payload;+pub mod pet;pub mod plugin_boot;pub mod style;pub mod window;diff --git a/src-tauri/src/desktop/pet.rs b/src-tauri/src/desktop/pet.rsnew file mode 100644index 00000000..1a2a4bbe--- /dev/null+++ b/src-tauri/src/desktop/pet.rs@@ -0,0 +1,218 @@+//! 桌宠外置窗口:独立的透明、置顶、无边框小窗口,用于展示 dsh 会话状态的+//! 动画宠物(桌宠外置化,issue #308)。+//!+//! 设计要点(参考 BongoCat 的多 WebView 桌宠方案):+//! - 独立窗口 label `pet`,`WebviewUrl::App("pet.html")`,与主窗口(`main`)+//! 并行,由主 webview 监听 dsh-container 的 invoke 桥来操控;+//! - 窗口特性:`transparent + always_on_top + decorations(false) ++//! skip_taskbar + shadow(false) + accept_first_mouse`,打造覆盖在普通+//! 窗口之上的不抢占焦点的宠物层;+//! - 几何(位置/大小)持久化到独立 store 键 `pet_window_state`,重启恢复,+//! 不与主窗口几何互相污染(主窗口用 `config::window_state`)。+//!+//! 平台说明:+//! - macOS 透明窗口需要 `macOSPrivateApi`(见 tauri.conf.json `app` 段),且+//! Tauri 的 masking 需 `macos-private-api` Cargo feature,由+//! `src-tauri/Cargo.toml` 按平台门控开启。这里透明依赖平台原生支持,创建失败+//! 时回退为非透明窗口继续工作。+//! - `always_on_top` 在 Windows 上 Tauri 原生 API 即可保持置顶(BongoCat 为+//! 额外稳定性用 SetWindowPos 循环轮询,本项目暂不做该平台特定加固)。++use crate::config::{self, STORE_PET_WINDOW_STATE_KEY};+use serde::{Deserialize, Serialize};+use tauri::{+ AppHandle, Manager, PhysicalPosition, Runtime, WebviewUrl, WebviewWindow, WebviewWindowBuilder,+ Window,+};+use tauri_plugin_store::StoreExt;++/// 桌宠窗口的 label(Tauri 窗口标识,脚本层与能力配置以此引用)。+pub const PET_WINDOW_LABEL: &str = "pet";+/// 桌宠窗口默认尺寸(逻辑像素),偶数值便于像素对齐的精灵图展示。+pub const PET_WINDOW_WIDTH: f64 = 240.0;+pub const PET_WINDOW_HEIGHT: f64 = 280.0;++/// 持久化的桌宠窗口位置(仅记录位置;大小固定为 PET_WINDOW_* 尺寸不随用户变化)。+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(default)]+pub struct PetWindowPosition {+ /// 非 None 时恢复物理位置;None 表示用户从未拖动过,走系统默认(居中靠下)。+ pub x: Option<i32>,+ pub y: Option<i32>,+}++fn store_dat_file_name() -> &'static str {+ if cfg!(debug_assertions) {+ config::STORE_DAT_DEV_FILE+ } else {+ config::STORE_DAT_FILE+ }+}++/// 读取上次保存的桌宠窗口位置;无记录时返回默认(None,位置未定)。+pub fn get_pet_window_position<R: Runtime>(app: &AppHandle<R>) -> PetWindowPosition {+ let store = app+ .store(store_dat_file_name())+ .expect("Failed to load store for pet window position");+ let raw = store.get(STORE_PET_WINDOW_STATE_KEY);+ let value = raw.as_ref().and_then(|v| {+ v.as_str()+ .and_then(|s| serde_json::from_str(s).ok())+ .or_else(|| Some(v.clone()))+ });+ value+ .and_then(|v| serde_json::from_value(v).ok())+ .unwrap_or_default()+}++/// 保存桌宠窗口位置(用户拖动后由 Moved 事件调用)。+pub fn save_pet_window_position<R: Runtime>(app: &AppHandle<R>, position: &PetWindowPosition) {+ let store = app+ .store(store_dat_file_name())+ .expect("Failed to load store for pet window position");+ let serialized =+ serde_json::to_value(position).expect("Failed to serialize pet window position");+ store.set(STORE_PET_WINDOW_STATE_KEY, serialized);+ store.save().expect("Failed to save pet window position");+}++/// 采样当前桌宠窗口位置并保存(窗口 Moved 时由 builder 调用)。+///+/// 接收基础 `Window`(`on_window_event` 回调类型),仅需其外部位与可见性。+pub fn save_pet_window_geometry<R: Runtime>(window: &Window<R>) {+ // 窗口未显示或正在全屏时采样到的可能是瞬态/无意义的位置,跳过。+ if !window.is_visible().unwrap_or(false) {+ return;+ }+ let Some(pos) = window.outer_position().ok() else {+ return;+ };+ let app = window.app_handle().clone();+ save_pet_window_position(+ &app,+ &PetWindowPosition {+ x: Some(pos.x),+ y: Some(pos.y),+ },+ );+}++/// 确保桌宠窗口存在并恢复位置。+///+/// 幂等:已注册时直接复用返回;首次调用时创建 `pet` 窗口并恢复上一次保存的+/// 位置(无记录则默认定位在主屏右下角略偏上,避免遮挡主工作区)。+pub fn ensure_pet_window<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<WebviewWindow<R>> {+ if let Some(window) = app.get_webview_window(PET_WINDOW_LABEL) {+ return Ok(window);+ }+ let app_handle = app.clone();+ // 非 Windows 平台在此前加入注入脚本时再赋值,故需要 mut;Windows 下保持只读。+ #[allow(unused_mut)]+ let mut builder = WebviewWindowBuilder::new(app, PET_WINDOW_LABEL, WebviewUrl::App("pet.html".into()))+ .title("Deepseek Harness Pet")+ .inner_size(PET_WINDOW_WIDTH, PET_WINDOW_HEIGHT)+ .resizable(false)+ .maximizable(false)+ .transparent(true)+ .always_on_top(true)+ .decorations(false)+ .skip_taskbar(true)+ .shadow(false)+ .accept_first_mouse(true)+ .visible(false);++ // 非 Windows 平台经 initialization script 让 dsh 容器的桥/兼容注入生效,+ // 与主窗口保持一致(桌宠页同样可能加载共享的前端模块)。+ #[cfg(not(windows))]+ {+ builder = builder+ .initialization_script_for_all_frames(crate::desktop::compat::ABORT_SIGNAL_ANY_SHIM_JS)+ .initialization_script_for_all_frames(crate::desktop::notification::NOTIFICATION_SHIM_JS)+ .initialization_script_for_all_frames(crate::desktop::nav::NAV_SHIM_JS)+ .initialization_script_for_all_frames(crate::desktop::style::IFRAME_STYLES_JS)+ .initialization_script_for_all_frames(crate::desktop::paste::PASTE_SHIM_JS)+ .initialization_script_for_all_frames(crate::desktop::plugin_boot::PLUGIN_BOOT_RELOAD_JS)+ .initialization_script_for_all_frames(crate::desktop::zoom::ZOOM_SHORTCUT_BRIDGE_JS);+ }++ let window = builder.build()?;+ let app_for_pos = app_handle.clone();+ let saved = get_pet_window_position(&app_for_pos);+ if let (Some(x), Some(y)) = (saved.x, saved.y) {+ // 恢复的位置必须落在某个可见屏幕内,否则回退默认定位。+ let _ = window.set_position(tauri::Position::Physical(PhysicalPosition::new(x, y)));+ }+ else {+ place_pet_at_default(&window);+ }+ Ok(window)+}++/// 把桌宠窗口放到主工作区右下角略偏上(主屏内、避开底部任务栏高度)。+fn place_pet_at_default<R: Runtime>(window: &WebviewWindow<R>) {+ let app = window.app_handle();+ let Some(monitor) = app.primary_monitor().ok().flatten() else {+ return;+ };+ let mon_pos = monitor.position();+ let mon_size = monitor.size();+ // 距屏幕右下角 32px 的物理偏移,尺寸用物理像素计算。+ let w = (PET_WINDOW_WIDTH * monitor.scale_factor()) as i32;+ let h = (PET_WINDOW_HEIGHT * monitor.scale_factor()) as i32;+ let x = mon_pos.x + mon_size.width as i32 - w - 32;+ let y = mon_pos.y + mon_size.height as i32 - h - 96;+ let _ = window.set_position(tauri::Position::Physical(PhysicalPosition::new(x, y)));+}++/// 按是否启用把桌宠窗口显示/隐藏。+///+/// - 未启用:隐藏窗口(保留窗口实例,避免反复重建)。+/// - 已启用:确保窗口存在并显示居中到上次位置。+pub fn sync_pet_window<R: Runtime>(app: &AppHandle<R>) {+ let enabled = crate::config::get_store_dat_setting(app).pet_enabled;+ if !enabled {+ if let Some(window) = app.get_webview_window(PET_WINDOW_LABEL) {+ let _ = window.hide();+ }+ return;+ }+ if ensure_pet_window(app).is_ok() {+ if let Some(window) = app.get_webview_window(PET_WINDOW_LABEL) {+ let _ = window.show();+ let _ = window.set_focus();+ }+ }+}++/// 创建桌宠窗口并沿用当前「是否启用」设置(应用启动时调用,幂等)。+pub fn init_pet_window<R: Runtime>(app: &AppHandle<R>) {+ sync_pet_window(app);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn pet_window_position_serde_roundtrip() {+ let pos = PetWindowPosition {+ x: Some(120),+ y: Some(240),+ };+ let json = serde_json::to_string(&pos).expect("serialize");+ let parsed: PetWindowPosition = serde_json::from_str(&json).expect("deserialize");+ assert_eq!(parsed.x, Some(120));+ assert_eq!(parsed.y, Some(240));+ }++ #[test]+ fn pet_window_position_defaults_to_none() {+ // 缺失字段 / 空对象时应回落默认(未定制位置),不能反序列化失败+ let parsed: PetWindowPosition = serde_json::from_str("{}").expect("deserialize");+ assert!(parsed.x.is_none());+ assert!(parsed.y.is_none());++ let default = PetWindowPosition::default();+ assert!(default.x.is_none() && default.y.is_none());+ }+}\ No newline at end of filediff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 175f028d..468c5380 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -10,6 +10,7 @@"frontendDist": "../dist"},"app": {+ "macOSPrivateApi": true,"security": {"csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost; img-src 'self' asset: http://asset.localhost data:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; frame-src http://127.0.0.1:*","devCsp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://localhost:1420 ws://localhost:1421; img-src 'self' asset: http://asset.localhost data:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; frame-src http://127.0.0.1:*"diff --git a/src/hooks/use-iframe-invoke.ts b/src/hooks/use-iframe-invoke.tsnew file mode 100644index 00000000..eab8beaf--- /dev/null+++ b/src/hooks/use-iframe-invoke.ts@@ -0,0 +1,74 @@+import type { RefObject } from 'react'+import { invoke } from '@tauri-apps/api/core'+import { useEvent } from 'react-use'+import { getIframeOrigin } from '@/utils/iframe'++/**+ * 壳层 invoke 桥监听器(宿主侧):把 iframe 内 dsh 界面/插件的 Tauri 调用+ * 转发到 `@tauri-apps/api/core` 的 `invoke`,再把结果回传给 iframe。+ *+ * 背景:dsh GUI 运行在 iframe 内,其触发的 Tauri command(如桌宠插件的+ * get_pet_status/set_pet_enabled)无法直接访问 `__TAURI_INTERNALS__`(只在+ * 顶层 webview)。dsh-tauri 客户端用 postMessage 把调用上报到主 webview,本+ * 监听器校验来源后执行 `invoke` 并回传。+ *+ * 协议(与 dsh-tauri client service/invoke.ts 逐字一致):+ * iframe → 宿主:{ source: 'dsh-tauri-invoke', type: 'dsh://tauri:invoke',+ * cmd, args, nonce }+ * 宿主 → iframe:{ source: 'dsh-desktop-invoke', type: 'dsh://tauri:reply',+ * nonce, ok, value | error }+ *+ * 安全:与通知/剪贴板桥一致,只接受 DSH 直接 iframe 发来的消息(event.source+ * 与 origin 双重校验),不兼容多层嵌套 iframe。+ */+interface InvokeBridgeRequest {+ source?: 'dsh-tauri-invoke'+ type?: 'dsh://tauri:invoke'+ cmd?: string+ args?: Record<string, unknown>+ nonce?: string+}++export function useIframeInvoke(iframeRef: RefObject<HTMLIFrameElement | null>): void {+ function handleMessage(event: MessageEvent<InvokeBridgeRequest>) {+ const data = event.data+ if (!data || typeof data !== 'object' || data.source !== 'dsh-tauri-invoke') {+ return+ }+ // 只接受 DSH 直接 iframe 发来的消息;不兼容多层嵌套 iframe。+ if (event.source !== iframeRef.current?.contentWindow) {+ return+ }+ const iframeOrigin = getIframeOrigin(iframeRef)+ if (!iframeOrigin || event.origin !== iframeOrigin) {+ return+ }+ if (data.type !== 'dsh://tauri:invoke' || !data.cmd) {+ return+ }+ const cmd = data.cmd+ const args = data.args+ const nonce = data.nonce ?? ''+ // 闭包外固定收窄后的 origin(TS 在闭包内丢失控制流收窄)。+ const origin = iframeOrigin++ function reply(payload: { ok: boolean, value?: unknown, error?: string }) {+ iframeRef.current?.contentWindow?.postMessage(+ { source: 'dsh-desktop-invoke', type: 'dsh://tauri:reply', nonce, ...payload },+ origin,+ )+ }+ // 统一以字符串承载错误(command 已按约定 `Result<_, String>` 返回带前缀 error)。+ void invoke<unknown>(cmd, args)+ .then(value => reply({ ok: true, value }))+ .catch((error: unknown) => {+ console.error(`[iframe-invoke] ${cmd} failed:`, error)+ reply({+ ok: false,+ error: (error instanceof Error ? error.message : String(error)).slice(0, 2000),+ })+ })+ }++ useEvent('message', handleMessage)+}\ No newline at end of filediff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsxindex c9741147..1d33fbed 100644--- a/src/layout/components/webview.tsx+++ b/src/layout/components/webview.tsx@@ -6,6 +6,7 @@ import { If } from 'react-if-lite'import { useStore } from 'valtio-define'import { PluginRecovery } from '@/components/plugin-recovery'import { useDesktopZoom } from '@/hooks/use-desktop-zoom'+import { useIframeInvoke } from '@/hooks/use-iframe-invoke'import { useIframeShim } from '@/hooks/use-iframe-shim'import { store } from '@/store'import { Loadable } from './loadable'@@ -42,6 +43,7 @@ export function Webview() {useDesktopZoom(iframeRef)useIframeShim(iframeRef)+ useIframeInvoke(iframeRef)if (status === 'error') {return (diff --git a/src/pet/main.tsx b/src/pet/main.tsxnew file mode 100644index 00000000..1aacd73a--- /dev/null+++ b/src/pet/main.tsx@@ -0,0 +1,14 @@+import React from 'react'+import ReactDOM from 'react-dom/client'+import { PetWindow } from './pet'+import './pet.css'++const root = document.getElementById('root') as HTMLElement+root.style.width = '100%'+root.style.height = '100%'++ReactDOM.createRoot(root).render(+ <React.StrictMode>+ <PetWindow />+ </React.StrictMode>,+)\ No newline at end of filediff --git a/src/pet/pet.css b/src/pet/pet.cssnew file mode 100644index 00000000..ee0556cf--- /dev/null+++ b/src/pet/pet.css@@ -0,0 +1,164 @@+/* 桌宠外置窗口样式:透明画布 + 像素风桌宠。+ 窗口本身 transparent=true(无边框、无阴影、跳过任务栏),因此 body 全透明,+ 只绘制宠物主体。尺寸由 Rust 侧 PET_WINDOW_WIDTH/HEIGHT(240x280)给定。 */++html,+body {+ margin: 0;+ padding: 0;+ width: 100%;+ height: 100%;+ overflow: hidden;+ background: transparent;+ /* 让拖动手把在这块区域可拖动 */+ -webkit-user-select: none;+ user-select: none;+ cursor: default;+ font-family: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+}++#root {+ width: 100%;+ height: 100%;+}++.pet-stage {+ position: relative;+ width: 100%;+ height: 100%;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: flex-end;+}++/* 顶部拖动手把:整条可拖动,视觉透明 */+.pet-drag {+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ height: 28px;+ cursor: grab;+ -webkit-app-region: drag;+ app-region: drag;+}++/* 宠物画布:居中,纵向从下往上生长 */+.pet-canvas {+ position: relative;+ display: flex;+ flex-direction: column;+ align-items: center;+ margin-bottom: 10px;+}++/* 像素主体容器:用固定逻辑尺寸,配合 preserve-3d 缩放无锯齿感 */+.pet-mascot {+ position: relative;+ width: 96px;+ height: 96px;+ filter: drop-shadow(0 6px 10px rgba(0, 0, 0, 0.35));+ transition: transform 240ms ease;+}+.pet-mascot.bobbing {+ animation: pet-bob 520ms ease-in-out;+}+@keyframes pet-bob {+ 0%,+ 100% {+ transform: translateY(0) scaleY(1);+ }+ 50% {+ transform: translateY(-6px) scaleY(0.98);+ }+}++/* 方形身体:圆角像素块,随不同 pet 由底色区分(可扩展为精灵图) */+.pixel-body {+ position: absolute;+ inset: 16px 8px 8px;+ border-radius: 22px;+ background: linear-gradient(160deg, #4f7cff 0%, #3b5bff 60%, #2f49ef 100%);+ border: 3px solid #1e2fae;+ box-shadow: inset 0 -14px 0 rgba(0, 0, 0, 0.12);+}++/* 面部 */+.pixel-face {+ position: absolute;+ inset: 36px 20px auto;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: center;+ gap: 18px;+}+.pixel-eye {+ width: 12px;+ height: 16px;+ border-radius: 8px;+ background: #1b1f3a;+ animation: pet-blink 4s infinite;+}+.pixel-eye.left {+ animation-delay: 0s;+}+.pixel-eye.right {+ animation-delay: 0s;+}+@keyframes pet-blink {+ 0%,+ 92%,+ 100% {+ transform: scaleY(1);+ }+ 96% {+ transform: scaleY(0.15);+ }+}+.pixel-mouth {+ width: 22px;+ height: 8px;+ margin-top: 10px;+ border-radius: 0 0 12px 12px;+ border-bottom: 3px solid #1b1f3a;+ border-left: 3px solid transparent;+ border-right: 3px solid transparent;+}++/* 宠物名称:悬浮小标签 */+.pet-name {+ margin-top: 4px;+ padding: 2px 10px;+ border-radius: 999px;+ font-size: 11px;+ line-height: 1.4;+ color: rgba(255, 255, 255, 0.92);+ background: rgba(20, 24, 52, 0.55);+ backdrop-filter: blur(2px);+ -webkit-backdrop-filter: blur(2px);+}++/* 关闭按钮:右下角小圆角方块,悬停显现 */+.pet-close {+ position: absolute;+ right: 8px;+ bottom: 8px;+ width: 20px;+ height: 20px;+ display: grid;+ place-items: center;+ border: none;+ border-radius: 6px;+ color: rgba(255, 255, 255, 0.55);+ background: rgba(20, 24, 52, 0.35);+ cursor: pointer;+ opacity: 0.55;+ transition: opacity 160ms ease, background 160ms ease;+}+.pet-close:hover {+ opacity: 1;+ background: rgba(160, 30, 30, 0.7);+ color: #fff;+}\ No newline at end of filediff --git a/src/pet/pet.tsx b/src/pet/pet.tsxnew file mode 100644index 00000000..b9272b11--- /dev/null+++ b/src/pet/pet.tsx@@ -0,0 +1,90 @@+import { useEffect, useState } from 'react'+import { invoke } from '@tauri-apps/api/core'++/**+ * 桌宠外置窗口(独立透明 Webview,label `pet`)。+ *+ * 展现 dsh 桌宠可活动物形象;窗口即画布(body 尺寸 = PET_WINDOW_*),+ * 顶部留一条可拖动把手(`data-tauri-drag-region`),右下角关闭按钮通过+ * `hide_pet` 命令隐藏(不动 `pet_enabled`,可再次经插件桥显示)。+ *+ * 该窗口是 Tauri 顶层 webview(非 iframe),可直接 `import { invoke }`。+ */++interface PetStatus {+ enabled: boolean+ active_pet?: string | null+}++/** 无状态时的默认动物文案(取 active_pet 的最后一段,去掉版本/扩展)。 */+function petDisplayName(id: string | null | undefined): string {+ if (!id)+ return 'dsh'+ const segment = id.split(/[\\/]/).pop() ?? id+ return segment.replace(/\.(zip|png|sprites)$/i, '') || 'dsh'+}++export function PetWindow() {+ const [activePet, setActivePet] = useState<string>('dsh')+ const [bobbing, setBobbing] = useState(false)++ useEffect(() => {+ let cancelled = false+ void invoke<PetStatus>('get_pet_status')+ .then((status) => {+ if (!cancelled && status.active_pet) {+ setActivePet(petDisplayName(status.active_pet))+ }+ })+ .catch((error) => {+ console.error('[pet] get_pet_status failed:', error)+ })+ return () => {+ cancelled = true+ }+ }, [])++ // 周期性俏皮「点头」,让桌宠显得有生命(仅视觉,与 dsh 会话状态无关)。+ useEffect(() => {+ const timer = setTimeout(() => setBobbing(true), 1200)+ return () => clearTimeout(timer)+ }, [bobbing])++ function hide() {+ void invoke('hide_pet').catch((error) => {+ console.error('[pet] hide_pet failed:', error)+ })+ }++ return (+ <div className="pet-stage">+ <div className="pet-drag" data-tauri-drag-region>+ {/* 拖动手把:拖动即触发桌面端 Moved 保存位置 */}+ </div>++ <div className="pet-canvas" role="img" aria-label={`Deepseek Harness pet: ${activePet}`}>+ <div className={`pet-mascot${bobbing ? ' bobbing' : ''}`}>+ {/* 像素风桌宠主体(CSS 拼块),形象随 activePet 称为文案提示 */}+ <div className="pixel-body" />+ <div className="pixel-face">+ <span className="pixel-eye left" />+ <span className="pixel-eye right" />+ <span className="pixel-mouth" />+ </div>+ </div>+ <span className="pet-name">{activePet}</span>+ </div>++ <button className="pet-close" type="button" onClick={hide} title="Hide pet">+ <svg viewBox="0 0 10 10" width="10" height="10" aria-hidden="true">+ <path+ d="M1 1 L9 9 M9 1 L1 9"+ stroke="currentColor"+ strokeWidth="1.6"+ strokeLinecap="round"+ />+ </svg>+ </button>+ </div>+ )+}\ No newline at end of filediff --git a/vite.config.ts b/vite.config.tsindex 4f327b50..80dc7147 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -16,6 +16,16 @@ export default defineConfig(async () => ({tailwindcss(),],+ // 多页入口:主窗口(index.html)与桌宠外置窗口(pet.html,独立透明窗口)。+ build: {+ rollupOptions: {+ input: {+ main: '/index.html',+ pet: '/pet.html',+ },+ },+ },+resolve: {alias: {'@': '/src',