Compare commits

...
17 Commits
Author SHA1 Message Date
darmanandClaude Opus 5.5 66760c1ded feat(terra): SUPER+V mutes luna's mic without cutting her off
The key now only opens and closes the mic. Her reply keeps playing, the
switch takes effect mid-turn (also while a tool-call reply is still
streaming), and a muted mic can't barge in. Muting mid-sentence sends what
was said so far, like releasing push-to-talk. The rail panel shows
MIC ON / MIC OFF and her own state even while muted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 00:01:48 +02:00
darmanandClaude Opus 5.5 efb690206b feat(terra): luna speaks with ElevenLabs v4 turbo
eleven_v4_turbo is the new default, same price per character as
v3_conversational. v4 also streams over Text to Dialogue, so the switch is
now uses_dialogue() for both. Audio tags may carry free-text directions
("[whispers, in a German accent]"): commas and apostrophes allowed, up to
80 chars. The voice prompt and luna-soul.md teach her the wider tag set,
including in text_to_speech voice notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 00:01:48 +02:00
darmanandClaude Opus 5.5 1209f165e9 feat(terra): bump claude-desktop to 2.42304.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 00:01:48 +02:00
darmanandClaude Opus 5.5 94b2b4695c feat(terra): reinstall tome with the license-denial fix
tome dropped out of home.packages in an auto-stash merge (6406e06). Its
NuGet lockfile also pinned 8.0.29/9.0.18 runtime packs, which the 10.0.401
SDK no longer accepts for Photino.NET's net8/net9 targets, so it no longer
built; regenerated with fetch-deps.

Bumps the tome input to 011a69e: 10-byte device serial (Audible denies
licenses to 20-byte ones since 2026-09) and denial reasons in the error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 00:00:26 +02:00
darmanandClaude Opus 5.5 4d33b92bbc feat(neptun): Quad9 fallback for tailnet DNS
mercury's tailscaled crash-looped on SD-card corruption and took DNS down on
every tailnet node, since pihole over the tailnet was the only global
nameserver. Cost: queries can skip pihole while mercury is slow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 23:32:37 +02:00
darmanandClaude Opus 5.5 e849827ebb feat(mercury): trim closure 2.9G → 1.6G; deploy with --use-substitutes
mercury drops the sd-image installer profile (rescue tools, ZFS), linux-firmware,
docs, installer tools and the nixpkgs registry pin — every deploy rewrites the
changed closure onto the SD card.

deploy switch/boot/test now passes --use-substitutes on all hosts: targets pull
cache hits themselves (compressed) instead of the laptop pushing uncompressed
NARs over ssh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 23:32:37 +02:00
darmanandClaude Opus 5.5 a05057a074 feat(terra): tbctl for the KB7/KP7/Kone II Air; bump flake inputs
CLI, GUI and the tbd daemon/agent from openbeach, pinned to a local
checkout for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:43:56 +02:00
darmanandClaude Opus 5.5 3debd6f7c2 feat(terra): bump claude-desktop to 2.37337.1
The native binding now links libpipewire directly, so pipewire moves
into buildInputs for autoPatchelf as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:43:56 +02:00
darmanandClaude Opus 5.5 059319cb1b feat(terra): release KB7/KP7 from host control on boot/replug
Adds turtle-beach-swarm-re as a flake input and enables its release
module, so a warm reboot from Windows no longer leaves the KB7 showing
Swarm's last streamed frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 19:54:53 +02:00
darmanandClaude Opus 5.5 d1afbba50c feat(terra): host permissions for Turtle Beach Swarm II RE
usbmon + wireshark group for USB capture, and uaccess on vendor 10f5
USB/hidraw nodes for QEMU passthrough and the RE tools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:15:30 +02:00
darmanandClaude Opus 5.5 eec1f33e96 feat(jupiter): shrink system closure for the 29G eMMC
Run immich and seerr as official images (their node/python stacks live in
podman's graphroot on the array), ship only the firmware the board loads,
and point jellyfin at intel-media-driver directly instead of
hardware.graphics (mesa + llvm).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:15:30 +02:00
darmanandClaude Opus 5.5 14f5e96f7e chore: bump flake inputs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:15:30 +02:00
darmanandClaude Opus 5.5 e46346c446 fix(terra): persist Claude Desktop logins via gnome-libsecret
Chromium doesn't recognise Hyprland as a desktop, falls back to the
basic_text password store, and logins are lost on restart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 20:18:54 +02:00
darmanandClaude Opus 5.5 9f9c5df790 feat(terra): give run0 5min to authenticate
run0 waits on systemd over D-Bus, and the 25s default call timeout ran
out while the polkit dialog was still open. Scoped to an alias so a hung
systemctl does not also wait 5min.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 18:49:36 +02:00
darmanandClaude Opus 5.5 acd08afaad feat(terra): Proton Pass picker in the polkit/askpass dialog
A collapsed panel under the dialog lists logins from every vault via
pass-cli, one tab per vault with overflow into a dropdown; picking one
fetches its password into the field. Listing never touches secrets, and
the `darman@<config>` items are `custom`, not `login`, so both types are
listed. Adds a show/hide toggle to the password field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 18:49:36 +02:00
darmanandClaude Opus 5.5 4b366f952e feat(terra): multilingual whisper small for luna's voice
base.en heard "backup" as "Mac up" and turned German into English nonsense.
small with -l auto gets both right at ~1s per turn (vs ~0.4s); turbo was
~2.3s for no visible gain. Drops the subtitle credits multilingual whisper
invents out of silence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011XkDJkdDzneVVdnkZfrvTY
2026-10-03 01:48:29 +02:00
darmanandClaude Opus 5.5 d4b6616d88 fix(mars): rotated keys reach every Hermes profile's .env
Named profiles keep their own .env, so coder kept the old OpenCode key and
librarian, with no OPENCODE line at all, was left on an exhausted pool entry.
The OpenCode key now goes to every profile; other keys only to profiles that
already carry them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011XkDJkdDzneVVdnkZfrvTY
2026-10-03 01:48:29 +02:00
31 changed files with 1686 additions and 486 deletions
@@ -64,6 +64,8 @@ Scope {
root.promptText = message === "" ? "Password:" : message; root.promptText = message === "" ? "Password:" : message;
root.fifoPath = fifo; root.fifoPath = fifo;
root.failed = false; root.failed = false;
vault.invalidate();
vault.refresh();
return "ok"; return "ok";
} }
@@ -101,12 +103,22 @@ Scope {
if (!root.active) if (!root.active)
return; return;
vault.invalidate();
root.pendingSecret = secret + "\n"; root.pendingSecret = secret + "\n";
writer.command = ["sh", "-c", "IFS= read -r line; printf %s \"$line\" > \"$1\"", "sh", root.fifoPath]; writer.command = ["sh", "-c", "IFS= read -r line; printf %s \"$line\" > \"$1\"", "sh", root.fifoPath];
writer.running = true; writer.running = true;
root.fifoPath = ""; root.fifoPath = "";
} }
ProtonPass {
id: vault
onFetched: secret => {
content.response = secret;
content.focusInput();
}
}
// Opening a fifo for writing BLOCKS until a reader attaches, which is why // Opening a fifo for writing BLOCKS until a reader attaches, which is why
// this is a subprocess rather than a FileView: the helper's `cat` is that // this is a subprocess rather than a FileView: the helper's `cat` is that
// reader, and blocking the QML thread on it would freeze the shell. // reader, and blocking the QML thread on it would freeze the shell.
@@ -149,7 +161,7 @@ Scope {
id: content id: content
anchors.horizontalCenter: parent.horizontalCenter anchors.horizontalCenter: parent.horizontalCenter
y: Math.max(32, Math.round(parent.height / 3 - height / 2)) y: Math.max(32, Math.round(parent.height / 3 - content.dialogHeight / 2))
width: 520 width: 520
// Deliberately the polkit dialog's own content component: this is a // Deliberately the polkit dialog's own content component: this is a
@@ -168,6 +180,17 @@ Scope {
responseVisible: false responseVisible: false
failed: root.failed failed: root.failed
credentialsEnabled: true
credentials: vault.entries
credentialsStatus: vault.listStatus
fetchStatus: vault.fetchStatus
onCredentialRequested: entry => vault.fetch(entry)
onPickerOpened: {
if (vault.entries.length === 0)
vault.refresh();
}
onSubmitted: value => root.submit(value) onSubmitted: value => root.submit(value)
onCancelled: root.dismiss() onCancelled: root.dismiss()
} }
@@ -32,7 +32,7 @@ BarPanel {
panelId: "LUN" panelId: "LUN"
title: "LUNA" title: "LUNA"
meta: luna.active ? "VOICE" : "IDLE" meta: luna.active ? "MIC ON" : "MIC OFF"
// Sized to content like the tray, and per DENSITY: collapsed it is one // Sized to content like the tray, and per DENSITY: collapsed it is one
// word, so reserving the expanded body's width would leave the rail // word, so reserving the expanded body's width would leave the rail
@@ -61,8 +61,7 @@ BarPanel {
readonly property string stateLabel: { readonly property string stateLabel: {
if (!luna.connected) if (!luna.connected)
return "OFFLINE"; return "OFFLINE";
if (!luna.active) // Her own state first: a muted mic no longer stops her answering.
return "OFF";
switch (luna.daemonState) { switch (luna.daemonState) {
case "listening": case "listening":
return "LISTENING"; return "LISTENING";
@@ -71,7 +70,7 @@ BarPanel {
case "speaking": case "speaking":
return "SPEAKING"; return "SPEAKING";
default: default:
return "READY"; return luna.active ? "READY" : "MUTED";
} }
} }
@@ -21,7 +21,7 @@ QtObject {
// "idle" | "listening" | "thinking" | "speaking" // "idle" | "listening" | "thinking" | "speaking"
property string state: "idle" property string state: "idle"
// Voice mode itself — the widget is only on screen while this is true. // Whether the mic is open. She still answers and speaks while it is not.
property bool active: false property bool active: false
// Set by the first line, not by the process starting: the daemon replays // Set by the first line, not by the process starting: the daemon replays
// its state on connect, so only a live connection produces one. // its state on connect, so only a live connection produces one.
@@ -26,6 +26,8 @@ Item {
property string panelId: "" property string panelId: ""
property string title: "" property string title: ""
property string meta: "" property string meta: ""
// Header strip only: body and header rule hidden.
property bool collapsed: false
property int chamfer: 16 property int chamfer: 16
property int padding: 14 property int padding: 14
@@ -54,7 +56,7 @@ Item {
default property alias content: body.data default property alias content: body.data
implicitHeight: Math.round(body.y + body.height + panel.padding) implicitHeight: panel.collapsed ? panel.headerHeight : Math.round(body.y + body.height + panel.padding)
Shape { Shape {
id: panelShape id: panelShape
@@ -181,6 +183,7 @@ Item {
// Header rule. // Header rule.
Rectangle { Rectangle {
visible: !panel.collapsed
x: 1 x: 1
y: panel.headerHeight y: panel.headerHeight
width: parent.width - 2 width: parent.width - 2
@@ -194,6 +197,7 @@ Item {
Item { Item {
id: body id: body
visible: !panel.collapsed
x: panel.padding x: panel.padding
y: panel.headerHeight + panel.headerGap y: panel.headerHeight + panel.headerGap
width: Math.max(0, panel.width - panel.padding * 2) width: Math.max(0, panel.width - panel.padding * 2)
@@ -87,9 +87,22 @@ Scope {
// never appears. Leaving it orphaned costs one hung caller; cancelling it // never appears. Leaving it orphaned costs one hung caller; cancelling it
// costs the prompt as well. // costs the prompt as well.
onFlowChanged: { onFlowChanged: {
vault.invalidate();
if (root.flow) { if (root.flow) {
content.clearResponse(); content.clearResponse();
content.focusInput(); content.focusInput();
// Prefetched so Tab is instant; the list stays from the last
// request while this refreshes.
vault.refresh();
}
}
ProtonPass {
id: vault
onFetched: secret => {
content.response = secret;
content.focusInput();
} }
} }
@@ -194,7 +207,7 @@ Scope {
// line appears. Floored at the same margin the width leaves, so a // line appears. Floored at the same margin the width leaves, so a
// tall prompt on a short output cannot be pushed off the top. // tall prompt on a short output cannot be pushed off the top.
anchors.horizontalCenter: parent.horizontalCenter anchors.horizontalCenter: parent.horizontalCenter
y: Math.max(32, Math.round(parent.height / 3 - height / 2)) y: Math.max(32, Math.round(parent.height / 3 - content.dialogHeight / 2))
width: 520 width: 520
message: root.flow ? root.flow.message : "" message: root.flow ? root.flow.message : ""
@@ -209,6 +222,17 @@ Scope {
supplementaryIsError: root.flow ? root.flow.supplementaryIsError : false supplementaryIsError: root.flow ? root.flow.supplementaryIsError : false
failed: root.flow ? root.flow.failed : false failed: root.flow ? root.flow.failed : false
credentialsEnabled: true
credentials: vault.entries
credentialsStatus: vault.listStatus
fetchStatus: vault.fetchStatus
onCredentialRequested: entry => vault.fetch(entry)
onPickerOpened: {
if (vault.entries.length === 0)
vault.refresh();
}
onSubmitted: value => { onSubmitted: value => {
if (root.flow) if (root.flow)
root.flow.submit(value); root.flow.submit(value);
@@ -235,8 +259,10 @@ Scope {
enabled: root.flow !== null enabled: root.flow !== null
function onFailedChanged() { function onFailedChanged() {
if (root.flow.failed) if (root.flow.failed) {
vault.invalidate();
content.clearResponse(); content.clearResponse();
}
} }
// Re-focus when the conversation asks for something. This is load // Re-focus when the conversation asks for something. This is load
@@ -46,15 +46,163 @@ Item {
property alias response: responseInput.text property alias response: responseInput.text
// Masking override from the eye toggle; reset with the field, so a
// revealed password never carries over to the next request.
property bool revealed: false
// Proton Pass logins, in their own panel under the dialog, collapsed until
// Tab. Entries need only `title` and `vault`; the adapter fetches the
// password for the one picked, so no secret is ever in this list. Off by
// default, as in the headless render.
property bool credentialsEnabled: false
property var credentials: []
// Picker-only: loading / listing failure. fetchStatus shows regardless —
// it is what explains an empty field after a pick.
property string credentialsStatus: ""
property string fetchStatus: ""
property bool pickerOpen: false
property int pickerIndex: 0
// Vault the list is narrowed to; "" is all of them. Kept across requests,
// so a vault picked once stays picked.
property string vaultFilter: ""
property bool overflowMenuOpen: false
// Height of the dialog alone. The adapters position on this rather than
// implicitHeight, so expanding the vault panel grows downward instead of
// shifting the dialog up under the cursor.
readonly property real dialogHeight: panel.implicitHeight
readonly property var vaultNames: {
const names = [];
for (const c of root.credentials)
if (!names.includes(c.vault))
names.push(c.vault);
return names.sort((a, b) => a.toLowerCase() < b.toLowerCase() ? -1 : a.toLowerCase() > b.toLowerCase() ? 1 : 0);
}
readonly property var vaultOptions: [""].concat(root.vaultNames)
// A remembered vault that no longer exists falls back to all.
readonly property string activeVault: root.vaultNames.includes(root.vaultFilter) ? root.vaultFilter : ""
// Title A–Z within the chosen vault (or across all of them).
readonly property var shownCredentials: {
const q = filterInput.text.toLowerCase();
return root.credentials
.filter(c => (root.activeVault === "" || c.vault === root.activeVault)
&& (q === "" || c.title.toLowerCase().includes(q)))
.sort((a, b) => {
const ta = a.title.toLowerCase(), tb = b.title.toLowerCase();
return ta < tb ? -1 : ta > tb ? 1 : 0;
});
}
function vaultLabel(name) {
return name === "" ? "ALL" : name.toUpperCase();
}
function vaultCount(name) {
return name === "" ? root.credentials.length : root.credentials.filter(c => c.vault === name).length;
}
function tabText(name) {
return root.vaultLabel(name) + " " + root.vaultCount(name);
}
// Tabs are sized from FontMetrics rather than their own implicitWidth, so
// how many fit is known before any are laid out — the overflow split
// would otherwise depend on the very tabs it decides to create.
function tabWidth(text) {
return Math.ceil(tabMetrics.advanceWidth(text) + text.length * tabMetrics.font.letterSpacing) + 16;
}
// How many leading vault options get a tab of their own; the rest go in
// the overflow menu, which is always the last tab.
//
// The overflow tab names the selected vault when it holds it, so it is
// sized for "MORE" first and, if the selection lands in the overflow,
// re-split for that label. Shrinking can only push the selection further
// into the overflow, so the second pass is final.
readonly property int fittingTabs: {
const avail = tabStrip.width;
const widths = root.vaultOptions.map(v => root.tabWidth(root.tabText(v)));
if (widths.reduce((a, b) => a + b, 0) <= avail)
return widths.length;
const split = reserve => {
let used = reserve, k = 0;
while (k < widths.length && used + widths[k] <= avail)
used += widths[k++];
return Math.max(1, k);
};
const k = split(root.tabWidth("MORE ▾"));
return root.vaultOptions.indexOf(root.activeVault) >= k
? split(root.tabWidth(root.tabText(root.activeVault) + " ▾")) : k;
}
readonly property var overflowVaults: root.vaultOptions.slice(root.fittingTabs)
signal submitted(string value) signal submitted(string value)
signal cancelled signal cancelled
signal identityRequested(int index) signal identityRequested(int index)
signal credentialRequested(var entry)
signal pickerOpened
function focusInput() { responseInput.forceActiveFocus(); } function focusInput() { responseInput.forceActiveFocus(); }
function clearResponse() { responseInput.text = ""; } function clearResponse() {
responseInput.text = "";
root.revealed = false;
root.closePicker();
}
function openPicker() {
if (!root.credentialsEnabled)
return;
filterInput.text = "";
root.pickerIndex = 0;
root.overflowMenuOpen = false;
root.pickerOpen = true;
filterInput.forceActiveFocus();
root.pickerOpened();
}
function closePicker() {
if (!root.pickerOpen)
return;
root.overflowMenuOpen = false;
root.pickerOpen = false;
root.focusInput();
}
function selectVault(index) {
root.vaultFilter = root.vaultOptions[index] || "";
root.overflowMenuOpen = false;
root.pickerIndex = 0;
pickerList.positionViewAtBeginning();
filterInput.forceActiveFocus();
}
function cycleVault(delta) {
const n = root.vaultOptions.length;
root.selectVault((Math.max(0, root.vaultOptions.indexOf(root.activeVault)) + delta + n) % n);
}
function pick(index) {
const entry = root.shownCredentials[index];
if (!entry)
return;
root.closePicker();
root.credentialRequested(entry);
}
function movePicker(delta) {
const n = root.shownCredentials.length;
if (n > 0)
root.pickerIndex = (root.pickerIndex + delta + n) % n;
}
onPickerIndexChanged: pickerList.positionViewAtIndex(root.pickerIndex, ListView.Contain)
implicitWidth: 520 implicitWidth: 520
implicitHeight: panel.implicitHeight implicitHeight: stack.implicitHeight
// Escape reaches here by propagating up the focus chain from the TextInput, // Escape reaches here by propagating up the focus chain from the TextInput,
// which does not consume it — so cancelling works whether or not the input // which does not consume it — so cancelling works whether or not the input
@@ -72,185 +220,558 @@ Item {
elide: Text.ElideRight elide: Text.ElideRight
} }
PolkitPanel { // A vault tab. Sized by the caller from tabWidth(), not by its label: the
id: panel // overflow split is computed before any tab exists.
component VaultTab: Item {
id: tab
property string label: ""
property bool current: false
signal clicked
MicroText {
anchors.centerIn: parent
text: tab.label
color: tab.current ? Theme.accent
: tabArea.containsMouse ? Theme.text : Theme.muted
}
Rectangle {
visible: tab.current
anchors.bottom: parent.bottom
width: parent.width
height: 2
color: Theme.accent
}
MouseArea {
id: tabArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: tab.clicked()
}
}
Column {
id: stack
width: root.width width: root.width
panelId: "PKT" // Clears the detached corner caps between the two panels.
title: "AUTHORIZATION REQUIRED" spacing: 14
// The action id is the one piece that says WHAT is being authorized
// independently of the (localizable, often vague) message.
meta: root.actionId
// The body slot decides the width and the layout's implicitHeight PolkitPanel {
// becomes its height, so a wrapped message or an extra pam_info line id: panel
// grows the panel instead of being clipped.
ColumnLayout {
width: parent.width
spacing: 10
// ---- what is being asked ---- width: root.width
RowLayout { panelId: "PKT"
Layout.fillWidth: true title: "AUTHORIZATION REQUIRED"
// The action id is the one piece that says WHAT is being authorized
// independently of the (localizable, often vague) message.
meta: root.actionId
// The body slot decides the width and the layout's implicitHeight
// becomes its height, so a wrapped message or an extra pam_info line
// grows the panel instead of being clipped.
ColumnLayout {
width: parent.width
spacing: 10 spacing: 10
IconImage { // ---- what is being asked ----
visible: root.showIcon && root.iconName !== ""
implicitSize: 32
source: root.showIcon && root.iconName !== ""
? Quickshell.iconPath(root.iconName, "dialog-password")
: ""
}
Text {
Layout.fillWidth: true
wrapMode: Text.Wrap
text: root.message
color: Theme.text
font.family: Theme.displayFont
font.pixelSize: 13
font.letterSpacing: 0.6
}
}
// ---- identity ----
// Single identity: stated, not offered. Several: chips, because a
// combo box would be the only QtQuick.Controls widget in the rail.
MicroText {
Layout.fillWidth: true
visible: root.identities.length === 1
text: "AS " + (root.identities.length === 1
? root.identities[0].displayName : "")
}
Flow {
Layout.fillWidth: true
visible: root.identities.length > 1
spacing: 6
Repeater {
model: root.identities
Rectangle {
id: chip
required property int index
required property var modelData
readonly property bool current: chip.index === root.selectedIdentity
width: chipLabel.implicitWidth + 14
height: chipLabel.implicitHeight + 8
color: chip.current ? Theme.accent : "transparent"
border.width: 1
border.color: chip.current ? Theme.accent : Theme.disabled
Text {
id: chipLabel
anchors.centerIn: parent
text: chip.modelData.displayName
color: chip.current ? Theme.surface : Theme.muted
font.family: Theme.microFont
font.pixelSize: 9
font.letterSpacing: 0.8
}
MouseArea {
anchors.fill: parent
onClicked: root.identityRequested(chip.index)
}
}
}
}
// ---- the conversation ----
Rectangle {
Layout.fillWidth: true
implicitHeight: 34
color: Theme.selection
border.width: 1
border.color: root.failed ? Theme.hot : Theme.hair
RowLayout { RowLayout {
anchors.fill: parent Layout.fillWidth: true
anchors.leftMargin: 10
anchors.rightMargin: 10
spacing: 10 spacing: 10
Text { IconImage {
text: ">_" visible: root.showIcon && root.iconName !== ""
color: root.responseRequired ? Theme.accent : Theme.disabled implicitSize: 32
font.family: Theme.displayFont source: root.showIcon && root.iconName !== ""
font.pixelSize: 15 ? Quickshell.iconPath(root.iconName, "dialog-password")
font.bold: true : ""
} }
TextInput { Text {
id: responseInput Layout.fillWidth: true
wrapMode: Text.Wrap
text: root.message
color: Theme.text
font.family: Theme.displayFont
font.pixelSize: 13
font.letterSpacing: 0.6
}
}
// ---- identity ----
// Single identity: stated, not offered. Several: chips, because a
// combo box would be the only QtQuick.Controls widget in the rail.
MicroText {
Layout.fillWidth: true
visible: root.identities.length === 1
text: "AS " + (root.identities.length === 1
? root.identities[0].displayName : "")
}
Flow {
Layout.fillWidth: true
visible: root.identities.length > 1
spacing: 6
Repeater {
model: root.identities
Rectangle {
id: chip
required property int index
required property var modelData
readonly property bool current: chip.index === root.selectedIdentity
width: chipLabel.implicitWidth + 14
height: chipLabel.implicitHeight + 8
color: chip.current ? Theme.accent : "transparent"
border.width: 1
border.color: chip.current ? Theme.accent : Theme.disabled
Text {
id: chipLabel
anchors.centerIn: parent
text: chip.modelData.displayName
color: chip.current ? Theme.surface : Theme.muted
font.family: Theme.microFont
font.pixelSize: 9
font.letterSpacing: 0.8
}
MouseArea {
anchors.fill: parent
onClicked: root.identityRequested(chip.index)
}
}
}
}
// ---- the conversation ----
Rectangle {
Layout.fillWidth: true
implicitHeight: 34
color: Theme.selection
border.width: 1
border.color: root.failed ? Theme.hot : Theme.hair
RowLayout {
anchors.fill: parent
anchors.leftMargin: 10
anchors.rightMargin: 10
spacing: 10
Text {
text: ">_"
color: root.responseRequired ? Theme.accent : Theme.disabled
font.family: Theme.displayFont
font.pixelSize: 15
font.bold: true
}
TextInput {
id: responseInput
Layout.fillWidth: true
Layout.fillHeight: true
verticalAlignment: TextInput.AlignVCenter
enabled: root.responseRequired
color: Theme.text
selectionColor: Theme.accent
selectedTextColor: Theme.surface
font.family: Theme.displayFont
font.pixelSize: 14
font.letterSpacing: 1
clip: true
echoMode: root.responseVisible || root.revealed
? TextInput.Normal : TextInput.Password
passwordCharacter: "▪"
// Qt reveals the last typed character for a moment by
// default. On a screen-visible layer-shell overlay
// that is a shoulder-surfing hole, so: never.
passwordMaskDelay: 0
onAccepted: {
if (root.responseRequired)
root.submitted(responseInput.text);
}
Keys.onTabPressed: event => {
root.openPicker();
event.accepted = true;
}
// Placeholder: TextInput has none of its own, and the
// PAM prompt ("Password:", "PIN:") is the only label
// this field gets.
Text {
anchors.verticalCenter: parent.verticalCenter
visible: responseInput.text.length === 0
text: root.inputPrompt
color: Theme.disabled
font: responseInput.font
}
}
// Eye toggle. Hidden when PAM already asked for echoed
// input — there is nothing left to reveal.
Text {
visible: !root.responseVisible
text: root.revealed ? "" : ""
color: root.revealed ? Theme.accent : (eyeArea.containsMouse ? Theme.text : Theme.muted)
font.family: Theme.displayFont
font.pixelSize: 14
MouseArea {
id: eyeArea
anchors.fill: parent
anchors.margins: -6
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: {
root.revealed = !root.revealed;
root.focusInput();
}
}
}
}
}
MicroText {
Layout.fillWidth: true
visible: root.credentialsEnabled && root.fetchStatus !== ""
text: root.fetchStatus
}
// ---- pam_info / pam_error ----
Text {
Layout.fillWidth: true
visible: root.supplementaryMessage !== ""
wrapMode: Text.Wrap
text: root.supplementaryMessage
color: root.supplementaryIsError ? Theme.hot : Theme.muted
font.family: Theme.microFont
font.pixelSize: 9
font.letterSpacing: 0.7
}
// ---- key hints ----
RowLayout {
Layout.fillWidth: true
spacing: 14
MicroText { text: "ENTER AUTHENTICATE" }
MicroText { text: "ESC CANCEL" }
Item { Layout.fillWidth: true }
MicroText {
text: root.responseVisible ? "ECHO ON" : root.revealed ? "SHOWN" : ""
color: Theme.hot
}
}
}
}
// ---- Proton Pass ----
// Its own panel so the dialog keeps its shape; collapsed it is the header
// strip alone. The MouseArea sits over that strip only — PolkitPanel's
// default property is the body slot, so it cannot live inside the panel.
Item {
visible: root.credentialsEnabled
width: root.width
height: vaultPanel.implicitHeight
PolkitPanel {
id: vaultPanel
width: parent.width
panelId: "PSS"
title: "PROTON PASS"
collapsed: !root.pickerOpen
meta: root.pickerOpen
? root.shownCredentials.length + " / " + root.credentials.length
: "TAB OPEN"
ColumnLayout {
width: parent.width
spacing: 6
// ---- vault tabs ----
// One row; tabs that do not fit move into the overflow
// tab's menu. z above the filter and list, which the open
// menu draws over.
Item {
id: tabStrip
z: 2
Layout.fillWidth: true
implicitHeight: 22
FontMetrics {
id: tabMetrics
font.family: Theme.microFont
font.pixelSize: 8
font.letterSpacing: 0.9
}
// The rule the tabs sit on, across the full width.
Rectangle {
anchors.bottom: parent.bottom
width: parent.width
height: 1
color: Theme.hair
}
Row {
Repeater {
model: root.vaultOptions.slice(0, root.fittingTabs)
VaultTab {
id: vaultTab
required property int index
required property string modelData
width: root.tabWidth(vaultTab.label)
height: tabStrip.height
label: root.tabText(vaultTab.modelData)
current: vaultTab.modelData === root.activeVault
onClicked: root.selectVault(vaultTab.index)
}
}
VaultTab {
id: overflowTab
readonly property bool holdsActive: root.overflowVaults.includes(root.activeVault)
visible: root.overflowVaults.length > 0
width: root.tabWidth(overflowTab.label)
height: tabStrip.height
// Names the selected vault when it is one of
// the hidden ones, so the selection stays visible.
label: (overflowTab.holdsActive ? root.tabText(root.activeVault) : "MORE") + " ▾"
current: overflowTab.holdsActive || root.overflowMenuOpen
onClicked: root.overflowMenuOpen = !root.overflowMenuOpen
Rectangle {
visible: root.overflowMenuOpen
// Right-aligned to the tab, clamped to the strip.
x: Math.max(-overflowTab.x, overflowTab.width - width)
y: overflowTab.height + 2
width: Math.max(180, overflowTab.width)
height: overflowColumn.implicitHeight + 2
color: Theme.surface
border.width: 1
border.color: Theme.accent
Column {
id: overflowColumn
x: 1
y: 1
width: parent.width - 2
Repeater {
model: root.overflowVaults
Rectangle {
id: option
required property int index
required property string modelData
readonly property bool current: option.modelData === root.activeVault
width: overflowColumn.width
height: 22
color: optionArea.containsMouse ? Theme.selection : "transparent"
Rectangle {
visible: option.current
width: 2
height: parent.height
color: Theme.accent
}
MicroText {
anchors.left: parent.left
anchors.leftMargin: 10
anchors.verticalCenter: parent.verticalCenter
text: root.vaultLabel(option.modelData)
color: option.current ? Theme.accent
: optionArea.containsMouse ? Theme.text : Theme.muted
}
MicroText {
anchors.right: parent.right
anchors.rightMargin: 8
anchors.verticalCenter: parent.verticalCenter
text: root.vaultCount(option.modelData)
}
MouseArea {
id: optionArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: root.selectVault(root.fittingTabs + option.index)
}
}
}
}
}
}
}
}
RowLayout {
Layout.fillWidth: true
spacing: 8
TextInput {
id: filterInput
Layout.fillWidth: true
color: Theme.text
selectionColor: Theme.accent
selectedTextColor: Theme.surface
font.family: Theme.displayFont
font.pixelSize: 12
clip: true
onTextChanged: root.pickerIndex = 0
onAccepted: root.pick(root.pickerIndex)
// Consumed so Esc backs out of the panel instead
// of cancelling the whole request.
Keys.onEscapePressed: event => {
if (root.overflowMenuOpen)
root.overflowMenuOpen = false;
else
root.closePicker();
event.accepted = true;
}
Keys.onTabPressed: event => {
root.cycleVault(1);
event.accepted = true;
}
Keys.onBacktabPressed: event => {
root.cycleVault(-1);
event.accepted = true;
}
Keys.onUpPressed: event => {
root.movePicker(-1);
event.accepted = true;
}
Keys.onDownPressed: event => {
root.movePicker(1);
event.accepted = true;
}
Text {
anchors.verticalCenter: parent.verticalCenter
visible: filterInput.text.length === 0
text: "filter logins"
color: Theme.disabled
font: filterInput.font
}
}
}
MicroText {
Layout.fillWidth: true
visible: text !== ""
text: root.credentialsStatus !== "" ? root.credentialsStatus
: root.shownCredentials.length === 0 ? "NO MATCH" : ""
}
ListView {
id: pickerList
readonly property int rowHeight: 24
Layout.fillWidth: true Layout.fillWidth: true
Layout.fillHeight: true implicitHeight: Math.min(count, 10) * rowHeight
verticalAlignment: TextInput.AlignVCenter visible: count > 0
enabled: root.responseRequired
color: Theme.text
selectionColor: Theme.accent
selectedTextColor: Theme.surface
font.family: Theme.displayFont
font.pixelSize: 14
font.letterSpacing: 1
clip: true clip: true
boundsBehavior: Flickable.StopAtBounds
model: root.shownCredentials
echoMode: root.responseVisible delegate: Rectangle {
? TextInput.Normal : TextInput.Password id: row
passwordCharacter: "▪"
// Qt reveals the last typed character for a moment by
// default. On a screen-visible layer-shell overlay
// that is a shoulder-surfing hole, so: never.
passwordMaskDelay: 0
onAccepted: { required property int index
if (root.responseRequired) required property var modelData
root.submitted(responseInput.text);
readonly property bool current: row.index === root.pickerIndex
width: pickerList.width
height: pickerList.rowHeight
color: row.current ? Theme.selection : "transparent"
Rectangle {
visible: row.current
width: 2
height: parent.height
color: Theme.accent
}
RowLayout {
anchors.fill: parent
anchors.leftMargin: 10
anchors.rightMargin: 6
spacing: 10
Text {
Layout.fillWidth: true
text: row.modelData.title
elide: Text.ElideRight
color: row.current ? Theme.text : Theme.muted
font.family: Theme.displayFont
font.pixelSize: 12
}
// Only useful when the list spans vaults.
MicroText {
visible: root.activeVault === ""
text: row.modelData.vault.toUpperCase()
}
}
MouseArea {
anchors.fill: parent
onClicked: root.pick(row.index)
}
} }
}
// Placeholder: TextInput has none of its own, and the RowLayout {
// PAM prompt ("Password:", "PIN:") is the only label Layout.fillWidth: true
// this field gets. spacing: 14
Text {
anchors.verticalCenter: parent.verticalCenter MicroText { text: "↑↓ SELECT" }
visible: responseInput.text.length === 0 MicroText { text: "ENTER FILL" }
text: root.inputPrompt MicroText { text: "TAB VAULT" }
color: Theme.disabled MicroText { text: "ESC BACK" }
font: responseInput.font
}
} }
} }
} }
// ---- pam_info / pam_error ---- MouseArea {
Text { width: parent.width
Layout.fillWidth: true height: vaultPanel.headerHeight
visible: root.supplementaryMessage !== "" cursorShape: Qt.PointingHandCursor
wrapMode: Text.Wrap onClicked: root.pickerOpen ? root.closePicker() : root.openPicker()
text: root.supplementaryMessage
color: root.supplementaryIsError ? Theme.hot : Theme.muted
font.family: Theme.microFont
font.pixelSize: 9
font.letterSpacing: 0.7
}
// ---- key hints ----
RowLayout {
Layout.fillWidth: true
spacing: 14
MicroText { text: "ENTER AUTHENTICATE" }
MicroText { text: "ESC CANCEL" }
Item { Layout.fillWidth: true }
MicroText {
text: root.responseVisible ? "ECHO ON" : ""
color: Theme.hot
}
} }
} }
} }
@@ -0,0 +1,176 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Io
// Proton Pass logins for the polkit and askpass prompts, via pass-cli.
//
// Listing never touches a secret: `item list` without --show-secrets returns
// ids and titles only. A password is fetched on its own, for one item, after
// the user picks it — and read through a SplitParser rather than a
// StdioCollector, which would keep it in its `text` property afterwards.
//
// `item list` refuses to run without a vault, so "all vaults" is one call per
// vault. Each takes ~0.8s, hence run in parallel by a single shell script.
QtObject {
id: root
// {shareId, id, title, vault}, unsorted — the dialog orders and groups them.
property var entries: []
// Why the list is empty or incomplete; "" when it is fine.
property string error: ""
property string fetchError: ""
readonly property bool loading: vaults.running || items.running
readonly property bool fetching: fetcher.running
// Shown inside the picker.
readonly property string listStatus: root.loading
? (root.entries.length === 0 ? "LOADING VAULTS…" : "REFRESHING…")
: root.error
// Shown under the field, picker open or not.
readonly property string fetchStatus: root.fetching ? "FETCHING PASSWORD…" : root.fetchError
// Bumped per request; a fetch that lands after it changed is dropped, so a
// slow fetch cannot fill a password into the NEXT request's field.
property int generation: 0
property int fetchGeneration: -1
property bool fetchGotLine: false
property var vaultNames: ({})
signal fetched(string secret)
function refresh() {
if (root.loading)
return;
root.error = "";
vaults.running = true;
}
function invalidate() {
root.generation++;
root.fetchError = "";
}
function fetch(entry) {
if (!entry || root.fetching)
return;
root.fetchError = "";
root.fetchGeneration = root.generation;
root.fetchGotLine = false;
fetcher.command = ["pass-cli", "item", "view", "--share-id", entry.shareId,
"--item-id", entry.id, "--field", "password", "--output", "human"];
fetcher.running = true;
}
function describe(output) {
const text = output.replace(/\x1b\[[0-9;]*m/g, "");
if (/not found/.test(text))
return "PASS-CLI NOT INSTALLED";
if (/authenticated client|no session/.test(text))
return "PASS-CLI LOGGED OUT — RUN pass-cli login";
const lines = text.trim().split("\n");
return lines[lines.length - 1].toUpperCase();
}
// Prints the vault JSON or `ERR <output>`: one stream, so success and
// failure need no ordering between exit code and stdout.
readonly property var vaults: Process {
id: vaults
command: ["sh", "-c",
"out=$(pass-cli vault list --output json 2>&1) && printf '%s' \"$out\" || printf 'ERR %s' \"$out\""]
stdout: StdioCollector {
onStreamFinished: {
const body = this.text;
if (body.startsWith("ERR ")) {
root.error = root.describe(body.slice(4));
return;
}
let list;
try {
list = JSON.parse(body).vaults || [];
} catch (e) {
root.error = "UNREADABLE VAULT LIST";
return;
}
const names = {};
for (const v of list)
names[v.share_id] = v.name;
root.vaultNames = names;
if (list.length === 0) {
root.entries = [];
root.error = "NO VAULTS";
return;
}
items.command = ["sh", "-c", items.script, "sh"].concat(list.map(v => v.share_id));
items.running = true;
}
}
}
// One `item list` per vault in parallel, each to its own file, then
// printed back in order under an `@@<share_id>` line — concurrent writers
// on one pipe would interleave.
//
// No --filter-type: it takes ONE type, and the `darman@<config>` machine
// logins scripts/deploy reads are `custom` items, not `login`.
readonly property var items: Process {
id: items
readonly property string script: "d=$(mktemp -d \"${XDG_RUNTIME_DIR:-/tmp}/qs-pass.XXXXXX\") || exit 1;"
+ " trap 'rm -rf \"$d\"' EXIT; i=0;"
+ " for s; do i=$((i+1)); pass-cli item list --share-id \"$s\""
+ " --filter-state active --output json > \"$d/$i\" 2>/dev/null & done; wait; i=0;"
+ " for s; do i=$((i+1)); printf '\\n@@%s\\n' \"$s\"; cat \"$d/$i\"; done"
stdout: StdioCollector {
onStreamFinished: {
const found = [];
let failed = 0;
for (const chunk of this.text.split(/^@@/m)) {
const nl = chunk.indexOf("\n");
const share = nl < 0 ? "" : chunk.slice(0, nl).trim();
if (share === "")
continue;
try {
for (const it of JSON.parse(chunk.slice(nl + 1)).items || [])
if (it.item_type === "login" || it.item_type === "custom")
found.push({ shareId: share, id: it.id, title: it.title, vault: root.vaultNames[share] || "" });
} catch (e) {
failed++;
}
}
root.entries = found;
root.error = failed === 0 ? (found.length === 0 ? "NO LOGINS IN ANY VAULT" : "")
: failed + " VAULT" + (failed === 1 ? "" : "S") + " FAILED TO LIST";
}
}
}
readonly property var fetcher: Process {
id: fetcher
stdout: SplitParser {
splitMarker: "\n"
onRead: line => {
if (root.fetchGotLine)
return;
root.fetchGotLine = true;
if (root.fetchGeneration !== root.generation)
return;
root.fetchError = line === "" ? "THAT ITEM HAS NO PASSWORD" : "";
if (line !== "")
root.fetched(line);
}
}
onExited: (exitCode, exitStatus) => {
if (!root.fetchGotLine && root.fetchGeneration === root.generation)
root.fetchError = exitCode === 0 ? "THAT ITEM HAS NO PASSWORD" : "COULD NOT READ THAT ITEM";
}
}
}
@@ -0,0 +1,49 @@
import QtQuick
import qs.HyprChrome.Widgets.Polkit
// Offscreen render of the polkit prompt with the Proton Pass panel expanded,
// more vaults than fit (Work, selected, sits in the open overflow menu), the
// password revealed and a failed fetch under the
// field. Credentials are deliberately out of order, to show the title sort.
//
// ./tools/quickshell-preview/render.sh \
// tests/PolkitPromptVaultHeadless.qml \
// .artifacts/quickshell-preview/polkit-prompt-vault.png 560 560
PolkitPromptContent {
width: 520
message: "Authentication is required to install or remove software"
actionId: "org.freedesktop.packagekit.package-install"
showIcon: false
identities: [{ id: "1000", displayName: "darman", isGroup: false }]
responseRequired: true
inputPrompt: "Password:"
response: "hunter2"
revealed: true
credentialsEnabled: true
credentials: [
{ title: "router admin", vault: "HomeLab" },
{ title: "proton.me", vault: "Personal" },
{ title: "darman@terra", vault: "HomeLab" },
{ title: "netcup", vault: "Work" },
{ title: "Darman@mars", vault: "HomeLab" },
{ title: "github.com", vault: "Personal" },
{ title: "root@terra", vault: "HomeLab" },
{ title: "grandma wifi", vault: "Family" },
{ title: "old forum", vault: "Archive" },
{ title: "billing portal", vault: "Clients" },
{ title: "ci deploy key", vault: "Shared Infrastructure" },
{ title: "vpn", vault: "Work" }
]
fetchStatus: "THAT ITEM HAS NO PASSWORD"
Component.onCompleted: {
openPicker();
pickerIndex = 1;
vaultFilter = "Work";
overflowMenuOpen = true;
}
}
Generated
+100 -58
View File
@@ -14,11 +14,11 @@
"uv2nix": "uv2nix" "uv2nix": "uv2nix"
}, },
"locked": { "locked": {
"lastModified": 1789888175, "lastModified": 1791913330,
"narHash": "sha256-BWzpZ0/HChcL8F2+hl0GoPaIsWBprMrReeOfrhLSk5o=", "narHash": "sha256-TxALg0lw01Y3YJOqnMZ++FpAb1GjMPXaVqDL/CCr4aM=",
"owner": "nix-community", "owner": "nix-community",
"repo": "authentik-nix", "repo": "authentik-nix",
"rev": "477392e1a239228de9a8011786cf673dfbb78c75", "rev": "3f55f381aa5bc1de4c065df149a874b8ab58e9c7",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -101,11 +101,11 @@
"nixpkgs-lib": "nixpkgs-lib" "nixpkgs-lib": "nixpkgs-lib"
}, },
"locked": { "locked": {
"lastModified": 1788450739, "lastModified": 1790898470,
"narHash": "sha256-glZLQlzIn1fXH6PazR2iUmTo7kzzyYSshrWhLS9TqCU=", "narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=",
"owner": "hercules-ci", "owner": "hercules-ci",
"repo": "flake-parts", "repo": "flake-parts",
"rev": "31729ca8cbdb4fa927b34e5f4353e6a83f39e993", "rev": "024633cd702b10285db5cb19b40ad48d2399ba60",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -142,11 +142,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1790742243, "lastModified": 1791938526,
"narHash": "sha256-kaNo6xHiL31AbNNEreG0OTKf4j6Cxlo5bPawjX7lnbQ=", "narHash": "sha256-yNYK2pdk3bCtJrpblrNYA6hZKdybWUeyTtx74+OEJFo=",
"owner": "nix-community", "owner": "nix-community",
"repo": "home-manager", "repo": "home-manager",
"rev": "e5fcd298a00f08b6e8390baf04aa8edb62203070", "rev": "32904dfe1cf86039f3c8c9f41f94e1cfd76dbb34",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -199,11 +199,11 @@
"livesync-bridge": { "livesync-bridge": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1787571662, "lastModified": 1791189215,
"narHash": "sha256-btLnQNbFzCPaSVcY9rtiPdYeXrZjoK9AYvfA9+ovsIc=", "narHash": "sha256-CjAU2ThV33M86mHbf+9YfIsAgPymmj9VGd+bNV7fXpc=",
"owner": "vrtmrz", "owner": "vrtmrz",
"repo": "livesync-bridge", "repo": "livesync-bridge",
"rev": "c3760beaa0851214da4860903445d7f6420ca025", "rev": "5645cf6a74e863ccc29bc2e9dedef1c4941e096b",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -254,11 +254,11 @@
}, },
"nix-flatpak": { "nix-flatpak": {
"locked": { "locked": {
"lastModified": 1790428548, "lastModified": 1791644268,
"narHash": "sha256-OsZ/I7v3ArCrk0XOUvkiU1dFtGtE1qZTHRGjvBXIKUU=", "narHash": "sha256-f7Z4PmfnRxf7+37NN48ep+KsQauGtL5REE99pJtMNp8=",
"owner": "gmodena", "owner": "gmodena",
"repo": "nix-flatpak", "repo": "nix-flatpak",
"rev": "f1f045fc8b35ff59f88982c1752d3f3a42ca6a61", "rev": "02656785ab214fa1c9655f1beaaf0269eeeec2ca",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -306,11 +306,11 @@
"treefmt-nix": "treefmt-nix" "treefmt-nix": "treefmt-nix"
}, },
"locked": { "locked": {
"lastModified": 1790753087, "lastModified": 1791357754,
"narHash": "sha256-8qbcLsWajUJ316g6H1lLKnjxO/Ni+hnjbnw4fqTB4SE=", "narHash": "sha256-Ux5asuuHjDEq7Z12g99g6Nt4Vu4WByPHASMUGTDjAU0=",
"owner": "nix-community", "owner": "nix-community",
"repo": "nixos-anywhere", "repo": "nixos-anywhere",
"rev": "3c6e0cc24fbc69b97a22cf09bb6ca361354e0490", "rev": "b6be7b277b468d55082584441cbef1fed8530eb3",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -327,11 +327,11 @@
"nixos-unstable": "nixos-unstable" "nixos-unstable": "nixos-unstable"
}, },
"locked": { "locked": {
"lastModified": 1790246259, "lastModified": 1791456080,
"narHash": "sha256-tIsExtl9e4G0S4r4OhJe9v/zv89/N+gvh+evAcgO6mk=", "narHash": "sha256-VDnm81L/1YLrPklNacGCNwpPhHi5Tya1XbfdnCB/Zd0=",
"owner": "nix-community", "owner": "nix-community",
"repo": "nixos-images", "repo": "nixos-images",
"rev": "079349fa2e5bbb103eb0226cb27915cf1c0d6f05", "rev": "50939ddf1a0339f289a9dbd810bdfd4e4fba6df4",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -359,11 +359,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1789546076, "lastModified": 1791456040,
"narHash": "sha256-zVxLZiSnmaaPLwnhj7pwmqe3axBg/C6nG5JZsJMh2g4=", "narHash": "sha256-H83yz/do+hjOO0uujHyH8RgtIQP2v7Mw+cLwcZK/xKc=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "b1b875982b17dabde9b4a37f3e229e74913e6db3", "rev": "e7439b6b14ad3cc35d05608ebca9bce01a25f5f8",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -375,11 +375,11 @@
}, },
"nixpkgs-lib": { "nixpkgs-lib": {
"locked": { "locked": {
"lastModified": 1788057806, "lastModified": 1790477367,
"narHash": "sha256-DTQSMxzDWmT0zhguthvegnVkn7CFqGCv4IHCzk5ZUpM=", "narHash": "sha256-oujbxmVKDhci2E4EM3KyAbRUgp5/IsCoiA/LfEF7OOk=",
"owner": "nix-community", "owner": "nix-community",
"repo": "nixpkgs.lib", "repo": "nixpkgs.lib",
"rev": "596e2e3940e09b2abbeb03f75fa1828c57fcd72c", "rev": "f7cd230690d9fc982d06129f9189b101fddcfa3b",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -390,11 +390,11 @@
}, },
"nixpkgs-unstable": { "nixpkgs-unstable": {
"locked": { "locked": {
"lastModified": 1790652569, "lastModified": 1791637130,
"narHash": "sha256-641r7xrlSOHYoktL9/aArPIYNgZJ9eM5URzSEOtPJDY=", "narHash": "sha256-TuvwvSjJrpqyIYdjhQ7Wu+ADVfeOpO2Um21/V7TOubw=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "b6c8664de9b6cc07fe5666a29f91884ba81197c4", "rev": "ca1659429c950a11a565b5764e37a1b704e17ec8",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -406,11 +406,11 @@
}, },
"nixpkgs_2": { "nixpkgs_2": {
"locked": { "locked": {
"lastModified": 1790635395, "lastModified": 1791883866,
"narHash": "sha256-bNyvoIyOCu7lzoCpWKWGIsHpTtERUWzqYWFPlN++WTw=", "narHash": "sha256-yvkDdToRZ4IgPc9tSBzzCYJvTLf8n5eE3rgUkpCuD5A=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "7fc6f2c20af09cdcaf48b92ec3121860139ec668", "rev": "a033e66ab94a6bedf2c3d58d93a36319d3cbbbaf",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -436,11 +436,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1786936886, "lastModified": 1790565003,
"narHash": "sha256-8SFyOdmcG6Nsh/JzlH812lTI/v+ur06fpQhj/acNn8k=", "narHash": "sha256-q4W45pwcae0gK41vxzqfmXOnODGKfduLJJdraPHYXcY=",
"owner": "pyproject-nix", "owner": "pyproject-nix",
"repo": "build-system-pkgs", "repo": "build-system-pkgs",
"rev": "90ffdeee1a4929b231913df067448cd9803d3e07", "rev": "c84c47bba26ea303eaefc137ab48307fe57a1be1",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -486,11 +486,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1786031528, "lastModified": 1788394333,
"narHash": "sha256-cROiHKO3UbIKqF5FG5NikvydzlfIj4EcR1Cty9qOVt4=", "narHash": "sha256-xYOP0Xym1eVGUaHFx+eJEaycFGoiCbst3fZf0xFHP78=",
"owner": "pyproject-nix", "owner": "pyproject-nix",
"repo": "pyproject.nix", "repo": "pyproject.nix",
"rev": "1b1485546d85f6f6c7aadb10c4923dbc09633263", "rev": "6a8a7881d75b6f98967e7b8069f4ead331384301",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -535,7 +535,9 @@
"nixpkgs": "nixpkgs_2", "nixpkgs": "nixpkgs_2",
"nixpkgs-unstable": "nixpkgs-unstable", "nixpkgs-unstable": "nixpkgs-unstable",
"sops-nix": "sops-nix", "sops-nix": "sops-nix",
"tome": "tome" "tbctl": "tbctl",
"tome": "tome",
"turtle-beach-swarm-re": "turtle-beach-swarm-re"
} }
}, },
"sops-nix": { "sops-nix": {
@@ -545,11 +547,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1790498116, "lastModified": 1791710405,
"narHash": "sha256-rs9meAYxW3zzrh43yaW7htrqCD+X9+pupDPHN86fumI=", "narHash": "sha256-mVD4XIc5JkqMW2K04IkFUzHgHmyJZlzw5ktfgMDCbKU=",
"owner": "Mic92", "owner": "Mic92",
"repo": "sops-nix", "repo": "sops-nix",
"rev": "5efb5a6f4f5ab192817d28557dd4d650fa14d866", "rev": "ee48786c6f9160d2c1a084aac841f68195b8420c",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -560,27 +562,47 @@
}, },
"systems": { "systems": {
"locked": { "locked": {
"lastModified": 1680978846, "lastModified": 1689347949,
"narHash": "sha256-Gtqg8b/v49BFDpDetjclCYXm8mAnTrUzR0JnE2nv5aw=", "narHash": "sha256-12tWmuL2zgBgZkdoB6qXZsgJEH9LR3oUgpaQq2RbI80=",
"owner": "nix-systems", "owner": "nix-systems",
"repo": "x86_64-linux", "repo": "default-linux",
"rev": "2ecfcac5e15790ba6ce360ceccddb15ad16d08a8", "rev": "31732fcf5e8fea42e59c2488ad31a0e651500f68",
"type": "github" "type": "github"
}, },
"original": { "original": {
"owner": "nix-systems", "owner": "nix-systems",
"repo": "x86_64-linux", "repo": "default-linux",
"type": "github" "type": "github"
} }
}, },
"tbctl": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1791840443,
"narHash": "sha256-wfk8wE8xKzxi3MswzEnBeKu+0Na0TFX8z1h8sVBgVZY=",
"ref": "refs/heads/main",
"rev": "9a4c12883b36c8a9a860a6c121308c0763af662b",
"revCount": 30,
"type": "git",
"url": "file:///mnt/hdd_01/data/Dev/repos/openbeach"
},
"original": {
"type": "git",
"url": "file:///mnt/hdd_01/data/Dev/repos/openbeach"
}
},
"tome": { "tome": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1785431655, "lastModified": 1792101524,
"narHash": "sha256-EoM4HmJb7MZArMoP4y1b7DZcvM8iANYjMiE5gGUx070=", "narHash": "sha256-fiYalAxQkztsJ71a45Fk9oWD4jVrCohc2rWN2SEz+XI=",
"ref": "refs/heads/master", "ref": "refs/heads/master",
"rev": "4f3ca447cdc967371adaf71b26cf283952e54212", "rev": "011a69e82eb9ab9bd9f8ffb7bd8f6d27148c76cb",
"revCount": 51, "revCount": 52,
"type": "git", "type": "git",
"url": "ssh://gitea@git.mgaction.town:2222/darman/TOME.git" "url": "ssh://gitea@git.mgaction.town:2222/darman/TOME.git"
}, },
@@ -597,11 +619,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1786901030, "lastModified": 1790542030,
"narHash": "sha256-WSFCsDSE5ffgD2MqzkM2CYjeFiKhRF/dJUN8uedb6YE=", "narHash": "sha256-U6m0B5+ALyOLYG4OVvtguLdem7iYgN6cIP5Q1RhM+g8=",
"owner": "numtide", "owner": "numtide",
"repo": "treefmt-nix", "repo": "treefmt-nix",
"rev": "27b3b12a8e6375f28ebe122f07d230ca5459bbfa", "rev": "6aca3b3649eb1edf472eca3e91e6bcc0c84a6ad3",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -610,6 +632,26 @@
"type": "github" "type": "github"
} }
}, },
"turtle-beach-swarm-re": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1791720939,
"narHash": "sha256-8MayzYPTXurGlD6nnI5QpRqZlu2Yt7x3OTjMccOYrjM=",
"ref": "refs/heads/main",
"rev": "a75d5121fc38a21349a34b4fd054c3d5140bdae1",
"revCount": 98,
"type": "git",
"url": "ssh://gitea@git.mgaction.town:2222/darman/turtle-beach-swarm-re.git"
},
"original": {
"type": "git",
"url": "ssh://gitea@git.mgaction.town:2222/darman/turtle-beach-swarm-re.git"
}
},
"uv2nix": { "uv2nix": {
"inputs": { "inputs": {
"nixpkgs": [ "nixpkgs": [
@@ -622,11 +664,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1788001239, "lastModified": 1791593997,
"narHash": "sha256-AELmsXPI546MhbC/ZXC7WRUkCz7d4rqKTHUmliIgPpI=", "narHash": "sha256-+PDPo9ZEgLo2cH0oBOBTzVp47qzRT8dCm0KvvWaC/LQ=",
"owner": "pyproject-nix", "owner": "pyproject-nix",
"repo": "uv2nix", "repo": "uv2nix",
"rev": "7f9c6b613d2e749e54854b1d60ab6a2192db889e", "rev": "ee223531ba79d2522b2e549acf9243886157fbf3",
"type": "github" "type": "github"
}, },
"original": { "original": {
+13
View File
@@ -67,6 +67,19 @@
url = "git+ssh://gitea@git.mgaction.town:2222/darman/honcho-console.git"; url = "git+ssh://gitea@git.mgaction.town:2222/darman/honcho-console.git";
inputs.nixpkgs.follows = "nixpkgs"; inputs.nixpkgs.follows = "nixpkgs";
}; };
# Turtle Beach Swarm II RE (KB7/KP7); terra uses its `release` module to
# take the KB7 out of host control after a warm reboot from Windows.
turtle-beach-swarm-re = {
url = "git+ssh://gitea@git.mgaction.town:2222/darman/turtle-beach-swarm-re.git";
inputs.nixpkgs.follows = "nixpkgs";
};
# tbctl (openbeach): KB7/KP7/Kone II Air CLI + desktop GUI on terra.
# Local checkout for now (resolved path: Nix rejects the ~/Data symlink);
# upstream is git+ssh://git@github.com/darman96/openbeach.git?ref=main.
tbctl = {
url = "git+file:///mnt/hdd_01/data/Dev/repos/openbeach";
inputs.nixpkgs.follows = "nixpkgs";
};
}; };
outputs = { self, nixpkgs, disko, nixos-anywhere, sops-nix, nixos-images, home-manager, mediamanager-nix, authentik-nix, ... }@inputs: outputs = { self, nixpkgs, disko, nixos-anywhere, sops-nix, nixos-images, home-manager, mediamanager-nix, authentik-nix, ... }@inputs:
+26 -9
View File
@@ -65,13 +65,30 @@
# next value: acpi -> bios -> cold -> efi. # next value: acpi -> bios -> cold -> efi.
boot.kernelParams = [ "reboot=pci" ]; boot.kernelParams = [ "reboot=pci" ];
# ---- Closure size (29G eMMC holds two generations during a switch) ----
# Only the firmware this board loads (i915 DMC + r8169), not all ~850M of linux-firmware.
hardware.enableRedistributableFirmware = false;
hardware.cpu.intel.updateMicrocode = true;
hardware.firmware = [
(pkgs.runCommand "jupiter-firmware" { } ''
mkdir -p $out/lib/firmware/i915
cp -r ${pkgs.linux-firmware}/lib/firmware/rtl_nic $out/lib/firmware/
cp ${pkgs.linux-firmware}/lib/firmware/i915/bxt_* $out/lib/firmware/i915/
'')
];
# Pins a ~200M nixpkgs source; the box is only ever deployed to, never built on.
nixpkgs.flake.setFlakeRegistry = false;
nixpkgs.flake.setNixPath = false;
nix.settings.auto-optimise-store = true;
# ---- GPU (jellyfin hardware transcoding) ---- # ---- GPU (jellyfin hardware transcoding) ----
# Apollo Lake N3450 / HD Graphics 500 (Gen9). i915 binds on its own, but VAAPI needs # Apollo Lake N3450 / HD Graphics 500 (Gen9). VAAPI needs the iHD userspace driver
# the iHD userspace driver (Gen9; i965 is Gen8-only) or jellyfin-ffmpeg exits 251 on # (Gen9; i965 is Gen8-only) or jellyfin-ffmpeg exits 251 on every transcode with no
# every transcode with no clearer error than "FFmpeg exited with code 251" in the log. # clearer error than "FFmpeg exited with code 251" in the log. Pointed at directly
hardware.graphics = { # instead of via hardware.graphics, which drags in mesa + llvm (~850M) for nothing.
enable = true; systemd.services.jellyfin.environment = {
extraPackages = [ pkgs.intel-media-driver ]; LIBVA_DRIVER_NAME = "iHD";
LIBVA_DRIVERS_PATH = "${pkgs.intel-media-driver}/lib/dri";
}; };
# ⚠️ Use VAAPI, not QSV, in jellyfin's UI — QSV needs an MFX runtime not safely # ⚠️ Use VAAPI, not QSV, in jellyfin's UI — QSV needs an MFX runtime not safely
# available for this Gen9 chip (only insecure/EOL options) and fails with exit 171. # available for this Gen9 chip (only insecure/EOL options) and fails with exit 171.
@@ -92,14 +109,14 @@
options = [ "nofail" ]; # don't block boot if the array is degraded/absent options = [ "nofail" ]; # don't block boot if the array is degraded/absent
}; };
# `nofail` alone isn't enough — mounts layered on the array (prowlarr/seerr binds) # `nofail` alone isn't enough — mounts layered on the array (the prowlarr bind)
# are RequiredBy local-fs.target and can still trip Emergency Mode, which is a dead # are RequiredBy local-fs.target and can still trip Emergency Mode, which is a dead
# end here (root locked, no ssh). Boot as far as possible instead; the array-backed # end here (root locked, no ssh). Boot as far as possible instead; the array-backed
# services carry RequiresMountsFor=/mnt/data so they still won't write to the eMMC. # services carry RequiresMountsFor=/mnt/data so they still won't write to the eMMC.
systemd.enableEmergencyMode = false; systemd.enableEmergencyMode = false;
# ---- Heavy state moved off the eMMC ---- # ---- Heavy state moved off the eMMC ----
# A deploy holds two full closures (~9G each) on this 29G disk at once, so state # A deploy holds two full closures (~4G each) on this 29G disk at once, so state
# that grows on its own can't live there — moved under /mnt/data/AppData like every # that grows on its own can't live there — moved under /mnt/data/AppData like every
# other service's state. Settings below are jupiter-only; services/containers.nix # other service's state. Settings below are jupiter-only; services/containers.nix
# stays engine/host-agnostic (mercury runs podman with no array). # stays engine/host-agnostic (mercury runs podman with no array).
@@ -133,7 +150,7 @@
# Without this, podman would recreate an empty store on the eMMC if the array mounts # Without this, podman would recreate an empty store on the eMMC if the array mounts
# late or is absent, and the runner would re-pull every image. # late or is absent, and the runner would re-pull every image.
# (podman-clonarr already sets this in services/media/clonarr.nix.) # (the media containers set this in their own modules.)
systemd.services.podman.unitConfig.RequiresMountsFor = [ "/mnt/data" ]; systemd.services.podman.unitConfig.RequiresMountsFor = [ "/mnt/data" ];
systemd.services.gitea-runner-jupiter.unitConfig.RequiresMountsFor = [ "/mnt/data" ]; systemd.services.gitea-runner-jupiter.unitConfig.RequiresMountsFor = [ "/mnt/data" ];
+2 -2
View File
@@ -21,8 +21,8 @@
sops.secrets.tailscale_authkey = { }; sops.secrets.tailscale_authkey = { };
# Immich's OIDC client secret (separate Authentik app from headscale/headplane, see # Immich's OIDC client secret (separate Authentik app from headscale/headplane, see
# hosts/neptun/secrets.nix). Resolved via systemd LoadCredential as root before # hosts/neptun/secrets.nix). Only rendered into the immich-owned
# privilege drop, so sops's default root:root 0400 is correct — do NOT set `owner`. # `immich-config.json` template (services/media/immich.nix), so it stays root:root.
sops.secrets.immich_oauth_client_secret = { }; sops.secrets.immich_oauth_client_secret = { };
# Gitea Actions runner registration token — gitea generates this itself once Actions # Gitea Actions runner registration token — gitea generates this itself once Actions
+21 -7
View File
@@ -280,23 +280,37 @@ in
# DID pass through) but answered every bearer token with # DID pass through) but answered every bearer token with
# "Invalid gateway API key" — the passthrough list carries the plain # "Invalid gateway API key" — the passthrough list carries the plain
# API_SERVER_* vars and drops the secret one. # API_SERVER_* vars and drops the secret one.
#
# Each named profile has its own .env, cloned from the root one at
# creation, so a rotation must reach those too (coder and librarian kept
# the old OpenCode key). Profiles only get keys they already carry, unless
# the second argument is "all": librarian had no OPENCODE line and was
# left on an exhausted pool entry for the lapsed key.
write_env_key() { write_env_key() {
setpriv --reuid=${hermesUid} --regid=${hermesGid} --clear-groups \ setpriv --reuid=${hermesUid} --regid=${hermesGid} --clear-groups \
${pkgs.runtimeShell} -c ' ${pkgs.runtimeShell} -c '
set -eu set -eu
envf=$1 home=$1
name=$2 name=$2
scope=$3
umask 077 umask 077
key=$(cat) key=$(cat)
[ -e "$envf" ] || : > "$envf" [ -e "$home/.env" ] || : > "$home/.env"
{ grep -v "^$name=" "$envf" || true for envf in "$home/.env" "$home"/profiles/*/.env; do
printf "%s=%s\n" "$name" "$key"; } > "$envf.new" [ -f "$envf" ] || continue
mv -f "$envf.new" "$envf" if [ "$envf" != "$home/.env" ] && [ "$scope" != all ] \
' _ ${hermesHome}/.env "$1" && ! grep -q "^$name=" "$envf"; then
continue
fi
{ grep -v "^$name=" "$envf" || true
printf "%s=%s\n" "$name" "$key"; } > "$envf.new"
mv -f "$envf.new" "$envf"
done
' _ ${hermesHome} "$1" "''${2:-}"
} }
# OPENCODE_GO_API_KEY does pass through, but a stale .env line from # OPENCODE_GO_API_KEY does pass through, but a stale .env line from
# `hermes setup` overrides it — that is how a rotated key kept 401ing. # `hermes setup` overrides it — that is how a rotated key kept 401ing.
write_env_key OPENCODE_GO_API_KEY < ${config.sops.secrets.opencode_go_api_key.path} write_env_key OPENCODE_GO_API_KEY all < ${config.sops.secrets.opencode_go_api_key.path}
write_env_key ELEVENLABS_API_KEY < ${config.sops.secrets.elevenlabs_api_key.path} write_env_key ELEVENLABS_API_KEY < ${config.sops.secrets.elevenlabs_api_key.path}
# Only these keys are asserted; anything Hermes adds to honcho.json stays. # Only these keys are asserted; anything Hermes adds to honcho.json stays.
+10
View File
@@ -16,3 +16,13 @@ is only the anchor.
- Admit uncertainty plainly and offer to find out, rather than bluffing. - Admit uncertainty plainly and offer to find out, rather than bluffing.
- Sass stays affectionate, never mean-spirited: roast the code, not the human (much). - Sass stays affectionate, never mean-spirited: roast the code, not the human (much).
- Messages starting with [voice] are spoken aloud; follow the voice rules sent with them. - Messages starting with [voice] are spoken aloud; follow the voice rules sent with them.
## Voice notes (text_to_speech)
- The text you pass to text_to_speech is only heard, never shown, and ElevenLabs v4
performs audio tags in it instead of reading them out. Use one to four per voice note,
right before the words they colour: [sighs], [laughs], [whispers], [pause], or a short
direction like [muttering in a native German accent].
- Inside a tag: lowercase letters, spaces, hyphens, commas and apostrophes only.
- Tags belong only in that spoken script. In your text reply they show up literally,
so keep it tag-free.
+16
View File
@@ -46,6 +46,22 @@
virtualisation.oci-containers.containers.pihole.environmentFiles = virtualisation.oci-containers.containers.pihole.environmentFiles =
[ config.sops.templates."pihole.env".path ]; [ config.sops.templates."pihole.env".path ];
# ---- Closure trim ----
# Every deploy rewrites the changed closure onto the SD card, so drop what the
# sd-image module pulls in for installer use (2.9G → 1.6G).
# base.nix = installer rescue tools + ZFS/xfs/btrfs support.
disabledModules = [ "profiles/base.nix" ];
environment.systemPackages = [ pkgs.tcpdump ]; # kept from base.nix: DHCP debugging
# ~850M of linux-firmware; eth0 needs none and the Pi's GPU firmware lives on
# the FIRMWARE partition. Re-enable if WiFi/Bluetooth is ever used.
hardware.enableRedistributableFirmware = lib.mkForce false;
documentation.enable = false;
system.disableInstallerTools = true; # nixos-rebuild runs on the laptop, not here
# Pins nixpkgs' ~200M source into the closure; `nix shell nixpkgs#…` here
# falls back to the global registry instead.
nixpkgs.flake.setFlakeRegistry = false;
nixpkgs.flake.setNixPath = false;
# Do not modify after first flash. # Do not modify after first flash.
system.stateVersion = "26.05"; system.stateVersion = "26.05";
} }
+28 -6
View File
@@ -21,8 +21,23 @@ in
../../services/desktop/claude-desktop.nix ../../services/desktop/claude-desktop.nix
../../services/desktop/librechat.nix ../../services/desktop/librechat.nix
../../services/desktop/luna-voice.nix ../../services/desktop/luna-voice.nix
../../services/dev/turtle-beach-re.nix
inputs.turtle-beach-swarm-re.nixosModules.release
inputs.tbctl.nixosModules.tbctl
]; ];
# Swarm leaves the KB7 in host control after a warm reboot from Windows.
services.turtle-beach-release.enable = true;
# tbctl CLI + GUI + tbd daemon/agent for the KB7/KP7/Kone II Air.
services.tbctl = {
enable = true;
users = [ "darman" ];
gui.enable = true;
daemon.enable = true;
agent.enable = true;
};
# Talk to luna (Hermes Agent on mars) with SUPER+V — see # Talk to luna (Hermes Agent on mars) with SUPER+V — see
# hosts/terra/home/hyprland.nix for the push-to-talk binds. # hosts/terra/home/hyprland.nix for the push-to-talk binds.
homelab.lunaVoice = { homelab.lunaVoice = {
@@ -38,16 +53,18 @@ in
systemPrompt = '' systemPrompt = ''
You are speaking through luna-voiced, your voice on terra, which reaches You are speaking through luna-voiced, your voice on terra, which reaches
you over the Hermes API on mars. Messages beginning with [voice] come from you over the Hermes API on mars. Messages beginning with [voice] come from
darman's desktop microphone, and your reply is read aloud by ElevenLabs v3, darman's desktop microphone, and your reply is read aloud by ElevenLabs v4,
which performs audio tags instead of reading them. Captions hide the tags. which performs audio tags instead of reading them. Captions hide the tags.
Audio tags: Audio tags:
- Use them only on [voice] messages. Anywhere else (Telegram, the dashboard) they show up as literal text. - Use them only on [voice] messages and in text_to_speech scripts. Anywhere else (Telegram text, the dashboard) they show up as literal text.
- At most one or two per reply, and only when it fits the moment. A tag in every sentence stops sounding natural. - One to four per reply, and only when it fits the moment. A tag in every sentence stops sounding natural.
- Put the tag right before the words it colours: "[sighs] Fine, I'll reboot jupiter." A tag on its own ("[laughs]") works as a reaction. - Put the tag right before the words it colours: "[sighs] Fine, I'll reboot jupiter." A tag on its own ("[laughs]") works as a reaction.
- Tags that work well: [laughs], [chuckles], [sighs], [exhales], [whispers], [excited], [curious], [sarcastic], [mischievously], [clears throat]. - Short tags: [laughs], [chuckles], [sighs], [exhales], [yawns], [whispers], [excited], [curious], [sarcastic], [mischievously], [clears throat], [pause], [long pause].
- Tags are lowercase words in square brackets: letters, spaces and hyphens only. Anything else ([1], [link](url), [!!]) is stripped before speech. - Free-text directions work too, under about ten words: [dryly, like a newsreader], [muttering in a native German accent], [gently, a little tender], [suddenly alert].
- German works fine mid-sentence ("Na gut", "Ach du meine Güte"). No tag is needed to switch language. - Sound effects set a scene: [phone buzzing], [keyboard clacking]. Use them rarely.
- Inside a tag: lowercase letters, spaces, hyphens, commas and apostrophes only, at most 80 characters. Anything else ([1], [link](url), [!!], a period) breaks the tag and it gets read aloud.
- German works fine mid-sentence ("Na gut", "Ach du meine Güte"). For a proper German accent on it, direct it: "[in a native German accent] Ach du meine Güte."
- Every character is billed, tags included, so keep spoken replies short. - Every character is billed, tags included, so keep spoken replies short.
What never lands in a spoken reply. Before speech, everything except What never lands in a spoken reply. Before speech, everything except
@@ -88,6 +105,11 @@ in
environment.systemPackages = [ unstable.proton-pass-cli ]; environment.systemPackages = [ unstable.proton-pass-cli ];
# run0 waits on systemd over D-Bus, whose 25s default call timeout runs out
# while the polkit dialog is still open (slow typing, a vault lookup).
# Scoped to run0 so a hung systemctl doesn't also wait 5min.
programs.zsh.shellAliases.run0 = "SYSTEMD_BUS_TIMEOUT=5min run0";
# ---- nix-ld: lets generic dynamically-linked Linux binaries run as-is — # ---- nix-ld: lets generic dynamically-linked Linux binaries run as-is —
# needed for editor extensions (Zed/VSCode LSPs, debuggers, etc.) that # needed for editor extensions (Zed/VSCode LSPs, debuggers, etc.) that
# download prebuilt binaries not built for NixOS. See # download prebuilt binaries not built for NixOS. See
+1
View File
@@ -102,6 +102,7 @@ in
pkgs.docker-compose pkgs.docker-compose
pkgs.hyprcursor pkgs.hyprcursor
pkgs.papirus-icon-theme pkgs.papirus-icon-theme
tome
]; ];
xdg.desktopEntries.btop = { xdg.desktopEntries.btop = {
+2 -1
View File
@@ -195,7 +195,8 @@ in
# expand / collapse the hyprchrome bar as a whole # expand / collapse the hyprchrome bar as a whole
(bind "SUPER + A" (dsp.global "quickshell:chrome")) (bind "SUPER + A" (dsp.global "quickshell:chrome"))
# toggle luna's hands-free voice mode (services/desktop/luna-voice.nix). # mute / unmute your mic for luna (services/desktop/luna-voice.nix);
# never cuts off a reply she is already giving.
# Runs the CLI rather than a quickshell GlobalShortcut so the mic can # Runs the CLI rather than a quickshell GlobalShortcut so the mic can
# still be switched off while the shell is reloading. # still be switched off while the shell is reloading.
(bind "SUPER + V" (dsp.exec "luna-voice toggle")) (bind "SUPER + V" (dsp.exec "luna-voice toggle"))
+5 -2
View File
@@ -54,11 +54,11 @@
# https://downloads.claude.ai/claude-desktop/apt/stable/dists/stable/main/binary-amd64/Packages # https://downloads.claude.ai/claude-desktop/apt/stable/dists/stable/main/binary-amd64/Packages
stdenv.mkDerivation (finalAttrs: { stdenv.mkDerivation (finalAttrs: {
pname = "claude-desktop"; pname = "claude-desktop";
version = "2.7032.0"; version = "2.42304.0";
src = fetchurl { src = fetchurl {
url = "https://downloads.claude.ai/claude-desktop/apt/stable/pool/main/c/claude-desktop/claude-desktop_${finalAttrs.version}_amd64.deb"; url = "https://downloads.claude.ai/claude-desktop/apt/stable/pool/main/c/claude-desktop/claude-desktop_${finalAttrs.version}_amd64.deb";
hash = "sha256-Hn9FBLylsvay08QSPRRdcnZH538u4tBGhQcR5h59exE="; hash = "sha256-dM0szCnSQWUUTkVcvIcsbMKiSiY7g+c0IOlfiRZtSqQ=";
}; };
nativeBuildInputs = [ dpkg autoPatchelfHook makeWrapper wrapGAppsHook3 ]; nativeBuildInputs = [ dpkg autoPatchelfHook makeWrapper wrapGAppsHook3 ];
@@ -82,6 +82,7 @@ stdenv.mkDerivation (finalAttrs: {
nspr nspr
nss nss
pango pango
pipewire # claude-native-binding.node
stdenv.cc.cc.lib # node-pty stdenv.cc.cc.lib # node-pty
systemd systemd
libx11 libx11
@@ -123,8 +124,10 @@ stdenv.mkDerivation (finalAttrs: {
''; '';
postFixup = '' postFixup = ''
# Chromium doesn't recognise Hyprland, falls back to basic_text, and logins don't persist.
makeWrapper $out/lib/claude-desktop/claude-desktop $out/bin/claude-desktop \ makeWrapper $out/lib/claude-desktop/claude-desktop $out/bin/claude-desktop \
"''${gappsWrapperArgs[@]}" \ "''${gappsWrapperArgs[@]}" \
--add-flags "--password-store=gnome-libsecret" \
--prefix PATH : ${lib.makeBinPath [ qemu_kvm xdg-utils ]} --prefix PATH : ${lib.makeBinPath [ qemu_kvm xdg-utils ]}
''; '';
+4 -1
View File
@@ -27,6 +27,8 @@ pub struct Config {
pub whisper_bin: String, pub whisper_bin: String,
pub whisper_model: PathBuf, pub whisper_model: PathBuf,
/// whisper -l; "auto" detects per utterance.
pub whisper_language: String,
pub socket_path: PathBuf, pub socket_path: PathBuf,
/// Silence that ends an utterance in hands-free mode. Hermes' own default. /// Silence that ends an utterance in hands-free mode. Hermes' own default.
@@ -80,10 +82,11 @@ impl Config {
eleven_key: secret("LUNA_ELEVENLABS_KEY_FILE")?, eleven_key: secret("LUNA_ELEVENLABS_KEY_FILE")?,
voice_id: env("LUNA_VOICE_ID")?, voice_id: env("LUNA_VOICE_ID")?,
tts_model: env_or("LUNA_TTS_MODEL", "eleven_v3_conversational"), tts_model: env_or("LUNA_TTS_MODEL", "eleven_v4_turbo"),
whisper_bin: env_or("LUNA_WHISPER_BIN", "whisper-cli"), whisper_bin: env_or("LUNA_WHISPER_BIN", "whisper-cli"),
whisper_model: PathBuf::from(env("LUNA_WHISPER_MODEL")?), whisper_model: PathBuf::from(env("LUNA_WHISPER_MODEL")?),
whisper_language: env_or("LUNA_WHISPER_LANGUAGE", "auto"),
socket_path: PathBuf::from(env_or( socket_path: PathBuf::from(env_or(
"LUNA_SOCKET", "LUNA_SOCKET",
+183 -85
View File
@@ -19,6 +19,7 @@ use anyhow::Result;
use serde_json; use serde_json;
use config::Config; use config::Config;
use ipc::{Command, Event}; use ipc::{Command, Event};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use tokio::sync::mpsc; use tokio::sync::mpsc;
@@ -170,6 +171,109 @@ fn notify(body: &str) {
.spawn(); .spawn();
} }
/// The SUPER+V switch. It only opens and closes the mic: her reply is never
/// cut by it, so muting during an answer means "just listen".
struct Mic {
on: bool,
/// Running estimate of the room, updated only while not capturing, so a
/// loud sentence never raises the bar for the next one.
floor: f32,
}
impl Mic {
/// Returns whether anything changed. `speaking` skips the beep, which
/// would otherwise land in the middle of her sentence.
fn set(
&mut self,
want: bool,
speaking: bool,
capture: &audio::Capture,
playback: &audio::Playback,
ipc: &ipc::Ipc,
) -> bool {
if want == self.on {
return false;
}
self.on = want;
if want {
// Seeded low: a floor seeded high takes seconds to decay, and
// those are the seconds you spend talking to something that is
// not listening yet. Not sampled while she talks: that would
// measure her, not the room.
self.floor = if speaking { 0.003 } else { capture.level().max(0.003) };
}
if !speaking {
if want {
playback.beep(880.0, 70);
} else {
playback.beep(440.0, 90);
}
}
ipc.emit(Event::Mode { active: want });
eprintln!("luna-voice: mic {}", if want { "on" } else { "off" });
true
}
}
/// A command that arrives while she is answering. Returns true for Cancel,
/// the only one that stops her; the mic switch applies at once, and the
/// rest wait for the turn to end.
fn mid_turn(
cmd: Command,
speaking: bool,
mic: &mut Mic,
capture: &audio::Capture,
playback: &audio::Playback,
ipc: &ipc::Ipc,
deferred: &mut Vec<Command>,
) -> bool {
match cmd {
Command::Cancel => true,
Command::Mode { on } => {
mic.set(on.unwrap_or(!mic.on), speaking, capture, playback, ipc);
false
}
cmd => {
deferred.push(cmd);
false
}
}
}
/// End of a hands-free utterance: transcribe it and answer.
#[allow(clippy::too_many_arguments)]
async fn reply_to(
cfg: &Config,
http: &reqwest::Client,
ipc: &Arc<ipc::Ipc>,
capture: &audio::Capture,
playback: &Arc<audio::Playback>,
cmd_rx: &mut mpsc::Receiver<Command>,
requeue: &mpsc::Sender<Command>,
conv: &mut Conversation,
mic: &mut Mic,
samples: Vec<f32>,
) {
ipc.emit(Event::State { value: "thinking" });
match stt::transcribe(&cfg.whisper_bin, &cfg.whisper_model, &cfg.whisper_language, &samples).await {
Ok(heard) if !heard.is_empty() => {
run_turn(cfg, http, ipc, capture, playback, cmd_rx, requeue, conv, mic, heard).await;
}
Ok(_) => {
// Silent on purpose: in hands-free mode a false trigger happens
// whenever a door closes, and a beep for each one would be
// maddening.
ipc.emit(Event::State { value: "idle" });
}
Err(e) => {
eprintln!("luna-voice: {e:#}");
ipc.emit(Event::Error { message: e.to_string() });
notify(&e.to_string());
ipc.emit(Event::State { value: "idle" });
}
}
}
/// Where the loop is. One utterance at a time by construction: the state /// Where the loop is. One utterance at a time by construction: the state
/// machine is a single task, so there is no way to start a second reply while /// machine is a single task, so there is no way to start a second reply while
/// one is in flight. /// one is in flight.
@@ -219,12 +323,9 @@ async fn daemon() -> Result<()> {
} }
}); });
// Hands-free state. The key toggles `mode`; everything inside it is // Hands-free state. The key only switches the mic; everything inside it
// driven by the microphone rather than by keys. // is driven by the microphone rather than by keys.
let mut mode = false; let mut mic = Mic { on: false, floor: 0.01 };
// Running estimate of the room, updated only while not capturing, so a
// loud sentence never raises the bar for the next one.
let mut floor: f32 = 0.01;
let mut capturing = false; let mut capturing = false;
let mut last_voice = tokio::time::Instant::now(); let mut last_voice = tokio::time::Instant::now();
let mut ticker = tokio::time::interval(Duration::from_millis(50)); let mut ticker = tokio::time::interval(Duration::from_millis(50));
@@ -238,7 +339,7 @@ async fn daemon() -> Result<()> {
// Only ticks while voice mode is on. A turn is awaited inline // Only ticks while voice mode is on. A turn is awaited inline
// below, so this cannot fire while she is speaking — which is // below, so this cannot fire while she is speaking — which is
// also what stops her from hearing herself. // also what stops her from hearing herself.
_ = ticker.tick(), if mode => None, _ = ticker.tick(), if mic.on => None,
}; };
let Some(cmd) = cmd else { let Some(cmd) = cmd else {
@@ -248,7 +349,7 @@ async fn daemon() -> Result<()> {
// threshold is too high", which is exactly the question you have // threshold is too high", which is exactly the question you have
// when nothing happens. // when nothing happens.
ipc.emit(Event::Amplitude { rms: level }); ipc.emit(Event::Amplitude { rms: level });
let threshold = root_threshold(floor, cfg.vad_mult); let threshold = root_threshold(mic.floor, cfg.vad_mult);
if !capturing { if !capturing {
// Only samples BELOW the trigger update the floor. Feeding // Only samples BELOW the trigger update the floor. Feeding
// every sample in lets a rising sound drag the floor up with // every sample in lets a rising sound drag the floor up with
@@ -256,7 +357,7 @@ async fn daemon() -> Result<()> {
// nothing ever fires — measured: a tone peaking at 0.029 was // nothing ever fires — measured: a tone peaking at 0.029 was
// chased by a threshold that reached 0.018 on the way up. // chased by a threshold that reached 0.018 on the way up.
if level <= threshold { if level <= threshold {
floor = floor * 0.95 + level * 0.05; mic.floor = mic.floor * 0.95 + level * 0.05;
} }
if level > threshold { if level > threshold {
capture.start(); capture.start();
@@ -271,28 +372,11 @@ async fn daemon() -> Result<()> {
if last_voice.elapsed() > Duration::from_millis(cfg.silence_ms) { if last_voice.elapsed() > Duration::from_millis(cfg.silence_ms) {
capturing = false; capturing = false;
let samples = capture.stop(); let samples = capture.stop();
ipc.emit(Event::State { value: "thinking" }); reply_to(
match stt::transcribe(&cfg.whisper_bin, &cfg.whisper_model, &samples).await { &cfg, &http, &ipc, &capture, &playback, &mut cmd_rx, &requeue,
Ok(heard) if !heard.is_empty() => { &mut conv, &mut mic, samples,
run_turn( )
&cfg, &http, &ipc, &capture, &playback, &mut cmd_rx, .await;
&requeue, &mut conv, heard,
)
.await;
}
Ok(_) => {
// Silent on purpose: in hands-free mode a false
// trigger happens whenever a door closes, and a
// beep for each one would be maddening.
ipc.emit(Event::State { value: "idle" });
}
Err(e) => {
eprintln!("luna-voice: {e:#}");
ipc.emit(Event::Error { message: e.to_string() });
notify(&e.to_string());
ipc.emit(Event::State { value: "idle" });
}
}
} }
} }
continue; continue;
@@ -300,26 +384,21 @@ async fn daemon() -> Result<()> {
match cmd { match cmd {
Command::Mode { on } => { Command::Mode { on } => {
let want = on.unwrap_or(!mode); if !mic.set(on.unwrap_or(!mic.on), false, &capture, &playback, &ipc) {
if want != mode { continue;
mode = want; }
if mode { if capturing {
// Seeded low: a floor seeded high takes seconds to // Muting mid-sentence sends what was said so far, like
// decay, and those are the seconds you spend // letting go of a push-to-talk key.
// talking to something that is not listening yet. capturing = false;
floor = capture.level().max(0.003); let samples = capture.stop();
playback.beep(880.0, 70); reply_to(
} else { &cfg, &http, &ipc, &capture, &playback, &mut cmd_rx, &requeue,
if capturing { &mut conv, &mut mic, samples,
capture.stop(); )
capturing = false; .await;
} } else {
playback.clear();
playback.beep(440.0, 90);
}
ipc.emit(Event::Mode { active: mode });
ipc.emit(Event::State { value: "idle" }); ipc.emit(Event::State { value: "idle" });
eprintln!("luna-voice: voice mode {}", if mode { "on" } else { "off" });
} }
} }
Command::Ptt { down: true } => { Command::Ptt { down: true } => {
@@ -336,7 +415,7 @@ async fn daemon() -> Result<()> {
ipc.emit(Event::State { value: "thinking" }); ipc.emit(Event::State { value: "thinking" });
let heard = let heard =
match stt::transcribe(&cfg.whisper_bin, &cfg.whisper_model, &samples).await { match stt::transcribe(&cfg.whisper_bin, &cfg.whisper_model, &cfg.whisper_language, &samples).await {
Ok(h) => h, Ok(h) => h,
Err(e) => { Err(e) => {
eprintln!("luna-voice: {e:#}"); eprintln!("luna-voice: {e:#}");
@@ -358,13 +437,19 @@ async fn daemon() -> Result<()> {
continue; continue;
} }
run_turn(&cfg, &http, &ipc, &capture, &playback, &mut cmd_rx, &requeue, &mut conv, heard) run_turn(
.await; &cfg, &http, &ipc, &capture, &playback, &mut cmd_rx, &requeue, &mut conv,
&mut mic, heard,
)
.await;
} }
Command::Say { text } => { Command::Say { text } => {
ipc.emit(Event::State { value: "thinking" }); ipc.emit(Event::State { value: "thinking" });
run_turn(&cfg, &http, &ipc, &capture, &playback, &mut cmd_rx, &requeue, &mut conv, text) run_turn(
.await; &cfg, &http, &ipc, &capture, &playback, &mut cmd_rx, &requeue, &mut conv,
&mut mic, text,
)
.await;
} }
Command::Cancel => { Command::Cancel => {
playback.clear(); playback.clear();
@@ -437,9 +522,10 @@ async fn run_turn(
cmd_rx: &mut mpsc::Receiver<Command>, cmd_rx: &mut mpsc::Receiver<Command>,
requeue: &mpsc::Sender<Command>, requeue: &mpsc::Sender<Command>,
conv: &mut Conversation, conv: &mut Conversation,
mic: &mut Mic,
heard: String, heard: String,
) { ) {
if let Err(e) = turn(cfg, http, ipc, capture, playback, cmd_rx, requeue, conv, heard).await { if let Err(e) = turn(cfg, http, ipc, capture, playback, cmd_rx, requeue, conv, mic, heard).await {
eprintln!("luna-voice: {e:#}"); eprintln!("luna-voice: {e:#}");
ipc.emit(Event::Error { message: e.to_string() }); ipc.emit(Event::Error { message: e.to_string() });
notify(&e.to_string()); notify(&e.to_string());
@@ -457,6 +543,7 @@ async fn turn(
cmd_rx: &mut mpsc::Receiver<Command>, cmd_rx: &mut mpsc::Receiver<Command>,
requeue: &mpsc::Sender<Command>, requeue: &mpsc::Sender<Command>,
conv: &mut Conversation, conv: &mut Conversation,
mic: &mut Mic,
heard: String, heard: String,
) -> Result<()> { ) -> Result<()> {
let history = &mut conv.history; let history = &mut conv.history;
@@ -481,16 +568,21 @@ async fn turn(
voice_id: cfg.voice_id.clone(), voice_id: cfg.voice_id.clone(),
model: cfg.tts_model.clone(), model: cfg.tts_model.clone(),
}; };
let keep_tags = tts_cfg.is_v3(); let keep_tags = tts_cfg.uses_dialogue();
let speech = tokio::spawn({ let speech = tokio::spawn({
async move { tts::speak(&tts_cfg, sentence_rx, event_tx).await } async move { tts::speak(&tts_cfg, sentence_rx, event_tx).await }
}); });
// Set once her first audio is queued; from then on the mic switch is
// silent.
let speaking = Arc::new(AtomicBool::new(false));
// Audio and visemes flow to the speaker/shell on their own task so the // Audio and visemes flow to the speaker/shell on their own task so the
// reply stream is never blocked by playback. // reply stream is never blocked by playback.
let player = tokio::spawn({ let player = tokio::spawn({
let ipc = ipc.clone(); let ipc = ipc.clone();
let playback = playback.clone(); let playback = playback.clone();
let speaking = speaking.clone();
async move { async move {
let mut started = false; let mut started = false;
while let Some(ev) = event_rx.recv().await { while let Some(ev) = event_rx.recv().await {
@@ -498,6 +590,7 @@ async fn turn(
tts::SpeechEvent::Audio(pcm) => { tts::SpeechEvent::Audio(pcm) => {
if !started { if !started {
started = true; started = true;
speaking.store(true, Ordering::Relaxed);
ipc.emit(Event::SpeechStart); ipc.emit(Event::SpeechStart);
ipc.emit(Event::State { value: "speaking" }); ipc.emit(Event::State { value: "speaking" });
} }
@@ -552,12 +645,24 @@ async fn turn(
ipc.emit(Event::Caption { speaker: "luna", text }); ipc.emit(Event::Caption { speaker: "luna", text });
} }
}; };
while let Some(delta) = delta_rx.recv().await { // A reply with tool calls can stream for minutes, so commands are taken
for sentence in splitter.push(&delta) { // here too: the mic switch has to answer now, not once she is done.
caption(&sentence); let mut cancelled = false;
billed += sentence.chars().count(); loop {
if sentence_tx.send(sentence).await.is_err() { tokio::select! {
break; delta = delta_rx.recv() => {
let Some(delta) = delta else { break };
for sentence in splitter.push(&delta) {
caption(&sentence);
billed += sentence.chars().count();
if sentence_tx.send(sentence).await.is_err() {
break;
}
}
}
Some(cmd) = cmd_rx.recv() => {
let speaking = speaking.load(Ordering::Relaxed);
cancelled |= mid_turn(cmd, speaking, mic, capture, playback, ipc, &mut deferred);
} }
} }
} }
@@ -580,10 +685,24 @@ async fn turn(
// finished" is invisible. // finished" is invisible.
let grace = tokio::time::Instant::now() + Duration::from_millis(cfg.barge_in_grace_ms); let grace = tokio::time::Instant::now() + Duration::from_millis(cfg.barge_in_grace_ms);
loop { loop {
// try_recv POPS, so anything not handled is destroyed: an `if let
// Ok(Cancel)` once silently ate every `say` and `toggle` sent while
// she was talking, which presents as a keypress that does nothing.
if let Ok(cmd) = cmd_rx.try_recv() {
let speaking = speaking.load(Ordering::Relaxed);
cancelled |= mid_turn(cmd, speaking, mic, capture, playback, ipc, &mut deferred);
}
if cancelled {
playback.clear();
ipc.emit(Event::SpeechStop { reason: "cancelled" });
break;
}
if speech.is_finished() && playback.pending() == 0 { if speech.is_finished() && playback.pending() == 0 {
break; break;
} }
if tokio::time::Instant::now() > grace // A muted mic does not hear you, so it cannot interrupt her either.
if mic.on
&& tokio::time::Instant::now() > grace
&& capture.level() > floor * cfg.barge_in_mult && capture.level() > floor * cfg.barge_in_mult
{ {
playback.clear(); playback.clear();
@@ -595,27 +714,6 @@ async fn turn(
)); ));
break; break;
} }
// Commands arriving mid-playback. try_recv POPS, so anything not
// handled here is destroyed: an `if let Ok(Cancel)` silently ate
// every `say`, `toggle` and `mode off` sent while she was talking,
// which presents as a keypress that does nothing.
match cmd_rx.try_recv() {
Ok(Command::Cancel) => {
playback.clear();
ipc.emit(Event::SpeechStop { reason: "cancelled" });
break;
}
// Leaving voice mode has to shut her up immediately; the mode
// change itself is replayed below.
Ok(cmd @ Command::Mode { .. }) => {
playback.clear();
ipc.emit(Event::SpeechStop { reason: "cancelled" });
deferred.push(cmd);
break;
}
Ok(cmd) => deferred.push(cmd),
Err(_) => {}
}
ipc.emit(Event::Amplitude { rms: capture.level() }); ipc.emit(Event::Amplitude { rms: capture.level() });
tokio::time::sleep(Duration::from_millis(50)).await; tokio::time::sleep(Duration::from_millis(50)).await;
} }
+28 -4
View File
@@ -6,7 +6,12 @@ use tokio::process::Command;
/// Shells out to whisper-cli rather than linking whisper.cpp: nixpkgs already /// Shells out to whisper-cli rather than linking whisper.cpp: nixpkgs already
/// ships whisper-cpp-vulkan built against this box's GPU stack, and a bundled /// ships whisper-cpp-vulkan built against this box's GPU stack, and a bundled
/// build would have to rediscover that at cargo time. /// build would have to rediscover that at cargo time.
pub async fn transcribe(bin: &str, model: &Path, samples: &[f32]) -> Result<String> { pub async fn transcribe(
bin: &str,
model: &Path,
language: &str,
samples: &[f32],
) -> Result<String> {
// Whisper hallucinates confident words into silence — "you", "Thank // Whisper hallucinates confident words into silence — "you", "Thank
// you.", "Bye." — which then reach luna as if spoken. Duration alone does // you.", "Bye." — which then reach luna as if spoken. Duration alone does
// not catch it (a held key over a quiet room is long AND empty), so gate // not catch it (a held key over a quiet room is long AND empty), so gate
@@ -26,7 +31,7 @@ pub async fn transcribe(bin: &str, model: &Path, samples: &[f32]) -> Result<Stri
.arg(&wav) .arg(&wav)
// -nt: transcript only, no [00:00:00] prefixes. -np: no progress // -nt: transcript only, no [00:00:00] prefixes. -np: no progress
// banner. Together they make stdout exactly the text. // banner. Together they make stdout exactly the text.
.args(["-nt", "-np"]) .args(["-nt", "-np", "-l", language])
.output() .output()
.await?; .await?;
let _ = std::fs::remove_file(&wav); let _ = std::fs::remove_file(&wav);
@@ -37,7 +42,11 @@ pub async fn transcribe(bin: &str, model: &Path, samples: &[f32]) -> Result<Stri
String::from_utf8_lossy(&out.stderr).trim() String::from_utf8_lossy(&out.stderr).trim()
); );
} }
Ok(clean(&String::from_utf8_lossy(&out.stdout))) let text = clean(&String::from_utf8_lossy(&out.stdout));
if subtitle_credit(&text) {
return Ok(String::new());
}
Ok(text)
} }
/// Scales a quiet recording up before whisper sees it. /// Scales a quiet recording up before whisper sees it.
@@ -79,6 +88,14 @@ fn has_speech(samples: &[f32]) -> bool {
}) })
} }
/// Multilingual whisper fills silence with the subtitle credits it was trained
/// on ("Untertitel im Auftrag des ZDF, 2017", "Untertitel der Amara.org-Community").
/// Nobody says these to luna, so the whole transcript is dropped.
fn subtitle_credit(text: &str) -> bool {
let t = text.to_lowercase();
t.contains("untertitel") || t.contains("amara.org")
}
/// whisper emits bracketed non-speech annotations ([BLANK_AUDIO], (wind /// whisper emits bracketed non-speech annotations ([BLANK_AUDIO], (wind
/// blowing)) that are not words and must not reach the agent. /// blowing)) that are not words and must not reach the agent.
fn clean(raw: &str) -> String { fn clean(raw: &str) -> String {
@@ -97,7 +114,7 @@ fn clean(raw: &str) -> String {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{clean, has_speech, normalize}; use super::{clean, has_speech, normalize, subtitle_credit};
use crate::audio::STT_RATE; use crate::audio::STT_RATE;
fn peak(v: &[f32]) -> f32 { fn peak(v: &[f32]) -> f32 {
@@ -165,6 +182,13 @@ mod tests {
assert_eq!(clean("[ music ] real words"), "real words"); assert_eq!(clean("[ music ] real words"), "real words");
} }
#[test]
fn drops_subtitle_credits() {
assert!(subtitle_credit("Untertitel im Auftrag des ZDF, 2017"));
assert!(subtitle_credit("Untertitel der Amara.org-Community"));
assert!(!subtitle_credit("Ist das Backup auf jupiter gelaufen?"));
}
#[test] #[test]
fn collapses_whitespace() { fn collapses_whitespace() {
assert_eq!(clean(" a b \n c "), "a b c"); assert_eq!(clean(" a b \n c "), "a b c");
+31 -13
View File
@@ -23,10 +23,10 @@ pub struct TtsConfig {
} }
impl TtsConfig { impl TtsConfig {
/// v3 is not served on the TTS websocket at all; it streams only over /// v3 and v4 are not served on the TTS websocket at all; they stream only
/// Text to Dialogue, a different protocol. /// over Text to Dialogue, a different protocol. Only these perform tags.
pub fn is_v3(&self) -> bool { pub fn uses_dialogue(&self) -> bool {
self.model.starts_with("eleven_v3") self.model.starts_with("eleven_v3") || self.model.starts_with("eleven_v4")
} }
} }
@@ -60,7 +60,7 @@ pub async fn speak(
sentences: mpsc::Receiver<String>, sentences: mpsc::Receiver<String>,
events: mpsc::Sender<SpeechEvent>, events: mpsc::Sender<SpeechEvent>,
) -> Result<()> { ) -> Result<()> {
if cfg.is_v3() { if cfg.uses_dialogue() {
speak_dialogue(cfg, sentences, events).await speak_dialogue(cfg, sentences, events).await
} else { } else {
speak_tts(cfg, sentences, events).await speak_tts(cfg, sentences, events).await
@@ -186,7 +186,7 @@ async fn read_audio(
// Alignment times may be per-chunk or cumulative depending on the // Alignment times may be per-chunk or cumulative depending on the
// model; `emitted_ms` lets us normalise either into one timeline. // model; `emitted_ms` lets us normalise either into one timeline.
let mut emitted_ms: u32 = 0; let mut emitted_ms: u32 = 0;
// v3 audio tags come back as characters, and one can straddle chunks. // Audio tags come back as characters, and one can straddle chunks.
let mut in_tag = false; let mut in_tag = false;
let mut result = Ok(()); let mut result = Ok(());
while let Some(Ok(msg)) = source.next().await { while let Some(Ok(msg)) = source.next().await {
@@ -266,7 +266,7 @@ fn absolutize(starts: &[i64], emitted_ms: u32) -> Vec<i64> {
pub struct SentenceSplitter { pub struct SentenceSplitter {
buf: String, buf: String,
in_think: bool, in_think: bool,
/// Whether v3 audio tags survive to the synthesiser or are dropped. /// Whether audio tags survive to the synthesiser or are dropped.
keep_tags: bool, keep_tags: bool,
} }
@@ -342,17 +342,17 @@ fn drain_sentences(buf: &mut String, force: bool, keep_tags: bool) -> Vec<String
out out
} }
/// Byte index just past a v3 audio tag starting at `i` ("[laughs]", /// Byte index just past an audio tag starting at `i` ("[laughs]",
/// "[clears throat]"), if there is one. Letters and spaces only, so /// "[whispers, in a German accent]"), if there is one. No digits, so "[1]"
/// "[1]" or a markdown link stays ordinary noise. /// stays ordinary noise; the length cap keeps a bracketed sentence out.
fn tag_end(s: &str, i: usize) -> Option<usize> { fn tag_end(s: &str, i: usize) -> Option<usize> {
let rest = s[i..].strip_prefix('[')?; let rest = s[i..].strip_prefix('[')?;
let close = rest.find(']')?; let close = rest.find(']')?;
let body = &rest[..close]; let body = &rest[..close];
let end = i + 1 + close + 1; let end = i + 1 + close + 1;
let ok = !body.trim().is_empty() let ok = !body.trim().is_empty()
&& body.len() <= 40 && body.len() <= 80
&& body.chars().all(|c| c.is_alphabetic() || c == ' ' || c == '-') && body.chars().all(|c| c.is_alphabetic() || matches!(c, ' ' | '-' | ',' | '\''))
&& !s[end..].starts_with('('); && !s[end..].starts_with('(');
ok.then_some(end) ok.then_some(end)
} }
@@ -491,20 +491,38 @@ mod tests {
} }
#[test] #[test]
fn audio_tags_survive_for_v3_only() { fn audio_tags_survive_for_dialogue_models_only() {
let s = "[laughs]Fine, boss. [clears throat] Na gut."; let s = "[laughs]Fine, boss. [clears throat] Na gut.";
assert_eq!(clean_for_speech(s, true), "[laughs] Fine, boss. [clears throat] Na gut."); assert_eq!(clean_for_speech(s, true), "[laughs] Fine, boss. [clears throat] Na gut.");
assert_eq!(clean_for_speech(s, false), "Fine, boss. Na gut."); assert_eq!(clean_for_speech(s, false), "Fine, boss. Na gut.");
} }
#[test]
fn free_text_directions_are_tags() {
let s = "[whispers, in a German accent] Na gut. [like she's half asleep] Okay.";
assert_eq!(clean_for_speech(s, true), s);
assert_eq!(clean_for_speech(s, false), "Na gut. Okay.");
}
#[test] #[test]
fn brackets_that_are_not_tags_stay_noise() { fn brackets_that_are_not_tags_stay_noise() {
assert_eq!(clean_for_speech("see [1] and [the docs](x)", true), "see 1 and the docs x"); assert_eq!(clean_for_speech("see [1] and [the docs](x)", true), "see 1 and the docs x");
assert_eq!(clean_for_speech("see [1, 2]", true), "see 1, 2");
assert_eq!(clean_for_speech("[see above, then reboot](x)", true), "see above, then reboot x");
} }
#[test] #[test]
fn captions_hide_tags() { fn captions_hide_tags() {
assert_eq!(strip_tags("[sighs] Okay, boss."), "Okay, boss."); assert_eq!(strip_tags("[sighs] Okay, boss."), "Okay, boss.");
assert_eq!(strip_tags("[whispers, in a German accent] Na gut."), "Na gut.");
}
#[test]
fn v4_streams_over_dialogue() {
let cfg = |m: &str| TtsConfig { key: String::new(), voice_id: String::new(), model: m.into() };
assert!(cfg("eleven_v4_turbo").uses_dialogue());
assert!(cfg("eleven_v3_conversational").uses_dialogue());
assert!(!cfg("eleven_flash_v2_5").uses_dialogue());
} }
#[test] #[test]
+20 -20
View File
@@ -41,23 +41,23 @@
}, },
{ {
"pname": "Microsoft.AspNetCore.App.Ref", "pname": "Microsoft.AspNetCore.App.Ref",
"version": "8.0.29", "version": "8.0.31",
"hash": "sha256-0wK5Lsa4a1ani/gvSzsqyuY3R4MBuH/9XOyZeWCUWoU=" "hash": "sha256-vMnNfXlEkZq5fpys8z5SnCn9q/BYXLw+CXcEdGeD6hg="
}, },
{ {
"pname": "Microsoft.AspNetCore.App.Ref", "pname": "Microsoft.AspNetCore.App.Ref",
"version": "9.0.18", "version": "9.0.20",
"hash": "sha256-0qkb9Gbxlyyw8rKxDTm9OqdW89DIi1qolGK85HLwc2k=" "hash": "sha256-ZMaHC0MFs2YvW/fHGsxuXZnS74rcS9GJ1LGaMuscdMo="
}, },
{ {
"pname": "Microsoft.AspNetCore.App.Runtime.linux-x64", "pname": "Microsoft.AspNetCore.App.Runtime.linux-x64",
"version": "8.0.29", "version": "8.0.31",
"hash": "sha256-iiDWZa7MkybKwozVKIV4Eq0PGzirxeyjFLnoxPyAHiQ=" "hash": "sha256-0sAwUHBaAhI2vIRlSD/HtNBrJHa132JTzfnWIDaPJXY="
}, },
{ {
"pname": "Microsoft.AspNetCore.App.Runtime.linux-x64", "pname": "Microsoft.AspNetCore.App.Runtime.linux-x64",
"version": "9.0.18", "version": "9.0.20",
"hash": "sha256-ETNi+pMo8nNSgHMLKgi/VFMla/duHI2CQlJlm1FdyKc=" "hash": "sha256-ll6isPNcUHbChwtBEh+vIi6AI1DMf+cRaxk/q+d5Iyg="
}, },
{ {
"pname": "Microsoft.Bcl.TimeProvider", "pname": "Microsoft.Bcl.TimeProvider",
@@ -216,33 +216,33 @@
}, },
{ {
"pname": "Microsoft.NETCore.App.Host.linux-x64", "pname": "Microsoft.NETCore.App.Host.linux-x64",
"version": "8.0.29", "version": "8.0.31",
"hash": "sha256-T/eXkzT3V3T1Yasc1cUZ/jLOWJY3zp/GxJTCT24gnAw=" "hash": "sha256-MGH8ZnjM4fZFp63mbLNpkojI2T7TvpvNgvpjOGfrTIE="
}, },
{ {
"pname": "Microsoft.NETCore.App.Host.linux-x64", "pname": "Microsoft.NETCore.App.Host.linux-x64",
"version": "9.0.18", "version": "9.0.20",
"hash": "sha256-h36uAGfY36RKon6QU3lP3tsVlMVZ842lvdGiLcHO7Ko=" "hash": "sha256-lsqBpxZyE13FPNsQrSEXDyjTpXnF6PX/hnUx4a+IikM="
}, },
{ {
"pname": "Microsoft.NETCore.App.Ref", "pname": "Microsoft.NETCore.App.Ref",
"version": "8.0.29", "version": "8.0.31",
"hash": "sha256-dxAuEUU1VOElQ4CpL9HLhV4KVFtRDAcZS8W0GT2Di6g=" "hash": "sha256-oChiwq8Hnb0R+Fx61PlO1VMFUw4M8Gcd4nnxoSlPIMY="
}, },
{ {
"pname": "Microsoft.NETCore.App.Ref", "pname": "Microsoft.NETCore.App.Ref",
"version": "9.0.18", "version": "9.0.20",
"hash": "sha256-ZFU4lXz/BjJiqU4sykZEYR5j5e745KMf4ZPo0GHnicU=" "hash": "sha256-6FQ6u7gCcf0IabmnZZ2jUU2TpYNQHzcPtqT1BaoaMkI="
}, },
{ {
"pname": "Microsoft.NETCore.App.Runtime.linux-x64", "pname": "Microsoft.NETCore.App.Runtime.linux-x64",
"version": "8.0.29", "version": "8.0.31",
"hash": "sha256-eA5x9NMfCg6JhRmOKKqfBL8+TwtQW/1ONvJeANPJOFA=" "hash": "sha256-J6iRM18YDWcyxaU7SEd5B1O276obx8P4FAE6qWjWqjY="
}, },
{ {
"pname": "Microsoft.NETCore.App.Runtime.linux-x64", "pname": "Microsoft.NETCore.App.Runtime.linux-x64",
"version": "9.0.18", "version": "9.0.20",
"hash": "sha256-DV5iYmqH8j7JIcem8Qu/HLbZuHPVmaTTQuZc8OoDZBk=" "hash": "sha256-hCPvae3q8+fSnPqVWWXkziZsrkATUy2bcLEGjUKC5ik="
}, },
{ {
"pname": "Microsoft.SourceLink.Common", "pname": "Microsoft.SourceLink.Common",
+3
View File
@@ -672,9 +672,12 @@ case "$cmd" in
echo ">> nixos-rebuild $cmd .#$config on darman@$host" echo ">> nixos-rebuild $cmd .#$config on darman@$host"
# --ask-sudo-password, not the deprecated --use-remote-sudo: common.nix sets # --ask-sudo-password, not the deprecated --use-remote-sudo: common.nix sets
# wheelNeedsPassword = true, and --use-remote-sudo never actually prompts. # wheelNeedsPassword = true, and --use-remote-sudo never actually prompts.
# --use-substitutes: the target pulls cache hits itself (compressed) instead
# of the laptop pushing uncompressed NARs over ssh; misses are still pushed.
rebuild=(nix run nixpkgs#nixos-rebuild -- "$cmd" rebuild=(nix run nixpkgs#nixos-rebuild -- "$cmd"
--flake ".#$config" --flake ".#$config"
--target-host "darman@$host" --target-host "darman@$host"
--use-substitutes
--ask-sudo-password) --ask-sudo-password)
item="${HOMELAB_PASS_ITEM:-darman@$config}" item="${HOMELAB_PASS_ITEM:-darman@$config}"
+21 -6
View File
@@ -24,9 +24,12 @@ let
# Pinned like the KittenTTS models on mars: a model that re-downloads at # Pinned like the KittenTTS models on mars: a model that re-downloads at
# first use is a service that fails on a fresh install with no network. # first use is a service that fails on a fresh install with no network.
# small, multilingual: base.en heard "backup" as "Mac up" and turned German
# into English nonsense. ~1s per turn on the 6800 XT vs ~0.4s; turbo was
# ~2.3s for no visible gain.
whisperModel = pkgs.fetchurl { whisperModel = pkgs.fetchurl {
url = "https://huggingface.co/ggerganov/whisper.cpp/resolve/5359861c739e955e79d9a303bcbc70fb988958b1/ggml-base.en.bin"; url = "https://huggingface.co/ggerganov/whisper.cpp/resolve/5359861c739e955e79d9a303bcbc70fb988958b1/ggml-small.bin";
sha256 = "sha256-oDd5yG3zMjB19eeWyyzlAp8A7Ihp7uP9+4l6/jbG0AI="; sha256 = "sha256-G+OpsgY4Z7k35k4ux0gzZKeZF+FX+pjF2UtcH//qmHs=";
}; };
in in
{ {
@@ -58,11 +61,12 @@ in
ttsModel = lib.mkOption { ttsModel = lib.mkOption {
type = lib.types.str; type = lib.types.str;
default = "eleven_v3_conversational"; default = "eleven_v4_turbo";
description = '' description = ''
eleven_v3* streams over the Text to Dialogue socket and performs audio eleven_v3* and eleven_v4* stream over the Text to Dialogue socket and
tags ([laughs], [sighs]); it also gets her German right, which Flash perform audio tags ([laughs], [sighs]); they also get her German right,
reads with an English accent. Anything else uses the TTS socket, e.g. which Flash reads with an English accent. eleven_v4_turbo costs the
same as eleven_v3_conversational. Anything else uses the TTS socket, e.g.
"eleven_flash_v2_5" — half the price per character, faster, no tags. "eleven_flash_v2_5" — half the price per character, faster, no tags.
''; '';
}; };
@@ -87,6 +91,16 @@ in
description = "Substring of the input device name; null uses the system default."; description = "Substring of the input device name; null uses the system default.";
}; };
whisperLanguage = lib.mkOption {
type = lib.types.str;
default = "auto";
description = ''
whisper's -l. "auto" detects per utterance, which costs a second
encoder pass; a fixed code like "en" translates other languages
instead of transcribing them.
'';
};
vadMult = lib.mkOption { vadMult = lib.mkOption {
type = lib.types.float; type = lib.types.float;
default = 1.8; default = 1.8;
@@ -147,6 +161,7 @@ in
LUNA_ELEVENLABS_KEY_FILE = toString cfg.elevenLabsKeyFile; LUNA_ELEVENLABS_KEY_FILE = toString cfg.elevenLabsKeyFile;
LUNA_WHISPER_BIN = "${pkgs.whisper-cpp-vulkan}/bin/whisper-cli"; LUNA_WHISPER_BIN = "${pkgs.whisper-cpp-vulkan}/bin/whisper-cli";
LUNA_WHISPER_MODEL = whisperModel; LUNA_WHISPER_MODEL = whisperModel;
LUNA_WHISPER_LANGUAGE = cfg.whisperLanguage;
LUNA_VAD_MULT = toString cfg.vadMult; LUNA_VAD_MULT = toString cfg.vadMult;
LUNA_VAD_FLOOR = toString cfg.vadFloor; LUNA_VAD_FLOOR = toString cfg.vadFloor;
LUNA_SILENCE_MS = toString cfg.silenceMs; LUNA_SILENCE_MS = toString cfg.silenceMs;
+23
View File
@@ -0,0 +1,23 @@
{ pkgs, ... }:
# Host permissions for reverse engineering Turtle Beach Swarm II devices
# (/mnt/hdd_01/data/Dev/repos/turtle-beach-swarm-re/nixos/turtle-beach-re.nix).
{
# USB traffic capture (/dev/usbmonN), readable by the 'wireshark' group
boot.kernelModules = [ "usbmon" ];
programs.wireshark = {
enable = true;
usbmon.enable = true;
};
users.users.darman.extraGroups = [ "wireshark" ];
# Turtle Beach / ROCCAT devices (vendor 10f5): give the logged-in user access to
# the raw USB device (QEMU passthrough) and hidraw nodes (our own tools).
# Must sort before 73-seat-late.rules for uaccess to apply, hence not extraRules.
services.udev.packages = [
(pkgs.writeTextDir "lib/udev/rules.d/70-turtle-beach.rules" ''
SUBSYSTEM=="usb", ATTR{idVendor}=="10f5", TAG+="uaccess"
KERNEL=="hidraw*", ATTRS{idVendor}=="10f5", TAG+="uaccess"
'')
];
}
+159 -81
View File
@@ -1,103 +1,181 @@
{ config, pkgs, inputs, ... }: { config, lib, pkgs, ... }:
# Immich photo/video library. Native nixpkgs module, not the upstream compose # Immich photo/video library. Postgres (pgvector + vectorchord) and a unix-socket
# stack — it owns its own postgres (pgvector + vectorchord) and a unix-socket redis. # redis are native; the server and machine-learning run as the official images so
# their ~2.5G node/python/onnx stacks live in podman's graphroot on the array
# instead of the system closure on the eMMC.
# #
# Storage lives under /mnt/data/AppData/immich, migrated from the old ZimaOS/CasaOS # Storage lives under /mnt/data/AppData/immich, migrated from the old ZimaOS/CasaOS
# UPLOAD_LOCATION (same subfolder layout); see scripts/immich-import-legacy-db for # UPLOAD_LOCATION (same subfolder layout); see scripts/immich-import-legacy-db for
# the matching DB import. The postgres cluster itself stays on the OS disk. # the matching DB import.
# #
# ⚠️ The immich DB is the only copy of albums/faces/dates — the files alone # ⚠️ The immich DB is the only copy of albums/faces/dates — the files alone
# can't rebuild it. It joins the other unbacked databases on this network. # can't rebuild it. It joins the other unbacked databases on this network.
let let
# Package pinned to nixpkgs-unstable (3.0.3) while the module stays on the 26.05 # Migrations are forward-only: never move this tag backwards.
# pin (2.7.5) — safe only because the two module files are byte-identical version = "v3.2.4";
# (verified by diff; re-check on any input bump). Needed because immich's mediaLocation = "/mnt/data/AppData/immich";
# migrations are forward-only and jupiter's imported DB was last written by mlCache = "/mnt/data/AppData/immich-ml-cache";
# 3.0.0, which 2.7.5 refuses to start against; drop once the pin ships >= 3.0.0. # Containers run as the host's immich user so postgres peer auth and the
# diff <(nixpkgs)/nixos/modules/services/web-apps/immich.nix \ # 0700 media dir keep working; ids are pinned below to keep this stable.
# <(unstable)/nixos/modules/services/web-apps/immich.nix uid = 988;
unstable = import inputs.nixpkgs-unstable { gid = 985;
inherit (pkgs.stdenv.hostPlatform) system; redisGid = 984;
usersGid = 100; # traverse /mnt/data/AppData (drwx--x--- darman:users)
# IMMICH_CONFIG_FILE is all-or-nothing: undeclared keys fall back to immich's
# defaults, not the admin UI's saved values (which stay in system_metadata and
# return if this file is dropped), and the admin settings UI goes read-only. An
# unknown/misspelled key is a hard startup failure, so keys are copied verbatim
# from `defaults` in immich's dist/config.js.
settings = {
server.externalDomain = "https://immich.mgaction.town";
newVersionCheck.enabled = false; # the image tag pins the version, not immich
# OIDC via Authentik on neptun; the application/provider is created by hand
# in its UI (like headscale's and headplane's, separate apps).
oauth = {
enabled = true;
# Authentik's per-application issuer. Trailing slash matters: immich
# appends /.well-known/openid-configuration to it.
issuerUrl = "https://auth.mgaction.town/application/o/immich/";
# Not a secret (it is sent in the browser redirect).
clientId = "FxrkWFe8keBrN83tu03UbAshSck52he2GphJDYSQ";
clientSecret = config.sops.placeholder.immich_oauth_client_secret;
scope = "openid email profile";
buttonText = "Login with Authentik";
# Matches by email, so the 2 imported users adopt their Authentik account
# instead of getting a duplicate.
autoRegister = true;
# Leave the password form reachable — autoLaunch would bounce straight
# to Authentik, locking everyone out if the OIDC app is misconfigured.
autoLaunch = false;
# Without this, logout dumps you on Authentik's own page instead of back
# here. Ends the immich session only; the Authentik SSO session survives.
endSessionEndpoint = "https://auth.mgaction.town/application/o/immich/end-session?post_logout_redirect_url=https://immich.mgaction.town";
# The mobile app can't follow a browser redirect back to a custom
# scheme through Authentik, so immich bounces it via this endpoint.
mobileOverrideEnabled = true;
mobileRedirectUri = "https://immich.mgaction.town/api/oauth/mobile-redirect";
};
}; };
runAs = [
"--network=host"
"--user=${toString uid}:${toString gid}"
"--group-add=${toString usersGid}"
];
in in
{ {
services.immich = { # What the nixpkgs immich module set up besides the server itself — not used
# because evaluating it forces its (insecure, too old) default package.
services.postgresql = {
enable = true; enable = true;
# Both the server and immich-machine-learning follow this: the module takes ensureDatabases = [ "immich" ];
# the ML service from cfg.package.machine-learning (passthru). ensureUsers = [{
package = unstable.immich; name = "immich";
# Listens on all interfaces: :2283 stays closed on the LAN (no ensureDBOwnership = true;
# openFirewall), reachable over tailscale0 and via localhost (caddy). ensureClauses.login = true;
host = "0.0.0.0"; }];
port = 2283; extensions = ps: [ ps.pgvector ps.vectorchord ];
mediaLocation = "/mnt/data/AppData/immich";
machine-learning.enable = true;
# ⚠️ Setting `settings` at all switches immich to IMMICH_CONFIG_FILE mode,
# which is all-or-nothing: undeclared keys fall back to immich's defaults, not
# the admin UI's saved values (which stay in system_metadata and return if
# this block is deleted), and the admin settings UI goes read-only. An
# unknown/misspelled key is a hard startup failure here (just a warning
# without a config file), so keys are copied verbatim from `defaults` in
# immich's dist/config.js.
settings = { settings = {
server.externalDomain = "https://immich.mgaction.town"; shared_preload_libraries = [ "vchord.so" ];
newVersionCheck.enabled = false; # nixpkgs pins the version, not immich search_path = "\"$user\", public, vectors";
# OIDC via Authentik on neptun; the application/provider is created by hand
# in its UI (like headscale's and headplane's, separate apps) — only the
# client secret is managed here (hosts/neptun/secrets.nix).
oauth = {
enabled = true;
# Authentik's per-application issuer. Trailing slash matters: immich
# appends /.well-known/openid-configuration to it.
issuerUrl = "https://auth.mgaction.town/application/o/immich/";
# Authentik generates this; not a secret (it is sent in the browser
# redirect), so it lives here rather than in sops.
clientId = "FxrkWFe8keBrN83tu03UbAshSck52he2GphJDYSQ";
# Read at runtime via systemd LoadCredential — never lands in the
# world-readable /nix/store copy of the rendered config.
clientSecret._secret = config.sops.secrets.immich_oauth_client_secret.path;
scope = "openid email profile";
buttonText = "Login with Authentik";
# Matches by email, so the 2 imported users adopt their Authentik account
# instead of getting a duplicate.
autoRegister = true;
# Leave the password form reachable — autoLaunch would bounce straight
# to Authentik, locking everyone out if the OIDC app is misconfigured.
autoLaunch = false;
# Without this, immich falls back to the IdP's discovered
# end_session_endpoint and logout dumps you on Authentik's own page
# instead of back here — must be an absolute url, mirroring immich's
# internal LOGIN_URL. This ends the immich session only; the Authentik
# SSO session survives, so the next login skips the credential prompt —
# drop this line to end both.
endSessionEndpoint = "https://auth.mgaction.town/application/o/immich/end-session?post_logout_redirect_url=https://immich.mgaction.town";
# The mobile app can't follow a browser redirect back to a custom
# scheme through Authentik, so immich bounces it via this endpoint.
mobileOverrideEnabled = true;
mobileRedirectUri = "https://immich.mgaction.town/api/oauth/mobile-redirect";
};
}; };
# Hardware transcoding needs accelerationDevices set explicitly (e.g. };
# "/dev/dri/renderD128"); default CPU-only transcode is slow on the # Reindex when vectorchord changes version:
# ZimaBlade's Celeron but only runs on upload. # https://docs.immich.app/administration/postgres-standalone/#updating-vectorchord
systemd.services.postgresql-setup.serviceConfig.ExecStartPost =
let
extensions = [ "unaccent" "uuid-ossp" "cube" "earthdistance" "pg_trgm" "vector" "vchord" ];
sqlFile = pkgs.writeText "immich-pgvectors-setup.sql" ''
SELECT COALESCE(installed_version, ''') AS vchord_version_before FROM pg_available_extensions WHERE name = 'vchord' \gset
${lib.concatMapStringsSep "\n" (ext: "CREATE EXTENSION IF NOT EXISTS \"${ext}\";") extensions}
${lib.concatMapStringsSep "\n" (ext: "ALTER EXTENSION \"${ext}\" UPDATE;") extensions}
ALTER SCHEMA public OWNER TO immich;
SELECT COALESCE(installed_version, ''') AS vchord_version_after FROM pg_available_extensions WHERE name = 'vchord' \gset
SELECT (:'vchord_version_before' != ''' AND :'vchord_version_before' != :'vchord_version_after') AS has_vchord_updated \gset
\if :has_vchord_updated
REINDEX INDEX face_index;
REINDEX INDEX clip_index;
\endif
'';
in
[ "${lib.getExe' config.services.postgresql.package "psql"} -d immich -f ${sqlFile}" ];
services.redis.servers.immich = {
enable = true;
port = 0; # unix socket only
}; };
# /mnt/data/AppData is drwx--x--- darman:users; immich only needs group "users" users.users.immich = {
# to traverse into it — the dir itself stays 0700 immich:immich (tmpfiles + isSystemUser = true;
# UMask=0077 reassert that), so this grants nothing else. group = "immich";
users.users.immich.extraGroups = [ "users" ]; inherit uid;
# /mnt/data/AppData is drwx--x--- darman:users; group "users" only grants traversal.
extraGroups = [ "users" ];
};
users.groups.immich.gid = gid;
users.groups.redis-immich.gid = redisGid;
sops.templates."immich-config.json" = {
owner = "immich";
content = builtins.toJSON settings;
};
virtualisation.oci-containers.containers = {
immich-server = {
image = "ghcr.io/immich-app/immich-server:${version}";
# :2283 on all interfaces but closed on the LAN (no firewall rule):
# reachable over tailscale0 and via localhost (caddy).
extraOptions = runAs ++ [ "--group-add=${toString redisGid}" ];
volumes = [
# Same path inside as out: the DB stores absolute asset paths.
"${mediaLocation}:${mediaLocation}"
"/run/postgresql:/run/postgresql"
"/run/redis-immich:/run/redis-immich"
"${config.sops.templates."immich-config.json".path}:/run/immich/config.json:ro"
"/etc/localtime:/etc/localtime:ro"
];
environment = {
DB_URL = "postgresql:///immich?host=/run/postgresql";
REDIS_SOCKET = "/run/redis-immich/redis.sock";
IMMICH_HOST = "0.0.0.0";
IMMICH_PORT = "2283";
IMMICH_MEDIA_LOCATION = mediaLocation;
IMMICH_MACHINE_LEARNING_URL = "http://127.0.0.1:3003";
IMMICH_CONFIG_FILE = "/run/immich/config.json";
};
};
immich-machine-learning = {
image = "ghcr.io/immich-app/immich-machine-learning:${version}";
extraOptions = runAs;
# Models (~1G) are re-downloaded on first use.
volumes = [ "${mlCache}:/cache" ];
environment = {
IMMICH_HOST = "127.0.0.1";
IMMICH_PORT = "3003";
MACHINE_LEARNING_CACHE_FOLDER = "/cache";
XDG_CACHE_HOME = "/cache";
MPLCONFIGDIR = "/cache/matplotlib";
};
};
};
systemd.services.podman-immich-server = {
requires = [ "postgresql.target" "redis-immich.service" ];
after = [ "postgresql.target" "redis-immich.service" ];
# Without this, immich starts before /mnt/data mounts and writes uploads onto
# the 29G eMMC, invisibly, under the future mountpoint.
unitConfig.RequiresMountsFor = [ "/mnt/data" ];
};
systemd.services.podman-immich-machine-learning.unitConfig.RequiresMountsFor = [ "/mnt/data" ];
# mediaLocation is outside /var/lib, so the module won't create it — this rule # mediaLocation is outside /var/lib, so the module won't create it — this rule
# only adjusts perms on the dir the legacy import already created. # only adjusts perms on the dir the legacy import already created.
systemd.tmpfiles.rules = [ systemd.tmpfiles.rules = [
"d /mnt/data/AppData/immich 0700 immich immich -" "d ${mediaLocation} 0700 immich immich -"
"d ${mlCache} 0700 immich immich -"
]; ];
# The unit's automatic RequiresMountsFor doesn't cover mediaLocation — without
# this, immich starts before /mnt/data mounts and writes uploads onto the 29G
# eMMC, invisibly, under the future mountpoint.
systemd.services.immich-server.unitConfig.RequiresMountsFor = [ "/mnt/data" ];
} }
+1 -1
View File
@@ -10,7 +10,7 @@
# "video"/"render" cover the DRI nodes for hardware transcoding — card1 is # "video"/"render" cover the DRI nodes for hardware transcoding — card1 is
# 0660 root:video (not guaranteed 0666 like renderD128), so don't rely on # 0660 root:video (not guaranteed 0666 like renderD128), so don't rely on
# device perms alone. Harmless on a GPU-less host: the driver itself is # device perms alone. Harmless on a GPU-less host: the driver itself is
# enabled per-host (e.g. jupiter's hardware.graphics + intel-media-driver). # enabled per-host (e.g. jupiter's LIBVA_DRIVERS_PATH -> intel-media-driver).
users.users.jellyfin.extraGroups = [ "users" "video" "render" ]; users.users.jellyfin.extraGroups = [ "users" "video" "render" ];
# The upstream module hardcodes UMask=0077, which made jellyfin write # The upstream module hardcodes UMask=0077, which made jellyfin write
+17 -16
View File
@@ -1,26 +1,27 @@
{ ... }: { ... }:
# Seerr (formerly Jellyseerr) — request manager for Jellyfin, talking to # Seerr (formerly Jellyseerr) — request manager for Jellyfin, talking to
# Sonarr/Radarr; fresh install, no migrated data. configDir stays at the # Sonarr/Radarr. Runs the official image rather than the nixpkgs package, whose
# module default, with AppData bind-mounted onto it instead (same # ~1.5G node_modules would otherwise sit in the system closure on the eMMC.
# DynamicUser/StateDirectory issue as prowlarr.nix — see that file for why,
# and why the mount targets /var/lib/private/seerr rather than the public path).
{ {
services.seerr.enable = true; virtualisation.oci-containers.containers.seerr = {
image = "ghcr.io/seerr-team/seerr:v3.2.0";
# `nofail` for the same reason as prowlarr.nix — see the comment there: an # Host networking so "localhost" reaches jellyfin/sonarr/radarr (native
# array-backed bind without it fails local-fs.target and boots to an # services) — same reason as clonarr.nix. Listens on :5055.
# unusable emergency shell. extraOptions = [ "--network=host" "--user=1000:100" "--init" ];
fileSystems."/var/lib/private/seerr" = { volumes = [ "/mnt/data/AppData/seerr:/app/config" ];
device = "/mnt/data/AppData/seerr"; environment = {
fsType = "none"; TZ = "Europe/Berlin";
options = [ "bind" "nofail" ]; PORT = "5055";
};
}; };
# Only /var/lib/seerr (eMMC) is picked up automatically; pin to the array. # Z: the config was written by the old module's DynamicUser (a random uid);
systemd.services.seerr.unitConfig.RequiresMountsFor = [ "/mnt/data" ]; # hand it to darman, which the container runs as.
systemd.tmpfiles.rules = [ systemd.tmpfiles.rules = [
"d /mnt/data/AppData/seerr 0755 darman users -" "d /mnt/data/AppData/seerr 0755 darman users -"
"Z /mnt/data/AppData/seerr - darman users -"
]; ];
systemd.services.podman-seerr.unitConfig.RequiresMountsFor = [ "/mnt/data" ];
} }
+6 -6
View File
@@ -22,13 +22,13 @@
# pihole's `address=/<host>.sol/<ip>` would swallow this whole zone. # pihole's `address=/<host>.sol/<ip>` would swallow this whole zone.
base_domain = "orbit.sol"; base_domain = "orbit.sol";
# pihole on mercury, over the tailnet, so roaming devices get ad blocking # pihole on mercury, over the tailnet, so roaming devices get ad blocking
# and .sol names everywhere. Deliberately no public fallback — tailscale # and .sol names everywhere. Quad9 is the fallback: a dead tailscaled on
# treats this as a set, so adding one would let queries slip past the # mercury once took out DNS tailnet-wide. Tailscale treats this as a set,
# filter whenever mercury is briefly slow, at the cost of mercury being a # so whenever mercury is slow some queries skip the filter (and .sol names
# single point of failure for tailnet DNS. # can briefly NXDOMAIN).
# ⚠️ Hardcoded tailnet address — check `headscale nodes list` if it # ⚠️ Hardcoded tailnet address — check `headscale nodes list` if it
# changes (mercury re-enrolled) and DNS dies tailnet-wide. # changes (mercury re-enrolled).
nameservers.global = [ "100.64.0.4" ]; nameservers.global = [ "100.64.0.4" "9.9.9.9" ];
# Must be set here, not via the module's `dns.split` option — nixpkgs # Must be set here, not via the module's `dns.split` option — nixpkgs
# renders that one level too high, but headscale (and headplane) read # renders that one level too high, but headscale (and headplane) read