@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/web/pet.js CHANGED
@@ -4,6 +4,7 @@ import { createSpeech, replyPreview } from './speech.js';
4
4
  import { createNoticeQueue, pendingInteractions, notificationPresentation, notificationCopy } from './notification-ui.js';
5
5
  import { shortSessionIds, sessionTime, sessionActivity, inboxContents, unreadReplies } from './session-ui.js';
6
6
  import { renderReplyMarkdown } from './markdown-runtime.js';
7
+ import { petLanguage, petCopy, localizedText, appNoticeCopy, automaticPetLanguage } from './locale.js';
7
8
  const PACK_LIMIT = 128 * 1024 * 1024;
8
9
  import { browserCharacters } from './character-library.js';
9
10
  const BUILTIN_ID = 'whale';
@@ -14,16 +15,18 @@ const interaction = $('interaction'), requests = $('requests');
14
15
  const panels = [conversations, chat, menu, characters, reader, requests];
15
16
  const noticeQueue = createNoticeQueue();
16
17
  let notificationState, currentNotice, interactionExpires = 0;
18
+ let toastNotice;
17
19
  const snoozing = new Map();
18
- const notificationLocale = () => options.locale ?? document.documentElement.lang ?? navigator.language;
20
+ const notificationLocale = () => options.locale ? petLanguage(options.locale) : automaticPetLanguage(navigator.languages ?? [navigator.language]);
21
+ const uiCopy = () => petCopy(notificationLocale());
19
22
  const pendingRequests = () => pendingInteractions(notificationState);
20
23
  const userInputOccupied = () => pressing || dragging || panels.some(p => !p.hidden) || !bubble.hidden;
21
24
  const userOccupied = () => userInputOccupied() || body?.layout?.busy;
22
25
  const panelAnchors = new WeakMap();
23
- const labels = { idle: '在这里陪你', thinking: '正在思考', talking: '正在回复', working: '正在忙', waiting: '等你确认', happy: '完成啦', error: '需要关注', sleeping: '休息中' };
24
26
  const library = native?.characters ?? browserCharacters;
25
27
  const sfx = createSfx({ storageKey: 'dsh-pet.sound.v2', volume: .35 });
26
- const nameIn = names => names?.zh ?? names?.en ?? Object.values(names ?? {})[0] ?? '';
28
+ const nameIn = names => localizedText(names, notificationLocale());
29
+ const wordName = (word, view = previewCharacter) => word.names?.[notificationLocale()]?.[0] ?? (view?.builtin ? uiCopy().words[word.id] : undefined) ?? nameIn(word.names)?.[0] ?? word.id;
27
30
  let body, previewBody, previewCharacter, activeView, activeScheme, activeName = 'DeepSeek 大肥鱼', libraryState, libraryBusy = false;
28
31
  let appliedMood, appliedControls, speech, speechExpires = Infinity, pressing = false, dragStart, dragging = false, previewScheme = "", reducedNeedsStep = true;
29
32
  let options = { size: 180, roam: true, notifications: true, bubbleDurationMs: 12000 };
@@ -35,6 +38,8 @@ let bubbleResult, readerResult, pendingOnly = false, talkAt = 0;
35
38
  let readerQueue, inboxState = { requests: [], issues: [], replies: [], total: 0 };
36
39
  let resizeLayout;
37
40
  const shownResults = new Set(), acknowledgedResults = new Set();
41
+ let renderedLocale;
42
+ let characterFeedback = { key: 'characterHint', args: [] };
38
43
  const motionPreference = matchMedia('(prefers-reduced-motion: reduce)');
39
44
  let reduced = motionPreference.matches;
40
45
  motionPreference.addEventListener('change', event => { reduced = event.matches; });
@@ -53,6 +58,45 @@ function send(action) {
53
58
  }
54
59
  }
55
60
 
61
+ function setCopyNode(id, key) { const node = $(id); node.dataset.i18n = key; node.textContent = uiCopy()[key]; }
62
+ function characterStatus(key, ...args) {
63
+ characterFeedback = { key, args }; delete $('character-status').dataset.i18n;
64
+ const value = uiCopy()[key]; $('character-status').textContent = typeof value === 'function' ? value(...args) : value;
65
+ }
66
+ function refreshPreviewCopy() {
67
+ const view = previewCharacter; if (!view) return;
68
+ for (const option of $('character-action').options) { const word = view.vocab.find(word => word.id === option.value); if (word) option.textContent = wordName(word); }
69
+ const selected = $('character-scheme').value; fillSchemes(view, previewScheme); $('character-scheme').value = selected;
70
+ $('character-about').textContent = nameIn(view.about);
71
+ $('character-credit').textContent = uiCopy().authorCredit(view.author ?? uiCopy().unknownAuthor, view.credits?.map(c => c.name).join('、') ?? '', view.builtin ? uiCopy().builtinLicense : view.license ?? uiCopy().authorLicense);
72
+ }
73
+ function applyLocale() {
74
+ const locale = notificationLocale(); if (renderedLocale === locale) return;
75
+ renderedLocale = locale;
76
+ const text = uiCopy(), notice = notificationCopy(locale);
77
+ document.documentElement.lang = locale === 'zh' ? 'zh-CN' : 'en'; document.title = text.title;
78
+ const lookup = key => key.startsWith('notice:') ? notice[key.slice(7)] : key.startsWith('demo:') ? text.demoButtons[key.slice(5)] : text[key];
79
+ for (const [attribute, target] of [['data-i18n', null], ['data-i18n-aria-label', 'aria-label'], ['data-i18n-placeholder', 'placeholder'], ['data-i18n-title', 'title']]) {
80
+ for (const node of document.querySelectorAll(`[${attribute}]`)) {
81
+ const value = lookup(node.getAttribute(attribute));
82
+ if (typeof value !== 'string') throw new Error(`Missing locale text: ${node.getAttribute(attribute)}`);
83
+ if (target) node.setAttribute(target, value); else node.textContent = value;
84
+ }
85
+ }
86
+ activeName = activeView ? nameIn(activeView.name) : text.defaultName;
87
+ $('chat-character').textContent = activeName; $('menu-name').textContent = activeName;
88
+ pet.setAttribute('aria-label', text.petLabel(activeName));
89
+ if (bubbleResult) bubble.setAttribute('aria-label', text.finalReply(snapshot.sessions.find(session => session.id === bubbleResult.sessionId)?.label ?? activeName));
90
+ if (libraryState) for (const option of $('character-select').options) { const view = libraryState.characters.find(view => view.id === option.value); if (view) option.textContent = nameIn(view.name); }
91
+ refreshPreviewCopy(); characterStatus(characterFeedback.key, ...characterFeedback.args);
92
+ if (currentNotice && !interaction.hidden) {
93
+ const value = notificationPresentation(currentNotice, locale, body?.words ?? []);
94
+ $('interaction-title').textContent = value.title; $('interaction-preview').textContent = value.body;
95
+ }
96
+ if (toastNotice && !$('toast').hidden) { const value = appNoticeCopy(toastNotice, locale); $('toast-title').textContent = value.title; $('toast-body').textContent = value.body; }
97
+ trayKey = undefined;
98
+ }
99
+
56
100
  function bounds() { return { W: innerWidth, H: innerHeight, floorY: innerHeight - 24, S: options.size / 256 }; }
57
101
  function previewBounds() { const el = $('character-preview'); return { W: el.clientWidth, H: el.clientHeight, floorY: el.clientHeight - 14, S: Math.min(el.clientWidth, el.clientHeight - 22) / 256 }; }
58
102
  function position() {
@@ -96,7 +140,7 @@ function speak(result) {
96
140
  const source = snapshot.sessions.find(session => session.id === result.sessionId);
97
141
  const preview = replyPreview(result.text);
98
142
  $('bubble-status').textContent = source?.label ?? '';
99
- bubble.setAttribute('aria-label', `${source?.label ?? activeName}的最终回复`);
143
+ bubble.setAttribute('aria-label', uiCopy().finalReply(source?.label ?? activeName));
100
144
  bubbleSession = result.sessionId; bubbleResult = result;
101
145
  $('bubble-session').hidden = !bubbleSession;
102
146
  $('bubble-expand').hidden = !preview.long;
@@ -135,8 +179,8 @@ function openReader(result, queue) {
135
179
  panels.forEach(p => { p.hidden = true; }); bubble.hidden = true; reader.hidden = false;
136
180
  readerResult = result; readerQueue = queue;
137
181
  const source = snapshot.sessions.find(s => s.id === result.sessionId);
138
- $('reader-title').textContent = source?.label ?? '会话回复';
139
- $('reader-detail').textContent = `${source?.project ?? ''} · ${sessionTime({ updatedAt: result.time })}`;
182
+ $('reader-title').textContent = source?.label ?? uiCopy().sessionReply;
183
+ $('reader-detail').textContent = `${source?.project ?? ''} · ${sessionTime({ updatedAt: result.time }, notificationLocale())}`;
140
184
  renderReplyMarkdown($('reader-text'), result.text); $('reader-text').scrollTop = 0;
141
185
  updateReaderNavigation(); acknowledge(result); updateMood(); position(); $('reader-text').focus();
142
186
  }
@@ -148,12 +192,17 @@ function updateReaderNavigation() {
148
192
  const index = history.findIndex(r => r.id === readerResult?.id);
149
193
  $('reader-count').textContent = `${Math.max(1, index + 1)} / ${Math.max(1, history.length)}`;
150
194
  $('reader-prev').disabled = index <= 0; $('reader-next').disabled = index < 0 || index >= history.length - 1;
195
+ if (readerResult) {
196
+ const source = snapshot.sessions.find(session => session.id === readerResult.sessionId);
197
+ $('reader-detail').textContent = `${source?.project ?? ''} · ${sessionTime({ updatedAt: readerResult.time }, notificationLocale())}`;
198
+ }
151
199
  }
152
200
  function react(mood) { reactionMood = mood; reactionUntil = performance.now() + 700; }
153
201
  function act(actor, pack, word) {
154
202
  if (pack?.vocab.some(w => w.id === word) && (!actor.words || actor.words.includes(word))) actor.do(word);
155
203
  }
156
204
  function updateMood(now = performance.now()) {
205
+ const labels = uiCopy().labels;
157
206
  const activity = sessionActivity(snapshot), active = activity.active;
158
207
  if (active || activity.waiting || activity.errors) asleep = false;
159
208
  const mood = now < reactionUntil && !userInputOccupied() ? reactionMood : active || activity.waiting || activity.errors ? activity.mood : pendingRequests().length ? 'waiting' : asleep ? 'sleeping' : activity.mood;
@@ -173,16 +222,17 @@ function updateMood(now = performance.now()) {
173
222
  if (key !== appliedControls) { if (controls.roam === 'off') body.stopWalk(0); body.set(controls); appliedControls = key; }
174
223
  $('toggle-roam').setAttribute('aria-checked', String(options.roam));
175
224
  $('toggle-sleep').setAttribute('aria-checked', String(asleep));
176
- $('toggle-sleep').disabled = active; $('toggle-sleep').title = active ? '正在忙,完成后再休息' : '有新的任务会自动醒来';
225
+ $('toggle-sleep').disabled = active; $('toggle-sleep').title = active ? uiCopy().sleepBusy : uiCopy().sleepWake;
177
226
  $('toggle-notices').setAttribute('aria-checked', String(options.notifications));
178
227
  $('toggle-sound').setAttribute('aria-checked', String(sfx.isOn()));
179
- $('menu-state').textContent = `${labels[mood] ?? labels.idle}${snapshot.sessionId ? ' · 有会话相伴' : ''}`;
180
- const presentation = { type: 'presentation', characterId: activeView.id, scheme: activeScheme, name: activeName, mood, sleeping: asleep, sound: sfx.isOn(), ready: !!body.layout };
228
+ $('menu-state').textContent = `${labels[mood] ?? labels.idle}${snapshot.sessionId ? ' · ' + uiCopy().connected : ''}`;
229
+ const presentation = { type: 'presentation', locale: notificationLocale(), characterId: activeView.id, scheme: activeScheme, name: activeName, mood, sleeping: asleep, sound: sfx.isOn(), ready: !!body.layout };
181
230
  const nextTrayKey = JSON.stringify(presentation);
182
231
  if (nextTrayKey !== trayKey) { trayKey = nextTrayKey; native?.action(presentation); }
183
232
  }
184
233
 
185
234
  function render() {
235
+ applyLocale(); const labels = uiCopy().labels;
186
236
  const previous = renderedSessionId;
187
237
  const selected = snapshot.sessions.find(session => session.id === snapshot.sessionId);
188
238
  const shortIds = shortSessionIds(snapshot.sessions);
@@ -193,7 +243,7 @@ function render() {
193
243
  const needsYou = s => ['waiting', 'error'].includes(s.mood) || pendingRequests().some(item => item.sessionId === s.id);
194
244
  const matches = snapshot.sessions.filter(session => (!pendingOnly || hasUnread(session) || needsYou(session)) && [session.label, session.project, session.cwd, session.prompt, session.id].join(' ').toLocaleLowerCase().includes(query));
195
245
  matches.sort((a, b) => Number(needsYou(b)) - Number(needsYou(a)) || Number(hasUnread(b)) - Number(hasUnread(a)) || Number(b.id === snapshot.sessionId) - Number(a.id === snapshot.sessionId) || (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
196
- const listKey = JSON.stringify([query, pendingOnly, matches.map(session => [session.id, session.label, session.prompt, session.cwd, session.updatedAt, session.mood, hasUnread(session), session.chatAvailable, session.id === snapshot.sessionId])]);
246
+ const listKey = JSON.stringify([notificationLocale(), query, pendingOnly, matches.map(session => [session.id, session.label, session.prompt, session.cwd, session.updatedAt, session.mood, hasUnread(session), session.chatAvailable, session.id === snapshot.sessionId])]);
197
247
  if (list.dataset.key !== listKey) {
198
248
  const activeId = document.activeElement?.dataset?.sessionId;
199
249
  const entries = matches.map(session => {
@@ -203,21 +253,21 @@ function render() {
203
253
  card.tabIndex = session.id === snapshot.sessionId ? 0 : -1;
204
254
  card.title = `${session.label}\n${session.prompt ?? ''}\n${session.cwd ?? session.project ?? ''}\n${session.id}`;
205
255
  const copy = document.createElement('span'), meta = document.createElement('small'), status = document.createElement('em'), time = document.createElement('span'), name = document.createElement('strong'), detail = document.createElement('small'), prompt = document.createElement('small'), mark = document.createElement('b');
206
- meta.className = 'session-meta'; status.textContent = `${session.id === snapshot.sessionId ? '关注 · ' : ''}${labels[session.mood] ?? labels.idle}${hasUnread(session) ? ' · 1 份未读' : ''}${session.chatAvailable === false ? ' · 未打开' : ''}`;
207
- time.textContent = sessionTime(session); meta.append(status, time);
208
- name.textContent = session.label; detail.className = 'session-detail'; detail.textContent = `${session.cwd || session.project || '会话'} · #${shortIds.get(session.id)}`;
209
- prompt.className = 'session-prompt'; prompt.textContent = session.prompt && session.prompt !== session.label ? `最近:${session.prompt}` : ''; prompt.hidden = !prompt.textContent;
256
+ meta.className = 'session-meta'; status.textContent = `${session.id === snapshot.sessionId ? uiCopy().focused + ' · ' : ''}${labels[session.mood] ?? labels.idle}${hasUnread(session) ? ' · ' + uiCopy().unread : ''}${session.chatAvailable === false ? ' · ' + uiCopy().notOpen : ''}`;
257
+ time.textContent = sessionTime(session, notificationLocale()); meta.append(status, time);
258
+ name.textContent = session.label; detail.className = 'session-detail'; detail.textContent = `${session.cwd || session.project || uiCopy().session} · #${shortIds.get(session.id)}`;
259
+ prompt.className = 'session-prompt'; prompt.textContent = session.prompt && session.prompt !== session.label ? uiCopy().recent(session.prompt) : ''; prompt.hidden = !prompt.textContent;
210
260
  mark.textContent = '✓'; mark.setAttribute('aria-hidden', 'true');
211
261
  copy.append(meta, name, prompt, detail); card.append(copy, mark); return card;
212
262
  });
213
263
  if (!entries.length) {
214
- const empty = document.createElement('p'); empty.className = 'conversation-empty'; empty.textContent = query ? '没找到这段对话。试试提问里的词或项目名?' : pendingOnly ? '都看过啦,安心做手边的事。' : '还没有可用的对话。先在 Harness 中打开一段对话,我就能听见它。'; entries.push(empty);
264
+ const empty = document.createElement('p'); empty.className = 'conversation-empty'; empty.textContent = query ? uiCopy().emptySearch : pendingOnly ? uiCopy().emptyPending : uiCopy().emptySessions; entries.push(empty);
215
265
  }
216
266
  list.replaceChildren(...entries); list.dataset.key = listKey;
217
267
  if (activeId) list.querySelector(`[data-session-id="${CSS.escape(activeId)}"]`)?.focus();
218
268
  }
219
269
  const activity = sessionActivity(snapshot);
220
- $('conversation-count').textContent = `${activity.busy} 段进行中 · ${snapshot.results ? unreadSources.size : activity.unread} 份未读回复`;
270
+ $('conversation-count').textContent = uiCopy().activity(activity.busy, snapshot.results ? unreadSources.size : activity.unread);
221
271
  $('sessions-all').setAttribute('aria-pressed', String(!pendingOnly)); $('sessions-pending').setAttribute('aria-pressed', String(pendingOnly));
222
272
  inboxState = inboxContents(snapshot, pendingRequests(), acknowledgedResults);
223
273
  const pendingCount = inboxState.requests.length + inboxState.issues.length;
@@ -225,9 +275,9 @@ function render() {
225
275
  $('attention-count').textContent = String(inboxState.total);
226
276
  $('attention').dataset.urgent = String(!!pendingCount);
227
277
  $('attention').title = $('attention').ariaLabel = notificationCopy(notificationLocale()).inboxSummary(inboxState.replies.length, pendingCount);
228
- $('chat-current').disabled = !snapshot.sessions.length; $('chat-session-name').textContent = selected?.label ?? '还没有对话';
229
- $('chat-current').setAttribute('aria-label', selected ? `当前对话:${selected.label}。点击切换` : '还没有可用的对话');
230
- $('chat-session-state').textContent = labels[selected?.mood] ?? '正在陪你聊';
278
+ $('chat-current').disabled = !snapshot.sessions.length; $('chat-session-name').textContent = selected?.label ?? uiCopy().noSession;
279
+ $('chat-current').setAttribute('aria-label', selected ? uiCopy().chatTarget(selected.label) : uiCopy().emptySessions);
280
+ $('chat-session-state').textContent = labels[selected?.mood] ?? labels.idle;
231
281
  $('chat-session-detail').textContent = selected ? `${selected.cwd || selected.project || ''} · #${shortIds.get(selected.id)}` : '';
232
282
  const latestReply = snapshot.results?.find(r => r.id === selected?.replyId)?.text || selected?.reply || '';
233
283
  $('chat-reply').textContent = latestReply ? replyPreview(latestReply).text : ''; $('chat-reply').hidden = !latestReply;
@@ -235,7 +285,7 @@ function render() {
235
285
  const enabled = !!snapshot.sessionId && selected?.chatAvailable !== false;
236
286
  $('message').disabled = !enabled; $('send').disabled = !enabled;
237
287
  $('conversation-open').disabled = !snapshot.sessionId; $('chat-session').disabled = !snapshot.sessionId;
238
- $('chat-help').textContent = enabled ? `消息交给「${selected.label}」,完成后只展示最终回复。` : snapshot.sessionId ? '这段对话尚未在 Harness 中打开,请先回去打开它。' : '先在 Harness 中打开一段对话,就可以从这里和我说话。';
288
+ $('chat-help').textContent = enabled ? uiCopy().chatHelp(selected.label) : snapshot.sessionId ? uiCopy().unavailableChat : uiCopy().noChat;
239
289
  if (previous !== snapshot.sessionId) {
240
290
  $('message').value = ''; bubble.hidden = true;
241
291
  clearTimeout(touchTimer); reactionUntil = 0;
@@ -298,7 +348,7 @@ function renderRequests() {
298
348
  const card = document.createElement('article'); card.className = 'inbox-card inbox-issue';
299
349
  const meta = document.createElement('small'), label = document.createElement('strong'), preview = document.createElement('p'), actions = document.createElement('div'), open = document.createElement('button');
300
350
  meta.textContent = `${session.mood === 'error' ? copy.errorLabel : copy.waitingLabel} · ${sourceDetail(session.id)}`;
301
- label.textContent = session.label; preview.textContent = session.text;
351
+ label.textContent = session.label; preview.textContent = session.mood === 'error' ? petCopy(notificationLocale()).issueError : petCopy(notificationLocale()).issueWaiting;
302
352
  open.textContent = copy.handle; open.dataset.inboxKey = session.id; open.dataset.action = 'open'; open.onclick = () => openSession(session.id);
303
353
  actions.append(open); card.append(meta, label, preview, actions); return card;
304
354
  }));
@@ -310,7 +360,7 @@ function renderRequests() {
310
360
  content.ariaLabel = `${copy.readReply} · ${sources.get(result.sessionId)?.label ?? result.sessionId}`;
311
361
  // Capture the queue at the explicit read action so incoming replies cannot reorder it.
312
362
  content.onclick = () => openReader(result, inboxContents(snapshot, pendingRequests(), acknowledgedResults).replies.map(item => ({ ...item })));
313
- meta.textContent = `${copy.newReply} · ${sessionTime({ updatedAt: result.time })}`;
363
+ meta.textContent = `${copy.newReply} · ${sessionTime({ updatedAt: result.time }, notificationLocale())}`;
314
364
  label.textContent = sources.get(result.sessionId)?.label ?? result.sessionId;
315
365
  preview.className = 'inbox-preview'; preview.textContent = replyPreview(result.text).text;
316
366
  detail.textContent = `${sourceDetail(result.sessionId)} · ${copy.readReply}`;
@@ -383,8 +433,10 @@ function receive(message) {
383
433
  // Task notices are expressed by the body and inbox, not another status card.
384
434
  if (message.notice.kind === 'task') { body?.cue('perk'); break; }
385
435
  noticeSession = message.notice.sessionId;
386
- $('toast-title').textContent = message.notice.title;
387
- $('toast-body').textContent = message.notice.body;
436
+ toastNotice = message.notice;
437
+ const toast = appNoticeCopy(message.notice, notificationLocale());
438
+ $('toast-title').textContent = toast.title;
439
+ $('toast-body').textContent = toast.body;
388
440
  $('toast').hidden = false; clearTimeout(toastTimer);
389
441
  toastTimer = setTimeout(() => { $('toast').hidden = true; }, options.bubbleDurationMs); break;
390
442
  }
@@ -501,7 +553,7 @@ $('chat-form').onsubmit = event => {
501
553
  if (!native) {
502
554
  const sessionId = snapshot.sessionId;
503
555
  demoState(sessionId, 'thinking');
504
- setTimeout(() => demoComplete(sessionId, `收到「${text}」!这是演示回复。真实插件会使用 Harness 的模型。`), 350);
556
+ setTimeout(() => demoComplete(sessionId, uiCopy().demoReply(text)), 350);
505
557
  }
506
558
  };
507
559
  function preference(field) {
@@ -587,16 +639,16 @@ else {
587
639
  options.size = 190; document.documentElement.style.setProperty('--size', '190px');
588
640
  snapshot.results = [];
589
641
  snapshot.sessionId = 'demo'; snapshot.sessions = [
590
- { id: 'demo', label: '演示会话', project: 'dsh-coopanion', cwd: '/workspace/dsh-coopanion', prompt: '让角色在思考与回复时做出对应的动作', createdAt: Date.now() - 3600000, updatedAt: Date.now(), mood: 'idle', text: snapshot.text, revision: 0 },
591
- { id: 'demo-notes', label: '另一个想法', project: 'dsh-coopanion', cwd: '/workspace/dsh-coopanion', prompt: '重做角色菜单与会话选择,让它更像伙伴', createdAt: Date.now() - 7200000, updatedAt: Date.now() - 1800000, mood: 'idle', text: '', revision: 0 },
642
+ { id: 'demo', label: uiCopy().demoSession, project: 'dsh-coopanion', cwd: '/workspace/dsh-coopanion', prompt: uiCopy().demoPrompt, createdAt: Date.now() - 3600000, updatedAt: Date.now(), mood: 'idle', text: snapshot.text, revision: 0 },
643
+ { id: 'demo-notes', label: uiCopy().demoOther, project: 'dsh-coopanion', cwd: '/workspace/dsh-coopanion', prompt: uiCopy().demoOtherPrompt, createdAt: Date.now() - 7200000, updatedAt: Date.now() - 1800000, mood: 'idle', text: '', revision: 0 },
592
644
  ];
593
- const texts = { thinking: '让我想一想,怎样把这个功能做好…', talking: '我想到了。让思考、说话与工作各有自己的动作,就能一眼看出这段对话在做什么。', working: '正在看文件 · src/index.ts', waiting: '下一步需要你确认。真实插件会引导你回到 Harness。', happy: '任务完成啦!要不要休息一下?🐳', error: '任务遇到了问题,请回到 Harness 查看详情。' };
645
+
594
646
  document.querySelectorAll('[data-demo]').forEach(button => { button.onclick = () => {
595
647
  const mood = button.dataset.demo;
596
- if (mood === 'happy') demoComplete(snapshot.sessionId, texts.happy);
597
- else if (mood === 'long') demoComplete(snapshot.sessionId, '动画、气泡和会话的展示已经分开了。\n\n' + '思考和工具调用由动作表达,最终回复可以展开阅读。长内容会完整保留,不会在一千二百字处截断。\n\n'.repeat(35) + '最后一句:这份回复完整地保留下来了。');
598
- else if (mood === 'background') demoComplete(snapshot.sessions.find(s => s.id !== snapshot.sessionId).id, '后台会话已经完成,这是它的最终回复。');
599
- else demoState(snapshot.sessionId, mood, texts[mood]);
648
+ if (mood === 'happy') demoComplete(snapshot.sessionId, uiCopy().demoTexts.happy);
649
+ else if (mood === 'long') demoComplete(snapshot.sessionId, uiCopy().demoLong);
650
+ else if (mood === 'background') demoComplete(snapshot.sessions.find(s => s.id !== snapshot.sessionId).id, uiCopy().demoBackground);
651
+ else demoState(snapshot.sessionId, mood, uiCopy().demoTexts[mood]);
600
652
  }; });
601
653
  y = innerHeight - pet.offsetHeight - 42; render();
602
654
  }
@@ -605,7 +657,7 @@ async function setCharacter(view, scheme = '') {
605
657
  const next = await loadBody({ layer: $('body-layer'), pack: view, start: { x: body?.layout?.x ?? innerWidth * .68, facing: body?.layout?.facing ?? 1, scheme }, theme: 'light', bounds: bounds(),
606
658
  onSound: (name, kind, ...args) => sfx.play(name, kind, ...args),
607
659
  onEvent: (kind, detail) => { if (body === next) onBody(kind, detail); },
608
- onError: error => { $('character-status').textContent = `角色运行失败:${error.message}`; if (body === next && view.id !== BUILTIN_ID) void restoreBuiltin(); },
660
+ onError: error => { characterStatus('bodyError', error.message); if (body === next && view.id !== BUILTIN_ID) void restoreBuiltin(); },
609
661
  });
610
662
  body?.dispose(); body = next; activeView = view; activeScheme = knownScheme(view, scheme); activeName = nameIn(view.name);
611
663
  // A new body has not reported its geometry yet. Retire the previous body's
@@ -615,7 +667,7 @@ async function setCharacter(view, scheme = '') {
615
667
  sfx.usePack(view.base, view.sounds);
616
668
  pet.dataset.character = view.id; pet.dataset.scheme = activeScheme;
617
669
  applyAppearance();
618
- pet.setAttribute('aria-label', `${activeName},点击互动,双击聊天,右键菜单,拖动移动`);
670
+ pet.setAttribute('aria-label', uiCopy().petLabel(activeName));
619
671
  render();
620
672
  }
621
673
  function applyAppearance() {
@@ -632,7 +684,7 @@ function applyAppearance() {
632
684
  }
633
685
  async function restoreBuiltin() {
634
686
  try { const view = await library.load(BUILTIN_ID); await setCharacter(view); await library.select(BUILTIN_ID, activeScheme); }
635
- catch (error) { $('character-status').textContent = `无法加载内置角色:${error.message}`; }
687
+ catch (error) { characterStatus('builtinError', error.message); }
636
688
  }
637
689
  function setBusy(value) {
638
690
  libraryBusy = value;
@@ -644,7 +696,7 @@ function setBusy(value) {
644
696
  function fillSchemes(pack, scheme) {
645
697
  previewScheme = knownScheme(pack, scheme);
646
698
  const choices = pack.presets.map(p => new Option(nameIn(p.name) || p.id, p.id));
647
- choices.push(new Option(pack.axes.length ? '自定义搭配' : '默认', '__custom'));
699
+ choices.push(new Option(pack.axes.length ? uiCopy().customOutfit : uiCopy().defaultScheme, '__custom'));
648
700
  $('character-scheme').replaceChildren(...choices);
649
701
  $('character-scheme').value = pack.presets.some(p => p.id === previewScheme) ? previewScheme : '__custom';
650
702
  const preset = pack.presets.find(p => p.id === previewScheme), parts = previewScheme.split('-');
@@ -660,15 +712,15 @@ async function preview(id) {
660
712
  previewCharacter = undefined; previewBody?.dispose(); previewBody = undefined;
661
713
  const view = await library.load(id);
662
714
  fillSchemes(view, libraryState.schemes[id]);
663
- $('character-action').replaceChildren(...view.vocab.map(w => new Option(w.names.zh?.[0] ?? w.id, w.id)));
715
+ $('character-action').replaceChildren(...view.vocab.map(w => new Option(wordName(w, view), w.id)));
664
716
  $('character-action').value = view.vocab.some(w => w.id === 'wave') ? 'wave' : view.vocab[0]?.id ?? '';
665
717
  const next = await loadBody({ layer: $('character-preview'), pack: view, start: { x: previewBounds().W / 2, facing: 1, scheme: previewScheme }, theme: 'light', bounds: previewBounds(),
666
- onError: error => { previewCharacter = undefined; $('character-status').textContent = `预览失败:${error.message}`; setBusy(false); },
718
+ onError: error => { previewCharacter = undefined; characterStatus('previewError', error.message); setBusy(false); },
667
719
  });
668
720
  previewBody = next; previewBody.set({ roam: 'off' }); previewCharacter = view;
669
721
  $('character-about').textContent = nameIn(view.about);
670
- $('character-credit').textContent = `作者:${view.author ?? '未注明'} · ${view.credits?.map(c => c.name).join('、') ?? ''} · 许可:${view.builtin ? '代码 AGPL-3.0-or-later;素材见权利声明' : view.license ?? '由角色作者注明'}`;
671
- $('character-use').textContent = pet.dataset.character === id ? '正在使用' : '使用角色';
722
+ $('character-credit').textContent = uiCopy().authorCredit(view.author ?? uiCopy().unknownAuthor, view.credits?.map(c => c.name).join('、') ?? '', view.builtin ? uiCopy().builtinLicense : view.license ?? uiCopy().authorLicense);
723
+ setCopyNode('character-use', pet.dataset.character === id ? 'using' : 'useCharacter');
672
724
  }
673
725
  async function refreshCharacters(selected) {
674
726
  libraryState = await library.list();
@@ -676,13 +728,13 @@ async function refreshCharacters(selected) {
676
728
  $('character-select').value = selected ?? libraryState.selected;
677
729
  if (!$('character-select').value) $('character-select').value = BUILTIN_ID;
678
730
  await preview($('character-select').value);
679
- if (libraryState.problems.length) $('character-status').textContent = libraryState.problems.join(';');
731
+ if (libraryState.problems.length) characterStatus('operationError', libraryState.problems.join('; '));
680
732
  }
681
733
  async function characterOperation(operation) {
682
734
  if (libraryBusy) return;
683
735
  setBusy(true);
684
736
  try { await operation(); }
685
- catch (error) { $('character-status').textContent = `操作未完成:${String(error.message ?? error).slice(0, 400)}`; }
737
+ catch (error) { characterStatus('operationError', String(error.message ?? error).slice(0, 400)); }
686
738
  finally { setBusy(false); position(); }
687
739
  }
688
740
  $('open-characters').onclick = () => {
@@ -696,23 +748,23 @@ $('character-scheme').onchange = () => void characterOperation(async () => {
696
748
  const custom = [...$('character-axes').querySelectorAll('select')].map(el => el.value).join('-');
697
749
  fillSchemes(previewCharacter, scheme === '__custom' ? custom : scheme);
698
750
  await previewBody?.setScheme(previewScheme, { fade: reduced ? 0 : .25 });
699
- $('character-use').textContent = '使用这个配色';
751
+ setCopyNode('character-use', 'useScheme');
700
752
  });
701
753
  $('character-axes').onchange = () => void characterOperation(async () => {
702
754
  const scheme = [...$('character-axes').querySelectorAll('select')].map(el => el.value).join('-');
703
755
  fillSchemes(previewCharacter, scheme);
704
756
  await previewBody?.setScheme(previewScheme, { fade: reduced ? 0 : .25 });
705
- $('character-use').textContent = '使用这个搭配';
757
+ setCopyNode('character-use', 'useOutfit');
706
758
  });
707
759
  $('character-test').onclick = () => { if (previewBody && previewCharacter) act(previewBody, previewCharacter, $('character-action').value); };
708
760
  $('character-import').onclick = () => $('character-file').click();
709
761
  $('character-file').onchange = () => void characterOperation(async () => {
710
762
  const file = $('character-file').files[0]; if (!file) return;
711
763
  try {
712
- if (file.size > PACK_LIMIT) throw new Error('角色包不能超过 128 MiB');
764
+ if (file.size > PACK_LIMIT) throw new Error(uiCopy().packTooLarge);
713
765
  const after = await library.import(await file.arrayBuffer());
714
766
  await refreshCharacters(after.importedId);
715
- $('character-status').textContent = '已导入。预览满意后点击使用角色。';
767
+ characterStatus('imported');
716
768
  } finally { $('character-file').value = ''; }
717
769
  });
718
770
  $('character-use').onclick = () => void characterOperation(async () => {
@@ -723,20 +775,20 @@ $('character-use').onclick = () => void characterOperation(async () => {
723
775
  applyAppearance();
724
776
  } else await setCharacter(previewCharacter, scheme);
725
777
  await library.select(previewCharacter.id, scheme);
726
- $('character-use').textContent = '正在使用'; $('character-status').textContent = '已切换,重启后会保留这个角色和配色。';
778
+ setCopyNode('character-use', 'using'); characterStatus('switched');
727
779
  });
728
780
  $('character-remove').onclick = () => void characterOperation(async () => {
729
781
  const id = $('character-select').value;
730
782
  if (pet.dataset.character === id) await restoreBuiltin();
731
783
  previewBody?.dispose(); previewBody = undefined;
732
- await library.remove(id); await refreshCharacters(); $('character-status').textContent = '已删除本地角色包。';
784
+ await library.remove(id); await refreshCharacters(); characterStatus('removed');
733
785
  });
734
786
  void (async () => {
735
787
  setBusy(true);
736
788
  try {
737
789
  libraryState = await library.list();
738
790
  try { await setCharacter(await library.load(libraryState.selected), libraryState.schemes[libraryState.selected]); }
739
- catch (error) { await restoreBuiltin(); $('character-status').textContent = `已恢复内置大肥鱼:${String(error.message ?? error).slice(0, 300)}`; }
740
- } catch (error) { $('character-status').textContent = `角色加载失败:${error.message}`; }
791
+ catch (error) { await restoreBuiltin(); characterStatus('restoreError', String(error.message ?? error).slice(0, 300)); }
792
+ } catch (error) { characterStatus('loadError', error.message); }
741
793
  finally { setBusy(false); }
742
794
  })();
package/web/session-ui.js CHANGED
@@ -8,9 +8,10 @@ export function shortSessionIds(sessions) {
8
8
  }));
9
9
  }
10
10
 
11
- export function sessionTime(session) {
11
+ import { petCopy, petLanguage } from './locale.js';
12
+ export function sessionTime(session, locale = 'zh') {
12
13
  const time = session.updatedAt || session.createdAt;
13
- return time ? new Intl.DateTimeFormat('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false }).format(time) : '时间未记录';
14
+ return time ? new Intl.DateTimeFormat(petLanguage(locale) === 'zh' ? 'zh-CN' : 'en-US', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false }).format(time) : petCopy(locale).timeUnknown;
14
15
  }
15
16
 
16
17
  /** Attention entries carry their own source; inspecting them never changes chat focus. */
package/web/style.css CHANGED
@@ -203,3 +203,5 @@ h1 { font-size: clamp(32px, 4vw, 54px); font-weight: 500; line-height: 1.4; lett
203
203
  .requests footer { border-top:1px dashed var(--line); padding-top:12px; }
204
204
  .requests footer button { background:transparent; color:var(--accent); font-size:12px; padding:0; }
205
205
  .requests #request-feedback { font-size:12px; line-height:1.5; color:var(--muted); }
206
+
207
+ #demo h1, #demo>p { white-space: pre-line; }