@firstpick/pi-package-webui 0.9.1 → 0.9.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 (70) hide show
  1. package/README.md +21 -5
  2. package/bin/pi-webui-launcher.mjs +23 -12
  3. package/bin/pi-webui.mjs +479 -60
  4. package/lib/agent-run-adapters.mjs +500 -0
  5. package/lib/agent-run-protocol.mjs +262 -0
  6. package/lib/agent-run-registry.mjs +339 -0
  7. package/lib/git-workflow-preferences.mjs +11 -4
  8. package/lib/trust-boundaries.mjs +2 -0
  9. package/lib/ui-layout-settings.mjs +172 -28
  10. package/lib/update/package-layout.mjs +50 -0
  11. package/lib/update/plan.mjs +11 -0
  12. package/package.json +1 -1
  13. package/public/app.js +1261 -314
  14. package/public/index.html +113 -68
  15. package/public/service-worker.js +1 -1
  16. package/public/styles.css +371 -93
  17. package/tests/agent-run-adapters.test.mjs +217 -0
  18. package/tests/agent-run-launcher.test.mjs +41 -0
  19. package/tests/agent-run-protocol.test.mjs +82 -0
  20. package/tests/agent-run-registry.test.mjs +102 -0
  21. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  22. package/tests/browser/control-deck-side-panels.spec.mjs +354 -0
  23. package/tests/browser/controls-layout.spec.mjs +122 -0
  24. package/tests/browser/file-tree-git-ignored.spec.mjs +113 -0
  25. package/tests/browser/interaction-continuity.spec.mjs +127 -0
  26. package/tests/browser/mobile-foundation.spec.mjs +26 -0
  27. package/tests/browser/model-search-focus.spec.mjs +96 -0
  28. package/tests/browser/optimistic-prompt.spec.mjs +22 -0
  29. package/tests/browser/persistent-ui-layout.spec.mjs +224 -66
  30. package/tests/browser/subagent-observability.spec.mjs +87 -0
  31. package/tests/codex-fast-mode-static.test.mjs +2 -2
  32. package/tests/component-update-api-static.test.mjs +2 -1
  33. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  34. package/tests/control-deck-component-updates-static.test.mjs +2 -0
  35. package/tests/control-deck-side-panels-static.test.mjs +68 -0
  36. package/tests/controls-layout-static.test.mjs +22 -0
  37. package/tests/fast-mode-client-static.test.mjs +1 -1
  38. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  39. package/tests/file-tree-git-ignored-static.test.mjs +152 -0
  40. package/tests/file-tree-search-layout-static.test.mjs +2 -1
  41. package/tests/fixtures/fake-pi.mjs +43 -7
  42. package/tests/git-workflow-preferences.test.mjs +55 -6
  43. package/tests/http-endpoints-harness.test.mjs +173 -14
  44. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  45. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  46. package/tests/mobile-foundation-static.test.mjs +3 -3
  47. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  48. package/tests/mobile-static.test.mjs +13 -3
  49. package/tests/open-issue-wizard-static.test.mjs +2 -2
  50. package/tests/persistent-ui-layout-static.test.mjs +13 -13
  51. package/tests/questionnaire-dialog.test.mjs +3 -3
  52. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  53. package/tests/session-sampling-ui-static.test.mjs +3 -3
  54. package/tests/side-panel-context-menu-static.test.mjs +1 -1
  55. package/tests/side-panel-resize-static.test.mjs +26 -16
  56. package/tests/side-panel-section-height-removal-static.test.mjs +4 -4
  57. package/tests/side-panel-section-reorder-static.test.mjs +16 -70
  58. package/tests/subagent-gate-visibility.test.mjs +2 -1
  59. package/tests/subagent-launch-slots.test.mjs +1 -1
  60. package/tests/subagent-observability-static.test.mjs +32 -0
  61. package/tests/subagent-reliability-integration.test.mjs +161 -0
  62. package/tests/subagents-helper.test.mjs +344 -4
  63. package/tests/terminal-tabs-resize-static.test.mjs +35 -0
  64. package/tests/theme-customizer-static.test.mjs +1 -1
  65. package/tests/ui-layout-settings.test.mjs +104 -32
  66. package/tests/update-api-harness.test.mjs +24 -10
  67. package/tests/update-package-layout.test.mjs +38 -0
  68. package/tests/update-plan.test.mjs +11 -1
  69. package/tests/webui-settings-locking.test.mjs +33 -3
  70. package/webui-rpc-helper.mjs +417 -28
@@ -1,6 +1,13 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { AgentSession, formatSkillsForPrompt } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ AGENT_RUN_PROVIDER_EVENT,
7
+ AgentRunIndex,
8
+ canonicalAgentRunId,
9
+ normalizeProviderSnapshot,
10
+ } from "./lib/agent-run-protocol.mjs";
4
11
  import { readWebuiSettings } from "./lib/git-workflow-preferences.mjs";
5
12
  import { mutatePiRuntimeFollowUpQueue } from "./lib/queue-mutation.mjs";
6
13
  import {
@@ -31,6 +38,15 @@ const APP_RUNNER_CONTEXT_TYPE = "webui-app-runner-output";
31
38
  const RETAINED_SUBAGENT_RUNS_TYPE = "webui-subagent-retained-runs-v1";
32
39
  const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
33
40
  const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
41
+ // The helper and the HTTP server can be version-skewed across restarts, so the
42
+ // canonical payload travels on its own status key and never replaces the v1 key.
43
+ const WEBUI_SUBAGENTS_V2_STATUS_KEY = "webui-subagents-v2";
44
+ const WEBUI_SUBAGENTS_V2_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V2 ";
45
+ const WEBUI_SUBAGENTS_V2_VERSION = 2;
46
+ const AGENT_RUN_PRODUCER_LIMIT = 16;
47
+ const AGENT_RUN_INSTANCE_LIMIT = 512;
48
+ const AGENT_RUN_DIAGNOSTIC_LIMIT = 16;
49
+ const AGENT_RUN_GATE_REFERENCE_LIMIT = 128;
34
50
  const SUBAGENT_RPC_VERSION = 1;
35
51
  const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
36
52
  const SUBAGENT_RPC_READY_EVENT = "subagents:rpc:v1:ready";
@@ -52,6 +68,8 @@ const WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS = {
52
68
  };
53
69
  const SUBAGENT_STATUS_POLL_MS = 1500;
54
70
  const SUBAGENT_STATUS_RPC_TIMEOUT_MS = 900;
71
+ const SUBAGENT_STATUS_HEARTBEAT_MS = 15_000;
72
+ const SUBAGENT_AUTHORITATIVE_ABSENCE_LIMIT = 2;
55
73
  const FINISHED_SUBAGENT_RUN_LIMIT = 16;
56
74
  const SUBAGENT_OUTPUT_LINE_LIMIT = 120;
57
75
  const SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
@@ -266,6 +284,20 @@ function replaceAvailableSkillsSection(systemPrompt, skills) {
266
284
  return systemPrompt;
267
285
  }
268
286
 
287
+ const CANONICAL_AGENT_RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
288
+
289
+ /** Opaque helper-owned output handle. The browser never sees run/agent internals or paths. */
290
+ function helperAgentRunOutputId(runId, agentId) {
291
+ return `h-${createHash("sha256").update(`${runId}\u0000${agentId}`).digest("hex").slice(0, 32)}`;
292
+ }
293
+
294
+ function canonicalAgentRunStatus(runStatus, agentStatus) {
295
+ for (const candidate of [agentStatus, runStatus]) {
296
+ if (candidate === "cancelled" || candidate === "failed" || candidate === "done") return candidate;
297
+ }
298
+ return "running";
299
+ }
300
+
269
301
  function subagentText(value, maxLength = 240) {
270
302
  const text = String(value || "").trim();
271
303
  return text ? text.slice(0, maxLength) : "";
@@ -771,6 +803,32 @@ function subagentRunningGraphAgents(workflowGraph, runId) {
771
803
  return agents;
772
804
  }
773
805
 
806
+ function normalizeSubagentFleet(value) {
807
+ if (!value || typeof value !== "object" || value.version !== 1 || !Array.isArray(value.entries)) return undefined;
808
+ const totalActive = Number.isSafeInteger(value.totalActive) && value.totalActive >= 0 ? value.totalActive : -1;
809
+ const omitted = Number.isSafeInteger(value.omitted) && value.omitted >= 0 ? value.omitted : -1;
810
+ if (totalActive < value.entries.length || omitted !== totalActive - value.entries.length) return undefined;
811
+ const entries = [];
812
+ const keys = new Set();
813
+ for (const candidate of value.entries.slice(0, 32)) {
814
+ const key = subagentText(candidate?.key, 160);
815
+ const agent = subagentAgentName(candidate?.agent);
816
+ const startedAt = candidate?.startedAt;
817
+ if (!key || !agent || keys.has(key) || !Number.isSafeInteger(startedAt) || startedAt < 0) return undefined;
818
+ keys.add(key);
819
+ entries.push({
820
+ key,
821
+ agent,
822
+ name: subagentAgentName(candidate?.role) || agent,
823
+ model: subagentModel(candidate?.model) || undefined,
824
+ thinking: subagentThinking(candidate?.effort) || subagentThinkingFromModel(candidate?.model) || undefined,
825
+ startedAt,
826
+ });
827
+ }
828
+ if (entries.length !== value.entries.length) return undefined;
829
+ return { version: 1, entries, totalActive, omitted };
830
+ }
831
+
774
832
  function parseSubagentStatusText(text, previousRuns = new Map()) {
775
833
  const runs = [];
776
834
  let current = null;
@@ -840,12 +898,23 @@ export default function webuiRpcHelper(pi) {
840
898
  let subagentBridgeAvailable = false;
841
899
  let subagentPollTimer = null;
842
900
  let subagentPollGeneration = 0;
843
- let subagentStatusRequestInFlight = false;
901
+ let subagentPollSequence = 0;
902
+ let subagentAppliedPollSequence = 0;
903
+ let subagentFleetSummary = null;
844
904
  let lastPublishedSubagentSignature = "";
905
+ let lastPublishedSubagentAt = 0;
906
+ let lastPublishedAgentRunSignature = "";
907
+ let lastPublishedAgentRunAt = 0;
845
908
  let lastPersistedRetainedSubagentSignature = "";
909
+ // producerId -> Map<instanceId, canonical instance>. One producer never owns another's rows.
910
+ const agentRunProviderSnapshots = new Map();
911
+ const agentRunProviderDiagnostics = [];
912
+ const helperAgentRunOutputSelections = new Map();
913
+ const subagentStatusRequestsInFlight = new Set();
846
914
  const asyncSubagentRuns = new Map();
847
915
  const foregroundSubagentRuns = new Map();
848
916
  const workflowSubagentRuns = new Map();
917
+ const recoveredSubagentRuns = new Map();
849
918
  const subagentGates = new Map();
850
919
 
851
920
  function ordinarySubagentRunEntries() {
@@ -1025,7 +1094,25 @@ export default function webuiRpcHelper(pi) {
1025
1094
  nested: false,
1026
1095
  })),
1027
1096
  }));
1028
- return [...ordinaryRuns, ...workflowRuns]
1097
+ const recoveredRuns = [...recoveredSubagentRuns.values()].map((run) => ({
1098
+ id: run.id,
1099
+ source: "recovered",
1100
+ mode: "single",
1101
+ status: "running",
1102
+ startedAt: run.startedAt,
1103
+ provisional: true,
1104
+ controllable: false,
1105
+ agents: [{
1106
+ id: run.agent.id,
1107
+ name: run.agent.name,
1108
+ status: "running",
1109
+ index: 0,
1110
+ model: run.agent.model,
1111
+ thinking: run.agent.thinking,
1112
+ nested: false,
1113
+ }],
1114
+ }));
1115
+ return [...ordinaryRuns, ...workflowRuns, ...recoveredRuns]
1029
1116
  .filter((run) => run.id && (run.status !== "running" || run.agents.length > 0))
1030
1117
  .sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id));
1031
1118
  }
@@ -1067,21 +1154,207 @@ export default function webuiRpcHelper(pi) {
1067
1154
  .sort((left, right) => left.startedAt - right.startedAt || left.id.localeCompare(right.id));
1068
1155
  }
1069
1156
 
1070
- function publishSubagentStatus() {
1071
- if (!subagentContext?.hasUI) return;
1072
- const runs = publicSubagentRuns();
1073
- const gates = publicSubagentGates();
1074
- const snapshot = { version: 1, available: subagentBridgeAvailable, runs, gates };
1157
+ function resetCanonicalAgentRunState() {
1158
+ agentRunProviderSnapshots.clear();
1159
+ agentRunProviderDiagnostics.length = 0;
1160
+ helperAgentRunOutputSelections.clear();
1161
+ lastPublishedAgentRunSignature = "";
1162
+ lastPublishedAgentRunAt = 0;
1163
+ }
1164
+
1165
+ function recordAgentRunDiagnostic(code, producerId) {
1166
+ const entry = { code, ...(producerId ? { producerId: canonicalAgentRunId(producerId, "producer") } : {}) };
1167
+ const signature = JSON.stringify(entry);
1168
+ if (agentRunProviderDiagnostics.some((item) => JSON.stringify(item) === signature)) return;
1169
+ agentRunProviderDiagnostics.push(entry);
1170
+ while (agentRunProviderDiagnostics.length > AGENT_RUN_DIAGNOSTIC_LIMIT) agentRunProviderDiagnostics.shift();
1171
+ }
1172
+
1173
+ /**
1174
+ * Ingest one bounded process-local provider snapshot. A malformed or oversized
1175
+ * snapshot is dropped with a diagnostic and can never clear another producer's rows.
1176
+ */
1177
+ function ingestAgentRunProviderSnapshot(value) {
1178
+ let snapshot;
1179
+ try {
1180
+ snapshot = normalizeProviderSnapshot(value);
1181
+ } catch {
1182
+ recordAgentRunDiagnostic("invalid-provider-snapshot", value?.producerId);
1183
+ return false;
1184
+ }
1185
+ const existing = agentRunProviderSnapshots.get(snapshot.producerId);
1186
+ if (!existing && agentRunProviderSnapshots.size >= AGENT_RUN_PRODUCER_LIMIT) {
1187
+ recordAgentRunDiagnostic("producer-limit-reached", snapshot.producerId);
1188
+ return false;
1189
+ }
1190
+ const rows = snapshot.complete ? new Map() : new Map(existing || []);
1191
+ for (const instance of snapshot.instances) rows.set(instance.instanceId, instance);
1192
+ for (const removed of snapshot.removals) rows.delete(removed);
1193
+ if (rows.size) agentRunProviderSnapshots.set(snapshot.producerId, rows);
1194
+ else agentRunProviderSnapshots.delete(snapshot.producerId);
1195
+ return true;
1196
+ }
1197
+
1198
+ function canonicalInstancesFromPublicRun(run, gateRunIds) {
1199
+ const workflow = run.source === "workflow";
1200
+ const rawParentSessionId = subagentContext?.sessionManager?.getSessionId?.();
1201
+ const parentSessionId = rawParentSessionId ? canonicalAgentRunId(rawParentSessionId, "session") : null;
1202
+ const recovered = run.source === "recovered";
1203
+ const terminal = run.status !== "running";
1204
+ const startedAt = Number.isFinite(run.startedAt) ? run.startedAt : Date.now();
1205
+ // Unknown terminal time stays anchored to the stable start time instead of inventing
1206
+ // a fresh timestamp on every projection and defeating status deduplication.
1207
+ const endedAt = terminal ? Math.max(startedAt, Number.isFinite(run.endedAt) ? run.endedAt : startedAt) : null;
1208
+ // Projection signatures must stay stable between source changes; publication adds its own heartbeat timestamp.
1209
+ const updatedAt = terminal ? endedAt : startedAt;
1210
+ const canonicalRunId = canonicalAgentRunId(run.id, "run");
1211
+ // Gate launches stay one canonical child: the launch family changes, the count does not.
1212
+ const launcher = gateRunIds.has(run.id) ? "gate" : workflow ? "workflow" : "pi-subagents";
1213
+ return (Array.isArray(run.agents) ? run.agents : []).map((agent) => {
1214
+ const status = canonicalAgentRunStatus(run.status, agent.status);
1215
+ const openable = !recovered;
1216
+ return {
1217
+ version: 1,
1218
+ instanceId: canonicalAgentRunId(agent.id, `${canonicalRunId}-agent`),
1219
+ runId: canonicalRunId,
1220
+ parentSessionId,
1221
+ launcher,
1222
+ provider: workflow ? "workflow-run" : "pi-subagents",
1223
+ origin: run.source,
1224
+ name: agent.name,
1225
+ status,
1226
+ startedAt,
1227
+ updatedAt,
1228
+ endedAt: ["done", "failed", "cancelled"].includes(status) ? endedAt : null,
1229
+ model: agent.model,
1230
+ thinking: agent.thinking,
1231
+ activityState: agent.activityState && CANONICAL_AGENT_RUN_ID_PATTERN.test(agent.activityState) ? agent.activityState : undefined,
1232
+ currentTool: agent.currentTool,
1233
+ capabilities: {
1234
+ open: openable,
1235
+ refresh: openable,
1236
+ // Only the owning pi-subagents lifecycle keeps cancel authority in v1.
1237
+ cancel: status === "running" && !workflow && !recovered && run.controllable !== false,
1238
+ steer: false,
1239
+ },
1240
+ outputRef: openable
1241
+ ? { kind: "helper", id: helperAgentRunOutputId(run.id, agent.id) }
1242
+ : { kind: "none" },
1243
+ _selection: openable ? { runId: run.id, agentId: agent.id } : null,
1244
+ };
1245
+ });
1246
+ }
1247
+
1248
+ /**
1249
+ * Canonical, deduplicated projection of every provider this helper observes.
1250
+ * Counts derive from canonical instance IDs only; gates and workflow containers
1251
+ * are references, never additional agents.
1252
+ */
1253
+ function canonicalAgentRunSnapshot(runs, gates) {
1254
+ const index = new AgentRunIndex();
1255
+ const selections = new Map();
1256
+ const gateRunIds = new Set();
1257
+ for (const gate of gates) {
1258
+ for (const attempt of gate.attempts) if (attempt.runId) gateRunIds.add(attempt.runId);
1259
+ }
1260
+
1261
+ const instanceIdByPublicRun = new Map();
1262
+ for (const run of runs) {
1263
+ for (const candidate of canonicalInstancesFromPublicRun(run, gateRunIds)) {
1264
+ const { _selection: selection, ...instance } = candidate;
1265
+ try {
1266
+ // The helper owns lifecycle and capabilities for the rows it observes directly.
1267
+ index.upsert(instance, { producerId: instance.provider, lifecycleOwner: true, capabilityOwner: true });
1268
+ } catch {
1269
+ recordAgentRunDiagnostic("invalid-helper-instance", instance.provider);
1270
+ continue;
1271
+ }
1272
+ if (selection) selections.set(instance.outputRef.id, selection);
1273
+ const known = instanceIdByPublicRun.get(run.id) || [];
1274
+ known.push(instance.instanceId);
1275
+ instanceIdByPublicRun.set(run.id, known);
1276
+ }
1277
+ }
1278
+
1279
+ for (const [producerId, rows] of agentRunProviderSnapshots) {
1280
+ for (const instance of rows.values()) {
1281
+ try {
1282
+ // Foreign producers may enrich an existing instance but never seize ownership.
1283
+ index.upsert(instance, { producerId, lifecycleOwner: false, capabilityOwner: false });
1284
+ } catch {
1285
+ recordAgentRunDiagnostic("invalid-provider-instance", producerId);
1286
+ }
1287
+ }
1288
+ }
1289
+
1290
+ const gateReferences = [];
1291
+ for (const gate of gates) {
1292
+ for (const attempt of gate.attempts) {
1293
+ if (!attempt.runId || gateReferences.length >= AGENT_RUN_GATE_REFERENCE_LIMIT) continue;
1294
+ const instanceIds = instanceIdByPublicRun.get(attempt.runId) || [];
1295
+ gateReferences.push({
1296
+ gateId: gate.id,
1297
+ attemptId: attempt.id,
1298
+ runId: canonicalAgentRunId(attempt.runId, "run"),
1299
+ instanceIds,
1300
+ resolved: instanceIds.length > 0,
1301
+ });
1302
+ }
1303
+ }
1304
+
1305
+ helperAgentRunOutputSelections.clear();
1306
+ for (const [outputId, selection] of selections) helperAgentRunOutputSelections.set(outputId, selection);
1307
+
1308
+ return {
1309
+ instances: index.values().slice(0, AGENT_RUN_INSTANCE_LIMIT),
1310
+ gateReferences,
1311
+ producers: [...agentRunProviderSnapshots.keys()].slice(0, AGENT_RUN_PRODUCER_LIMIT),
1312
+ diagnostics: agentRunProviderDiagnostics.slice(-AGENT_RUN_DIAGNOSTIC_LIMIT),
1313
+ };
1314
+ }
1315
+
1316
+ function publishCanonicalAgentRunStatus(runs, gates, now) {
1317
+ const snapshot = { version: WEBUI_SUBAGENTS_V2_VERSION, available: subagentBridgeAvailable, ...canonicalAgentRunSnapshot(runs, gates) };
1318
+ const signature = JSON.stringify(snapshot);
1319
+ if (signature === lastPublishedAgentRunSignature && now - lastPublishedAgentRunAt < SUBAGENT_STATUS_HEARTBEAT_MS) return;
1320
+ try {
1321
+ subagentContext.ui.setStatus(WEBUI_SUBAGENTS_V2_STATUS_KEY, `${WEBUI_SUBAGENTS_V2_PAYLOAD_PREFIX}${JSON.stringify({ ...snapshot, updatedAt: now })}`);
1322
+ lastPublishedAgentRunSignature = signature;
1323
+ lastPublishedAgentRunAt = now;
1324
+ } catch {
1325
+ // Leave the signature uncommitted so a later poll or lifecycle event retries delivery.
1326
+ }
1327
+ }
1328
+
1329
+ function publishLegacySubagentStatus(snapshot, now) {
1075
1330
  const signature = JSON.stringify(snapshot);
1076
- if (signature === lastPublishedSubagentSignature) return;
1077
- lastPublishedSubagentSignature = signature;
1331
+ if (signature === lastPublishedSubagentSignature && now - lastPublishedSubagentAt < SUBAGENT_STATUS_HEARTBEAT_MS) return;
1078
1332
  try {
1079
- subagentContext.ui.setStatus(WEBUI_SUBAGENTS_STATUS_KEY, `${WEBUI_SUBAGENTS_PAYLOAD_PREFIX}${JSON.stringify({ ...snapshot, updatedAt: Date.now() })}`);
1333
+ subagentContext.ui.setStatus(WEBUI_SUBAGENTS_STATUS_KEY, `${WEBUI_SUBAGENTS_PAYLOAD_PREFIX}${JSON.stringify({ ...snapshot, updatedAt: now })}`);
1334
+ lastPublishedSubagentSignature = signature;
1335
+ lastPublishedSubagentAt = now;
1080
1336
  } catch {
1081
- // The old context may become stale while Pi replaces a session.
1337
+ // Leave the signature uncommitted so a later poll or lifecycle event retries delivery.
1082
1338
  }
1083
1339
  }
1084
1340
 
1341
+ function publishSubagentStatus() {
1342
+ if (!subagentContext?.hasUI) return;
1343
+ const runs = publicSubagentRuns();
1344
+ const gates = publicSubagentGates();
1345
+ const now = Date.now();
1346
+ // Both keys are published independently: an old server keeps consuming v1,
1347
+ // a new server prefers v2, and a failure on one key never suppresses the other.
1348
+ publishLegacySubagentStatus({
1349
+ version: 1,
1350
+ available: subagentBridgeAvailable,
1351
+ runs,
1352
+ gates,
1353
+ ...(subagentFleetSummary ? { fleet: subagentFleetSummary } : {}),
1354
+ }, now);
1355
+ publishCanonicalAgentRunStatus(runs, gates, now);
1356
+ }
1357
+
1085
1358
  function requestSubagentRpc(method, params = {}) {
1086
1359
  const requestId = `webui-${Date.now()}-${Math.random().toString(36).slice(2)}`;
1087
1360
  return new Promise((resolve, reject) => {
@@ -1249,6 +1522,15 @@ export default function webuiRpcHelper(pi) {
1249
1522
  }
1250
1523
 
1251
1524
  async function subagentOutputSnapshot(payload = {}) {
1525
+ // Opaque helper-owned handles resolve to an internal selection here; the browser
1526
+ // never supplies a run/agent path or an arbitrary locator.
1527
+ const outputId = subagentText(payload.outputId, 160);
1528
+ if (outputId) {
1529
+ const selection = helperAgentRunOutputSelections.get(outputId);
1530
+ if (!selection) throw new Error("Subagent output handle is no longer tracked");
1531
+ return subagentOutputSnapshot({ runId: selection.runId, agentId: selection.agentId });
1532
+ }
1533
+
1252
1534
  const workflowRunId = workflowSubagentIdentifier(payload.runId, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.runIdentifierLength);
1253
1535
  const workflowAgentId = workflowSubagentIdentifier(payload.agentId, WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS.agentIdentifierLength);
1254
1536
  if (workflowRunId && workflowAgentId) {
@@ -1330,19 +1612,73 @@ export default function webuiRpcHelper(pi) {
1330
1612
  }
1331
1613
  }
1332
1614
 
1333
- async function refreshSubagentStatus() {
1334
- if (subagentStatusRequestInFlight) return;
1335
- subagentStatusRequestInFlight = true;
1615
+ function reconcileSubagentFleet(fleet, parsedIds) {
1616
+ subagentFleetSummary = fleet ? { version: 1, totalActive: fleet.totalActive, omitted: fleet.omitted } : null;
1617
+ if (!fleet) return new Set();
1618
+ const slots = [];
1619
+ const addSlots = (runs, priority) => {
1620
+ for (const run of runs) {
1621
+ if (run?.status !== "running") continue;
1622
+ for (const agent of Array.isArray(run.agents) ? run.agents : []) {
1623
+ if (agent?.status !== "running" || !subagentAgentName(agent.name)) continue;
1624
+ slots.push({ run, agent, priority: parsedIds.has(run.id) ? 0 : priority, claimed: false });
1625
+ }
1626
+ }
1627
+ };
1628
+ addSlots(asyncSubagentRuns.values(), 1);
1629
+ addSlots(foregroundSubagentRuns.values(), 2);
1630
+ slots.sort((left, right) => left.priority - right.priority);
1631
+
1632
+ const matchedRunIds = new Set();
1633
+ const unmatched = [];
1634
+ for (const entry of fleet.entries) {
1635
+ const slot = slots.find((candidate) => !candidate.claimed && candidate.agent.name === entry.agent);
1636
+ if (!slot) {
1637
+ unmatched.push(entry);
1638
+ continue;
1639
+ }
1640
+ slot.claimed = true;
1641
+ matchedRunIds.add(slot.run.id);
1642
+ recoveredSubagentRuns.delete(entry.key);
1643
+ }
1644
+
1645
+ const unmatchedKeys = new Set(unmatched.map((entry) => entry.key));
1646
+ for (const entry of unmatched) {
1647
+ const previous = recoveredSubagentRuns.get(entry.key);
1648
+ recoveredSubagentRuns.set(entry.key, {
1649
+ ...previous,
1650
+ id: `fleet:${entry.key}`,
1651
+ startedAt: entry.startedAt,
1652
+ absenceGeneration: subagentPollGeneration,
1653
+ absenceCount: 0,
1654
+ agent: {
1655
+ id: `fleet:${entry.key}:agent`,
1656
+ name: entry.name,
1657
+ model: entry.model,
1658
+ thinking: entry.thinking,
1659
+ },
1660
+ });
1661
+ }
1662
+ if (fleet.omitted === 0) {
1663
+ for (const [key, run] of recoveredSubagentRuns) {
1664
+ if (unmatchedKeys.has(key)) continue;
1665
+ const count = run.absenceGeneration === subagentPollGeneration ? Number(run.absenceCount || 0) + 1 : 1;
1666
+ if (count >= SUBAGENT_AUTHORITATIVE_ABSENCE_LIMIT) recoveredSubagentRuns.delete(key);
1667
+ else Object.assign(run, { absenceGeneration: subagentPollGeneration, absenceCount: count });
1668
+ }
1669
+ }
1670
+ return matchedRunIds;
1671
+ }
1672
+
1673
+ async function refreshSubagentStatus(generation = subagentPollGeneration) {
1674
+ if (generation !== subagentPollGeneration || subagentStatusRequestsInFlight.has(generation)) return;
1675
+ const sequence = ++subagentPollSequence;
1676
+ subagentStatusRequestsInFlight.add(generation);
1336
1677
  try {
1337
1678
  const data = await requestSubagentStatus();
1338
- subagentBridgeAvailable = true;
1679
+ if (generation !== subagentPollGeneration || sequence <= subagentAppliedPollSequence) return;
1339
1680
  const parsedRuns = parseSubagentStatusText(data?.text, asyncSubagentRuns);
1340
- const nextIds = new Set(parsedRuns.map((run) => run.id));
1341
- for (const run of asyncSubagentRuns.values()) {
1342
- if (run?.status === "running" && !nextIds.has(run.id) && Date.now() - Number(run.eventSeenAt || 0) > SUBAGENT_STATUS_POLL_MS * 2) {
1343
- finishSubagentRun(run, "done");
1344
- }
1345
- }
1681
+ const nextRuns = [];
1346
1682
  for (const run of parsedRuns) {
1347
1683
  const previous = asyncSubagentRuns.get(run.id);
1348
1684
  if (previous?.status && previous.status !== "running") continue;
@@ -1359,16 +1695,39 @@ export default function webuiRpcHelper(pi) {
1359
1695
  ...previous,
1360
1696
  ...run,
1361
1697
  eventSeenAt: previous?.eventSeenAt || Date.now(),
1698
+ authoritativeAbsenceGeneration: generation,
1699
+ authoritativeAbsenceCount: 0,
1362
1700
  agents: [...completedAgents, ...runningAgents],
1363
1701
  };
1364
1702
  await enrichAsyncSubagentRun(merged);
1365
- asyncSubagentRuns.set(run.id, merged);
1703
+ if (generation !== subagentPollGeneration || sequence <= subagentAppliedPollSequence) return;
1704
+ nextRuns.push(merged);
1705
+ }
1706
+ if (generation !== subagentPollGeneration || sequence <= subagentAppliedPollSequence) return;
1707
+ subagentAppliedPollSequence = sequence;
1708
+ subagentBridgeAvailable = true;
1709
+ for (const run of nextRuns) asyncSubagentRuns.set(run.id, run);
1710
+ const nextIds = new Set(nextRuns.map((run) => run.id));
1711
+ const fleet = normalizeSubagentFleet(data?.fleet);
1712
+ const fleetRunIds = reconcileSubagentFleet(fleet, nextIds);
1713
+ for (const run of asyncSubagentRuns.values()) {
1714
+ if (run?.status !== "running") continue;
1715
+ if (nextIds.has(run.id) || fleetRunIds.has(run.id)) {
1716
+ run.authoritativeAbsenceGeneration = generation;
1717
+ run.authoritativeAbsenceCount = 0;
1718
+ continue;
1719
+ }
1720
+ if (!fleet || fleet.omitted !== 0) continue;
1721
+ const count = run.authoritativeAbsenceGeneration === generation ? Number(run.authoritativeAbsenceCount || 0) + 1 : 1;
1722
+ run.authoritativeAbsenceGeneration = generation;
1723
+ run.authoritativeAbsenceCount = count;
1724
+ if (count >= SUBAGENT_AUTHORITATIVE_ABSENCE_LIMIT) finishSubagentRun(run, "done");
1366
1725
  }
1367
- publishSubagentStatus();
1368
1726
  } catch {
1369
1727
  // The optional pi-subagents extension may not be loaded in this tab.
1370
1728
  } finally {
1371
- subagentStatusRequestInFlight = false;
1729
+ subagentStatusRequestsInFlight.delete(generation);
1730
+ if (generation === subagentPollGeneration) publishSubagentStatus();
1372
1731
  }
1373
1732
  }
1374
1733
 
@@ -1376,7 +1735,7 @@ export default function webuiRpcHelper(pi) {
1376
1735
  clearTimeout(subagentPollTimer);
1377
1736
  subagentPollTimer = setTimeout(async () => {
1378
1737
  if (generation !== subagentPollGeneration || !subagentContext) return;
1379
- await refreshSubagentStatus();
1738
+ await refreshSubagentStatus(generation);
1380
1739
  scheduleSubagentStatusPoll(generation);
1381
1740
  }, delay);
1382
1741
  subagentPollTimer.unref?.();
@@ -1394,10 +1753,17 @@ export default function webuiRpcHelper(pi) {
1394
1753
  // Ignore malformed cross-extension events without disrupting current live rows.
1395
1754
  }
1396
1755
  }),
1756
+ pi.events.on(AGENT_RUN_PROVIDER_EVENT, (value) => {
1757
+ // Generic process-local producers: bounded, validated, and producer-scoped.
1758
+ // Rejected snapshots still publish so their bounded diagnostic becomes visible;
1759
+ // repeated identical failures collapse into one deduplicated entry.
1760
+ ingestAgentRunProviderSnapshot(value);
1761
+ publishSubagentStatus();
1762
+ }),
1397
1763
  pi.events.on(SUBAGENT_RPC_READY_EVENT, () => {
1398
1764
  subagentBridgeAvailable = true;
1399
1765
  publishSubagentStatus();
1400
- void refreshSubagentStatus();
1766
+ void refreshSubagentStatus(subagentPollGeneration);
1401
1767
  }),
1402
1768
  pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, (value) => {
1403
1769
  const info = value && typeof value === "object" ? value : {};
@@ -1760,9 +2126,13 @@ export default function webuiRpcHelper(pi) {
1760
2126
  foregroundSubagentRuns.clear();
1761
2127
  asyncSubagentRuns.clear();
1762
2128
  workflowSubagentRuns.clear();
2129
+ recoveredSubagentRuns.clear();
1763
2130
  subagentGates.clear();
2131
+ resetCanonicalAgentRunState();
2132
+ subagentFleetSummary = null;
1764
2133
  restoreRetainedSubagentRuns(ctx);
1765
2134
  lastPublishedSubagentSignature = "";
2135
+ lastPublishedSubagentAt = 0;
1766
2136
  publishSubagentStatus();
1767
2137
  scheduleSubagentStatusPoll(subagentPollGeneration, 0);
1768
2138
  });
@@ -1773,11 +2143,19 @@ export default function webuiRpcHelper(pi) {
1773
2143
  restoreSkillsFromBranch(ctx, globalDefaults);
1774
2144
  restoreSamplingParamsFromBranch(ctx);
1775
2145
  subagentContext = ctx;
2146
+ subagentPollGeneration += 1;
1776
2147
  foregroundSubagentRuns.clear();
1777
2148
  asyncSubagentRuns.clear();
2149
+ workflowSubagentRuns.clear();
2150
+ recoveredSubagentRuns.clear();
2151
+ subagentGates.clear();
2152
+ resetCanonicalAgentRunState();
2153
+ subagentFleetSummary = null;
1778
2154
  restoreRetainedSubagentRuns(ctx);
1779
2155
  lastPublishedSubagentSignature = "";
2156
+ lastPublishedSubagentAt = 0;
1780
2157
  publishSubagentStatus();
2158
+ scheduleSubagentStatusPoll(subagentPollGeneration, 0);
1781
2159
  });
1782
2160
 
1783
2161
  pi.on("tool_execution_start", (event, ctx) => {
@@ -1785,6 +2163,7 @@ export default function webuiRpcHelper(pi) {
1785
2163
  const id = subagentText(event.toolCallId, 160);
1786
2164
  if (!id) return;
1787
2165
  subagentContext = ctx;
2166
+ const workflowProvisional = typeof event.args?.workflowScript === "string" && event.args.workflowScript.trim().length > 0;
1788
2167
  const initialAgents = subagentInitialAgentsFromArgs(event.args).map((agent, index) => ({
1789
2168
  id: `${id}:${index}:${agent.name}`,
1790
2169
  name: agent.name,
@@ -1794,6 +2173,9 @@ export default function webuiRpcHelper(pi) {
1794
2173
  thinking: agent.thinking,
1795
2174
  nested: false,
1796
2175
  }));
2176
+ if (!initialAgents.length && workflowProvisional) {
2177
+ initialAgents.push({ id: `${id}:0:workflow`, name: "workflow", status: "running", index: 0, nested: false });
2178
+ }
1797
2179
  if (!initialAgents.length) return;
1798
2180
  foregroundSubagentRuns.set(id, {
1799
2181
  id,
@@ -1802,6 +2184,7 @@ export default function webuiRpcHelper(pi) {
1802
2184
  status: "running",
1803
2185
  startedAt: Date.now(),
1804
2186
  controlRunId: undefined,
2187
+ workflowProvisional,
1805
2188
  agents: initialAgents,
1806
2189
  });
1807
2190
  publishSubagentStatus();
@@ -1816,6 +2199,7 @@ export default function webuiRpcHelper(pi) {
1816
2199
  const details = event.partialResult?.details || event.result?.details;
1817
2200
  const agents = subagentRunningAgentsFromDetails(details, details?.runId || id);
1818
2201
  if (agents.length) {
2202
+ run.workflowProvisional = false;
1819
2203
  const runningAgents = agents.map((agent) => {
1820
2204
  const previous = run.agents.find((candidate) => candidate.index === agent.index && candidate.name === agent.name);
1821
2205
  return {
@@ -1842,8 +2226,10 @@ export default function webuiRpcHelper(pi) {
1842
2226
  pi.on("tool_execution_end", (event) => {
1843
2227
  if (event.toolName !== "subagent") return;
1844
2228
  const toolCallId = subagentText(event.toolCallId, 160);
1845
- const run = [...foregroundSubagentRuns.values()].find((candidate) => candidate?.id === toolCallId) || foregroundSubagentRuns.get(toolCallId);
1846
- if (run) finishSubagentRun(run, event.isError === true || event.result?.isError === true ? "failed" : "done");
2229
+ const entry = [...foregroundSubagentRuns.entries()].find(([key, candidate]) => candidate?.id === toolCallId || key === toolCallId);
2230
+ const run = entry?.[1];
2231
+ if (run?.workflowProvisional) foregroundSubagentRuns.delete(entry[0]);
2232
+ else if (run) finishSubagentRun(run, event.isError === true || event.result?.isError === true ? "failed" : "done");
1847
2233
  publishSubagentStatus();
1848
2234
  });
1849
2235
 
@@ -1856,7 +2242,10 @@ export default function webuiRpcHelper(pi) {
1856
2242
  foregroundSubagentRuns.clear();
1857
2243
  asyncSubagentRuns.clear();
1858
2244
  workflowSubagentRuns.clear();
2245
+ recoveredSubagentRuns.clear();
1859
2246
  subagentGates.clear();
2247
+ resetCanonicalAgentRunState();
2248
+ subagentFleetSummary = null;
1860
2249
  for (const unsubscribe of subagentEventUnsubscribers) unsubscribe();
1861
2250
  });
1862
2251