@takboo/dsh-coopanion 0.4.7 → 0.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/desktop/main.cjs +19 -15
- package/desktop/tray-state.cjs +10 -5
- package/dist/bridge.js +4 -1
- package/dist/bridge.js.map +2 -2
- package/dist/client.js +371 -7
- package/dist/index.js +333 -8
- package/dist/index.js.map +4 -4
- package/docs/release-notes.md +13 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +5 -4
- package/scripts/check-package.mjs +1 -1
- package/src/bridge.ts +4 -1
- package/src/client/index.ts +21 -3
- package/src/client/locale-sync.ts +34 -0
- package/src/client/notification-copy.ts +3 -2
- package/src/index.ts +32 -4
- package/tests/desktop.mjs +15 -3
- package/tests/install.mjs +8 -0
- package/tests/locale-client.mjs +25 -0
- package/tests/locale-sync.test.ts +36 -0
- package/tests/locale-ui.mjs +79 -0
- package/tests/plugin.test.ts +27 -1
- package/tests/presentation.test.js +16 -1
- package/tests/session-replies-ui.mjs +1 -1
- package/tests/ui.mjs +1 -1
- package/web/index.html +42 -42
- package/web/locale.d.ts +6 -0
- package/web/locale.js +76 -0
- package/web/notification-ui.js +3 -2
- package/web/pet.js +102 -50
- package/web/session-ui.js +3 -2
- package/web/style.css +2 -0
package/docs/release-notes.md
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
# v0.4.8
|
|
2
|
+
|
|
3
|
+
## 桌宠语言跟随 Harness
|
|
4
|
+
|
|
5
|
+
- 启动时读取 Harness 已保存的中英文偏好;Client 独立订阅实际解析的语言与回退链,切换立即同步,关闭通知或尚未挂载 workspace 时也能更新。
|
|
6
|
+
- 移除通知轮询对语言的覆盖;当前 Harness 窗口获得焦点时重新同步,断线后重试,快速切换会撤销旧请求。清除显式偏好后恢复自动语言。
|
|
7
|
+
- 桌面菜单、聊天、会话列表、收件箱、完整阅读、角色面板、动作/配色选项、日期、提示和无障碍文案共用中英文解析规则;原生托盘状态、提示和菜单同步切换。
|
|
8
|
+
- 已打开的面板更新语言时,保留当前角色与配色、阅读正文、用户输入、会话标题和 AI 回复。应用自身的提示使用当前语言,原始会话内容保持原文。
|
|
9
|
+
|
|
10
|
+
新增语言同步、超时与重试、快速切换、整套英文界面、热切换、自动语言恢复及原生 JSON IPC 回归;实际 Harness 安装检查覆盖设置切换后桌宠立即更新。
|
|
11
|
+
|
|
12
|
+
安装包:`dsh-coopanion-0.4.8.tgz`。npm、版本化 Release 包及固定别名 `dsh-coopanion.tgz` 使用同一份通过 CI 的压缩包。
|
|
13
|
+
|
|
1
14
|
# v0.4.7
|
|
2
15
|
|
|
3
16
|
## 未读回复按会话去重
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@takboo/dsh-coopanion",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.8",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@takboo/dsh-coopanion",
|
|
9
|
-
"version": "0.4.
|
|
9
|
+
"version": "0.4.8",
|
|
10
10
|
"license": "AGPL-3.0-or-later",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"dompurify": "3.4.17",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@takboo/dsh-coopanion",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.8",
|
|
4
4
|
"description": "DeepSeek Whale desktop companion and task notifications for DeepSeek Harness",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "AGPL-3.0-or-later",
|
|
@@ -71,11 +71,11 @@
|
|
|
71
71
|
"build": "node scripts/build.mjs",
|
|
72
72
|
"setup:electron": "node node_modules/electron/install.js",
|
|
73
73
|
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.client.json",
|
|
74
|
-
"test": "vitest run && node --test tests/release-checks.mjs tests/client-build.mjs",
|
|
74
|
+
"test": "vitest run && node --test tests/release-checks.mjs tests/client-build.mjs && node --test tests/locale-client.mjs",
|
|
75
75
|
"verify:metadata": "node scripts/verify-metadata.mjs",
|
|
76
76
|
"verify:release": "node scripts/verify-release.mjs",
|
|
77
77
|
"verify:package": "node scripts/check-package.mjs",
|
|
78
|
-
"test:ui": "node tests/ui.mjs",
|
|
78
|
+
"test:ui": "node tests/ui.mjs && node --test tests/locale-ui.mjs",
|
|
79
79
|
"test:desktop": "node tests/desktop.mjs",
|
|
80
80
|
"test:install": "node tests/install.mjs",
|
|
81
81
|
"test:n0": "vitest run tests/notification-contract.test.ts && node scripts/prepare-notification-probe.mjs",
|
|
@@ -85,7 +85,8 @@
|
|
|
85
85
|
"demo": "node scripts/demo.mjs",
|
|
86
86
|
"prepack": "npm run build",
|
|
87
87
|
"test:notification-ui": "node tests/notification-ui.mjs",
|
|
88
|
-
"test:inbox-ui": "node tests/inbox-ui.mjs && node --test tests/session-replies-ui.mjs"
|
|
88
|
+
"test:inbox-ui": "node tests/inbox-ui.mjs && node --test tests/session-replies-ui.mjs",
|
|
89
|
+
"test:locale-ui": "node --test tests/locale-ui.mjs"
|
|
89
90
|
},
|
|
90
91
|
"dependencies": {
|
|
91
92
|
"dompurify": "3.4.17",
|
|
@@ -25,7 +25,7 @@ assert.ok(unpack('dist/client.js').includes(`id: ${JSON.stringify(packed.name)}`
|
|
|
25
25
|
if (values['expected-version']) assert.equal(packed.version, values['expected-version'], 'archive version differs from tag');
|
|
26
26
|
else assert.equal(packed.version, pkg.version);
|
|
27
27
|
assert.equal(packed.repository.url, pkg.repository.url);
|
|
28
|
-
for (const required of ['dist/client.js', 'dist/index.js', 'dist/character-store.cjs', 'dist/figure-server.cjs', 'cordis.patch.yml', 'desktop/main.cjs', 'desktop/tray-state.cjs', 'desktop/preload.cjs', 'web/index.html', 'web/pet.js', 'web/speech.js', 'web/session-ui.js', 'web/reply-markdown.js', 'web/markdown-runtime.js', 'web/tray-icon.js', 'web/upstream/kit/rig.js', 'web/upstream/kit/body.js', 'web/upstream/figure-frame.html', 'web/upstream/body-host.js', 'web/upstream/whale/figure.json', 'web/upstream/whale/model.json', 'web/upstream/whale/tex/face.png', 'web/upstream/UPSTREAM.md', 'web/upstream/THIRD_PARTY_NOTICES.md', 'src/figure-server.ts', 'src/upstream/packs.ts', 'scripts/build.mjs', 'npm-shrinkwrap.json', 'tsconfig.json', 'tsconfig.client.json', '.node-version', 'docs/characters.md', 'examples/star/figure.json', 'examples/star/figure.js', 'tests/figures.test.ts', 'docs/licenses/marked.txt', 'docs/licenses/dompurify.txt', 'THIRD_PARTY_NOTICES.md', 'LICENSE', 'LICENSE-MIT', 'README.md']) assert.ok(entries.includes(`package/${required}`), `missing ${required}`);
|
|
28
|
+
for (const required of ['dist/client.js', 'dist/index.js', 'dist/character-store.cjs', 'dist/figure-server.cjs', 'cordis.patch.yml', 'desktop/main.cjs', 'desktop/tray-state.cjs', 'desktop/preload.cjs', 'web/index.html', 'web/pet.js', 'web/speech.js', 'web/session-ui.js', 'web/locale.js', 'web/locale.d.ts', 'src/client/locale-sync.ts', 'tests/locale-ui.mjs', 'tests/locale-client.mjs', 'web/reply-markdown.js', 'web/markdown-runtime.js', 'web/tray-icon.js', 'web/upstream/kit/rig.js', 'web/upstream/kit/body.js', 'web/upstream/figure-frame.html', 'web/upstream/body-host.js', 'web/upstream/whale/figure.json', 'web/upstream/whale/model.json', 'web/upstream/whale/tex/face.png', 'web/upstream/UPSTREAM.md', 'web/upstream/THIRD_PARTY_NOTICES.md', 'src/figure-server.ts', 'src/upstream/packs.ts', 'scripts/build.mjs', 'npm-shrinkwrap.json', 'tsconfig.json', 'tsconfig.client.json', '.node-version', 'docs/characters.md', 'examples/star/figure.json', 'examples/star/figure.js', 'tests/figures.test.ts', 'docs/licenses/marked.txt', 'docs/licenses/dompurify.txt', 'THIRD_PARTY_NOTICES.md', 'LICENSE', 'LICENSE-MIT', 'README.md']) assert.ok(entries.includes(`package/${required}`), `missing ${required}`);
|
|
29
29
|
assert.ok(!entries.some(path => path.includes('node_modules/') || path.includes('.cache/')));
|
|
30
30
|
assert.ok(!entries.some(path => /character-runtime|character.schema|\/animation\.|\/character-pack\.|\/web\/characters\//.test(path)), 'old engine and format must not be packaged');
|
|
31
31
|
const bytes = readFileSync(archive);
|
package/src/bridge.ts
CHANGED
|
@@ -113,7 +113,10 @@ export class ElectronBridge extends EventEmitter implements PetBridge {
|
|
|
113
113
|
}
|
|
114
114
|
onAction(listener: (action: unknown) => void): void { this.on('action', listener); }
|
|
115
115
|
removeAction(listener: (action: unknown) => void): void { this.off('action', listener); }
|
|
116
|
-
|
|
116
|
+
// JSON IPC omits undefined. An explicit null lets a cleared Harness
|
|
117
|
+
// preference restore the renderer's automatic language instead of retaining
|
|
118
|
+
// its previous locale during a merged configuration update.
|
|
119
|
+
configure(options: DesktopOptions): void { this.send({ type: 'configure', options: { ...options, locale: options.locale ?? null } }); }
|
|
117
120
|
control(command: 'show' | 'hide' | 'characters'): void { this.send({ type: 'control', command }); }
|
|
118
121
|
focusHarness(): void { this.send({ type: 'control', command: 'focus-harness' }); }
|
|
119
122
|
onLifecycle(listener: (state: NativeLifecycle) => void): void { this.on('lifecycle', listener); }
|
package/src/client/index.ts
CHANGED
|
@@ -12,6 +12,7 @@ import css from './settings.css';
|
|
|
12
12
|
import type { BrowserNotificationApi } from './system-notifications.ts';
|
|
13
13
|
import { NotificationClient } from './notification-client.ts';
|
|
14
14
|
import { notificationPreferencesSchema, type DeliveryClaim, type NotificationSnapshot } from '../notification-contract.ts';
|
|
15
|
+
import { syncPetLocale } from './locale-sync.ts';
|
|
15
16
|
|
|
16
17
|
declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { coopanion: LocaleKey; } }
|
|
17
18
|
declare module '@deepseek-ai/cordis' { interface Context { connection: ConnectionHandle; } }
|
|
@@ -19,7 +20,24 @@ export const inject = ['slots', 'locale', 'configForms', 'connection'];
|
|
|
19
20
|
|
|
20
21
|
/** A regular DSH settings section, using Host forms and the authenticated Connection carrier. */
|
|
21
22
|
export function apply(ctx: Context): void {
|
|
23
|
+
const currentLocale = () => ctx.locale.resolveText({ zh: 'zh', en: 'en' });
|
|
22
24
|
ctx.effect(() => ctx.locale.register('coopanion', { zh, en }));
|
|
25
|
+
ctx.effect(() => {
|
|
26
|
+
if (!ctx.connection.isLoopback) return () => {};
|
|
27
|
+
return syncPetLocale({
|
|
28
|
+
current: currentLocale,
|
|
29
|
+
subscribe: listener => {
|
|
30
|
+
const unsubscribe = ctx.locale.subscribe(() => listener());
|
|
31
|
+
const focus = () => { if (document.visibilityState !== 'hidden') listener(true); };
|
|
32
|
+
window.addEventListener('focus', focus); document.addEventListener('visibilitychange', focus);
|
|
33
|
+
return () => { unsubscribe(); window.removeEventListener('focus', focus); document.removeEventListener('visibilitychange', focus); };
|
|
34
|
+
},
|
|
35
|
+
send: async (locale, signal) => {
|
|
36
|
+
const response = await ctx.connection.rpc.call('/api', 'coopanion/locale', { locale }, signal);
|
|
37
|
+
if (!response.ok) throw new Error(response.error.message);
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
});
|
|
23
41
|
ctx.effect(() => {
|
|
24
42
|
const tag = document.createElement('style'); tag.dataset.plugin = 'dsh-coopanion'; tag.textContent = css;
|
|
25
43
|
document.head.append(tag); return () => tag.remove();
|
|
@@ -48,10 +66,10 @@ export function apply(ctx: Context): void {
|
|
|
48
66
|
return reply.value as T;
|
|
49
67
|
};
|
|
50
68
|
const client = new NotificationClient({
|
|
51
|
-
locale:
|
|
69
|
+
locale: currentLocale,
|
|
52
70
|
api: globalThis.Notification as unknown as BrowserNotificationApi,
|
|
53
71
|
transport: {
|
|
54
|
-
state: signal => request<NotificationSnapshot>('notification-state', {
|
|
72
|
+
state: signal => request<NotificationSnapshot>('notification-state', {}, signal),
|
|
55
73
|
claim: (payload, signal) => request<DeliveryClaim | null>('notification-claim', payload, signal),
|
|
56
74
|
receipt: (payload, signal) => request('notification-receipt', payload, signal),
|
|
57
75
|
snooze: (payload, signal) => request('notification-snooze', payload, signal),
|
|
@@ -62,7 +80,7 @@ export function apply(ctx: Context): void {
|
|
|
62
80
|
},
|
|
63
81
|
openSession: sessionId => { child.uiWorkspace.openSession(sessionId as SessionId); window.focus(); },
|
|
64
82
|
testClaim: async (clientId, signal) => {
|
|
65
|
-
const state = await request<NotificationSnapshot>('notification-state', {
|
|
83
|
+
const state = await request<NotificationSnapshot>('notification-state', {}, signal);
|
|
66
84
|
return request<DeliveryClaim>('notification-test', { clientId, generation: state.runtime.generation }, signal);
|
|
67
85
|
},
|
|
68
86
|
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { petLanguage } from '../../web/locale.js';
|
|
2
|
+
|
|
3
|
+
/** The resolved Harness locale follows plugin lifetime, independently of workspace and notifications. */
|
|
4
|
+
export function syncPetLocale({ current, subscribe, send, retryMs = 750, timeoutMs = 5000 }: {
|
|
5
|
+
current: () => string;
|
|
6
|
+
subscribe: (listener: (force?: boolean) => void) => () => void;
|
|
7
|
+
send: (locale: string, signal: AbortSignal) => Promise<void>;
|
|
8
|
+
retryMs?: number; timeoutMs?: number;
|
|
9
|
+
}): () => void {
|
|
10
|
+
let stopped = false, accepted: string | undefined, pending: string | undefined;
|
|
11
|
+
let controller: AbortController | undefined, retry: ReturnType<typeof setTimeout> | undefined;
|
|
12
|
+
const sync = (force = false) => {
|
|
13
|
+
if (stopped) return;
|
|
14
|
+
const locale = petLanguage(current());
|
|
15
|
+
if (!force && (locale === pending || locale === accepted && !pending)) return;
|
|
16
|
+
clearTimeout(retry); controller?.abort();
|
|
17
|
+
const request = new AbortController(); controller = request; pending = locale;
|
|
18
|
+
const deadline = setTimeout(() => request.abort(), timeoutMs);
|
|
19
|
+
const aborted = new Promise<never>((_, reject) => request.signal.addEventListener('abort', () => reject(new Error('Locale request cancelled')), { once: true }));
|
|
20
|
+
void Promise.race([Promise.resolve().then(() => {
|
|
21
|
+
if (request.signal.aborted) throw new Error('Locale request cancelled');
|
|
22
|
+
return send(locale, request.signal);
|
|
23
|
+
}), aborted]).then(() => {
|
|
24
|
+
if (controller === request && !request.signal.aborted) accepted = locale;
|
|
25
|
+
}).catch(() => {
|
|
26
|
+
if (controller === request && !stopped) retry = setTimeout(sync, retryMs);
|
|
27
|
+
}).finally(() => {
|
|
28
|
+
clearTimeout(deadline);
|
|
29
|
+
if (controller === request) { pending = undefined; controller = undefined; }
|
|
30
|
+
});
|
|
31
|
+
};
|
|
32
|
+
const unsubscribe = subscribe(sync); sync();
|
|
33
|
+
return () => { stopped = true; unsubscribe(); clearTimeout(retry); controller?.abort(); };
|
|
34
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { TaskNotice } from '../notification-contract.ts';
|
|
2
|
+
import { petLanguage, appStatusBody } from '../../web/locale.js';
|
|
2
3
|
|
|
3
4
|
const zh = {
|
|
4
5
|
completed: '任务完成啦', approval: '下一步需要你确认', question: '有个问题想问你', error: '任务需要关注',
|
|
@@ -14,12 +15,12 @@ const en: typeof zh = {
|
|
|
14
15
|
};
|
|
15
16
|
/** Localize application copy while preserving source identity and user-authored previews exactly. */
|
|
16
17
|
export function systemNotificationCopy(notice: TaskNotice, locale = 'zh'): TaskNotice {
|
|
17
|
-
const copy =
|
|
18
|
+
const copy = petLanguage(locale) === 'zh' ? zh : en;
|
|
18
19
|
if (notice.stage === 'reminder') {
|
|
19
20
|
const summary = notice.requestIds.length > 1 ? copy.grouped(notice.requestIds.length) : copy.reminder;
|
|
20
21
|
return { ...notice, title: summary, body: summary };
|
|
21
22
|
}
|
|
22
23
|
const title = copy[notice.category];
|
|
23
24
|
const short = ['stopped', 'interrupted', 'blocked', 'max-tokens'].includes(notice.category);
|
|
24
|
-
return { ...notice, title, body: short ? title : notice
|
|
25
|
+
return { ...notice, title, body: short ? title : appStatusBody(notice, locale) };
|
|
25
26
|
}
|
package/src/index.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { ElectronBridge, isRecord, type PetBridge, type DesktopOptions } from '.
|
|
|
16
16
|
import { PetModel } from './model.ts';
|
|
17
17
|
import { PetControls } from './controls.ts';
|
|
18
18
|
import { z as wire } from 'zod';
|
|
19
|
+
import { petLanguage } from '../web/locale.js';
|
|
19
20
|
|
|
20
21
|
export const name = 'dsh-coopanion';
|
|
21
22
|
export const inject = ['agents'];
|
|
@@ -50,7 +51,29 @@ export async function mountPet(ctx: Context, options: Config, bridge: PetBridge)
|
|
|
50
51
|
ctx.inject(['settings'], child => { savePreference = (field, value) => child.settings.mutate('dsh-coopanion', [{ op: 'set', path: [field], value }]); });
|
|
51
52
|
const currentOptions = (): DesktopOptions => ({ size: options.size.get(), roam: options.roam.get(), notifications: options.notifications.get(), bubbleDurationMs: options.bubbleDurationMs.get(), systemNotifications: options.systemNotifications.get(), reminders: options.reminders.get(), reminderDelayMs: options.reminderDelayMs.get(), electronPath: options.electronPath, locale, ...preferences });
|
|
52
53
|
const controls = new PetControls(bridge, currentOptions);
|
|
53
|
-
let locale
|
|
54
|
+
let locale: string | undefined;
|
|
55
|
+
let clientLocale: string | undefined;
|
|
56
|
+
let dedicatedLocale = false;
|
|
57
|
+
let storedLocale: (() => string | undefined) | undefined;
|
|
58
|
+
const syncLocale = () => {
|
|
59
|
+
const preference = storedLocale?.();
|
|
60
|
+
const next = preference ? petLanguage(preference) : clientLocale;
|
|
61
|
+
if (next === locale) return;
|
|
62
|
+
locale = next; controls.configure();
|
|
63
|
+
};
|
|
64
|
+
const adoptClientLocale = (value: string) => { clientLocale = petLanguage(value); syncLocale(); };
|
|
65
|
+
ctx.inject(['settings'], child => {
|
|
66
|
+
const read = () => {
|
|
67
|
+
const value = child.settings.describe({ redactSecrets: true }).find(entry => entry.ns === 'locale')?.value;
|
|
68
|
+
const preference = isRecord(value) && typeof value.preference === 'string' ? value.preference.toLowerCase() : undefined;
|
|
69
|
+
// Only the Client knows additional registered languages and its resolved
|
|
70
|
+
// browser fallback. Bootstrap from the two built-in durable choices.
|
|
71
|
+
return preference === 'zh' || preference === 'en' ? preference : undefined;
|
|
72
|
+
};
|
|
73
|
+
storedLocale = read;
|
|
74
|
+
child.effect(() => () => { if (storedLocale === read) storedLocale = undefined; });
|
|
75
|
+
syncLocale();
|
|
76
|
+
});
|
|
54
77
|
let navigation: { sessionId: string; expires: number } | undefined;
|
|
55
78
|
ctx.provide('coopanion', controls);
|
|
56
79
|
const update = () => {
|
|
@@ -99,11 +122,16 @@ export async function mountPet(ctx: Context, options: Config, bridge: PetBridge)
|
|
|
99
122
|
const timer = setInterval(() => { if (model.settle()) update(); }, 250);
|
|
100
123
|
timer.unref(); return () => clearInterval(timer);
|
|
101
124
|
});
|
|
102
|
-
ctx.on('settings/document-updated', ns => { if (ns === 'dsh-coopanion') { broker.preferences(notificationPrefs()); controls.configure(); } });
|
|
125
|
+
ctx.on('settings/document-updated', ns => { if (ns === 'dsh-coopanion') { broker.preferences(notificationPrefs()); controls.configure(); } else if (ns === 'locale') syncLocale(); });
|
|
103
126
|
ctx.inject(['connection'], child => {
|
|
104
127
|
const dispatch = async (endpoint: string, payload: unknown, signal: AbortSignal) => {
|
|
105
128
|
try {
|
|
106
129
|
if (signal.aborted) throw new Error('请求已取消');
|
|
130
|
+
if (endpoint === 'locale') {
|
|
131
|
+
const input = wire.object({ locale: wire.enum(['zh', 'en']) }).strict().parse(payload);
|
|
132
|
+
dedicatedLocale = true;
|
|
133
|
+
adoptClientLocale(input.locale); return { ok: true, value: { locale } };
|
|
134
|
+
}
|
|
107
135
|
if (endpoint === 'status') {
|
|
108
136
|
wire.object({}).strict().parse(payload);
|
|
109
137
|
return { ok: true, value: controls.status() };
|
|
@@ -114,7 +142,7 @@ export async function mountPet(ctx: Context, options: Config, bridge: PetBridge)
|
|
|
114
142
|
navigation = undefined;
|
|
115
143
|
return { ok: true, value };
|
|
116
144
|
}
|
|
117
|
-
if (endpoint === 'notification-state') { const input = notificationRequests.state.parse(payload); if (input.locale &&
|
|
145
|
+
if (endpoint === 'notification-state') { const input = notificationRequests.state.parse(payload); if (input.locale && !dedicatedLocale) adoptClientLocale(input.locale); return { ok: true, value: broker.snapshot() }; }
|
|
118
146
|
if (endpoint === 'notification-claim') { const input = notificationRequests.claim.parse(payload); return { ok: true, value: broker.claim(input.clientId, input.generation) }; }
|
|
119
147
|
if (endpoint === 'notification-receipt') { return { ok: true, value: { accepted: broker.receipt(notificationRequests.receipt.parse(payload)) } }; }
|
|
120
148
|
if (endpoint === 'notification-snooze') { const input = notificationRequests.snooze.parse(payload); if (!broker.snooze(input.interactionId, input.generation)) throw new Error('待处理请求已变化或提醒暂不可用'); return { ok: true, value: { accepted: true } }; }
|
|
@@ -140,7 +168,7 @@ export async function mountPet(ctx: Context, options: Config, bridge: PetBridge)
|
|
|
140
168
|
};
|
|
141
169
|
// Exact Connection routes coexist with the Gateway's exclusive /api interceptor.
|
|
142
170
|
// The Connection carrier applies its normal Host/Origin and authentication checks.
|
|
143
|
-
for (const endpoint of ['status', 'control', 'navigation', ...notificationEndpoints] as const) {
|
|
171
|
+
for (const endpoint of ['status', 'control', 'navigation', 'locale', ...notificationEndpoints] as const) {
|
|
144
172
|
child.effect(() => child.connection.fetch.register({
|
|
145
173
|
path: `/api/coopanion/${endpoint}`, methods: ['POST'], requestBody: 'buffered',
|
|
146
174
|
fetch: async request => {
|
package/tests/desktop.mjs
CHANGED
|
@@ -47,7 +47,7 @@ try {
|
|
|
47
47
|
const failures = []; bridge.on('failure', error => failures.push(error.message));
|
|
48
48
|
const snapshot = { mood: 'thinking', active: true, text: '真实 IPC 桌面测试', sessionId: 'native-test', results: [], sessions: [{ id: 'native-test', label: '桌面测试会话', mood: 'thinking', active: true, text: '', reply: '' }] };
|
|
49
49
|
bridge.update(snapshot);
|
|
50
|
-
await bridge.start({ size: 150, roam: false, notifications: true, bubbleDurationMs: 12000 });
|
|
50
|
+
await bridge.start({ locale: 'zh', size: 150, roam: false, notifications: true, bubbleDurationMs: 12000 });
|
|
51
51
|
browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
|
|
52
52
|
let page = browser.contexts()[0].pages()[0];
|
|
53
53
|
await page.waitForSelector('#pet[data-host-ready=true][data-mood=thinking]');
|
|
@@ -153,9 +153,21 @@ try {
|
|
|
153
153
|
await page.locator('#reader-session').click();
|
|
154
154
|
for (let n = 0; n < 30 && !actions.slice(actionStart).some(action => action.type === 'open-session'); n++) await pause(50);
|
|
155
155
|
assert.deepEqual(actions.slice(actionStart).filter(action => ['select', 'read', 'open-session'].includes(action.type)), [{ type: 'read', resultId: olderBackgroundReply.id }, { type: 'read', resultId: backgroundReply.id }, { type: 'open-session', sessionId: backgroundReply.sessionId }], 'native inbox acknowledges every captured turn and carries the exact source identity');
|
|
156
|
+
bridge.configure({ locale: 'en', size: 150, roam: false, notifications: true, bubbleDurationMs: 12000 });
|
|
157
|
+
await page.waitForFunction(() => document.documentElement.lang === 'en');
|
|
158
|
+
assert.equal(await page.locator('#chat-title').textContent(), 'I’m here. Take your time.');
|
|
159
|
+
await waitTray(state => state?.tooltip.includes('Focused:'));
|
|
160
|
+
const automatic = await page.evaluate(() => {
|
|
161
|
+
const language = navigator.languages.find(language => /^(zh|en)(-|$)/i.test(language)) ?? 'en';
|
|
162
|
+
return /^zh/i.test(language) ? 'zh-CN' : 'en';
|
|
163
|
+
});
|
|
164
|
+
bridge.configure({ locale: automatic === 'en' ? 'zh' : 'en', size: 150, roam: false, notifications: true, bubbleDurationMs: 12000 });
|
|
165
|
+
await page.waitForFunction(expected => document.documentElement.lang !== expected, automatic);
|
|
166
|
+
bridge.configure({ size: 150, roam: false, notifications: true, bubbleDurationMs: 12000 });
|
|
167
|
+
await page.waitForFunction(expected => document.documentElement.lang === expected, automatic);
|
|
156
168
|
for (let n = 0; n < 100 && !trayIcons.some(icon => icon.icon === 'talking'); n++) await pause(50);
|
|
157
169
|
assert.ok(trayIcons.some(icon => icon.icon === 'talking' && icon.title === '' && icon.template === (process.platform === 'darwin')), 'native icon is rendered with the state glyph and macOS template appearance');
|
|
158
|
-
bridge.configure({ size: 150, roam: false, notifications: false, bubbleDurationMs: 12000 });
|
|
170
|
+
bridge.configure({ locale: 'zh', size: 150, roam: false, notifications: false, bubbleDurationMs: 12000 });
|
|
159
171
|
await waitTray(state => state?.roam === false && state.notifications === false);
|
|
160
172
|
bridge.control('hide'); await waitTray(state => state?.visible === false);
|
|
161
173
|
await waitLifecycle(state => state?.generation > 0 && state.visibilityRevision > 0 && !state.visible);
|
|
@@ -169,7 +181,7 @@ try {
|
|
|
169
181
|
await bridge.dispose();
|
|
170
182
|
await browser.close(); browser = undefined;
|
|
171
183
|
bridge = new ElectronBridge(); bridge.on('failure', error => failures.push(error.message)); bridge.update(snapshot);
|
|
172
|
-
await bridge.start({ size: 150, roam: false, notifications: false, bubbleDurationMs: 12000 });
|
|
184
|
+
await bridge.start({ locale: 'zh', size: 150, roam: false, notifications: false, bubbleDurationMs: 12000 });
|
|
173
185
|
browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); page = browser.contexts()[0].pages()[0];
|
|
174
186
|
await page.waitForSelector('#pet[data-character=paper-star][data-scheme=night]');
|
|
175
187
|
await page.waitForSelector('#pet[data-host-ready=true][data-mood=thinking]');
|
package/tests/install.mjs
CHANGED
|
@@ -343,6 +343,11 @@ try {
|
|
|
343
343
|
await settings.getByRole('menuitem', { name: 'English', exact: true }).click();
|
|
344
344
|
await settings.getByRole('button', { name: 'Desktop pet', exact: true }).click();
|
|
345
345
|
await surface.getByRole('heading', { name: 'Pet status', exact: true }).waitFor();
|
|
346
|
+
await reopened.waitForFunction(() => document.documentElement.lang === 'en');
|
|
347
|
+
assert.equal(await reopened.locator('#chat-title').textContent(), 'I’m here. Take your time.');
|
|
348
|
+
assert.match(await reopened.locator('#menu-chat').textContent(), /Say something/);
|
|
349
|
+
assert.equal(await reopened.locator('#menu-name').textContent(), 'DeepSeek Whale');
|
|
350
|
+
assert.equal(await reopened.locator('#reader-close').getAttribute('aria-label'), 'Close full reply');
|
|
346
351
|
await surface.getByRole('switch', { name: 'Start with Harness', exact: true }).waitFor();
|
|
347
352
|
await surface.getByRole('button', { name: 'Manage characters', exact: true }).waitFor();
|
|
348
353
|
assert.equal(await surface.getByRole('spinbutton', { name: 'Character size', exact: true }).inputValue(), '180');
|
|
@@ -351,6 +356,9 @@ try {
|
|
|
351
356
|
await settings.getByRole('button', { name: 'English', exact: true }).click();
|
|
352
357
|
await settings.getByRole('menuitem', { name: '中文', exact: true }).click();
|
|
353
358
|
await settings.getByRole('button', { name: '桌宠', exact: true }).waitFor();
|
|
359
|
+
await reopened.waitForFunction(() => document.documentElement.lang === 'zh-CN');
|
|
360
|
+
assert.equal(await reopened.locator('#chat-title').textContent(), '我在,慢慢说。');
|
|
361
|
+
assert.equal(await reopened.locator('#menu-name').textContent(), 'DeepSeek 大肥鱼');
|
|
354
362
|
await waitProfile(/preference: zh/);
|
|
355
363
|
await stop(host); assert.equal(host.exitCode, 0, hostLog);
|
|
356
364
|
await bootHost();
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { runInNewContext } from 'node:vm';
|
|
4
|
+
import { test } from 'node:test';
|
|
5
|
+
|
|
6
|
+
test('the real Client factory synchronizes resolved Harness locale without workspace or notifications', async () => {
|
|
7
|
+
let factory, active='en'; const listeners=new Set(), calls=[], cleanup=[];
|
|
8
|
+
const focusEvents=new EventTarget(), documentEvents=new EventTarget();
|
|
9
|
+
const document={createElement:()=>({dataset:{},remove(){}}),head:{append(){}},visibilityState:'visible',addEventListener:documentEvents.addEventListener.bind(documentEvents),removeEventListener:documentEvents.removeEventListener.bind(documentEvents)};
|
|
10
|
+
runInNewContext(readFileSync(new URL('../dist/client.js',import.meta.url),'utf8'),{window:{__ModuleLoader__:{load(value){factory=value.factory;}},addEventListener:focusEvents.addEventListener.bind(focusEvents),removeEventListener:focusEvents.removeEventListener.bind(focusEvents)},document,URL,TextEncoder,TextDecoder,AbortController,setTimeout,clearTimeout});
|
|
11
|
+
const client=factory(()=>({}));
|
|
12
|
+
const ctx={effect(fn){const stop=fn(); if(stop) cleanup.push(stop);},inject(){},locale:{register:()=>()=>{},getLocale:()=>({active}),resolveText:()=>active==='custom'?'zh':active,subscribe(fn){listeners.add(fn);return()=>listeners.delete(fn);}},configForms:{get:()=>({getSnapshot:()=>({value:{notifications:false,systemNotifications:false}})})},slots:{inject(){}},connection:{isLoopback:true,rpc:{async call(...args){calls.push(args);return{ok:true,value:{}};}}}};
|
|
13
|
+
client.apply(ctx); await new Promise(resolve=>setTimeout(resolve,20));
|
|
14
|
+
assert.ok(calls.some(call=>call[2]?.locale==='en'),'initial resolved language is sent even without uiWorkspace');
|
|
15
|
+
active='zh'; for(const listener of listeners) listener(); await new Promise(resolve=>setTimeout(resolve,20));
|
|
16
|
+
assert.equal(calls.at(-1)[2].locale,'zh','language changes propagate immediately');
|
|
17
|
+
const previous=calls.length; focusEvents.dispatchEvent(new Event('focus')); await new Promise(resolve=>setTimeout(resolve,20));
|
|
18
|
+
assert.equal(calls.length,previous+1,'focused Harness window reasserts its actual language without a preference change');
|
|
19
|
+
active='custom'; for(const listener of listeners) listener(); await new Promise(resolve=>setTimeout(resolve,20));
|
|
20
|
+
assert.equal(calls.at(-1)[2].locale,'zh','the registered Harness fallback chain determines the plugin language');
|
|
21
|
+
for(const stop of cleanup.reverse()) stop();
|
|
22
|
+
assert.equal(listeners.size,0,'locale subscription follows plugin lifecycle');
|
|
23
|
+
const disposedCalls=calls.length; focusEvents.dispatchEvent(new Event('focus')); await new Promise(resolve=>setTimeout(resolve,20));
|
|
24
|
+
assert.equal(calls.length,disposedCalls,'focus subscriptions are removed on disposal');
|
|
25
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { afterEach, expect, it, vi } from 'vitest';
|
|
2
|
+
import { syncPetLocale } from '../src/client/locale-sync.ts';
|
|
3
|
+
import { appNoticeCopy, appStatusBody, petCopy } from '../web/locale.js';
|
|
4
|
+
|
|
5
|
+
afterEach(() => vi.useRealTimers());
|
|
6
|
+
it('aborts an in-flight language change when returning to the previously accepted language', async () => {
|
|
7
|
+
let current='en', change: (force?: boolean) => void = () => {};
|
|
8
|
+
const calls: {locale:string;signal:AbortSignal}[]=[];
|
|
9
|
+
const stop=syncPetLocale({current:()=>current,subscribe:listener=>{change=listener;return()=>{};},send:async(locale,signal)=>{calls.push({locale,signal});if(locale==='zh') await new Promise(()=>{});}});
|
|
10
|
+
await vi.waitFor(()=>expect(calls).toHaveLength(1));
|
|
11
|
+
current='zh';change();await vi.waitFor(()=>expect(calls).toHaveLength(2));
|
|
12
|
+
current='en';change();await vi.waitFor(()=>expect(calls).toHaveLength(3));
|
|
13
|
+
expect(calls.map(call=>call.locale)).toEqual(['en','zh','en']);expect(calls[1].signal.aborted).toBe(true);
|
|
14
|
+
stop();
|
|
15
|
+
});
|
|
16
|
+
it('retries the current locale after connection failure and stops timers on disposal', async () => {
|
|
17
|
+
vi.useFakeTimers(); const send=vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(undefined);
|
|
18
|
+
const stop=syncPetLocale({current:()=> 'zh-CN',subscribe:()=>()=>{},send,retryMs:10});
|
|
19
|
+
await vi.advanceTimersByTimeAsync(11); expect(send).toHaveBeenCalledTimes(2);expect(send.mock.calls[1][0]).toBe('zh');
|
|
20
|
+
stop(); await vi.advanceTimersByTimeAsync(10000); expect(send).toHaveBeenCalledTimes(2);
|
|
21
|
+
});
|
|
22
|
+
it('bounds a transport that ignores abort and retries without retaining old requests', async () => {
|
|
23
|
+
vi.useFakeTimers();const send=vi.fn(()=>new Promise<void>(()=>{}));
|
|
24
|
+
const stop=syncPetLocale({current:()=> 'en',subscribe:()=>()=>{},send,timeoutMs:10,retryMs:10});
|
|
25
|
+
await vi.advanceTimersByTimeAsync(21);expect(send).toHaveBeenCalledTimes(2);
|
|
26
|
+
stop(); await vi.advanceTimersByTimeAsync(100);expect(send).toHaveBeenCalledTimes(2);
|
|
27
|
+
});
|
|
28
|
+
it('keeps complete paired dictionaries and translates only application diagnostics', () => {
|
|
29
|
+
expect(Object.keys(petCopy('en')).sort()).toEqual(Object.keys(petCopy('zh')).sort());
|
|
30
|
+
expect(Object.keys(petCopy('en').labels)).toEqual(Object.keys(petCopy('zh').labels));
|
|
31
|
+
expect(appNoticeCopy({title:'会话尚未就绪',body:'请先回到 Harness 打开这个会话,然后再发送消息。'},'en')).toEqual({title:'Conversation not ready',body:'Open this conversation in Harness before sending a message.'});
|
|
32
|
+
const text='任务遇到了问题,请回到 Harness 查看详情。';
|
|
33
|
+
expect(appStatusBody({category:'error',body:text},'en')).toBe(petCopy('en').issueError);
|
|
34
|
+
expect(appStatusBody({category:'completed',body:text},'en')).toBe(text);
|
|
35
|
+
expect(appStatusBody({category:'question',body:text},'en')).toBe(text);
|
|
36
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { before, after, test } from 'node:test';
|
|
8
|
+
import { chromium } from 'playwright-core';
|
|
9
|
+
import { previewServer } from '../scripts/preview.mjs';
|
|
10
|
+
|
|
11
|
+
let directory, server, browser;
|
|
12
|
+
before(async () => {
|
|
13
|
+
directory = await mkdtemp(join(tmpdir(), 'dsh-locale-ui-'));
|
|
14
|
+
server = previewServer({ dataDir: directory }); server.listen(0, '127.0.0.1'); await once(server, 'listening');
|
|
15
|
+
browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH ?? (existsSync('/usr/bin/chromium') ? '/usr/bin/chromium' : chromium.executablePath()), headless: true, args: ['--no-sandbox', '--enable-unsafe-swiftshader'] });
|
|
16
|
+
});
|
|
17
|
+
after(async () => { await browser?.close(); if (server) await new Promise(resolve => server.close(resolve)); if (directory) await rm(directory, { recursive: true, force: true }); });
|
|
18
|
+
async function fixture(t, locale = 'en') {
|
|
19
|
+
const page = await browser.newPage({ locale: 'zh-CN', viewport: { width: 1100, height: 800 }, reducedMotion: 'reduce' });
|
|
20
|
+
t.after(() => page.close());
|
|
21
|
+
const errors = []; page.on('pageerror', error => errors.push(error.message)); t.after(() => assert.deepEqual(errors, []));
|
|
22
|
+
await page.addInitScript(() => { window.localeActions=[]; window.dshPetBridge={ subscribe(fn) { window.localeReceive=fn; }, action(value) { window.localeActions.push(value); }, hit() {} }; });
|
|
23
|
+
await page.goto(`http://127.0.0.1:${server.address().port}`); await page.waitForSelector('#pet[data-character=whale][data-mode]');
|
|
24
|
+
const receive = value => page.evaluate(value => window.localeReceive(value), value);
|
|
25
|
+
const session = { id: 'source', label: '用户的中文会话', project: 'User project', mood: 'idle', unread: 1, chatAvailable: true };
|
|
26
|
+
const result = { id: 'reply', sessionId: session.id, text: '**中文回复** stays unchanged.', time: 1, read: false };
|
|
27
|
+
await receive({ type:'init', options:{locale,roam:false,notifications:false}, snapshot:{sessionId:session.id,mood:'idle',active:false,sessions:[session],results:[result]} });
|
|
28
|
+
return { page, receive, session, result };
|
|
29
|
+
}
|
|
30
|
+
test('Harness English overrides the desktop browser language across the whole interface', async t => {
|
|
31
|
+
const { page } = await fixture(t);
|
|
32
|
+
assert.equal(await page.locator('html').getAttribute('lang'), 'en');
|
|
33
|
+
assert.equal(await page.locator('#chat-title').innerText(), 'I’m here. Take your time.');
|
|
34
|
+
assert.equal(await page.locator('#message').getAttribute('placeholder'), 'Continue this conversation…');
|
|
35
|
+
assert.equal(await page.locator('#characters header strong').innerText(), 'Characters and animation');
|
|
36
|
+
assert.equal(await page.locator('#chat-session-name').innerText(), '用户的中文会话');
|
|
37
|
+
assert.match(await page.locator('#menu-chat').innerText(), /Say something/);
|
|
38
|
+
assert.match(await page.locator('#pet').getAttribute('aria-label'), /double-click to chat/);
|
|
39
|
+
assert.equal(await page.locator('#menu-name').innerText(), 'DeepSeek Whale');
|
|
40
|
+
const ownLabels = await page.evaluate(() => [...document.querySelectorAll('#stage button,#stage input,#stage textarea,#stage label,#stage header strong')].flatMap(node => [node.textContent,node.getAttribute('aria-label'),node.getAttribute('placeholder')]).filter(Boolean).filter(text => !text.includes('用户的中文会话')));
|
|
41
|
+
assert.deepEqual(ownLabels.filter(text => /\p{Script=Han}/u.test(text)), [], 'English UI contains no hardcoded Chinese controls');
|
|
42
|
+
});
|
|
43
|
+
test('live language changes refresh open readers and character metadata without rewriting replies', async t => {
|
|
44
|
+
const { page, receive } = await fixture(t);
|
|
45
|
+
await page.locator('#attention').click();
|
|
46
|
+
const reply = await page.locator('#reader-text').innerText();
|
|
47
|
+
await receive({type:'configure',options:{locale:'zh'}});
|
|
48
|
+
assert.equal(await page.locator('#reader-close').getAttribute('aria-label'), '收起完整回复');
|
|
49
|
+
assert.equal(await page.locator('#chat-title').innerText(), '我在,慢慢说。');
|
|
50
|
+
assert.equal(await page.locator('#reader-text').innerText(), reply);
|
|
51
|
+
await receive({type:'configure',options:{locale:'en-US'}});
|
|
52
|
+
assert.equal(await page.locator('#reader-close').getAttribute('aria-label'), 'Close full reply');
|
|
53
|
+
assert.equal(await page.locator('#menu-name').innerText(), 'DeepSeek Whale');
|
|
54
|
+
assert.equal(await page.locator('#reader-text').innerText(), reply);
|
|
55
|
+
await page.keyboard.press('Escape');
|
|
56
|
+
await page.locator('#open-characters').evaluate(node => node.click());
|
|
57
|
+
await page.waitForFunction(() => !document.getElementById('character-use').disabled);
|
|
58
|
+
assert.equal(await page.locator('#character-select option:checked').innerText(), 'DeepSeek Whale');
|
|
59
|
+
assert.match(await page.locator('#character-credit').innerText(), /^Author:/);
|
|
60
|
+
assert.equal(await page.locator('#character-action option:checked').innerText(), 'Wave');
|
|
61
|
+
assert.equal(await page.locator('#character-action').evaluate(node => [...node.options].some(option => /\p{Script=Han}/u.test(option.textContent))), false, 'every built-in action has an English label');
|
|
62
|
+
const selected = await page.locator('#character-scheme').inputValue();
|
|
63
|
+
await receive({type:'configure',options:{locale:'zh-CN'}});
|
|
64
|
+
assert.equal(await page.locator('#character-select option:checked').innerText(), 'DeepSeek 大肥鱼');
|
|
65
|
+
assert.equal(await page.locator('#character-scheme').inputValue(), selected, 'language changes preserve the selected outfit');
|
|
66
|
+
await mkdir('artifacts',{recursive:true}); await page.locator('#characters').screenshot({path:'artifacts/locale-character-zh.png'});
|
|
67
|
+
await receive({type:'configure',options:{locale:'en'}});
|
|
68
|
+
await page.locator('#characters').screenshot({path:'artifacts/locale-character-en.png'});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('clearing the language preference follows the browser again and app diagnostics switch live', async t => {
|
|
72
|
+
const { page, receive } = await fixture(t);
|
|
73
|
+
await receive({type:'configure',options:{notifications:true}});
|
|
74
|
+
await receive({type:'notice',notice:{sessionId:'source',title:'会话尚未就绪',body:'请先回到 Harness 打开这个会话,然后再发送消息。'}});
|
|
75
|
+
assert.equal(await page.locator('#toast-title').innerText(),'Conversation not ready');
|
|
76
|
+
await receive({type:'configure',options:{locale:null}});
|
|
77
|
+
assert.equal(await page.locator('html').getAttribute('lang'),'zh-CN','JSON IPC null clears the previous override');
|
|
78
|
+
assert.equal(await page.locator('#toast-title').innerText(),'会话尚未就绪');
|
|
79
|
+
});
|
package/tests/plugin.test.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { NativeLifecycle, PetBridge } from '../src/bridge.ts';
|
|
|
6
6
|
import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
7
7
|
import { ApprovalRequestId } from '@deepseek-ai/dsh-user-approval';
|
|
8
8
|
import { LlmAttemptId } from '@deepseek-ai/dsh-llm';
|
|
9
|
+
import type { SettingsNamespace } from '@deepseek-ai/dsh-settings';
|
|
9
10
|
|
|
10
11
|
function nativeBridge(): PetBridge {
|
|
11
12
|
const listeners = new Set<(state: NativeLifecycle) => void>(); let generation = 0, revision = 0;
|
|
@@ -20,6 +21,24 @@ function nativeBridge(): PetBridge {
|
|
|
20
21
|
return bridge;
|
|
21
22
|
}
|
|
22
23
|
|
|
24
|
+
it('boots in the durable Harness language and reacts to locale settings independently of notifications', async () => {
|
|
25
|
+
const ctx = new Context(); let preference: string | undefined = 'en';
|
|
26
|
+
ctx.provide('agents', { list: () => [] });
|
|
27
|
+
const describe = vi.fn(() => [{ ns: 'locale', value: { preference } }]);
|
|
28
|
+
ctx.provide('settings', { describe, mutate: vi.fn() });
|
|
29
|
+
const bridge = { ...nativeBridge(), configure: vi.fn() };
|
|
30
|
+
const fiber = ctx.plugin(async ctx => mountPet(ctx, Config({ notifications: false }), bridge));
|
|
31
|
+
try {
|
|
32
|
+
await fiber.await(); await vi.waitFor(() => expect(bridge.start).toHaveBeenCalledOnce());
|
|
33
|
+
expect(bridge.start).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en', notifications: false }), expect.anything());
|
|
34
|
+
expect(describe).toHaveBeenCalledWith({ redactSecrets: true });
|
|
35
|
+
preference = 'zh'; ctx.emit('settings/document-updated', 'locale' as SettingsNamespace, 1);
|
|
36
|
+
expect(bridge.configure).toHaveBeenLastCalledWith(expect.objectContaining({ locale: 'zh' }));
|
|
37
|
+
preference = undefined; ctx.emit('settings/document-updated', 'locale' as SettingsNamespace, 2);
|
|
38
|
+
expect(bridge.configure).toHaveBeenLastCalledWith(expect.objectContaining({ locale: undefined }));
|
|
39
|
+
} finally { await fiber.dispose(); await ctx.fiber.dispose(); }
|
|
40
|
+
});
|
|
41
|
+
|
|
23
42
|
it('uses the real Cordis event bus, delegates approval, logs user input through the agent, and releases resources', async () => {
|
|
24
43
|
const ctx = new Context();
|
|
25
44
|
const session = { id: SessionId('live'), header: { origin: undefined, version: 4, id: SessionId('live'), createdAt: 0, isSeeded: false, cwd: '/project/live' } } as Session;
|
|
@@ -103,14 +122,21 @@ it('registers and disposes exact authenticated Connection routes without taking
|
|
|
103
122
|
let action: ((value: unknown) => void) | undefined;
|
|
104
123
|
const bridge: PetBridge = { ...nativeBridge(), onAction: listener => { action = listener; }, focusHarness: vi.fn() };
|
|
105
124
|
const fiber = ctx.plugin(async scope => mountPet(scope, Config({ autoStart: false }), bridge)); await fiber.await();
|
|
106
|
-
expect([...routes.keys()]).toEqual(['status', 'control', 'navigation', 'notification-state', 'notification-claim', 'notification-receipt', 'notification-snooze', 'notification-test'].map(endpoint => `/api/coopanion/${endpoint}`));
|
|
125
|
+
expect([...routes.keys()]).toEqual(['status', 'control', 'navigation', 'locale', 'notification-state', 'notification-claim', 'notification-receipt', 'notification-snooze', 'notification-test'].map(endpoint => `/api/coopanion/${endpoint}`));
|
|
107
126
|
const invoke = async (payload: unknown) => {
|
|
108
127
|
const response = await routes.get('/api/coopanion/control')!.fetch(new Request('http://localhost/api/coopanion/control', { method: 'POST', body: JSON.stringify({ type: 'client-request', rpcId: 'test', method: 'coopanion/control', payload }) }));
|
|
109
128
|
return response.json();
|
|
110
129
|
};
|
|
111
130
|
expect((await invoke({ command: 'start', electronPath: '/untrusted' })).result.ok).toBe(false);
|
|
112
131
|
expect(bridge.start).not.toHaveBeenCalled();
|
|
132
|
+
const language = async (payload: unknown) => (await routes.get('/api/coopanion/locale')!.fetch(new Request('http://localhost/api/coopanion/locale', { method: 'POST', body: JSON.stringify({ type: 'client-request', rpcId: 'locale-test', method: 'coopanion/locale', payload }) }))).json();
|
|
133
|
+
expect((await language({ locale: 'en', extra: true })).result.ok).toBe(false);
|
|
134
|
+
expect((await language({ locale: 'en-US' })).result.ok).toBe(false);
|
|
135
|
+
expect((await language({ locale: 'zh' })).result).toEqual({ ok: true, value: { locale: 'zh' } });
|
|
136
|
+
expect((await language({ locale: 'en' })).result).toEqual({ ok: true, value: { locale: 'en' } });
|
|
137
|
+
await routes.get('/api/coopanion/notification-state')!.fetch(new Request('http://localhost/api/coopanion/notification-state', { method: 'POST', body: JSON.stringify({ type: 'client-request', rpcId: 'legacy', method: 'coopanion/notification-state', payload: { locale: 'zh' } }) }));
|
|
113
138
|
expect(await invoke({ command: 'start' })).toEqual({ type: 'server-response', rpcId: 'test', result: { ok: true, value: { phase: 'running', visible: true, generation: 1, visibilityRevision: 2, suspended: false } } });
|
|
139
|
+
expect(bridge.start).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en' }), expect.anything());
|
|
114
140
|
const malformed = await routes.get('/api/coopanion/status')!.fetch(new Request('http://localhost/api/coopanion/status', { method: 'POST', body: '{}' }));
|
|
115
141
|
expect(malformed.status).toBe(400);
|
|
116
142
|
expect(bridge.update).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'existing' }));
|
|
@@ -3,6 +3,21 @@ import { createSpeech, replyPreview } from '../web/speech.js';
|
|
|
3
3
|
import { shortSessionIds, sessionActivity, inboxContents } from '../web/session-ui.js';
|
|
4
4
|
import tray from '../desktop/tray-state.cjs';
|
|
5
5
|
|
|
6
|
+
it('resolves native language before the first Host configuration arrives', () => {
|
|
7
|
+
expect(tray.trayLocale(undefined, {}, ['zh-CN'])).toBe('zh');
|
|
8
|
+
expect(tray.trayLocale(undefined, {}, ['fr-FR','en-US'])).toBe('en');
|
|
9
|
+
expect(tray.trayLocale({ locale:'en' }, { locale:'zh' }, ['zh-CN'])).toBe('en');
|
|
10
|
+
expect(tray.trayLocale({ locale:null }, { locale:'zh' }, ['en-US'])).toBe('zh');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it('uses the Harness language for native tray labels and preserves user session titles', () => {
|
|
14
|
+
const snapshot = { sessionId:'locale-source',mood:'thinking',active:true,sessions:[{id:'locale-source',label:'用户的中文会话',mood:'thinking',active:true}] };
|
|
15
|
+
const state = tray.trayState(snapshot, {}, { locale:'en' }, true);
|
|
16
|
+
expect(state.stateLabel).toBe('Thinking');
|
|
17
|
+
expect(state.tooltip).toContain('Focused: 用户的中文会话');
|
|
18
|
+
expect(state.sessionLabel).toBe('用户的中文会话');
|
|
19
|
+
});
|
|
20
|
+
|
|
6
21
|
it('keeps the visible Unicode prefix and punctuation pause when live speech is extended', () => {
|
|
7
22
|
const node = { textContent: '' }, spoken = [];
|
|
8
23
|
const speech = createSpeech({ text: '你好,', node, onCharacter: ch => spoken.push(ch) });
|
|
@@ -23,7 +38,7 @@ it('distinguishes host IDs with the same session prefix and collision-prone firs
|
|
|
23
38
|
|
|
24
39
|
it('projects selected session, appearance, visibility and preferences into the macOS status bar', () => {
|
|
25
40
|
const snapshot = { sessionId: 'b', mood: 'talking', active: true, sessions: [{ id: 'a', label: '菜单' }, { id: 'b', label: '修复同步', mood: 'talking' }] };
|
|
26
|
-
const state = tray.trayState(snapshot, { characterId: 'whale', scheme: 'harness', name: '大肥鱼', sleeping: true, sound: false }, { roam: false, notifications: false }, true);
|
|
41
|
+
const state = tray.trayState(snapshot, { characterId: 'whale', scheme: 'harness', name: '大肥鱼', sleeping: true, sound: false }, { locale: 'zh', roam: false, notifications: false }, true);
|
|
27
42
|
expect(state).toMatchObject({ sessionId: 'b', sessionLabel: '修复同步', mood: 'talking', title: '', icon: 'talking', sleeping: false, characterId: 'whale', scheme: 'harness', visible: true, roam: false, notifications: false, sound: false });
|
|
28
43
|
expect(state.sessions.map(s => s.selected)).toEqual([true, false]);
|
|
29
44
|
expect(state.tooltip).toContain('正在回复');
|
|
@@ -25,7 +25,7 @@ const other = { ...source, id: 'other', label: '另一段会话', unread: 1 };
|
|
|
25
25
|
const reply = (id, sessionId, time, text) => ({ id, sessionId, time, text, read: false });
|
|
26
26
|
const frame = results => ({ mood: 'idle', active: false, sessionId: focus.id, sessions: [focus, source, other], results });
|
|
27
27
|
async function fixture(t, results) {
|
|
28
|
-
const page = await browser.newPage({ viewport: { width: 1000, height: 800 }, reducedMotion: 'reduce' });
|
|
28
|
+
const page = await browser.newPage({ locale: 'zh-CN', viewport: { width: 1000, height: 800 }, reducedMotion: 'reduce' });
|
|
29
29
|
t.after(() => page.close());
|
|
30
30
|
page.setDefaultTimeout(5000);
|
|
31
31
|
const errors = []; page.on('pageerror', error => errors.push(error.message));
|
package/tests/ui.mjs
CHANGED
|
@@ -15,7 +15,7 @@ const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PAT
|
|
|
15
15
|
const speechDone = page => page.waitForSelector('#bubble[data-typing=false]');
|
|
16
16
|
const mainFrame = page => page.locator('#body-layer iframe').contentFrame();
|
|
17
17
|
try {
|
|
18
|
-
const page = await browser.newPage({ viewport: { width: 1200, height: 800 } });
|
|
18
|
+
const page = await browser.newPage({ locale: 'zh-CN', viewport: { width: 1200, height: 800 } });
|
|
19
19
|
page.setDefaultTimeout(12000);
|
|
20
20
|
const errors = []; page.on('pageerror', error => errors.push(error.message));
|
|
21
21
|
const petClick = async (options = {}, twice = false) => {
|