@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
@@ -0,0 +1,343 @@
1
+ import { isLivingClip } from './living-body.mjs';
2
+ import { MotionFacts } from './motion-facts.mjs';
3
+ import { additional, atlas, signals, staticSkins, validId, visualAlias, workAction } from './pet-motion-assets.mjs';
4
+ /** Select one truthful body from Host facts and local, user-controlled gestures. */
5
+ export class PetMotion {
6
+ constructor(element, options = {}) {
7
+ this.element = element;
8
+ const setTimer = options.setTimer ?? globalThis.setTimeout;
9
+ const clearTimer = options.clearTimer ?? globalThis.clearTimeout;
10
+ this.setTimer = (callback, delay) => setTimer.call(globalThis, callback, delay);
11
+ this.clearTimer = id => clearTimer.call(globalThis, id);
12
+ this.now = options.now ?? Date.now;
13
+ this.livingBody = options.livingBody;
14
+ this.reducedMotion = options.reducedMotion ?? globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
15
+ this.autoPlay = options.autoPlay === true;
16
+ this.autoPlayIdleMs = Math.max(90_000, options.autoPlayIdleMs ?? 90_000);
17
+ this.autoPlayCooldownMs = Math.max(180_000, options.autoPlayCooldownMs ?? 180_000);
18
+ this.lastPlayAt = Number.NEGATIVE_INFINITY;
19
+ this.skin = 'xianxian-codex';
20
+ this.phase = 'idle';
21
+ this.base = 'idle';
22
+ this.action = '';
23
+ this.frame = 0;
24
+ this.dragging = false;
25
+ this.oneShot = false;
26
+ this.pendingDecision = false;
27
+ this.dockedEdge = null;
28
+ this.dockZone = null;
29
+ this.resting = false;
30
+ this.transient = null;
31
+ this.facts = new MotionFacts({ now: this.now, setTimer: this.setTimer, clearTimer: this.clearTimer,
32
+ changed: () => this.refresh() });
33
+ this.seenEvents = new Map();
34
+ }
35
+
36
+ setContext({ skin, phase, nativeActivity, muted }) {
37
+ const selectedSkin = ['xianxian-codex', 'yanyan-codex', ...Object.keys(staticSkins)].includes(skin)
38
+ ? skin : 'xianxian-codex';
39
+ const wasSleeping = this.action === 'sleeping' || this.resting;
40
+ this.context = { skin: selectedSkin, phase, nativeActivity, muted };
41
+ const changedSkin = selectedSkin !== this.skin;
42
+ this.skin = selectedSkin;
43
+ this.phase = phase;
44
+ if (phase !== 'idle' || nativeActivity !== 'none') {
45
+ this.resting = false;
46
+ this.cancelIdleTimers();
47
+ }
48
+ if (nativeActivity !== 'none' && this.transient?.action !== 'failed') this.transient = null;
49
+ else if (wasSleeping && ['talking', 'connecting'].includes(phase) && !muted)
50
+ this.transient = { action: 'waking' };
51
+ this.refresh(changedSkin);
52
+ }
53
+ setBehaviorEnabled(enabled) {
54
+ const next = enabled === true;
55
+ if (this.autoPlay === next) return;
56
+ this.autoPlay = next;
57
+ if (!next) {
58
+ if (this.autoTimer !== undefined) this.clearTimer(this.autoTimer);
59
+ this.autoTimer = undefined;
60
+ if (this.transient?.automatic) {
61
+ this.transient = null;
62
+ this.refresh();
63
+ }
64
+ return;
65
+ }
66
+ this.refresh();
67
+ }
68
+ syncSnapshot(value) {
69
+ this.syncFacts(value, false);
70
+ }
71
+ syncNativeSnapshot(value) {
72
+ this.syncFacts(value, true);
73
+ }
74
+ syncFacts(value, nativeOnly) {
75
+ const now = this.now();
76
+ this.hasNativeWork = value !== null && value !== undefined;
77
+ for (const [id, expiresAt] of this.seenEvents) if (expiresAt <= now) this.seenEvents.delete(id);
78
+ if (nativeOnly) this.facts.syncNative(value);
79
+ else this.facts.sync(value, this.dragging);
80
+ if (this.snapshot.work) {
81
+ this.resting = false;
82
+ this.cancelIdleTimers();
83
+ if (this.transient?.action !== 'failed') this.transient = null;
84
+ } else if (this.resting && (this.snapshot.delivery || this.snapshot.travel)) {
85
+ this.resting = false;
86
+ this.cancelRest();
87
+ this.transient = { action: 'waking' };
88
+ }
89
+ this.refresh();
90
+ }
91
+ syncTravel(value) {
92
+ this.facts.syncTravel(value, this.dragging);
93
+ if (this.resting && this.snapshot.travel) {
94
+ this.resting = false;
95
+ this.cancelRest();
96
+ this.transient = { action: 'waking' };
97
+ }
98
+ this.refresh();
99
+ }
100
+ setPendingDecision(value) {
101
+ const pending = value === true;
102
+ if (this.pendingDecision === pending) return;
103
+ this.pendingDecision = pending;
104
+ if (pending) {
105
+ this.resting = false;
106
+ this.transient = null;
107
+ this.cancelIdleTimers();
108
+ }
109
+ this.refresh();
110
+ }
111
+ setDockedEdge(value) {
112
+ const candidate = typeof value === 'string' ? { edge: value, zone: 'corner' } : value;
113
+ const edge = ['left', 'right'].includes(candidate?.edge) ? candidate.edge : null;
114
+ const zone = edge && ['corner', 'mid'].includes(candidate?.zone) ? candidate.zone : edge ? 'corner' : null;
115
+ if (this.dockedEdge === edge && this.dockZone === zone) return;
116
+ this.dockedEdge = edge;
117
+ this.dockZone = zone;
118
+ if (edge) this.cancelIdleTimers();
119
+ this.refresh(this.action === 'peek');
120
+ }
121
+ signal(kind, eventId) {
122
+ if (kind === 'answered') return;
123
+ if (kind === 'connected' && this.living()) return;
124
+ if (kind === 'play') {
125
+ if (!this.canPlay()) return;
126
+ this.lastPlayAt = this.now();
127
+ this.resting = false;
128
+ this.cancelIdleTimers();
129
+ this.transient = { action: 'play', automatic: false };
130
+ this.refresh();
131
+ return;
132
+ }
133
+ let requested = signals[kind];
134
+ if (kind === 'received' && (this.action === 'sleeping' || this.resting)) requested = 'waking';
135
+ if (!requested || this.dragging || staticSkins[this.skin]) return;
136
+ const now = this.now();
137
+ if (validId(eventId)) {
138
+ if (this.seenEvents.has(eventId)) return;
139
+ this.seenEvents.set(eventId, now + 3_600_000);
140
+ }
141
+ this.resting = false;
142
+ this.cancelIdleTimers();
143
+ this.transient = { action: requested };
144
+ this.refresh();
145
+ }
146
+ move(dx, dy) {
147
+ if (!Number.isFinite(dx) || !Number.isFinite(dy) || Math.hypot(dx, dy) < 6) return;
148
+ if (this.dragging) return;
149
+ this.dragging = true;
150
+ this.element.classList?.add('dragging');
151
+ this.element.dataset.interaction = 'held-candidate';
152
+ this.facts.suppressTravel();
153
+ this.resting = false;
154
+ this.transient = null;
155
+ this.cancelIdleTimers();
156
+ this.refresh();
157
+ }
158
+ stopMove() {
159
+ if (!this.dragging) return;
160
+ this.dragging = false;
161
+ this.element.classList?.remove('dragging');
162
+ delete this.element.dataset.interaction;
163
+ this.refresh();
164
+ }
165
+ close() {
166
+ this.cancelFrame();
167
+ this.cancelIdleTimers();
168
+ this.facts.close();
169
+ this.livingBody?.close();
170
+ }
171
+ living() { return this.skin === 'xianxian-codex' && Boolean(this.livingBody); }
172
+ resolve(action) {
173
+ if (action === 'pending_decision' && !this.living()) return 'waiting';
174
+ if (action === 'peek' && !this.living()) return 'idle';
175
+ if (staticSkins[this.skin]) return 'idle';
176
+ const visual = visualAlias[action] ?? action;
177
+ if (this.skin !== 'xianxian-codex' && visual in additional)
178
+ return visual === 'sleeping' ? 'idle' : 'review';
179
+ return action;
180
+ }
181
+ refresh(force = false) {
182
+ this.element.dataset.listening = String(this.listening());
183
+ const selection = this.select();
184
+ this.base = this.baseAction();
185
+ const action = this.resolve(selection.action);
186
+ const changed = action !== this.action;
187
+ if (changed || force || selection.oneShot !== this.oneShot) {
188
+ this.oneShot = selection.oneShot;
189
+ this.play(action, force);
190
+ }
191
+ if (action === 'idle') this.armRest();
192
+ else if (action !== 'sleeping') this.cancelRest();
193
+ }
194
+ select() {
195
+ if (this.dragging) return { action: 'held', oneShot: false };
196
+ if (this.transient?.action === 'failed') return { action: 'failed', oneShot: true };
197
+ if (this.pendingDecision) return { action: 'pending_decision', oneShot: false };
198
+ const work = this.activeWorkAction();
199
+ if (work) return { action: work, oneShot: false };
200
+ if (this.transient && this.transient.action !== 'play')
201
+ return { action: this.transient.action, oneShot: true };
202
+ const delivery = this.facts.consumeDelivery();
203
+ if (delivery) {
204
+ this.transient = { action: 'delivering', resultId: delivery.resultId };
205
+ return { action: 'delivering', oneShot: true };
206
+ }
207
+ if (!this.reducedMotion && this.snapshot.travel) {
208
+ const { dx, dy } = this.snapshot.travel;
209
+ return { action: Math.abs(dx) >= Math.abs(dy) ? dx < 0 ? 'running-left' : 'running-right' : 'running', oneShot: false };
210
+ }
211
+ if (this.transient?.action === 'play') return { action: 'play', oneShot: true };
212
+ if (this.dockedEdge) return { action: 'peek', oneShot: false };
213
+ if (this.listening()) return { action: 'waiting', oneShot: false };
214
+ if (this.resting) return { action: 'sleeping', oneShot: false };
215
+ return { action: 'idle', oneShot: false };
216
+ }
217
+ baseAction() {
218
+ if (this.pendingDecision) return 'pending_decision';
219
+ const work = this.activeWorkAction();
220
+ if (work) return work;
221
+ if (this.dockedEdge) return 'peek';
222
+ if (this.listening()) return 'waiting';
223
+ return 'idle';
224
+ }
225
+
226
+ listening() { return ['talking', 'connecting'].includes(this.phase) && !this.context?.muted; }
227
+ activeWorkAction() {
228
+ if (this.snapshot.work) return workAction[this.snapshot.work.kind];
229
+ if (!this.hasNativeWork && this.context?.nativeActivity === 'tool_running') return 'working';
230
+ if (!this.hasNativeWork && this.context?.nativeActivity === 'reasoning') return 'staged_thought';
231
+ return null;
232
+ }
233
+ play(action, force = false) {
234
+ if (this.action === action && !force) return;
235
+ this.cancelFrame();
236
+ this.action = action;
237
+ this.frame = 0;
238
+ this.paint();
239
+ this.scheduleFrame();
240
+ }
241
+ paint() {
242
+ const { style, dataset } = this.element;
243
+ dataset.skin = this.skin;
244
+ dataset.action = this.action;
245
+ dataset.dockEdge = this.dockedEdge ?? 'none';
246
+ dataset.dockZone = this.dockZone ?? 'none';
247
+ if (this.living()) {
248
+ style.backgroundImage = 'none';
249
+ this.livingBody.show(this.action, { reducedMotion: this.reducedMotion, onEnded: () => this.completeOneShot() });
250
+ return;
251
+ }
252
+ this.livingBody?.hide();
253
+ const staticFile = staticSkins[this.skin];
254
+ if (staticFile) {
255
+ style.backgroundImage = `url("./skins/${staticFile}")`;
256
+ style.backgroundSize = 'contain';
257
+ style.backgroundPosition = 'center';
258
+ return;
259
+ }
260
+ const visual = visualAlias[this.action] ?? this.action;
261
+ const extra = this.skin === 'xianxian-codex' ? additional[visual] : undefined;
262
+ style.backgroundImage = `url("./skins/${extra?.file ?? `${this.skin}.webp`}")`;
263
+ style.backgroundSize = extra ? '960px 130px' : '960px 1170px';
264
+ style.backgroundPosition = `${-120 * this.frame}px ${-130 * (atlas[visual]?.row ?? 0)}px`;
265
+ }
266
+ scheduleFrame() {
267
+ if (this.reducedMotion) {
268
+ if (this.oneShot) this.frameTimer = this.setTimer(() => { this.frameTimer = undefined; this.completeOneShot(); }, 1_000);
269
+ return;
270
+ }
271
+ if (staticSkins[this.skin]) return;
272
+ if (this.living()) {
273
+ if (isLivingClip(this.action) || !this.oneShot) return;
274
+ this.frameTimer = this.setTimer(() => { this.frameTimer = undefined; this.completeOneShot(); }, 700);
275
+ return;
276
+ }
277
+ const visual = visualAlias[this.action] ?? this.action;
278
+ const frames = additional[visual]?.frames ?? atlas[visual]?.frames;
279
+ if (!frames) return;
280
+ this.frameTimer = this.setTimer(() => {
281
+ this.frameTimer = undefined;
282
+ if (this.frame + 1 === frames.length && this.oneShot) {
283
+ this.completeOneShot();
284
+ return;
285
+ }
286
+ this.frame = (this.frame + 1) % frames.length;
287
+ this.paint();
288
+ this.scheduleFrame();
289
+ }, frames[this.frame]);
290
+ }
291
+ cancelFrame() {
292
+ if (this.frameTimer !== undefined) this.clearTimer(this.frameTimer);
293
+ this.frameTimer = undefined;
294
+ }
295
+ completeOneShot() {
296
+ if (!this.oneShot) return;
297
+ this.oneShot = false;
298
+ this.transient = null;
299
+ this.action = '';
300
+ this.refresh();
301
+ }
302
+ canPlay() {
303
+ return !this.reducedMotion && !this.dragging && !this.pendingDecision && this.phase === 'idle'
304
+ && !this.activeWorkAction() && !this.snapshot.delivery && !this.snapshot.travel && !this.dockedEdge
305
+ && !staticSkins[this.skin];
306
+ }
307
+
308
+ armRest() {
309
+ if (this.restTimer === undefined && !this.resting && !this.pendingDecision && !this.dockedEdge) {
310
+ this.restTimer = this.setTimer(() => {
311
+ this.restTimer = undefined;
312
+ if (this.action === 'idle' && !this.dragging && !this.transient) {
313
+ this.resting = true;
314
+ this.refresh();
315
+ }
316
+ }, 45_000);
317
+ }
318
+ if (this.autoPlay && !this.reducedMotion && this.autoTimer === undefined) {
319
+ const delay = Math.max(this.autoPlayIdleMs, this.lastPlayAt + this.autoPlayCooldownMs - this.now());
320
+ this.autoTimer = this.setTimer(() => {
321
+ this.autoTimer = undefined;
322
+ if (!this.canPlay()) return;
323
+ this.lastPlayAt = this.now();
324
+ this.resting = false;
325
+ this.transient = { action: 'play', automatic: true };
326
+ this.refresh();
327
+ }, delay);
328
+ }
329
+ }
330
+
331
+ cancelRest() {
332
+ if (this.restTimer !== undefined) this.clearTimer(this.restTimer);
333
+ this.restTimer = undefined;
334
+ }
335
+
336
+ cancelIdleTimers() {
337
+ this.cancelRest();
338
+ if (this.autoTimer !== undefined) this.clearTimer(this.autoTimer);
339
+ this.autoTimer = undefined;
340
+ }
341
+
342
+ get snapshot() { return this.facts.snapshot; }
343
+ }
@@ -0,0 +1,74 @@
1
+ /** A compact projection of Host history plus the current unsaved voice caption. */
2
+ export class RecentBubble {
3
+ constructor(rows) {
4
+ this.rows = rows;
5
+ this.history = [];
6
+ this.live = new Map();
7
+ }
8
+ load(messages) {
9
+ this.history = messages.slice(-2);
10
+ this.render();
11
+ }
12
+ loadTranscript(rows, companionName = '猫猫') {
13
+ this.load(rows.map(row => ({
14
+ role: row.role,
15
+ text: row.text,
16
+ name: row.source?.kind === 'typed' ? '你' : row.role === 'assistant' ? companionName : '语音',
17
+ })));
18
+ }
19
+ append(role, text, name = role === 'user' ? '你' : '猫猫') {
20
+ if (!['user', 'assistant'].includes(role) || typeof text !== 'string') return;
21
+ const previous = this.live.get(role);
22
+ this.live.set(role, { name, text: `${previous?.text ?? ''}${text}`.slice(-240) });
23
+ this.render();
24
+ }
25
+ finish(role) {
26
+ this.live.delete(role);
27
+ this.render();
28
+ }
29
+ reset() {
30
+ this.live.clear();
31
+ this.render();
32
+ }
33
+ clear() {
34
+ this.history = [];
35
+ this.live.clear();
36
+ this.render();
37
+ }
38
+ hasContent() {
39
+ return this.history.length > 0 || this.live.size > 0;
40
+ }
41
+ render() {
42
+ const live = [...this.live].map(([role, value]) => ({ role, ...value }));
43
+ const entries = [...this.history.slice(-Math.max(0, 2 - live.length)), ...live].slice(-2);
44
+ for (const [index, row] of this.rows.entries()) {
45
+ const entry = entries[index];
46
+ row.hidden = !entry;
47
+ const speaker = entry ? `${String(entry.name).slice(0, 28)}:` : '';
48
+ const message = entry ? String(entry.text).slice(-120) : '';
49
+ row.textContent = `${speaker}${message}`;
50
+ if (entry && row.ownerDocument?.createElement && typeof row.replaceChildren === 'function') {
51
+ const speakerNode = row.ownerDocument.createElement('span');
52
+ const messageNode = row.ownerDocument.createElement('span');
53
+ const messageText = row.ownerDocument.createElement('bdi');
54
+ speakerNode.className = 'recent-speaker';
55
+ messageNode.className = 'recent-message';
56
+ messageText.className = 'recent-message-text';
57
+ messageText.dir = 'auto';
58
+ speakerNode.textContent = speaker;
59
+ // dir=auto resolves the first strong character. Reversing code points for
60
+ // this hidden-in-the-same-tick probe therefore resolves the latest strong
61
+ // character, which is the edge this compact tail projection must retain.
62
+ messageText.textContent = Array.from(message).reverse().join('');
63
+ messageNode.append(messageText);
64
+ row.replaceChildren(speakerNode, messageNode);
65
+ const direction = row.ownerDocument.defaultView?.getComputedStyle(messageText).direction;
66
+ messageText.dir = direction === 'rtl' ? 'rtl' : 'ltr';
67
+ messageText.textContent = message;
68
+ messageNode.dataset.direction = direction === 'rtl' ? 'rtl' : 'ltr';
69
+ }
70
+ row.dataset ??= {};
71
+ row.dataset.role = entry?.role ?? '';
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,171 @@
1
+ const sameValue = (left, right) => Object.is(left, right);
2
+ const canStopCall = field => ['dutyCatProfileId', 'householdReadsAllowed'].includes(field);
3
+
4
+ /**
5
+ * Renderer-side settings state only. The Host remains the single source of
6
+ * persisted values, roster truth, media stopping and plugin lifecycle.
7
+ */
8
+ export class SettingsController {
9
+ constructor({ client, changed = () => {} }) {
10
+ this.client = client;
11
+ this.changed = changed;
12
+ this.readOperation = 0;
13
+ this.writeOperation = 0;
14
+ this.state = { phase: 'idle', page: 'main', saving: false, notice: null, confirmation: null, retry: null };
15
+ }
16
+
17
+ publish(patch = {}) {
18
+ this.state = { ...this.state, ...patch };
19
+ this.changed(this.state);
20
+ }
21
+
22
+ applySettings(reply, patch = {}) {
23
+ if (reply?.kind !== 'settings' || reply.status !== 'available') return false;
24
+ this.publish({
25
+ phase: this.state.saving ? 'saving' : 'ready',
26
+ values: reply.values,
27
+ companions: reply.companions,
28
+ selectedCompanionStatus: reply.selectedCompanionStatus,
29
+ ...patch,
30
+ });
31
+ return true;
32
+ }
33
+
34
+ async load({ preserveSettlement = false } = {}) {
35
+ // A panel reopen is presentation work, not authority to cancel an in-flight
36
+ // write. The write performs its own canonical readback before settlement.
37
+ if (this.state.saving) return false;
38
+ const operation = ++this.readOperation;
39
+ this.publish({ phase: 'loading', ...(preserveSettlement ? {} : { notice: null, retry: null }) });
40
+ try {
41
+ const reply = await this.client.readSettings();
42
+ if (operation !== this.readOperation) return false;
43
+ const clearsUnknown = preserveSettlement && this.state.notice?.kind === 'unconfirmed';
44
+ if (this.applySettings(reply, clearsUnknown ? { notice: null, retry: null } : {})) return true;
45
+ this.publish({ phase: 'unavailable', reason: reply.reason, saving: false });
46
+ } catch (error) {
47
+ if (operation !== this.readOperation) return false;
48
+ this.publish({ phase: 'unavailable', saving: false,
49
+ reason: error?.code === 'invalid_request' ? 'host_upgrade_required' : 'temporarily_unavailable' });
50
+ }
51
+ return false;
52
+ }
53
+
54
+ navigate(page) {
55
+ this.publish({ page, confirmation: null });
56
+ }
57
+
58
+ async requestUpdate(field, value, { confirm = false } = {}) {
59
+ if (this.state.saving || sameValue(this.state.values?.[field], value)) return false;
60
+ if (confirm) {
61
+ this.publish({ page: 'confirm',
62
+ confirmation: { kind: 'setting', field, value, returnPage: this.state.page },
63
+ notice: null, retry: null });
64
+ return true;
65
+ }
66
+ await this.commitUpdate(field, value, this.state.page);
67
+ return true;
68
+ }
69
+
70
+ async readCanonical(operation) {
71
+ try {
72
+ const reply = await this.client.readSettings();
73
+ if (operation !== this.writeOperation || reply?.kind !== 'settings' || reply.status !== 'available') return null;
74
+ return reply;
75
+ } catch { return null; }
76
+ }
77
+
78
+ async commitUpdate(field, value, returnPage = this.state.page) {
79
+ if (this.state.saving) return { callStopped: null };
80
+ const operation = ++this.writeOperation;
81
+ this.publish({ phase: 'saving', saving: true, notice: null, retry: null });
82
+ let receipt;
83
+ try {
84
+ receipt = await this.client.updateSetting(field, value);
85
+ } catch {
86
+ if (operation !== this.writeOperation) return { callStopped: null };
87
+ const canonical = await this.readCanonical(operation);
88
+ if (operation !== this.writeOperation) return { callStopped: null };
89
+ if (canonical) this.applySettings(canonical);
90
+ const saved = canonical && sameValue(canonical.values[field], value);
91
+ const callStopped = canStopCall(field) ? null : false;
92
+ this.publish({ phase: canonical ? 'ready' : this.state.values ? 'ready' : 'unavailable', saving: false,
93
+ page: returnPage, confirmation: null,
94
+ retry: canonical && !saved ? { field, value } : null,
95
+ notice: canonical
96
+ ? { kind: saved ? 'reconciled_saved' : 'reconciled_not_saved', field, callStopped }
97
+ : { kind: 'unconfirmed', field, callStopped } });
98
+ return { callStopped };
99
+ }
100
+ if (operation !== this.writeOperation) return { callStopped: null };
101
+ const canonical = await this.readCanonical(operation);
102
+ if (operation !== this.writeOperation) return { callStopped: null };
103
+ if (canonical) this.applySettings(canonical);
104
+ const callStopped = receipt.callStatus === 'stopped';
105
+ let notice;
106
+ if (receipt.outcome === 'saved') {
107
+ notice = { kind: 'saved', field, callStopped, applies: receipt.applies };
108
+ } else if (receipt.outcome === 'rejected') {
109
+ notice = { kind: 'rejected', field, callStopped, reason: receipt.reason };
110
+ } else if (!canonical) {
111
+ notice = { kind: 'unconfirmed', field, callStopped };
112
+ } else {
113
+ notice = {
114
+ kind: sameValue(canonical.values[field], value) ? 'reconciled_saved' : 'reconciled_not_saved',
115
+ field,
116
+ callStopped,
117
+ };
118
+ }
119
+ const retry = (receipt.outcome === 'rejected' && ['save_failed', 'call_stop_failed'].includes(receipt.reason))
120
+ || (receipt.outcome === 'unconfirmed' && canonical && !sameValue(canonical.values[field], value))
121
+ ? { field, value } : null;
122
+ this.publish({ phase: canonical ? 'ready' : this.state.values ? 'ready' : 'unavailable', saving: false,
123
+ page: returnPage, confirmation: null, notice, retry });
124
+ return { callStopped };
125
+ }
126
+
127
+ async confirm() {
128
+ const confirmation = this.state.confirmation;
129
+ if (!confirmation || this.state.saving) return { callStopped: null };
130
+ if (confirmation.kind === 'setting') {
131
+ return this.commitUpdate(confirmation.field, confirmation.value, confirmation.returnPage);
132
+ }
133
+ const operation = ++this.writeOperation;
134
+ this.publish({ phase: 'saving', saving: true, notice: null });
135
+ try {
136
+ await this.client.disableCompanion();
137
+ if (operation !== this.writeOperation) return { callStopped: null };
138
+ this.publish({ phase: 'disabled', saving: false, confirmation: null });
139
+ return { callStopped: true };
140
+ } catch {
141
+ if (operation !== this.writeOperation) return { callStopped: null };
142
+ this.publish({ phase: this.state.values ? 'ready' : 'unavailable', saving: false,
143
+ page: confirmation.returnPage, confirmation: null, notice: { kind: 'disable_failed' } });
144
+ return { callStopped: null };
145
+ }
146
+ }
147
+
148
+ requestDisable() {
149
+ if (this.state.saving) return;
150
+ this.publish({ page: 'disable', confirmation: { kind: 'disable', returnPage: this.state.page }, notice: null });
151
+ }
152
+
153
+ async retry({ confirm = false } = {}) {
154
+ const retry = this.state.retry;
155
+ if (!retry || this.state.saving) return;
156
+ if (confirm && canStopCall(retry.field)) {
157
+ this.publish({ page: 'confirm',
158
+ confirmation: { kind: 'setting', field: retry.field, value: retry.value, returnPage: this.state.page } });
159
+ return;
160
+ }
161
+ await this.commitUpdate(retry.field, retry.value, this.state.page);
162
+ }
163
+
164
+ async resetPosition() {
165
+ if (this.state.saving) return;
166
+ try {
167
+ await this.client.resetPosition();
168
+ this.publish({ notice: { kind: 'position_reset' } });
169
+ } catch { this.publish({ notice: { kind: 'position_reset_failed' } }); }
170
+ }
171
+ }