Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/noko/Noko.qml

Raw
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Io

// Dictation through the speak_to_me engine: one engine process while needed,
// JSON-RPC lines over its stdin and stdout. The engine captures the microphone;
// noko types finished text with `wtype -`. noko-engine.nu owns every engine path,
// release URL and command line; this file owns the protocol (methods below).
Item {
    id: root

    // Engine protocol: profile, model roles and recognition options in one place.
    readonly property string engineScript: Qt.resolvedUrl("noko-engine.nu").toString().replace(/^file:\/\//, "")
    readonly property string engineProfile: "high"
    readonly property var engineRoles: ["stt", "vad", "kws"]
    // Nemotron punctuates and capitalises by itself; the extra punctuation model
    // doubles commas, so finals are typed as recognised.
    readonly property var recognitionOptions: ({
            "punctuation": false,
            "enhancement": false
        })

    property string status: "checking"
    property string lastError: ""
    property string lastChecked: ""
    // Why the last dictation produced no text, in words; cleared by the next capture.
    property string captureError: ""
    property string lastInsertError: ""
    // Newest first, at most historyLimit; transcripts never leave through stateJson().
    property var historyEntries: []

    // Installed engine and its update, as noko-engine.nu reports them.
    property bool statusKnown: false
    property string engineRevision: ""
    property bool typingReady: true
    property string latestRevision: ""
    property real latestSize: 0
    // An unpacked newer revision; switched to while no dictation runs.
    property string pendingRevision: ""
    // Model bytes the engine still needs: the current engine's (first install)
    // or the pending revision's (an update held until they are installed).
    property real assetBytes: 0
    property bool currentAssetsMissing: false
    property bool pendingAssetsMissing: false
    property bool updating: false
    property string updateError: ""
    property double lastUpdateCheck: 0
    // Consented work: the first engine download or a model download.
    property bool installing: false
    property real installProgress: 0
    property string installLabel: ""

    // Dictation.
    property bool starting: false
    property bool listening: false
    property bool transcribing: false
    property bool finished: false
    property bool failed: false
    // Committed finals and the revisable partial of the running dictation.
    property var finals: []
    property string partialText: ""
    // What the overlay shows: the newest words of the running dictation, or the
    // finished text while "finished" shows; never part of stateJson().
    property string liveText: ""

    // Wake word and hotwords: drafts as typed, persisted once valid.
    property bool settingsLoaded: false
    property bool wakeEnabled: false
    property string wakePhrase: "hello computer"
    property string wakePhraseError: ""
    property string hotwordsText: ""
    property var hotwords: []
    property string hotwordsError: ""
    property string wakeError: ""

    readonly property bool ready: statusKnown && engineRevision.length > 0 && !currentAssetsMissing
    readonly property bool dictating: starting || listening || transcribing
    readonly property bool blocked: status === "blocked" || status === "error"
    // The microphone is open for the wake word: from arming until it is released.
    readonly property bool wakeListening: wakeOperation.length > 0 || wakePriming
    readonly property bool active: blocked || dictating || installing || wakeListening
    readonly property bool strong: blocked || installing
    readonly property string role: blocked || installing ? "warning" : (dictating || finished || wakeListening ? "ui.accent" : "ui.focus")
    readonly property string overlayState: starting ? "starting" : (listening ? "capturing" : (transcribing ? "transcribing" : (finished ? "finished" : (failed ? "failed" : ""))))
    readonly property bool busy: installing || dictating || maintenance
    readonly property bool wakeWanted: wakeEnabled && wakePhraseError === "" && wakePhrase.trim().length > 0 && ready && settingsLoaded && !installing
    readonly property string historyPath: Quickshell.statePath("noko-history.jsonl")
    readonly property string settingsPath: Quickshell.statePath("noko-settings.json")
    readonly property int historyLimit: 20
    // A forgotten capture ends itself; the engine lingers this long for the next one.
    property int captureLimitMs: 300000
    property int engineLingerMs: 60000
    // A capture the wake word started ends after this much silence, not the first pause.
    property int wakeSilenceMs: 2500
    readonly property int updateIntervalMs: 86400000

    // Engine process state.
    property string engineMode: ""
    property string engineRunningRevision: ""
    property bool engineOpen: false
    property bool engineStopping: false
    property var nextEngine: null
    property var rpcCallbacks: ({})
    property int rpcId: 0
    property string dictationOperation: ""
    property bool recognitionRequested: false
    property bool inputReady: false
    property bool stopRequested: false
    property bool wakeCapture: false
    property int speechFrames: 0
    property string wakeOperation: ""
    property bool wakeHit: false
    property bool wakeCancelling: false
    property bool wakePriming: false
    property string primeOperation: ""
    property bool primed: false
    property string armedPhrase: ""
    property bool maintenance: false
    property string maintenanceOperation: ""
    property real maintenanceBytes: 0
    property var assetProgress: ({})
    property bool unconfirmed: false
    property bool updateFailed: false

    // Setup is checked at startup, on every popup opening and on entering Config;
    // updates are looked for at startup and at most daily on opening, never while
    // closed. Opening also retries a wake word that stopped.
    function refresh(): string {
        if (!statusKnown && !busy)
            status = "checking";
        if (!statusProc.running)
            statusProc.exec(["nu", "--no-config-file", engineScript, "status"]);
        if (Date.now() - lastUpdateCheck >= updateIntervalMs)
            checkForUpdate();
        if (wakeError) {
            wakeError = "";
            Qt.callLater(settle);
        }
        return stateJson();
    }

    function checkForUpdate(): void {
        if (checkProc.running || installProc.running)
            return;
        lastUpdateCheck = Date.now();
        checkProc.exec(["nu", "--no-config-file", engineScript, "check"]);
    }

    // Consent: the first engine download, or the models an engine still needs.
    function install(): string {
        if (busy || installProc.running)
            return stateJson();
        lastError = "";
        if (engineRevision === "" && pendingRevision === "") {
            installing = true;
            installProgress = 0;
            installLabel = "downloading";
            status = "installing";
            installProc.exec(["nu", "--no-config-file", engineScript, "install"]);
            return stateJson();
        }
        const target = pendingAssetsMissing ? pendingRevision : (currentAssetsMissing ? engineRevision : "");
        if (!target)
            return stateJson();
        installing = true;
        maintenance = true;
        installProgress = 0;
        installLabel = "downloading";
        status = "installing";
        assetProgress = ({});
        maintenanceBytes = assetBytes;
        if (engineOpen && engineRunningRevision === target && !engineStopping)
            prepareAssets();
        else
            startEngine(target, target === engineRevision ? "current" : "candidate");
        return stateJson();
    }

    function trigger(): string {
        return starting || listening ? stopCapture() : startCapture();
    }

    function startCapture(): string {
        return beginDictation(false);
    }

    function beginDictation(fromWake: bool): string {
        if (busy)
            return stateJson();
        if (!ready)
            return refresh();
        starting = true;
        listening = false;
        transcribing = false;
        finished = false;
        failed = false;
        captureError = "";
        lastInsertError = "";
        finals = [];
        partialText = "";
        liveText = "";
        speechFrames = 0;
        inputReady = false;
        stopRequested = false;
        recognitionRequested = false;
        wakeCapture = fromWake;
        status = "listening";
        captureLimit.restart();
        engineLinger.stop();
        if (engineOpen && engineMode === "current" && !engineStopping)
            settle();
        else
            startEngine(engineRevision, "current");
        return stateJson();
    }

    function stopCapture(): string {
        if (!starting && !listening)
            return stateJson();
        starting = false;
        listening = false;
        transcribing = true;
        status = "transcribing";
        captureLimit.stop();
        wakeSilence.stop();
        if (dictationOperation)
            rpc("recognition.finish", {
                "operation": dictationOperation
            });
        else
            stopRequested = true;
        return stateJson();
    }

    // The seam between the final transcript and typing: a later cleanup step
    // rewrites the text here. Today it is typed as recognised.
    function refineTranscript(text: string): string {
        return text;
    }

    // The single decision point once the engine is open or an operation ended:
    // a waiting dictation starts, a staged update switches while idle, the wake
    // word re-arms, or the engine lingers and goes.
    function settle(): void {
        if (!engineOpen || engineStopping)
            return;
        if (engineMode === "candidate")
            return;
        // A wake request in flight has no operation to cancel yet: its answer settles again.
        if (wakePriming && !wakeOperation && !primeOperation)
            return;
        if (dictating) {
            if (wakeOperation || primeOperation) {
                cancelWake();
                return;
            }
            if (!dictationOperation && !recognitionRequested)
                sendRecognitionStart();
            return;
        }
        if (maintenance)
            return;
        if (pendingRevision && !pendingAssetsMissing && !updateFailed) {
            if (wakeOperation || primeOperation) {
                cancelWake();
                return;
            }
            startEngine(pendingRevision, "candidate");
            return;
        }
        if (wakeWanted && !wakeError) {
            if (!wakeOperation && !primeOperation)
                armWake();
            engineLinger.stop();
            return;
        }
        if (wakeOperation || primeOperation) {
            cancelWake();
            return;
        }
        engineLinger.restart();
    }

    function sendRecognitionStart(): void {
        recognitionRequested = true;
        rpc("recognition.start", Object.assign({
            "hotwords": hotwords
        }, recognitionOptions), (result, error) => {
            if (!dictating)
                return;
            if (!result || !result.operation) {
                failDictation(starting ? "microphone unavailable" : "transcription failed");
                settle();
                return;
            }
            dictationOperation = String(result.operation);
            if (stopRequested)
                rpc("recognition.finish", {
                    "operation": dictationOperation
                });
        });
    }

    // A fresh engine loads its recogniser on first use, which is slow; before
    // waiting for the wake word it runs one discarded recognition so a hit
    // captures at once.
    function armWake(): void {
        wakeHit = false;
        if (!primed) {
            wakePriming = true;
            rpc("recognition.start", Object.assign({
                "hotwords": hotwords
            }, recognitionOptions), result => {
                if (result && result.operation)
                    primeOperation = String(result.operation);
                else {
                    wakePriming = false;
                    wakeError = "wake word stopped";
                }
                // Wanted no longer, e.g. a dictation began meanwhile: cancel it.
                if (dictating || !wakeWanted)
                    settle();
            });
            return;
        }
        wakePriming = true;
        armedPhrase = wakePhrase.trim();
        rpc("wake.start", {
            "phrases": [armedPhrase]
        }, result => {
            wakePriming = false;
            if (result && result.operation)
                wakeOperation = String(result.operation);
            else
                wakeError = "wake phrase not recognised";
            settle();
        });
    }

    function cancelWake(): void {
        if (wakeCancelling)
            return;
        const operation = wakeOperation || primeOperation;
        if (!operation)
            return;
        wakeCancelling = true;
        rpc("operation.cancel", {
            "operation": operation
        });
    }

    function startEngine(revision: string, mode: string): void {
        engineLinger.stop();
        if (engineProc.running) {
            nextEngine = {
                "revision": revision,
                "mode": mode
            };
            stopEngine();
            return;
        }
        nextEngine = null;
        engineMode = mode;
        engineRunningRevision = revision;
        engineOpen = false;
        engineStopping = false;
        primed = false;
        rpcCallbacks = ({});
        engineProc.stdinEnabled = true;
        engineProc.exec(["nu", "--no-config-file", engineScript, "serve", revision]);
    }

    // Closing its input ends the engine; it settles its operations first.
    function stopEngine(): void {
        if (!engineProc.running || engineStopping)
            return;
        engineStopping = true;
        if (engineOpen)
            rpc("service.shutdown", {});
        engineProc.stdinEnabled = false;
    }

    function rpc(method: string, params: var, done: var): void {
        if (!engineProc.running)
            return;
        rpcId++;
        if (done)
            rpcCallbacks[rpcId] = done;
        engineProc.write(JSON.stringify({
            "jsonrpc": "2.0",
            "id": rpcId,
            "method": method,
            "params": params
        }) + "\n");
    }

    function engineStarted(): void {
        rpc("resource.open", {
            "profile": engineProfile
        }, result => {
            if (!result) {
                stopEngine();
                return;
            }
            engineOpen = true;
            rpc("pipeline.plan", {
                "action": "warm",
                "roles": engineRoles
            }, plan => applyPlan(plan && plan.plan));
        });
    }

    function applyPlan(plan: var): void {
        const missing = plan && Array.isArray(plan.missing) ? plan.missing : null;
        if (!missing) {
            stopEngine();
            return;
        }
        const bytes = Number(plan.download_bytes || 0);
        if (engineMode === "candidate") {
            if (missing.length === 0) {
                switchProc.exec(["nu", "--no-config-file", engineScript, "switch", engineRunningRevision]);
                return;
            }
            pendingAssetsMissing = true;
            assetBytes = bytes;
            if (maintenance) {
                prepareAssets();
                return;
            }
            // Held: the old engine keeps dictating until the models are installed.
            if (engineRevision && (dictating || wakeWanted))
                startEngine(engineRevision, "current");
            else
                stopEngine();
            return;
        }
        currentAssetsMissing = missing.length > 0;
        if (currentAssetsMissing) {
            assetBytes = bytes;
            if (maintenance) {
                prepareAssets();
                return;
            }
            if (dictating)
                failDictation("speech model missing");
            status = "blocked";
        } else if (!dictating && !installing)
            status = "ready";
        settle();
    }

    // Consented model download through the engine's own verified installer.
    function prepareAssets(): void {
        rpc("pipeline.prepare", {
            "roles": engineRoles
        }, result => {
            if (result && result.operation)
                maintenanceOperation = String(result.operation);
            else
                failInstall("speech model download failed");
        });
    }

    function applySwitch(revision: string): void {
        engineRevision = revision;
        pendingRevision = "";
        pendingAssetsMissing = false;
        currentAssetsMissing = false;
        assetBytes = 0;
        unconfirmed = true;
        engineMode = "current";
        if (installing) {
            installing = false;
            maintenance = false;
            installProgress = 1;
        }
        if (!dictating)
            status = "ready";
        settle();
    }

    function applyEngineLine(line: string): void {
        const message = parseJson(line);
        if (!message)
            return;
        if (message.id !== undefined && !message.method) {
            const done = rpcCallbacks[message.id];
            delete rpcCallbacks[message.id];
            if (done)
                done(message.result || null, message.error || null);
            return;
        }
        const params = message.params || {};
        const operation = String(params.operation || "");
        const data = params.data || {};
        if (operation && operation === dictationOperation)
            applyDictationEvent(String(message.method), data);
        else if (operation && operation === wakeOperation)
            applyWakeEvent(String(message.method), data);
        else if (operation && operation === primeOperation)
            applyPrimeEvent(String(message.method), data);
        else if (operation && operation === maintenanceOperation)
            applyMaintenanceEvent(String(message.method), data);
    }

    function applyDictationEvent(method: string, data: var): void {
        if (method === "pipeline.input.ready") {
            inputReady = true;
            if (starting) {
                starting = false;
                listening = true;
                if (wakeCapture)
                    wakeSilence.restart();
            }
        } else if (method === "pipeline.partial") {
            partialText = String(data.text || "");
            showLive();
        } else if (method === "pipeline.vad") {
            if (wakeCapture && listening) {
                if (data.speech === true)
                    wakeSilence.stop();
                else
                    wakeSilence.restart();
            }
        } else if (method === "pipeline.final") {
            const text = String(data.text || "").trim();
            if (text)
                finals = finals.concat([text]);
            speechFrames = Math.max(speechFrames, Number(data.end_frame || data.input_frames || 0));
            partialText = "";
            showLive();
            if (data.segment)
                rpc("recognition.ack", {
                    "operation": dictationOperation,
                    "segment": String(data.segment)
                });
        } else if (method === "pipeline.ended") {
            endDictation(String(data.outcome || "failed"));
        }
    }

    function showLive(): void {
        liveText = finals.concat(partialText ? [partialText] : []).join(" ").slice(-400);
    }

    function applyWakeEvent(method: string, data: var): void {
        if (method === "pipeline.keyword")
            wakeHit = true;
        else if (method === "pipeline.ended") {
            const hit = wakeHit && data.outcome === "completed";
            const cancelled = wakeCancelling;
            wakeOperation = "";
            wakeCancelling = false;
            wakeHit = false;
            // Live wake detection ends only on a hit or when told to.
            if (!hit && !cancelled)
                wakeError = "wake word stopped";
            if (hit && !dictating)
                beginDictation(true);
            else
                settle();
        }
    }

    function applyPrimeEvent(method: string, data: var): void {
        if (method === "pipeline.input.ready" && !wakeCancelling)
            rpc("recognition.finish", {
                "operation": primeOperation,
                "discard": true
            });
        else if (method === "pipeline.final" && data.segment)
            rpc("recognition.ack", {
                "operation": primeOperation,
                "segment": String(data.segment)
            });
        else if (method === "pipeline.ended") {
            primeOperation = "";
            wakePriming = false;
            const cancelled = wakeCancelling;
            wakeCancelling = false;
            if (data.outcome === "completed" && !cancelled)
                primed = true;
            else if (data.outcome === "failed")
                wakeError = "wake word stopped";
            settle();
        }
    }

    function applyMaintenanceEvent(method: string, data: var): void {
        if (method === "pipeline.asset") {
            const asset = String(data.asset || "");
            const total = Number(data.total_bytes || data.bytes || 0);
            const received = data.state === "ready" ? total : Number(data.received_bytes || 0);
            assetProgress[asset] = Math.min(received, total);
            let sum = 0;
            for (const key in assetProgress)
                sum += assetProgress[key];
            installProgress = maintenanceBytes > 0 ? Math.max(0, Math.min(1, sum / maintenanceBytes)) : 0;
            installLabel = data.state === "verifying" ? "verifying" : "downloading";
        } else if (method === "pipeline.ended") {
            maintenanceOperation = "";
            if (data.outcome !== "completed") {
                failInstall("speech model download failed");
                return;
            }
            installProgress = 1;
            rpc("pipeline.plan", {
                "action": "warm",
                "roles": engineRoles
            }, plan => {
                const missing = plan && plan.plan && Array.isArray(plan.plan.missing) ? plan.plan.missing : null;
                if (!missing || missing.length > 0) {
                    failInstall("speech model download failed");
                    return;
                }
                // The switch ends the installation (applySwitch).
                if (engineMode === "candidate")
                    switchProc.exec(["nu", "--no-config-file", engineScript, "switch", engineRunningRevision]);
                else {
                    maintenance = false;
                    installing = false;
                    currentAssetsMissing = false;
                    assetBytes = 0;
                    status = "ready";
                    settle();
                }
            });
        }
    }

    function endDictation(outcome: string): void {
        const text = finals.join(" ").replace(/\s+/g, " ").trim();
        const wasReady = inputReady;
        dictationOperation = "";
        recognitionRequested = false;
        if (outcome === "completed" && text) {
            deliver(refineTranscript(text));
            if (unconfirmed) {
                unconfirmed = false;
                confirmProc.exec(["nu", "--no-config-file", engineScript, "confirm"]);
            }
        } else if (outcome === "completed")
            failDictation("no speech heard");
        else
            failDictation(!wasReady ? "microphone unavailable" : (transcribing ? "transcription failed" : "microphone stopped"));
        settle();
    }

    function deliver(text: string): void {
        starting = false;
        listening = false;
        transcribing = false;
        captureLimit.stop();
        wakeSilence.stop();
        status = "ready";
        partialText = "";
        liveText = text.slice(-400);
        insertProcess.createObject(root, {
            "payload": text
        });
        historyEntries = [
            {
                "timestamp": new Date().toISOString(),
                "transcript": text,
                "duration": Math.round(speechFrames / 160) / 100
            }
        ].concat(historyEntries).slice(0, historyLimit);
        saveHistory();
        finished = true;
        finishedTimer.restart();
    }

    // A dictation that produced no text: said in the overlay and the panel, and
    // never dressed as finished.
    function failDictation(message: string): void {
        starting = false;
        listening = false;
        transcribing = false;
        finished = false;
        dictationOperation = "";
        recognitionRequested = false;
        captureLimit.stop();
        wakeSilence.stop();
        partialText = "";
        liveText = "";
        captureError = message;
        failed = true;
        failedTimer.restart();
        status = ready ? "ready" : "blocked";
    }

    function failInstall(message: string): void {
        installing = false;
        maintenance = false;
        maintenanceOperation = "";
        lastError = message;
        status = "error";
        settle();
    }

    function engineExited(): void {
        const intentional = engineStopping;
        const opened = engineOpen;
        const mode = engineMode;
        engineOpen = false;
        engineStopping = false;
        engineMode = "";
        rpcCallbacks = ({});
        wakeOperation = "";
        primeOperation = "";
        wakePriming = false;
        wakeCancelling = false;
        // An engine stopped to make way for the next one served neither.
        const replaced = nextEngine !== null;
        if (dictating && (dictationOperation || recognitionRequested || !replaced))
            failDictation("speech engine stopped");
        if (maintenance && (maintenanceOperation || !replaced))
            failInstall("speech model download stopped");
        if (!intentional && wakeWanted)
            wakeError = "wake word stopped";
        if (mode === "candidate" && !opened && !replaced) {
            // An update that cannot even start stays unused this session.
            updateFailed = true;
            lastError = "update failed to start";
        }
        if (mode === "current" && !opened && unconfirmed && !intentional) {
            unconfirmed = false;
            rollbackProc.exec(["nu", "--no-config-file", engineScript, "rollback"]);
            return;
        }
        if (replaced) {
            const next = nextEngine;
            startEngine(next.revision, next.mode);
        } else if (dictating || (wakeWanted && !wakeError))
            startEngine(engineRevision, "current");
    }

    function applyStatus(text: string): void {
        const report = parseJson(text.trim().split("\n").pop());
        lastChecked = new Date().toISOString();
        if (!report) {
            statusKnown = false;
            lastError = "speech engine check did not run";
            if (!busy)
                status = "error";
            return;
        }
        statusKnown = true;
        const installed = report.installed ? String(report.installed) : "";
        if (installed !== engineRevision && !dictating)
            engineRevision = installed;
        typingReady = report.typing === true;
        const staged = Array.isArray(report.staged) ? report.staged.map(String) : [];
        if (!pendingRevision && staged.length > 0)
            pendingRevision = staged[staged.length - 1];
        if (!busy)
            status = engineRevision && !currentAssetsMissing ? "ready" : "blocked";
        if (status === "ready" && lastError === "speech engine check did not run")
            lastError = "";
        settle();
        if (!engineProc.running && (wakeWanted && !wakeError || pendingRevision && !pendingAssetsMissing && !updateFailed))
            startEngine(engineRevision || pendingRevision, engineRevision ? "current" : "candidate");
    }

    function applyCheck(text: string): void {
        const report = parseJson(text.trim().split("\n").pop());
        if (!report || report.event !== "latest")
            return;
        latestRevision = String(report.revision || "");
        latestSize = Number(report.size || 0);
        // Updates come by themselves; a first install waits for consent.
        if (engineRevision && latestRevision && latestRevision !== engineRevision && latestRevision !== pendingRevision && !report.rejected && !installProc.running) {
            updating = true;
            installProc.exec(["nu", "--no-config-file", engineScript, "install"]);
        }
    }

    function applyInstallEvent(text: string): void {
        const event = parseJson(text);
        if (!event)
            return;
        if (installing && !maintenance) {
            if (event.label)
                installLabel = String(event.label);
            if (event.progress !== undefined)
                installProgress = Math.max(0, Math.min(1, Number(event.progress)));
        }
        if (event.event === "done" && event.revision)
            staged(String(event.revision));
    }

    // A downloaded revision: checked by running it while no dictation runs.
    function staged(revision: string): void {
        updating = false;
        updateError = "";
        if (revision === engineRevision)
            return;
        pendingRevision = revision;
        pendingAssetsMissing = false;
        updateFailed = false;
        if (installing && !maintenance) {
            // First install: the engine says which models it still needs.
            installing = false;
            installProgress = 1;
        }
        if (engineProc.running)
            settle();
        else if (!dictating)
            startEngine(revision, "candidate");
    }

    function failEngineInstall(text: string): void {
        updating = false;
        if (!installing || maintenance) {
            updateError = "update failed";
            return;
        }
        installing = false;
        lastError = text.trim().replace(/^noko-engine: /, "") || "speech engine download interrupted; retry";
        status = "error";
    }

    // Settings: one term per line, as the engine accepts them.
    function phraseProblem(term: string): string {
        if (/[\/@:#\u0000]/.test(term))
            return "drop / @ : #";
        let bytes = 0;
        for (const character of term) {
            const code = character.codePointAt(0);
            bytes += code < 0x80 ? 1 : (code < 0x800 ? 2 : (code < 0x10000 ? 3 : 4));
        }
        if (bytes > 200)
            return "too long";
        return "";
    }

    function editHotwords(text: string): void {
        hotwordsText = String(text);
        const terms = [];
        let problem = "";
        hotwordsText.split("\n").forEach((line, index) => {
            const term = line.trim().replace(/\s+/g, " ");
            if (!term || terms.indexOf(term) >= 0)
                return;
            const found = phraseProblem(term);
            if (found && !problem)
                problem = `line ${index + 1}: ${found}`;
            terms.push(term);
        });
        if (!problem && terms.length > 64)
            problem = "at most 64 terms";
        hotwordsError = problem;
        if (!problem) {
            hotwords = terms;
            saveSettingsTimer.restart();
        }
    }

    function editWakePhrase(text: string): void {
        wakePhrase = String(text);
        const phrase = wakePhrase.trim();
        wakePhraseError = !phrase ? "type a phrase to listen for" : phraseProblem(phrase);
        if (!wakePhraseError) {
            wakeError = "";
            saveSettingsTimer.restart();
        }
        // Typing re-arms once, after a pause, not on every key.
        wakePhraseSettle.restart();
    }

    function setWakeEnabled(enabled: bool): void {
        wakeEnabled = !!enabled;
        wakeError = "";
        saveSettingsTimer.restart();
        restartWake();
    }

    // A changed phrase or switch re-arms with it; off releases the microphone.
    function restartWake(): void {
        if (wakeOperation || primeOperation)
            cancelWake();
        else if (engineProc.running)
            settle();
        else if (wakeWanted)
            startEngine(engineRevision, "current");
    }

    function saveSettings(): void {
        settingsFile.setText(JSON.stringify({
            "hotwords": hotwords,
            "wakeEnabled": wakeEnabled,
            "wakePhrase": wakePhrase.trim()
        }) + "\n");
    }

    function loadSettingsText(text: string): void {
        const settings = parseJson(text) || ({});
        if (Array.isArray(settings.hotwords))
            editHotwords(settings.hotwords.map(String).join("\n"));
        if (typeof settings.wakePhrase === "string" && settings.wakePhrase.trim())
            wakePhrase = settings.wakePhrase;
        wakeEnabled = settings.wakeEnabled === true;
        saveSettingsTimer.stop();
        settingsLoaded = true;
        restartWake();
    }

    function saveHistory(): void {
        historyFile.setText(historyEntries.slice().reverse().map(row => JSON.stringify(row) + "\n").join(""));
    }

    function clearHistory(): void {
        historyEntries = [];
        saveHistory();
    }

    function loadHistoryText(text: string): void {
        const rows = [];
        for (const line of text.split("\n")) {
            const row = parseJson(line);
            if (row && row.transcript)
                rows.unshift(row);
        }
        historyEntries = rows.slice(0, historyLimit);
    }

    function copyTranscript(text): void {
        copyProcess.createObject(root, {
            "payload": String(text)
        });
    }

    function parseJson(text): var {
        try {
            const value = JSON.parse(String(text));
            return value !== null && typeof value === "object" ? value : null;
        } catch (error) {
            return null;
        }
    }

    // IPC and diagnostics: state only, never what was said, typed or listened for.
    function stateJson(): string {
        return JSON.stringify({
            "status": status,
            "ready": ready,
            "active": active,
            "strong": strong,
            "role": role,
            "overlayState": overlayState,
            "lastError": lastError,
            "lastChecked": lastChecked,
            "captureError": captureError,
            "historyCount": historyEntries.length,
            "installing": installing,
            "installProgress": installProgress,
            "installLabel": installLabel,
            "engineInstalled": engineRevision.length > 0,
            "updatePending": pendingRevision.length > 0,
            "updating": updating,
            "assetBytes": assetBytes,
            "wakeEnabled": wakeEnabled,
            "wakeListening": wakeListening,
            "hotwordCount": hotwords.length
        });
    }

    Component.onCompleted: refresh()

    FileView {
        id: historyFile
        path: root.historyPath
        blockWrites: true
        atomicWrites: true
        printErrors: false
        onLoaded: root.loadHistoryText(historyFile.text())
        onLoadFailed: root.historyEntries = []
    }

    FileView {
        id: settingsFile
        path: root.settingsPath
        blockWrites: true
        atomicWrites: true
        printErrors: false
        onLoaded: root.loadSettingsText(settingsFile.text())
        onLoadFailed: root.loadSettingsText("")
    }

    Timer {
        id: saveSettingsTimer

        interval: 400
        onTriggered: root.saveSettings()
    }

    Timer {
        id: wakePhraseSettle

        interval: 600
        // The same phrase stays armed: no needless release and reopening.
        onTriggered: if (!(root.wakeOperation && root.wakeWanted && root.armedPhrase === root.wakePhrase.trim()))
            root.restartWake()
    }

    Timer {
        id: finishedTimer

        interval: 1800
        onTriggered: {
            root.finished = false;
            if (!root.dictating)
                root.liveText = "";
        }
    }

    Timer {
        id: failedTimer

        interval: 2400
        onTriggered: root.failed = false
    }

    Timer {
        id: captureLimit

        interval: root.captureLimitMs
        onTriggered: root.stopCapture()
    }

    Timer {
        id: wakeSilence

        interval: root.wakeSilenceMs
        onTriggered: root.stopCapture()
    }

    Timer {
        id: engineLinger

        interval: root.engineLingerMs
        onTriggered: if (!root.dictating && !root.wakeListening && !root.maintenance)
            root.stopEngine()
    }

    Process {
        id: statusProc
        running: false
        stdout: StdioCollector {
            waitForEnd: true
            onStreamFinished: root.applyStatus(this.text)
        }
    }

    Process {
        id: checkProc
        running: false
        stdout: StdioCollector {
            waitForEnd: true
            onStreamFinished: root.applyCheck(this.text)
        }
    }

    Process {
        id: installProc
        running: false
        onExited: (code, exitStatus) => {
            if (code !== 0 || exitStatus !== 0)
                root.failEngineInstall(installErrors.text);
        }
        stdout: SplitParser {
            onRead: data => root.applyInstallEvent(data)
        }
        stderr: StdioCollector {
            id: installErrors

            waitForEnd: true
        }
    }

    Process {
        id: switchProc
        running: false
        stdout: StdioCollector {
            waitForEnd: true
            onStreamFinished: {
                const event = root.parseJson(this.text.trim());
                if (event && event.event === "switched")
                    root.applySwitch(String(event.revision));
                else {
                    root.updateFailed = true;
                    root.failInstall("update could not switch");
                }
            }
        }
    }

    Process {
        id: confirmProc
        running: false
    }

    Process {
        id: rollbackProc
        running: false
        onExited: root.refresh()
    }

    Process {
        id: engineProc
        running: false
        stdinEnabled: true
        onStarted: root.engineStarted()
        onRunningChanged: if (!running)
            root.engineExited()
        stdout: SplitParser {
            onRead: data => root.applyEngineLine(data)
        }
    }

    Component {
        id: copyProcess
        Process {
            property string payload
            command: ["wl-copy"]
            stdinEnabled: true
            running: true
            onStarted: {
                write(payload);
                stdinEnabled = false;
                payload = "";
            }
            onRunningChanged: if (!running)
                destroy()
        }
    }

    Component {
        id: insertProcess
        Process {
            property string payload
            command: ["wtype", "-"]
            stdinEnabled: true
            running: true
            onStarted: {
                write(payload);
                stdinEnabled = false;
                payload = "";
            }
            onRunningChanged: if (!running)
                destroy()
            stderr: StdioCollector {
                waitForEnd: true
                onStreamFinished: if (this.text.trim().length > 0)
                    root.lastInsertError = this.text.trim()
            }
        }
    }
}