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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
|
// deck-it - assistant panel
// 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.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// desktop-assistant on the tablet: chat with formatted streamed replies,
// voice through the tablet's mic, model choice, and the canvas's Ask
// presets and Do ops on a file picked on the PC. Every control is an icon
// (the Nerd Font the server serves), sized for a finger.
import { offline } from "../offline.js";
import { render } from "../md.js";
import { peak, toWav } from "../wav.js";
// Font Awesome codepoints, present in Inconsolata Nerd Font.
const G = { tools: "", stop: "", mic: "", micOff: "", plus: "",
cloud: "", close: "", copy: "", fallback: "" };
const MAX_REC = 59;
// Below this peak a clip is silence (room noise measured ~260, speech
// 15000+); the model would invent a question from it, so it is not sent.
const SILENT = 1500;
const STATUS = { thinking: "thinking…", transcribing: "transcribing…" };
async function post(action, body = {}) {
const r = await fetch(`/api/assistant/${action}`, {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
});
if (!r.ok) throw new Error((await r.text()) || r.statusText);
}
function iconBtn(glyph, label, cls = "") {
const b = document.createElement("button");
b.className = `ib nf ${cls}`;
b.textContent = glyph;
b.setAttribute("aria-label", label);
b.title = label;
return b;
}
function note(el, text) {
el._note = text;
clearTimeout(el._noteT);
el._noteT = setTimeout(() => { el._note = ""; }, 6000);
}
function act(el, action, body) {
post(action, body).catch((e) => note(el, e.message));
}
function addCopy(box) {
for (const pre of box.querySelectorAll("pre")) {
const b = iconBtn(G.copy, "Copy", "copy");
// The tablet's clipboard; the button's own glyph is outside <code>.
b.onclick = () => navigator.clipboard?.writeText(pre.querySelector("code")?.innerText ?? "");
pre.append(b);
}
}
// One exchange as chat bubbles: the question on the right with the user's
// avatar, the reply on the left with the assistant's; "…" while a reply has
// no text yet.
function turnNode(t, live) {
const d = document.createElement("div");
d.className = "as-turn";
if (t.user) {
const row = document.createElement("div");
row.className = "as-row me";
row.innerHTML = `<div class="as-q"></div><div class="as-av me"></div>`;
row.firstElementChild.textContent = t.user;
d.append(row);
}
const row = document.createElement("div");
row.className = "as-row bot";
row.innerHTML = `<div class="as-av bot"></div><div class="as-bubble"></div>`;
const bubble = row.lastElementChild;
if (t.tools?.length) {
const tools = document.createElement("div");
tools.className = "as-tools";
tools.textContent = t.tools.join(" · ");
bubble.append(tools);
}
const a = document.createElement("div");
a.className = "as-a md";
if (t.reply) a.innerHTML = render(t.reply);
else if (live) a.textContent = "…";
if (!live) addCopy(a);
bubble.append(a);
if (t.error && t.error !== "stopped") {
const e = document.createElement("div");
e.className = "as-err bad";
e.textContent = t.error;
bubble.append(e);
}
d.append(row);
return d;
}
// The assistant's avatar is the background picture zoomed onto the face
// ([assistant] face); its real size is needed to scale it, so it is loaded once.
function faceStyle(el, face) {
if (!face || el._face) return;
el._face = true;
const img = new Image();
img.onload = () => {
const [x, y, size] = face;
const k = 40 / size; // the avatar is 40px
const box = el.querySelector(".assistant");
box.style.setProperty("--face-size", `${img.naturalWidth * k}px ${img.naturalHeight * k}px`);
box.style.setProperty("--face-pos", `${-(x - size / 2) * k}px ${-(y - size / 2) * k}px`);
box.classList.add("has-face");
};
img.src = "/api/bg";
}
function renderLog(log, st, el) {
if (el._epoch !== st.epoch || el._done > st.turns.length) {
log.textContent = "";
el._epoch = st.epoch;
el._done = 0;
}
log.querySelector(".as-live")?.remove();
for (; el._done < st.turns.length; el._done++) log.append(turnNode(st.turns[el._done], false));
if (st.pending) {
const live = turnNode(st.pending, true);
live.classList.add("as-live");
log.append(live);
}
if (el._stick) log.scrollTop = log.scrollHeight;
}
function renderPicking(box, st, el) {
box.hidden = !st.picking;
if (!st.picking || box._key === st.picking) return;
box._key = st.picking;
box.innerHTML = `<span></span>`;
box.firstElementChild.textContent = `${st.picking}: choose the file on the PC`;
const cancel = iconBtn(G.close, "Cancel");
cancel.onclick = () => act(el, "cancel");
box.append(cancel);
}
// The presets and ops, in an overlay opened from the header, so the
// transcript keeps the screen.
function renderStrip(strip, st, el) {
const cat = st.catalog;
const key = JSON.stringify([cat?.presets, cat?.ops, st.catalogError]);
if (strip._key === key) return;
strip._key = key;
strip.textContent = "";
if (!cat) {
strip.innerHTML = `<div class="as-note"></div>`;
strip.firstElementChild.textContent = st.catalogError || "Loading presets…";
return;
}
const SECTIONS = [
["preset", cat.presets ?? [], "Ask the assistant", "Pick a file on the PC; the assistant answers about it here."],
["op", cat.ops ?? [], "Convert files", "Pick files on the PC; the result is saved in its output folder."],
];
for (const [kind, items, title, hint] of SECTIONS) {
const head = document.createElement("div");
head.className = "as-sec";
head.innerHTML = `<h3></h3><p></p>`;
head.firstElementChild.textContent = title;
head.lastElementChild.textContent = hint;
strip.append(head);
const row = document.createElement("div");
row.className = `as-row ${kind}`;
for (const item of items) {
const b = document.createElement("button");
b.className = "as-tile";
b.title = item.prompt ?? item.label;
b.setAttribute("aria-label", item.label);
b.innerHTML = `<i class="nf"></i><span></span>`;
b.querySelector("i").textContent = item.icon || G.fallback;
b.querySelector("span").textContent = item.label;
b.onclick = () => { strip.hidden = true; act(el, "pick", { [kind]: item.label }); };
row.append(b);
}
strip.append(row);
}
}
function renderOp(box, op) {
box.hidden = !op;
if (!op) return;
const name = (p) => p.slice(p.lastIndexOf("/") + 1);
box.className = `as-op ${op.running ? "" : op.ok ? "good" : "bad"}`;
box.textContent = op.running ? `${op.label}…`
: op.ok ? `Saved: ${[].concat(op.out ?? []).map(name).join(", ")}` : `${op.label}: ${op.error}`;
}
function renderModels(panel, st, el) {
const key = JSON.stringify([st.models, st.wanted]);
if (panel._key === key) return;
panel._key = key;
panel.textContent = "";
for (const m of st.models) {
const b = document.createElement("button");
b.className = `as-mrow${m.id === st.wanted ? " on" : ""}`;
b.innerHTML = `<i class="nf"></i><span></span><small></small>`;
b.querySelector("i").textContent = m.cloud ? G.cloud : "";
b.querySelector("span").textContent = m.id;
b.querySelector("small").textContent = m.cloud ? m.provider : m.status;
b.onclick = () => { panel.hidden = true; act(el, "model", { id: m.id }); };
panel.append(b);
}
}
// The mic's look follows the recorder at once, not at the next poll: a tap
// with no feedback invites a second one, which made a silent clip.
function micLook(el) {
el.querySelector(".mic").classList.toggle("on", !!(el._rec || el._recStarting));
}
async function toggleMic(el) {
if (el._rec) { el._rec.stop(); return; }
if (el._recStarting) return;
el._recStarting = true;
micLook(el);
let stream, rec;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
el._micDenied = false;
} catch (e) {
el._micDenied = true;
note(el, `microphone: ${e.message}`);
return;
} finally {
el._recStarting = false;
micLook(el);
}
try {
rec = new MediaRecorder(stream);
} catch (e) {
stream.getTracks().forEach((t) => t.stop());
note(el, `microphone: ${e.message}`);
return;
}
const chunks = [];
rec.ondataavailable = (e) => chunks.push(e.data);
rec.onstop = async () => {
stream.getTracks().forEach((t) => t.stop());
clearTimeout(el._recCap);
const secs = (Date.now() - el._recAt) / 1000;
el._rec = null;
micLook(el);
if (secs < 0.5) return;
try {
const wav = await toWav(new Blob(chunks, { type: rec.mimeType }));
if (peak(wav) < SILENT) return note(el, "nothing heard");
const r = await fetch("/api/assistant/voice", {
method: "POST", headers: { "Content-Type": "audio/wav" }, body: wav,
});
if (!r.ok) throw new Error((await r.text()) || r.statusText);
} catch (e) {
note(el, `voice: ${e.message}`);
}
};
el._rec = rec;
el._recAt = Date.now();
rec.start();
micLook(el);
el._recCap = setTimeout(() => rec.state === "recording" && rec.stop(), MAX_REC * 1000);
}
export default {
title: "Assistant",
tab: "Assistant",
interval: 0.5,
mount(el) {
el.innerHTML = `
<div class="assistant">
<div class="as-off"></div>
<div class="as-main">
<div class="as-head">
<button class="as-model"><i class="nf"></i><span></span></button>
</div>
<div class="as-models" hidden></div>
<div class="as-strip" hidden></div>
<div class="as-picking" hidden></div>
<div class="as-op" hidden></div>
<div class="as-hello" aria-hidden="true">
<h2>How may I help you?</h2>
<p>Tap the mic and ask.</p>
<p>Or open the wrench to work on a file from the PC.</p>
</div>
<div class="as-log"></div>
<div class="as-notice"></div>
<div class="as-bar"><span class="as-status"></span></div>
</div>
</div>`;
const head = el.querySelector(".as-head");
const panel = el.querySelector(".as-models");
const strip = el.querySelector(".as-strip");
const tools = iconBtn(G.tools, "Presets and file operations", "tools");
tools.onclick = () => { strip.hidden = !strip.hidden; panel.hidden = true; };
const fresh = iconBtn(G.plus, "New chat", "fresh");
fresh.onclick = () => act(el, "new");
head.append(tools, fresh);
el.querySelector(".as-model").onclick = () => {
panel.hidden = !panel.hidden;
strip.hidden = true;
if (!panel.hidden) act(el, "models");
};
const log = el.querySelector(".as-log");
el._stick = true;
log.addEventListener("scroll", () => { el._stick = log.scrollHeight - log.scrollTop - log.clientHeight < 40; });
el.addEventListener("pointerdown", (e) => {
if (!e.target.closest(".as-models, .as-model")) panel.hidden = true;
if (!e.target.closest(".as-strip, .tools")) strip.hidden = true;
});
// No keyboard: the PC is at hand for typing. Voice, and Stop while a
// reply streams.
const bar = el.querySelector(".as-bar");
const mic = iconBtn(G.mic, "Ask by voice", "mic");
mic.onclick = () => toggleMic(el);
const stop = iconBtn(G.stop, "Stop", "stop");
stop.onclick = () => act(el, "stop");
bar.append(mic, stop);
},
update(st, el) {
const main = el.querySelector(".as-main");
const off = el.querySelector(".as-off");
main.hidden = !st.connected;
if (!st.connected) {
offline(off, {
icon: "/icons/assistant.svg", // hidden by offline.js when the theme has none
title: "Assistant not running",
detail: "Start desktop-assistant and the chat appears here.",
reason: st.error,
});
return;
}
off.textContent = "";
off._offline = null;
faceStyle(el, st.face);
el._busy = !!st.pending || st.state !== "idle";
// The backdrop shows more while the chat is empty.
el.querySelector(".assistant").classList.toggle("idle", !st.turns.length && !st.pending);
const model = el.querySelector(".as-model");
const cloud = st.models.some((m) => m.cloud && m.id === st.wanted);
model.querySelector("i").textContent = cloud ? G.cloud : "";
model.querySelector("span").textContent = st.wanted || st.model || "model";
el.querySelector(".as-status").textContent =
st.state === "tool" ? `running ${st.tool}…` : STATUS[st.state] ?? "";
const panel = el.querySelector(".as-models");
if (!panel.hidden) renderModels(panel, st, el);
renderStrip(el.querySelector(".as-strip"), st, el);
renderPicking(el.querySelector(".as-picking"), st, el);
renderOp(el.querySelector(".as-op"), st.op);
renderLog(el.querySelector(".as-log"), st, el);
el.querySelector(".as-notice").textContent = el._note || st.notice || "";
el.querySelector(".stop").hidden = !el._busy;
const mic = el.querySelector(".mic");
const deaf = !st.hears || el._micDenied;
mic.disabled = !st.hears && !el._rec;
mic.textContent = deaf ? G.micOff : G.mic;
micLook(el);
mic.title = el._micDenied ? "Microphone not allowed"
: !st.hears ? `${st.wanted || st.model} takes no audio`
: el._rec ? `Recording ${Math.floor((Date.now() - el._recAt) / 1000)}s, tap to send` : "Ask by voice";
mic.dataset.secs = el._rec ? `${Math.floor((Date.now() - el._recAt) / 1000)}` : "";
},
};
|