@firstpick/pi-package-webui 0.8.6 → 0.8.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.
Files changed (90) hide show
  1. package/README.md +18 -606
  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 +562 -524
  5. package/index.ts +8 -5
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +17 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-preferences.mjs +16 -1
  11. package/lib/subagent-launch-slots.mjs +14 -2
  12. package/lib/trust-boundaries.mjs +3 -0
  13. package/lib/update/executor.mjs +99 -0
  14. package/lib/update/journal.mjs +175 -0
  15. package/lib/update/owners.mjs +70 -0
  16. package/lib/update/plan.mjs +134 -0
  17. package/lib/update/resolver.mjs +168 -0
  18. package/lib/update/supervisor.mjs +238 -0
  19. package/lib/update/verify.mjs +52 -0
  20. package/lib/update-commands.mjs +25 -13
  21. package/lib/webui-workspaces.mjs +17 -1
  22. package/package.json +4 -4
  23. package/public/app.js +1543 -109
  24. package/public/index.html +146 -48
  25. package/public/middle-button-drag-scroll.mjs +154 -0
  26. package/public/sampling-parameter-controls.mjs +361 -0
  27. package/public/service-worker.js +3 -1
  28. package/public/styles.css +512 -1
  29. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  30. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  31. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  32. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  33. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  34. package/tests/browser/update-reconnect.spec.mjs +92 -0
  35. package/tests/codex-fast-mode-static.test.mjs +2 -2
  36. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  37. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  38. package/tests/component-update-api-static.test.mjs +22 -61
  39. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  40. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  41. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  42. package/tests/fast-mode-client-static.test.mjs +1 -1
  43. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  44. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  45. package/tests/fixtures/fake-pi.mjs +68 -1
  46. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  47. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  48. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  49. package/tests/http-endpoints-harness.test.mjs +68 -18
  50. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  51. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  52. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  53. package/tests/mobile-foundation-static.test.mjs +4 -4
  54. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  55. package/tests/mobile-static.test.mjs +217 -24
  56. package/tests/open-issue-wizard-static.test.mjs +1 -1
  57. package/tests/optional-feature-migration-frontend.test.mjs +13 -5
  58. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  59. package/tests/prompt-routing-tab-status.test.mjs +8 -0
  60. package/tests/questionnaire-dialog.test.mjs +3 -3
  61. package/tests/remote-auth-settings-harness.test.mjs +34 -0
  62. package/tests/rpc-supervisor-host.test.mjs +11 -2
  63. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  64. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  65. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  66. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  67. package/tests/sampling-parameter-controls.test.mjs +241 -0
  68. package/tests/session-sampling-helper.test.mjs +228 -0
  69. package/tests/session-sampling-http.test.mjs +168 -0
  70. package/tests/session-sampling-ui-static.test.mjs +370 -0
  71. package/tests/session-summary-core.test.mjs +24 -11
  72. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  73. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  74. package/tests/staged-content-hash-contract.test.mjs +52 -11
  75. package/tests/subagent-launch-slots.test.mjs +18 -1
  76. package/tests/theme-customizer-static.test.mjs +1 -1
  77. package/tests/ui-layout-settings.test.mjs +18 -1
  78. package/tests/update-api-harness.test.mjs +111 -0
  79. package/tests/update-commands.test.mjs +15 -45
  80. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  81. package/tests/update-journal-harness.test.mjs +59 -0
  82. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  83. package/tests/update-owners.test.mjs +27 -0
  84. package/tests/update-plan.test.mjs +58 -0
  85. package/tests/update-resolver.test.mjs +56 -0
  86. package/tests/update-supervisor-harness.test.mjs +57 -0
  87. package/tests/update-tab-restore-harness.test.mjs +24 -0
  88. package/tests/update-verify.test.mjs +31 -0
  89. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  90. package/webui-rpc-helper.mjs +119 -0
@@ -0,0 +1,168 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import {
9
+ BUILTIN_SAMPLING_APIS,
10
+ resolveSamplingParameterCapabilities,
11
+ } from "../lib/sampling-parameter-capabilities.mjs";
12
+ import { terminateProcessTree } from "../lib/process-tree.mjs";
13
+
14
+ const packageRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
15
+ const serverScript = path.join(packageRoot, "bin", "pi-webui.mjs");
16
+ const fakePi = path.join(packageRoot, "tests", "fixtures", "fake-pi.mjs");
17
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-sampling-http-"));
18
+ const agentDir = path.join(root, "agent");
19
+ const cwd = path.join(root, "project");
20
+ const settingsFile = path.join(root, "settings.json");
21
+ const port = 30000 + Math.floor(Math.random() * 20000);
22
+
23
+ await mkdir(agentDir, { recursive: true });
24
+ await mkdir(cwd, { recursive: true });
25
+ await writeFile(path.join(agentDir, "trust.json"), `${JSON.stringify({ [cwd]: true }, null, 2)}\n`, "utf8");
26
+ await writeFile(settingsFile, `${JSON.stringify({ version: 3 })}\n`, "utf8");
27
+ await chmod(fakePi, 0o755);
28
+
29
+ async function request(pathname, { method = "GET", body } = {}) {
30
+ const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
31
+ method,
32
+ headers: body === undefined ? undefined : { "content-type": "application/json" },
33
+ body: body === undefined ? undefined : JSON.stringify(body),
34
+ signal: AbortSignal.timeout(5_000),
35
+ });
36
+ let payload;
37
+ try { payload = await response.json(); } catch { payload = undefined; }
38
+ return { status: response.status, body: payload, headers: response.headers };
39
+ }
40
+
41
+ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
42
+ stdio: ["ignore", "pipe", "pipe"],
43
+ env: {
44
+ ...process.env,
45
+ PI_CODING_AGENT_DIR: agentDir,
46
+ PI_WEBUI_SETTINGS_FILE: settingsFile,
47
+ PI_WEBUI_RPC_SUPERVISOR: "0",
48
+ },
49
+ });
50
+ let output = "";
51
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
52
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
53
+
54
+ try {
55
+ let health;
56
+ for (let attempt = 0; attempt < 100; attempt++) {
57
+ if (child.exitCode !== null) break;
58
+ try {
59
+ health = await request("/api/health");
60
+ if (health.status === 200 && health.body?.piRunning === true) break;
61
+ } catch {
62
+ // The focused server is still starting.
63
+ }
64
+ await delay(100);
65
+ }
66
+ assert.equal(health?.status, 200, `server should become healthy\n${output}`);
67
+ assert.equal(health.body?.piRunning, true, `fake Pi should be running\n${output}`);
68
+
69
+ const tabs = await request("/api/tabs");
70
+ const tabId = tabs.body?.data?.tabs?.[0]?.id;
71
+ assert.ok(tabId, "sampling HTTP test requires a startup tab");
72
+ const endpoint = `/api/tabs/${encodeURIComponent(tabId)}/sampling-parameters`;
73
+
74
+ const initial = await request(endpoint);
75
+ assert.equal(initial.status, 200, initial.body?.error);
76
+ assert.equal(initial.headers.get("cache-control"), "private, no-store");
77
+ assert.deepEqual(initial.body?.data?.session, {});
78
+ assert.deepEqual(initial.body?.data?.defaults, { temperature: 0.7 });
79
+ assert.deepEqual(initial.body?.data?.effective, { temperature: 0.7 });
80
+ const initialSupport = initial.body?.data?.support;
81
+ assert.equal(initialSupport?.supported, true);
82
+ assert.equal(initialSupport?.api, "openai-completions", "the additive capability map must preserve the legacy API diagnostic");
83
+ assert.deepEqual(initialSupport?.model, { provider: "fake", id: "fake-model", name: "Fake Model" });
84
+ assert.deepEqual(initialSupport?.compatibleApis, BUILTIN_SAMPLING_APIS, "the fake diagnostic API list should derive from production");
85
+ assert.equal(initialSupport?.message, "Session sampling parameters apply to subsequent provider requests.");
86
+ assert.deepEqual(Object.keys(initialSupport?.parameters || {}), [
87
+ "temperature",
88
+ "top_p",
89
+ "frequency_penalty",
90
+ "presence_penalty",
91
+ "seed",
92
+ "top_k",
93
+ "min_p",
94
+ ]);
95
+ assert.deepEqual(
96
+ initialSupport?.parameters,
97
+ resolveSamplingParameterCapabilities({ api: "openai-completions" }),
98
+ "the fake per-key capability map should remain in parity with the production resolver",
99
+ );
100
+ assert.deepEqual(initialSupport?.parameters?.temperature, {
101
+ supported: true,
102
+ reason: "Supported by openai-completions.",
103
+ source: "api",
104
+ });
105
+ assert.deepEqual(initialSupport?.parameters?.top_k, {
106
+ supported: false,
107
+ reason: "openai-completions does not declare Top K support.",
108
+ source: "unsupported",
109
+ });
110
+
111
+ const stored = { temperature: 0.2, top_p: 0.9, top_k: 40, vendor_mode: "strict" };
112
+ const saved = await request(endpoint, { method: "PUT", body: stored });
113
+ assert.equal(saved.status, 200, saved.body?.error);
114
+ assert.deepEqual(saved.body?.data?.session, stored, "unsupported and unknown values must remain stored");
115
+ assert.deepEqual(saved.body?.data?.effective, { temperature: 0.2, top_p: 0.9 }, "unsupported and unknown stored values must remain inert");
116
+ assert.deepEqual(saved.body?.data?.support, initialSupport, "writes must retain capability and backward-compatible support fields");
117
+ const reloaded = await request(endpoint);
118
+ assert.deepEqual(reloaded.body?.data?.session, stored);
119
+ assert.deepEqual(reloaded.body?.data?.effective, { temperature: 0.2, top_p: 0.9 });
120
+
121
+ const invalidKnownWrites = [
122
+ [{ temperature: "0.2" }, /Temperature must be a number\./],
123
+ [{ top_p: 0 }, /Top P must be greater than 0 and at most 1\./],
124
+ [{ seed: 1.5 }, /Seed must be an integer\./],
125
+ ];
126
+ for (const [body, errorPattern] of invalidKnownWrites) {
127
+ const rejected = await request(endpoint, { method: "PUT", body });
128
+ assert.equal(rejected.status, 400, "HTTP writes should reject invalid catalog values");
129
+ assert.match(rejected.body?.error || "", errorPattern, "HTTP rejection should identify the violated catalog constraint");
130
+ assert.deepEqual((await request(endpoint)).body?.data?.session, stored, "invalid catalog values must not replace active HTTP state");
131
+ }
132
+
133
+ const rejected = await request(endpoint, { method: "PUT", body: ["not-an-object"] });
134
+ assert.equal(rejected.status, 400, "non-object roots should be rejected by the helper");
135
+ assert.deepEqual((await request(endpoint)).body?.data?.session, stored, "rejected writes must preserve active state");
136
+
137
+ const malformed = await fetch(`http://127.0.0.1:${port}${endpoint}`, {
138
+ method: "PUT",
139
+ headers: { "content-type": "application/json" },
140
+ body: '{"temperature":',
141
+ signal: AbortSignal.timeout(5_000),
142
+ });
143
+ assert.equal(malformed.status, 400, "malformed JSON should be reported as a client error");
144
+ const empty = await request(endpoint, { method: "PUT" });
145
+ assert.equal(empty.status, 400, "an absent body must not silently reset sampling state");
146
+ assert.deepEqual((await request(endpoint)).body?.data?.session, stored, "malformed and empty writes must preserve active state");
147
+
148
+ const reset = await request(endpoint, { method: "PUT", body: {} });
149
+ assert.equal(reset.status, 200, reset.body?.error);
150
+ assert.deepEqual(reset.body?.data?.session, {});
151
+ assert.deepEqual(reset.body?.data?.effective, { temperature: 0.7 });
152
+ assert.deepEqual(reset.body?.data?.support, initialSupport, "reset must not remove additive or legacy support fields");
153
+ assert.equal((await request("/api/tabs/missing-tab/sampling-parameters")).status, 404);
154
+
155
+ const oversized = await fetch(`http://127.0.0.1:${port}${endpoint}`, {
156
+ method: "PUT",
157
+ headers: { "content-type": "application/json" },
158
+ body: JSON.stringify({ value: "x".repeat(21 * 1024) }),
159
+ signal: AbortSignal.timeout(5_000),
160
+ });
161
+ assert.equal(oversized.status, 413, "sampling writes should be bounded at HTTP ingress");
162
+
163
+ console.log("session-sampling-http.test.mjs passed");
164
+ } finally {
165
+ try { await request("/api/shutdown", { method: "POST", body: {} }); } catch { /* Best-effort graceful shutdown. */ }
166
+ if (child.exitCode === null) terminateProcessTree(child);
167
+ await rm(root, { recursive: true, force: true });
168
+ }
@@ -0,0 +1,370 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import vm from "node:vm";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import {
7
+ SAMPLING_PARAMETER_CATALOG,
8
+ buildSamplingParametersFromDraft,
9
+ createSamplingControlDraft,
10
+ samplingControlDraftEquals,
11
+ samplingParameterCapability,
12
+ samplingParameterSliderValue,
13
+ splitSamplingParameters,
14
+ summarizePreservedSamplingParameters,
15
+ validateSamplingControlDraft,
16
+ } from "../public/sampling-parameter-controls.mjs";
17
+
18
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
19
+ const [html, css, app, serviceWorker] = await Promise.all([
20
+ readFile(join(root, "public", "index.html"), "utf8"),
21
+ readFile(join(root, "public", "styles.css"), "utf8"),
22
+ readFile(join(root, "public", "app.js"), "utf8"),
23
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
24
+ ]);
25
+
26
+ // --- Static markup, startup graph, and accessibility ------------------------
27
+
28
+ const section = html.match(/<section class="side-panel-section collapsed" data-side-panel-section="sampling">[\s\S]*?<\/section>/)?.[0] || "";
29
+ assert.ok(section, "Sampling parameters should remain a first-class collapsed side-panel section");
30
+ assert.match(section, /id="sidePanelSectionToggleSampling"[\s\S]*aria-controls="sidePanelSectionSampling"[\s\S]*data-side-panel-section-toggle="sampling"/, "the sampling section should follow the shared toggle contract");
31
+ assert.match(section, /id="samplingParametersControls" class="sampling-parameter-groups"/, "native controls should have a dedicated generated-control host");
32
+ assert.match(section, /id="samplingParametersPreserved"/, "hidden JSON keys should have a count-only preservation status");
33
+ assert.doesNotMatch(section, /<textarea|samplingParametersInput|JSON object|<code id="samplingParameters(?:Defaults|Effective)"/, "the sampling UI must not expose raw JSON editing or raw JSON readouts");
34
+ assert.match(section, /id="samplingParametersSupport"[^>]*role="status"[^>]*aria-live="polite"/, "compatibility should be announced politely");
35
+ assert.match(section, /id="samplingParametersStatus"[^>]*role="status"[^>]*aria-live="polite"/, "validation and write outcomes should be announced politely");
36
+ assert.match(section, /id="applySamplingParametersButton"[^>]*disabled>Apply<\/button>/, "Apply should start disabled");
37
+ assert.match(section, /id="resetSamplingParametersButton"[^>]*disabled>Reset<\/button>/, "Reset should start disabled");
38
+ assert.match(app, /from "\.\/sampling-parameter-controls\.mjs";/, "the browser should consume the pure sampling control model");
39
+ assert.match(app, /enable\.type = "checkbox";/, "each generated parameter should have a native enable checkbox");
40
+ assert.match(app, /number\.type = "number";/, "each parameter should have a native exact number input");
41
+ assert.match(app, /range\.type = "range";/, "each parameter should have a native common-range slider");
42
+ assert.match(app, /number\.setAttribute\("aria-describedby", `\$\{descriptionId\} \$\{errorId\}`\)/, "number inputs should be linked to help and field errors");
43
+ assert.match(app, /tooltip\.setAttribute\("role", "tooltip"\)/, "each generated row should own a real tooltip element");
44
+ assert.match(app, /refs\.row\.setAttribute\("aria-describedby", tooltipId\)/, "unsupported focus targets should expose the tooltip reason to assistive technology");
45
+ assert.match(app, /refs\.enable\.setAttribute\("aria-describedby", tooltipId\)/, "disabled checkboxes should expose the same reason");
46
+ assert.match(app, /refs\.tooltip\.hidden = !parameterUnsupported;/, "supported rows should hide their unused tooltip nodes");
47
+ assert.match(app, /refs\.tooltip\.textContent = parameterUnsupported \? capability\.reason : "";/, "supported rows should clear tooltip text from the accessibility tree");
48
+ assert.match(app, /Sampling-capable APIs:/, "the diagnostic API label should not imply universal parameter compatibility");
49
+ assert.doesNotMatch(app, / Compatible APIs:/, "the outdated universal-compatibility wording should be removed");
50
+ assert.match(app, /event\.key !== "Escape"[\s\S]*sampling-tooltip-dismissed/, "Escape should dismiss only an active sampling tooltip");
51
+ assert.match(app, /pointerenter[\s\S]*focusin[\s\S]*focusout/, "dismissal should reset across new pointer and focus lifecycles");
52
+ assert.match(app, /spaceAbove < naturalHeight && spaceBelow > spaceAbove/, "tooltip placement should flip within the available scrollport bounds");
53
+ assert.match(app, /sampling: \["Sampling parameters", \["sidePanelSectionSampling"\]\]/, "mobile More should reuse the canonical sampling section");
54
+ assert.match(css, /\.sampling-parameter-control\.invalid \{[\s\S]*border-color:/, "invalid controls should be visually distinct");
55
+ assert.match(css, /\.sampling-parameter-editor \{[\s\S]*grid-template-columns:/, "native number and range inputs should have responsive layout");
56
+ assert.match(css, /\.sampling-parameter-control\.unsupported:hover:not\(\.sampling-tooltip-dismissed\) > \.sampling-parameter-unsupported-tooltip/, "pointer hover should reveal dismissible unsupported reasons");
57
+ assert.match(css, /\.sampling-parameter-control\.unsupported:focus-visible:not\(\.sampling-tooltip-dismissed\) > \.sampling-parameter-unsupported-tooltip/, "keyboard focus should reveal dismissible unsupported reasons");
58
+ assert.match(css, /\.sampling-parameter-unsupported-tooltip\.sampling-tooltip-below/, "bounded placement should support flipping below top-edge rows");
59
+ assert.match(css, /pointer-events: auto;/, "a visible unsupported tooltip should remain pointer-hoverable");
60
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v81"/, "native-control assets should advance the cache identity");
61
+ assert.match(serviceWorker, /"\/sampling-parameter-controls\.mjs"/, "the pure sampling module should be part of the offline app shell");
62
+ assert.match(html, /styles\.css\?v=104/, "the changed stylesheet should have a new revision");
63
+ assert.match(html, /app\.js\?v=120/, "the changed app module should have a new revision");
64
+
65
+ // --- Browser state behavior -------------------------------------------------
66
+
67
+ const blockStart = app.indexOf("function samplingParametersPath(");
68
+ const blockEnd = app.indexOf("\nfunction sessionCopyButton(", blockStart);
69
+ assert.ok(blockStart >= 0 && blockEnd > blockStart, "sampling browser state should remain a focused frontend block");
70
+ const samplingBlock = app.slice(blockStart, blockEnd);
71
+
72
+ function classListNode() {
73
+ const classes = new Set();
74
+ return {
75
+ classes,
76
+ classList: {
77
+ add(name) { classes.add(name); },
78
+ remove(name) { classes.delete(name); },
79
+ toggle(name, force) {
80
+ if (force) classes.add(name);
81
+ else classes.delete(name);
82
+ },
83
+ contains(name) { return classes.has(name); },
84
+ },
85
+ };
86
+ }
87
+
88
+ function simpleNode() {
89
+ const node = classListNode();
90
+ return Object.assign(node, {
91
+ textContent: "",
92
+ value: "",
93
+ disabled: false,
94
+ checked: false,
95
+ hidden: false,
96
+ tabIndex: -1,
97
+ attributes: {},
98
+ setAttribute(name, value) { this.attributes[name] = value; },
99
+ removeAttribute(name) { delete this.attributes[name]; },
100
+ });
101
+ }
102
+
103
+ function controlRefs() {
104
+ return {
105
+ row: simpleNode(),
106
+ enable: simpleNode(),
107
+ number: simpleNode(),
108
+ range: simpleNode(),
109
+ defaultValue: simpleNode(),
110
+ effectiveValue: simpleNode(),
111
+ error: simpleNode(),
112
+ tooltip: simpleNode(),
113
+ };
114
+ }
115
+
116
+ const elements = {
117
+ samplingParametersControls: null, // Dynamic DOM construction is covered statically; refs are installed below.
118
+ samplingParametersPreserved: simpleNode(),
119
+ applySamplingParametersButton: simpleNode(),
120
+ resetSamplingParametersButton: simpleNode(),
121
+ reloadSamplingParametersButton: simpleNode(),
122
+ samplingParametersSupport: simpleNode(),
123
+ samplingParametersStatus: simpleNode(),
124
+ };
125
+ const refs = Object.fromEntries(SAMPLING_PARAMETER_CATALOG.map(({ key }) => [key, controlRefs()]));
126
+ const plain = (value) => JSON.parse(JSON.stringify(value ?? null));
127
+ const hostValue = (value, fallback = undefined) => value === undefined ? fallback : JSON.parse(JSON.stringify(value));
128
+ const requests = [];
129
+ let sectionActive = true;
130
+ let nextResponse = null;
131
+ let nextError = null;
132
+ let responseGate = null;
133
+ const context = {
134
+ console,
135
+ elements,
136
+ SAMPLING_PARAMETER_CATALOG,
137
+ buildSamplingParametersFromDraft: (draft) => buildSamplingParametersFromDraft(hostValue(draft, null)),
138
+ createSamplingControlDraft: (parameters, options) => createSamplingControlDraft(hostValue(parameters, {}), hostValue(options, {})),
139
+ samplingControlDraftEquals: (left, right) => samplingControlDraftEquals(hostValue(left, null), hostValue(right, null)),
140
+ samplingParameterCapability: (parameters, key) => samplingParameterCapability(hostValue(parameters, undefined), key),
141
+ samplingParameterSliderValue,
142
+ splitSamplingParameters: (parameters) => splitSamplingParameters(hostValue(parameters, {})),
143
+ summarizePreservedSamplingParameters: (parameters) => summarizePreservedSamplingParameters(hostValue(parameters, {})),
144
+ validateSamplingControlDraft: (draft) => validateSamplingControlDraft(hostValue(draft, null)),
145
+ sidePanelSectionRecords: () => [{
146
+ id: "sampling",
147
+ section: { hidden: !sectionActive, classList: { contains: () => !sectionActive } },
148
+ }],
149
+ api: async (path, options = {}) => {
150
+ requests.push({ path, method: options.method || "GET", body: options.body, scoped: options.scoped });
151
+ if (responseGate) await responseGate;
152
+ if (nextError) throw nextError;
153
+ return { data: nextResponse };
154
+ },
155
+ };
156
+ context.refsFromHost = refs;
157
+ vm.runInNewContext(`
158
+ let samplingParametersState = null;
159
+ let samplingParametersStateTabId = null;
160
+ const samplingParametersDrafts = new Map();
161
+ let samplingParametersLoading = false;
162
+ let samplingParametersBusy = false;
163
+ let samplingParametersError = "";
164
+ let samplingParametersNotice = "";
165
+ let samplingParametersFeedbackTabId = null;
166
+ let samplingParametersRequestSerial = 0;
167
+ let activeTabId = "tab-a";
168
+ function activeTabContext(tabId = activeTabId) { return { tabId: tabId || null, generation: 0 }; }
169
+ ${samplingBlock}
170
+ for (const [key, value] of Object.entries(globalThis.refsFromHost)) samplingParameterControlElements.set(key, value);
171
+ globalThis.samplingHarness = {
172
+ setActiveTab(value) { activeTabId = value; },
173
+ setDraft(value, tabId = activeTabId) { setSamplingParametersDraft(value, tabId); },
174
+ draft(tabId = activeTabId) { return samplingParametersDraft(tabId); },
175
+ editable(tabId = activeTabId) { return samplingParametersEditableDraft(tabId); },
176
+ dirty: samplingParametersDraftIsDirty,
177
+ state() { return samplingParametersState; },
178
+ stateTabId() { return samplingParametersStateTabId; },
179
+ render: renderSamplingParameters,
180
+ load: loadSamplingParameters,
181
+ refresh: refreshSamplingParametersForTabContext,
182
+ apply: applySamplingParameters,
183
+ reset: resetSamplingParameters,
184
+ ensureLoaded: ensureSamplingParametersLoaded,
185
+ };
186
+ `, context);
187
+ const harness = context.samplingHarness;
188
+
189
+ function capabilitiesFor(supportedKeys, api = "fixture-api") {
190
+ const supported = new Set(supportedKeys);
191
+ return Object.fromEntries(SAMPLING_PARAMETER_CATALOG.map(({ key, label }) => [key, {
192
+ supported: supported.has(key),
193
+ reason: supported.has(key) ? `Supported by ${api}.` : `${api} does not declare ${label} support.`,
194
+ source: supported.has(key) ? "api" : "unsupported",
195
+ }]));
196
+ }
197
+
198
+ const supportedState = (session = {}, defaults = { temperature: 1 }) => ({
199
+ session,
200
+ defaults,
201
+ effective: { ...defaults, ...session },
202
+ support: {
203
+ supported: true,
204
+ api: "openai-completions",
205
+ model: { provider: "openai", id: "gpt-5", name: "GPT-5" },
206
+ parameters: capabilitiesFor(SAMPLING_PARAMETER_CATALOG.map(({ key }) => key), "openai-completions"),
207
+ compatibleApis: ["openai-completions", "openai-responses", "azure-openai-responses"],
208
+ message: "Session sampling parameters apply to subsequent provider requests.",
209
+ },
210
+ });
211
+
212
+ nextResponse = supportedState({ temperature: 0.2, vendor_mode: "strict" }, { temperature: 1, top_p: 0.95 });
213
+ await harness.load({ tabId: "tab-a" });
214
+ assert.deepEqual(plain(requests), [{ path: "/api/tabs/tab-a/sampling-parameters", method: "GET", scoped: false }]);
215
+ assert.equal(refs.temperature.enable.checked, true, "stored catalog values should enable their controls");
216
+ assert.equal(refs.temperature.number.value, "0.2", "the exact session value should populate the number input");
217
+ assert.equal(refs.temperature.range.value, "0.2", "the slider should mirror an in-range exact value");
218
+ assert.equal(refs.top_p.enable.checked, false, "model defaults should not become session overrides");
219
+ assert.equal(refs.top_p.number.value, "0.95", "a disabled control may show its model default as a suggestion");
220
+ assert.equal(refs.temperature.defaultValue.textContent, "1");
221
+ assert.equal(refs.temperature.effectiveValue.textContent, "0.2");
222
+ assert.equal(refs.temperature.tooltip.hidden, true, "supported rows should hide unused tooltip nodes");
223
+ assert.equal(refs.temperature.tooltip.textContent, "", "supported rows should clear unused tooltip text");
224
+ assert.equal(refs.temperature.row.attributes["aria-describedby"], undefined, "supported rows should not reference an unsupported reason");
225
+ assert.match(elements.samplingParametersPreserved.textContent, /1 additional parameter is preserved/, "unknown keys should be counted without exposure");
226
+ assert.doesNotMatch(elements.samplingParametersPreserved.textContent, /vendor_mode/);
227
+ assert.equal(elements.applySamplingParametersButton.disabled, false);
228
+
229
+ // Applying a known edit preserves hidden keys and sends the existing direct-object API shape.
230
+ requests.length = 0;
231
+ const edited = createSamplingControlDraft({ temperature: 0.2, vendor_mode: "strict" }, { defaults: { temperature: 1, top_p: 0.95 } });
232
+ edited.controls.top_p.enabled = true;
233
+ edited.controls.top_p.value = "0.9";
234
+ harness.setDraft(edited);
235
+ harness.render();
236
+ nextResponse = supportedState({ temperature: 0.2, top_p: 0.9, vendor_mode: "strict" });
237
+ await harness.apply();
238
+ assert.deepEqual(plain(requests), [{
239
+ path: "/api/tabs/tab-a/sampling-parameters",
240
+ method: "PUT",
241
+ body: { vendor_mode: "strict", temperature: 0.2, top_p: 0.9 },
242
+ scoped: false,
243
+ }], "Apply should merge enabled known controls over preserved hidden keys");
244
+ assert.equal(harness.draft(), null, "successful Apply should clear only the submitted tab draft");
245
+ assert.match(elements.samplingParametersStatus.textContent, /Applied to this Pi session/);
246
+
247
+ // Disabling a known control removes only that key.
248
+ requests.length = 0;
249
+ const disabledTemperature = createSamplingControlDraft({ temperature: 0.2, vendor_mode: "strict" });
250
+ disabledTemperature.controls.temperature.enabled = false;
251
+ harness.setDraft(disabledTemperature);
252
+ nextResponse = supportedState({ vendor_mode: "strict" });
253
+ await harness.apply();
254
+ assert.deepEqual(plain(requests[0]?.body), { vendor_mode: "strict" });
255
+
256
+ // Invalid exact values are field-linked and block writes.
257
+ requests.length = 0;
258
+ const invalid = createSamplingControlDraft({ top_p: 0.5 });
259
+ invalid.controls.top_p.value = "0";
260
+ harness.setDraft(invalid);
261
+ harness.render();
262
+ assert.equal(refs.top_p.number.attributes["aria-invalid"], "true");
263
+ assert.match(refs.top_p.error.textContent, /greater than 0/);
264
+ assert.ok(refs.top_p.row.classes.has("invalid"));
265
+ assert.equal(elements.applySamplingParametersButton.disabled, true);
266
+ await harness.apply();
267
+ assert.deepEqual(requests, [], "invalid controls should never send a request");
268
+ assert.match(elements.samplingParametersStatus.textContent, /greater than 0/);
269
+
270
+ // Exact integer values can exceed the soft slider range without being clamped.
271
+ requests.length = 0;
272
+ const largeTopK = createSamplingControlDraft({ top_k: 1000 });
273
+ harness.setDraft(largeTopK);
274
+ harness.render();
275
+ assert.equal(refs.top_k.number.value, "1000");
276
+ assert.equal(refs.top_k.range.value, "200", "the range should stop at its common maximum only visually");
277
+ nextResponse = supportedState({ top_k: 1000 });
278
+ await harness.apply();
279
+ assert.equal(requests[0]?.body?.top_k, 1000, "Apply should retain the authoritative exact number");
280
+
281
+ // A response already in flight must not erase controls changed after the request began.
282
+ requests.length = 0;
283
+ let releaseResponse;
284
+ responseGate = new Promise((resolve) => { releaseResponse = resolve; });
285
+ nextResponse = supportedState({ temperature: 0.2 });
286
+ const inFlightRefresh = harness.load({ tabId: "tab-a", force: true });
287
+ await Promise.resolve();
288
+ const changedDuringLoad = createSamplingControlDraft({ min_p: 0.25 });
289
+ harness.setDraft(changedDuringLoad, "tab-a");
290
+ harness.render();
291
+ releaseResponse();
292
+ await inFlightRefresh;
293
+ responseGate = null;
294
+ assert.equal(harness.draft("tab-a").controls.min_p.value, 0.25, "an in-flight refresh should preserve newly edited controls");
295
+
296
+ // Successful delayed PUTs clear the originating tab only.
297
+ harness.setActiveTab("tab-a");
298
+ const delayedDraft = createSamplingControlDraft({ temperature: 0.42 });
299
+ harness.setDraft(delayedDraft, "tab-a");
300
+ nextResponse = supportedState({ temperature: 0.42 });
301
+ let releaseWrite;
302
+ responseGate = new Promise((resolve) => { releaseWrite = resolve; });
303
+ const inFlightWrite = harness.apply();
304
+ await Promise.resolve();
305
+ harness.setActiveTab("tab-b");
306
+ releaseWrite();
307
+ await inFlightWrite;
308
+ responseGate = null;
309
+ assert.equal(harness.draft("tab-a"), null, "a completed PUT should clear the originating tab draft after a tab switch");
310
+
311
+ // Tab B remains independently editable while tab A retains a different draft.
312
+ harness.setActiveTab("tab-a");
313
+ harness.setDraft(createSamplingControlDraft({ temperature: 0.33 }), "tab-a");
314
+ harness.setActiveTab("tab-b");
315
+ nextResponse = supportedState({ top_p: 0.8 });
316
+ await harness.load({ tabId: "tab-b", force: true });
317
+ assert.equal(refs.top_p.number.value, "0.8");
318
+ assert.equal(harness.draft("tab-a").controls.temperature.value, 0.33);
319
+
320
+ // Unsupported APIs remain readable but cannot be applied.
321
+ requests.length = 0;
322
+ nextResponse = {
323
+ session: { temperature: 0.2 },
324
+ defaults: {},
325
+ effective: {},
326
+ support: {
327
+ supported: false,
328
+ api: "anthropic-messages",
329
+ model: { provider: "anthropic", id: "claude", name: "Claude" },
330
+ parameters: capabilitiesFor([], "anthropic-messages"),
331
+ compatibleApis: ["openai-completions", "openai-responses", "azure-openai-responses"],
332
+ message: "Session sampling parameters are stored but not applied to anthropic-messages.",
333
+ },
334
+ };
335
+ await harness.load({ tabId: "tab-b", force: true });
336
+ assert.equal(elements.applySamplingParametersButton.disabled, true);
337
+ assert.equal(refs.temperature.number.value, "0.2", "stored controls should remain readable on unsupported APIs");
338
+ assert.equal(refs.temperature.enable.checked, true, "stored unsupported values should remain visibly checked");
339
+ assert.equal(refs.temperature.enable.disabled, true, "unsupported checkboxes should be disabled");
340
+ assert.equal(refs.temperature.number.disabled, true, "unsupported number inputs should be disabled");
341
+ assert.equal(refs.temperature.range.disabled, true, "unsupported range inputs should be disabled");
342
+ assert.equal(refs.temperature.row.tabIndex, 0, "unsupported rows should remain keyboard focusable");
343
+ assert.equal(refs.temperature.row.attributes["aria-disabled"], "true");
344
+ assert.equal(refs.temperature.row.attributes["aria-describedby"], "samplingParameterTemperatureUnsupportedReason");
345
+ assert.equal(refs.temperature.tooltip.hidden, false, "unsupported tooltip nodes should remain available");
346
+ assert.match(refs.temperature.tooltip.textContent, /does not declare Temperature support/);
347
+ assert.match(elements.samplingParametersSupport.textContent, /Sampling-capable APIs:/);
348
+ assert.doesNotMatch(elements.samplingParametersSupport.textContent, /Compatible APIs:/);
349
+ requests.length = 0;
350
+ await harness.apply();
351
+ assert.deepEqual(requests, []);
352
+ assert.match(elements.samplingParametersStatus.textContent, /no verified sampling parameters/);
353
+
354
+ // Reset uses explicit {} and clears both known and hidden session parameters.
355
+ requests.length = 0;
356
+ nextResponse = supportedState({});
357
+ await harness.reset();
358
+ assert.deepEqual(plain(requests[0]?.body), {});
359
+ assert.match(elements.samplingParametersStatus.textContent, /Session override cleared/);
360
+ assert.match(elements.samplingParametersPreserved.textContent, /No additional parameters/);
361
+
362
+ // Backend failures remain visible and do not fabricate state.
363
+ requests.length = 0;
364
+ nextError = new Error("helper unavailable");
365
+ await harness.load({ tabId: "tab-b", force: true });
366
+ nextError = null;
367
+ assert.match(elements.samplingParametersStatus.textContent, /Could not load sampling parameters: helper unavailable/);
368
+ assert.ok(elements.samplingParametersStatus.classes.has("error"));
369
+
370
+ console.log("session-sampling-ui-static.test.mjs passed");
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
2
2
  import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
5
6
  import { writeSessionSummaryPreferences } from "../lib/session-summary-preferences.mjs";
6
7
  import {
7
8
  SESSION_SUMMARY_DISPLAY_TYPE,
@@ -26,6 +27,15 @@ import {
26
27
  shouldApplySummaryTitle,
27
28
  } from "../lib/session-summary-core.mjs";
28
29
 
30
+ async function waitFor(label, predicate, timeoutMs = 5_000) {
31
+ const deadline = Date.now() + timeoutMs;
32
+ while (Date.now() < deadline) {
33
+ if (predicate()) return;
34
+ await delay(10);
35
+ }
36
+ throw new Error(`${label} did not happen within ${timeoutMs}ms`);
37
+ }
38
+
29
39
  const entries = [
30
40
  { type: "message", id: "u1", message: { role: "user", content: [{ type: "text", text: "Please fix auth" }, { type: "image", data: "SECRET_IMAGE" }] } },
31
41
  { type: "message", id: "a1", message: { role: "assistant", content: [
@@ -315,7 +325,7 @@ try {
315
325
  const settledReturn = handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
316
326
  assert.equal(settledReturn, undefined, "settled handler returns synchronously");
317
327
  assert.equal(completionCalls.length, 0, "provider work does not delay outward settlement");
318
- for (let i = 0; i < 20 && completionCalls.length === 0; i += 1) await new Promise((resolve) => setImmediate(resolve));
328
+ await waitFor("automatic session-summary completion start", () => completionCalls.length === 1);
319
329
  assert.equal(completionCalls.length, 1);
320
330
  const [, completionContext, completionOptions] = completionCalls[0];
321
331
  assert.equal(completionContext.tools, undefined);
@@ -330,7 +340,7 @@ try {
330
340
  assert.equal(typeof completionOptions.sessionId, "string");
331
341
  assert.notEqual(completionOptions.sessionId, "fake-session", "completion uses a fresh routing ID");
332
342
  releaseComplete();
333
- for (let i = 0; i < 20 && !branchEntries.some((entry) => entry.customType === SESSION_SUMMARY_STATE_TYPE); i += 1) await new Promise((resolve) => setImmediate(resolve));
343
+ await waitFor("persisted automatic session-summary state", () => branchEntries.some((entry) => entry.customType === SESSION_SUMMARY_STATE_TYPE));
334
344
  const persistedState = latestSummaryState(branchEntries);
335
345
  assert.equal(persistedState.result.summaryMarkdown, "# Summary\n\nCore is ready.");
336
346
  assert.equal(sessionName, "Summary core", "first generated title applies immediately");
@@ -348,7 +358,7 @@ try {
348
358
  nextCompletionError = new Error("overlap failed");
349
359
  const overlapCallIndex = completionCalls.length;
350
360
  handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
351
- for (let i = 0; i < 20 && completionCalls.length === overlapCallIndex; i += 1) await new Promise((resolve) => setImmediate(resolve));
361
+ await waitFor("overlapping automatic session-summary start", () => completionCalls.length === overlapCallIndex + 1);
352
362
  assert.equal(completionCalls.length, overlapCallIndex + 1);
353
363
  const overlapRefresh = commands.get("summary").handler("refresh", ctx);
354
364
  releaseComplete();
@@ -364,20 +374,21 @@ try {
364
374
  const coalescedFailureCountBefore = branchEntries.filter((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed").length;
365
375
  const coalescedCallIndex = completionCalls.length;
366
376
  handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
367
- for (let i = 0; i < 20 && completionCalls.length === coalescedCallIndex; i += 1) await new Promise((resolve) => setImmediate(resolve));
377
+ await waitFor("coalesced automatic session-summary start", () => completionCalls.length === coalescedCallIndex + 1);
368
378
  assert.equal(completionCalls.length, coalescedCallIndex + 1);
369
379
  handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
370
380
  nextCompletionError = new Error("pending automatic failed");
371
381
  completeGate = Promise.resolve();
372
382
  releaseComplete();
373
- for (let i = 0; i < 40 && !branchEntries.some((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed"); i += 1) {
374
- await new Promise((resolve) => setImmediate(resolve));
375
- }
383
+ await waitFor(
384
+ "pending automatic session-summary failure",
385
+ () => branchEntries.some((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed"),
386
+ );
376
387
  assert.equal(completionCalls.length, coalescedCallIndex + 2, "pending automatic refresh launches after the first succeeds");
377
388
  const coalescedFailures = branchEntries.filter((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed");
378
389
  assert.equal(coalescedFailures.length - coalescedFailureCountBefore, 1, "an internally launched pending failure emits exactly one terminal RPC event");
379
390
 
380
- for (let i = 0; i < 20 && !branchEntries.some((entry) => entry.details?.kind === "success"); i += 1) await new Promise((resolve) => setImmediate(resolve));
391
+ await waitFor("automatic session-summary success", () => branchEntries.some((entry) => entry.details?.kind === "success"));
381
392
  assert.equal(latestSummaryNameProvenance(branchEntries), undefined, "self-generated rename does not record explicit provenance");
382
393
 
383
394
  api.setSessionName("Summary core");
@@ -424,7 +435,7 @@ try {
424
435
  fakeOutput = { version: 1, title: "Stale title", summaryMarkdown: "# Stale result" };
425
436
  const staleCallIndex = completionCalls.length;
426
437
  const staleRefresh = commands.get("summary").handler("refresh", ctx);
427
- for (let i = 0; i < 20 && completionCalls.length === staleCallIndex; i += 1) await new Promise((resolve) => setImmediate(resolve));
438
+ await waitFor("stale-source session-summary start", () => completionCalls.length === staleCallIndex + 1);
428
439
  assert.equal(completionCalls.length, staleCallIndex + 1);
429
440
  activeBranch = branchB;
430
441
  leafId = branchB.at(-1).id;
@@ -499,8 +510,10 @@ try {
499
510
  }
500
511
  }
501
512
 
502
- const testCwd = "/tmp/test-workspace-a";
503
- const crossCwd = "/tmp/test-workspace-b";
513
+ const testCwd = join(extensionTemp, "test-workspace-a");
514
+ const crossCwd = join(extensionTemp, "test-workspace-b");
515
+ await mkdir(testCwd, { recursive: true });
516
+ await mkdir(crossCwd, { recursive: true });
504
517
  const fakeChannel = new FakeChannel();
505
518
  fakeChannel.peers.set("self-sender-1", { cwd: testCwd, pid: process.pid });
506
519
  const w2Tools = new Map();