@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,57 @@
1
+ import assert from "node:assert/strict";
2
+ import { createServer } from "node:http";
3
+ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import {
7
+ listenWithRetry,
8
+ managedRuntimePaths,
9
+ probeCandidateRuntime,
10
+ readRuntimePointer,
11
+ rollbackRuntimePointer,
12
+ switchRuntimePointer,
13
+ writeRuntimePointer,
14
+ } from "../lib/update/supervisor.mjs";
15
+
16
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-supervisor-"));
17
+ try {
18
+ const paths = managedRuntimePaths(root);
19
+ const makeRuntime = async (name, version) => {
20
+ const runtimeRoot = path.join(paths.runtimesDir, name);
21
+ const serverEntry = path.join(runtimeRoot, "bin", "pi-webui.mjs");
22
+ await mkdir(path.dirname(serverEntry), { recursive: true });
23
+ await writeFile(serverEntry, `if (process.argv[2] === "--candidate-probe") console.log(JSON.stringify({ok:true,version:${JSON.stringify(version)},piVersion:"9.9.9"}));\n`, "utf8");
24
+ return { runtimeRoot, serverEntry, version };
25
+ };
26
+ const first = await makeRuntime("first", "1.0.0");
27
+ const second = await makeRuntime("second", "2.0.0");
28
+ await switchRuntimePointer(root, first);
29
+ assert.equal((await readRuntimePointer(root, "current")).version, "1.0.0");
30
+ const bootstrapRollback = await rollbackRuntimePointer(root);
31
+ assert.equal(bootstrapRollback.bootstrapFallback, true, "the first failed managed activation must fall back to the installed bootstrap");
32
+ assert.equal(await readRuntimePointer(root, "current"), null);
33
+ await switchRuntimePointer(root, first);
34
+ await switchRuntimePointer(root, second);
35
+ assert.equal((await readRuntimePointer(root, "current")).version, "2.0.0");
36
+ assert.equal((await readRuntimePointer(root, "previous")).version, "1.0.0");
37
+ await rollbackRuntimePointer(root);
38
+ assert.equal((await readRuntimePointer(root, "current")).version, "1.0.0");
39
+ await assert.rejects(() => writeRuntimePointer(root, "current", { runtimeRoot: path.join(root, "escape"), serverEntry: path.join(root, "escape", "server.mjs"), version: "3.0.0" }), /escapes/);
40
+ const probe = await probeCandidateRuntime(second.serverEntry, { expectedVersion: "2.0.0", expectedPiVersion: "9.9.9" });
41
+ assert.equal(probe.ok, true);
42
+ assert.equal((await probeCandidateRuntime(second.serverEntry, { expectedVersion: "2.0.0", expectedPiVersion: "8.8.8" })).ok, false);
43
+ const wrongProbe = await probeCandidateRuntime(second.serverEntry, { expectedVersion: "9.0.0" });
44
+ assert.equal(wrongProbe.ok, false);
45
+
46
+ const occupied = createServer();
47
+ await new Promise((resolve) => occupied.listen(0, "127.0.0.1", resolve));
48
+ const port = occupied.address().port;
49
+ const replacement = createServer((_req, res) => res.end("ok"));
50
+ setTimeout(() => occupied.close(), 180);
51
+ const attempt = await listenWithRetry(replacement, { port, host: "127.0.0.1", attempts: 6, initialDelayMs: 50 });
52
+ assert.ok(attempt > 1, "EADDRINUSE startup should retry with bounded backoff");
53
+ await new Promise((resolve) => replacement.close(resolve));
54
+ } finally {
55
+ await rm(root, { recursive: true, force: true });
56
+ }
57
+ console.log("update supervisor harness passed");
@@ -0,0 +1,24 @@
1
+ import assert from "node:assert/strict";
2
+ import { access, mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { createRestoreFile, readRestoreFileOnce } from "../lib/update/supervisor.mjs";
6
+
7
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-restore-"));
8
+ try {
9
+ const tabs = Array.from({ length: 130 }, (_, index) => ({ id: `tab-${index + 1}`, index: index + 1, title: `Tab ${index + 1}`, cwd: root, sessionFile: path.join(root, `${index + 1}.jsonl`) }));
10
+ const handoff = await createRestoreFile(root, tabs);
11
+ assert.equal(handoff.count, 130, "private restore handoff must support at least 125 tabs");
12
+ const restored = await readRestoreFileOnce(handoff.file, root);
13
+ assert.equal(restored.length, 130);
14
+ assert.equal(restored[124].id, "tab-125");
15
+ await assert.rejects(() => access(handoff.file), /ENOENT/, "restore handoff must be deleted after its first read");
16
+
17
+ const outside = path.join(root, "outside.json");
18
+ await writeFile(outside, JSON.stringify({ schemaVersion: 1, tabs: [] }));
19
+ await assert.rejects(() => readRestoreFileOnce(outside, root), /outside the private temp root/);
20
+ await access(outside);
21
+ } finally {
22
+ await rm(root, { recursive: true, force: true });
23
+ }
24
+ console.log("update tab restore harness passed");
@@ -0,0 +1,31 @@
1
+ import assert from "node:assert/strict";
2
+ import { failedTargetReceipt, reduceUpdateReceipts, rolledBackTargetReceipt, verifyTargetResult } from "../lib/update/verify.mjs";
3
+
4
+ const pi = { id: "pi", kind: "pi", currentVersion: "1.0.0", targetVersion: "2.0.0" };
5
+ const webui = { id: "webui", kind: "webui", currentVersion: "0.8.6", targetVersion: "0.9.0" };
6
+ const identity = { canonicalId: "pi:/active/cli.js" };
7
+ for (const target of [pi, webui]) {
8
+ const unchanged = verifyTargetResult(target, { beforeIdentity: identity, afterIdentity: identity, afterVersion: target.currentVersion });
9
+ assert.equal(unchanged.status, "failed");
10
+ assert.match(unchanged.message, /without changing/i, `${target.kind} exit-zero/no-change must fail`);
11
+ }
12
+ const wrong = verifyTargetResult(pi, { beforeIdentity: identity, afterIdentity: identity, afterVersion: "1.5.0" });
13
+ assert.equal(wrong.status, "failed");
14
+ assert.match(wrong.message, /Expected exact version 2\.0\.0/);
15
+ const changedIdentity = verifyTargetResult(pi, { beforeIdentity: identity, afterIdentity: { canonicalId: "pi:/path/cli.js" }, afterVersion: "2.0.0" });
16
+ assert.equal(changedIdentity.status, "failed");
17
+ const success = verifyTargetResult(pi, { beforeIdentity: identity, afterIdentity: identity, afterVersion: "2.0.0" });
18
+ assert.equal(success.status, "success");
19
+
20
+ const partial = reduceUpdateReceipts([success, failedTargetReceipt(webui, "fixture failure")]);
21
+ assert.equal(partial.outcome, "partial");
22
+ assert.deepEqual(partial.receipts.map((item) => item.targetId), ["pi", "webui"], "partial receipts retain target order");
23
+ assert.deepEqual(partial.counts, { success: 1, failed: 1, rolledBack: 0 });
24
+ const optional = { id: "optional:statsCommand", kind: "optional", currentVersion: "1.0.0", targetVersion: "2.0.0" };
25
+ const webuiSuccess = verifyTargetResult(webui, { beforeIdentity: { canonicalId: "webui:/active" }, afterIdentity: { canonicalId: "webui:/active" }, afterVersion: "0.9.0" });
26
+ const optionalPartial = reduceUpdateReceipts([webuiSuccess, failedTargetReceipt(optional, "fixture optional-package failure")]);
27
+ assert.equal(optionalPartial.outcome, "partial", "a verified WebUI target plus a failed Pi-owned optional package must remain partial");
28
+ assert.deepEqual(optionalPartial.receipts.map((item) => item.targetId), ["webui", "optional:statsCommand"]);
29
+ assert.equal(reduceUpdateReceipts([failedTargetReceipt(pi, "failed")]).outcome, "failed");
30
+ assert.equal(reduceUpdateReceipts([rolledBackTargetReceipt(webui, "restored")]).outcome, "rolled-back");
31
+ console.log("update-verify.test.mjs passed");
@@ -52,25 +52,34 @@ assert.match(shutdown, /workspaceFilesLiveWatcher\.closeAll\(\)/, "server shutdo
52
52
 
53
53
  // WS2 client-side contract assertions.
54
54
  const handleEvent = functionBody(app, "handleEvent");
55
+ const renderSignature = functionBody(app, "fileTreeRenderSignature");
56
+ const renderTree = functionBody(app, "renderFileTree");
55
57
  const loadDirectory = functionBody(app, "loadFileTreeDirectory");
58
+ const searchFiles = functionBody(app, "runFileTreeSearch");
56
59
  const liveRefresh = functionBody(app, "refreshFileTreeLive");
57
60
  const liveDirectories = functionBody(app, "refreshLoadedFileTreeDirectories");
58
61
 
59
62
  assert.match(handleEvent, /case "webui_workspace_files_changed":\s*if \(event\.tabId && event\.tabId !== activeTabId\) break;\s*refreshFileTreeLive\(tabContext\)\.catch/, "workspace file changes should refresh only the matching active tab");
60
- assert.match(loadDirectory, /const hadCachedEntries = fileTreeState\.entriesByPath\.has\(normalized\);[\s\S]*?if \(!hadCachedEntries\) setFileTreeStatus\(normalized \? `Loading \$\{normalized\}…` : "Loading workspace files…"\);/, "cached directories should preserve the current item-count status while background refreshes are in flight");
63
+ assert.match(renderSignature, /entriesByPath[\s\S]*fileTreeEntryRenderSignature[\s\S]*gitStatusByPath[\s\S]*selectedPath[\s\S]*searchEntries/, "file tree render identity should cover every state value that changes visible rows");
64
+ assert.doesNotMatch(renderSignature, /mtimeMs|size/, "content-only file metadata must not invalidate the visible file tree");
65
+ assert.match(renderTree, /const renderSignature = fileTreeRenderSignature\(\);\s*if \(renderSignature === fileTreeLastRenderSignature\) return;\s*fileTreeLastRenderSignature = renderSignature;[\s\S]*root\.replaceChildren\(\)/, "unchanged live snapshots should preserve the existing file-tree DOM");
66
+ assert.match(loadDirectory, /const hadCachedEntries = fileTreeState\.entriesByPath\.has\(normalized\);[\s\S]*?if \(!hadCachedEntries\) \{\s*setFileTreeStatus\(normalized \? `Loading \$\{normalized\}…` : "Loading workspace files…"\);\s*renderFileTree\(\);\s*\}/, "cached directories should preserve their rows without rendering transient loading state");
67
+ assert.match(loadDirectory, /renderResult && isCurrentTabContext\(tabContext\)/, "batched live refreshes should be able to defer rendering until all cached directories are updated");
61
68
  assert.match(loadDirectory, /fileTreeState\.entriesByPath\.set\(normalized, entries\);\s*if \(!normalized \|\| !hadCachedEntries\) \{\s*setFileTreeStatus\(fileTreeEntriesStatus\(entries,/, "root refreshes should publish the updated item count while cached child refreshes leave it stable");
69
+ assert.match(searchFiles, /if \(!background\) \{[\s\S]*fileTreeState\.searchEntries = \[\][\s\S]*renderFileTree\(\)/, "background search refreshes should preserve current results while the request is in flight");
62
70
 
63
- assert.match(liveRefresh, /fileTreeSearchQueryText\(\)[\s\S]*?await runFileTreeSearch\(\)[\s\S]*?await refreshLoadedFileTreeDirectories\(refreshContext\)/, "live refresh should rerun an active search or refresh loaded directories");
71
+ assert.match(liveRefresh, /fileTreeSearchQueryText\(\)[\s\S]*?await runFileTreeSearch\(\{ background: true \}\)[\s\S]*?await refreshLoadedFileTreeDirectories\(refreshContext\)/, "live refresh should update an active search in the background or refresh loaded directories");
64
72
  assert.match(liveRefresh, /if \(fileTreeLiveRefreshInProgress\) \{\s*fileTreeLiveRefreshPendingContext = tabContext;\s*return;\s*\}/, "events arriving during a refresh should retain the pending tab context");
65
73
  assert.match(liveRefresh, /refreshContext = fileTreeLiveRefreshPendingContext/, "a queued follow-up pass should replay the latest matching tab context");
66
74
  assert.match(liveRefresh, /pendingContext && isCurrentTabContext\(pendingContext\)[\s\S]*?retryContext && isCurrentTabContext\(retryContext\)/, "completion should prefer a pending current-tab event over a same-tab loading retry");
67
75
  assert.match(liveRefresh, /fileTreeLiveRefreshRetryTimer = setTimeout\([\s\S]*?refreshFileTreeLive\(nextContext\)/, "loading collisions should schedule a bounded follow-up refresh");
68
76
 
69
- assert.match(liveDirectories, /if \(fileTreeState\.loading\.has\(FILE_TREE_ROOT_PATH\)\) return true;\s*await loadFileTreeDirectory\(FILE_TREE_ROOT_PATH, \{ force: true \}\);[\s\S]*?collectDirectories\(FILE_TREE_ROOT_PATH\);[\s\S]*?for \(const path of cachedDirectories\)/, "the root directory should reload first, or request a retry when it is already loading");
77
+ assert.match(liveDirectories, /if \(fileTreeState\.loading\.has\(FILE_TREE_ROOT_PATH\)\) return true;\s*await loadFileTreeDirectory\(FILE_TREE_ROOT_PATH, \{ force: true, renderResult: false \}\);[\s\S]*?collectDirectories\(FILE_TREE_ROOT_PATH\);[\s\S]*?for \(const path of cachedDirectories\)/, "the root directory should reload first without an intermediate render, or request a retry when it is already loading");
70
78
  assert.match(liveDirectories, /\.sort\(\(a, b\) => a\.split\("\/"\)\.length - b\.split\("\/"\)\.length/, "loaded directories should refresh shallow-to-deep");
71
79
  assert.match(liveDirectories, /if \(!knownDirectories\.has\(path\)\) \{\s*clearFileTreeEntryCache\(path\);\s*continue;\s*\}/, "directories missing after reload should be pruned from caches and expansion");
72
80
  assert.match(liveDirectories, /if \(fileTreeState\.loading\.has\(path\)\) \{\s*skippedLoadingDirectory = true;\s*collectDirectories\(path\);\s*continue;\s*\}/, "already-loading directories should be preserved for a follow-up retry instead of being silently skipped or pruned");
73
- assert.match(liveDirectories, /await loadFileTreeDirectory\(path, \{ force: true \}\);[\s\S]*?collectDirectories\(path\)/, "only directories still present should be reloaded and kept");
81
+ assert.match(liveDirectories, /await loadFileTreeDirectory\(path, \{ force: true, renderResult: false \}\);[\s\S]*?collectDirectories\(path\)/, "only directories still present should be reloaded and kept without intermediate renders");
82
+ assert.match(liveDirectories, /for \(const path of cachedDirectories\)[\s\S]*renderFileTree\(\);\s*return skippedLoadingDirectory;/, "one live refresh pass should commit at most one batched tree render");
74
83
  assert.ok(!liveRefresh.includes("expanded.clear()") && !liveDirectories.includes("expanded.clear()"), "live refresh should preserve still-valid expanded directories");
75
84
 
76
85
  console.log("workspace-files-live-updates-static.test.mjs passed");
@@ -0,0 +1,288 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, mkdir, rm, symlink, utimes, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import {
6
+ WORKSPACE_SUMMARY_COMMAND_MAX_CHARS,
7
+ WORKSPACE_SUMMARY_MAX_LIVE_BYTES,
8
+ WORKSPACE_SUMMARY_PROTOCOL_VERSION,
9
+ WORKSPACE_SUMMARY_TOOL_MAX_CHARS,
10
+ canonicalizeWorkspaceCwd,
11
+ createLiveSummaryPayload,
12
+ discoverPersistedWorkspaceSummaries,
13
+ formatWorkspaceSummariesForCommand,
14
+ formatWorkspaceSummariesForTool,
15
+ mergeWorkspaceSessionSummaries,
16
+ normalizeLiveSummaryPayload,
17
+ workspaceCwdsEqual,
18
+ } from "../lib/workspace-session-summaries.mjs";
19
+ import { SESSION_SUMMARY_STATE_TYPE } from "../lib/session-summary-core.mjs";
20
+
21
+ function summaryState(sessionId, summaryMarkdown, {
22
+ title = "Workspace task",
23
+ generatedAt = "2026-08-05T12:00:00.000Z",
24
+ version = 1,
25
+ } = {}) {
26
+ return {
27
+ version,
28
+ source: {
29
+ sessionId,
30
+ leafId: "leaf",
31
+ fingerprint: "f".repeat(64),
32
+ entryCount: 4,
33
+ },
34
+ result: { title, summaryMarkdown },
35
+ generation: {
36
+ provider: "test-provider",
37
+ modelId: "test-model",
38
+ thinkingLevel: "low",
39
+ promptRevision: "session-summary-v1",
40
+ },
41
+ generatedAt,
42
+ settledTurnOrdinal: 2,
43
+ };
44
+ }
45
+
46
+ function sessionJsonl({ id, cwd, summary, name, headerVersion = 3, extraLines = [] }) {
47
+ const entries = [
48
+ { type: "session", version: headerVersion, id, timestamp: "2026-08-05T11:00:00.000Z", cwd },
49
+ { type: "message", id: "raw00001", parentId: null, timestamp: "2026-08-05T11:01:00.000Z", message: { role: "user", content: "RAW_TRANSCRIPT_SECRET ghp_rawtranscript1234567890 /home/private/.pi/agent/sessions/private.jsonl" } },
50
+ ...(name ? [{ type: "session_info", id: "name0001", parentId: "raw00001", timestamp: "2026-08-05T11:02:00.000Z", name }] : []),
51
+ ...extraLines,
52
+ { type: "custom", id: "sum00001", parentId: name ? "name0001" : "raw00001", timestamp: "2026-08-05T12:00:00.000Z", customType: SESSION_SUMMARY_STATE_TYPE, data: summary },
53
+ ];
54
+ return `${entries.map((entry) => typeof entry === "string" ? entry : JSON.stringify(entry)).join("\n")}\n`;
55
+ }
56
+
57
+ function livePayload(cwd, sessionId, summaryMarkdown, generatedAt = "2026-08-05T13:00:00.000Z") {
58
+ return {
59
+ version: WORKSPACE_SUMMARY_PROTOCOL_VERSION,
60
+ sessionId,
61
+ cwd: canonicalizeWorkspaceCwd(cwd),
62
+ title: `Title ${sessionId}`,
63
+ summaryMarkdown,
64
+ generatedAt,
65
+ sessionName: `Session ${sessionId}`,
66
+ };
67
+ }
68
+
69
+ const root = await mkdtemp(path.join(os.tmpdir(), "workspace-session-summaries-"));
70
+ try {
71
+ const workspace = path.join(root, "workspace");
72
+ const otherWorkspace = path.join(root, "other");
73
+ const sessionDir = path.join(root, "sessions");
74
+ await Promise.all([mkdir(workspace), mkdir(otherWorkspace), mkdir(sessionDir)]);
75
+
76
+ assert.equal(canonicalizeWorkspaceCwd(path.join(workspace, ".")), workspace);
77
+ assert.equal(workspaceCwdsEqual(workspace, path.join(workspace, "nested", "..")), true);
78
+ assert.equal(canonicalizeWorkspaceCwd("\0unsafe"), undefined);
79
+ if (process.platform !== "win32") {
80
+ const alias = path.join(root, "workspace-alias");
81
+ await symlink(workspace, alias, "dir");
82
+ assert.equal(workspaceCwdsEqual(workspace, alias), true, "symlink and real CWD should canonicalize equally");
83
+ }
84
+
85
+ const currentId = "current-session";
86
+ const sameId = "same-session";
87
+ const otherId = "other-session";
88
+ const invalidId = "invalid-session";
89
+ await writeFile(path.join(sessionDir, "current.jsonl"), sessionJsonl({
90
+ id: currentId,
91
+ cwd: workspace,
92
+ summary: summaryState(currentId, "Current persisted copy"),
93
+ }));
94
+ await writeFile(path.join(sessionDir, "same.jsonl"), sessionJsonl({
95
+ id: sameId,
96
+ cwd: workspace,
97
+ name: "Same workspace",
98
+ summary: summaryState(sameId, "Implement durable discovery."),
99
+ extraLines: ["{malformed-json", "x".repeat(30 * 1024)],
100
+ }));
101
+ await writeFile(path.join(sessionDir, "other.jsonl"), sessionJsonl({
102
+ id: otherId,
103
+ cwd: otherWorkspace,
104
+ summary: summaryState(otherId, "Must not cross CWD boundaries."),
105
+ }));
106
+ await writeFile(path.join(sessionDir, "invalid-version.jsonl"), sessionJsonl({
107
+ id: invalidId,
108
+ cwd: workspace,
109
+ headerVersion: 2,
110
+ summary: summaryState(invalidId, "Must not migrate or consume old formats."),
111
+ }));
112
+ await writeFile(path.join(sessionDir, "wrong-state-session.jsonl"), sessionJsonl({
113
+ id: "header-session",
114
+ cwd: workspace,
115
+ summary: summaryState("forged-session", "Mismatched state identity."),
116
+ }));
117
+
118
+ const now = new Date("2026-08-05T14:00:00.000Z");
119
+ await utimes(path.join(sessionDir, "same.jsonl"), now, now);
120
+ const discovered = await discoverPersistedWorkspaceSummaries({ cwd: workspace, sessionDir, currentSessionId: currentId });
121
+ assert.deepEqual(discovered.map((entry) => entry.sessionId), [sameId]);
122
+ assert.equal(discovered[0].source, "persisted");
123
+ assert.equal(discovered[0].sessionName, "Same workspace");
124
+ assert.equal(Object.hasOwn(discovered[0], "sessionFile"), false);
125
+ assert.equal(JSON.stringify(discovered).includes("RAW_TRANSCRIPT_SECRET"), false);
126
+ assert.equal(JSON.stringify(discovered).includes(sessionDir), false);
127
+
128
+ const oversizedFileId = "tail-session";
129
+ await writeFile(path.join(sessionDir, "tail.jsonl"), sessionJsonl({
130
+ id: oversizedFileId,
131
+ cwd: workspace,
132
+ summary: summaryState(oversizedFileId, "Found from a bounded tail read."),
133
+ extraLines: [{ type: "message", id: "large001", parentId: "raw00001", timestamp: "2026-08-05T11:30:00.000Z", message: { role: "user", content: "z".repeat(80_000) } }],
134
+ }));
135
+ const tailDiscovered = await discoverPersistedWorkspaceSummaries({
136
+ cwd: workspace,
137
+ sessionDir,
138
+ currentSessionId: currentId,
139
+ maxFileBytes: 32 * 1024,
140
+ });
141
+ assert.equal(tailDiscovered.some((entry) => entry.sessionId === oversizedFileId), true, "bounded tail should retain a recent summary after an oversized line");
142
+ const escapedSessionId = "escaped-session";
143
+ await writeFile(path.join(sessionDir, "escaped.jsonl"), sessionJsonl({
144
+ id: escapedSessionId,
145
+ cwd: workspace,
146
+ summary: summaryState(escapedSessionId, "\\".repeat(16_000)),
147
+ }));
148
+ const escapedDiscovered = await discoverPersistedWorkspaceSummaries({ cwd: workspace, sessionDir, currentSessionId: currentId });
149
+ assert.equal(escapedDiscovered.some((entry) => entry.sessionId === escapedSessionId), true, "valid decoded summaries remain discoverable when JSON escaping expands the custom-entry line");
150
+
151
+ const currentState = summaryState(currentId, "Current work summary.");
152
+ const publication = createLiveSummaryPayload({ cwd: workspace, state: currentState, sessionName: "Current worker" });
153
+ assert.ok(publication);
154
+ assert.equal(Buffer.byteLength(JSON.stringify(publication)) <= WORKSPACE_SUMMARY_MAX_LIVE_BYTES, true);
155
+ assert.equal(normalizeLiveSummaryPayload(publication)?.sessionId, currentId);
156
+ const redactedPublication = createLiveSummaryPayload({
157
+ cwd: workspace,
158
+ state: summaryState(currentId, [
159
+ "Token ghp_abcdefghijklmnopqrstuvwxyz123456 at /home/private/.pi/agent/sessions/private.jsonl",
160
+ "Windows C:\\Users\\alice\\.pi\\agent\\sessions\\--repo--\\secret.jsonl",
161
+ "AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE",
162
+ "npm_auth_token=npm_abcdefghijklmnopqrstuvwxyz123456",
163
+ "-----BEGIN PRIVATE KEY-----\nprivate-material\n-----END PRIVATE KEY-----",
164
+ ].join("\n")),
165
+ sessionName: "authorization: secret-value",
166
+ });
167
+ const redactedPublicationText = JSON.stringify(redactedPublication);
168
+ for (const sensitive of ["ghp_abcdefghijklmnopqrstuvwxyz123456", "private.jsonl", "secret.jsonl", "AKIAIOSFODNN7EXAMPLE", "npm_abcdefghijklmnopqrstuvwxyz123456", "private-material", "secret-value"]) {
169
+ assert.equal(redactedPublicationText.includes(sensitive), false, `live publication redacts ${sensitive} before transport`);
170
+ }
171
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, transcript: "private" }), undefined, "unknown live fields should fail closed");
172
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, version: 2 }), undefined);
173
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, cwd: `${otherWorkspace}/nested/..` }), undefined, "non-canonical live CWD should fail");
174
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, summaryMarkdown: "x".repeat(13 * 1024) }), undefined);
175
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, generatedAt: "not-a-date" }), undefined);
176
+ assert.equal(normalizeLiveSummaryPayload({ ...publication, sessionId: "a\tb" }), undefined, "control characters in identifiers fail closed instead of being normalized");
177
+ assert.equal(createLiveSummaryPayload({ cwd: workspace, state: summaryState(currentId, "x".repeat(16 * 1024)) }).summaryMarkdown.length <= 12 * 1024, true);
178
+ assert.equal(createLiveSummaryPayload({
179
+ cwd: path.join(root, "w".repeat(3900)),
180
+ state: summaryState(currentId, "x".repeat(16 * 1024)),
181
+ }), undefined, "aggregate live payloads above the 15 KiB transport envelope fail closed");
182
+
183
+ const liveSame = livePayload(workspace, sameId, "Newer live copy.");
184
+ const liveDisconnected = livePayload(workspace, "disconnected", "Disconnected and stale.");
185
+ const liveCrossCwd = livePayload(otherWorkspace, "cross-cwd", "Wrong workspace.");
186
+ const liveSelf = livePayload(workspace, "self-live", "Self sender.");
187
+ const snapshot = mergeWorkspaceSessionSummaries({
188
+ cwd: workspace,
189
+ currentSessionId: currentId,
190
+ currentState,
191
+ currentSessionName: "Current worker",
192
+ selfSenderId: "sender-self",
193
+ liveAvailable: true,
194
+ connectedSessions: [
195
+ { senderId: "sender-live", cwd: workspace },
196
+ { senderId: "sender-cross", cwd: otherWorkspace },
197
+ { senderId: "sender-self", cwd: workspace },
198
+ ],
199
+ livePeers: [
200
+ { senderId: "sender-live", payload: liveSame, receivedAt: "2026-08-05T13:01:00.000Z" },
201
+ { senderId: "sender-gone", payload: liveDisconnected },
202
+ { senderId: "sender-cross", payload: liveCrossCwd },
203
+ { senderId: "sender-self", payload: liveSelf },
204
+ ],
205
+ persisted: [
206
+ ...discovered,
207
+ { sessionId: "persisted-new", title: "Persisted", summaryMarkdown: "Historical work.", generatedAt: "2026-08-05T14:00:00.000Z", modifiedAt: "2026-08-05T14:00:00.000Z" },
208
+ { sessionId: "persisted-old", title: "Persisted", summaryMarkdown: "Older historical work.", generatedAt: "2026-08-04T14:00:00.000Z", modifiedAt: "2026-08-04T14:00:00.000Z" },
209
+ ],
210
+ });
211
+ assert.deepEqual(snapshot.entries.map((entry) => [entry.sessionId, entry.source]), [
212
+ [currentId, "current"],
213
+ [sameId, "live"],
214
+ ["persisted-new", "persisted"],
215
+ ["persisted-old", "persisted"],
216
+ ]);
217
+ assert.deepEqual(snapshot.counts, { current: 1, live: 1, persisted: 2, peers: 3 });
218
+ assert.equal(snapshot.entries.some((entry) => entry.sessionId === "disconnected"), false);
219
+ assert.equal(snapshot.entries.some((entry) => entry.sessionId === "cross-cwd"), false);
220
+ const claimedIdCollision = mergeWorkspaceSessionSummaries({
221
+ cwd: workspace,
222
+ liveAvailable: true,
223
+ connectedSessions: [{ id: "sender-a", cwd: workspace }, { id: "sender-b", cwd: workspace }],
224
+ livePeers: [
225
+ { senderId: "sender-a", payload: livePayload(workspace, "claimed", "Sender A") },
226
+ { senderId: "sender-b", payload: livePayload(workspace, "claimed", "Sender B") },
227
+ ],
228
+ });
229
+ assert.equal(claimedIdCollision.counts.live, 2, "authoritative live senders are not collapsed by a payload-declared Pi session ID");
230
+ assert.deepEqual(new Set(claimedIdCollision.entries.map((entry) => entry.senderId)), new Set(["sender-a", "sender-b"]));
231
+
232
+ const fallback = mergeWorkspaceSessionSummaries({
233
+ cwd: workspace,
234
+ currentSessionId: currentId,
235
+ currentState,
236
+ liveAvailable: false,
237
+ connectedSessions: [{ senderId: "sender-live", cwd: workspace }],
238
+ livePeers: [{ senderId: "sender-live", payload: liveSame }],
239
+ persisted: discovered,
240
+ });
241
+ assert.equal(fallback.entries.find((entry) => entry.sessionId === sameId)?.source, "persisted");
242
+ assert.equal(fallback.liveAvailable, false);
243
+
244
+ const privateSnapshot = mergeWorkspaceSessionSummaries({
245
+ cwd: workspace,
246
+ currentSessionId: currentId,
247
+ currentState: summaryState(currentId, [
248
+ "Safe goal.",
249
+ "/home/private/.pi/agent/sessions/--private--/secret.jsonl",
250
+ "authorization: BearerValueThatMustNotAppear",
251
+ "ghp_abcdefghijklmnopqrstuvwxyz123456",
252
+ ].join("\n")),
253
+ liveAvailable: false,
254
+ });
255
+ const toolText = formatWorkspaceSummariesForTool(privateSnapshot);
256
+ const commandText = formatWorkspaceSummariesForCommand(privateSnapshot);
257
+ for (const text of [toolText, commandText]) {
258
+ assert.equal(text.includes("secret.jsonl"), false);
259
+ assert.equal(text.includes("BearerValueThatMustNotAppear"), false);
260
+ assert.equal(text.includes("ghp_abcdefghijklmnopqrstuvwxyz123456"), false);
261
+ assert.match(text, /reference-only/i);
262
+ assert.match(text, /intercom/i);
263
+ }
264
+ assert.equal(toolText.length <= WORKSPACE_SUMMARY_TOOL_MAX_CHARS, true);
265
+ assert.equal(commandText.length <= WORKSPACE_SUMMARY_COMMAND_MAX_CHARS, true);
266
+
267
+ const manyPersisted = Array.from({ length: 40 }, (_, index) => ({
268
+ sessionId: `bounded-${String(index).padStart(2, "0")}`,
269
+ title: `Bounded ${index}`,
270
+ summaryMarkdown: "content ".repeat(1000),
271
+ generatedAt: new Date(Date.UTC(2026, 7, 5, 10, index)).toISOString(),
272
+ modifiedAt: new Date(Date.UTC(2026, 7, 5, 10, index)).toISOString(),
273
+ }));
274
+ const boundedSnapshot = mergeWorkspaceSessionSummaries({ cwd: workspace, persisted: manyPersisted, maxEntries: 3 });
275
+ assert.deepEqual(boundedSnapshot.entries.map((entry) => entry.sessionId), ["bounded-39", "bounded-38", "bounded-37"]);
276
+ const boundedToolText = formatWorkspaceSummariesForTool(boundedSnapshot, { maxChars: 1000 });
277
+ const boundedCommandText = formatWorkspaceSummariesForCommand(boundedSnapshot, { maxChars: 700 });
278
+ assert.equal(boundedToolText.length <= 1000, true);
279
+ assert.equal(boundedCommandText.length <= 700, true);
280
+ for (const text of [boundedToolText, boundedCommandText]) {
281
+ assert.match(text, /untrusted|reference-only/i, "safety framing survives aggregate truncation");
282
+ assert.match(text, /intercom/i, "coordination guidance survives aggregate truncation");
283
+ }
284
+
285
+ console.log("workspace-session-summaries tests passed");
286
+ } finally {
287
+ await rm(root, { recursive: true, force: true });
288
+ }
@@ -9,11 +9,24 @@ import {
9
9
  subagentLaunchSlotScopeEntry,
10
10
  } from "./lib/subagent-launch-slots.mjs";
11
11
  import { SUBAGENT_GATE_UPDATE_EVENT } from "./lib/subagent-gate.mjs";
12
+ import {
13
+ applySupportedSamplingParameters,
14
+ BUILTIN_SAMPLING_APIS,
15
+ filterSupportedSamplingParameters,
16
+ resolveSamplingParameterCapabilities,
17
+ } from "./lib/sampling-parameter-capabilities.mjs";
18
+ import {
19
+ SamplingParameterValidationError,
20
+ validateSamplingParameterObject,
21
+ } from "./public/sampling-parameter-controls.mjs";
12
22
 
13
23
  const HELPER_COMMAND = "webui-helper";
14
24
  const RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
15
25
  const TOOLS_CONFIG_TYPE = "webui-tools-config";
16
26
  const SKILLS_CONFIG_TYPE = "webui-skills-config";
27
+ const SAMPLING_CONFIG_TYPE = "webui-session-sampling-params-v1";
28
+ const SAMPLING_MAX_KEYS = 128;
29
+ const SAMPLING_MAX_BYTES = 16 * 1024;
17
30
  const APP_RUNNER_CONTEXT_TYPE = "webui-app-runner-output";
18
31
  const RETAINED_SUBAGENT_RUNS_TYPE = "webui-subagent-retained-runs-v1";
19
32
  const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
@@ -135,6 +148,30 @@ function lastBranchConfig(ctx, customType) {
135
148
  return found;
136
149
  }
137
150
 
151
+ function isPlainObject(value) {
152
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
153
+ const prototype = Object.getPrototypeOf(value);
154
+ return prototype === Object.prototype || prototype === null;
155
+ }
156
+
157
+ function normalizeSamplingParams(value) {
158
+ if (!isPlainObject(value)) throw new Error("Sampling parameters must be a JSON object");
159
+ const keys = Object.keys(value);
160
+ if (keys.length > SAMPLING_MAX_KEYS) throw new Error(`Sampling parameters may contain at most ${SAMPLING_MAX_KEYS} top-level keys`);
161
+ let serialized;
162
+ try {
163
+ serialized = JSON.stringify(value);
164
+ } catch {
165
+ throw new Error("Sampling parameters must contain only JSON-compatible values");
166
+ }
167
+ if (Buffer.byteLength(serialized, "utf8") > SAMPLING_MAX_BYTES) {
168
+ throw new Error(`Sampling parameters must be at most ${SAMPLING_MAX_BYTES} bytes`);
169
+ }
170
+ const normalized = JSON.parse(serialized);
171
+ if (!isPlainObject(normalized)) throw new Error("Sampling parameters must be a JSON object");
172
+ return normalized;
173
+ }
174
+
138
175
  function normalizeNameList(value) {
139
176
  if (!Array.isArray(value)) return [];
140
177
  const names = [];
@@ -797,6 +834,7 @@ export default function webuiRpcHelper(pi) {
797
834
  let enabledTools = new Set();
798
835
  let disabledSkills = new Set();
799
836
  let inheritedEnabledSkills = null;
837
+ let sessionSamplingParams = {};
800
838
  let subagentLaunchSlotGuidance = "";
801
839
  let subagentContext = null;
802
840
  let subagentBridgeAvailable = false;
@@ -1408,6 +1446,72 @@ export default function webuiRpcHelper(pi) {
1408
1446
  return pi.getAllTools().map((tool) => tool.name);
1409
1447
  }
1410
1448
 
1449
+ function restoreSamplingParamsFromBranch(ctx) {
1450
+ const saved = lastBranchConfig(ctx, SAMPLING_CONFIG_TYPE);
1451
+ try {
1452
+ sessionSamplingParams = saved?.version === 1 ? normalizeSamplingParams(saved.samplingParams) : {};
1453
+ } catch {
1454
+ sessionSamplingParams = {};
1455
+ }
1456
+ }
1457
+
1458
+ function persistSamplingParams() {
1459
+ pi.appendEntry(SAMPLING_CONFIG_TYPE, { version: 1, samplingParams: sessionSamplingParams });
1460
+ }
1461
+
1462
+ function samplingState(ctx) {
1463
+ const model = ctx.model;
1464
+ const api = typeof model?.api === "string" ? model.api : null;
1465
+ const parameters = resolveSamplingParameterCapabilities(model, { thinkingLevel: ctx.thinkingLevel });
1466
+ const supported = Object.values(parameters).some((capability) => capability.supported);
1467
+ const defaults = isPlainObject(model?.samplingParams) ? { ...model.samplingParams } : {};
1468
+ const session = { ...sessionSamplingParams };
1469
+ return {
1470
+ session,
1471
+ defaults,
1472
+ effective: {
1473
+ ...filterSupportedSamplingParameters(defaults, parameters),
1474
+ ...filterSupportedSamplingParameters(session, parameters),
1475
+ },
1476
+ support: {
1477
+ supported,
1478
+ api,
1479
+ model: model ? {
1480
+ provider: typeof model.provider === "string" ? model.provider : null,
1481
+ id: typeof model.id === "string" ? model.id : null,
1482
+ name: typeof model.name === "string" ? model.name : null,
1483
+ } : null,
1484
+ parameters,
1485
+ compatibleApis: [...BUILTIN_SAMPLING_APIS],
1486
+ message: supported
1487
+ ? "Session sampling parameters apply to subsequent provider requests."
1488
+ : api
1489
+ ? `Session sampling parameters are stored but not applied to ${api}.`
1490
+ : "Session sampling parameters are stored but no active model is available.",
1491
+ },
1492
+ };
1493
+ }
1494
+
1495
+ function setSamplingParams(ctx, payload) {
1496
+ const normalized = normalizeSamplingParams(payload?.samplingParams);
1497
+ const validation = validateSamplingParameterObject(normalized);
1498
+ if (!validation.valid) {
1499
+ throw new SamplingParameterValidationError(
1500
+ `Invalid sampling parameters: ${Object.values(validation.errors).join(" ")}`,
1501
+ validation.errors,
1502
+ );
1503
+ }
1504
+ sessionSamplingParams = normalized;
1505
+ persistSamplingParams();
1506
+ return samplingState(ctx);
1507
+ }
1508
+
1509
+ function resetSamplingParams(ctx) {
1510
+ sessionSamplingParams = {};
1511
+ persistSamplingParams();
1512
+ return samplingState(ctx);
1513
+ }
1514
+
1411
1515
  async function readGlobalResourceDefaults() {
1412
1516
  try {
1413
1517
  return (await readWebuiSettings()).resourceDefaults;
@@ -1607,6 +1711,12 @@ export default function webuiRpcHelper(pi) {
1607
1711
  return skillState(ctx);
1608
1712
  case "skills-set":
1609
1713
  return setSkillState(ctx, payload);
1714
+ case "sampling-state":
1715
+ return samplingState(ctx);
1716
+ case "sampling-set":
1717
+ return setSamplingParams(ctx, payload);
1718
+ case "sampling-reset":
1719
+ return resetSamplingParams(ctx);
1610
1720
  case "app-runner-context":
1611
1721
  return transferAppRunnerContext(ctx, payload);
1612
1722
  case "subagent-output":
@@ -1643,6 +1753,7 @@ export default function webuiRpcHelper(pi) {
1643
1753
  const globalDefaults = await readGlobalResourceDefaults();
1644
1754
  restoreToolsFromBranch(ctx, globalDefaults);
1645
1755
  restoreSkillsFromBranch(ctx, globalDefaults);
1756
+ restoreSamplingParamsFromBranch(ctx);
1646
1757
  await loadSubagentLaunchSlotGuidance(ctx);
1647
1758
  subagentContext = ctx;
1648
1759
  subagentPollGeneration += 1;
@@ -1660,6 +1771,7 @@ export default function webuiRpcHelper(pi) {
1660
1771
  const globalDefaults = await readGlobalResourceDefaults();
1661
1772
  restoreToolsFromBranch(ctx, globalDefaults);
1662
1773
  restoreSkillsFromBranch(ctx, globalDefaults);
1774
+ restoreSamplingParamsFromBranch(ctx);
1663
1775
  subagentContext = ctx;
1664
1776
  foregroundSubagentRuns.clear();
1665
1777
  asyncSubagentRuns.clear();
@@ -1748,6 +1860,13 @@ export default function webuiRpcHelper(pi) {
1748
1860
  for (const unsubscribe of subagentEventUnsubscribers) unsubscribe();
1749
1861
  });
1750
1862
 
1863
+ pi.on("before_provider_request", (event, ctx) => {
1864
+ if (Object.keys(sessionSamplingParams).length === 0) return undefined;
1865
+ return applySupportedSamplingParameters(event.payload, ctx.model, sessionSamplingParams, {
1866
+ thinkingLevel: ctx.thinkingLevel,
1867
+ });
1868
+ });
1869
+
1751
1870
  pi.on("input", async (event, ctx) => {
1752
1871
  const match = String(event.text || "").trim().match(/^\/skill:([^\s]+)/i);
1753
1872
  if (!match) return { action: "continue" };