@firstpick/pi-package-webui 0.5.5 → 0.5.7

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
@@ -10,6 +10,7 @@ const elements = {
10
10
  newTabMenuPanel: $("#newTabMenuPanel"),
11
11
  newTabCurrentDirectoryButton: $("#newTabCurrentDirectoryButton"),
12
12
  newTabChooseDirectoryButton: $("#newTabChooseDirectoryButton"),
13
+ newTabWorktreeButton: $("#newTabWorktreeButton"),
13
14
  closeAllTabsButton: $("#closeAllTabsButton"),
14
15
  commandPaletteButton: $("#commandPaletteButton"),
15
16
  workspaceDashboardToggleButton: $("#workspaceDashboardToggleButton"),
@@ -257,10 +258,20 @@ let tabSeenCompletionSerials = new Map();
257
258
  let streamBubble = null;
258
259
  let streamText = null;
259
260
  let streamRawText = "";
261
+ let streamThinkingRawText = "";
262
+ let streamDerivedTextCache = { rawText: null, assistantText: "", thinkingFormat: null, finalText: "" };
260
263
  let streamBubbleVisibleSince = 0;
261
264
  let streamBubbleHideTimer = null;
262
265
  let streamTextRenderTimer = null;
266
+ let streamTextRenderFrame = null;
263
267
  let streamToolCallSeen = false;
268
+ let streamToolCallBubble = null;
269
+ let streamToolCallText = null;
270
+ let streamToolCallRawArguments = "";
271
+ let streamToolCallName = "";
272
+ let streamToolCallId = "";
273
+ let streamToolCallContentIndex = null;
274
+ let streamToolCallComplete = false;
264
275
  let streamThinkingBubble = null;
265
276
  let streamThinking = null;
266
277
  let streamMessageActive = false;
@@ -268,6 +279,8 @@ let runIndicatorBubble = null;
268
279
  let runIndicatorText = null;
269
280
  let runIndicatorMeta = null;
270
281
  let runIndicatorTimer = null;
282
+ let runIndicatorRenderFrame = null;
283
+ let runIndicatorRenderScroll = false;
271
284
  let runIndicatorGraceCheckTimer = null;
272
285
  let runIndicatorLastStateCheckAt = 0;
273
286
  let runIndicatorLocallyActive = false;
@@ -277,6 +290,7 @@ let refreshMessagesTimer = null;
277
290
  let refreshStateTimer = null;
278
291
  let refreshFooterTimer = null;
279
292
  let refreshTabsTimer = null;
293
+ let tabsRenderFrame = null;
280
294
  let foregroundReconcileTimer = null;
281
295
  let eventSource = null;
282
296
  let activeDialog = null;
@@ -366,6 +380,7 @@ let terminalTabsLayout = "top";
366
380
  let webuiSettings = {};
367
381
  let busyPromptBehavior = "followUp";
368
382
  let composerModeRenderSignature = "";
383
+ let composerModeButtonsFrame = null;
369
384
  let autocompleteMaxVisible = 12;
370
385
  let doubleEscapeAction = "none";
371
386
  let treeFilterMode = "default";
@@ -389,6 +404,11 @@ const contextUsageUnknownAfterCompactionByTab = new Map();
389
404
  let autoFollowChat = true;
390
405
  let chatFollowFrame = null;
391
406
  let chatFollowSettleTimer = null;
407
+ let chatFollowNeedsSettle = false;
408
+ let liveWidgetRenderFrame = null;
409
+ let liveTodoProgressSyncFrame = null;
410
+ let liveTodoProgressPendingText = "";
411
+ let liveTodoProgressPendingTabId = null;
392
412
  let lastChatProgrammaticScrollAt = 0;
393
413
  let chatUserScrollIntentUntil = 0;
394
414
  let mobileFooterExpanded = false;
@@ -396,7 +416,7 @@ let footerModelPickerOpen = false;
396
416
  let footerThinkingPickerOpen = false;
397
417
  let footerAutoCompactionToggleInFlight = false;
398
418
  let footerBranchPickerOpen = false;
399
- let footerBranchPickerState = { loading: false, error: "", branches: [], current: "", root: "", switching: "", tabId: null };
419
+ let footerBranchPickerState = { loading: false, error: "", branches: [], current: "", root: "", repoRoot: "", currentWorktreePath: "", defaultWorktreesRoot: "", worktrees: [], occupiedBranches: [], switching: "", tabId: null };
400
420
  let footerBranchCreateDraft = { type: "", name: "" };
401
421
  let footerBranchPickerRequestSerial = 0;
402
422
  let footerScopedModelDragKey = "";
@@ -543,9 +563,12 @@ const statusEntries = new Map();
543
563
  const widgets = new Map();
544
564
  const widgetsByTab = new Map();
545
565
  const todoProgressWidgetExpandedByTab = new Map();
566
+ const todoProgressGoalByTab = new Map();
567
+ const todoProgressSignatureByTab = new Map();
546
568
  const releaseNpmOutputExpandedByTab = new Map();
547
569
  const appRunnerDataByTab = new Map();
548
570
  const appRunnerInputDraftByRun = new Map();
571
+ const appRunnerContextLineDraftByRun = new Map();
549
572
  const liveToolRuns = new Map();
550
573
  const liveToolCards = new Map();
551
574
  const liveToolRenderQueue = new Map();
@@ -568,6 +591,8 @@ const optionalFeatureAvailability = {
568
591
  remoteWebui: false,
569
592
  themeBundle: false,
570
593
  };
594
+ const APP_RUNNER_CONTEXT_DEFAULT_LINES = 80;
595
+ const APP_RUNNER_CONTEXT_MAX_LINES = 1000;
571
596
  const OPTIONAL_FEATURES = [
572
597
  {
573
598
  id: "btwCommand",
@@ -878,22 +903,24 @@ const GIT_INIT_WORKFLOW_ACTIVE_INDEX = {
878
903
  done: 7,
879
904
  };
880
905
  const GIT_WORKFLOW_CREATE_PR_TOOLTIP = [
881
- "Create PR branch:",
906
+ "Create PR worktree:",
882
907
  "1. Ask Pi to generate a type/feature-name branch from staged changes.",
883
908
  "2. Read dev/COMMIT/staged-branch-name.txt.",
884
909
  "3. Let you confirm or edit the generated branch name.",
885
- "4. Run git switch -c <branch>.",
886
- "5. Return here to commit short, long, or typed input on that branch.",
887
- "6. Push and Create PR will push upstream, run /pr, let you review, then run gh pr create.",
910
+ "4. Create or open a Git worktree for that branch instead of switching this checkout.",
911
+ "5. Copy staged changes and commit message files into the worktree, then switch to its tab.",
912
+ "6. Commit short, long, or typed input in the worktree tab.",
913
+ "7. Push and Create PR will push upstream, run /pr, let you review, then run gh pr create.",
888
914
  ].join("\n");
889
915
  const GIT_WORKFLOW_MANUAL_BRANCH_TOOLTIP = [
890
- "Manual PR branch:",
916
+ "Manual PR worktree:",
891
917
  "1. Skip agent branch-name generation.",
892
918
  "2. Prefill a branch from the commit message if possible.",
893
919
  "3. Let you type or edit the type/feature-name branch name.",
894
- "4. Run git switch -c <branch>.",
895
- "5. Return here to commit short, long, or typed input on that branch.",
896
- "6. Push and Create PR will push upstream, run /pr, let you review, then run gh pr create.",
920
+ "4. Create or open a Git worktree for that branch instead of switching this checkout.",
921
+ "5. Copy staged changes and commit message files into the worktree, then switch to its tab.",
922
+ "6. Commit short, long, or typed input in the worktree tab.",
923
+ "7. Push and Create PR will push upstream, run /pr, let you review, then run gh pr create.",
897
924
  ].join("\n");
898
925
  const GIT_BRANCH_TYPE_SUGGESTIONS = ["feat", "fix", "change", "perf", "test", "chore", "refactor", "docs", "style", "build", "ci", "revert"];
899
926
  const GIT_FOOTER_STATUS_SETUP_TOOLTIP = [
@@ -1883,6 +1910,17 @@ function trackSkillsFromMessages(messages = latestMessages, tabId = activeTabId)
1883
1910
  for (const message of messages || []) trackSkillsFromMessage(tabId, message);
1884
1911
  }
1885
1912
 
1913
+ function assistantMessageUpdateType(event) {
1914
+ return event?.assistantMessageEvent?.type || "";
1915
+ }
1916
+
1917
+ function eventMayAffectSkillUsage(event) {
1918
+ const type = event?.type || "";
1919
+ return ["tool_execution_start", "tool_execution_update", "tool_execution_end"].includes(type)
1920
+ || (type === "message_update" && assistantMessageUpdateType(event) === "toolcall_start")
1921
+ || (type === "response" && event.command === "new_session");
1922
+ }
1923
+
1886
1924
  function trackSkillsFromEvent(event) {
1887
1925
  const tabId = event?.tabId || activeTabId;
1888
1926
  if (!tabId || !event) return;
@@ -1890,11 +1928,9 @@ function trackSkillsFromEvent(event) {
1890
1928
  trackSkillsFromToolInvocation(tabId, event.toolName, event.args, { sourcePrefix: `event:${event.type}` });
1891
1929
  return;
1892
1930
  }
1893
- if (event.type === "message_update") {
1931
+ if (assistantMessageUpdateType(event) === "toolcall_start") {
1894
1932
  const update = event.assistantMessageEvent || {};
1895
- if (update.type === "toolcall_start") {
1896
- trackSkillsFromToolInvocation(tabId, update.name || update.toolName || update.toolCall?.name, update.arguments || update.args || update.toolCall?.arguments || {}, { sourcePrefix: "event:message_update" });
1897
- }
1933
+ trackSkillsFromToolInvocation(tabId, update.name || update.toolName || update.toolCall?.name, update.arguments || update.args || update.toolCall?.arguments || {}, { sourcePrefix: "event:message_update" });
1898
1934
  return;
1899
1935
  }
1900
1936
  if (event.type === "response" && event.command === "new_session") {
@@ -2179,6 +2215,16 @@ function updateComposerModeButtons() {
2179
2215
  document.body.classList.toggle("pi-run-active", runActive || abortAvailable);
2180
2216
  }
2181
2217
 
2218
+ function scheduleComposerModeButtonsUpdate() {
2219
+ if (composerModeButtonsFrame !== null) return;
2220
+ const flush = () => {
2221
+ composerModeButtonsFrame = null;
2222
+ updateComposerModeButtons();
2223
+ };
2224
+ if (typeof requestAnimationFrame === "function") composerModeButtonsFrame = requestAnimationFrame(flush);
2225
+ else composerModeButtonsFrame = setTimeout(flush, 0);
2226
+ }
2227
+
2182
2228
  function isFooterPickerOpen() {
2183
2229
  return footerModelPickerOpen || footerThinkingPickerOpen || footerBranchPickerOpen;
2184
2230
  }
@@ -2314,7 +2360,7 @@ function setWorkspaceDashboardCollapsed(collapsed, { persist = true } = {}) {
2314
2360
  elements.workspaceDashboardToggleButton.setAttribute("aria-expanded", workspaceDashboardCollapsed ? "false" : "true");
2315
2361
  const tooltip = workspaceDashboardCollapsed ? "Show workspace overview" : "Hide workspace overview";
2316
2362
  const tooltipDetail = `${tooltip}:\n• Shows current tab, cwd, model, context, session, and queue.\n• Opens common workspace/session actions from one place.`;
2317
- elements.workspaceDashboardToggleButton.title = tooltip;
2363
+ elements.workspaceDashboardToggleButton.removeAttribute("title");
2318
2364
  elements.workspaceDashboardToggleButton.setAttribute("aria-label", tooltip);
2319
2365
  elements.workspaceDashboardToggleButton.setAttribute("data-tooltip", tooltipDetail);
2320
2366
  }
@@ -2516,7 +2562,7 @@ function messageCopyText(message, body = null) {
2516
2562
  return sections.join("\n\n").trimEnd() || messageCopyFallbackText(body);
2517
2563
  }
2518
2564
  if (message.role === "thinking") return visibleThinkingText(message.thinking || textFromContent(message.content)).trimEnd() || messageCopyFallbackText(body);
2519
- if (message.role === "toolCall") return JSON.stringify(message.arguments ?? message.content ?? {}, null, 2);
2565
+ if (message.role === "toolCall") return toolCallDisplayText(message).trimEnd() || messageCopyFallbackText(body);
2520
2566
  if (message.role === "assistantEvent") {
2521
2567
  return (typeof message.content === "string" ? message.content : JSON.stringify(message.content ?? {}, null, 2)).trimEnd();
2522
2568
  }
@@ -4453,6 +4499,7 @@ function syncTabMetadata(nextTabs = []) {
4453
4499
  if (!tab?.id) continue;
4454
4500
  liveIds.add(tab.id);
4455
4501
  setTabActivity(tab.id, tab.activity);
4502
+ if (Object.prototype.hasOwnProperty.call(tab, "appRunner")) setAppRunnerData(tab.id, { activeRun: tab.appRunner });
4456
4503
  }
4457
4504
  for (const tabId of tabActivities.keys()) {
4458
4505
  if (!liveIds.has(tabId)) {
@@ -4464,6 +4511,7 @@ function syncTabMetadata(nextTabs = []) {
4464
4511
  skillUsageByTab.delete(tabId);
4465
4512
  tabMessagesCache.delete(tabId);
4466
4513
  widgetsByTab.delete(tabId);
4514
+ appRunnerDataByTab.delete(tabId);
4467
4515
  clearGitWorkflowForTab(tabId);
4468
4516
  }
4469
4517
  }
@@ -4514,7 +4562,7 @@ function tabIndicator(tab) {
4514
4562
  }
4515
4563
 
4516
4564
  function hasWorkingTab() {
4517
- return tabs.some((tab) => ["working", "blocked"].includes(tabIndicator(tab).state));
4565
+ return tabs.some((tab) => ["working", "blocked"].includes(tabIndicator(tab).state) || tabAppRunnerRunningRun(tab));
4518
4566
  }
4519
4567
 
4520
4568
  function scheduleRefreshTabs(delay = 1500) {
@@ -4544,7 +4592,7 @@ function markTabWorkingLocally(tabId = activeTabId) {
4544
4592
  const previous = activityForTab(tab);
4545
4593
  const next = normalizeTabActivity({ ...previous, status: "working", isWorking: true });
4546
4594
  tabActivities.set(tabId, next);
4547
- if (tabActivityStateChanged(previous, next)) renderTabs();
4595
+ if (tabActivityStateChanged(previous, next)) scheduleTabsRender();
4548
4596
  return true;
4549
4597
  }
4550
4598
 
@@ -4554,7 +4602,7 @@ function markTabIdleLocally(tabId = activeTabId) {
4554
4602
  const previous = activityForTab(tab);
4555
4603
  const next = normalizeTabActivity({ ...previous, status: "idle", isWorking: false });
4556
4604
  tabActivities.set(tabId, next);
4557
- if (tabActivityStateChanged(previous, next)) renderTabs();
4605
+ if (tabActivityStateChanged(previous, next)) scheduleTabsRender();
4558
4606
  return true;
4559
4607
  }
4560
4608
 
@@ -4570,7 +4618,7 @@ function markTabDoneLocally(tabId = activeTabId) {
4570
4618
  lastCompletedAt: new Date().toISOString(),
4571
4619
  });
4572
4620
  tabActivities.set(tabId, next);
4573
- if (tabActivityStateChanged(previous, next)) renderTabs();
4621
+ if (tabActivityStateChanged(previous, next)) scheduleTabsRender();
4574
4622
  return true;
4575
4623
  }
4576
4624
 
@@ -4610,7 +4658,7 @@ function markTabOutputSeen(tabId = activeTabId, { force = false } = {}) {
4610
4658
  const previousSerial = tabSeenCompletionSerials.get(tabId) ?? 0;
4611
4659
  if (previousSerial >= completionSerial) return false;
4612
4660
  tabSeenCompletionSerials.set(tabId, completionSerial);
4613
- renderTabs();
4661
+ scheduleTabsRender();
4614
4662
  return true;
4615
4663
  }
4616
4664
 
@@ -4630,7 +4678,14 @@ function ingestEventTabActivity(event) {
4630
4678
  const next = setTabActivity(event.tabId, event.tabActivity);
4631
4679
  changed = tabActivityStateChanged(previous, next) || changed;
4632
4680
  }
4633
- if (changed) renderTabs();
4681
+ if (changed) scheduleTabsRender();
4682
+ }
4683
+
4684
+ function eventHasTabActivityPayload(event) {
4685
+ return !!(
4686
+ event?.tabId &&
4687
+ (event.tabTitle || event.tabActivity || Object.prototype.hasOwnProperty.call(event, "pendingExtensionUiRequestCount"))
4688
+ );
4634
4689
  }
4635
4690
 
4636
4691
  function trackAutoRetryStateFromEvent(event) {
@@ -4752,11 +4807,42 @@ function restoreWidgetsForActiveTab() {
4752
4807
  for (const [key, value] of cache) widgets.set(key, value);
4753
4808
  }
4754
4809
 
4810
+ function todoProgressSignatureFromLines(lines = []) {
4811
+ const parsed = parseTodoProgressWidget(lines);
4812
+ if (!parsed) return JSON.stringify(lines.map(stripAnsi));
4813
+ return JSON.stringify({ goal: parsed.goal, done: parsed.done, total: parsed.total, partial: parsed.partial, items: parsed.items, footer: parsed.footer });
4814
+ }
4815
+
4816
+ function rememberTodoProgressGoalForTab(tabId, widgetKey, request) {
4817
+ if (widgetKey !== "todo-progress" || !tabId) return;
4818
+ if (!Array.isArray(request?.widgetLines)) {
4819
+ todoProgressGoalByTab.delete(tabId);
4820
+ todoProgressSignatureByTab.delete(tabId);
4821
+ return;
4822
+ }
4823
+ const parsed = parseTodoProgressWidget(request.widgetLines);
4824
+ if (parsed?.goal) todoProgressGoalByTab.set(tabId, parsed.goal);
4825
+ todoProgressSignatureByTab.set(tabId, todoProgressSignatureFromLines(request.widgetLines));
4826
+ }
4827
+
4828
+ function widgetRequestEquivalent(a, b) {
4829
+ const aHasLines = Array.isArray(a?.widgetLines);
4830
+ const bHasLines = Array.isArray(b?.widgetLines);
4831
+ if (aHasLines !== bHasLines) return false;
4832
+ if (!aHasLines) return true;
4833
+ if (a.widgetLines.length !== b.widgetLines.length) return false;
4834
+ return a.widgetLines.every((line, index) => String(line) === String(b.widgetLines[index]));
4835
+ }
4836
+
4755
4837
  function setWidgetForTab(tabId, widgetKey, request) {
4756
- if (!widgetKey) return;
4838
+ if (!widgetKey) return false;
4757
4839
  const targetTabId = tabId || activeTabId;
4758
4840
  const cache = widgetCacheForTab(targetTabId);
4759
4841
  const hasLines = Array.isArray(request?.widgetLines);
4842
+ const current = cache?.get(widgetKey) || (targetTabId === activeTabId ? widgets.get(widgetKey) : undefined);
4843
+ if (widgetRequestEquivalent(current, request)) return false;
4844
+
4845
+ rememberTodoProgressGoalForTab(targetTabId, widgetKey, request);
4760
4846
 
4761
4847
  if (cache) {
4762
4848
  if (hasLines) cache.set(widgetKey, request);
@@ -4768,11 +4854,21 @@ function setWidgetForTab(tabId, widgetKey, request) {
4768
4854
  if (hasLines) widgets.set(widgetKey, request);
4769
4855
  else widgets.delete(widgetKey);
4770
4856
  }
4857
+
4858
+ return true;
4771
4859
  }
4772
4860
 
4773
4861
  function clearWidgetsForTab(tabId = activeTabId) {
4774
- if (tabId) widgetsByTab.delete(tabId);
4862
+ if (tabId) {
4863
+ widgetsByTab.delete(tabId);
4864
+ todoProgressGoalByTab.delete(tabId);
4865
+ todoProgressSignatureByTab.delete(tabId);
4866
+ }
4775
4867
  if (!tabId || tabId === activeTabId) widgets.clear();
4868
+ if (!tabId) {
4869
+ todoProgressGoalByTab.clear();
4870
+ todoProgressSignatureByTab.clear();
4871
+ }
4776
4872
  }
4777
4873
 
4778
4874
  function resetActiveTabUi() {
@@ -4911,15 +5007,43 @@ function terminalDisplayGroupDetail(group, fallback = "group") {
4911
5007
  return `${cwdLabels[0]} + ${cwdLabels.length - 1} cwd${cwdLabels.length === 2 ? "" : "s"}`;
4912
5008
  }
4913
5009
 
5010
+ function tabAppRunnerRun(tab) {
5011
+ if (!tab?.id) return null;
5012
+ const cached = appRunnerDataByTab.get(tab.id);
5013
+ if (cached && Object.prototype.hasOwnProperty.call(cached, "activeRun")) return cached.activeRun || null;
5014
+ if (Object.prototype.hasOwnProperty.call(tab, "appRunner")) return tab.appRunner || null;
5015
+ return null;
5016
+ }
5017
+
5018
+ function tabAppRunnerRunningRun(tab) {
5019
+ const run = tabAppRunnerRun(tab);
5020
+ return appRunnerIsRunning(run) ? run : null;
5021
+ }
5022
+
5023
+ function tabGroupAppRunnerRunningRun(groupTabs = []) {
5024
+ return groupTabs.map(tabAppRunnerRunningRun).find(Boolean) || null;
5025
+ }
5026
+
5027
+ function terminalAppRunnerLabel(run) {
5028
+ const command = cleanStatusText(run?.displayCommand || run?.label || run?.command || "app runner");
5029
+ return command && command !== "app runner" ? `app runner: ${command}` : "app runner running";
5030
+ }
5031
+
5032
+ function terminalAppRunnerTooltip(run) {
5033
+ return appRunnerIsRunning(run) ? ` · ${terminalAppRunnerLabel(run)}` : "";
5034
+ }
5035
+
4914
5036
  function terminalTabMeta(tab, indicator) {
4915
- return tab.running ? `${indicator.meta} · pid ${tab.pid || "…"}` : "stopped";
5037
+ const meta = tab.running ? `${indicator.meta} · pid ${tab.pid || "…"}` : "stopped";
5038
+ return tabAppRunnerRunningRun(tab) ? `${meta} · app runner` : meta;
4916
5039
  }
4917
5040
 
4918
- function appendTerminalTabContent(button, { title, indicator, meta, count = null }) {
5041
+ function appendTerminalTabContent(button, { title, indicator, meta, count = null, appRunnerRun = null }) {
4919
5042
  const titleRow = make("span", "terminal-tab-title-row");
4920
5043
  const indicatorDot = make("span", "terminal-tab-activity-indicator");
4921
5044
  indicatorDot.setAttribute("aria-hidden", "true");
4922
5045
  titleRow.append(indicatorDot, make("span", "terminal-tab-title", title));
5046
+ if (appRunnerIsRunning(appRunnerRun)) titleRow.append(make("span", "terminal-tab-app-runner-indicator", "app"));
4923
5047
  if (count !== null) titleRow.append(make("span", "terminal-tab-group-count", String(count)));
4924
5048
  button.append(titleRow, make("span", "terminal-tab-meta", meta));
4925
5049
  }
@@ -4927,7 +5051,9 @@ function appendTerminalTabContent(button, { title, indicator, meta, count = null
4927
5051
  function renderTerminalTab(tab) {
4928
5052
  const isActive = tab.id === activeTabId;
4929
5053
  const indicator = tabIndicator(tab);
4930
- const wrapper = make("div", `terminal-tab activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}`);
5054
+ const appRunnerRun = tabAppRunnerRunningRun(tab);
5055
+ const appRunnerLabel = appRunnerRun ? terminalAppRunnerLabel(appRunnerRun) : "";
5056
+ const wrapper = make("div", `terminal-tab activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}${appRunnerRun ? " app-runner-running" : ""}`);
4931
5057
  wrapper.dataset.tabId = tab.id;
4932
5058
  bindTerminalTabDragAndDrop(wrapper, { sourceTabId: tab.id, target: { type: "tab", tabId: tab.id } });
4933
5059
  const button = make("button", "terminal-tab-button");
@@ -4935,9 +5061,10 @@ function renderTerminalTab(tab) {
4935
5061
  button.draggable = false;
4936
5062
  button.setAttribute("role", "tab");
4937
5063
  button.setAttribute("aria-selected", isActive ? "true" : "false");
4938
- button.setAttribute("aria-label", `${tab.title}: ${indicator.label}`);
4939
- button.title = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"} · drag onto another tab or group to group`;
4940
- appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator) });
5064
+ button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}`);
5065
+ const tooltip = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"}${terminalAppRunnerTooltip(appRunnerRun)} · drag onto another tab or group to group`;
5066
+ applyStyledTooltip(button, tooltip, { ariaLabel: false });
5067
+ appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun });
4941
5068
  button.addEventListener("click", () => switchTab(tab.id));
4942
5069
  wrapper.append(button);
4943
5070
 
@@ -4945,8 +5072,8 @@ function renderTerminalTab(tab) {
4945
5072
  const close = make("button", "terminal-tab-close", "×");
4946
5073
  close.type = "button";
4947
5074
  close.draggable = false;
4948
- close.title = `Close ${tab.title}`;
4949
- close.setAttribute("aria-label", `Close ${tab.title}`);
5075
+ const closeTooltip = `Close ${tab.title}`;
5076
+ applyStyledTooltip(close, closeTooltip, { ariaLabel: closeTooltip });
4950
5077
  close.addEventListener("click", (event) => {
4951
5078
  event.stopPropagation();
4952
5079
  closeTerminalTab(tab.id);
@@ -4960,7 +5087,9 @@ function renderTerminalTab(tab) {
4960
5087
  function renderTerminalTabGroupItem(tab, group) {
4961
5088
  const isActive = tab.id === activeTabId;
4962
5089
  const indicator = tabIndicator(tab);
4963
- const item = make("div", `terminal-tab-group-item activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}`);
5090
+ const appRunnerRun = tabAppRunnerRunningRun(tab);
5091
+ const appRunnerLabel = appRunnerRun ? terminalAppRunnerLabel(appRunnerRun) : "";
5092
+ const item = make("div", `terminal-tab-group-item activity-${indicator.state}${isActive ? " active" : ""}${tab.running ? "" : " stopped"}${appRunnerRun ? " app-runner-running" : ""}`);
4964
5093
  item.dataset.tabId = tab.id;
4965
5094
  bindTerminalTabDragAndDrop(item, { sourceTabId: tab.id, target: group?.custom ? { type: "group", group } : { type: "tab", tabId: tab.id } });
4966
5095
  const button = make("button", "terminal-tab-button terminal-tab-group-item-button");
@@ -4968,9 +5097,10 @@ function renderTerminalTabGroupItem(tab, group) {
4968
5097
  button.draggable = false;
4969
5098
  button.setAttribute("role", "tab");
4970
5099
  button.setAttribute("aria-selected", isActive ? "true" : "false");
4971
- button.setAttribute("aria-label", `${tab.title}: ${indicator.label}`);
4972
- button.title = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"} · drag onto another tab or group to group`;
4973
- appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator) });
5100
+ button.setAttribute("aria-label", `${tab.title}: ${indicator.label}${appRunnerLabel ? `, ${appRunnerLabel}` : ""}`);
5101
+ const tooltip = `${tab.title} · ${indicator.label}${tab.running ? ` · pid ${tab.pid || "starting"}` : " · stopped"}${terminalAppRunnerTooltip(appRunnerRun)} · drag onto another tab or group to group`;
5102
+ applyStyledTooltip(button, tooltip, { ariaLabel: false });
5103
+ appendTerminalTabContent(button, { title: tab.title, indicator, meta: terminalTabMeta(tab, indicator), appRunnerRun });
4974
5104
  button.addEventListener("click", (event) => {
4975
5105
  event.stopPropagation();
4976
5106
  switchTab(tab.id);
@@ -4981,8 +5111,8 @@ function renderTerminalTabGroupItem(tab, group) {
4981
5111
  const close = make("button", "terminal-tab-close terminal-tab-group-item-close", "×");
4982
5112
  close.type = "button";
4983
5113
  close.draggable = false;
4984
- close.title = `Close ${tab.title}`;
4985
- close.setAttribute("aria-label", `Close ${tab.title}`);
5114
+ const closeTooltip = `Close ${tab.title}`;
5115
+ applyStyledTooltip(close, closeTooltip, { ariaLabel: closeTooltip });
4986
5116
  close.addEventListener("click", (event) => {
4987
5117
  event.stopPropagation();
4988
5118
  closeTerminalTab(tab.id);
@@ -5004,10 +5134,14 @@ function renderTerminalTabGroup(group, groupCount = 1) {
5004
5134
  const isActive = groupTabs.some((tab) => tab.id === activeTabId);
5005
5135
  const isStopped = groupTabs.every((tab) => !tab.running);
5006
5136
  const indicator = tabGroupIndicator(groupTabs);
5137
+ const appRunnerRun = tabGroupAppRunnerRunningRun(groupTabs);
5138
+ const appRunnerCount = groupTabs.filter(tabAppRunnerRunningRun).length;
5139
+ const appRunnerSummary = appRunnerCount > 1 ? `${appRunnerCount} app runners running` : appRunnerRun ? terminalAppRunnerLabel(appRunnerRun) : "";
5140
+ const groupAppRunnerMeta = appRunnerCount > 1 ? `${appRunnerCount} app runners` : appRunnerRun ? "app runner" : "";
5007
5141
  const groupTitle = terminalDisplayGroupTitle(group, activeGroupTab?.title || "group");
5008
5142
  const activeTitle = activeGroupTab?.title || groupTitle;
5009
5143
  const groupDetail = terminalDisplayGroupDetail(group, groupTitle);
5010
- const wrapper = make("div", `terminal-tab terminal-tab-group${group.custom ? " terminal-tab-custom-group" : ""} activity-${indicator.state}${isActive ? " active" : ""}${isStopped ? " stopped" : ""}`);
5144
+ const wrapper = make("div", `terminal-tab terminal-tab-group${group.custom ? " terminal-tab-custom-group" : ""} activity-${indicator.state}${isActive ? " active" : ""}${isStopped ? " stopped" : ""}${appRunnerRun ? " app-runner-running" : ""}`);
5011
5145
  wrapper.dataset.groupKey = group.key;
5012
5146
  if (group.customGroupId) wrapper.dataset.customGroupId = group.customGroupId;
5013
5147
  bindTerminalTabDragAndDrop(wrapper, { sourceTabId: activeGroupTab?.id || "", target: { type: "group", group } });
@@ -5026,9 +5160,10 @@ function renderTerminalTabGroup(group, groupCount = 1) {
5026
5160
  button.setAttribute("aria-selected", isActive ? "true" : "false");
5027
5161
  button.setAttribute("aria-haspopup", "true");
5028
5162
  button.setAttribute("aria-expanded", group.key === openTerminalTabGroupKey ? "true" : "false");
5029
- button.setAttribute("aria-label", `${groupTitle} ${group.custom ? "custom" : "cwd"} group: ${groupTabs.length} tabs, ${indicator.label}. Active ${activeTitle}`);
5030
- button.title = `${activeTitle} · ${groupTitle} · ${groupDetail} · ${groupTabs.length} tabs · ${indicator.label} · drop tabs here to add to group`;
5031
- appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}`, count: groupTabs.length });
5163
+ button.setAttribute("aria-label", `${groupTitle} ${group.custom ? "custom" : "cwd"} group: ${groupTabs.length} tabs, ${indicator.label}${appRunnerSummary ? `, ${appRunnerSummary}` : ""}. Active ${activeTitle}`);
5164
+ const tooltip = `${activeTitle} · ${groupTitle} · ${groupDetail} · ${groupTabs.length} tabs · ${indicator.label}${appRunnerSummary ? ` · ${appRunnerSummary}` : ""} · drop tabs here to add to group`;
5165
+ applyStyledTooltip(button, tooltip, { ariaLabel: false });
5166
+ appendTerminalTabContent(button, { title: activeTitle, indicator, meta: `${groupTitle} · ${indicator.meta}${groupAppRunnerMeta ? ` · ${groupAppRunnerMeta}` : ""}`, appRunnerRun, count: groupTabs.length });
5032
5167
  button.addEventListener("click", () => switchTab(activeGroupTab.id));
5033
5168
  wrapper.append(button);
5034
5169
 
@@ -5036,8 +5171,8 @@ function renderTerminalTabGroup(group, groupCount = 1) {
5036
5171
  const close = make("button", "terminal-tab-close terminal-tab-group-close", "×");
5037
5172
  close.type = "button";
5038
5173
  close.draggable = false;
5039
- close.title = `Close ${groupTitle} group`;
5040
- close.setAttribute("aria-label", `Close ${groupTitle} group`);
5174
+ const closeTooltip = `Close ${groupTitle} group`;
5175
+ applyStyledTooltip(close, closeTooltip, { ariaLabel: closeTooltip });
5041
5176
  close.addEventListener("click", (event) => {
5042
5177
  event.stopPropagation();
5043
5178
  closeTerminalTabGroup(group);
@@ -5053,8 +5188,8 @@ function renderTerminalTabGroup(group, groupCount = 1) {
5053
5188
  const add = make("button", "terminal-tab-group-add", "+ Tab");
5054
5189
  add.type = "button";
5055
5190
  add.draggable = false;
5056
- add.title = `Add tab in ${groupTitle}`;
5057
- add.setAttribute("aria-label", `Add tab in ${groupTitle}`);
5191
+ const addTooltip = `Add tab in ${groupTitle}`;
5192
+ applyStyledTooltip(add, addTooltip, { ariaLabel: addTooltip });
5058
5193
  add.addEventListener("click", (event) => {
5059
5194
  event.stopPropagation();
5060
5195
  createTerminalTab(activeGroupTab?.cwd || group.cwd || currentDirectoryForNewTab(), { triggerButton: add, customGroupId: group.customGroupId || null });
@@ -5093,6 +5228,11 @@ function setNewTabMenuOpen(open) {
5093
5228
  if (!newTabMenuOpen) scheduleDeferredUiFlushAfterDropdownClose();
5094
5229
  }
5095
5230
 
5231
+ function initializeTerminalHeaderTooltips() {
5232
+ applyStyledTooltip(elements.newTabButton, "Start a separate isolated Pi terminal", { ariaLabel: "Start a separate isolated Pi terminal" });
5233
+ applyStyledTooltip(elements.closeAllTabsButton, "Close all terminal tabs", { ariaLabel: "Close all terminal tabs" });
5234
+ }
5235
+
5096
5236
  function openNewTabMenu() {
5097
5237
  setPublishMenuOpen(false);
5098
5238
  setNativeCommandMenuOpen(false);
@@ -5101,26 +5241,42 @@ function openNewTabMenu() {
5101
5241
  setNewTabMenuOpen(true);
5102
5242
  }
5103
5243
 
5244
+ function newTabMenuItems() {
5245
+ return [elements.newTabCurrentDirectoryButton, elements.newTabChooseDirectoryButton, elements.newTabWorktreeButton].filter(Boolean);
5246
+ }
5247
+
5104
5248
  function focusNewTabMenuItem(direction = "first") {
5105
- const items = [elements.newTabCurrentDirectoryButton, elements.newTabChooseDirectoryButton].filter(Boolean);
5249
+ const items = newTabMenuItems();
5106
5250
  const item = direction === "last" ? items.at(-1) : items[0];
5107
5251
  item?.focus({ preventScroll: true });
5108
5252
  }
5109
5253
 
5110
5254
  function moveNewTabMenuFocus(delta) {
5111
- const items = [elements.newTabCurrentDirectoryButton, elements.newTabChooseDirectoryButton].filter(Boolean);
5255
+ const items = newTabMenuItems();
5112
5256
  if (!items.length) return;
5113
5257
  const currentIndex = Math.max(0, items.indexOf(document.activeElement));
5114
5258
  const nextIndex = (currentIndex + delta + items.length) % items.length;
5115
5259
  items[nextIndex].focus({ preventScroll: true });
5116
5260
  }
5117
5261
 
5262
+ function scheduleTabsRender() {
5263
+ if (tabsRenderFrame !== null) return;
5264
+ const flush = () => {
5265
+ tabsRenderFrame = null;
5266
+ renderTabs();
5267
+ };
5268
+ if (typeof requestAnimationFrame === "function") tabsRenderFrame = requestAnimationFrame(flush);
5269
+ else tabsRenderFrame = setTimeout(flush, 0);
5270
+ }
5271
+
5118
5272
  function renderTabs() {
5119
5273
  if (deferUiRenderDuringPointerActivation("tabs", renderTabs)) return;
5120
5274
  const active = activeTab();
5121
5275
  const activeIndicator = active ? tabIndicator(active) : null;
5122
5276
  elements.terminalTabsToggleButton.textContent = active ? `${activeIndicator.glyph} ${active.title}${tabs.length > 1 ? ` · ${tabs.length}` : ""}` : "Tabs";
5123
- elements.terminalTabsToggleButton.title = active ? `Show terminal tabs · active: ${active.title} · ${activeIndicator.label}` : "Show terminal tabs";
5277
+ const toggleTooltip = active ? `Show terminal tabs · active: ${active.title} · ${activeIndicator.label}` : "Show terminal tabs";
5278
+ applyStyledTooltip(elements.terminalTabsToggleButton, toggleTooltip, { ariaLabel: toggleTooltip });
5279
+ if (footerTooltipTarget && elements.tabBar.contains(footerTooltipTarget)) hideFooterTooltip();
5124
5280
  elements.tabBar.replaceChildren();
5125
5281
  elements.tabBar.dataset.tabCount = String(tabs.length);
5126
5282
  elements.tabBar.classList.toggle("terminal-tabs-dense", tabs.length >= 10);
@@ -6057,6 +6213,24 @@ function normalizeDisplayPath(value) {
6057
6213
  return String(value || "").replace(/\\/g, "/");
6058
6214
  }
6059
6215
 
6216
+ function normalizeGitWorkspaceInfo(workspace) {
6217
+ if (!workspace || typeof workspace !== "object") return null;
6218
+ return {
6219
+ repoRoot: normalizeDisplayPath(workspace.repoRoot || ""),
6220
+ commonGitDir: normalizeDisplayPath(workspace.commonGitDir || ""),
6221
+ worktreePath: normalizeDisplayPath(workspace.worktreePath || workspace.path || ""),
6222
+ branch: cleanStatusText(workspace.branch || ""),
6223
+ worktreeCount: Number.isFinite(Number(workspace.worktreeCount)) ? Number(workspace.worktreeCount) : null,
6224
+ isMainWorktree: workspace.isMainWorktree === true,
6225
+ };
6226
+ }
6227
+
6228
+ function gitWorkspaceBadgeLabel(workspace = normalizeGitWorkspaceInfo(activeTab()?.gitWorkspace)) {
6229
+ if (!workspace?.worktreePath) return "";
6230
+ const branch = workspace.branch || "detached";
6231
+ return workspace.isMainWorktree ? `main worktree · ${branch}` : `worktree · ${branch}`;
6232
+ }
6233
+
6060
6234
  function textFromContent(content) {
6061
6235
  if (typeof content === "string") return content;
6062
6236
  if (!Array.isArray(content)) return JSON.stringify(content ?? "");
@@ -6076,9 +6250,13 @@ function cleanTooltipText(value) {
6076
6250
  return stripAnsi(value).replace(/\r\n?/g, "\n").replace(/[^\S\n]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
6077
6251
  }
6078
6252
 
6253
+ const TOOLTIP_HOVER_DELAY_MS = 500;
6254
+
6079
6255
  let footerTooltipNode = null;
6080
6256
  let footerTooltipTarget = null;
6081
6257
  let footerTooltipEventsBound = false;
6258
+ let footerTooltipHoverTimer = null;
6259
+ let footerTooltipPendingTarget = null;
6082
6260
 
6083
6261
  function ensureFooterTooltipNode() {
6084
6262
  if (!footerTooltipNode) {
@@ -6119,7 +6297,15 @@ function positionFooterTooltip(target) {
6119
6297
  footerTooltipNode.style.top = `${Math.round(top)}px`;
6120
6298
  }
6121
6299
 
6300
+ function clearFooterTooltipHoverTimer(target) {
6301
+ if (target && footerTooltipPendingTarget && target !== footerTooltipPendingTarget) return;
6302
+ if (footerTooltipHoverTimer) clearTimeout(footerTooltipHoverTimer);
6303
+ footerTooltipHoverTimer = null;
6304
+ footerTooltipPendingTarget = null;
6305
+ }
6306
+
6122
6307
  function showFooterTooltip(target) {
6308
+ clearFooterTooltipHoverTimer();
6123
6309
  const text = target?.getAttribute("data-tooltip");
6124
6310
  if (!text) return;
6125
6311
  footerTooltipTarget = target;
@@ -6130,7 +6316,21 @@ function showFooterTooltip(target) {
6130
6316
  positionFooterTooltip(target);
6131
6317
  }
6132
6318
 
6319
+ function scheduleFooterTooltip(target) {
6320
+ const text = target?.getAttribute("data-tooltip");
6321
+ if (!text) return;
6322
+ clearFooterTooltipHoverTimer();
6323
+ footerTooltipPendingTarget = target;
6324
+ footerTooltipHoverTimer = setTimeout(() => {
6325
+ const pendingTarget = footerTooltipPendingTarget;
6326
+ clearFooterTooltipHoverTimer();
6327
+ if (!pendingTarget?.isConnected || !pendingTarget.matches?.(":hover")) return;
6328
+ showFooterTooltip(pendingTarget);
6329
+ }, TOOLTIP_HOVER_DELAY_MS);
6330
+ }
6331
+
6133
6332
  function hideFooterTooltip(target) {
6333
+ clearFooterTooltipHoverTimer(target);
6134
6334
  if (target && target !== footerTooltipTarget) return;
6135
6335
  footerTooltipTarget = null;
6136
6336
  if (!footerTooltipNode) return;
@@ -6138,19 +6338,34 @@ function hideFooterTooltip(target) {
6138
6338
  footerTooltipNode.classList.remove("visible");
6139
6339
  }
6140
6340
 
6141
- function applyFooterTooltip(node, tooltip, options = {}) {
6341
+ function bindStyledTooltipEvents(node) {
6342
+ if (!node || node._styledTooltipBound) return;
6343
+ node._styledTooltipBound = true;
6344
+ node.addEventListener("mouseenter", () => scheduleFooterTooltip(node));
6345
+ node.addEventListener("mouseleave", () => hideFooterTooltip(node));
6346
+ node.addEventListener("focus", () => showFooterTooltip(node));
6347
+ node.addEventListener("blur", () => hideFooterTooltip(node));
6348
+ }
6349
+
6350
+ function applyStyledTooltip(node, tooltip, options = {}) {
6351
+ if (!node) return node;
6142
6352
  const text = cleanTooltipText(tooltip);
6143
6353
  if (!text) return node;
6144
6354
  node.setAttribute("data-tooltip", text);
6145
- node.setAttribute("aria-label", text.replace(/\s+/g, " "));
6355
+ node.removeAttribute("title");
6356
+ if (options.ariaLabel !== false) {
6357
+ const ariaLabel = typeof options.ariaLabel === "string" ? options.ariaLabel : text.replace(/\s+/g, " ");
6358
+ node.setAttribute("aria-label", ariaLabel);
6359
+ }
6146
6360
  if (options.align) node.setAttribute("data-tooltip-align", options.align);
6147
- node.addEventListener("mouseenter", () => showFooterTooltip(node));
6148
- node.addEventListener("mouseleave", () => hideFooterTooltip(node));
6149
- node.addEventListener("focus", () => showFooterTooltip(node));
6150
- node.addEventListener("blur", () => hideFooterTooltip(node));
6361
+ bindStyledTooltipEvents(node);
6151
6362
  return node;
6152
6363
  }
6153
6364
 
6365
+ function applyFooterTooltip(node, tooltip, options = {}) {
6366
+ return applyStyledTooltip(node, tooltip, options);
6367
+ }
6368
+
6154
6369
  function footerMetric(icon, label, value, tone = "", options = {}) {
6155
6370
  const isAction = typeof options.onClick === "function";
6156
6371
  const node = make(isAction ? "button" : "span", ["footer-metric", tone, isAction ? "footer-metric-action" : ""].filter(Boolean).join(" "));
@@ -6229,6 +6444,7 @@ const FOOTER_META_CLASS_BY_KEY = new Map([
6229
6444
  ["sync", "footer-sync"],
6230
6445
  ["changes", "footer-changes"],
6231
6446
  ["git-extra", "footer-git-extra"],
6447
+ ["worktree", "footer-worktree"],
6232
6448
  ["context", "footer-context"],
6233
6449
  ["model", "footer-model"],
6234
6450
  ["thinking", "footer-thinking"],
@@ -6247,6 +6463,7 @@ const GIT_FOOTER_TOOLTIP_COPY = {
6247
6463
  sync: "Remote tracking divergence. ↑ means local commits ahead; ↓ means remote commits to pull.",
6248
6464
  changes: "Working tree and fetched remote summary. 🟢 staged, ✏️ modified unstaged, ➕ untracked, ⚠️ conflicted; ⬇️ means fetched remote commits to pull; 🔄/✓/⚠️ fetch shows the tab git fetch state; ✅ means no changes.",
6249
6465
  "git-extra": "Extra Git signals. 📦 stash, 🧩 dirty submodules, 🌳 worktrees, 🏷️ tag at HEAD, 🕒 last commit age, 🔓 signing mismatch.",
6466
+ worktree: "Git worktree checkout for this tab. Use branch worktrees to work on branches in parallel without switching this checkout.",
6250
6467
  model: "Scoped model for this tab.",
6251
6468
  thinking: "Reasoning/thinking effort for this tab.",
6252
6469
  };
@@ -6419,7 +6636,10 @@ function footerPayloadWithLiveModel(payload) {
6419
6636
  if (!payload) return payload;
6420
6637
  const model = currentState?.model ? shortModelLabel(currentState.model) : "";
6421
6638
  const effort = footerThinkingDisplay();
6639
+ const workspace = normalizeGitWorkspaceInfo(activeTab()?.gitWorkspace);
6640
+ const worktreeLabel = gitWorkspaceBadgeLabel(workspace);
6422
6641
  const hasThinkingChip = [...payload.main, ...payload.meta].some((chip) => chip?.key === "thinking");
6642
+ const hasWorktreeChip = [...payload.main, ...payload.meta].some((chip) => chip?.key === "worktree");
6423
6643
  const contextChip = (chip) => {
6424
6644
  const usageUnknown = contextUsageUnknownAfterCompaction();
6425
6645
  const value = usageUnknown ? footerContextDisplayWithAuto(unknownFooterContextText(chip?.contextUsage)) : footerContextDisplayWithAuto(chip?.value);
@@ -6427,6 +6647,7 @@ function footerPayloadWithLiveModel(payload) {
6427
6647
  return { ...chip, value, title: `context: ${value}`, ...(contextUsage ? { contextUsage } : {}) };
6428
6648
  };
6429
6649
  const effortChip = (chip) => ({ ...chip, key: "thinking", label: "effort", value: effort, title: `effort: ${effort}`, tone: "mauve" });
6650
+ const worktreeChip = () => ({ key: "worktree", label: "worktree", value: worktreeLabel, icon: "🌳", tone: workspace?.isMainWorktree ? "teal" : "green", title: workspace?.worktreePath || "Git worktree" });
6430
6651
  const splitChip = (chip) => {
6431
6652
  if (chip?.key === "context") return [contextChip(chip)];
6432
6653
  if (chip?.key === "thinking") return [effortChip(chip)];
@@ -6434,9 +6655,11 @@ function footerPayloadWithLiveModel(payload) {
6434
6655
  const modelChip = { ...chip, value: model, title: `model: ${model}` };
6435
6656
  return hasThinkingChip ? [modelChip] : [modelChip, effortChip(chip)];
6436
6657
  };
6658
+ const meta = payload.meta.flatMap(splitChip);
6659
+ if (worktreeLabel && !hasWorktreeChip) meta.splice(Math.min(meta.length, 2), 0, worktreeChip());
6437
6660
  return {
6438
6661
  main: payload.main.flatMap(splitChip),
6439
- meta: payload.meta.flatMap(splitChip),
6662
+ meta,
6440
6663
  };
6441
6664
  }
6442
6665
 
@@ -6484,11 +6707,14 @@ function footerTuiItem(value, className = "", options = {}) {
6484
6707
 
6485
6708
  function renderTuiFooterLine({ cwd, cwdTitle, message = "", stats = [], model = "" } = {}) {
6486
6709
  const tab = activeTab();
6710
+ const workspace = normalizeGitWorkspaceInfo(tab?.gitWorkspace);
6711
+ const worktreeLabel = gitWorkspaceBadgeLabel(workspace);
6487
6712
  const line = make("div", "footer-line footer-line-tui");
6488
6713
  line.append(footerTuiItem(cwd || "loading…", "footer-tui-cwd", tab ? {
6489
6714
  onClick: changeActiveTabCwd,
6490
6715
  title: cwdTitle || `Change cwd for ${tab.title}: ${cwd}`,
6491
6716
  } : { title: cwdTitle }));
6717
+ if (worktreeLabel) line.append(footerTuiItem(worktreeLabel, "footer-tui-worktree", { title: workspace?.worktreePath || worktreeLabel }));
6492
6718
  if (message) line.append(footerTuiItem(message, "footer-tui-status"));
6493
6719
  for (const stat of stats.filter(Boolean)) line.append(footerTuiItem(stat, "footer-tui-stat"));
6494
6720
  if (model) {
@@ -6586,7 +6812,10 @@ function renderGitFooterPayloadMeta(chip, tab) {
6586
6812
  action = "No Git repository detected. Click to initialize a repo, create README.md, add origin, and push main.";
6587
6813
  } else if (chip.key === "git") {
6588
6814
  options.onClick = () => setFooterBranchPickerOpen(!footerBranchPickerOpen);
6589
- action = "Click to switch to another local branch.";
6815
+ action = "Click to open, create, or switch branches. Worktree actions are the safe default for parallel work.";
6816
+ } else if (chip.key === "worktree") {
6817
+ options.onClick = () => setFooterBranchPickerOpen(!footerBranchPickerOpen);
6818
+ action = "Click to manage branch worktrees for this repository.";
6590
6819
  } else if (chip.key === "changes") {
6591
6820
  options.onClick = openGitChangesDialog;
6592
6821
  action = "Click to view the current git diff.";
@@ -6602,7 +6831,7 @@ function renderGitFooterPayloadMeta(chip, tab) {
6602
6831
  options.tooltipAlign = gitFooterTooltipAlign(chip);
6603
6832
  const node = footerMeta(chip.label, chip.value, footerMetaClassForPayload(chip), options);
6604
6833
  applyFooterChangedFilesDropdown(node, chip);
6605
- if (chip.key === "git" && options.onClick && cleanFooterPayloadText(chip.value, "").toLowerCase() !== "no repo") {
6834
+ if (["git", "worktree"].includes(chip.key) && options.onClick && cleanFooterPayloadText(chip.value, "").toLowerCase() !== "no repo") {
6606
6835
  node.setAttribute("aria-haspopup", "listbox");
6607
6836
  node.setAttribute("aria-expanded", footerBranchPickerOpen ? "true" : "false");
6608
6837
  }
@@ -6626,7 +6855,10 @@ function gitFooterChipShapeKey(chip) {
6626
6855
  }
6627
6856
 
6628
6857
  function gitFooterPickerStateKey() {
6629
- return `${footerModelPickerOpen ? 1 : 0}|${footerThinkingPickerOpen ? 1 : 0}|${footerBranchPickerOpen ? 1 : 0}|${mobileFooterExpanded ? 1 : 0}`;
6858
+ const tabContext = activeTabContext();
6859
+ const refreshInFlight = tabContext.tabId ? gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId) : false;
6860
+ const refreshAvailable = hasLoadedRpcCommand("git-footer-refresh");
6861
+ return `${footerModelPickerOpen ? 1 : 0}|${footerThinkingPickerOpen ? 1 : 0}|${footerBranchPickerOpen ? 1 : 0}|${mobileFooterExpanded ? 1 : 0}|${refreshInFlight ? 1 : 0}|${refreshAvailable ? 1 : 0}`;
6630
6862
  }
6631
6863
 
6632
6864
  function updateGitFooterChipNodeValue(node, chip, valueSelector) {
@@ -6642,6 +6874,40 @@ function invalidateGitFooterRenderCache() {
6642
6874
  gitFooterRenderCache = null;
6643
6875
  }
6644
6876
 
6877
+ function triggerGitFooterRefreshFromButton() {
6878
+ const tabContext = activeTabContext();
6879
+ if (!tabContext.tabId || gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId)) return;
6880
+ if (!resolveAvailableCommandName("git-footer-refresh", { rpcOnly: true })) {
6881
+ addEvent(optionalFeatureUnavailableMessage("gitFooterStatus"), "warn");
6882
+ return;
6883
+ }
6884
+ requestGitFooterWebuiPayload(tabContext, { force: true, silent: false, allowDuringRun: true });
6885
+ }
6886
+
6887
+ function renderGitFooterRefreshButton() {
6888
+ const tabContext = activeTabContext();
6889
+ const inFlight = tabContext.tabId ? gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId) : false;
6890
+ const commandAvailable = !!resolveAvailableCommandName("git-footer-refresh", { rpcOnly: true });
6891
+ const button = make("button", "git-footer-refresh-button");
6892
+ button.type = "button";
6893
+ button.title = inFlight
6894
+ ? "Refreshing git footer status…"
6895
+ : commandAvailable
6896
+ ? "Refresh git footer status (/git-footer-refresh)"
6897
+ : optionalFeatureUnavailableMessage("gitFooterStatus");
6898
+ button.setAttribute("aria-label", inFlight ? "Refreshing git footer status" : "Refresh git footer status");
6899
+ if (!commandAvailable) button.setAttribute("aria-disabled", "true");
6900
+ if (inFlight) button.setAttribute("aria-busy", "true");
6901
+ button.disabled = inFlight || !tabContext.tabId;
6902
+ button.append(make("span", "git-footer-refresh-icon", "↻"));
6903
+ button.addEventListener("click", (event) => {
6904
+ event.preventDefault();
6905
+ event.stopPropagation();
6906
+ triggerGitFooterRefreshFromButton();
6907
+ });
6908
+ return button;
6909
+ }
6910
+
6645
6911
  function renderGitFooterPayload(payload) {
6646
6912
  const tab = activeTab();
6647
6913
  const pickerKey = gitFooterPickerStateKey();
@@ -6688,7 +6954,7 @@ function renderGitFooterPayload(payload) {
6688
6954
  const row2 = make("div", "footer-line footer-line-meta");
6689
6955
  row2.append(...metaNodes, footerToggle);
6690
6956
 
6691
- elements.statusBar.append(row1, row2);
6957
+ elements.statusBar.append(row1, row2, renderGitFooterRefreshButton());
6692
6958
  if (footerModelPickerOpen) elements.statusBar.append(renderFooterModelPicker());
6693
6959
  if (footerThinkingPickerOpen) elements.statusBar.append(renderFooterThinkingPicker());
6694
6960
  if (footerBranchPickerOpen) elements.statusBar.append(renderFooterBranchPicker());
@@ -7478,6 +7744,8 @@ function renderWorkspaceDashboard() {
7478
7744
  const tab = activeTab();
7479
7745
  const snapshot = contextUsageSnapshot();
7480
7746
  const workspaceLabel = latestWorkspace?.displayCwd || (tab?.cwd ? normalizeDisplayPath(tab.cwd) : "Choose or create a tab to start");
7747
+ const workspaceInfo = normalizeGitWorkspaceInfo(tab?.gitWorkspace);
7748
+ const worktreeLabel = gitWorkspaceBadgeLabel(workspaceInfo);
7481
7749
  const queueCount = Number(currentState?.pendingMessageCount || 0) || 0;
7482
7750
  const tabIndicatorState = tab ? tabIndicator(tab) : null;
7483
7751
  const sessionSummary = dashboardSessionSummary();
@@ -7490,6 +7758,12 @@ function renderWorkspaceDashboard() {
7490
7758
  const signature = JSON.stringify({
7491
7759
  title: tab?.title || "Pi Web UI",
7492
7760
  workspaceLabel,
7761
+ gitWorkspace: workspaceInfo ? {
7762
+ branch: workspaceInfo.branch,
7763
+ worktreePath: workspaceInfo.worktreePath,
7764
+ isMainWorktree: workspaceInfo.isMainWorktree,
7765
+ worktreeCount: workspaceInfo.worktreeCount,
7766
+ } : null,
7493
7767
  tabIndicatorState,
7494
7768
  tabsLength: tabs.length,
7495
7769
  queueCount,
@@ -7519,6 +7793,13 @@ function renderWorkspaceDashboard() {
7519
7793
  statusChip.append(make("span", "workspace-dashboard-chip-dot", tabIndicatorState.glyph), make("span", undefined, tabIndicatorState.label));
7520
7794
  meta.append(statusChip);
7521
7795
  }
7796
+ if (worktreeLabel) {
7797
+ const worktreeChip = make("button", "workspace-dashboard-chip worktree", worktreeLabel);
7798
+ worktreeChip.type = "button";
7799
+ worktreeChip.title = workspaceInfo?.worktreePath || worktreeLabel;
7800
+ worktreeChip.addEventListener("click", () => openBranchWorktreePicker());
7801
+ meta.append(worktreeChip);
7802
+ }
7522
7803
  meta.append(
7523
7804
  make("span", "workspace-dashboard-chip", `${tabs.length} tab${tabs.length === 1 ? "" : "s"}`),
7524
7805
  make("span", `workspace-dashboard-chip ${queueCount ? "attention" : ""}`.trim(), queueCount ? `${queueCount} queued` : "queue clear"),
@@ -7528,6 +7809,7 @@ function renderWorkspaceDashboard() {
7528
7809
  actions.append(
7529
7810
  dashboardAction("Command palette", () => openCommandPalette(), "primary"),
7530
7811
  dashboardAction("New tab", () => createTerminalTab()),
7812
+ dashboardAction("Branch worktree", () => openBranchWorktreePicker(), "worktree"),
7531
7813
  dashboardAction("Resume", () => runNativeCommandMenu("/resume")),
7532
7814
  dashboardAction("Model", () => runNativeCommandMenu("/model")),
7533
7815
  dashboardAction("Settings", () => runNativeCommandMenu("/settings")),
@@ -7622,19 +7904,50 @@ function setFooterThinkingPickerOpen(open) {
7622
7904
  }
7623
7905
 
7624
7906
  function normalizeFooterGitBranches(data = {}) {
7625
- const current = cleanStatusText(data.current || "");
7907
+ const current = cleanStatusText(data.current || data.currentBranch || "");
7626
7908
  const seen = new Set();
7627
7909
  const branches = [];
7628
7910
  for (const item of Array.isArray(data.branches) ? data.branches : []) {
7629
7911
  const name = cleanStatusText(typeof item === "string" ? item : item?.name);
7630
7912
  if (!name || seen.has(name)) continue;
7631
7913
  seen.add(name);
7632
- branches.push({ name, current: Boolean(item?.current) || (!!current && name === current) });
7914
+ branches.push({
7915
+ name,
7916
+ current: Boolean(item?.current) || (!!current && name === current),
7917
+ occupied: Boolean(item?.occupied),
7918
+ worktreePath: cleanFooterPayloadText(item?.worktreePath, "", 4000),
7919
+ worktreeCurrent: Boolean(item?.worktreeCurrent),
7920
+ mainWorktree: Boolean(item?.mainWorktree),
7921
+ });
7633
7922
  }
7923
+ const worktrees = (Array.isArray(data.worktrees) ? data.worktrees : [])
7924
+ .map((item) => ({
7925
+ path: cleanFooterPayloadText(item?.path, "", 4000),
7926
+ branch: cleanStatusText(item?.branch || ""),
7927
+ current: Boolean(item?.current),
7928
+ isMainWorktree: Boolean(item?.isMainWorktree),
7929
+ prunable: Boolean(item?.prunable),
7930
+ locked: Boolean(item?.locked),
7931
+ }))
7932
+ .filter((item) => item.path);
7933
+ const occupiedBranches = (Array.isArray(data.occupiedBranches) ? data.occupiedBranches : [])
7934
+ .map((item) => ({
7935
+ branch: cleanStatusText(item?.branch || ""),
7936
+ path: cleanFooterPayloadText(item?.path, "", 4000),
7937
+ current: Boolean(item?.current),
7938
+ isMainWorktree: Boolean(item?.isMainWorktree),
7939
+ }))
7940
+ .filter((item) => item.branch && item.path);
7634
7941
  return {
7635
- root: cleanFooterPayloadText(data.root, "", 4000),
7942
+ root: cleanFooterPayloadText(data.root || data.currentWorktreePath, "", 4000),
7943
+ repoRoot: cleanFooterPayloadText(data.repoRoot || data.root, "", 4000),
7944
+ commonGitDir: cleanFooterPayloadText(data.commonGitDir, "", 4000),
7945
+ currentWorktreePath: cleanFooterPayloadText(data.currentWorktreePath || data.root, "", 4000),
7946
+ defaultWorktreesRoot: cleanFooterPayloadText(data.defaultWorktreesRoot, "", 4000),
7636
7947
  current,
7637
7948
  branches,
7949
+ worktrees,
7950
+ occupiedBranches,
7638
7951
  };
7639
7952
  }
7640
7953
 
@@ -7659,12 +7972,19 @@ function applyOptimisticGitFooterBranch(branch, tabContext = activeTabContext())
7659
7972
  async function loadFooterBranchPicker(tabContext = activeTabContext()) {
7660
7973
  const requestSerial = ++footerBranchPickerRequestSerial;
7661
7974
  const tabId = tabContext.tabId || activeTabId;
7975
+ const preserveState = footerBranchPickerState.tabId === tabId ? footerBranchPickerState : {};
7662
7976
  footerBranchPickerState = {
7663
7977
  loading: true,
7664
7978
  error: "",
7665
- branches: footerBranchPickerState.tabId === tabId ? footerBranchPickerState.branches : [],
7666
- current: footerBranchPickerState.tabId === tabId ? footerBranchPickerState.current : "",
7667
- root: footerBranchPickerState.tabId === tabId ? footerBranchPickerState.root : "",
7979
+ branches: preserveState.branches || [],
7980
+ current: preserveState.current || "",
7981
+ root: preserveState.root || "",
7982
+ repoRoot: preserveState.repoRoot || "",
7983
+ commonGitDir: preserveState.commonGitDir || "",
7984
+ currentWorktreePath: preserveState.currentWorktreePath || "",
7985
+ defaultWorktreesRoot: preserveState.defaultWorktreesRoot || "",
7986
+ worktrees: preserveState.worktrees || [],
7987
+ occupiedBranches: preserveState.occupiedBranches || [],
7668
7988
  switching: "",
7669
7989
  tabId,
7670
7990
  };
@@ -7757,6 +8077,24 @@ function confirmFooterGitBranchAction(branch, { create = false, requireConfirm =
7757
8077
  return window.confirm(message);
7758
8078
  }
7759
8079
 
8080
+ function confirmFooterGitWorktreeAction(branch, { path = "", create = false, requireConfirm = false } = {}) {
8081
+ const branchName = cleanStatusText(branch);
8082
+ if (!requireConfirm) return true;
8083
+ const targetPath = cleanFooterPayloadText(path, "", 4000);
8084
+ const message = [
8085
+ `${create ? "Create" : "Open"} branch worktree: ${branchName || targetPath}?`,
8086
+ "",
8087
+ `Repository: ${footerBranchPickerState.repoRoot || footerBranchPickerState.root || currentGitFooterCacheCwd() || "current tab"}`,
8088
+ targetPath ? `Worktree: ${targetPath}` : `Default location: ${footerBranchPickerState.defaultWorktreesRoot || "repo sibling .worktrees directory"}`,
8089
+ "",
8090
+ "This opens a separate checkout in a separate Pi tab and does not switch this tab's branch.",
8091
+ "Ignored dependencies such as node_modules or .venv are not copied; bootstrap them manually if needed.",
8092
+ "",
8093
+ "Continue?",
8094
+ ].join("\n");
8095
+ return window.confirm(message);
8096
+ }
8097
+
7760
8098
  function footerBranchCreateType(value = footerBranchCreateDraft.type) {
7761
8099
  return slugifyGitBranchPart(value);
7762
8100
  }
@@ -7799,20 +8137,42 @@ function gitSwitchCreateCommandDisplay(branch) {
7799
8137
  return `git switch -c ${quoteGitBranchForDisplay(branch)}`;
7800
8138
  }
7801
8139
 
7802
- function footerBranchCreateTooltip(branchName = footerBranchCreateName()) {
7803
- const command = gitSwitchCreateCommandDisplay(branchName || footerBranchCreatePreviewName());
8140
+ function slugifyWorktreePathPart(value) {
8141
+ return String(value || "")
8142
+ .toLowerCase()
8143
+ .replace(/[^a-z0-9._-]+/g, "-")
8144
+ .replace(/[-.]{2,}/g, "-")
8145
+ .replace(/^-+|-+$/g, "")
8146
+ .slice(0, 96) || "branch";
8147
+ }
8148
+
8149
+ function footerBranchCreateWorktreePathPreview(branch = footerBranchCreateName(), state = footerBranchPickerState) {
8150
+ const root = state.defaultWorktreesRoot || "<repo>.worktrees";
8151
+ return `${root.replace(/\/+$/, "")}/${slugifyWorktreePathPart(branch || footerBranchCreatePreviewName())}`;
8152
+ }
8153
+
8154
+ function gitWorktreeCreateCommandDisplay(branch, state = footerBranchPickerState) {
8155
+ return `git worktree add -b ${quoteGitBranchForDisplay(branch)} ${quoteGitBranchForDisplay(footerBranchCreateWorktreePathPreview(branch, state))}`;
8156
+ }
8157
+
8158
+ function gitWorktreeOpenCommandDisplay(path) {
8159
+ return `pi-webui --cwd ${quoteGitBranchForDisplay(path || "<worktree-path>")}`;
8160
+ }
8161
+
8162
+ function footerBranchCreateTooltip(branchName = footerBranchCreateName(), state = footerBranchPickerState) {
8163
+ const command = gitWorktreeCreateCommandDisplay(branchName || footerBranchCreatePreviewName(), state);
7804
8164
  return [
7805
- "Create new branch",
7806
- "A branch is a safe workspace for your changes.",
8165
+ "Create branch worktree",
8166
+ "A branch worktree is a separate checkout for parallel changes.",
7807
8167
  "",
7808
- `This will run: ${command}`,
8168
+ `This will run roughly: ${command}`,
7809
8169
  "",
7810
8170
  "What happens:",
7811
- "• creates the branch from the current code",
7812
- "• switches this tab to that branch",
7813
- "• does not commit, push, or delete anything",
8171
+ "• creates the branch from the current HEAD when it does not exist",
8172
+ "• opens a separate Pi tab rooted at that worktree",
8173
+ "• does not switch this tab's branch, commit, push, or delete anything",
7814
8174
  "",
7815
- "Tip: use short lowercase words, e.g. fix/login-button.",
8175
+ "Tip: ignored dependencies such as node_modules or .venv are not copied.",
7816
8176
  ].join("\n");
7817
8177
  }
7818
8178
 
@@ -7827,6 +8187,72 @@ async function createFooterGitBranch(branch = footerBranchCreateName()) {
7827
8187
  await applyFooterGitBranch(branchName, { create: true, tabContext, skipConfirm: true });
7828
8188
  }
7829
8189
 
8190
+ async function openWorktreeResponseTab(response, { branchName = "", action = "open" } = {}) {
8191
+ if (!response.ok) throw new Error(response.error || `Failed to ${action} branch worktree`);
8192
+ const payload = response.data || {};
8193
+ if (Array.isArray(payload.tabs)) {
8194
+ tabs = payload.tabs;
8195
+ syncTabMetadata(tabs);
8196
+ }
8197
+ if (payload.tab) applyTabMetadata(payload.tab);
8198
+ footerBranchPickerOpen = false;
8199
+ footerBranchPickerRequestSerial += 1;
8200
+ footerBranchPickerState = { ...footerBranchPickerState, loading: false, switching: "" };
8201
+ renderTabs();
8202
+ const targetTab = payload.tab;
8203
+ if (targetTab?.id) await switchTab(targetTab.id);
8204
+ const branch = cleanStatusText(payload.worktree?.branch || payload.branch || branchName || targetTab?.gitWorkspace?.branch || "");
8205
+ const where = payload.worktree?.path || payload.path || targetTab?.cwd || "worktree";
8206
+ const prefix = payload.created ? "Created" : payload.openedExisting || payload.openedExistingTab ? "Opened existing" : "Opened";
8207
+ addEvent(`${prefix} branch worktree${branch ? ` ${branch}` : ""} at ${normalizeDisplayPath(where)}.`, "success");
8208
+ if (payload.session?.warning) addEvent(payload.session.warning, "warn");
8209
+ if (payload.dependencyHint) addEvent(payload.dependencyHint, "info");
8210
+ requestGitFooterWebuiPayload(activeTabContext(), { force: true });
8211
+ }
8212
+
8213
+ async function createFooterGitBranchWorktree(branch = footerBranchCreateName(), { tabContext = activeTabContext(), skipConfirm = false } = {}) {
8214
+ const branchName = cleanStatusText(branch);
8215
+ if (!branchName) {
8216
+ addEvent("Enter a branch name before creating a branch worktree.", "warn");
8217
+ return;
8218
+ }
8219
+ if (!skipConfirm && !confirmFooterGitWorktreeAction(branchName, { create: true, requireConfirm: true })) return;
8220
+ const tabId = tabContext.tabId || activeTabId;
8221
+ try {
8222
+ footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "", switching: branchName, tabId };
8223
+ renderFooter();
8224
+ const response = await api("/api/git-worktrees", { method: "POST", body: { branchName, sessionMode: "fork-current", openTab: true }, tabId });
8225
+ await openWorktreeResponseTab(response, { branchName, action: "create" });
8226
+ } catch (error) {
8227
+ if (isCurrentTabContext(tabContext)) {
8228
+ footerBranchPickerState = { ...footerBranchPickerState, loading: false, switching: "", error: error.message || String(error) };
8229
+ renderFooter();
8230
+ updateFooterModelPickerPosition();
8231
+ }
8232
+ addEvent(error.message || String(error), "error");
8233
+ }
8234
+ }
8235
+
8236
+ async function openFooterGitWorktree(path, { branchName = "", tabContext = activeTabContext(), skipConfirm = false } = {}) {
8237
+ const worktreePath = cleanFooterPayloadText(path, "", 4000);
8238
+ if (!worktreePath) return;
8239
+ if (!skipConfirm && !confirmFooterGitWorktreeAction(branchName, { path: worktreePath, requireConfirm: false })) return;
8240
+ const tabId = tabContext.tabId || activeTabId;
8241
+ try {
8242
+ footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "", switching: branchName || worktreePath, tabId };
8243
+ renderFooter();
8244
+ const response = await api("/api/git-worktrees/open", { method: "POST", body: { path: worktreePath, sessionMode: "fork-current", openTab: true }, tabId });
8245
+ await openWorktreeResponseTab(response, { branchName, action: "open" });
8246
+ } catch (error) {
8247
+ if (isCurrentTabContext(tabContext)) {
8248
+ footerBranchPickerState = { ...footerBranchPickerState, loading: false, switching: "", error: error.message || String(error) };
8249
+ renderFooter();
8250
+ updateFooterModelPickerPosition();
8251
+ }
8252
+ addEvent(error.message || String(error), "error");
8253
+ }
8254
+ }
8255
+
7830
8256
  async function applyFooterGitBranch(branch, { create = false, tabContext = activeTabContext(), skipConfirm = false } = {}) {
7831
8257
  const branchName = cleanStatusText(branch);
7832
8258
  if (!branchName) return;
@@ -7862,10 +8288,10 @@ async function applyFooterGitBranch(branch, { create = false, tabContext = activ
7862
8288
 
7863
8289
  function renderFooterBranchCreateForm(state = footerBranchPickerState) {
7864
8290
  const form = make("form", "footer-branch-create-form");
7865
- form.setAttribute("aria-label", "Create new git branch");
8291
+ form.setAttribute("aria-label", "Create branch worktree");
7866
8292
 
7867
8293
  const header = make("div", "footer-branch-create-header");
7868
- header.append(make("strong", "footer-branch-create-title", "Create new branch"));
8294
+ header.append(make("strong", "footer-branch-create-title", "Create branch worktree"));
7869
8295
 
7870
8296
  const fields = make("div", "footer-branch-create-fields");
7871
8297
  const typeField = make("div", "footer-branch-create-type-field");
@@ -7914,19 +8340,19 @@ function renderFooterBranchCreateForm(state = footerBranchPickerState) {
7914
8340
  nameInput.spellcheck = false;
7915
8341
  nameInput.setAttribute("aria-label", "New branch name");
7916
8342
 
7917
- const submitButton = make("button", "footer-branch-create-submit", state.switching ? "Creating…" : "Create new branch");
8343
+ const submitButton = make("button", "footer-branch-create-submit", state.switching ? "Opening…" : "Open worktree tab");
7918
8344
  submitButton.type = "submit";
7919
8345
 
7920
8346
  const preview = make("div", "footer-branch-create-preview");
7921
8347
  const updatePreview = () => {
7922
8348
  const branchName = footerBranchCreateName();
7923
- preview.textContent = gitSwitchCreateCommandDisplay(branchName || footerBranchCreatePreviewName());
8349
+ preview.textContent = gitWorktreeCreateCommandDisplay(branchName || footerBranchCreatePreviewName(), state);
7924
8350
  const submitDisabled = Boolean(state.switching) || !branchName;
7925
8351
  submitButton.disabled = false;
7926
8352
  submitButton.classList.toggle("footer-branch-create-submit-disabled", submitDisabled);
7927
8353
  submitButton.setAttribute("aria-disabled", submitDisabled ? "true" : "false");
7928
8354
  submitButton.dataset.tooltip = footerBranchCreateTooltip(branchName);
7929
- submitButton.setAttribute("aria-label", branchName ? `Create and switch to ${branchName}` : "Create new branch: enter both a branch type and name first");
8355
+ submitButton.setAttribute("aria-label", branchName ? `Create and open branch worktree ${branchName}` : "Create branch worktree: enter both a branch type and name first");
7930
8356
  submitButton.removeAttribute("title");
7931
8357
  };
7932
8358
 
@@ -7967,7 +8393,7 @@ function renderFooterBranchCreateForm(state = footerBranchPickerState) {
7967
8393
  event.preventDefault();
7968
8394
  if (state.switching) return;
7969
8395
  const branchName = footerBranchCreateName();
7970
- createFooterGitBranch(branchName).catch((error) => addEvent(error.message || String(error), "error"));
8396
+ createFooterGitBranchWorktree(branchName).catch((error) => addEvent(error.message || String(error), "error"));
7971
8397
  });
7972
8398
 
7973
8399
  updatePreview();
@@ -7978,14 +8404,94 @@ function renderFooterBranchCreateForm(state = footerBranchPickerState) {
7978
8404
  return form;
7979
8405
  }
7980
8406
 
8407
+ function footerBranchWorktreePath(branch, state = footerBranchPickerState) {
8408
+ const direct = cleanFooterPayloadText(branch?.worktreePath, "", 4000);
8409
+ if (direct) return direct;
8410
+ return cleanFooterPayloadText(state.occupiedBranches?.find((item) => item.branch === branch?.name)?.path, "", 4000);
8411
+ }
8412
+
8413
+ function footerBranchOptionDetail(branch, state, { selected, worktreePath } = {}) {
8414
+ if (state.switching === branch.name) return "opening…";
8415
+ if (selected) return branch.worktreeCurrent ? "current branch in this worktree" : "current branch";
8416
+ if (worktreePath) return branch.mainWorktree ? "checked out in main worktree · open tab" : "checked out in another worktree · open tab";
8417
+ return "open branch in a new worktree tab";
8418
+ }
8419
+
8420
+ function openFooterBranchOption(branch, state = footerBranchPickerState) {
8421
+ const worktreePath = footerBranchWorktreePath(branch, state);
8422
+ if (worktreePath && !branch.worktreeCurrent) return openFooterGitWorktree(worktreePath, { branchName: branch.name, skipConfirm: true });
8423
+ return createFooterGitBranchWorktree(branch.name, { skipConfirm: true });
8424
+ }
8425
+
8426
+ function renderFooterBranchOption(branch, state = footerBranchPickerState) {
8427
+ const selected = branch.current || (!!state.current && branch.name === state.current);
8428
+ const worktreePath = footerBranchWorktreePath(branch, state);
8429
+ const busy = state.loading || !!state.switching;
8430
+ const primaryDisabled = busy || selected;
8431
+ const row = make("div", `footer-branch-option-row${selected ? " active" : ""}${worktreePath && !branch.worktreeCurrent ? " worktree-occupied" : ""}`);
8432
+ row.setAttribute("role", "option");
8433
+ row.setAttribute("aria-selected", selected ? "true" : "false");
8434
+
8435
+ const primary = make("button", "footer-model-option footer-branch-option footer-branch-primary-action");
8436
+ primary.type = "button";
8437
+ primary.disabled = primaryDisabled;
8438
+ primary.title = selected ? `Current branch: ${branch.name}` : worktreePath ? `Open existing worktree: ${worktreePath}` : `Open ${branch.name} in a new Git worktree tab`;
8439
+ primary.append(
8440
+ make("span", "footer-model-option-main", branch.name),
8441
+ make("span", "footer-model-option-name", footerBranchOptionDetail(branch, state, { selected, worktreePath })),
8442
+ );
8443
+ if (!primaryDisabled) primary.addEventListener("click", () => openFooterBranchOption(branch, state));
8444
+ row.append(primary);
8445
+
8446
+ if (!selected) {
8447
+ const advanced = make("button", "footer-branch-advanced-action", "Switch here");
8448
+ advanced.type = "button";
8449
+ advanced.disabled = busy || !!worktreePath;
8450
+ advanced.title = worktreePath
8451
+ ? "This branch is already checked out elsewhere; use the primary worktree action instead of switching this checkout."
8452
+ : `Advanced: git switch ${branch.name} in this checkout`;
8453
+ advanced.addEventListener("click", () => applyFooterGitBranch(branch.name));
8454
+ row.append(advanced);
8455
+ }
8456
+ return row;
8457
+ }
8458
+
8459
+ function renderFooterWorktreeList(state = footerBranchPickerState) {
8460
+ const worktrees = (state.worktrees || []).filter((item) => item.path && !item.prunable);
8461
+ if (worktrees.length <= 1) return null;
8462
+ const section = make("div", "footer-branch-worktree-section");
8463
+ section.append(make("div", "footer-branch-section-title", `Open worktrees (${worktrees.length})`));
8464
+ for (const worktree of worktrees.slice(0, 8)) {
8465
+ const selected = worktree.current || worktree.path === state.currentWorktreePath;
8466
+ const button = make("button", `footer-model-option footer-worktree-option${selected ? " active" : ""}`);
8467
+ button.type = "button";
8468
+ button.disabled = selected || state.loading || !!state.switching;
8469
+ button.title = selected ? `Current worktree: ${worktree.path}` : `Open worktree: ${worktree.path}`;
8470
+ button.append(
8471
+ make("span", "footer-model-option-main", worktree.branch || "detached"),
8472
+ make("span", "footer-model-option-name", `${selected ? "current" : "open"} · ${normalizeDisplayPath(worktree.path)}`),
8473
+ );
8474
+ if (!button.disabled) button.addEventListener("click", () => openFooterGitWorktree(worktree.path, { branchName: worktree.branch || "", skipConfirm: true }));
8475
+ section.append(button);
8476
+ }
8477
+ return section;
8478
+ }
8479
+
8480
+ function openBranchWorktreePicker() {
8481
+ setNewTabMenuOpen(false);
8482
+ setMobileTabsExpanded(false);
8483
+ setComposerActionsOpen(false);
8484
+ setFooterBranchPickerOpen(true);
8485
+ }
8486
+
7981
8487
  function renderFooterBranchPicker() {
7982
8488
  const picker = make("div", "footer-model-picker footer-branch-picker");
7983
8489
  picker.setAttribute("role", "listbox");
7984
- picker.setAttribute("aria-label", "Git branches");
8490
+ picker.setAttribute("aria-label", "Git branches and worktrees");
7985
8491
  const state = footerBranchPickerState;
7986
8492
  const current = state.current || "detached";
7987
- picker.append(make("div", "footer-model-picker-title", "Git branches"));
7988
- picker.append(make("div", "footer-model-picker-source", `${state.loading ? "Refreshing" : "Current"}: ${state.switching || current}${state.root ? ` · ${state.root}` : ""}`));
8493
+ picker.append(make("div", "footer-model-picker-title", "Git branches & worktrees"));
8494
+ picker.append(make("div", "footer-model-picker-source", `${state.loading ? "Refreshing" : "Current"}: ${state.switching || current}${state.currentWorktreePath ? ` · ${normalizeDisplayPath(state.currentWorktreePath)}` : state.root ? ` · ${state.root}` : ""}`));
7989
8495
 
7990
8496
  if (state.error) {
7991
8497
  const error = make("div", "footer-model-picker-empty error");
@@ -7994,35 +8500,23 @@ function renderFooterBranchPicker() {
7994
8500
  return picker;
7995
8501
  }
7996
8502
  if (state.loading && state.branches.length === 0) {
7997
- picker.append(make("div", "footer-model-picker-empty muted", "Loading existing local branches… New branch creation is available."), renderFooterBranchCreateForm(state));
8503
+ picker.append(make("div", "footer-model-picker-empty muted", "Loading existing local branches and worktrees… Worktree creation is available once branch data loads."), renderFooterBranchCreateForm(state));
7998
8504
  return picker;
7999
8505
  }
8000
8506
 
8001
8507
  const hasOtherBranches = state.branches.some((branch) => !branch.current && branch.name !== state.current);
8002
8508
  if (!state.loading && !hasOtherBranches) {
8003
8509
  const empty = make("div", "footer-model-picker-empty muted");
8004
- empty.append(make("strong", undefined, "No other local branches available."), make("span", undefined, " Create a branch from the current HEAD to continue."));
8510
+ empty.append(make("strong", undefined, "No other local branches available."), make("span", undefined, " Create a branch worktree from the current HEAD to continue."));
8005
8511
  picker.append(empty);
8006
8512
  }
8007
8513
 
8008
8514
  picker.append(renderFooterBranchCreateForm(state));
8515
+ const worktreeSection = renderFooterWorktreeList(state);
8516
+ if (worktreeSection) picker.append(worktreeSection);
8517
+ picker.append(make("div", "footer-branch-section-title", "Branches"));
8009
8518
 
8010
- for (const branch of state.branches) {
8011
- const selected = branch.current || (!!state.current && branch.name === state.current);
8012
- const disabled = selected || state.loading || !!state.switching;
8013
- const button = make("button", `footer-model-option footer-branch-option${selected ? " active" : ""}`);
8014
- button.type = "button";
8015
- button.disabled = disabled;
8016
- button.setAttribute("role", "option");
8017
- button.setAttribute("aria-selected", selected ? "true" : "false");
8018
- button.title = selected ? `Current branch: ${branch.name}` : `git switch ${branch.name}`;
8019
- button.append(
8020
- make("span", "footer-model-option-main", branch.name),
8021
- make("span", "footer-model-option-name", selected ? "current branch" : state.switching === branch.name ? "switching…" : "switch to this branch"),
8022
- );
8023
- if (!disabled) button.addEventListener("click", () => applyFooterGitBranch(branch.name));
8024
- picker.append(button);
8025
- }
8519
+ for (const branch of state.branches) picker.append(renderFooterBranchOption(branch, state));
8026
8520
  return picker;
8027
8521
  }
8028
8522
 
@@ -9040,13 +9534,27 @@ function renderReleaseDialogMessage(parent, text) {
9040
9534
  }
9041
9535
  }
9042
9536
 
9537
+ function textLines(raw) {
9538
+ const value = String(raw || "");
9539
+ const lines = [];
9540
+ let start = 0;
9541
+ for (let index = 0; index < value.length; index += 1) {
9542
+ if (value[index] !== "\n") continue;
9543
+ const end = index > start && value[index - 1] === "\r" ? index - 1 : index;
9544
+ lines.push(value.slice(start, end));
9545
+ start = index + 1;
9546
+ }
9547
+ if (start <= value.length) lines.push(value.slice(start));
9548
+ return lines;
9549
+ }
9550
+
9043
9551
  function stripTodoProgressLines(text, { streaming = false } = {}) {
9044
9552
  if (!isOptionalFeatureEnabled("todoProgressWidget")) return String(text || "");
9045
9553
  let inFence = false;
9046
9554
  const kept = [];
9047
9555
  const raw = String(text || "");
9048
9556
  const hasTrailingNewline = /\r?\n$/.test(raw);
9049
- const lines = raw.split(/\r?\n/);
9557
+ const lines = textLines(raw);
9050
9558
 
9051
9559
  lines.forEach((line, index) => {
9052
9560
  const isUnfinishedTail = streaming && !hasTrailingNewline && index === lines.length - 1;
@@ -9076,7 +9584,7 @@ function todoProgressStatusLabel(status) {
9076
9584
  return "[ ]";
9077
9585
  }
9078
9586
 
9079
- function liveTodoProgressWidgetLinesFromText(text) {
9587
+ function liveTodoProgressWidgetLinesFromText(text, tabId = activeTabId) {
9080
9588
  if (!isOptionalFeatureEnabled("todoProgressWidget")) return null;
9081
9589
  const raw = String(text || "");
9082
9590
  if (!raw.trim()) return null;
@@ -9090,7 +9598,7 @@ function liveTodoProgressWidgetLinesFromText(text) {
9090
9598
  current = [];
9091
9599
  };
9092
9600
 
9093
- for (const line of raw.split(/\r?\n/)) {
9601
+ for (const line of textLines(raw)) {
9094
9602
  if (/^\s*```/.test(line)) {
9095
9603
  inFence = !inFence;
9096
9604
  flush();
@@ -9114,22 +9622,61 @@ function liveTodoProgressWidgetLinesFromText(text) {
9114
9622
  const items = blocks.at(-1) || [];
9115
9623
  if (!items.length) return null;
9116
9624
 
9625
+ if (goal && tabId) todoProgressGoalByTab.set(tabId, goal);
9626
+ const displayGoal = goal || (tabId ? todoProgressGoalByTab.get(tabId) : "") || "";
9117
9627
  const done = items.filter((item) => item.status === "done").length;
9118
9628
  const partial = items.filter((item) => item.status === "partial").length;
9119
9629
  const lines = [];
9120
- if (goal) lines.push(`Goal: ${goal}`);
9630
+ if (displayGoal) lines.push(`Goal: ${displayGoal}`);
9121
9631
  lines.push(`Todo ${done}/${items.length} done${partial ? `, ${partial} partial` : ""}`);
9122
9632
  for (const item of items) lines.push(`${todoProgressStatusLabel(item.status)} ${item.text}`);
9123
9633
  return lines;
9124
9634
  }
9125
9635
 
9636
+ // Coalesce live widget rebuilds to one per animation frame. The streaming
9637
+ // output handler calls into here on every text token, but the widget area
9638
+ // must not be torn down/rebuilt per token (that is UI reacting to the agent
9639
+ // output stream). One render per frame keeps streaming transcript-local.
9640
+ function scheduleLiveWidgetRender() {
9641
+ if (liveWidgetRenderFrame !== null) return;
9642
+ const flush = () => {
9643
+ liveWidgetRenderFrame = null;
9644
+ renderWidgets();
9645
+ };
9646
+ if (typeof requestAnimationFrame === "function") liveWidgetRenderFrame = requestAnimationFrame(flush);
9647
+ else liveWidgetRenderFrame = setTimeout(flush, 0);
9648
+ }
9649
+
9650
+ function scheduleLiveTodoProgressWidgetSync(text, tabId = activeTabId) {
9651
+ liveTodoProgressPendingText = String(text || "");
9652
+ liveTodoProgressPendingTabId = tabId || activeTabId;
9653
+ if (liveTodoProgressSyncFrame !== null) return;
9654
+ const flush = () => {
9655
+ const pendingText = liveTodoProgressPendingText;
9656
+ const pendingTabId = liveTodoProgressPendingTabId || activeTabId;
9657
+ liveTodoProgressSyncFrame = null;
9658
+ liveTodoProgressPendingText = "";
9659
+ liveTodoProgressPendingTabId = null;
9660
+ syncLiveTodoProgressWidgetFromText(pendingText, pendingTabId);
9661
+ };
9662
+ if (typeof requestAnimationFrame === "function") liveTodoProgressSyncFrame = requestAnimationFrame(flush);
9663
+ else liveTodoProgressSyncFrame = setTimeout(flush, 0);
9664
+ }
9665
+
9126
9666
  function syncLiveTodoProgressWidgetFromText(text, tabId = activeTabId) {
9127
- const lines = liveTodoProgressWidgetLinesFromText(text);
9667
+ const lines = liveTodoProgressWidgetLinesFromText(text, tabId);
9128
9668
  if (!lines) return false;
9129
- setWidgetForTab(tabId, "todo-progress", { method: "setWidget", widgetKey: "todo-progress", widgetLines: lines, tabId, live: true });
9130
- updateOptionalFeatureAvailability();
9131
- if (tabId === activeTabId) renderWidgets();
9132
- return true;
9669
+ const signature = todoProgressSignatureFromLines(lines);
9670
+ if (tabId && todoProgressSignatureByTab.get(tabId) === signature) return false;
9671
+ // liveTodoProgressWidgetLinesFromText already short-circuits unless the
9672
+ // feature is enabled, so detection is settled here. Do NOT run
9673
+ // updateOptionalFeatureAvailability() per token: it triggers git-footer
9674
+ // payload reconciliation and a full optional-feature control rebuild.
9675
+ // Availability is reconciled on command/state refreshes and RPC widget
9676
+ // updates instead, keeping streaming output decoupled from chrome UI.
9677
+ const changed = setWidgetForTab(tabId, "todo-progress", { method: "setWidget", widgetKey: "todo-progress", widgetLines: lines, tabId, live: true });
9678
+ if (changed && tabId === activeTabId) scheduleLiveWidgetRender();
9679
+ return changed;
9133
9680
  }
9134
9681
 
9135
9682
  function parseTodoProgressWidget(lines) {
@@ -9524,12 +10071,18 @@ function activeAppRunnerData() {
9524
10071
  function setAppRunnerData(tabId, data = {}) {
9525
10072
  if (!tabId) return;
9526
10073
  const previous = appRunnerDataByTab.get(tabId) || { runners: [], activeRun: null, customRunnerConfig: null };
9527
- appRunnerDataByTab.set(tabId, {
10074
+ const hasActiveRun = Object.prototype.hasOwnProperty.call(data, "activeRun");
10075
+ const next = {
9528
10076
  cwd: data.cwd || previous.cwd || "",
9529
10077
  runners: Array.isArray(data.runners) ? data.runners : previous.runners || [],
9530
10078
  customRunnerConfig: data.customRunnerConfig || previous.customRunnerConfig || null,
9531
- activeRun: Object.prototype.hasOwnProperty.call(data, "activeRun") ? data.activeRun : previous.activeRun || null,
9532
- });
10079
+ activeRun: hasActiveRun ? data.activeRun : previous.activeRun || null,
10080
+ };
10081
+ appRunnerDataByTab.set(tabId, next);
10082
+ if (hasActiveRun) {
10083
+ const tab = tabs.find((item) => item.id === tabId);
10084
+ if (tab) tab.appRunner = next.activeRun || null;
10085
+ }
9533
10086
  }
9534
10087
 
9535
10088
  function appRunnerIsRunning(run) {
@@ -9602,6 +10155,7 @@ async function runAppRunner(runnerId) {
9602
10155
  setAppRunnerData(tabContext.tabId, response.data || {});
9603
10156
  renderAppRunnerControls();
9604
10157
  renderWidgets();
10158
+ renderTabs();
9605
10159
  const command = response.data?.activeRun?.displayCommand || "app runner";
9606
10160
  addEvent(`started ${command}`, "info");
9607
10161
  } catch (error) {
@@ -9610,6 +10164,7 @@ async function runAppRunner(runnerId) {
9610
10164
  setAppRunnerData(tabContext.tabId, { activeRun: appRunnerFailureState(runnerId, error, activeAppRunnerData()) });
9611
10165
  renderAppRunnerControls();
9612
10166
  renderWidgets();
10167
+ renderTabs();
9613
10168
  addEvent(`app runner failed: ${message}`, "error");
9614
10169
  }
9615
10170
  }
@@ -9623,6 +10178,7 @@ async function stopAppRunner() {
9623
10178
  setAppRunnerData(tabContext.tabId, response.data || {});
9624
10179
  renderAppRunnerControls();
9625
10180
  renderWidgets();
10181
+ renderTabs();
9626
10182
  addEvent("app runner stop requested", "warn");
9627
10183
  } catch (error) {
9628
10184
  if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
@@ -9638,6 +10194,7 @@ async function clearAppRunner() {
9638
10194
  setAppRunnerData(tabContext.tabId, response.data || {});
9639
10195
  renderAppRunnerControls();
9640
10196
  renderWidgets();
10197
+ renderTabs();
9641
10198
  } catch (error) {
9642
10199
  if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
9643
10200
  }
@@ -9681,6 +10238,73 @@ function appRunnerInputDraftKey(run) {
9681
10238
  return run?.id || run?.runnerId || "active";
9682
10239
  }
9683
10240
 
10241
+ function normalizeAppRunnerContextLineCount(value) {
10242
+ const number = Number.parseInt(String(value ?? ""), 10);
10243
+ if (!Number.isFinite(number)) return APP_RUNNER_CONTEXT_DEFAULT_LINES;
10244
+ return Math.max(1, Math.min(APP_RUNNER_CONTEXT_MAX_LINES, number));
10245
+ }
10246
+
10247
+ function appRunnerContextDraftKey(run) {
10248
+ return appRunnerInputDraftKey(run);
10249
+ }
10250
+
10251
+ async function transferAppRunnerOutputToContext(run, form) {
10252
+ const tabContext = activeTabContext();
10253
+ if (!tabContext.tabId || !run) return;
10254
+ const key = appRunnerContextDraftKey(run);
10255
+ const input = form?.querySelector?.(".app-runner-context-lines-input");
10256
+ const lineCount = normalizeAppRunnerContextLineCount(input?.value || appRunnerContextLineDraftByRun.get(key) || APP_RUNNER_CONTEXT_DEFAULT_LINES);
10257
+ if (input) input.value = String(lineCount);
10258
+ appRunnerContextLineDraftByRun.set(key, String(lineCount));
10259
+ const buttons = [...(form?.querySelectorAll?.("button") || [])];
10260
+ buttons.forEach((button) => { button.disabled = true; });
10261
+ try {
10262
+ const response = await api("/api/app-runner/context", { method: "POST", body: { lineCount }, tabId: tabContext.tabId });
10263
+ if (!isCurrentTabContext(tabContext)) return;
10264
+ const data = response.data || {};
10265
+ if (data.activeRun) setAppRunnerData(tabContext.tabId, { activeRun: data.activeRun });
10266
+ const deliveredAsSteer = data.delivery === "steer";
10267
+ addEvent(deliveredAsSteer
10268
+ ? `sent last ${data.lineCount || lineCount} app runner output lines as live steering context`
10269
+ : `added last ${data.lineCount || lineCount} app runner output lines to agent context`, "info");
10270
+ scheduleRefreshMessages(120, tabContext);
10271
+ scheduleRefreshState(120, tabContext);
10272
+ } catch (error) {
10273
+ if (isCurrentTabContext(tabContext)) addEvent(`app runner context transfer failed: ${error.message || String(error)}`, "error");
10274
+ } finally {
10275
+ buttons.forEach((button) => { button.disabled = false; });
10276
+ }
10277
+ }
10278
+
10279
+ function renderAppRunnerContextForm(run) {
10280
+ const key = appRunnerContextDraftKey(run);
10281
+ const form = make("form", "app-runner-context-form");
10282
+ form.dataset.runId = key;
10283
+ const label = make("label", "app-runner-context-lines-label");
10284
+ label.append(make("span", "", "Context lines"));
10285
+ const input = make("input", "app-runner-context-lines-input");
10286
+ input.type = "number";
10287
+ input.min = "1";
10288
+ input.max = String(APP_RUNNER_CONTEXT_MAX_LINES);
10289
+ input.step = "1";
10290
+ input.inputMode = "numeric";
10291
+ input.value = String(normalizeAppRunnerContextLineCount(appRunnerContextLineDraftByRun.get(key) || APP_RUNNER_CONTEXT_DEFAULT_LINES));
10292
+ input.setAttribute("aria-label", "Number of recent app runner output lines to add to agent context");
10293
+ input.addEventListener("input", () => {
10294
+ appRunnerContextLineDraftByRun.set(key, String(normalizeAppRunnerContextLineCount(input.value)));
10295
+ });
10296
+ label.append(input);
10297
+ const transfer = make("button", "release-npm-action app-runner-context-action", "Add to context");
10298
+ transfer.type = "submit";
10299
+ transfer.title = "Add the selected number of recent app runner output lines to this agent session's context";
10300
+ form.addEventListener("submit", (event) => {
10301
+ event.preventDefault();
10302
+ transferAppRunnerOutputToContext(run, form);
10303
+ });
10304
+ form.append(label, transfer);
10305
+ return form;
10306
+ }
10307
+
9684
10308
  function captureAppRunnerInputFocus() {
9685
10309
  const input = document.activeElement;
9686
10310
  if (!input?.classList?.contains("app-runner-stdin-input")) return null;
@@ -10181,11 +10805,12 @@ function renderAppRunnerWidget() {
10181
10805
  actions.append(appRunnerActionButton("Clear", clearAppRunner));
10182
10806
  }
10183
10807
  const inputForm = running ? renderAppRunnerInputForm(run) : null;
10808
+ const contextForm = renderAppRunnerContextForm(run);
10184
10809
  const pills = make("div", "app-runner-output-pills");
10185
10810
  if (run.kind) pills.append(make("span", "release-npm-pill", run.kind));
10186
10811
  pills.append(make("span", `release-npm-pill app-runner-status ${run.status || "running"}`.trim(), status));
10187
10812
  if (elapsed) pills.append(make("span", "release-npm-pill elapsed", elapsed));
10188
- controls.append(actions);
10813
+ controls.append(actions, contextForm);
10189
10814
  if (inputForm) controls.append(inputForm);
10190
10815
  controls.append(pills, make("span", "app-runner-output-meta", controlParts.join(" · ")));
10191
10816
  const outputDetails = renderReleaseNpmOutputDetails(`app-runner:${run.id || run.runnerId || "active"}`, streamHeader, terminal, controls);
@@ -11792,7 +12417,7 @@ function gitWorkflowTitle() {
11792
12417
  case "generating": return "Waiting for /git-staged-msg";
11793
12418
  case "message": return gitWorkflow.prMode ? "Choose PR branch commit message" : "Choose commit message";
11794
12419
  case "branchNaming": return "Waiting for branch name";
11795
- case "branching": return "Creating PR branch";
12420
+ case "branching": return "Opening PR branch worktree";
11796
12421
  case "committing": return "Committing";
11797
12422
  case "push": return gitWorkflow.prMode ? "Push branch and create PR" : "Push commit";
11798
12423
  case "pushing": return "Pushing";
@@ -11827,11 +12452,11 @@ function gitWorkflowHint() {
11827
12452
  case "add": return "Step 1: run git add . in the current Pi working directory.";
11828
12453
  case "generate": return "Step 2: run /git-staged-msg, or type a commit message and use Commit input.";
11829
12454
  case "generating": return "Pi is generating dev/COMMIT/staged-commit-short.txt and staged-commit-long.txt.";
11830
- case "message": return gitWorkflow.prMode ? `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 first.";
11831
- case "branchNaming": return "Pi is generating dev/COMMIT/staged-branch-name.txt. Cancel will request Pi abort.";
11832
- case "branching": return "Creating a new branch with git switch -c before committing.";
12455
+ 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.";
12456
+ case "branchNaming": return "Pi is generating dev/COMMIT/staged-branch-name.txt for a PR branch worktree. Cancel will request Pi abort.";
12457
+ case "branching": return "Creating or opening a branch worktree, copying staged changes, and switching to that tab before committing.";
11833
12458
  case "committing": return "Running native git commit with the selected message.";
11834
- case "push": return gitWorkflow.prMode ? "Push the PR branch, generate /pr, review the description, then create the pull request." : "Step 5: push the new commit to the configured remote.";
12459
+ case "push": return gitWorkflow.prMode ? "Push the PR worktree branch, generate /pr, review the description, then create the pull request." : "Step 5: push the new commit to the configured remote.";
11835
12460
  case "pushing": return "Running git push. Cancel will request process termination.";
11836
12461
  case "prGenerating": return "Pi is generating dev/PR/<current-branch>.md with /pr.";
11837
12462
  case "prReview": return "Review or edit the generated PR description before creating the pull request.";
@@ -11949,8 +12574,8 @@ function renderGitWorkflow() {
11949
12574
  addGitWorkflowAction("Refresh message preview", () => loadGitWorkflowMessage({ requireFresh: true }), "", false);
11950
12575
  } else if (gitWorkflow.step === "message") {
11951
12576
  if (!gitWorkflow.prMode) {
11952
- addGitWorkflowAction("Create PR", () => createGitPrBranch(), "primary", false, GIT_WORKFLOW_CREATE_PR_TOOLTIP);
11953
- addGitWorkflowAction("Manual branch", () => createGitPrBranchManually(), "", false, GIT_WORKFLOW_MANUAL_BRANCH_TOOLTIP);
12577
+ addGitWorkflowAction("Create PR worktree", () => createGitPrBranch(), "primary", false, GIT_WORKFLOW_CREATE_PR_TOOLTIP);
12578
+ addGitWorkflowAction("Manual worktree", () => createGitPrBranchManually(), "", false, GIT_WORKFLOW_MANUAL_BRANCH_TOOLTIP);
11954
12579
  }
11955
12580
  const commitInputButton = renderGitWorkflowManualCommitInput({ appendCommitButton: false });
11956
12581
  addGitWorkflowAction("Commit short", () => commitGitWorkflow("short"), gitWorkflow.prMode ? "primary" : "", false);
@@ -11959,9 +12584,9 @@ function renderGitWorkflow() {
11959
12584
  elements.gitWorkflowActions.append(commitInputButton);
11960
12585
  } else if (gitWorkflow.step === "branchNaming") {
11961
12586
  addGitWorkflowAction("Refresh branch name", () => loadGitWorkflowBranchName({ requireFresh: true }), "", false);
11962
- addGitWorkflowAction("Manual branch", () => createGitPrBranchManually(), "", !!gitWorkflow.busy, GIT_WORKFLOW_MANUAL_BRANCH_TOOLTIP);
12587
+ addGitWorkflowAction("Manual worktree", () => createGitPrBranchManually(), "", !!gitWorkflow.busy, GIT_WORKFLOW_MANUAL_BRANCH_TOOLTIP);
11963
12588
  } else if (gitWorkflow.step === "branching") {
11964
- addGitWorkflowAction("Creating branch…", () => {}, "primary", true);
12589
+ addGitWorkflowAction("Opening worktree…", () => {}, "primary", true);
11965
12590
  } else if (gitWorkflow.step === "push") {
11966
12591
  if (gitWorkflow.prMode) addGitWorkflowAction("Push and Create PR", () => pushAndCreatePrGitWorkflow(), "primary", false);
11967
12592
  else addGitWorkflowAction("Run git push", () => pushGitWorkflow(), "primary", false);
@@ -12032,7 +12657,7 @@ function startGitWorkflow(tabId = activeTabId) {
12032
12657
  step: "add",
12033
12658
  process: "stage",
12034
12659
  busy: false,
12035
- 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 to switch to a new branch before committing.",
12660
+ 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.",
12036
12661
  error: "",
12037
12662
  githubUsername: "",
12038
12663
  repoName: "",
@@ -12582,26 +13207,89 @@ async function loadGitWorkflowBranchName({ requireFresh = false, retries = 0, ru
12582
13207
  }
12583
13208
  }
12584
13209
 
13210
+ function syncGitWorkflowWorktreeTabs(result) {
13211
+ if (Array.isArray(result?.tabs)) {
13212
+ tabs = result.tabs;
13213
+ syncTabMetadata(tabs);
13214
+ }
13215
+ if (result?.tab) applyTabMetadata(result.tab);
13216
+ renderTabs();
13217
+ }
13218
+
13219
+ function gitWorkflowWorktreeOutput(result, branch) {
13220
+ const prBranch = cleanStatusText(result?.branch || result?.tab?.gitWorkspace?.branch || branch);
13221
+ const worktreePath = result?.worktree?.path || result?.path || result?.tab?.cwd || "worktree";
13222
+ const copied = result?.carriedStagedChanges
13223
+ ? "Staged changes were copied into the worktree index."
13224
+ : result?.openedExisting || result?.openedExistingTab
13225
+ ? "Existing worktree opened; review its current changes before committing."
13226
+ : "Source index was clean; no staged changes were copied.";
13227
+ return `${formatGitCommandResult(result)}\n\nOpened PR branch worktree ${prBranch || branch} at ${normalizeDisplayPath(worktreePath)}. ${copied}\n\nChoose Commit short, Commit long, or Commit input to commit in this worktree tab.`;
13228
+ }
13229
+
12585
13230
  async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowActionTabId(), expectedRunId) {
12586
13231
  const workflow = gitWorkflowForTab(tabId, { create: false });
12587
13232
  if (!workflow) return;
12588
- const proposedBranch = prompt("New PR branch name (example: type/feature-name)", suggestion || defaultGitPrBranchName(workflow.message));
13233
+ const sourceWorkflow = { ...workflow, actionsDone: createGitWorkflowActionsDone(workflow.actionsDone) };
13234
+ const proposedBranch = prompt("New PR branch worktree name (example: type/feature-name)", suggestion || defaultGitPrBranchName(workflow.message));
12589
13235
  if (expectedRunId !== undefined && !isCurrentGitWorkflowRun(expectedRunId, tabId)) return;
12590
13236
  if (proposedBranch === null) {
12591
- setGitWorkflow({ step: "message", busy: false, output: `${formatCommitMessagePreview(workflow.message)}\n\nPR branch creation cancelled. Use Create PR to generate a branch name again or Manual branch to type one.` }, { tabId });
13237
+ setGitWorkflow({ step: "message", busy: false, output: `${formatCommitMessagePreview(sourceWorkflow.message)}\n\nPR branch worktree creation cancelled. Use Create PR worktree to generate a branch name again or Manual worktree to type one.` }, { tabId });
12592
13238
  return;
12593
13239
  }
12594
13240
  const branch = proposedBranch.trim();
12595
13241
  if (!branch) {
12596
- failGitWorkflow(new Error("Branch name is required to create a PR branch."), "message", { tabId });
13242
+ failGitWorkflow(new Error("Branch name is required to create a PR branch worktree."), "message", { tabId });
12597
13243
  return;
12598
13244
  }
12599
13245
  const runId = workflow.runId;
12600
- setGitWorkflow({ step: "branching", prMode: true, prBranch: branch, branchName: branch, busy: true, error: "", output: `${formatCommitMessagePreview(workflow.message)}\n\nRunning git switch -c ${branch}…` }, { tabId });
13246
+ setGitWorkflow({ step: "branching", prMode: true, prBranch: branch, branchName: branch, busy: true, error: "", output: `${formatCommitMessagePreview(sourceWorkflow.message)}\n\nCreating or opening branch worktree ${branch}…` }, { tabId });
12601
13247
  try {
12602
- const result = await gitWorkflowRequest("/api/git-workflow/branch", { body: { branch }, runId, tabId });
13248
+ const result = await gitWorkflowRequest("/api/git-workflow/branch", { body: { branch, sessionMode: "fork-current", openTab: true }, runId, tabId });
12603
13249
  if (!result) return;
12604
- setGitWorkflow({ step: "message", prMode: true, prBranch: result.branch || branch, branchName: result.branch || branch, busy: false, output: `${formatGitCommandResult(result)}\n\nCreated PR branch ${result.branch || branch}. Choose Commit short, Commit long, or Commit input to commit on this branch.` }, { tabId });
13250
+ syncGitWorkflowWorktreeTabs(result);
13251
+ const targetTabId = result.tab?.id && tabs.some((tab) => tab.id === result.tab.id) ? result.tab.id : tabId;
13252
+ const prBranch = cleanStatusText(result.branch || result.tab?.gitWorkspace?.branch || branch);
13253
+ const output = gitWorkflowWorktreeOutput(result, prBranch || branch);
13254
+ const nextState = {
13255
+ active: true,
13256
+ mode: "standard",
13257
+ step: "message",
13258
+ process: "commit",
13259
+ busy: false,
13260
+ runId,
13261
+ output,
13262
+ error: "",
13263
+ githubUsername: "",
13264
+ repoName: "",
13265
+ remoteUrl: "",
13266
+ stack: "",
13267
+ readmeRequestedAt: 0,
13268
+ gitignoreRequestedAt: 0,
13269
+ initFilesStatus: null,
13270
+ message: sourceWorkflow.message,
13271
+ manualCommitMessage: sourceWorkflow.manualCommitMessage || "",
13272
+ manualCommitMessageDefault: sourceWorkflow.manualCommitMessageDefault || "",
13273
+ manualCommitMessageDefaultReason: sourceWorkflow.manualCommitMessageDefaultReason || "",
13274
+ manualCommitMessageDefaultPath: sourceWorkflow.manualCommitMessageDefaultPath || "",
13275
+ manualCommitMessageDefaultAction: sourceWorkflow.manualCommitMessageDefaultAction || "",
13276
+ manualCommitMessageDefaultRequestedAt: sourceWorkflow.manualCommitMessageDefaultRequestedAt || 0,
13277
+ manualCommitMessageDefaultLoading: false,
13278
+ messageRequestedAt: sourceWorkflow.messageRequestedAt || 0,
13279
+ branchName: prBranch || branch,
13280
+ branchNameRequestedAt: sourceWorkflow.branchNameRequestedAt || 0,
13281
+ actionsDone: createGitWorkflowActionsDone({ ...sourceWorkflow.actionsDone, branch: true }),
13282
+ prMode: true,
13283
+ prBranch: prBranch || branch,
13284
+ pr: null,
13285
+ prRequestedAt: 0,
13286
+ };
13287
+ if (targetTabId !== tabId) {
13288
+ 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 });
13289
+ }
13290
+ setGitWorkflow(nextState, { tabId: targetTabId });
13291
+ if (targetTabId !== tabId) await switchTab(targetTabId);
13292
+ addEvent(`Opened PR branch worktree ${prBranch || branch}. Continue the guided Git workflow in its tab.`, "success");
12605
13293
  } catch (error) {
12606
13294
  if (isCurrentGitWorkflowRun(runId, tabId)) {
12607
13295
  setGitWorkflow({ prMode: false, prBranch: "" }, { tabId });
@@ -12842,14 +13530,51 @@ function queueSummaryPill(label, count, tone) {
12842
13530
  return pill;
12843
13531
  }
12844
13532
 
12845
- function renderQueueGroup(label, items, tone) {
13533
+ async function removeQueuedFollowUpPrompt(index, message, tabId = activeTabId) {
13534
+ if (!tabId) return false;
13535
+ const tabContext = activeTabContext(tabId);
13536
+ try {
13537
+ const response = await api("/api/queue/remove", { method: "POST", body: { kind: "followUp", index, message }, tabId });
13538
+ const data = response?.data || {};
13539
+ if (data.queue && isCurrentTabContext(tabContext)) renderQueue({ tabId, ...data.queue });
13540
+ if (data.removed) {
13541
+ if (isCurrentTabContext(tabContext)) addEvent(`removed queued follow-up #${index + 1}`);
13542
+ scheduleRefreshState(120, tabContext);
13543
+ return true;
13544
+ }
13545
+ if (isCurrentTabContext(tabContext)) addEvent("queued follow-up changed before it could be removed; refreshed queue", "warn");
13546
+ scheduleRefreshState(120, tabContext);
13547
+ return false;
13548
+ } catch (error) {
13549
+ if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
13550
+ return false;
13551
+ }
13552
+ }
13553
+
13554
+ function renderQueueGroup(label, items, tone, { removable = false, tabId } = {}) {
12846
13555
  const group = make("section", `queue-group ${tone}`.trim());
12847
13556
  const heading = make("h3", "queue-group-title");
12848
13557
  heading.append(make("span", undefined, label), make("span", "queue-group-count", String(items.length)));
12849
13558
  const list = make("ol", "queue-list");
12850
13559
  items.forEach((item, index) => {
12851
- const row = make("li", "queue-item");
13560
+ const row = make("li", `queue-item${removable ? " can-remove" : ""}`);
12852
13561
  row.append(make("span", "queue-item-number", `#${index + 1}`), make("div", "queue-item-text", item));
13562
+ if (removable) {
13563
+ const removeButton = make("button", "queue-remove-button", "Remove");
13564
+ removeButton.type = "button";
13565
+ removeButton.title = `Remove queued follow-up #${index + 1}`;
13566
+ removeButton.setAttribute("aria-label", `Remove queued follow-up #${index + 1}`);
13567
+ removeButton.addEventListener("click", async () => {
13568
+ removeButton.disabled = true;
13569
+ removeButton.textContent = "Removing…";
13570
+ const removed = await removeQueuedFollowUpPrompt(index, item, tabId);
13571
+ if (!removed && removeButton.isConnected) {
13572
+ removeButton.disabled = false;
13573
+ removeButton.textContent = "Remove";
13574
+ }
13575
+ });
13576
+ row.append(removeButton);
13577
+ }
12853
13578
  list.append(row);
12854
13579
  });
12855
13580
  group.append(heading, list);
@@ -12882,9 +13607,9 @@ function renderQueue(event) {
12882
13607
  summary.append(counts);
12883
13608
 
12884
13609
  elements.queueBox.append(summary);
12885
- if (steering.length) elements.queueBox.append(renderQueueGroup("Steering", steering, "steering"));
12886
- if (followUp.length) elements.queueBox.append(renderQueueGroup("Follow-up", followUp, "follow-up"));
12887
- elements.queueBox.append(make("div", "queue-hint", "Alt+Up restores this queue snapshot to the composer. RPC queue clearing is pending upstream support."));
13610
+ if (steering.length) elements.queueBox.append(renderQueueGroup("Steering", steering, "steering", { tabId }));
13611
+ if (followUp.length) elements.queueBox.append(renderQueueGroup("Follow-up", followUp, "follow-up", { removable: true, tabId }));
13612
+ elements.queueBox.append(make("div", "queue-hint", "Alt+Up restores this queue snapshot to the composer without clearing Pi's queue. Use Remove beside follow-ups to drop them from the queue."));
12888
13613
  updateStickyUserPromptButton();
12889
13614
  }
12890
13615
 
@@ -13768,16 +14493,21 @@ function streamingMarkdownStableBoundary(text) {
13768
14493
  return boundary;
13769
14494
  }
13770
14495
 
14496
+ function clearStreamingMarkdownBlock(block) {
14497
+ while (block.firstChild) block.firstChild.remove();
14498
+ }
14499
+
13771
14500
  function renderStreamingMarkdown(block, text) {
13772
14501
  let state = streamMarkdownState;
13773
14502
  if (!state || state.block !== block) {
13774
- block.replaceChildren();
14503
+ clearStreamingMarkdownBlock(block);
13775
14504
  state = streamMarkdownState = { block, stableText: "", tailNodes: [] };
13776
14505
  }
13777
14506
  if (!text.startsWith(state.stableText)) {
13778
- // Earlier content changed retroactively (e.g. todo-progress stripping);
13779
- // fall back to a full re-render for correctness.
13780
- block.replaceChildren();
14507
+ // Derived streaming text should be append-only; if a provider still sends a
14508
+ // retroactive rewrite, reset the streaming renderer without replaceChildren
14509
+ // so this path cannot tear down external chrome or widget nodes.
14510
+ clearStreamingMarkdownBlock(block);
13781
14511
  state.stableText = "";
13782
14512
  state.tailNodes = [];
13783
14513
  }
@@ -14218,6 +14948,30 @@ function assistantToolCallArguments(part) {
14218
14948
  return part?.arguments || part?.args || part?.input || part?.toolCall?.arguments || {};
14219
14949
  }
14220
14950
 
14951
+ function toolCallArgumentsText(value, { includeEmptyObject = true } = {}) {
14952
+ if (typeof value === "string") return value;
14953
+ if (value === undefined || value === null) return includeEmptyObject ? "{}" : "";
14954
+ if (typeof value === "object") {
14955
+ if (!includeEmptyObject && !Array.isArray(value) && Object.keys(value).length === 0) return "";
14956
+ try {
14957
+ return JSON.stringify(value, null, 2);
14958
+ } catch {
14959
+ return String(value);
14960
+ }
14961
+ }
14962
+ return String(value);
14963
+ }
14964
+
14965
+ function toolCallDisplayText(message, options = {}) {
14966
+ if (typeof message?.rawArguments === "string" && message.rawArguments.length > 0) return message.rawArguments;
14967
+ return toolCallArgumentsText(message?.arguments ?? message?.content ?? {}, options);
14968
+ }
14969
+
14970
+ function renderToolCallMessageBody(body, message, { placeholder = "{}" } = {}) {
14971
+ const text = toolCallDisplayText(message).trimEnd() || placeholder;
14972
+ appendText(body, text, "code-block tool-call-arguments");
14973
+ }
14974
+
14221
14975
  function assistantTextPartText(part) {
14222
14976
  if (!part || typeof part !== "object" || part.type !== "text") return "";
14223
14977
  if (typeof part.text === "string") return part.text;
@@ -15252,7 +16006,7 @@ function appendMessage(message, { streaming = false, messageIndex = -1, transien
15252
16006
  const thinkingText = visibleThinkingText(message.thinking || textFromContent(message.content));
15253
16007
  if (thinkingOutputVisible && thinkingText) appendText(body, thinkingText, "thinking-text");
15254
16008
  } else if (message.role === "toolCall") {
15255
- appendText(body, JSON.stringify(message.arguments ?? message.content ?? {}, null, 2), "code-block");
16009
+ renderToolCallMessageBody(body, message);
15256
16010
  } else if (message.role === "assistantEvent") {
15257
16011
  appendText(body, typeof message.content === "string" ? message.content : JSON.stringify(message.content ?? {}, null, 2), "code-block");
15258
16012
  } else {
@@ -15449,6 +16203,19 @@ function renderRunIndicator({ scroll = false } = {}) {
15449
16203
  if (shouldFollow) scrollChatToBottom();
15450
16204
  }
15451
16205
 
16206
+ function scheduleRunIndicatorRender({ scroll = false } = {}) {
16207
+ runIndicatorRenderScroll = runIndicatorRenderScroll || scroll;
16208
+ if (runIndicatorRenderFrame !== null) return;
16209
+ const flush = () => {
16210
+ const shouldScroll = runIndicatorRenderScroll;
16211
+ runIndicatorRenderFrame = null;
16212
+ runIndicatorRenderScroll = false;
16213
+ renderRunIndicator({ scroll: shouldScroll });
16214
+ };
16215
+ if (typeof requestAnimationFrame === "function") runIndicatorRenderFrame = requestAnimationFrame(flush);
16216
+ else runIndicatorRenderFrame = setTimeout(flush, 0);
16217
+ }
16218
+
15452
16219
  function setRunIndicatorActivity(activity, { active = true, scroll = true } = {}) {
15453
16220
  const wasLocallyActive = runIndicatorLocallyActive;
15454
16221
  const previousActivity = runIndicatorActivity;
@@ -15459,9 +16226,9 @@ function setRunIndicatorActivity(activity, { active = true, scroll = true } = {}
15459
16226
  }
15460
16227
  runIndicatorActivity = activity || runIndicatorActivity || "Waiting for output or action…";
15461
16228
  const needsRender = scroll || !hadRunIndicatorBubble || wasLocallyActive !== runIndicatorLocallyActive || previousActivity !== runIndicatorActivity;
15462
- if (needsRender) renderRunIndicator({ scroll });
16229
+ if (needsRender) scheduleRunIndicatorRender({ scroll });
15463
16230
  else if (runIndicatorIsActive()) startRunIndicatorTicker();
15464
- updateComposerModeButtons();
16231
+ scheduleComposerModeButtonsUpdate();
15465
16232
  if (active) scheduleRunIndicatorGraceCheck();
15466
16233
  }
15467
16234
 
@@ -15887,11 +16654,15 @@ function applyChatFollowScroll() {
15887
16654
  updateStickyUserPromptButton();
15888
16655
  }
15889
16656
 
15890
- function scheduleChatFollowScroll() {
16657
+ function scheduleChatFollowScroll({ settle = true } = {}) {
15891
16658
  if (chatFollowFrame === null) chatFollowFrame = requestAnimationFrame(applyChatFollowScroll);
16659
+ if (!settle) return;
16660
+ chatFollowNeedsSettle = true;
15892
16661
  clearTimeout(chatFollowSettleTimer);
15893
16662
  chatFollowSettleTimer = setTimeout(() => {
15894
16663
  chatFollowSettleTimer = null;
16664
+ if (!chatFollowNeedsSettle) return;
16665
+ chatFollowNeedsSettle = false;
15895
16666
  applyChatFollowScroll();
15896
16667
  }, CHAT_FOLLOW_SETTLE_DELAY_MS);
15897
16668
  }
@@ -15900,16 +16671,7 @@ function scrollChatToBottom({ force = false } = {}) {
15900
16671
  if (deferChatFollowScrollDuringPointerActivation({ force })) return;
15901
16672
  if (deferChatFollowScrollDuringInteractiveDropdown({ force })) return;
15902
16673
  if (force) autoFollowChat = true;
15903
- if (!autoFollowChat) {
15904
- updateJumpToLatestButton();
15905
- updateStickyUserPromptButton();
15906
- return;
15907
- }
15908
- lastChatProgrammaticScrollAt = performance.now();
15909
- setChatScrollTopInstant(elements.chat.scrollHeight);
15910
16674
  scheduleChatFollowScroll();
15911
- updateJumpToLatestButton();
15912
- updateStickyUserPromptButton();
15913
16675
  }
15914
16676
 
15915
16677
  function syncAutoFollowFromChatScroll() {
@@ -16156,9 +16918,9 @@ async function refreshOptionalFeaturePackageStatuses({ announce = false } = {})
16156
16918
  }
16157
16919
  }
16158
16920
 
16159
- function requestGitFooterWebuiPayload(tabContext = activeTabContext(), { force = false } = {}) {
16921
+ function requestGitFooterWebuiPayload(tabContext = activeTabContext(), { force = false, silent = true, allowDuringRun = false } = {}) {
16160
16922
  if (!tabContext.tabId || isOptionalFeatureDisabled("gitFooterStatus")) return;
16161
- if (currentState?.isStreaming || currentState?.isCompacting) return;
16923
+ if (!allowDuringRun && (currentState?.isStreaming || currentState?.isCompacting)) return;
16162
16924
  const refreshCommand = resolveAvailableCommandName("git-footer-refresh", { rpcOnly: true });
16163
16925
  if (!refreshCommand || (!force && statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY))) return;
16164
16926
  if (gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId)) return;
@@ -16167,7 +16929,7 @@ function requestGitFooterWebuiPayload(tabContext = activeTabContext(), { force =
16167
16929
  if (isCurrentTabContext(tabContext)) renderFooter();
16168
16930
  api("/api/prompt", {
16169
16931
  method: "POST",
16170
- body: { message: `/${refreshCommand} --webui-silent`, streamingBehavior: "steer" },
16932
+ body: { message: `/${refreshCommand}${silent ? " --webui-silent" : ""}`, streamingBehavior: "steer" },
16171
16933
  tabId: tabContext.tabId,
16172
16934
  }).catch((error) => {
16173
16935
  if (isCurrentTabContext(tabContext)) addEvent(`git footer payload refresh failed: ${error.message || String(error)}`, "warn");
@@ -17444,6 +18206,8 @@ function cancelStreamBubbleHide() {
17444
18206
  function cancelStreamingAssistantTextRender() {
17445
18207
  clearTimeout(streamTextRenderTimer);
17446
18208
  streamTextRenderTimer = null;
18209
+ if (streamTextRenderFrame !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(streamTextRenderFrame);
18210
+ streamTextRenderFrame = null;
17447
18211
  }
17448
18212
 
17449
18213
  function removeStreamBubble() {
@@ -17456,10 +18220,54 @@ function removeStreamBubble() {
17456
18220
  renderRunIndicator({ scroll: false });
17457
18221
  }
17458
18222
 
17459
- function streamRenderableAssistantText() {
18223
+ function resetStreamDerivedTextCache() {
18224
+ streamDerivedTextCache = { rawText: null, assistantText: "", thinkingFormat: null, finalText: "" };
18225
+ }
18226
+
18227
+ function setStreamRawText(text) {
18228
+ const nextText = String(text || "");
18229
+ if (nextText === streamRawText) return false;
18230
+ streamRawText = nextText;
18231
+ resetStreamDerivedTextCache();
18232
+ return true;
18233
+ }
18234
+
18235
+ function appendStreamRawText(delta) {
18236
+ const text = String(delta || "");
18237
+ if (!text) return false;
18238
+ streamRawText += text;
18239
+ resetStreamDerivedTextCache();
18240
+ return true;
18241
+ }
18242
+
18243
+ function streamingAssistantTextFallback(event) {
18244
+ // Fallback for legacy/summary events that do not carry a delta. The hot
18245
+ // text_delta path appends update.delta and avoids this accumulated-message scan.
18246
+ return assistantTextFromMessage(assistantStreamingMessage(event), { streaming: true });
18247
+ }
18248
+
18249
+ function syncStreamRawTextFromUpdate(event, update) {
18250
+ if (update.type === "text_delta") {
18251
+ const delta = update.delta ?? update.text ?? update.content ?? "";
18252
+ if (appendStreamRawText(delta)) return true;
18253
+ }
18254
+ if (typeof update.content === "string") return setStreamRawText(update.content);
18255
+ if (typeof update.text === "string") return setStreamRawText(update.text);
18256
+ const partialText = streamingAssistantTextFallback(event);
18257
+ return typeof partialText === "string" ? setStreamRawText(partialText) : false;
18258
+ }
18259
+
18260
+ function streamDerivedText() {
18261
+ if (streamDerivedTextCache.rawText === streamRawText) return streamDerivedTextCache;
17460
18262
  const assistantText = stripTodoProgressLines(streamRawText, { streaming: true });
17461
- const parsed = splitThinkingFormatText(assistantText, { streaming: true });
17462
- return parsed?.hasThinkingFormat ? stripTodoProgressLines(parsed.finalText, { streaming: true }) : assistantText;
18263
+ const thinkingFormat = splitThinkingFormatText(assistantText, { streaming: true });
18264
+ const finalText = thinkingFormat?.hasThinkingFormat ? stripTodoProgressLines(thinkingFormat.finalText, { streaming: true }) : assistantText;
18265
+ streamDerivedTextCache = { rawText: streamRawText, assistantText, thinkingFormat, finalText };
18266
+ return streamDerivedTextCache;
18267
+ }
18268
+
18269
+ function streamRenderableAssistantText() {
18270
+ return streamDerivedText().finalText;
17463
18271
  }
17464
18272
 
17465
18273
  function scheduleStreamBubbleHide() {
@@ -17474,8 +18282,8 @@ function scheduleStreamBubbleHide() {
17474
18282
  }, delayMs);
17475
18283
  }
17476
18284
 
17477
- function syncStreamingThinkingFormat(assistantText) {
17478
- const parsed = splitThinkingFormatText(assistantText, { streaming: true });
18285
+ function syncStreamingThinkingFormat() {
18286
+ const parsed = streamDerivedText().thinkingFormat;
17479
18287
  if (!parsed?.hasThinkingFormat) return null;
17480
18288
  const thinking = visibleThinkingText(parsed.thinkingText);
17481
18289
  if (thinking) setStreamingThinkingText(thinking);
@@ -17484,9 +18292,8 @@ function syncStreamingThinkingFormat(assistantText) {
17484
18292
  }
17485
18293
 
17486
18294
  function renderStreamingAssistantText() {
17487
- const assistantText = stripTodoProgressLines(streamRawText, { streaming: true });
17488
- const thinkingFormat = syncStreamingThinkingFormat(assistantText);
17489
- const finalText = thinkingFormat?.hasThinkingFormat ? stripTodoProgressLines(thinkingFormat.finalText, { streaming: true }) : assistantText;
18295
+ const thinkingFormat = syncStreamingThinkingFormat();
18296
+ const finalText = thinkingFormat?.hasThinkingFormat ? streamDerivedText().finalText : streamRenderableAssistantText();
17490
18297
  if (finalText) {
17491
18298
  ensureStreamBubble();
17492
18299
  renderStreamingMarkdown(streamText, finalText);
@@ -17495,19 +18302,72 @@ function renderStreamingAssistantText() {
17495
18302
  }
17496
18303
  }
17497
18304
 
17498
- function scheduleStreamingAssistantTextRender() {
17499
- if (streamTextRenderTimer) return;
17500
- streamTextRenderTimer = setTimeout(() => {
18305
+ function scheduleStreamingAssistantTextRender({ immediate = false } = {}) {
18306
+ if (streamTextRenderTimer || streamTextRenderFrame !== null) return;
18307
+ const flush = () => {
17501
18308
  streamTextRenderTimer = null;
18309
+ streamTextRenderFrame = null;
17502
18310
  renderStreamingAssistantText();
17503
- }, STREAM_OUTPUT_TOOLCALL_GUARD_MS);
18311
+ scheduleChatFollowScroll();
18312
+ };
18313
+ if (immediate && typeof requestAnimationFrame === "function") streamTextRenderFrame = requestAnimationFrame(flush);
18314
+ else streamTextRenderTimer = setTimeout(flush, immediate ? 0 : STREAM_OUTPUT_TOOLCALL_GUARD_MS);
17504
18315
  }
17505
18316
 
17506
18317
  function suppressStreamingAssistantTextBeforeToolCall() {
17507
- streamRawText = "";
18318
+ setStreamRawText("");
17508
18319
  removeStreamBubble();
17509
18320
  }
17510
18321
 
18322
+ function resetStreamingToolCallState({ remove = true } = {}) {
18323
+ if (remove) streamToolCallBubble?.remove();
18324
+ streamToolCallBubble = null;
18325
+ streamToolCallText = null;
18326
+ streamToolCallRawArguments = "";
18327
+ streamToolCallName = "";
18328
+ streamToolCallId = "";
18329
+ streamToolCallContentIndex = null;
18330
+ streamToolCallComplete = false;
18331
+ }
18332
+
18333
+ function streamingToolCallTitle() {
18334
+ const name = streamToolCallName || "tool";
18335
+ return `tool call: ${name}${streamToolCallComplete ? " (ready)" : " (building)"}`;
18336
+ }
18337
+
18338
+ function streamingToolCallMessage() {
18339
+ return {
18340
+ role: "toolCall",
18341
+ title: streamingToolCallTitle(),
18342
+ timestamp: Date.now(),
18343
+ toolName: streamToolCallName || "tool",
18344
+ toolCallId: streamToolCallId,
18345
+ rawArguments: streamToolCallRawArguments,
18346
+ content: streamToolCallRawArguments,
18347
+ };
18348
+ }
18349
+
18350
+ function renderStreamingToolCallCard({ scroll = false } = {}) {
18351
+ const message = streamingToolCallMessage();
18352
+ const displayText = streamToolCallRawArguments || (streamToolCallComplete ? "{}" : "(waiting for argument stream…)");
18353
+ if (!streamToolCallBubble?.parentElement || !streamToolCallText) {
18354
+ const created = appendMessage(message, { streaming: true });
18355
+ streamToolCallBubble = created.bubble;
18356
+ streamToolCallText = created.body.querySelector(".tool-call-arguments") || created.body.querySelector(".code-block");
18357
+ }
18358
+ streamToolCallBubble._copyMessage = message;
18359
+ const role = streamToolCallBubble.querySelector(":scope > .message-header .message-role");
18360
+ if (role && role.textContent !== message.title) role.textContent = message.title;
18361
+ if (streamToolCallText && streamToolCallText.textContent !== displayText) streamToolCallText.textContent = displayText;
18362
+ renderRunIndicator({ scroll: false });
18363
+ if (scroll) scrollChatToBottom();
18364
+ }
18365
+
18366
+ function removeStreamingToolCallCard() {
18367
+ resetStreamingToolCallState({ remove: true });
18368
+ renderRunIndicator({ scroll: false });
18369
+ }
18370
+
17511
18371
  function ensureStreamBubble() {
17512
18372
  cancelStreamBubbleHide();
17513
18373
  if (streamBubble?.parentElement === elements.chat) return;
@@ -17542,16 +18402,19 @@ function resetStreamBubble() {
17542
18402
  streamBubble = null;
17543
18403
  streamText = null;
17544
18404
  streamRawText = "";
18405
+ streamThinkingRawText = "";
18406
+ resetStreamDerivedTextCache();
17545
18407
  streamMarkdownState = null;
17546
18408
  streamBubbleVisibleSince = 0;
17547
18409
  streamToolCallSeen = false;
18410
+ resetStreamingToolCallState({ remove: true });
17548
18411
  streamThinkingBubble = null;
17549
18412
  streamThinking = null;
17550
18413
  streamMessageActive = false;
17551
18414
  }
17552
18415
 
17553
18416
  function liveStreamRenderActive() {
17554
- return streamMessageActive && currentState?.isStreaming === true && Boolean(streamBubble || streamThinkingBubble || streamRawText);
18417
+ return streamMessageActive && currentState?.isStreaming === true && Boolean(streamBubble || streamThinkingBubble || streamToolCallBubble || streamRawText || streamToolCallRawArguments);
17555
18418
  }
17556
18419
 
17557
18420
  /**
@@ -17562,15 +18425,19 @@ function liveStreamRenderActive() {
17562
18425
  function restoreStreamRenderAfterChatRebuild() {
17563
18426
  const thinkingText = streamThinking?.textContent || "";
17564
18427
  const thinkingComplete = streamThinkingBubble?.classList.contains("complete") === true;
18428
+ const toolCallWasVisible = !!(streamToolCallBubble?.parentElement === elements.chat || streamToolCallRawArguments || streamToolCallName);
17565
18429
  streamBubble = null;
17566
18430
  streamText = null;
17567
18431
  streamThinkingBubble = null;
17568
18432
  streamThinking = null;
18433
+ streamToolCallBubble = null;
18434
+ streamToolCallText = null;
17569
18435
  streamBubbleVisibleSince = 0;
17570
18436
  if (thinkingText && setStreamingThinkingText(thinkingText) && thinkingComplete) {
17571
18437
  streamThinkingBubble?.classList.add("complete");
17572
18438
  }
17573
- if (stripTodoProgressLines(streamRawText, { streaming: true })) renderStreamingAssistantText();
18439
+ if (toolCallWasVisible) renderStreamingToolCallCard();
18440
+ if (streamRenderableAssistantText()) renderStreamingAssistantText();
17574
18441
  }
17575
18442
 
17576
18443
  function thinkingDeltaText(update) {
@@ -17583,6 +18450,56 @@ function assistantStreamingMessage(event) {
17583
18450
  return partial?.role === "assistant" ? partial : null;
17584
18451
  }
17585
18452
 
18453
+ function assistantToolCallPartFromUpdate(event, update = event?.assistantMessageEvent || {}) {
18454
+ if (isAssistantToolCallPart(update.toolCall)) return update.toolCall;
18455
+ const message = assistantStreamingMessage(event);
18456
+ const content = message?.content;
18457
+ if (!Array.isArray(content)) return null;
18458
+ const contentIndex = Number(update.contentIndex);
18459
+ if (Number.isInteger(contentIndex) && isAssistantToolCallPart(content[contentIndex])) return content[contentIndex];
18460
+ for (let index = content.length - 1; index >= 0; index -= 1) {
18461
+ if (isAssistantToolCallPart(content[index])) return content[index];
18462
+ }
18463
+ return null;
18464
+ }
18465
+
18466
+ function streamToolCallNameFromUpdate(update, part) {
18467
+ const rawName = update.name || update.toolName || update.toolCall?.name || assistantToolCallName(part);
18468
+ const name = runIndicatorToolName(rawName);
18469
+ return name === "unknown" ? "tool" : name;
18470
+ }
18471
+
18472
+ function streamingToolCallContentIndexFromUpdate(update) {
18473
+ const contentIndex = Number(update.contentIndex);
18474
+ return Number.isInteger(contentIndex) ? contentIndex : null;
18475
+ }
18476
+
18477
+ function updateStreamingToolCallFromEvent(event, { reset = false, appendDelta = false, complete = false, scroll = false } = {}) {
18478
+ const update = event.assistantMessageEvent || {};
18479
+ const part = assistantToolCallPartFromUpdate(event, update);
18480
+ const contentIndex = streamingToolCallContentIndexFromUpdate(update);
18481
+ if (reset || (contentIndex !== null && streamToolCallContentIndex !== null && contentIndex !== streamToolCallContentIndex)) {
18482
+ resetStreamingToolCallState({ remove: true });
18483
+ }
18484
+ streamToolCallContentIndex = contentIndex ?? streamToolCallContentIndex;
18485
+ streamToolCallName = streamToolCallNameFromUpdate(update, part) || streamToolCallName || "tool";
18486
+ streamToolCallId = assistantToolCallId(update.toolCall || part) || streamToolCallId;
18487
+ streamToolCallComplete = !!complete;
18488
+
18489
+ const partArgumentText = toolCallArgumentsText(assistantToolCallArguments(update.toolCall || part), { includeEmptyObject: false });
18490
+ if (reset) streamToolCallRawArguments = partArgumentText || "";
18491
+ if (appendDelta && update.delta !== undefined && update.delta !== null) streamToolCallRawArguments += typeof update.delta === "string" ? update.delta : String(update.delta);
18492
+ if (!streamToolCallRawArguments && partArgumentText) streamToolCallRawArguments = partArgumentText;
18493
+ if (complete) {
18494
+ const finalArgumentText = toolCallArgumentsText(assistantToolCallArguments(update.toolCall || part), { includeEmptyObject: true });
18495
+ if (finalArgumentText && (finalArgumentText !== "{}" || !streamToolCallRawArguments)) streamToolCallRawArguments = finalArgumentText;
18496
+ if (!streamToolCallRawArguments) streamToolCallRawArguments = "{}";
18497
+ }
18498
+
18499
+ renderStreamingToolCallCard({ scroll });
18500
+ return streamToolCallName || "tool";
18501
+ }
18502
+
17586
18503
  function assistantTextFromMessage(message, { streaming = false } = {}) {
17587
18504
  void streaming;
17588
18505
  const content = message?.content;
@@ -17627,58 +18544,98 @@ function setStreamingThinkingText(text) {
17627
18544
  return true;
17628
18545
  }
17629
18546
 
17630
- function syncStreamingThinkingFromMessage(event, { placeholder = "" } = {}) {
18547
+ function streamingThinkingTextFallback(event) {
18548
+ return assistantThinkingTextFromMessage(assistantStreamingMessage(event), { streaming: true });
18549
+ }
18550
+
18551
+ function setStreamThinkingRawText(text) {
18552
+ const thinking = visibleThinkingText(text);
18553
+ if (thinking === streamThinkingRawText) return false;
18554
+ streamThinkingRawText = thinking;
18555
+ return true;
18556
+ }
18557
+
18558
+ function appendStreamThinkingText(delta) {
18559
+ const thinking = visibleThinkingText(delta);
18560
+ if (!thinking) return false;
18561
+ streamThinkingRawText += thinking;
18562
+ return true;
18563
+ }
18564
+
18565
+ function syncStreamingThinkingFromUpdate(event, update, { placeholder = "" } = {}) {
17631
18566
  if (!thinkingOutputVisible) return true;
17632
- const text = assistantThinkingTextFromMessage(assistantStreamingMessage(event), { streaming: true });
17633
- if (text === null) return false;
17634
- return setStreamingThinkingText(text || placeholder);
18567
+ const delta = thinkingDeltaText(update);
18568
+ if (update.type === "thinking_delta" && delta) {
18569
+ appendStreamThinkingText(delta);
18570
+ return setStreamingThinkingText(streamThinkingRawText || placeholder);
18571
+ }
18572
+ if (update.type === "thinking_start") {
18573
+ if (delta) setStreamThinkingRawText(delta);
18574
+ return streamThinkingRawText ? setStreamingThinkingText(streamThinkingRawText || placeholder) : false;
18575
+ }
18576
+ if (update.type === "thinking_end") {
18577
+ if (delta) setStreamThinkingRawText(delta);
18578
+ else {
18579
+ const fallback = streamingThinkingTextFallback(event);
18580
+ if (fallback !== null) setStreamThinkingRawText(fallback);
18581
+ }
18582
+ return setStreamingThinkingText(streamThinkingRawText || placeholder);
18583
+ }
18584
+ const fallback = streamingThinkingTextFallback(event);
18585
+ if (fallback === null) return false;
18586
+ setStreamThinkingRawText(fallback);
18587
+ return setStreamingThinkingText(streamThinkingRawText || placeholder);
17635
18588
  }
17636
18589
 
17637
18590
  function handleMessageUpdate(event) {
17638
18591
  const update = event.assistantMessageEvent || {};
17639
18592
  if (update.type === "thinking_start") {
17640
18593
  setRunIndicatorActivity("Thinking…", { scroll: false });
17641
- syncStreamingThinkingFromMessage(event);
17642
- scrollChatToBottom();
18594
+ syncStreamingThinkingFromUpdate(event, update);
18595
+ scheduleChatFollowScroll();
17643
18596
  } else if (update.type === "thinking_delta") {
17644
18597
  const delta = thinkingDeltaText(update);
17645
18598
  setRunIndicatorActivity("Thinking…", { scroll: false });
17646
- const synced = syncStreamingThinkingFromMessage(event);
18599
+ const synced = syncStreamingThinkingFromUpdate(event, update);
17647
18600
  if (thinkingOutputVisible && delta && (!synced || !streamThinking?.textContent)) {
17648
18601
  showStreamingThinking("");
17649
18602
  if (streamThinking?.textContent === "Thinking…") streamThinking.textContent = "";
17650
18603
  if (streamThinking) streamThinking.textContent += delta;
17651
18604
  }
17652
- scrollChatToBottom();
18605
+ scheduleChatFollowScroll();
17653
18606
  } else if (update.type === "thinking_end") {
17654
- const finalThinking = assistantThinkingTextFromMessage(assistantStreamingMessage(event), { streaming: true }) || thinkingDeltaText(update);
17655
- if (finalThinking) setStreamingThinkingText(finalThinking);
17656
- streamThinkingBubble?.classList.add("complete");
18607
+ if (syncStreamingThinkingFromUpdate(event, update)) streamThinkingBubble?.classList.add("complete");
17657
18608
  setRunIndicatorActivity("Finished thinking; waiting for the next output or action…", { scroll: false });
17658
18609
  } else if (update.type === "text_delta" || update.type === "text_end") {
17659
- const delta = update.type === "text_delta" ? update.delta || "" : "";
17660
- const partialText = assistantTextFromMessage(assistantStreamingMessage(event), { streaming: true });
17661
- if (typeof partialText === "string") streamRawText = partialText;
17662
- else if (update.type === "text_end" && typeof update.content === "string") streamRawText = update.content;
17663
- else streamRawText += delta;
17664
- syncLiveTodoProgressWidgetFromText(streamRawText, event.tabId || activeTabId);
18610
+ syncStreamRawTextFromUpdate(event, update);
18611
+ scheduleLiveTodoProgressWidgetSync(streamRawText, event.tabId || activeTabId);
17665
18612
  setRunIndicatorActivity("Writing response…", { scroll: false });
17666
- if (streamToolCallSeen || streamBubble) renderStreamingAssistantText();
17667
- else scheduleStreamingAssistantTextRender();
18613
+ scheduleStreamingAssistantTextRender({ immediate: !!(streamToolCallSeen || streamBubble) });
17668
18614
  // Streaming output must stay transcript-local. Full footer/status
17669
18615
  // reconciliation happens on message/state refreshes, not per token.
17670
- scrollChatToBottom();
18616
+ scheduleChatFollowScroll();
17671
18617
  } else if (update.type === "toolcall_start") {
17672
18618
  streamToolCallSeen = true;
17673
18619
  suppressStreamingAssistantTextBeforeToolCall();
17674
- const name = runIndicatorToolName(update.name || update.toolName || update.toolCall?.name);
17675
- setRunIndicatorActivity(`Preparing tool call: ${name}…`);
18620
+ const name = updateStreamingToolCallFromEvent(event, { reset: true, scroll: true });
18621
+ setRunIndicatorActivity(`Building tool call: ${name}…`, { scroll: false });
17676
18622
  addEvent(`tool call started in assistant message`, "info");
18623
+ } else if (update.type === "toolcall_delta") {
18624
+ streamToolCallSeen = true;
18625
+ suppressStreamingAssistantTextBeforeToolCall();
18626
+ const name = updateStreamingToolCallFromEvent(event, { appendDelta: true });
18627
+ setRunIndicatorActivity(`Building tool call: ${name}…`, { scroll: false });
18628
+ scheduleChatFollowScroll();
18629
+ } else if (update.type === "toolcall_end") {
18630
+ streamToolCallSeen = true;
18631
+ suppressStreamingAssistantTextBeforeToolCall();
18632
+ const name = updateStreamingToolCallFromEvent(event, { complete: true, scroll: true });
18633
+ setRunIndicatorActivity(`Tool call ready: ${name}; waiting to run…`, { scroll: false });
17677
18634
  } else if (update.type === "error") {
17678
18635
  setRunIndicatorActivity("Assistant stream reported an error…");
17679
18636
  appendMessage({ role: "error", title: "assistant error", timestamp: Date.now(), content: update.reason || update.errorMessage || "assistant error", level: "error" }, { streaming: true });
17680
18637
  renderRunIndicator({ scroll: false });
17681
- scrollChatToBottom();
18638
+ scheduleChatFollowScroll();
17682
18639
  }
17683
18640
  }
17684
18641
 
@@ -18589,6 +19546,7 @@ function commandPaletteCoreItems() {
18589
19546
  const items = [
18590
19547
  { kind: "Action", label: "New tab", description: "Start an isolated Pi terminal in the current directory", keywords: "workspace session", run: () => createTerminalTab() },
18591
19548
  { kind: "Action", label: "Choose directory for new tab", description: "Pick a cwd before starting a tab", keywords: "cwd folder workspace", run: () => createTerminalTabFromChosenDirectory({ triggerButton: elements.commandPaletteButton }) },
19549
+ { kind: "Git", label: "Branch worktree", description: "Create or open a Git worktree tab for parallel branch work", keywords: "git branch worktree parallel checkout", run: () => openBranchWorktreePicker() },
18592
19550
  { kind: "Action", label: "New session", description: "Start a fresh session in the active tab", keywords: "/new clear", run: () => elements.newSessionButton.click() },
18593
19551
  { kind: "Action", label: "Compact context", description: contextUsageDetail(), keywords: "/compact context window tokens", run: () => requestManualCompaction() },
18594
19552
  { kind: "Action", label: footerAutoCompactionEnabled() ? "Disable auto-compaction" : "Enable auto-compaction", description: footerAutoCompactionToggleAction(), keywords: "context automatic", run: () => toggleFooterAutoCompaction() },
@@ -19287,7 +20245,7 @@ function handleExtensionUiRequest(request) {
19287
20245
  closeRemoteWebuiQrPopup();
19288
20246
  }
19289
20247
  } else {
19290
- setWidgetForTab(requestTabId, widgetKey, request);
20248
+ if (!setWidgetForTab(requestTabId, widgetKey, request)) return;
19291
20249
  }
19292
20250
  updateOptionalFeatureAvailability();
19293
20251
  renderWidgets();
@@ -19424,9 +20382,9 @@ function handleInactiveTabEvent(event) {
19424
20382
  }
19425
20383
 
19426
20384
  function handleEvent(event) {
19427
- ingestEventTabActivity(event);
19428
- trackAutoRetryStateFromEvent(event);
19429
- trackSkillsFromEvent(event);
20385
+ if (eventHasTabActivityPayload(event)) ingestEventTabActivity(event);
20386
+ if (event?.type === "auto_retry_start" || event?.type === "auto_retry_end") trackAutoRetryStateFromEvent(event);
20387
+ if (eventMayAffectSkillUsage(event)) trackSkillsFromEvent(event);
19430
20388
  if (!eventTargetsActiveTab(event)) {
19431
20389
  handleInactiveTabEvent(event);
19432
20390
  return;
@@ -19496,12 +20454,14 @@ function handleEvent(event) {
19496
20454
  setAppRunnerData(event.tabId || activeTabId, { cwd: event.cwd, activeRun: event.activeRun });
19497
20455
  renderAppRunnerControls();
19498
20456
  renderWidgets();
20457
+ renderTabs();
19499
20458
  break;
19500
20459
  case "webui_cwd_changed":
19501
20460
  addEvent(`${event.tabTitle || "terminal"} cwd changed to ${event.cwd}`);
19502
20461
  setAppRunnerData(event.tabId || activeTabId, { cwd: event.cwd, activeRun: null, runners: [] });
19503
20462
  renderAppRunnerControls();
19504
20463
  renderWidgets();
20464
+ renderTabs();
19505
20465
  refreshTabs().catch((error) => addEvent(error.message, "error"));
19506
20466
  refreshAppRunners(tabContext).catch((error) => addEvent(error.message, "error"));
19507
20467
  scheduleRefreshFooter();
@@ -19595,6 +20555,7 @@ function handleEvent(event) {
19595
20555
  case "tool_execution_start":
19596
20556
  streamToolCallSeen = true;
19597
20557
  suppressStreamingAssistantTextBeforeToolCall();
20558
+ removeStreamingToolCallCard();
19598
20559
  handleToolExecutionStart(event);
19599
20560
  setRunIndicatorActivity(`Running tool: ${runIndicatorToolName(event.toolName)}…`);
19600
20561
  addEvent(`tool ${event.toolName} started`);
@@ -19866,6 +20827,7 @@ elements.newTabMenu?.addEventListener("focusout", () => {
19866
20827
  });
19867
20828
  elements.newTabCurrentDirectoryButton?.addEventListener("click", () => createTerminalTab(currentDirectoryForNewTab(), { triggerButton: elements.newTabCurrentDirectoryButton }));
19868
20829
  elements.newTabChooseDirectoryButton?.addEventListener("click", () => createTerminalTabFromChosenDirectory({ triggerButton: elements.newTabChooseDirectoryButton }));
20830
+ elements.newTabWorktreeButton?.addEventListener("click", () => openBranchWorktreePicker());
19869
20831
  elements.closeAllTabsButton.addEventListener("click", () => closeAllTerminalTabs());
19870
20832
  elements.commandPaletteButton?.addEventListener("click", () => openCommandPalette());
19871
20833
  elements.workspaceDashboardToggleButton?.addEventListener("click", () => setWorkspaceDashboardCollapsed(!workspaceDashboardCollapsed));
@@ -20951,6 +21913,7 @@ restoreTerminalTabsLayoutSetting();
20951
21913
  restoreTerminalCustomGroups();
20952
21914
  restoreToolOutputExpansionSetting();
20953
21915
  restoreWorkspaceDashboardState();
21916
+ initializeTerminalHeaderTooltips();
20954
21917
  restoreSidePanelSectionState();
20955
21918
  bindSidePanelSectionToggles();
20956
21919
  restoreSidePanelState();