Skip to content

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

feat(pet): mockup-shaped settings tabs, live percent resize, robust sidebar row

hairyff7ac21ff61fe
diff --git a/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx b/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
index 9429adf0..ef45dc0b 100644
--- a/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
+++ b/packages/dsh-tauri-pet/src/client/components/pet-settings.tsx
@@ -1,58 +1,134 @@
/**
- * components/pet-settings.tsx — 「宠物」设置分区(注册进 settings.section 槽,
- * 与 dsh-tauri-session 的归档分区同点位、同布局语言)。
+ * components/pet-settings.tsx — 「宠物」设置分区(注册进 settings.section 槽)。
*
- * 结构(参照归档页):页标题 + 分组卡片;启用开关、宠物大小拖动条(松手提交
- * set_pet_size)、选择宠物、显示/隐藏。所有变更走 invoke 桥;失败在页内
- * `{error && <div role="alert">}` 展示(同归档页错误条模式)。
+ * 布局遵循 issue #308 规范稿:页签(选择宠物 / Codex)+ 右侧工具栏 + 描述行 +
+ * 分隔线 + 宠物卡片列表(图 + 名 + 描述 + 右侧动作按钮)。
+ * - 「选择宠物」页签:工具栏 刷新 / 创建(即将支持)/ 唤醒·收起宠物;卡片 =
+ * 内置宠 + 已导入包,按钮「选择/已选」;大小滑条实时提交(拖动中即生效,
+ * 不显示数值)。
+ * - 「Codex」页签:工具栏 刷新 / 导入(.zip,base64 上桥);卡片 = 已导入包。
+ * 所有变更走 invoke 桥;失败在页内 `{error && <div role="alert">}` 展示
+ * (同 dsh-tauri-session 归档页错误条模式)。
*/
-import type { LocaleKey } from '../types'
-import { useEffect, useState, useSyncExternalStore } from 'react'
+import type { ChangeEvent } from 'react'
+import type { LocaleKey, PetListItem } from '../types'
+import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
import { DEFAULT_PETS, PET_DEFAULT_SIZE, PET_SIZE_MAX, PET_SIZE_MIN, PET_SIZE_STEP } from '../constants'
import { text } from '../locales'
-import { fetchPetStatus, hidePet, setActivePet, setPetEnabled, setPetSize, showPet } from '../service/pet'
+import { fetchPetList, fetchPetStatus, hidePet, importPet, setActivePet, setPetEnabled, setPetSize } from '../service/pet'
import { getPetUiSnapshot, setPetStatus, subscribePetUi } from '../store'
type PetSettingsProps = Record<never, never>
+// ── 工具栏图标(currentColor 跟随按钮悬停变色)────────────────────────
+const REFRESH_ICON = (
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M17.65 6.35A7.96 7.96 0 0 0 12 4a8 8 0 1 0 7.73 10h-2.08A6 6 0 1 1 12 6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />
+ </svg>
+)
+const PLUS_ICON = (
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6z" />
+ </svg>
+)
+const CHAT_ICON = (
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M20 2H4a2 2 0 0 0-2 2v18l4-4h14a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2z" />
+ </svg>
+)
+const DOWNLOAD_ICON = (
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" />
+ </svg>
+)
+
+interface PetCardProps {
+ /** 卡片缩略图形符(内置宠/导入包用 emoji 占位,避免随包携带位图资源)。 */
+ glyph: string
+ name: string
+ desc: string
+ actionLabel: string
+ actionActive: boolean
+ disabled: boolean
+ onAction: () => void
+}
+
+/** 宠物卡片:左图 + 中间名/描述 + 右侧动作按钮(规范稿的横向卡片)。 */
+function PetCard(props: PetCardProps) {
+ return (
+ <div className="dshpet-cardItem">
+ <span className="dshpet-cardThumb" aria-hidden="true">{props.glyph}</span>
+ <span className="dshpet-cardBody">
+ <span className="dshpet-cardName">{props.name}</span>
+ {props.desc
+ ? <span className="dshpet-cardDesc">{props.desc}</span>
+ : null}
+ </span>
+ <button
+ type="button"
+ className={props.actionActive ? 'dshpet-cardAction dshpet-cardActionActive' : 'dshpet-cardAction'}
+ disabled={props.disabled}
+ onClick={props.onAction}
+ >
+ {props.actionLabel}
+ </button>
+ </div>
+ )
+}
+
+/** File → base64(去 dataURL 前缀;供 import_pet 落盘 .zip)。 */
+function readAsBase64(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onload = () => {
+ const result = String(reader.result ?? '')
+ const comma = result.indexOf(',')
+ resolve(comma >= 0 ? result.slice(comma + 1) : result)
+ }
+ reader.onerror = () => reject(new Error('file read failed'))
+ reader.readAsDataURL(file)
+ })
+}
+
export function PetSettings(_props: PetSettingsProps) {
const { status } = useSyncExternalStore(subscribePetUi, getPetUiSnapshot, getPetUiSnapshot)
const [busy, setBusy] = useState(false)
const [errorMsg, setErrorMsg] = useState<LocaleKey | null>(null)
+ const [tab, setTab] = useState<'pets' | 'codex'>('pets')
+ const [imported, setImported] = useState<PetListItem[]>([])
const [size, setSize] = useState(status?.pet_size ?? PET_DEFAULT_SIZE)
+ // 最近一次提交成功的大小:回填滑条时用于识别「别处改的」vs「自己提交的回声」,
+ // 避免拖动中滑条被自己上一帧的响应拽回去。
+ const committedSizeRef = useRef<number | null>(null)
const enabled = Boolean(status?.enabled)
const statusSize = status?.pet_size ?? PET_DEFAULT_SIZE
+ const activePet = status?.active_pet
- // 进入分区时拉一次状态(同归档页刷新语义),与侧栏图标共享缓存。
+ // 进入分区拉一次状态 + 导入列表(同归档页刷新语义),与侧栏图标共享缓存。
useEffect(() => {
- let cancelled = false
- fetchPetStatus().then((value) => {
- if (!cancelled)
- setPetStatus(value)
- }).catch((error) => {
- console.error('[dsh-tauri-pet] fetchPetStatus failed:', error)
- })
- return () => {
- cancelled = true
- }
+ void refreshAll()
}, [])
- // 状态里的尺寸被别处(重新拉取/默认值落定)更新时回填滑条。
+ // 状态里的尺寸被别处更新时回填滑条;自己刚提交的值不回拽。
useEffect(() => {
- setSize(statusSize)
+ if (statusSize !== committedSizeRef.current)
+ setSize(statusSize)
}, [statusSize])
- async function toggleEnabled() {
+ async function refreshAll() {
if (busy)
return
setBusy(true)
setErrorMsg(null)
try {
- setPetStatus(await setPetEnabled(!enabled))
+ const [nextStatus, nextList] = await Promise.all([fetchPetStatus(), fetchPetList()])
+ committedSizeRef.current = null
+ setPetStatus(nextStatus)
+ setImported(nextList)
}
catch (error) {
- console.error('[dsh-tauri-pet] setPetEnabled failed:', error)
- setErrorMsg('setEnabledFailed')
+ console.error('[dsh-tauri-pet] refresh failed:', error)
+ setErrorMsg('listFailed')
}
finally {
setBusy(false)
@@ -60,7 +136,7 @@ export function PetSettings(_props: PetSettingsProps) {
}
async function choose(id: string) {
- if (busy || id === status?.active_pet)
+ if (busy || id === activePet)
return
setBusy(true)
setErrorMsg(null)
@@ -76,19 +152,58 @@ export function PetSettings(_props: PetSettingsProps) {
}
}
- /** 拖动条松手(pointerup / keyup)后提交,拖动过程只更新本地回显。 */
- async function commitSize() {
- if (busy || size === statusSize)
+ /** 唤醒/收起宠物:唤醒 = 启用并显示;收起 = 仅隐藏窗口(不改启用设置)。 */
+ async function toggleWindow() {
+ if (busy)
return
setBusy(true)
setErrorMsg(null)
try {
- setPetStatus(await setPetSize(size))
+ if (enabled)
+ await hidePet()
+ else
+ setPetStatus(await setPetEnabled(true))
+ }
+ catch (error) {
+ console.error('[dsh-tauri-pet] toggleWindow failed:', error)
+ setErrorMsg('toggleFailed')
+ }
+ finally {
+ setBusy(false)
+ }
+ }
+
+ /** 滑条实时提交:拖动中每次 change 都落盘并经事件推送窗口即时缩放。 */
+ async function commitSize(value: number) {
+ setErrorMsg(null)
+ try {
+ const nextStatus = await setPetSize(value)
+ committedSizeRef.current = value
+ setPetStatus(nextStatus)
}
catch (error) {
console.error('[dsh-tauri-pet] setPetSize failed:', error)
setErrorMsg('setSizeFailed')
}
+ }
+
+ async function onImportFile(event: ChangeEvent<HTMLInputElement>) {
+ const file = event.target.files?.[0]
+ // 重置 input,让同一文件可重复选择。
+ event.target.value = ''
+ if (!file || busy)
+ return
+ setBusy(true)
+ setErrorMsg(null)
+ try {
+ const data = await readAsBase64(file)
+ await importPet(file.name, data)
+ setImported(await fetchPetList())
+ }
+ catch (error) {
+ console.error('[dsh-tauri-pet] importPet failed:', error)
+ setErrorMsg('importFailed')
+ }
finally {
setBusy(false)
}
@@ -96,67 +211,118 @@ export function PetSettings(_props: PetSettingsProps) {
return (
<div className="dshpet-page">
- <h1 className="dshpet-title">{text('name')}</h1>
-
- <section className="dshpet-card">
- <div className="dshpet-row">
- <span className="dshpet-rowLabel">{text(enabled ? 'enabled' : 'disabled')}</span>
- <button type="button" className={`dshpet-toggle${enabled ? ' on' : ''}`} aria-pressed={enabled} disabled={busy} onClick={() => toggleEnabled()}>
- <span className="dshpet-toggleDot" />
- {enabled ? text('disable') : text('enable')}
+ <div className="dshpet-tabs">
+ <div className="dshpet-tabList">
+ <button type="button" className={tab === 'pets' ? 'dshpet-tabBtn dshpet-tabBtnActive' : 'dshpet-tabBtn'} onClick={() => setTab('pets')}>
+ {text('selectPet')}
+ </button>
+ <button type="button" className={tab === 'codex' ? 'dshpet-tabBtn dshpet-tabBtnActive' : 'dshpet-tabBtn'} onClick={() => setTab('codex')}>
+ Codex
</button>
</div>
- <p className="dshpet-hint">{enabled ? text('enabledHint') : text('disabledHint')}</p>
- </section>
-
- <section className="dshpet-card">
- <div className="dshpet-row">
- <span className="dshpet-rowLabel">{text('sizeLabel')}</span>
- <span className="dshpet-rowValue">
- {size}
- px
- </span>
- </div>
- <input
- type="range"
- className="dshpet-slider"
- min={PET_SIZE_MIN}
- max={PET_SIZE_MAX}
- step={PET_SIZE_STEP}
- value={size}
- disabled={busy}
- aria-label={text('sizeLabel')}
- onChange={event => setSize(Number(event.target.value))}
- onPointerUp={() => {
- void commitSize()
- }}
- onKeyUp={() => {
- void commitSize()
- }}
- />
- <p className="dshpet-hint">{text('sizeHint')}</p>
- </section>
-
- <section className="dshpet-card">
- <div className="dshpet-row">
- <span className="dshpet-rowLabel">{text('selectPet')}</span>
- </div>
- <div className="dshpet-pets">
- {DEFAULT_PETS.map(p => (
- <button key={p.id} type="button" className={`dshpet-petBtn${status?.active_pet === p.id ? ' dshpet-petBtnActive' : ''}`} disabled={busy} onClick={() => choose(p.id)}>
- {p.id === 'codex' ? text('chooseCodex') : p.label}
- </button>
- ))}
+ <div className="dshpet-tabTools">
+ {tab === 'pets'
+ ? (
+ <>
+ <button type="button" className="dshpet-toolBtn" disabled={busy} onClick={() => { void refreshAll() }}>
+ {REFRESH_ICON}
+ {text('refresh')}
+ </button>
+ <button type="button" className="dshpet-toolBtn" disabled title={text('createHint')}>
+ {PLUS_ICON}
+ {text('create')}
+ </button>
+ <button type="button" className="dshpet-toolBtn" disabled={busy} onClick={() => { void toggleWindow() }}>
+ {CHAT_ICON}
+ {text(enabled ? 'collapsePet' : 'wakePet')}
+ </button>
+ </>
+ )
+ : (
+ <>
+ <button type="button" className="dshpet-toolBtn" disabled={busy} onClick={() => { void refreshAll() }}>
+ {REFRESH_ICON}
+ {text('refresh')}
+ </button>
+ <label className="dshpet-toolBtn">
+ {DOWNLOAD_ICON}
+ {text('import')}
+ <input type="file" accept=".zip" hidden disabled={busy} onChange={(event) => { void onImportFile(event) }} />
+ </label>
+ </>
+ )}
</div>
- <p className="dshpet-hint">{text('petWindowHint')}</p>
- </section>
+ </div>
+ <p className="dshpet-tabDesc">{tab === 'pets' ? text('tabInstalledDesc') : text('tabCodexDesc')}</p>
+ <div className="dshpet-divider" role="separator" />
- <section className="dshpet-card">
- <div className="dshpet-actions">
- <button type="button" className="dshpet-btn" onClick={() => { void showPet().catch(error => console.error('[dsh-tauri-pet] showPet failed:', error)) }}>{text('show')}</button>
- <button type="button" className="dshpet-btn" onClick={() => { void hidePet().catch(error => console.error('[dsh-tauri-pet] hidePet failed:', error)) }}>{text('hide')}</button>
- </div>
- </section>
+ {tab === 'pets'
+ ? (
+ <>
+ <div className="dshpet-sizeRow">
+ <span className="dshpet-sizeLabel">{text('sizeLabel')}</span>
+ <input
+ type="range"
+ className="dshpet-sizeSlider"
+ min={PET_SIZE_MIN}
+ max={PET_SIZE_MAX}
+ step={PET_SIZE_STEP}
+ value={size}
+ aria-label={text('sizeLabel')}
+ onChange={(event) => {
+ const value = Number(event.target.value)
+ setSize(value)
+ void commitSize(value)
+ }}
+ />
+ </div>
+ <p className="dshpet-hint">{text('sizeHint')}</p>
+ <div className="dshpet-cards">
+ {DEFAULT_PETS.map(pet => (
+ <PetCard
+ key={pet.id}
+ glyph={pet.id === 'dsh' ? '🐱' : '🐶'}
+ name={text(pet.id === 'dsh' ? 'petNameDsh' : 'petNameCodex')}
+ desc={text(pet.id === 'dsh' ? 'petDescDsh' : 'petDescCodex')}
+ actionLabel={text(activePet === pet.id ? 'selected' : 'select')}
+ actionActive={activePet === pet.id}
+ disabled={busy || activePet === pet.id}
+ onAction={() => { void choose(pet.id) }}
+ />
+ ))}
+ {imported.map(item => (
+ <PetCard
+ key={item.id}
+ glyph="🐾"
+ name={item.name}
+ desc=""
+ actionLabel={text(activePet === item.id ? 'selected' : 'select')}
+ actionActive={activePet === item.id}
+ disabled={busy || activePet === item.id}
+ onAction={() => { void choose(item.id) }}
+ />
+ ))}
+ </div>
+ </>
+ )
+ : (
+ <div className="dshpet-cards">
+ {imported.length === 0
+ ? <div className="dshpet-empty">{text('emptyImported')}</div>
+ : imported.map(item => (
+ <PetCard
+ key={item.id}
+ glyph="🐾"
+ name={item.name}
+ desc=""
+ actionLabel={text('imported')}
+ actionActive
+ disabled
+ onAction={() => {}}
+ />
+ ))}
+ </div>
+ )}
{errorMsg
? <div className="dshpet-error" role="alert">{text(errorMsg)}</div>
diff --git a/packages/dsh-tauri-pet/src/client/constants.ts b/packages/dsh-tauri-pet/src/client/constants.ts
index b8946a53..10f63415 100644
--- a/packages/dsh-tauri-pet/src/client/constants.ts
+++ b/packages/dsh-tauri-pet/src/client/constants.ts
@@ -39,11 +39,15 @@ export const CMD_SET_PET_SIZE = 'set_pet_size'
export const CMD_SHOW_PET = 'show_pet'
/** 隐藏桌宠窗口(不改 enabled)。 */
export const CMD_HIDE_PET = 'hide_pet'
+/** 列出已导入的桌宠资源包(.zip)。 */
+export const CMD_LIST_PETS = 'list_pets'
+/** 导入桌宠资源包(.zip,base64 上传)。 */
+export const CMD_IMPORT_PET = 'import_pet'
-/** 内置可选桌宠列表(可导入 .zip 扩展)。 */
+/** 内置可选桌宠(展示名/描述走 locale;导入包按文件名展示)。 */
export const DEFAULT_PETS = [
- { id: 'codex', label: 'Codex' },
{ id: 'dsh', label: 'Deepseek' },
+ { id: 'codex', label: 'Codex' },
] as const
// ── 侧栏入口 DOM 补丁(参照 dsh-tauri-session 的 workspace-patch 模式)──
@@ -62,12 +66,12 @@ export const PET_SETTINGS_ROW_CLASS = 'dshpet-settingsRow'
export const PET_ICON_RETRY_MS = 500
export const PET_ICON_RETRY_MAX = 30
-// ── 桌宠尺寸(设置页拖动条;区间与 bridge/pet.rs 的 PET_SIZE_* 对齐)──
-/** 精灵图默认显示宽度(逻辑像素)。 */
-export const PET_DEFAULT_SIZE = 160
-/** 拖动条最小值。 */
-export const PET_SIZE_MIN = 96
-/** 拖动条最大值(不超过宠物窗口 240px 宽的可用空间)。 */
-export const PET_SIZE_MAX = 220
-/** 拖动条步进。 */
-export const PET_SIZE_STEP = 4
+// ── 桌宠大小(设置页滑条;百分比模型,与 bridge/pet.rs 的 PET_SIZE_* 对齐)──
+/** 未设置时的默认缩放百分比(100% = 精灵图原始尺寸)。 */
+export const PET_DEFAULT_SIZE = 100
+/** 滑条最小百分比。 */
+export const PET_SIZE_MIN = 50
+/** 滑条最大百分比(窗口尺寸由桌面端按同一百分比实时换算)。 */
+export const PET_SIZE_MAX = 200
+/** 滑条步进(拖动中每次 change 都实时提交)。 */
+export const PET_SIZE_STEP = 5
diff --git a/packages/dsh-tauri-pet/src/client/dom/sidebar-icon.ts b/packages/dsh-tauri-pet/src/client/dom/sidebar-icon.ts
index 9010ad3c..d58e0eb6 100644
--- a/packages/dsh-tauri-pet/src/client/dom/sidebar-icon.ts
+++ b/packages/dsh-tauri-pet/src/client/dom/sidebar-icon.ts
@@ -64,6 +64,10 @@ export function installSidebarPetIcon(): () => void {
const button = createPetIconButton()
/** 当前打过设置行类的宿主(卸载时移除,React 重渲染换宿主时随旧节点废弃)。 */
let rowHost: HTMLElement | undefined
+ /** 上一次做过内联宽度修正的触发器(折叠态/卸载时撤销)。 */
+ let patchedTrigger: HTMLElement | undefined
+ /** 上次修正时触发器是否为折叠态(Rail),状态翻转时需重写内联样式。 */
+ let patchedRail: boolean | undefined
const unsubscribe = subscribePetUi(() => syncIconState(button))
void fetchPetStatus()
@@ -71,19 +75,45 @@ export function installSidebarPetIcon(): () => void {
.catch(error => console.error('[dsh-tauri-pet] fetchPetStatus failed:', error))
syncIconState(button)
+ /**
+ * 把触发器宿主立成 flex 行(复刻新版 dsh 客户端 SettingsRoot 的 triggerRow)。
+ * 除行类 + CSS 规则外再写一份内联样式兜底:CSS 可能被加载顺序/特异性盖过
+ * (表现为图标仍被挤到下一行),而 React 对未声明 style 的节点不会清除外部
+ * 内联样式;折叠态(Rail 圆形按钮)保持定宽,不做拉伸修正。
+ */
+ function applyRowStyles(host: HTMLElement, trigger: HTMLElement): void {
+ const rail = trigger.classList.contains('dsh-tu-settingsTriggerRail')
+ if (host === rowHost && trigger === patchedTrigger && rail === patchedRail)
+ return
+ host.classList.add(PET_SETTINGS_ROW_CLASS)
+ host.style.display = 'flex'
+ host.style.alignItems = 'center'
+ host.style.gap = '8px'
+ host.style.width = '100%'
+ if (rail) {
+ trigger.style.removeProperty('flex')
+ trigger.style.removeProperty('width')
+ trigger.style.removeProperty('min-width')
+ }
+ else {
+ trigger.style.flex = '1 1 auto'
+ trigger.style.width = 'auto'
+ trigger.style.minWidth = '0'
+ }
+ rowHost = host
+ patchedTrigger = trigger
+ patchedRail = rail
+ }
+
/**
* 看护入口按钮:设置触发器就绪且按钮不在其右侧时(首次挂载 / React 重渲染
- * 丢弃)重新插入;同时给宿主容器补 flex 行类——新版 dsh 客户端的
- * SettingsRoot 用 triggerRow(flex 行)承载齿轮与行内图标,旧版是通栏块级
- * 按钮,直接 after 会被挤到下一行,必须由本类把行立起来。
+ * 丢弃)重新插入;同时把触发器宿主立成 flex 行,保证图标与齿轮同行排布。
*/
function ensurePlaced(): void {
const trigger = document.querySelector<HTMLElement>(SETTINGS_TRIGGER_SELECTOR)
if (!trigger?.parentElement)
return
- const host = trigger.parentElement
- host.classList.add(PET_SETTINGS_ROW_CLASS)
- rowHost = host
+ applyRowStyles(trigger.parentElement, trigger)
if (button.isConnected && button.previousElementSibling === trigger)
return
trigger.after(button)
@@ -120,8 +150,21 @@ export function installSidebarPetIcon(): () => void {
observer.disconnect()
unsubscribe()
button.remove()
- rowHost?.classList.remove(PET_SETTINGS_ROW_CLASS)
+ if (rowHost) {
+ rowHost.classList.remove(PET_SETTINGS_ROW_CLASS)
+ rowHost.style.removeProperty('display')
+ rowHost.style.removeProperty('align-items')
+ rowHost.style.removeProperty('gap')
+ rowHost.style.removeProperty('width')
+ }
+ if (patchedTrigger) {
+ patchedTrigger.style.removeProperty('flex')
+ patchedTrigger.style.removeProperty('width')
+ patchedTrigger.style.removeProperty('min-width')
+ }
rowHost = undefined
+ patchedTrigger = undefined
+ patchedRail = undefined
if (timer !== undefined)
clearInterval(timer)
}
diff --git a/packages/dsh-tauri-pet/src/client/locales/index.ts b/packages/dsh-tauri-pet/src/client/locales/index.ts
index 6cab8b2f..26e8feb8 100644
--- a/packages/dsh-tauri-pet/src/client/locales/index.ts
+++ b/packages/dsh-tauri-pet/src/client/locales/index.ts
@@ -1,5 +1,5 @@
/**
- * locales/index.ts — 本插件自有文案(桌宠开关、选择宠物、大小拖动条、提示)。
+ * locales/index.ts — 本插件自有文案(设置页页签/工具栏/宠物卡片/大小滑条/错误)。
* 走 locale 服务的非类型化注册面(register(ns, locale, dict)),zh/en 双语齐备,
* 语言自动跟随宿主 UI;`text()` 支持 `{name}` 插值。
*/
@@ -12,45 +12,59 @@ 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',
- petWindowHint: '桌宠会以独立透明窗口显示在桌面一角,拖动宠物本体即可移动位置',
- enabledHint: '桌宠已启用,正在桌面显示;侧栏入口图标右上角有绿点标识',
- disabledHint: '桌宠未启用',
- loadFailed: '读取桌宠状态失败',
- setEnabledFailed: '切换桌宠状态失败',
+ refresh: '刷新',
+ create: '创建',
+ createHint: '创建宠物即将支持',
+ wakePet: '唤醒宠物',
+ collapsePet: '收起宠物',
+ import: '导入',
+ imported: '已导入',
+ selected: '已选',
+ select: '选择',
+ tabInstalledDesc: '宠物会管理对话串,并突出显示需要关注的事项',
+ tabCodexDesc: '从 Codex 或压缩包中导入 Codex 宠物(支持 .zip 文件)',
+ petNameDsh: '猫咪小助手',
+ petNameCodex: '柴犬阿黄',
+ petDescDsh: '一个聪明友好的虚拟宠物,协助您高效处理日常工作与对话串。',
+ petDescCodex: '忠诚、活泼,能够随时提醒您关注重要事务。',
+ emptyImported: '尚未导入宠物,点击右上角「导入」添加 .zip 资源包',
+ importFailed: '导入宠物失败',
+ listFailed: '读取宠物列表失败',
+ toggleFailed: '切换桌宠窗口失败',
setPetFailed: '选择宠物失败',
setSizeFailed: '设置宠物大小失败',
sizeLabel: '宠物大小',
- sizeHint: '拖动滑条调整宠物显示大小,松手后生效',
+ sizeHint: '拖动滑杆实时调整宠物大小(50%–200%)',
}
/** 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',
- petWindowHint: 'The pet shows in a separate transparent window on the desktop; drag the pet body to move it',
- enabledHint: 'Pet enabled, showing on the desktop; the sidebar entry shows a green dot',
- disabledHint: 'Pet disabled',
- loadFailed: 'Failed to load pet status',
- setEnabledFailed: 'Failed to toggle pet status',
+ refresh: 'Refresh',
+ create: 'Create',
+ createHint: 'Creating pets is coming soon',
+ wakePet: 'Wake pet',
+ collapsePet: 'Collapse pet',
+ import: 'Import',
+ imported: 'Imported',
+ selected: 'Selected',
+ select: 'Choose',
+ tabInstalledDesc: 'Pets manage your conversation threads and highlight items that need attention',
+ tabCodexDesc: 'Import Codex pets from Codex or archives (.zip files supported)',
+ petNameDsh: 'Kitty Assistant',
+ petNameCodex: 'Shiba Ahuang',
+ petDescDsh: 'A smart, friendly virtual pet that helps you handle daily work and threads efficiently.',
+ petDescCodex: 'Loyal and lively, always ready to remind you of what matters.',
+ emptyImported: 'No pets imported yet. Click "Import" in the top right to add a .zip package',
+ importFailed: 'Failed to import pet',
+ listFailed: 'Failed to load pet list',
+ toggleFailed: 'Failed to toggle the pet window',
setPetFailed: 'Failed to select pet',
setSizeFailed: 'Failed to set pet size',
sizeLabel: 'Pet size',
- sizeHint: 'Drag the slider to resize the pet; it takes effect on release',
+ sizeHint: 'Drag the slider to resize the pet in real time (50%–200%)',
}
/** 活跃语言 id(module 级缓存,apply 时初始化并由订阅推进)。 */
diff --git a/packages/dsh-tauri-pet/src/client/service/pet.ts b/packages/dsh-tauri-pet/src/client/service/pet.ts
index 058ceae1..9a490396 100644
--- a/packages/dsh-tauri-pet/src/client/service/pet.ts
+++ b/packages/dsh-tauri-pet/src/client/service/pet.ts
@@ -1,4 +1,4 @@
-import type { PetStatus } from '../types'
+import type { PetListItem, PetStatus } from '../types'
/**
* service/pet.ts — 桌宠 Tauri 命令的桥客户端。
*
@@ -9,9 +9,9 @@ import type { PetStatus } from '../types'
* `#[tauri::command]` 一一对应。
*/
import { invokeBridgedTauri } from 'dsh-tauri/client'
-import { CMD_GET_PET_STATUS, CMD_HIDE_PET, CMD_SET_ACTIVE_PET, CMD_SET_PET_ENABLED, CMD_SET_PET_SIZE, CMD_SHOW_PET } from '../constants'
+import { CMD_GET_PET_STATUS, CMD_HIDE_PET, CMD_IMPORT_PET, CMD_LIST_PETS, CMD_SET_ACTIVE_PET, CMD_SET_PET_ENABLED, CMD_SET_PET_SIZE, CMD_SHOW_PET } from '../constants'
-/** 查询桌宠当前状态(启用与否 + 当前选择)。 */
+/** 查询桌宠当前状态(启用与否 + 当前选择 + 大小百分比)。 */
export function fetchPetStatus(): Promise<PetStatus> {
return invokeBridgedTauri<PetStatus>(CMD_GET_PET_STATUS)
}
@@ -26,7 +26,7 @@ export function setActivePet(id: string): Promise<PetStatus> {
return invokeBridgedTauri<PetStatus>(CMD_SET_ACTIVE_PET, { id })
}
-/** 设置精灵图显示宽度(逻辑像素;拖动条松手时提交)。 */
+/** 设置宠物大小百分比(50–200;拖动条拖动中实时提交)。 */
export function setPetSize(size: number): Promise<PetStatus> {
return invokeBridgedTauri<PetStatus>(CMD_SET_PET_SIZE, { size })
}
@@ -40,3 +40,13 @@ export function showPet(): Promise<void> {
export function hidePet(): Promise<void> {
return invokeBridgedTauri<void>(CMD_HIDE_PET)
}
+
+/** 列出已导入的桌宠资源包(app 数据目录 pets/ 下的 .zip)。 */
+export function fetchPetList(): Promise<PetListItem[]> {
+ return invokeBridgedTauri<PetListItem[]>(CMD_LIST_PETS)
+}
+
+/** 导入桌宠资源包(.zip 文件以 base64 上传,包名取自文件名)。 */
+export function importPet(name: string, data: string): Promise<PetListItem> {
+ return invokeBridgedTauri<PetListItem>(CMD_IMPORT_PET, { name, data })
+}
diff --git a/packages/dsh-tauri-pet/src/client/styles/index.ts b/packages/dsh-tauri-pet/src/client/styles/index.ts
index f2222ed9..a388ba38 100644
--- a/packages/dsh-tauri-pet/src/client/styles/index.ts
+++ b/packages/dsh-tauri-pet/src/client/styles/index.ts
@@ -3,7 +3,10 @@
*
* 侧栏入口按钮复刻官方 `.rtSEdW_iconButton`(appearance/color/border-radius/
* padding/hover/focus-visible 与 data-tip 气泡),并叠加右上角绿色激活圆点;
- * 设置分区沿用 settings.section 的版式语言(卡片 + 行 + 次级文案),全部走
+ * 设置行布局复刻新版 dsh 客户端 SettingsRoot 的 triggerRow(flex 行 + gap,
+ * 齿轮与行内图标同一行)——规则全部拆成单选择器(不依赖 data-slot 包裹层,
+ * 由补丁直接给宿主加 .dshpet-settingsRow 并同步内联样式兜底);
+ * 设置分区遵循 issue #308 规范稿:页签 + 工具栏 + 描述 + 卡片列表,全部走
* `--dsw-alias-*` 主题变量,明暗主题自适应。
*/
import { CssRender } from 'css-render'
@@ -71,111 +74,164 @@ const style = c([
// ── 设置行布局:复刻新版 dsh 客户端 SettingsRoot 的 triggerRow(flex 行)──
// 旧版客户端 sidebar.settings 是通栏块级触发器,图标按钮直接插会被挤到下
- // 一行;把设置槽包裹层立成 flex 行、触发器占满剩余宽度,图标排右侧。
- // 两个钩子并存:renderer 的 data-slot 包裹层(稳定)+ 补丁加的行类(兜底)。
- c('[data-slot="sidebar"] [data-slot="sidebar.settings"], .dshpet-settingsRow', {
+ // 一行;补丁给触发器宿主加 .dshpet-settingsRow(并同步内联 display:flex 兜
+ // 底),触发器占满剩余宽度、图标排右侧,行内 gap 对齐官方排布。
+ c('.dshpet-settingsRow', {
display: 'flex',
alignItems: 'center',
+ gap: '8px',
+ width: '100%',
}),
- c('[data-slot="sidebar"] [data-slot="sidebar.settings"] > .dsh-tu-settingsTrigger:not(.dsh-tu-settingsTriggerRail), .dshpet-settingsRow > .dsh-tu-settingsTrigger:not(.dsh-tu-settingsTriggerRail)', {
+ c('.dshpet-settingsRow > .dsh-tu-settingsTrigger:not(.dsh-tu-settingsTriggerRail)', {
flex: '1 1 auto',
width: 'auto',
minWidth: '0',
}),
- c('[data-slot="sidebar"] [data-slot="sidebar.settings"] > .dshpet-iconButton, .dshpet-settingsRow > .dshpet-iconButton', {
+ c('.dshpet-settingsRow > .dshpet-iconButton', {
flex: 'none',
marginRight: '2px',
}),
- // ── 设置分区(settings.section):卡片 + 行,主题变量自适应 ──
+ // ── 设置分区(settings.section):页签 + 工具栏 + 描述 + 卡片,不自设宽度 ──
c('.dshpet-page', {
display: 'flex',
flexDirection: 'column',
- gap: '16px',
- maxWidth: '560px',
+ gap: '12px',
color: 'var(--dsw-alias-label-primary)',
}),
- c('.dshpet-title', { margin: '0', fontSize: '20px', fontWeight: '600', lineHeight: '28px' }),
- c('.dshpet-card', {
+ c('.dshpet-tabs', {
display: 'flex',
- flexDirection: 'column',
- gap: '10px',
- padding: '14px 16px',
- borderRadius: '12px',
- border: '1px solid var(--dsw-alias-border-weak, rgba(127,127,127,0.2))',
- background: 'var(--dsw-alias-bg-base)',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '12px',
+ flexWrap: 'wrap',
}),
- c('.dshpet-row', { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '8px' }),
- c('.dshpet-rowLabel', { fontWeight: '500', color: 'var(--dsw-alias-label-primary)' }),
- c('.dshpet-rowValue', { color: 'var(--dsw-alias-label-secondary)', fontVariantNumeric: 'tabular-nums' }),
- c('.dshpet-hint', {
- margin: '0',
- fontSize: '12px',
- lineHeight: '18px',
+ c('.dshpet-tabList', { display: 'flex', alignItems: 'center', gap: '4px' }),
+ c('.dshpet-tabBtn', {
+ appearance: 'none',
+ background: '0 0',
+ border: '0',
+ cursor: 'pointer',
+ padding: '6px 12px',
+ borderRadius: '8px',
+ fontSize: '13px',
+ lineHeight: '20px',
color: 'var(--dsw-alias-label-secondary, var(--dsw-alias-label-primary))',
+ }, [
+ c('&:hover', { background: 'var(--dsw-alias-bg-layer-1)' }),
+ ]),
+ c('.dshpet-tabBtn.dshpet-tabBtnActive', {
+ background: 'var(--dsw-alias-bg-layer-1)',
+ color: 'var(--dsw-alias-label-primary)',
+ fontWeight: '600',
}),
- c('.dshpet-slider', {
- width: '100%',
- accentColor: 'var(--dsw-alias-brand-primary)',
+ c('.dshpet-tabTools', { display: 'flex', alignItems: 'center', gap: '6px' }),
+ c('.dshpet-toolBtn', {
+ appearance: 'none',
+ background: '0 0',
+ border: '1px solid var(--dsw-alias-border-weak, rgba(127,127,127,0.2))',
cursor: 'pointer',
- }),
- c('.dshpet-toggle', {
display: 'inline-flex',
alignItems: 'center',
gap: '6px',
padding: '5px 10px',
- borderRadius: '999px',
- cursor: 'pointer',
- border: '1px solid var(--dsw-alias-border-weak, rgba(127,127,127,0.2))',
- background: 'transparent',
- color: 'var(--dsw-alias-label-primary)',
+ borderRadius: '8px',
fontSize: '12px',
+ lineHeight: '18px',
+ color: 'var(--dsw-alias-label-secondary, var(--dsw-alias-label-primary))',
}, [
+ c('&:hover:not(:disabled)', {
+ background: 'var(--dsw-alias-bg-layer-1)',
+ color: 'var(--dsw-alias-label-primary)',
+ }),
c('&:disabled', { opacity: '0.4', cursor: 'default' }),
]),
- c('.dshpet-toggle.on', {
- borderColor: 'var(--dsw-alias-state-success-primary, #3ddc84)',
- color: 'var(--dsw-alias-state-success-primary, #3ddc84)',
+ c('.dshpet-tabDesc', {
+ margin: '0',
+ fontSize: '13px',
+ lineHeight: '20px',
+ color: 'var(--dsw-alias-label-secondary, var(--dsw-alias-label-primary))',
}),
- c('.dshpet-toggleDot', {
- width: '8px',
- height: '8px',
- borderRadius: '50%',
- background: 'var(--dsw-alias-label-tertiary)',
+ c('.dshpet-divider', {
+ border: '0',
+ borderTop: '1px solid var(--dsw-alias-border-weak, rgba(127,127,127,0.2))',
+ }),
+ c('.dshpet-sizeRow', { display: 'flex', alignItems: 'center', gap: '12px' }),
+ c('.dshpet-sizeLabel', { flex: 'none', fontWeight: '500' }),
+ c('.dshpet-sizeSlider', {
+ flex: '1',
+ accentColor: 'var(--dsw-alias-brand-primary)',
+ cursor: 'pointer',
+ }),
+ c('.dshpet-hint', {
+ margin: '0',
+ fontSize: '12px',
+ lineHeight: '18px',
+ color: 'var(--dsw-alias-label-secondary, var(--dsw-alias-label-primary))',
+ }),
+ c('.dshpet-cards', { display: 'flex', flexDirection: 'column', gap: '12px' }),
+ c('.dshpet-cardItem', {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ padding: '12px 14px',
+ borderRadius: '12px',
+ border: '1px solid var(--dsw-alias-border-weak, rgba(127,127,127,0.2))',
+ background: 'var(--dsw-alias-bg-base)',
+ }),
+ c('.dshpet-cardThumb', {
flex: 'none',
+ width: '56px',
+ height: '56px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: '28px',
+ borderRadius: '10px',
+ background: 'var(--dsw-alias-bg-layer-1)',
}),
- c('.dshpet-toggle.on .dshpet-toggleDot', { background: 'var(--dsw-alias-state-success-primary, #3ddc84)' }),
- c('.dshpet-pets', { display: 'flex', gap: '8px' }),
- c('.dshpet-petBtn', {
+ c('.dshpet-cardBody', {
flex: '1',
- padding: '7px 8px',
- borderRadius: '8px',
+ minWidth: '0',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '2px',
+ }),
+ c('.dshpet-cardName', { fontWeight: '600', fontSize: '14px', lineHeight: '20px' }),
+ c('.dshpet-cardDesc', {
+ fontSize: '12px',
+ lineHeight: '18px',
+ color: 'var(--dsw-alias-label-secondary, var(--dsw-alias-label-primary))',
+ }),
+ c('.dshpet-cardAction', {
+ flex: 'none',
+ appearance: 'none',
cursor: 'pointer',
+ padding: '5px 14px',
+ borderRadius: '8px',
border: '1px solid var(--dsw-alias-border-weak, rgba(127,127,127,0.2))',
background: 'transparent',
color: 'var(--dsw-alias-label-primary)',
+ fontSize: '12px',
+ lineHeight: '18px',
}, [
c('&:hover:not(:disabled)', { background: 'var(--dsw-alias-interactive-bg-hover)' }),
c('&:disabled', { opacity: '0.4', cursor: 'default' }),
]),
- c('.dshpet-petBtnActive', {
+ c('.dshpet-cardAction.dshpet-cardActionActive', {
borderColor: 'var(--dsw-alias-brand-primary)',
color: 'var(--dsw-alias-brand-primary)',
background: 'var(--dsw-alias-interactive-bg-hover)',
}),
- c('.dshpet-actions', { display: 'flex', gap: '8px' }),
- c('.dshpet-btn', {
- flex: '1',
- padding: '7px 8px',
- borderRadius: '8px',
- cursor: 'pointer',
- border: '1px solid var(--dsw-alias-border-weak, rgba(127,127,127,0.2))',
- background: 'transparent',
- color: 'var(--dsw-alias-label-primary)',
- }, [
- c('&:hover:not(:disabled)', { background: 'var(--dsw-alias-interactive-bg-hover)' }),
- c('&:disabled', { opacity: '0.4', cursor: 'default' }),
- ]),
+ c('.dshpet-empty', {
+ padding: '24px 16px',
+ textAlign: 'center',
+ fontSize: '13px',
+ lineHeight: '20px',
+ borderRadius: '12px',
+ border: '1px dashed var(--dsw-alias-border-weak, rgba(127,127,127,0.2))',
+ color: 'var(--dsw-alias-label-secondary, var(--dsw-alias-label-primary))',
+ }),
c('.dshpet-error', {
fontSize: '12px',
lineHeight: '18px',
diff --git a/packages/dsh-tauri-pet/src/client/types/index.ts b/packages/dsh-tauri-pet/src/client/types/index.ts
index 2db7615e..e4a3f0c1 100644
--- a/packages/dsh-tauri-pet/src/client/types/index.ts
+++ b/packages/dsh-tauri-pet/src/client/types/index.ts
@@ -4,26 +4,41 @@
export interface PetStatus {
enabled: boolean
active_pet?: string | null
- /** 精灵图显示宽度(逻辑像素);null/缺省 = 未设置,窗口侧用默认值。 */
+ /** 宠物大小百分比(50–200,100 = 精灵图原始尺寸);null/缺省 = 未设置。 */
pet_size?: number | null
}
+/** 已导入的桌宠资源包条目(与桌面端 bridge/pet.rs 的 PetListItem 对齐)。 */
+export interface PetListItem {
+ /** 资源包标志(文件名去 .zip;同时作为 active_pet 的取值)。 */
+ id: string
+ /** 展示名(与 id 相同:导入即以文件名命名)。 */
+ name: string
+}
+
/** 文案键(locale 字典键集合的权威来源)。 */
export type LocaleKey
= | 'name'
- | 'enable'
- | 'disable'
- | 'enabled'
- | 'disabled'
| 'selectPet'
- | 'show'
- | 'hide'
- | 'chooseCodex'
- | 'petWindowHint'
- | 'enabledHint'
- | 'disabledHint'
- | 'loadFailed'
- | 'setEnabledFailed'
+ | 'refresh'
+ | 'create'
+ | 'createHint'
+ | 'wakePet'
+ | 'collapsePet'
+ | 'import'
+ | 'imported'
+ | 'selected'
+ | 'select'
+ | 'tabInstalledDesc'
+ | 'tabCodexDesc'
+ | 'petNameDsh'
+ | 'petNameCodex'
+ | 'petDescDsh'
+ | 'petDescCodex'
+ | 'emptyImported'
+ | 'importFailed'
+ | 'listFailed'
+ | 'toggleFailed'
| 'setPetFailed'
| 'setSizeFailed'
| 'sizeLabel'
diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rs
index 34bbbeb0..a54d7a14 100644
--- a/src-tauri/src/bridge/pet.rs
+++ b/src-tauri/src/bridge/pet.rs
@@ -1,20 +1,32 @@
//! 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_*:`)。
+//! 这些命令被 dsh 容器(iframe 内的 dsh 界面 / dsh-tauri-pet 插件)经 invoke
+//! 桥调用(壳层桥监听模块 `src/hooks/use-iframe-invoke.ts` 把 iframe 的
+//! postMessage invoke 转发到 `@tauri-apps/api/core` 的 `invoke`)。所有状态
+//! 读写统一落在 `config::setting`(持久化)与 `desktop::pet`(窗口)。
+//! 错误遵循仓库约定:`Result<_, String>`,Err 以大写协议前缀开头(如
+//! `PET_SIZE_OUT_OF_RANGE:`)。
+//!
+//! 实时性:一切会改变状态(开关/选择/大小)的命令都通过 `pet://status` 事件
+//! 把最新 PetStatus 推给 pet 窗口——设置页拖动条拖动中实时调整宠物大小就是
+//! 走这条通道;pet 窗口的 get_pet_status 轮询仅作兜底。
use crate::config;
use crate::desktop::pet as pet_window;
+use base64::{engine::general_purpose::STANDARD, Engine};
use serde::{Deserialize, Serialize};
-use tauri::{AppHandle, Manager};
+use std::path::PathBuf;
+use tauri::{AppHandle, Emitter, Manager};
+
+/// 宠物大小百分比合法区间(精灵图缩放 50%–200%,与插件设置页滑条一致)。
+pub const PET_SIZE_MIN: f64 = pet_window::PET_SIZE_MIN_PERCENT;
+pub const PET_SIZE_MAX: f64 = pet_window::PET_SIZE_MAX_PERCENT;
+
+/// 导入桌宠资源包的大小上限(32 MiB)。
+const PET_PACKAGE_MAX_BYTES: usize = 32 * 1024 * 1024;
-/// 桌宠精灵图显示宽度的合法区间(逻辑像素,与设置页滑条一致)。
-pub const PET_SIZE_MIN: f64 = 96.0;
-pub const PET_SIZE_MAX: f64 = 220.0;
+/// 状态变化推送给 pet 窗口的事件名(实时同步大小/选择;轮询兜底)。
+pub const PET_STATUS_EVENT: &str = "pet://status";
/// 桌宠当前状态(设置页与插件读取)。
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -24,11 +36,25 @@ pub struct PetStatus {
pub enabled: bool,
/// 当前选中的桌宠模型包名;None/空 = 未选择(默认宠)。
pub active_pet: Option<String>,
- /// 精灵图显示宽度(逻辑像素);None = 未设置(窗口侧用默认 160)。
+ /// 宠物大小百分比(50–200,100 = 精灵图原始尺寸);None = 未设置(默认 100)。
pub pet_size: Option<f64>,
}
-/// 查询桌宠当前状态(启用与否 + 当前选择的宠物模型 + 显示大小)。
+/// 已导入的桌宠资源包条目(应用数据目录 `pets/` 下的 .zip)。
+#[derive(Debug, Clone, Serialize)]
+pub struct PetListItem {
+ /// 资源包标志(文件名去 .zip;同时作为 active_pet 的取值)。
+ pub id: String,
+ /// 展示名(与 id 相同:导入即以文件名命名)。
+ pub name: String,
+}
+
+/// 把最新状态推送给 pet 窗口(拖动条实时调整大小的主要通道)。
+fn emit_pet_status(app: &AppHandle, status: &PetStatus) {
+ let _ = app.emit_to(pet_window::PET_WINDOW_LABEL, PET_STATUS_EVENT, status.clone());
+}
+
+/// 查询桌宠当前状态(启用与否 + 当前选择的宠物模型 + 显示大小百分比)。
#[tauri::command]
pub fn get_pet_status(app: AppHandle) -> PetStatus {
let setting = config::get_store_dat_setting(&app);
@@ -49,16 +75,18 @@ pub fn set_pet_enabled(app: AppHandle, enabled: bool) -> Result<PetStatus, Strin
// 无论启用还是停用都同步窗口(停用隐藏、启用创建+显示)。
pet_window::sync_pet_window(&app);
- Ok(PetStatus {
+ let status = PetStatus {
enabled: updated.pet_enabled,
active_pet: updated.active_pet.clone(),
pet_size: updated.pet_size,
- })
+ };
+ emit_pet_status(&app, &status);
+ Ok(status)
}
/// 选择桌宠模型包(设置页「选择宠物」),并持久化 active_pet。
///
-/// `id` 为模型包标志(`x.x.x.sprites/` 目录名或用户导入的 .zip 包名)。
+/// `id` 为模型包标志(内置宠 id 或用户导入的 .zip 包名)。
#[tauri::command]
pub fn set_active_pet(app: AppHandle, id: String) -> Result<PetStatus, String> {
let id = id.trim().to_string();
@@ -69,33 +97,39 @@ pub fn set_active_pet(app: AppHandle, id: String) -> Result<PetStatus, String> {
setting.active_pet = Some(id);
});
- Ok(PetStatus {
+ let status = PetStatus {
enabled: updated.pet_enabled,
active_pet: updated.active_pet.clone(),
pet_size: updated.pet_size,
- })
+ };
+ emit_pet_status(&app, &status);
+ Ok(status)
}
-/// 设置桌宠精灵图的显示宽度(设置页拖动条),并持久化 pet_size。
+/// 设置宠物大小百分比(设置页滑条,50–200),并实时同步窗口尺寸。
///
-/// 宠物窗口按逻辑像素轮询读取该值并缩放精灵图;超出合法区间直接拒绝,
-/// 避免把窗口撑爆或缩到不可点按。
+/// 命令在拖动过程中被高频调用:先持久化,再立刻重设已存在窗口的尺寸,并
+/// 经 `pet://status` 事件推给 pet 窗口缩放精灵图;超出合法区间直接拒绝。
#[tauri::command]
pub fn set_pet_size(app: AppHandle, size: f64) -> Result<PetStatus, String> {
if !size.is_finite() || size < PET_SIZE_MIN || size > PET_SIZE_MAX {
return Err(format!(
- "PET_SIZE_OUT_OF_RANGE: pet size must be within {PET_SIZE_MIN}..={PET_SIZE_MAX}"
+ "PET_SIZE_OUT_OF_RANGE: pet size percent must be within {PET_SIZE_MIN}..={PET_SIZE_MAX}"
));
}
let updated = config::update_store_dat_setting(&app, |setting| {
setting.pet_size = Some(size);
});
- Ok(PetStatus {
+ pet_window::apply_pet_size(&app);
+
+ let status = PetStatus {
enabled: updated.pet_enabled,
active_pet: updated.active_pet.clone(),
pet_size: updated.pet_size,
- })
+ };
+ emit_pet_status(&app, &status);
+ Ok(status)
}
/// 显示桌宠窗口(仅当已启用时有效)。
@@ -115,4 +149,81 @@ pub fn hide_pet(app: AppHandle) -> Result<(), String> {
let _ = window.hide();
}
Ok(())
-}
\ No newline at end of file
+}
+
+/// 已导入桌宠资源包目录(`app_data_dir()/pets`,不存在则创建)。
+fn pets_dir(app: &AppHandle) -> Result<PathBuf, String> {
+ let dir = app
+ .path()
+ .app_data_dir()
+ .map_err(|error| format!("PET_DIR_FAILED: failed to resolve app data dir: {error}"))?
+ .join("pets");
+ std::fs::create_dir_all(&dir)
+ .map_err(|error| format!("PET_DIR_FAILED: failed to create pets dir: {error}"))?;
+ Ok(dir)
+}
+
+/// 列出已导入的桌宠资源包(`pets/` 下的 .zip,按包名排序)。
+///
+/// 目录不存在/读取失败时返回空列表(导入面板展示空态而不是报错)。
+#[tauri::command]
+pub fn list_pets(app: AppHandle) -> Vec<PetListItem> {
+ let Ok(dir) = pets_dir(&app) else {
+ return Vec::new();
+ };
+ let Ok(entries) = std::fs::read_dir(&dir) else {
+ return Vec::new();
+ };
+ let mut items: Vec<PetListItem> = entries
+ .flatten()
+ .filter(|entry| {
+ entry
+ .path()
+ .extension()
+ .and_then(|ext| ext.to_str())
+ .is_some_and(|ext| ext.eq_ignore_ascii_case("zip"))
+ })
+ .filter_map(|entry| {
+ let id = entry.path().file_stem()?.to_string_lossy().to_string();
+ Some(PetListItem { name: id.clone(), id })
+ })
+ .collect();
+ items.sort_by(|a, b| a.id.cmp(&b.id));
+ items
+}
+
+/// 导入桌宠资源包(设置页 Codex 页签:.zip 文件 base64 上传后落盘)。
+///
+/// 包名取自文件名(去 .zip),仅允许 ASCII 字母/数字/`-`/`_` 且 ≤ 64 字符,
+/// 防路径注入;同名包已存在时拒绝(PET_ALREADY_IMPORTED)。
+#[tauri::command]
+pub fn import_pet(app: AppHandle, name: String, data: String) -> Result<PetListItem, String> {
+ let name = name.trim().trim_end_matches(".zip").trim().to_string();
+ let valid = !name.is_empty()
+ && name.len() <= 64
+ && name
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
+ if !valid {
+ return Err(
+ "PET_NAME_INVALID: pet name must be 1..=64 ascii letters/digits/-/_".to_string(),
+ );
+ }
+ let bytes = STANDARD
+ .decode(data.as_bytes())
+ .map_err(|error| format!("PET_PACKAGE_DECODE_FAILED: invalid base64 payload: {error}"))?;
+ if bytes.len() > PET_PACKAGE_MAX_BYTES {
+ return Err(format!(
+ "PET_PACKAGE_TOO_LARGE: pet package must not exceed {PET_PACKAGE_MAX_BYTES} bytes"
+ ));
+ }
+ let dir = pets_dir(&app)?;
+ let target = dir.join(format!("{name}.zip"));
+ if target.exists() {
+ return Err(format!("PET_ALREADY_IMPORTED: pet package {name} already exists"));
+ }
+ std::fs::write(&target, bytes).map_err(|error| {
+ format!("PET_PACKAGE_WRITE_FAILED: failed to write pet package: {error}")
+ })?;
+ Ok(PetListItem { id: name.clone(), name })
+}
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index deebd567..4dfc883d 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -578,6 +578,8 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::set_pet_size,
crate::bridge::show_pet,
crate::bridge::hide_pet,
+ crate::bridge::list_pets,
+ crate::bridge::import_pet,
]
}
diff --git a/src-tauri/src/desktop/pet.rs b/src-tauri/src/desktop/pet.rs
index e1b13bdc..9cf6a0b2 100644
--- a/src-tauri/src/desktop/pet.rs
+++ b/src-tauri/src/desktop/pet.rs
@@ -28,11 +28,19 @@ 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;
+/// 精灵图基准尺寸(dsh-pet 呆味预览帧 220x124,透明 PNG)。
+pub const PET_SPRITE_BASE_WIDTH: f64 = 220.0;
+pub const PET_SPRITE_BASE_HEIGHT: f64 = 124.0;
+/// 窗口相对精灵图的四周留白(逻辑像素):横向 32、纵向 40(含浮动/阴影余量)。
+const PET_WINDOW_PAD_X: f64 = 32.0;
+const PET_WINDOW_PAD_Y: f64 = 40.0;
+/// 宠物大小百分比合法区间(设置页滑条 50%–200%;bridge/pet.rs 引用同一常量)。
+pub const PET_SIZE_MIN_PERCENT: f64 = 50.0;
+pub const PET_SIZE_MAX_PERCENT: f64 = 200.0;
+/// 未设置 pet_size 时的默认缩放(100% = 精灵图原始尺寸)。
+pub const PET_SIZE_DEFAULT_PERCENT: f64 = 100.0;
-/// 持久化的桌宠窗口位置(仅记录位置;大小固定为 PET_WINDOW_* 尺寸不随用户变化)。
+/// 持久化的桌宠窗口位置(仅记录位置;大小由设置页 pet_size 百分比实时推导)。
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PetWindowPosition {
@@ -97,6 +105,32 @@ pub fn save_pet_window_geometry<R: Runtime>(window: &Window<R>) {
);
}
+/// 读取宠物大小百分比(设置持久化值;缺省回落默认,越界收敛进合法区间)。
+pub fn get_pet_size_percent<R: Runtime>(app: &AppHandle<R>) -> f64 {
+ crate::config::get_store_dat_setting(app)
+ .pet_size
+ .unwrap_or(PET_SIZE_DEFAULT_PERCENT)
+ .clamp(PET_SIZE_MIN_PERCENT, PET_SIZE_MAX_PERCENT)
+}
+
+/// 由百分比换算桌宠窗口逻辑尺寸:精灵图基准尺寸 × 缩放 + 四周留白。
+pub fn pet_window_logical_size(percent: f64) -> (f64, f64) {
+ let scale = percent / 100.0;
+ (
+ (PET_SPRITE_BASE_WIDTH * scale) + PET_WINDOW_PAD_X,
+ (PET_SPRITE_BASE_HEIGHT * scale) + PET_WINDOW_PAD_Y,
+ )
+}
+
+/// 实时应用宠物大小:窗口已存在时直接重设尺寸(设置页拖动条拖动中实时调用)。
+pub fn apply_pet_size<R: Runtime>(app: &AppHandle<R>) {
+ let Some(window) = app.get_webview_window(PET_WINDOW_LABEL) else {
+ return;
+ };
+ let (width, height) = pet_window_logical_size(get_pet_size_percent(app));
+ let _ = window.set_size(tauri::LogicalSize::new(width, height));
+}
+
/// 确保桌宠窗口存在并恢复位置。
///
/// 幂等:已注册时直接复用返回;首次调用时创建 `pet` 窗口并恢复上一次保存的
@@ -106,11 +140,12 @@ pub fn ensure_pet_window<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<Webvie
return Ok(window);
}
let app_handle = app.clone();
+ let (width, height) = pet_window_logical_size(get_pet_size_percent(app));
// 非 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)
+ .inner_size(width, height)
.resizable(false)
.maximizable(false)
.transparent(true)
@@ -163,9 +198,11 @@ fn position_on_any_monitor<R: Runtime>(window: &WebviewWindow<R>, x: i32, y: i32
let Ok(monitors) = app.available_monitors() else {
return false;
};
- // 以窗口自身的物理尺寸近似命中矩形,允许窗口底部/右侧探出一点点也不误判。
- let w = (PET_WINDOW_WIDTH * window.scale_factor().unwrap_or(1.0)) as i32;
- let h = (PET_WINDOW_HEIGHT * window.scale_factor().unwrap_or(1.0)) as i32;
+ // 以当前设置的窗口逻辑尺寸 × 缩放系数近似命中矩形,允许窗口底部/右侧
+ // 探出一点点也不误判。
+ let (lw, lh) = pet_window_logical_size(get_pet_size_percent(window.app_handle()));
+ let w = (lw * window.scale_factor().unwrap_or(1.0)) as i32;
+ let h = (lh * window.scale_factor().unwrap_or(1.0)) as i32;
let hit_left = x;
let hit_top = y;
let hit_right = x + w;
@@ -188,9 +225,10 @@ fn place_pet_at_default<R: Runtime>(window: &WebviewWindow<R>) {
};
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;
+ // 距屏幕右下角 32px 的物理偏移;尺寸 = 当前设置逻辑尺寸 × 屏幕缩放系数。
+ let (lw, lh) = pet_window_logical_size(get_pet_size_percent(app));
+ let w = (lw * monitor.scale_factor()) as i32;
+ let h = (lh * 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)));
@@ -247,4 +285,12 @@ mod tests {
let default = PetWindowPosition::default();
assert!(default.x.is_none() && default.y.is_none());
}
+
+ #[test]
+ fn pet_window_logical_size_scales_with_percent() {
+ // 100% = 精灵图原始尺寸 + 留白;50% / 200% 线性缩放。
+ assert_eq!(pet_window_logical_size(100.0), (252.0, 164.0));
+ assert_eq!(pet_window_logical_size(50.0), (142.0, 102.0));
+ assert_eq!(pet_window_logical_size(200.0), (472.0, 288.0));
+ }
}
\ No newline at end of file
diff --git a/src/hooks/use-iframe-invoke.ts b/src/hooks/use-iframe-invoke.ts
index 7456b367..a17c2daa 100644
--- a/src/hooks/use-iframe-invoke.ts
+++ b/src/hooks/use-iframe-invoke.ts
@@ -41,6 +41,8 @@ const ALLOWED_INVOKE_CMDS = new Set([
'set_pet_size',
'show_pet',
'hide_pet',
+ 'list_pets',
+ 'import_pet',
])
export function useIframeInvoke(iframeRef: RefObject<HTMLIFrameElement | null>): void {
diff --git a/src/pet/pet.css b/src/pet/pet.css
index df8571d2..1e60b9ec 100644
--- a/src/pet/pet.css
+++ b/src/pet/pet.css
@@ -1,7 +1,7 @@
/* 桌宠外置窗口样式:透明画布 + dsh-pet 精灵图。
窗口本身 transparent=true(无边框、无阴影、跳过任务栏),因此 body 全透明,
- 只绘制宠物主体。窗口尺寸由 Rust 侧 PET_WINDOW_WIDTH/HEIGHT(240x280)给定。
- 只有宠物本体(.pet-canvas,宽度 = 设置的 pet_size)是拖动区域;stage 负责居中。 */
+ 只绘制宠物主体。窗口尺寸由 Rust 侧按 pet_size 百分比换算(基准 220x124 +
+ 留白)给定并实时重设。只有宠物本体(.pet-canvas)是拖动区域;stage 负责居中。 */
html,
body {
diff --git a/src/pet/pet.tsx b/src/pet/pet.tsx
index 40c7ea13..b4e6a270 100644
--- a/src/pet/pet.tsx
+++ b/src/pet/pet.tsx
@@ -1,4 +1,5 @@
import { invoke } from '@tauri-apps/api/core'
+import { listen } from '@tauri-apps/api/event'
import { useEffect, useState } from 'react'
import petSpriteUrl from './assets/dsh-pet-idle.png'
@@ -9,9 +10,10 @@ import petSpriteUrl from './assets/dsh-pet-idle.png'
* 尺寸一致(`data-tauri-drag-region` 挂在精灵图容器上,而不是整个窗口),
* 隐藏桌宠统一走插件侧 `hide_pet` 命令(在设置页操作)。
*
- * 精灵图取自 dsh-pet(PC2005-cloud/dsh-pet)呆味预览图第一帧,透明 PNG,
- * 窗口侧仅做轻量「呼吸/浮动」自绘动画(符合「只借静态精灵图,窗口自绘动画」)。
- * 显示宽度来自设置页拖动条持久化的 `pet_size`(轮询 get_pet_status 同步)。
+ * 大小模型:`pet_size` 是百分比(50–200,100 = 精灵图原始尺寸 220x124)。
+ * 实时通道:桌面端在开关/选择/大小变化时 emit `pet://status` 事件,本窗口
+ * 监听后立即缩放精灵图(拖动条拖动中即时生效);get_pet_status 轮询仅兜底。
+ * 窗口自身尺寸由 Rust 侧按同一百分比换算(desktop::pet::apply_pet_size)。
* 该窗口是 Tauri 顶层 webview(非 iframe),可直接 `import { invoke }`。
*/
@@ -21,13 +23,38 @@ interface PetStatus {
pet_size?: number | null
}
-/** 未设置 pet_size 时的默认显示宽度(与插件侧 PET_DEFAULT_SIZE 对齐)。 */
-const PET_DEFAULT_SIZE = 160
+/** 精灵图基准宽度(dsh-pet 呆味帧 220x124;与 desktop/pet.rs 常量对齐)。 */
+const PET_SPRITE_BASE_WIDTH = 220
+/** 未设置 pet_size 时的默认缩放百分比(与 bridge/pet.rs 默认对齐)。 */
+const PET_DEFAULT_SIZE_PERCENT = 100
+/** 桌面端实时推送的状态事件(与 bridge/pet.rs PET_STATUS_EVENT 对齐)。 */
+const PET_STATUS_EVENT = 'pet://status'
const PET_STATUS_POLL_MS = 1500
export function PetWindow() {
- const [petSize, setPetSize] = useState<number>(PET_DEFAULT_SIZE)
+ const [petSizePercent, setPetSizePercent] = useState<number>(PET_DEFAULT_SIZE_PERCENT)
+ // 实时通道:桌面端每次状态变化(含拖动中的 set_pet_size)都会推送事件。
+ useEffect(() => {
+ let cancelled = false
+ let dispose: (() => void) | undefined
+ void listen<PetStatus>(PET_STATUS_EVENT, (event) => {
+ if (!cancelled)
+ setPetSizePercent(event.payload.pet_size ?? PET_DEFAULT_SIZE_PERCENT)
+ }).then((unlisten) => {
+ // 订阅建立前组件已卸载时立即退订,避免泄漏。
+ if (cancelled)
+ unlisten()
+ else
+ dispose = unlisten
+ })
+ return () => {
+ cancelled = true
+ dispose?.()
+ }
+ }, [])
+
+ // 兜底轮询:事件丢失/旧版桌面端未推送时也能同步到最新设置。
useEffect(() => {
let cancelled = false
@@ -35,7 +62,7 @@ export function PetWindow() {
try {
const status = await invoke<PetStatus>('get_pet_status')
if (!cancelled)
- setPetSize(status.pet_size ?? PET_DEFAULT_SIZE)
+ setPetSizePercent(status.pet_size ?? PET_DEFAULT_SIZE_PERCENT)
}
catch (error) {
console.error('[pet] get_pet_status failed:', error)
@@ -43,7 +70,6 @@ export function PetWindow() {
}
void refresh()
- // 设置页调整大小/切换宠物后轮询同步,避免展示陈旧设置。
const timer = window.setInterval(refresh, PET_STATUS_POLL_MS)
return () => {
cancelled = true
@@ -51,10 +77,16 @@ export function PetWindow() {
}
}, [])
+ // 拖动区域 = 宠物本体:宽度 = 基准尺寸 × 百分比,高度随精灵图比例。
return (
<div className="pet-stage">
- {/* 拖动区域 = 宠物本体:宽度即 pet_size,高度随精灵图比例 */}
- <div className="pet-canvas" data-tauri-drag-region role="img" aria-label="DeepSeek Harness pet" style={{ width: `${petSize}px` }}>
+ <div
+ className="pet-canvas"
+ data-tauri-drag-region
+ role="img"
+ aria-label="DeepSeek Harness pet"
+ style={{ width: `${(PET_SPRITE_BASE_WIDTH * petSizePercent) / 100}px` }}
+ >
<img className="pet-sprite" src={petSpriteUrl} alt="" draggable={false} decoding="async" />
</div>
</div>