@firstpick/pi-package-webui 0.8.0 → 0.8.2

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 (63) hide show
  1. package/README.md +34 -5
  2. package/bin/pi-webui.mjs +606 -102
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/npm-command.mjs +81 -0
  5. package/lib/queue-mutation.mjs +6 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/workspace-files-live-watcher.mjs +138 -0
  8. package/package.json +8 -3
  9. package/public/app.js +4231 -376
  10. package/public/index.html +265 -52
  11. package/public/mobile-shell-state.mjs +166 -0
  12. package/public/service-worker.js +60 -13
  13. package/public/styles.css +1790 -383
  14. package/public/subagent-gate-visibility.mjs +16 -0
  15. package/public/subagent-launch-slot-state.mjs +16 -0
  16. package/public/transcript-renderer.mjs +433 -0
  17. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  18. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  19. package/tests/browser/interaction-continuity.spec.mjs +897 -0
  20. package/tests/browser/mobile-foundation.spec.mjs +363 -0
  21. package/tests/browser/optimistic-prompt.spec.mjs +130 -0
  22. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  23. package/tests/browser/stats-overlay.spec.mjs +265 -0
  24. package/tests/chat-scroll-intent-static.test.mjs +6 -1
  25. package/tests/codex-fast-mode-static.test.mjs +8 -5
  26. package/tests/compact-sections-static.test.mjs +20 -2
  27. package/tests/compaction-mutation-contract.test.mjs +18 -4
  28. package/tests/compaction-static.test.mjs +1 -0
  29. package/tests/completion-signal-contract.test.mjs +13 -2
  30. package/tests/component-update-api-static.test.mjs +67 -0
  31. package/tests/component-update-state.test.mjs +80 -0
  32. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  33. package/tests/fast-mode-client-static.test.mjs +7 -4
  34. package/tests/fixtures/fake-pi.mjs +305 -2
  35. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  36. package/tests/git-panel-gitignore-static.test.mjs +104 -0
  37. package/tests/http-endpoints-harness.test.mjs +228 -2
  38. package/tests/interaction-state-stability-static.test.mjs +271 -0
  39. package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
  40. package/tests/mobile-foundation-static.test.mjs +71 -0
  41. package/tests/mobile-phone-experience-static.test.mjs +65 -0
  42. package/tests/mobile-shell-state.test.mjs +69 -0
  43. package/tests/mobile-static.test.mjs +246 -39
  44. package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
  45. package/tests/native-parity-harness.test.mjs +2 -0
  46. package/tests/npm-command.test.mjs +64 -1
  47. package/tests/open-issue-wizard-static.test.mjs +2 -1
  48. package/tests/queue-edit-reorder-static.test.mjs +9 -1
  49. package/tests/queue-mutation-contract.test.mjs +22 -0
  50. package/tests/service-worker-lifecycle.test.mjs +120 -0
  51. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  52. package/tests/sse-backpressure-harness.test.mjs +137 -0
  53. package/tests/stats-dashboard-static.test.mjs +266 -0
  54. package/tests/streaming-ui-coupling.test.mjs +7 -1
  55. package/tests/subagent-gate-visibility.test.mjs +18 -2
  56. package/tests/subagent-launch-slot-state.test.mjs +32 -0
  57. package/tests/subagent-launch-slots-static.test.mjs +8 -2
  58. package/tests/subagents-helper.test.mjs +90 -0
  59. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  60. package/tests/update-commands.test.mjs +4 -0
  61. package/tests/workspace-files-live-updates-static.test.mjs +76 -0
  62. package/tests/workspace-files-live-watcher.test.mjs +95 -0
  63. package/webui-rpc-helper.mjs +175 -3
@@ -0,0 +1,76 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [server, watcher, app] = await Promise.all([
8
+ readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
9
+ readFile(join(root, "lib", "workspace-files-live-watcher.mjs"), "utf8"),
10
+ readFile(join(root, "public", "app.js"), "utf8"),
11
+ ]);
12
+
13
+ function functionBody(source, name) {
14
+ const syncStart = source.indexOf(`function ${name}(`);
15
+ const asyncStart = source.indexOf(`async function ${name}(`);
16
+ const start = syncStart === -1 ? asyncStart : asyncStart === -1 ? syncStart : Math.min(syncStart, asyncStart);
17
+ assert.notEqual(start, -1, `${name} should be defined`);
18
+ const nextSync = source.indexOf("\nfunction ", start + 1);
19
+ const nextAsync = source.indexOf("\nasync function ", start + 1);
20
+ const candidates = [nextSync, nextAsync].filter((index) => index !== -1);
21
+ return source.slice(start, candidates.length ? Math.min(...candidates) : source.length);
22
+ }
23
+
24
+ const createTab = functionBody(server, "createTab");
25
+ const hydrateManagedTabs = functionBody(server, "hydrateManagedTabs");
26
+ const updateTabCwd = functionBody(server, "performTabCwdUpdate");
27
+ const closeTab = functionBody(server, "closeTab");
28
+ const discardTab = functionBody(server, "discardTab");
29
+ const shutdown = functionBody(server, "shutdown");
30
+
31
+ assert.match(server, /import \{ createWorkspaceFilesLiveWatcher \} from "\.\.\/lib\/workspace-files-live-watcher\.mjs";/, "the dedicated workspace watcher should be imported");
32
+ assert.match(watcher, /watch\(root, \{ recursive: true, persistent: false \}/, "workspace watches should be recursive and non-persistent");
33
+ assert.match(watcher, /record\.tabIds = new Set\(record\.tabs\)/, "filesystem changes should snapshot affected tabs");
34
+ assert.match(watcher, /maximumWaitMs[\s\S]*remainingMs[\s\S]*Math\.min\(delayMs, remainingMs\)/, "continuous changes should be bounded by the maximum wait");
35
+ assert.match(watcher, /onChange\(\{ root, tabIds, changedAt:/, "watcher notifications should carry tab ids, root, and time");
36
+ assert.match(watcher, /record\.watcher\.on\?\.\("error", \(error\) => failRoot\(root, error\)\)/, "runtime watcher errors should be non-fatal");
37
+ assert.match(watcher, /catch \(error\) \{[\s\S]*?roots\.delete\(root\);[\s\S]*?reportError\(root, error\);[\s\S]*?return null;/, "watcher startup errors should be non-fatal");
38
+ assert.match(watcher, /if \(!record\.tabs\.size\) closeRoot/, "the last workspace subscriber should release its watcher");
39
+ assert.match(watcher, /function closeAll\(\)[\s\S]*closeRoot\(root\)/, "closeAll should release every workspace watcher");
40
+
41
+ assert.match(server, /const workspaceFilesLiveWatcher = createWorkspaceFilesLiveWatcher\(\{[\s\S]*?onChange: \(\{ root, tabIds, changedAt \}\)[\s\S]*?for \(const tabId of tabIds\)[\s\S]*?workspaceFilesLiveWatcher\.subscribedRootForTab\(tab\.id\) !== root[\s\S]*?broadcastTabEvent\(tab, \{ type: "webui_workspace_files_changed", tabId: tab\.id, root, changedAt \}\)/, "workspace changes should emit only to still-subscribed affected tabs with the approved event shape");
42
+ assert.match(server, /webui_workspace_files_watch_error[\s\S]*sanitizeError\(error\)/, "workspace watcher diagnostics should sanitize errors");
43
+
44
+ assert.match(createTab, /tabs\.set\(id, tab\);\s*workspaceFilesLiveWatcher\.subscribe\(tab\.id, tab\.cwd\)/, "new tabs should subscribe their workspace");
45
+ assert.match(createTab, /gitLiveWatcher\.unsubscribe\(id\);\s*workspaceFilesLiveWatcher\.unsubscribe\(id\);\s*tabs\.delete\(id\);/, "failed tab creation should release the workspace watcher");
46
+ assert.match(hydrateManagedTabs, /tabs\.set\(tab\.id, tab\);\s*workspaceFilesLiveWatcher\.subscribe\(tab\.id, tab\.cwd\);/, "hydrated tabs should subscribe their workspace");
47
+ assert.match(hydrateManagedTabs, /tab\.rpc\.dispose\?\.\(\);\s*workspaceFilesLiveWatcher\.unsubscribe\(tab\.id\);\s*tabs\.delete\(tab\.id\);/, "failed hydration should release workspace subscriptions");
48
+ assert.match(updateTabCwd, /tab\.cwd = nextCwd;[\s\S]*?workspaceFilesLiveWatcher\.unsubscribe\(tab\.id\);\s*workspaceFilesLiveWatcher\.subscribe\(tab\.id, tab\.cwd\);/, "cwd changes should replace workspace subscriptions");
49
+ assert.match(closeTab, /workspaceFilesLiveWatcher\.unsubscribe\(tab\.id\)/, "tab closure should release workspace subscriptions");
50
+ assert.match(discardTab, /workspaceFilesLiveWatcher\.unsubscribe\(tab\.id\)/, "discarded tabs should release workspace subscriptions");
51
+ assert.match(shutdown, /workspaceFilesLiveWatcher\.closeAll\(\)/, "server shutdown should release all workspace watchers");
52
+
53
+ // WS2 client-side contract assertions.
54
+ const handleEvent = functionBody(app, "handleEvent");
55
+ const loadDirectory = functionBody(app, "loadFileTreeDirectory");
56
+ const liveRefresh = functionBody(app, "refreshFileTreeLive");
57
+ const liveDirectories = functionBody(app, "refreshLoadedFileTreeDirectories");
58
+
59
+ 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");
61
+ 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");
62
+
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");
64
+ assert.match(liveRefresh, /if \(fileTreeLiveRefreshInProgress\) \{\s*fileTreeLiveRefreshPendingContext = tabContext;\s*return;\s*\}/, "events arriving during a refresh should retain the pending tab context");
65
+ assert.match(liveRefresh, /refreshContext = fileTreeLiveRefreshPendingContext/, "a queued follow-up pass should replay the latest matching tab context");
66
+ 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
+ assert.match(liveRefresh, /fileTreeLiveRefreshRetryTimer = setTimeout\([\s\S]*?refreshFileTreeLive\(nextContext\)/, "loading collisions should schedule a bounded follow-up refresh");
68
+
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");
70
+ assert.match(liveDirectories, /\.sort\(\(a, b\) => a\.split\("\/"\)\.length - b\.split\("\/"\)\.length/, "loaded directories should refresh shallow-to-deep");
71
+ 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
+ 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");
74
+ assert.ok(!liveRefresh.includes("expanded.clear()") && !liveDirectories.includes("expanded.clear()"), "live refresh should preserve still-valid expanded directories");
75
+
76
+ console.log("workspace-files-live-updates-static.test.mjs passed");
@@ -0,0 +1,95 @@
1
+ import assert from "node:assert/strict";
2
+ import { EventEmitter } from "node:events";
3
+ import path from "node:path";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ import { createWorkspaceFilesLiveWatcher } from "../lib/workspace-files-live-watcher.mjs";
6
+
7
+ const created = [];
8
+ const changes = [];
9
+ const errors = [];
10
+
11
+ function fakeWatch(root, options, listener) {
12
+ const watcher = new EventEmitter();
13
+ watcher.root = root;
14
+ watcher.options = options;
15
+ watcher.listener = listener;
16
+ watcher.closed = false;
17
+ watcher.close = () => {
18
+ watcher.closed = true;
19
+ };
20
+ created.push(watcher);
21
+ return watcher;
22
+ }
23
+
24
+ const manager = createWorkspaceFilesLiveWatcher({
25
+ watch: fakeWatch,
26
+ debounceMs: 20,
27
+ onChange: (event) => changes.push(event),
28
+ onError: (event) => errors.push(event),
29
+ });
30
+
31
+ const firstRoot = path.resolve("/tmp/pi-webui-workspace-live-one");
32
+ const secondRoot = path.resolve("/tmp/pi-webui-workspace-live-two");
33
+
34
+ assert.equal(manager.subscribe("tab-a", firstRoot), true);
35
+ assert.equal(manager.subscribe("tab-b", firstRoot), true);
36
+ assert.equal(created.length, 1, "tabs in one workspace should share one recursive watcher");
37
+ assert.deepEqual(created[0].options, { recursive: true, persistent: false });
38
+ assert.equal(manager.watchedRootCount(), 1);
39
+
40
+ created[0].listener("change", "file.txt");
41
+ created[0].listener("rename", "created.txt");
42
+ created[0].listener("change", "file.txt");
43
+ await delay(50);
44
+ assert.equal(changes.length, 1, "one filesystem burst should emit one debounced invalidation");
45
+ assert.equal(changes[0].root, firstRoot);
46
+ assert.deepEqual(changes[0].tabIds, ["tab-a", "tab-b"], "invalidations should snapshot the affected tab ids");
47
+ assert.match(changes[0].changedAt, /^\d{4}-\d{2}-\d{2}T/);
48
+
49
+ const maxWaitChanges = [];
50
+ const maxWaitManager = createWorkspaceFilesLiveWatcher({
51
+ watch: fakeWatch,
52
+ debounceMs: 80,
53
+ maxWaitMs: 40,
54
+ onChange: (event) => maxWaitChanges.push(event),
55
+ });
56
+ assert.equal(maxWaitManager.subscribe("tab-max-wait", firstRoot), true);
57
+ const maxWaitWatcher = created.at(-1);
58
+ maxWaitWatcher.listener("change", "continuous.txt");
59
+ await delay(25);
60
+ maxWaitWatcher.listener("change", "continuous.txt");
61
+ await delay(30);
62
+ assert.equal(maxWaitChanges.length, 1, "sustained writes should emit by the bounded maximum wait");
63
+ assert.deepEqual(maxWaitChanges[0].tabIds, ["tab-max-wait"]);
64
+ maxWaitManager.closeAll();
65
+
66
+ assert.equal(manager.unsubscribe("tab-a"), true);
67
+ assert.equal(created[0].closed, false, "the shared watcher should remain while another tab subscribes");
68
+ assert.equal(manager.subscribe("tab-b", secondRoot), true, "moving a tab should subscribe its new workspace");
69
+ assert.equal(created[0].closed, true, "moving the last subscriber should close the old watcher");
70
+ assert.equal(created.length, 3);
71
+ assert.equal(manager.subscribedRootForTab("tab-b"), secondRoot);
72
+
73
+ created.at(-1).emit("error", new Error("fixture watcher failed"));
74
+ assert.equal(errors.length, 1, "runtime watcher failures should be reported once");
75
+ assert.equal(errors[0].root, secondRoot);
76
+ assert.equal(manager.watchedRootCount(), 0, "a failed watcher should be removed");
77
+ assert.equal(manager.subscribedRootForTab("tab-b"), "", "failed roots should release tab subscriptions for later retry");
78
+
79
+ const throwingManager = createWorkspaceFilesLiveWatcher({
80
+ watch: () => {
81
+ throw new Error("watch unsupported");
82
+ },
83
+ onError: (event) => errors.push(event),
84
+ });
85
+ assert.equal(throwingManager.subscribe("tab-c", firstRoot), false, "synchronous watcher startup errors should be non-fatal");
86
+ assert.match(errors.at(-1)?.error?.message || "", /watch unsupported/);
87
+
88
+ assert.equal(manager.subscribe("tab-d", firstRoot), true);
89
+ assert.equal(manager.subscribe("tab-e", secondRoot), true);
90
+ const latestWatchers = created.slice(-2);
91
+ manager.closeAll();
92
+ assert.equal(manager.watchedRootCount(), 0);
93
+ assert.equal(latestWatchers.every((watcher) => watcher.closed), true, "closeAll should release every watcher");
94
+
95
+ console.log("workspace-files-live-watcher.test.mjs passed");
@@ -43,6 +43,13 @@ const FINISHED_SUBAGENT_RUN_LIMIT = 16;
43
43
  const SUBAGENT_OUTPUT_LINE_LIMIT = 120;
44
44
  const SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
45
45
  const SUBAGENT_TRANSCRIPT_TAIL_BYTES = 512 * 1024;
46
+ const SUBAGENT_TELEMETRY_SCAN_BYTES = 2 * 1024 * 1024;
47
+ const SUBAGENT_TELEMETRY_ENTRY_LIMIT = 4096;
48
+ const SUBAGENT_TELEMETRY_TOKEN_LIMIT = 1_000_000_000;
49
+ const SUBAGENT_TELEMETRY_CONTEXT_WINDOW_LIMIT = 16_000_000;
50
+ const SUBAGENT_TELEMETRY_RESPONSE_DURATION_MS = 15 * 60 * 1000;
51
+ const SUBAGENT_TELEMETRY_SPEED_LIMIT = 1_000_000;
52
+ const STATS_INITIAL_PROMPT_ESTIMATE_TYPE = "stats_initial_prompt_estimate";
46
53
 
47
54
  const ACTIVE_COMMAND_SESSION_KEY = Symbol.for("pi.webui.helper.activeCommandSession");
48
55
 
@@ -497,6 +504,156 @@ function subagentTranscriptOutput(sessionFile) {
497
504
  }
498
505
  }
499
506
 
507
+ function subagentTelemetryNumber(value, limit = SUBAGENT_TELEMETRY_TOKEN_LIMIT) {
508
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= limit ? value : null;
509
+ }
510
+
511
+ function subagentTelemetryTimestamp(value) {
512
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
513
+ if (typeof value !== "string" || value.length > 128) return null;
514
+ const timestamp = Date.parse(value);
515
+ return Number.isFinite(timestamp) && timestamp > 0 ? timestamp : null;
516
+ }
517
+
518
+ function subagentAssistantModel(message) {
519
+ const model = subagentModel(message?.responseModel || message?.model);
520
+ if (!model) return "";
521
+ const provider = subagentText(message?.provider, 80);
522
+ return provider && !model.startsWith(`${provider}/`) ? subagentModel(`${provider}/${model}`) : model;
523
+ }
524
+
525
+ function subagentContextWindow(model, context) {
526
+ const effectiveModel = subagentModel(model);
527
+ const match = effectiveModel.match(/^([^/]+)\/(.+)$/);
528
+ if (!match || typeof context?.modelRegistry?.getAvailable !== "function") return null;
529
+ const provider = match[1];
530
+ const modelId = match[2].replace(/:(off|minimal|low|medium|high|xhigh|max)$/i, "");
531
+ try {
532
+ const available = context.modelRegistry.getAvailable();
533
+ const entry = (Array.isArray(available) ? available : []).find((candidate) => candidate?.provider === provider && candidate?.id === modelId);
534
+ return subagentTelemetryNumber(entry?.contextWindow, SUBAGENT_TELEMETRY_CONTEXT_WINDOW_LIMIT);
535
+ } catch {
536
+ return null;
537
+ }
538
+ }
539
+
540
+ function subagentEmptyTelemetry({ model, effort, context } = {}) {
541
+ const effectiveModel = subagentModel(model) || null;
542
+ return {
543
+ promptInjectionTokens: null,
544
+ inputTokens: null,
545
+ outputTokens: null,
546
+ tokenSpeed: null,
547
+ contextTokens: null,
548
+ contextWindow: subagentContextWindow(effectiveModel, context),
549
+ model: effectiveModel,
550
+ effort: subagentThinking(effort) || subagentThinkingFromModel(effectiveModel) || null,
551
+ };
552
+ }
553
+
554
+ function subagentSessionTelemetry(sessionFile, { model, effort, context } = {}) {
555
+ const empty = subagentEmptyTelemetry({ model, effort, context });
556
+ const file = String(sessionFile || "");
557
+ if (!file || !path.isAbsolute(file) || path.extname(file) !== ".jsonl") return empty;
558
+
559
+ let fd;
560
+ try {
561
+ fd = openSync(file, "r");
562
+ const size = fstatSync(fd).size;
563
+ if (size <= 0) return empty;
564
+ const length = Math.min(size, SUBAGENT_TELEMETRY_SCAN_BYTES);
565
+ const start = size - length;
566
+ const buffer = Buffer.alloc(length);
567
+ const bytesRead = readSync(fd, buffer, 0, length, start);
568
+ const rawLines = buffer.subarray(0, bytesRead).toString("utf8").split(/\r?\n/);
569
+ if (start > 0) rawLines.shift();
570
+
571
+ let promptInjectionTokens = null;
572
+ let inputTokens = 0;
573
+ let outputTokens = 0;
574
+ let inputSeen = false;
575
+ let outputSeen = false;
576
+ let inputOverflow = false;
577
+ let outputOverflow = false;
578
+ let speedOutputTokens = 0;
579
+ let speedDurationMs = 0;
580
+ let speedOverflow = false;
581
+ let contextTokens = null;
582
+ let latestAssistantModel = "";
583
+
584
+ for (const rawLine of rawLines.slice(-SUBAGENT_TELEMETRY_ENTRY_LIMIT)) {
585
+ if (!rawLine.trim()) continue;
586
+ let entry;
587
+ try {
588
+ entry = JSON.parse(rawLine);
589
+ } catch {
590
+ continue;
591
+ }
592
+ if (entry?.type === "custom" && entry?.customType === STATS_INITIAL_PROMPT_ESTIMATE_TYPE) {
593
+ const value = subagentTelemetryNumber(entry?.data?.actualInjectedTokens);
594
+ if (value !== null) promptInjectionTokens = value;
595
+ continue;
596
+ }
597
+
598
+ const message = entry?.type === "message" ? entry.message : entry?.message?.role ? entry.message : null;
599
+ if (message?.role !== "assistant") continue;
600
+ latestAssistantModel = subagentAssistantModel(message) || latestAssistantModel;
601
+ const usage = message.usage && typeof message.usage === "object" ? message.usage : null;
602
+ if (!usage) continue;
603
+ const input = subagentTelemetryNumber(usage.input);
604
+ const output = subagentTelemetryNumber(usage.output);
605
+ if (input !== null) {
606
+ inputSeen = true;
607
+ if (inputTokens > SUBAGENT_TELEMETRY_TOKEN_LIMIT - input) inputOverflow = true;
608
+ else inputTokens += input;
609
+ const cacheRead = subagentTelemetryNumber(usage.cacheRead);
610
+ const cacheWrite = subagentTelemetryNumber(usage.cacheWrite);
611
+ contextTokens = cacheRead !== null && cacheWrite !== null && input <= SUBAGENT_TELEMETRY_TOKEN_LIMIT - cacheRead - cacheWrite
612
+ ? input + cacheRead + cacheWrite
613
+ : input;
614
+ } else {
615
+ contextTokens = null;
616
+ }
617
+ if (output !== null) {
618
+ outputSeen = true;
619
+ if (outputTokens > SUBAGENT_TELEMETRY_TOKEN_LIMIT - output) outputOverflow = true;
620
+ else outputTokens += output;
621
+ const startedAt = subagentTelemetryTimestamp(message.timestamp);
622
+ const completedAt = subagentTelemetryTimestamp(entry.timestamp);
623
+ const durationMs = startedAt !== null && completedAt !== null ? completedAt - startedAt : 0;
624
+ if (output > 0 && durationMs > 0 && durationMs <= SUBAGENT_TELEMETRY_RESPONSE_DURATION_MS) {
625
+ if (speedOutputTokens > SUBAGENT_TELEMETRY_TOKEN_LIMIT - output || speedDurationMs > SUBAGENT_TELEMETRY_RESPONSE_DURATION_MS * SUBAGENT_TELEMETRY_ENTRY_LIMIT - durationMs) speedOverflow = true;
626
+ else {
627
+ speedOutputTokens += output;
628
+ speedDurationMs += durationMs;
629
+ }
630
+ }
631
+ }
632
+ }
633
+
634
+ const effectiveModel = subagentModel(model) || latestAssistantModel || null;
635
+ const tokenSpeed = !speedOverflow && speedOutputTokens > 0 && speedDurationMs > 0
636
+ ? subagentTelemetryNumber((speedOutputTokens * 1000) / speedDurationMs, SUBAGENT_TELEMETRY_SPEED_LIMIT)
637
+ : null;
638
+ return {
639
+ promptInjectionTokens,
640
+ inputTokens: inputSeen && !inputOverflow ? inputTokens : null,
641
+ outputTokens: outputSeen && !outputOverflow ? outputTokens : null,
642
+ tokenSpeed,
643
+ contextTokens,
644
+ contextWindow: subagentContextWindow(effectiveModel, context),
645
+ model: effectiveModel,
646
+ effort: subagentThinking(effort) || subagentThinkingFromModel(effectiveModel) || null,
647
+ };
648
+ } catch {
649
+ return empty;
650
+ } finally {
651
+ if (fd !== undefined) {
652
+ try { closeSync(fd); } catch { /* Best-effort close for bounded session telemetry. */ }
653
+ }
654
+ }
655
+ }
656
+
500
657
  function subagentInitialAgentsFromStep(step, defaults = {}) {
501
658
  if (!step || typeof step !== "object") return [];
502
659
  if (Array.isArray(step.parallel)) {
@@ -952,8 +1109,9 @@ export default function webuiRpcHelper(pi) {
952
1109
  status: "running",
953
1110
  activityState: agent.activityState,
954
1111
  model: agent.model,
955
- // Workflow snapshots do not carry reasoning data.
1112
+ // Workflow snapshots do not carry child-session telemetry or reasoning data.
956
1113
  thinking: undefined,
1114
+ telemetry: subagentEmptyTelemetry(),
957
1115
  recentTools: [],
958
1116
  recentOutput: agent.recentOutput,
959
1117
  transcript: [],
@@ -1016,6 +1174,11 @@ export default function webuiRpcHelper(pi) {
1016
1174
  }
1017
1175
 
1018
1176
  function subagentOutputSnapshotFromAgent(run, agent, patch = {}) {
1177
+ const model = subagentModel(patch.model || agent.model) || undefined;
1178
+ const thinking = subagentThinking(patch.thinking || agent.thinking) || undefined;
1179
+ const telemetry = patch.telemetry && typeof patch.telemetry === "object"
1180
+ ? patch.telemetry
1181
+ : subagentEmptyTelemetry({ model, effort: thinking, context: subagentContext });
1019
1182
  return {
1020
1183
  version: 1,
1021
1184
  runId: run.id,
@@ -1036,8 +1199,9 @@ export default function webuiRpcHelper(pi) {
1036
1199
  turnCount: Number.isFinite(patch.turnCount) ? patch.turnCount : Number.isFinite(agent.turnCount) ? agent.turnCount : undefined,
1037
1200
  toolCount: Number.isFinite(patch.toolCount) ? patch.toolCount : Number.isFinite(agent.toolCount) ? agent.toolCount : undefined,
1038
1201
  tokens: Number.isFinite(patch.tokens) ? patch.tokens : Number.isFinite(agent.tokens) ? agent.tokens : undefined,
1039
- model: subagentModel(patch.model || agent.model) || undefined,
1040
- thinking: subagentThinking(patch.thinking || agent.thinking) || undefined,
1202
+ model,
1203
+ thinking,
1204
+ telemetry,
1041
1205
  recentTools: subagentRecentTools(patch.recentTools || agent.recentTools),
1042
1206
  recentOutput: subagentOutputLines(patch.recentOutput || agent.recentOutput),
1043
1207
  transcript: Array.isArray(patch.transcript) ? patch.transcript : [],
@@ -1075,10 +1239,12 @@ export default function webuiRpcHelper(pi) {
1075
1239
  }
1076
1240
  }
1077
1241
  const transcriptOutput = subagentTranscriptOutput(agent.sessionFile);
1242
+ const telemetry = subagentSessionTelemetry(agent.sessionFile, { model: agent.model, effort: agent.thinking, context: subagentContext });
1078
1243
  const hasLocator = !!(agent.sessionFile && existsSync(agent.sessionFile));
1079
1244
  return subagentOutputSnapshotFromAgent(run, agent, {
1080
1245
  recentOutput: transcriptOutput.recentOutput.length ? transcriptOutput.recentOutput : agent.recentOutput,
1081
1246
  transcript: transcriptOutput.transcript,
1247
+ telemetry,
1082
1248
  updatedAt: run.endedAt,
1083
1249
  error: !hasLocator && !(Array.isArray(agent.recentOutput) && agent.recentOutput.length)
1084
1250
  ? "Retained subagent output is unavailable because its child output locator is missing."
@@ -1107,10 +1273,16 @@ export default function webuiRpcHelper(pi) {
1107
1273
  const sessionFile = subagentText(step.sessionFile || (steps.length === 1 ? status.sessionFile : ""), 4096);
1108
1274
  if (sessionFile && path.isAbsolute(sessionFile) && path.extname(sessionFile) === ".jsonl") agent.sessionFile = path.normalize(sessionFile);
1109
1275
  const transcriptOutput = subagentTranscriptOutput(agent.sessionFile);
1276
+ const telemetry = subagentSessionTelemetry(agent.sessionFile, {
1277
+ model: subagentModel(step.model) || agent.model,
1278
+ effort: subagentThinking(step.thinking) || subagentThinkingFromModel(step.model) || agent.thinking,
1279
+ context: subagentContext,
1280
+ });
1110
1281
  return subagentOutputSnapshotFromAgent(run, agent, {
1111
1282
  ...step,
1112
1283
  recentOutput: transcriptOutput.recentOutput.length ? transcriptOutput.recentOutput : step.recentOutput,
1113
1284
  transcript: transcriptOutput.transcript,
1285
+ telemetry,
1114
1286
  status: step.status || status.state,
1115
1287
  updatedAt: step.lastActivityAt || status.lastUpdate,
1116
1288
  tokens: Number.isFinite(step.tokens?.total) ? step.tokens.total : step.tokens,