@firstpick/pi-package-webui 0.7.8 → 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.
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
 
@@ -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;
@@ -8508,8 +8481,9 @@ function responseWithPendingThinking(tab, response) {
8508
8481
  }
8509
8482
 
8510
8483
  function eventForTabClients(tab, event) {
8484
+ const decorated = event?.type === "queue_update" ? { ...event, source: "pi-runtime" } : event;
8511
8485
  return {
8512
- ...rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, event)),
8486
+ ...rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, decorated)),
8513
8487
  tabId: tab.id,
8514
8488
  tabTitle: tab.title,
8515
8489
  tabActivity: tabActivitySnapshot(tab),
@@ -8615,14 +8589,18 @@ function normalizeWebuiSubagentPayload(value) {
8615
8589
  if (!rawRun || typeof rawRun !== "object") continue;
8616
8590
  const id = normalizeWebuiSubagentText(rawRun.id, 160);
8617
8591
  if (!id) continue;
8592
+ const status = ["running", "done", "failed", "cancelled"].includes(rawRun.status) ? rawRun.status : "running";
8618
8593
  const agents = [];
8619
8594
  for (const rawAgent of Array.isArray(rawRun.agents) ? rawRun.agents.slice(0, WEBUI_SUBAGENT_AGENT_LIMIT) : []) {
8620
8595
  const name = normalizeWebuiSubagentText(rawAgent?.name, 160);
8621
- 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;
8622
8600
  agents.push({
8623
8601
  id: normalizeWebuiSubagentText(rawAgent.id || `${id}:${agents.length}`, 240),
8624
8602
  name,
8625
- status: "running",
8603
+ status: agentStatus,
8626
8604
  index: Number.isInteger(rawAgent.index) ? rawAgent.index : agents.length,
8627
8605
  currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
8628
8606
  activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
@@ -8631,13 +8609,17 @@ function normalizeWebuiSubagentPayload(value) {
8631
8609
  nested: rawAgent.nested === true,
8632
8610
  });
8633
8611
  }
8634
- if (!agents.length) continue;
8612
+ if (status === "running" && !agents.length) continue;
8635
8613
  runs.push({
8636
8614
  id,
8637
8615
  source: normalizeWebuiSubagentSource(rawRun.source),
8638
8616
  mode: ["single", "parallel", "chain"].includes(rawRun.mode) ? rawRun.mode : "single",
8639
- status: "running",
8617
+ status,
8640
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,
8641
8623
  agents: agents.sort((a, b) => a.index - b.index || a.name.localeCompare(b.name)),
8642
8624
  });
8643
8625
  }
@@ -8845,6 +8827,75 @@ function compactionQueueForTab(tab) {
8845
8827
  return tab.compactionQueue;
8846
8828
  }
8847
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
+
8848
8899
  function queueableCompactionCommand(command) {
8849
8900
  return ["prompt", "steer", "follow_up"].includes(command?.type) && !!String(command.message || "").trim();
8850
8901
  }
@@ -8864,7 +8915,7 @@ function compactQueuedCommand(command) {
8864
8915
  return queued;
8865
8916
  }
8866
8917
 
8867
- function compactionQueueEvent(tab, extra = {}) {
8918
+ function compactionQueueSnapshot(tab) {
8868
8919
  const queue = compactionQueueForTab(tab);
8869
8920
  const steering = [];
8870
8921
  const followUp = [];
@@ -8874,20 +8925,67 @@ function compactionQueueEvent(tab, extra = {}) {
8874
8925
  if (item.command.mode === "followUp") followUp.push(message);
8875
8926
  else steering.push(message);
8876
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);
8877
8939
  return {
8878
8940
  type: "webui_compaction_queue_update",
8879
8941
  tabId: tab.id,
8880
8942
  tabTitle: tab.title,
8881
8943
  queueLength: queue.length,
8882
8944
  pendingMessageCount: queue.length,
8883
- steering,
8884
- followUp,
8885
- draining: tab.compactionQueueDraining === true,
8945
+ ...compactionQueueSnapshot(tab),
8886
8946
  tabActivity: tabActivitySnapshot(tab),
8887
8947
  ...extra,
8888
8948
  };
8889
8949
  }
8890
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
+
8891
8989
  function enqueueCommandUntilCompactionEnds(tab, command) {
8892
8990
  const queue = compactionQueueForTab(tab);
8893
8991
  const item = {
@@ -8896,6 +8994,7 @@ function enqueueCommandUntilCompactionEnds(tab, command) {
8896
8994
  enqueuedAt: new Date().toISOString(),
8897
8995
  };
8898
8996
  queue.push(item);
8997
+ advanceCompactionQueueRevision(tab);
8899
8998
  broadcastTabEvent(tab, compactionQueueEvent(tab, { queuedId: item.id }));
8900
8999
  return rpcSuccess(command.type, {
8901
9000
  queued: true,
@@ -8940,6 +9039,7 @@ function requeueCompactionItems(tab, items) {
8940
9039
  if (!items?.length) return;
8941
9040
  const queue = compactionQueueForTab(tab);
8942
9041
  queue.unshift(...items);
9042
+ advanceCompactionQueueRevision(tab);
8943
9043
  broadcastTabEvent(tab, compactionQueueEvent(tab));
8944
9044
  }
8945
9045
 
@@ -8956,6 +9056,7 @@ async function flushCompactionQueue(tab, event = {}) {
8956
9056
  if (!queue.length || tab.compactionQueueDraining) return;
8957
9057
  const items = queue.splice(0);
8958
9058
  tab.compactionQueueDraining = true;
9059
+ advanceCompactionQueueRevision(tab);
8959
9060
  broadcastTabEvent(tab, compactionQueueEvent(tab));
8960
9061
  const remaining = [...items];
8961
9062
  try {
@@ -9349,6 +9450,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
9349
9450
  bashQueue: [],
9350
9451
  bashQueueDraining: false,
9351
9452
  compactionQueue: [],
9453
+ compactionQueueRevision: 0,
9352
9454
  compactionQueueDraining: false,
9353
9455
  cwdChangeInProgress: false,
9354
9456
  rpc,
@@ -9519,6 +9621,8 @@ function webuiSubagentsData() {
9519
9621
  runs,
9520
9622
  gates,
9521
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),
9522
9626
  gateCount: gates.length,
9523
9627
  };
9524
9628
  });
@@ -9528,6 +9632,8 @@ function webuiSubagentsData() {
9528
9632
  available: tabSummaries.some((tab) => tab.available),
9529
9633
  totalRuns: tabSummaries.reduce((count, tab) => count + tab.runs.length, 0),
9530
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),
9531
9637
  totalGates: tabSummaries.reduce((count, tab) => count + tab.gateCount, 0),
9532
9638
  tabs: tabSummaries,
9533
9639
  };
@@ -9651,9 +9757,9 @@ function normalizeWebuiSubagentOutput(value, selection) {
9651
9757
  async function webuiSubagentOutputData(tab, runId, agentId) {
9652
9758
  const runs = Array.isArray(tab.webuiSubagents?.runs) ? tab.webuiSubagents.runs : [];
9653
9759
  const run = runs.find((candidate) => candidate.id === runId);
9654
- if (!run) throw makeHttpError(404, `Running subagent run not found: ${runId}`);
9760
+ if (!run) throw makeHttpError(404, `Subagent run not found: ${runId}`);
9655
9761
  const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate.id === agentId);
9656
- if (!agent) throw makeHttpError(404, `Running subagent not found: ${agentId}`);
9762
+ if (!agent) throw makeHttpError(404, `Subagent not found: ${agentId}`);
9657
9763
  const data = await sendWebuiHelperCommand(tab, "subagent-output", { runId, agentId });
9658
9764
  return normalizeWebuiSubagentOutput(data, { run, agent });
9659
9765
  }
@@ -9706,6 +9812,140 @@ async function restorableTabsForRestart() {
9706
9812
  return mergeRestorableTabDescriptors(liveDescriptors);
9707
9813
  }
9708
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
+
9709
9949
  function spawnRestartServer(restorableTabs, supervisorCursor) {
9710
9950
  const env = {
9711
9951
  ...process.env,
@@ -12490,10 +12730,10 @@ async function handleNativeSlashCommand(tab, body, req) {
12490
12730
  }
12491
12731
  }
12492
12732
 
12493
- async function closeTab(id) {
12733
+ async function closeTab(id, { allowLast = false } = {}) {
12494
12734
  const tab = tabs.get(id);
12495
12735
  if (!tab) throw makeHttpError(404, `Unknown Pi tab: ${id}`);
12496
- 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");
12497
12737
 
12498
12738
  let restorableState = null;
12499
12739
  if (!options.noSession) {
@@ -12583,19 +12823,19 @@ async function openPlanRecovery(body = {}) {
12583
12823
  }
12584
12824
  }
12585
12825
 
12586
- async function closeTabs(ids) {
12826
+ async function closeTabs(ids, { allowEmpty = false } = {}) {
12587
12827
  const uniqueIds = [...new Set((Array.isArray(ids) ? ids : []).map((id) => String(id || "").trim()).filter(Boolean))];
12588
12828
  const targetTabs = uniqueIds.map((id) => tabs.get(id)).filter(Boolean);
12589
12829
  if (!targetTabs.length) return [];
12590
12830
 
12591
- if (targetTabs.length >= tabs.size) {
12831
+ if (!allowEmpty && targetTabs.length >= tabs.size) {
12592
12832
  await createTab({ cwd: targetTabs[0]?.cwd || options.cwd });
12593
12833
  }
12594
12834
 
12595
12835
  const closed = [];
12596
12836
  for (const tab of targetTabs) {
12597
12837
  if (!tabs.has(tab.id)) continue;
12598
- closed.push(await closeTab(tab.id));
12838
+ closed.push(await closeTab(tab.id, { allowLast: allowEmpty }));
12599
12839
  }
12600
12840
  return closed;
12601
12841
  }
@@ -13205,6 +13445,57 @@ const server = createServer(async (req, res) => {
13205
13445
  return;
13206
13446
  }
13207
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
+
13208
13499
  if (url.pathname === "/api/subagents" && req.method === "GET") {
13209
13500
  sendJson(res, 200, { ok: true, data: webuiSubagentsData() });
13210
13501
  return;
@@ -13233,6 +13524,26 @@ const server = createServer(async (req, res) => {
13233
13524
  return;
13234
13525
  }
13235
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
+
13236
13547
  if (url.pathname === "/api/tabs" && req.method === "POST") {
13237
13548
  const body = await readJsonBody(req);
13238
13549
  const tab = await createTab({ title: body.title, cwd: body.cwd });
@@ -13242,7 +13553,7 @@ const server = createServer(async (req, res) => {
13242
13553
 
13243
13554
  if (url.pathname === "/api/tabs/close" && req.method === "POST") {
13244
13555
  const body = await readJsonBody(req);
13245
- const closed = await closeTabs(body.ids || body.tabIds || []);
13556
+ const closed = await closeTabs(body.ids || body.tabIds || [], { allowEmpty: body.allowEmpty === true });
13246
13557
  sendJson(res, 200, { ok: true, data: { closedIds: closed.map((tab) => tab.id), tabs: listTabs(), activeTabId: firstTab()?.id || null } });
13247
13558
  return;
13248
13559
  }
@@ -13992,6 +14303,19 @@ const server = createServer(async (req, res) => {
13992
14303
  return;
13993
14304
  }
13994
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
+
13995
14319
  if (url.pathname === "/api/prompt" && req.method === "POST") {
13996
14320
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
13997
14321
  const tab = getRequestedTab(req, url, body);