pi-famulus 0.2.2-beta.2 → 0.2.2-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/intercom/intercom.ts +44 -8
- package/src/manager-client.ts +19 -1
- package/src/tui/famulus-command.ts +82 -8
- package/src/tui/famulus-settings.ts +47 -9
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-famulus",
|
|
3
|
-
"version": "0.2.2-beta.
|
|
3
|
+
"version": "0.2.2-beta.4",
|
|
4
4
|
"description": "Keep your main agent's context clean: subagents on cheaper models, long bash in the background, and monitors that wake the agent. One Rust daemon runs the shells.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -54,12 +54,12 @@
|
|
|
54
54
|
"pi-famulus": "./bin/pi-famulus.js"
|
|
55
55
|
},
|
|
56
56
|
"optionalDependencies": {
|
|
57
|
-
"pi-famulus-linux-x64": "0.2.2-beta.
|
|
58
|
-
"pi-famulus-linux-arm64": "0.2.2-beta.
|
|
59
|
-
"pi-famulus-darwin-x64": "0.2.2-beta.
|
|
60
|
-
"pi-famulus-darwin-arm64": "0.2.2-beta.
|
|
61
|
-
"pi-famulus-win-x64": "0.2.2-beta.
|
|
62
|
-
"pi-famulus-win-arm64": "0.2.2-beta.
|
|
57
|
+
"pi-famulus-linux-x64": "0.2.2-beta.4",
|
|
58
|
+
"pi-famulus-linux-arm64": "0.2.2-beta.4",
|
|
59
|
+
"pi-famulus-darwin-x64": "0.2.2-beta.4",
|
|
60
|
+
"pi-famulus-darwin-arm64": "0.2.2-beta.4",
|
|
61
|
+
"pi-famulus-win-x64": "0.2.2-beta.4",
|
|
62
|
+
"pi-famulus-win-arm64": "0.2.2-beta.4"
|
|
63
63
|
},
|
|
64
64
|
"pi": {
|
|
65
65
|
"extensions": [
|
package/src/intercom/intercom.ts
CHANGED
|
@@ -21,8 +21,9 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
|
|
|
21
21
|
import { createRequire } from "node:module";
|
|
22
22
|
import fs from "node:fs";
|
|
23
23
|
import os from "node:os";
|
|
24
|
+
import { stripVTControlCharacters } from "node:util";
|
|
24
25
|
import path from "node:path";
|
|
25
|
-
import { ManagerClient } from "../manager-client";
|
|
26
|
+
import { ManagerClient, type MessagingStatus } from "../manager-client";
|
|
26
27
|
import type { IntercomFrame, SessionRow } from "./types";
|
|
27
28
|
import { createManagerTransport, IntercomError, type IntercomTransport } from "./transport";
|
|
28
29
|
import { ChatCard, ChatText, formatTimestamp } from "./widgets";
|
|
@@ -207,7 +208,11 @@ export function registerIntercom(pi: ExtensionAPI, deps: IntercomDeps): void {
|
|
|
207
208
|
let lastCtx: ExtensionContext | undefined;
|
|
208
209
|
let retryTimer: ReturnType<typeof setInterval> | undefined;
|
|
209
210
|
let manualCompactionRefresh: ReturnType<typeof setTimeout> | undefined;
|
|
210
|
-
let
|
|
211
|
+
let lastMessagingFooter: string | undefined;
|
|
212
|
+
/** The current outage already produced its notice; later texts only update the footer. */
|
|
213
|
+
let outageNotified = false;
|
|
214
|
+
/** A relay outage was reported, so the next healthy status is a recovery. */
|
|
215
|
+
let relayOutage = false;
|
|
211
216
|
let statusCheckEpoch: number | undefined;
|
|
212
217
|
let legacyPluginNotified = false;
|
|
213
218
|
let autocompleteBound = false;
|
|
@@ -278,11 +283,32 @@ export function registerIntercom(pi: ExtensionAPI, deps: IntercomDeps): void {
|
|
|
278
283
|
}
|
|
279
284
|
};
|
|
280
285
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
+
/** Notify once per outage; `footer` (default: the message) is the live status line. */
|
|
287
|
+
function updateMessagingError(message?: string, level: "warning" | "error" = "error", footer = message) {
|
|
288
|
+
if (footer !== lastMessagingFooter) {
|
|
289
|
+
lastMessagingFooter = footer;
|
|
290
|
+
lastCtx?.ui.setStatus?.("famulus-messaging", footer);
|
|
291
|
+
}
|
|
292
|
+
if (!message) {
|
|
293
|
+
outageNotified = false;
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (outageNotified) return;
|
|
297
|
+
outageNotified = true;
|
|
298
|
+
notify(message, level);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const FOOTER_ERROR_MAX = 60;
|
|
302
|
+
|
|
303
|
+
function messagingFooter(m: MessagingStatus): string {
|
|
304
|
+
let error = stripVTControlCharacters(m.error || "").replace(/\s+/g, " ").trim();
|
|
305
|
+
if (error.length > FOOTER_ERROR_MAX) error = `${error.slice(0, FOOTER_ERROR_MAX - 1)}…`;
|
|
306
|
+
const retry = m.state === "disconnected" && typeof m.retry_at_ms === "number"
|
|
307
|
+
? Math.ceil((m.retry_at_ms - Date.now()) / 1000)
|
|
308
|
+
: undefined;
|
|
309
|
+
const label = retry === undefined ? m.state : "reconnecting";
|
|
310
|
+
const when = retry === undefined ? "" : retry > 0 ? ` · retry in ${retry}s` : " · retrying";
|
|
311
|
+
return `msg: ${label}${when}${error ? ` · ${error}` : ""}`;
|
|
286
312
|
}
|
|
287
313
|
|
|
288
314
|
async function checkMessagingStatus() {
|
|
@@ -294,11 +320,20 @@ export function registerIntercom(pi: ExtensionAPI, deps: IntercomDeps): void {
|
|
|
294
320
|
const { messaging } = await client.status();
|
|
295
321
|
if (stopped || epoch !== expectedEpoch || !lastCtx || !useContext(lastCtx)) return;
|
|
296
322
|
if (!messaging || messaging.state === "disabled") {
|
|
323
|
+
relayOutage = false;
|
|
297
324
|
updateMessagingError();
|
|
298
325
|
} else if (messaging.error || messaging.state === "disconnected" || messaging.state === "unavailable") {
|
|
299
|
-
|
|
326
|
+
relayOutage = true;
|
|
327
|
+
updateMessagingError(
|
|
328
|
+
`pi-famulus messaging ${messaging.state}: ${messaging.error || "relay not connected"}`,
|
|
329
|
+
"error",
|
|
330
|
+
messagingFooter(messaging),
|
|
331
|
+
);
|
|
300
332
|
} else {
|
|
301
333
|
updateMessagingError();
|
|
334
|
+
// The outage notice was the only signal; say when it is over.
|
|
335
|
+
if (relayOutage) notify("pi-famulus messaging reconnected", "info");
|
|
336
|
+
relayOutage = false;
|
|
302
337
|
}
|
|
303
338
|
} catch (error) {
|
|
304
339
|
if (!stopped && epoch === expectedEpoch && lastCtx && useContext(lastCtx)) {
|
|
@@ -735,6 +770,7 @@ export function registerIntercom(pi: ExtensionAPI, deps: IntercomDeps): void {
|
|
|
735
770
|
readiness = undefined;
|
|
736
771
|
started = false;
|
|
737
772
|
listCache = undefined;
|
|
773
|
+
relayOutage = false;
|
|
738
774
|
updateMessagingError();
|
|
739
775
|
lastCtx = undefined;
|
|
740
776
|
stopPromise = (async () => {
|
package/src/manager-client.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { famulusPaths } from "./config";
|
|
|
18
18
|
import { realClock, type Clock, type ClockTimer } from "./clock";
|
|
19
19
|
|
|
20
20
|
const MAX_FRAME_BYTES = 4 * 1024 * 1024; // 4 MiB (§3.3)
|
|
21
|
-
const EXTENSION_VERSION = "0.2.2-beta.
|
|
21
|
+
const EXTENSION_VERSION = "0.2.2-beta.4";
|
|
22
22
|
export { EXTENSION_VERSION };
|
|
23
23
|
// 6: hosted subagents. 7: the extension's messaging bridge (`intercom`
|
|
24
24
|
// request plus `intercom`/`intercom_reset` events).
|
|
@@ -188,6 +188,19 @@ export interface MessagingStatus {
|
|
|
188
188
|
name: string;
|
|
189
189
|
/** Why the bridge is not running. */
|
|
190
190
|
error?: string;
|
|
191
|
+
/** Epoch ms of the next reconnect attempt; only while disconnected with one scheduled. */
|
|
192
|
+
retry_at_ms?: number;
|
|
193
|
+
/** Enrolled device id for the configured server; absent or empty when not enrolled. */
|
|
194
|
+
device_id?: string;
|
|
195
|
+
/** Local sessions the relay assigns to another device; peers cannot reach them. */
|
|
196
|
+
conflicts?: RelayConflict[];
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export interface RelayConflict {
|
|
200
|
+
id: string;
|
|
201
|
+
name: string;
|
|
202
|
+
/** Owning device name or id; empty when the relay does not list the session. */
|
|
203
|
+
owner: string;
|
|
191
204
|
}
|
|
192
205
|
|
|
193
206
|
export interface SessionInfo {
|
|
@@ -657,6 +670,11 @@ export class ManagerClient {
|
|
|
657
670
|
};
|
|
658
671
|
}
|
|
659
672
|
|
|
673
|
+
/** Ask the daemon to retry the relay connection now instead of at the next scheduled attempt. */
|
|
674
|
+
async messagingReconnect(): Promise<void> {
|
|
675
|
+
await this.request({ type: "messaging_reconnect" });
|
|
676
|
+
}
|
|
677
|
+
|
|
660
678
|
/** Connected sessions (status). Older managers may reject this for extension clients. */
|
|
661
679
|
async sessions(): Promise<SessionInfo[]> {
|
|
662
680
|
return (await this.status()).sessions;
|
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
* whether messaging reaches its relay, and the settings pages.
|
|
4
4
|
*/
|
|
5
5
|
import { execFile } from "node:child_process";
|
|
6
|
+
import { dirname } from "node:path";
|
|
6
7
|
import { stripVTControlCharacters } from "node:util";
|
|
7
8
|
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
-
import type
|
|
9
|
+
import { ManagerError, type ManagerClient, type MessagingStatus } from "../manager-client";
|
|
9
10
|
import { SETTINGS_SECTIONS, listTheme, readConfigText, sectionPage, writeConfigText } from "./famulus-settings";
|
|
10
11
|
import { loadPiTui, truncateToWidth, wrapTextWithAnsi } from "./pi-tui-load";
|
|
11
12
|
|
|
@@ -20,6 +21,8 @@ export interface FamulusCommandDeps {
|
|
|
20
21
|
messagingEnabled?: boolean;
|
|
21
22
|
/** `<binary> --version`; null when it cannot be run. */
|
|
22
23
|
binaryVersion?: (path: string) => Promise<string | null>;
|
|
24
|
+
/** Exchange an enrollment token using the current messaging configuration. */
|
|
25
|
+
enrollMessagingToken?: (token: string) => Promise<void>;
|
|
23
26
|
}
|
|
24
27
|
|
|
25
28
|
export interface FamulusInfo {
|
|
@@ -49,9 +52,28 @@ export function formatMessaging(info: FamulusInfo): string {
|
|
|
49
52
|
const m = info.messaging;
|
|
50
53
|
if (!m) return info.daemon ? "not reported by this manager" : "unknown (manager not connected)";
|
|
51
54
|
const state = RELAY_STATES[m.state] ?? "unavailable";
|
|
52
|
-
|
|
55
|
+
let label = m.name && RELAY_STATES[m.state] ? `${state} · name ${singleLine(m.name)}` : state;
|
|
56
|
+
if (m.state === "disconnected" && typeof m.retry_at_ms === "number") {
|
|
57
|
+
const seconds = Math.ceil((m.retry_at_ms - Date.now()) / 1000);
|
|
58
|
+
label += seconds > 0 ? ` · retry in ${seconds}s` : " · retrying";
|
|
59
|
+
}
|
|
53
60
|
const error = singleLine(m.error ?? "");
|
|
54
|
-
|
|
61
|
+
const count = m.conflicts?.length ?? 0;
|
|
62
|
+
const conflicts = count ? ` · ${count} session${count === 1 ? "" : "s"} unpublished` : "";
|
|
63
|
+
return `${label}${conflicts}${error ? ` (${error})` : ""}`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Why some local sessions are invisible to peers, one entry per session. */
|
|
67
|
+
export function formatConflicts(m: MessagingStatus | null): string {
|
|
68
|
+
if (!m?.conflicts?.length) return "";
|
|
69
|
+
const rows = m.conflicts.map((c) => {
|
|
70
|
+
const id = singleLine(c.id);
|
|
71
|
+
const name = singleLine(c.name);
|
|
72
|
+
const who = name && name !== id ? `${name} (${id})` : id;
|
|
73
|
+
const owner = singleLine(c.owner);
|
|
74
|
+
return owner ? `${who} owned by ${owner}` : `${who} not listed`;
|
|
75
|
+
});
|
|
76
|
+
return `Unpublished: the relay assigns these sessions to another device, so peers cannot reach them until they restart: ${rows.join("; ")}`;
|
|
55
77
|
}
|
|
56
78
|
|
|
57
79
|
export function formatFamulusInfo(info: FamulusInfo): string {
|
|
@@ -80,6 +102,17 @@ export function readBinaryVersion(path: string): Promise<string | null> {
|
|
|
80
102
|
});
|
|
81
103
|
}
|
|
82
104
|
|
|
105
|
+
export function exchangeMessagingToken(managerPath: string | null, configPath: string, token: string): Promise<void> {
|
|
106
|
+
if (!managerPath) return Promise.reject(new Error("pi-famulus binary is unavailable."));
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
execFile(managerPath, ["--home", dirname(configPath), "intercom", "enroll", "--token", token],
|
|
109
|
+
{ timeout: 25_000, windowsHide: true }, (error, _stdout, stderr) => {
|
|
110
|
+
if (error) reject(new Error(stderr.trim() || `Device enrollment failed (${error.code ?? "command failed"}).`));
|
|
111
|
+
else resolve();
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
83
116
|
const STATUS_TIMEOUT_MS = 2000;
|
|
84
117
|
|
|
85
118
|
async function readMessaging(client: ManagerClient): Promise<MessagingStatus | null> {
|
|
@@ -112,10 +145,34 @@ export async function collectFamulusInfo(deps: FamulusCommandDeps): Promise<Famu
|
|
|
112
145
|
};
|
|
113
146
|
}
|
|
114
147
|
|
|
115
|
-
type OverviewChoice = "edit-raw" | "reload" | undefined;
|
|
148
|
+
type OverviewChoice = "edit-raw" | "reload" | "reconnect" | undefined;
|
|
149
|
+
|
|
150
|
+
/** Whether "Reconnect messaging now" makes sense for what the manager reported. */
|
|
151
|
+
const canReconnect = (m: MessagingStatus | null) => m?.state === "disconnected" || m?.state === "unavailable";
|
|
152
|
+
|
|
153
|
+
/** Ask the manager to retry the relay now; the notice text says how that went. */
|
|
154
|
+
export async function requestMessagingReconnect(client: ManagerClient | null): Promise<{ text: string; error: boolean }> {
|
|
155
|
+
if (!client?.isAvailable()) return { text: "The manager is not connected.", error: true };
|
|
156
|
+
try {
|
|
157
|
+
await client.messagingReconnect();
|
|
158
|
+
return { text: "Reconnect requested; the status refreshes below.", error: false };
|
|
159
|
+
} catch (error) {
|
|
160
|
+
const message = (error as Error).message;
|
|
161
|
+
// An older daemon rejects the request type itself.
|
|
162
|
+
if (error instanceof ManagerError && error.code === "E_BAD_REQUEST" && /unknown|unrecognized|unsupported/i.test(message)) {
|
|
163
|
+
return { text: "The manager is too old to reconnect on demand; restart it.", error: true };
|
|
164
|
+
}
|
|
165
|
+
return { text: `Reconnect failed: ${singleLine(message)}`, error: true };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
116
168
|
|
|
117
169
|
/** Status first, then one row per settings section and the two actions. */
|
|
118
|
-
function showOverview(
|
|
170
|
+
function showOverview(
|
|
171
|
+
ctx: ExtensionCommandContext,
|
|
172
|
+
info: FamulusInfo,
|
|
173
|
+
configPath: string,
|
|
174
|
+
enrollMessagingToken: (token: string) => Promise<void>,
|
|
175
|
+
): Promise<OverviewChoice> {
|
|
119
176
|
const piTui = loadPiTui();
|
|
120
177
|
if (!piTui) {
|
|
121
178
|
ctx.ui.notify(formatFamulusInfo(info), "info");
|
|
@@ -127,6 +184,8 @@ function showOverview(ctx: ExtensionCommandContext, info: FamulusInfo, configPat
|
|
|
127
184
|
tui: piTui,
|
|
128
185
|
theme,
|
|
129
186
|
configPath,
|
|
187
|
+
messaging: info.messaging,
|
|
188
|
+
enrollMessagingToken,
|
|
130
189
|
requestRender: () => tui.requestRender(),
|
|
131
190
|
notice: (text: string, error = false) => {
|
|
132
191
|
notice = theme.fg(error ? "error" : "success", text);
|
|
@@ -140,6 +199,13 @@ function showOverview(ctx: ExtensionCommandContext, info: FamulusInfo, configPat
|
|
|
140
199
|
currentValue: "›",
|
|
141
200
|
submenu: (_current: string, close: (value?: string) => void) => sectionPage(deps, section, () => close()),
|
|
142
201
|
})),
|
|
202
|
+
...(canReconnect(info.messaging) ? [{
|
|
203
|
+
id: "reconnect",
|
|
204
|
+
label: "Reconnect messaging now",
|
|
205
|
+
description: "Retry the relay connection immediately instead of waiting for the next attempt",
|
|
206
|
+
currentValue: "",
|
|
207
|
+
values: [""],
|
|
208
|
+
}] : []),
|
|
143
209
|
{
|
|
144
210
|
id: "edit-raw",
|
|
145
211
|
label: "Edit config.json",
|
|
@@ -154,7 +220,7 @@ function showOverview(ctx: ExtensionCommandContext, info: FamulusInfo, configPat
|
|
|
154
220
|
10,
|
|
155
221
|
listTheme(theme),
|
|
156
222
|
(id) => {
|
|
157
|
-
if (id === "edit-raw" || id === "reload") done(id);
|
|
223
|
+
if (id === "edit-raw" || id === "reload" || id === "reconnect") done(id);
|
|
158
224
|
},
|
|
159
225
|
() => done(undefined),
|
|
160
226
|
);
|
|
@@ -170,8 +236,10 @@ function showOverview(ctx: ExtensionCommandContext, info: FamulusInfo, configPat
|
|
|
170
236
|
})];
|
|
171
237
|
const error = singleLine(info.messaging?.error ?? "");
|
|
172
238
|
if (error) lines.push(...wrapTextWithAnsi(theme.fg("error", `Messaging error: ${error}`), width));
|
|
239
|
+
const conflicts = formatConflicts(info.messaging);
|
|
240
|
+
if (conflicts) lines.push(...wrapTextWithAnsi(theme.fg("warning", conflicts), width));
|
|
173
241
|
lines.push("", ...list.render(width));
|
|
174
|
-
if (notice) lines.push("", notice);
|
|
242
|
+
if (notice) lines.push("", ...wrapTextWithAnsi(notice, width));
|
|
175
243
|
return lines.map((line) => truncateToWidth(line, width));
|
|
176
244
|
},
|
|
177
245
|
invalidate: () => list.invalidate(),
|
|
@@ -193,7 +261,13 @@ export function registerFamulusCommand(pi: ExtensionAPI, deps: FamulusCommandDep
|
|
|
193
261
|
return;
|
|
194
262
|
}
|
|
195
263
|
while (true) {
|
|
196
|
-
const action = await showOverview(ctx, await collectFamulusInfo(deps), deps.configPath
|
|
264
|
+
const action = await showOverview(ctx, await collectFamulusInfo(deps), deps.configPath,
|
|
265
|
+
deps.enrollMessagingToken ?? ((token) => exchangeMessagingToken(deps.managerPath, deps.configPath, token)));
|
|
266
|
+
if (action === "reconnect") {
|
|
267
|
+
const outcome = await requestMessagingReconnect(deps.getClient());
|
|
268
|
+
ctx.ui.notify(outcome.text, outcome.error ? "error" : "info");
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
197
271
|
if (action === "reload") {
|
|
198
272
|
await ctx.reload();
|
|
199
273
|
return;
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { hostname } from "node:os";
|
|
7
7
|
import { dirname } from "node:path";
|
|
8
|
+
import type { MessagingStatus } from "../manager-client";
|
|
8
9
|
import type { PiTuiInteractive, PiTuiModule, PiTuiSettingItem, PiTuiSettingsListTheme } from "./pi-tui-load";
|
|
9
10
|
|
|
10
11
|
type Kind = "int" | "text" | "secret" | "bool" | "enum" | "duration";
|
|
@@ -99,7 +100,7 @@ export const SETTINGS_SECTIONS: SettingsSection[] = [
|
|
|
99
100
|
{ path: ["messaging", "enabled"], kind: "bool", default: "false", description: "Opt in to cross-session messaging tools, commands, and connections.", applies: "reload the extension and restart the manager daemon to apply" },
|
|
100
101
|
{ path: ["messaging", "name"], kind: "text", default: hostname(), description: "Device name shown to peers; the hostname when unset." },
|
|
101
102
|
{ path: ["messaging", "server"], kind: "text", default: "https://127.0.0.1:8443", description: "Relay server URL." },
|
|
102
|
-
{ path: ["messaging", "token"], kind: "secret", default: "not set", description: "
|
|
103
|
+
{ path: ["messaging", "token"], kind: "secret", default: "not set", description: "Enrollment token; Enter exchanges it for a saved device credential. The token is not stored.", applies: "exchanges immediately" },
|
|
103
104
|
{ path: ["messaging", "localOnly"], kind: "bool", default: "false", description: "Only local sessions, no relay. Enable explicitly for local-only messaging." },
|
|
104
105
|
{ path: ["messaging", "remoteMessages"], kind: "enum", values: ["allow", "refuse"], default: "allow", description: "Whether messages from other machines are accepted." },
|
|
105
106
|
{ path: ["messaging", "tlsInsecure"], kind: "bool", default: "false", description: "Skip relay TLS certificate verification." },
|
|
@@ -212,6 +213,9 @@ export interface SettingsPageDeps {
|
|
|
212
213
|
tui: PiTuiModule;
|
|
213
214
|
theme: { fg(color: string, text: string): string };
|
|
214
215
|
configPath: string;
|
|
216
|
+
/** What the manager reported; null when it is unreachable or silent. */
|
|
217
|
+
messaging?: MessagingStatus | null;
|
|
218
|
+
enrollMessagingToken(token: string): Promise<void>;
|
|
215
219
|
requestRender(): void;
|
|
216
220
|
/** Report a save or its failure under the list. */
|
|
217
221
|
notice(text: string, error?: boolean): void;
|
|
@@ -229,6 +233,12 @@ export function listTheme(theme: SettingsPageDeps["theme"]): PiTuiSettingsListTh
|
|
|
229
233
|
|
|
230
234
|
const keyOf = (spec: SettingSpec) => spec.path.join(".");
|
|
231
235
|
|
|
236
|
+
/** The token is removed after enrollment, so the row shows enrollment instead. */
|
|
237
|
+
function enrollmentValue(messaging: SettingsPageDeps["messaging"]): string {
|
|
238
|
+
if (!messaging) return "unknown";
|
|
239
|
+
return messaging.device_id ? `enrolled · device ${messaging.device_id.slice(0, 8)}` : "not enrolled";
|
|
240
|
+
}
|
|
241
|
+
|
|
232
242
|
function describe(spec: SettingSpec & { applies?: string }, section: SettingsSection, raw: unknown): string {
|
|
233
243
|
const state = raw === undefined ? `not set (default ${spec.default})` : `default ${spec.default}`;
|
|
234
244
|
return `${spec.description} · ${state} · ${spec.applies ?? section.applies}`;
|
|
@@ -239,7 +249,7 @@ function valueEditor(
|
|
|
239
249
|
deps: SettingsPageDeps,
|
|
240
250
|
spec: SettingSpec,
|
|
241
251
|
raw: unknown,
|
|
242
|
-
save: (value: unknown) => boolean
|
|
252
|
+
save: (value: unknown) => boolean | Promise<boolean>,
|
|
243
253
|
done: (shown?: string) => void,
|
|
244
254
|
): PiTuiInteractive {
|
|
245
255
|
const input = new deps.tui.Input();
|
|
@@ -253,6 +263,7 @@ function valueEditor(
|
|
|
253
263
|
? "enter save · empty keeps the current value · esc cancel"
|
|
254
264
|
: `enter save · empty resets to ${spec.default} · esc cancel`;
|
|
255
265
|
let error = "";
|
|
266
|
+
let pending = false;
|
|
256
267
|
input.onSubmit = (text) => {
|
|
257
268
|
if (spec.kind === "secret" && text.trim() === "") return done();
|
|
258
269
|
const parsed = parseInput(spec, text);
|
|
@@ -261,7 +272,19 @@ function valueEditor(
|
|
|
261
272
|
deps.requestRender();
|
|
262
273
|
return;
|
|
263
274
|
}
|
|
264
|
-
|
|
275
|
+
error = "";
|
|
276
|
+
const saved = save(parsed.value);
|
|
277
|
+
if (typeof saved === "boolean") {
|
|
278
|
+
if (saved) done(displayValue(spec, parsed.value));
|
|
279
|
+
} else {
|
|
280
|
+
pending = true;
|
|
281
|
+
deps.requestRender();
|
|
282
|
+
void saved.then((success) => {
|
|
283
|
+
pending = false;
|
|
284
|
+
if (success) done("enrolled");
|
|
285
|
+
deps.requestRender();
|
|
286
|
+
});
|
|
287
|
+
}
|
|
265
288
|
};
|
|
266
289
|
input.onEscape = () => done();
|
|
267
290
|
return {
|
|
@@ -269,12 +292,12 @@ function valueEditor(
|
|
|
269
292
|
deps.theme.fg("accent", keyOf(spec)),
|
|
270
293
|
deps.theme.fg("dim", spec.description),
|
|
271
294
|
"",
|
|
272
|
-
...input.render(width),
|
|
295
|
+
...(pending ? [deps.theme.fg("dim", "Exchanging token...")] : input.render(width)),
|
|
273
296
|
"",
|
|
274
|
-
error ? deps.theme.fg("error", error) : deps.theme.fg("dim", hint),
|
|
297
|
+
error ? deps.theme.fg("error", error) : deps.theme.fg("dim", pending ? "Waiting for enrollment response" : hint),
|
|
275
298
|
],
|
|
276
299
|
invalidate: () => input.invalidate(),
|
|
277
|
-
handleInput: (data) => input.handleInput(data),
|
|
300
|
+
handleInput: (data) => { if (!pending) input.handleInput(data); },
|
|
278
301
|
};
|
|
279
302
|
}
|
|
280
303
|
|
|
@@ -288,7 +311,19 @@ export function sectionPage(deps: SettingsPageDeps, section: SettingsSection, cl
|
|
|
288
311
|
config = {};
|
|
289
312
|
}
|
|
290
313
|
const specs = new Map(section.specs.map((spec) => [keyOf(spec), spec]));
|
|
291
|
-
const
|
|
314
|
+
const enroll = async (token: string): Promise<boolean> => {
|
|
315
|
+
try {
|
|
316
|
+
await deps.enrollMessagingToken(token);
|
|
317
|
+
setConfigValue(deps.configPath, ["messaging", "token"], undefined);
|
|
318
|
+
deps.notice("Device enrolled; device credential saved.");
|
|
319
|
+
return true;
|
|
320
|
+
} catch (error) {
|
|
321
|
+
deps.notice(`Device enrollment failed: ${(error as Error).message.replaceAll(token, "[redacted]")}`, true);
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
const save = (spec: SettingSpec & { applies?: string }, value: unknown): boolean | Promise<boolean> => {
|
|
326
|
+
if (keyOf(spec) === "messaging.token") return enroll(value as string);
|
|
292
327
|
try {
|
|
293
328
|
setConfigValue(deps.configPath, spec.path, value);
|
|
294
329
|
} catch (error) {
|
|
@@ -300,11 +335,14 @@ export function sectionPage(deps: SettingsPageDeps, section: SettingsSection, cl
|
|
|
300
335
|
};
|
|
301
336
|
const items: PiTuiSettingItem[] = section.specs.map((spec) => {
|
|
302
337
|
const raw = lookup(config, spec.path);
|
|
338
|
+
const isToken = keyOf(spec) === "messaging.token";
|
|
303
339
|
const item: PiTuiSettingItem = {
|
|
304
340
|
id: keyOf(spec),
|
|
305
341
|
label: spec.path[spec.path.length - 1],
|
|
306
|
-
description:
|
|
307
|
-
|
|
342
|
+
description: isToken
|
|
343
|
+
? `Entering a token ${deps.messaging?.device_id ? "re-enrolls" : "enrolls"} this device. ${spec.description} · ${spec.applies}`
|
|
344
|
+
: describe(spec, section, raw),
|
|
345
|
+
currentValue: isToken ? enrollmentValue(deps.messaging) : displayValue(spec, raw),
|
|
308
346
|
};
|
|
309
347
|
if (spec.kind === "bool") item.values = ["true", "false"];
|
|
310
348
|
else if (spec.kind === "enum") item.values = spec.values;
|