repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

add nuguland noko transcription

d09fa7e669d74e14df73900db1c89e17f2ba7c65

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (14)

Notes

Modified
1 -Subproject commit 54979e29cdb661f1845ee30916c04296d687dbf9
1 +Subproject commit bb91b3fdd57d9d1be71281dc5d06887594528167

niri/cfg/keybinds.kdl

Modified
11 11 Mod+Space hotkey-overlay-title="Nuguland: launcher" {
12 12 spawn "uwsm" "app" "-s" "session-graphical.slice" "--" "qs" "ipc" "-c" "nuguland" "call" "nuguland" "openLauncher"
14 + Mod+grave repeat=false allow-inhibiting=false hotkey-overlay-title="Nuguland: noko capture" {
15 + spawn "uwsm" "app" "-s" "session-graphical.slice" "--" "qs" "ipc" "-c" "nuguland" "call" "noko" "trigger"
16 + }
14 17 Mod+Shift+O hotkey-overlay-title="Nuguland: toggle bar orientation" {
15 18 spawn "uwsm" "app" "-s" "session-graphical.slice" "--" "qs" "ipc" "-c" "nuguland" "call" "nuguland" "setOrientation" "toggle"

quickshell/nuguland/Bar.qml

Modified
23 23 required property Power powerService
24 24 required property Idle idleService
25 25 required property Lock lockService
26 + required property Noko nokoService
26 27 required property SurfaceManager surfaces
27 28 required property Usage usageService
28 29 required property CalDav caldavService
39 40 return "launch";
40 41 case "media":
41 42 return "media";
43 + case "noko":
44 + return root.nokoService ? root.nokoService.label : "noko";
42 45 case "system":
43 46 return "system";
44 47 case "clipboard":
66 69 switch (String(name)) {
67 70 case "media":
68 71 return !!(root.mediaService && root.mediaService.playing);
72 + case "noko":
73 + return !!(root.nokoService && root.nokoService.active);
69 74 case "notifications":
70 75 return !!(root.notificationService && root.notificationService.unreadCount > 0);
71 76 case "tray":
81 86 // idle (keep-awake) is important enough to pop louder than a subtle dot
82 87 function chipActiveStrong(name) {
83 - return String(name) === "idle" && root.chipActive(name);
88 + const key = String(name);
89 + if (key === "noko")
90 + return !!(root.nokoService && root.nokoService.strong);
91 + return key === "idle" && root.chipActive(name);
92 + }
94 + function chipRole(name) {
95 + if (String(name) === "noko" && root.nokoService)
96 + return root.nokoService.role;
97 + return "ui.accent";
86 100 function itemRectInBar(item) {
406 420 bluetoothService: root.bluetoothService
407 421 powerService: root.powerService
408 422 lockService: root.lockService
423 + nokoService: root.nokoService
409 424 barWindow: root
724 739 readonly property bool selected: root.surfaces && root.surfaces.popoutName === popoutName
725 740 readonly property bool active: root.chipActive(popoutName)
726 741 readonly property bool activeStrong: root.chipActiveStrong(popoutName)
742 + readonly property bool nokoCapture: popoutName === "noko" && root.nokoService && (root.nokoService.listening || root.nokoService.transcribing)
743 + readonly property color roleColor: !root.theme ? "transparent" : (root.chipRole(popoutName) === "warning" ? root.theme.warning : root.theme.ui.accent)
728 745 Layout.preferredWidth: preferredWidth
729 746 Layout.preferredHeight: 26
730 747 Layout.alignment: Qt.AlignVCenter
731 748 radius: 9
732 - color: !root.theme ? "transparent" : (selected ? root.theme.ui.focus : (activeStrong && !selected ? root.theme.withAlpha(root.theme.ui.accent, 0.3) : root.theme.withAlpha(root.theme.ui.minor, 0.1)))
749 + color: !root.theme ? "transparent" : (selected ? root.theme.ui.focus : (activeStrong && !selected ? root.theme.withAlpha(chip.roleColor, 0.3) : root.theme.withAlpha(root.theme.ui.minor, 0.1)))
733 750 clip: true
734 751 border.width: chip.activeStrong && !chip.selected ? 1 : 0
735 - border.color: root.theme && chip.activeStrong ? root.theme.ui.accent : "transparent"
752 + border.color: root.theme && chip.activeStrong ? chip.roleColor : "transparent"
736 753 Component.onCompleted: Qt.callLater(() => {
737 754 return root.registerAnchor(chip.popoutName, chip);
753 770 font.bold: chip.activeStrong && !chip.selected
754 771 horizontalAlignment: Text.AlignHCenter
755 772 elide: Text.ElideRight
756 - color: !root.theme ? "transparent" : (chip.selected ? root.theme.content.backdrop : (chip.activeStrong ? root.theme.ui.accent : root.theme.content.normal))
773 + color: !root.theme ? "transparent" : (chip.selected ? root.theme.content.backdrop : (chip.activeStrong ? chip.roleColor : root.theme.content.normal))
760 777 Rectangle {
761 778 id: activeDot
763 - visible: chip.active && !chip.activeStrong && !chip.selected
780 + visible: chip.active && !chip.activeStrong && !chip.selected && !chip.nokoCapture
764 781 width: 5
765 782 height: 5
766 783 radius: 2.5
768 785 anchors.right: parent.right
769 786 anchors.topMargin: 4
770 787 anchors.rightMargin: 5
771 - color: root.theme ? root.theme.ui.accent : "white"
788 + color: root.theme ? chip.roleColor : "white"
772 789 opacity: 0.9
800 + Rectangle {
801 + visible: chip.nokoCapture
802 + anchors.horizontalCenter: parent.horizontalCenter
803 + anchors.bottom: parent.bottom
804 + anchors.bottomMargin: 3
805 + width: Math.max(16, parent.width * 0.42)
806 + height: 2
807 + radius: 1
808 + color: chip.roleColor
809 + opacity: 0.65
810 + z: 4
812 + SequentialAnimation on opacity {
813 + running: chip.nokoCapture && !(root.theme && root.theme.lowPowerMode)
814 + loops: Animation.Infinite
815 + NumberAnimation {
816 + to: 0.25
817 + duration: 520
818 + easing.type: Easing.InOutSine
820 + NumberAnimation {
821 + to: 0.78
822 + duration: 520
823 + easing.type: Easing.InOutSine
783 828 StateLayer {
784 829 theme: root.theme
785 830 cornerRadius: chip.radius

quickshell/nuguland/NOKO.md

Modified
37 37 - At 16 kHz, one frame is `480` samples.
38 38 - Output only speech samples to Parakeet.
40 -Handy-derived defaults:
40 +VAD defaults:
42 42 - threshold: `0.3`
43 43 - frame size: `30 ms`
133 133 - inference error/crash
134 134 - CPU instruction incompatibility
136 -## Main lesson from Handy
136 +## Main lesson
138 138 Parakeet should receive clean, normalized, speech-only 16 kHz mono audio. Resampling, VAD, smoothing, history, and output are app responsibilities outside Parakeet.
140 +## Noko-owned assets
142 +Noko does not depend on another app's model cache. By default it owns assets under `$NOKO_DATA_DIR`, or `$XDG_DATA_HOME/nuguland/noko`, or `~/.local/share/nuguland/noko`.
144 +Commands:
146 +```sh
147 +node noko.mjs assets-json
148 +node noko.mjs check-assets-json
149 +node noko.mjs install-assets
150 +node noko.mjs update-assets
151 +node noko.mjs install-assets-progress
152 +node noko.mjs update-assets-progress
153 +node noko.mjs transcribe-capture-json 5 history.jsonl
154 +node noko.mjs transcribe-raw-json capture.f32 history.jsonl
155 +```
157 +`check-assets-json` uses remote `HEAD` metadata and local file sizes to report whether VAD/model updates are available. `install-assets` installs/fetches missing files. `update-assets` redownloads model/VAD files from the configured source URLs. The `*-progress` variants emit NDJSON progress events for the popup progress bar.
159 +`install-assets` installs/fetches:
161 +- `onnxruntime-node` into `runtime/node_modules/`
162 +- Silero VAD ONNX into `vad/silero_vad.onnx`
163 +- Parakeet TDT int8 ONNX files into `parakeet-tdt-0.6b-v3-int8/`
165 +System runtime deps are checked by `doctor` and shown in setup:
167 +- `pw-record` for PipeWire mic capture
168 +- `wtype` for typing finished transcripts into the focused Wayland control
170 +During `install-assets`, Noko installs missing system deps through `pkexec` and the host package manager when a supported plan exists. This deliberately triggers Nuguland's Polkit prompt instead of hiding privilege escalation.
172 +`NOKO_VAD_ONNX` and `NOKO_PARAKEET_DIR` are overrides only.
174 +## Implementation status
176 +- `noko.js`: core audio normalization, 16 kHz resampling, 30 ms framing, VAD smoothing, postprocess, history records, injected Parakeet pipeline.
177 +- `noko.mjs`: CLI doctor, setup installer, real PipeWire capture to 16 kHz mono float JSON, raw indefinite capture transcription, real ONNX VAD probabilities, real VAD-gated speech JSON, one-command mic→VAD→Parakeet transcription, plus JSON fixture transcription path.
178 +- `noko-vad.mjs`: real Silero/equivalent ONNX VAD bridge; accepts 480-sample Noko frames and adapts to Silero state/context feeds.
179 +- `noko-parakeet.mjs`: Parakeet model-directory discovery, ONNX preprocessor→encoder→TDT decoder/joint inference, vocab decode, optional SentencePiece token decode, and serialized inference guard.
180 +- `noko.test.js`: unit, injected end-to-end, VAD bridge, asset-path, and model-directory tests.
181 +- `Noko.qml` + bar wiring: compact Nuguland status chip, automatic update checks, setup/update popup, system-runtime checks, toggle capture, capture waveform, focused-window text insertion via `wtype`, scrollable transcript history, and IPC.
183 +Verified end to end with:
185 +- real captured/fixture 16 kHz mono audio
186 +- temporary Silero VAD ONNX + `onnxruntime-node`
187 +- Noko-owned Parakeet TDT int8 model directory outside any other app cache
188 +- default `NOKO_DATA_DIR` asset resolution with no other-app path in `assets-json` or `doctor`
189 +- default Node `onnxruntime-node` Parakeet backend running preprocessor→encoder→TDT decoder/joint→vocab decode
190 +- output transcript `Hello world`
191 +- persisted history JSONL record
193 +Default `doctor` points at Noko-owned asset paths and reports missing runtime/assets until `install-assets` has populated them. `sentencepiece-js` is only required for model directories that use `tokenizer.model`; the verified Parakeet directory uses `vocab.txt`.
195 +Bar/popup widget states:
197 +- `checking`: transient after refresh
198 +- `blocked`: missing VAD, Parakeet assets, or runtime; chip label `noko!` with warning role
199 +- `installing`: setup is downloading runtime/models; warning strong chip
200 +- `ready`: all required local assets/runtime are readable; chip label `noko`
201 +- `listening`: indefinite capture is running; subtle animated accent line in the bar chip
202 +- `transcribing`: inference is running; subtle animated accent line in the bar chip
203 +- `error`: invalid doctor output or process failure; warning role
205 +Popup actions:
207 +- refresh doctor
208 +- automatically check setup updates
209 +- install/update setup with progress bar
210 +- start/stop toggle capture
211 +- show capture waveform and scrollable local transcript history
213 +Global trigger:
215 +- niri owns `Super+\`` because global compositor keybinds belong in `niri/cfg/keybinds.kdl`.
216 +- Nuguland owns what that trigger does through `qs ipc -c nuguland call noko trigger`.
217 +- Finished transcripts are typed into the focused Wayland control with `wtype -- <text>`.
218 +- Toggle mode is the only supported mode: first press starts capture, second press stops and transcribes.
219 +- Push-to-talk is intentionally unsupported because niri's normal keybind action does not provide key-release events.

quickshell/nuguland/Noko.qml

Added
new file mode 100644
1 +pragma ComponentBehavior: Bound
2 +import QtQuick
3 +import Quickshell
4 +import Quickshell.Io
6 +Item {
7 + id: root
9 + property string status: "checking"
10 + property string lastError: ""
11 + property string lastChecked: ""
12 + property string lastTranscript: ""
13 + property string lastDuration: ""
14 + property string lastInsertError: ""
15 + property var historyEntries: []
16 + property bool ready: false
17 + property bool listening: false
18 + property bool transcribing: false
19 + property bool finished: false
20 + property bool installing: false
21 + property real installProgress: 0
22 + property string installLabel: ""
23 + property bool checkingUpdates: false
24 + property bool updateAvailable: false
25 + property bool updateUnknown: false
26 + property string updateChecked: ""
27 + property var updateReport: ({})
28 + property var assets: ({})
29 + property var doctor: ({})
30 + readonly property bool blocked: status === "blocked" || status === "error"
31 + readonly property bool active: blocked || listening || transcribing || installing
32 + readonly property bool strong: blocked || installing
33 + readonly property string label: blocked ? "noko!" : "noko"
34 + readonly property string role: blocked || installing ? "warning" : (listening || transcribing || finished ? "ui.accent" : "ui.focus")
35 + readonly property string overlayState: listening ? "capturing" : (transcribing ? "transcribing" : (finished ? "finished" : ""))
36 + readonly property string cliPath: Qt.resolvedUrl("noko.mjs").toString().replace(/^file:\/\//, "")
37 + readonly property string historyPath: Quickshell.statePath("noko-history.jsonl")
38 + readonly property string capturePath: Quickshell.cachePath("noko-capture.f32")
40 + function refresh(): string {
41 + if (!installing && !listening && !transcribing)
42 + status = "checking";
43 + assetsProc.exec(["node", cliPath, "assets-json"]);
44 + doctorProc.exec(["node", cliPath, "doctor"]);
45 + return stateJson();
46 + }
48 + function checkUpdates(): string {
49 + checkingUpdates = true;
50 + updateUnknown = false;
51 + updateProc.exec(["node", cliPath, "check-assets-json"]);
52 + return stateJson();
53 + }
55 + function install(): string {
56 + installing = true;
57 + listening = false;
58 + transcribing = false;
59 + installProgress = 0;
60 + installLabel = "starting";
61 + status = "installing";
62 + installProc.exec(["node", cliPath, "install-assets-progress"]);
63 + return stateJson();
64 + }
66 + function update(): string {
67 + installing = true;
68 + listening = false;
69 + transcribing = false;
70 + installProgress = 0;
71 + installLabel = "updating";
72 + status = "installing";
73 + installProc.exec(["node", cliPath, "update-assets-progress"]);
74 + return stateJson();
75 + }
77 + function trigger(): string {
78 + if (listening)
79 + return stopCapture();
80 + return startCapture();
81 + }
83 + function startCapture(): string {
84 + if (!ready)
85 + return refresh();
86 + installing = false;
87 + listening = true;
88 + transcribing = false;
89 + finished = false;
90 + lastError = "";
91 + status = "listening";
92 + captureProc.exec(["sh", "-c", "exec pw-record --raw --rate 16000 --channels 1 --format f32 - > \"$1\"", "noko-capture", capturePath]);
93 + return stateJson();
94 + }
96 + function stopCapture(): string {
97 + if (!listening)
98 + return stateJson();
99 + listening = false;
100 + transcribing = true;
101 + finished = false;
102 + status = "transcribing";
103 + captureProc.signal(2);
104 + return stateJson();
107 + function transcribe(seconds): string {
108 + return trigger();
111 + function beginListening(): string {
112 + listening = true;
113 + transcribing = false;
114 + finished = false;
115 + status = "listening";
116 + return stateJson();
119 + function beginTranscribing(): string {
120 + listening = false;
121 + transcribing = true;
122 + finished = false;
123 + status = "transcribing";
124 + return stateJson();
127 + function finish(): string {
128 + listening = false;
129 + transcribing = false;
130 + finished = false;
131 + installing = false;
132 + refresh();
133 + return stateJson();
136 + function parseJson(text, fallback): var {
137 + try {
138 + return JSON.parse(String(text || "{}"));
139 + } catch (error) {
140 + lastError = fallback;
141 + status = "error";
142 + return null;
146 + function applyAssets(text): void {
147 + const report = parseJson(text, "assets-json");
148 + if (report)
149 + assets = report;
152 + function applyUpdateCheck(text): void {
153 + checkingUpdates = false;
154 + const report = parseJson(text, "update-check-json");
155 + if (!report)
156 + return;
157 + updateReport = report;
158 + updateAvailable = !!report.updateAvailable;
159 + updateUnknown = report.unknown && report.unknown.length > 0;
160 + updateChecked = report.checkedAt || new Date().toISOString();
163 + function applyDoctor(text): void {
164 + const report = parseJson(text, "doctor-json");
165 + if (!report)
166 + return;
167 + doctor = report;
168 + ready = !!report.ok;
169 + lastChecked = new Date().toISOString();
170 + if (ready) {
171 + lastError = "";
172 + if (!installing && !listening && !transcribing)
173 + status = "ready";
174 + if (!checkingUpdates && (!updateChecked || updateUnknown))
175 + checkUpdates();
176 + return;
178 + const missing = [];
179 + const systemMissing = report.missingSystemDependencies || [];
180 + for (let i = 0; i < systemMissing.length; i++)
181 + missing.push(String(systemMissing[i]));
182 + if (!report.vad || !report.vad.readable)
183 + missing.push("vad");
184 + if (!report.parakeet || !report.parakeet.ok)
185 + missing.push("parakeet");
186 + if (!report.runtime || !report.runtime.onnxruntimeNode)
187 + missing.push("onnxruntime");
188 + if (report.parakeet && report.parakeet.needsSentencePiece && (!report.runtime || !report.runtime.sentencepieceJs))
189 + missing.push("sentencepiece");
190 + lastError = missing.join(",") || "not-ready";
191 + if (!installing && !listening && !transcribing)
192 + status = "blocked";
195 + function applyInstallEvent(text): void {
196 + const event = parseJson(text, "install-progress");
197 + if (!event)
198 + return;
199 + if (event.label)
200 + installLabel = String(event.label);
201 + if (event.progress !== undefined)
202 + installProgress = Math.max(0, Math.min(1, Number(event.progress)));
203 + if (event.assets)
204 + assets = event.assets;
205 + if (event.event === "done") {
206 + installing = false;
207 + installProgress = 1;
208 + installLabel = "done";
209 + updateChecked = "";
210 + updateAvailable = false;
211 + updateUnknown = false;
212 + refresh();
216 + function loadHistoryText(text): void {
217 + const rows = [];
218 + const lines = String(text || "").trim().split("\n").filter(line => line.length > 0);
219 + for (let i = Math.max(0, lines.length - 20); i < lines.length; i++) {
220 + const row = parseJson(lines[i], "history-json");
221 + if (row && row.transcript)
222 + rows.unshift(row);
224 + historyEntries = rows;
225 + if (rows.length > 0) {
226 + lastTranscript = String(rows[0].transcript || "");
227 + lastDuration = rows[0].duration !== undefined ? `${rows[0].duration}s` : "";
231 + function applyTranscribe(text): void {
232 + listening = false;
233 + transcribing = false;
234 + const report = parseJson(text, "transcribe-json");
235 + if (!report)
236 + return;
237 + lastTranscript = String(report.text || "");
238 + lastDuration = report.history && report.history.duration !== undefined ? `${report.history.duration}s` : "";
239 + lastInsertError = "";
240 + if (lastTranscript.length > 0)
241 + insertProc.exec(["wtype", "--", lastTranscript]);
242 + if (report.history)
243 + historyEntries = [report.history].concat(historyEntries).slice(0, 20);
244 + status = "ready";
245 + finished = true;
246 + finishedTimer.restart();
247 + refresh();
250 + function fail(phase, text): void {
251 + installing = false;
252 + listening = false;
253 + transcribing = false;
254 + finished = false;
255 + ready = false;
256 + lastError = String(text || phase).trim() || phase;
257 + status = "error";
260 + function stateJson(): string {
261 + return JSON.stringify({
262 + "backend": "Noko.qml",
263 + "status": status,
264 + "ready": ready,
265 + "active": active,
266 + "strong": strong,
267 + "label": label,
268 + "role": role,
269 + "overlayState": overlayState,
270 + "lastError": lastError,
271 + "lastChecked": lastChecked,
272 + "lastTranscript": lastTranscript,
273 + "lastDuration": lastDuration,
274 + "lastInsertError": lastInsertError,
275 + "historyEntries": historyEntries,
276 + "capturePath": capturePath,
277 + "installing": installing,
278 + "installProgress": installProgress,
279 + "installLabel": installLabel,
280 + "checkingUpdates": checkingUpdates,
281 + "updateAvailable": updateAvailable,
282 + "updateUnknown": updateUnknown,
283 + "updateChecked": updateChecked,
284 + "historyPath": historyPath,
285 + "cliPath": cliPath,
286 + "assets": assets,
287 + "doctor": doctor
288 + });
291 + Component.onCompleted: refresh()
293 + FileView {
294 + id: historyFile
295 + path: root.historyPath
296 + blockWrites: true
297 + printErrors: false
298 + onLoaded: root.loadHistoryText(historyFile.text())
299 + onLoadFailed: root.historyEntries = []
302 + Timer {
303 + id: finishedTimer
305 + interval: 1400
306 + onTriggered: root.finished = false
309 + Timer {
310 + interval: 60000
311 + repeat: true
312 + running: true
313 + onTriggered: root.refresh()
316 + Process {
317 + id: assetsProc
318 + running: false
319 + stdout: StdioCollector {
320 + waitForEnd: true
321 + onStreamFinished: root.applyAssets(this.text)
323 + stderr: StdioCollector {
324 + waitForEnd: true
325 + onStreamFinished: {
326 + if (this.text.length > 0)
327 + root.fail("assets", this.text);
332 + Process {
333 + id: doctorProc
334 + running: false
335 + stdout: StdioCollector {
336 + waitForEnd: true
337 + onStreamFinished: root.applyDoctor(this.text)
339 + stderr: StdioCollector {
340 + waitForEnd: true
341 + onStreamFinished: {
342 + if (this.text.length > 0 && root.status === "checking")
343 + root.fail("doctor", this.text);
348 + Process {
349 + id: updateProc
350 + running: false
351 + stdout: StdioCollector {
352 + waitForEnd: true
353 + onStreamFinished: root.applyUpdateCheck(this.text)
355 + stderr: StdioCollector {
356 + waitForEnd: true
357 + onStreamFinished: {
358 + if (this.text.length > 0) {
359 + root.checkingUpdates = false;
360 + root.updateUnknown = true;
366 + Process {
367 + id: installProc
368 + running: false
369 + stdout: SplitParser {
370 + onRead: data => root.applyInstallEvent(data)
372 + stderr: StdioCollector {
373 + waitForEnd: true
374 + onStreamFinished: {
375 + if (this.text.length > 0)
376 + root.fail("install", this.text);
381 + Process {
382 + id: captureProc
383 + running: false
384 + onRunningChanged: {
385 + if (!running && root.status === "transcribing")
386 + transcribeProc.exec(["node", root.cliPath, "transcribe-raw-json", root.capturePath, root.historyPath]);
388 + stderr: StdioCollector {
389 + waitForEnd: true
390 + onStreamFinished: {
391 + if (this.text.length > 0 && root.listening)
392 + root.fail("capture", this.text);
397 + Process {
398 + id: insertProc
399 + running: false
400 + stderr: StdioCollector {
401 + waitForEnd: true
402 + onStreamFinished: root.lastInsertError = String(this.text || "").trim()
406 + Process {
407 + id: transcribeProc
408 + running: false
409 + stdout: StdioCollector {
410 + waitForEnd: true
411 + onStreamFinished: root.applyTranscribe(this.text)
413 + stderr: StdioCollector {
414 + waitForEnd: true
415 + onStreamFinished: {
416 + if (this.text.length > 0)
417 + root.fail("transcribe", this.text);

quickshell/nuguland/PopoutHost.qml

Modified
28 28 required property Bluetooth bluetoothService
29 29 required property Power powerService
30 30 required property Lock lockService
31 + required property Noko nokoService
31 32 required property var barWindow
32 33 readonly property var contentSize: surfaces ? surfaces.popoutContentSize(surfaces.popoutName) : ({
33 34 "width": 320,
79 80 return trayContent;
80 81 case "media":
81 82 return mediaContent;
83 + case "noko":
84 + return nokoContent;
82 85 case "clipboard":
83 86 return clipboardContent;
84 87 case "launcher":
1239 + Component {
1240 + id: nokoContent
1242 + NokoPanel {
1243 + theme: root.theme
1244 + panelState: root.nokoService
1236 1248 Component {
1237 1249 id: clipboardContent
2816 + component NokoPanel: Column {
2817 + id: root
2819 + required property Theme theme
2820 + required property Noko panelState
2821 + property int waveTick: 0
2822 + property int copiedIndex: -1
2824 + function roleColor(role) {
2825 + if (!theme)
2826 + return "transparent";
2827 + if (role === "warning")
2828 + return theme.warning;
2829 + if (role === "error")
2830 + return theme.error;
2831 + return theme.ui.accent;
2834 + function assetOk(name) {
2835 + const a = panelState && panelState.assets ? panelState.assets : ({});
2836 + if (name === "vad")
2837 + return !!(a.vad && a.vad.exists);
2838 + if (name === "model")
2839 + return !!(a.parakeet && a.parakeet.complete);
2840 + if (name === "runtime")
2841 + return !!(a.runtime && a.runtime.exists);
2842 + return false;
2845 + function toolOk(command) {
2846 + const deps = panelState && panelState.doctor && panelState.doctor.systemDependencies ? panelState.doctor.systemDependencies : [];
2847 + for (let i = 0; i < deps.length; i++)
2848 + if (deps[i].command === command)
2849 + return !!deps[i].exists;
2850 + return false;
2853 + function friendlyProblem() {
2854 + if (!panelState)
2855 + return "local speech status unknown";
2856 + if (panelState.listening)
2857 + return "capturing locally until toggled off";
2858 + if (panelState.transcribing)
2859 + return "transcribing locally";
2860 + if (panelState.installing)
2861 + return "downloading local runtime and speech models";
2862 + if (panelState.lastError.length === 0)
2863 + return "local speech ready";
2864 + return "setup required before recording";
2867 + function setupActionLabel() {
2868 + if (!panelState)
2869 + return "install setup";
2870 + if (panelState.installing)
2871 + return `${panelState.installLabel || "downloading"} ${Math.round(panelState.installProgress * 100)}%`;
2872 + if (panelState.ready && panelState.updateAvailable)
2873 + return "apply update";
2874 + return panelState.ready ? "" : "install setup";
2877 + function showSetupAction() {
2878 + return !!panelState && (panelState.installing || !panelState.ready || panelState.updateAvailable);
2881 + function updateAccent() {
2882 + if (!theme)
2883 + return "white";
2884 + if (!panelState || panelState.updateUnknown || panelState.updateAvailable)
2885 + return theme.warning;
2886 + if (panelState.checkingUpdates)
2887 + return theme.ui.accent;
2888 + return panelState.updateChecked ? theme.ui.accent : theme.ui.minor;
2891 + function waveLevel(index) {
2892 + if (!panelState || (!panelState.listening && !panelState.transcribing))
2893 + return 0.2 + (index % 3) * 0.08;
2894 + const phase = (waveTick + index * 5) / (panelState.transcribing ? 7 : 4);
2895 + return 0.24 + Math.abs(Math.sin(phase)) * (panelState.transcribing ? 0.42 : 0.7);
2898 + function updateLine() {
2899 + if (!panelState)
2900 + return "updates not checked";
2901 + if (panelState.checkingUpdates)
2902 + return "checking updates";
2903 + if (panelState.updateUnknown)
2904 + return "update check failed";
2905 + if (!panelState.updateChecked)
2906 + return "updates not checked";
2907 + return panelState.updateAvailable ? "update available" : "up to date";
2910 + width: parent ? parent.width : 0
2911 + height: parent ? parent.height : implicitHeight
2912 + spacing: 14
2913 + Component.onCompleted: if (panelState)
2914 + panelState.refresh()
2916 + Timer {
2917 + interval: 90
2918 + repeat: true
2919 + running: root.panelState && (root.panelState.listening || root.panelState.transcribing)
2920 + onTriggered: root.waveTick++
2923 + Timer {
2924 + id: copyFeedbackTimer
2926 + interval: 1200
2927 + onTriggered: root.copiedIndex = -1
2930 + Rectangle {
2931 + width: parent.width
2932 + height: 76
2933 + radius: 16
2934 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.09) : "transparent"
2936 + Rectangle {
2937 + width: 3
2938 + height: 42
2939 + radius: 2
2940 + anchors.left: parent.left
2941 + anchors.leftMargin: 12
2942 + anchors.top: parent.top
2943 + anchors.topMargin: 14
2944 + color: root.theme ? root.roleColor(root.panelState ? root.panelState.role : "warning") : "white"
2947 + Column {
2948 + anchors.fill: parent
2949 + anchors.leftMargin: 28
2950 + anchors.rightMargin: root.showSetupAction() ? 242 : 14
2951 + anchors.topMargin: 13
2952 + anchors.bottomMargin: 12
2953 + spacing: 7
2955 + Row {
2956 + width: parent.width
2957 + spacing: 8
2959 + NuguText {
2960 + theme: root.theme
2961 + variant: "title"
2962 + text: "noko"
2963 + color: root.theme ? root.theme.content.normal : "white"
2966 + NuguText {
2967 + theme: root.theme
2968 + variant: "meta"
2969 + text: root.panelState ? root.panelState.status : "unknown"
2970 + color: root.theme ? root.roleColor(root.panelState ? root.panelState.role : "warning") : "white"
2974 + NuguText {
2975 + theme: root.theme
2976 + width: parent.width
2977 + variant: "meta"
2978 + text: root.friendlyProblem()
2979 + color: root.theme ? root.theme.ui.minor : "white"
2983 + NokoButton {
2984 + visible: root.showSetupAction()
2985 + anchors.right: parent.right
2986 + anchors.rightMargin: 14
2987 + anchors.verticalCenter: parent.verticalCenter
2988 + theme: root.theme
2989 + label: root.setupActionLabel()
2990 + kind: "primary"
2991 + buttonWidth: 210
2992 + onClicked: if (root.panelState) {
2993 + if (root.panelState.ready)
2994 + root.panelState.update();
2995 + else
2996 + root.panelState.install();
3001 + Column {
3002 + width: parent.width
3003 + spacing: 7
3005 + Row {
3006 + width: parent.width
3007 + height: 24
3008 + spacing: 8
3010 + NuguText {
3011 + id: setupTitle
3013 + anchors.verticalCenter: parent.verticalCenter
3014 + theme: root.theme
3015 + variant: "title"
3016 + font.pixelSize: 13
3017 + text: "setup"
3018 + color: root.theme ? root.theme.ui.accent : "white"
3021 + Item {
3022 + width: Math.max(1, parent.width - setupTitle.implicitWidth - updateBadge.width - 8)
3023 + height: 1
3026 + Rectangle {
3027 + id: updateBadge
3029 + anchors.verticalCenter: parent.verticalCenter
3030 + width: 136
3031 + height: 24
3032 + radius: 10
3033 + color: root.theme ? root.theme.withAlpha(root.updateAccent(), 0.13) : "transparent"
3034 + border.width: root.panelState && root.panelState.updateAvailable ? 1 : 0
3035 + border.color: root.updateAccent()
3037 + Row {
3038 + anchors.centerIn: parent
3039 + spacing: 7
3041 + Rectangle {
3042 + anchors.verticalCenter: parent.verticalCenter
3043 + width: 6
3044 + height: 6
3045 + radius: 3
3046 + color: root.updateAccent()
3049 + NuguText {
3050 + anchors.verticalCenter: parent.verticalCenter
3051 + theme: root.theme
3052 + variant: "meta"
3053 + font.pixelSize: 12
3054 + text: root.updateLine()
3055 + color: root.updateAccent()
3061 + Rectangle {
3062 + width: parent.width
3063 + height: setupFlow.implicitHeight + 18 + (root.panelState && root.panelState.installing ? 25 : 0)
3064 + radius: 12
3065 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.07) : "transparent"
3067 + Column {
3068 + anchors.fill: parent
3069 + anchors.margins: 9
3070 + spacing: 6
3072 + Flow {
3073 + id: setupFlow
3075 + width: parent.width
3076 + spacing: 14
3078 + NokoAssetRow {
3079 + theme: root.theme
3080 + label: "voice detector"
3081 + ok: root.assetOk("vad")
3083 + NokoAssetRow {
3084 + theme: root.theme
3085 + label: "speech model"
3086 + ok: root.assetOk("model")
3088 + NokoAssetRow {
3089 + theme: root.theme
3090 + label: "local runtime"
3091 + ok: root.assetOk("runtime")
3093 + NokoAssetRow {
3094 + theme: root.theme
3095 + label: "mic capture"
3096 + ok: root.toolOk("pw-record")
3098 + NokoAssetRow {
3099 + theme: root.theme
3100 + label: "text insertion"
3101 + ok: root.toolOk("wtype")
3105 + Rectangle {
3106 + visible: root.panelState && root.panelState.installing
3107 + width: parent.width
3108 + height: 6
3109 + radius: 3
3110 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.22) : "transparent"
3112 + Rectangle {
3113 + width: parent.width * Math.max(0, Math.min(1, root.panelState ? root.panelState.installProgress : 0))
3114 + height: parent.height
3115 + radius: parent.radius
3116 + color: root.theme ? root.theme.ui.accent : "white"
3120 + NuguText {
3121 + visible: root.panelState && root.panelState.installing
3122 + theme: root.theme
3123 + variant: "meta"
3124 + font.pixelSize: 12
3125 + text: root.panelState ? root.panelState.installLabel : "downloading"
3126 + color: root.theme ? root.theme.ui.minor : "white"
3132 + Column {
3133 + width: parent.width
3134 + spacing: 7
3136 + NuguText {
3137 + theme: root.theme
3138 + variant: "title"
3139 + font.pixelSize: 13
3140 + text: "capture"
3141 + color: root.theme ? root.theme.ui.accent : "white"
3144 + Rectangle {
3145 + width: parent.width
3146 + height: 58
3147 + radius: 14
3148 + color: root.theme ? root.theme.withAlpha(root.panelState && root.panelState.listening ? root.theme.ui.accent : root.theme.ui.minor, root.panelState && root.panelState.listening ? 0.11 : 0.06) : "transparent"
3149 + border.width: root.panelState && root.panelState.listening ? 1 : 0
3150 + border.color: root.theme && root.panelState && root.panelState.listening ? root.theme.withAlpha(root.theme.ui.accent, 0.35) : "transparent"
3151 + clip: true
3153 + Row {
3154 + anchors.centerIn: parent
3155 + spacing: 5
3156 + height: 36
3158 + Repeater {
3159 + model: 31
3161 + Rectangle {
3162 + required property int index
3164 + anchors.verticalCenter: parent.verticalCenter
3165 + width: 4
3166 + height: Math.max(5, parent.height * root.waveLevel(index))
3167 + radius: 2
3168 + color: root.theme ? (root.panelState && root.panelState.listening ? root.theme.ui.accent : root.theme.ui.minor) : "white"
3169 + opacity: root.panelState && root.panelState.ready ? 0.86 : 0.3
3171 + Behavior on height {
3172 + NumberAnimation {
3173 + duration: root.theme && root.theme.lowPowerMode ? 0 : 120
3174 + easing.type: Easing.OutCubic
3182 + NokoButton {
3183 + theme: root.theme
3184 + label: root.panelState && root.panelState.listening ? "stop capture" : (root.panelState && root.panelState.transcribing ? "transcribing…" : "start capture")
3185 + kind: root.panelState && root.panelState.listening ? "primary" : "ghost"
3186 + enabled: root.panelState && root.panelState.ready && !root.panelState.transcribing
3187 + buttonWidth: parent.width
3188 + onClicked: if (root.panelState)
3189 + root.panelState.trigger()
3193 + Rectangle {
3194 + width: parent.width
3195 + height: Math.max(150, root.height - y)
3196 + radius: 14
3197 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.07) : "transparent"
3199 + Column {
3200 + anchors.fill: parent
3201 + anchors.margins: 12
3202 + spacing: 7
3204 + NuguText {
3205 + theme: root.theme
3206 + variant: "title"
3207 + font.pixelSize: 13
3208 + text: "last transcripts"
3209 + color: root.theme ? root.theme.ui.accent : "white"
3212 + Item {
3213 + width: parent.width
3214 + height: Math.max(1, parent.height - y)
3215 + clip: true
3217 + Flickable {
3218 + id: historyFlick
3220 + anchors.fill: parent
3221 + anchors.rightMargin: contentHeight > height ? 8 : 0
3222 + clip: true
3223 + contentWidth: width
3224 + contentHeight: historyColumn.implicitHeight
3225 + boundsBehavior: Flickable.StopAtBounds
3226 + interactive: contentHeight > height
3228 + Column {
3229 + id: historyColumn
3230 + width: historyFlick.width
3231 + spacing: 7
3233 + Repeater {
3234 + model: root.panelState ? root.panelState.historyEntries : []
3236 + delegate: Rectangle {
3237 + id: transcriptEntry
3239 + required property int index
3240 + required property var modelData
3241 + readonly property string transcript: String(modelData.transcript || "")
3242 + readonly property bool copied: root.copiedIndex === index
3244 + width: historyColumn.width
3245 + height: entryColumn.implicitHeight + 10
3246 + radius: 10
3247 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.06) : "transparent"
3249 + Column {
3250 + id: entryColumn
3252 + anchors.left: parent.left
3253 + anchors.right: copyButton.left
3254 + anchors.top: parent.top
3255 + anchors.margins: 8
3256 + spacing: 3
3258 + NuguText {
3259 + theme: root.theme
3260 + width: parent.width
3261 + wrapMode: Text.WordWrap
3262 + text: transcriptEntry.transcript
3263 + color: root.theme ? root.theme.content.normal : "white"
3266 + NuguText {
3267 + theme: root.theme
3268 + variant: "meta"
3269 + width: parent.width
3270 + text: transcriptEntry.modelData.duration !== undefined ? `${transcriptEntry.modelData.duration}s` : "local history"
3271 + color: root.theme ? root.theme.ui.minor : "white"
3275 + Rectangle {
3276 + id: copyButton
3278 + anchors.right: parent.right
3279 + anchors.top: parent.top
3280 + anchors.margins: 8
3281 + width: 44
3282 + height: 24
3283 + radius: 8
3284 + color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, transcriptEntry.copied ? 0.36 : (copyArea.containsMouse ? 0.22 : 0.12)) : "transparent"
3286 + NuguText {
3287 + anchors.centerIn: parent
3288 + theme: root.theme
3289 + variant: "meta"
3290 + font.pixelSize: 12
3291 + text: transcriptEntry.copied ? "copied" : "copy"
3292 + color: root.theme ? (transcriptEntry.copied ? root.theme.content.normal : root.theme.ui.accent) : "white"
3295 + MouseArea {
3296 + id: copyArea
3298 + anchors.fill: parent
3299 + hoverEnabled: true
3300 + cursorShape: Qt.PointingHandCursor
3301 + onClicked: if (transcriptEntry.transcript.length > 0) {
3302 + Quickshell.execDetached(["wl-copy", transcriptEntry.transcript]);
3303 + root.copiedIndex = transcriptEntry.index;
3304 + copyFeedbackTimer.restart();
3311 + NuguText {
3312 + visible: !root.panelState || root.panelState.historyEntries.length === 0
3313 + theme: root.theme
3314 + width: parent.width
3315 + text: "no captures yet"
3316 + color: root.theme ? root.theme.content.normal : "white"
3321 + Rectangle {
3322 + visible: historyFlick.contentHeight > historyFlick.height
3323 + anchors.top: parent.top
3324 + anchors.bottom: parent.bottom
3325 + anchors.right: parent.right
3326 + width: 3
3327 + radius: 2
3328 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.14) : "transparent"
3330 + Rectangle {
3331 + width: parent.width
3332 + height: Math.max(18, parent.height * historyFlick["visibleArea"]["heightRatio"])
3333 + y: Math.max(0, Math.min(parent.height - height, parent.height * historyFlick["visibleArea"]["yPosition"]))
3334 + radius: parent.radius
3335 + color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.55) : "white"
3343 + component NokoAssetRow: Row {
3344 + id: row
3346 + required property Theme theme
3347 + property string label: ""
3348 + property bool ok: false
3349 + property real rowWidth: 0
3351 + width: rowWidth > 0 ? rowWidth : implicitWidth
3352 + height: 14
3353 + spacing: 5
3355 + Rectangle {
3356 + width: 6
3357 + height: 6
3358 + radius: 3
3359 + anchors.verticalCenter: parent.verticalCenter
3360 + color: row.theme ? (row.ok ? row.theme.ui.accent : row.theme.warning) : "white"
3363 + NuguText {
3364 + id: labelText
3365 + anchors.verticalCenter: parent.verticalCenter
3366 + width: implicitWidth
3367 + height: parent.height
3368 + verticalAlignment: Text.AlignVCenter
3369 + theme: row.theme
3370 + variant: "meta"
3371 + font.pixelSize: 12
3372 + text: row.label
3373 + elide: Text.ElideRight
3374 + color: row.theme ? row.theme.content.normal : "white"
3377 + NuguText {
3378 + id: statusText
3379 + anchors.verticalCenter: parent.verticalCenter
3380 + height: parent.height
3381 + verticalAlignment: Text.AlignVCenter
3382 + theme: row.theme
3383 + variant: "meta"
3384 + font.pixelSize: 12
3385 + text: row.ok ? "· ok" : "· missing"
3386 + color: row.theme ? (row.ok ? row.theme.ui.accent : row.theme.warning) : "white"
3390 + component NokoButton: Rectangle {
3391 + id: btn
3393 + required property Theme theme
3394 + property string label: ""
3395 + property string kind: "ghost"
3396 + property real buttonWidth: 0
3397 + readonly property bool primary: kind === "primary"
3398 + signal clicked
3400 + width: buttonWidth > 0 ? buttonWidth : Math.max(1, parent ? (parent.width - 8) / 2 : 160)
3401 + height: 34
3402 + radius: 10
3403 + color: theme ? theme.withAlpha(primary ? theme.ui.accent : theme.ui.minor, enabled ? (primary ? 0.34 : 0.11) : 0.06) : "transparent"
3404 + border.width: 0
3405 + border.color: "transparent"
3406 + opacity: 1
3408 + NuguText {
3409 + anchors.centerIn: parent
3410 + width: parent.width
3411 + height: parent.height
3412 + horizontalAlignment: Text.AlignHCenter
3413 + verticalAlignment: Text.AlignVCenter
3414 + theme: btn.theme
3415 + variant: "meta"
3416 + text: btn.label
3417 + color: btn.theme ? (btn.enabled ? (btn.primary ? btn.theme.ui.accent : btn.theme.content.normal) : btn.theme.ui.normal) : "white"
3420 + MouseArea {
3421 + anchors.fill: parent
3422 + enabled: btn.enabled
3423 + hoverEnabled: true
3424 + cursorShape: Qt.PointingHandCursor
3425 + onClicked: btn.clicked()
2804 3429 component BrightnessPanel: Column {
2805 3430 id: root
3003 3628 refreshBluetooth(bluetoothService.deviceAction(kind, id));
3631 + function bluetoothDeviceIcon(type) {
3632 + const t = String(type || "");
3633 + if (t.indexOf("gaming") >= 0)
3634 + return "\uF11B";
3635 + if (t.indexOf("headset") >= 0 || t.indexOf("headphone") >= 0)
3636 + return "\uF025";
3637 + if (t.indexOf("card") >= 0 || t.indexOf("speaker") >= 0 || t.indexOf("audio") >= 0)
3638 + return "\uF028";
3639 + if (t.indexOf("keyboard") >= 0)
3640 + return "\uF11C";
3641 + return "\uF293";
3644 + function bluetoothBatteryLabel(device) {
3645 + return device && device.battery >= 0 ? "\uF240 " + device.battery + "%" : "󰂑";
3006 3648 function roleColor(role) {
3007 3649 if (!theme)
3008 3650 return "white";
3550 4192 width: parent.width
3551 4193 spacing: 6
4195 + Row {
4196 + id: bluetoothHeader
4198 + width: parent.width
4199 + height: 22
4200 + spacing: 6
4202 + Item {
4203 + width: 34
4204 + height: 1
4207 + NuguText {
4208 + theme: root.theme
4209 + variant: "meta"
4210 + text: "device"
4211 + width: bluetoothHeader.width - 34 - 78 - 84 - 96 - bluetoothHeader.spacing * 4
4212 + opacity: 0.75
4215 + NuguText {
4216 + theme: root.theme
4217 + variant: "meta"
4218 + text: "trust"
4219 + width: 78
4220 + horizontalAlignment: Text.AlignHCenter
4221 + opacity: 0.75
4224 + NuguText {
4225 + theme: root.theme
4226 + variant: "meta"
4227 + text: "state"
4228 + width: 84
4229 + horizontalAlignment: Text.AlignHCenter
4230 + opacity: 0.75
4233 + NuguText {
4234 + theme: root.theme
4235 + variant: "meta"
4236 + text: "battery"
4237 + width: 96
4238 + horizontalAlignment: Text.AlignRight
4239 + opacity: 0.75
4243 + Rectangle {
4244 + width: parent.width
4245 + height: 1
4246 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.24) : "transparent"
3553 4249 Repeater {
3554 4250 model: root.bluetoothState.devices || []
3559 4255 required property var modelData
3561 4257 width: root.width
3562 - height: 36
4258 + height: 42
3563 4259 radius: 10
3564 4260 color: root.theme ? root.theme.withAlpha(modelData.connected ? root.theme.ui.focus : root.theme.ui.minor, modelData.connected ? 0.24 : 0.1) : "transparent"
3565 - border.width: 0
4261 + border.width: modelData.connected ? 1 : 0
3566 4262 border.color: root.roleColor(modelData.blocked ? "error" : modelData.connected ? "ui.accent" : "ui.minor")
3568 - NuguText {
3569 - anchors.left: parent.left
3570 - anchors.leftMargin: 8
3571 - anchors.verticalCenter: parent.verticalCenter
3572 - theme: root.theme
3573 - text: deviceRow.modelData.name
3574 - width: parent.width - 136
3575 - elide: Text.ElideRight
4264 + Row {
4265 + id: deviceLine
3578 - NuguText {
3579 - objectName: "batteryBadges"
3580 - anchors.right: parent.right
4267 + anchors.fill: parent
4268 + anchors.leftMargin: 8
3581 4269 anchors.rightMargin: 8
3582 - anchors.verticalCenter: parent.verticalCenter
3583 - theme: root.theme
3584 - variant: "meta"
3585 - text: deviceRow.modelData.battery >= 0 ? `${deviceRow.modelData.battery}%` : "--"
4270 + spacing: 6
4272 + Text {
4273 + width: 26
4274 + anchors.verticalCenter: parent.verticalCenter
4275 + font.family: "Symbols Nerd Font Mono"
4276 + font.pixelSize: 17
4277 + color: root.roleColor(deviceRow.modelData.connected ? "ui.accent" : "ui.minor")
4278 + text: root.bluetoothDeviceIcon(deviceRow.modelData.type)
4279 + horizontalAlignment: Text.AlignHCenter
4282 + NuguText {
4283 + anchors.verticalCenter: parent.verticalCenter
4284 + theme: root.theme
4285 + text: deviceRow.modelData.name
4286 + width: deviceLine.width - 26 - 78 - 84 - 96 - deviceLine.spacing * 4
4287 + elide: Text.ElideRight
4290 + Rectangle {
4291 + width: 78
4292 + height: 23
4293 + anchors.verticalCenter: parent.verticalCenter
4294 + radius: 8
4295 + color: root.theme ? root.theme.withAlpha(deviceRow.modelData.trusted ? root.theme.ui.accent : root.theme.ui.minor, deviceRow.modelData.trusted ? 0.18 : 0.1) : "transparent"
4297 + NuguText {
4298 + anchors.centerIn: parent
4299 + theme: root.theme
4300 + variant: "meta"
4301 + text: deviceRow.modelData.trusted ? "✓ trusted" : "untrusted"
4302 + color: root.roleColor(deviceRow.modelData.trusted ? "ui.accent" : "ui.minor")
4306 + Rectangle {
4307 + width: 84
4308 + height: 23
4309 + anchors.verticalCenter: parent.verticalCenter
4310 + radius: 8
4311 + color: root.theme ? root.theme.withAlpha(deviceRow.modelData.connected ? root.theme.ui.accent : root.theme.ui.minor, deviceRow.modelData.connected ? 0.22 : 0.1) : "transparent"
4313 + NuguText {
4314 + anchors.centerIn: parent
4315 + theme: root.theme
4316 + variant: "meta"
4317 + text: deviceRow.modelData.connected ? "● linked" : "○ off"
4318 + color: root.roleColor(deviceRow.modelData.connected ? "ui.accent" : "ui.minor")
4322 + NuguText {
4323 + objectName: "batteryBadges"
4324 + anchors.verticalCenter: parent.verticalCenter
4325 + theme: root.theme
4326 + variant: "mono"
4327 + width: 96
4328 + horizontalAlignment: Text.AlignRight
4329 + font.family: "Symbols Nerd Font Mono"
4330 + color: root.roleColor(deviceRow.modelData.battery >= 0 ? "content.accent" : "ui.minor")
4331 + text: root.bluetoothBatteryLabel(deviceRow.modelData)
3588 4335 MouseArea {
4562 5309 refreshFrom(mediaService.select(id));
5312 + function actionIcon(kind) {
5313 + if (kind === "shuffle")
5314 + return "\uF074";
5315 + if (kind === "previous")
5316 + return "󰒮";
5317 + if (kind === "playPause")
5318 + return root.player.playbackState === "playing" ? "\uF04C" : "\uF04B";
5319 + if (kind === "next")
5320 + return "󰒭";
5321 + if (kind === "repeat")
5322 + return "\uF01E";
5323 + return "\uF001";
5326 + function actionActive(kind) {
5327 + return kind === "playPause" || kind === "shuffle" && root.player.shuffle || kind === "repeat" && root.player.repeat !== "none";
5330 + function actionLabel(kind) {
5331 + if (kind === "playPause")
5332 + return root.player.playbackState === "playing" ? "pause" : "play";
5333 + return kind;
5336 + function roleColor(role) {
5337 + if (!theme)
5338 + return "white";
5339 + if (role === "ui.minor")
5340 + return theme.ui.minor;
5341 + if (role === "content.accent")
5342 + return theme.content.accent;
5343 + return theme.ui.accent;
4565 5346 spacing: 10
4566 5347 width: parent ? parent.width : 0
5348 + height: parent ? parent.height : 360
4568 - Row {
4569 - width: parent.width
4570 - spacing: 12
5350 + Rectangle {
5351 + id: nowPlayingCard
5353 + objectName: "coverDetailsProgressTransport"
4571 5354 visible: root.hasMedia
5355 + width: parent.width
5356 + height: Math.max(300, root.height - (root.players.length > 1 ? 42 : 0))
5357 + radius: 18
5358 + color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.72) : "transparent"
5359 + border.width: 1
5360 + border.color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.22) : "transparent"
5361 + clip: true
5363 + Rectangle {
5364 + anchors.fill: parent
5365 + color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.05) : "transparent"
4573 5368 Rectangle {
4574 5369 id: coverCard
4576 - objectName: "coverDetailsProgressTransport"
4577 - width: 96
4578 - height: 96
4579 - radius: 18
4580 - color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.24) : "transparent"
4581 - border.width: 0
4582 - border.color: root.theme ? root.theme.ui.accent : "transparent"
5371 + anchors.left: parent.left
5372 + anchors.top: parent.top
5373 + anchors.margins: 22
5374 + width: 178
5375 + height: 178
5376 + radius: 22
5377 + color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.2) : "transparent"
5378 + border.width: 1
5379 + border.color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.35) : "transparent"
4583 5380 clip: true
4585 - NuguText {
5382 + Image {
5383 + id: coverArt
5385 + anchors.fill: parent
5386 + visible: root.player.artAvailable && status === Image.Ready
5387 + source: root.player.cover || ""
5388 + fillMode: Image.PreserveAspectCrop
5389 + asynchronous: true
5392 + Text {
4586 5393 anchors.centerIn: parent
4587 - theme: root.theme
4588 - variant: "title"
4589 - selected: true
4590 - text: root.player.playbackState === "playing" ? "▶" : "Ⅱ"
5394 + visible: !coverArt.visible
5395 + font.family: "Symbols Nerd Font Mono"
5396 + font.pixelSize: 54
5397 + color: root.theme ? root.theme.ui.accent : "white"
5398 + text: "\uF001"
5399 + opacity: 0.9
4593 5402 Rectangle {
4594 5403 anchors.left: parent.left
4595 5404 anchors.right: parent.right
4596 5405 anchors.bottom: parent.bottom
4597 - height: 5
5406 + height: 7
4598 5407 color: root.theme ? root.theme.ui.accent : "transparent"
4599 5408 opacity: root.player.playbackState === "playing" ? 1 : 0.35
4603 5412 Column {
4604 - width: parent.width - coverCard.width - parent.spacing
4605 - spacing: 7
5413 + anchors.left: coverCard.right
5414 + anchors.leftMargin: 24
5415 + anchors.right: parent.right
5416 + anchors.rightMargin: 24
5417 + anchors.top: parent.top
5418 + anchors.topMargin: 28
5419 + spacing: 8
5421 + Row {
5422 + width: parent.width
5423 + spacing: 8
5425 + Rectangle {
5426 + width: stateText.implicitWidth + 18
5427 + height: 24
5428 + radius: 12
5429 + color: root.theme ? root.theme.withAlpha(root.player.playbackState === "playing" ? root.theme.ui.accent : root.theme.ui.minor, 0.18) : "transparent"
5431 + NuguText {
5432 + id: stateText
5434 + anchors.centerIn: parent
5435 + theme: root.theme
5436 + variant: "meta"
5437 + text: root.player.playbackState === "playing" ? "● now playing" : root.player.playbackState
5438 + color: root.roleColor(root.player.playbackState === "playing" ? "ui.accent" : "ui.minor")
5442 + NuguText {
5443 + theme: root.theme
5444 + variant: "meta"
5445 + text: root.player.identity || "mpris"
5446 + width: parent.width - stateText.implicitWidth - 28
5447 + opacity: 0.6
5448 + elide: Text.ElideRight
4607 5452 NuguText {
4608 5453 theme: root.theme
4609 5454 variant: "title"
4610 5455 text: root.player.title || root.player.identity || "Untitled"
4611 5456 width: parent.width
5457 + font.pixelSize: 24
4612 5458 elide: Text.ElideRight
4615 5461 NuguText {
4616 5462 theme: root.theme
4617 - text: root.player.artist || ""
4618 - visible: text.length > 0
5463 + text: root.player.artist || "unknown artist"
4619 5464 width: parent.width
5465 + font.pixelSize: 16
5466 + opacity: root.player.artist ? 0.9 : 0.45
4620 5467 elide: Text.ElideRight
4626 5473 text: root.player.album || ""
4627 5474 visible: text.length > 0
4628 5475 width: parent.width
5476 + opacity: 0.62
4629 5477 elide: Text.ElideRight
4632 - Row {
4633 - width: parent.width
4634 - spacing: 6
5481 + Item {
5482 + id: progressBlock
4636 - NuguText {
4637 - theme: root.theme
4638 - variant: "meta"
4639 - text: root.mmss(root.player.position)
4640 - width: 34
5484 + anchors.left: parent.left
5485 + anchors.right: parent.right
5486 + anchors.leftMargin: 24
5487 + anchors.rightMargin: 24
5488 + anchors.bottom: transportRow.top
5489 + anchors.bottomMargin: 22
5490 + height: 38
5492 + NuguText {
5493 + anchors.left: parent.left
5494 + anchors.top: parent.top
5495 + theme: root.theme
5496 + variant: "mono"
5497 + text: root.mmss(root.player.position)
5498 + opacity: 0.72
5501 + NuguText {
5502 + anchors.right: parent.right
5503 + anchors.top: parent.top
5504 + theme: root.theme
5505 + variant: "mono"
5506 + text: root.mmss(root.player.length)
5507 + opacity: 0.72
5510 + Rectangle {
5511 + id: progressRail
5513 + objectName: "mpris-progress"
5514 + anchors.left: parent.left
5515 + anchors.right: parent.right
5516 + anchors.bottom: parent.bottom
5517 + height: 12
5518 + radius: 6
5519 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.24) : "transparent"
5521 + Rectangle {
5522 + anchors.left: parent.left
5523 + anchors.top: parent.top
5524 + anchors.bottom: parent.bottom
5525 + width: Math.round(parent.width * Math.max(0, Math.min(1, Number(root.player.progress || 0))))
5526 + radius: parent.radius
5527 + color: root.theme ? root.theme.ui.accent : "white"
4643 5530 Rectangle {
4644 - id: progressRail
5531 + width: 16
5532 + height: 16
5533 + radius: 8
5534 + anchors.verticalCenter: parent.verticalCenter
5535 + x: Math.max(0, Math.min(parent.width - width, Math.round(parent.width * Math.max(0, Math.min(1, Number(root.player.progress || 0)))) - width / 2))
5536 + color: root.theme ? root.theme.content.normal : "white"
5537 + border.width: 3
5538 + border.color: root.theme ? root.theme.ui.accent : "white"
4646 - objectName: "mpris-progress"
4647 - width: Math.max(1, parent.width - 76)
4648 - height: 10
4649 - radius: 5
4650 - color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.28) : "transparent"
4651 - border.width: 0
4652 - border.color: root.theme ? root.theme.ui.minor : "transparent"
5541 + MouseArea {
5542 + anchors.fill: parent
5543 + cursorShape: Qt.PointingHandCursor
5544 + onClicked: event => root.seekByRatio(event.x / Math.max(1, width))
4654 - Rectangle {
4655 - anchors.left: parent.left
4656 - anchors.top: parent.top
4657 - anchors.bottom: parent.bottom
4658 - width: Math.round(parent.width * Math.max(0, Math.min(1, Number(root.player.progress || 0))))
4659 - radius: parent.radius
4660 - color: root.theme ? root.theme.ui.accent : "white"
5549 + Row {
5550 + id: transportRow
5552 + objectName: "transportActions"
5553 + anchors.horizontalCenter: parent.horizontalCenter
5554 + anchors.bottom: parent.bottom
5555 + anchors.bottomMargin: 22
5556 + spacing: 12
5558 + Repeater {
5559 + model: root.transportActions
5561 + delegate: Rectangle {
5562 + id: transportButton
5564 + required property string modelData
5565 + readonly property bool primary: modelData === "playPause"
5566 + readonly property bool active: root.actionActive(modelData)
5568 + width: primary ? 64 : 46
5569 + height: primary ? 64 : 46
5570 + radius: width / 2
5571 + anchors.verticalCenter: parent.verticalCenter
5572 + color: root.theme ? root.theme.withAlpha(active ? root.theme.ui.focus : root.theme.ui.minor, primary ? 0.34 : (active ? 0.24 : 0.12)) : "transparent"
5573 + border.width: active ? 1 : 0
5574 + border.color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, 0.65) : "transparent"
5576 + Text {
5577 + anchors.centerIn: parent
5578 + font.family: "Symbols Nerd Font Mono"
5579 + font.pixelSize: transportButton.primary ? 25 : 19
5580 + text: root.actionIcon(transportButton.modelData)
5581 + color: root.roleColor(transportButton.active ? "ui.accent" : "content.accent")
4663 5584 MouseArea {
4664 5585 anchors.fill: parent
4665 - onClicked: event => {
4666 - return root.seekByRatio(event.x / Math.max(1, width));
4671 - NuguText {
4672 - theme: root.theme
4673 - variant: "meta"
4674 - text: root.mmss(root.player.length)
4675 - width: 34
4679 - Row {
4680 - objectName: "transportActions"
4681 - width: parent.width
4682 - spacing: 6
4684 - Repeater {
4685 - model: root.transportActions
4687 - delegate: Rectangle {
4688 - id: transportButton
4690 - required property string modelData
4692 - width: modelData === "playPause" ? 58 : 38
4693 - height: 28
4694 - radius: 10
4695 - color: root.theme ? root.theme.withAlpha(modelData === "playPause" ? root.theme.ui.focus : root.theme.ui.accent, 0.2) : "transparent"
4696 - border.width: 0
4697 - border.color: root.theme ? root.theme.ui.accent : "transparent"
4699 - NuguText {
4700 - anchors.centerIn: parent
4701 - theme: root.theme
4702 - variant: "meta"
4703 - selected: transportButton.modelData === "playPause"
4704 - text: transportButton.modelData === "playPause" ? (root.player.playbackState === "playing" ? "pause" : "play") : transportButton.modelData
4707 - MouseArea {
4708 - anchors.fill: parent
4709 - onClicked: root.runAction(transportButton.modelData)
5586 + cursorShape: Qt.PointingHandCursor
5587 + onClicked: root.runAction(transportButton.modelData)

quickshell/nuguland/SurfaceManager.qml

Modified
91 91 "width": width,
92 92 "height": heightBudget(420)
94 + case "noko":
95 + return {
96 + "width": width,
97 + "height": heightBudget(560)
98 + };
94 99 case "clipboard":
95 100 return {
96 101 "width": width,
208 213 "source": "Media.qml",
209 214 "visual": ["active-player", "transport", "progress", "selection"]
216 + "noko": {
217 + "component": "speech-transcription",
218 + "source": "Noko.qml noko.mjs",
219 + "visual": ["doctor", "setup", "record", "history"]
220 + },
211 221 "clipboard": {
212 222 "component": "clipboard-history",
213 223 "source": "Clipboard.qml",

quickshell/nuguland/Usage.qml

Modified
13 13 // Canonical widget set; array order is the tie-break for equal counts.
14 14 // "clock" is intentionally absent: it is pinned at a constant bar-center
15 15 // position by Bar.qml, so it must never drift in the usage-sorted order.
16 - readonly property var widgets: ["launcher", "media", "system", "clipboard", "audio", "brightness", "connectivity", "power", "notifications", "tray", "idle"]
16 + readonly property var widgets: ["launcher", "media", "noko", "system", "clipboard", "audio", "brightness", "connectivity", "power", "notifications", "tray", "idle"]
18 18 // Snapshotted once at load (see FileView.onLoaded); the bar binds to this.
19 19 property var layoutOrder: widgets

quickshell/nuguland/noko-parakeet.mjs

Added
new file mode 100644
1 +// noko-parakeet.mjs — Parakeet ONNX model-directory runtime.
3 +import { createRequire } from 'node:module';
4 +import { existsSync, readFileSync, readdirSync } from 'node:fs';
5 +import { join } from 'node:path';
6 +import { loadOnnxRuntime } from './noko-vad.mjs';
8 +const require = createRequire(import.meta.url);
9 +const DEFAULT_MAX_TOKENS_PER_STEP = 10;
11 +export function loadSentencePiece() {
12 + try {
13 + return require('sentencepiece-js');
14 + } catch (error) {
15 + throw new Error(`tokenizer runtime unavailable: sentencepiece-js (${error.message})`);
16 + }
19 +function walk(dir, prefix = '') {
20 + if (!dir || !existsSync(dir)) return [];
21 + const out = [];
22 + for (const entry of readdirSync(dir, { withFileTypes: true })) {
23 + if (entry.name.startsWith('._')) continue;
24 + const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
25 + const abs = join(dir, entry.name);
26 + if (entry.isDirectory()) out.push(...walk(abs, rel));
27 + else out.push({ rel, abs });
28 + }
29 + return out;
32 +function pick(files, tests) {
33 + return files.find(file => tests.some(test => test.test(file.rel.toLowerCase()))) || null;
36 +export function discoverParakeetDir(dir) {
37 + const files = walk(dir);
38 + const found = {
39 + preprocessor: pick(files, [/preprocessor.*\.onnx$/, /nemo\d+.*\.onnx$/]),
40 + encoder: pick(files, [/encoder.*\.onnx$/]),
41 + decoderJoint: pick(files, [/(decoder|joint).*\.onnx$/]),
42 + tokenizer: pick(files, [/tokenizer\.model$/, /vocab.*\.(txt|json)$/])
43 + };
44 + const missing = [];
45 + if (!found.preprocessor) missing.push('preprocessor');
46 + if (!found.encoder) missing.push('encoder');
47 + if (!found.decoderJoint) missing.push('decoder-or-joint');
48 + if (!found.tokenizer) missing.push('vocabulary-or-tokenizer');
49 + return {
50 + path: dir || '',
51 + ok: missing.length === 0,
52 + missing,
53 + files: Object.fromEntries(Object.entries(found).map(([key, value]) => [key, value ? value.rel : '']))
54 + };
57 +export async function loadTokenizer(path, runtime) {
58 + const sp = runtime || loadSentencePiece();
59 + const processor = new sp.SentencePieceProcessor();
60 + await processor.load(path);
61 + return processor;
64 +export function decodeTokens(tokenizer, tokens) {
65 + if (!tokenizer || typeof tokenizer.decodeIds !== 'function') throw new Error('sentencepiece tokenizer missing');
66 + return tokenizer.decodeIds((tokens || []).map(Number));
69 +function loadVocabulary(path) {
70 + const vocab = new Map();
71 + for (const line of readFileSync(path, 'utf8').split(/\r?\n/)) {
72 + if (!line) continue;
73 + const split = line.lastIndexOf(' ');
74 + if (split <= 0) continue;
75 + vocab.set(Number(line.slice(split + 1)), line.slice(0, split).replaceAll('▁', ' '));
76 + }
77 + const blank = Array.from(vocab.entries()).find(([, token]) => token === '<blk>');
78 + return {
79 + type: 'vocab',
80 + vocab,
81 + size: vocab.size,
82 + blankIdx: blank ? blank[0] : Math.max(...vocab.keys()),
83 + decodeIds(ids) {
84 + const text = ids.map(id => vocab.get(id) || '').join('');
85 + return text.replace(/^\s|\s\B|(\s)\b/g, (_match, keep) => keep ? ' ' : '');
86 + }
87 + };
90 +async function loadDecoder(path, options) {
91 + if (path.toLowerCase().endsWith('.model')) {
92 + const tokenizer = await loadTokenizer(path, options.sentencepiece);
93 + return {
94 + type: 'sentencepiece',
95 + size: null,
96 + blankIdx: null,
97 + decodeIds: ids => decodeTokens(tokenizer, ids)
98 + };
99 + }
100 + return loadVocabulary(path);
103 +function first(record, names) {
104 + for (const name of names) if (record[name] !== undefined) return record[name];
105 + return Object.values(record)[0];
108 +function tensorData(tensor) {
109 + return tensor && tensor.data !== undefined ? tensor.data : tensor;
112 +function numericDim(value, fallback) {
113 + return typeof value === 'number' && value > 0 ? value : fallback;
116 +function argmax(data, start = 0, end = data.length) {
117 + let best = start;
118 + for (let i = start + 1; i < end; i++) if (data[i] > data[best]) best = i;
119 + return best - start;
122 +export class ParakeetOnnx {
123 + constructor(ort, sessions, model, decoder, options = {}) {
124 + this.ort = ort;
125 + this.sessions = sessions;
126 + this.model = model;
127 + this.decoder = decoder;
128 + this.maxTokensPerStep = Number(options.maxTokensPerStep || DEFAULT_MAX_TOKENS_PER_STEP);
129 + this.busy = false;
130 + this.state = 'ready';
133 + static async create(dir, options = {}) {
134 + const model = discoverParakeetDir(dir);
135 + if (!model.ok) throw new Error(`parakeet model dir incomplete: ${model.missing.join(', ')}`);
136 + const ort = options.ort || await loadOnnxRuntime();
137 + const sessionOptions = { executionProviders: options.executionProviders || ['cpu'] };
138 + const sessions = {
139 + preprocessor: await ort.InferenceSession.create(join(dir, model.files.preprocessor), sessionOptions),
140 + encoder: await ort.InferenceSession.create(join(dir, model.files.encoder), sessionOptions),
141 + decoderJoint: await ort.InferenceSession.create(join(dir, model.files.decoderJoint), sessionOptions)
142 + };
143 + const decoder = await loadDecoder(join(dir, model.files.tokenizer), options);
144 + return new ParakeetOnnx(ort, sessions, model, decoder, options);
147 + async preprocess(samples) {
148 + const output = await this.sessions.preprocessor.run({
149 + waveforms: new this.ort.Tensor('float32', samples, [1, samples.length]),
150 + waveforms_lens: new this.ort.Tensor('int64', BigInt64Array.from([BigInt(samples.length)]), [1])
151 + });
152 + return {
153 + features: first(output, ['features']),
154 + lengths: first(output, ['features_lens'])
155 + };
158 + async encode(features, lengths) {
159 + const output = await this.sessions.encoder.run({
160 + audio_signal: features,
161 + length: lengths
162 + });
163 + return {
164 + encoded: first(output, ['outputs']),
165 + lengths: first(output, ['encoded_lengths'])
166 + };
169 + createDecoderState() {
170 + const inputs = Object.fromEntries((this.sessions.decoderJoint.inputNames || []).map(name => [name, null]));
171 + const metadata = Object.fromEntries((this.sessions.decoderJoint.inputMetadata || []).map(input => [input.name, input]));
172 + const shape1 = metadata.input_states_1 ? metadata.input_states_1.shape : [2, 1, 640];
173 + const shape2 = metadata.input_states_2 ? metadata.input_states_2.shape : [2, 1, 640];
174 + void inputs;
175 + return {
176 + state1: new Float32Array(numericDim(shape1[0], 2) * 1 * numericDim(shape1[2], 640)),
177 + state2: new Float32Array(numericDim(shape2[0], 2) * 1 * numericDim(shape2[2], 640)),
178 + state1Shape: [numericDim(shape1[0], 2), 1, numericDim(shape1[2], 640)],
179 + state2Shape: [numericDim(shape2[0], 2), 1, numericDim(shape2[2], 640)]
180 + };
183 + async decodeFrame(prevTokens, state, frame) {
184 + const previous = prevTokens.length ? prevTokens[prevTokens.length - 1] : this.decoder.blankIdx;
185 + const output = await this.sessions.decoderJoint.run({
186 + encoder_outputs: new this.ort.Tensor('float32', frame, [1, frame.length, 1]),
187 + targets: new this.ort.Tensor('int32', Int32Array.from([previous]), [1, 1]),
188 + target_length: new this.ort.Tensor('int32', Int32Array.from([1]), [1]),
189 + input_states_1: new this.ort.Tensor('float32', state.state1, state.state1Shape),
190 + input_states_2: new this.ort.Tensor('float32', state.state2, state.state2Shape)
191 + });
192 + const logits = tensorData(first(output, ['outputs']));
193 + return {
194 + logits,
195 + step: argmax(logits, this.decoder.size, logits.length),
196 + state: {
197 + state1: new Float32Array(tensorData(first(output, ['output_states_1']))),
198 + state2: new Float32Array(tensorData(first(output, ['output_states_2']))),
199 + state1Shape: state.state1Shape,
200 + state2Shape: state.state2Shape
202 + };
205 + async transcribe(samples) {
206 + if (this.busy) throw new Error('parakeet inference already running');
207 + if (!samples || samples.length === 0) throw new Error('empty speech buffer');
208 + this.busy = true;
209 + this.state = 'transcribing';
210 + try {
211 + const { features, lengths } = await this.preprocess(samples instanceof Float32Array ? samples : new Float32Array(samples));
212 + const { encoded, lengths: encodedLengths } = await this.encode(features, lengths);
213 + const encodedData = tensorData(encoded);
214 + const dims = encoded.dims || encoded.dimensions;
215 + const channels = Number(dims[1]);
216 + const frames = Number(dims[2]);
217 + const limit = Math.min(frames, Number(tensorData(encodedLengths)[0]));
218 + const state = this.createDecoderState();
219 + let currentState = state;
220 + const tokens = [];
221 + let emittedTokens = 0;
222 + for (let t = 0; t < limit;) {
223 + const frame = new Float32Array(channels);
224 + for (let c = 0; c < channels; c++) frame[c] = encodedData[c * frames + t];
225 + const decoded = await this.decodeFrame(tokens, currentState, frame);
226 + const token = argmax(decoded.logits, 0, this.decoder.size);
227 + if (token !== this.decoder.blankIdx) {
228 + currentState = decoded.state;
229 + tokens.push(token);
230 + emittedTokens++;
232 + if (decoded.step > 0) {
233 + t += decoded.step;
234 + emittedTokens = 0;
235 + } else if (token === this.decoder.blankIdx || emittedTokens === this.maxTokensPerStep) {
236 + t++;
237 + emittedTokens = 0;
240 + return {
241 + text: this.decoder.decodeIds(tokens),
242 + meta: {
243 + model: 'parakeet-onnx',
244 + quantization: this.model.files.encoder.includes('int8') ? 'int8' : 'unknown',
245 + runtimeProvider: 'onnxruntime-node'
247 + };
248 + } finally {
249 + this.busy = false;
250 + this.state = 'ready';

quickshell/nuguland/noko-vad.mjs

Added
new file mode 100644
1 +// noko-vad.mjs — real ONNX VAD runtime bridge for Noko.
2 +// Loads Silero/equivalent ONNX through onnxruntime-node when available.
4 +import { createRequire } from 'node:module';
5 +import { existsSync } from 'node:fs';
7 +const require = createRequire(import.meta.url);
8 +const SILERO_CHUNK_16K = 512;
9 +const SILERO_CONTEXT_16K = 64;
10 +const SILERO_STATE_SIZE = 128;
12 +function dataDir() {
13 + if (process.env.NOKO_DATA_DIR) return process.env.NOKO_DATA_DIR;
14 + const root = process.env.XDG_DATA_HOME || `${process.env.HOME || '.'}/.local/share`;
15 + return `${root}/nuguland/noko`;
18 +function runtimeModulePath() {
19 + return process.env.NOKO_ONNXRUNTIME_NODE || `${dataDir()}/runtime/node_modules/onnxruntime-node`;
22 +export async function loadOnnxRuntime() {
23 + try {
24 + return require('onnxruntime-node');
25 + } catch (requireError) {
26 + try {
27 + return await import('onnxruntime-node');
28 + } catch (importError) {
29 + try {
30 + return require(runtimeModulePath());
31 + } catch (localError) {
32 + throw new Error(`runtime provider unavailable: onnxruntime-node (${requireError.message}; ${importError.message}; ${localError.message})`);
33 + }
34 + }
35 + }
38 +function tensorValue(tensor) {
39 + if (!tensor) return null;
40 + if (tensor.data !== undefined) return tensor.data;
41 + return tensor;
44 +function scalar(value) {
45 + const data = tensorValue(value);
46 + if (ArrayBuffer.isView(data) || Array.isArray(data)) return Number(data[0] || 0);
47 + return Number(data || 0);
50 +function firstPresent(record, names) {
51 + for (const name of names) if (record && record[name] !== undefined) return record[name];
52 + return null;
55 +export async function vadRuntimeReport(modelPath, options = {}) {
56 + const report = {
57 + path: modelPath || '',
58 + loadable: false,
59 + inputNames: [],
60 + outputNames: [],
61 + stateful: false,
62 + srInput: false,
63 + frameSamples: 480,
64 + smokeProbability: null,
65 + error: ''
66 + };
67 + try {
68 + const vad = await OnnxVad.create(modelPath, options);
69 + report.loadable = true;
70 + report.inputNames = vad.session.inputNames || [];
71 + report.outputNames = vad.session.outputNames || [];
72 + report.stateful = report.inputNames.indexOf('state') >= 0;
73 + report.srInput = report.inputNames.indexOf('sr') >= 0;
74 + if (options.smoke !== false)
75 + report.smokeProbability = await vad.probability(new Float32Array(vad.frameSamples));
76 + } catch (error) {
77 + report.error = String(error && error.message ? error.message : error);
78 + }
79 + return report;
82 +export class OnnxVad {
83 + constructor(ort, session, options = {}) {
84 + if (!ort || !ort.Tensor) throw new Error('onnxruntime Tensor constructor missing');
85 + if (!session || typeof session.run !== 'function') throw new Error('onnxruntime session missing');
86 + this.ort = ort;
87 + this.session = session;
88 + this.sampleRate = Number(options.sampleRate || 16000);
89 + this.frameSamples = Number(options.frameSamples || 480);
90 + this.state = new Float32Array(2 * SILERO_STATE_SIZE);
91 + this.context = new Float32Array(SILERO_CONTEXT_16K);
92 + this.inputNames = session.inputNames || ['input'];
93 + }
95 + static async create(modelPath, options = {}) {
96 + if (!modelPath || !existsSync(modelPath)) throw new Error(`vad model missing: ${modelPath || '(unset)'}`);
97 + const ort = options.ort || await loadOnnxRuntime();
98 + const session = options.session || await ort.InferenceSession.create(modelPath, {
99 + executionProviders: options.executionProviders || ['cpu']
100 + });
101 + return new OnnxVad(ort, session, options);
104 + reset() {
105 + this.state.fill(0);
106 + this.context.fill(0);
109 + sileroInput(frame) {
110 + const out = new Float32Array(SILERO_CONTEXT_16K + SILERO_CHUNK_16K);
111 + out.set(this.context, 0);
112 + out.set(frame.slice(0, this.frameSamples), SILERO_CONTEXT_16K);
113 + this.context = out.slice(out.length - SILERO_CONTEXT_16K);
114 + return out;
117 + feeds(frame) {
118 + if (!frame || frame.length !== this.frameSamples) throw new Error(`vad frame must be exactly ${this.frameSamples} samples`);
119 + const hasState = this.inputNames.indexOf('state') >= 0;
120 + const input = hasState ? this.sileroInput(frame) : new Float32Array(frame);
121 + const feeds = {
122 + input: new this.ort.Tensor('float32', input, [1, input.length])
123 + };
124 + if (hasState) feeds.state = new this.ort.Tensor('float32', this.state, [2, 1, SILERO_STATE_SIZE]);
125 + if (this.inputNames.indexOf('sr') >= 0) feeds.sr = new this.ort.Tensor('int64', BigInt64Array.from([BigInt(this.sampleRate)]), []);
126 + return feeds;
129 + async probability(frame) {
130 + const output = await this.session.run(this.feeds(frame));
131 + const nextState = firstPresent(output, ['stateN', 'state', 'hn', 'h']);
132 + if (nextState) this.state = new Float32Array(tensorValue(nextState));
133 + return scalar(firstPresent(output, ['output', 'prob', 'speech_probs']) || Object.values(output)[0]);
137 +export async function vadProbabilities(samples, options = {}) {
138 + const vad = options.vad || await OnnxVad.create(options.modelPath || process.env.NOKO_VAD_ONNX || '', options);
139 + const frameSamples = options.frameSamples || 480;
140 + const out = [];
141 + for (let offset = 0; offset + frameSamples <= samples.length; offset += frameSamples) {
142 + out.push(await vad.probability(samples.slice(offset, offset + frameSamples)));
144 + return out;

quickshell/nuguland/noko.js

Added
new file mode 100644
1 +// noko.js — pure Noko speech-to-text pipeline helpers.
2 +// NO I/O, NO native audio, NO ONNX imports. Receives samples + injected VAD/engine.
3 +// Dual-mode: node `require` (tests) + QML import.
5 +var TARGET_RATE = 16000;
6 +var FRAME_MS = 30;
7 +var FRAME_SAMPLES = 480;
9 +function finiteNumber(value, fallback) {
10 + var n = Number(value);
11 + return isFinite(n) ? n : fallback;
14 +function assertPositiveInt(value, name) {
15 + var n = Number(value);
16 + if (!Number.isInteger(n) || n <= 0) throw new Error(name + " must be a positive integer");
17 + return n;
20 +function interleavedToMonoFloat32(samples, channels) {
21 + var ch = assertPositiveInt(channels || 1, "channels");
22 + var input = samples || [];
23 + var frames = Math.floor(input.length / ch);
24 + var out = new Float32Array(frames);
25 + for (var i = 0; i < frames; i++) {
26 + var sum = 0;
27 + for (var c = 0; c < ch; c++) sum += finiteNumber(input[i * ch + c], 0);
28 + out[i] = Math.max(-1, Math.min(1, sum / ch));
29 + }
30 + return out;
33 +function pcm16leToMonoFloat32(buffer, channels) {
34 + var ch = assertPositiveInt(channels || 1, "channels");
35 + var bytes = buffer || [];
36 + if (bytes.length % 2 !== 0) throw new Error("pcm16le byte length must be even");
37 + var sampleCount = Math.floor(bytes.length / 2);
38 + var tmp = new Float32Array(sampleCount);
39 + for (var i = 0; i < sampleCount; i++) {
40 + var lo = bytes[i * 2];
41 + var hi = bytes[i * 2 + 1];
42 + var v = (hi << 8) | lo;
43 + if (v & 0x8000) v -= 0x10000;
44 + tmp[i] = Math.max(-1, Math.min(1, v / 32768));
45 + }
46 + return interleavedToMonoFloat32(tmp, ch);
49 +function float32leToFloat32(buffer, channels) {
50 + var ch = assertPositiveInt(channels || 1, "channels");
51 + var bytes = buffer || [];
52 + if (bytes.length % 4 !== 0) throw new Error("float32le byte length must be divisible by 4");
53 + var sampleCount = Math.floor(bytes.length / 4);
54 + var tmp = new Float32Array(sampleCount);
55 + for (var i = 0; i < sampleCount; i++) {
56 + var value = typeof bytes.readFloatLE === "function" ? bytes.readFloatLE(i * 4) : new DataView(bytes.buffer, bytes.byteOffset || 0, bytes.byteLength || bytes.length).getFloat32(i * 4, true);
57 + tmp[i] = Math.max(-1, Math.min(1, finiteNumber(value, 0)));
58 + }
59 + return interleavedToMonoFloat32(tmp, ch);
62 +function resampleLinear(samples, fromRate, toRate) {
63 + var srcRate = assertPositiveInt(fromRate, "fromRate");
64 + var dstRate = assertPositiveInt(toRate || TARGET_RATE, "toRate");
65 + var input = samples || [];
66 + if (input.length === 0 || srcRate === dstRate) return new Float32Array(input);
67 + if (input.length === 1) return new Float32Array([finiteNumber(input[0], 0)]);
68 + var outLen = Math.max(1, Math.round(input.length * dstRate / srcRate));
69 + var out = new Float32Array(outLen);
70 + var scale = (input.length - 1) / Math.max(1, outLen - 1);
71 + for (var i = 0; i < outLen; i++) {
72 + var pos = i * scale;
73 + var left = Math.floor(pos);
74 + var right = Math.min(input.length - 1, left + 1);
75 + var frac = pos - left;
76 + out[i] = finiteNumber(input[left], 0) * (1 - frac) + finiteNumber(input[right], 0) * frac;
77 + }
78 + return out;
81 +function splitFrames(samples, frameSamples) {
82 + var size = assertPositiveInt(frameSamples || FRAME_SAMPLES, "frameSamples");
83 + var input = samples || [];
84 + var count = Math.floor(input.length / size);
85 + var out = [];
86 + for (var i = 0; i < count; i++) out.push(new Float32Array(Array.prototype.slice.call(input, i * size, (i + 1) * size)));
87 + return out;
90 +function concatFrames(frames) {
91 + var list = frames || [];
92 + var total = 0;
93 + for (var i = 0; i < list.length; i++) total += list[i].length;
94 + var out = new Float32Array(total);
95 + var offset = 0;
96 + for (var j = 0; j < list.length; j++) {
97 + out.set(list[j], offset);
98 + offset += list[j].length;
99 + }
100 + return out;
103 +function vadGate(frames, probabilities, options) {
104 + var opts = options || {};
105 + var threshold = finiteNumber(opts.threshold, 0.3);
106 + var preRollLimit = assertPositiveInt(opts.preRoll === undefined ? 15 : opts.preRoll + 1, "preRoll") - 1;
107 + var onsetLimit = assertPositiveInt(opts.onset || 2, "onset");
108 + var hangoverLimit = assertPositiveInt(opts.hangover === undefined ? 15 : opts.hangover + 1, "hangover") - 1;
109 + var list = frames || [];
110 + var probs = probabilities || [];
111 + var out = [];
112 + var kept = [];
113 + var pre = [];
114 + var onset = [];
115 + var inSpeech = false;
116 + var hangover = 0;
117 + for (var i = 0; i < list.length; i++) {
118 + var speech = finiteNumber(probs[i], 0) >= threshold;
119 + if (inSpeech) {
120 + if (speech) {
121 + out.push(list[i]);
122 + kept.push(i);
123 + hangover = hangoverLimit;
124 + } else if (hangover > 0) {
125 + out.push(list[i]);
126 + kept.push(i);
127 + hangover--;
128 + } else {
129 + inSpeech = false;
130 + pre = [list[i]];
131 + onset = [];
133 + continue;
135 + if (speech) {
136 + onset.push({ frame: list[i], index: i });
137 + if (onset.length >= onsetLimit) {
138 + for (var p = 0; p < pre.length; p++) out.push(pre[p].frame);
139 + for (var pi = 0; pi < pre.length; pi++) kept.push(pre[pi].index);
140 + for (var o = 0; o < onset.length; o++) out.push(onset[o].frame);
141 + for (var oi = 0; oi < onset.length; oi++) kept.push(onset[oi].index);
142 + inSpeech = true;
143 + hangover = hangoverLimit;
144 + pre = [];
145 + onset = [];
147 + } else {
148 + onset = [];
149 + pre.push({ frame: list[i], index: i });
150 + if (pre.length > preRollLimit) pre.shift();
153 + return {
154 + samples: concatFrames(out),
155 + frameIndexes: kept,
156 + speechFrameCount: out.length
157 + };
160 +function postprocess(text, junkTokens) {
161 + var out = String(text || "");
162 + var junk = junkTokens || [];
163 + for (var i = 0; i < junk.length; i++) out = out.split(String(junk[i])).join(" ");
164 + return out.replace(/\s+/g, " ").trim();
167 +function validateParakeetModelFiles(names) {
168 + var files = (names || []).map(function (n) { return String(n).toLowerCase(); });
169 + function has(part) {
170 + for (var i = 0; i < files.length; i++) if (files[i].indexOf(part) >= 0) return true;
171 + return false;
173 + var missing = [];
174 + if (!has("preprocessor") && !has("nemo")) missing.push("preprocessor");
175 + if (!has("encoder")) missing.push("encoder");
176 + if (!has("decoder") && !has("joint")) missing.push("decoder-or-joint");
177 + if (!has("vocab") && !has("token") && !has("model_config")) missing.push("vocabulary-or-tokenizer");
178 + return { ok: missing.length === 0, missing: missing };
181 +function EngineState() {
182 + this.state = "unloaded";
183 + this.error = "";
186 +EngineState.prototype.set = function (next, error) {
187 + this.state = String(next);
188 + this.error = String(error || "");
189 + return this.state;
192 +function historyRecord(transcript, speechSamples, meta) {
193 + var info = meta || {};
194 + return {
195 + timestamp: info.timestamp || new Date().toISOString(),
196 + transcript: String(transcript || ""),
197 + sampleCount: speechSamples ? speechSamples.length : 0,
198 + duration: speechSamples ? Math.round(speechSamples.length / TARGET_RATE * 1000) / 1000 : 0,
199 + model: info.model || "parakeet",
200 + quantization: info.quantization || "unknown",
201 + runtimeProvider: info.runtimeProvider || "unknown",
202 + audioPath: info.audioPath || "",
203 + error: info.error || ""
204 + };
207 +function transcribePipeline(input, vad, engine, history, options) {
208 + var opts = options || {};
209 + var state = opts.state || new EngineState();
210 + if (!input || !input.samples) throw new Error("no input samples");
211 + if (!vad || typeof vad.probability !== "function") throw new Error("vad probability function missing");
212 + if (!engine || typeof engine.transcribe !== "function") throw new Error("parakeet engine missing");
213 + state.set("transcribing");
214 + try {
215 + var mono = interleavedToMonoFloat32(input.samples, input.channels || 1);
216 + var resampled = resampleLinear(mono, input.sampleRate || TARGET_RATE, TARGET_RATE);
217 + var frameList = splitFrames(resampled, FRAME_SAMPLES);
218 + var probabilities = [];
219 + for (var i = 0; i < frameList.length; i++) probabilities.push(Number(vad.probability(frameList[i], i)) || 0);
220 + var gated = vadGate(frameList, probabilities, opts.vad || {});
221 + if (gated.samples.length === 0) throw new Error("empty speech buffer after vad");
222 + var raw = engine.transcribe(gated.samples, { sampleRate: TARGET_RATE });
223 + var text = postprocess(raw && raw.text !== undefined ? raw.text : raw, opts.junkTokens || []);
224 + if (!text) throw new Error("empty transcript");
225 + var record = historyRecord(text, gated.samples, Object.assign({}, opts.history || {}, raw && raw.meta ? raw.meta : {}));
226 + if (history && typeof history.write === "function") history.write(record);
227 + state.set("ready");
228 + return {
229 + text: text,
230 + sampleRate: TARGET_RATE,
231 + speechSamples: gated.samples,
232 + frameIndexes: gated.frameIndexes,
233 + history: record,
234 + state: state.state
235 + };
236 + } catch (error) {
237 + state.set("failed", String(error && error.message ? error.message : error));
238 + throw error;
242 +if (typeof module !== 'undefined' && module.exports) {
243 + module.exports = {
244 + TARGET_RATE: TARGET_RATE,
245 + FRAME_MS: FRAME_MS,
246 + FRAME_SAMPLES: FRAME_SAMPLES,
247 + interleavedToMonoFloat32: interleavedToMonoFloat32,
248 + pcm16leToMonoFloat32: pcm16leToMonoFloat32,
249 + float32leToFloat32: float32leToFloat32,
250 + resampleLinear: resampleLinear,
251 + splitFrames: splitFrames,
252 + concatFrames: concatFrames,
253 + vadGate: vadGate,
254 + postprocess: postprocess,
255 + validateParakeetModelFiles: validateParakeetModelFiles,
256 + EngineState: EngineState,
257 + historyRecord: historyRecord,
258 + transcribePipeline: transcribePipeline
259 + };

quickshell/nuguland/noko.mjs

Added
new file mode 100644
1 +#!/usr/bin/env node
2 +import { createRequire } from 'node:module';
3 +import { appendFileSync, createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
4 +import { access, constants } from 'node:fs/promises';
5 +import { spawnSync } from 'node:child_process';
6 +import { Readable } from 'node:stream';
7 +import { discoverParakeetDir, loadSentencePiece, ParakeetOnnx } from './noko-parakeet.mjs';
8 +import { loadOnnxRuntime, OnnxVad, vadProbabilities, vadRuntimeReport } from './noko-vad.mjs';
10 +const require = createRequire(import.meta.url);
11 +const Noko = require('./noko.js');
13 +function usage() {
14 + return `usage:
15 + node noko.mjs doctor
16 + node noko.mjs system-deps-json
17 + node noko.mjs assets-json
18 + node noko.mjs check-assets-json
19 + node noko.mjs install-assets
20 + node noko.mjs update-assets
21 + node noko.mjs install-assets-progress
22 + node noko.mjs update-assets-progress
23 + node noko.mjs capture-json seconds output.json [device]
24 + node noko.mjs vad-json input.json output.json
25 + node noko.mjs vad-gate-json input.json output.json
26 + node noko.mjs transcribe-real-json input.json history.jsonl
27 + node noko.mjs transcribe-raw-json input.f32 history.jsonl
28 + node noko.mjs transcribe-capture-json seconds history.jsonl [device]
29 + node noko.mjs transcribe-json input.json history.jsonl
31 +env:
32 + NOKO_DATA_DIR Noko-owned asset root, defaults to XDG data dir
33 + NOKO_VAD_ONNX override path to Silero/equivalent VAD ONNX
34 + NOKO_PARAKEET_DIR override Parakeet model directory
35 + NOKO_NO_SYSTEM_INSTALL=1 skips package-manager install during setup
36 +`;
39 +function commandExists(name) {
40 + const result = spawnSync('sh', ['-c', `command -v ${JSON.stringify(name)} >/dev/null 2>&1`]);
41 + return result.status === 0;
44 +const SYSTEM_DEPENDENCIES = [
45 + {
46 + command: 'pw-record',
47 + label: 'mic capture',
48 + required: true,
49 + packages: {
50 + arch: 'pipewire',
51 + fedora: 'pipewire-utils',
52 + debian: 'pipewire-bin'
53 + }
54 + },
55 + {
56 + command: 'wtype',
57 + label: 'text insertion',
58 + required: true,
59 + packages: {
60 + arch: 'wtype',
61 + fedora: 'wtype',
62 + debian: 'wtype'
63 + }
64 + }
65 +];
67 +function systemDependencyReport() {
68 + return SYSTEM_DEPENDENCIES.map(dep => Object.assign({}, dep, {
69 + exists: commandExists(dep.command)
70 + }));
73 +function missingSystemDependencies(report = systemDependencyReport()) {
74 + return report.filter(dep => dep.required && !dep.exists).map(dep => dep.command);
77 +function osIdLike() {
78 + try {
79 + const text = readFileSync('/etc/os-release', 'utf8');
80 + const ids = [];
81 + for (const key of ['ID', 'ID_LIKE']) {
82 + const match = text.match(new RegExp(`^${key}=(.*)$`, 'm'));
83 + if (match) ids.push(...match[1].replace(/^"|"$/g, '').split(/\s+/));
84 + }
85 + return ids;
86 + } catch (_error) {
87 + return [];
88 + }
91 +function packageFamily() {
92 + const ids = osIdLike();
93 + if (ids.includes('arch') || commandExists('pacman')) return 'arch';
94 + if (ids.includes('fedora') || ids.includes('rhel') || commandExists('dnf')) return 'fedora';
95 + if (ids.includes('debian') || ids.includes('ubuntu') || commandExists('apt-get')) return 'debian';
96 + return '';
99 +function unique(values) {
100 + return Array.from(new Set(values.filter(Boolean)));
103 +function systemInstallCommand(report = systemDependencyReport()) {
104 + const missing = report.filter(dep => dep.required && !dep.exists);
105 + if (missing.length === 0) return [];
106 + const family = packageFamily();
107 + const packages = unique(missing.map(dep => dep.packages && dep.packages[family]));
108 + if (packages.length === 0) return [];
109 + if (family === 'arch') return ['pkexec', 'pacman', '-S', '--needed', '--noconfirm', ...packages];
110 + if (family === 'fedora') return ['pkexec', 'dnf', 'install', '-y', ...packages];
111 + if (family === 'debian') return ['pkexec', 'apt-get', 'install', '-y', ...packages];
112 + return [];
115 +function systemDependencyStatus() {
116 + const dependencies = systemDependencyReport();
117 + return {
118 + dependencies,
119 + missing: missingSystemDependencies(dependencies),
120 + installCommand: systemInstallCommand(dependencies),
121 + packageFamily: packageFamily(),
122 + canInstall: systemInstallCommand(dependencies).length > 0 && commandExists('pkexec')
123 + };
126 +function installSystemDependencies(options = {}) {
127 + const status = systemDependencyStatus();
128 + emitProgress(options.emit, { event: 'system-deps-start', label: 'system tools', progress: 0.01, missing: status.missing });
129 + if (status.missing.length === 0 || process.env.NOKO_NO_SYSTEM_INSTALL === '1') {
130 + emitProgress(options.emit, { event: 'system-deps-done', label: 'system tools', progress: 0.08, skipped: true, missing: status.missing });
131 + return Object.assign({ skipped: true }, status);
133 + if (!status.canInstall) throw new Error(`missing system tools: ${status.missing.join(', ')}; no supported pkexec install command`);
134 + const result = spawnSync(status.installCommand[0], status.installCommand.slice(1), {
135 + encoding: 'utf8',
136 + maxBuffer: 1024 * 1024 * 4
137 + });
138 + if (result.status !== 0) throw new Error(`system tool install failed: ${(result.stderr || result.stdout || '').trim()}`);
139 + const after = systemDependencyStatus();
140 + if (after.missing.length > 0) throw new Error(`system tools still missing: ${after.missing.join(', ')}`);
141 + emitProgress(options.emit, { event: 'system-deps-done', label: 'system tools', progress: 0.08, skipped: false });
142 + return Object.assign({ skipped: false }, after);
145 +function dataDir() {
146 + if (process.env.NOKO_DATA_DIR) return process.env.NOKO_DATA_DIR;
147 + const root = process.env.XDG_DATA_HOME || `${process.env.HOME || '.'}/.local/share`;
148 + return `${root}/nuguland/noko`;
151 +const PARAKEET_REPO = process.env.NOKO_PARAKEET_REPO || 'https://huggingface.co/smcleod/parakeet-tdt-0.6b-v3-int8/resolve/main';
152 +const ASSET_FILES = {
153 + vad: {
154 + file: 'silero_vad.onnx',
155 + url: process.env.NOKO_VAD_URL || 'https://github.com/snakers4/silero-vad/raw/master/src/silero_vad/data/silero_vad.onnx'
156 + },
157 + parakeet: {
158 + dir: 'parakeet-tdt-0.6b-v3-int8',
159 + files: {
160 + config: { file: 'config.json', url: `${PARAKEET_REPO}/config.json` },
161 + preprocessor: { file: 'nemo128.onnx', url: `${PARAKEET_REPO}/nemo128.onnx` },
162 + encoder: { file: 'encoder-model.int8.onnx', url: `${PARAKEET_REPO}/encoder-model.int8.onnx` },
163 + decoderJoint: { file: 'decoder_joint-model.int8.onnx', url: `${PARAKEET_REPO}/decoder_joint-model.int8.onnx` },
164 + vocab: { file: 'vocab.txt', url: `${PARAKEET_REPO}/vocab.txt` }
169 +function defaultVadPath() {
170 + return `${dataDir()}/vad/${ASSET_FILES.vad.file}`;
173 +function defaultParakeetDir() {
174 + return `${dataDir()}/${ASSET_FILES.parakeet.dir}`;
177 +function runtimeDir() {
178 + return `${dataDir()}/runtime`;
181 +function runtimeModulePath() {
182 + return `${runtimeDir()}/node_modules/onnxruntime-node`;
185 +function resolvedVadPath() {
186 + return process.env.NOKO_VAD_ONNX || defaultVadPath();
189 +function resolvedParakeetDir() {
190 + return process.env.NOKO_PARAKEET_DIR || defaultParakeetDir();
193 +function fileStatus(path) {
194 + try {
195 + const stat = statSync(path);
196 + return { path, exists: true, size: stat.size };
197 + } catch (_error) {
198 + return { path, exists: false, size: 0 };
202 +function assetFiles(report = null) {
203 + const current = report || assetReport();
204 + return [{ key: 'vad', url: current.vad.url, path: current.vad.path }]
205 + .concat(Object.entries(current.parakeet.files).map(([key, value]) => Object.assign({ key }, value)));
208 +function assetReport() {
209 + const root = dataDir();
210 + const parakeetPath = resolvedParakeetDir();
211 + const parakeetFiles = Object.fromEntries(Object.entries(ASSET_FILES.parakeet.files).map(([key, value]) => [key, Object.assign({
212 + url: value.url
213 + }, fileStatus(`${parakeetPath}/${value.file}`))]));
214 + return {
215 + dataDir: root,
216 + vad: Object.assign({ url: ASSET_FILES.vad.url }, fileStatus(resolvedVadPath())),
217 + parakeet: {
218 + path: parakeetPath,
219 + files: parakeetFiles,
220 + complete: Object.values(parakeetFiles).every(file => file.exists)
221 + },
222 + runtime: Object.assign({
223 + package: 'onnxruntime-node@1.27.0'
224 + }, fileStatus(runtimeModulePath()))
225 + };
228 +async function remoteStatus(file) {
229 + try {
230 + const response = await fetch(file.url, { method: 'HEAD' });
231 + if (!response.ok) return { key: file.key, url: file.url, path: file.path, ok: false, error: `http ${response.status}`, updateAvailable: false };
232 + const remoteSize = Number(response.headers.get('content-length') || 0);
233 + const local = fileStatus(file.path);
234 + return {
235 + key: file.key,
236 + url: file.url,
237 + path: file.path,
238 + exists: local.exists,
239 + localSize: local.size,
240 + remoteSize,
241 + etag: response.headers.get('etag') || '',
242 + lastModified: response.headers.get('last-modified') || '',
243 + ok: true,
244 + updateAvailable: !local.exists || (remoteSize > 0 && local.size !== remoteSize)
245 + };
246 + } catch (error) {
247 + return { key: file.key, url: file.url, path: file.path, ok: false, error: String(error && error.message ? error.message : error), updateAvailable: false };
251 +async function checkAssets() {
252 + const assets = assetReport();
253 + const files = Object.fromEntries(await Promise.all(assetFiles(assets).map(async file => [file.key, await remoteStatus(file)])));
254 + return {
255 + checkedAt: new Date().toISOString(),
256 + assets,
257 + files,
258 + updateAvailable: Object.values(files).some(file => file.updateAvailable),
259 + unknown: Object.values(files).filter(file => !file.ok).map(file => file.key)
260 + };
263 +function emitProgress(emit, event) {
264 + if (emit) emit(event);
267 +async function writeStream(stream, path, emit, base) {
268 + const out = createWriteStream(path);
269 + let loaded = 0;
270 + for await (const chunk of Readable.fromWeb(stream)) {
271 + loaded += chunk.length;
272 + if (!out.write(chunk)) await new Promise(resolve => out.once('drain', resolve));
273 + emitProgress(emit, Object.assign({}, base, {
274 + event: 'download',
275 + loaded,
276 + progress: base.totalBytes > 0 ? loaded / base.totalBytes : base.progress
277 + }));
279 + await new Promise((resolve, reject) => out.end(error => error ? reject(error) : resolve()));
282 +async function downloadFile(url, path, options = {}) {
283 + if (options.force && existsSync(path)) unlinkSync(path);
284 + if (existsSync(path)) {
285 + emitProgress(options.emit, { event: 'skip', label: options.label || path, progress: options.progress || 1, path });
286 + return { path, skipped: true };
288 + mkdirSync(path.slice(0, path.lastIndexOf('/')), { recursive: true });
289 + const tmp = `${path}.tmp-${process.pid}`;
290 + const response = await fetch(url);
291 + if (!response.ok || !response.body) throw new Error(`download failed ${response.status} ${url}`);
292 + const totalBytes = Number(response.headers.get('content-length') || 0);
293 + emitProgress(options.emit, { event: 'download-start', label: options.label || path, progress: options.progress || 0, totalBytes, path });
294 + await writeStream(response.body, tmp, options.emit, {
295 + label: options.label || path,
296 + progress: options.progress || 0,
297 + totalBytes,
298 + path
299 + });
300 + renameSync(tmp, path);
301 + emitProgress(options.emit, { event: 'download-done', label: options.label || path, progress: options.doneProgress || 1, path });
302 + return { path, skipped: false };
305 +function installRuntime(options = {}) {
306 + emitProgress(options.emit, { event: 'runtime-start', label: 'runtime', progress: 0.08, path: runtimeModulePath() });
307 + if (existsSync(runtimeModulePath())) {
308 + emitProgress(options.emit, { event: 'runtime-done', label: 'runtime', progress: 0.18, path: runtimeModulePath(), skipped: true });
309 + return { path: runtimeModulePath(), skipped: true };
311 + mkdirSync(runtimeDir(), { recursive: true });
312 + const result = spawnSync('npm', ['install', '--prefix', runtimeDir(), 'onnxruntime-node@1.27.0'], {
313 + encoding: 'utf8',
314 + maxBuffer: 1024 * 1024 * 8
315 + });
316 + if (result.status !== 0) throw new Error(`runtime install failed: ${(result.stderr || result.stdout || '').trim()}`);
317 + emitProgress(options.emit, { event: 'runtime-done', label: 'runtime', progress: 0.18, path: runtimeModulePath(), skipped: false });
318 + return { path: runtimeModulePath(), skipped: false };
321 +async function installAssets(options = {}) {
322 + const report = assetReport();
323 + const results = [];
324 + const emit = options.emit;
325 + const files = assetFiles(report);
326 + emitProgress(emit, { event: 'start', label: options.force ? 'update' : 'install', progress: 0 });
327 + try {
328 + if (!options.force) results.push(installSystemDependencies({ emit }));
329 + results.push(installRuntime({ emit }));
330 + for (let i = 0; i < files.length; i++) {
331 + const start = 0.18 + i / files.length * 0.82;
332 + const end = 0.18 + (i + 1) / files.length * 0.82;
333 + results.push(await downloadFile(files[i].url, files[i].path, {
334 + label: files[i].key,
335 + progress: start,
336 + doneProgress: end,
337 + emit,
338 + force: options.force
339 + }));
341 + } catch (error) {
342 + for (const file of [assetReport().vad].concat(Object.values(assetReport().parakeet.files))) {
343 + const tmp = `${file.path}.tmp-${process.pid}`;
344 + if (existsSync(tmp)) unlinkSync(tmp);
346 + throw error;
348 + const done = { event: 'done', progress: 1, installed: results, assets: assetReport() };
349 + emitProgress(emit, done);
350 + return { installed: results, assets: done.assets };
353 +function jsonLine(event) {
354 + process.stdout.write(JSON.stringify(event) + '\n');
357 +function recursiveNames(dir, prefix = '') {
358 + if (!dir || !existsSync(dir)) return [];
359 + const out = [];
360 + for (const entry of readdirSync(dir, { withFileTypes: true })) {
361 + const name = prefix ? `${prefix}/${entry.name}` : entry.name;
362 + if (entry.isDirectory()) out.push(...recursiveNames(`${dir}/${entry.name}`, name));
363 + else out.push(name);
365 + return out;
368 +async function readable(path) {
369 + if (!path) return false;
370 + try {
371 + await access(path, constants.R_OK);
372 + return true;
373 + } catch (_error) {
374 + return false;
378 +async function doctor() {
379 + const vadPath = resolvedVadPath();
380 + const modelDir = resolvedParakeetDir();
381 + const modelFiles = recursiveNames(modelDir);
382 + const model = discoverParakeetDir(modelDir);
383 + const conceptualModel = Noko.validateParakeetModelFiles(modelFiles);
384 + const onnxRuntime = await loadOnnxRuntime().then(() => true, () => false);
385 + const sentencePiece = (() => {
386 + try {
387 + loadSentencePiece();
388 + return true;
389 + } catch (_error) {
390 + return false;
392 + })();
393 + const vadDetails = vadPath && onnxRuntime ? await vadRuntimeReport(vadPath) : null;
394 + const systemDependencies = systemDependencyReport();
395 + const missingSystem = missingSystemDependencies(systemDependencies);
396 + const report = {
397 + systemDependencies,
398 + missingSystemDependencies: missingSystem,
399 + capture: {
400 + pwRecord: commandExists('pw-record'),
401 + parec: commandExists('parec')
402 + },
403 + vad: Object.assign({
404 + path: vadPath,
405 + readable: await readable(vadPath)
406 + }, vadDetails ? {
407 + loadable: vadDetails.loadable,
408 + inputNames: vadDetails.inputNames,
409 + outputNames: vadDetails.outputNames,
410 + stateful: vadDetails.stateful,
411 + srInput: vadDetails.srInput,
412 + frameSamples: vadDetails.frameSamples,
413 + smokeProbability: vadDetails.smokeProbability,
414 + error: vadDetails.error
415 + } : {}),
416 + parakeet: {
417 + path: modelDir,
418 + readable: await readable(modelDir),
419 + ok: model.ok,
420 + missing: model.missing,
421 + files: model.files,
422 + conceptualMissing: conceptualModel.missing
423 + },
424 + runtime: {
425 + onnxruntimeNode: onnxRuntime,
426 + sentencepieceJs: sentencePiece
428 + };
429 + const needsSentencePiece = Boolean(model.files.tokenizer && model.files.tokenizer.endsWith('.model'));
430 + const parakeetRuntimeOk = report.runtime.onnxruntimeNode && (!needsSentencePiece || report.runtime.sentencepieceJs);
431 + report.parakeet.needsSentencePiece = needsSentencePiece;
432 + report.ok = missingSystem.length === 0 && report.vad.readable && report.parakeet.ok && parakeetRuntimeOk;
433 + return report;
436 +function captureSamples(secondsArg, device) {
437 + const seconds = Math.max(0.03, Math.min(60, Number(secondsArg)));
438 + if (!isFinite(seconds)) throw new Error('seconds must be a number');
439 + const sampleCount = Math.round(seconds * Noko.TARGET_RATE);
440 + const argv = ['--raw', '--rate', String(Noko.TARGET_RATE), '--channels', '1', '--format', 'f32', '--sample-count', String(sampleCount)];
441 + if (device) argv.push('--target', String(device));
442 + argv.push('-');
443 + const result = spawnSync('pw-record', argv, {
444 + encoding: 'buffer',
445 + maxBuffer: Math.max(1024 * 1024, sampleCount * 8)
446 + });
447 + if (result.status !== 0 && result.stdout.length === 0) {
448 + const err = result.stderr ? result.stderr.toString('utf8').trim() : '';
449 + throw new Error(`pw-record failed${err ? `: ${err}` : ''}`);
451 + return Noko.float32leToFloat32(result.stdout.subarray(0, sampleCount * 4), 1);
454 +function capturePayload(secondsArg, device) {
455 + const samples = captureSamples(secondsArg, device);
456 + return {
457 + sampleRate: Noko.TARGET_RATE,
458 + channels: 1,
459 + format: 'float32-mono-json',
460 + samples: Array.from(samples)
461 + };
464 +function captureJson(secondsArg, outputPath, device) {
465 + if (!secondsArg || !outputPath) throw new Error(usage());
466 + const payload = capturePayload(secondsArg, device);
467 + writeFileSync(outputPath, JSON.stringify(payload));
468 + return {
469 + outputPath,
470 + sampleRate: Noko.TARGET_RATE,
471 + channels: 1,
472 + sampleCount: payload.samples.length,
473 + duration: Math.round(payload.samples.length / Noko.TARGET_RATE * 1000) / 1000
474 + };
477 +function normalizedSamplesFromJson(inputPath) {
478 + const input = JSON.parse(readFileSync(inputPath, 'utf8'));
479 + const mono = Noko.interleavedToMonoFloat32(new Float32Array(input.samples || []), input.channels || 1);
480 + return Noko.resampleLinear(mono, input.sampleRate || Noko.TARGET_RATE, Noko.TARGET_RATE);
483 +function samplesFromRawFloat32(path) {
484 + return Noko.float32leToFloat32(readFileSync(path), 1);
487 +async function vadJson(inputPath, outputPath) {
488 + if (!inputPath || !outputPath) throw new Error(usage());
489 + const samples = normalizedSamplesFromJson(inputPath);
490 + const vad = await OnnxVad.create(resolvedVadPath());
491 + const probabilities = await vadProbabilities(samples, { vad });
492 + writeFileSync(outputPath, JSON.stringify({
493 + sampleRate: Noko.TARGET_RATE,
494 + frameSamples: Noko.FRAME_SAMPLES,
495 + frameCount: probabilities.length,
496 + probabilities
497 + }));
498 + return {
499 + outputPath,
500 + frameSamples: Noko.FRAME_SAMPLES,
501 + frameCount: probabilities.length
502 + };
505 +async function vadGateJson(inputPath, outputPath) {
506 + if (!inputPath || !outputPath) throw new Error(usage());
507 + const samples = normalizedSamplesFromJson(inputPath);
508 + const frames = Noko.splitFrames(samples, Noko.FRAME_SAMPLES);
509 + const vad = await OnnxVad.create(resolvedVadPath());
510 + const probabilities = await vadProbabilities(samples, { vad });
511 + const gated = Noko.vadGate(frames, probabilities, {
512 + threshold: 0.3,
513 + preRoll: 15,
514 + onset: 2,
515 + hangover: 15
516 + });
517 + writeFileSync(outputPath, JSON.stringify({
518 + sampleRate: Noko.TARGET_RATE,
519 + frameSamples: Noko.FRAME_SAMPLES,
520 + inputFrameCount: frames.length,
521 + speechFrameCount: gated.speechFrameCount,
522 + frameIndexes: gated.frameIndexes,
523 + probabilities,
524 + samples: Array.from(gated.samples)
525 + }));
526 + return {
527 + outputPath,
528 + inputFrameCount: frames.length,
529 + speechFrameCount: gated.speechFrameCount,
530 + sampleCount: gated.samples.length
531 + };
534 +async function transcribeSamples(samples, historyPath) {
535 + if (!historyPath) throw new Error(usage());
536 + samples = samples instanceof Float32Array ? samples : new Float32Array(samples);
537 + const frames = Noko.splitFrames(samples, Noko.FRAME_SAMPLES);
538 + const vad = await OnnxVad.create(resolvedVadPath());
539 + const probabilities = await vadProbabilities(samples, { vad });
540 + const gated = Noko.vadGate(frames, probabilities, {
541 + threshold: 0.3,
542 + preRoll: 15,
543 + onset: 2,
544 + hangover: 15
545 + });
546 + if (gated.samples.length === 0) throw new Error('empty speech buffer after vad');
547 + const raw = await (await ParakeetOnnx.create(resolvedParakeetDir())).transcribe(gated.samples);
548 + const text = Noko.postprocess(raw && raw.text !== undefined ? raw.text : raw);
549 + if (!text) throw new Error('empty transcript');
550 + const record = Noko.historyRecord(text, gated.samples, Object.assign({
551 + runtimeProvider: 'onnxruntime-node'
552 + }, raw && raw.meta ? raw.meta : {}));
553 + appendFileSync(historyPath, JSON.stringify(record) + '\n');
554 + return {
555 + text,
556 + frameIndexes: gated.frameIndexes,
557 + history: record
558 + };
561 +async function transcribeRealJson(inputPath, historyPath) {
562 + if (!inputPath || !historyPath) throw new Error(usage());
563 + return transcribeSamples(normalizedSamplesFromJson(inputPath), historyPath);
566 +async function transcribeRawJson(inputPath, historyPath) {
567 + if (!inputPath || !historyPath) throw new Error(usage());
568 + return transcribeSamples(samplesFromRawFloat32(inputPath), historyPath);
571 +async function transcribeCaptureJson(secondsArg, historyPath, device) {
572 + if (!secondsArg || !historyPath) throw new Error(usage());
573 + return transcribeSamples(capturePayload(secondsArg, device).samples, historyPath);
576 +function transcribeJson(inputPath, historyPath) {
577 + if (!inputPath || !historyPath) throw new Error(usage());
578 + const input = JSON.parse(readFileSync(inputPath, 'utf8'));
579 + const probabilities = input.probabilities || [];
580 + const result = Noko.transcribePipeline({
581 + samples: new Float32Array(input.samples || []),
582 + sampleRate: input.sampleRate || Noko.TARGET_RATE,
583 + channels: input.channels || 1
584 + }, {
585 + probability: (_frame, index) => Number(probabilities[index] || 0)
586 + }, {
587 + transcribe: () => ({
588 + text: String(input.transcript || ''),
589 + meta: {
590 + model: input.model || 'json-fixture',
591 + quantization: input.quantization || 'fixture',
592 + runtimeProvider: 'fixture'
594 + })
595 + }, {
596 + write: record => appendFileSync(historyPath, JSON.stringify(record) + '\n')
597 + }, input.options || {});
598 + return result;
601 +async function main(argv) {
602 + const command = argv[2] || 'help';
603 + if (command === 'doctor') return doctor();
604 + if (command === 'system-deps-json') return systemDependencyStatus();
605 + if (command === 'assets-json') return assetReport();
606 + if (command === 'check-assets-json') return checkAssets();
607 + if (command === 'install-assets') return installAssets();
608 + if (command === 'update-assets') return installAssets({ force: true });
609 + if (command === 'install-assets-progress') {
610 + await installAssets({ emit: jsonLine });
611 + return null;
613 + if (command === 'update-assets-progress') {
614 + await installAssets({ force: true, emit: jsonLine });
615 + return null;
617 + if (command === 'capture-json') return captureJson(argv[3], argv[4], argv[5]);
618 + if (command === 'vad-json') return vadJson(argv[3], argv[4]);
619 + if (command === 'vad-gate-json') return vadGateJson(argv[3], argv[4]);
620 + if (command === 'transcribe-real-json') return transcribeRealJson(argv[3], argv[4]);
621 + if (command === 'transcribe-raw-json') return transcribeRawJson(argv[3], argv[4]);
622 + if (command === 'transcribe-capture-json') return transcribeCaptureJson(argv[3], argv[4], argv[5]);
623 + if (command === 'transcribe-json') return transcribeJson(argv[3], argv[4]);
624 + if (command === 'help' || command === '--help' || command === '-h') return usage();
625 + throw new Error(`unknown command: ${command}\n${usage()}`);
628 +main(process.argv).then(result => {
629 + if (result === null || result === undefined) return;
630 + if (typeof result === 'string') {
631 + process.stdout.write(result);
632 + return;
634 + process.stdout.write(JSON.stringify(result, null, 2) + '\n');
635 +}).catch(error => {
636 + process.stderr.write(String(error && error.message ? error.message : error) + '\n');
637 + process.exit(1);
638 +});

quickshell/nuguland/noko.test.js

Added
new file mode 100644
1 +const assert = require('assert');
2 +const { execFileSync } = require('child_process');
3 +const { mkdtempSync, readFileSync, writeFileSync } = require('fs');
4 +const { join } = require('path');
5 +const { tmpdir } = require('os');
6 +const N = require('./noko.js');
8 +// stereo averaging + clamp
9 +assert.deepStrictEqual(Array.from(N.interleavedToMonoFloat32([1, -1, 0.5, 0.25], 2)), [0, 0.375]);
10 +assert.deepStrictEqual(Array.from(N.interleavedToMonoFloat32([2, -2], 1)), [1, -1]);
12 +// pcm16le -> mono float32
13 +const pcm = Buffer.from([0x00, 0x80, 0xff, 0x7f]); // -32768, 32767
14 +const mono = N.pcm16leToMonoFloat32(pcm, 1);
15 +assert.strictEqual(mono[0], -1);
16 +assert.ok(Math.abs(mono[1] - 32767 / 32768) < 1e-8);
17 +assert.throws(() => N.pcm16leToMonoFloat32(Buffer.from([1]), 1), /even/);
18 +const f32 = Buffer.alloc(8);
19 +f32.writeFloatLE(-0.25, 0);
20 +f32.writeFloatLE(0.75, 4);
21 +assert.deepStrictEqual(Array.from(N.float32leToFloat32(f32, 1)), [-0.25, 0.75]);
22 +assert.throws(() => N.float32leToFloat32(Buffer.from([0, 1]), 1), /divisible by 4/);
24 +// resample 48 kHz -> 16 kHz reduces by 3x and preserves endpoints
25 +const ramp = new Float32Array([0, 1, 2, 3, 4, 5]);
26 +const down = N.resampleLinear(ramp, 48000, 16000);
27 +assert.strictEqual(down.length, 2);
28 +assert.strictEqual(down[0], 0);
29 +assert.strictEqual(down[1], 5);
31 +// exact 30 ms frames at 16 kHz
32 +const samples = new Float32Array(480 * 3 + 12).fill(0.25);
33 +const frames = N.splitFrames(samples, N.FRAME_SAMPLES);
34 +assert.strictEqual(frames.length, 3);
35 +assert.strictEqual(frames[0].length, 480);
37 +// VAD smoothing: 2 speech frames trigger pre-roll flush, then 1 hangover noise frame kept.
38 +const tinyFrames = [0, 1, 2, 3, 4].map(v => new Float32Array([v]));
39 +const gated = N.vadGate(tinyFrames, [0, 0.4, 0.5, 0, 0], {
40 + threshold: 0.3,
41 + preRoll: 1,
42 + onset: 2,
43 + hangover: 1
44 +});
45 +assert.deepStrictEqual(gated.frameIndexes, [0, 1, 2, 3]);
46 +assert.deepStrictEqual(Array.from(gated.samples), [0, 1, 2, 3]);
48 +// postprocess: trim, collapse spaces, remove junk tokens.
49 +assert.strictEqual(N.postprocess(' hello <unk> world ', ['<unk>']), 'hello world');
51 +// model dir concept validation.
52 +assert.deepStrictEqual(N.validateParakeetModelFiles([
53 + 'nemo128.onnx',
54 + 'encoder.int8.onnx',
55 + 'decoder_joint.int8.onnx',
56 + 'vocab.txt'
57 +]), { ok: true, missing: [] });
58 +assert.deepStrictEqual(N.validateParakeetModelFiles(['encoder.onnx']).missing, [
59 + 'preprocessor',
60 + 'decoder-or-joint',
61 + 'vocabulary-or-tokenizer'
62 +]);
64 +// End-to-end core flow with injected VAD and Parakeet engine.
65 +const input = new Float32Array(480 * 6).fill(0);
66 +for (let i = 480 * 2; i < 480 * 4; i++) input[i] = 0.6;
67 +const writes = [];
68 +const state = new N.EngineState();
69 +const result = N.transcribePipeline({ samples: input, sampleRate: 16000, channels: 1 }, {
70 + probability: (_frame, index) => index >= 2 && index <= 3 ? 0.9 : 0.01
71 +}, {
72 + transcribe: (speech, ctx) => {
73 + assert.strictEqual(ctx.sampleRate, 16000);
74 + assert.ok(speech.length > 0);
75 + return { text: ' hello noko ', meta: { model: 'fake-parakeet', quantization: 'int8', runtimeProvider: 'fake-onnx' } };
76 + }
77 +}, {
78 + write: record => writes.push(record)
79 +}, { state: state, vad: { preRoll: 1, onset: 2, hangover: 1 } });
81 +assert.strictEqual(result.text, 'hello noko');
82 +assert.strictEqual(result.state, 'ready');
83 +assert.strictEqual(state.state, 'ready');
84 +assert.strictEqual(writes.length, 1);
85 +assert.strictEqual(writes[0].transcript, 'hello noko');
86 +assert.strictEqual(writes[0].model, 'fake-parakeet');
87 +assert.ok(writes[0].duration > 0);
89 +assert.throws(() => N.transcribePipeline({ samples: new Float32Array(480 * 2), sampleRate: 16000 }, {
90 + probability: () => 0
91 +}, {
92 + transcribe: () => 'nope'
93 +}), /empty speech buffer after vad/);
95 +// CLI fixture proves the command path saves JSONL history after a full injected flow.
96 +const dir = mkdtempSync(join(tmpdir(), 'noko-'));
97 +const fixture = join(dir, 'fixture.json');
98 +const history = join(dir, 'history.jsonl');
99 +writeFileSync(fixture, JSON.stringify({
100 + samples: Array.from(input),
101 + sampleRate: 16000,
102 + channels: 1,
103 + probabilities: [0, 0, 0.9, 0.9, 0, 0],
104 + transcript: ' cli noko ',
105 + options: { vad: { preRoll: 1, onset: 2, hangover: 1 } }
106 +}));
107 +const cliOut = JSON.parse(execFileSync('node', ['noko.mjs', 'transcribe-json', fixture, history], { cwd: __dirname, encoding: 'utf8' }));
108 +assert.strictEqual(cliOut.text, 'cli noko');
109 +assert.strictEqual(JSON.parse(readFileSync(history, 'utf8').trim()).transcript, 'cli noko');
110 +assert.throws(() => execFileSync('node', ['noko.mjs', 'transcribe-real-json', fixture, join(dir, 'real.jsonl')], { cwd: __dirname, encoding: 'utf8', stdio: 'pipe', env: { ...process.env, NOKO_DATA_DIR: join(dir, 'missing-data') } }), /vad model missing/);
112 +const customDataDir = join(dir, 'noko-data');
113 +const assets = JSON.parse(execFileSync('node', ['noko.mjs', 'assets-json'], { cwd: __dirname, encoding: 'utf8', env: { ...process.env, NOKO_DATA_DIR: customDataDir } }));
114 +assert.strictEqual(assets.dataDir, customDataDir);
115 +assert.ok(assets.vad.path.startsWith(customDataDir));
116 +assert.ok(assets.parakeet.path.startsWith(customDataDir));
117 +assert.ok(assets.runtime.path.startsWith(customDataDir));
118 +assert.equal(assets.runtime.package, 'onnxruntime-node@1.27.0');
119 +assert.match(assets.parakeet.files.encoder.url, /^https:\/\/huggingface\.co\//);
120 +assert.doesNotMatch(JSON.stringify(assets), /com\.pais\.handy|Handy/);
121 +for (const file of [assets.vad, ...Object.values(assets.parakeet.files)]) {
122 + require('fs').mkdirSync(require('path').dirname(file.path), { recursive: true });
123 + writeFileSync(file.path, 'x');
125 +require('fs').mkdirSync(assets.runtime.path, { recursive: true });
126 +const progressLines = execFileSync('node', ['noko.mjs', 'install-assets-progress'], { cwd: __dirname, encoding: 'utf8', env: { ...process.env, NOKO_DATA_DIR: customDataDir } }).trim().split('\n').map(JSON.parse);
127 +assert.equal(progressLines.at(-1).event, 'done');
128 +assert.equal(progressLines.at(-1).progress, 1);
129 +const deps = JSON.parse(execFileSync('node', ['noko.mjs', 'system-deps-json'], { cwd: __dirname, encoding: 'utf8' }));
130 +assert.ok(deps.dependencies.some(dep => dep.command === 'pw-record' && dep.required === true));
131 +assert.ok(deps.dependencies.some(dep => dep.command === 'wtype' && dep.required === true));
132 +assert.ok(Array.isArray(deps.missing));
133 +assert.ok(deps.installCommand.length === 0 || deps.installCommand[0] === 'pkexec');
134 +const doctor = JSON.parse(execFileSync('node', ['noko.mjs', 'doctor'], { cwd: __dirname, encoding: 'utf8', env: { ...process.env, NOKO_DATA_DIR: customDataDir } }));
135 +assert.strictEqual(typeof doctor.capture.pwRecord, 'boolean');
136 +assert.ok(Array.isArray(doctor.systemDependencies));
137 +assert.ok(doctor.systemDependencies.some(dep => dep.command === 'pw-record' && dep.required === true));
138 +assert.ok(doctor.systemDependencies.some(dep => dep.command === 'wtype' && dep.required === true));
139 +assert.strictEqual(typeof doctor.missingSystemDependencies.length, 'number');
140 +assert.strictEqual(typeof doctor.ok, 'boolean');
141 +assert.strictEqual(doctor.vad.path, assets.vad.path);
142 +assert.strictEqual(doctor.parakeet.path, assets.parakeet.path);
143 +assert.doesNotMatch(JSON.stringify(doctor), /com\.pais\.handy|Handy/);
145 +execFileSync('node', ['--input-type=module', '-e', `
146 +import assert from 'node:assert/strict';
147 +import { execFile } from 'node:child_process';
148 +import { promisify } from 'node:util';
149 +import { createServer } from 'node:http';
150 +import { mkdirSync, writeFileSync } from 'node:fs';
151 +import { join } from 'node:path';
152 +import { tmpdir } from 'node:os';
153 +const dir = join(tmpdir(), 'noko-update-check-' + process.pid);
154 +const assetDir = join(dir, 'assets');
155 +mkdirSync(join(assetDir, 'vad'), { recursive: true });
156 +mkdirSync(join(assetDir, 'parakeet-tdt-0.6b-v3-int8'), { recursive: true });
157 +writeFileSync(join(assetDir, 'vad', 'silero_vad.onnx'), 'old');
158 +for (const name of ['config.json', 'nemo128.onnx', 'encoder-model.int8.onnx', 'decoder_joint-model.int8.onnx', 'vocab.txt'])
159 + writeFileSync(join(assetDir, 'parakeet-tdt-0.6b-v3-int8', name), name === 'encoder-model.int8.onnx' ? 'old' : 'same');
160 +const payload = {
161 + '/silero_vad.onnx': 'old',
162 + '/config.json': 'same',
163 + '/nemo128.onnx': 'same',
164 + '/encoder-model.int8.onnx': 'newer-remote',
165 + '/decoder_joint-model.int8.onnx': 'same',
166 + '/vocab.txt': 'same'
168 +const server = createServer((req, res) => {
169 + const body = payload[req.url] || '';
170 + res.setHeader('content-length', Buffer.byteLength(body));
171 + res.setHeader('connection', 'close');
172 + res.end(req.method === 'HEAD' ? '' : body);
173 +});
174 +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
175 +const base = 'http://127.0.0.1:' + server.address().port;
176 +const env = { ...process.env, NOKO_DATA_DIR: assetDir, NOKO_VAD_URL: base + '/silero_vad.onnx', NOKO_PARAKEET_REPO: base };
177 +const run = promisify(execFile);
178 +const { stdout } = await run('node', ['noko.mjs', 'check-assets-json'], { cwd: process.cwd(), encoding: 'utf8', env });
179 +const check = JSON.parse(stdout);
180 +assert.equal(check.updateAvailable, true);
181 +assert.equal(check.files.encoder.updateAvailable, true);
182 +assert.equal(check.files.vad.updateAvailable, false);
183 +server.closeAllConnections();
184 +await new Promise(resolve => server.close(resolve));
185 +`], { cwd: __dirname, encoding: 'utf8' });
187 +// Real VAD bridge shape test: the public API accepts 480-sample frames, then
188 +// prepares a Silero-compatible ONNX feed with context/state/sr when required.
189 +execFileSync('node', ['--input-type=module', '-e', `
190 +import assert from 'node:assert/strict';
191 +import { OnnxVad, vadRuntimeReport } from './noko-vad.mjs';
192 +class Tensor { constructor(type, data, dims) { this.type = type; this.data = data; this.dims = dims; } }
193 +const calls = [];
194 +const session = {
195 + inputNames: ['input', 'state', 'sr'],
196 + outputNames: ['output', 'stateN'],
197 + async run(feeds) {
198 + calls.push(feeds);
199 + assert.deepEqual(feeds.input.dims, [1, 576]);
200 + assert.deepEqual(feeds.state.dims, [2, 1, 128]);
201 + assert.deepEqual(feeds.sr.dims, []);
202 + return { output: new Tensor('float32', new Float32Array([0.7]), [1, 1]), stateN: new Tensor('float32', new Float32Array(256).fill(0.1), [2, 1, 128]) };
205 +const vad = new OnnxVad({ Tensor }, session);
206 +assert.ok(Math.abs(await vad.probability(new Float32Array(480).fill(0.2)) - 0.7) < 1e-6);
207 +assert.equal(calls.length, 1);
208 +assert.throws(() => vad.feeds(new Float32Array(479)), /exactly 480/);
209 +const report = await vadRuntimeReport('./noko.test.js', { ort: { Tensor }, session });
210 +assert.equal(report.loadable, true);
211 +assert.deepEqual(report.inputNames, ['input', 'state', 'sr']);
212 +assert.deepEqual(report.outputNames, ['output', 'stateN']);
213 +assert.equal(report.stateful, true);
214 +assert.equal(report.srInput, true);
215 +assert.ok(Math.abs(report.smokeProbability - 0.7) < 1e-6);
216 +`], { cwd: __dirname, encoding: 'utf8' });
218 +execFileSync('node', ['--input-type=module', '-e', `
219 +import assert from 'node:assert/strict';
220 +import { mkdirSync, writeFileSync } from 'node:fs';
221 +import { join } from 'node:path';
222 +import { tmpdir } from 'node:os';
223 +import { decodeTokens, discoverParakeetDir, ParakeetOnnx } from './noko-parakeet.mjs';
224 +const dir = join(tmpdir(), 'noko-parakeet-' + process.pid);
225 +mkdirSync(join(dir, 'onnx_int8'), { recursive: true });
226 +writeFileSync(join(dir, 'onnx_int8', '._encoder.int8.onnx'), '');
227 +writeFileSync(join(dir, 'onnx_int8', 'nemo128.onnx'), '');
228 +writeFileSync(join(dir, 'onnx_int8', 'encoder.int8.onnx'), '');
229 +writeFileSync(join(dir, 'onnx_int8', 'decoder_joint.int8.onnx'), '');
230 +writeFileSync(join(dir, 'onnx_int8', 'tokenizer.model'), '');
231 +const found = discoverParakeetDir(dir);
232 +assert.equal(found.ok, true);
233 +assert.equal(found.files.preprocessor, 'onnx_int8/nemo128.onnx');
234 +assert.equal(found.files.encoder, 'onnx_int8/encoder.int8.onnx');
235 +assert.deepEqual(discoverParakeetDir(join(dir, 'missing')).missing, ['preprocessor', 'encoder', 'decoder-or-joint', 'vocabulary-or-tokenizer']);
236 +await assert.rejects(() => ParakeetOnnx.create(join(dir, 'missing'), { ort: {} }), /model dir incomplete/);
237 +assert.equal(decodeTokens({ decodeIds: ids => ids.join(',') }, [1, 2, 3]), '1,2,3');
238 +assert.throws(() => decodeTokens(null, [1]), /tokenizer missing/);
239 +const runtime = new ParakeetOnnx({}, {}, found, { size: 1, blankIdx: 0, decodeIds: () => '' });
240 +await assert.rejects(() => runtime.transcribe(new Float32Array()), /empty speech buffer/);
241 +runtime.busy = true;
242 +await assert.rejects(() => runtime.transcribe(new Float32Array([0])), /already running/);
243 +runtime.busy = false;
244 +assert.equal(runtime.state, 'ready');
245 +class Tensor { constructor(type, data, dims) { this.type = type; this.data = data; this.dims = dims; } }
246 +const stateTensor = new Tensor('float32', new Float32Array(2 * 1 * 640), [2, 1, 640]);
247 +const fake = new ParakeetOnnx({ Tensor }, {
248 + preprocessor: { async run() { return { features: new Tensor('float32', new Float32Array([0]), [1, 1, 1]), features_lens: new Tensor('int64', BigInt64Array.from([1n]), [1]) }; } },
249 + encoder: { async run() { return { outputs: new Tensor('float32', new Float32Array([0.1, 0.2]), [1, 2, 1]), encoded_lengths: new Tensor('int64', BigInt64Array.from([1n]), [1]) }; } },
250 + decoderJoint: {
251 + inputMetadata: [
252 + { name: 'input_states_1', shape: [2, 'batch', 640] },
253 + { name: 'input_states_2', shape: [2, 'batch', 640] }
254 + ],
255 + async run() { return { outputs: new Tensor('float32', new Float32Array([0.9, 0.1, 0, 1]), [1, 1, 1, 4]), output_states_1: stateTensor, output_states_2: stateTensor }; }
257 +}, { files: { encoder: 'encoder-model.int8.onnx' } }, { size: 2, blankIdx: 1, decodeIds: ids => ids.map(id => id === 0 ? 'hello' : '').join('') });
258 +const fakeResult = await fake.transcribe(new Float32Array([0.4]));
259 +assert.equal(fakeResult.text, 'hello');
260 +assert.equal(fakeResult.meta.runtimeProvider, 'onnxruntime-node');
261 +`], { cwd: __dirname, encoding: 'utf8' });
263 +console.log('noko.test.js: ALL PASS');

quickshell/nuguland/shell.qml

Modified
158 158 id: surfaceManager
161 + Noko {
162 + id: noko
161 165 Usage {
162 166 id: usage
337 + Variants {
338 + model: Quickshell.screens
340 + delegate: Component {
341 + PanelWindow {
342 + id: nokoOverlayWindow
344 + required property var modelData
346 + objectName: "nokoFocusOverlaySurface"
347 + screen: modelData
348 + visible: (noko.overlayState || "").length > 0 && String(modelData.name || "") === String(niri.focusedOutputName || shell.primaryScreenName)
349 + implicitWidth: 1
350 + implicitHeight: 1
351 + color: "transparent"
352 + exclusionMode: ExclusionMode.Ignore
353 + WlrLayershell.layer: WlrLayer.Overlay
354 + WlrLayershell.namespace: "nuguland-noko-overlay"
355 + WlrLayershell.keyboardFocus: WlrKeyboardFocus.None
357 + anchors {
358 + top: true
359 + left: true
360 + right: true
361 + bottom: true
364 + NokoFocusOverlay {
365 + anchors.fill: parent
366 + theme: nuguTheme
367 + nokoService: noko
368 + niriService: niri
369 + barHeight: nokoOverlayWindow.modelData.name === shell.primaryScreenName ? surfaceManager.barHeight : 0
370 + orientation: shell.orientation
373 + mask: Region {}
333 378 Variants {
334 379 model: Quickshell.screens
534 579 powerService: power
535 580 idleService: idle
536 581 lockService: lock
582 + nokoService: noko
537 583 surfaces: surfaceManager
538 584 usageService: usage
539 585 caldavService: caldav
592 + IpcHandler {
593 + target: "noko"
595 + function state(): string {
596 + return noko.stateJson();
599 + function refresh(): string {
600 + return noko.refresh();
603 + function install(): string {
604 + return noko.install();
607 + function update(): string {
608 + return noko.update();
611 + function checkUpdates(): string {
612 + return noko.checkUpdates();
615 + function trigger(): string {
616 + return noko.trigger();
619 + function start(): string {
620 + return noko.startCapture();
623 + function stop(): string {
624 + return noko.stopCapture();
627 + function transcribe(seconds: int): string {
628 + return noko.transcribe(seconds);
631 + function listening(): string {
632 + return noko.beginListening();
635 + function transcribing(): string {
636 + return noko.beginTranscribing();
639 + function finish(): string {
640 + return noko.finish();
546 644 IpcHandler {
547 645 function increase() {
548 646 return audio.increase();
1346 1444 Rectangle {
1347 1445 anchors.centerIn: parent
1348 - width: Math.min(parent.width - 48, 560)
1349 - height: Math.min(parent.height - 48, 370)
1350 - radius: 22
1351 - color: root.theme ? root.theme.ui.backdrop : "transparent"
1352 - border.width: 0
1353 - border.color: root.theme ? root.theme.warning : "transparent"
1446 + width: Math.min(parent.width - 48, 520)
1447 + height: cardColumn.implicitHeight + 44
1448 + radius: 24
1449 + color: root.theme ? root.theme.withAlpha(root.theme.ui.backdrop, 0.98) : "#181818"
1450 + border.width: 1
1451 + border.color: root.theme ? root.theme.withAlpha(root.panelState.error ? root.theme.error : root.theme.ui.accent, 0.32) : "transparent"
1355 1453 Column {
1356 - anchors.fill: parent
1454 + id: cardColumn
1456 + anchors.left: parent.left
1457 + anchors.right: parent.right
1458 + anchors.top: parent.top
1357 1459 anchors.margins: 22
1358 - spacing: 12
1460 + spacing: 16
1360 - NuguText {
1361 - theme: root.theme
1362 - variant: "meta"
1363 - text: "authentication required"
1462 + Row {
1364 1463 width: parent.width
1365 - wrapMode: Text.WordWrap
1464 + spacing: 12
1368 - Rectangle {
1369 - objectName: "requestIdentityCard"
1370 - width: parent.width
1371 - height: 94
1372 - radius: 15
1373 - color: root.theme ? root.theme.withAlpha(root.theme.warning, 0.14) : "transparent"
1374 - border.width: 0
1375 - border.color: root.theme ? root.theme.warning : "transparent"
1466 + Rectangle {
1467 + width: 38
1468 + height: 38
1469 + radius: 14
1470 + color: root.theme ? root.theme.withAlpha(root.panelState.error ? root.theme.error : root.theme.ui.accent, 0.18) : "transparent"
1472 + Text {
1473 + anchors.centerIn: parent
1474 + text: root.panelState.error ? "!" : "◆"
1475 + color: root.theme ? (root.panelState.error ? root.theme.error : root.theme.ui.accent) : "white"
1476 + font.family: "IBM Plex Mono"
1477 + font.pixelSize: 18
1478 + font.bold: true
1377 1482 Column {
1378 - anchors.fill: parent
1379 - anchors.margins: 12
1380 - spacing: 5
1483 + width: parent.width - 50
1484 + spacing: 3
1382 1486 NuguText {
1383 1487 theme: root.theme
1384 1488 variant: "title"
1385 - text: root.request.app || "polkit"
1386 - width: parent.width
1387 - elide: Text.ElideRight
1390 - NuguText {
1391 - theme: root.theme
1392 - text: root.request.message || "Authentication required"
1489 + text: root.panelState.error ? "authentication unavailable" : "authorization required"
1393 1490 width: parent.width
1394 1491 elide: Text.ElideRight
1397 1494 NuguText {
1398 1495 theme: root.theme
1399 1496 variant: "meta"
1400 - text: root.request.actionId || "native Polkit request"
1497 + text: root.request.message || "A system change needs your password."
1401 1498 width: parent.width
1499 + wrapMode: Text.WordWrap
1500 + color: root.theme ? root.theme.ui.minor : "white"
1505 + Rectangle {
1506 + objectName: "requestIdentityCard"
1507 + width: parent.width
1508 + height: identityColumn.implicitHeight + 18
1509 + radius: 16
1510 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.07) : "transparent"
1512 + Column {
1513 + id: identityColumn
1515 + anchors.left: parent.left
1516 + anchors.right: parent.right
1517 + anchors.top: parent.top
1518 + anchors.margins: 10
1519 + spacing: 4
1521 + NuguText {
1522 + theme: root.theme
1523 + variant: "meta"
1524 + text: root.request.app || "system policy"
1525 + width: parent.width
1526 + color: root.theme ? root.theme.content.normal : "white"
1527 + elide: Text.ElideRight
1530 + NuguText {
1531 + visible: (root.request.actionId || "").length > 0
1532 + theme: root.theme
1533 + variant: "meta"
1534 + text: root.request.actionId || ""
1535 + width: parent.width
1536 + color: root.theme ? root.theme.ui.minor : "white"
1402 1537 elide: Text.ElideMiddle
1408 1543 objectName: "failureShakeSlot"
1409 1544 active: root.panelState.error && root.panelState.error.length > 0
1410 1545 width: parent.width
1411 - height: secretBox.height
1546 + height: inputColumn.implicitHeight
1413 - Rectangle {
1414 - id: secretBox
1548 + Column {
1549 + id: inputColumn
1416 - objectName: "secretPromptField"
1417 1551 width: parent.width
1418 - height: 46
1419 - radius: 23
1420 - color: root.theme ? root.theme.withAlpha(root.panelState.error ? root.theme.error : root.theme.ui.focus, root.panelState.error ? 0.18 : 0.12) : "transparent"
1421 - border.width: 0
1422 - border.color: root.theme ? (root.panelState.error ? root.theme.error : root.theme.ui.focus) : "transparent"
1552 + spacing: 7
1554 + Rectangle {
1555 + id: secretBox
1557 + objectName: "secretPromptField"
1558 + width: parent.width
1559 + height: 48
1560 + radius: 16
1561 + color: root.theme ? root.theme.withAlpha(root.theme.ui.focus, 0.1) : "transparent"
1562 + border.width: 1
1563 + border.color: root.theme ? root.theme.withAlpha(root.panelState.error ? root.theme.error : root.theme.ui.focus, root.panelState.error ? 0.45 : 0.22) : "transparent"
1565 + NuguText {
1566 + anchors.left: parent.left
1567 + anchors.leftMargin: 14
1568 + anchors.verticalCenter: parent.verticalCenter
1569 + theme: root.theme
1570 + variant: "meta"
1571 + text: root.request.prompt || "password"
1572 + opacity: 0.68
1575 + TextInput {
1576 + id: secretInput
1578 + anchors.left: parent.left
1579 + anchors.leftMargin: 104
1580 + anchors.right: parent.right
1581 + anchors.rightMargin: 14
1582 + anchors.verticalCenter: parent.verticalCenter
1583 + color: root.theme ? root.theme.content.normal : "white"
1584 + selectionColor: root.theme ? root.theme.ui.focus : "white"
1585 + selectedTextColor: root.theme ? root.theme.content.backdrop : "black"
1586 + font.family: "IBM Plex Mono"
1587 + echoMode: root.request.responseVisible ? TextInput.Normal : TextInput.Password
1588 + inputMethodHints: Qt.ImhSensitiveData
1589 + focus: root.panelState.active
1590 + onActiveFocusChanged: {
1591 + if (!activeFocus && root.panelState.active)
1592 + forceActiveFocus();
1594 + Keys.onReturnPressed: event => {
1595 + event.accepted = true;
1596 + root.submitSecret(text);
1597 + text = "";
1599 + Keys.onEnterPressed: event => {
1600 + event.accepted = true;
1601 + root.submitSecret(text);
1602 + text = "";
1604 + Keys.onEscapePressed: event => {
1605 + event.accepted = true;
1606 + root.cancel();
1607 + text = "";
1424 1612 NuguText {
1425 - anchors.left: parent.left
1426 - anchors.leftMargin: 14
1427 - anchors.verticalCenter: parent.verticalCenter
1613 + visible: root.panelState.error && root.panelState.error.length > 0
1428 1614 theme: root.theme
1429 1615 variant: "meta"
1430 - text: root.request.prompt || "Password"
1431 - opacity: 0.74
1434 - TextInput {
1435 - id: secretInput
1437 - anchors.left: parent.left
1438 - anchors.leftMargin: 106
1439 - anchors.right: parent.right
1440 - anchors.rightMargin: 14
1441 - anchors.verticalCenter: parent.verticalCenter
1442 - color: root.theme ? root.theme.content.normal : "white"
1443 - selectionColor: root.theme ? root.theme.ui.focus : "white"
1444 - selectedTextColor: root.theme ? root.theme.content.backdrop : "black"
1445 - font.family: "IBM Plex Mono"
1446 - echoMode: root.request.responseVisible ? TextInput.Normal : TextInput.Password
1447 - inputMethodHints: Qt.ImhSensitiveData
1448 - focus: root.panelState.active
1449 - onActiveFocusChanged: {
1450 - if (!activeFocus && root.panelState.active)
1451 - forceActiveFocus();
1453 - Keys.onReturnPressed: event => {
1454 - event.accepted = true;
1455 - root.submitSecret(text);
1456 - text = "";
1458 - Keys.onEnterPressed: event => {
1459 - event.accepted = true;
1460 - root.submitSecret(text);
1461 - text = "";
1463 - Keys.onEscapePressed: event => {
1464 - event.accepted = true;
1465 - root.cancel();
1466 - text = "";
1616 + text: root.panelState.error === "no-active-polkit-flow" ? "No active authentication request." : root.panelState.error
1617 + width: parent.width
1618 + color: root.theme ? root.theme.error : "white"
1619 + elide: Text.ElideRight
1472 - NuguText {
1473 - theme: root.theme
1474 - variant: "meta"
1475 - text: root.panelState.error || "No decoration. No command construction. Native Polkit route."
1476 - width: parent.width
1477 - color: root.panelState.error && root.theme ? root.theme.error : (root.theme ? root.theme.content.normal : "white")
1478 - elide: Text.ElideRight
1482 1625 objectName: "denyCancelConfirmRow"
1483 1626 width: parent.width
1484 - spacing: 8
1627 + spacing: 10
1629 + Rectangle {
1630 + width: Math.floor((parent.width - 10) * 0.38)
1631 + height: 40
1632 + radius: 13
1633 + color: root.theme ? root.theme.withAlpha(root.theme.ui.minor, 0.1) : "transparent"
1635 + NuguText {
1636 + anchors.centerIn: parent
1637 + theme: root.theme
1638 + variant: "meta"
1639 + text: "cancel"
1642 + MouseArea {
1643 + anchors.fill: parent
1644 + cursorShape: Qt.PointingHandCursor
1645 + onClicked: {
1646 + root.cancel();
1647 + secretInput.text = "";
1652 + Rectangle {
1653 + width: parent.width - Math.floor((parent.width - 10) * 0.38) - 10
1654 + height: 40
1655 + radius: 13
1656 + color: root.theme ? root.theme.withAlpha(root.theme.ui.accent, enabled ? 0.26 : 0.08) : "transparent"
1657 + enabled: root.panelState.active
1659 + NuguText {
1660 + anchors.centerIn: parent
1661 + theme: root.theme
1662 + variant: "meta"
1663 + selected: true
1664 + text: "authorize"
1665 + color: root.theme ? (parent.enabled ? root.theme.ui.accent : root.theme.ui.normal) : "white"
1668 + MouseArea {
1669 + anchors.fill: parent
1670 + enabled: parent.enabled
1671 + cursorShape: parent.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
1672 + onClicked: {
1673 + root.submitSecret(secretInput.text);
1674 + secretInput.text = "";
1683 + component NokoFocusOverlay: Item {
1684 + id: overlay
1686 + required property Theme theme
1687 + required property Noko nokoService
1688 + required property Niri niriService
1689 + property int barHeight: 0
1690 + property string orientation: "horizontal"
1691 + readonly property string phase: nokoService ? nokoService.overlayState : ""
1692 + property int tick: 0
1693 + readonly property color accent: !theme ? "white" : (phase === "finished" ? theme.info : theme.ui.accent)
1694 + readonly property bool verticalBar: orientation === "vertical"
1695 + readonly property real usableX: verticalBar ? barHeight : 0
1696 + readonly property real usableY: verticalBar ? 0 : barHeight
1697 + readonly property real usableWidth: Math.max(1, width - usableX)
1698 + readonly property real usableHeight: Math.max(1, height - usableY)
1699 + readonly property real tabX: Math.round(usableX + usableWidth / 2 - statusTab.width / 2)
1700 + readonly property real tabY: Math.round(usableY + 18)
1702 + visible: phase.length > 0
1703 + opacity: visible ? 1 : 0
1705 + Timer {
1706 + interval: 90
1707 + repeat: true
1708 + running: overlay.visible && overlay.phase !== "finished"
1709 + onTriggered: overlay.tick++
1712 + Rectangle {
1713 + id: statusTab
1715 + x: overlay.tabX
1716 + y: overlay.tabY
1717 + width: Math.max(178, tabRow.implicitWidth + 28)
1718 + height: 42
1719 + radius: 14
1720 + color: overlay.theme ? overlay.theme.withAlpha(overlay.theme.ui.backdrop, 0.92) : "#222"
1721 + border.width: 1
1722 + border.color: overlay.theme ? overlay.theme.withAlpha(overlay.accent, 0.48) : "white"
1724 + Row {
1725 + id: tabRow
1727 + anchors.centerIn: parent
1728 + spacing: 12
1730 + NuguText {
1731 + anchors.verticalCenter: parent.verticalCenter
1732 + theme: overlay.theme
1733 + variant: "title"
1734 + font.pixelSize: 13
1735 + text: overlay.phase
1736 + color: overlay.accent
1739 + Row {
1740 + visible: overlay.phase !== "finished"
1741 + anchors.verticalCenter: parent.verticalCenter
1742 + spacing: 3
1743 + height: 24
1486 1745 Repeater {
1487 - model: ["deny", "cancel", "confirm"]
1746 + model: 7
1489 - delegate: Rectangle {
1490 - id: action
1748 + Rectangle {
1749 + required property int index
1492 - required property string modelData
1751 + anchors.verticalCenter: parent.verticalCenter
1752 + width: 3
1753 + height: 7 + Math.abs(Math.sin(overlay.tick / (overlay.phase === "transcribing" ? 2.8 : 1.8) + index)) * 17
1754 + radius: 2
1755 + color: overlay.accent
1756 + opacity: 0.82
1494 - width: Math.floor((parent.width - 16) / 3)
1495 - height: 38
1496 - radius: 12
1497 - color: root.theme ? root.theme.withAlpha(action.modelData === "confirm" ? root.theme.ui.focus : root.theme.ui.minor, action.modelData === "confirm" ? 0.16 : 0.1) : "transparent"
1498 - border.width: 0
1499 - border.color: root.theme ? (action.modelData === "confirm" ? root.theme.ui.focus : root.theme.ui.minor) : "transparent"
1501 - NuguText {
1502 - anchors.centerIn: parent
1503 - theme: root.theme
1504 - variant: "meta"
1505 - selected: action.modelData === "confirm"
1506 - text: action.modelData
1509 - MouseArea {
1510 - anchors.fill: parent
1511 - onClicked: {
1512 - if (action.modelData === "deny") {
1513 - root.deny();
1514 - } else if (action.modelData === "cancel") {
1515 - root.cancel();
1516 - } else {
1517 - root.submitSecret(secretInput.text);
1518 - secretInput.text = "";
1758 + Behavior on height {
1759 + NumberAnimation {
1760 + duration: overlay.theme && overlay.theme.lowPowerMode ? 0 : 90
1761 + easing.type: Easing.OutCubic
1768 + Text {
1769 + visible: overlay.phase === "finished"
1770 + anchors.verticalCenter: parent.verticalCenter
1771 + text: "✓"
1772 + color: overlay.accent
1773 + font.family: "IBM Plex Mono"
1774 + font.pixelSize: 16
1775 + font.bold: true