@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/public/app.js CHANGED
@@ -108,6 +108,7 @@ const elements = {
108
108
  optionsNameButton: $("#optionsNameButton"),
109
109
  optionsCloneButton: $("#optionsCloneButton"),
110
110
  optionsSettingsButton: $("#optionsSettingsButton"),
111
+ optionsGitWorkflowSetupButton: $("#optionsGitWorkflowSetupButton"),
111
112
  optionsExportButton: $("#optionsExportButton"),
112
113
  optionsForkButton: $("#optionsForkButton"),
113
114
  optionsTreeButton: $("#optionsTreeButton"),
@@ -208,6 +209,9 @@ const elements = {
208
209
  sidePanelBackdrop: $("#sidePanelBackdrop"),
209
210
  sidePanel: $("#sidePanel"),
210
211
  stateDetails: $("#stateDetails"),
212
+ subagentsStatus: $("#subagentsStatus"),
213
+ subagentsBox: $("#subagentsBox"),
214
+ subagentCountBadge: $("#subagentCountBadge"),
211
215
  queueBox: $("#queueBox"),
212
216
  queueCountBadge: $("#queueCountBadge"),
213
217
  createPromptListButton: $("#createPromptListButton"),
@@ -426,6 +430,16 @@ let claudeUsageError = null;
426
430
  let claudeUsageLoading = false;
427
431
  let refreshClaudeUsageTimer = null;
428
432
  let claudeUsageRenderTimer = null;
433
+ let latestSubagents = null;
434
+ let subagentsError = null;
435
+ let subagentsLoading = false;
436
+ let refreshSubagentsTimer = null;
437
+ let subagentOverlaySelection = null;
438
+ let subagentOverlayData = null;
439
+ let subagentOverlayError = "";
440
+ let subagentOverlayLoading = false;
441
+ let subagentOverlayRefreshTimer = null;
442
+ let subagentOverlayRequestSerial = 0;
429
443
  let backendOffline = false;
430
444
  let serverRestartInProgress = false;
431
445
  let updateRequestInProgress = false;
@@ -676,6 +690,10 @@ const CODEX_USAGE_REFRESH_MS = 5 * 60 * 1000;
676
690
  const CODEX_USAGE_RENDER_TICK_MS = 30 * 1000;
677
691
  const CLAUDE_USAGE_REFRESH_MS = 5 * 60 * 1000;
678
692
  const CLAUDE_USAGE_RENDER_TICK_MS = 30 * 1000;
693
+ const SUBAGENTS_ACTIVE_REFRESH_MS = 1500;
694
+ const SUBAGENTS_IDLE_REFRESH_MS = 4000;
695
+ const SUBAGENTS_HIDDEN_REFRESH_MS = 10_000;
696
+ const SUBAGENT_OVERLAY_REFRESH_MS = 1000;
679
697
  const UPDATE_STATUS_REFRESH_MS = 6 * 60 * 60 * 1000;
680
698
  const UPDATE_STATUS_INITIAL_DELAY_MS = 1800;
681
699
  const RUN_INDICATOR_TICK_MS = 1000;
@@ -925,8 +943,8 @@ const HIDDEN_COMMAND_NAMES = new Set(["webui-tree-navigate", "webui-helper"]);
925
943
  HIDDEN_COMMAND_NAMES.add("stats-webui");
926
944
  HIDDEN_COMMAND_NAMES.add("btw-status");
927
945
  HIDDEN_COMMAND_NAMES.add("btw-transfer");
928
- const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
929
- const SETTINGS_THINKING_OPTIONS = ["off", "minimal", "low", "medium", "high", "xhigh"];
946
+ const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
947
+ const SETTINGS_THINKING_OPTIONS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
930
948
  const SETTINGS_TRANSPORT_OPTIONS = ["sse", "websocket", "websocket-cached", "auto"];
931
949
  const SETTINGS_HTTP_IDLE_TIMEOUT_OPTIONS = [
932
950
  { value: "30000", label: "30 sec" },
@@ -1023,11 +1041,14 @@ function createGitWorkflowState() {
1023
1041
  prBranch: "",
1024
1042
  pr: null,
1025
1043
  prRequestedAt: 0,
1044
+ preferences: null,
1045
+ verificationConfirmed: false,
1026
1046
  };
1027
1047
  }
1028
1048
 
1029
1049
  const gitWorkflowsByTab = new Map();
1030
1050
  let gitWorkflow = createGitWorkflowState();
1051
+ let gitWorkflowPreferences = null;
1031
1052
 
1032
1053
  function gitWorkflowForTab(tabId = activeTabId, { create = true } = {}) {
1033
1054
  if (!tabId) return null;
@@ -7001,7 +7022,7 @@ function restoreActiveDraft() {
7001
7022
 
7002
7023
  function focusPromptInput({ defer = false } = {}) {
7003
7024
  const focus = () => {
7004
- if (!elements.promptInput || elements.dialog.open || elements.pathPickerDialog.open || elements.gitChangesDialog?.open || elements.commandPaletteDialog?.open || elements.editRetryDialog?.open || elements.nativeCommandDialog.open || elements.remoteQrDialog?.open || elements.appRunnerInfoDialog?.open || elements.gitFooterVisibilityDialog?.open || elements.promptListDialog?.open || elements.attachmentTextDialog?.open || elements.skillEditorDialog?.open || document.visibilityState === "hidden") return;
7025
+ if (!elements.promptInput || elements.dialog.open || elements.pathPickerDialog.open || elements.gitChangesDialog?.open || elements.commandPaletteDialog?.open || elements.editRetryDialog?.open || elements.nativeCommandDialog.open || elements.remoteQrDialog?.open || elements.appRunnerInfoDialog?.open || elements.gitFooterVisibilityDialog?.open || elements.statsOverlayDialog?.open || elements.promptListDialog?.open || elements.attachmentTextDialog?.open || elements.skillEditorDialog?.open || document.visibilityState === "hidden") return;
7005
7026
  try {
7006
7027
  elements.promptInput.focus({ preventScroll: true });
7007
7028
  } catch {
@@ -8386,7 +8407,7 @@ function applyOptimisticThinkingSelection(data, tabContext = activeTabContext())
8386
8407
 
8387
8408
  function footerThinkingLevels() {
8388
8409
  const levels = Array.from(elements.thinkingSelect?.options || []).map((option) => option.value).filter(Boolean);
8389
- return levels.length ? levels : ["off", "minimal", "low", "medium", "high", "xhigh"];
8410
+ return levels.length ? levels : ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
8390
8411
  }
8391
8412
 
8392
8413
  function formatFooterTokenCount(value) {
@@ -13484,6 +13505,320 @@ function initializeClaudeUsage() {
13484
13505
  claudeUsageRenderTimer = setInterval(renderClaudeUsage, CLAUDE_USAGE_RENDER_TICK_MS);
13485
13506
  }
13486
13507
 
13508
+ function subagentTabsWithRunningAgents() {
13509
+ return (Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : [])
13510
+ .filter((tab) => Number(tab?.agentCount || 0) > 0)
13511
+ .sort((a, b) => Number(a.tabIndex || 0) - Number(b.tabIndex || 0) || String(a.tabTitle || "").localeCompare(String(b.tabTitle || "")));
13512
+ }
13513
+
13514
+ function subagentSessionFileName(value) {
13515
+ return String(value || "").split(/[\\/]/).filter(Boolean).pop() || "";
13516
+ }
13517
+
13518
+ function subagentTabMeta(tab) {
13519
+ const sessionName = String(tab?.sessionName || "").trim();
13520
+ const title = String(tab?.tabTitle || "").trim();
13521
+ if (sessionName && sessionName !== title) return sessionName;
13522
+ return subagentSessionFileName(tab?.sessionFile) || normalizeDisplayPath(tab?.cwd || "") || "session";
13523
+ }
13524
+
13525
+ function subagentRunElapsed(run) {
13526
+ const startedAt = Number(run?.startedAt);
13527
+ return Number.isFinite(startedAt) ? formatDuration(Math.max(0, Date.now() - startedAt)) : "";
13528
+ }
13529
+
13530
+ function subagentOverlayOutputLines(data = subagentOverlayData) {
13531
+ const agent = data?.agent || subagentOverlaySelection?.agent || {};
13532
+ const output = (Array.isArray(agent.recentOutput) ? agent.recentOutput : [])
13533
+ .flatMap((line) => stripAnsi(String(line ?? "")).replace(/\r/g, "").split("\n"));
13534
+ if (output.length) return output;
13535
+ const tools = (Array.isArray(agent.recentTools) ? agent.recentTools : [])
13536
+ .map((entry) => `✓ ${entry.tool || "tool"}${entry.args ? ` ${entry.args}` : ""}`);
13537
+ if (agent.currentTool) tools.push(`▶ ${agent.currentTool}${agent.currentToolArgs ? ` ${agent.currentToolArgs}` : ""}`);
13538
+ return tools;
13539
+ }
13540
+
13541
+ function appendSubagentOutputWaitingIndicator(parent) {
13542
+ const row = make("div", "release-npm-line subagent-output-waiting");
13543
+ row.setAttribute("role", "status");
13544
+ row.setAttribute("aria-label", "Waiting for agent output");
13545
+ row.append(
13546
+ make("span", "subagent-output-waiting-dot", "."),
13547
+ make("span", "subagent-output-waiting-dot", "."),
13548
+ make("span", "subagent-output-waiting-dot", "."),
13549
+ );
13550
+ parent.append(row);
13551
+ }
13552
+
13553
+ function subagentOverlayStateFacts(data = subagentOverlayData) {
13554
+ const agent = data?.agent || subagentOverlaySelection?.agent || {};
13555
+ return [
13556
+ agent.status || "running",
13557
+ data?.mode || subagentOverlaySelection?.run?.mode,
13558
+ data?.source || subagentOverlaySelection?.run?.source,
13559
+ agent.nested ? "nested" : "",
13560
+ agent.currentTool ? `tool ${agent.currentTool}` : "",
13561
+ Number.isFinite(agent.turnCount) ? `${agent.turnCount} turns` : "",
13562
+ Number.isFinite(agent.toolCount) ? `${agent.toolCount} tools` : "",
13563
+ Number.isFinite(agent.tokens) ? `${Number(agent.tokens).toLocaleString()} tokens` : "",
13564
+ ].filter(Boolean);
13565
+ }
13566
+
13567
+ function subagentOverlayMeaningfulSignature() {
13568
+ return JSON.stringify({
13569
+ selection: subagentOverlaySelection ? {
13570
+ tabId: subagentOverlaySelection.tabId,
13571
+ runId: subagentOverlaySelection.runId,
13572
+ agentId: subagentOverlaySelection.agentId,
13573
+ finished: subagentOverlaySelection.finished === true,
13574
+ } : null,
13575
+ data: subagentOverlayData ? { ...subagentOverlayData, updatedAt: undefined } : null,
13576
+ error: subagentOverlayError,
13577
+ });
13578
+ }
13579
+
13580
+ function renderSubagentOverlayWidget() {
13581
+ const selection = subagentOverlaySelection;
13582
+ if (!selection || selection.tabId !== activeTabId) return null;
13583
+ const data = subagentOverlayData;
13584
+ const agent = data?.agent || selection.agent || {};
13585
+ const tab = tabs.find((item) => item.id === selection.tabId) || selection.tab;
13586
+ const running = !selection.finished && (agent.status === "running" || agent.status === "queued" || agent.status === "pending" || !agent.status);
13587
+ const lines = subagentOverlayOutputLines(data);
13588
+ const shownLines = lines.length ? lines : running && agent.currentTool ? [] : [running ? "Waiting for the first agent activity…" : "No recent output was captured."];
13589
+ const widget = make("section", `widget release-npm-widget app-runner-widget subagent-overlay-widget${running ? " app-runner-live-widget" : " app-runner-log-widget"}`);
13590
+ widget.setAttribute("aria-label", `Live output for subagent ${agent.name || "subagent"}`);
13591
+
13592
+ const header = make("div", "release-npm-header");
13593
+ const titleWrap = make("div", "release-npm-title-wrap");
13594
+ titleWrap.append(make("span", "release-npm-kicker", "subagent"), make("strong", "release-npm-title", agent.name || "subagent"));
13595
+ const meta = make("div", "release-npm-meta");
13596
+ for (const fact of subagentOverlayStateFacts(data)) meta.append(make("span", "release-npm-pill", fact));
13597
+ header.append(titleWrap, meta);
13598
+
13599
+ const streamHeader = releaseNpmStreamHeader(running ? "Live agent output" : "Agent output", shownLines.length, { live: running });
13600
+ const terminal = make("div", "release-npm-terminal subagent-overlay-terminal");
13601
+ terminal.setAttribute("role", "log");
13602
+ terminal.setAttribute("aria-live", running ? "polite" : "off");
13603
+ for (const line of shownLines) appendReleaseNpmTerminalLine(terminal, line);
13604
+ if (running && agent.currentTool) appendSubagentOutputWaitingIndicator(terminal);
13605
+
13606
+ const controls = make("div", "release-npm-controls subagent-overlay-output-controls");
13607
+ const actions = make("div", "app-runner-output-actions");
13608
+ const copyButton = appRunnerActionButton("Copy output", copySubagentOverlayOutput, "subagent-overlay-copy-action");
13609
+ copyButton.disabled = subagentOverlayOutputLines(data).length === 0;
13610
+ const refreshButton = appRunnerActionButton(subagentOverlayLoading ? "Refreshing…" : "Refresh", () => {
13611
+ refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
13612
+ }, "subagent-overlay-refresh-action");
13613
+ refreshButton.disabled = subagentOverlayLoading || selection.finished;
13614
+ actions.append(copyButton, refreshButton, appRunnerActionButton("Close", closeSubagentOverlay, "subagent-overlay-close-action"));
13615
+ const details = [
13616
+ `${tab?.title || `Terminal ${selection.tabIndex || "?"}`} · run ${selection.runId}`,
13617
+ agent.currentPath ? `path: ${agent.currentPath}` : "",
13618
+ agent.activityState ? `activity: ${agent.activityState}` : "",
13619
+ agent.error ? `status warning: ${agent.error}` : "",
13620
+ subagentOverlayError,
13621
+ ].filter(Boolean);
13622
+ controls.append(actions, make("span", `app-runner-output-meta${subagentOverlayError ? " warning" : ""}`, details.join(" · ")));
13623
+ const outputDetails = renderReleaseNpmOutputDetails(`subagent:${selection.tabId}:${selection.agentId}`, streamHeader, terminal, controls);
13624
+ widget.append(header, outputDetails);
13625
+ requestAnimationFrame(() => { if (outputDetails.open) terminal.scrollTop = terminal.scrollHeight; });
13626
+ return widget;
13627
+ }
13628
+
13629
+ function scheduleSubagentOverlayRefresh(delay = SUBAGENT_OVERLAY_REFRESH_MS) {
13630
+ clearTimeout(subagentOverlayRefreshTimer);
13631
+ if (!subagentOverlaySelection || subagentOverlaySelection.finished) return;
13632
+ subagentOverlayRefreshTimer = setTimeout(() => {
13633
+ refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
13634
+ }, delay);
13635
+ }
13636
+
13637
+ async function refreshSubagentOverlay() {
13638
+ const selection = subagentOverlaySelection;
13639
+ if (!selection || subagentOverlayLoading) return;
13640
+ const requestSerial = ++subagentOverlayRequestSerial;
13641
+ const previousSignature = subagentOverlayMeaningfulSignature();
13642
+ subagentOverlayLoading = true;
13643
+ try {
13644
+ const query = new URLSearchParams({ tab: selection.tabId, run: selection.runId, agent: selection.agentId });
13645
+ const response = await api(`/api/subagents/output?${query}`, { scoped: false });
13646
+ if (requestSerial !== subagentOverlayRequestSerial || subagentOverlaySelection !== selection) return;
13647
+ subagentOverlayData = response.data || null;
13648
+ subagentOverlayError = "";
13649
+ } catch (error) {
13650
+ if (requestSerial !== subagentOverlayRequestSerial || subagentOverlaySelection !== selection) return;
13651
+ if (error?.statusCode === 404) selection.finished = true;
13652
+ subagentOverlayError = error?.statusCode === 404
13653
+ ? "This subagent has finished or is no longer tracked. Showing the last captured output."
13654
+ : `Subagent output refresh failed: ${error.message || String(error)}`;
13655
+ } finally {
13656
+ if (requestSerial === subagentOverlayRequestSerial && subagentOverlaySelection === selection) {
13657
+ subagentOverlayLoading = false;
13658
+ if (selection.tabId === activeTabId && previousSignature !== subagentOverlayMeaningfulSignature()) renderWidgets();
13659
+ }
13660
+ }
13661
+ }
13662
+
13663
+ async function openSubagentOverlay(tab, run, agent) {
13664
+ if (!tab?.tabId || !run?.id || !agent?.id) return;
13665
+ try {
13666
+ if (activeTabId !== tab.tabId) await switchTab(tab.tabId);
13667
+ subagentOverlaySelection = {
13668
+ tabId: tab.tabId,
13669
+ tabIndex: tab.tabIndex,
13670
+ tab,
13671
+ run,
13672
+ agent,
13673
+ runId: run.id,
13674
+ agentId: agent.id,
13675
+ finished: false,
13676
+ };
13677
+ subagentOverlayData = null;
13678
+ subagentOverlayError = "";
13679
+ subagentOverlayRequestSerial += 1;
13680
+ renderWidgets();
13681
+ await refreshSubagentOverlay();
13682
+ scheduleSubagentOverlayRefresh();
13683
+ } catch (error) {
13684
+ addEvent(`could not open subagent output: ${error.message || String(error)}`, "error");
13685
+ }
13686
+ }
13687
+
13688
+ function closeSubagentOverlay() {
13689
+ clearTimeout(subagentOverlayRefreshTimer);
13690
+ subagentOverlayRefreshTimer = null;
13691
+ subagentOverlayRequestSerial += 1;
13692
+ subagentOverlaySelection = null;
13693
+ subagentOverlayData = null;
13694
+ subagentOverlayError = "";
13695
+ subagentOverlayLoading = false;
13696
+ renderWidgets();
13697
+ }
13698
+
13699
+ async function copySubagentOverlayOutput() {
13700
+ const text = subagentOverlayOutputLines().join("\n").trimEnd();
13701
+ if (!text) {
13702
+ addEvent("subagent output is empty", "warn");
13703
+ return;
13704
+ }
13705
+ try {
13706
+ await copyText(text);
13707
+ addEvent("copied subagent output", "info");
13708
+ } catch (error) {
13709
+ addEvent(`subagent output copy failed: ${error.message || String(error)}`, "warn");
13710
+ }
13711
+ }
13712
+
13713
+ function renderSubagentAgent(tab, run, agent) {
13714
+ const row = make("button", `subagent-agent-row${agent?.nested ? " nested" : ""}`);
13715
+ row.type = "button";
13716
+ const dot = make("span", "subagent-running-dot");
13717
+ dot.setAttribute("aria-hidden", "true");
13718
+ const content = make("div", "subagent-agent-content");
13719
+ content.append(make("strong", "subagent-agent-name", agent?.name || "subagent"));
13720
+ const elapsed = subagentRunElapsed(run);
13721
+ const facts = [
13722
+ agent?.nested ? "nested" : "",
13723
+ run?.mode && run.mode !== "single" ? run.mode : "",
13724
+ run?.source === "foreground" ? "foreground" : "async",
13725
+ agent?.currentTool ? `tool: ${agent.currentTool}` : "",
13726
+ elapsed ? `running ${elapsed}` : "",
13727
+ ].filter(Boolean);
13728
+ content.append(make("span", "subagent-agent-meta", facts.join(" · ")));
13729
+ row.append(dot, content);
13730
+ row.title = `${agent?.name || "subagent"} · ${facts.join(" · ")} · run ${run?.id || "unknown"} · open live output`;
13731
+ row.setAttribute("aria-label", `Open live output for ${agent?.name || "subagent"} in ${tab?.tabTitle || `Terminal ${tab?.tabIndex || "?"}`}`);
13732
+ row.addEventListener("click", () => openSubagentOverlay(tab, run, agent));
13733
+ return row;
13734
+ }
13735
+
13736
+ function renderSubagentTabGroup(tab) {
13737
+ const group = make("section", `subagent-tab-group${tab.tabId === activeTabId ? " active" : ""}`);
13738
+ const header = make("button", "subagent-tab-header");
13739
+ header.type = "button";
13740
+ header.setAttribute("aria-label", `Open ${tab.tabTitle || `Terminal ${tab.tabIndex || ""}`}`);
13741
+ const title = make("span", "subagent-tab-title");
13742
+ title.append(
13743
+ make("strong", undefined, tab.tabTitle || `Terminal ${tab.tabIndex || "?"}`),
13744
+ make("span", "subagent-tab-session", `Terminal ${tab.tabIndex || "?"} · ${subagentTabMeta(tab)}`),
13745
+ );
13746
+ header.append(title, make("span", "subagent-tab-count", String(tab.agentCount || 0)));
13747
+ header.addEventListener("click", () => switchTab(tab.tabId));
13748
+ group.append(header);
13749
+
13750
+ const list = make("div", "subagent-agent-list");
13751
+ const runs = (Array.isArray(tab.runs) ? tab.runs : [])
13752
+ .slice()
13753
+ .sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0) || String(a.id || "").localeCompare(String(b.id || "")));
13754
+ for (const run of runs) {
13755
+ const agents = (Array.isArray(run.agents) ? run.agents : [])
13756
+ .filter((agent) => agent?.status === "running")
13757
+ .sort((a, b) => Number(a.index || 0) - Number(b.index || 0) || String(a.name || "").localeCompare(String(b.name || "")));
13758
+ for (const agent of agents) list.append(renderSubagentAgent(tab, run, agent));
13759
+ }
13760
+ group.append(list);
13761
+ return group;
13762
+ }
13763
+
13764
+ function renderSubagents() {
13765
+ const box = elements.subagentsBox;
13766
+ if (!box) return;
13767
+ const activeTabs = subagentTabsWithRunningAgents();
13768
+ const totalAgents = activeTabs.reduce((count, tab) => count + Number(tab.agentCount || 0), 0);
13769
+ if (elements.subagentCountBadge) {
13770
+ elements.subagentCountBadge.textContent = String(totalAgents);
13771
+ elements.subagentCountBadge.hidden = totalAgents === 0;
13772
+ }
13773
+ if (elements.subagentsStatus) {
13774
+ elements.subagentsStatus.textContent = totalAgents > 0
13775
+ ? `${totalAgents} running across ${activeTabs.length} ${activeTabs.length === 1 ? "terminal" : "terminals"}`
13776
+ : subagentsLoading && !latestSubagents
13777
+ ? "Checking running subagents…"
13778
+ : "No running subagents.";
13779
+ }
13780
+
13781
+ box.replaceChildren();
13782
+ box.classList.toggle("muted", totalAgents === 0);
13783
+ box.classList.toggle("has-items", totalAgents > 0);
13784
+ if (totalAgents === 0) {
13785
+ box.append(make("div", "subagents-empty", subagentsError ? `Subagent status unavailable: ${subagentsError.message || subagentsError}` : "Running subagents will appear here, grouped by terminal and session."));
13786
+ return;
13787
+ }
13788
+ for (const tab of activeTabs) box.append(renderSubagentTabGroup(tab));
13789
+ if (subagentsError) box.append(make("div", "subagents-stale muted", `Latest refresh failed: ${subagentsError.message || subagentsError}`));
13790
+ }
13791
+
13792
+ async function refreshSubagents() {
13793
+ if (subagentsLoading) return;
13794
+ subagentsLoading = true;
13795
+ renderSubagents();
13796
+ try {
13797
+ const response = await api("/api/subagents", { scoped: false });
13798
+ latestSubagents = response.data || null;
13799
+ subagentsError = null;
13800
+ } catch (error) {
13801
+ subagentsError = error;
13802
+ } finally {
13803
+ subagentsLoading = false;
13804
+ renderSubagents();
13805
+ }
13806
+ }
13807
+
13808
+ function scheduleRefreshSubagents(delay) {
13809
+ clearTimeout(refreshSubagentsTimer);
13810
+ const totalAgents = Number(latestSubagents?.totalAgents || 0);
13811
+ const nextDelay = delay ?? (document.visibilityState === "hidden" ? SUBAGENTS_HIDDEN_REFRESH_MS : totalAgents > 0 ? SUBAGENTS_ACTIVE_REFRESH_MS : SUBAGENTS_IDLE_REFRESH_MS);
13812
+ refreshSubagentsTimer = setTimeout(() => {
13813
+ refreshSubagents().finally(() => scheduleRefreshSubagents());
13814
+ }, nextDelay);
13815
+ }
13816
+
13817
+ function initializeSubagents() {
13818
+ renderSubagents();
13819
+ refreshSubagents().finally(() => scheduleRefreshSubagents());
13820
+ }
13821
+
13487
13822
  function renderStatus() {
13488
13823
  if (deferUiRenderDuringPointerActivation("status", renderStatus)) return;
13489
13824
  const state = currentState;
@@ -15989,6 +16324,8 @@ function renderWidgets() {
15989
16324
  if (workflowSubprocessWidget) elements.widgetArea.append(workflowSubprocessWidget);
15990
16325
  const appRunnerWidget = renderAppRunnerWidget();
15991
16326
  if (appRunnerWidget) elements.widgetArea.append(appRunnerWidget);
16327
+ const subagentWidget = renderSubagentOverlayWidget();
16328
+ if (subagentWidget) elements.widgetArea.append(subagentWidget);
15992
16329
  const btwWidget = renderBtwOutputWidget();
15993
16330
  if (btwWidget) elements.widgetArea.append(btwWidget);
15994
16331
 
@@ -16541,7 +16878,7 @@ function gitWorkflowTitle() {
16541
16878
  case "remoteAdding": return "Adding origin remote";
16542
16879
  case "initialPush": return "Push main upstream";
16543
16880
  case "initialPushing": return "Pushing main";
16544
- case "add": return "Stage all changes";
16881
+ case "add": return (gitWorkflow.preferences || gitWorkflowPreferences)?.stagingPolicy === "all" ? "Stage all changes" : "Review staged changes";
16545
16882
  case "generate": return "Generate staged commit message";
16546
16883
  case "generating": return "Waiting for /git-staged-msg";
16547
16884
  case "message": return gitWorkflow.prMode ? "Choose PR branch commit message" : "Choose commit message";
@@ -16578,7 +16915,9 @@ function gitWorkflowHint() {
16578
16915
  case "remoteAdding": return "Adding the GitHub origin remote.";
16579
16916
  case "initialPush": return "Step 7: run git push -u origin main.";
16580
16917
  case "initialPushing": return "Pushing main upstream. Authentication must already be available to git.";
16581
- case "add": return "Step 1: run git add . in the current Pi working directory.";
16918
+ case "add": return (gitWorkflow.preferences || gitWorkflowPreferences)?.stagingPolicy === "all"
16919
+ ? "Step 1: explicitly stage all changes with git add ."
16920
+ : "Step 1: review changes, stage only intended files, then accept the current staged set.";
16582
16921
  case "generate": return "Step 2: run /git-staged-msg, or type a commit message and use Commit input.";
16583
16922
  case "generating": return "Pi is generating dev/COMMIT/staged-commit-short.txt and staged-commit-long.txt.";
16584
16923
  case "message": return gitWorkflow.prMode ? `Worktree branch ${gitWorkflow.prBranch || "created"}: choose short, long, or typed input before opening a PR.` : "Step 3/4: preview the native g-msg output, type a commit message if needed, commit here, or create a PR branch worktree first.";
@@ -16692,8 +17031,17 @@ function renderGitWorkflow() {
16692
17031
  return;
16693
17032
  }
16694
17033
 
17034
+ const preferences = gitWorkflow.preferences || gitWorkflowPreferences || {};
16695
17035
  if (gitWorkflow.step === "add") {
16696
- addGitWorkflowAction("Run git add .", () => runGitAdd(), "primary", false);
17036
+ if (preferences.stagingPolicy === "all") {
17037
+ addGitWorkflowAction("Run git add .", () => runGitAdd(), "primary", false);
17038
+ } else if (preferences.stagingPolicy === "preserve") {
17039
+ addGitWorkflowAction("Use current staged set", () => acceptCurrentGitStaging(), "primary", false);
17040
+ addGitWorkflowAction("Review/select changes", () => openGitChangesDialog(), "", false);
17041
+ } else {
17042
+ addGitWorkflowAction("Review/select changes", () => openGitChangesDialog(), "primary", false);
17043
+ addGitWorkflowAction("Use current staged set", () => acceptCurrentGitStaging(), "", false);
17044
+ }
16697
17045
  } else if (gitWorkflow.step === "generate") {
16698
17046
  const commitInputButton = renderGitWorkflowManualCommitInput({ appendCommitButton: false });
16699
17047
  addGitWorkflowAction("Run /git-staged-msg", () => runGitMessagePrompt(), "primary", false);
@@ -16702,13 +17050,16 @@ function renderGitWorkflow() {
16702
17050
  } else if (gitWorkflow.step === "generating") {
16703
17051
  addGitWorkflowAction("Refresh message preview", () => loadGitWorkflowMessage({ requireFresh: true }), "", false);
16704
17052
  } else if (gitWorkflow.step === "message") {
17053
+ const deliveryMode = preferences.deliveryMode || "ask";
17054
+ const preferredVariant = preferences.commit?.defaultVariant || "short";
16705
17055
  if (!gitWorkflow.prMode) {
16706
- addGitWorkflowAction("Create PR worktree", () => createGitPrBranch(), "primary", false, GIT_WORKFLOW_CREATE_PR_TOOLTIP);
17056
+ addGitWorkflowAction("Create PR worktree", () => createGitPrBranch(), deliveryMode === "pr-worktree" ? "primary" : "", false, GIT_WORKFLOW_CREATE_PR_TOOLTIP);
16707
17057
  addGitWorkflowAction("Manual worktree", () => createGitPrBranchManually(), "", false, GIT_WORKFLOW_MANUAL_BRANCH_TOOLTIP);
16708
17058
  }
16709
17059
  const commitInputButton = renderGitWorkflowManualCommitInput({ appendCommitButton: false });
16710
- addGitWorkflowAction("Commit short", () => commitGitWorkflow("short"), gitWorkflow.prMode ? "primary" : "", false);
16711
- addGitWorkflowAction("Commit long", () => commitGitWorkflow("long"), gitWorkflow.prMode ? "primary" : "", false);
17060
+ const highlightCommit = gitWorkflow.prMode || deliveryMode !== "pr-worktree";
17061
+ addGitWorkflowAction(`Commit short${preferredVariant === "short" ? " (default)" : ""}`, () => commitGitWorkflow("short"), highlightCommit && preferredVariant === "short" ? "primary" : "", false);
17062
+ addGitWorkflowAction(`Commit long${preferredVariant === "long" ? " (default)" : ""}`, () => commitGitWorkflow("long"), highlightCommit && preferredVariant === "long" ? "primary" : "", false);
16712
17063
  addGitWorkflowAction("Regenerate", () => runGitMessagePrompt(), "", false);
16713
17064
  elements.gitWorkflowActions.append(commitInputButton);
16714
17065
  } else if (gitWorkflow.step === "branchNaming") {
@@ -16767,7 +17118,18 @@ function failGitWorkflow(error, step, { tabId = activeTabId } = {}) {
16767
17118
  }, { tabId });
16768
17119
  }
16769
17120
 
16770
- function startGitWorkflow(tabId = activeTabId) {
17121
+ function gitWorkflowStagingReadyMessage(preferences) {
17122
+ switch (preferences?.stagingPolicy) {
17123
+ case "preserve":
17124
+ return "Using the repository's current staged set. Review it before generating a message.";
17125
+ case "all":
17126
+ return "Ready to stage all working-tree changes with git add .";
17127
+ default:
17128
+ return "Review changes and stage only the files intended for this commit, then continue with the current staged set.";
17129
+ }
17130
+ }
17131
+
17132
+ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {}) {
16771
17133
  if (!tabId) return;
16772
17134
  if (!isOptionalFeatureEnabled("gitWorkflow")) {
16773
17135
  const tabContext = activeTabContext(tabId);
@@ -16777,8 +17139,29 @@ function startGitWorkflow(tabId = activeTabId) {
16777
17139
  });
16778
17140
  return;
16779
17141
  }
17142
+
17143
+ let setupData;
17144
+ try {
17145
+ const response = await api("/api/git-workflow/preferences", { tabId });
17146
+ setupData = response.data || {};
17147
+ gitWorkflowPreferences = setupData.preferences || null;
17148
+ } catch (error) {
17149
+ addEvent(`guided Git setup could not be loaded: ${error.message || String(error)}`, "error");
17150
+ return;
17151
+ }
17152
+ if (!setupData.configured) {
17153
+ if (skipSetup) {
17154
+ addEvent("Guided Git setup is incomplete.", "warn");
17155
+ return;
17156
+ }
17157
+ addEvent("Complete Guided Git Setup before starting the workflow.", "info");
17158
+ await openNativeGitWorkflowSetupDialog({ onSaved: () => startGitWorkflow(tabId, { skipSetup: true }) });
17159
+ return;
17160
+ }
17161
+
16780
17162
  const workflow = gitWorkflowForTab(tabId);
16781
17163
  if (workflow.active && !["done", "cancelled", "error"].includes(workflow.step) && !confirm("Restart the active git workflow?")) return;
17164
+ const preferences = setupData.preferences;
16782
17165
  workflow.runId += 1;
16783
17166
  setGitWorkflow({
16784
17167
  active: true,
@@ -16786,7 +17169,7 @@ function startGitWorkflow(tabId = activeTabId) {
16786
17169
  step: "add",
16787
17170
  process: "stage",
16788
17171
  busy: false,
16789
- output: "Ready to stage all changes with git add .\n\nNative mode is used for g-msg/g-short/g-long: dev/COMMIT message files are read directly and git commit is run without fish. In the Message stage you can also type a commit message and use Commit input. After the message is generated, use Create PR worktree to open a branch worktree before committing.",
17172
+ output: `${gitWorkflowStagingReadyMessage(preferences)}\n\nGit text will use ${preferences.generation.provider}/${preferences.generation.modelId} at ${preferences.generation.thinkingLevel} effort. The active tab model is restored after generation.`,
16790
17173
  error: "",
16791
17174
  githubUsername: "",
16792
17175
  repoName: "",
@@ -16806,6 +17189,8 @@ function startGitWorkflow(tabId = activeTabId) {
16806
17189
  prBranch: "",
16807
17190
  pr: null,
16808
17191
  prRequestedAt: 0,
17192
+ preferences,
17193
+ verificationConfirmed: false,
16809
17194
  }, { tabId });
16810
17195
  }
16811
17196
 
@@ -17139,6 +17524,31 @@ async function runGitAdd(tabId = gitWorkflowActionTabId()) {
17139
17524
  }
17140
17525
  }
17141
17526
 
17527
+ async function acceptCurrentGitStaging(tabId = gitWorkflowActionTabId()) {
17528
+ const tabContext = activeTabContext(tabId);
17529
+ const workflow = gitWorkflowForTab(tabId, { create: false });
17530
+ if (!workflow) return;
17531
+ const runId = workflow.runId;
17532
+ setGitWorkflow({ step: "add", busy: true, error: "", output: "Checking the current staged set…" }, { tabId });
17533
+ try {
17534
+ const response = await api("/api/git-changes", { tabId });
17535
+ const staged = Number(response.data?.summary?.staged || 0);
17536
+ if (staged <= 0) throw new Error("No staged files are available. Use Review/select changes to stage the intended files first.");
17537
+ setGitWorkflow({
17538
+ step: "generate",
17539
+ process: "message",
17540
+ busy: false,
17541
+ ...resetGitWorkflowManualCommitDefaultPatch(),
17542
+ ...gitWorkflowActionDonePatch(workflow, "stage"),
17543
+ output: `Using the current staged set (${staged} file${staged === 1 ? "" : "s"}). Review the staged diff, then generate or type a commit message.`,
17544
+ }, { tabId });
17545
+ loadGitWorkflowDefaultCommitMessage({ runId, tabId });
17546
+ if (isCurrentTabContext(tabContext)) scheduleRefreshFooter();
17547
+ } catch (error) {
17548
+ if (isCurrentGitWorkflowRun(runId, tabId)) failGitWorkflow(error, "add", { tabId });
17549
+ }
17550
+ }
17551
+
17142
17552
  async function loadGitWorkflowDefaultCommitMessage({ runId, tabId = activeTabId } = {}) {
17143
17553
  const workflow = gitWorkflowForTab(tabId, { create: false });
17144
17554
  const expectedRunId = runId ?? workflow?.runId;
@@ -17190,9 +17600,9 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
17190
17600
  }, { tabId });
17191
17601
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /git-staged-msg to Pi…");
17192
17602
  try {
17193
- await api("/api/prompt", { method: "POST", body: { message: "/git-staged-msg" }, tabId });
17194
- if (!isCurrentGitWorkflowRun(runId, tabId)) return;
17195
- appendGitWorkflowOutput("/git-staged-msg accepted. Waiting for agent_end, then the message files will be loaded.", { tabId });
17603
+ const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "commit" }, runId, tabId });
17604
+ if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
17605
+ appendGitWorkflowOutput(`/git-staged-msg accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the message files will be loaded.`, { tabId });
17196
17606
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
17197
17607
  setTimeout(() => {
17198
17608
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -17286,9 +17696,9 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
17286
17696
  }, { tabId });
17287
17697
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending branch-name request to Pi…");
17288
17698
  try {
17289
- await api("/api/prompt", { method: "POST", body: { message: gitBranchNamePromptMessage() }, tabId });
17290
- if (!isCurrentGitWorkflowRun(runId, tabId)) return;
17291
- appendGitWorkflowOutput("Branch-name request accepted. Waiting for agent_end, then the branch name will be loaded.", { tabId });
17699
+ const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "branch" }, runId, tabId });
17700
+ if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
17701
+ appendGitWorkflowOutput(`Branch-name request accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the branch name will be loaded.`, { tabId });
17292
17702
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
17293
17703
  setTimeout(() => {
17294
17704
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -17412,6 +17822,8 @@ async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowAc
17412
17822
  prBranch: prBranch || branch,
17413
17823
  pr: null,
17414
17824
  prRequestedAt: 0,
17825
+ preferences: sourceWorkflow.preferences || gitWorkflowPreferences,
17826
+ verificationConfirmed: false,
17415
17827
  };
17416
17828
  if (targetTabId !== tabId) {
17417
17829
  setGitWorkflow({ step: "message", prMode: false, prBranch: "", branchName: prBranch || branch, busy: false, output: `${formatCommitMessagePreview(sourceWorkflow.message)}\n\nOpened PR branch worktree ${prBranch || branch} in ${result.tab?.title || "a new tab"}. Continue the commit and PR flow there; this checkout stayed on its current branch.` }, { tabId });
@@ -17434,6 +17846,18 @@ async function commitGitWorkflow(variant, tabId = gitWorkflowActionTabId()) {
17434
17846
  const runId = workflow.runId;
17435
17847
  const failureStep = variant === "input" && workflow.step === "generate" ? "generate" : "message";
17436
17848
  const inputMessage = variant === "input" ? gitWorkflowManualCommitInputMessage(workflow) : "";
17849
+ if (workflow.preferences?.verificationPolicy === "ask" && !workflow.verificationConfirmed) {
17850
+ const proceed = window.confirm([
17851
+ "Pre-commit verification reminder",
17852
+ "",
17853
+ "Review the staged diff and any relevant test, lint, or build results before committing.",
17854
+ "Git hooks and signing configuration will still run normally.",
17855
+ "",
17856
+ "Continue with this commit?",
17857
+ ].join("\n"));
17858
+ if (!proceed) return;
17859
+ workflow.verificationConfirmed = true;
17860
+ }
17437
17861
  if (variant === "input" && !inputMessage) {
17438
17862
  failGitWorkflow(new Error("Type a commit message, or stage exactly one created/updated/deleted file to use the default."), failureStep, { tabId });
17439
17863
  return;
@@ -17459,6 +17883,7 @@ async function pushGitWorkflow(tabId = gitWorkflowActionTabId()) {
17459
17883
  const tabContext = activeTabContext(tabId);
17460
17884
  const workflow = gitWorkflowForTab(tabId, { create: false });
17461
17885
  if (!workflow) return;
17886
+ if (!window.confirm("Push the committed changes to the configured upstream?\n\nGuided Git never force-pushes automatically.")) return;
17462
17887
  const runId = workflow.runId;
17463
17888
  setGitWorkflow({ step: "pushing", busy: true, error: "", output: "Running git push…" }, { tabId });
17464
17889
  try {
@@ -17496,9 +17921,9 @@ async function runGitPrPrompt(tabId = gitWorkflowActionTabId(), { prefixOutput =
17496
17921
  }, { tabId });
17497
17922
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /pr to Pi…");
17498
17923
  try {
17499
- await api("/api/prompt", { method: "POST", body: { message: "/pr" }, tabId });
17500
- if (!isCurrentGitWorkflowRun(runId, tabId)) return;
17501
- appendGitWorkflowOutput("/pr accepted. Waiting for agent_end, then the PR description will be loaded.", { tabId });
17924
+ const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "pr" }, runId, tabId });
17925
+ if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
17926
+ appendGitWorkflowOutput(`/pr accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the PR description will be loaded.`, { tabId });
17502
17927
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
17503
17928
  setTimeout(() => {
17504
17929
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -17549,8 +17974,9 @@ async function pushAndCreatePrGitWorkflow(tabId = gitWorkflowActionTabId()) {
17549
17974
  const tabContext = activeTabContext(tabId);
17550
17975
  const workflow = gitWorkflowForTab(tabId, { create: false });
17551
17976
  if (!workflow) return;
17552
- const runId = workflow.runId;
17553
17977
  const branch = workflow.prBranch || "current branch";
17978
+ if (!window.confirm(`Push ${branch} and continue to generated PR review?\n\nThe pull request is still created only after a second explicit review/confirmation.`)) return;
17979
+ const runId = workflow.runId;
17554
17980
  setGitWorkflow({ step: "pushing", busy: true, error: "", output: `Pushing PR branch ${branch}…` }, { tabId });
17555
17981
  try {
17556
17982
  const result = await gitWorkflowRequest("/api/git-workflow/push", { body: { setUpstream: true, branch: workflow.prBranch }, runId, tabId });
@@ -18124,14 +18550,101 @@ function appendText(parent, text, className = "text-block") {
18124
18550
  return block;
18125
18551
  }
18126
18552
 
18553
+ function markdownFilePathFromHref(url) {
18554
+ const href = String(url || "").trim();
18555
+ if (!href || href.startsWith("#") || /[\u0000-\u001f\u007f]/.test(href)) return "";
18556
+ if (/^(?:https?:|mailto:)/i.test(href)) return "";
18557
+ if (/^file:/i.test(href)) {
18558
+ try {
18559
+ const parsed = new URL(href);
18560
+ if (parsed.protocol !== "file:" || (parsed.hostname && parsed.hostname.toLowerCase() !== "localhost")) return "";
18561
+ let pathname = decodeURIComponent(parsed.pathname || "");
18562
+ if (/^\/[A-Za-z]:\//.test(pathname)) pathname = pathname.slice(1);
18563
+ return pathname.replace(/\\/g, "/");
18564
+ } catch {
18565
+ return "";
18566
+ }
18567
+ }
18568
+ if (/^[A-Za-z][A-Za-z\d+.-]*:/.test(href) && !/^[A-Za-z]:[\\/]/.test(href)) return "";
18569
+ if (/^(?:\/\/|\\\\)/.test(href)) return "";
18570
+ const pathText = href.replace(/[?#].*$/, "");
18571
+ try {
18572
+ return decodeURIComponent(pathText).replace(/\\/g, "/");
18573
+ } catch {
18574
+ return pathText.replace(/\\/g, "/");
18575
+ }
18576
+ }
18577
+
18127
18578
  function safeMarkdownLinkHref(url) {
18128
18579
  const href = String(url || "").trim();
18129
18580
  if (!href || /[\u0000-\u001f\u007f]/.test(href)) return "";
18130
18581
  if (/^(?:https?:|mailto:)/i.test(href)) return href;
18131
- if (/^(?:#|\/(?!\/)|\.\/|\.\.\/)/.test(href)) return href;
18582
+ if (href.startsWith("#") || markdownFilePathFromHref(href)) return href;
18132
18583
  return "";
18133
18584
  }
18134
18585
 
18586
+ function normalizeMarkdownWorkspacePath(value) {
18587
+ const parts = [];
18588
+ for (const part of String(value || "").replace(/\\/g, "/").split("/")) {
18589
+ if (!part || part === ".") continue;
18590
+ if (part === "..") {
18591
+ if (!parts.length) return "";
18592
+ parts.pop();
18593
+ continue;
18594
+ }
18595
+ parts.push(part);
18596
+ }
18597
+ return parts.join("/");
18598
+ }
18599
+
18600
+ function markdownWorkspaceFilePath(url, cwd = "", basePath = "") {
18601
+ let target = markdownFilePathFromHref(url);
18602
+ if (!target) return "";
18603
+ const absoluteTarget = target.startsWith("/") || /^[A-Za-z]:\//.test(target);
18604
+ if (absoluteTarget) {
18605
+ const normalizedCwd = String(cwd || "").trim().replace(/\\/g, "/");
18606
+ const workspaceRoot = normalizedCwd.replace(/\/+$/, "") || (normalizedCwd.startsWith("/") ? "/" : "");
18607
+ if (!workspaceRoot) return "";
18608
+ const windowsPath = /^[A-Za-z]:\//.test(target) && /^[A-Za-z]:(?:\/|$)/.test(workspaceRoot);
18609
+ const comparableTarget = windowsPath ? target.toLowerCase() : target;
18610
+ const comparableRoot = windowsPath ? workspaceRoot.toLowerCase() : workspaceRoot;
18611
+ const prefix = comparableRoot === "/" ? "/" : `${comparableRoot}/`;
18612
+ if (!comparableTarget.startsWith(prefix)) return "";
18613
+ target = target.slice(prefix.length);
18614
+ } else if (basePath) {
18615
+ target = `${basePath}/${target}`;
18616
+ }
18617
+ return normalizeMarkdownWorkspacePath(target);
18618
+ }
18619
+
18620
+ function configureMarkdownLink(link, href) {
18621
+ const filePath = markdownFilePathFromHref(href);
18622
+ if (!filePath) {
18623
+ link.href = href;
18624
+ if (/^https?:/i.test(href)) {
18625
+ link.target = "_blank";
18626
+ link.rel = "noopener noreferrer";
18627
+ }
18628
+ return;
18629
+ }
18630
+ link.href = "#";
18631
+ link.classList.add("markdown-file-link");
18632
+ link.dataset.markdownFileHref = href;
18633
+ link.title = `Open ${filePath} in the WebUI file viewer`;
18634
+ link.addEventListener("click", (event) => {
18635
+ event.preventDefault();
18636
+ const cwd = latestWorkspace?.cwd || activeTab()?.cwd || "";
18637
+ const basePath = link.closest?.(".file-viewer-preview") && activeFileViewer ? fileParentPath(activeFileViewer.path) : "";
18638
+ const workspacePath = markdownWorkspaceFilePath(href, cwd, basePath);
18639
+ if (!workspacePath) {
18640
+ addEvent(`Cannot open Markdown link outside this tab's working directory: ${filePath}`, "error");
18641
+ return;
18642
+ }
18643
+ setSidePanelCollapsed(false);
18644
+ openFileInViewer(workspacePath).catch((error) => addEvent(error.message || String(error), "error"));
18645
+ });
18646
+ }
18647
+
18135
18648
  function appendInlineMarkdown(parent, text, depth = 0) {
18136
18649
  const value = String(text || "");
18137
18650
  if (!value) return;
@@ -18162,11 +18675,7 @@ function appendInlineMarkdown(parent, text, depth = 0) {
18162
18675
  const href = safeMarkdownLinkHref(value.slice(labelEnd + 2, linkEnd));
18163
18676
  if (href) {
18164
18677
  const link = make("a");
18165
- link.href = href;
18166
- if (/^https?:/i.test(href)) {
18167
- link.target = "_blank";
18168
- link.rel = "noopener noreferrer";
18169
- }
18678
+ configureMarkdownLink(link, href);
18170
18679
  appendInlineMarkdown(link, label, depth + 1);
18171
18680
  parent.append(link);
18172
18681
  } else {
@@ -22051,6 +22560,159 @@ async function openNativeSettingsDialog() {
22051
22560
  const save = addNativeCommandAction("Apply", () => applySettings(false, save), "primary");
22052
22561
  }
22053
22562
 
22563
+ function replaceNativeSettingSelectOptions(select, options, preferredValue) {
22564
+ const normalized = normalizedSettingOptions(options);
22565
+ select.replaceChildren();
22566
+ for (const option of normalized) {
22567
+ const element = make("option", undefined, option.label);
22568
+ element.value = option.value;
22569
+ select.append(element);
22570
+ }
22571
+ const values = normalized.map((option) => option.value);
22572
+ select.value = values.includes(String(preferredValue)) ? String(preferredValue) : values[0] || "";
22573
+ }
22574
+
22575
+ function gitWorkflowSetupModelKey(model) {
22576
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
22577
+ }
22578
+
22579
+ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
22580
+ openNativeCommandDialog({
22581
+ title: "/git-workflow-setup",
22582
+ message: "Configure the dedicated model and safe defaults used by Guided Git. The selected generation profile is applied only while commit, branch, or PR text is generated.",
22583
+ });
22584
+ renderNativeLoading("Loading guided Git preferences and available models…");
22585
+
22586
+ let data;
22587
+ try {
22588
+ const response = await nativeCommandApi("/api/git-workflow/preferences");
22589
+ data = response.data || {};
22590
+ } catch (error) {
22591
+ setNativeCommandError(error.message || String(error));
22592
+ elements.nativeCommandBody.replaceChildren();
22593
+ return;
22594
+ }
22595
+
22596
+ const preferences = data.preferences || {};
22597
+ const models = Array.isArray(data.models) ? data.models : [];
22598
+ if (!models.length) {
22599
+ setNativeCommandError("No authenticated Pi models are available. Run /login or configure a provider first.");
22600
+ elements.nativeCommandBody.replaceChildren();
22601
+ return;
22602
+ }
22603
+
22604
+ const configuredModelKey = `${preferences.generation?.provider || ""}/${preferences.generation?.modelId || ""}`;
22605
+ const activeModelKey = gitWorkflowSetupModelKey(currentState?.model);
22606
+ const modelKeys = new Set(models.map(gitWorkflowSetupModelKey));
22607
+ const initialModelKey = modelKeys.has(configuredModelKey)
22608
+ ? configuredModelKey
22609
+ : modelKeys.has(activeModelKey)
22610
+ ? activeModelKey
22611
+ : gitWorkflowSetupModelKey(models[0]);
22612
+ const modelOptions = models.map((model) => ({
22613
+ value: gitWorkflowSetupModelKey(model),
22614
+ label: `${gitWorkflowSetupModelKey(model)}${model.name && model.name !== model.id ? ` · ${model.name}` : ""}`,
22615
+ }));
22616
+
22617
+ const controls = {
22618
+ model: nativeSettingSelect("Git-writing model", initialModelKey, modelOptions, "Exact authenticated provider/model used for commit messages, branch names, and PR descriptions.", { label: "required", tone: "safety" }),
22619
+ thinking: nativeSettingSelect("Reasoning effort", preferences.generation?.thinkingLevel || "low", SETTINGS_THINKING_OPTIONS, "Only levels supported by the selected model are shown. Low is recommended for routine commit messages.", { label: "required", tone: "safety" }),
22620
+ language: nativeSettingSelect("Generated language", preferences.commit?.language || "en", [
22621
+ { value: "en", label: "English" },
22622
+ { value: "de", label: "German" },
22623
+ ], "Language for generated commit and PR text.", { label: "saved", tone: "browser" }),
22624
+ defaultVariant: nativeSettingSelect("Default message", preferences.commit?.defaultVariant || "short", [
22625
+ { value: "short", label: "Short subject" },
22626
+ { value: "long", label: "Long subject + body" },
22627
+ ], "Highlights the preferred commit choice; committing always remains explicit.", { label: "saved", tone: "browser" }),
22628
+ scope: nativeSettingSelect("Conventional scope", preferences.commit?.scope || "auto", [
22629
+ { value: "auto", label: "Auto-detect when clear" },
22630
+ { value: "never", label: "Never include a scope" },
22631
+ { value: "required", label: "Always include a scope" },
22632
+ ], "Controls type(scope): subject generation.", { label: "saved", tone: "browser" }),
22633
+ staging: nativeSettingSelect("Staging behavior", preferences.stagingPolicy || "review", [
22634
+ { value: "review", label: "Review/select files" },
22635
+ { value: "preserve", label: "Use current staged set" },
22636
+ { value: "all", label: "Stage all with git add ." },
22637
+ ], "Review/select is the safe default and opens Git Changes for per-file staging.", { label: "safety", tone: "safety" }),
22638
+ delivery: nativeSettingSelect("Delivery path", preferences.deliveryMode || "ask", [
22639
+ { value: "ask", label: "Ask each workflow" },
22640
+ { value: "current", label: "Prefer current branch" },
22641
+ { value: "pr-worktree", label: "Prefer PR worktree" },
22642
+ ], "Controls which explicit commit/PR action is highlighted.", { label: "saved", tone: "browser" }),
22643
+ verification: nativeSettingSelect("Pre-commit verification", preferences.verificationPolicy || "ask", [
22644
+ { value: "ask", label: "Show verification reminder" },
22645
+ { value: "none", label: "No reminder" },
22646
+ ], "The reminder never claims tests were run and does not bypass Git hooks.", { label: "safety", tone: "safety" }),
22647
+ };
22648
+
22649
+ const thinkingLevelsForModel = (modelKey) => {
22650
+ const levels = data.modelThinkingLevels?.[modelKey];
22651
+ return Array.isArray(levels) && levels.length ? levels : ["off"];
22652
+ };
22653
+ const syncThinkingLevels = () => {
22654
+ const current = controls.thinking.select.value || preferences.generation?.thinkingLevel || "low";
22655
+ const levels = thinkingLevelsForModel(controls.model.select.value);
22656
+ replaceNativeSettingSelectOptions(controls.thinking.select, levels, current);
22657
+ };
22658
+ controls.model.select.addEventListener("change", syncThinkingLevels);
22659
+ syncThinkingLevels();
22660
+
22661
+ const body = make("div", "native-settings-panel");
22662
+ body.append(
22663
+ nativeSettingsNote("Persistence", `Saved globally in ${data.path || "the Pi Web UI settings file"}. Credentials are never stored here.`),
22664
+ nativeSettingsSection("Generation profile", "Required model and effort for generated Git text.", [controls.model, controls.thinking], { open: true }),
22665
+ nativeSettingsSection("Commit style", "Conventional Commit output preferences.", [controls.language, controls.defaultVariant, controls.scope], { open: true }),
22666
+ nativeSettingsSection("Workflow safety", "Staging, delivery, and verification defaults; push and PR confirmation remain mandatory.", [controls.staging, controls.delivery, controls.verification], { open: true }),
22667
+ );
22668
+ elements.nativeCommandBody.replaceChildren(body);
22669
+ elements.nativeCommandActions.replaceChildren();
22670
+ addNativeCommandAction("Cancel", closeNativeCommandDialog);
22671
+
22672
+ const save = addNativeCommandAction("Save setup", async () => {
22673
+ setNativeActionBusy(save, true, "Saving…");
22674
+ setNativeCommandError("");
22675
+ try {
22676
+ const selectedModel = models.find((model) => gitWorkflowSetupModelKey(model) === controls.model.select.value);
22677
+ if (!selectedModel) throw new Error("Select an available Git-writing model.");
22678
+ const response = await nativeCommandApi("/api/git-workflow/preferences", {
22679
+ method: "POST",
22680
+ body: {
22681
+ preferences: {
22682
+ generation: {
22683
+ provider: selectedModel.provider,
22684
+ modelId: selectedModel.id,
22685
+ thinkingLevel: controls.thinking.select.value,
22686
+ unavailablePolicy: "ask",
22687
+ },
22688
+ commit: {
22689
+ language: controls.language.select.value,
22690
+ defaultVariant: controls.defaultVariant.select.value,
22691
+ scope: controls.scope.select.value,
22692
+ },
22693
+ stagingPolicy: controls.staging.select.value,
22694
+ deliveryMode: controls.delivery.select.value,
22695
+ verificationPolicy: controls.verification.select.value,
22696
+ },
22697
+ },
22698
+ });
22699
+ gitWorkflowPreferences = response.data?.preferences || null;
22700
+ addTransientMessage({
22701
+ role: "native",
22702
+ title: "/git-workflow-setup",
22703
+ content: `Guided Git setup saved for ${gitWorkflowSetupModelKey(selectedModel)} at ${controls.thinking.select.value} effort.`,
22704
+ level: "info",
22705
+ });
22706
+ closeNativeCommandDialog();
22707
+ if (typeof onSaved === "function") await onSaved(gitWorkflowPreferences);
22708
+ } catch (error) {
22709
+ setNativeCommandError(error.message || String(error));
22710
+ } finally {
22711
+ setNativeActionBusy(save, false);
22712
+ }
22713
+ }, "primary");
22714
+ }
22715
+
22054
22716
  async function openNativeForkSelector() {
22055
22717
  openNativeCommandDialog({ title: "/fork", message: "Choose a previous user message to fork before.", searchPlaceholder: "Filter fork points…" });
22056
22718
  renderNativeLoading("Loading fork points…");
@@ -22563,6 +23225,9 @@ async function handleNativeSlashSelectorCommand(message, { usesPromptInput = fal
22563
23225
  case "settings":
22564
23226
  await openNativeSettingsDialog();
22565
23227
  return true;
23228
+ case "git-workflow-setup":
23229
+ await openNativeGitWorkflowSetupDialog();
23230
+ return true;
22566
23231
  case "theme":
22567
23232
  openNativeThemeSelector();
22568
23233
  return true;
@@ -25603,6 +26268,7 @@ elements.optionsRemoteButton.addEventListener("click", () => runNativeCommandMen
25603
26268
  elements.optionsNameButton.addEventListener("click", () => runNativeCommandMenu("/name"));
25604
26269
  elements.optionsCloneButton.addEventListener("click", () => runNativeCommandMenu("/clone"));
25605
26270
  elements.optionsSettingsButton.addEventListener("click", () => runNativeCommandMenu("/settings"));
26271
+ elements.optionsGitWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/git-workflow-setup"));
25606
26272
  elements.optionsExportButton.addEventListener("click", () => runNativeCommandMenu("/export"));
25607
26273
  elements.optionsForkButton.addEventListener("click", () => runNativeCommandMenu("/fork"));
25608
26274
  elements.optionsTreeButton.addEventListener("click", () => runNativeCommandMenu("/tree"));
@@ -26314,8 +26980,13 @@ window.addEventListener("keydown", (event) => {
26314
26980
 
26315
26981
  window.addEventListener("keydown", handleNativeAppShortcut, { capture: true });
26316
26982
  document.addEventListener("visibilitychange", () => {
26317
- if (document.visibilityState === "visible") scheduleForegroundReconcile("visibility resume", 0);
26318
- else resetAbortLongPressAffordance();
26983
+ if (document.visibilityState === "visible") {
26984
+ scheduleForegroundReconcile("visibility resume", 0);
26985
+ refreshSubagents().finally(() => scheduleRefreshSubagents());
26986
+ } else {
26987
+ resetAbortLongPressAffordance();
26988
+ scheduleRefreshSubagents();
26989
+ }
26319
26990
  });
26320
26991
  window.addEventListener("pageshow", () => scheduleForegroundReconcile("page show", 0));
26321
26992
  window.addEventListener("focus", () => scheduleForegroundReconcile("window focus"));
@@ -26653,6 +27324,7 @@ bindSidePanelSectionToggles();
26653
27324
  restoreSidePanelState();
26654
27325
  initializeCodexUsage();
26655
27326
  initializeClaudeUsage();
27327
+ initializeSubagents();
26656
27328
  initializeUpdateNotifications();
26657
27329
  bindMobileViewChanges();
26658
27330
  bindSidePanelOverlayViewChanges();