Skip to content

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

fix(pet): 桌宠状态气泡跟随 DSH 语言 (#1223)

Hairy6169d3e81fd6
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 78e8b676..899d6b65 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -98,6 +98,66 @@
"menu.open_folder": "Open Folder",
"pet.show_main_window": "Show Main Window",
"pet.close": "Close Pet",
+ "pet.unavailable": "Pet “{{id}}” is unavailable — pick another one in Settings → Pets",
+ "pet.bubble.untitled": "New session",
+ "pet.bubble.approval": "Needs approval",
+ "pet.bubble.choice": "Needs your input",
+ "pet.bubble.subagent": "Subagent",
+ "pet.bubble.thought": "Thought",
+ "pet.bubble.tool": "Tool",
+ "pet.bubble.task": "Working on “{{task}}”",
+ "pet.bubble.failed": "Failed: {{error}}",
+ "pet.bubble.done": "Done",
+ "pet.bubble.status.thinking.0": "Analyzing information",
+ "pet.bubble.status.thinking.1": "Thinking",
+ "pet.bubble.status.thinking.2": "Organizing results",
+ "pet.bubble.status.working.0": "Processing task",
+ "pet.bubble.status.working.1": "Step in progress",
+ "pet.bubble.status.working.2": "System is working",
+ "pet.bubble.status.result.0": "Organizing results",
+ "pet.bubble.status.result.1": "Step completed, preparing for next step",
+ "pet.bubble.status.result.2": "Confirming next action",
+ "pet.bubble.status.waiting.0": "Awaiting your confirmation",
+ "pet.bubble.status.waiting.1": "Requires your input",
+ "pet.bubble.status.waiting.2": "Please decide on the next step",
+ "pet.bubble.status.approval.0": "Awaiting your approval",
+ "pet.bubble.status.approval.1": "Authorization required",
+ "pet.bubble.status.approval.2": "Please confirm and authorize this action",
+ "pet.bubble.status.success.0": "Task completed successfully",
+ "pet.bubble.status.success.1": "Current phase completed",
+ "pet.bubble.status.success.2": "Execution succeeded",
+ "pet.bubble.status.running.0": "Task is running",
+ "pet.bubble.status.running.1": "Current step is processing",
+ "pet.bubble.status.review.0": "Consolidating",
+ "pet.bubble.status.review.1": "Ready for your review",
+ "pet.bubble.status.failed.0": "Step execution failed",
+ "pet.bubble.status.failed.1": "An error occurred during operation",
+ "pet.bubble.status.error.0": "Task encountered an error",
+ "pet.bubble.status.error.1": "Exception detected, please check",
+ "pet.bubble.status.error.2": "Process failed to complete",
+ "pet.bubble.status.stopped.0": "Task terminated",
+ "pet.bubble.status.stopped.1": "Task paused at this stage",
+ "pet.bubble.activity.searching.0": "Searching",
+ "pet.bubble.activity.searching.1": "Searching across the project",
+ "pet.bubble.activity.searching.2": "Checking related files",
+ "pet.bubble.activity.editing.0": "Editing",
+ "pet.bubble.activity.editing.1": "Applying changes",
+ "pet.bubble.activity.editing.2": "Adjusting implementation",
+ "pet.bubble.activity.testing.0": "Verifying",
+ "pet.bubble.activity.testing.1": "Running test suites",
+ "pet.bubble.activity.testing.2": "Verifying changes",
+ "pet.bubble.activity.commanding.0": "Executing",
+ "pet.bubble.activity.commanding.1": "Starting project services",
+ "pet.bubble.activity.commanding.2": "Monitoring command execution",
+ "pet.bubble.tool.read": "Read",
+ "pet.bubble.tool.read_image": "View image",
+ "pet.bubble.tool.write": "Write",
+ "pet.bubble.tool.edit": "Edit",
+ "pet.bubble.tool.str_replace_editor": "Edit",
+ "pet.bubble.tool.web_search": "Search",
+ "pet.bubble.tool.web_fetch": "Fetch",
+ "pet.bubble.tool.think": "Think",
+ "pet.bubble.tool.skill": "Skill",
"menu.close": "Close",
"menu.quit": "Quit",
"menu.documentation": "Documentation",
diff --git a/src/i18n/locales/ko-KR.json b/src/i18n/locales/ko-KR.json
index e54d6982..678f1b1c 100644
--- a/src/i18n/locales/ko-KR.json
+++ b/src/i18n/locales/ko-KR.json
@@ -98,6 +98,66 @@
"menu.open_folder": "폴더 열기",
"pet.show_main_window": "기본 창 표시",
"pet.close": "펫 닫기",
+ "pet.unavailable": "펫 「{{id}}」의 리소스를 사용할 수 없습니다. 설정 → 펫에서 다시 선택해 주세요.",
+ "pet.bubble.untitled": "새 세션",
+ "pet.bubble.approval": "승인 필요",
+ "pet.bubble.choice": "입력 필요",
+ "pet.bubble.subagent": "하위 에이전트",
+ "pet.bubble.thought": "생각",
+ "pet.bubble.tool": "도구",
+ "pet.bubble.task": "「{{task}}」 처리 중",
+ "pet.bubble.failed": "실패: {{error}}",
+ "pet.bubble.done": "완료",
+ "pet.bubble.status.thinking.0": "정보 분석 중",
+ "pet.bubble.status.thinking.1": "생각 중",
+ "pet.bubble.status.thinking.2": "결과 정리 중",
+ "pet.bubble.status.working.0": "작업 처리 중",
+ "pet.bubble.status.working.1": "단계 진행 중",
+ "pet.bubble.status.working.2": "시스템 작업 중",
+ "pet.bubble.status.result.0": "결과 정리 중",
+ "pet.bubble.status.result.1": "단계 완료, 다음 단계 준비 중",
+ "pet.bubble.status.result.2": "다음 작업 확인 중",
+ "pet.bubble.status.waiting.0": "확인 대기 중",
+ "pet.bubble.status.waiting.1": "입력이 필요합니다",
+ "pet.bubble.status.waiting.2": "다음 작업을 선택해 주세요",
+ "pet.bubble.status.approval.0": "승인 대기 중",
+ "pet.bubble.status.approval.1": "권한 승인이 필요합니다",
+ "pet.bubble.status.approval.2": "이 작업을 확인하고 승인해 주세요",
+ "pet.bubble.status.success.0": "작업 완료",
+ "pet.bubble.status.success.1": "현재 단계 완료",
+ "pet.bubble.status.success.2": "실행 성공",
+ "pet.bubble.status.running.0": "작업 실행 중",
+ "pet.bubble.status.running.1": "현재 단계 처리 중",
+ "pet.bubble.status.review.0": "변경 사항 정리 중",
+ "pet.bubble.status.review.1": "검토 준비 완료",
+ "pet.bubble.status.failed.0": "단계 실행 실패",
+ "pet.bubble.status.failed.1": "작업 중 오류 발생",
+ "pet.bubble.status.error.0": "작업 오류 발생",
+ "pet.bubble.status.error.1": "오류를 확인해 주세요",
+ "pet.bubble.status.error.2": "작업을 완료하지 못했습니다",
+ "pet.bubble.status.stopped.0": "작업 종료됨",
+ "pet.bubble.status.stopped.1": "현재 단계에서 일시 중지됨",
+ "pet.bubble.activity.searching.0": "검색 중",
+ "pet.bubble.activity.searching.1": "프로젝트 전체 검색 중",
+ "pet.bubble.activity.searching.2": "관련 파일 확인 중",
+ "pet.bubble.activity.editing.0": "수정 중",
+ "pet.bubble.activity.editing.1": "변경 사항 적용 중",
+ "pet.bubble.activity.editing.2": "구현 조정 중",
+ "pet.bubble.activity.testing.0": "검증 중",
+ "pet.bubble.activity.testing.1": "테스트 실행 중",
+ "pet.bubble.activity.testing.2": "변경 사항 검증 중",
+ "pet.bubble.activity.commanding.0": "실행 중",
+ "pet.bubble.activity.commanding.1": "프로젝트 서비스 시작 중",
+ "pet.bubble.activity.commanding.2": "명령 실행 상태 확인 중",
+ "pet.bubble.tool.read": "읽기",
+ "pet.bubble.tool.read_image": "이미지 보기",
+ "pet.bubble.tool.write": "쓰기",
+ "pet.bubble.tool.edit": "편집",
+ "pet.bubble.tool.str_replace_editor": "편집",
+ "pet.bubble.tool.web_search": "검색",
+ "pet.bubble.tool.web_fetch": "가져오기",
+ "pet.bubble.tool.think": "생각",
+ "pet.bubble.tool.skill": "스킬",
"menu.close": "닫기",
"menu.quit": "종료",
"menu.documentation": "문서",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 9b922dda..36f44fe7 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -98,6 +98,66 @@
"menu.open_folder": "打开文件夹",
"pet.show_main_window": "显示主界面",
"pet.close": "关闭宠物",
+ "pet.unavailable": "宠物「{{id}}」的资源不可用,请在 设置 → 宠物 中重新选择",
+ "pet.bubble.untitled": "新会话",
+ "pet.bubble.approval": "需授权",
+ "pet.bubble.choice": "需选择",
+ "pet.bubble.subagent": "子代理",
+ "pet.bubble.thought": "思考",
+ "pet.bubble.tool": "工具调用",
+ "pet.bubble.task": "正在处理「{{task}}」",
+ "pet.bubble.failed": "失败:{{error}}",
+ "pet.bubble.done": "已完成",
+ "pet.bubble.status.thinking.0": "正在分析",
+ "pet.bubble.status.thinking.1": "思考中",
+ "pet.bubble.status.thinking.2": "整理结果中",
+ "pet.bubble.status.working.0": "正在处理任务",
+ "pet.bubble.status.working.1": "步骤正在进行中",
+ "pet.bubble.status.working.2": "系统运行中",
+ "pet.bubble.status.result.0": "正在整理结果",
+ "pet.bubble.status.result.1": "步骤已完成,准备下一步",
+ "pet.bubble.status.result.2": "正在确认后续操作",
+ "pet.bubble.status.waiting.0": "等待确认",
+ "pet.bubble.status.waiting.1": "需提供后续指令",
+ "pet.bubble.status.waiting.2": "请决策下一步操作",
+ "pet.bubble.status.approval.0": "等待审批",
+ "pet.bubble.status.approval.1": "需授权确认",
+ "pet.bubble.status.approval.2": "敏感操作确认授权",
+ "pet.bubble.status.success.0": "任务已完成",
+ "pet.bubble.status.success.1": "本阶段任务已完成",
+ "pet.bubble.status.success.2": "流程执行成功",
+ "pet.bubble.status.running.0": "任务运行中",
+ "pet.bubble.status.running.1": "当前步骤正在处理",
+ "pet.bubble.status.review.0": "正在汇总变更",
+ "pet.bubble.status.review.1": "变更已就绪,等待审阅",
+ "pet.bubble.status.failed.0": "步骤执行失败",
+ "pet.bubble.status.failed.1": "操作执行过程中发生异常",
+ "pet.bubble.status.error.0": "任务发生错误",
+ "pet.bubble.status.error.1": "出现异常,请进行排查",
+ "pet.bubble.status.error.2": "流程未能成功",
+ "pet.bubble.status.stopped.0": "任务已终止",
+ "pet.bubble.status.stopped.1": "任务已在此处暂停",
+ "pet.bubble.activity.searching.0": "正在检索",
+ "pet.bubble.activity.searching.1": "正在项目中进行全面搜索",
+ "pet.bubble.activity.searching.2": "正在调阅相关文件",
+ "pet.bubble.activity.editing.0": "正在修改",
+ "pet.bubble.activity.editing.1": "正在写入变更内容",
+ "pet.bubble.activity.editing.2": "正在调整代码实现",
+ "pet.bubble.activity.testing.0": "正在检验",
+ "pet.bubble.activity.testing.1": "正在运行测试集进行确认",
+ "pet.bubble.activity.testing.2": "正在验证变更有效性",
+ "pet.bubble.activity.commanding.0": "正在执行",
+ "pet.bubble.activity.commanding.1": "正在启动项目服务",
+ "pet.bubble.activity.commanding.2": "正在监控指令执行状态",
+ "pet.bubble.tool.read": "读取",
+ "pet.bubble.tool.read_image": "看图",
+ "pet.bubble.tool.write": "写入",
+ "pet.bubble.tool.edit": "编辑",
+ "pet.bubble.tool.str_replace_editor": "编辑",
+ "pet.bubble.tool.web_search": "搜索",
+ "pet.bubble.tool.web_fetch": "抓取",
+ "pet.bubble.tool.think": "思考",
+ "pet.bubble.tool.skill": "技能",
"menu.close": "关闭",
"menu.quit": "退出",
"menu.documentation": "文档",
diff --git a/src/pet/hooks/use-bubble-tracker.constants.ts b/src/pet/hooks/use-bubble-tracker.constants.ts
index 066c9d95..2e6024ec 100644
--- a/src/pet/hooks/use-bubble-tracker.constants.ts
+++ b/src/pet/hooks/use-bubble-tracker.constants.ts
@@ -1,47 +1,21 @@
import type { Motion } from 'dsh-pet-component'
-/** 桌宠窗口无 i18n 基础设施,就地按窗口语言取单语文案。 */
-export const IS_ZH = (typeof document !== 'undefined' ? document.documentElement.lang || navigator.language : 'zh-CN')
- .toLowerCase()
- .startsWith('zh')
-
-/** 语言二选一助手,降低代码冗余 */
-export const pickLang = <T>(zh: T, en: T): T => (IS_ZH ? zh : en)
-
-/** 会话标题兜底文案 */
-export const UNTITLED_SESSION_TITLE = pickLang('新会话', 'New session')
-
-/** 会话标题前缀 */
-export const SESSION_LABELS = {
- subagent: pickLang('子代理', 'Subagent'),
- waitApproval: pickLang('需授权', 'Needs approval'),
- waitChoice: pickLang('需选择', 'Needs your input'),
-} as const
-
-/** 气泡文案库(按组多备选句) */
-export const STATUS_COPY: Record<string, readonly string[]> = {
- thinking: pickLang(['正在分析', '思考中', '整理结果中'], ['Analyzing information', 'Thinking', 'Organizing results']),
- working: pickLang(['正在处理任务', '步骤正在进行中', '系统运行中'], ['Processing task', 'Step in progress', 'System is working']),
- result: pickLang(['正在整理结果', '步骤已完成,准备下一步', '正在确认后续操作'], ['Organizing results', 'Step completed, preparing for next step', 'Confirming next action']),
- waiting: pickLang(['等待确认', '需提供后续指令', '请决策下一步操作'], ['Awaiting your confirmation', 'Requires your input', 'Please decide on the next step']),
- approval: pickLang(['等待审批', '需授权确认', '敏感操作确认授权'], ['Awaiting your approval', 'Authorization required', 'Please confirm and authorize this action']),
- success: pickLang(['任务已完成', '本阶段任务已完成', '流程执行成功'], ['Task completed successfully', 'Current phase completed', 'Execution succeeded']),
- running: pickLang(['任务运行中', '当前步骤正在处理'], ['Task is running', 'Current step is processing']),
- review: pickLang(['正在汇总变更', '变更已就绪,等待审阅'], ['Consolidating', 'Ready for your review']),
- failed: pickLang(['步骤执行失败', '操作执行过程中发生异常'], ['Step execution failed', 'An error occurred during operation']),
- error: pickLang(['任务发生错误', '出现异常,请进行排查', '流程未能成功'], ['Task encountered an error', 'Exception detected, please check', 'Process failed to complete']),
- stopped: pickLang(['任务已终止', '任务已在此处暂停'], ['Task terminated', 'Task paused at this stage']),
-} as const
+export const STATUS_COPY: Record<string, number> = {
+ thinking: 3,
+ working: 3,
+ result: 3,
+ waiting: 3,
+ approval: 3,
+ success: 3,
+ running: 2,
+ review: 2,
+ failed: 2,
+ error: 3,
+ stopped: 2,
+}
-/** 工具活动分类文案 */
-export const ACTIVITY_COPY: Record<string, readonly string[]> = {
- searching: pickLang(['正在检索', '正在项目中进行全面搜索', '正在调阅相关文件'], ['Searching', 'Searching across the project', 'Checking related files']),
- editing: pickLang(['正在修改', '正在写入变更内容', '正在调整代码实现'], ['Editing', 'Applying changes', 'Adjusting implementation']),
- testing: pickLang(['正在检验', '正在运行测试集进行确认', '正在验证变更有效性'], ['Verifying', 'Running test suites', 'Verifying changes']),
- commanding: pickLang(['正在执行', '正在启动项目服务', '正在监控指令执行状态'], ['Executing', 'Starting project services', 'Monitoring command execution']),
-} as const
+export const ACTIVITY_COPY = new Set(['searching', 'editing', 'testing', 'commanding'])
-/** 状态与动画分类集合 */
export const DONE_BUBBLE_TIMEOUT = 3000
export const TERMINAL_MOTIONS = new Set<Motion>(['failed', 'review', 'error', 'success'])
export const WORK_STATUSES = new Set(['thinking', 'working', 'result', 'waiting', 'success', 'error'])
@@ -52,17 +26,10 @@ export const TOOL_LABELS: Record<string, string> = {
bash: 'Bash',
grep: 'Grep',
glob: 'Glob',
- read: '读取',
- read_image: '看图',
- write: '写入',
- edit: '编辑',
- str_replace_editor: '编辑',
- web_search: '搜索',
- web_fetch: '抓取',
- think: '思考',
- skill: '技能',
}
+export const TRANSLATED_TOOLS = new Set(['read', 'read_image', 'write', 'edit', 'str_replace_editor', 'web_search', 'web_fetch', 'think', 'skill'])
+
export const TOOL_ARG_KEYS: Record<string, readonly string[]> = {
pwsh: ['command'],
bash: ['command'],
@@ -85,15 +52,3 @@ export const TOOL_PATTERNS: Array<[RegExp, string]> = [
[/test|check|lint|build|verify/, 'testing'],
[/shell|bash|exec|command|terminal|powershell|pwsh/, 'commanding'],
]
-
-export const STATUS_TEXT_MAP: Record<string, string> = {
- think: pickLang('思考中', 'Thinking'),
- thinking: pickLang('思考中', 'Thinking'),
- working: pickLang('处理中', 'Working'),
- result: pickLang('整理中', 'Organizing'),
- waiting: pickLang('等待中', 'Waiting'),
- review: pickLang('待审阅', 'Review'),
- failed: pickLang('失败', 'Failed'),
- error: pickLang('出错', 'Error'),
- success: pickLang('已完成', 'Done'),
-}
diff --git a/src/pet/hooks/use-bubble-tracker.helpers.test.ts b/src/pet/hooks/use-bubble-tracker.helpers.test.ts
index a3382a5a..1d150afe 100644
--- a/src/pet/hooks/use-bubble-tracker.helpers.test.ts
+++ b/src/pet/hooks/use-bubble-tracker.helpers.test.ts
@@ -1,6 +1,10 @@
-import { describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { setPetLanguage } from '../i18n'
import { bubbleContent, getLiveActivity, rawSession, sessionMotion } from './use-bubble-tracker.helpers'
+beforeEach(() => setPetLanguage('zh'))
+afterEach(() => setPetLanguage('en'))
+
describe('rawSession', () => {
it('rejects payloads that carry no usable session id', () => {
expect(rawSession(undefined)).toBeUndefined()
diff --git a/src/pet/hooks/use-bubble-tracker.helpers.ts b/src/pet/hooks/use-bubble-tracker.helpers.ts
index 1306b1e5..06af412d 100644
--- a/src/pet/hooks/use-bubble-tracker.helpers.ts
+++ b/src/pet/hooks/use-bubble-tracker.helpers.ts
@@ -1,15 +1,13 @@
import type { Motion } from 'dsh-pet-component'
+import { petI18n } from '../i18n'
import {
ACTIVE_MOTIONS,
ACTIVITY_COPY,
- pickLang,
- SESSION_LABELS,
STATUS_COPY,
- STATUS_TEXT_MAP,
TOOL_ARG_KEYS,
TOOL_LABELS,
TOOL_PATTERNS,
- UNTITLED_SESSION_TITLE,
+ TRANSLATED_TOOLS,
WORK_STATUSES,
} from './use-bubble-tracker.constants'
@@ -36,27 +34,28 @@ export function seedNumber(seed: string | number | undefined): number {
return [...value].reduce((total, char) => total + (char.codePointAt(0) ?? 0), 0)
}
-function selectCopy(variants: readonly string[], seed?: string | number): string {
- return variants[seedNumber(seed) % variants.length] ?? variants[0]
-}
-
export function statusCopy(group: string, seed?: string | number): string {
- return selectCopy(STATUS_COPY[group] ?? STATUS_COPY.working, seed)
+ const key = Object.hasOwn(STATUS_COPY, group) ? group : 'working'
+ return petI18n.t(`pet.bubble.status.${key}.${seedNumber(seed) % STATUS_COPY[key]}`)
}
export function activityCopy(activity: string, seed?: string | number): string {
- return selectCopy(ACTIVITY_COPY[activity] ?? STATUS_COPY.working, seed)
+ return ACTIVITY_COPY.has(activity)
+ ? petI18n.t(`pet.bubble.activity.${activity}.${seedNumber(seed) % 3}`)
+ : statusCopy('working', seed)
}
export function taskCopy(task: string | undefined): string | undefined {
const value = String(task ?? '').trim().replace(/[。!?.!?]+$/u, '')
if (!value)
return undefined
+ if (petI18n.language !== 'zh-CN')
+ return petI18n.t('pet.bubble.task', { task: value })
if (/^(?:正在|继续)/u.test(value))
return value
if (/^(?:准备|检查|验证|修改|修复|测试|构建|整理|分析|梳理|查找|搜索|读取|实现)/u.test(value))
return `正在${value}`
- return `正在处理「${value}」`
+ return petI18n.t('pet.bubble.task', { task: value })
}
export function toolActivityGroup(tool: string | undefined): string {
@@ -67,14 +66,14 @@ export function toolActivityGroup(tool: string | undefined): string {
export function sessionTitle(session: SessionTitleSource): string {
const base = [session.title, session.displayTitle, session.name]
.find((v): v is string => typeof v === 'string' && v.trim().length > 0)
- ?.trim() ?? UNTITLED_SESSION_TITLE
+ ?.trim() ?? petI18n.t('pet.bubble.untitled')
if (session.phase === 'approval')
- return `${SESSION_LABELS.waitApproval} · ${base}`
+ return `${petI18n.t('pet.bubble.approval')} · ${base}`
if (session.phase === 'user-question' || session.phase === 'blocked')
- return `${SESSION_LABELS.waitChoice} · ${base}`
+ return `${petI18n.t('pet.bubble.choice')} · ${base}`
if (session.origin === 'subagent')
- return `${SESSION_LABELS.subagent} · ${base}`
+ return `${petI18n.t('pet.bubble.subagent')} · ${base}`
return base
}
@@ -149,13 +148,13 @@ export function getLiveActivity(session: BubbleSession, motion: Motion): string
const { kind, text, name, args } = session.liveActivity as Record<string, unknown>
if (kind === 'reasoning' && typeof text === 'string' && text.trim()) {
- return pickLang(`思考 · ${sanitizeText(text)}`, `Thought · ${sanitizeText(text)}`)
+ return `${petI18n.t('pet.bubble.thought')} · ${sanitizeText(text)}`
}
if (kind === 'tool' && typeof name === 'string' && name) {
const tool = name.toLowerCase()
- const label = TOOL_LABELS[tool]
+ const label = TRANSLATED_TOOLS.has(tool) ? petI18n.t(`pet.bubble.tool.${tool}`) : TOOL_LABELS[tool]
if (!label)
- return pickLang(`工具调用 · ${name}`, `Tool · ${name}`)
+ return `${petI18n.t('pet.bubble.tool')} · ${name}`
const detail = toolArgDetail(tool, args)
return detail ? `${label} · ${detail}` : label
}
@@ -163,15 +162,9 @@ export function getLiveActivity(session: BubbleSession, motion: Motion): string
}
export function bubbleContent(session: BubbleSession, motion: Motion) {
- const isSub = session.origin === 'subagent'
const title = sessionTitle(session)
const seed = session.id
- const statusText = STATUS_TEXT_MAP[motion]
- ?? (motion === 'running'
- ? (isSub ? pickLang('运行中', 'Running') : pickLang('思考中', 'Thinking'))
- : pickLang('空闲', 'Idle'))
-
const fallbackCopy = motion === 'waiting'
? statusCopy(session.phase === 'approval' ? 'approval' : 'waiting', seed)
: motion === 'working'
@@ -179,18 +172,17 @@ export function bubbleContent(session: BubbleSession, motion: Motion) {
: statusCopy(motion, seed)
const candidates = [
- session.lastAgentError ? pickLang(`失败:${String(session.lastAgentError)}`, `Failed: ${String(session.lastAgentError)}`) : undefined,
+ session.lastAgentError ? petI18n.t('pet.bubble.failed', { error: String(session.lastAgentError) }) : undefined,
taskCopy(session.task as string | undefined),
getLiveActivity(session, motion),
fallbackCopy,
session.description,
session.message,
- statusText,
]
const description = candidates
.find((item): item is string => typeof item === 'string' && item.trim().length > 0)
- ?.trim() ?? pickLang('会话', 'Session')
+ ?.trim() ?? petI18n.t('pet.bubble.untitled')
return {
title,
diff --git a/src/pet/hooks/use-bubble-tracker.locale.test.ts b/src/pet/hooks/use-bubble-tracker.locale.test.ts
new file mode 100644
index 00000000..558bc1f0
--- /dev/null
+++ b/src/pet/hooks/use-bubble-tracker.locale.test.ts
@@ -0,0 +1,182 @@
+// @vitest-environment jsdom
+import type { PetBubbleHandle, PetBubbleOptions, PetRef } from 'dsh-pet-component'
+import { act, cleanup, render, renderHook, screen, waitFor } from '@testing-library/react'
+import { createElement } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { Hint } from '@/ui/pet/hint'
+import { petI18n, setPetLanguage } from '../i18n'
+import { createBubbleTracker, useBubbleTracker } from './use-bubble-tracker'
+import { bubbleContent, getLiveActivity, statusCopy } from './use-bubble-tracker.helpers'
+
+const native = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ listeners: new Map<string, (event: { payload: unknown }) => void>(),
+}))
+vi.mock('@tauri-apps/api/core', () => ({ invoke: native.invoke }))
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: vi.fn((event: string, handler: (event: { payload: unknown }) => void) => {
+ native.listeners.set(event, handler)
+ return Promise.resolve(() => {
+ native.listeners.delete(event)
+ })
+ }),
+}))
+
+function makeBubble() {
+ const bubble = Object.assign(vi.fn((options: PetBubbleOptions) => options.id ?? 'bubble'), { close: vi.fn(), clear: vi.fn() })
+ return bubble as typeof bubble & PetBubbleHandle
+}
+
+beforeEach(() => {
+ document.documentElement.lang = 'zh-CN'
+ native.invoke.mockReset()
+ native.listeners.clear()
+ setPetLanguage('en')
+})
+afterEach(() => {
+ cleanup()
+ setPetLanguage('en')
+ vi.restoreAllMocks()
+})
+
+describe('pet language regression', () => {
+ it('updates the unavailable-pet hint with the shared pet locale', () => {
+ render(createElement(Hint, { petId: 'cat' }))
+ expect(screen.getByText('Pet “cat” is unavailable — pick another one in Settings → Pets').textContent)
+ .toBe('Pet “cat” is unavailable — pick another one in Settings → Pets')
+ act(() => setPetLanguage('ko'))
+ expect(screen.getByText('펫 「cat」의 리소스를 사용할 수 없습니다. 설정 → 펫에서 다시 선택해 주세요.').textContent)
+ .toBe('펫 「cat」의 리소스를 사용할 수 없습니다. 설정 → 펫에서 다시 선택해 주세요.')
+ })
+
+ it('uses English approval and thinking copy despite the HTML language', () => {
+ document.documentElement.lang = 'zh-CN'
+ expect(bubbleContent({ id: '0', phase: 'approval' }, 'waiting'))
+ .toEqual({ title: 'Needs approval · New session', description: 'Awaiting your approval', loading: false })
+ expect(getLiveActivity({ id: '0', liveActivity: { kind: 'reasoning', text: 'Checking code' } }, 'thinking'))
+ .toBe('Thought · Checking code')
+ expect(bubbleContent({ id: '0', task: 'Fix login' }, 'working').description).toBe('Working on “Fix login”')
+ expect(getLiveActivity({ id: '0', liveActivity: { kind: 'tool', name: 'read', args: '{"path":"a.ts"}' } }, 'working'))
+ .toBe('Read · a.ts')
+ })
+
+ it.each([
+ ['en-US', 'New session', 'Analyzing information', 'Awaiting your approval'],
+ ['zh-CN', '新会话', '正在分析', '等待审批'],
+ ['ko-KR', '새 세션', '정보 분석 중', '승인 대기 중'],
+ ])('resolves all work status groups at display time in %s', (locale, title, thinking, approval) => {
+ setPetLanguage(locale)
+ expect(bubbleContent({ id: '0' }, 'thinking')).toEqual({ title, description: thinking, loading: true })
+ expect(statusCopy('approval', 0)).toBe(approval)
+ for (const group of ['thinking', 'working', 'waiting', 'result', 'success', 'error', 'review', 'failed', 'running', 'stopped']) {
+ for (const seed of [0, 1, 2]) {
+ const copy = statusCopy(group, seed)
+ expect(copy).not.toContain('pet.bubble.')
+ expect(copy.length).toBeGreaterThan(0)
+ }
+ }
+ })
+
+ it('preserves error and task precedence over default status copy', () => {
+ expect(bubbleContent({ id: '0', task: 'custom task', lastAgentError: 'custom error' }, 'error').description)
+ .toBe('Failed: custom error')
+ expect(bubbleContent({ id: '0', task: 'custom task', liveActivity: { kind: 'reasoning', text: 'custom thought' } }, 'thinking').description)
+ .toBe('Working on “custom task”')
+ })
+
+ it('refreshes an existing approval bubble when native settings change', async () => {
+ native.invoke.mockResolvedValue({ language: 'en' })
+ const bubble = makeBubble()
+ renderHook(() => useBubbleTracker({ bubble } as unknown as PetRef))
+ await waitFor(() => expect(native.invoke).toHaveBeenCalledWith('get_app_config'))
+ act(() => native.listeners.get('session:create')!({ payload: { id: '0', phase: 'approval', workStatus: 'waiting' } }))
+ expect(bubble.mock.calls.at(-1)![0].title).toBe('Needs approval · New session')
+ act(() => native.listeners.get('setting_updated')!({ payload: { language: 'ko' } }))
+ expect(bubble.mock.calls.at(-1)![0]).toMatchObject({ id: '0', title: '승인 필요 · 새 세션', description: '승인 대기 중' })
+ expect(document.documentElement.lang).toBe('ko-KR')
+ expect(native.invoke.mock.calls).toEqual([['get_app_config']])
+ })
+
+ it.each([
+ ['zh-CN', '需授权 · 新会话', '等待审批'],
+ ['ko-KR', '승인 필요 · 새 세션', '승인 대기 중'],
+ ])('falls back to %s when the native preference cannot be loaded', async (locale, title, description) => {
+ vi.spyOn(navigator, 'language', 'get').mockReturnValue(locale)
+ const error = new Error('settings unavailable')
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ native.invoke.mockRejectedValue(error)
+ const bubble = makeBubble()
+ renderHook(() => useBubbleTracker({ bubble } as unknown as PetRef))
+ act(() => native.listeners.get('session:create')!({ payload: { id: '0', phase: 'approval', workStatus: 'waiting' } }))
+ await waitFor(() => expect(warn).toHaveBeenCalledWith('[pet] failed to load language:', error))
+ expect(petI18n.language).toBe(locale)
+ expect(bubble.mock.calls.at(-1)![0]).toMatchObject({ id: '0', title, description })
+ })
+
+ it('ignores a failed initial preference after a newer language event', async () => {
+ vi.spyOn(navigator, 'language', 'get').mockReturnValue('zh-CN')
+ let reject!: (reason: Error) => void
+ native.invoke.mockReturnValue(new Promise((_resolve, fail) => {
+ reject = fail
+ }))
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const error = new Error('settings unavailable')
+ const bubble = makeBubble()
+ renderHook(() => useBubbleTracker({ bubble } as unknown as PetRef))
+ act(() => native.listeners.get('session:create')!({ payload: { id: '0', phase: 'approval', workStatus: 'waiting' } }))
+ act(() => native.listeners.get('setting_updated')!({ payload: { language: 'ko' } }))
+ const count = bubble.mock.calls.length
+ await act(async () => reject(error))
+ expect(warn).toHaveBeenCalledWith('[pet] failed to load language:', error)
+ expect(petI18n.language).toBe('ko-KR')
+ expect(bubble).toHaveBeenCalledTimes(count)
+ })
+
+ it('ignores a failed initial preference after unmount', async () => {
+ vi.spyOn(navigator, 'language', 'get').mockReturnValue('zh-CN')
+ let reject!: (reason: Error) => void
+ native.invoke.mockReturnValue(new Promise((_resolve, fail) => {
+ reject = fail
+ }))
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const error = new Error('settings unavailable')
+ const bubble = makeBubble()
+ const { unmount } = renderHook(() => useBubbleTracker({ bubble } as unknown as PetRef))
+ unmount()
+ await act(async () => reject(error))
+ expect(warn).toHaveBeenCalledWith('[pet] failed to load language:', error)
+ expect(petI18n.language).toBe('en-US')
+ expect(bubble).not.toHaveBeenCalled()
+ expect(native.listeners.size).toBe(0)
+ })
+
+ it('ignores an initial preference that arrives after a newer language event', async () => {
+ let resolve!: (value: { language: string }) => void
+ native.invoke.mockReturnValue(new Promise((done) => {
+ resolve = done
+ }))
+ const bubble = makeBubble()
+ const { unmount } = renderHook(() => useBubbleTracker({ bubble } as unknown as PetRef))
+ act(() => native.listeners.get('setting_updated')!({ payload: { language: 'ko' } }))
+ await act(async () => resolve({ language: 'zh' }))
+ expect(petI18n.language).toBe('ko-KR')
+ unmount()
+ await waitFor(() => expect(native.listeners.size).toBe(0))
+ })
+
+ it('translates subsequent updates and one-shot completion without replaying terminal bubbles', () => {
+ const bubble = makeBubble()
+ const tracker = createBubbleTracker(bubble)
+ tracker.apply({ id: '0', status: 'running' }, 'create')
+ setPetLanguage('ko')
+ tracker.flush()
+ expect(bubble.mock.calls.at(-1)![0].description).toBe('작업 실행 중')
+ tracker.apply({ id: '0' }, 'update')
+ expect(bubble.mock.calls.at(-1)![0]).toMatchObject({ id: '0:done', description: '완료', timeout: 3000 })
+ tracker.apply({ id: '1', workStatus: 'success' }, 'create')
+ const count = bubble.mock.calls.length
+ setPetLanguage('en')
+ tracker.flush()
+ expect(bubble).toHaveBeenCalledTimes(count)
+ })
+})
diff --git a/src/pet/hooks/use-bubble-tracker.test.ts b/src/pet/hooks/use-bubble-tracker.test.ts
index a55cddc8..e5ebbc5f 100644
--- a/src/pet/hooks/use-bubble-tracker.test.ts
+++ b/src/pet/hooks/use-bubble-tracker.test.ts
@@ -6,9 +6,10 @@
* (档位推导、子代理静默、终态只下发一次、挂载前被丢弃的气泡能靠 flush 补齐)。
*/
import type { PetBubbleHandle, PetBubbleOptions } from 'dsh-pet-component'
-import { describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { setPetLanguage } from '../i18n'
+
import { createBubbleTracker } from './use-bubble-tracker'
-import { UNTITLED_SESSION_TITLE } from './use-bubble-tracker.constants'
import {
activityCopy,
seedNumber,
@@ -18,6 +19,9 @@ import {
toolActivityGroup,
} from './use-bubble-tracker.helpers'
+beforeEach(() => setPetLanguage('zh'))
+afterEach(() => setPetLanguage('en'))
+
describe('seedNumber', () => {
it('numeric strings resolve to the absolute truncated integer', () => {
expect(seedNumber('12.9')).toBe(12)
@@ -128,10 +132,10 @@ describe('sessionTitle', () => {
it('falls back to the untitled label instead of leaking the internal session id', () => {
const title = sessionTitle({ id: 'session-2a2abd15-b0d4-499c-aed1-dd1424003bb3' })
- expect(title).toBe(UNTITLED_SESSION_TITLE)
+ expect(title).toBe('新会话')
expect(title).not.toContain('session-')
// 空白标题与缺失标题同档:都不得回落到 id。
- expect(sessionTitle({ title: ' ', displayTitle: '' })).toBe(UNTITLED_SESSION_TITLE)
+ expect(sessionTitle({ title: ' ', displayTitle: '' })).toBe('新会话')
})
it('keeps the attention prefixes on top of the untitled fallback', () => {
@@ -139,8 +143,8 @@ describe('sessionTitle', () => {
const expected = phase === 'approval' ? '需授权 · 会话' : '需选择 · 会话'
expect(sessionTitle({ phase, title: '会话' })).toBe(expected)
}
- expect(sessionTitle({ phase: 'approval' })).toContain(UNTITLED_SESSION_TITLE)
- expect(sessionTitle({ origin: 'subagent' })).toContain(UNTITLED_SESSION_TITLE)
+ expect(sessionTitle({ phase: 'approval' })).toContain('新会话')
+ expect(sessionTitle({ origin: 'subagent' })).toContain('新会话')
})
})
diff --git a/src/pet/hooks/use-bubble-tracker.ts b/src/pet/hooks/use-bubble-tracker.ts
index bf7525f2..d1eace31 100644
--- a/src/pet/hooks/use-bubble-tracker.ts
+++ b/src/pet/hooks/use-bubble-tracker.ts
@@ -1,12 +1,13 @@
import type { Motion, PetBubbleHandle, PetRef } from 'dsh-pet-component'
import type { BubbleSession } from './use-bubble-tracker.helpers'
import type { PetSource } from './use-pet-source'
-import { useUnmount, useWatch } from '@reause/core'
+import { useMount, useUnmount, useWatch } from '@reause/core'
+import { invoke } from '@tauri-apps/api/core'
import { useRef } from 'react'
import { useListen } from '@/hooks/use-listen'
+import { petI18n, setPetLanguage } from '../i18n'
import {
DONE_BUBBLE_TIMEOUT,
- pickLang,
TERMINAL_MOTIONS,
} from './use-bubble-tracker.constants'
import {
@@ -31,6 +32,35 @@ export function useBubbleTracker(pet: PetRef, source?: PetSource | null) {
const trackerRef = useRef<BubbleTracker | null>(null)
trackerRef.current ??= createBubbleTracker(pet.bubble)
const tracker = trackerRef.current
+ const languageRevisionRef = useRef(0)
+
+ function updateLanguage(language?: string | null): void {
+ const previous = petI18n.language
+ setPetLanguage(language)
+ if (previous !== petI18n.language)
+ tracker.flush()
+ }
+
+ useListen<{ language?: string | null }>('setting_updated', ({ payload }) => {
+ languageRevisionRef.current++
+ updateLanguage(payload.language)
+ })
+ useMount(() => {
+ const revision = languageRevisionRef.current
+ void invoke<{ language?: string | null }>('get_app_config')
+ .then((setting) => {
+ if (revision === languageRevisionRef.current)
+ updateLanguage(setting.language)
+ })
+ .catch((error) => {
+ console.warn('[pet] failed to load language:', error)
+ if (revision === languageRevisionRef.current)
+ updateLanguage()
+ })
+ })
+ useUnmount(() => {
+ languageRevisionRef.current++
+ })
useWatch(source !== null, (ready) => {
if (ready)
@@ -76,7 +106,7 @@ export function createBubbleTracker(bubble: PetBubbleHandle): BubbleTracker {
bubble({
id: `${id}:done`,
title: sessionTitle(session).trim(),
- description: pickLang('已完成', 'Done'),
+ description: petI18n.t('pet.bubble.done'),
variant: 'success',
timeout: DONE_BUBBLE_TIMEOUT,
})
diff --git a/src/pet/i18n.ts b/src/pet/i18n.ts
new file mode 100644
index 00000000..40fd76cb
--- /dev/null
+++ b/src/pet/i18n.ts
@@ -0,0 +1,21 @@
+import { createInstance } from 'i18next'
+import { resources } from '@/i18n/index.resource'
+
+// issue #1214:桌宠只读原生语言偏好,主窗口的探测器会回写设置。
+export const petI18n = createInstance()
+void petI18n.init({
+ lng: 'en-US',
+ fallbackLng: 'en-US',
+ resources,
+ interpolation: { escapeValue: false },
+ keySeparator: false,
+ nsSeparator: false,
+ initAsync: false,
+})
+
+export function setPetLanguage(language?: string | null): void {
+ const value = (language || (typeof navigator === 'undefined' ? 'en' : navigator.language)).toLowerCase()
+ void petI18n.changeLanguage(value.startsWith('zh') ? 'zh-CN' : value.startsWith('ko') ? 'ko-KR' : 'en-US')
+ if (typeof document !== 'undefined')
+ document.documentElement.lang = petI18n.language
+}
diff --git a/src/ui/pet/hint.tsx b/src/ui/pet/hint.tsx
index 9f8f0f7d..d4e191a7 100644
--- a/src/ui/pet/hint.tsx
+++ b/src/ui/pet/hint.tsx
@@ -1,26 +1,17 @@
-import { IS_ZH } from '@/pet/hooks/use-bubble-tracker.constants'
-
-/**
- * hint.tsx — 桌宠窗口里唯一会出现的文字提示。
- *
- * 桌宠窗口是透明置顶小窗,**没有任何其它 UI 或 i18n 基础设施**(气泡文案同样就地取
- * 单语),所以这里按窗口语言(`pet/hooks/use-bubble-tracker` 的 `IS_ZH`,与气泡文案同源)就近给出
- * 单句提示。静默留空是不行的:用户看到的是「宠物加载不出来」,既不知道原因也不知道去哪修。
- */
+import { useTranslation } from 'react-i18next'
+import { petI18n } from '@/pet/i18n'
export interface HintProps {
- /** 已选中的宠物 id(用于提示里点名,便于用户回设置页找到它)。 */
petId: string
}
-/** 选中的宠物解析不出资源时的可见提示(导入的宠物被删除、清单里没有这个 id 等)。 */
export function Hint(props: HintProps) {
+ const { t } = useTranslation(undefined, { i18n: petI18n })
+
return (
<div className="pointer-events-none absolute inset-x-0 bottom-6 flex justify-center select-none">
<div className="max-w-[95%] rounded-lg bg-black/70 px-3 py-1.5 text-center text-xs leading-relaxed text-white">
- {IS_ZH
- ? `宠物「${props.petId}」的资源不可用,请在 设置 → 宠物 中重新选择`
- : `Pet “${props.petId}” is unavailable — pick another one in Settings → Pets`}
+ {t('pet.unavailable', { id: props.petId })}
</div>
</div>
)