@firstpick/pi-package-webui 0.6.6 → 0.6.8

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.
@@ -0,0 +1,126 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import webuiRpcHelper from "../webui-rpc-helper.mjs";
6
+
7
+ class EventBus {
8
+ constructor() {
9
+ this.handlers = new Map();
10
+ }
11
+
12
+ on(name, handler) {
13
+ const handlers = this.handlers.get(name) || new Set();
14
+ handlers.add(handler);
15
+ this.handlers.set(name, handlers);
16
+ return () => handlers.delete(handler);
17
+ }
18
+
19
+ emit(name, value) {
20
+ for (const handler of [...(this.handlers.get(name) || [])]) handler(value);
21
+ }
22
+ }
23
+
24
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-resource-defaults-"));
25
+ const settingsFile = path.join(root, "settings.json");
26
+ const previousSettingsFile = process.env.PI_WEBUI_SETTINGS_FILE;
27
+ process.env.PI_WEBUI_SETTINGS_FILE = settingsFile;
28
+
29
+ try {
30
+ await writeFile(settingsFile, `${JSON.stringify({
31
+ version: 3,
32
+ resourceDefaults: {
33
+ tools: { enabledTools: ["read", "write"] },
34
+ skills: { enabledSkills: ["skill-a", "skill-c"] },
35
+ },
36
+ }, null, 2)}\n`, "utf8");
37
+
38
+ const extensionHandlers = new Map();
39
+ const registeredCommands = new Map();
40
+ const notifications = [];
41
+ const appendedEntries = [];
42
+ const bus = new EventBus();
43
+ let activeTools = ["read", "bash", "write"];
44
+ let branchEntries = [];
45
+ let availableSkills = [];
46
+
47
+ const pi = {
48
+ events: bus,
49
+ on(name, handler) {
50
+ const handlers = extensionHandlers.get(name) || [];
51
+ handlers.push(handler);
52
+ extensionHandlers.set(name, handlers);
53
+ },
54
+ registerCommand(name, command) { registeredCommands.set(name, command); },
55
+ getAllTools() {
56
+ return ["read", "bash", "write"].map((name) => ({ name, description: `${name} tool`, sourceInfo: { source: "builtin" } }));
57
+ },
58
+ getActiveTools() { return [...activeTools]; },
59
+ setActiveTools(names) { activeTools = [...names]; },
60
+ appendEntry(customType, data) { appendedEntries.push({ customType, data }); },
61
+ };
62
+
63
+ const ctx = {
64
+ mode: "rpc",
65
+ hasUI: true,
66
+ cwd: root,
67
+ sessionManager: {
68
+ getBranch() { return branchEntries; },
69
+ },
70
+ getSystemPromptOptions() {
71
+ return {
72
+ skills: availableSkills.map((name) => ({ name, description: `${name} skill` })),
73
+ };
74
+ },
75
+ ui: {
76
+ setStatus() {},
77
+ notify(message, type) { notifications.push({ message, type }); },
78
+ },
79
+ };
80
+
81
+ webuiRpcHelper(pi);
82
+ const helperCommand = registeredCommands.get("webui-helper");
83
+ assert.ok(helperCommand?.handler, "resource defaults test requires the hidden helper command");
84
+
85
+ async function runHelper(action, payload = {}) {
86
+ const requestId = `${action}-${notifications.length}`;
87
+ await helperCommand.handler(JSON.stringify({ requestId, action, payload }), ctx);
88
+ const notice = notifications.findLast((entry) => entry.message.includes(`\"requestId\":\"${requestId}\"`));
89
+ assert.ok(notice, `${action} should emit a helper response`);
90
+ const response = JSON.parse(notice.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length));
91
+ assert.equal(response.ok, true, response.error);
92
+ return response.data;
93
+ }
94
+
95
+ for (const handler of extensionHandlers.get("session_start") || []) await handler({ reason: "startup" }, ctx);
96
+ availableSkills = ["skill-a", "skill-b", "skill-c"];
97
+ assert.deepEqual(activeTools, ["read", "write"], "a new session should inherit the global tool allowlist");
98
+ assert.deepEqual(
99
+ (await runHelper("skills-state")).skills.map((skill) => [skill.name, skill.enabled]),
100
+ [["skill-a", true], ["skill-b", false], ["skill-c", true]],
101
+ "a new session should inherit the global skill allowlist",
102
+ );
103
+
104
+ branchEntries = [
105
+ { type: "custom", customType: "webui-tools-config", data: { enabledTools: ["bash"] } },
106
+ { type: "custom", customType: "webui-skills-config", data: { disabledSkills: ["skill-a"] } },
107
+ ];
108
+ for (const handler of extensionHandlers.get("session_start") || []) await handler({ reason: "resume" }, ctx);
109
+ assert.deepEqual(activeTools, ["bash"], "session tool choices should override the global default");
110
+ assert.deepEqual(
111
+ (await runHelper("skills-state")).skills.map((skill) => [skill.name, skill.enabled]),
112
+ [["skill-a", false], ["skill-b", true], ["skill-c", true]],
113
+ "session skill choices should override the global default",
114
+ );
115
+
116
+ await runHelper("tools-set", { enabledTools: ["read"] });
117
+ await runHelper("skills-set", { enabledSkills: ["skill-a", "skill-c"] });
118
+ assert.deepEqual(appendedEntries.map((entry) => entry.customType), ["webui-tools-config", "webui-skills-config"], "session updates should remain branch-persisted");
119
+
120
+ for (const handler of extensionHandlers.get("session_shutdown") || []) await handler({ reason: "quit" }, ctx);
121
+ console.log("resource-defaults-helper.test.mjs passed");
122
+ } finally {
123
+ if (previousSettingsFile === undefined) delete process.env.PI_WEBUI_SETTINGS_FILE;
124
+ else process.env.PI_WEBUI_SETTINGS_FILE = previousSettingsFile;
125
+ await rm(root, { recursive: true, force: true });
126
+ }
@@ -119,8 +119,8 @@ try {
119
119
  assert.equal(deleted.method, "unlink");
120
120
  assert.equal(existsSync(deletablePath), false);
121
121
 
122
- const auth = createAuthContext();
123
- const payload = authProvidersPayload(auth.modelRegistry);
122
+ const auth = await createAuthContext();
123
+ const payload = await authProvidersPayload(auth.modelRuntime);
124
124
  assert.ok(Array.isArray(payload.loginProviders));
125
125
  assert.ok(Array.isArray(payload.logoutProviders));
126
126
  assert.equal(payload.browserLoginSupported, false);
@@ -0,0 +1,44 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
6
+
7
+ const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+
9
+ assert.deepEqual(piUpdateCommandSteps(), [
10
+ { label: "Pi CLI", args: ["update", "--self"] },
11
+ ], "Pi-only updates should use the explicit cross-version self flag");
12
+
13
+ assert.deepEqual(piUpdateCommandSteps({ all: true, supportsAll: true }), [
14
+ { label: "Pi CLI and configured packages", args: ["update", "--all"] },
15
+ ], "all updates should prefer --all when the selected Pi executable supports it");
16
+
17
+ const fallbackSteps = piUpdateCommandSteps({ all: true });
18
+ assert.deepEqual(fallbackSteps, [
19
+ { label: "Pi CLI", args: ["update", "--self"] },
20
+ { label: "configured Pi packages", args: ["update", "--extensions"] },
21
+ ], "all updates should split self and extension updates when --all is unavailable");
22
+
23
+ assert.equal(piUpdateHelpSupportsAll("Usage: pi update [--self|--extensions|--all]"), true);
24
+ assert.equal(piUpdateHelpSupportsAll(" --all Update pi and installed packages"), true);
25
+ assert.equal(piUpdateHelpSupportsAll("Usage: pi update [--self] [--extensions]"), false);
26
+ assert.equal(piUpdateHelpSupportsAll(" --allow-project-files"), false, "similar option names must not count as --all");
27
+
28
+ assert.equal(piUpdateCommandText(), "pi update --self");
29
+ assert.equal(piUpdateCommandText({ all: true, supportsAll: true }), "pi update --all");
30
+ assert.equal(piUpdateCommandText({ all: true }), "pi update --self && pi update --extensions");
31
+
32
+ const [server, app, readme] = await Promise.all([
33
+ readFile(join(packageRoot, "bin", "pi-webui.mjs"), "utf8"),
34
+ readFile(join(packageRoot, "public", "app.js"), "utf8"),
35
+ readFile(join(packageRoot, "README.md"), "utf8"),
36
+ ]);
37
+ assert.match(server, /async function piUpdateCommandSupportsAll\(command\)[\s\S]*piUpdateHelpSupportsAll/, "server should inspect update help from the selected Pi command");
38
+ assert.match(server, /resolveCommand\(\["update", "--help"\]\)[\s\S]*piUpdateCommandSteps\(\{ all, supportsAll \}\)/, "server should plan commands from the capability result");
39
+ assert.match(server, /const piTasks = await resolvePiUpdateCommands\(\{ all \}\)/, "all-mode task resolution should preserve the selected Pi update plan");
40
+ assert.match(server, /allCommand: piUpdateCommandText\(\{ all: true, supportsAll: true \}\)[\s\S]*allFallbackCommand: piUpdateCommandText\(\{ all: true \}\)/, "update status should expose preferred and fallback command text");
41
+ assert.match(app, /"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"/, "update confirmation should describe capability selection and fallback");
42
+ assert.match(readme, /first checks the selected Pi executable's `pi update --help`[\s\S]*uses `pi update --all` when advertised[\s\S]*otherwise falls back/, "documentation should explain the checked fallback behavior");
43
+
44
+ console.log("update command planning tests passed");
@@ -1,6 +1,7 @@
1
1
  import { closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { AgentSession, formatSkillsForPrompt } from "@earendil-works/pi-coding-agent";
4
+ import { readWebuiSettings } from "./lib/git-workflow-preferences.mjs";
4
5
 
5
6
  const HELPER_COMMAND = "webui-helper";
6
7
  const RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
@@ -424,6 +425,7 @@ function parseSubagentStatusText(text, previousRuns = new Map()) {
424
425
  export default function webuiRpcHelper(pi) {
425
426
  let enabledTools = new Set();
426
427
  let disabledSkills = new Set();
428
+ let inheritedEnabledSkills = null;
427
429
  let subagentContext = null;
428
430
  let subagentBridgeAvailable = false;
429
431
  let subagentPollTimer = null;
@@ -655,6 +657,15 @@ export default function webuiRpcHelper(pi) {
655
657
  return pi.getAllTools().map((tool) => tool.name);
656
658
  }
657
659
 
660
+ async function readGlobalResourceDefaults() {
661
+ try {
662
+ return (await readWebuiSettings()).resourceDefaults;
663
+ } catch (error) {
664
+ console.warn(`Web UI resource defaults could not be read: ${error instanceof Error ? error.message : String(error)}`);
665
+ return { tools: { enabledTools: null }, skills: { enabledSkills: null } };
666
+ }
667
+ }
668
+
658
669
  function persistToolsState() {
659
670
  pi.appendEntry(TOOLS_CONFIG_TYPE, { enabledTools: [...enabledTools] });
660
671
  }
@@ -664,11 +675,13 @@ export default function webuiRpcHelper(pi) {
664
675
  pi.setActiveTools([...enabledTools].filter((name) => existing.has(name)));
665
676
  }
666
677
 
667
- function restoreToolsFromBranch(ctx) {
678
+ function restoreToolsFromBranch(ctx, globalDefaults) {
668
679
  const saved = lastBranchConfig(ctx, TOOLS_CONFIG_TYPE)?.enabledTools;
669
- if (Array.isArray(saved)) {
680
+ const inherited = globalDefaults?.tools?.enabledTools;
681
+ const selected = Array.isArray(saved) ? saved : inherited;
682
+ if (Array.isArray(selected)) {
670
683
  const existing = new Set(allToolNames());
671
- enabledTools = new Set(normalizeNameList(saved).filter((name) => existing.has(name)));
684
+ enabledTools = new Set(normalizeNameList(selected).filter((name) => existing.has(name)));
672
685
  applyTools();
673
686
  return;
674
687
  }
@@ -707,9 +720,20 @@ export default function webuiRpcHelper(pi) {
707
720
  pi.appendEntry(SKILLS_CONFIG_TYPE, { disabledSkills: [...disabledSkills] });
708
721
  }
709
722
 
710
- function restoreSkillsFromBranch(ctx) {
723
+ function isSkillEnabled(name) {
724
+ return inheritedEnabledSkills instanceof Set ? inheritedEnabledSkills.has(name) : !disabledSkills.has(name);
725
+ }
726
+
727
+ function restoreSkillsFromBranch(ctx, globalDefaults) {
711
728
  const saved = lastBranchConfig(ctx, SKILLS_CONFIG_TYPE)?.disabledSkills;
712
- disabledSkills = new Set(normalizeNameList(saved));
729
+ if (Array.isArray(saved)) {
730
+ inheritedEnabledSkills = null;
731
+ disabledSkills = new Set(normalizeNameList(saved));
732
+ return;
733
+ }
734
+ const inherited = globalDefaults?.skills?.enabledSkills;
735
+ inheritedEnabledSkills = Array.isArray(inherited) ? new Set(normalizeNameList(inherited)) : null;
736
+ disabledSkills = new Set();
713
737
  }
714
738
 
715
739
  function skillsFromContext(ctx) {
@@ -718,7 +742,7 @@ export default function webuiRpcHelper(pi) {
718
742
  return skills.map((skill) => ({
719
743
  name: skill.name,
720
744
  description: skill.description || "",
721
- enabled: !disabledSkills.has(skill.name),
745
+ enabled: isSkillEnabled(skill.name),
722
746
  disableModelInvocation: skill.disableModelInvocation === true,
723
747
  filePath: skill.filePath,
724
748
  sourceInfo: safeSourceInfo(skill.sourceInfo),
@@ -726,13 +750,16 @@ export default function webuiRpcHelper(pi) {
726
750
  }
727
751
 
728
752
  function skillState(ctx) {
729
- const known = new Set(skillsFromContext(ctx).map((skill) => skill.name));
730
- disabledSkills = new Set([...disabledSkills].filter((name) => known.has(name)));
753
+ if (inheritedEnabledSkills === null) {
754
+ const known = new Set(skillsFromContext(ctx).map((skill) => skill.name));
755
+ disabledSkills = new Set([...disabledSkills].filter((name) => known.has(name)));
756
+ }
731
757
  return { skills: skillsFromContext(ctx) };
732
758
  }
733
759
 
734
760
  function setSkillState(ctx, payload) {
735
761
  const allNames = new Set(skillsFromContext(ctx).map((skill) => skill.name));
762
+ inheritedEnabledSkills = null;
736
763
  if (Array.isArray(payload.enabledSkills)) {
737
764
  const enabled = new Set(normalizeNameList(payload.enabledSkills));
738
765
  disabledSkills = new Set([...allNames].filter((name) => !enabled.has(name)));
@@ -800,8 +827,9 @@ export default function webuiRpcHelper(pi) {
800
827
  });
801
828
 
802
829
  pi.on("session_start", async (_event, ctx) => {
803
- restoreToolsFromBranch(ctx);
804
- restoreSkillsFromBranch(ctx);
830
+ const globalDefaults = await readGlobalResourceDefaults();
831
+ restoreToolsFromBranch(ctx, globalDefaults);
832
+ restoreSkillsFromBranch(ctx, globalDefaults);
805
833
  subagentContext = ctx;
806
834
  subagentPollGeneration += 1;
807
835
  foregroundSubagentRuns.clear();
@@ -812,8 +840,9 @@ export default function webuiRpcHelper(pi) {
812
840
  });
813
841
 
814
842
  pi.on("session_tree", async (_event, ctx) => {
815
- restoreToolsFromBranch(ctx);
816
- restoreSkillsFromBranch(ctx);
843
+ const globalDefaults = await readGlobalResourceDefaults();
844
+ restoreToolsFromBranch(ctx, globalDefaults);
845
+ restoreSkillsFromBranch(ctx, globalDefaults);
817
846
  subagentContext = ctx;
818
847
  });
819
848
 
@@ -875,18 +904,20 @@ export default function webuiRpcHelper(pi) {
875
904
  const match = String(event.text || "").trim().match(/^\/skill:([^\s]+)/i);
876
905
  if (!match) return { action: "continue" };
877
906
  const skillName = match[1];
878
- if (!disabledSkills.has(skillName)) return { action: "continue" };
907
+ if (isSkillEnabled(skillName)) return { action: "continue" };
879
908
  ctx.ui.notify(`Skill /skill:${skillName} is disabled in the Web UI /skills selector.`, "warning");
880
909
  return { action: "handled" };
881
910
  });
882
911
 
883
912
  pi.on("before_agent_start", async (event) => {
884
- if (disabledSkills.size === 0) return;
913
+ if (disabledSkills.size === 0 && inheritedEnabledSkills === null) return;
885
914
  const allSkills = Array.isArray(event.systemPromptOptions?.skills) ? event.systemPromptOptions.skills : [];
886
915
  if (allSkills.length === 0) return;
887
- const filteredSkills = allSkills.filter((skill) => !disabledSkills.has(skill.name));
916
+ const disabledNames = allSkills.filter((skill) => !isSkillEnabled(skill.name)).map((skill) => skill.name);
917
+ if (disabledNames.length === 0) return;
918
+ const filteredSkills = allSkills.filter((skill) => isSkillEnabled(skill.name));
888
919
  let nextPrompt = replaceAvailableSkillsSection(event.systemPrompt, filteredSkills);
889
- for (const name of disabledSkills) nextPrompt = nextPrompt.replace(skillBlockPattern(name), "");
920
+ for (const name of disabledNames) nextPrompt = nextPrompt.replace(skillBlockPattern(name), "");
890
921
  return { systemPrompt: nextPrompt };
891
922
  });
892
923
  }