@clowder-ai/companion 0.1.0-alpha.2 → 0.1.0-alpha.20

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.
Files changed (57) hide show
  1. package/NOTICE +10 -2
  2. package/README.md +59 -0
  3. package/manifest.json +5 -5
  4. package/package.json +19 -6
  5. package/plugin.yaml +5 -5
  6. package/renderer/call-transcript-view.mjs +238 -0
  7. package/renderer/client.mjs +13 -1
  8. package/renderer/companion-identity.mjs +42 -0
  9. package/renderer/conversation.mjs +144 -24
  10. package/renderer/decision-view.mjs +124 -0
  11. package/renderer/errors.mjs +4 -4
  12. package/renderer/index.html +168 -26
  13. package/renderer/living-body.mjs +147 -0
  14. package/renderer/living-edge.mjs +16 -0
  15. package/renderer/living-geometry.mjs +96 -0
  16. package/renderer/motion-facts.mjs +108 -0
  17. package/renderer/native-window-travel.mjs +89 -0
  18. package/renderer/native-work-motion.mjs +39 -0
  19. package/renderer/peer.mjs +1 -1
  20. package/renderer/pet-controls.mjs +130 -0
  21. package/renderer/pet-motion-assets.mjs +22 -0
  22. package/renderer/pet-motion.mjs +343 -0
  23. package/renderer/recent-bubble.mjs +74 -0
  24. package/renderer/settings-controller.mjs +171 -0
  25. package/renderer/settings-view.mjs +234 -0
  26. package/renderer/skins/ragdoll-v1.png +0 -0
  27. package/renderer/skins/xianxian-codex.webp +0 -0
  28. package/renderer/skins/xianxian-living/clips/carry.webm +0 -0
  29. package/renderer/skins/xianxian-living/clips/peek.webm +0 -0
  30. package/renderer/skins/xianxian-living/clips/peek_fade.webm +0 -0
  31. package/renderer/skins/xianxian-living/clips/pounce.webm +0 -0
  32. package/renderer/skins/xianxian-living/clips/sleep.webm +0 -0
  33. package/renderer/skins/xianxian-living/clips/think.webm +0 -0
  34. package/renderer/skins/xianxian-living/clips/trot.webm +0 -0
  35. package/renderer/skins/xianxian-living/clips/wait.webm +0 -0
  36. package/renderer/skins/xianxian-living/clips/wake.webm +0 -0
  37. package/renderer/skins/xianxian-living/layers/body.webp +0 -0
  38. package/renderer/skins/xianxian-living/layers/closed.webp +0 -0
  39. package/renderer/skins/xianxian-living/layers/earL.webp +0 -0
  40. package/renderer/skins/xianxian-living/layers/earR.webp +0 -0
  41. package/renderer/skins/xianxian-living/layers/head.webp +0 -0
  42. package/renderer/skins/xianxian-living/layers/irisL.webp +0 -0
  43. package/renderer/skins/xianxian-living/layers/irisR.webp +0 -0
  44. package/renderer/skins/xianxian-living/layers/meta.json +88 -0
  45. package/renderer/skins/xianxian-living/layers/mouth.webp +0 -0
  46. package/renderer/skins/xianxian-living/layers/scared.webp +0 -0
  47. package/renderer/skins/xianxian-living/layers/tail.webp +0 -0
  48. package/renderer/skins/xianxian-living/layers/whiteL.webp +0 -0
  49. package/renderer/skins/xianxian-living/layers/whiteR.webp +0 -0
  50. package/renderer/skins/xianxian-sleeping-row.png +0 -0
  51. package/renderer/skins/xianxian-staged-thought-row.png +0 -0
  52. package/renderer/skins/xianxian-working-row.png +0 -0
  53. package/renderer/skins/yarn-ball.png +0 -0
  54. package/renderer/style.css +240 -308
  55. package/renderer/surface.mjs +350 -69
  56. package/renderer/transcript-view.mjs +60 -7
  57. package/source-lock.json +138 -4
@@ -4,102 +4,383 @@ import { explainError } from './errors.mjs';
4
4
  import { VoicePeer } from './peer.mjs';
5
5
  import { ScreenShare } from './screen-share.mjs';
6
6
  import { TranscriptView } from './transcript-view.mjs';
7
-
7
+ import { CallTranscriptView } from './call-transcript-view.mjs';
8
+ import { SettingsView } from './settings-view.mjs';
9
+ import { RecentBubble } from './recent-bubble.mjs';
10
+ import { PetMotion } from './pet-motion.mjs';
11
+ import { LivingBody } from './living-body.mjs';
12
+ import { detectDockedEdge } from './living-edge.mjs';
13
+ import { bindPetControls } from './pet-controls.mjs';
14
+ import { decisionBadge, decisionPresentation, decisionRows } from './decision-view.mjs';
15
+ import { nativeWorkLabel, normalizeNativeWork } from './native-work-motion.mjs';
16
+ import { NativeWindowTravel } from './native-window-travel.mjs';
17
+ import { currentCompanionIdentity } from './companion-identity.mjs';
8
18
  const $ = id => document.getElementById(id);
9
- const status = text => { $('status').textContent = text; };
10
- const transcript = new TranscriptView($('transcript'));
11
- let expanded = false;
12
- let sharing = false;
13
- let pendingScreen = false;
14
-
19
+ const label = (id, text) => { $(id).querySelector('.label').textContent = text; };
20
+ const status = text => {
21
+ $('status').textContent = text;
22
+ $('menu-status').textContent = text;
23
+ $('chat-status').textContent = text;
24
+ $('announcement').textContent = text;
25
+ };
26
+ const transcript = new TranscriptView($('chat-transcript'));
27
+ const callTranscript = new CallTranscriptView($('call-transcript-log'), {
28
+ onUnread: count => {
29
+ $('call-unread').hidden = count === 0;
30
+ $('call-unread').textContent = count ? `${count} 条新消息` : '';
31
+ },
32
+ });
33
+ const bubble = new RecentBubble([$('bubble-first'), $('bubble-second')]);
34
+ const callBubble = new RecentBubble([$('call-bubble-first'), $('call-bubble-second')]);
35
+ const motion = new PetMotion($('pet'), { livingBody: new LivingBody({ root: $('pet'), sit: $('living-sit'),
36
+ video: $('living-video'), transitionVideo: $('living-video-transition') }) });
37
+ const nativeTravel = new NativeWindowTravel({
38
+ readPosition: () => ({ x: window.screenX, y: window.screenY }),
39
+ changed: value => motion.syncTravel(value),
40
+ });
41
+ let sharing = false, pendingScreen = false, loading = false, transcriptLoading = false, latestHistory, previousPhase = 'idle';
42
+ let didMove = false, decisionLoading = false, decisionOffset = 0, threadTitle, settingsView, settingsValues, latestDecisionPage;
43
+ // F229 stays quiet: a history ID change has no provenance for proactive text.
44
+ const ambientPanel = active => active ? 'actions' : 'none';
45
+ const setTexts = (ids, text) => { for (const id of ids) $(id).textContent = text; };
46
+ const setHidden = (ids, hidden) => { for (const id of ids) $(id).hidden = hidden; };
47
+ const decisionReadBasis = page => page?.version === 1
48
+ ? [page.status, page.totalCount ?? 'unknown', ...['approvals', 'needsMe']
49
+ .flatMap(key => [page.sources?.[key]?.status, page.sources?.[key]?.coverage])].join('|')
50
+ : page ? 'legacy' : null;
15
51
  if (!window.clowderCompanion) {
16
- status('请从 Clowder 的插件页面打开猫猫球');
17
- for (const id of ['begin', 'documents', 'history']) $(id).disabled = true;
52
+ $('actions').hidden = false; $('status').hidden = false;
53
+ status('请从 Clowder 的聊聊入口打开猫猫球');
54
+ document.querySelectorAll('button').forEach(button => { button.disabled = true; });
18
55
  } else {
56
+ nativeTravel.start();
19
57
  const client = createCompanionClient(window.clowderCompanion);
58
+ const controls = bindPetControls(client, {
59
+ error: (error, context) => status(context?.panel === 'settings' && error?.code === 'invalid_request' ? '这个 Host 版本还不支持猫旁设置。原来的设置入口会继续保留。' : explainError(error)),
60
+ moved: (dx, dy) => {
61
+ if (dx !== 'stop') { didMove = true; nativeTravel.setManual(true); motion.move(dx, dy); return; }
62
+ nativeTravel.setManual(false);
63
+ motion.stopMove();
64
+ if (!didMove) return;
65
+ didMove = false;
66
+ void conversation.refresh();
67
+ setTimeout(() => motion.setDockedEdge(detectDockedEdge(window, $('pet').getBoundingClientRect())), 100);
68
+ },
69
+ changed: panel => {
70
+ if (panel === 'chat') void readHistory();
71
+ if (panel === 'transcript') void readCallTranscript();
72
+ if (panel === 'decisions') void readDecisions();
73
+ if (panel === 'settings') void settingsView?.open();
74
+ },
75
+ action(kind) {
76
+ if (kind === 'begin') { transcript.reset(); callTranscript.reset(); bubble.reset(); callBubble.clear(); void conversation.begin(); void controls.show('none'); }
77
+ if (kind === 'listen') { transcript.reset(); callTranscript.reset(); bubble.reset(); callBubble.clear(); void conversation.begin('receive_only'); void controls.show('none'); }
78
+ if (kind === 'stop') void conversation.end();
79
+ if (kind === 'mute') conversation.muteMic();
80
+ if (kind === 'speaker') conversation.muteSpeaker();
81
+ if (kind === 'share') toggleScreen();
82
+ if (kind === 'documents') void conversation.documents(conversation.identity?.documentsAllowed === false);
83
+ if (kind === 'hide') void client.hide().catch(error => status(explainError(error)));
84
+ if (kind === 'transcript-return') void controls.show('actions');
85
+ if (kind === 'transcript-expand') {
86
+ const expanded = $('transcript').dataset.expanded !== 'true';
87
+ $('transcript').dataset.expanded = String(expanded);
88
+ setTexts(['transcript-expand-label'], expanded ? '收起' : '展开');
89
+ void controls.show('transcript');
90
+ }
91
+ if (kind === 'play' && conversation.identity?.skin === 'xianxian-codex') {
92
+ void controls.show('none');
93
+ motion.signal('play');
94
+ }
95
+ },
96
+ });
20
97
  const screen = new ScreenShare({
21
98
  screenRequest: () => client.screenPick(),
22
- screenStart: (selectionId, label) => client.screenOpen(selectionId, label),
99
+ screenStart: (selectionId, name) => client.screenOpen(selectionId, name),
23
100
  screenFrame: (selectionId, frame) => client.screenFrame(selectionId, {
24
101
  ...frame, frameId: crypto.randomUUID(), sourceLabel: '所选画面', observedAt: Date.now(),
25
- }),
26
- screenStop: () => client.screenClose(),
102
+ }), screenStop: () => client.screenClose(),
27
103
  }, value => {
28
- sharing = value.sharing;
29
- pendingScreen = value.pending === true;
30
- $('share').textContent = sharing ? '停止共享' : pendingScreen ? '取消选屏' : '共享屏幕';
31
- $('share').setAttribute('aria-pressed', String(sharing));
32
- $('screen-status').hidden = !sharing && !pendingScreen && value.message === '未共享屏幕';
33
- $('screen-status').textContent = sharing ? `正在共享:${value.label}` : value.message;
34
- $('screen-status').dataset.state = sharing ? 'sharing' : pendingScreen ? 'pending' : 'stopped';
104
+ const wasActive = sharing || pendingScreen;
105
+ sharing = value.sharing; pendingScreen = value.pending === true;
106
+ for (const id of ['share', 'menu-share', 'chat-share', 'settings-share']) label(id, sharing ? '停止共享' : pendingScreen ? '取消选屏' : '共享画面');
107
+ for (const prefix of ['call', 'menu', 'chat', 'transcript', 'settings']) {
108
+ $(`${prefix}-share-context`).hidden = !sharing;
109
+ $(`${prefix}-share-target`).textContent = sharing ? `共享中:${value.label}` : '';
110
+ }
111
+ $('share-badge').hidden = !sharing && !pendingScreen;
112
+ $('share-badge').title = sharing ? `正在共享:${value.label},点此停止` : '正在选屏,点此取消';
113
+ $('share-badge').setAttribute('aria-label', sharing ? `停止共享:${value.label}` : '取消选屏');
114
+ if (value.message && value.message !== '未共享屏幕' && (wasActive || pendingScreen)) status(value.message);
35
115
  });
116
+ function toggleScreen() {
117
+ if (conversation.phase !== 'talking') {
118
+ status('先开始语音通话,连上后可选择窗口或屏幕');
119
+ $('status').hidden = false;
120
+ void controls.show('actions');
121
+ return;
122
+ }
123
+ void (sharing || pendingScreen ? screen.stop('屏幕共享已停止') : screen.start()).catch(error => status(explainError(error)));
124
+ }
36
125
  const conversation = new CompanionConversation({
37
126
  client, createPeer: callback => new VoicePeer(callback, client), stopScreen: () => screen.stop(),
38
- transcript: event => event.type === 'turn-done' ? transcript.finish(event) : transcript.append(event.role, event.text, !event.typed),
127
+ transcript: event => {
128
+ if (event.type === 'turn-done') {
129
+ transcript.finish(event); callTranscript.finish(event); bubble.finish(event.role); callBubble.finish(event.role);
130
+ void readHistory(); void readCallTranscript();
131
+ } else if (event.type === 'typed') {
132
+ callTranscript.appendTyped(event);
133
+ void readHistory(); void readCallTranscript();
134
+ } else {
135
+ transcript.append(event.role, event.text, true);
136
+ callTranscript.appendLive(event);
137
+ const speaker = event.role === 'assistant' ? conversation.identity?.displayName ?? '猫猫' : '语音';
138
+ bubble.append(event.role, event.text, speaker); callBubble.append(event.role, event.text, speaker);
139
+ void controls.setAmbient('actions');
140
+ }
141
+ },
39
142
  render(value) {
143
+ const showFailure = value.failed && previousPhase !== 'idle' && value.phase === 'idle';
144
+ const justConnected = previousPhase !== 'talking' && value.phase === 'talking';
145
+ if (previousPhase !== 'idle' && value.phase === 'idle') {
146
+ transcript.reset(); callTranscript.reset(); bubble.reset(); callBubble.clear(); void readHistory();
147
+ if (controls.panel === 'transcript') void controls.show('menu');
148
+ }
149
+ previousPhase = value.phase;
40
150
  const active = value.phase !== 'idle';
41
- document.body.className = value.phase === 'talking' ? 'connected' : active ? 'connecting' : '';
42
- $('idle').hidden = active; $('controls').hidden = !active;
43
- $('share').hidden = value.phase !== 'talking';
44
- $('compose').querySelector('button').disabled = value.phase !== 'talking';
45
- $('begin').disabled = !value.identity;
46
- status(value.message);
151
+ const receiveOnly = value.audioMode === 'receive_only';
152
+ const canReceiveOnly = value.identity?.audio?.supportedModes?.includes('receive_only') === true;
153
+ const retryReceiveOnly = value.failed && value.retryMode === 'receive_only' && canReceiveOnly;
154
+ callTranscript.setCall(value.callId);
155
+ void controls.setAmbient(ambientPanel(active));
156
+ $('begin').hidden = active; $('begin').disabled = !value.identity;
157
+ $('listen').hidden = active || !canReceiveOnly; $('listen').disabled = !value.identity;
158
+ label('begin', value.failed && !retryReceiveOnly ? '重试语音通话' : '语音通话');
159
+ label('listen', retryReceiveOnly ? '重试只听' : '只听');
160
+ $('begin').className = retryReceiveOnly ? '' : 'primary';
161
+ $('listen').className = retryReceiveOnly ? 'primary' : '';
162
+ $('mic').hidden = value.phase !== 'talking' || receiveOnly; $('speaker').hidden = !active;
163
+ $('chat-mic').hidden = value.phase !== 'talking' || receiveOnly;
164
+ $('transcript-mic').hidden = value.phase !== 'talking' || receiveOnly;
165
+ $('settings-mic').hidden = value.phase !== 'talking' || receiveOnly;
166
+ $('active-actions').hidden = !active;
167
+ $('share').disabled = value.phase !== 'talking';
168
+ $('compose').querySelector('button').disabled = !value.identity || value.phase === 'connecting';
169
+ status(value.message ?? '');
170
+ $('status').hidden = !value.message || /^(点击|正在听|只听模式|只听已结束|语音通话已结束|已发送)/.test(value.message);
171
+ $('menu-status').hidden = !value.message;
172
+ const callState = value.recovering ? '连接不稳定' : value.phase === 'connecting' ? '正在连接'
173
+ : receiveOnly ? '只听中' : active ? '通话中' : '';
174
+ const microphoneState = receiveOnly ? '麦克风未启用'
175
+ : value.phase === 'connecting' ? '正在请求麦克风'
176
+ : value.recovering ? `正在等待原连接恢复 · ${value.muted ? '麦克风已静音' : '麦克风已开启'}`
177
+ : value.muted ? '麦克风已静音' : active ? '麦克风已开启' : '';
178
+ for (const id of ['actions', 'chat-call-context', 'transcript-call-context', 'menu-call-context', 'settings-call-context']) $(id).dataset.connectionState = value.recovering ? 'recovering' : active ? 'connected' : 'idle';
179
+ setTexts(['call-state', 'chat-call-state', 'transcript-call-state', 'menu-call-state', 'settings-call-state'], callState);
180
+ setTexts(['call-mic-state', 'chat-call-mic-state', 'transcript-call-mic-state', 'menu-call-mic-state', 'settings-call-mic-state'], microphoneState);
181
+ setHidden(['chat-call-context', 'transcript-call-context', 'menu-call-context', 'settings-call-context'], !active);
182
+ label('mic', value.muted ? '取消静音' : '静音'); $('mic').setAttribute('aria-pressed', String(value.muted));
183
+ $('mic-icon').setAttribute('href', value.muted ? '#i-mic-off' : '#i-mic');
184
+ $('chat-mic').textContent = value.muted ? '取消静音' : '静音';
185
+ $('settings-mic').textContent = value.muted ? '取消静音' : '静音';
186
+ $('transcript-mic').setAttribute('aria-label', value.muted ? '取消静音' : '静音');
187
+ $('transcript-mic').setAttribute('aria-pressed', String(value.muted));
188
+ $('transcript-mic-icon').setAttribute('href', value.muted ? '#i-mic-off' : '#i-mic');
189
+ label('speaker', value.silent ? '开启播音' : '关闭播音');
47
190
  const identity = value.identity;
191
+ const companionIdentity = currentCompanionIdentity(identity);
192
+ const nativeSnapshot = normalizeNativeWork(identity?.nativeWork);
193
+ const workLabel = nativeWorkLabel(nativeSnapshot, identity?.nativeActivity);
194
+ const workState = workLabel ? `${identity.displayName}${workLabel}` : '';
195
+ setTexts(['call-work', 'chat-call-work', 'transcript-call-work', 'menu-call-work', 'settings-call-work'], workState);
196
+ setHidden(['call-work', 'chat-call-work', 'transcript-call-work', 'menu-call-work', 'settings-call-work'], !workState);
197
+ motion.setContext({ skin: identity?.skin, phase: value.phase,
198
+ nativeActivity: identity?.nativeActivity ?? 'none', muted: value.muted || receiveOnly });
199
+ motion.setBehaviorEnabled(identity?.behaviorEnabled === true);
200
+ motion.syncNativeSnapshot(nativeSnapshot);
201
+ if (justConnected) motion.signal('connected');
202
+ if (showFailure) motion.signal('failed');
48
203
  if (identity) {
49
- $('identity').textContent = identity.displayName;
50
- $('chat-name').textContent = identity.displayName;
51
- $('pet').setAttribute('aria-label', `${identity.displayName},拖动可以移动`);
52
- $('pet').dataset.skin = identity.skin;
53
- $('dock').setAttribute('aria-label', `和${identity.displayName}交流`);
54
- $('message').setAttribute('aria-label', `给${identity.displayName}写一句`);
55
- document.documentElement.style.setProperty('--speaker-label', JSON.stringify(identity.carrier.displayName));
56
- $('documents').textContent = `资料查询 · ${identity.documentsAllowed ? '开启' : '暂停'}`;
204
+ $('menu-play').hidden = identity.skin !== 'xianxian-codex';
205
+ const companionLabel = companionIdentity
206
+ ? `${companionIdentity.title} · ${companionIdentity.partnerLabel}` : identity.displayName;
207
+ $('chat-name').textContent = threadTitle ?? companionLabel; $('menu-name').textContent = companionLabel;
208
+ $('call-message').placeholder = `发消息给${identity.displayName}…`;
209
+ $('pet').setAttribute('aria-label', `${companionLabel}:点击或右键打开名片,拖动移动`);
210
+ $('documents').querySelector('.menu-status').textContent = identity.documentsAllowed ? '开启' : '暂停';
57
211
  $('documents').setAttribute('aria-pressed', String(identity.documentsAllowed));
58
- $('connection-scope').textContent = identity.duty.catId === identity.carrier.catId
59
- ? (active && identity.documentsAllowed ? `资料工具 · ${identity.toolsReady ? '已连接' : '连接中'}` : '交流保存在同一段聊天中')
60
- : `${identity.duty.displayName} · 实时语音由${identity.carrier.displayName}承载`;
61
- }
62
- for (const [id, muted, target, off, on] of [
63
- ['mic', value.muted, '麦克风', '取消静音', '静音'],
64
- ['speaker', value.silent, '播音', '开声音', '关声音'],
65
- ]) {
66
- $(id).setAttribute('aria-pressed', String(muted));
67
- $(id).setAttribute('aria-label', `${muted ? '开启' : '关闭'}${target}`);
68
- $(id).querySelector('span').textContent = muted ? off : on;
212
+ if (companionIdentity) {
213
+ $('connection-scope').textContent = `${companionIdentity.partnerLabel} · ${companionIdentity.liveLabel} · ${companionIdentity.deepLabel}`;
214
+ } else {
215
+ const live = identity.liveTransport?.kind === 'gpt_live_v3'
216
+ ? 'GPT Live · 实时型号未证实' : '实时载体未确认';
217
+ $('connection-scope').textContent = identity.duty.catId === identity.carrier.catId
218
+ ? `${identity.duty.displayName} · ${live}`
219
+ : `${identity.duty.displayName} · ${live} · 绑定载体 ${identity.carrier.displayName}`;
220
+ }
69
221
  }
222
+ if (showFailure) void controls.show('menu');
70
223
  },
71
224
  });
72
- function details(value) {
73
- expanded = value;
74
- $('details').hidden = !value;
75
- $('write').setAttribute('aria-expanded', String(value));
76
- void client.resize(value).catch(error => status(explainError(error)));
225
+ settingsView = new SettingsView({
226
+ document,
227
+ client,
228
+ close: () => void controls.show('menu'),
229
+ callActive: () => conversation.active,
230
+ expectHostStop: () => conversation.expectHostStop(),
231
+ settleExpectedHostStop: callStopped => conversation.settleExpectedHostStop(callStopped),
232
+ layoutChanged: () => { if (controls.panel === 'settings') controls.remeasure?.(); },
233
+ onValues(values) {
234
+ settingsValues = values;
235
+ document.documentElement?.style?.setProperty?.('--pet-scale', String(values.ballSize / 72));
236
+ $('anchor').dataset.ballSize = String(values.ballSize);
237
+ motion.setBehaviorEnabled(values.behaviorEnabled);
238
+ $('documents').hidden = true;
239
+ if (latestDecisionPage) showDecisionBadge(latestDecisionPage);
240
+ },
241
+ });
242
+ async function readHistory() {
243
+ if (loading) return;
244
+ loading = true;
245
+ try {
246
+ const history = await client.readConversation();
247
+ $('history').textContent = history.hasMore ? '在 Cat Café 中查看更早聊天 ↗' : '在 Cat Café 中查看完整聊天 ↗';
248
+ threadTitle = history.threadTitle;
249
+ $('chat-name').textContent = threadTitle;
250
+ bubble.load(history.messages);
251
+ void controls.setAmbient(ambientPanel(conversation.phase !== 'idle'));
252
+ const serialized = JSON.stringify(history.messages);
253
+ if (serialized !== latestHistory) { latestHistory = serialized; transcript.load(history.messages); }
254
+ } catch { $('chat-status').textContent = '聊天记录暂未更新 · 正在说的话仍会显示'; }
255
+ finally { loading = false; }
256
+ }
257
+ async function readCallTranscript() {
258
+ if (transcriptLoading || !conversation.active || !conversation.callId) return;
259
+ transcriptLoading = true;
260
+ const callId = conversation.callId;
261
+ try {
262
+ const reply = await client.readTranscript();
263
+ if (!conversation.active || conversation.callId !== callId) return;
264
+ callTranscript.load(reply);
265
+ callBubble.loadTranscript(reply.rows, conversation.identity?.displayName);
266
+ $('call-transcript-status').textContent = reply.hasMore ? '这里只显示这次通话最近的内容' : '';
267
+ } catch {
268
+ if (conversation.active && conversation.callId === callId) $('call-transcript-status').textContent = '字幕暂未更新 · 实时内容仍会继续显示';
269
+ } finally { transcriptLoading = false; }
77
270
  }
78
- $('begin').onclick = () => { transcript.reset(); void conversation.begin(); };
79
- $('end').onclick = () => void conversation.end();
80
- $('mic').onclick = () => conversation.muteMic();
81
- $('speaker').onclick = () => conversation.muteSpeaker();
82
- $('write').onclick = () => details(!expanded);
83
- $('collapse').onclick = () => details(false);
84
- $('share').onclick = () => void (sharing || pendingScreen ? screen.stop('屏幕共享已停止') : screen.start()).catch(() => status('屏幕共享已停止'));
271
+ function showDecisionBadge(page) {
272
+ latestDecisionPage = page;
273
+ const badge = decisionBadge(page);
274
+ $('pending-badge').hidden = !badge.visible || settingsValues?.proactivePolicy !== 'quiet-badge';
275
+ $('pending-count').textContent = badge.label;
276
+ $('pending-badge').title = badge.title;
277
+ $('pending-badge').setAttribute('aria-label', badge.title);
278
+ $('menu-pending').textContent = badge.label;
279
+ $('menu-pending').dataset.state = badge.state;
280
+ }
281
+ async function readDecisions(more = false) {
282
+ if (decisionLoading) return;
283
+ decisionLoading = true;
284
+ if (!more && controls.panel === 'decisions') $('decision-status').textContent = '正在读取待办…';
285
+ try {
286
+ const previousReadBasis = decisionReadBasis(latestDecisionPage);
287
+ const page = await client.readDecisions(more ? decisionOffset : 0, 10);
288
+ const presentation = decisionPresentation(page);
289
+ const changedRead = more && presentation.renderRows && previousReadBasis !== null
290
+ && decisionReadBasis(page) !== previousReadBasis;
291
+ showDecisionBadge(page);
292
+ motion.setPendingDecision(presentation.pending);
293
+ if (controls.panel !== 'decisions') return;
294
+ const list = $('decision-list');
295
+ if (!more || changedRead) { list.replaceChildren(); list.scrollTop = 0; }
296
+ const retainedRows = more && !presentation.renderRows && list.children.length > 0;
297
+ const knownVariantRefs = new Set(Array.from(list.children)
298
+ .map(item => item.dataset.variantRef).filter(Boolean));
299
+ for (const row of presentation.renderRows && !changedRead ? decisionRows(page) : []) {
300
+ if (row.variantRef && knownVariantRefs.has(row.variantRef)) continue;
301
+ const item = document.createElement('li');
302
+ if (row.variantRef) { item.dataset.variantRef = row.variantRef; knownVariantRefs.add(row.variantRef); }
303
+ const title = document.createElement('strong');
304
+ const meta = document.createElement('span');
305
+ title.textContent = row.title; meta.textContent = row.meta;
306
+ item.append(title, meta); list.append(item);
307
+ if (row.navigation) {
308
+ const button = document.createElement('button');
309
+ button.type = 'button'; button.textContent = row.navigation.label;
310
+ button.onclick = async () => {
311
+ try {
312
+ const result = await client.openDecision(row.navigation.variantRef, row.navigation.target);
313
+ $('decision-status').textContent = result.delivery === 'requested'
314
+ ? '已请求打开对应事项' : '打开对应事项尚未确认 · 请从 Cat Café 查看';
315
+ } catch { $('decision-status').textContent = '暂时无法打开对应事项 · 请稍后重试'; }
316
+ };
317
+ item.append(button);
318
+ } else if (row.previewable) {
319
+ const button = document.createElement('button');
320
+ button.type = 'button'; button.textContent = '查看确认演练';
321
+ button.onclick = async () => {
322
+ try {
323
+ const result = await client.inspectF221(row.proposalId);
324
+ $('decision-status').textContent = result.status === 'trial_confirmed'
325
+ ? '确认演练已完成;没有写回提案'
326
+ : result.status === 'stale' ? '提案已变化,请重新查看原处卡片'
327
+ : result.status === 'dismissed' ? '已取消演练;提案没有变化'
328
+ : '确认演练暂不可用;请在原处处理';
329
+ } catch { $('decision-status').textContent = '确认演练暂不可用;请在原处处理'; }
330
+ };
331
+ item.append(button);
332
+ }
333
+ }
334
+ decisionOffset = changedRead ? 0 : page.page.offset + page.page.limit;
335
+ $('decision-reload').textContent = changedRead ? '刷新' : presentation.reloadLabel;
336
+ $('decision-status').textContent = changedRead && page.totalCount !== 0
337
+ ? '待办已变化 · 请刷新查看最新列表'
338
+ : retainedRows
339
+ ? `${presentation.badge.state === 'authentication' ? '待办需要登录' : '待办暂不可读'} · 以下为上次读到的内容`
340
+ : presentation.message;
341
+ $('decision-more').hidden = changedRead || !presentation.hasMore;
342
+ } catch {
343
+ showDecisionBadge(undefined);
344
+ motion.setPendingDecision(null);
345
+ if (controls.panel === 'decisions') {
346
+ const retained = $('decision-list').children.length > 0;
347
+ $('decision-status').textContent = retained
348
+ ? '待办暂不可读 · 以下为上次读到的内容'
349
+ : '待办暂不可读 · 请稍后刷新';
350
+ $('decision-reload').textContent = '重试';
351
+ $('decision-more').hidden = true;
352
+ }
353
+ } finally { decisionLoading = false; }
354
+ }
355
+ $('share-badge').onclick = toggleScreen;
356
+ $('pending-badge').onclick = () => void controls.show('decisions');
357
+ $('decision-reload').onclick = () => void readDecisions();
358
+ $('decision-more').onclick = () => void readDecisions(true);
85
359
  $('history').onclick = () => void client.openConversation().then(result => {
86
- if (result.delivery === 'unconfirmed') status('打开聊天尚未确认 · 请从 Clowder 查看猫猫球聊天');
360
+ if (result.delivery === 'unconfirmed') status('打开聊天尚未确认 · 请从 Clowder 查看');
87
361
  }).catch(error => status(explainError(error)));
88
- $('documents').onclick = () => void conversation.documents(conversation.identity?.documentsAllowed === false);
89
- $('compose').onsubmit = async event => {
90
- event.preventDefault();
91
- const text = $('message').value;
362
+ async function submitMessage(event, inputId) {
363
+ event.preventDefault(); const input = $(inputId); const text = input.value;
92
364
  if (await conversation.send(text)) {
93
- if ($('message').value === text) $('message').value = '';
365
+ motion.signal('received');
366
+ if (input.value === text) input.value = '';
367
+ latestHistory = undefined; void readHistory();
94
368
  }
95
- };
369
+ }
370
+ $('compose').onsubmit = event => submitMessage(event, 'message');
371
+ $('call-compose').onsubmit = event => submitMessage(event, 'call-message');
372
+ $('call-unread').onclick = () => callTranscript.scrollToBottom();
96
373
  const unsubscribe = client.subscribe(event => {
97
- if (event.kind === 'media-stopped') void conversation.releaseLocal('语音已停止 · 点击开始聊天继续');
374
+ if (event.kind === 'media-stopped') void conversation.hostStopped(event.reason);
375
+ if (event.kind === 'view-dismiss') controls.dismiss();
98
376
  });
99
- const monitor = setInterval(() => void conversation.refresh(), 3000);
100
- void conversation.refresh();
377
+ const statusMonitor = setInterval(() => void conversation.refresh(), 1000);
378
+ const historyMonitor = setInterval(() => void readHistory(), 3000);
379
+ const transcriptMonitor = setInterval(() => void readCallTranscript(), 1000);
380
+ const decisionMonitor = setInterval(() => { if (controls.panel !== 'decisions') void readDecisions(); }, 15000);
381
+ void conversation.refresh(); void readHistory(); void readDecisions(); void settingsView.controller.load(); void controls.show('none');
101
382
  window.addEventListener('beforeunload', () => {
102
- clearInterval(monitor); unsubscribe();
103
- void conversation.end();
383
+ clearInterval(statusMonitor); clearInterval(historyMonitor); clearInterval(transcriptMonitor); clearInterval(decisionMonitor);
384
+ unsubscribe(); nativeTravel.close(); motion.close(); void conversation.end();
104
385
  });
105
386
  }
@@ -1,7 +1,10 @@
1
+ import { historicalCompanionIdentity } from './companion-identity.mjs';
2
+
1
3
  export class TranscriptView {
2
4
  constructor(container) {
3
5
  this.container = container;
4
6
  this.activeRows = new Map();
7
+ this.historyRows = new Map();
5
8
  this.completed = new Set();
6
9
  }
7
10
  append(role, text, chunk = false) {
@@ -11,30 +14,80 @@ export class TranscriptView {
11
14
  if (!row) {
12
15
  row = this.container.ownerDocument.createElement('p');
13
16
  row.className = role;
17
+ if (chunk) { row.dataset.live = 'true'; row.dataset.author = `实时语音 · ${role === 'user' ? '你' : '猫猫'}`; }
14
18
  this.container.append(row);
15
19
  if (chunk) this.activeRows.set(role, row);
16
20
  }
17
- row.textContent += text;
21
+ row.textContent = (row.textContent + text).slice(-16000);
18
22
  if (pinned) this.container.scrollTop = this.container.scrollHeight;
19
23
  }
20
24
  finish({ role, transcript, turnId }) {
21
25
  if (!['user', 'assistant'].includes(role) || (turnId && this.completed.has(turnId))) return;
22
26
  const pinned = this.nearBottom();
23
- let row = this.activeRows.get(role);
24
- if (!row && transcript) {
25
- this.append(role, '', true);
26
- row = this.activeRows.get(role);
27
- }
28
- if (row && typeof transcript === 'string') row.textContent = transcript;
27
+ // A provider caption is ephemeral. Only Host history can create a saved row.
28
+ this.activeRows.get(role)?.remove();
29
29
  this.activeRows.delete(role);
30
30
  if (turnId) this.completed.add(turnId);
31
+ if (this.completed.size > 256) this.completed.delete(this.completed.values().next().value);
31
32
  if (pinned) this.container.scrollTop = this.container.scrollHeight;
32
33
  }
33
34
  nearBottom() {
34
35
  return this.container.scrollHeight - this.container.scrollTop - this.container.clientHeight < 32;
35
36
  }
37
+ visibleHistoryAnchor() {
38
+ const viewport = this.container.getBoundingClientRect?.();
39
+ if (!viewport) return null;
40
+ for (const [id, row] of this.historyRows) {
41
+ const rect = row.getBoundingClientRect?.();
42
+ if (rect && rect.bottom > viewport.top && rect.top < viewport.bottom)
43
+ return { id, offset: rect.top - viewport.top };
44
+ }
45
+ return null;
46
+ }
36
47
  reset() {
48
+ for (const row of this.activeRows.values()) row.remove();
37
49
  this.activeRows.clear();
38
50
  this.completed.clear();
39
51
  }
52
+ load(messages) {
53
+ const pinned = this.nearBottom();
54
+ const readingPosition = this.container.scrollTop;
55
+ const anchor = pinned ? null : this.visibleHistoryAnchor();
56
+ const previous = this.historyRows;
57
+ this.historyRows = new Map();
58
+ const rows = messages.map(message => {
59
+ const row = previous.get(message.id) ?? this.container.ownerDocument.createElement('p');
60
+ row.className = message.role; row.dataset.messageId = message.id;
61
+ if (row.textContent !== message.text) row.textContent = message.text;
62
+ const identity = historicalCompanionIdentity(message.companionIdentity, message.name);
63
+ row.dataset.author = identity.authorLabel;
64
+ if (identity.companionKnown) {
65
+ row.dataset.companion = identity.partnerLabel;
66
+ row.dataset.companionLive = identity.liveLabel;
67
+ row.dataset.companionDeep = identity.deepLabel;
68
+ row.dataset.companionAvatar = identity.avatarCatId;
69
+ row.dataset.companionSkin = identity.skin;
70
+ row.title = [identity.authorLabel, identity.partnerLabel, identity.liveLabel, identity.deepLabel].join('\n');
71
+ row.setAttribute('aria-label', [identity.authorLabel, message.text,
72
+ identity.partnerLabel, identity.liveLabel, identity.deepLabel].join('。'));
73
+ } else {
74
+ for (const key of ['companion', 'companionLive', 'companionDeep', 'companionAvatar', 'companionSkin'])
75
+ delete row.dataset[key];
76
+ row.title = identity.authorLabel;
77
+ row.removeAttribute?.('aria-label');
78
+ }
79
+ this.historyRows.set(message.id, row);
80
+ return row;
81
+ });
82
+ this.container.replaceChildren(...rows, ...this.activeRows.values());
83
+ if (pinned) this.container.scrollTop = this.container.scrollHeight;
84
+ else if (anchor) {
85
+ const row = this.historyRows.get(anchor.id) ?? rows[0];
86
+ const rect = row?.getBoundingClientRect?.();
87
+ const viewport = this.container.getBoundingClientRect?.();
88
+ this.container.scrollTop = rect && viewport
89
+ ? this.container.scrollTop + rect.top - viewport.top - anchor.offset
90
+ : readingPosition;
91
+ } else this.container.scrollTop = readingPosition;
92
+ }
40
93
  }