@firstpick/pi-package-webui 0.8.5 → 0.8.7

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.
Files changed (110) hide show
  1. package/README.md +18 -584
  2. package/bin/pi-webui-launcher.mjs +22 -0
  3. package/bin/pi-webui-update-supervisor.mjs +86 -0
  4. package/bin/pi-webui.mjs +933 -554
  5. package/index.ts +16 -6
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +20 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-core.mjs +4 -3
  11. package/lib/session-summary-preferences.mjs +16 -1
  12. package/lib/subagent-launch-slots.mjs +14 -2
  13. package/lib/trust-boundaries.mjs +16 -0
  14. package/lib/update/executor.mjs +99 -0
  15. package/lib/update/journal.mjs +175 -0
  16. package/lib/update/owners.mjs +70 -0
  17. package/lib/update/plan.mjs +134 -0
  18. package/lib/update/resolver.mjs +168 -0
  19. package/lib/update/supervisor.mjs +238 -0
  20. package/lib/update/verify.mjs +52 -0
  21. package/lib/update-commands.mjs +25 -13
  22. package/lib/webui-workspaces.mjs +17 -1
  23. package/lib/workspace-session-summaries.mjs +400 -0
  24. package/package.json +4 -4
  25. package/public/app.js +2487 -349
  26. package/public/index.html +200 -51
  27. package/public/middle-button-drag-scroll.mjs +154 -0
  28. package/public/sampling-parameter-controls.mjs +361 -0
  29. package/public/service-worker.js +5 -1
  30. package/public/stream-output-controller.mjs +327 -0
  31. package/public/styles.css +666 -71
  32. package/public/theme-contract.mjs +244 -0
  33. package/session-summary.ts +164 -4
  34. package/tests/aur-review-widget-static.test.mjs +2 -1
  35. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  36. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  37. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  38. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  39. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  40. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  41. package/tests/browser/session-summary.spec.mjs +131 -3
  42. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  43. package/tests/browser/update-reconnect.spec.mjs +92 -0
  44. package/tests/codex-fast-mode-static.test.mjs +2 -2
  45. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  46. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  47. package/tests/component-update-api-static.test.mjs +22 -61
  48. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  49. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  50. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  51. package/tests/fast-mode-client-static.test.mjs +3 -2
  52. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  53. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  54. package/tests/fixtures/fake-pi.mjs +269 -2
  55. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  56. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  57. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  58. package/tests/git-workflow-preferences.test.mjs +7 -1
  59. package/tests/guided-git-aur-review.test.mjs +4 -3
  60. package/tests/http-endpoints-harness.test.mjs +274 -23
  61. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  62. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  63. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  64. package/tests/mobile-foundation-static.test.mjs +5 -6
  65. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  66. package/tests/mobile-static.test.mjs +85 -50
  67. package/tests/native-parity.test.mjs +1 -1
  68. package/tests/open-issue-wizard-static.test.mjs +2 -3
  69. package/tests/optional-feature-migration-frontend.test.mjs +9 -5
  70. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  71. package/tests/questionnaire-dialog.test.mjs +3 -3
  72. package/tests/remote-auth-settings-harness.test.mjs +43 -0
  73. package/tests/rpc-supervisor-host.test.mjs +11 -2
  74. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  75. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  76. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  77. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  78. package/tests/sampling-parameter-controls.test.mjs +241 -0
  79. package/tests/session-sampling-helper.test.mjs +228 -0
  80. package/tests/session-sampling-http.test.mjs +168 -0
  81. package/tests/session-sampling-ui-static.test.mjs +370 -0
  82. package/tests/session-summary-core.test.mjs +205 -10
  83. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  84. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  85. package/tests/staged-content-hash-contract.test.mjs +52 -11
  86. package/tests/stream-lifecycle-core.test.mjs +134 -0
  87. package/tests/stream-output-controller.test.mjs +252 -0
  88. package/tests/stream-output-isolation-static.test.mjs +89 -0
  89. package/tests/streaming-ui-coupling.test.mjs +50 -0
  90. package/tests/subagent-gate-visibility.test.mjs +1 -1
  91. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  92. package/tests/subagent-launch-slots.test.mjs +18 -1
  93. package/tests/theme-contract.test.mjs +104 -0
  94. package/tests/theme-customizer-static.test.mjs +82 -0
  95. package/tests/theme-scheme-mode.test.mjs +15 -0
  96. package/tests/ui-layout-settings.test.mjs +18 -1
  97. package/tests/update-api-harness.test.mjs +111 -0
  98. package/tests/update-commands.test.mjs +15 -45
  99. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  100. package/tests/update-journal-harness.test.mjs +59 -0
  101. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  102. package/tests/update-owners.test.mjs +27 -0
  103. package/tests/update-plan.test.mjs +58 -0
  104. package/tests/update-resolver.test.mjs +56 -0
  105. package/tests/update-supervisor-harness.test.mjs +57 -0
  106. package/tests/update-tab-restore-harness.test.mjs +24 -0
  107. package/tests/update-verify.test.mjs +31 -0
  108. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  109. package/tests/workspace-session-summaries.test.mjs +288 -0
  110. package/webui-rpc-helper.mjs +119 -0
@@ -0,0 +1,167 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ applySupportedSamplingParameters,
4
+ BUILTIN_SAMPLING_APIS,
5
+ filterSupportedSamplingParameters,
6
+ resolveSamplingParameterCapabilities,
7
+ SAMPLING_PARAMETER_KEYS,
8
+ } from "../lib/sampling-parameter-capabilities.mjs";
9
+
10
+ const expectedKeys = {
11
+ "openai-completions": ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed"],
12
+ "openai-responses": ["temperature", "top_p"],
13
+ "azure-openai-responses": ["temperature", "top_p"],
14
+ "openai-codex-responses": ["temperature"],
15
+ "anthropic-messages": ["temperature"],
16
+ "google-generative-ai": ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed", "top_k"],
17
+ "google-vertex": ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed", "top_k"],
18
+ "bedrock-converse-stream": ["temperature", "top_p"],
19
+ "mistral-conversations": ["temperature"],
20
+ "pi-messages": ["temperature"],
21
+ };
22
+
23
+ assert.deepEqual(BUILTIN_SAMPLING_APIS, Object.keys(expectedKeys), "the resolver must cover every built-in Pi API family");
24
+ for (const api of BUILTIN_SAMPLING_APIS) {
25
+ const parameters = resolveSamplingParameterCapabilities({ api });
26
+ assert.deepEqual(Object.keys(parameters), SAMPLING_PARAMETER_KEYS, `${api} should return a stable capability entry for every catalog key`);
27
+ assert.deepEqual(
28
+ SAMPLING_PARAMETER_KEYS.filter((key) => parameters[key].supported),
29
+ expectedKeys[api],
30
+ `${api} should expose only verified keys`,
31
+ );
32
+ for (const [key, capability] of Object.entries(parameters)) {
33
+ assert.equal(typeof capability.reason, "string", `${api}/${key} should explain its capability`);
34
+ assert.ok(capability.reason.length > 0);
35
+ assert.ok(["api", "model", "unsupported"].includes(capability.source));
36
+ }
37
+ }
38
+
39
+ const unknown = resolveSamplingParameterCapabilities({ api: "custom-provider-v1" });
40
+ assert.ok(Object.values(unknown).every((entry) => entry.supported === false && entry.source === "unsupported"));
41
+ assert.match(unknown.temperature.reason, /provider has not declared support/i, "unknown APIs must fail closed with an actionable reason");
42
+ assert.ok(Object.values(resolveSamplingParameterCapabilities(null)).every((entry) => entry.supported === false));
43
+
44
+ const openAiExtension = resolveSamplingParameterCapabilities({
45
+ api: "openai-completions",
46
+ samplingParams: { top_k: 40, min_p: 0.05 },
47
+ });
48
+ assert.equal(openAiExtension.top_k.supported, true);
49
+ assert.equal(openAiExtension.top_k.source, "model");
50
+ assert.equal(openAiExtension.min_p.supported, true);
51
+ assert.equal(openAiExtension.min_p.source, "model");
52
+ assert.equal(resolveSamplingParameterCapabilities({ api: "openai-completions", samplingParams: {} }).top_k.supported, false);
53
+
54
+ const anthropicModel = { api: "anthropic-messages", reasoning: true, compat: { supportsTemperature: true } };
55
+ assert.equal(resolveSamplingParameterCapabilities(anthropicModel, { thinkingLevel: "off" }).temperature.supported, true);
56
+ const anthropicThinking = resolveSamplingParameterCapabilities(anthropicModel, { thinkingLevel: "high" }).temperature;
57
+ assert.equal(anthropicThinking.supported, false);
58
+ assert.match(anthropicThinking.reason, /extended thinking/i);
59
+ const anthropicUnsafeModel = resolveSamplingParameterCapabilities({
60
+ api: "anthropic-messages",
61
+ reasoning: false,
62
+ compat: { supportsTemperature: false },
63
+ }).temperature;
64
+ assert.equal(anthropicUnsafeModel.supported, false);
65
+ assert.match(anthropicUnsafeModel.reason, /model marks it unsupported/i);
66
+
67
+ const allValues = {
68
+ temperature: 0.2,
69
+ top_p: 0.8,
70
+ frequency_penalty: 0.3,
71
+ presence_penalty: 0.4,
72
+ seed: 7,
73
+ top_k: 42,
74
+ min_p: 0.06,
75
+ vendor_extension: "preserved-only",
76
+ };
77
+ const completionCapabilities = resolveSamplingParameterCapabilities({ api: "openai-completions" });
78
+ assert.deepEqual(filterSupportedSamplingParameters(allValues, completionCapabilities), {
79
+ temperature: 0.2,
80
+ top_p: 0.8,
81
+ frequency_penalty: 0.3,
82
+ presence_penalty: 0.4,
83
+ seed: 7,
84
+ }, "filtering should omit unsupported and unknown values without modifying stored state");
85
+ assert.equal(allValues.vendor_extension, "preserved-only");
86
+
87
+ const cases = [
88
+ {
89
+ api: "openai-completions",
90
+ payload: { model: "chat", messages: [], untouched: true },
91
+ expected: { model: "chat", messages: [], untouched: true, temperature: 0.2, top_p: 0.8, frequency_penalty: 0.3, presence_penalty: 0.4, seed: 7 },
92
+ },
93
+ {
94
+ api: "openai-responses",
95
+ payload: { model: "response", input: [], metadata: { trace: true } },
96
+ expected: { model: "response", input: [], metadata: { trace: true }, temperature: 0.2, top_p: 0.8 },
97
+ },
98
+ {
99
+ api: "azure-openai-responses",
100
+ payload: { model: "deployment", input: [], service_tier: "default" },
101
+ expected: { model: "deployment", input: [], service_tier: "default", temperature: 0.2, top_p: 0.8 },
102
+ },
103
+ {
104
+ api: "openai-codex-responses",
105
+ payload: { model: "gpt-5.6-sol", input: [], reasoning: { effort: "high" } },
106
+ expected: { model: "gpt-5.6-sol", input: [], reasoning: { effort: "high" }, temperature: 0.2 },
107
+ },
108
+ {
109
+ api: "anthropic-messages",
110
+ model: { reasoning: true, compat: { supportsTemperature: true } },
111
+ options: { thinkingLevel: "off" },
112
+ payload: { model: "claude", messages: [], max_tokens: 2048 },
113
+ expected: { model: "claude", messages: [], max_tokens: 2048, temperature: 0.2 },
114
+ },
115
+ {
116
+ api: "google-generative-ai",
117
+ payload: { model: "gemini", contents: [], config: { maxOutputTokens: 1024, thinkingConfig: { thinkingBudget: 0 } } },
118
+ expected: { model: "gemini", contents: [], config: { maxOutputTokens: 1024, thinkingConfig: { thinkingBudget: 0 }, temperature: 0.2, topP: 0.8, topK: 42, frequencyPenalty: 0.3, presencePenalty: 0.4, seed: 7 } },
119
+ },
120
+ {
121
+ api: "google-vertex",
122
+ payload: { contents: [], config: { systemInstruction: "keep", custom: { nested: true } } },
123
+ expected: { contents: [], config: { systemInstruction: "keep", custom: { nested: true }, temperature: 0.2, topP: 0.8, topK: 42, frequencyPenalty: 0.3, presencePenalty: 0.4, seed: 7 } },
124
+ },
125
+ {
126
+ api: "bedrock-converse-stream",
127
+ payload: { modelId: "bedrock", messages: [], inferenceConfig: { maxTokens: 512 }, additionalModelRequestFields: { keep: true } },
128
+ expected: { modelId: "bedrock", messages: [], inferenceConfig: { maxTokens: 512, temperature: 0.2, topP: 0.8 }, additionalModelRequestFields: { keep: true } },
129
+ },
130
+ {
131
+ api: "mistral-conversations",
132
+ payload: { model: "mistral", inputs: [], maxTokens: 1024 },
133
+ expected: { model: "mistral", inputs: [], maxTokens: 1024, temperature: 0.2 },
134
+ },
135
+ {
136
+ api: "pi-messages",
137
+ payload: { model: "pi", context: { messages: [] }, options: { maxTokens: 512, reasoning: "high" } },
138
+ expected: { model: "pi", context: { messages: [] }, options: { maxTokens: 512, reasoning: "high", temperature: 0.2 } },
139
+ },
140
+ ];
141
+
142
+ for (const testCase of cases) {
143
+ const model = { api: testCase.api, ...(testCase.model || {}) };
144
+ const originalPayload = structuredClone(testCase.payload);
145
+ const result = applySupportedSamplingParameters(testCase.payload, model, allValues, testCase.options);
146
+ assert.deepEqual(result, testCase.expected, `${testCase.api} should map only verified values to its API-native payload`);
147
+ assert.deepEqual(testCase.payload, originalPayload, `${testCase.api} mapping must not mutate the provider payload`);
148
+ }
149
+
150
+ assert.equal(
151
+ applySupportedSamplingParameters({ request: true }, { api: "custom-provider-v1" }, allValues),
152
+ undefined,
153
+ "unknown APIs must not receive any stored sampling values",
154
+ );
155
+ assert.equal(
156
+ applySupportedSamplingParameters({ model: "claude", thinking: { type: "enabled", budget_tokens: 1024 } }, anthropicModel, allValues, { thinkingLevel: "off" }),
157
+ undefined,
158
+ "the final Anthropic payload safety check must not add temperature when extended thinking is present",
159
+ );
160
+ assert.equal(
161
+ applySupportedSamplingParameters({ model: "claude" }, anthropicModel, allValues, { thinkingLevel: "high" }),
162
+ undefined,
163
+ "active Anthropic thinking must filter temperature before payload application",
164
+ );
165
+ assert.equal(applySupportedSamplingParameters([], { api: "openai-completions" }, allValues), undefined);
166
+
167
+ console.log("sampling-parameter-capabilities.test.mjs passed");
@@ -0,0 +1,241 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ SAMPLING_PARAMETER_CATALOG,
4
+ SAMPLING_PARAMETER_KEYS,
5
+ SamplingParameterValidationError,
6
+ buildSamplingParametersFromDraft,
7
+ createSamplingControlDraft,
8
+ samplingControlDraftEquals,
9
+ samplingParameterCapability,
10
+ samplingParameterDefinition,
11
+ samplingParameterSliderValue,
12
+ splitSamplingParameters,
13
+ summarizePreservedSamplingParameters,
14
+ validateSamplingControlDraft,
15
+ validateSamplingParameterObject,
16
+ validateSamplingParameterValue,
17
+ } from "../public/sampling-parameter-controls.mjs";
18
+
19
+ assert.deepEqual(SAMPLING_PARAMETER_KEYS, [
20
+ "temperature",
21
+ "top_p",
22
+ "frequency_penalty",
23
+ "presence_penalty",
24
+ "seed",
25
+ "top_k",
26
+ "min_p",
27
+ ], "the catalog should expose exactly the approved core and server-extension parameters");
28
+ assert.ok(Object.isFrozen(SAMPLING_PARAMETER_CATALOG));
29
+ assert.ok(Object.isFrozen(SAMPLING_PARAMETER_KEYS));
30
+ assert.ok(SAMPLING_PARAMETER_CATALOG.every((definition) => Object.isFrozen(definition) && Object.isFrozen(definition.slider)), "catalog metadata should be deeply frozen");
31
+ assert.deepEqual(
32
+ SAMPLING_PARAMETER_CATALOG.filter(({ group }) => group === "server-extension").map(({ key }) => key),
33
+ ["top_k", "min_p"],
34
+ "only the approved llama.cpp/vLLM extensions should be grouped as server extensions",
35
+ );
36
+ assert.equal(samplingParameterDefinition("temperature")?.label, "Temperature");
37
+ assert.equal(samplingParameterDefinition("missing"), null);
38
+
39
+ assert.deepEqual(samplingParameterCapability({
40
+ temperature: { supported: true, reason: "Supported by openai-codex-responses.", source: "api" },
41
+ }, "temperature"), {
42
+ supported: true,
43
+ reason: "Supported by openai-codex-responses.",
44
+ source: "api",
45
+ }, "an explicit per-key backend capability should be consumed verbatim");
46
+ assert.deepEqual(samplingParameterCapability(undefined, "top_p"), {
47
+ supported: false,
48
+ reason: "Top P is disabled because support was not reported for the active model.",
49
+ source: "unsupported",
50
+ }, "a missing support.parameters map must fail closed");
51
+ assert.equal(samplingParameterCapability({ top_p: { supported: "yes" } }, "top_p").supported, false, "only an exact supported=true declaration enables a control");
52
+ assert.throws(() => samplingParameterCapability({}, "missing"), /Unknown sampling parameter/);
53
+
54
+ function assertValid(key, rawValue, expected = rawValue) {
55
+ assert.deepEqual(validateSamplingParameterValue(key, rawValue), { valid: true, value: expected }, `${key}=${String(rawValue)} should be valid`);
56
+ }
57
+
58
+ function assertInvalid(key, rawValue, pattern) {
59
+ const result = validateSamplingParameterValue(key, rawValue);
60
+ assert.equal(result.valid, false, `${key}=${String(rawValue)} should be invalid`);
61
+ assert.match(result.error, pattern);
62
+ }
63
+
64
+ assertValid("temperature", 0);
65
+ assertValid("temperature", 2);
66
+ assertValid("temperature", " 1.25 ", 1.25);
67
+ assertValid("temperature", "1e-2", 0.01);
68
+ assertInvalid("temperature", -0.01, /0 to 2/);
69
+ assertInvalid("temperature", 2.01, /0 to 2/);
70
+ assertInvalid("temperature", "", /finite number/);
71
+ assertInvalid("temperature", "Infinity", /finite number/);
72
+ assertInvalid("temperature", Number.NaN, /finite number/);
73
+
74
+ assertValid("top_p", 0.01);
75
+ assertValid("top_p", 1);
76
+ assertInvalid("top_p", 0, /greater than 0 and at most 1/);
77
+ assertInvalid("top_p", 1.01, /greater than 0 and at most 1/);
78
+
79
+ for (const key of ["frequency_penalty", "presence_penalty"]) {
80
+ assertValid(key, -2);
81
+ assertValid(key, 2);
82
+ assertInvalid(key, -2.1, /-2 to 2/);
83
+ assertInvalid(key, 2.1, /-2 to 2/);
84
+ }
85
+
86
+ for (const key of ["seed", "top_k"]) {
87
+ assertValid(key, -1);
88
+ assertValid(key, 0);
89
+ assertValid(key, 2147483648);
90
+ assertInvalid(key, -2, /at least -1/);
91
+ assertInvalid(key, 1.5, /integer/);
92
+ }
93
+
94
+ assertValid("min_p", 0);
95
+ assertValid("min_p", 1);
96
+ assertInvalid("min_p", -0.01, /0 to 1/);
97
+ assertInvalid("min_p", 1.01, /0 to 1/);
98
+ assertInvalid("missing", 1, /Unknown sampling parameter/);
99
+
100
+ assert.deepEqual(validateSamplingParameterObject({
101
+ temperature: 0.5,
102
+ top_p: 0.9,
103
+ seed: 7,
104
+ vendor_extension: { mode: "strict" },
105
+ }), { valid: true, errors: {} }, "direct JSON validation should accept valid catalog numbers and preserve unknown-key freedom");
106
+ assert.deepEqual(validateSamplingParameterObject({ temperature: "0.5", top_p: 0, seed: 1.5 }), {
107
+ valid: false,
108
+ errors: {
109
+ temperature: "Temperature must be a number.",
110
+ top_p: "Top P must be greater than 0 and at most 1.",
111
+ seed: "Seed must be an integer.",
112
+ },
113
+ }, "direct JSON validation should enforce numeric type, range, and integer catalog constraints");
114
+ assert.equal(validateSamplingParameterObject({ vendor_extension: [1, { enabled: true }] }).valid, true);
115
+ assert.equal(validateSamplingParameterObject([]).valid, false);
116
+
117
+ const sliderDraft = createSamplingControlDraft({ top_k: 1000, seed: -1, top_p: 0.5 });
118
+ assert.equal(samplingParameterSliderValue("top_k", sliderDraft.controls.top_k.value), 200, "the top_k slider should stop at its common maximum");
119
+ assert.equal(sliderDraft.controls.top_k.value, 1000, "calculating slider position must not clamp the exact number value");
120
+ assert.equal(samplingParameterSliderValue("seed", sliderDraft.controls.seed.value), 0, "seed -1 should remain exact while its slider rests at the common minimum");
121
+ assert.equal(sliderDraft.controls.seed.value, -1);
122
+ assert.equal(samplingParameterSliderValue("top_p", sliderDraft.controls.top_p.value), 0.5);
123
+ assert.equal(samplingParameterSliderValue("top_p", "not-a-number"), 0.01, "invalid input should use a safe visual slider position only");
124
+ assert.throws(() => samplingParameterSliderValue("missing", 1), /Unknown sampling parameter/);
125
+
126
+ const source = JSON.parse('{"temperature":0.4,"top_k":42,"vendor_mode":{"name":"fast","weights":[1,2]},"__proto__":{"polluted":true}}');
127
+ const split = splitSamplingParameters(source);
128
+ assert.deepEqual(split.known, { temperature: 0.4, top_k: 42 });
129
+ assert.deepEqual(split.unknown.vendor_mode, { name: "fast", weights: [1, 2] });
130
+ assert.equal(Object.hasOwn(split.unknown, "__proto__"), true, "a JSON __proto__ key should remain an inert own property");
131
+ assert.equal({}.polluted, undefined, "splitting untrusted JSON keys must not alter Object.prototype");
132
+ split.unknown.vendor_mode.weights.push(3);
133
+ assert.deepEqual(source.vendor_mode.weights, [1, 2], "split output should not alias API state");
134
+
135
+ assert.throws(() => splitSamplingParameters([]), /plain object/);
136
+ assert.throws(() => splitSamplingParameters(new (class Sampling {})()), /plain object/);
137
+ assert.throws(() => splitSamplingParameters({ custom: new Date() }), /plain object prototype/);
138
+ assert.throws(() => splitSamplingParameters({ custom: Number.NaN }), /finite JSON numbers/);
139
+ const circular = {};
140
+ circular.self = circular;
141
+ assert.throws(() => splitSamplingParameters(circular), /circular/);
142
+
143
+ const draft = createSamplingControlDraft(
144
+ { temperature: 0.3, top_p: 0, vendor_flag: true, nested_vendor: { mode: "strict" } },
145
+ { defaults: { temperature: 1, frequency_penalty: 0.5, seed: "invalid" } },
146
+ );
147
+ assert.equal(draft.controls.temperature.enabled, true);
148
+ assert.equal(draft.controls.temperature.value, 0.3, "an enabled session value should win over a model default");
149
+ assert.equal(draft.controls.top_p.enabled, true);
150
+ assert.equal(draft.controls.top_p.value, 0, "an invalid existing value should be retained for an explicit validation error");
151
+ assert.equal(draft.controls.frequency_penalty.enabled, false);
152
+ assert.equal(draft.controls.frequency_penalty.value, 0.5, "a valid model default may be shown as a disabled suggestion");
153
+ assert.equal(draft.controls.seed.enabled, false);
154
+ assert.equal(draft.controls.seed.value, "", "an invalid model default must not become an editable suggestion");
155
+ assert.equal(draft.controls.presence_penalty.value, "", "an absent parameter must not receive an invented value");
156
+ assert.deepEqual(draft.preservedUnknown, { vendor_flag: true, nested_vendor: { mode: "strict" } });
157
+
158
+ const invalidDraft = validateSamplingControlDraft(draft);
159
+ assert.equal(invalidDraft.valid, false);
160
+ assert.match(invalidDraft.errors.top_p, /greater than 0/);
161
+ assert.throws(
162
+ () => buildSamplingParametersFromDraft(draft),
163
+ (error) => error instanceof SamplingParameterValidationError
164
+ && error.code === "SAMPLING_PARAMETERS_INVALID"
165
+ && Boolean(error.errors.top_p),
166
+ "invalid legacy values should block serialization instead of being silently clamped",
167
+ );
168
+
169
+ const editedDraft = structuredClone(draft);
170
+ editedDraft.controls.top_p.value = "0.9";
171
+ editedDraft.controls.temperature.enabled = false;
172
+ editedDraft.controls.frequency_penalty.enabled = true;
173
+ editedDraft.controls.frequency_penalty.value = "-1.2";
174
+ editedDraft.controls.top_k.enabled = true;
175
+ editedDraft.controls.top_k.value = "1000";
176
+ const validDraft = validateSamplingControlDraft(editedDraft);
177
+ assert.deepEqual(validDraft, {
178
+ valid: true,
179
+ errors: {},
180
+ values: { top_p: 0.9, frequency_penalty: -1.2, top_k: 1000 },
181
+ });
182
+ assert.deepEqual(buildSamplingParametersFromDraft(editedDraft), {
183
+ vendor_flag: true,
184
+ nested_vendor: { mode: "strict" },
185
+ top_p: 0.9,
186
+ frequency_penalty: -1.2,
187
+ top_k: 1000,
188
+ }, "enabled known controls should merge over cloned hidden values while disabled known controls disappear");
189
+ assert.equal(draft.controls.temperature.enabled, true, "editing a cloned draft must not mutate the loaded draft");
190
+
191
+ const defensiveDraft = {
192
+ controls: {
193
+ temperature: { enabled: false, value: 1 },
194
+ min_p: { enabled: true, value: 0.2 },
195
+ },
196
+ preservedUnknown: { temperature: 1.8, vendor: "kept" },
197
+ };
198
+ assert.deepEqual(buildSamplingParametersFromDraft(defensiveDraft), { vendor: "kept", min_p: 0.2 }, "known keys must be deleted from the preserved map before enabled controls are merged");
199
+ assert.deepEqual(buildSamplingParametersFromDraft({ controls: {}, preservedUnknown: {} }), {});
200
+ assert.equal(validateSamplingControlDraft({ controls: { seed: { enabled: "yes", value: 1 } }, preservedUnknown: {} }).valid, false);
201
+ assert.equal(validateSamplingControlDraft({ controls: { seed: 1 }, preservedUnknown: {} }).valid, false);
202
+ assert.equal(validateSamplingControlDraft(null).valid, false);
203
+ assert.equal(validateSamplingControlDraft({ controls: {}, preservedUnknown: [] }).valid, false);
204
+
205
+ const hiddenProto = JSON.parse('{"__proto__":{"polluted":true},"custom":7}');
206
+ const protoOutput = buildSamplingParametersFromDraft({ controls: {}, preservedUnknown: hiddenProto });
207
+ assert.equal(Object.hasOwn(protoOutput, "__proto__"), true);
208
+ assert.equal(protoOutput.custom, 7);
209
+ assert.equal({}.polluted, undefined, "serializing hidden keys must remain prototype-safe");
210
+
211
+ assert.deepEqual(summarizePreservedSamplingParameters({}), {
212
+ count: 0,
213
+ text: "No additional parameters are preserved outside this editor.",
214
+ });
215
+ assert.deepEqual(summarizePreservedSamplingParameters({ vendor: true }), {
216
+ count: 1,
217
+ text: "1 additional parameter is preserved outside this editor.",
218
+ });
219
+ assert.deepEqual(summarizePreservedSamplingParameters({ one: 1, two: 2 }), {
220
+ count: 2,
221
+ text: "2 additional parameters are preserved outside this editor.",
222
+ });
223
+ assert.doesNotMatch(summarizePreservedSamplingParameters({ secret_vendor_key: true }).text, /secret_vendor_key/, "the summary should not expose hidden JSON keys");
224
+
225
+ const equivalentA = createSamplingControlDraft({ temperature: 1, custom: { b: 2, a: 1 } });
226
+ const equivalentB = createSamplingControlDraft({ custom: { a: 1, b: 2 }, temperature: 1 });
227
+ equivalentB.controls.temperature.value = "1.0";
228
+ assert.equal(samplingControlDraftEquals(equivalentA, equivalentB), true, "numeric text and hidden object key order should not create a dirty draft");
229
+ equivalentB.controls.temperature.value = "1.1";
230
+ assert.equal(samplingControlDraftEquals(equivalentA, equivalentB), false);
231
+ equivalentB.controls.temperature.enabled = false;
232
+ assert.equal(samplingControlDraftEquals(equivalentA, equivalentB), false, "enabled state is part of draft meaning");
233
+ const invalidA = createSamplingControlDraft({});
234
+ const invalidB = createSamplingControlDraft({});
235
+ invalidA.controls.temperature.enabled = true;
236
+ invalidB.controls.temperature.enabled = true;
237
+ invalidA.controls.temperature.value = "bad-a";
238
+ invalidB.controls.temperature.value = "bad-b";
239
+ assert.equal(samplingControlDraftEquals(invalidA, invalidB), false, "distinct invalid edits must remain distinguishable");
240
+
241
+ console.log("sampling-parameter-controls.test.mjs passed");
@@ -0,0 +1,228 @@
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() { this.handlers = new Map(); }
9
+ on(name, handler) {
10
+ const handlers = this.handlers.get(name) || new Set();
11
+ handlers.add(handler);
12
+ this.handlers.set(name, handlers);
13
+ return () => handlers.delete(handler);
14
+ }
15
+ emit(name, value) {
16
+ for (const handler of [...(this.handlers.get(name) || [])]) handler(value);
17
+ }
18
+ }
19
+
20
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-session-sampling-"));
21
+ const settingsFile = path.join(root, "settings.json");
22
+ const previousSettingsFile = process.env.PI_WEBUI_SETTINGS_FILE;
23
+ process.env.PI_WEBUI_SETTINGS_FILE = settingsFile;
24
+
25
+ try {
26
+ await writeFile(settingsFile, `${JSON.stringify({ version: 3 })}\n`, "utf8");
27
+ const extensionHandlers = new Map();
28
+ const registeredCommands = new Map();
29
+ const notifications = [];
30
+ const appendedEntries = [];
31
+ const bus = new EventBus();
32
+ let branchEntries = [{
33
+ type: "custom",
34
+ customType: "webui-session-sampling-params-v1",
35
+ data: { version: 1, samplingParams: { temperature: 0.4, nested: { top_k: 12 } } },
36
+ }];
37
+ let model = {
38
+ provider: "fixture",
39
+ id: "compatible-model",
40
+ name: "Compatible model",
41
+ api: "openai-completions",
42
+ samplingParams: { temperature: 0.8, top_p: 0.95 },
43
+ };
44
+
45
+ const pi = {
46
+ events: bus,
47
+ on(name, handler) {
48
+ const handlers = extensionHandlers.get(name) || [];
49
+ handlers.push(handler);
50
+ extensionHandlers.set(name, handlers);
51
+ },
52
+ registerCommand(name, command) { registeredCommands.set(name, command); },
53
+ getAllTools() { return []; },
54
+ getActiveTools() { return []; },
55
+ setActiveTools() {},
56
+ appendEntry(customType, data) { appendedEntries.push({ customType, data }); },
57
+ getCommands() { return []; },
58
+ };
59
+
60
+ const ctx = {
61
+ mode: "rpc",
62
+ hasUI: true,
63
+ cwd: root,
64
+ sessionManager: { getBranch() { return branchEntries; } },
65
+ get model() { return model; },
66
+ thinkingLevel: "off",
67
+ getSystemPromptOptions() { return { skills: [] }; },
68
+ isIdle() { return true; },
69
+ ui: {
70
+ setStatus() {},
71
+ notify(message, type) { notifications.push({ message, type }); },
72
+ },
73
+ };
74
+
75
+ webuiRpcHelper(pi);
76
+ const helperCommand = registeredCommands.get("webui-helper");
77
+ assert.ok(helperCommand?.handler, "sampling test requires the hidden helper command");
78
+
79
+ async function runHelper(action, payload = {}, { ok = true } = {}) {
80
+ const requestId = `${action}-${notifications.length}`;
81
+ await helperCommand.handler(JSON.stringify({ requestId, action, payload }), ctx);
82
+ const notice = notifications.findLast((entry) => entry.message.includes(`\"requestId\":\"${requestId}\"`));
83
+ assert.ok(notice, `${action} should emit a helper response`);
84
+ const response = JSON.parse(notice.message.slice("__PI_WEBUI_HELPER_RESPONSE__:".length));
85
+ assert.equal(response.ok, ok, response.error);
86
+ return response;
87
+ }
88
+
89
+ for (const handler of extensionHandlers.get("session_start") || []) await handler({ reason: "resume" }, ctx);
90
+ const restored = (await runHelper("sampling-state")).data;
91
+ assert.deepEqual(restored.session, { temperature: 0.4, nested: { top_k: 12 } });
92
+ assert.deepEqual(restored.defaults, { temperature: 0.8, top_p: 0.95 });
93
+ assert.deepEqual(restored.effective, { temperature: 0.4, top_p: 0.95 }, "unknown stored keys should be preserved but inert");
94
+ assert.equal(restored.support.supported, true);
95
+ assert.equal(restored.support.api, "openai-completions");
96
+ assert.deepEqual(Object.keys(restored.support.parameters), [
97
+ "temperature",
98
+ "top_p",
99
+ "frequency_penalty",
100
+ "presence_penalty",
101
+ "seed",
102
+ "top_k",
103
+ "min_p",
104
+ ]);
105
+ assert.equal(restored.support.parameters.temperature.supported, true);
106
+ assert.equal(restored.support.parameters.top_k.supported, false);
107
+ assert.deepEqual(restored.support.model, {
108
+ provider: "fixture",
109
+ id: "compatible-model",
110
+ name: "Compatible model",
111
+ }, "sampling state should read the active model from the public context property");
112
+
113
+ const requestHook = (extensionHandlers.get("before_provider_request") || [])[0];
114
+ assert.ok(requestHook, "sampling test requires the provider request hook");
115
+ assert.deepEqual(
116
+ await requestHook({ payload: { model: "compatible-model", temperature: 1, messages: [] } }, ctx),
117
+ { model: "compatible-model", temperature: 0.4, messages: [] },
118
+ "only supported session values should win for compatible requests",
119
+ );
120
+
121
+ const updated = (await runHelper("sampling-set", { samplingParams: { temperature: 0.2, top_p: 0.9, extra: [1, { enabled: true }] } })).data;
122
+ assert.deepEqual(updated.session, { temperature: 0.2, top_p: 0.9, extra: [1, { enabled: true }] });
123
+ assert.deepEqual(appendedEntries.at(-1), {
124
+ customType: "webui-session-sampling-params-v1",
125
+ data: { version: 1, samplingParams: { temperature: 0.2, top_p: 0.9, extra: [1, { enabled: true }] } },
126
+ });
127
+
128
+ const persistedCount = appendedEntries.length;
129
+ const invalidKnownWrites = [
130
+ [{ temperature: "0.2" }, /Temperature must be a number\./],
131
+ [{ top_p: 0 }, /Top P must be greater than 0 and at most 1\./],
132
+ [{ seed: 1.5 }, /Seed must be an integer\./],
133
+ ];
134
+ for (const [samplingParams, errorPattern] of invalidKnownWrites) {
135
+ const rejected = await runHelper("sampling-set", { samplingParams }, { ok: false });
136
+ assert.match(rejected.error, errorPattern, "direct helper writes should explicitly reject invalid catalog values");
137
+ assert.equal(appendedEntries.length, persistedCount, "invalid catalog values must not persist");
138
+ assert.deepEqual((await runHelper("sampling-state")).data.session, updated.session, "invalid catalog values must not replace active state");
139
+ }
140
+ assert.match((await runHelper("sampling-set", { samplingParams: [] }, { ok: false })).error, /JSON object/i);
141
+ assert.match((await runHelper("sampling-set", { samplingParams: Object.fromEntries(Array.from({ length: 129 }, (_, index) => [`key${index}`, index])) }, { ok: false })).error, /at most 128/i);
142
+ assert.match((await runHelper("sampling-set", { samplingParams: { prompt: "x".repeat(17 * 1024) } }, { ok: false })).error, /at most 16384 bytes/i);
143
+ assert.equal(appendedEntries.length, persistedCount, "rejected values must not persist or replace active state");
144
+ assert.deepEqual((await runHelper("sampling-state")).data.session, updated.session);
145
+
146
+ for (const api of ["openai-responses", "azure-openai-responses"]) {
147
+ model = { ...model, api };
148
+ assert.equal((await runHelper("sampling-state")).data.support.supported, true, `${api} should be supported`);
149
+ assert.equal((await requestHook({ payload: { input: [] } }, ctx)).temperature, 0.2);
150
+ }
151
+
152
+ model = {
153
+ ...model,
154
+ provider: "openai-codex",
155
+ id: "gpt-5.6-sol",
156
+ name: "GPT-5.6 Sol",
157
+ api: "openai-codex-responses",
158
+ };
159
+ const codex = (await runHelper("sampling-state")).data;
160
+ assert.deepEqual(codex.support.model, {
161
+ provider: "openai-codex",
162
+ id: "gpt-5.6-sol",
163
+ name: "GPT-5.6 Sol",
164
+ }, "Codex models should be recognized by the per-key capability contract");
165
+ assert.equal(codex.support.api, "openai-codex-responses");
166
+ assert.equal(codex.support.supported, true);
167
+ assert.equal(codex.support.parameters.temperature.supported, true);
168
+ assert.equal(codex.support.parameters.top_p.supported, false);
169
+ assert.deepEqual(codex.effective, { temperature: 0.2 }, "Codex should expose only its verified temperature value");
170
+ assert.deepEqual(await requestHook({ payload: { model: "gpt-5.6-sol", input: [], service_tier: "priority" } }, ctx), {
171
+ model: "gpt-5.6-sol",
172
+ input: [],
173
+ service_tier: "priority",
174
+ temperature: 0.2,
175
+ }, "unsupported stored values must not overwrite unrelated provider payload fields");
176
+
177
+ model = { ...model, api: "anthropic-messages", reasoning: true, compat: { supportsTemperature: true } };
178
+ ctx.thinkingLevel = "high";
179
+ const thinking = (await runHelper("sampling-state")).data;
180
+ assert.equal(thinking.support.supported, false);
181
+ assert.match(thinking.support.parameters.temperature.reason, /extended thinking/i);
182
+ assert.deepEqual(thinking.session, updated.session, "unsupported models should retain the complete session override");
183
+ assert.deepEqual(thinking.effective, {}, "conditionally unsupported values should disappear from effective state");
184
+ assert.equal(await requestHook({ payload: { model: "claude", thinking: { type: "enabled" } } }, ctx), undefined, "Anthropic thinking payloads must remain untouched");
185
+
186
+ model = { ...model, api: "custom-provider-v1" };
187
+ ctx.thinkingLevel = "off";
188
+ const unsupported = (await runHelper("sampling-state")).data;
189
+ assert.equal(unsupported.support.supported, false);
190
+ assert.ok(Object.values(unsupported.support.parameters).every((entry) => entry.supported === false));
191
+ assert.deepEqual(unsupported.session, updated.session, "unknown APIs should preserve the session override");
192
+ assert.deepEqual(unsupported.effective, {}, "unknown APIs should fail closed");
193
+ assert.equal(await requestHook({ payload: { model: "unsupported", temperature: 1 } }, ctx), undefined, "unknown provider payloads must remain untouched");
194
+
195
+ model = { ...model, api: "openai-completions", reasoning: false };
196
+ const reactivated = (await runHelper("sampling-state")).data;
197
+ assert.deepEqual(reactivated.effective, { temperature: 0.2, top_p: 0.9 }, "preserved values should reactivate after switching back to a compatible API");
198
+
199
+ const reset = (await runHelper("sampling-reset")).data;
200
+ assert.deepEqual(reset.session, {});
201
+ assert.deepEqual(appendedEntries.at(-1), {
202
+ customType: "webui-session-sampling-params-v1",
203
+ data: { version: 1, samplingParams: {} },
204
+ }, "reset must persist an empty entry so earlier branch values cannot reappear");
205
+
206
+ branchEntries = [
207
+ branchEntries[0],
208
+ { type: "custom", customType: "webui-session-sampling-params-v1", data: { version: 1, samplingParams: { top_p: 0.5 } } },
209
+ { type: "custom", customType: "webui-session-sampling-params-v1", data: { version: 1, samplingParams: {} } },
210
+ ];
211
+ for (const handler of extensionHandlers.get("session_tree") || []) await handler({ newLeafId: "leaf-reset" }, ctx);
212
+ assert.deepEqual((await runHelper("sampling-state")).data.session, {}, "tree navigation should restore the last value on the active branch");
213
+
214
+ branchEntries = [{
215
+ type: "custom",
216
+ customType: "webui-session-sampling-params-v1",
217
+ data: { version: 1, samplingParams: ["invalid persisted shape"] },
218
+ }];
219
+ for (const handler of extensionHandlers.get("session_tree") || []) await handler({ newLeafId: "leaf-invalid" }, ctx);
220
+ assert.deepEqual((await runHelper("sampling-state")).data.session, {}, "malformed persisted entries should fail closed");
221
+
222
+ for (const handler of extensionHandlers.get("session_shutdown") || []) await handler({ reason: "quit" }, ctx);
223
+ console.log("session-sampling-helper.test.mjs passed");
224
+ } finally {
225
+ if (previousSettingsFile === undefined) delete process.env.PI_WEBUI_SETTINGS_FILE;
226
+ else process.env.PI_WEBUI_SETTINGS_FILE = previousSettingsFile;
227
+ await rm(root, { recursive: true, force: true });
228
+ }