@firstpick/pi-package-webui 0.8.2 → 0.8.3
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/README.md +9 -3
- package/bin/pi-webui.mjs +97 -12
- package/lib/git-workflow-preferences.mjs +246 -19
- package/lib/thinking-stream-recovery.mjs +156 -0
- package/lib/ui-layout-settings.mjs +254 -0
- package/package.json +5 -3
- package/public/app.js +1618 -41
- package/public/index.html +35 -14
- package/public/service-worker.js +1 -1
- package/public/styles.css +324 -1
- package/tests/boot-failure-diagnostics.test.mjs +3 -3
- package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
- package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
- package/tests/browser/interaction-continuity.spec.mjs +29 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
- package/tests/fast-mode-client-static.test.mjs +2 -2
- package/tests/feature-decision-output-popup-static.test.mjs +172 -0
- package/tests/fixtures/fake-pi.mjs +51 -1
- package/tests/git-workflow-preferences.test.mjs +4 -2
- package/tests/http-endpoints-harness.test.mjs +88 -1
- package/tests/interaction-state-stability-static.test.mjs +3 -0
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +3 -3
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +32 -15
- package/tests/open-issue-wizard-static.test.mjs +1 -1
- package/tests/persistent-ui-layout-static.test.mjs +267 -0
- package/tests/questionnaire-dialog.test.mjs +511 -0
- package/tests/queue-edit-reorder-static.test.mjs +1 -0
- package/tests/remote-auth-settings-harness.test.mjs +1 -1
- package/tests/side-panel-resize-static.test.mjs +1 -0
- package/tests/side-panel-section-reorder-static.test.mjs +3 -3
- package/tests/subagent-launch-slots.test.mjs +1 -1
- package/tests/thinking-stream-recovery.test.mjs +88 -0
- package/tests/ui-layout-settings.test.mjs +92 -0
- package/tests/webui-settings-locking.test.mjs +159 -0
package/README.md
CHANGED
|
@@ -139,13 +139,19 @@ Environment variables:
|
|
|
139
139
|
- `PI_WEBUI_OUTPUT_MODE=normal|compact-v1` sets the server default for newly auto-negotiated browser connections.
|
|
140
140
|
- `PI_WEBUI_RPC_SUPERVISOR=0` opts out to the legacy server-owned Pi transport only when the current scope has no live managed tabs. Use explicit shutdown before disabling or downgrading; fallback startup refuses to create duplicate direct children for a live managed scope.
|
|
141
141
|
- Pi Web UI automatically injects a loopback `PI_WEBUI_RECOVERY_URL` and a bearer `PI_WEBUI_RECOVERY_TOKEN` into spawned Pi RPC processes. The authenticated endpoint can only create a separate plan-only recovery tab; keep any manually supplied token private.
|
|
142
|
-
- `PI_WEBUI_SETTINGS_FILE=/path/to/settings.json` overrides
|
|
142
|
+
- `PI_WEBUI_SETTINGS_FILE=/path/to/settings.json` authoritatively overrides the private Web UI settings file (normally `~/.pi/webui/settings.json`) and disables automatic import from the old XDG location.
|
|
143
143
|
- `PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT=/path/to/package-root` overrides the npm prefix used for optional companion installs.
|
|
144
144
|
- `PI_WEBUI_FAST_PICKS_FILE=/path/to/paths.json` overrides saved cwd fast-pick storage.
|
|
145
145
|
- `PI_WEBUI_NPM_BIN=/path/to/npm` overrides the npm executable used by optional feature install/update actions. By default, Web UI resolves the selected `pi` command, prefers `npm-cli.js` from that Pi installation, and runs it through Node. This prevents stale earlier `PATH` shims such as `%APPDATA%\npm\npm.cmd` from redirecting updates away from the active Pi installation.
|
|
146
146
|
- `PI_BANG_AUTOCOMPLETE_INCLUDE_HISTORY=1` lets optional bang-command autocomplete include local fish/bash/zsh history executables.
|
|
147
147
|
- `PI_BANG_AUTOCOMPLETE_RUNTIME_STORE_PATH=/path/to/runtime.json` overrides the runtime store shared with `@firstpick/pi-extension-bang-command-autocomplete`.
|
|
148
148
|
|
|
149
|
+
### Persistent interface settings
|
|
150
|
+
|
|
151
|
+
Pi Web UI stores user-scoped settings in `~/.pi/webui/settings.json` by default. When that file is absent, a valid prior `$XDG_CONFIG_HOME/pi-webui/settings.json` (or `~/.config/pi-webui/settings.json`) is imported once without modifying or deleting the old file. An existing new file always wins, including when it is malformed, and `PI_WEBUI_SETTINGS_FILE` remains isolated from this migration. Writes use a private same-directory temporary file, atomic replacement, and a bounded same-host process lock; newly created settings files and directories use private permissions on supported platforms.
|
|
152
|
+
|
|
153
|
+
The authenticated `GET /api/interface-preferences` response includes normalized `preferences`, versioned `layout`, and an opaque `layoutRevision`. `PUT /api/interface-preferences` remains compatible with width-only `{ "sidePanelWidth": 612 }` writes. Layout patches require the latest revision in `expectedLayoutRevision`, merge only named fields, and are limited to 32 KiB; stale revisions return `409`, unsupported media types `415`, oversized bodies `413`, and invalid or unknown fields `400`. Browser local storage remains a non-destructive compatibility cache. Semantic file moves, prompt attachments, and follow-up queue mutations are not stored in the interface-layout envelope.
|
|
154
|
+
|
|
149
155
|
### Durable Pi session continuity
|
|
150
156
|
|
|
151
157
|
Pi Web UI normally runs Pi RPC tabs under a narrow detached supervisor. Restarting only the HTTP Web UI—through `/webui-start` on the same URL, **Restart**, a successful **Update & restart**, `POST /api/restart`, or a restart-safe service-manager `SIGTERM`—preserves each managed Pi PID, tab identity, cwd, session file, running state, and active model turn. Output produced while the HTTP server is absent is replayed in supervisor order. The browser rejects duplicate or older replay records; if the bounded live buffer has a gap, it refreshes tabs, state, and the durable transcript from Pi and warns that buffered live output may be incomplete.
|
|
@@ -333,7 +339,7 @@ Discovery-path rules: at most 24 paths and direct children only (no recursive wa
|
|
|
333
339
|
- **What it is:** A browser-native `/skills` setup dialog for skills available in the active Pi tab.
|
|
334
340
|
- **What you can do:** Find skills by name or description, then use **Session only** to change automatic invocation on the current branch or **Global default** to save the skill allowlist inherited by future sessions.
|
|
335
341
|
|
|
336
|
-
Session-specific choices always win when their branch is resumed or selected in `/tree`. Saving a global default does not mutate currently open sessions. Global defaults are stored in the Pi Web UI settings file (normally `~/.
|
|
342
|
+
Session-specific choices always win when their branch is resumed or selected in `/tree`. Saving a global default does not mutate currently open sessions. Global defaults are stored in the Pi Web UI settings file (normally `~/.pi/webui/settings.json`).
|
|
337
343
|
|
|
338
344
|
### Optional features
|
|
339
345
|
|
|
@@ -463,7 +469,7 @@ Optional companions:
|
|
|
463
469
|
|
|
464
470
|
The Git workflow button runs local git commands in the active Pi working directory. It covers both empty/new projects and existing repositories.
|
|
465
471
|
|
|
466
|
-
Before first use, run `/git-workflow-setup` in Pi or choose **Common Pi Options → Guided Git Setup** in the browser. Select an exact authenticated `provider/modelId`, a supported reasoning effort, and the workflow defaults described below. The browser preselects the active tab model when possible, but saving is always explicit. Preferences are stored globally in the Pi Web UI settings file (normally `~/.
|
|
472
|
+
Before first use, run `/git-workflow-setup` in Pi or choose **Common Pi Options → Guided Git Setup** in the browser. Select an exact authenticated `provider/modelId`, a supported reasoning effort, and the workflow defaults described below. The browser preselects the active tab model when possible, but saving is always explicit. Preferences are stored globally in the Pi Web UI settings file (normally `~/.pi/webui/settings.json`), not in browser storage.
|
|
467
473
|
|
|
468
474
|
For a new project, the browser flow can:
|
|
469
475
|
|
package/bin/pi-webui.mjs
CHANGED
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
} from "../lib/session-actions.mjs";
|
|
34
34
|
import { sweepStaleTempEntries } from "../lib/temp-artifacts.mjs";
|
|
35
35
|
import { terminateProcessTree } from "../lib/process-tree.mjs";
|
|
36
|
+
import { ThinkingStreamRecovery } from "../lib/thinking-stream-recovery.mjs";
|
|
36
37
|
import {
|
|
37
38
|
classifyGitPathFailure,
|
|
38
39
|
findWindowsReservedGitPath,
|
|
@@ -61,6 +62,12 @@ import {
|
|
|
61
62
|
writeGitWorkflowPreferences,
|
|
62
63
|
writeWebuiSettings,
|
|
63
64
|
} from "../lib/git-workflow-preferences.mjs";
|
|
65
|
+
import {
|
|
66
|
+
UI_LAYOUT_REQUEST_MAX_BYTES,
|
|
67
|
+
mergeUiLayout,
|
|
68
|
+
uiLayoutRevision,
|
|
69
|
+
validateUiLayoutPatch,
|
|
70
|
+
} from "../lib/ui-layout-settings.mjs";
|
|
64
71
|
import {
|
|
65
72
|
SUBAGENT_LAUNCH_SLOT_LIMITS,
|
|
66
73
|
SUBAGENT_LAUNCH_SLOT_ROLE_CATALOG,
|
|
@@ -383,6 +390,7 @@ const OPTIONAL_FEATURE_PACKAGES = new Map([
|
|
|
383
390
|
["todoProgressWidget", "@firstpick/pi-extension-todo-progress"],
|
|
384
391
|
["tuiToolsCommand", "@firstpick/pi-extension-tools"],
|
|
385
392
|
["remoteWebui", "@firstpick/pi-package-remote-webui"],
|
|
393
|
+
["questionnaire", "@firstpick/pi-package-questionnaire"],
|
|
386
394
|
["naturalConversation", "@firstpick/pi-package-natural-conversation"],
|
|
387
395
|
["gitFooterStatus", "@firstpick/pi-extension-git-footer-status"],
|
|
388
396
|
["statsCommand", "@firstpick/pi-extension-stats"],
|
|
@@ -9796,7 +9804,8 @@ async function primeTabRpc(tab) {
|
|
|
9796
9804
|
function attachRpcToTab(tab, rpc) {
|
|
9797
9805
|
tab.rpcUnsubscribe?.();
|
|
9798
9806
|
tab.rpc = rpc;
|
|
9799
|
-
tab.rpcUnsubscribe = rpc.onEvent((
|
|
9807
|
+
tab.rpcUnsubscribe = rpc.onEvent((rawEvent) => {
|
|
9808
|
+
const event = tab.thinkingStreamRecovery.ingest(rawEvent);
|
|
9800
9809
|
if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event)) return;
|
|
9801
9810
|
updateTabActivityFromEvent(tab, event);
|
|
9802
9811
|
let scopedEvent = eventForTabClients(tab, event);
|
|
@@ -9836,6 +9845,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
|
|
|
9836
9845
|
gitWorkspace: gitWorkspace || null,
|
|
9837
9846
|
lastState: null,
|
|
9838
9847
|
pendingThinkingLevel: undefined,
|
|
9848
|
+
thinkingStreamRecovery: new ThinkingStreamRecovery(),
|
|
9839
9849
|
gitWorkflowGenerationRestore: null,
|
|
9840
9850
|
gitWorkflowMessageGeneration: null,
|
|
9841
9851
|
activity: createTabActivity(createdAt),
|
|
@@ -11266,7 +11276,11 @@ function fallbackRpcResponse(tab, command, error) {
|
|
|
11266
11276
|
|
|
11267
11277
|
async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
11268
11278
|
try {
|
|
11269
|
-
|
|
11279
|
+
const response = rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
|
|
11280
|
+
if (command?.type === "get_messages" && Array.isArray(response?.data?.messages)) {
|
|
11281
|
+
response.data = { ...response.data, messages: tab.thinkingStreamRecovery.applyToMessages(response.data.messages) };
|
|
11282
|
+
}
|
|
11283
|
+
return response;
|
|
11270
11284
|
} catch (error) {
|
|
11271
11285
|
const message = sanitizeError(error);
|
|
11272
11286
|
if (/Pi RPC process is not running/i.test(message)) return responseWithPendingThinking(tab, fallbackRpcResponse(tab, command, error));
|
|
@@ -13724,18 +13738,73 @@ async function saveOutputModeDefault(value) {
|
|
|
13724
13738
|
return outputModeMetadata();
|
|
13725
13739
|
}
|
|
13726
13740
|
|
|
13741
|
+
function interfacePreferencesResponse(settings) {
|
|
13742
|
+
return {
|
|
13743
|
+
preferences: settings.interfacePreferences,
|
|
13744
|
+
layout: settings.uiLayout,
|
|
13745
|
+
layoutRevision: uiLayoutRevision(settings.uiLayout),
|
|
13746
|
+
};
|
|
13747
|
+
}
|
|
13748
|
+
|
|
13749
|
+
function interfacePreferencesRequestError(error, operation) {
|
|
13750
|
+
if (error?.statusCode) return error;
|
|
13751
|
+
if (error?.code === "UI_LAYOUT_INVALID" || error instanceof TypeError) return makeHttpError(400, formatCliError(error));
|
|
13752
|
+
if (error?.code === "UI_LAYOUT_STALE_REVISION") return makeHttpError(409, "The interface layout changed after it was read; refresh and retry.");
|
|
13753
|
+
const message = error?.code === "WEBUI_SETTINGS_LOCK_TIMEOUT"
|
|
13754
|
+
? "Interface preferences are busy; retry shortly."
|
|
13755
|
+
: `Could not ${operation} interface preferences.`;
|
|
13756
|
+
const wrapped = makeHttpError(error?.code === "WEBUI_SETTINGS_LOCK_TIMEOUT" ? 503 : 500, message);
|
|
13757
|
+
wrapped.userMessage = message;
|
|
13758
|
+
return wrapped;
|
|
13759
|
+
}
|
|
13760
|
+
|
|
13761
|
+
function requireInterfacePreferencesJsonRequest(req) {
|
|
13762
|
+
const contentType = String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
|
|
13763
|
+
if (contentType !== "application/json") throw makeHttpError(415, "Interface preference saves require Content-Type: application/json.");
|
|
13764
|
+
}
|
|
13765
|
+
|
|
13766
|
+
function validateInterfacePreferencesBody(body) {
|
|
13767
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) throw makeHttpError(400, "Interface preference save body must be an object.");
|
|
13768
|
+
const allowed = new Set(["sidePanelWidth", "layout", "expectedLayoutRevision"]);
|
|
13769
|
+
const unknown = Object.keys(body).filter((key) => !allowed.has(key));
|
|
13770
|
+
if (unknown.length) throw makeHttpError(400, `Interface preference save contains unsupported field${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`);
|
|
13771
|
+
const hasWidth = Object.hasOwn(body, "sidePanelWidth");
|
|
13772
|
+
const hasLayout = Object.hasOwn(body, "layout");
|
|
13773
|
+
if (!hasWidth && !hasLayout) throw makeHttpError(400, "Interface preference save must include sidePanelWidth or layout.");
|
|
13774
|
+
if (hasWidth) {
|
|
13775
|
+
if (typeof body.sidePanelWidth !== "number" || !Number.isFinite(body.sidePanelWidth) || body.sidePanelWidth < WEBUI_SIDE_PANEL_WIDTH_MIN_PX || body.sidePanelWidth > WEBUI_SIDE_PANEL_WIDTH_MAX_PX) {
|
|
13776
|
+
throw makeHttpError(400, `sidePanelWidth must be between ${WEBUI_SIDE_PANEL_WIDTH_MIN_PX} and ${WEBUI_SIDE_PANEL_WIDTH_MAX_PX} pixels`);
|
|
13777
|
+
}
|
|
13778
|
+
}
|
|
13779
|
+
if (hasLayout) {
|
|
13780
|
+
if (!Object.hasOwn(body, "expectedLayoutRevision") || typeof body.expectedLayoutRevision !== "string" || !/^[a-f0-9]{64}$/u.test(body.expectedLayoutRevision)) {
|
|
13781
|
+
throw makeHttpError(400, "layout saves require the latest layoutRevision as expectedLayoutRevision.");
|
|
13782
|
+
}
|
|
13783
|
+
validateUiLayoutPatch(body.layout);
|
|
13784
|
+
} else if (Object.hasOwn(body, "expectedLayoutRevision")) {
|
|
13785
|
+
throw makeHttpError(400, "expectedLayoutRevision is only valid with a layout save.");
|
|
13786
|
+
}
|
|
13787
|
+
return { hasWidth, hasLayout };
|
|
13788
|
+
}
|
|
13789
|
+
|
|
13727
13790
|
async function interfacePreferencesData() {
|
|
13728
|
-
|
|
13729
|
-
return { preferences: settings.interfacePreferences };
|
|
13791
|
+
return interfacePreferencesResponse(await readWebuiSettings());
|
|
13730
13792
|
}
|
|
13731
13793
|
|
|
13732
13794
|
async function saveInterfacePreferences(body = {}) {
|
|
13733
|
-
const
|
|
13734
|
-
|
|
13735
|
-
|
|
13736
|
-
|
|
13737
|
-
|
|
13738
|
-
|
|
13795
|
+
const { hasWidth, hasLayout } = validateInterfacePreferencesBody(body);
|
|
13796
|
+
const settings = await updateWebuiSettings((current) => {
|
|
13797
|
+
if (hasLayout && body.expectedLayoutRevision !== uiLayoutRevision(current.uiLayout)) {
|
|
13798
|
+
const error = new Error("stale interface layout revision");
|
|
13799
|
+
error.code = "UI_LAYOUT_STALE_REVISION";
|
|
13800
|
+
throw error;
|
|
13801
|
+
}
|
|
13802
|
+
const patch = {};
|
|
13803
|
+
if (hasWidth) patch.interfacePreferences = { sidePanelWidth: Math.round(body.sidePanelWidth) };
|
|
13804
|
+
if (hasLayout) patch.uiLayout = mergeUiLayout(current.uiLayout, body.layout);
|
|
13805
|
+
return patch;
|
|
13806
|
+
});
|
|
13807
|
+
return interfacePreferencesResponse(settings);
|
|
13739
13808
|
}
|
|
13740
13809
|
|
|
13741
13810
|
const remoteAuth = {
|
|
@@ -14240,12 +14309,28 @@ const server = createServer(async (req, res) => {
|
|
|
14240
14309
|
}
|
|
14241
14310
|
|
|
14242
14311
|
if (url.pathname === "/api/interface-preferences" && req.method === "GET") {
|
|
14243
|
-
|
|
14312
|
+
try {
|
|
14313
|
+
sendJson(res, 200, { ok: true, data: await interfacePreferencesData() });
|
|
14314
|
+
} catch (error) {
|
|
14315
|
+
throw interfacePreferencesRequestError(error, "read");
|
|
14316
|
+
}
|
|
14244
14317
|
return;
|
|
14245
14318
|
}
|
|
14246
14319
|
|
|
14247
14320
|
if (url.pathname === "/api/interface-preferences" && req.method === "PUT") {
|
|
14248
|
-
|
|
14321
|
+
requireInterfacePreferencesJsonRequest(req);
|
|
14322
|
+
try {
|
|
14323
|
+
let body;
|
|
14324
|
+
try {
|
|
14325
|
+
body = await readJsonBody(req, { limitBytes: UI_LAYOUT_REQUEST_MAX_BYTES });
|
|
14326
|
+
} catch (error) {
|
|
14327
|
+
if (error instanceof SyntaxError) throw makeHttpError(400, "Interface preference save body must be valid JSON.");
|
|
14328
|
+
throw error;
|
|
14329
|
+
}
|
|
14330
|
+
sendJson(res, 200, { ok: true, data: await saveInterfacePreferences(body) });
|
|
14331
|
+
} catch (error) {
|
|
14332
|
+
throw interfacePreferencesRequestError(error, "save");
|
|
14333
|
+
}
|
|
14249
14334
|
return;
|
|
14250
14335
|
}
|
|
14251
14336
|
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { mkdir, readFile, rename,
|
|
1
|
+
import { mkdir, open, readFile, readdir, rename, rm, rmdir } from "node:fs/promises";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
5
|
import { normalizeSubagentLaunchSlots } from "./subagent-launch-slots.mjs";
|
|
6
|
+
import { normalizeUiLayout } from "./ui-layout-settings.mjs";
|
|
5
7
|
import { normalizeOutputMode, OUTPUT_MODE_NORMAL } from "./webui-output-mode.mjs";
|
|
6
8
|
|
|
7
9
|
export const GIT_WORKFLOW_SETUP_VERSION = 1;
|
|
@@ -24,8 +26,10 @@ export function supportedGitWorkflowThinkingLevels(model) {
|
|
|
24
26
|
});
|
|
25
27
|
}
|
|
26
28
|
|
|
27
|
-
const WEBUI_SETTINGS_VERSION =
|
|
29
|
+
const WEBUI_SETTINGS_VERSION = 6;
|
|
28
30
|
const WEBUI_SETTINGS_FILE_ENV = "PI_WEBUI_SETTINGS_FILE";
|
|
31
|
+
const WEBUI_SETTINGS_LOCK_TIMEOUT_MS = 2_000;
|
|
32
|
+
const WEBUI_SETTINGS_LOCK_RETRY_MS = 25;
|
|
29
33
|
export const WEBUI_SIDE_PANEL_WIDTH_MIN_PX = 320;
|
|
30
34
|
export const WEBUI_SIDE_PANEL_WIDTH_MAX_PX = 4096;
|
|
31
35
|
const webuiSettingsUpdateQueues = new Map();
|
|
@@ -112,6 +116,10 @@ export function gitWorkflowPreferencesSummary(preferences) {
|
|
|
112
116
|
|
|
113
117
|
export function webuiSettingsFile(env = process.env) {
|
|
114
118
|
if (env[WEBUI_SETTINGS_FILE_ENV]) return path.resolve(String(env[WEBUI_SETTINGS_FILE_ENV]).replace(/^~(?=$|[\\/])/, homedir()));
|
|
119
|
+
return path.join(homedir(), ".pi", "webui", "settings.json");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function legacyWebuiSettingsFile(env = process.env) {
|
|
115
123
|
const configRoot = env.XDG_CONFIG_HOME || path.join(homedir(), ".config");
|
|
116
124
|
return path.join(configRoot, "pi-webui", "settings.json");
|
|
117
125
|
}
|
|
@@ -169,24 +177,236 @@ export function normalizeWebuiSettings(value) {
|
|
|
169
177
|
gitWorkflow: normalizeGitWorkflowPreferences(source.gitWorkflow),
|
|
170
178
|
resourceDefaults: normalizeResourceDefaults(source.resourceDefaults),
|
|
171
179
|
interfacePreferences: normalizeInterfacePreferences(source.interfacePreferences),
|
|
180
|
+
uiLayout: normalizeUiLayout(source.uiLayout),
|
|
172
181
|
subagentLaunchSlots: normalizeSubagentLaunchSlots(source.subagentLaunchSlots),
|
|
173
182
|
};
|
|
174
183
|
}
|
|
175
184
|
|
|
176
|
-
|
|
185
|
+
function settingsReadError(storageFile, error) {
|
|
186
|
+
const wrapped = new Error(`Cannot read Pi Web UI settings at ${storageFile}: ${error instanceof Error ? error.message : String(error)}`);
|
|
187
|
+
wrapped.code = "WEBUI_SETTINGS_READ_FAILED";
|
|
188
|
+
wrapped.cause = error;
|
|
189
|
+
return wrapped;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function readRawWebuiSettings(storageFile, { missing = {} } = {}) {
|
|
193
|
+
let text;
|
|
194
|
+
try {
|
|
195
|
+
text = await readFile(storageFile, "utf8");
|
|
196
|
+
} catch (error) {
|
|
197
|
+
if (error?.code === "ENOENT") return missing;
|
|
198
|
+
throw settingsReadError(storageFile, error);
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
const parsed = JSON.parse(text);
|
|
202
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("settings must contain a JSON object");
|
|
203
|
+
return parsed;
|
|
204
|
+
} catch (error) {
|
|
205
|
+
throw settingsReadError(storageFile, error);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function isDefaultSettingsTarget(storageFile, env = process.env) {
|
|
210
|
+
return !env[WEBUI_SETTINGS_FILE_ENV] && path.resolve(storageFile) === path.resolve(webuiSettingsFile(env));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function ensurePrivateSettingsDirectory(storageFile) {
|
|
214
|
+
await mkdir(path.dirname(storageFile), { recursive: true, mode: 0o700 });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function lockDirectoryFor(storageFile) {
|
|
218
|
+
return `${storageFile}.lock`;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function lockOwnerIsDead(pid) {
|
|
222
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
177
223
|
try {
|
|
178
|
-
|
|
224
|
+
process.kill(pid, 0);
|
|
225
|
+
return false;
|
|
179
226
|
} catch (error) {
|
|
180
|
-
|
|
181
|
-
throw new Error(`Cannot read Pi Web UI settings at ${storageFile}: ${error instanceof Error ? error.message : String(error)}`);
|
|
227
|
+
return error?.code === "ESRCH";
|
|
182
228
|
}
|
|
183
229
|
}
|
|
184
230
|
|
|
231
|
+
async function readSettingsLockRecords(lockDirectory) {
|
|
232
|
+
const names = (await readdir(lockDirectory)).filter((name) => name.endsWith(".json")).sort();
|
|
233
|
+
return Promise.all(names.map(async (name) => {
|
|
234
|
+
const recordFile = path.join(lockDirectory, name);
|
|
235
|
+
try {
|
|
236
|
+
const value = JSON.parse(await readFile(recordFile, "utf8"));
|
|
237
|
+
const valid = Number.isSafeInteger(value?.pid)
|
|
238
|
+
&& value.pid > 0
|
|
239
|
+
&& typeof value?.token === "string"
|
|
240
|
+
&& value.token.length > 0
|
|
241
|
+
&& ["pending", "active"].includes(value?.state);
|
|
242
|
+
return { ...value, name, recordFile, valid };
|
|
243
|
+
} catch {
|
|
244
|
+
return { name, recordFile, valid: false };
|
|
245
|
+
}
|
|
246
|
+
}));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function writeSettingsLockRecord(recordFile, value) {
|
|
250
|
+
const temporaryFile = `${recordFile}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
|
|
251
|
+
let handle;
|
|
252
|
+
try {
|
|
253
|
+
handle = await open(temporaryFile, "wx", 0o600);
|
|
254
|
+
await handle.writeFile(`${JSON.stringify(value)}\n`, "utf8");
|
|
255
|
+
await handle.sync();
|
|
256
|
+
await handle.close();
|
|
257
|
+
handle = undefined;
|
|
258
|
+
await rename(temporaryFile, recordFile);
|
|
259
|
+
} catch (error) {
|
|
260
|
+
await handle?.close().catch(() => {});
|
|
261
|
+
await rm(temporaryFile, { force: true }).catch(() => {});
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function releaseSettingsLock(lockDirectory, recordFile) {
|
|
267
|
+
await rm(recordFile, { force: true });
|
|
268
|
+
await rmdir(lockDirectory).catch((error) => {
|
|
269
|
+
if (error?.code !== "ENOENT" && error?.code !== "ENOTEMPTY" && error?.code !== "EEXIST") throw error;
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export async function withWebuiSettingsLock(storageFile, operation, {
|
|
274
|
+
timeoutMs = WEBUI_SETTINGS_LOCK_TIMEOUT_MS,
|
|
275
|
+
retryMs = WEBUI_SETTINGS_LOCK_RETRY_MS,
|
|
276
|
+
} = {}) {
|
|
277
|
+
await ensurePrivateSettingsDirectory(storageFile);
|
|
278
|
+
const lockDirectory = lockDirectoryFor(storageFile);
|
|
279
|
+
await mkdir(lockDirectory, { mode: 0o700 }).catch((error) => {
|
|
280
|
+
if (error?.code !== "EEXIST") throw error;
|
|
281
|
+
});
|
|
282
|
+
const token = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
283
|
+
const recordFile = path.join(lockDirectory, `${token}.json`);
|
|
284
|
+
const ownRecord = { pid: process.pid, token, state: "pending" };
|
|
285
|
+
let handle;
|
|
286
|
+
try {
|
|
287
|
+
handle = await open(recordFile, "wx", 0o600);
|
|
288
|
+
await handle.writeFile(`${JSON.stringify(ownRecord)}\n`, "utf8");
|
|
289
|
+
await handle.sync();
|
|
290
|
+
await handle.close();
|
|
291
|
+
handle = undefined;
|
|
292
|
+
} catch (error) {
|
|
293
|
+
await handle?.close().catch(() => {});
|
|
294
|
+
await rm(recordFile, { force: true }).catch(() => {});
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
299
|
+
let acquired = false;
|
|
300
|
+
try {
|
|
301
|
+
while (!acquired) {
|
|
302
|
+
let records = await readSettingsLockRecords(lockDirectory);
|
|
303
|
+
let removedDeadOwner = false;
|
|
304
|
+
for (const record of records) {
|
|
305
|
+
if (record.valid && lockOwnerIsDead(record.pid)) {
|
|
306
|
+
await rm(record.recordFile, { force: true });
|
|
307
|
+
removedDeadOwner = true;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
if (removedDeadOwner) continue;
|
|
311
|
+
|
|
312
|
+
const active = records.filter((record) => record.valid && record.state === "active");
|
|
313
|
+
if (active.length === 1 && active[0].token === token) {
|
|
314
|
+
acquired = true;
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
if (active.length === 0 && records[0]?.token === token && records[0]?.valid) {
|
|
318
|
+
ownRecord.state = "active";
|
|
319
|
+
await writeSettingsLockRecord(recordFile, ownRecord);
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
if (Date.now() >= deadline) {
|
|
323
|
+
const timeoutError = new Error("Timed out waiting for the Pi Web UI settings lock");
|
|
324
|
+
timeoutError.code = "WEBUI_SETTINGS_LOCK_TIMEOUT";
|
|
325
|
+
throw timeoutError;
|
|
326
|
+
}
|
|
327
|
+
await delay(Math.max(1, Math.min(retryMs, deadline - Date.now())));
|
|
328
|
+
}
|
|
329
|
+
return await operation();
|
|
330
|
+
} finally {
|
|
331
|
+
await releaseSettingsLock(lockDirectory, recordFile);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function syncDirectoryBestEffort(directory) {
|
|
336
|
+
let handle;
|
|
337
|
+
try {
|
|
338
|
+
handle = await open(directory, "r");
|
|
339
|
+
await handle.sync();
|
|
340
|
+
} catch {
|
|
341
|
+
// Directory fsync is unsupported on some platforms/filesystems.
|
|
342
|
+
} finally {
|
|
343
|
+
await handle?.close().catch(() => {});
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async function writePrivateAtomicSettings(storageFile, value) {
|
|
348
|
+
await ensurePrivateSettingsDirectory(storageFile);
|
|
349
|
+
const temporaryFile = path.join(
|
|
350
|
+
path.dirname(storageFile),
|
|
351
|
+
`.${path.basename(storageFile)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,
|
|
352
|
+
);
|
|
353
|
+
let handle;
|
|
354
|
+
try {
|
|
355
|
+
handle = await open(temporaryFile, "wx", 0o600);
|
|
356
|
+
await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
357
|
+
await handle.sync();
|
|
358
|
+
await handle.close();
|
|
359
|
+
handle = undefined;
|
|
360
|
+
await rename(temporaryFile, storageFile);
|
|
361
|
+
await syncDirectoryBestEffort(path.dirname(storageFile));
|
|
362
|
+
} catch (error) {
|
|
363
|
+
await handle?.close().catch(() => {});
|
|
364
|
+
await rm(temporaryFile, { force: true }).catch(() => {});
|
|
365
|
+
throw error;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export async function migrateLegacyWebuiSettings(targetFile, legacyFile) {
|
|
370
|
+
if (path.resolve(targetFile) === path.resolve(legacyFile)) return false;
|
|
371
|
+
try {
|
|
372
|
+
await readFile(targetFile, "utf8");
|
|
373
|
+
return false;
|
|
374
|
+
} catch (error) {
|
|
375
|
+
if (error?.code !== "ENOENT") throw settingsReadError(targetFile, error);
|
|
376
|
+
}
|
|
377
|
+
let legacy;
|
|
378
|
+
try {
|
|
379
|
+
legacy = await readRawWebuiSettings(legacyFile, { missing: null });
|
|
380
|
+
} catch {
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
if (!legacy) return false;
|
|
384
|
+
return withWebuiSettingsLock(targetFile, async () => {
|
|
385
|
+
try {
|
|
386
|
+
await readFile(targetFile, "utf8");
|
|
387
|
+
return false;
|
|
388
|
+
} catch (error) {
|
|
389
|
+
if (error?.code !== "ENOENT") throw settingsReadError(targetFile, error);
|
|
390
|
+
}
|
|
391
|
+
const { settings, persistLaunchSlots, persistedUiLayout } = mergeWebuiSettings(legacy, {});
|
|
392
|
+
const persisted = { ...settings, uiLayout: persistedUiLayout };
|
|
393
|
+
if (!persistLaunchSlots) delete persisted.subagentLaunchSlots;
|
|
394
|
+
await writePrivateAtomicSettings(targetFile, persisted);
|
|
395
|
+
return true;
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async function ensureDefaultSettingsMigration(storageFile, env = process.env) {
|
|
400
|
+
if (!isDefaultSettingsTarget(storageFile, env)) return false;
|
|
401
|
+
return migrateLegacyWebuiSettings(storageFile, legacyWebuiSettingsFile(env));
|
|
402
|
+
}
|
|
403
|
+
|
|
185
404
|
export async function readWebuiSettings(storageFile = webuiSettingsFile(), { reportInvalidOutputMode = false } = {}) {
|
|
405
|
+
await ensureDefaultSettingsMigration(storageFile);
|
|
186
406
|
const raw = await readRawWebuiSettings(storageFile);
|
|
187
407
|
const normalized = normalizeWebuiSettings(raw);
|
|
188
408
|
if (reportInvalidOutputMode && raw.outputModeDefault !== undefined && normalized.outputModeDefault !== raw.outputModeDefault) {
|
|
189
|
-
console.warn(`Invalid persisted Web UI output mode ${JSON.stringify(raw.outputModeDefault)}
|
|
409
|
+
console.warn(`Invalid persisted Web UI output mode ${JSON.stringify(raw.outputModeDefault)}; using ${OUTPUT_MODE_NORMAL}.`);
|
|
190
410
|
}
|
|
191
411
|
return normalized;
|
|
192
412
|
}
|
|
@@ -214,6 +434,9 @@ function mergeWebuiSettings(rawCurrent, patch) {
|
|
|
214
434
|
interfacePreferences: patchValue.interfacePreferences
|
|
215
435
|
? { ...current.interfacePreferences, ...patchValue.interfacePreferences }
|
|
216
436
|
: current.interfacePreferences,
|
|
437
|
+
uiLayout: Object.hasOwn(patchValue, "uiLayout")
|
|
438
|
+
? normalizeUiLayout(patchValue.uiLayout)
|
|
439
|
+
: current.uiLayout,
|
|
217
440
|
};
|
|
218
441
|
if (persistLaunchSlots) {
|
|
219
442
|
source.subagentLaunchSlots = hasLaunchSlotPatch
|
|
@@ -224,17 +447,18 @@ function mergeWebuiSettings(rawCurrent, patch) {
|
|
|
224
447
|
delete source.subagentLaunchSlots;
|
|
225
448
|
source.version = Math.max(WEBUI_SETTINGS_VERSION, Number.isInteger(raw.version) ? raw.version : 0);
|
|
226
449
|
}
|
|
227
|
-
|
|
450
|
+
const settings = normalizeWebuiSettings(source);
|
|
451
|
+
const persistedUiLayout = !Object.hasOwn(patchValue, "uiLayout") && raw.uiLayout !== undefined
|
|
452
|
+
? raw.uiLayout
|
|
453
|
+
: settings.uiLayout;
|
|
454
|
+
return { settings, persistLaunchSlots, persistedUiLayout };
|
|
228
455
|
}
|
|
229
456
|
|
|
230
457
|
async function writeMergedWebuiSettings(rawCurrent, patch, storageFile) {
|
|
231
|
-
const { settings, persistLaunchSlots } = mergeWebuiSettings(rawCurrent, patch);
|
|
232
|
-
const persisted = { ...settings };
|
|
458
|
+
const { settings, persistLaunchSlots, persistedUiLayout } = mergeWebuiSettings(rawCurrent, patch);
|
|
459
|
+
const persisted = { ...settings, uiLayout: persistedUiLayout };
|
|
233
460
|
if (!persistLaunchSlots) delete persisted.subagentLaunchSlots;
|
|
234
|
-
await
|
|
235
|
-
const temporaryFile = `${storageFile}.${process.pid}.${Date.now()}.tmp`;
|
|
236
|
-
await writeFile(temporaryFile, `${JSON.stringify(persisted, null, 2)}\n`, { mode: 0o600 });
|
|
237
|
-
await rename(temporaryFile, storageFile);
|
|
461
|
+
await writePrivateAtomicSettings(storageFile, persisted);
|
|
238
462
|
return settings;
|
|
239
463
|
}
|
|
240
464
|
|
|
@@ -246,11 +470,14 @@ export function updateWebuiSettings(updater, storageFile = webuiSettingsFile())
|
|
|
246
470
|
const queueKey = path.resolve(storageFile);
|
|
247
471
|
const previous = webuiSettingsUpdateQueues.get(queueKey) || Promise.resolve();
|
|
248
472
|
const currentUpdate = previous.catch(() => {}).then(async () => {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
473
|
+
await ensureDefaultSettingsMigration(storageFile);
|
|
474
|
+
return withWebuiSettingsLock(storageFile, async () => {
|
|
475
|
+
const rawCurrent = await readRawWebuiSettings(storageFile);
|
|
476
|
+
const current = normalizeWebuiSettings(rawCurrent);
|
|
477
|
+
const patch = await updater(current);
|
|
478
|
+
if (patch === undefined) return current;
|
|
479
|
+
return writeMergedWebuiSettings(rawCurrent, patch, storageFile);
|
|
480
|
+
});
|
|
254
481
|
});
|
|
255
482
|
webuiSettingsUpdateQueues.set(queueKey, currentUpdate);
|
|
256
483
|
return currentUpdate.finally(() => {
|