@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
package/bin/pi-webui.mjs CHANGED
@@ -14,6 +14,13 @@ import { brotliCompress, constants as zlibConstants, gzip } from "node:zlib";
14
14
  import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendil-works/pi-coding-agent";
15
15
  import { authProvidersPayload, createAuthContext, logoutStoredProvider } from "../lib/auth-actions.mjs";
16
16
  import { resolveCodexUsageAuth } from "../lib/codex-usage-auth.mjs";
17
+ import { resolveScopedModelsFromPatterns } from "../lib/scoped-models.mjs";
18
+ import {
19
+ deleteWebuiWorkspace,
20
+ getWebuiWorkspace,
21
+ listWebuiWorkspaces,
22
+ saveWebuiWorkspace,
23
+ } from "../lib/webui-workspaces.mjs";
17
24
  import { nativeExportDownloadPayload } from "../lib/native-export-payload.mjs";
18
25
  import { discoverStartAttachRpcSupervisor } from "../lib/rpc-supervisor-client.mjs";
19
26
  import { readSupervisorState, supervisorPaths } from "../lib/rpc-supervisor-state.mjs";
@@ -181,6 +188,7 @@ const FILE_SEARCH_MAX_SCANNED = 12_000;
181
188
  const FILE_SEARCH_MAX_DEPTH = 8;
182
189
  const FILE_SEARCH_EXCLUDED_DIRS = new Set([".git", "node_modules"]);
183
190
  const PROMPT_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
191
+ const QUEUE_MUTATION_MAX_ITEMS = 512;
184
192
  const VOICE_AUDIO_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
185
193
  const VOICE_AUDIO_JSON_BODY_LIMIT_BYTES = Math.ceil(VOICE_AUDIO_BODY_LIMIT_BYTES * 1.4) + 1024 * 1024;
186
194
  const VOICE_PROVIDER_TIMEOUT_MS = Math.max(1000, Number.parseInt(process.env.PI_VOICE_PROVIDER_TIMEOUT_MS || "120000", 10) || 120000);
@@ -4660,48 +4668,12 @@ async function configuredScopedModelPatterns(cwd = options.cwd) {
4660
4668
  return { patterns: [], source: "none" };
4661
4669
  }
4662
4670
 
4663
- function stripThinkingSuffix(pattern) {
4664
- const text = String(pattern || "").trim();
4665
- const slashIndex = text.indexOf("/");
4666
- const colonIndex = text.lastIndexOf(":");
4667
- if (colonIndex > (slashIndex === -1 ? -1 : slashIndex)) return text.slice(0, colonIndex);
4668
- return text;
4669
- }
4670
-
4671
- function globToRegExp(pattern) {
4672
- const escaped = pattern.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
4673
- return new RegExp(`^${escaped}$`, "i");
4674
- }
4675
-
4676
- function modelMatchesPattern(model, pattern) {
4677
- const clean = stripThinkingSuffix(pattern).toLowerCase();
4678
- if (!clean) return false;
4679
- const full = `${model.provider}/${model.id}`.toLowerCase();
4680
- const id = String(model.id || "").toLowerCase();
4681
- if (/[?*\[]/.test(clean)) return globToRegExp(clean).test(full) || globToRegExp(clean).test(id);
4682
- return full === clean || id === clean || full.includes(clean) || id.includes(clean);
4683
- }
4684
-
4685
- function resolveScopedModelsFromPatterns(patterns, models) {
4686
- const scoped = [];
4687
- const seen = new Set();
4688
- for (const pattern of patterns || []) {
4689
- for (const model of models || []) {
4690
- const key = `${model.provider}/${model.id}`;
4691
- if (seen.has(key) || !modelMatchesPattern(model, pattern)) continue;
4692
- seen.add(key);
4693
- scoped.push(model);
4694
- }
4695
- }
4696
- return scoped;
4697
- }
4698
-
4699
4671
  async function getScopedModelData(tab) {
4700
4672
  const { patterns, source } = await configuredScopedModelPatterns(tab.cwd);
4701
4673
  if (!patterns.length) return { models: [], patterns, source };
4702
4674
  const response = await safeRpcResponse(tab, { type: "get_available_models" });
4703
4675
  if (response.success === false) throw makeHttpError(400, response.error || "failed to load available models");
4704
- return { models: resolveScopedModelsFromPatterns(patterns, response.data?.models || []), patterns, source, rpcRunning: response.rpcRunning !== false };
4676
+ return { models: await resolveScopedModelsFromPatterns(patterns, response.data?.models || []), patterns, source, rpcRunning: response.rpcRunning !== false };
4705
4677
  }
4706
4678
 
4707
4679
  function modelKey(model) {
@@ -4713,7 +4685,7 @@ async function cycleTabModel(tab, direction = "forward") {
4713
4685
  if (availableResponse.success === false) return availableResponse;
4714
4686
  const allModels = Array.isArray(availableResponse.data?.models) ? availableResponse.data.models : [];
4715
4687
  const { patterns, source } = await configuredScopedModelPatterns(tab.cwd);
4716
- const scopedModels = patterns.length ? resolveScopedModelsFromPatterns(patterns, allModels) : [];
4688
+ const scopedModels = patterns.length ? await resolveScopedModelsFromPatterns(patterns, allModels) : [];
4717
4689
  const candidates = scopedModels.length ? scopedModels : allModels;
4718
4690
  if (!candidates.length) throw makeHttpError(400, "No models are available to cycle.");
4719
4691
 
@@ -7654,7 +7626,7 @@ async function readBundledThemes() {
7654
7626
  function normalizeStaticPath(urlPath) {
7655
7627
  if (urlPath === "/") return "index.html";
7656
7628
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
7657
- if (!["index.html", "app.js", "fast-output-live.mjs", "subagent-launch-slot-state.mjs", "subagent-gate-visibility.mjs", "workflow-status-stack.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7629
+ if (!["index.html", "app.js", "issue-wizard-state.mjs", "issue-bot-client.mjs", "fast-output-live.mjs", "subagent-launch-slot-state.mjs", "subagent-gate-visibility.mjs", "workflow-status-stack.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
7658
7630
  return name;
7659
7631
  }
7660
7632
 
@@ -7752,7 +7724,7 @@ async function serveStatic(req, res, url) {
7752
7724
  function requestBodyLimitForPath(pathname) {
7753
7725
  if (pathname === "/api/attachments") return UPLOAD_BODY_LIMIT_BYTES;
7754
7726
  if (pathname === "/api/files/content") return FILE_VIEWER_BODY_LIMIT_BYTES;
7755
- if (["/api/prompt", "/api/steer", "/api/follow-up"].includes(pathname)) return PROMPT_BODY_LIMIT_BYTES;
7727
+ if (["/api/prompt", "/api/steer", "/api/follow-up", "/api/queue/mutate"].includes(pathname)) return PROMPT_BODY_LIMIT_BYTES;
7756
7728
  return BODY_LIMIT_BYTES;
7757
7729
  }
7758
7730
 
@@ -8275,6 +8247,7 @@ let rpcSupervisor = null;
8275
8247
  let rpcSupervisorSnapshot = null;
8276
8248
  let rpcSupervisorEventUnsubscribe = null;
8277
8249
  let rpcSupervisorSequenceState = null;
8250
+ let workspaceLoadInProgress = false;
8278
8251
 
8279
8252
  function markRpcSupervisorDiscontinuity(reason) {
8280
8253
  if (!rpcSupervisorSnapshot) return;
@@ -8410,13 +8383,13 @@ async function initializeRpcSupervisor() {
8410
8383
  });
8411
8384
  }
8412
8385
 
8413
- function supervisedTabMetadata(tab) {
8386
+ function supervisedTabMetadata(tab, { cwd = tab.cwd } = {}) {
8414
8387
  return {
8415
8388
  index: tab.index,
8416
8389
  title: tab.title,
8417
8390
  titleSource: tab.titleSource,
8418
8391
  conversationStarted: tab.conversationStarted === true,
8419
- cwd: tab.cwd,
8392
+ cwd,
8420
8393
  sessionFile: tabRestorableSessionFile(tab),
8421
8394
  gitWorkspace: tab.gitWorkspace || null,
8422
8395
  createdAt: tab.createdAt,
@@ -8424,7 +8397,9 @@ function supervisedTabMetadata(tab) {
8424
8397
  }
8425
8398
 
8426
8399
  function scheduleSupervisorMetadataUpdate(tab) {
8427
- if (!(tab?.rpc instanceof SupervisorPiRpcProcess) || tab.supervisorMetadataUpdateQueued) return;
8400
+ if (!(tab?.rpc instanceof SupervisorPiRpcProcess)) return;
8401
+ if (tab.cwdChangeInProgress) return;
8402
+ if (tab.supervisorMetadataUpdateQueued) return;
8428
8403
  tab.supervisorMetadataUpdateQueued = true;
8429
8404
  queueMicrotask(() => {
8430
8405
  tab.supervisorMetadataUpdateQueued = false;
@@ -8506,8 +8481,9 @@ function responseWithPendingThinking(tab, response) {
8506
8481
  }
8507
8482
 
8508
8483
  function eventForTabClients(tab, event) {
8484
+ const decorated = event?.type === "queue_update" ? { ...event, source: "pi-runtime" } : event;
8509
8485
  return {
8510
- ...rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, event)),
8486
+ ...rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, decorated)),
8511
8487
  tabId: tab.id,
8512
8488
  tabTitle: tab.title,
8513
8489
  tabActivity: tabActivitySnapshot(tab),
@@ -8538,6 +8514,7 @@ function createTabActivity(now = new Date().toISOString()) {
8538
8514
  return {
8539
8515
  status: "idle",
8540
8516
  isWorking: false,
8517
+ runStarted: false,
8541
8518
  completionSerial: 0,
8542
8519
  lastChangedAt: now,
8543
8520
  lastStartedAt: null,
@@ -8612,14 +8589,18 @@ function normalizeWebuiSubagentPayload(value) {
8612
8589
  if (!rawRun || typeof rawRun !== "object") continue;
8613
8590
  const id = normalizeWebuiSubagentText(rawRun.id, 160);
8614
8591
  if (!id) continue;
8592
+ const status = ["running", "done", "failed", "cancelled"].includes(rawRun.status) ? rawRun.status : "running";
8615
8593
  const agents = [];
8616
8594
  for (const rawAgent of Array.isArray(rawRun.agents) ? rawRun.agents.slice(0, WEBUI_SUBAGENT_AGENT_LIMIT) : []) {
8617
8595
  const name = normalizeWebuiSubagentText(rawAgent?.name, 160);
8618
- if (!name || rawAgent?.status !== "running") continue;
8596
+ const agentStatus = ["running", "done", "failed", "cancelled"].includes(rawAgent?.status)
8597
+ ? rawAgent.status
8598
+ : status === "cancelled" ? "cancelled" : status === "running" ? "running" : "done";
8599
+ if (!name || (status === "running" && agentStatus !== "running")) continue;
8619
8600
  agents.push({
8620
8601
  id: normalizeWebuiSubagentText(rawAgent.id || `${id}:${agents.length}`, 240),
8621
8602
  name,
8622
- status: "running",
8603
+ status: agentStatus,
8623
8604
  index: Number.isInteger(rawAgent.index) ? rawAgent.index : agents.length,
8624
8605
  currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
8625
8606
  activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
@@ -8628,13 +8609,17 @@ function normalizeWebuiSubagentPayload(value) {
8628
8609
  nested: rawAgent.nested === true,
8629
8610
  });
8630
8611
  }
8631
- if (!agents.length) continue;
8612
+ if (status === "running" && !agents.length) continue;
8632
8613
  runs.push({
8633
8614
  id,
8634
8615
  source: normalizeWebuiSubagentSource(rawRun.source),
8635
8616
  mode: ["single", "parallel", "chain"].includes(rawRun.mode) ? rawRun.mode : "single",
8636
- status: "running",
8617
+ status,
8637
8618
  startedAt: Number.isFinite(rawRun.startedAt) ? rawRun.startedAt : Date.now(),
8619
+ endedAt: status === "running" ? undefined : Number.isFinite(rawRun.endedAt) ? rawRun.endedAt : undefined,
8620
+ cancelReason: status === "cancelled" ? normalizeWebuiSubagentText(rawRun.cancelReason, 120) || undefined : undefined,
8621
+ cancelNote: status === "cancelled" ? normalizeWebuiSubagentText(rawRun.cancelNote, 2000) || undefined : undefined,
8622
+ cancelledBy: status === "cancelled" && rawRun.cancelledBy === "user" ? "user" : undefined,
8638
8623
  agents: agents.sort((a, b) => a.index - b.index || a.name.localeCompare(b.name)),
8639
8624
  });
8640
8625
  }
@@ -8842,6 +8827,75 @@ function compactionQueueForTab(tab) {
8842
8827
  return tab.compactionQueue;
8843
8828
  }
8844
8829
 
8830
+ function compactionQueueRevision(tab) {
8831
+ if (!Number.isSafeInteger(tab.compactionQueueRevision) || tab.compactionQueueRevision < 0) tab.compactionQueueRevision = 0;
8832
+ return tab.compactionQueueRevision;
8833
+ }
8834
+
8835
+ function advanceCompactionQueueRevision(tab) {
8836
+ tab.compactionQueueRevision = compactionQueueRevision(tab) + 1;
8837
+ return tab.compactionQueueRevision;
8838
+ }
8839
+
8840
+ function queueMutationText(value, label, { allowBlank = false, normalize = true } = {}) {
8841
+ if (typeof value !== "string") throw makeHttpError(400, `${label} must be a string`);
8842
+ if (Buffer.byteLength(value, "utf8") > PROMPT_BODY_LIMIT_BYTES) throw makeHttpError(413, `${label} is too large`);
8843
+ if (!allowBlank && !value.trim()) throw makeHttpError(400, `${label} is required`);
8844
+ if (value.includes("\0")) throw makeHttpError(400, `${label} contains a NUL byte`);
8845
+ return normalize ? value.trim() : value;
8846
+ }
8847
+
8848
+ function queueMutationExpected(body) {
8849
+ const expected = body?.expected;
8850
+ if (!expected || typeof expected !== "object" || !Array.isArray(expected.steering) || !Array.isArray(expected.followUp)) {
8851
+ throw makeHttpError(400, "Queue mutation requires complete expected steering and followUp arrays");
8852
+ }
8853
+ if (expected.steering.length > QUEUE_MUTATION_MAX_ITEMS || expected.followUp.length > QUEUE_MUTATION_MAX_ITEMS) {
8854
+ throw makeHttpError(400, `Queue mutation expected arrays may contain at most ${QUEUE_MUTATION_MAX_ITEMS} items`);
8855
+ }
8856
+ return {
8857
+ steering: expected.steering.map((item, index) => queueMutationText(item, `expected.steering[${index}]`, { normalize: false })),
8858
+ followUp: expected.followUp.map((item, index) => queueMutationText(item, `expected.followUp[${index}]`, { normalize: false })),
8859
+ };
8860
+ }
8861
+
8862
+ function queueMutationIndex(value, label) {
8863
+ if (!Number.isSafeInteger(value) || value < 0) throw makeHttpError(400, `${label} must be a non-negative integer`);
8864
+ return value;
8865
+ }
8866
+
8867
+ function queueMutationRequest(body) {
8868
+ if (!body || typeof body !== "object") throw makeHttpError(400, "Queue mutation body must be an object");
8869
+ const source = String(body.source || "");
8870
+ if (source !== "pi-runtime" && source !== "webui-compaction") throw makeHttpError(400, "Queue mutation source must be pi-runtime or webui-compaction");
8871
+ if (body.kind !== "followUp") throw makeHttpError(400, "Queue mutation kind must be followUp");
8872
+ const operation = body.operation;
8873
+ if (!operation || typeof operation !== "object") throw makeHttpError(400, "Queue mutation operation is required");
8874
+ const expectedText = queueMutationText(operation.expectedText, "operation.expectedText", { normalize: false });
8875
+ const request = {
8876
+ source,
8877
+ kind: "followUp",
8878
+ expected: queueMutationExpected(body),
8879
+ operation: { type: String(operation.type || ""), expectedText },
8880
+ };
8881
+ if (request.operation.type === "edit") {
8882
+ request.operation.index = queueMutationIndex(operation.index, "operation.index");
8883
+ request.operation.text = queueMutationText(operation.text, "operation.text");
8884
+ } else if (request.operation.type === "move") {
8885
+ request.operation.from = queueMutationIndex(operation.from, "operation.from");
8886
+ request.operation.to = queueMutationIndex(operation.to, "operation.to");
8887
+ } else {
8888
+ throw makeHttpError(400, "Queue mutation operation type must be edit or move");
8889
+ }
8890
+ if (source === "webui-compaction") {
8891
+ if (!Number.isSafeInteger(body.revision) || body.revision < 0) throw makeHttpError(400, "Compaction queue mutation requires a non-negative revision");
8892
+ request.revision = body.revision;
8893
+ } else if (Object.hasOwn(body, "revision")) {
8894
+ throw makeHttpError(400, "Pi runtime queue mutation must not include a revision");
8895
+ }
8896
+ return request;
8897
+ }
8898
+
8845
8899
  function queueableCompactionCommand(command) {
8846
8900
  return ["prompt", "steer", "follow_up"].includes(command?.type) && !!String(command.message || "").trim();
8847
8901
  }
@@ -8861,7 +8915,7 @@ function compactQueuedCommand(command) {
8861
8915
  return queued;
8862
8916
  }
8863
8917
 
8864
- function compactionQueueEvent(tab, extra = {}) {
8918
+ function compactionQueueSnapshot(tab) {
8865
8919
  const queue = compactionQueueForTab(tab);
8866
8920
  const steering = [];
8867
8921
  const followUp = [];
@@ -8871,20 +8925,67 @@ function compactionQueueEvent(tab, extra = {}) {
8871
8925
  if (item.command.mode === "followUp") followUp.push(message);
8872
8926
  else steering.push(message);
8873
8927
  }
8928
+ return {
8929
+ source: "webui-compaction",
8930
+ revision: compactionQueueRevision(tab),
8931
+ steering,
8932
+ followUp,
8933
+ draining: tab.compactionQueueDraining === true,
8934
+ };
8935
+ }
8936
+
8937
+ function compactionQueueEvent(tab, extra = {}) {
8938
+ const queue = compactionQueueForTab(tab);
8874
8939
  return {
8875
8940
  type: "webui_compaction_queue_update",
8876
8941
  tabId: tab.id,
8877
8942
  tabTitle: tab.title,
8878
8943
  queueLength: queue.length,
8879
8944
  pendingMessageCount: queue.length,
8880
- steering,
8881
- followUp,
8882
- draining: tab.compactionQueueDraining === true,
8945
+ ...compactionQueueSnapshot(tab),
8883
8946
  tabActivity: tabActivitySnapshot(tab),
8884
8947
  ...extra,
8885
8948
  };
8886
8949
  }
8887
8950
 
8951
+ function sameQueueSnapshot(expected, current) {
8952
+ return expected.steering.length === current.steering.length
8953
+ && expected.followUp.length === current.followUp.length
8954
+ && expected.steering.every((item, index) => item === current.steering[index])
8955
+ && expected.followUp.every((item, index) => item === current.followUp[index]);
8956
+ }
8957
+
8958
+ function compactionFollowUpSlots(queue) {
8959
+ return queue.flatMap((item, index) => item?.command?.mode === "followUp" && String(item.command.message || "").trim() ? [index] : []);
8960
+ }
8961
+
8962
+ function mutateCompactionFollowUpQueue(tab, request) {
8963
+ const queue = compactionQueueForTab(tab);
8964
+ const current = compactionQueueSnapshot(tab);
8965
+ const failed = (reason) => ({ mutated: false, reason, source: "webui-compaction", queue: compactionQueueSnapshot(tab) });
8966
+ if (current.draining) return failed("queue-draining");
8967
+ if (request.revision !== current.revision || !sameQueueSnapshot(request.expected, current)) return failed("queue-changed");
8968
+
8969
+ const slots = compactionFollowUpSlots(queue);
8970
+ const operation = request.operation;
8971
+ if (operation.type === "edit") {
8972
+ if (operation.index >= slots.length || current.followUp[operation.index] !== operation.expectedText) return failed("invalid-request");
8973
+ queue[slots[operation.index]].command.message = operation.text;
8974
+ } else {
8975
+ if (operation.from >= slots.length || operation.to >= slots.length || operation.from === operation.to
8976
+ || current.followUp[operation.from] !== operation.expectedText) return failed("invalid-request");
8977
+ const followUps = slots.map((index) => queue[index]);
8978
+ const [moved] = followUps.splice(operation.from, 1);
8979
+ followUps.splice(operation.to, 0, moved);
8980
+ slots.forEach((slot, index) => { queue[slot] = followUps[index]; });
8981
+ }
8982
+
8983
+ advanceCompactionQueueRevision(tab);
8984
+ const result = { mutated: true, source: "webui-compaction", queue: compactionQueueSnapshot(tab) };
8985
+ broadcastTabEvent(tab, compactionQueueEvent(tab));
8986
+ return result;
8987
+ }
8988
+
8888
8989
  function enqueueCommandUntilCompactionEnds(tab, command) {
8889
8990
  const queue = compactionQueueForTab(tab);
8890
8991
  const item = {
@@ -8893,6 +8994,7 @@ function enqueueCommandUntilCompactionEnds(tab, command) {
8893
8994
  enqueuedAt: new Date().toISOString(),
8894
8995
  };
8895
8996
  queue.push(item);
8997
+ advanceCompactionQueueRevision(tab);
8896
8998
  broadcastTabEvent(tab, compactionQueueEvent(tab, { queuedId: item.id }));
8897
8999
  return rpcSuccess(command.type, {
8898
9000
  queued: true,
@@ -8937,6 +9039,7 @@ function requeueCompactionItems(tab, items) {
8937
9039
  if (!items?.length) return;
8938
9040
  const queue = compactionQueueForTab(tab);
8939
9041
  queue.unshift(...items);
9042
+ advanceCompactionQueueRevision(tab);
8940
9043
  broadcastTabEvent(tab, compactionQueueEvent(tab));
8941
9044
  }
8942
9045
 
@@ -8953,6 +9056,7 @@ async function flushCompactionQueue(tab, event = {}) {
8953
9056
  if (!queue.length || tab.compactionQueueDraining) return;
8954
9057
  const items = queue.splice(0);
8955
9058
  tab.compactionQueueDraining = true;
9059
+ advanceCompactionQueueRevision(tab);
8956
9060
  broadcastTabEvent(tab, compactionQueueEvent(tab));
8957
9061
  const remaining = [...items];
8958
9062
  try {
@@ -9143,10 +9247,11 @@ async function cancelPendingExtensionUiRequests(tab) {
9143
9247
  return ids.length;
9144
9248
  }
9145
9249
 
9146
- function markTabWorking(tab, timestamp = new Date().toISOString()) {
9250
+ function markTabWorking(tab, timestamp = new Date().toISOString(), { runStarted = false } = {}) {
9147
9251
  const activity = tab.activity || createTabActivity(timestamp);
9148
9252
  activity.status = "working";
9149
9253
  activity.isWorking = true;
9254
+ activity.runStarted = activity.runStarted === true || runStarted === true;
9150
9255
  activity.lastStartedAt = timestamp;
9151
9256
  activity.lastChangedAt = timestamp;
9152
9257
  tab.activity = activity;
@@ -9156,6 +9261,7 @@ function markTabDone(tab, timestamp = new Date().toISOString()) {
9156
9261
  const activity = tab.activity || createTabActivity(timestamp);
9157
9262
  activity.status = "done";
9158
9263
  activity.isWorking = false;
9264
+ activity.runStarted = false;
9159
9265
  activity.completionSerial = (Number(activity.completionSerial) || 0) + 1;
9160
9266
  activity.lastCompletedAt = timestamp;
9161
9267
  activity.lastChangedAt = timestamp;
@@ -9166,6 +9272,7 @@ function markTabIdle(tab, timestamp = new Date().toISOString()) {
9166
9272
  const activity = tab.activity || createTabActivity(timestamp);
9167
9273
  activity.status = "idle";
9168
9274
  activity.isWorking = false;
9275
+ activity.runStarted = false;
9169
9276
  activity.lastChangedAt = timestamp;
9170
9277
  tab.activity = activity;
9171
9278
  }
@@ -9195,11 +9302,14 @@ function reconcileTabActivityFromState(tab, state, timestamp = new Date().toISOS
9195
9302
  return tabActivitySnapshot(tab);
9196
9303
  }
9197
9304
  if (stateHasVisibleWork(state)) {
9198
- if (!tab.activity?.isWorking) markTabWorking(tab, timestamp);
9305
+ if (!tab.activity?.isWorking || (state.isStreaming && !tab.activity?.runStarted)) {
9306
+ markTabWorking(tab, timestamp, { runStarted: state.isStreaming === true });
9307
+ }
9199
9308
  return tabActivitySnapshot(tab);
9200
9309
  }
9201
9310
  if (tab.activity?.isWorking && !activityRecentlyStarted(tab.activity)) {
9202
- markTabDone(tab, timestamp);
9311
+ if (tab.activity.runStarted) markTabDone(tab, timestamp);
9312
+ else markTabIdle(tab, timestamp);
9203
9313
  }
9204
9314
  return tabActivitySnapshot(tab);
9205
9315
  }
@@ -9231,27 +9341,30 @@ function updateTabActivityFromEvent(tab, event) {
9231
9341
  switch (event?.type) {
9232
9342
  case "agent_start":
9233
9343
  patchTabState(tab, { isStreaming: true });
9234
- markTabWorking(tab, timestamp);
9344
+ markTabWorking(tab, timestamp, { runStarted: true });
9235
9345
  break;
9236
9346
  case "compaction_start":
9237
9347
  patchTabState(tab, { isCompacting: true });
9238
9348
  markTabWorking(tab, timestamp);
9239
9349
  break;
9240
9350
  case "agent_end":
9351
+ // A low-level run ended, but Pi may still retry, compact, or process a follow-up.
9352
+ break;
9353
+ case "agent_settled":
9241
9354
  patchTabState(tab, { isStreaming: false });
9242
- markTabDone(tab, timestamp);
9355
+ if (tab.activity?.runStarted) markTabDone(tab, timestamp);
9356
+ else if (tab.activity?.isWorking) markTabIdle(tab, timestamp);
9243
9357
  break;
9244
9358
  case "compaction_end":
9245
9359
  patchTabState(tab, { isCompacting: false });
9246
- markTabDone(tab, timestamp);
9360
+ if (!tab.lastState?.isStreaming && !tab.activity?.runStarted) markTabIdle(tab, timestamp);
9247
9361
  break;
9248
9362
  case "queue_update":
9249
9363
  patchTabState(tab, { pendingMessageCount: (event.steering?.length || 0) + (event.followUp?.length || 0) });
9250
9364
  break;
9251
9365
  case "pi_process_exit":
9252
9366
  case "pi_process_error":
9253
- if (tab.activity?.isWorking) markTabDone(tab, timestamp);
9254
- else markTabIdle(tab, timestamp);
9367
+ markTabIdle(tab, timestamp);
9255
9368
  break;
9256
9369
  case "response":
9257
9370
  if (event.command === "get_state" && event.success !== false) {
@@ -9337,7 +9450,9 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9337
9450
  bashQueue: [],
9338
9451
  bashQueueDraining: false,
9339
9452
  compactionQueue: [],
9453
+ compactionQueueRevision: 0,
9340
9454
  compactionQueueDraining: false,
9455
+ cwdChangeInProgress: false,
9341
9456
  rpc,
9342
9457
  rpcUnsubscribe: undefined,
9343
9458
  sseClients: new Set(),
@@ -9506,6 +9621,8 @@ function webuiSubagentsData() {
9506
9621
  runs,
9507
9622
  gates,
9508
9623
  agentCount: runs.reduce((count, run) => count + run.agents.length, 0),
9624
+ runningRuns: runs.filter((run) => run.status === "running").length,
9625
+ runningAgents: runs.reduce((count, run) => count + run.agents.filter((agent) => agent.status === "running").length, 0),
9509
9626
  gateCount: gates.length,
9510
9627
  };
9511
9628
  });
@@ -9515,6 +9632,8 @@ function webuiSubagentsData() {
9515
9632
  available: tabSummaries.some((tab) => tab.available),
9516
9633
  totalRuns: tabSummaries.reduce((count, tab) => count + tab.runs.length, 0),
9517
9634
  totalAgents: tabSummaries.reduce((count, tab) => count + tab.agentCount, 0),
9635
+ runningRuns: tabSummaries.reduce((count, tab) => count + tab.runningRuns, 0),
9636
+ runningAgents: tabSummaries.reduce((count, tab) => count + tab.runningAgents, 0),
9518
9637
  totalGates: tabSummaries.reduce((count, tab) => count + tab.gateCount, 0),
9519
9638
  tabs: tabSummaries,
9520
9639
  };
@@ -9638,9 +9757,9 @@ function normalizeWebuiSubagentOutput(value, selection) {
9638
9757
  async function webuiSubagentOutputData(tab, runId, agentId) {
9639
9758
  const runs = Array.isArray(tab.webuiSubagents?.runs) ? tab.webuiSubagents.runs : [];
9640
9759
  const run = runs.find((candidate) => candidate.id === runId);
9641
- if (!run) throw makeHttpError(404, `Running subagent run not found: ${runId}`);
9760
+ if (!run) throw makeHttpError(404, `Subagent run not found: ${runId}`);
9642
9761
  const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate.id === agentId);
9643
- if (!agent) throw makeHttpError(404, `Running subagent not found: ${agentId}`);
9762
+ if (!agent) throw makeHttpError(404, `Subagent not found: ${agentId}`);
9644
9763
  const data = await sendWebuiHelperCommand(tab, "subagent-output", { runId, agentId });
9645
9764
  return normalizeWebuiSubagentOutput(data, { run, agent });
9646
9765
  }
@@ -9693,6 +9812,140 @@ async function restorableTabsForRestart() {
9693
9812
  return mergeRestorableTabDescriptors(liveDescriptors);
9694
9813
  }
9695
9814
 
9815
+ function workspaceLoadWarning(savedTabId, code, message) {
9816
+ return { savedTabId, code, message };
9817
+ }
9818
+
9819
+ async function workspaceLoadDescriptor(descriptor, warnings) {
9820
+ const next = { ...descriptor };
9821
+ if (next.sessionFile) {
9822
+ const sessionInfo = await stat(next.sessionFile).catch(() => null);
9823
+ if (!sessionInfo?.isFile()) {
9824
+ delete next.sessionFile;
9825
+ warnings.push(workspaceLoadWarning(descriptor.id, "missing_session_file", "The saved session file is unavailable; opened a fresh session instead."));
9826
+ }
9827
+ }
9828
+ try {
9829
+ next.cwd = await resolveCwd(next.cwd, options.cwd);
9830
+ } catch {
9831
+ next.cwd = options.cwd;
9832
+ warnings.push(workspaceLoadWarning(descriptor.id, "missing_cwd", "The saved working directory is unavailable; opened in the default directory instead."));
9833
+ }
9834
+ return next;
9835
+ }
9836
+
9837
+ function workspaceReplacementIntent(body) {
9838
+ if (!body || typeof body !== "object" || Array.isArray(body) || body.replaceOpenTabs !== true) {
9839
+ throw makeHttpError(400, "Replacing open tabs requires replaceOpenTabs: true and one save or discard decision");
9840
+ }
9841
+ const hasDiscard = Object.hasOwn(body, "discardCurrent");
9842
+ const hasSave = Object.hasOwn(body, "saveCurrent");
9843
+ if (hasDiscard === hasSave) {
9844
+ throw makeHttpError(400, "Choose exactly one of discardCurrent or saveCurrent when replacing open tabs");
9845
+ }
9846
+ if (hasDiscard) {
9847
+ if (body.discardCurrent !== true) throw makeHttpError(400, "discardCurrent must be true when replacing open tabs");
9848
+ return { discardCurrent: true };
9849
+ }
9850
+ if (!body.saveCurrent || typeof body.saveCurrent !== "object" || Array.isArray(body.saveCurrent)) {
9851
+ throw makeHttpError(400, "saveCurrent must be an object when replacing open tabs");
9852
+ }
9853
+ return { saveCurrent: body.saveCurrent };
9854
+ }
9855
+
9856
+ function openTabsUnchanged(tabIds) {
9857
+ return tabs.size === tabIds.length && tabIds.every((id) => tabs.has(id));
9858
+ }
9859
+
9860
+ async function saveCurrentWorkspaceForReplacement(saveCurrent, tabIds) {
9861
+ const descriptors = await restorableTabsForRestart();
9862
+ const descriptorIds = new Set(descriptors.map((descriptor) => descriptor.id));
9863
+ if (descriptors.length !== tabIds.length || tabIds.some((id) => !descriptorIds.has(id))) {
9864
+ throw makeHttpError(400, `Only ${RESTORE_TAB_LIMIT} open tabs can be saved; close some tabs or choose Load without saving`);
9865
+ }
9866
+ try {
9867
+ return await saveWebuiWorkspace({
9868
+ name: saveCurrent.name,
9869
+ groups: saveCurrent.groups,
9870
+ activeTabId: saveCurrent.activeTabId,
9871
+ overwrite: saveCurrent.overwrite === true,
9872
+ tabs: descriptors,
9873
+ });
9874
+ } catch (error) {
9875
+ if (error?.code === "WORKSPACE_NAME_CONFLICT") throw makeHttpError(409, error.message);
9876
+ throw error;
9877
+ }
9878
+ }
9879
+
9880
+ async function loadWebuiWorkspace(id, body = {}) {
9881
+ if (workspaceLoadInProgress) throw makeHttpError(409, "A workspace load is already in progress");
9882
+ workspaceLoadInProgress = true;
9883
+ try {
9884
+ const workspace = await getWebuiWorkspace(id);
9885
+ if (!workspace) throw makeHttpError(404, "Workspace not found");
9886
+
9887
+ const openTabIds = [...tabs.keys()];
9888
+ let closedIds = [];
9889
+ let savedCurrent;
9890
+ if (openTabIds.length) {
9891
+ const intent = workspaceReplacementIntent(body);
9892
+ if (intent.saveCurrent) {
9893
+ savedCurrent = await saveCurrentWorkspaceForReplacement(intent.saveCurrent, openTabIds);
9894
+ broadcastServerEvent({
9895
+ type: "webui_workspace_saved",
9896
+ workspaceId: savedCurrent.workspace.id,
9897
+ workspaceName: savedCurrent.workspace.name,
9898
+ tabCount: savedCurrent.workspace.tabCount,
9899
+ evictedIds: savedCurrent.evicted.map((workspace) => workspace.id),
9900
+ });
9901
+ }
9902
+ if (!openTabsUnchanged(openTabIds)) {
9903
+ const savedNote = savedCurrent ? "The current workspace was saved, but " : "";
9904
+ throw makeHttpError(409, `${savedNote}open tabs changed before the workspace could be replaced`);
9905
+ }
9906
+ closedIds = (await closeTabs(openTabIds, { allowEmpty: true })).map((tab) => tab.id);
9907
+ }
9908
+
9909
+ const warnings = [];
9910
+ const idMap = {};
9911
+ for (const descriptor of workspace.tabs) {
9912
+ const preflighted = await workspaceLoadDescriptor(descriptor, warnings);
9913
+ try {
9914
+ const tab = await createTab(preflighted);
9915
+ idMap[descriptor.id] = tab.id;
9916
+ } catch (error) {
9917
+ warnings.push(workspaceLoadWarning(descriptor.id, "tab_create_failed", `Could not restore this tab: ${sanitizeError(error)}`));
9918
+ }
9919
+ }
9920
+ const groups = workspace.groups.map((group) => ({
9921
+ title: group.title,
9922
+ tabIds: group.tabIds.map((tabId) => idMap[tabId]).filter(Boolean),
9923
+ })).filter((group) => group.tabIds.length);
9924
+ const activeTabId = workspace.activeTabId ? idMap[workspace.activeTabId] || null : null;
9925
+ const data = {
9926
+ tabs: listTabs(),
9927
+ idMap,
9928
+ groups,
9929
+ activeTabId,
9930
+ warnings,
9931
+ closedIds,
9932
+ ...(savedCurrent ? { savedCurrent } : {}),
9933
+ };
9934
+ broadcastServerEvent({
9935
+ type: "webui_workspace_loaded",
9936
+ workspaceId: workspace.id,
9937
+ workspaceName: workspace.name,
9938
+ tabCount: data.tabs.length,
9939
+ warningCount: warnings.length,
9940
+ closedIds,
9941
+ ...(savedCurrent ? { savedCurrentId: savedCurrent.workspace.id } : {}),
9942
+ });
9943
+ return data;
9944
+ } finally {
9945
+ workspaceLoadInProgress = false;
9946
+ }
9947
+ }
9948
+
9696
9949
  function spawnRestartServer(restorableTabs, supervisorCursor) {
9697
9950
  const env = {
9698
9951
  ...process.env,
@@ -10264,9 +10517,23 @@ function responseWithTab(response, tab) {
10264
10517
  async function updateTabCwd(id, cwd) {
10265
10518
  const tab = tabs.get(id);
10266
10519
  if (!tab) throw makeHttpError(404, `Unknown Pi tab: ${id}`);
10520
+ if (tab.cwdChangeInProgress) throw makeHttpError(409, `${tab.title} is already changing its working folder`);
10267
10521
 
10522
+ tab.cwdChangeInProgress = true;
10523
+ try {
10524
+ return await performTabCwdUpdate(tab, cwd);
10525
+ } finally {
10526
+ tab.cwdChangeInProgress = false;
10527
+ scheduleSupervisorMetadataUpdate(tab);
10528
+ }
10529
+ }
10530
+
10531
+ async function performTabCwdUpdate(tab, cwd) {
10268
10532
  const nextCwd = await resolveCwd(cwd, tab.cwd);
10269
10533
  if (nextCwd === tab.cwd) return { tab, changed: false };
10534
+ if (tab.rpc instanceof SupervisorPiRpcProcess && !tab.rpc.supervisor.isCurrentVersion()) {
10535
+ throw makeHttpError(503, "The detached Pi supervisor is from an older WebUI build. Fully shut down Pi WebUI (not Restart), then start it again before changing working folders.");
10536
+ }
10270
10537
 
10271
10538
  // Capture the live session before stopping the old RPC so the conversation
10272
10539
  // survives the cwd restart, mirroring restartTabRpc. Best-effort: a dead RPC
@@ -10277,39 +10544,47 @@ async function updateTabCwd(id, cwd) {
10277
10544
  const piArgs = await buildPiArgsForTab(tab.index, tab.title, nextCwd);
10278
10545
  if (sessionFile && !options.noSession) piArgs.push("--session", sessionFile);
10279
10546
  const piCommand = await resolvePiCommand(piArgs);
10280
- gitLiveWatcher.unsubscribe(tab.id);
10281
10547
  const restartingEvent = { type: "webui_tab_restarting", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, sessionFile };
10282
10548
  broadcastTabEvent(tab, restartingEvent);
10283
10549
 
10284
10550
  const oldRpc = tab.rpc;
10285
- tab.rpcUnsubscribe?.();
10286
- tab.rpcUnsubscribe = undefined;
10287
10551
  rejectTabBashQueue(tab, new Error("Pi tab is restarting; queued bash commands were cancelled"));
10288
10552
  stopAppRunnerForTab(tab, "cwd changed", { force: true });
10289
-
10290
- tab.cwd = nextCwd;
10291
- resetTabActivity(tab);
10292
10553
  clearPendingExtensionUiRequests(tab);
10293
10554
  clearExtensionStatuses(tab);
10294
10555
  clearExtensionWidgets(tab);
10295
10556
  clearWebuiSubagents(tab);
10296
10557
  resetNaturalConversationMode(tab);
10558
+
10297
10559
  let rpc;
10298
- if (oldRpc instanceof SupervisorPiRpcProcess) {
10299
- const snapshot = await oldRpc.replace({
10300
- child: { command: piCommand.command, args: piCommand.args, cwd: tab.cwd },
10301
- metadata: supervisedTabMetadata(tab),
10302
- displayCommand: piCommand.displayCommand,
10303
- });
10304
- oldRpc.dispose();
10305
- rpc = new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: tab.id, displayCommand: piCommand.displayCommand, cwd: tab.cwd, snapshot });
10306
- attachRpcToTab(tab, rpc);
10307
- } else {
10308
- oldRpc.stop();
10309
- rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd, env: piRpcEnvironment() });
10310
- attachRpcToTab(tab, rpc);
10311
- rpc.start();
10560
+ let startDirectRpc = false;
10561
+ try {
10562
+ if (oldRpc instanceof SupervisorPiRpcProcess) {
10563
+ const snapshot = await oldRpc.replace({
10564
+ child: { command: piCommand.command, args: piCommand.args, cwd: nextCwd },
10565
+ metadata: supervisedTabMetadata(tab, { cwd: nextCwd }),
10566
+ displayCommand: piCommand.displayCommand,
10567
+ });
10568
+ oldRpc.dispose();
10569
+ rpc = new SupervisorPiRpcProcess({ supervisor: rpcSupervisor, tabId: tab.id, displayCommand: piCommand.displayCommand, cwd: nextCwd, snapshot });
10570
+ } else {
10571
+ oldRpc.stop();
10572
+ rpc = new PiRpcProcess({ ...piCommand, cwd: nextCwd, env: piRpcEnvironment() });
10573
+ startDirectRpc = true;
10574
+ }
10575
+ } catch (error) {
10576
+ const detail = sanitizeError(error);
10577
+ broadcastTabEvent(tab, { type: "webui_cwd_change_failed", tabId: tab.id, tabTitle: tab.title, cwd: nextCwd, error: detail });
10578
+ throw makeHttpError(502, `Could not restart ${tab.title} in ${displayPath(nextCwd)}: ${detail}`);
10312
10579
  }
10580
+
10581
+ tab.rpcUnsubscribe?.();
10582
+ tab.rpcUnsubscribe = undefined;
10583
+ tab.cwd = nextCwd;
10584
+ resetTabActivity(tab);
10585
+ attachRpcToTab(tab, rpc);
10586
+ if (startDirectRpc) rpc.start();
10587
+ gitLiveWatcher.unsubscribe(tab.id);
10313
10588
  // Non-fatal: a failed start surfaces through pi_process_error/exit events.
10314
10589
  await primeTabRpc(tab).catch(() => {});
10315
10590
 
@@ -12455,10 +12730,10 @@ async function handleNativeSlashCommand(tab, body, req) {
12455
12730
  }
12456
12731
  }
12457
12732
 
12458
- async function closeTab(id) {
12733
+ async function closeTab(id, { allowLast = false } = {}) {
12459
12734
  const tab = tabs.get(id);
12460
12735
  if (!tab) throw makeHttpError(404, `Unknown Pi tab: ${id}`);
12461
- if (tabs.size <= 1) throw makeHttpError(400, "Cannot close the last Pi tab");
12736
+ if (!allowLast && tabs.size <= 1) throw makeHttpError(400, "Cannot close the last Pi tab");
12462
12737
 
12463
12738
  let restorableState = null;
12464
12739
  if (!options.noSession) {
@@ -12548,19 +12823,19 @@ async function openPlanRecovery(body = {}) {
12548
12823
  }
12549
12824
  }
12550
12825
 
12551
- async function closeTabs(ids) {
12826
+ async function closeTabs(ids, { allowEmpty = false } = {}) {
12552
12827
  const uniqueIds = [...new Set((Array.isArray(ids) ? ids : []).map((id) => String(id || "").trim()).filter(Boolean))];
12553
12828
  const targetTabs = uniqueIds.map((id) => tabs.get(id)).filter(Boolean);
12554
12829
  if (!targetTabs.length) return [];
12555
12830
 
12556
- if (targetTabs.length >= tabs.size) {
12831
+ if (!allowEmpty && targetTabs.length >= tabs.size) {
12557
12832
  await createTab({ cwd: targetTabs[0]?.cwd || options.cwd });
12558
12833
  }
12559
12834
 
12560
12835
  const closed = [];
12561
12836
  for (const tab of targetTabs) {
12562
12837
  if (!tabs.has(tab.id)) continue;
12563
- closed.push(await closeTab(tab.id));
12838
+ closed.push(await closeTab(tab.id, { allowLast: allowEmpty }));
12564
12839
  }
12565
12840
  return closed;
12566
12841
  }
@@ -13170,6 +13445,57 @@ const server = createServer(async (req, res) => {
13170
13445
  return;
13171
13446
  }
13172
13447
 
13448
+ if (url.pathname === "/api/workspaces" && req.method === "GET") {
13449
+ sendJson(res, 200, { ok: true, data: { workspaces: await listWebuiWorkspaces() } });
13450
+ return;
13451
+ }
13452
+
13453
+ if (url.pathname === "/api/workspaces" && req.method === "POST") {
13454
+ if (!tabs.size) throw makeHttpError(400, "A workspace requires at least one open tab");
13455
+ const body = await readJsonBody(req);
13456
+ const descriptors = await restorableTabsForRestart();
13457
+ if (!descriptors.length) throw makeHttpError(400, "A workspace requires at least one open tab");
13458
+ let data;
13459
+ try {
13460
+ data = await saveWebuiWorkspace({
13461
+ name: body.name,
13462
+ groups: body.groups,
13463
+ activeTabId: body.activeTabId,
13464
+ overwrite: body.overwrite === true,
13465
+ tabs: descriptors,
13466
+ });
13467
+ } catch (error) {
13468
+ if (error?.code === "WORKSPACE_NAME_CONFLICT") throw makeHttpError(409, error.message);
13469
+ throw error;
13470
+ }
13471
+ broadcastServerEvent({
13472
+ type: "webui_workspace_saved",
13473
+ workspaceId: data.workspace.id,
13474
+ workspaceName: data.workspace.name,
13475
+ tabCount: data.workspace.tabCount,
13476
+ evictedIds: data.evicted.map((workspace) => workspace.id),
13477
+ });
13478
+ sendJson(res, 201, { ok: true, data });
13479
+ return;
13480
+ }
13481
+
13482
+ const workspaceLoadRoute = /^\/api\/workspaces\/([^/]+)\/load$/.exec(url.pathname);
13483
+ if (workspaceLoadRoute && req.method === "POST") {
13484
+ const body = await readJsonBody(req);
13485
+ sendJson(res, 200, { ok: true, data: await loadWebuiWorkspace(decodeURIComponent(workspaceLoadRoute[1]), body) });
13486
+ return;
13487
+ }
13488
+
13489
+ if (url.pathname.startsWith("/api/workspaces/") && req.method === "DELETE") {
13490
+ const id = decodeURIComponent(url.pathname.slice("/api/workspaces/".length));
13491
+ if (!id || id.includes("/")) throw makeHttpError(404, "Workspace not found");
13492
+ const data = await deleteWebuiWorkspace(id);
13493
+ if (!data) throw makeHttpError(404, "Workspace not found");
13494
+ broadcastServerEvent({ type: "webui_workspace_deleted", workspaceId: data.deletedId });
13495
+ sendJson(res, 200, { ok: true, data });
13496
+ return;
13497
+ }
13498
+
13173
13499
  if (url.pathname === "/api/subagents" && req.method === "GET") {
13174
13500
  sendJson(res, 200, { ok: true, data: webuiSubagentsData() });
13175
13501
  return;
@@ -13198,6 +13524,26 @@ const server = createServer(async (req, res) => {
13198
13524
  return;
13199
13525
  }
13200
13526
 
13527
+ if (url.pathname === "/api/subagents/cancel" && req.method === "POST") {
13528
+ requireLocalhostRoute(req, url.pathname);
13529
+ const body = await readJsonBody(req);
13530
+ const tab = getRequestedTab(req, url, body);
13531
+ sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, "subagent-cancel", {
13532
+ runId: body.runId,
13533
+ reason: body.reason,
13534
+ note: body.note,
13535
+ }) });
13536
+ return;
13537
+ }
13538
+
13539
+ if (url.pathname === "/api/subagents/dismiss" && req.method === "POST") {
13540
+ requireLocalhostRoute(req, url.pathname);
13541
+ const body = await readJsonBody(req);
13542
+ const tab = getRequestedTab(req, url, body);
13543
+ sendJson(res, 200, { ok: true, data: await sendWebuiHelperCommand(tab, "subagent-dismiss", { runId: body.runId }) });
13544
+ return;
13545
+ }
13546
+
13201
13547
  if (url.pathname === "/api/tabs" && req.method === "POST") {
13202
13548
  const body = await readJsonBody(req);
13203
13549
  const tab = await createTab({ title: body.title, cwd: body.cwd });
@@ -13207,7 +13553,7 @@ const server = createServer(async (req, res) => {
13207
13553
 
13208
13554
  if (url.pathname === "/api/tabs/close" && req.method === "POST") {
13209
13555
  const body = await readJsonBody(req);
13210
- const closed = await closeTabs(body.ids || body.tabIds || []);
13556
+ const closed = await closeTabs(body.ids || body.tabIds || [], { allowEmpty: body.allowEmpty === true });
13211
13557
  sendJson(res, 200, { ok: true, data: { closedIds: closed.map((tab) => tab.id), tabs: listTabs(), activeTabId: firstTab()?.id || null } });
13212
13558
  return;
13213
13559
  }
@@ -13957,6 +14303,19 @@ const server = createServer(async (req, res) => {
13957
14303
  return;
13958
14304
  }
13959
14305
 
14306
+ if (url.pathname === "/api/queue/mutate" && req.method === "POST") {
14307
+ const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
14308
+ const tab = getRequestedTab(req, url, body);
14309
+ const request = queueMutationRequest(body);
14310
+ const data = request.source === "webui-compaction"
14311
+ ? mutateCompactionFollowUpQueue(tab, request)
14312
+ : await sendWebuiHelperCommand(tab, "queue-mutate", request);
14313
+ const conflict = data?.mutated === false && ["queue-changed", "queue-desynchronized", "queue-draining"].includes(data.reason);
14314
+ const status = data?.mutated === true ? 200 : conflict ? 409 : 400;
14315
+ sendJson(res, status, { ok: data?.mutated === true, data });
14316
+ return;
14317
+ }
14318
+
13960
14319
  if (url.pathname === "/api/prompt" && req.method === "POST") {
13961
14320
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
13962
14321
  const tab = getRequestedTab(req, url, body);