@firstpick/pi-package-webui 0.9.6 → 0.9.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.
Files changed (52) hide show
  1. package/README.md +7 -3
  2. package/bin/pi-webui.mjs +367 -72
  3. package/lib/git-workflow-preferences.mjs +21 -1
  4. package/lib/session-tree-event-targets.mjs +70 -0
  5. package/lib/subagent-launch-policy.mjs +375 -0
  6. package/lib/subagent-launch-slots.mjs +2 -1
  7. package/package.json +1 -1
  8. package/public/app.js +721 -35
  9. package/public/index.html +38 -2
  10. package/public/service-worker.js +1 -1
  11. package/public/styles.css +254 -3
  12. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  13. package/tests/browser/control-visibility.spec.mjs +141 -2
  14. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  15. package/tests/browser/guided-git-fallback.spec.mjs +153 -0
  16. package/tests/codex-fast-mode-static.test.mjs +2 -2
  17. package/tests/compact-sections-static.test.mjs +4 -0
  18. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  19. package/tests/control-visibility-static.test.mjs +66 -3
  20. package/tests/controls-layout-static.test.mjs +3 -3
  21. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  22. package/tests/fast-mode-client-static.test.mjs +5 -2
  23. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  24. package/tests/file-viewer-image-static.test.mjs +3 -3
  25. package/tests/git-workflow-preferences.test.mjs +30 -1
  26. package/tests/guided-git-fallback-runtime.test.mjs +418 -0
  27. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  28. package/tests/guided-git-message-reliability-static.test.mjs +8 -7
  29. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  30. package/tests/main-output-loading-static.test.mjs +3 -3
  31. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  32. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  33. package/tests/mobile-foundation-static.test.mjs +3 -3
  34. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  35. package/tests/mobile-static.test.mjs +7 -5
  36. package/tests/open-issue-wizard-static.test.mjs +1 -1
  37. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  38. package/tests/prompt-input-vertical-scroll-static.test.mjs +3 -3
  39. package/tests/questionnaire-dialog.test.mjs +3 -3
  40. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  41. package/tests/resource-defaults-helper.test.mjs +12 -0
  42. package/tests/session-sampling-helper.test.mjs +1 -0
  43. package/tests/session-sampling-ui-static.test.mjs +3 -3
  44. package/tests/session-tree-event-targets.test.mjs +106 -0
  45. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  46. package/tests/subagent-launch-policy.test.mjs +532 -0
  47. package/tests/subagent-observability-static.test.mjs +2 -2
  48. package/tests/subagents-helper.test.mjs +211 -1
  49. package/tests/syntax-highlighting-static.test.mjs +3 -3
  50. package/tests/tab-close-continuity-static.test.mjs +23 -0
  51. package/tests/theme-customizer-static.test.mjs +1 -1
  52. package/webui-rpc-helper.mjs +220 -3
package/README.md CHANGED
@@ -21,7 +21,7 @@ Pi Web UI keeps the normal Pi agent experience while giving you more room to man
21
21
  | **Live agent work** | Follow streaming Markdown with syntax highlighting for code blocks, thinking, tool output, queues, todo progress, managed agent runs, and direct agent-to-agent conversations without leaving the browser. |
22
22
  | **Models and controls** | Change models and thinking effort, manage scoped models, configure tools and skills, and use the command palette. |
23
23
  | **Files and prompts** | Upload or paste files and images, edit text attachments, use slash-command suggestions, browse project files, and reference project paths with `@`. |
24
- | **Git workflows** | Inspect changes, switch branches, review diffs, stage work, generate commit messages, push, and prepare pull requests through guided steps. |
24
+ | **Git workflows** | Inspect changes, switch branches, review diffs, stage work, generate commit messages with an optional one-shot fallback model, push, and prepare pull requests through guided steps. |
25
25
  | **Project utilities** | Launch detected app runners, manage working directories, search files and transcripts, and customize themes. |
26
26
  | **Companion features** | Add stats, remote access, voice, `/btw`, richer Git status, themes, release tools, and other supported Pi packages. |
27
27
  | **Desktop and mobile** | Use a full desktop workspace with resizable left and right side panels, or a compact phone layout with touch-friendly navigation and controls. |
@@ -67,12 +67,16 @@ Check the server at any time with:
67
67
 
68
68
  When session history is still loading, the main window shows **Loading agent output…** with a small inline spinner. Existing transcript content and controls remain available; no popup interrupts your work.
69
69
 
70
+ Open **Events** to see bounded tool activity details such as status, duration, a safe target when available, and a shortened call ID. Use **Show** to isolate errors and failures, warnings, tool activity, or rows with **Tree…** available; **All events** restores the full browser-held history. Select a row to jump to its chat card. Right-click any row, or use its keyboard context-menu shortcut, to switch between **Detailed** and **Compact** display. Compact keeps the timestamp and summary while hiding secondary metadata; tool rows retain a colored lifecycle accent. Eligible tool rows also offer **Tree…** to confirm navigation to that exact point in the session; use `/tree` to navigate back.
71
+
70
72
  Tracked skills appear as compact tags above the composer. Select a named tag to open its skill file; when space is limited, select the **+X** tag to expand the remaining selectable tags upward.
71
73
 
72
- To simplify the interface, right-click a supported button and choose **Hide** (an Undo notice appears), or right-click empty space in a marked toolbar, Control Deck header/footer, or composer area to choose every visible control and input-tag type. Use **Show all** or **Reset defaults** there, or the **Show all controls** / **Reset control visibility** actions in the command palette, to recover hidden items. This preference is global across Web UI workspaces and browsers; **Send** always remains available.
74
+ To simplify the interface, right-click a supported button or empty space in a marked toolbar, Control Deck header/footer, or composer area, then choose **Open setup**. The setup groups every optional control and input-tag type in one scrollable dialog; clear or select a checkbox to save that change immediately. You can still choose **Hide** for one button, use **Show all** or **Reset defaults**, or run the matching recovery actions from the command palette. Visibility is global across Web UI workspaces and browsers. Unavailable controls may stay hidden, and **Send** always remains available.
73
75
 
74
76
  Open **Subagents** to follow agent runs launched by managed extensions or registered SDK, RPC, JSON, print, interactive, tmux, workflow, schedule, gate, and custom integrations. Runs linked to an open WebUI terminal stay in that terminal’s group; other registered runs appear under **External agents**. Each agent row shows its launch source and lifecycle, and only offers output or controls that its owner supports. A `pi-subagents` workflow appears as a collapsible **Workflow** header with its model-powered agents nested inside, rather than as another agent row. Starting or restarting the server reconnects active runs without reopening stale, lost, or already-finished rows from an earlier server run.
75
77
 
78
+ Use **Agent models** in the Subagents panel to choose the default model and thinking level for each built-in role. WebUI applies those defaults when a `subagent` or `subagent_gate` launch omits its model, including children started by `runs.run` and `runs.all` workflow scripts. An explicit reviewer model that does not match its configured slot is blocked rather than silently replaced; omit the model or correct it before retrying. Only after you explicitly authorize the exact exception may Pi use `approve_subagent_model_deviation`; the tool shows you the exact occurrence and model in a confirmation dialog before creating a short-lived, one-use local permit. Save model changes, then reload the active Pi tab.
79
+
76
80
  Independent Pi processes do not appear automatically. Start them through `pi-webui agent run`, attach a persisted session with `pi-webui agent attach`, or use a cooperating registration adapter. See [TECHNICAL.md](TECHNICAL.md#subagent-observability) for supported commands and limitations.
77
81
 
78
82
  When agents exchange direct Intercom messages or use native subagent-supervisor coordination, one compact tag per conversation appears beneath the composer. Up to eight tags share one row; denser groups wrap into a compact grid instead of creating a horizontal scrollbar. Long names shorten with an ellipsis, while the full name remains available to assistive technology and on hover. Select a tag to open a read-only chat view showing the two agent names or IDs and their messages. Generic Intercom transport calls and received Intercom records stay out of the main agent-output transcript, while attachments, tool output, and reasoning remain excluded from the chat view.
@@ -182,7 +186,7 @@ Launch detected development servers, tests, builds, scripts, and project-defined
182
186
 
183
187
  **Optional feature needed:** `@firstpick/pi-prompts-git-pr` for generated commit messages, branch names, and pull-request content. `@firstpick/pi-extension-aur-review` optionally adds the staged-review gate.
184
188
 
185
- Move through review, staging, commit-message generation, commit, push, and pull-request steps with explicit confirmations.
189
+ Move through review, staging, commit-message generation, commit, push, and pull-request steps with explicit confirmations. In **Guided Git Setup**, you can optionally choose a fallback model and its own reasoning effort. If the primary model reaches a final generation failure, Guided Git tries the fallback once, reports the change in the workflow, and restores the tab’s prior model and effort afterward. Validation failures, cancellation, Git command failures, and a stopped Pi process do not trigger fallback.
186
190
 
187
191
  #### Git branch picker
188
192
 
package/bin/pi-webui.mjs CHANGED
@@ -27,6 +27,7 @@ import { AgentRunRegistry } from "../lib/agent-run-registry.mjs";
27
27
  import { resolveScopedModelsFromPatterns } from "../lib/scoped-models.mjs";
28
28
  import { projectIntercomConversations } from "../lib/intercom-conversations.mjs";
29
29
  import { filterIntercomTranscriptMessages } from "../lib/intercom-transcript-filter.mjs";
30
+ import { sessionTreeEventTargets } from "../lib/session-tree-event-targets.mjs";
30
31
  import {
31
32
  readSessionSummaryPreferences,
32
33
  supportedSessionSummaryThinkingLevels,
@@ -1184,12 +1185,17 @@ function makeHttpError(statusCode, message) {
1184
1185
  }
1185
1186
 
1186
1187
  function sendError(res, statusCode, error) {
1187
- const message = statusCode >= 500 ? sanitizeError(error) : formatCliError(error);
1188
+ const message = error?.gitWorkflowGeneration
1189
+ ? "Guided Git generation failed after the configured model attempts."
1190
+ : statusCode >= 500 ? sanitizeError(error) : formatCliError(error);
1188
1191
  const payload = { ok: false, error: message };
1189
1192
  const isThemeError = typeof error?.code === "string" && error.code.startsWith("THEME_");
1190
1193
  if (isThemeError) payload.code = error.code;
1191
1194
  if (isThemeError && error?.details && typeof error.details === "object") payload.details = error.details;
1192
1195
  if (error?.optionalFeatureInstall) payload.optionalFeatureInstall = error.optionalFeatureInstall;
1196
+ if (error?.gitWorkflowGeneration && typeof error.gitWorkflowGeneration === "object") {
1197
+ payload.gitWorkflowGeneration = error.gitWorkflowGeneration;
1198
+ }
1193
1199
  sendJson(res, statusCode, payload);
1194
1200
  }
1195
1201
 
@@ -2889,6 +2895,7 @@ function requireGitWorkflowBoolean(value, key) {
2889
2895
  async function saveGitWorkflowPreferencesData(tab, body = {}) {
2890
2896
  const submitted = body.preferences && typeof body.preferences === "object" ? body.preferences : body;
2891
2897
  if (submitted.generation?.thinkingLevel !== undefined) requireGitWorkflowChoice(submitted.generation.thinkingLevel, "generation.thinkingLevel", GIT_WORKFLOW_THINKING_LEVELS);
2898
+ if (submitted.generation?.fallback?.thinkingLevel !== undefined) requireGitWorkflowChoice(submitted.generation.fallback.thinkingLevel, "generation.fallback.thinkingLevel", GIT_WORKFLOW_THINKING_LEVELS);
2892
2899
  if (submitted.commit?.language !== undefined) requireGitWorkflowChoice(submitted.commit.language, "commit.language", GIT_WORKFLOW_LANGUAGES);
2893
2900
  if (submitted.commit?.defaultVariant !== undefined) requireGitWorkflowChoice(submitted.commit.defaultVariant, "commit.defaultVariant", GIT_WORKFLOW_DEFAULT_VARIANTS);
2894
2901
  if (submitted.commit?.scope !== undefined) requireGitWorkflowChoice(submitted.commit.scope, "commit.scope", GIT_WORKFLOW_SCOPE_POLICIES);
@@ -2911,6 +2918,19 @@ async function saveGitWorkflowPreferencesData(tab, body = {}) {
2911
2918
  throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${next.generation.thinkingLevel}`);
2912
2919
  }
2913
2920
 
2921
+ const fallbackProvider = String(next.generation.fallback?.provider || "").trim();
2922
+ const fallbackModelId = String(next.generation.fallback?.modelId || "").trim();
2923
+ if (!!fallbackProvider !== !!fallbackModelId) throw makeHttpError(400, "Select both a fallback provider and model, or clear both to disable fallback");
2924
+ if (fallbackProvider && fallbackModelId) {
2925
+ if (fallbackProvider === provider && fallbackModelId === modelId) throw makeHttpError(400, "The fallback model must be different from the primary Git-writing model");
2926
+ const fallbackModel = models.find((candidate) => candidate.provider === fallbackProvider && candidate.id === fallbackModelId);
2927
+ if (!fallbackModel) throw makeHttpError(400, `Selected fallback model is not currently available: ${fallbackProvider}/${fallbackModelId}`);
2928
+ const fallbackSupportedLevels = supportedGitWorkflowThinkingLevels(fallbackModel);
2929
+ if (!fallbackSupportedLevels.includes(next.generation.fallback.thinkingLevel)) {
2930
+ throw makeHttpError(400, `${fallbackProvider}/${fallbackModelId} does not support fallback thinking level ${next.generation.fallback.thinkingLevel}`);
2931
+ }
2932
+ }
2933
+
2914
2934
  await writeGitWorkflowPreferences(next);
2915
2935
  return gitWorkflowPreferencesData(tab);
2916
2936
  }
@@ -3094,27 +3114,79 @@ function gitWorkflowGenerationPrompt(kind, preferences) {
3094
3114
  }
3095
3115
  }
3096
3116
 
3097
- async function restoreGitWorkflowGenerationProfile(tab) {
3098
- const restore = tab?.gitWorkflowGenerationRestore;
3117
+ function boundedGitWorkflowGenerationError(message, fallback = "Guided Git generation failed") {
3118
+ const text = typeof message === "string" ? message : fallback;
3119
+ return text.replace(/[\r\n]+/g, " ").trim().slice(0, 240) || fallback;
3120
+ }
3121
+
3122
+ function gitWorkflowGenerationCancellationError() {
3123
+ const error = makeHttpError(409, "Guided Git generation was cancelled");
3124
+ error.code = "GIT_WORKFLOW_CANCELLED";
3125
+ return error;
3126
+ }
3127
+
3128
+ function assertGitWorkflowGenerationOwnership(tab, record) {
3129
+ if (tab.gitWorkflowGeneration !== record) throw new Error("Guided Git generation is no longer active");
3130
+ if (record.cancelled) throw gitWorkflowGenerationCancellationError();
3131
+ }
3132
+
3133
+ function attachGitWorkflowGenerationError(error, record) {
3134
+ if (!error || typeof error !== "object" || !record?.generationId || !record.fallbackStarted || record.cancelled || record.processLost) return error;
3135
+ error.gitWorkflowGeneration = {
3136
+ generationId: record.generationId,
3137
+ kind: record.kind,
3138
+ fallbackUsed: record.fallbackStarted === true,
3139
+ generation: publicGitWorkflowGenerationProfile(record.fallbackStarted && record.fallback ? record.fallback : record.primary),
3140
+ primaryGeneration: publicGitWorkflowGenerationProfile(record.primary),
3141
+ };
3142
+ return error;
3143
+ }
3144
+
3145
+ function gitWorkflowGenerationProfile(provider, modelId, thinkingLevel, models) {
3146
+ const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId) || null;
3147
+ return { provider, modelId, thinkingLevel, model };
3148
+ }
3149
+
3150
+ function publicGitWorkflowGenerationProfile(profile) {
3151
+ return {
3152
+ provider: String(profile?.provider || ""),
3153
+ modelId: String(profile?.modelId || ""),
3154
+ thinkingLevel: String(profile?.thinkingLevel || ""),
3155
+ };
3156
+ }
3157
+
3158
+ async function restoreGitWorkflowGenerationProfile(tab, expectedRecord = tab?.gitWorkflowGeneration) {
3159
+ const record = expectedRecord && tab?.gitWorkflowGeneration === expectedRecord ? expectedRecord : null;
3160
+ const restore = record?.restore || tab?.gitWorkflowGenerationRestore;
3099
3161
  if (!restore) return;
3100
- tab.gitWorkflowGenerationRestore = null;
3101
- try {
3102
- if (!tab.rpc?.isRunning?.()) return;
3103
- if (restore.model?.provider && restore.model?.id) {
3104
- const modelResponse = await tab.rpc.send({ type: "set_model", provider: restore.model.provider, modelId: restore.model.id });
3105
- if (modelResponse.success === false) throw new Error(modelResponse.error || "Failed to restore model");
3106
- }
3107
- if (restore.thinkingLevel) {
3108
- const thinkingResponse = await setThinkingLevelForTab(tab, restore.thinkingLevel, { allowPending: false });
3109
- if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || "Failed to restore thinking level");
3162
+ if (record?.restorePromise) return record.restorePromise;
3163
+ const operation = (async () => {
3164
+ try {
3165
+ if (!tab.rpc?.isRunning?.()) return;
3166
+ if (restore.model?.provider && restore.model?.id) {
3167
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: restore.model.provider, modelId: restore.model.id });
3168
+ if (modelResponse.success === false) throw new Error(modelResponse.error || "Failed to restore model");
3169
+ }
3170
+ if (restore.thinkingLevel) {
3171
+ const thinkingResponse = await setThinkingLevelForTab(tab, restore.thinkingLevel, { allowPending: false });
3172
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || "Failed to restore thinking level");
3173
+ }
3174
+ recordEvent({ type: "git_workflow_generation_profile_restored", tabId: tab.id, tabTitle: tab.title });
3175
+ } catch (error) {
3176
+ console.error(`[guided-git] failed to restore generation profile for ${record?.generationId || tab.id}: ${sanitizeError(error)}`);
3177
+ recordEvent({ type: "git_workflow_generation_profile_restore_failed", tabId: tab.id, tabTitle: tab.title, error: boundedGitWorkflowGenerationError("Guided Git could not restore the previous model profile.") });
3178
+ } finally {
3179
+ if (!record || tab.gitWorkflowGeneration === record) {
3180
+ tab.gitWorkflowGeneration = null;
3181
+ tab.gitWorkflowGenerationRestore = null;
3182
+ }
3110
3183
  }
3111
- recordEvent({ type: "git_workflow_generation_profile_restored", tabId: tab.id, tabTitle: tab.title });
3112
- } catch (error) {
3113
- recordEvent({ type: "git_workflow_generation_profile_restore_failed", tabId: tab.id, tabTitle: tab.title, error: sanitizeError(error) });
3114
- }
3184
+ })();
3185
+ if (record) record.restorePromise = operation;
3186
+ return operation;
3115
3187
  }
3116
3188
 
3117
- async function createGitWorkflowMessageGeneration(tab) {
3189
+ async function createGitWorkflowMessageGeneration(tab, generationId) {
3118
3190
  // Keep generation dispatch backward-compatible for tabs whose cwd has not
3119
3191
  // become a repository yet; the Guided Git flow itself still verifies Git
3120
3192
  // state at its staging/review boundaries.
@@ -3122,68 +3194,256 @@ async function createGitWorkflowMessageGeneration(tab) {
3122
3194
  const cwd = gitWorkflowMessageCwd(root, tab.cwd);
3123
3195
  const paths = commitMessagePaths(cwd);
3124
3196
  return {
3125
- id: randomUUID(),
3197
+ id: generationId,
3126
3198
  kind: "commit",
3127
3199
  root,
3128
3200
  cwd,
3129
3201
  createdAt: Date.now(),
3130
3202
  baseline: await readStableGitMessageArtifactPair(paths),
3203
+ terminal: false,
3204
+ successful: false,
3205
+ };
3206
+ }
3207
+
3208
+ function emitGitWorkflowFallbackLifecycle(tab, record, phase) {
3209
+ const event = {
3210
+ type: `webui_git_workflow_generation_fallback_${phase}`,
3211
+ tabId: tab.id,
3212
+ tabTitle: tab.title,
3213
+ generationId: record.generationId,
3214
+ kind: record.kind,
3215
+ generation: publicGitWorkflowGenerationProfile(record.fallback),
3216
+ primaryGeneration: publicGitWorkflowGenerationProfile(record.primary),
3217
+ ...(phase === "started"
3218
+ ? { reason: boundedGitWorkflowGenerationError("The primary Git-writing model ended with an error.") }
3219
+ : { error: boundedGitWorkflowGenerationError("The fallback Git-writing model ended with an error.") }),
3220
+ };
3221
+ const lifecycle = tab.gitWorkflowFallbackLifecycle;
3222
+ if (lifecycle?.generationId === record.generationId) {
3223
+ lifecycle.events = [...lifecycle.events.filter((item) => item.type !== event.type), event].slice(-2);
3224
+ }
3225
+ broadcastTabEvent(tab, event);
3226
+ }
3227
+
3228
+ function replayGitWorkflowFallbackLifecycle(tab, client) {
3229
+ const lifecycle = tab.gitWorkflowFallbackLifecycle;
3230
+ for (const event of lifecycle?.events || []) sendSseToClient(client, { ...event, replayed: true });
3231
+ }
3232
+
3233
+ async function finishGitWorkflowGeneration(tab, record, { successful }) {
3234
+ if (tab.gitWorkflowGeneration !== record || record.finishing) return;
3235
+ record.finishing = true;
3236
+ const artifactGeneration = record.artifactGeneration;
3237
+ if (artifactGeneration && tab.gitWorkflowArtifactGeneration === artifactGeneration) {
3238
+ artifactGeneration.terminal = true;
3239
+ artifactGeneration.successful = successful === true && !record.cancelled;
3240
+ }
3241
+ if (!successful && record.messageGeneration && tab.gitWorkflowMessageGeneration?.id === record.messageGeneration.id) {
3242
+ tab.gitWorkflowMessageGeneration = record.previousMessageGeneration;
3243
+ }
3244
+ markTabIdle(tab);
3245
+ await restoreGitWorkflowGenerationProfile(tab, record);
3246
+ }
3247
+
3248
+ async function dispatchGitWorkflowGenerationAttempt(tab, record, profile, attempt) {
3249
+ assertGitWorkflowGenerationOwnership(tab, record);
3250
+ if (!tab.rpc?.isRunning?.()) throw new Error("Pi RPC process is not running");
3251
+ if (!profile.model) throw new Error(`Configured ${attempt} Git-writing model is unavailable: ${profile.provider}/${profile.modelId}`);
3252
+ if (!supportedGitWorkflowThinkingLevels(profile.model).includes(profile.thinkingLevel)) {
3253
+ throw new Error(`Configured ${attempt} thinking level ${profile.thinkingLevel} is unavailable for ${profile.provider}/${profile.modelId}`);
3254
+ }
3255
+
3256
+ record.attempt = attempt;
3257
+ record.attemptRunStarted = false;
3258
+ record.promptAccepted = false;
3259
+ record.pendingSettlement = null;
3260
+ if (record.currentModelKey !== `${profile.provider}/${profile.modelId}`) {
3261
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: profile.provider, modelId: profile.modelId });
3262
+ assertGitWorkflowGenerationOwnership(tab, record);
3263
+ if (modelResponse.success === false) throw new Error(modelResponse.error || `Failed to select ${profile.provider}/${profile.modelId}`);
3264
+ record.currentModelKey = `${profile.provider}/${profile.modelId}`;
3265
+ }
3266
+ const thinkingResponse = await setThinkingLevelForTab(tab, profile.thinkingLevel, { allowPending: false });
3267
+ assertGitWorkflowGenerationOwnership(tab, record);
3268
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${profile.thinkingLevel}`);
3269
+
3270
+ assertGitWorkflowGenerationOwnership(tab, record);
3271
+ markTabWorking(tab);
3272
+ const response = await tab.rpc.send({ type: "prompt", message: record.message });
3273
+ assertGitWorkflowGenerationOwnership(tab, record);
3274
+ if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
3275
+ record.promptAccepted = true;
3276
+ const pendingSettlement = record.pendingSettlement;
3277
+ if (pendingSettlement?.attempt === attempt) {
3278
+ record.pendingSettlement = null;
3279
+ void settleGitWorkflowGeneration(tab, record, pendingSettlement);
3280
+ }
3281
+ return {
3282
+ accepted: true,
3283
+ kind: record.kind,
3284
+ message: record.message,
3285
+ generationId: record.generationId,
3286
+ generation: publicGitWorkflowGenerationProfile(profile),
3287
+ fallbackUsed: attempt === "fallback",
3288
+ primaryGeneration: publicGitWorkflowGenerationProfile(record.primary),
3131
3289
  };
3132
3290
  }
3133
3291
 
3292
+ async function startGitWorkflowFallback(tab, record, primaryError) {
3293
+ if (tab.gitWorkflowGeneration !== record || record.fallbackStarted || !record.fallback) return null;
3294
+ if (record.cancelled || !tab.rpc?.isRunning?.()) return null;
3295
+ record.fallbackStarted = true;
3296
+ record.attempt = "fallback";
3297
+ record.attemptRunStarted = false;
3298
+ record.promptAccepted = false;
3299
+ console.error(`[guided-git] primary generation ${record.generationId} failed; starting fallback: ${sanitizeError(primaryError)}`);
3300
+ emitGitWorkflowFallbackLifecycle(tab, record, "started");
3301
+ try {
3302
+ return await dispatchGitWorkflowGenerationAttempt(tab, record, record.fallback, "fallback");
3303
+ } catch (error) {
3304
+ if (!record.cancelled && tab.gitWorkflowGeneration === record) {
3305
+ console.error(`[guided-git] fallback generation ${record.generationId} failed: ${sanitizeError(error)}`);
3306
+ emitGitWorkflowFallbackLifecycle(tab, record, "failed");
3307
+ }
3308
+ await finishGitWorkflowGeneration(tab, record, { successful: false });
3309
+ throw error;
3310
+ }
3311
+ }
3312
+
3313
+ async function settleGitWorkflowGeneration(tab, record, { failed, cancelled }) {
3314
+ if (tab.gitWorkflowGeneration !== record || record.finishing) return;
3315
+ if (cancelled) record.cancelled = true;
3316
+ if (record.attempt === "primary" && failed && !record.cancelled && record.fallback) {
3317
+ try {
3318
+ await startGitWorkflowFallback(tab, record, "The primary Git-writing model ended with an error");
3319
+ } catch {
3320
+ // startGitWorkflowFallback emitted the bounded terminal lifecycle event.
3321
+ }
3322
+ return;
3323
+ }
3324
+ if (record.attempt === "fallback" && failed) {
3325
+ emitGitWorkflowFallbackLifecycle(tab, record, "failed");
3326
+ }
3327
+ await finishGitWorkflowGeneration(tab, record, { successful: !failed && !record.cancelled });
3328
+ }
3329
+
3330
+ function consumeGitWorkflowGenerationEvent(tab, event, { finalError = false } = {}) {
3331
+ const record = tab.gitWorkflowGeneration;
3332
+ if (!record || record.finishing) return;
3333
+ if ((event?.type === "agent_end" || event?.type === "agent_settled") && event.aborted === true) record.cancelled = true;
3334
+ if (event?.type === "agent_start") {
3335
+ record.attemptRunStarted = true;
3336
+ return;
3337
+ }
3338
+ if (event?.type !== "agent_settled" || !record.attemptRunStarted) return;
3339
+ record.attemptRunStarted = false;
3340
+ const settlement = { attempt: record.attempt, failed: finalError, cancelled: record.cancelled };
3341
+ if (!record.promptAccepted) {
3342
+ record.pendingSettlement = settlement;
3343
+ return;
3344
+ }
3345
+ void settleGitWorkflowGeneration(tab, record, settlement);
3346
+ }
3347
+
3134
3348
  async function startGitWorkflowGeneration(tab, body = {}) {
3135
- if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
3136
- // Browser state is untrusted. When it claims an approved content token,
3137
- // verify the exact current index again at this server action boundary.
3138
- await assertExpectedStagedContentHash(tab, body);
3139
- const preferences = await readGitWorkflowPreferences();
3140
- if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
3349
+ if (tab.gitWorkflowGeneration || tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
3141
3350
  const kind = String(body.kind || "").trim();
3142
- const message = gitWorkflowGenerationPrompt(kind, preferences);
3351
+ if (!new Set(["commit", "branch", "pr"]).has(kind)) throw makeHttpError(400, "generation kind must be commit, branch, or pr");
3352
+
3353
+ // Reserve the tab synchronously before the first await. All preflight and
3354
+ // profile transitions retain this exact object as their ownership token.
3355
+ const record = {
3356
+ generationId: randomUUID(),
3357
+ kind,
3358
+ message: "",
3359
+ restore: null,
3360
+ previousMessageGeneration: tab.gitWorkflowMessageGeneration || null,
3361
+ messageGeneration: null,
3362
+ artifactGeneration: null,
3363
+ primary: null,
3364
+ fallback: null,
3365
+ fallbackStarted: false,
3366
+ cancelled: false,
3367
+ finishing: false,
3368
+ attempt: "primary",
3369
+ attemptRunStarted: false,
3370
+ promptAccepted: false,
3371
+ pendingSettlement: null,
3372
+ currentModelKey: "",
3373
+ };
3374
+ tab.gitWorkflowGeneration = record;
3375
+ tab.gitWorkflowFallbackLifecycle = { generationId: record.generationId, kind, events: [] };
3143
3376
 
3144
- const state = await currentSessionState(tab);
3145
- if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
3146
- const models = await availableGitWorkflowModels(tab);
3147
- const selectedModel = models.find((model) => model.provider === preferences.generation.provider && model.id === preferences.generation.modelId);
3148
- if (!selectedModel) throw makeHttpError(409, `Configured Git-writing model is unavailable: ${preferences.generation.provider}/${preferences.generation.modelId}. Open Guided Git Setup to choose another model.`);
3149
- const supportedLevels = supportedGitWorkflowThinkingLevels(selectedModel);
3150
- if (!supportedLevels.includes(preferences.generation.thinkingLevel)) {
3151
- throw makeHttpError(409, `Configured thinking level ${preferences.generation.thinkingLevel} is unavailable for ${gitWorkflowModelKey(selectedModel)}. Open Guided Git Setup to update it.`);
3152
- }
3153
-
3154
- const restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
3155
- const previousMessageGeneration = tab.gitWorkflowMessageGeneration || null;
3156
- const messageGeneration = kind === "commit" ? await createGitWorkflowMessageGeneration(tab) : null;
3157
- tab.gitWorkflowGenerationRestore = restore;
3158
- if (messageGeneration) tab.gitWorkflowMessageGeneration = messageGeneration;
3159
3377
  try {
3160
- if (gitWorkflowModelKey(state.model) !== gitWorkflowModelKey(selectedModel)) {
3161
- const modelResponse = await tab.rpc.send({ type: "set_model", provider: selectedModel.provider, modelId: selectedModel.id });
3162
- if (modelResponse.success === false) throw new Error(modelResponse.error || `Failed to select ${gitWorkflowModelKey(selectedModel)}`);
3163
- }
3164
- const thinkingResponse = await setThinkingLevelForTab(tab, preferences.generation.thinkingLevel, { allowPending: false });
3165
- if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${preferences.generation.thinkingLevel}`);
3378
+ // Browser state is untrusted. When it claims an approved content token,
3379
+ // verify the exact current index again at this server action boundary.
3380
+ await assertExpectedStagedContentHash(tab, body);
3381
+ assertGitWorkflowGenerationOwnership(tab, record);
3382
+ const preferences = await readGitWorkflowPreferences();
3383
+ assertGitWorkflowGenerationOwnership(tab, record);
3384
+ if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
3385
+ record.message = gitWorkflowGenerationPrompt(kind, preferences);
3386
+
3387
+ const state = await currentSessionState(tab);
3388
+ assertGitWorkflowGenerationOwnership(tab, record);
3389
+ if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
3390
+ const models = await availableGitWorkflowModels(tab);
3391
+ assertGitWorkflowGenerationOwnership(tab, record);
3392
+ record.primary = gitWorkflowGenerationProfile(
3393
+ preferences.generation.provider,
3394
+ preferences.generation.modelId,
3395
+ preferences.generation.thinkingLevel,
3396
+ models,
3397
+ );
3398
+ const fallbackConfigured = !!preferences.generation.fallback?.provider
3399
+ && !!preferences.generation.fallback?.modelId
3400
+ && (preferences.generation.fallback.provider !== preferences.generation.provider
3401
+ || preferences.generation.fallback.modelId !== preferences.generation.modelId);
3402
+ record.fallback = fallbackConfigured
3403
+ ? gitWorkflowGenerationProfile(
3404
+ preferences.generation.fallback.provider,
3405
+ preferences.generation.fallback.modelId,
3406
+ preferences.generation.fallback.thinkingLevel,
3407
+ models,
3408
+ )
3409
+ : null;
3166
3410
 
3167
- markTabWorking(tab);
3168
- const response = await tab.rpc.send({ type: "prompt", message });
3169
- if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
3170
- return {
3171
- accepted: true,
3411
+ record.restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
3412
+ record.currentModelKey = gitWorkflowModelKey(state.model);
3413
+ tab.gitWorkflowGenerationRestore = record.restore;
3414
+ record.messageGeneration = kind === "commit" ? await createGitWorkflowMessageGeneration(tab, record.generationId) : null;
3415
+ assertGitWorkflowGenerationOwnership(tab, record);
3416
+ record.artifactGeneration = record.messageGeneration || {
3417
+ id: record.generationId,
3172
3418
  kind,
3173
- message,
3174
- generationId: messageGeneration?.id || "",
3175
- generation: {
3176
- provider: selectedModel.provider,
3177
- modelId: selectedModel.id,
3178
- thinkingLevel: preferences.generation.thinkingLevel,
3179
- },
3419
+ cwd: path.resolve(tab.cwd),
3420
+ createdAt: Date.now(),
3421
+ terminal: false,
3422
+ successful: false,
3180
3423
  };
3424
+ tab.gitWorkflowArtifactGeneration = record.artifactGeneration;
3425
+ if (record.messageGeneration) tab.gitWorkflowMessageGeneration = record.messageGeneration;
3426
+
3427
+ try {
3428
+ return await dispatchGitWorkflowGenerationAttempt(tab, record, record.primary, "primary");
3429
+ } catch (primaryError) {
3430
+ markTabIdle(tab);
3431
+ if (record.fallback && !record.cancelled && tab.rpc?.isRunning?.()) {
3432
+ try {
3433
+ const fallbackResult = await startGitWorkflowFallback(tab, record, primaryError);
3434
+ if (fallbackResult) return fallbackResult;
3435
+ } catch (fallbackError) {
3436
+ throw attachGitWorkflowGenerationError(fallbackError, record);
3437
+ }
3438
+ }
3439
+ await finishGitWorkflowGeneration(tab, record, { successful: false });
3440
+ throw attachGitWorkflowGenerationError(primaryError, record);
3441
+ }
3181
3442
  } catch (error) {
3182
- if (messageGeneration && tab.gitWorkflowMessageGeneration?.id === messageGeneration.id) {
3183
- tab.gitWorkflowMessageGeneration = previousMessageGeneration;
3443
+ if (tab.gitWorkflowGeneration === record && !record.finishing) {
3444
+ if (record.restore) await finishGitWorkflowGeneration(tab, record, { successful: false });
3445
+ else tab.gitWorkflowGeneration = null;
3184
3446
  }
3185
- markTabIdle(tab);
3186
- await restoreGitWorkflowGenerationProfile(tab);
3187
3447
  throw error;
3188
3448
  }
3189
3449
  }
@@ -7403,7 +7663,17 @@ function commitMessagePaths(baseDir) {
7403
7663
  };
7404
7664
  }
7405
7665
 
7406
- async function readGitWorkflowBranchName(cwd) {
7666
+ function assertGitWorkflowArtifactGenerationReady(generationId, generation, kind) {
7667
+ if (!generationId) return;
7668
+ if (!generation || generation.id !== generationId || generation.kind !== kind) {
7669
+ throw new Error(`This ${kind} generation is no longer active. Regenerate the artifact.`);
7670
+ }
7671
+ if (!generation.terminal) throw new Error(`The correlated ${kind} generation is still running.`);
7672
+ if (!generation.successful) throw new Error(`The correlated ${kind} generation did not finish successfully. Regenerate the artifact.`);
7673
+ }
7674
+
7675
+ async function readGitWorkflowBranchName(cwd, { generationId = "", generation = null } = {}) {
7676
+ assertGitWorkflowArtifactGenerationReady(generationId, generation, "branch");
7407
7677
  const root = await getGitRoot(cwd);
7408
7678
  const messageCwd = gitWorkflowMessageCwd(root, cwd);
7409
7679
  const { branchPath } = commitMessagePaths(messageCwd);
@@ -7446,6 +7716,12 @@ async function readGitWorkflowMessages(cwd, { generationId = "", generation = nu
7446
7716
  if (generationId && (!generation || generation.id !== generationId || generation.kind !== "commit" || generation.cwd !== messageCwd)) {
7447
7717
  return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "This commit-message generation is no longer active. Regenerate the message files.", { expired: true });
7448
7718
  }
7719
+ if (generationId && !generation.terminal) {
7720
+ return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "The correlated commit-message generation is still running.");
7721
+ }
7722
+ if (generationId && !generation.successful) {
7723
+ return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "The correlated commit-message generation did not finish successfully. Regenerate the message files.", { expired: true });
7724
+ }
7449
7725
  try {
7450
7726
  let pair = await readStableGitMessageArtifactPair(paths);
7451
7727
  if (generationId) {
@@ -8188,7 +8464,8 @@ function prDescriptionPath(root, branch) {
8188
8464
  return { base, prPath: target };
8189
8465
  }
8190
8466
 
8191
- async function readGitWorkflowPrDescription(cwd) {
8467
+ async function readGitWorkflowPrDescription(cwd, { generationId = "", generation = null } = {}) {
8468
+ assertGitWorkflowArtifactGenerationReady(generationId, generation, "pr");
8192
8469
  const root = await getGitRoot(cwd);
8193
8470
  const branch = await currentGitBranch(root);
8194
8471
  const { prPath } = prDescriptionPath(root, branch);
@@ -8345,14 +8622,18 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
8345
8622
  case "/api/git-workflow/message": {
8346
8623
  const generationId = String(body.generationId || "").trim();
8347
8624
  if (generationId && !tab) throw new Error("Fresh commit-message lookup requires a Web UI tab");
8348
- return { ok: true, data: await readGitWorkflowMessages(cwd, { generationId, generation: tab?.gitWorkflowMessageGeneration || null }) };
8625
+ return { ok: true, data: await readGitWorkflowMessages(cwd, { generationId, generation: tab?.gitWorkflowArtifactGeneration || null }) };
8349
8626
  }
8350
8627
  case "/api/git-workflow/default-commit-message":
8351
8628
  return { ok: true, data: await readGitWorkflowDefaultCommitMessage(cwd) };
8352
- case "/api/git-workflow/branch-name":
8353
- return { ok: true, data: await readGitWorkflowBranchName(cwd) };
8354
- case "/api/git-workflow/pr-description":
8355
- return { ok: true, data: await readGitWorkflowPrDescription(cwd) };
8629
+ case "/api/git-workflow/branch-name": {
8630
+ const generationId = String(body.generationId || "").trim();
8631
+ return { ok: true, data: await readGitWorkflowBranchName(cwd, { generationId, generation: tab?.gitWorkflowArtifactGeneration || null }) };
8632
+ }
8633
+ case "/api/git-workflow/pr-description": {
8634
+ const generationId = String(body.generationId || "").trim();
8635
+ return { ok: true, data: await readGitWorkflowPrDescription(cwd, { generationId, generation: tab?.gitWorkflowArtifactGeneration || null }) };
8636
+ }
8356
8637
  case "/api/git-workflow/init":
8357
8638
  await ensureOutsideGitRepository(cwd);
8358
8639
  return gitMutationPayload(await runGitMutationCommand(["init"], { cwd }));
@@ -8485,7 +8766,9 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
8485
8766
  return payload;
8486
8767
  }
8487
8768
  case "/api/git-workflow/cancel": {
8488
- const cancelled = !!activeGitWorkflowProcess;
8769
+ const generation = tab?.gitWorkflowGeneration || null;
8770
+ if (generation) generation.cancelled = true;
8771
+ const cancelled = !!activeGitWorkflowProcess || !!generation;
8489
8772
  if (activeGitWorkflowProcess) activeGitWorkflowProcess.cancel();
8490
8773
  return { ok: true, data: { cancelled } };
8491
8774
  }
@@ -10996,9 +11279,16 @@ function attachRpcToTab(tab, rpc) {
10996
11279
  tab.rpcUnsubscribe = rpc.onEvent((rawEvent) => {
10997
11280
  const event = tab.thinkingStreamRecovery.ingest(rawEvent);
10998
11281
  if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event) || consumeSessionSummaryRpcEvent(tab, event)) return;
11282
+ const gitWorkflowFinalError = event?.type === "agent_settled" && tab.pendingTurnFailure === true;
10999
11283
  updateTabActivityFromEvent(tab, event);
11000
11284
  let scopedEvent = eventForTabClients(tab, event);
11001
11285
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
11286
+ if (tab.gitWorkflowGeneration) tab.gitWorkflowGeneration.processLost = true;
11287
+ if (tab.gitWorkflowArtifactGeneration) {
11288
+ tab.gitWorkflowArtifactGeneration.terminal = true;
11289
+ tab.gitWorkflowArtifactGeneration.successful = false;
11290
+ }
11291
+ tab.gitWorkflowGeneration = null;
11002
11292
  tab.gitWorkflowGenerationRestore = null;
11003
11293
  tab.gitWorkflowMessageGeneration = null;
11004
11294
  clearPendingExtensionUiRequests(tab);
@@ -11017,7 +11307,7 @@ function attachRpcToTab(tab, rpc) {
11017
11307
  recordEvent(scopedEvent);
11018
11308
  for (const client of tab.sseClients) sendSseToClient(client, scopedEvent);
11019
11309
  if (event?.type === "compaction_end") void flushCompactionQueue(tab, event);
11020
- if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
11310
+ consumeGitWorkflowGenerationEvent(tab, event, { finalError: gitWorkflowFinalError });
11021
11311
  });
11022
11312
  }
11023
11313
 
@@ -11035,8 +11325,11 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
11035
11325
  lastState: null,
11036
11326
  pendingThinkingLevel: undefined,
11037
11327
  thinkingStreamRecovery: new ThinkingStreamRecovery(),
11328
+ gitWorkflowGeneration: null,
11038
11329
  gitWorkflowGenerationRestore: null,
11039
11330
  gitWorkflowMessageGeneration: null,
11331
+ gitWorkflowArtifactGeneration: null,
11332
+ gitWorkflowFallbackLifecycle: null,
11040
11333
  activity: createTabActivity(createdAt),
11041
11334
  pendingExtensionUiRequests: new Map(),
11042
11335
  extensionStatuses: new Map(),
@@ -14577,6 +14870,7 @@ async function getSessionTreeData(tab) {
14577
14870
  cwd: manager.getCwd(),
14578
14871
  leafId,
14579
14872
  nodes: flattenSessionTree(manager.getTree(), { leafId }),
14873
+ eventTargets: sessionTreeEventTargets(manager.getEntries()),
14580
14874
  };
14581
14875
  }
14582
14876
 
@@ -16148,6 +16442,7 @@ const server = createServer(async (req, res) => {
16148
16442
  }
16149
16443
  replayExtensionStatuses(tab, client);
16150
16444
  replayExtensionWidgets(tab, client);
16445
+ replayGitWorkflowFallbackLifecycle(tab, client);
16151
16446
  if (tab.sessionSummary) {
16152
16447
  sendSseToClient(client, {
16153
16448
  type: "webui_session_summary",