1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
|
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
import Quickshell
import Quickshell.Io
import QtQuick
import "../.."
import "Config.js" as C
// desktop-assistant's daemon settings: its config.toml, the tools it loads,
// and a restart, since it reads both only at startup. The module holds the
// data and the writes; AssistantPage is the view. See README.md.
Module {
id: am
name: "assistant"
label: "Assistant"
// nf-fa-comments, present in Inconsolata Nerd Font.
icon: "\uf086"
settings: true
group: "Assistant"
keywords: ["llm", "model", "llama", "server", "prompt", "temperature", "thinking",
"rounds", "tools", "environment", "daemon", "restart"]
readonly property string home: Quickshell.env("HOME")
readonly property string daemonDir: home + "/Programming/GIT/desktop-assistant"
readonly property string cfgDir: (Quickshell.env("XDG_CONFIG_HOME") || home + "/.config")
+ "/desktop-assistant"
readonly property string cfgPath: cfgDir + "/config.toml"
readonly property string toolsDir: cfgDir + "/tools"
// The system interpreter, as for calctl: python3 on PATH is a pyenv shim.
readonly property string python: "/usr/bin/python3"
readonly property var keys: ["llm", "system", "tool_rounds", "temperature", "thinking"]
readonly property var labels: ({ llm: "Server", system: "System prompt", tool_rounds: "Tool rounds",
temperature: "Temperature", thinking: "Thinking" })
// config.toml as last read or written; "" when there is none.
property string text: ""
readonly property var values: C.scalars(am.text, am.keys)
readonly property var envList: C.env(am.text)
// The daemon's built-in values, from assistant.py --defaults.
property var defaults: ({})
// [{name, on, description}]
property var tools: []
// A write since the last restart, which the daemon has not read yet.
property bool pending: false
// The router's models, [{id, status}], status as it reports it:
// "loaded", "loading", "unloaded" and so on. Empty when it is down.
property var models: []
// The id being loaded, "" when none is.
property string loading: ""
property string modelError: ""
// The router answers /models and /models/load on the server's root, and
// the OpenAI API under /v1, which is what the daemon's llm points at.
readonly property string llm: am.values.llm ?? am.defaults.llm ?? "http://localhost:8181/v1"
readonly property string routerRoot: am.llm.replace(/\/v1\/?$/, "")
property bool restarting: false
property string status: ""
property string error: ""
searchItems: am.keys.map(k => ({ text: am.labels[k], key: "key:" + k }))
.concat(am.envList.map(e => ({ text: e.key + " = " + e.value, key: "env:" + e.key })))
.concat(am.tools.map(t => ({ text: "tool: " + t.name, key: "tool:" + t.name })))
.concat(am.models.map(m => ({ text: "model: " + m.id, key: "model:" + m.id })))
function refresh() {
fv.reload();
am.listTools();
am.listModels();
if (Object.keys(am.defaults).length === 0)
am.run([am.python, am.daemonDir + "/assistant.py", "--defaults"], null, (code, out) => {
try { if (code === 0) am.defaults = JSON.parse(out); } catch (e) {}
});
}
property FileView fv: FileView {
path: am.cfgPath
watchChanges: true
printErrors: false
onFileChanged: reload()
onLoaded: am.text = text()
onLoadFailed: am.text = ""
}
// One Process per call, so calls never share one (a running Process
// ignores a second start, AGENTS.md). input, when not null, is written
// to stdin and stdin closed. cb(code, stdout, stderr) runs once the exit
// and both streams are in, which arrive in no fixed order.
function run(cmd, input, cb) {
op.createObject(am, { command: cmd, input: input, cb: cb, stdinEnabled: input !== null }).running = true;
}
property Component op: Component {
Process {
id: proc
property var input: null
property var cb: null
property int left: 3
property int code: -1
property string out: ""
property string err: ""
function step() {
if (--left > 0) return;
try { if (proc.cb) proc.cb(proc.code, proc.out, proc.err); }
finally { proc.destroy(); }
}
onStarted: if (proc.input !== null) { proc.write(proc.input); proc.stdinEnabled = false; }
onExited: code => { proc.code = code; proc.step(); }
stdout: StdioCollector { onStreamFinished: { proc.out = text; proc.step(); } }
stderr: StdioCollector { onStreamFinished: { proc.err = text; proc.step(); } }
}
}
// Validates the whole file with tomllib before it replaces the old one,
// atomically, so a bad edit can never leave a config the daemon refuses
// to start with.
readonly property string writer: "import os, sys, tomllib\n"
+ "t = sys.stdin.read()\n"
+ "try:\n tomllib.loads(t)\n"
+ "except tomllib.TOMLDecodeError as e:\n sys.exit(f'not valid TOML: {e}')\n"
+ "p = sys.argv[1]\nos.makedirs(os.path.dirname(p), exist_ok=True)\n"
+ "with open(p + '.tmp', 'w') as f:\n f.write(t)\n"
+ "os.replace(p + '.tmp', p)\n"
function save(t) {
am.run([am.python, "-c", am.writer, am.cfgPath], t, (code, out, err) => {
if (code === 0) { am.text = t; am.pending = true; am.error = ""; }
else am.error = err.trim() || "config.toml could not be written";
});
}
// toml is the value written as TOML, or null to fall back to the default.
function setKey(key, toml) { am.save(C.setScalar(am.text, key, toml)); }
function setEnv(key, value) { am.save(C.setEnv(am.text, key, value)); }
function quote(s) { return C.quote(s); }
// Every tools/*.toml is loaded; *.toml.off is the same file switched off.
readonly property string lister: "import glob, json, os, sys, tomllib\n"
+ "out = []\n"
+ "for p in glob.glob(sys.argv[1] + '/*.toml') + glob.glob(sys.argv[1] + '/*.toml.off'):\n"
+ " on = p.endswith('.toml')\n"
+ " name = os.path.basename(p).removesuffix('.off').removesuffix('.toml')\n"
+ " try:\n d = tomllib.load(open(p, 'rb')).get('description', '')\n"
+ " except Exception as e:\n d = f'unreadable: {e}'\n"
+ " out.append({'name': name, 'on': on, 'description': d})\n"
+ "print(json.dumps(sorted(out, key=lambda t: t['name'])))\n"
function listTools() {
am.run([am.python, "-c", am.lister, am.toolsDir], null, (code, out) => {
try { if (code === 0) am.tools = JSON.parse(out); } catch (e) {}
});
}
function toggleTool(t) {
const on = am.toolsDir + "/" + t.name + ".toml";
const off = on + ".off";
// -n: never overwrite a file that already holds the other name.
am.run(["mv", "-n", t.on ? on : off, t.on ? off : on], null, (code, out, err) => {
if (code === 0) { am.pending = true; am.error = ""; }
else am.error = err.trim() || "could not switch " + t.name;
am.listTools();
});
}
function listModels(done) {
am.run(["curl", "-sf", "-m", "3", am.llm + "/models"], null, (code, out) => {
try {
am.models = code === 0 ? JSON.parse(out).data.map(m => ({ id: m.id, status: m.status?.value ?? "" })) : [];
} catch (e) { am.models = []; }
if (done) done();
});
}
// The router keeps one model resident, so this swaps out whatever is
// loaded, for every client. It does not touch the preferred model: a
// load from the page is for now, and the canvas brings the preferred one
// back when it opens. The list is polled until the router reports the
// model loaded, since the request may return before the load finishes.
function loadModel(id) {
am.modelError = "";
am.loading = id;
am.run(["curl", "-s", "-m", "600", "-X", "POST", "-H", "Content-Type: application/json",
"-d", JSON.stringify({ model: id }), am.routerRoot + "/models/load"], null, (code, out) => {
let err = code === 0 ? "" : "the router did not answer";
try {
const e = JSON.parse(out).error;
// Already running is the outcome asked for, not a failure.
if (e && e.message !== "model is already running") err = e.message;
} catch (x) {}
if (err) { am.modelError = `${id}: ${err}`; am.loading = ""; am.listModels(); }
else { poll.left = 300; poll.start(); }
});
}
// Called when the assistant canvas opens: the preferred model, if one is
// set, still listed, and neither loaded nor loading, is loaded. One model
// and one client at a time is how this desktop runs, so opening the
// assistant is the moment to bring its model back.
function ensurePreferred() {
const id = Prefs.assistantModel;
if (id === "" || am.loading !== "") return;
am.listModels(() => {
const m = am.models.find(x => x.id === id);
if (m && m.status !== "loaded" && m.status !== "loading") am.loadModel(id);
});
}
property Timer poll: Timer {
property int left: 0
interval: 1000
repeat: true
onTriggered: am.listModels(() => {
const m = am.models.find(x => x.id === am.loading);
if (m && m.status === "loaded") { am.loading = ""; am.poll.stop(); }
else if (--am.poll.left <= 0) {
am.modelError = `${am.loading} did not finish loading`;
am.loading = "";
am.poll.stop();
}
})
}
function restart() {
am.restarting = true;
am.run([am.daemonDir + "/assistant.sh", "restart"], null, (code, out) => {
am.restarting = false;
// assistant.sh ends on its status: the process, the socket, and
// the log's tail, which is where a refused config says why.
am.status = code === 0 ? "Restarted." : out.trim();
if (code === 0) am.pending = false;
});
}
page: Component {
Page {
title: "Assistant"
AssistantPage { width: parent.width; asst: am }
}
}
}
|