cortico-world-agent-speed 0.2.0 → 0.2.2

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 (189) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/LICENSE +0 -14
  3. package/README.md +29 -11
  4. package/THIRD_PARTY_NOTICES.md +69 -0
  5. package/activity.d.ts +15 -0
  6. package/activity.js +88 -3
  7. package/describe.json +806 -0
  8. package/dist/webui.css +2 -0
  9. package/dist/webui.css.map +7 -0
  10. package/dist/webui.js +2 -0
  11. package/dist/webui.js.map +7 -0
  12. package/host/app-store.cjs +68 -0
  13. package/host/cursor.cjs +67 -0
  14. package/host/electron-main.cjs +666 -0
  15. package/host/input-shape.cjs +63 -0
  16. package/host/mouse-lease.cjs +77 -0
  17. package/host/overlay.cjs +139 -0
  18. package/host/portrait.cjs +52 -0
  19. package/host/preload.cjs +60 -14
  20. package/host/renderer-gone.cjs +24 -0
  21. package/host/windows.cjs +251 -0
  22. package/package.json +27 -7
  23. package/scripts/build-webui.mjs +40 -0
  24. package/scripts/speech-bank/build.py +166 -0
  25. package/scripts/speech-bank/dicts.py +76 -0
  26. package/src/ENV_PROMPT.en.md +51 -0
  27. package/src/ENV_PROMPT.md +51 -0
  28. package/src/asr/address.ts +25 -0
  29. package/src/asr/hotkey.ts +335 -0
  30. package/src/asr/result.ts +51 -0
  31. package/src/asr/segmenter.ts +269 -0
  32. package/src/asr/sherpa.ts +280 -0
  33. package/src/asr/simplify.ts +38 -0
  34. package/src/asr/system-recognizer.ts +292 -0
  35. package/src/asr/system-sapi.ps1 +173 -0
  36. package/src/asr/transcription-api.ts +176 -0
  37. package/src/chat.ts +212 -0
  38. package/src/config.ts +481 -0
  39. package/src/cua/ENV_PROMPT.en.md +29 -0
  40. package/src/cua/ENV_PROMPT.md +29 -0
  41. package/src/cua/config.ts +88 -0
  42. package/src/cua/cua.ts +712 -0
  43. package/src/cua/engine/darwin.ts +410 -0
  44. package/src/cua/engine/display.ts +55 -0
  45. package/src/cua/engine/fail.ts +15 -0
  46. package/src/cua/engine/foreground.ts +8 -0
  47. package/src/cua/engine/image.ts +57 -0
  48. package/src/cua/engine/keys.ts +70 -0
  49. package/src/cua/engine/linux-keys.ts +29 -0
  50. package/src/cua/engine/linux.ts +343 -0
  51. package/src/cua/engine/mac-keys.ts +57 -0
  52. package/src/cua/engine/user-activity.ts +54 -0
  53. package/src/cua/engine/wait-idle.ts +31 -0
  54. package/src/cua/engine/win32.ts +299 -0
  55. package/src/cua/engine-child.ts +274 -0
  56. package/src/cua/engine-ipc.ts +140 -0
  57. package/src/cua/i18n/de.ts +53 -0
  58. package/src/cua/i18n/en.ts +63 -0
  59. package/src/cua/i18n/es-419.ts +53 -0
  60. package/src/cua/i18n/fr.ts +53 -0
  61. package/src/cua/i18n/index.ts +26 -0
  62. package/src/cua/i18n/it.ts +53 -0
  63. package/src/cua/i18n/ja.ts +53 -0
  64. package/src/cua/i18n/ko.ts +53 -0
  65. package/src/cua/i18n/pt-BR.ts +53 -0
  66. package/src/cua/i18n/ru.ts +59 -0
  67. package/src/cua/i18n/zh-Hant.ts +53 -0
  68. package/src/cua/i18n/zh.ts +59 -0
  69. package/src/cua/model-text.ts +252 -0
  70. package/src/cua/terminal.ts +31 -0
  71. package/src/cua/tools.ts +153 -0
  72. package/src/definition.ts +146 -0
  73. package/src/host-reason.ts +32 -0
  74. package/src/i18n/de.ts +409 -0
  75. package/src/i18n/en.ts +443 -0
  76. package/src/i18n/es-419.ts +409 -0
  77. package/src/i18n/fr.ts +409 -0
  78. package/src/i18n/index.ts +56 -0
  79. package/src/i18n/it.ts +409 -0
  80. package/src/i18n/ja.ts +409 -0
  81. package/src/i18n/ko.ts +409 -0
  82. package/src/i18n/pt-BR.ts +409 -0
  83. package/src/i18n/ru.ts +415 -0
  84. package/src/i18n/zh-Hant.ts +409 -0
  85. package/src/i18n/zh.ts +440 -0
  86. package/src/index.ts +15 -0
  87. package/src/model-text.ts +344 -0
  88. package/src/moves.ts +101 -0
  89. package/src/pack-import.ts +361 -0
  90. package/src/packs.ts +449 -0
  91. package/src/runtime/download.ts +29 -0
  92. package/src/runtime/store.ts +293 -0
  93. package/src/script.ts +202 -0
  94. package/src/self.ts +247 -0
  95. package/src/server.ts +479 -0
  96. package/src/speech/data/CMUDICT-LICENSE +33 -0
  97. package/src/speech/data/IPADIC-COPYING +71 -0
  98. package/src/speech/data/UNICODE-LICENSE +39 -0
  99. package/src/speech/data/en.tsv.gz +0 -0
  100. package/src/speech/data/ja-ipadic.tsv.gz +0 -0
  101. package/src/speech/data/ja-unihan.tsv.gz +0 -0
  102. package/src/speech/data/zh.json +1 -0
  103. package/src/speech/index.ts +204 -0
  104. package/src/speech/ipa.ts +83 -0
  105. package/src/speech/japanese.ts +105 -0
  106. package/src/speech/jukujikun.ts +22 -0
  107. package/src/speech/korean.ts +35 -0
  108. package/src/speech/lang.ts +151 -0
  109. package/src/speech/rules.ts +72 -0
  110. package/src/speech/syllable.ts +76 -0
  111. package/src/status.ts +164 -0
  112. package/src/tools.ts +110 -0
  113. package/src/webui/api-rows.css +2 -0
  114. package/src/webui/api-rows.ts +44 -0
  115. package/src/webui/client.ts +451 -0
  116. package/src/webui/dress-dialog.css +14 -0
  117. package/src/webui/dress-dialog.ts +117 -0
  118. package/src/webui/dress-panel.ts +160 -0
  119. package/src/webui/key-capture.ts +60 -0
  120. package/src/webui/shared/modal.css +13 -0
  121. package/src/webui/shared/modal.ts +77 -0
  122. package/src/webui/shared/problem.css +15 -0
  123. package/src/webui/shared/problem.ts +217 -0
  124. package/src/webui/shared/strings.ts +5 -0
  125. package/src/webui/style.css +50 -0
  126. package/src/window-host.ts +116 -0
  127. package/src/world.ts +2926 -0
  128. package/web/activity-motion.js +117 -0
  129. package/web/appearance.js +60 -0
  130. package/web/body-host.js +257 -0
  131. package/web/coo/coo.js +384 -0
  132. package/web/coo/figure.js +15 -0
  133. package/web/coo/figure.json +1224 -0
  134. package/web/dist/dress-dialog.css +1 -0
  135. package/web/dist/dress-dialog.js +1 -0
  136. package/web/drag-row.js +49 -0
  137. package/web/drag.js +149 -0
  138. package/web/dress.css +170 -0
  139. package/web/dress.html +37 -0
  140. package/web/dress.js +786 -0
  141. package/web/figure-frame.html +16 -0
  142. package/web/figure-frame.js +128 -0
  143. package/web/frame-loop.js +55 -0
  144. package/web/hints.js +77 -0
  145. package/web/i18n/de.js +170 -0
  146. package/web/i18n/en.js +177 -0
  147. package/web/i18n/es-419.js +170 -0
  148. package/web/i18n/fr.js +170 -0
  149. package/web/i18n/it.js +170 -0
  150. package/web/i18n/ja.js +170 -0
  151. package/web/i18n/ko.js +170 -0
  152. package/web/i18n/pt-BR.js +170 -0
  153. package/web/i18n/ru.js +170 -0
  154. package/web/i18n/zh-Hant.js +170 -0
  155. package/web/i18n/zh.js +175 -0
  156. package/web/i18n.js +54 -0
  157. package/{renderer/vendor → web}/kit/body.js +31 -58
  158. package/web/looks.js +70 -0
  159. package/web/mic-worklet.js +36 -0
  160. package/web/mic.js +117 -0
  161. package/web/motion-frames.js +80 -0
  162. package/web/motion-level.js +40 -0
  163. package/web/new-year-2027.svg +238 -0
  164. package/web/overlay.html +16 -0
  165. package/web/overlay.js +100 -0
  166. package/web/pet-app.js +3000 -0
  167. package/web/pet.css +642 -0
  168. package/web/pet.html +21 -0
  169. package/web/scale-slider.js +259 -0
  170. package/web/show-hide.js +49 -0
  171. package/web/sound.js +245 -0
  172. package/web/speech/zh.json +1 -0
  173. package/web/speech/zh.ogg +0 -0
  174. package/web/speech.js +197 -0
  175. package/web/stage.js +160 -0
  176. package/web/swap-motion.js +119 -0
  177. package/web/ui.js +195 -0
  178. package/host/launch.js +0 -187
  179. package/host/library.cjs +0 -638
  180. package/host/main.cjs +0 -389
  181. package/index.js +0 -93
  182. package/renderer/index.html +0 -22
  183. package/renderer/pet-sandbox.html +0 -11
  184. package/renderer/pet.css +0 -38
  185. package/renderer/pet.js +0 -251
  186. package/renderer/vendor/activity-motion.js +0 -101
  187. package/renderer/vendor/figure-frame.js +0 -115
  188. package/renderer/vendor/pack.css +0 -2
  189. /package/{renderer/vendor → web}/kit/rig.js +0 -0
@@ -0,0 +1,451 @@
1
+ import { actionProblem, listProblem } from './shared/problem.ts';
2
+ /**
3
+ * Console panels for the desktop pet: `pet` (window, dressing, window runtime) and `voice`
4
+ * (recognition engine, the FunASR or Whisper model download or the transcription service's settings (api-rows.ts),
5
+ * microphone level, recognized lines). Data goes
6
+ * through `ctx.invoke`, the level meter through `ctx.stream('voice')`. Text is the World's table
7
+ * (src/i18n) for the console's language.
8
+ */
9
+ import type { WebUiClientBundle, WebUiPanel, WebUiPanelContext } from 'cortico/web/shared/client-panel.ts';
10
+ import { petText } from '../i18n/index.ts';
11
+ import { describeHostReason, type HostReason } from '../host-reason.ts';
12
+ import { captureKey, PRESSES, splitTaps, withTaps } from './key-capture.ts';
13
+ import { apiRows, type ApiState } from './api-rows.ts';
14
+ import { mountDress } from './dress-panel.ts';
15
+ import './style.css';
16
+
17
+ interface Artifact { phase: 'absent' | 'working' | 'ready' | 'error'; path: string; done: number; total: number | null; detail: string | null }
18
+ interface PetState {
19
+ inWindow: boolean;
20
+ url: string | null;
21
+ window: { phase: string; pid: number | null; source: string | null; reason: HostReason | null } | null;
22
+ electron: Artifact & { supported: boolean };
23
+ screen: { w: number; h: number } | null;
24
+ }
25
+ interface VoiceState {
26
+ enabled: boolean;
27
+ serviceEnabled: boolean;
28
+ /** The engine in force, and the setting it came from */
29
+ engine: Engine;
30
+ engineSetting: Engine;
31
+ systemSupported: boolean;
32
+ server: { phase: string; url: string; pid: number | null; detail: string | null } | null;
33
+ /** The download of the FunASR or Whisper model: the engine in force's, else the app language's. */
34
+ model: Artifact & { bytes: number; engine: Exclude<Engine, 'system' | 'api'> };
35
+ api: ApiState;
36
+ mic: { state: string; detail: string | null };
37
+ input: {
38
+ mode: MicMode;
39
+ hotkey: string;
40
+ deviceId: string;
41
+ openOnPress: boolean;
42
+ /** The keys alone; how they are pressed is the press choice beside them */
43
+ keyLabel: string;
44
+ hint: string;
45
+ hotkeyProblem: string | null;
46
+ open: boolean;
47
+ devices: Array<{ id: string; label: string }>;
48
+ };
49
+ /** `asr.recording`; `range` is the allowed `maxMinutes`. */
50
+ recording: { enabled: boolean; transcript: boolean; maxMinutes: number; range: [number, number]; endpointTakesAudio: boolean };
51
+ level: number;
52
+ thresholdDb: number;
53
+ recent: Array<{ text: string; at: number; ms: number; dropped?: boolean }>;
54
+ counts: { utterances: number; delivered: number; dropped: number };
55
+ }
56
+
57
+ type MicMode = 'hold' | 'toggle' | 'always';
58
+ type Engine = 'funasr' | 'whisper' | 'system' | 'api';
59
+
60
+ const MB = (n: number) => `${Math.round(n / 1048576)} MB`;
61
+ const progress = (a: Artifact) => (a.total ? `${Math.round((a.done / a.total) * 100)}%` : MB(a.done));
62
+ const errText = (err: unknown) => (err instanceof Error ? err.message : String(err));
63
+
64
+ /** `note`: the detail explains the setting, shown whole in the text font; otherwise it is a status line cut to two lines. */
65
+ function statusRow(ctx: WebUiPanelContext, name: string, note = false) {
66
+ const { ui } = ctx;
67
+ const row = ui.h('div', 'mountrow');
68
+ const dot = ui.h('span', 'navdot');
69
+ const state = ui.h('span', 'mstate', '—');
70
+ const detail = ui.h('span', note ? 'mdetail pet-note' : 'mdetail');
71
+ const acts = ui.h('span', 'macts');
72
+ row.append(dot, ui.h('span', 'mname', name), state, detail, acts);
73
+ return {
74
+ row, acts,
75
+ set(text: string, tone: 'on' | 'off' | 'busy' | 'bad', more = '') {
76
+ state.textContent = text;
77
+ detail.textContent = more;
78
+ // cut with an ellipsis where the row is short of room: the whole line on hover
79
+ detail.title = more;
80
+ dot.className = `navdot ${tone === 'on' ? 'ok' : tone === 'bad' ? 'bad' : tone === 'busy' ? 'warn' : ''}`;
81
+ },
82
+ };
83
+ }
84
+
85
+ /** A card without a heading: the tab above it already names the page. */
86
+ function untitledSheet(ui: WebUiPanelContext['ui']): { el: HTMLElement; body: HTMLElement } {
87
+ const el = ui.h('div', 'sheet tabbed pet-untitled');
88
+ const body = ui.h('div', 'sheetbody');
89
+ el.append(body);
90
+ return { el, body };
91
+ }
92
+
93
+ const petPanel: WebUiPanel = {
94
+ mount(ctx) {
95
+ const { ui, root } = ctx;
96
+ const problem = actionProblem(ui, root.ownerDocument, ctx.signal, ctx.language);
97
+ const t = petText(ctx.language).panel;
98
+ const card = untitledSheet(ui);
99
+ root.appendChild(card.el);
100
+ const s = card.body;
101
+ const msg = ui.h('div', 'read-feedback');
102
+ root.prepend(msg);
103
+ card.el.hidden = true;
104
+
105
+ const win = statusRow(ctx, t.window);
106
+ const btnOpen = ui.button(t.openWindow, { size: 'sm', variant: 'primary' });
107
+ const btnClose = ui.button(t.closeWindow, { size: 'sm' });
108
+ win.acts.append(btnClose, btnOpen);
109
+
110
+ const rt = statusRow(ctx, t.runtime);
111
+ const btnInstall = ui.button(t.install, { size: 'sm', variant: 'primary' });
112
+ rt.acts.append(btnInstall);
113
+
114
+ const dress = ui.sheet({ title: t.dress, desc: ctx.language === 'zh' || ctx.language === 'zh-Hant' ? '保存后同步到桌宠窗口' : 'Save changes to update the pet window' });
115
+ root.appendChild(dress.el);
116
+ mountDress(ctx, dress.body);
117
+
118
+ s.append(win.row, rt.row);
119
+ dress.el.hidden = true;
120
+
121
+ let st: PetState | null = null;
122
+ const render = (next: PetState) => {
123
+ st = next;
124
+ card.el.hidden = dress.el.hidden = false;
125
+ msg.replaceChildren();
126
+ const w = next.window;
127
+ if (next.inWindow) win.set(t.connected, 'on');
128
+ else if (w?.phase === 'running') win.set(t.starting, 'busy');
129
+ else win.set(w?.phase === 'missing' || w?.phase === 'error' ? t.cannotOpen : t.notOpen, w?.phase === 'missing' || w?.phase === 'error' ? 'bad' : 'off', w?.reason ? describeHostReason(petText(ctx.language).windowReason, w.reason) : '');
130
+ btnOpen.disabled = w?.phase === 'running';
131
+ btnClose.disabled = w?.phase !== 'running';
132
+ const e = next.electron;
133
+ if (w?.source && w.source !== e.path && e.phase !== 'ready') rt.set(t.external, 'on', w.source);
134
+ else if (e.phase === 'ready') rt.set(t.installed, 'on', e.path);
135
+ else if (e.phase === 'working') rt.set(t.downloading(progress(e)), 'busy', e.detail ?? '');
136
+ else if (e.phase === 'error') rt.set(t.installFailed, 'bad', e.detail ?? '');
137
+ else rt.set(e.supported ? t.notInstalled : t.noBuild, 'off', e.supported ? t.electronSize : '');
138
+ btnInstall.hidden = e.phase === 'ready' || !e.supported;
139
+ btnInstall.disabled = e.phase === 'working';
140
+ };
141
+ const refresh = async () => { try { render(await ctx.invoke<PetState>('state')); } catch (err) { if (!ctx.signal.aborted) msg.replaceChildren(listProblem(root.ownerDocument, errText(err))); } };
142
+ const call = (method: string, anchor: HTMLElement) => async () => {
143
+ try { render(await ctx.invoke<PetState>(method)); } catch (err) { if (!ctx.signal.aborted) problem(anchor, errText(err)); }
144
+ };
145
+ btnOpen.addEventListener('click', call('openWindow', btnOpen));
146
+ btnClose.addEventListener('click', call('closeWindow', btnClose));
147
+ btnInstall.addEventListener('click', call('installElectron', btnInstall));
148
+ void refresh();
149
+ ctx.interval(() => void refresh(), 1500);
150
+ },
151
+ };
152
+
153
+ /** The engines with a name of their own; the system recognizer's is in the text table. */
154
+ const ENGINE_NAMES: Partial<Record<Engine, string>> = { funasr: 'FunASR', whisper: 'Whisper' };
155
+
156
+ const FLOOR_DB = -60;
157
+ const meterPct = (db: number) => Math.max(0, Math.min(100, ((db - FLOOR_DB) / -FLOOR_DB) * 100));
158
+ /** The threshold the mark can be set to: the meter's span, whole dB. */
159
+ const markDb = (db: number) => Math.round(Math.max(FLOOR_DB, Math.min(0, db)));
160
+ const ARROW_STEPS: Record<string, number> = { ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1 };
161
+
162
+ const voicePanel: WebUiPanel = {
163
+ mount(ctx) {
164
+ const { ui, root } = ctx;
165
+ const problem = actionProblem(ui, root.ownerDocument, ctx.signal, ctx.language);
166
+ const text = petText(ctx.language);
167
+ const t = text.panel;
168
+ const card = untitledSheet(ui);
169
+ root.appendChild(card.el);
170
+ const s = card.body;
171
+ const msg = ui.h('div', 'read-feedback');
172
+ root.prepend(msg);
173
+ card.el.hidden = true;
174
+
175
+ // The master switch: everything below only works while it is on.
176
+ const master = ui.h('label', 'pet-master');
177
+ const masterText = ui.h('span', 'pet-mastertext');
178
+ const masterTitle = ui.h('span', 'pet-mastertitle', t.enable);
179
+ const masterHint = ui.h('span', 'pet-masterhint');
180
+ masterText.append(masterTitle, masterHint);
181
+ const enabled = ui.h('input', 'pet-switch');
182
+ enabled.type = 'checkbox';
183
+ enabled.setAttribute('role', 'switch');
184
+ enabled.addEventListener('change', () => void call('setEnabled', enabled, [enabled.checked])());
185
+ master.append(masterText, enabled);
186
+ const settings = ui.h('div', 'pet-voicebody');
187
+
188
+ const eng = statusRow(ctx, t.engine, true);
189
+ const engineSel = ui.select();
190
+ eng.acts.append(engineSel);
191
+
192
+ const srv = statusRow(ctx, t.server);
193
+ const btnStart = ui.button(t.start, { size: 'sm', variant: 'primary' });
194
+ const btnStop = ui.button(t.stop, { size: 'sm' });
195
+ srv.acts.append(btnStop, btnStart);
196
+
197
+ const rt = statusRow(ctx, t.model);
198
+ const btnInstall = ui.button(t.download, { size: 'sm', variant: 'primary' });
199
+ rt.acts.append(btnInstall);
200
+ const api = apiRows(ctx, t, (name) => statusRow(ctx, name), (patch, anchor) => void call('setApi', anchor, [patch])());
201
+
202
+ const micRow = statusRow(ctx, t.mic);
203
+ const deviceSel = ui.select();
204
+ micRow.acts.append(deviceSel);
205
+
206
+ const modeRow = statusRow(ctx, t.mode, true);
207
+ const modeSel = ui.select();
208
+ modeSel.replaceChildren(...(Object.keys(t.modes) as MicMode[]).map((m) => { const o = ui.h('option', null, t.modes[m]); o.value = m; return o; }));
209
+ const pressSel = ui.select();
210
+ modeRow.acts.append(modeSel, pressSel);
211
+ // hold mode only: the microphone opens with the talk key
212
+ const onPressRow = statusRow(ctx, t.openOnPress, true);
213
+ const onPress = ui.h('input', 'pet-switch');
214
+ onPress.type = 'checkbox';
215
+ onPress.setAttribute('role', 'switch');
216
+ onPress.addEventListener('change', () => void call('setMic', onPress, [{ openOnPress: onPress.checked }])());
217
+ onPressRow.acts.append(onPress);
218
+ const switchIn = (row: ReturnType<typeof statusRow>, change: (on: boolean) => void) => {
219
+ const input = ui.h('input', 'pet-switch');
220
+ input.type = 'checkbox';
221
+ input.setAttribute('role', 'switch');
222
+ input.addEventListener('change', () => change(input.checked));
223
+ row.acts.append(input);
224
+ return input;
225
+ };
226
+ const recRow = statusRow(ctx, t.recording, true);
227
+ const rec = switchIn(recRow, (enabled) => void call('setRecording', rec, [{ enabled }])());
228
+ // the transcript and the limit only matter while a recording goes along
229
+ const transcriptRow = statusRow(ctx, t.transcript, true);
230
+ const transcript = switchIn(transcriptRow, (on) => void call('setRecording', transcript, [{ transcript: on }])());
231
+ const maxRow = statusRow(ctx, t.recordingMax, true);
232
+ const maxInput = ui.input({
233
+ type: 'number', cls: 'pet-minutes',
234
+ onChange: (value) => void call('setRecording', maxInput, [{ maxMinutes: Number(value) }])(),
235
+ });
236
+ maxInput.step = '1';
237
+ maxRow.acts.append(maxInput, ui.h('span', 'pet-unit', t.minutes));
238
+ // the talk key has a row of its own above how it listens: the key, and a button to set another
239
+ const keyRow = statusRow(ctx, t.talkKeyName);
240
+ const keyBtn = ui.button(t.changeKey, { size: 'sm' });
241
+ keyRow.acts.append(keyBtn);
242
+
243
+ // the level meter as one more row: its name in the names' column, the bar where the others' values start
244
+ const meterRow = ui.h('div', 'mountrow pet-meterrow');
245
+ const meterDot = ui.h('span', 'navdot');
246
+ meterDot.style.visibility = 'hidden';
247
+ const meterWrap = ui.h('div', 'pet-meterwrap');
248
+ const meter = ui.h('div', 'pet-meter');
249
+ const fill = ui.h('div', 'pet-meterfill');
250
+ meter.append(fill);
251
+ // the speech threshold, dragged along the meter or moved with the arrow keys
252
+ const mark = ui.h('div', 'pet-metermark');
253
+ mark.tabIndex = 0;
254
+ mark.title = t.thresholdHint;
255
+ mark.setAttribute('role', 'slider');
256
+ mark.setAttribute('aria-label', text.config.thresholdDb.title);
257
+ mark.setAttribute('aria-valuemin', String(FLOOR_DB));
258
+ mark.setAttribute('aria-valuemax', '0');
259
+ meterWrap.append(meter, mark);
260
+ meterRow.append(meterDot, ui.h('span', 'mname', t.level), meterWrap);
261
+
262
+ const log = ui.log({ max: 100, empty: t.noResults });
263
+ settings.append(eng.row, srv.row, rt.row, ...api.rows, micRow.row, keyRow.row, modeRow.row, onPressRow.row, meterRow, recRow.row, transcriptRow.row, maxRow.row);
264
+ s.append(master, settings);
265
+ const results = ui.sheet({ title: t.results, desc: t.resultsHint });
266
+ results.body.append(log.el);
267
+ root.appendChild(results.el);
268
+ results.el.hidden = true;
269
+
270
+ let st: VoiceState | null = null;
271
+ let seen = 0;
272
+ /** The threshold under the pointer while the mark is held */
273
+ let held: number | null = null;
274
+ const placeMark = (db: number) => {
275
+ mark.style.left = `${meterPct(db)}%`;
276
+ mark.setAttribute('aria-valuenow', String(db));
277
+ mark.setAttribute('aria-valuetext', `${db} dBFS`);
278
+ };
279
+ const render = (next: VoiceState) => {
280
+ st = next;
281
+ card.el.hidden = results.el.hidden = false;
282
+ msg.replaceChildren();
283
+ enabled.checked = next.enabled;
284
+ master.classList.toggle('on', next.enabled);
285
+ const onPressOn = next.input.mode === 'hold' && next.input.openOnPress;
286
+ const audioOnly = next.recording.enabled && next.recording.endpointTakesAudio && !next.recording.transcript;
287
+ masterHint.textContent = !next.enabled ? t.disabledHint
288
+ : !next.serviceEnabled && !audioOnly ? text.voice.serviceStopped
289
+ : onPressOn ? t.enabledHintOnPress : t.enabledHint;
290
+ settings.classList.toggle('off', !next.enabled);
291
+ const engines: Partial<Record<Engine, string>> = { funasr: t.funasr, whisper: t.whisper };
292
+ // Windows' own recognizer exists only there
293
+ if (next.systemSupported) engines.system = t.system;
294
+ engines.api = t.api;
295
+ if (engineSel.dataset.list !== JSON.stringify(engines)) {
296
+ engineSel.dataset.list = JSON.stringify(engines);
297
+ engineSel.replaceChildren(...(Object.keys(engines) as Engine[]).map((k) => { const o = ui.h('option', null, engines[k] ?? k); o.value = k; return o; }));
298
+ }
299
+ if (document.activeElement !== engineSel) engineSel.value = next.engine;
300
+ eng.set(ENGINE_NAMES[next.engine] ?? (next.engine === 'api' ? t.apiName : t.system), 'on', { funasr: t.funasrHint, whisper: t.whisperHint, system: t.systemHint, api: t.apiHint }[next.engine]);
301
+ const sv = next.server;
302
+ if (!next.serviceEnabled) srv.set(t.stopped, 'off');
303
+ else if (!sv) srv.set('—', 'off');
304
+ else if (sv.phase === 'running') srv.set(t.ready, 'on', sv.url);
305
+ else if (sv.phase === 'starting') srv.set(t.starting, 'busy', sv.url);
306
+ else if (sv.phase === 'error') srv.set(t.error, 'bad', sv.detail ?? '');
307
+ else srv.set(t.stopped, 'off', sv.url);
308
+ btnStart.disabled = !next.enabled || (next.serviceEnabled && (sv?.phase === 'running' || sv?.phase === 'starting'));
309
+ btnStop.disabled = !next.enabled || !next.serviceEnabled;
310
+
311
+ const m = next.model;
312
+ if (m.phase === 'working') rt.set(t.downloading(progress(m)), 'busy', m.detail ?? '');
313
+ else if (m.phase === 'error') rt.set(t.downloadFailed, 'bad', m.detail ?? '');
314
+ else if (m.phase === 'ready') rt.set(t.downloaded, 'on', m.path);
315
+ else rt.set(t.notDownloaded, 'off', t.modelSource(MB(m.bytes)));
316
+ btnInstall.disabled = m.phase === 'working';
317
+ btnInstall.hidden = m.phase === 'ready';
318
+ btnInstall.textContent = m.phase === 'error' ? t.retry : t.download;
319
+ // the system recognizer and the transcription service have no model to download
320
+ rt.row.style.display = next.engine === 'system' || next.engine === 'api' ? 'none' : '';
321
+ api.render(next.api, next.engine === 'api');
322
+
323
+ const mic = next.mic;
324
+ micRow.set(t.micStates[mic.state] ?? mic.state, mic.state === 'on' ? 'on' : mic.state === 'off' ? 'off' : 'bad', mic.detail ?? '');
325
+ const input = next.input;
326
+ const choices = [{ id: '', label: t.defaultDevice }, ...input.devices];
327
+ if (input.deviceId && !choices.some((d) => d.id === input.deviceId)) choices.push({ id: input.deviceId, label: t.missingDevice });
328
+ if (deviceSel.dataset.list !== JSON.stringify(choices)) {
329
+ deviceSel.dataset.list = JSON.stringify(choices);
330
+ deviceSel.replaceChildren(...choices.map((d, i) => { const o = ui.h('option', null, d.label || t.micN(i)); o.value = d.id; return o; }));
331
+ }
332
+ if (document.activeElement !== deviceSel) deviceSel.value = input.deviceId;
333
+ if (document.activeElement !== modeSel) modeSel.value = input.mode;
334
+ // a talk key set to three presses in config.json keeps its choice; the panel offers two or one
335
+ const { taps } = splitTaps(input.hotkey);
336
+ const press = input.mode === 'toggle' ? 'toggle' : 'hold';
337
+ const presses = PRESSES.filter((n) => n < 3 || n === taps).map((n) => [n, t.presses[n]![press]] as const);
338
+ if (pressSel.dataset.list !== JSON.stringify(presses)) {
339
+ pressSel.dataset.list = JSON.stringify(presses);
340
+ pressSel.replaceChildren(...presses.map(([n, label]) => { const o = ui.h('option', null, label); o.value = String(n); return o; }));
341
+ }
342
+ if (document.activeElement !== pressSel) pressSel.value = String(taps);
343
+ // 「一直收音」 hides the key's row, its 「取消」 with it: a capture still listening there ends
344
+ if (capture && input.mode === 'always') capture.stop();
345
+ if (!capture) keyRow.set(input.keyLabel, input.hotkeyProblem ? 'bad' : 'on');
346
+ pressSel.hidden = input.mode === 'always';
347
+ keyRow.row.style.display = input.mode === 'always' ? 'none' : '';
348
+ modeRow.set(input.open ? t.listening : t.waitingKey, input.open ? 'on' : 'off', input.hint);
349
+ onPressRow.row.style.display = input.mode === 'hold' ? '' : 'none';
350
+ onPress.checked = input.openOnPress;
351
+ onPressRow.set(input.openOnPress ? t.switchOn : t.switchOff, input.openOnPress ? 'on' : 'off', t.openOnPressHint);
352
+ const r = next.recording;
353
+ const goes = r.enabled && r.endpointTakesAudio;
354
+ rec.checked = r.enabled;
355
+ recRow.set(r.enabled ? t.switchOn : t.switchOff, goes ? 'on' : 'off', r.endpointTakesAudio ? t.recordingHint : t.recordingNoAudio);
356
+ transcriptRow.row.style.display = maxRow.row.style.display = goes ? '' : 'none';
357
+ transcript.checked = r.transcript;
358
+ transcriptRow.set(r.transcript ? t.switchOn : t.switchOff, r.transcript ? 'on' : 'off', t.transcriptHint);
359
+ [maxInput.min, maxInput.max] = r.range.map(String) as [string, string];
360
+ if (document.activeElement !== maxInput) maxInput.value = String(r.maxMinutes);
361
+ maxRow.set('', 'on', t.recordingMaxHint);
362
+ // the loudness threshold only decides where speech starts when the key is not held down
363
+ mark.hidden = input.mode === 'hold';
364
+ if (document.activeElement !== mark) placeMark(next.thresholdDb);
365
+ for (const line of next.recent) {
366
+ if (line.at <= seen) continue;
367
+ seen = line.at;
368
+ const el = log.append(line.text, line.dropped ? 'dim' : 'plain');
369
+ if (line.dropped) el.style.textDecoration = 'line-through';
370
+ }
371
+ };
372
+ const refresh = async () => { try { render(await ctx.invoke<VoiceState>('state')); } catch (err) { if (!ctx.signal.aborted) msg.replaceChildren(listProblem(root.ownerDocument, errText(err))); } };
373
+ const call = (method: string, anchor: HTMLElement, args: unknown[] = []) => async () => {
374
+ try { render(await ctx.invoke<VoiceState>(method, args)); } catch (err) { if (!ctx.signal.aborted) problem(anchor, errText(err)); }
375
+ };
376
+ btnStart.addEventListener('click', call('start', btnStart));
377
+ engineSel.addEventListener('change', () => void call('setEngine', engineSel, [engineSel.value])());
378
+ btnStop.addEventListener('click', call('stop', btnStop));
379
+ btnInstall.addEventListener('click', call('install', btnInstall));
380
+ modeSel.addEventListener('change', () => void call('setMic', modeSel, [{ mode: modeSel.value }])());
381
+ deviceSel.addEventListener('change', () => void call('setMic', deviceSel, [{ deviceId: deviceSel.value }])());
382
+ const dbAt = (x: number) => {
383
+ const r = meter.getBoundingClientRect();
384
+ return markDb(FLOOR_DB + ((x - r.left) / r.width) * -FLOOR_DB);
385
+ };
386
+ mark.addEventListener('pointerdown', (e) => {
387
+ e.preventDefault();
388
+ mark.focus();
389
+ mark.setPointerCapture(e.pointerId);
390
+ held = dbAt(e.clientX);
391
+ placeMark(held);
392
+ });
393
+ mark.addEventListener('pointermove', (e) => {
394
+ if (held === null) return;
395
+ held = dbAt(e.clientX);
396
+ placeMark(held);
397
+ });
398
+ mark.addEventListener('pointerup', () => {
399
+ if (held === null) return;
400
+ const db = held;
401
+ held = null;
402
+ void call('setThreshold', mark, [db])();
403
+ });
404
+ mark.addEventListener('pointercancel', () => {
405
+ held = null;
406
+ if (st) placeMark(st.thresholdDb);
407
+ });
408
+ mark.addEventListener('keydown', (e) => {
409
+ const step = ARROW_STEPS[e.key];
410
+ if (!step || held !== null) return;
411
+ e.preventDefault();
412
+ const db = markDb(Number(mark.getAttribute('aria-valuenow')) + step);
413
+ placeMark(db);
414
+ void call('setThreshold', mark, [db])();
415
+ });
416
+ pressSel.addEventListener('change', () => {
417
+ if (st) void call('setMic', pressSel, [{ hotkey: withTaps(splitTaps(st.input.hotkey).combo, Number(pressSel.value)) }])();
418
+ });
419
+
420
+ // The talk key is a new combination (key-capture.ts); how it is pressed (`*2`) stays as chosen beside it.
421
+ let capture: { stop(): void } | null = null;
422
+ const finishCapture = (combo: string | null) => {
423
+ capture = null;
424
+ keyBtn.textContent = t.changeKey;
425
+ if (combo && st) void call('setMic', keyBtn, [{ hotkey: withTaps(combo, splitTaps(st.input.hotkey).taps) }])();
426
+ else void refresh();
427
+ };
428
+ keyBtn.addEventListener('click', () => {
429
+ if (capture) { capture.stop(); return; }
430
+ keyRow.set('…', 'busy', t.capture);
431
+ keyBtn.textContent = t.cancelKey;
432
+ capture = captureKey(window, finishCapture);
433
+ });
434
+ ctx.own({ dispose: () => capture?.stop() });
435
+ ctx.stream({
436
+ message: (text: string) => {
437
+ const f = JSON.parse(text) as { type: string; level?: number; speaking?: boolean; open?: boolean };
438
+ if (f.type === 'level' && typeof f.level === 'number') {
439
+ fill.style.width = `${meterPct(f.level)}%`;
440
+ fill.classList.toggle('on', !!f.speaking);
441
+ meter.classList.toggle('open', !!f.open);
442
+ } else void refresh();
443
+ },
444
+ });
445
+ void refresh();
446
+ ctx.interval(() => void refresh(), 1500);
447
+ },
448
+ };
449
+
450
+ const bundle: WebUiClientBundle = { panels: { pet: petPanel, voice: voicePanel } };
451
+ export default bundle;
@@ -0,0 +1,14 @@
1
+ /* Pack details and choices; the modal shell comes from shared/ui/modal.css. */
2
+ .figure-dialog-lead{margin:0 0 14px;font-size:13px;line-height:1.6;white-space:pre-wrap;overflow-wrap:anywhere}
3
+ .figure-dialog-items{display:grid;gap:8px}
4
+ .figure-dialog-item{display:flex;align-items:flex-start;gap:10px;padding:10px;border:1px solid var(--line);border-radius:8px;min-width:0}
5
+ label.figure-dialog-item{cursor:pointer}
6
+ .figure-dialog-item>input{flex:none;margin:4px 0 0;accent-color:var(--accent)}
7
+ .figure-dialog-item>img{flex:none;width:52px;height:52px;object-fit:cover;border-radius:6px}
8
+ .figure-dialog-info{display:flex;flex-direction:column;gap:3px;min-width:0;overflow-wrap:anywhere}
9
+ .figure-dialog-info>b{font-size:14px}
10
+ .figure-dialog-meta{font-size:12px;color:var(--ink-dim,var(--muted));line-height:1.5}
11
+ .figure-dialog-meta p{margin:3px 0}
12
+ .figure-dialog-note{font-size:12px;color:var(--accent)}
13
+ .figure-dialog-warning{font-size:12px;color:var(--danger,var(--anger));margin:10px 0 0;overflow-wrap:anywhere;white-space:pre-wrap}
14
+ .figure-dialog-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:8px;margin-top:20px}
@@ -0,0 +1,117 @@
1
+ /** Figure import content inside the settings window's shared modal shell. */
2
+ import { openLayer, openModal, modalCard, type OverlayEnv, type Overlay } from './shared/modal.ts';
3
+ import './dress-dialog.css';
4
+
5
+ export interface DressDialogView {
6
+ title: string;
7
+ body?: string;
8
+ busy?: boolean;
9
+ selectable?: boolean;
10
+ items?: Array<{ key: string; label: string; image?: string; meta: string[]; notice?: string; details?: { title: string; lines: string[] } }>;
11
+ warnings?: string[];
12
+ actions: Array<{ key: string; label: string; kind?: 'primary' | 'danger'; selection?: boolean; file?: 'zip' | 'directory' }>;
13
+ }
14
+ export interface DressDialogAnswer {
15
+ action: string;
16
+ selected: string[];
17
+ files?: Array<{ path: string; file: File }>;
18
+ }
19
+
20
+ /** Only text and known form controls cross the frame boundary. */
21
+ export function isDressDialog(value: unknown): value is DressDialogView {
22
+ if (!value || typeof value !== 'object') return false;
23
+ const v = value as DressDialogView;
24
+ const strings = (xs: unknown): xs is string[] => Array.isArray(xs) && xs.every(x => typeof x === 'string');
25
+ return typeof v.title === 'string' && (v.body === undefined || typeof v.body === 'string')
26
+ && (v.busy === undefined || typeof v.busy === 'boolean')
27
+ && (v.selectable === undefined || typeof v.selectable === 'boolean')
28
+ && (v.warnings === undefined || strings(v.warnings)) && Array.isArray(v.actions)
29
+ && v.actions.every(a => a && typeof a.key === 'string' && typeof a.label === 'string'
30
+ && (a.selection === undefined || typeof a.selection === 'boolean')
31
+ && (a.kind === undefined || a.kind === 'primary' || a.kind === 'danger')
32
+ && (a.file === undefined || a.file === 'zip' || a.file === 'directory'))
33
+ && (v.items === undefined || Array.isArray(v.items) && v.items.every(i => i && typeof i.key === 'string'
34
+ && typeof i.label === 'string' && strings(i.meta) && (i.image === undefined || typeof i.image === 'string')
35
+ && (i.notice === undefined || typeof i.notice === 'string')
36
+ && (i.details === undefined || i.details && typeof i.details.title === 'string' && strings(i.details.lines))));
37
+ }
38
+
39
+ export function showDressDialog(env: OverlayEnv, view: DressDialogView, answer: (result: DressDialogAnswer) => void): Overlay {
40
+ let answered = false;
41
+ const closed = () => { if (!answered) answer({ action: 'cancel', selected: [] }); };
42
+ const layer = view.busy ? openLayer(env, env.doc.createElement('div'), closed) : openModal(env, closed);
43
+ if (view.busy) { layer.el.className = 'modal busy'; layer.el.setAttribute('role', 'dialog'); layer.el.setAttribute('aria-modal', 'true'); layer.el.setAttribute('aria-busy', 'true'); }
44
+ const { card, body } = modalCard(env, layer, view.title, !view.items?.length);
45
+ card.classList.add('figure-dialog');
46
+ const node = (tag: string, cls: string, text = '') => { const el = env.doc.createElement(tag); el.className = cls; el.textContent = text; return el; };
47
+ if (view.body) body.append(node('p', 'figure-dialog-lead', view.body));
48
+ const selected = new Set(view.selectable ? view.items?.map(i => i.key) : []);
49
+ const selectionButtons: HTMLButtonElement[] = [];
50
+ if (view.items?.length) {
51
+ const list = node('div', 'figure-dialog-items');
52
+ for (const item of view.items) {
53
+ const row = node(view.selectable ? 'label' : 'div', 'figure-dialog-item');
54
+ if (view.selectable) {
55
+ const box = env.doc.createElement('input'); box.type = 'checkbox'; box.checked = true; box.value = item.key;
56
+ box.addEventListener('change', () => { if (box.checked) selected.add(item.key); else selected.delete(item.key); for (const b of selectionButtons) b.disabled = selected.size === 0; }, { signal: layer.signal });
57
+ row.append(box);
58
+ }
59
+ if (item.image) {
60
+ const url = URL.canParse(item.image, env.doc.baseURI) ? new URL(item.image, env.doc.baseURI) : null;
61
+ if (url && ['http:', 'https:', 'data:', 'blob:'].includes(url.protocol)) { const img = env.doc.createElement('img'); img.src = url.href; img.alt = ''; row.append(img); }
62
+ }
63
+ const info = node('div', 'figure-dialog-info'); info.append(node('b', '', item.label));
64
+ for (const text of item.meta) info.append(node('span', 'figure-dialog-meta', text));
65
+ if (item.notice) info.append(node('span', 'figure-dialog-note', item.notice));
66
+ if (item.details) { const details = node('details', 'figure-dialog-meta'); details.append(node('summary', '', item.details.title)); for (const text of item.details.lines) details.append(node('p', '', text)); info.append(details); }
67
+ row.append(info); list.append(row);
68
+ }
69
+ body.append(list);
70
+ }
71
+ for (const text of view.warnings ?? []) body.append(node('p', 'figure-dialog-warning', text));
72
+ const finish = (action: string, files?: DressDialogAnswer['files']) => {
73
+ answered = true; layer.close(); answer({ action, selected: [...selected], ...(files ? { files } : {}) });
74
+ };
75
+ if (view.actions.length) {
76
+ const bar = node('div', 'figure-dialog-actions');
77
+ for (const action of view.actions) {
78
+ const btn = env.doc.createElement('button'); btn.type = 'button'; btn.className = `btn sm ${action.kind ?? ''}`; btn.textContent = action.label; btn.dataset.action = action.key;
79
+ if (action.selection) { selectionButtons.push(btn); btn.disabled = selected.size === 0; }
80
+ if (action.file) {
81
+ const input = env.doc.createElement('input'); input.type = 'file'; input.hidden = true;
82
+ if (action.file === 'zip') input.accept = '.zip,application/zip'; else input.setAttribute('webkitdirectory', '');
83
+ input.addEventListener('change', () => { const files = Array.from(input.files ?? []).map(file => ({ path: file.webkitRelativePath || file.name, file })); if (files.length) finish(action.key, files); }, { signal: layer.signal });
84
+ btn.addEventListener('click', () => input.click(), { signal: layer.signal }); bar.append(input);
85
+ } else btn.addEventListener('click', () => finish(action.key), { signal: layer.signal });
86
+ bar.append(btn);
87
+ }
88
+ body.append(bar); bar.querySelector<HTMLButtonElement>('button:not(:disabled)')?.focus();
89
+ }
90
+ return layer;
91
+ }
92
+
93
+ /**
94
+ * Shows the dialogs of the dressing page in `frame` (web/appearance.js `hostDressDialogs`) until `env.signal` aborts, and
95
+ * sends each answer back through `companion:dialog-action`. Messages count only from that frame at `frame.dataset.origin`.
96
+ */
97
+ export function hostFrameDressDialogs(env: OverlayEnv, frame: HTMLIFrameElement): void {
98
+ let dialog: Overlay | undefined;
99
+ env.doc.defaultView!.addEventListener('message', (e) => {
100
+ if (e.source !== frame.contentWindow || e.origin !== frame.dataset.origin) return;
101
+ if (e.data?.type === 'companion:dialog' && isDressDialog(e.data.view)) {
102
+ dialog?.close();
103
+ dialog = showDressDialog(env, e.data.view, (result) => {
104
+ frame.contentWindow?.postMessage({ type: 'companion:dialog-action', id: e.data.id, result }, e.origin);
105
+ });
106
+ } else if (e.data?.type === 'companion:dialog-close') { dialog?.close(); dialog = undefined; }
107
+ }, { signal: env.signal });
108
+ }
109
+
110
+ /** Standalone dressing pages use the same renderer as the embedding settings window. */
111
+ export function localDressDialogs(doc: Document, signal: AbortSignal) {
112
+ let current: Overlay | undefined;
113
+ return {
114
+ show(view: DressDialogView, answer: (result: DressDialogAnswer) => void) { current?.close(); if (signal.aborted) return; current = showDressDialog({ doc, host: doc.body, signal }, view, answer); },
115
+ close() { current?.close(); current = undefined; },
116
+ };
117
+ }