@firstpick/pi-package-webui 0.7.7 → 0.7.9

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 (50) hide show
  1. package/README.md +23 -0
  2. package/bin/pi-webui-rpc-supervisor.mjs +115 -21
  3. package/bin/pi-webui.mjs +447 -88
  4. package/lib/queue-mutation.mjs +109 -0
  5. package/lib/rpc-supervisor-client.mjs +18 -2
  6. package/lib/rpc-supervisor-protocol.mjs +11 -2
  7. package/lib/scoped-models.mjs +19 -0
  8. package/lib/webui-workspaces.mjs +265 -0
  9. package/package.json +4 -4
  10. package/public/app.js +2227 -195
  11. package/public/index.html +143 -2
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +3 -1
  15. package/public/styles.css +787 -56
  16. package/public/voice-conversation.mjs +1 -1
  17. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  18. package/tests/compaction-mutation-contract.test.mjs +166 -0
  19. package/tests/compaction-resume-harness.test.mjs +113 -2
  20. package/tests/compaction-static.test.mjs +5 -0
  21. package/tests/completion-signal-contract.test.mjs +156 -0
  22. package/tests/cwd-footer-reliability-static.test.mjs +112 -0
  23. package/tests/durable-rpc-supervisor-harness.test.mjs +25 -2
  24. package/tests/fast-mode-client-static.test.mjs +1 -1
  25. package/tests/file-selection-overlay-static.test.mjs +21 -0
  26. package/tests/file-viewer-search-static.test.mjs +65 -0
  27. package/tests/fixtures/compacting-pi.mjs +0 -0
  28. package/tests/fixtures/fake-pi.mjs +186 -49
  29. package/tests/footer-context-contrast-static.test.mjs +10 -0
  30. package/tests/git-panel-file-preview-static.test.mjs +20 -5
  31. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  32. package/tests/http-endpoints-harness.test.mjs +160 -1
  33. package/tests/issue-bot-client.test.mjs +135 -0
  34. package/tests/issue-wizard-state.test.mjs +126 -0
  35. package/tests/mobile-static.test.mjs +61 -42
  36. package/tests/native-parity.test.mjs +3 -3
  37. package/tests/open-issue-wizard-static.test.mjs +75 -0
  38. package/tests/prompt-routing-tab-status.test.mjs +5 -0
  39. package/tests/queue-edit-reorder-static.test.mjs +101 -0
  40. package/tests/queue-mutation-contract.test.mjs +143 -0
  41. package/tests/rpc-supervisor-host.test.mjs +135 -2
  42. package/tests/rpc-supervisor-protocol.test.mjs +26 -0
  43. package/tests/scoped-models.test.mjs +42 -0
  44. package/tests/streaming-ui-coupling.test.mjs +3 -2
  45. package/tests/subagents-helper.test.mjs +216 -3
  46. package/tests/terminal-tab-workspace-static.test.mjs +101 -0
  47. package/tests/webui-workspaces-harness.test.mjs +223 -0
  48. package/tests/webui-workspaces.test.mjs +106 -0
  49. package/tests/workspace-save-load-static.test.mjs +69 -0
  50. package/webui-rpc-helper.mjs +300 -41
@@ -1,7 +1,8 @@
1
- import { closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
1
+ import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { AgentSession, formatSkillsForPrompt } from "@earendil-works/pi-coding-agent";
4
4
  import { readWebuiSettings } from "./lib/git-workflow-preferences.mjs";
5
+ import { mutatePiRuntimeFollowUpQueue } from "./lib/queue-mutation.mjs";
5
6
  import {
6
7
  formatSubagentLaunchSlotGuidance,
7
8
  resolveSubagentLaunchSlotProjectKey,
@@ -14,6 +15,7 @@ const RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
14
15
  const TOOLS_CONFIG_TYPE = "webui-tools-config";
15
16
  const SKILLS_CONFIG_TYPE = "webui-skills-config";
16
17
  const APP_RUNNER_CONTEXT_TYPE = "webui-app-runner-output";
18
+ const RETAINED_SUBAGENT_RUNS_TYPE = "webui-subagent-retained-runs-v1";
17
19
  const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
18
20
  const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
19
21
  const SUBAGENT_RPC_VERSION = 1;
@@ -37,6 +39,7 @@ const WORKFLOW_SUBAGENT_SNAPSHOT_LIMITS = {
37
39
  };
38
40
  const SUBAGENT_STATUS_POLL_MS = 1500;
39
41
  const SUBAGENT_STATUS_RPC_TIMEOUT_MS = 900;
42
+ const FINISHED_SUBAGENT_RUN_LIMIT = 16;
40
43
  const SUBAGENT_OUTPUT_LINE_LIMIT = 120;
41
44
  const SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
42
45
  const SUBAGENT_TRANSCRIPT_TAIL_BYTES = 512 * 1024;
@@ -147,8 +150,9 @@ function queueMessageText(message) {
147
150
 
148
151
  function queuedMessagesSnapshot(session) {
149
152
  return {
150
- steering: Array.from(session?.getSteeringMessages?.() || []).map((item) => String(item || "")).filter((item) => item.trim()),
151
- followUp: Array.from(session?.getFollowUpMessages?.() || []).map((item) => String(item || "")).filter((item) => item.trim()),
153
+ source: "pi-runtime",
154
+ steering: Array.isArray(session?._steeringMessages) ? [...session._steeringMessages] : [],
155
+ followUp: Array.isArray(session?._followUpMessages) ? [...session._followUpMessages] : [],
152
156
  };
153
157
  }
154
158
 
@@ -183,6 +187,12 @@ function removeQueuedPrompt(payload = {}) {
183
187
  return { removed: true, kind, index, message: currentText, queue: queuedMessagesSnapshot(session) };
184
188
  }
185
189
 
190
+ function mutateQueuedFollowUp(payload = {}) {
191
+ const session = activeCommandSession();
192
+ if (!session) throw new Error("Web UI queue mutation is unavailable in this Pi version; reload this tab and retry.");
193
+ return mutatePiRuntimeFollowUpQueue(session, payload);
194
+ }
195
+
186
196
  function parseHelperArgs(args) {
187
197
  let parsed;
188
198
  try {
@@ -637,34 +647,169 @@ export default function webuiRpcHelper(pi) {
637
647
  let subagentPollGeneration = 0;
638
648
  let subagentStatusRequestInFlight = false;
639
649
  let lastPublishedSubagentSignature = "";
650
+ let lastPersistedRetainedSubagentSignature = "";
640
651
  const asyncSubagentRuns = new Map();
641
652
  const foregroundSubagentRuns = new Map();
642
653
  const workflowSubagentRuns = new Map();
643
654
  const subagentGates = new Map();
644
655
 
645
- function publicSubagentRuns() {
646
- const ordinaryRuns = [...foregroundSubagentRuns.values(), ...asyncSubagentRuns.values()]
656
+ function ordinarySubagentRunEntries() {
657
+ return [
658
+ ...[...foregroundSubagentRuns.entries()].map(([key, run]) => ({ runs: foregroundSubagentRuns, key, run })),
659
+ ...[...asyncSubagentRuns.entries()].map(([key, run]) => ({ runs: asyncSubagentRuns, key, run })),
660
+ ];
661
+ }
662
+
663
+ function trimFinishedSubagentRuns() {
664
+ const finished = ordinarySubagentRunEntries()
665
+ .filter(({ run }) => run?.status && run.status !== "running")
666
+ .sort((left, right) => Number(left.run.endedAt || 0) - Number(right.run.endedAt || 0) || String(left.run.id).localeCompare(String(right.run.id)));
667
+ while (finished.length > FINISHED_SUBAGENT_RUN_LIMIT) {
668
+ const oldest = finished.shift();
669
+ oldest.runs.delete(oldest.key);
670
+ }
671
+ }
672
+
673
+ function retainedSubagentAgent(agent, run, index) {
674
+ const asyncDir = subagentText(agent?.asyncDir, 4096);
675
+ const sessionFile = subagentText(agent?.sessionFile, 4096);
676
+ const hasOutputLocator = (asyncDir && path.isAbsolute(asyncDir))
677
+ || (sessionFile && path.isAbsolute(sessionFile) && path.extname(sessionFile) === ".jsonl");
678
+ return {
679
+ id: subagentText(agent?.id || `${run.id}:${index}`, 240),
680
+ name: subagentAgentName(agent?.name),
681
+ status: run.status === "cancelled" ? "cancelled" : "done",
682
+ index: Number.isInteger(agent?.index) ? agent.index : index,
683
+ currentTool: subagentText(agent?.currentTool, 120) || undefined,
684
+ currentToolArgs: subagentText(agent?.currentToolArgs, 500) || undefined,
685
+ currentPath: subagentText(agent?.currentPath, 1000) || undefined,
686
+ activityState: subagentText(agent?.activityState, 80) || undefined,
687
+ model: subagentModel(agent?.model) || undefined,
688
+ thinking: subagentThinking(agent?.thinking) || subagentThinkingFromModel(agent?.model) || undefined,
689
+ nested: agent?.nested === true,
690
+ targetRunId: subagentText(agent?.targetRunId, 160) || undefined,
691
+ asyncDir: asyncDir && path.isAbsolute(asyncDir) ? path.normalize(asyncDir) : undefined,
692
+ sessionFile: sessionFile && path.isAbsolute(sessionFile) && path.extname(sessionFile) === ".jsonl" ? path.normalize(sessionFile) : undefined,
693
+ recentTools: hasOutputLocator ? [] : subagentRecentTools(agent?.recentTools),
694
+ recentOutput: hasOutputLocator ? [] : subagentOutputLines(agent?.recentOutput),
695
+ turnCount: Number.isFinite(agent?.turnCount) ? agent.turnCount : undefined,
696
+ toolCount: Number.isFinite(agent?.toolCount) ? agent.toolCount : undefined,
697
+ tokens: Number.isFinite(agent?.tokens) ? agent.tokens : undefined,
698
+ };
699
+ }
700
+
701
+ function retainedSubagentRunsSnapshot() {
702
+ return ordinarySubagentRunEntries()
703
+ .map(({ run }) => run)
704
+ .filter((run) => run?.status && run.status !== "running")
705
+ .sort((left, right) => Number(left.endedAt || 0) - Number(right.endedAt || 0) || String(left.id).localeCompare(String(right.id)))
706
+ .slice(-FINISHED_SUBAGENT_RUN_LIMIT)
647
707
  .map((run) => ({
648
708
  id: subagentText(run.id, 160),
649
709
  source: run.source === "foreground" ? "foreground" : "async",
650
710
  mode: subagentMode(run.mode),
651
- status: "running",
711
+ status: run.status,
652
712
  startedAt: Number.isFinite(run.startedAt) ? run.startedAt : Date.now(),
713
+ endedAt: Number.isFinite(run.endedAt) ? run.endedAt : Date.now(),
714
+ cancelReason: run.status === "cancelled" ? subagentText(run.cancelReason, 120) || undefined : undefined,
715
+ cancelNote: run.status === "cancelled" ? subagentText(run.cancelNote, 2000) || undefined : undefined,
716
+ cancelledBy: run.status === "cancelled" && run.cancelledBy === "user" ? "user" : undefined,
653
717
  agents: (Array.isArray(run.agents) ? run.agents : [])
654
- .filter((agent) => agent?.status === "running" && subagentAgentName(agent.name))
655
718
  .slice(0, 128)
656
- .map((agent, index) => ({
657
- id: subagentText(agent.id || `${run.id}:${index}`, 240),
658
- name: subagentAgentName(agent.name),
659
- status: "running",
660
- index: Number.isInteger(agent.index) ? agent.index : index,
661
- currentTool: subagentText(agent.currentTool, 120) || undefined,
662
- activityState: subagentText(agent.activityState, 80) || undefined,
663
- model: subagentModel(agent.model) || undefined,
664
- thinking: subagentThinking(agent.thinking) || subagentThinkingFromModel(agent.model) || undefined,
665
- nested: agent.nested === true,
666
- })),
719
+ .map((agent, index) => retainedSubagentAgent(agent, run, index))
720
+ .filter((agent) => agent.name),
667
721
  }));
722
+ }
723
+
724
+ function persistRetainedSubagentRuns() {
725
+ const runs = retainedSubagentRunsSnapshot();
726
+ const snapshot = { version: 1, runs };
727
+ const signature = JSON.stringify(snapshot);
728
+ if (signature === lastPersistedRetainedSubagentSignature) return;
729
+ lastPersistedRetainedSubagentSignature = signature;
730
+ pi.appendEntry(RETAINED_SUBAGENT_RUNS_TYPE, snapshot);
731
+ }
732
+
733
+ function restoreRetainedSubagentRuns(ctx) {
734
+ const saved = lastBranchConfig(ctx, RETAINED_SUBAGENT_RUNS_TYPE);
735
+ const rawRuns = saved?.version === 1 && Array.isArray(saved.runs) ? saved.runs.slice(-FINISHED_SUBAGENT_RUN_LIMIT) : [];
736
+ for (const rawRun of rawRuns) {
737
+ if (!rawRun || typeof rawRun !== "object") continue;
738
+ const id = subagentText(rawRun.id, 160);
739
+ const status = ["done", "failed", "cancelled"].includes(rawRun.status) ? rawRun.status : "";
740
+ if (!id || !status) continue;
741
+ const source = rawRun.source === "foreground" ? "foreground" : "async";
742
+ const agents = (Array.isArray(rawRun.agents) ? rawRun.agents : []).slice(0, 128)
743
+ .map((agent, index) => retainedSubagentAgent(agent, { id, status }, index))
744
+ .filter((agent) => agent.name);
745
+ const run = {
746
+ id,
747
+ source,
748
+ mode: subagentMode(rawRun.mode),
749
+ status,
750
+ startedAt: Number.isFinite(rawRun.startedAt) ? rawRun.startedAt : Date.now(),
751
+ endedAt: Number.isFinite(rawRun.endedAt) ? rawRun.endedAt : Date.now(),
752
+ cancelReason: status === "cancelled" ? subagentText(rawRun.cancelReason, 120) || undefined : undefined,
753
+ cancelNote: status === "cancelled" ? subagentText(rawRun.cancelNote, 2000) || undefined : undefined,
754
+ cancelledBy: status === "cancelled" && rawRun.cancelledBy === "user" ? "user" : undefined,
755
+ agents,
756
+ };
757
+ (source === "foreground" ? foregroundSubagentRuns : asyncSubagentRuns).set(id, run);
758
+ }
759
+ trimFinishedSubagentRuns();
760
+ lastPersistedRetainedSubagentSignature = JSON.stringify({ version: 1, runs: retainedSubagentRunsSnapshot() });
761
+ }
762
+
763
+ function finishSubagentRun(run, status = "done", fields = {}) {
764
+ if (!run || (run.status !== "running" && fields.force !== true)) return false;
765
+ const finalStatus = ["done", "failed", "cancelled"].includes(status) ? status : "done";
766
+ run.status = finalStatus;
767
+ run.endedAt = Date.now();
768
+ if (finalStatus === "cancelled") {
769
+ run.cancelledBy = "user";
770
+ run.cancelReason = fields.reason || undefined;
771
+ run.cancelNote = fields.note || undefined;
772
+ }
773
+ run.agents = (Array.isArray(run.agents) ? run.agents : []).map((agent) => ({
774
+ ...agent,
775
+ status: finalStatus === "cancelled" ? "cancelled" : "done",
776
+ }));
777
+ trimFinishedSubagentRuns();
778
+ persistRetainedSubagentRuns();
779
+ return true;
780
+ }
781
+
782
+ function publicSubagentRuns() {
783
+ const ordinaryRuns = ordinarySubagentRunEntries()
784
+ .map(({ run }) => {
785
+ const status = ["running", "done", "failed", "cancelled"].includes(run.status) ? run.status : "running";
786
+ const finalAgentStatus = status === "cancelled" ? "cancelled" : "done";
787
+ return {
788
+ id: subagentText(run.id, 160),
789
+ source: run.source === "foreground" ? "foreground" : "async",
790
+ mode: subagentMode(run.mode),
791
+ status,
792
+ startedAt: Number.isFinite(run.startedAt) ? run.startedAt : Date.now(),
793
+ endedAt: status === "running" ? undefined : Number.isFinite(run.endedAt) ? run.endedAt : undefined,
794
+ cancelReason: status === "cancelled" ? subagentText(run.cancelReason, 120) || undefined : undefined,
795
+ cancelNote: status === "cancelled" ? subagentText(run.cancelNote, 2000) || undefined : undefined,
796
+ cancelledBy: status === "cancelled" && run.cancelledBy === "user" ? "user" : undefined,
797
+ agents: (Array.isArray(run.agents) ? run.agents : [])
798
+ .filter((agent) => (status === "running" ? agent?.status === "running" : true) && subagentAgentName(agent?.name))
799
+ .slice(0, 128)
800
+ .map((agent, index) => ({
801
+ id: subagentText(agent.id || `${run.id}:${index}`, 240),
802
+ name: subagentAgentName(agent.name),
803
+ status: status === "running" ? "running" : finalAgentStatus,
804
+ index: Number.isInteger(agent.index) ? agent.index : index,
805
+ currentTool: subagentText(agent.currentTool, 120) || undefined,
806
+ activityState: subagentText(agent.activityState, 80) || undefined,
807
+ model: subagentModel(agent.model) || undefined,
808
+ thinking: subagentThinking(agent.thinking) || subagentThinkingFromModel(agent.model) || undefined,
809
+ nested: agent.nested === true,
810
+ })),
811
+ };
812
+ });
668
813
  const workflowRuns = [...workflowSubagentRuns.values()]
669
814
  .map((run) => ({
670
815
  id: run.id,
@@ -686,7 +831,7 @@ export default function webuiRpcHelper(pi) {
686
831
  })),
687
832
  }));
688
833
  return [...ordinaryRuns, ...workflowRuns]
689
- .filter((run) => run.id && run.agents.length > 0)
834
+ .filter((run) => run.id && (run.status !== "running" || run.agents.length > 0))
690
835
  .sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id));
691
836
  }
692
837
 
@@ -742,35 +887,44 @@ export default function webuiRpcHelper(pi) {
742
887
  }
743
888
  }
744
889
 
745
- function requestSubagentStatus(params = {}) {
890
+ function requestSubagentRpc(method, params = {}) {
746
891
  const requestId = `webui-${Date.now()}-${Math.random().toString(36).slice(2)}`;
747
892
  return new Promise((resolve, reject) => {
748
893
  let unsubscribe;
749
894
  const timeout = setTimeout(() => {
750
895
  if (typeof unsubscribe === "function") unsubscribe();
751
- reject(new Error("Timed out waiting for pi-subagents status RPC"));
896
+ reject(new Error(`Timed out waiting for pi-subagents ${method} RPC`));
752
897
  }, SUBAGENT_STATUS_RPC_TIMEOUT_MS);
753
898
  unsubscribe = pi.events.on(`${SUBAGENT_RPC_REPLY_PREFIX}${requestId}`, (reply) => {
754
899
  clearTimeout(timeout);
755
900
  if (typeof unsubscribe === "function") unsubscribe();
756
- if (reply?.success === false) reject(new Error(reply.error?.message || "pi-subagents status RPC failed"));
901
+ if (reply?.success === false) reject(new Error(reply.error?.message || `pi-subagents ${method} RPC failed`));
757
902
  else resolve(reply?.data || {});
758
903
  });
759
904
  pi.events.emit(SUBAGENT_RPC_REQUEST_EVENT, {
760
905
  version: SUBAGENT_RPC_VERSION,
761
906
  requestId,
762
- method: "status",
907
+ method,
763
908
  params,
764
909
  source: { extension: "pi-package-webui" },
765
910
  });
766
911
  });
767
912
  }
768
913
 
914
+ function requestSubagentStatus(params = {}) {
915
+ return requestSubagentRpc("status", params);
916
+ }
917
+
918
+ function findTrackedSubagentRun(runId) {
919
+ const entry = ordinarySubagentRunEntries().find((candidate) => candidate.run?.id === runId);
920
+ if (!entry) throw new Error(`Subagent run not found: ${runId}`);
921
+ return entry;
922
+ }
923
+
769
924
  function findTrackedSubagent(runId, agentId) {
770
- const run = [...foregroundSubagentRuns.values(), ...asyncSubagentRuns.values()].find((candidate) => candidate?.id === runId);
771
- if (!run) throw new Error(`Running subagent run not found: ${runId}`);
925
+ const { run } = findTrackedSubagentRun(runId);
772
926
  const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate?.id === agentId);
773
- if (!agent) throw new Error(`Running subagent not found: ${agentId}`);
927
+ if (!agent) throw new Error(`Subagent not found: ${agentId}`);
774
928
  return { run, agent };
775
929
  }
776
930
 
@@ -849,6 +1003,9 @@ export default function webuiRpcHelper(pi) {
849
1003
  if (!step) return;
850
1004
  agent.model = subagentModel(step.model) || agent.model;
851
1005
  agent.thinking = subagentThinking(step.thinking) || subagentThinkingFromModel(step.model) || agent.thinking;
1006
+ const steps = Array.isArray(status.steps) ? status.steps : [];
1007
+ const sessionFile = subagentText(step.sessionFile || (steps.length === 1 ? status.sessionFile : ""), 4096);
1008
+ if (sessionFile && path.isAbsolute(sessionFile) && path.extname(sessionFile) === ".jsonl") agent.sessionFile = path.normalize(sessionFile);
852
1009
  }
853
1010
 
854
1011
  async function enrichAsyncSubagentRun(run) {
@@ -901,7 +1058,33 @@ export default function webuiRpcHelper(pi) {
901
1058
  const agentId = subagentText(payload.agentId, 240);
902
1059
  if (!runId || !agentId) throw new Error("Subagent output requires runId and agentId");
903
1060
  const { run, agent } = findTrackedSubagent(runId, agentId);
904
- if (run.source === "foreground") return subagentOutputSnapshotFromAgent(run, agent);
1061
+ if (run.source === "foreground") return subagentOutputSnapshotFromAgent(run, agent, { updatedAt: run.endedAt });
1062
+ if (run.status !== "running") {
1063
+ if (!agent.sessionFile && agent.asyncDir) {
1064
+ try {
1065
+ const status = JSON.parse(readFileSync(path.join(agent.asyncDir, "status.json"), "utf8"));
1066
+ const targetRunId = subagentText(agent.targetRunId || run.id, 160);
1067
+ if (!status?.runId || status.runId === targetRunId) {
1068
+ const step = subagentStatusStepForAgent(status, agent);
1069
+ const steps = Array.isArray(status?.steps) ? status.steps : [];
1070
+ const sessionFile = subagentText(step?.sessionFile || (steps.length === 1 ? status.sessionFile : ""), 4096);
1071
+ if (sessionFile && path.isAbsolute(sessionFile) && path.extname(sessionFile) === ".jsonl") agent.sessionFile = path.normalize(sessionFile);
1072
+ }
1073
+ } catch {
1074
+ // Retained metadata remains viewable even when its async status locator is stale.
1075
+ }
1076
+ }
1077
+ const transcriptOutput = subagentTranscriptOutput(agent.sessionFile);
1078
+ const hasLocator = !!(agent.sessionFile && existsSync(agent.sessionFile));
1079
+ return subagentOutputSnapshotFromAgent(run, agent, {
1080
+ recentOutput: transcriptOutput.recentOutput.length ? transcriptOutput.recentOutput : agent.recentOutput,
1081
+ transcript: transcriptOutput.transcript,
1082
+ updatedAt: run.endedAt,
1083
+ error: !hasLocator && !(Array.isArray(agent.recentOutput) && agent.recentOutput.length)
1084
+ ? "Retained subagent output is unavailable because its child output locator is missing."
1085
+ : undefined,
1086
+ });
1087
+ }
905
1088
 
906
1089
  const targetRunId = subagentText(agent.targetRunId || run.id, 160);
907
1090
  let asyncDir = subagentText(agent.asyncDir || (targetRunId === run.id ? run.asyncDir : ""), 4096);
@@ -921,7 +1104,9 @@ export default function webuiRpcHelper(pi) {
921
1104
  ? steps.find((candidate) => candidate?.agent === agent.name && ["running", "queued", "pending"].includes(candidate?.status)) || steps[status.currentStep] || steps[0]
922
1105
  : steps[agent.index] || steps.find((candidate) => candidate?.agent === agent.name && ["running", "queued", "pending"].includes(candidate?.status));
923
1106
  if (!step) return subagentOutputSnapshotFromAgent(run, agent, { status: status?.state, updatedAt: status?.lastUpdate });
924
- const transcriptOutput = subagentTranscriptOutput(step.sessionFile || (steps.length === 1 ? status.sessionFile : undefined));
1107
+ const sessionFile = subagentText(step.sessionFile || (steps.length === 1 ? status.sessionFile : ""), 4096);
1108
+ if (sessionFile && path.isAbsolute(sessionFile) && path.extname(sessionFile) === ".jsonl") agent.sessionFile = path.normalize(sessionFile);
1109
+ const transcriptOutput = subagentTranscriptOutput(agent.sessionFile);
925
1110
  return subagentOutputSnapshotFromAgent(run, agent, {
926
1111
  ...step,
927
1112
  recentOutput: transcriptOutput.recentOutput.length ? transcriptOutput.recentOutput : step.recentOutput,
@@ -943,21 +1128,28 @@ export default function webuiRpcHelper(pi) {
943
1128
  subagentBridgeAvailable = true;
944
1129
  const parsedRuns = parseSubagentStatusText(data?.text, asyncSubagentRuns);
945
1130
  const nextIds = new Set(parsedRuns.map((run) => run.id));
946
- for (const id of asyncSubagentRuns.keys()) {
947
- const run = asyncSubagentRuns.get(id);
948
- if (!nextIds.has(id) && Date.now() - Number(run?.eventSeenAt || 0) > SUBAGENT_STATUS_POLL_MS * 2) asyncSubagentRuns.delete(id);
1131
+ for (const run of asyncSubagentRuns.values()) {
1132
+ if (run?.status === "running" && !nextIds.has(run.id) && Date.now() - Number(run.eventSeenAt || 0) > SUBAGENT_STATUS_POLL_MS * 2) {
1133
+ finishSubagentRun(run, "done");
1134
+ }
949
1135
  }
950
1136
  for (const run of parsedRuns) {
951
1137
  const previous = asyncSubagentRuns.get(run.id);
1138
+ if (previous?.status && previous.status !== "running") continue;
952
1139
  const previousAgents = Array.isArray(previous?.agents) ? previous.agents : [];
1140
+ const runningAgents = run.agents.map((agent) => ({
1141
+ ...previousAgents.find((candidate) => candidate.index === agent.index && candidate.name === agent.name),
1142
+ ...agent,
1143
+ status: "running",
1144
+ }));
1145
+ const completedAgents = previousAgents
1146
+ .filter((candidate) => !runningAgents.some((agent) => agent.index === candidate.index && agent.name === candidate.name))
1147
+ .map((agent) => ({ ...agent, status: agent.status === "running" ? "done" : agent.status }));
953
1148
  const merged = {
954
1149
  ...previous,
955
1150
  ...run,
956
1151
  eventSeenAt: previous?.eventSeenAt || Date.now(),
957
- agents: run.agents.map((agent) => ({
958
- ...previousAgents.find((candidate) => candidate.index === agent.index && candidate.name === agent.name),
959
- ...agent,
960
- })),
1152
+ agents: [...completedAgents, ...runningAgents],
961
1153
  };
962
1154
  await enrichAsyncSubagentRun(merged);
963
1155
  asyncSubagentRuns.set(run.id, merged);
@@ -1012,7 +1204,6 @@ export default function webuiRpcHelper(pi) {
1012
1204
  : [];
1013
1205
  agents = names.map((name, index) => ({ id: `${id}:${index}:${subagentAgentName(name)}`, name: subagentAgentName(name), status: "running", index, nested: false })).filter((agent) => agent.name);
1014
1206
  }
1015
- foregroundSubagentRuns.clear();
1016
1207
  asyncSubagentRuns.set(id, {
1017
1208
  id,
1018
1209
  source: "async",
@@ -1028,7 +1219,8 @@ export default function webuiRpcHelper(pi) {
1028
1219
  }),
1029
1220
  pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, (value) => {
1030
1221
  const id = subagentText(value?.id || value?.runId, 160);
1031
- if (id) asyncSubagentRuns.delete(id);
1222
+ const run = id ? [...asyncSubagentRuns.values()].find((candidate) => candidate?.id === id) : undefined;
1223
+ if (run) finishSubagentRun(run, value?.status === "failed" || value?.state === "failed" || value?.error ? "failed" : "done");
1032
1224
  publishSubagentStatus();
1033
1225
  }),
1034
1226
  pi.events.on(SUBAGENT_GATE_UPDATE_EVENT, (value) => {
@@ -1189,6 +1381,50 @@ export default function webuiRpcHelper(pi) {
1189
1381
  };
1190
1382
  }
1191
1383
 
1384
+ function dismissSubagentRun(payload = {}) {
1385
+ const runId = subagentText(payload.runId, 160);
1386
+ if (!runId) throw new Error("Subagent dismiss requires runId");
1387
+ const entry = findTrackedSubagentRun(runId);
1388
+ if (entry.run.status === "running") throw new Error(`Cannot dismiss running subagent run: ${runId}`);
1389
+ entry.runs.delete(entry.key);
1390
+ persistRetainedSubagentRuns();
1391
+ publishSubagentStatus();
1392
+ return { runId, dismissed: true };
1393
+ }
1394
+
1395
+ async function cancelSubagentRun(ctx, payload = {}) {
1396
+ const runId = subagentText(payload.runId, 160);
1397
+ if (!runId) throw new Error("Subagent cancel requires runId");
1398
+ const { run } = findTrackedSubagentRun(runId);
1399
+ if (run.status !== "running") throw new Error(`Subagent run is already finished: ${runId}`);
1400
+ const reason = subagentText(payload.reason, 120) || undefined;
1401
+ const note = subagentText(payload.note, 2000) || undefined;
1402
+ const rpcMethod = run.source === "foreground" ? "interrupt" : "stop";
1403
+ const controlRunId = run.source === "foreground" ? subagentText(run.controlRunId, 160) : run.id;
1404
+ if (!controlRunId) throw new Error(`Subagent run is not ready to be cancelled yet: ${runId}`);
1405
+ await requestSubagentRpc(rpcMethod, { id: controlRunId });
1406
+ finishSubagentRun(run, "cancelled", { reason, note, force: true });
1407
+ const agentNames = (Array.isArray(run.agents) ? run.agents : [])
1408
+ .map((agent) => subagentAgentName(agent?.name))
1409
+ .filter(Boolean)
1410
+ .slice(0, 128);
1411
+ const content = [
1412
+ `The user cancelled subagent run ${run.id} (${agentNames.join(", ") || "subagent"}) from the Web UI.`,
1413
+ ...(reason ? [`Reason: ${reason}`] : []),
1414
+ ...(note ? [`Note: ${note}`] : []),
1415
+ "The run was stopped or interrupted at the user's request and should not be automatically retried without asking.",
1416
+ ].join("\n");
1417
+ const isIdle = ctx.isIdle();
1418
+ pi.sendMessage({
1419
+ customType: "webui-subagent-cancelled",
1420
+ content,
1421
+ display: true,
1422
+ details: { runId: run.id, agentNames, reason, note },
1423
+ }, isIdle ? undefined : { deliverAs: "steer" });
1424
+ publishSubagentStatus();
1425
+ return { runId: run.id, state: "cancelled", delivery: isIdle ? "context" : "steer", rpcMethod };
1426
+ }
1427
+
1192
1428
  async function executeAction(action, payload, ctx) {
1193
1429
  switch (action) {
1194
1430
  case "tools-state":
@@ -1203,8 +1439,14 @@ export default function webuiRpcHelper(pi) {
1203
1439
  return transferAppRunnerContext(ctx, payload);
1204
1440
  case "subagent-output":
1205
1441
  return subagentOutputSnapshot(payload);
1442
+ case "subagent-dismiss":
1443
+ return dismissSubagentRun(payload);
1444
+ case "subagent-cancel":
1445
+ return cancelSubagentRun(ctx, payload);
1206
1446
  case "queue-remove":
1207
1447
  return removeQueuedPrompt(payload);
1448
+ case "queue-mutate":
1449
+ return mutateQueuedFollowUp(payload);
1208
1450
  default:
1209
1451
  throw new Error(`Unknown ${HELPER_COMMAND} action: ${action}`);
1210
1452
  }
@@ -1236,6 +1478,7 @@ export default function webuiRpcHelper(pi) {
1236
1478
  asyncSubagentRuns.clear();
1237
1479
  workflowSubagentRuns.clear();
1238
1480
  subagentGates.clear();
1481
+ restoreRetainedSubagentRuns(ctx);
1239
1482
  lastPublishedSubagentSignature = "";
1240
1483
  publishSubagentStatus();
1241
1484
  scheduleSubagentStatusPoll(subagentPollGeneration, 0);
@@ -1246,6 +1489,11 @@ export default function webuiRpcHelper(pi) {
1246
1489
  restoreToolsFromBranch(ctx, globalDefaults);
1247
1490
  restoreSkillsFromBranch(ctx, globalDefaults);
1248
1491
  subagentContext = ctx;
1492
+ foregroundSubagentRuns.clear();
1493
+ asyncSubagentRuns.clear();
1494
+ restoreRetainedSubagentRuns(ctx);
1495
+ lastPublishedSubagentSignature = "";
1496
+ publishSubagentStatus();
1249
1497
  });
1250
1498
 
1251
1499
  pi.on("tool_execution_start", (event, ctx) => {
@@ -1269,6 +1517,7 @@ export default function webuiRpcHelper(pi) {
1269
1517
  mode: Array.isArray(event.args?.chain) ? "chain" : Array.isArray(event.args?.tasks) ? "parallel" : "single",
1270
1518
  status: "running",
1271
1519
  startedAt: Date.now(),
1520
+ controlRunId: undefined,
1272
1521
  agents: initialAgents,
1273
1522
  });
1274
1523
  publishSubagentStatus();
@@ -1278,29 +1527,39 @@ export default function webuiRpcHelper(pi) {
1278
1527
  if (event.toolName !== "subagent") return;
1279
1528
  const id = subagentText(event.toolCallId, 160);
1280
1529
  const run = foregroundSubagentRuns.get(id);
1281
- if (!run) return;
1530
+ if (!run || run.status !== "running") return;
1282
1531
  subagentContext = ctx;
1283
1532
  const details = event.partialResult?.details || event.result?.details;
1284
1533
  const agents = subagentRunningAgentsFromDetails(details, details?.runId || id);
1285
1534
  if (agents.length) {
1286
- run.agents = agents.map((agent) => {
1535
+ const runningAgents = agents.map((agent) => {
1287
1536
  const previous = run.agents.find((candidate) => candidate.index === agent.index && candidate.name === agent.name);
1288
1537
  return {
1289
1538
  ...previous,
1290
1539
  ...agent,
1540
+ status: "running",
1291
1541
  model: agent.model || previous?.model,
1292
1542
  thinking: agent.thinking || previous?.thinking,
1293
1543
  };
1294
1544
  });
1545
+ const completedAgents = run.agents
1546
+ .filter((candidate) => !runningAgents.some((agent) => agent.index === candidate.index && agent.name === candidate.name))
1547
+ .map((agent) => ({ ...agent, status: agent.status === "running" ? "done" : agent.status }));
1548
+ run.agents = [...completedAgents, ...runningAgents];
1549
+ }
1550
+ if (details?.runId) {
1551
+ run.controlRunId = subagentText(details.runId, 160);
1552
+ run.id = run.controlRunId;
1295
1553
  }
1296
- if (details?.runId) run.id = subagentText(details.runId, 160);
1297
1554
  run.mode = subagentMode(details?.mode, run.mode);
1298
1555
  publishSubagentStatus();
1299
1556
  });
1300
1557
 
1301
1558
  pi.on("tool_execution_end", (event) => {
1302
1559
  if (event.toolName !== "subagent") return;
1303
- foregroundSubagentRuns.delete(subagentText(event.toolCallId, 160));
1560
+ const toolCallId = subagentText(event.toolCallId, 160);
1561
+ const run = [...foregroundSubagentRuns.values()].find((candidate) => candidate?.id === toolCallId) || foregroundSubagentRuns.get(toolCallId);
1562
+ if (run) finishSubagentRun(run, event.isError === true || event.result?.isError === true ? "failed" : "done");
1304
1563
  publishSubagentStatus();
1305
1564
  });
1306
1565