@firstpick/pi-package-webui 0.6.5 → 0.6.6

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
@@ -21,6 +21,23 @@ import {
21
21
  validateSessionDelete,
22
22
  } from "../lib/session-actions.mjs";
23
23
  import { sweepStaleTempEntries } from "../lib/temp-artifacts.mjs";
24
+ import {
25
+ GIT_WORKFLOW_DEFAULT_VARIANTS,
26
+ GIT_WORKFLOW_DELIVERY_MODES,
27
+ GIT_WORKFLOW_LANGUAGES,
28
+ GIT_WORKFLOW_SCOPE_POLICIES,
29
+ GIT_WORKFLOW_STAGING_POLICIES,
30
+ GIT_WORKFLOW_THINKING_LEVELS,
31
+ GIT_WORKFLOW_VERIFICATION_POLICIES,
32
+ isGitWorkflowSetupComplete,
33
+ mergeGitWorkflowPreferences,
34
+ readGitWorkflowPreferences,
35
+ readWebuiSettings,
36
+ supportedGitWorkflowThinkingLevels,
37
+ webuiSettingsFile,
38
+ writeGitWorkflowPreferences,
39
+ writeWebuiSettings,
40
+ } from "../lib/git-workflow-preferences.mjs";
24
41
  import {
25
42
  evaluateDispatchTrustGuards,
26
43
  guardsForNativeCommand,
@@ -55,7 +72,6 @@ const publicDir = path.join(packageRoot, "public");
55
72
  const webuiHelperExtensionPath = path.join(packageRoot, "webui-rpc-helper.mjs");
56
73
  const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(homedir(), ".pi", "agent");
57
74
  const OPTIONAL_FEATURE_INSTALL_ROOT_ENV = "PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT";
58
- const WEBUI_SETTINGS_FILE_ENV = "PI_WEBUI_SETTINGS_FILE";
59
75
  const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
60
76
  let piPackageJson = {};
61
77
  try {
@@ -75,6 +91,12 @@ const PROMPT_REQUEST_TIMEOUT_MS = Math.max(REQUEST_TIMEOUT_MS, Number.parseInt(p
75
91
  const WEBUI_HELPER_TIMEOUT_MS = 8 * 1000;
76
92
  const WEBUI_HELPER_COMMAND = "webui-helper";
77
93
  const WEBUI_HELPER_RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
94
+ const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
95
+ const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
96
+ const WEBUI_SUBAGENT_RUN_LIMIT = 128;
97
+ const WEBUI_SUBAGENT_AGENT_LIMIT = 256;
98
+ const WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT = 120;
99
+ const WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
78
100
  const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
79
101
  const WEBUI_PACKAGE = packageJson.name || "@firstpick/pi-package-webui";
80
102
  const PI_LATEST_VERSION_URL = process.env.PI_WEBUI_PI_LATEST_VERSION_URL || "https://pi.dev/api/latest-version";
@@ -116,7 +138,7 @@ const ATTACHMENT_UPLOAD_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
116
138
  const INLINE_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
117
139
  const INLINE_IMAGE_TOTAL_MAX_BYTES = 16 * 1024 * 1024;
118
140
  const RPC_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
119
- const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
141
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
120
142
  const SETTINGS_TRANSPORT_CHOICES = ["sse", "websocket", "websocket-cached", "auto"];
121
143
  const SETTINGS_HTTP_IDLE_TIMEOUT_CHOICES = [
122
144
  { label: "30 sec", timeoutMs: 30_000 },
@@ -448,16 +470,44 @@ function formatUrlHost(host) {
448
470
  return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
449
471
  }
450
472
 
473
+ function makeUserFacingError(message, props = {}) {
474
+ const text = String(message || "Unknown error").trim() || "Unknown error";
475
+ const error = new Error(text);
476
+ error.userMessage = text;
477
+ Object.assign(error, props);
478
+ return error;
479
+ }
480
+
451
481
  function sanitizeError(error) {
452
482
  if (!error) return "Unknown error";
453
483
  if (typeof error === "string") return error;
484
+ if (error.userMessage) return error.userMessage;
454
485
  return error.stack || error.message || String(error);
455
486
  }
456
487
 
457
488
  function formatCliError(error) {
458
489
  if (!error) return "Unknown error";
459
490
  if (typeof error === "string") return error;
460
- return error.message || String(error);
491
+ return error.userMessage || error.message || String(error);
492
+ }
493
+
494
+ function formatCommandSpawnError(command, error) {
495
+ const commandText = String(command || "command");
496
+ const executable = commandText.split(/[\\/]/).pop() || commandText;
497
+ const isGit = /^git(?:\.exe)?$/i.test(executable);
498
+ if (error?.code === "ENOENT") {
499
+ if (isGit) {
500
+ const windowsHint = process.platform === "win32"
501
+ ? " On Windows, install Git for Windows and choose 'Git from the command line and also from 3rd-party software', or add Git's cmd/bin directory to PATH."
502
+ : "";
503
+ return `Git executable not found on PATH (spawn ${executable} ENOENT). Install Git and ensure the 'git' command is available to the Pi Web UI process, then restart Pi Web UI.${windowsHint}`;
504
+ }
505
+ return `${executable} executable not found on PATH (spawn ${executable} ENOENT). Install it or add it to PATH, then restart Pi Web UI.`;
506
+ }
507
+ if (error?.code === "EACCES" || error?.code === "EPERM") {
508
+ return `Cannot start ${executable}: permission denied. Check executable permissions and PATH.`;
509
+ }
510
+ return formatCliError(error);
461
511
  }
462
512
 
463
513
  function delay(ms) {
@@ -1149,7 +1199,10 @@ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20
1149
1199
  stderr += String(chunk);
1150
1200
  if (stderr.length > maxOutputLength) stderr = stderr.slice(-maxOutputLength);
1151
1201
  });
1152
- child.on("error", (error) => finish({ exitCode: undefined, stdout, stderr: sanitizeError(error), error: sanitizeError(error) }));
1202
+ child.on("error", (error) => {
1203
+ const message = formatCommandSpawnError(command, error);
1204
+ finish({ exitCode: undefined, stdout, stderr: message, error: message, errorCode: error?.code });
1205
+ });
1153
1206
  // "close", not "exit": exit can fire before the stdio pipes flush, which
1154
1207
  // intermittently truncates stdout (empty `git rev-parse --show-toplevel`
1155
1208
  // output resolves to process.cwd() and reads the wrong repository).
@@ -1550,48 +1603,168 @@ async function writePathFastPicks(picks) {
1550
1603
  return normalized;
1551
1604
  }
1552
1605
 
1553
- function webuiSettingsFile() {
1554
- if (process.env[WEBUI_SETTINGS_FILE_ENV]) return path.resolve(expandUserPath(process.env[WEBUI_SETTINGS_FILE_ENV]));
1555
- const configRoot = process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config");
1556
- return path.join(configRoot, "pi-webui", "settings.json");
1606
+ async function readPersistedRemoteAuthEnabled() {
1607
+ return (await readWebuiSettings()).remoteAuthEnabled === true;
1608
+ }
1609
+
1610
+ async function saveRemoteAuthPreference(enabled) {
1611
+ const nextEnabled = enabled === true;
1612
+ await writeWebuiSettings({ remoteAuthEnabled: nextEnabled });
1613
+ persistedRemoteAuthEnabled = nextEnabled;
1614
+ return persistedRemoteAuthEnabled;
1615
+ }
1616
+
1617
+ function gitWorkflowModelKey(model) {
1618
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
1619
+ }
1620
+
1621
+ async function availableGitWorkflowModels(tab) {
1622
+ const response = await safeRpcData(tab, { type: "get_available_models" });
1623
+ if (!response.ok) throw makeHttpError(400, response.error || "Failed to load available models");
1624
+ return (Array.isArray(response.data?.models) ? response.data.models : [])
1625
+ .filter((model) => model?.provider && model?.id)
1626
+ .sort((left, right) => gitWorkflowModelKey(left).localeCompare(gitWorkflowModelKey(right)));
1557
1627
  }
1558
1628
 
1559
- function normalizeWebuiSettings(value) {
1629
+ function gitWorkflowPreferenceOptions() {
1560
1630
  return {
1561
- version: 1,
1562
- remoteAuthEnabled: value?.remoteAuthEnabled === true,
1631
+ thinkingLevels: GIT_WORKFLOW_THINKING_LEVELS,
1632
+ languages: GIT_WORKFLOW_LANGUAGES,
1633
+ defaultVariants: GIT_WORKFLOW_DEFAULT_VARIANTS,
1634
+ scopePolicies: GIT_WORKFLOW_SCOPE_POLICIES,
1635
+ stagingPolicies: GIT_WORKFLOW_STAGING_POLICIES,
1636
+ deliveryModes: GIT_WORKFLOW_DELIVERY_MODES,
1637
+ verificationPolicies: GIT_WORKFLOW_VERIFICATION_POLICIES,
1638
+ };
1639
+ }
1640
+
1641
+ async function gitWorkflowPreferencesData(tab) {
1642
+ const [preferences, models] = await Promise.all([
1643
+ readGitWorkflowPreferences(),
1644
+ availableGitWorkflowModels(tab),
1645
+ ]);
1646
+ return {
1647
+ preferences,
1648
+ configured: isGitWorkflowSetupComplete(preferences),
1649
+ models,
1650
+ modelThinkingLevels: Object.fromEntries(models.map((model) => [gitWorkflowModelKey(model), supportedGitWorkflowThinkingLevels(model)])),
1651
+ options: gitWorkflowPreferenceOptions(),
1652
+ path: webuiSettingsFile(),
1563
1653
  };
1564
1654
  }
1565
1655
 
1566
- let webuiSettingsCache = null;
1656
+ function requireGitWorkflowChoice(value, key, choices) {
1657
+ const text = String(value ?? "").trim();
1658
+ if (!choices.includes(text)) throw makeHttpError(400, `${key} must be one of: ${choices.join(", ")}`);
1659
+ return text;
1660
+ }
1661
+
1662
+ async function saveGitWorkflowPreferencesData(tab, body = {}) {
1663
+ const submitted = body.preferences && typeof body.preferences === "object" ? body.preferences : body;
1664
+ if (submitted.generation?.thinkingLevel !== undefined) requireGitWorkflowChoice(submitted.generation.thinkingLevel, "generation.thinkingLevel", GIT_WORKFLOW_THINKING_LEVELS);
1665
+ if (submitted.commit?.language !== undefined) requireGitWorkflowChoice(submitted.commit.language, "commit.language", GIT_WORKFLOW_LANGUAGES);
1666
+ if (submitted.commit?.defaultVariant !== undefined) requireGitWorkflowChoice(submitted.commit.defaultVariant, "commit.defaultVariant", GIT_WORKFLOW_DEFAULT_VARIANTS);
1667
+ if (submitted.commit?.scope !== undefined) requireGitWorkflowChoice(submitted.commit.scope, "commit.scope", GIT_WORKFLOW_SCOPE_POLICIES);
1668
+ if (submitted.stagingPolicy !== undefined) requireGitWorkflowChoice(submitted.stagingPolicy, "stagingPolicy", GIT_WORKFLOW_STAGING_POLICIES);
1669
+ if (submitted.deliveryMode !== undefined) requireGitWorkflowChoice(submitted.deliveryMode, "deliveryMode", GIT_WORKFLOW_DELIVERY_MODES);
1670
+ if (submitted.verificationPolicy !== undefined) requireGitWorkflowChoice(submitted.verificationPolicy, "verificationPolicy", GIT_WORKFLOW_VERIFICATION_POLICIES);
1671
+
1672
+ const current = await readGitWorkflowPreferences();
1673
+ const next = mergeGitWorkflowPreferences(current, submitted);
1674
+ const provider = String(next.generation.provider || "").trim();
1675
+ const modelId = String(next.generation.modelId || "").trim();
1676
+ if (!provider || !modelId) throw makeHttpError(400, "Select a Git-writing model before saving setup");
1567
1677
 
1568
- async function readWebuiSettings() {
1569
- if (webuiSettingsCache) return webuiSettingsCache;
1570
- webuiSettingsCache = normalizeWebuiSettings(await readJsonFileIfExists(webuiSettingsFile()));
1571
- return webuiSettingsCache;
1678
+ const models = await availableGitWorkflowModels(tab);
1679
+ const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId);
1680
+ if (!model) throw makeHttpError(400, `Selected model is not currently available: ${provider}/${modelId}`);
1681
+ const supportedLevels = supportedGitWorkflowThinkingLevels(model);
1682
+ if (!supportedLevels.includes(next.generation.thinkingLevel)) {
1683
+ throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${next.generation.thinkingLevel}`);
1684
+ }
1685
+
1686
+ await writeGitWorkflowPreferences(next);
1687
+ return gitWorkflowPreferencesData(tab);
1572
1688
  }
1573
1689
 
1574
- async function writeWebuiSettings(patch) {
1575
- const current = await readWebuiSettings();
1576
- const next = normalizeWebuiSettings({ ...current, ...(patch || {}) });
1577
- const storageFile = webuiSettingsFile();
1578
- await mkdir(path.dirname(storageFile), { recursive: true });
1579
- const tmpFile = `${storageFile}.${process.pid}.${Date.now()}.tmp`;
1580
- await writeFile(tmpFile, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
1581
- await rename(tmpFile, storageFile);
1582
- webuiSettingsCache = next;
1583
- return next;
1690
+ function gitWorkflowGenerationPrompt(kind, preferences) {
1691
+ switch (kind) {
1692
+ case "commit":
1693
+ return `/git-staged-msg ${preferences.commit.language} ${preferences.commit.scope}`;
1694
+ case "branch":
1695
+ return "/git-branch-name";
1696
+ case "pr":
1697
+ return `/pr ${preferences.commit.language}`;
1698
+ default:
1699
+ throw makeHttpError(400, "generation kind must be commit, branch, or pr");
1700
+ }
1584
1701
  }
1585
1702
 
1586
- async function readPersistedRemoteAuthEnabled() {
1587
- return (await readWebuiSettings()).remoteAuthEnabled === true;
1703
+ async function restoreGitWorkflowGenerationProfile(tab) {
1704
+ const restore = tab?.gitWorkflowGenerationRestore;
1705
+ if (!restore) return;
1706
+ tab.gitWorkflowGenerationRestore = null;
1707
+ try {
1708
+ if (!tab.rpc?.isRunning?.()) return;
1709
+ if (restore.model?.provider && restore.model?.id) {
1710
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: restore.model.provider, modelId: restore.model.id });
1711
+ if (modelResponse.success === false) throw new Error(modelResponse.error || "Failed to restore model");
1712
+ }
1713
+ if (restore.thinkingLevel) {
1714
+ const thinkingResponse = await setThinkingLevelForTab(tab, restore.thinkingLevel, { allowPending: false });
1715
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || "Failed to restore thinking level");
1716
+ }
1717
+ recordEvent({ type: "git_workflow_generation_profile_restored", tabId: tab.id, tabTitle: tab.title });
1718
+ } catch (error) {
1719
+ recordEvent({ type: "git_workflow_generation_profile_restore_failed", tabId: tab.id, tabTitle: tab.title, error: sanitizeError(error) });
1720
+ }
1588
1721
  }
1589
1722
 
1590
- async function saveRemoteAuthPreference(enabled) {
1591
- const nextEnabled = enabled === true;
1592
- await writeWebuiSettings({ remoteAuthEnabled: nextEnabled });
1593
- persistedRemoteAuthEnabled = nextEnabled;
1594
- return persistedRemoteAuthEnabled;
1723
+ async function startGitWorkflowGeneration(tab, body = {}) {
1724
+ if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
1725
+ const preferences = await readGitWorkflowPreferences();
1726
+ if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
1727
+
1728
+ const state = await currentSessionState(tab);
1729
+ if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
1730
+ const models = await availableGitWorkflowModels(tab);
1731
+ const selectedModel = models.find((model) => model.provider === preferences.generation.provider && model.id === preferences.generation.modelId);
1732
+ if (!selectedModel) throw makeHttpError(409, `Configured Git-writing model is unavailable: ${preferences.generation.provider}/${preferences.generation.modelId}. Open Guided Git Setup to choose another model.`);
1733
+ const supportedLevels = supportedGitWorkflowThinkingLevels(selectedModel);
1734
+ if (!supportedLevels.includes(preferences.generation.thinkingLevel)) {
1735
+ throw makeHttpError(409, `Configured thinking level ${preferences.generation.thinkingLevel} is unavailable for ${gitWorkflowModelKey(selectedModel)}. Open Guided Git Setup to update it.`);
1736
+ }
1737
+
1738
+ const restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
1739
+ tab.gitWorkflowGenerationRestore = restore;
1740
+ try {
1741
+ if (gitWorkflowModelKey(state.model) !== gitWorkflowModelKey(selectedModel)) {
1742
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: selectedModel.provider, modelId: selectedModel.id });
1743
+ if (modelResponse.success === false) throw new Error(modelResponse.error || `Failed to select ${gitWorkflowModelKey(selectedModel)}`);
1744
+ }
1745
+ const thinkingResponse = await setThinkingLevelForTab(tab, preferences.generation.thinkingLevel, { allowPending: false });
1746
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${preferences.generation.thinkingLevel}`);
1747
+
1748
+ const kind = String(body.kind || "").trim();
1749
+ const message = gitWorkflowGenerationPrompt(kind, preferences);
1750
+ markTabWorking(tab);
1751
+ const response = await tab.rpc.send({ type: "prompt", message });
1752
+ if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
1753
+ return {
1754
+ accepted: true,
1755
+ kind,
1756
+ message,
1757
+ generation: {
1758
+ provider: selectedModel.provider,
1759
+ modelId: selectedModel.id,
1760
+ thinkingLevel: preferences.generation.thinkingLevel,
1761
+ },
1762
+ };
1763
+ } catch (error) {
1764
+ markTabIdle(tab);
1765
+ await restoreGitWorkflowGenerationProfile(tab);
1766
+ throw error;
1767
+ }
1595
1768
  }
1596
1769
 
1597
1770
  function parseCliScopedModelPatterns() {
@@ -3957,7 +4130,7 @@ const GIT_STATUS_KIND_RANK = Object.freeze({ changed: 0, untracked: 1, modified:
3957
4130
  async function getGitRoot(cwd) {
3958
4131
  const result = await runCommand("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 2000 });
3959
4132
  if (result.exitCode !== 0) {
3960
- throw new Error((result.stderr || result.stdout || "Not inside a git repository").trim());
4133
+ throw makeUserFacingError((result.stderr || result.stdout || "Not inside a git repository").trim());
3961
4134
  }
3962
4135
  return path.resolve(result.stdout.trim());
3963
4136
  }
@@ -3971,7 +4144,7 @@ async function runGitReadCommandDetailed(root, args, { timeoutMs = GIT_CHANGES_C
3971
4144
  const message = result.timedOut
3972
4145
  ? `${command} timed out`
3973
4146
  : (result.stderr || result.stdout || result.error || `${command} failed with exit code ${result.exitCode ?? "unknown"}`);
3974
- throw new Error(String(message).trim());
4147
+ throw makeUserFacingError(String(message).trim());
3975
4148
  }
3976
4149
 
3977
4150
  async function runGitReadCommand(root, args, options = {}) {
@@ -5673,7 +5846,10 @@ function runWorkflowCommand(command, args, { cwd, label = formatWorkflowCommand(
5673
5846
  stderr += String(chunk);
5674
5847
  if (stderr.length > 100000) stderr = stderr.slice(-100000);
5675
5848
  });
5676
- child.on("error", (error) => finish({ exitCode: undefined, stderr: stderr || sanitizeError(error), error: sanitizeError(error) }));
5849
+ child.on("error", (error) => {
5850
+ const message = formatCommandSpawnError(command, error);
5851
+ finish({ exitCode: undefined, stderr: stderr || message, error: message, errorCode: error?.code });
5852
+ });
5677
5853
  // "close", not "exit": exit can fire before the stdio pipes flush,
5678
5854
  // intermittently truncating collected stdout/stderr.
5679
5855
  child.on("close", (exitCode, signal) => finish({ exitCode, signal }));
@@ -6627,6 +6803,71 @@ function clearExtensionWidgets(tab) {
6627
6803
  tab?.extensionWidgets?.clear();
6628
6804
  }
6629
6805
 
6806
+ function clearWebuiSubagents(tab) {
6807
+ if (tab) tab.webuiSubagents = null;
6808
+ }
6809
+
6810
+ function normalizeWebuiSubagentText(value, maxLength = 240) {
6811
+ const text = String(value || "").trim();
6812
+ return text ? text.slice(0, maxLength) : "";
6813
+ }
6814
+
6815
+ function normalizeWebuiSubagentPayload(value) {
6816
+ if (!value || typeof value !== "object" || value.version !== 1) return null;
6817
+ const runs = [];
6818
+ for (const rawRun of Array.isArray(value.runs) ? value.runs.slice(0, WEBUI_SUBAGENT_RUN_LIMIT) : []) {
6819
+ if (!rawRun || typeof rawRun !== "object") continue;
6820
+ const id = normalizeWebuiSubagentText(rawRun.id, 160);
6821
+ if (!id) continue;
6822
+ const agents = [];
6823
+ for (const rawAgent of Array.isArray(rawRun.agents) ? rawRun.agents.slice(0, WEBUI_SUBAGENT_AGENT_LIMIT) : []) {
6824
+ const name = normalizeWebuiSubagentText(rawAgent?.name, 160);
6825
+ if (!name || rawAgent?.status !== "running") continue;
6826
+ agents.push({
6827
+ id: normalizeWebuiSubagentText(rawAgent.id || `${id}:${agents.length}`, 240),
6828
+ name,
6829
+ status: "running",
6830
+ index: Number.isInteger(rawAgent.index) ? rawAgent.index : agents.length,
6831
+ currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
6832
+ activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
6833
+ nested: rawAgent.nested === true,
6834
+ });
6835
+ }
6836
+ if (!agents.length) continue;
6837
+ runs.push({
6838
+ id,
6839
+ source: rawRun.source === "foreground" ? "foreground" : "async",
6840
+ mode: ["single", "parallel", "chain"].includes(rawRun.mode) ? rawRun.mode : "single",
6841
+ status: "running",
6842
+ startedAt: Number.isFinite(rawRun.startedAt) ? rawRun.startedAt : Date.now(),
6843
+ agents: agents.sort((a, b) => a.index - b.index || a.name.localeCompare(b.name)),
6844
+ });
6845
+ }
6846
+ return {
6847
+ version: 1,
6848
+ available: value.available === true,
6849
+ updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
6850
+ receivedAt: Date.now(),
6851
+ runs: runs.sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id)),
6852
+ };
6853
+ }
6854
+
6855
+ function rememberWebuiSubagentsStatusEvent(tab, event) {
6856
+ if (event?.type !== "extension_ui_request" || event.method !== "setStatus" || event.statusKey !== WEBUI_SUBAGENTS_STATUS_KEY) return false;
6857
+ const statusText = String(event.statusText || "");
6858
+ if (!statusText) {
6859
+ clearWebuiSubagents(tab);
6860
+ return true;
6861
+ }
6862
+ if (!statusText.startsWith(WEBUI_SUBAGENTS_PAYLOAD_PREFIX)) return true;
6863
+ try {
6864
+ tab.webuiSubagents = normalizeWebuiSubagentPayload(JSON.parse(statusText.slice(WEBUI_SUBAGENTS_PAYLOAD_PREFIX.length)));
6865
+ } catch {
6866
+ tab.webuiSubagents = null;
6867
+ }
6868
+ return true;
6869
+ }
6870
+
6630
6871
  function naturalConversationStatusState(statusText) {
6631
6872
  const text = stripAnsi(statusText).replace(/\s+/g, " ").trim();
6632
6873
  if (!text) return { enabled: false, uiState: "off", statusText: "" };
@@ -7207,13 +7448,15 @@ function attachRpcToTab(tab, rpc) {
7207
7448
  tab.rpcUnsubscribe?.();
7208
7449
  tab.rpc = rpc;
7209
7450
  tab.rpcUnsubscribe = rpc.onEvent((event) => {
7210
- if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event)) return;
7451
+ if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event)) return;
7211
7452
  updateTabActivityFromEvent(tab, event);
7212
7453
  let scopedEvent = eventForTabClients(tab, event);
7213
7454
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
7455
+ tab.gitWorkflowGenerationRestore = null;
7214
7456
  clearPendingExtensionUiRequests(tab);
7215
7457
  clearExtensionStatuses(tab);
7216
7458
  clearExtensionWidgets(tab);
7459
+ clearWebuiSubagents(tab);
7217
7460
  resetNaturalConversationMode(tab);
7218
7461
  } else {
7219
7462
  rememberExtensionStatusEvent(tab, scopedEvent);
@@ -7225,6 +7468,7 @@ function attachRpcToTab(tab, rpc) {
7225
7468
  recordEvent(scopedEvent);
7226
7469
  for (const client of tab.sseClients) sendSse(client, scopedEvent);
7227
7470
  if (event?.type === "compaction_end" && event.aborted !== true) void flushCompactionQueue(tab, event);
7471
+ if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
7228
7472
  });
7229
7473
  }
7230
7474
 
@@ -7254,10 +7498,12 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
7254
7498
  gitWorkspace: gitWorkspace || null,
7255
7499
  lastState: null,
7256
7500
  pendingThinkingLevel: undefined,
7501
+ gitWorkflowGenerationRestore: null,
7257
7502
  activity: createTabActivity(createdAt),
7258
7503
  pendingExtensionUiRequests: new Map(),
7259
7504
  extensionStatuses: new Map(),
7260
7505
  extensionWidgets: new Map(),
7506
+ webuiSubagents: null,
7261
7507
  webuiHelperRequests: new Map(),
7262
7508
  webuiHelperResponseIds: new Set(),
7263
7509
  bashQueue: [],
@@ -7320,6 +7566,84 @@ function listTabs() {
7320
7566
  return [...tabs.values()].map(tabMeta);
7321
7567
  }
7322
7568
 
7569
+ function webuiSubagentsData() {
7570
+ const sortedTabs = [...tabs.values()].sort((a, b) => a.index - b.index || a.title.localeCompare(b.title));
7571
+ const tabSummaries = sortedTabs.map((tab) => {
7572
+ const status = tab.webuiSubagents || { version: 1, available: false, updatedAt: null, receivedAt: null, runs: [] };
7573
+ const runs = Array.isArray(status.runs) ? status.runs : [];
7574
+ return {
7575
+ tabId: tab.id,
7576
+ tabIndex: tab.index,
7577
+ tabTitle: tab.title,
7578
+ cwd: tab.cwd,
7579
+ sessionName: normalizeWebuiSubagentText(tab.lastState?.sessionName || tab.title, 160),
7580
+ sessionFile: tabRestorableSessionFile(tab) || null,
7581
+ running: tab.rpc.isRunning(),
7582
+ available: status.available === true,
7583
+ updatedAt: status.updatedAt || null,
7584
+ receivedAt: status.receivedAt || null,
7585
+ runs,
7586
+ agentCount: runs.reduce((count, run) => count + run.agents.length, 0),
7587
+ };
7588
+ });
7589
+ return {
7590
+ version: 1,
7591
+ updatedAt: Date.now(),
7592
+ available: tabSummaries.some((tab) => tab.available),
7593
+ totalRuns: tabSummaries.reduce((count, tab) => count + tab.runs.length, 0),
7594
+ totalAgents: tabSummaries.reduce((count, tab) => count + tab.agentCount, 0),
7595
+ tabs: tabSummaries,
7596
+ };
7597
+ }
7598
+
7599
+ function normalizeWebuiSubagentOutput(value, selection) {
7600
+ if (!value || typeof value !== "object" || value.version !== 1) throw makeHttpError(502, "Invalid subagent output response from Web UI helper");
7601
+ const rawAgent = value.agent && typeof value.agent === "object" ? value.agent : {};
7602
+ const recentOutput = (Array.isArray(rawAgent.recentOutput) ? rawAgent.recentOutput : [])
7603
+ .slice(-WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT)
7604
+ .map((line) => String(line ?? "").replace(/\r/g, "").slice(0, WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH));
7605
+ const recentTools = (Array.isArray(rawAgent.recentTools) ? rawAgent.recentTools : []).slice(-20).map((entry) => ({
7606
+ tool: normalizeWebuiSubagentText(entry?.tool, 120),
7607
+ args: normalizeWebuiSubagentText(entry?.args, 500),
7608
+ endMs: Number.isFinite(entry?.endMs) ? entry.endMs : undefined,
7609
+ })).filter((entry) => entry.tool);
7610
+ return {
7611
+ version: 1,
7612
+ runId: normalizeWebuiSubagentText(value.runId, 160) || selection.run.id,
7613
+ source: value.source === "foreground" ? "foreground" : "async",
7614
+ mode: ["single", "parallel", "chain"].includes(value.mode) ? value.mode : selection.run.mode,
7615
+ startedAt: Number.isFinite(value.startedAt) ? value.startedAt : selection.run.startedAt,
7616
+ updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
7617
+ agent: {
7618
+ id: selection.agent.id,
7619
+ name: normalizeWebuiSubagentText(rawAgent.name, 160) || selection.agent.name,
7620
+ index: Number.isInteger(rawAgent.index) ? rawAgent.index : selection.agent.index,
7621
+ nested: rawAgent.nested === true,
7622
+ status: normalizeWebuiSubagentText(rawAgent.status, 40) || "running",
7623
+ activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
7624
+ currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
7625
+ currentToolArgs: normalizeWebuiSubagentText(rawAgent.currentToolArgs, 500) || undefined,
7626
+ currentPath: normalizeWebuiSubagentText(rawAgent.currentPath, 1000) || undefined,
7627
+ turnCount: Number.isFinite(rawAgent.turnCount) ? rawAgent.turnCount : undefined,
7628
+ toolCount: Number.isFinite(rawAgent.toolCount) ? rawAgent.toolCount : undefined,
7629
+ tokens: Number.isFinite(rawAgent.tokens) ? rawAgent.tokens : undefined,
7630
+ recentTools,
7631
+ recentOutput,
7632
+ error: normalizeWebuiSubagentText(rawAgent.error, 1000) || undefined,
7633
+ },
7634
+ };
7635
+ }
7636
+
7637
+ async function webuiSubagentOutputData(tab, runId, agentId) {
7638
+ const runs = Array.isArray(tab.webuiSubagents?.runs) ? tab.webuiSubagents.runs : [];
7639
+ const run = runs.find((candidate) => candidate.id === runId);
7640
+ if (!run) throw makeHttpError(404, `Running subagent run not found: ${runId}`);
7641
+ const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate.id === agentId);
7642
+ if (!agent) throw makeHttpError(404, `Running subagent not found: ${agentId}`);
7643
+ const data = await sendWebuiHelperCommand(tab, "subagent-output", { runId, agentId });
7644
+ return normalizeWebuiSubagentOutput(data, { run, agent });
7645
+ }
7646
+
7323
7647
  function restorableTabDescriptor(tab, state = null) {
7324
7648
  return normalizeRestoreTabDescriptor({
7325
7649
  id: tab.id,
@@ -7909,6 +8233,7 @@ async function updateTabCwd(id, cwd) {
7909
8233
  clearPendingExtensionUiRequests(tab);
7910
8234
  clearExtensionStatuses(tab);
7911
8235
  clearExtensionWidgets(tab);
8236
+ clearWebuiSubagents(tab);
7912
8237
  resetNaturalConversationMode(tab);
7913
8238
  const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
7914
8239
  attachRpcToTab(tab, rpc);
@@ -7948,6 +8273,7 @@ async function restartTabRpc(tab, reason = "reload") {
7948
8273
  clearPendingExtensionUiRequests(tab);
7949
8274
  clearExtensionStatuses(tab);
7950
8275
  clearExtensionWidgets(tab);
8276
+ clearWebuiSubagents(tab);
7951
8277
  resetNaturalConversationMode(tab);
7952
8278
  const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
7953
8279
  attachRpcToTab(tab, rpc);
@@ -9877,6 +10203,7 @@ async function handleNativeSlashCommand(tab, body, req) {
9877
10203
  clearPendingExtensionUiRequests(tab);
9878
10204
  clearExtensionStatuses(tab);
9879
10205
  clearExtensionWidgets(tab);
10206
+ clearWebuiSubagents(tab);
9880
10207
  resetNaturalConversationMode(tab);
9881
10208
  return respondNative("new", {
9882
10209
  status: "succeeded",
@@ -10471,6 +10798,20 @@ const server = createServer(async (req, res) => {
10471
10798
  return;
10472
10799
  }
10473
10800
 
10801
+ if (url.pathname === "/api/subagents" && req.method === "GET") {
10802
+ sendJson(res, 200, { ok: true, data: webuiSubagentsData() });
10803
+ return;
10804
+ }
10805
+
10806
+ if (url.pathname === "/api/subagents/output" && req.method === "GET") {
10807
+ const tab = getRequestedTab(req, url);
10808
+ const runId = normalizeWebuiSubagentText(url.searchParams.get("run"), 160);
10809
+ const agentId = normalizeWebuiSubagentText(url.searchParams.get("agent"), 240);
10810
+ if (!runId || !agentId) throw makeHttpError(400, "run and agent query parameters are required");
10811
+ sendJson(res, 200, { ok: true, data: await webuiSubagentOutputData(tab, runId, agentId) });
10812
+ return;
10813
+ }
10814
+
10474
10815
  if (url.pathname === "/api/tabs" && req.method === "POST") {
10475
10816
  const body = await readJsonBody(req);
10476
10817
  const tab = await createTab({ title: body.title, cwd: body.cwd });
@@ -11070,6 +11411,28 @@ const server = createServer(async (req, res) => {
11070
11411
  return;
11071
11412
  }
11072
11413
 
11414
+ if (url.pathname === "/api/git-workflow/preferences" && req.method === "GET") {
11415
+ const tab = getRequestedTab(req, url);
11416
+ sendJson(res, 200, { ok: true, data: await gitWorkflowPreferencesData(tab) });
11417
+ return;
11418
+ }
11419
+
11420
+ if (url.pathname === "/api/git-workflow/preferences" && req.method === "POST") {
11421
+ const body = await readJsonBody(req);
11422
+ const tab = getRequestedTab(req, url, body);
11423
+ ensureNaturalConversationRouteAllowed(tab, "guided Git setup changes are blocked");
11424
+ sendJson(res, 200, { ok: true, data: await saveGitWorkflowPreferencesData(tab, body) });
11425
+ return;
11426
+ }
11427
+
11428
+ if (url.pathname === "/api/git-workflow/generate" && req.method === "POST") {
11429
+ const body = await readJsonBody(req);
11430
+ const tab = getRequestedTab(req, url, body);
11431
+ ensureNaturalConversationRouteAllowed(tab, "guided Git generation is blocked");
11432
+ sendJson(res, 200, { ok: true, data: await startGitWorkflowGeneration(tab, body) });
11433
+ return;
11434
+ }
11435
+
11073
11436
  if (url.pathname === "/api/settings" && req.method === "GET") {
11074
11437
  const tab = getRequestedTab(req, url);
11075
11438
  sendJson(res, 200, { ok: true, data: nativeSettingsPayload(settingsManagerForTab(tab)) });
@@ -11406,6 +11769,7 @@ const server = createServer(async (req, res) => {
11406
11769
  clearPendingExtensionUiRequests(tab);
11407
11770
  clearExtensionStatuses(tab);
11408
11771
  clearExtensionWidgets(tab);
11772
+ clearWebuiSubagents(tab);
11409
11773
  resetNaturalConversationMode(tab);
11410
11774
  }
11411
11775
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));