@firstpick/pi-package-webui 0.9.6 → 0.9.8

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 (70) hide show
  1. package/README.md +13 -5
  2. package/bin/pi-webui.mjs +480 -96
  3. package/index.ts +2 -1
  4. package/lib/git-workflow-preferences.mjs +21 -1
  5. package/lib/optional-feature-catalog.mjs +1 -1
  6. package/lib/session-tree-event-targets.mjs +70 -0
  7. package/lib/subagent-launch-policy.mjs +375 -0
  8. package/lib/subagent-launch-slots.mjs +2 -1
  9. package/package.json +1 -1
  10. package/public/app.js +1348 -131
  11. package/public/guided-git-command-state.mjs +175 -1
  12. package/public/index.html +48 -9
  13. package/public/service-worker.js +1 -1
  14. package/public/styles.css +387 -34
  15. package/public/transcript-renderer.mjs +62 -0
  16. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  17. package/tests/browser/control-visibility.spec.mjs +141 -2
  18. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  19. package/tests/browser/footer-model-advanced-layout.spec.mjs +512 -0
  20. package/tests/browser/guided-git-extension-command.spec.mjs +180 -0
  21. package/tests/browser/guided-git-fallback.spec.mjs +218 -0
  22. package/tests/browser/interaction-continuity.spec.mjs +33 -0
  23. package/tests/codex-fast-mode-static.test.mjs +2 -2
  24. package/tests/compact-sections-static.test.mjs +4 -0
  25. package/tests/compaction-static.test.mjs +1 -1
  26. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  27. package/tests/control-visibility-static.test.mjs +66 -3
  28. package/tests/controls-layout-static.test.mjs +3 -3
  29. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  30. package/tests/fast-mode-client-static.test.mjs +5 -2
  31. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  32. package/tests/file-viewer-image-static.test.mjs +3 -3
  33. package/tests/fixtures/fake-pi.mjs +34 -3
  34. package/tests/git-footer-context-menu-static.test.mjs +103 -1
  35. package/tests/git-workflow-preferences.test.mjs +30 -1
  36. package/tests/guided-git-activation-http.test.mjs +194 -0
  37. package/tests/guided-git-activation-static.test.mjs +80 -0
  38. package/tests/guided-git-activation.test.mjs +244 -0
  39. package/tests/guided-git-fallback-runtime.test.mjs +419 -0
  40. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  41. package/tests/guided-git-message-reliability-static.test.mjs +9 -7
  42. package/tests/guided-git-optional-feature.test.mjs +31 -0
  43. package/tests/http-endpoints-harness.test.mjs +3 -0
  44. package/tests/interaction-state-stability-static.test.mjs +1 -1
  45. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  46. package/tests/main-output-loading-static.test.mjs +11 -9
  47. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  48. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  49. package/tests/mobile-foundation-static.test.mjs +3 -3
  50. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  51. package/tests/mobile-static.test.mjs +92 -9
  52. package/tests/open-issue-wizard-static.test.mjs +1 -1
  53. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  54. package/tests/prompt-input-vertical-scroll-static.test.mjs +6 -6
  55. package/tests/prompt-routing-input-clear-static.test.mjs +1 -1
  56. package/tests/questionnaire-dialog.test.mjs +3 -3
  57. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  58. package/tests/resource-defaults-helper.test.mjs +12 -0
  59. package/tests/session-sampling-helper.test.mjs +1 -0
  60. package/tests/session-sampling-ui-static.test.mjs +3 -3
  61. package/tests/session-tree-event-targets.test.mjs +106 -0
  62. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  63. package/tests/subagent-launch-policy.test.mjs +532 -0
  64. package/tests/subagent-observability-static.test.mjs +2 -2
  65. package/tests/subagents-helper.test.mjs +211 -1
  66. package/tests/syntax-highlighting-static.test.mjs +3 -3
  67. package/tests/tab-close-continuity-static.test.mjs +25 -0
  68. package/tests/theme-customizer-static.test.mjs +1 -1
  69. package/tests/thinking-block-grouping.test.mjs +79 -0
  70. package/webui-rpc-helper.mjs +220 -3
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,
@@ -449,6 +450,12 @@ let optionalFeatureStartupReady = false;
449
450
  const UPDATE_PACKAGE_NAMES = [...CORE_UPDATE_PACKAGE_NAMES].sort();
450
451
  const NATURAL_CONVERSATION_STATUS_KEY = "natural-conversation";
451
452
  const NATURAL_CONVERSATION_COMMAND_NAMES = ["talk", "voice", "conversation"];
453
+ const GUIDED_GIT_START_STATUS_KEY = "git-guided-workflow:webui-start";
454
+ const GUIDED_GIT_START_PAYLOAD_TYPE = "firstpick.pi-extension-git-guided-workflow.start";
455
+ const GUIDED_GIT_START_PAYLOAD_VERSION = 1;
456
+ const GUIDED_GIT_LAUNCH_TTL_MS = 15_000;
457
+ const GUIDED_GIT_UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
458
+ const GUIDED_GIT_COMMAND_MESSAGE = /^\/git-guided-workflow(?::\d+)?$/u;
452
459
  // Codex subscription Fast mode is owned by the optional @firstpick/pi-extension-codex-fast-mode
453
460
  // package. The Web UI never inspects ChatGPT credentials or request payloads; it only mirrors the
454
461
  // extension-published status key and drives the package-owned /fast-mode command over RPC.
@@ -1184,12 +1191,17 @@ function makeHttpError(statusCode, message) {
1184
1191
  }
1185
1192
 
1186
1193
  function sendError(res, statusCode, error) {
1187
- const message = statusCode >= 500 ? sanitizeError(error) : formatCliError(error);
1194
+ const message = error?.gitWorkflowGeneration
1195
+ ? "Guided Git generation failed after the configured model attempts."
1196
+ : statusCode >= 500 ? sanitizeError(error) : formatCliError(error);
1188
1197
  const payload = { ok: false, error: message };
1189
1198
  const isThemeError = typeof error?.code === "string" && error.code.startsWith("THEME_");
1190
1199
  if (isThemeError) payload.code = error.code;
1191
1200
  if (isThemeError && error?.details && typeof error.details === "object") payload.details = error.details;
1192
1201
  if (error?.optionalFeatureInstall) payload.optionalFeatureInstall = error.optionalFeatureInstall;
1202
+ if (error?.gitWorkflowGeneration && typeof error.gitWorkflowGeneration === "object") {
1203
+ payload.gitWorkflowGeneration = error.gitWorkflowGeneration;
1204
+ }
1193
1205
  sendJson(res, statusCode, payload);
1194
1206
  }
1195
1207
 
@@ -2889,6 +2901,7 @@ function requireGitWorkflowBoolean(value, key) {
2889
2901
  async function saveGitWorkflowPreferencesData(tab, body = {}) {
2890
2902
  const submitted = body.preferences && typeof body.preferences === "object" ? body.preferences : body;
2891
2903
  if (submitted.generation?.thinkingLevel !== undefined) requireGitWorkflowChoice(submitted.generation.thinkingLevel, "generation.thinkingLevel", GIT_WORKFLOW_THINKING_LEVELS);
2904
+ if (submitted.generation?.fallback?.thinkingLevel !== undefined) requireGitWorkflowChoice(submitted.generation.fallback.thinkingLevel, "generation.fallback.thinkingLevel", GIT_WORKFLOW_THINKING_LEVELS);
2892
2905
  if (submitted.commit?.language !== undefined) requireGitWorkflowChoice(submitted.commit.language, "commit.language", GIT_WORKFLOW_LANGUAGES);
2893
2906
  if (submitted.commit?.defaultVariant !== undefined) requireGitWorkflowChoice(submitted.commit.defaultVariant, "commit.defaultVariant", GIT_WORKFLOW_DEFAULT_VARIANTS);
2894
2907
  if (submitted.commit?.scope !== undefined) requireGitWorkflowChoice(submitted.commit.scope, "commit.scope", GIT_WORKFLOW_SCOPE_POLICIES);
@@ -2911,6 +2924,19 @@ async function saveGitWorkflowPreferencesData(tab, body = {}) {
2911
2924
  throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${next.generation.thinkingLevel}`);
2912
2925
  }
2913
2926
 
2927
+ const fallbackProvider = String(next.generation.fallback?.provider || "").trim();
2928
+ const fallbackModelId = String(next.generation.fallback?.modelId || "").trim();
2929
+ if (!!fallbackProvider !== !!fallbackModelId) throw makeHttpError(400, "Select both a fallback provider and model, or clear both to disable fallback");
2930
+ if (fallbackProvider && fallbackModelId) {
2931
+ if (fallbackProvider === provider && fallbackModelId === modelId) throw makeHttpError(400, "The fallback model must be different from the primary Git-writing model");
2932
+ const fallbackModel = models.find((candidate) => candidate.provider === fallbackProvider && candidate.id === fallbackModelId);
2933
+ if (!fallbackModel) throw makeHttpError(400, `Selected fallback model is not currently available: ${fallbackProvider}/${fallbackModelId}`);
2934
+ const fallbackSupportedLevels = supportedGitWorkflowThinkingLevels(fallbackModel);
2935
+ if (!fallbackSupportedLevels.includes(next.generation.fallback.thinkingLevel)) {
2936
+ throw makeHttpError(400, `${fallbackProvider}/${fallbackModelId} does not support fallback thinking level ${next.generation.fallback.thinkingLevel}`);
2937
+ }
2938
+ }
2939
+
2914
2940
  await writeGitWorkflowPreferences(next);
2915
2941
  return gitWorkflowPreferencesData(tab);
2916
2942
  }
@@ -3094,27 +3120,79 @@ function gitWorkflowGenerationPrompt(kind, preferences) {
3094
3120
  }
3095
3121
  }
3096
3122
 
3097
- async function restoreGitWorkflowGenerationProfile(tab) {
3098
- const restore = tab?.gitWorkflowGenerationRestore;
3123
+ function boundedGitWorkflowGenerationError(message, fallback = "Guided Git generation failed") {
3124
+ const text = typeof message === "string" ? message : fallback;
3125
+ return text.replace(/[\r\n]+/g, " ").trim().slice(0, 240) || fallback;
3126
+ }
3127
+
3128
+ function gitWorkflowGenerationCancellationError() {
3129
+ const error = makeHttpError(409, "Guided Git generation was cancelled");
3130
+ error.code = "GIT_WORKFLOW_CANCELLED";
3131
+ return error;
3132
+ }
3133
+
3134
+ function assertGitWorkflowGenerationOwnership(tab, record) {
3135
+ if (tab.gitWorkflowGeneration !== record) throw new Error("Guided Git generation is no longer active");
3136
+ if (record.cancelled) throw gitWorkflowGenerationCancellationError();
3137
+ }
3138
+
3139
+ function attachGitWorkflowGenerationError(error, record) {
3140
+ if (!error || typeof error !== "object" || !record?.generationId || !record.fallbackStarted || record.cancelled || record.processLost) return error;
3141
+ error.gitWorkflowGeneration = {
3142
+ generationId: record.generationId,
3143
+ kind: record.kind,
3144
+ fallbackUsed: record.fallbackStarted === true,
3145
+ generation: publicGitWorkflowGenerationProfile(record.fallbackStarted && record.fallback ? record.fallback : record.primary),
3146
+ primaryGeneration: publicGitWorkflowGenerationProfile(record.primary),
3147
+ };
3148
+ return error;
3149
+ }
3150
+
3151
+ function gitWorkflowGenerationProfile(provider, modelId, thinkingLevel, models) {
3152
+ const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId) || null;
3153
+ return { provider, modelId, thinkingLevel, model };
3154
+ }
3155
+
3156
+ function publicGitWorkflowGenerationProfile(profile) {
3157
+ return {
3158
+ provider: String(profile?.provider || ""),
3159
+ modelId: String(profile?.modelId || ""),
3160
+ thinkingLevel: String(profile?.thinkingLevel || ""),
3161
+ };
3162
+ }
3163
+
3164
+ async function restoreGitWorkflowGenerationProfile(tab, expectedRecord = tab?.gitWorkflowGeneration) {
3165
+ const record = expectedRecord && tab?.gitWorkflowGeneration === expectedRecord ? expectedRecord : null;
3166
+ const restore = record?.restore || tab?.gitWorkflowGenerationRestore;
3099
3167
  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");
3168
+ if (record?.restorePromise) return record.restorePromise;
3169
+ const operation = (async () => {
3170
+ try {
3171
+ if (!tab.rpc?.isRunning?.()) return;
3172
+ if (restore.model?.provider && restore.model?.id) {
3173
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: restore.model.provider, modelId: restore.model.id });
3174
+ if (modelResponse.success === false) throw new Error(modelResponse.error || "Failed to restore model");
3175
+ }
3176
+ if (restore.thinkingLevel) {
3177
+ const thinkingResponse = await setThinkingLevelForTab(tab, restore.thinkingLevel, { allowPending: false });
3178
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || "Failed to restore thinking level");
3179
+ }
3180
+ recordEvent({ type: "git_workflow_generation_profile_restored", tabId: tab.id, tabTitle: tab.title });
3181
+ } catch (error) {
3182
+ console.error(`[guided-git] failed to restore generation profile for ${record?.generationId || tab.id}: ${sanitizeError(error)}`);
3183
+ 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.") });
3184
+ } finally {
3185
+ if (!record || tab.gitWorkflowGeneration === record) {
3186
+ tab.gitWorkflowGeneration = null;
3187
+ tab.gitWorkflowGenerationRestore = null;
3188
+ }
3110
3189
  }
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
- }
3190
+ })();
3191
+ if (record) record.restorePromise = operation;
3192
+ return operation;
3115
3193
  }
3116
3194
 
3117
- async function createGitWorkflowMessageGeneration(tab) {
3195
+ async function createGitWorkflowMessageGeneration(tab, generationId) {
3118
3196
  // Keep generation dispatch backward-compatible for tabs whose cwd has not
3119
3197
  // become a repository yet; the Guided Git flow itself still verifies Git
3120
3198
  // state at its staging/review boundaries.
@@ -3122,68 +3200,256 @@ async function createGitWorkflowMessageGeneration(tab) {
3122
3200
  const cwd = gitWorkflowMessageCwd(root, tab.cwd);
3123
3201
  const paths = commitMessagePaths(cwd);
3124
3202
  return {
3125
- id: randomUUID(),
3203
+ id: generationId,
3126
3204
  kind: "commit",
3127
3205
  root,
3128
3206
  cwd,
3129
3207
  createdAt: Date.now(),
3130
3208
  baseline: await readStableGitMessageArtifactPair(paths),
3209
+ terminal: false,
3210
+ successful: false,
3131
3211
  };
3132
3212
  }
3133
3213
 
3214
+ function emitGitWorkflowFallbackLifecycle(tab, record, phase) {
3215
+ const event = {
3216
+ type: `webui_git_workflow_generation_fallback_${phase}`,
3217
+ tabId: tab.id,
3218
+ tabTitle: tab.title,
3219
+ generationId: record.generationId,
3220
+ kind: record.kind,
3221
+ generation: publicGitWorkflowGenerationProfile(record.fallback),
3222
+ primaryGeneration: publicGitWorkflowGenerationProfile(record.primary),
3223
+ ...(phase === "started"
3224
+ ? { reason: boundedGitWorkflowGenerationError("The primary Git-writing model ended with an error.") }
3225
+ : { error: boundedGitWorkflowGenerationError("The fallback Git-writing model ended with an error.") }),
3226
+ };
3227
+ const lifecycle = tab.gitWorkflowFallbackLifecycle;
3228
+ if (lifecycle?.generationId === record.generationId) {
3229
+ lifecycle.events = [...lifecycle.events.filter((item) => item.type !== event.type), event].slice(-2);
3230
+ }
3231
+ broadcastTabEvent(tab, event);
3232
+ }
3233
+
3234
+ function replayGitWorkflowFallbackLifecycle(tab, client) {
3235
+ const lifecycle = tab.gitWorkflowFallbackLifecycle;
3236
+ for (const event of lifecycle?.events || []) sendSseToClient(client, { ...event, replayed: true });
3237
+ }
3238
+
3239
+ async function finishGitWorkflowGeneration(tab, record, { successful }) {
3240
+ if (tab.gitWorkflowGeneration !== record || record.finishing) return;
3241
+ record.finishing = true;
3242
+ const artifactGeneration = record.artifactGeneration;
3243
+ if (artifactGeneration && tab.gitWorkflowArtifactGeneration === artifactGeneration) {
3244
+ artifactGeneration.terminal = true;
3245
+ artifactGeneration.successful = successful === true && !record.cancelled;
3246
+ }
3247
+ if (!successful && record.messageGeneration && tab.gitWorkflowMessageGeneration?.id === record.messageGeneration.id) {
3248
+ tab.gitWorkflowMessageGeneration = record.previousMessageGeneration;
3249
+ }
3250
+ markTabIdle(tab);
3251
+ await restoreGitWorkflowGenerationProfile(tab, record);
3252
+ }
3253
+
3254
+ async function dispatchGitWorkflowGenerationAttempt(tab, record, profile, attempt) {
3255
+ assertGitWorkflowGenerationOwnership(tab, record);
3256
+ if (!tab.rpc?.isRunning?.()) throw new Error("Pi RPC process is not running");
3257
+ if (!profile.model) throw new Error(`Configured ${attempt} Git-writing model is unavailable: ${profile.provider}/${profile.modelId}`);
3258
+ if (!supportedGitWorkflowThinkingLevels(profile.model).includes(profile.thinkingLevel)) {
3259
+ throw new Error(`Configured ${attempt} thinking level ${profile.thinkingLevel} is unavailable for ${profile.provider}/${profile.modelId}`);
3260
+ }
3261
+
3262
+ record.attempt = attempt;
3263
+ record.attemptRunStarted = false;
3264
+ record.promptAccepted = false;
3265
+ record.pendingSettlement = null;
3266
+ if (record.currentModelKey !== `${profile.provider}/${profile.modelId}`) {
3267
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: profile.provider, modelId: profile.modelId });
3268
+ assertGitWorkflowGenerationOwnership(tab, record);
3269
+ if (modelResponse.success === false) throw new Error(modelResponse.error || `Failed to select ${profile.provider}/${profile.modelId}`);
3270
+ record.currentModelKey = `${profile.provider}/${profile.modelId}`;
3271
+ }
3272
+ const thinkingResponse = await setThinkingLevelForTab(tab, profile.thinkingLevel, { allowPending: false });
3273
+ assertGitWorkflowGenerationOwnership(tab, record);
3274
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${profile.thinkingLevel}`);
3275
+
3276
+ assertGitWorkflowGenerationOwnership(tab, record);
3277
+ markTabWorking(tab);
3278
+ const response = await tab.rpc.send({ type: "prompt", message: record.message });
3279
+ assertGitWorkflowGenerationOwnership(tab, record);
3280
+ if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
3281
+ record.promptAccepted = true;
3282
+ const pendingSettlement = record.pendingSettlement;
3283
+ if (pendingSettlement?.attempt === attempt) {
3284
+ record.pendingSettlement = null;
3285
+ void settleGitWorkflowGeneration(tab, record, pendingSettlement);
3286
+ }
3287
+ return {
3288
+ accepted: true,
3289
+ kind: record.kind,
3290
+ message: record.message,
3291
+ generationId: record.generationId,
3292
+ generation: publicGitWorkflowGenerationProfile(profile),
3293
+ fallbackUsed: attempt === "fallback",
3294
+ primaryGeneration: publicGitWorkflowGenerationProfile(record.primary),
3295
+ };
3296
+ }
3297
+
3298
+ async function startGitWorkflowFallback(tab, record, primaryError) {
3299
+ if (tab.gitWorkflowGeneration !== record || record.fallbackStarted || !record.fallback) return null;
3300
+ if (record.cancelled || !tab.rpc?.isRunning?.()) return null;
3301
+ record.fallbackStarted = true;
3302
+ record.attempt = "fallback";
3303
+ record.attemptRunStarted = false;
3304
+ record.promptAccepted = false;
3305
+ console.error(`[guided-git] primary generation ${record.generationId} failed; starting fallback: ${sanitizeError(primaryError)}`);
3306
+ emitGitWorkflowFallbackLifecycle(tab, record, "started");
3307
+ try {
3308
+ return await dispatchGitWorkflowGenerationAttempt(tab, record, record.fallback, "fallback");
3309
+ } catch (error) {
3310
+ if (!record.cancelled && tab.gitWorkflowGeneration === record) {
3311
+ console.error(`[guided-git] fallback generation ${record.generationId} failed: ${sanitizeError(error)}`);
3312
+ emitGitWorkflowFallbackLifecycle(tab, record, "failed");
3313
+ }
3314
+ await finishGitWorkflowGeneration(tab, record, { successful: false });
3315
+ throw error;
3316
+ }
3317
+ }
3318
+
3319
+ async function settleGitWorkflowGeneration(tab, record, { failed, cancelled }) {
3320
+ if (tab.gitWorkflowGeneration !== record || record.finishing) return;
3321
+ if (cancelled) record.cancelled = true;
3322
+ if (record.attempt === "primary" && failed && !record.cancelled && record.fallback) {
3323
+ try {
3324
+ await startGitWorkflowFallback(tab, record, "The primary Git-writing model ended with an error");
3325
+ } catch {
3326
+ // startGitWorkflowFallback emitted the bounded terminal lifecycle event.
3327
+ }
3328
+ return;
3329
+ }
3330
+ if (record.attempt === "fallback" && failed) {
3331
+ emitGitWorkflowFallbackLifecycle(tab, record, "failed");
3332
+ }
3333
+ await finishGitWorkflowGeneration(tab, record, { successful: !failed && !record.cancelled });
3334
+ }
3335
+
3336
+ function consumeGitWorkflowGenerationEvent(tab, event, { finalError = false } = {}) {
3337
+ const record = tab.gitWorkflowGeneration;
3338
+ if (!record || record.finishing) return;
3339
+ if ((event?.type === "agent_end" || event?.type === "agent_settled") && event.aborted === true) record.cancelled = true;
3340
+ if (event?.type === "agent_start") {
3341
+ record.attemptRunStarted = true;
3342
+ return;
3343
+ }
3344
+ if (event?.type !== "agent_settled" || !record.attemptRunStarted) return;
3345
+ record.attemptRunStarted = false;
3346
+ const settlement = { attempt: record.attempt, failed: finalError, cancelled: record.cancelled };
3347
+ if (!record.promptAccepted) {
3348
+ record.pendingSettlement = settlement;
3349
+ return;
3350
+ }
3351
+ void settleGitWorkflowGeneration(tab, record, settlement);
3352
+ }
3353
+
3134
3354
  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");
3355
+ if (tab.gitWorkflowGeneration || tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
3141
3356
  const kind = String(body.kind || "").trim();
3142
- const message = gitWorkflowGenerationPrompt(kind, preferences);
3357
+ if (!new Set(["commit", "branch", "pr"]).has(kind)) throw makeHttpError(400, "generation kind must be commit, branch, or pr");
3358
+
3359
+ // Reserve the tab synchronously before the first await. All preflight and
3360
+ // profile transitions retain this exact object as their ownership token.
3361
+ const record = {
3362
+ generationId: randomUUID(),
3363
+ kind,
3364
+ message: "",
3365
+ restore: null,
3366
+ previousMessageGeneration: tab.gitWorkflowMessageGeneration || null,
3367
+ messageGeneration: null,
3368
+ artifactGeneration: null,
3369
+ primary: null,
3370
+ fallback: null,
3371
+ fallbackStarted: false,
3372
+ cancelled: false,
3373
+ finishing: false,
3374
+ attempt: "primary",
3375
+ attemptRunStarted: false,
3376
+ promptAccepted: false,
3377
+ pendingSettlement: null,
3378
+ currentModelKey: "",
3379
+ };
3380
+ tab.gitWorkflowGeneration = record;
3381
+ tab.gitWorkflowFallbackLifecycle = { generationId: record.generationId, kind, events: [] };
3143
3382
 
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
3383
  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}`);
3384
+ // Browser state is untrusted. When it claims an approved content token,
3385
+ // verify the exact current index again at this server action boundary.
3386
+ await assertExpectedStagedContentHash(tab, body);
3387
+ assertGitWorkflowGenerationOwnership(tab, record);
3388
+ const preferences = await readGitWorkflowPreferences();
3389
+ assertGitWorkflowGenerationOwnership(tab, record);
3390
+ if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
3391
+ record.message = gitWorkflowGenerationPrompt(kind, preferences);
3392
+
3393
+ const state = await currentSessionState(tab);
3394
+ assertGitWorkflowGenerationOwnership(tab, record);
3395
+ if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
3396
+ const models = await availableGitWorkflowModels(tab);
3397
+ assertGitWorkflowGenerationOwnership(tab, record);
3398
+ record.primary = gitWorkflowGenerationProfile(
3399
+ preferences.generation.provider,
3400
+ preferences.generation.modelId,
3401
+ preferences.generation.thinkingLevel,
3402
+ models,
3403
+ );
3404
+ const fallbackConfigured = !!preferences.generation.fallback?.provider
3405
+ && !!preferences.generation.fallback?.modelId
3406
+ && (preferences.generation.fallback.provider !== preferences.generation.provider
3407
+ || preferences.generation.fallback.modelId !== preferences.generation.modelId);
3408
+ record.fallback = fallbackConfigured
3409
+ ? gitWorkflowGenerationProfile(
3410
+ preferences.generation.fallback.provider,
3411
+ preferences.generation.fallback.modelId,
3412
+ preferences.generation.fallback.thinkingLevel,
3413
+ models,
3414
+ )
3415
+ : null;
3166
3416
 
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,
3417
+ record.restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
3418
+ record.currentModelKey = gitWorkflowModelKey(state.model);
3419
+ tab.gitWorkflowGenerationRestore = record.restore;
3420
+ record.messageGeneration = kind === "commit" ? await createGitWorkflowMessageGeneration(tab, record.generationId) : null;
3421
+ assertGitWorkflowGenerationOwnership(tab, record);
3422
+ record.artifactGeneration = record.messageGeneration || {
3423
+ id: record.generationId,
3172
3424
  kind,
3173
- message,
3174
- generationId: messageGeneration?.id || "",
3175
- generation: {
3176
- provider: selectedModel.provider,
3177
- modelId: selectedModel.id,
3178
- thinkingLevel: preferences.generation.thinkingLevel,
3179
- },
3425
+ cwd: path.resolve(tab.cwd),
3426
+ createdAt: Date.now(),
3427
+ terminal: false,
3428
+ successful: false,
3180
3429
  };
3430
+ tab.gitWorkflowArtifactGeneration = record.artifactGeneration;
3431
+ if (record.messageGeneration) tab.gitWorkflowMessageGeneration = record.messageGeneration;
3432
+
3433
+ try {
3434
+ return await dispatchGitWorkflowGenerationAttempt(tab, record, record.primary, "primary");
3435
+ } catch (primaryError) {
3436
+ markTabIdle(tab);
3437
+ if (record.fallback && !record.cancelled && tab.rpc?.isRunning?.()) {
3438
+ try {
3439
+ const fallbackResult = await startGitWorkflowFallback(tab, record, primaryError);
3440
+ if (fallbackResult) return fallbackResult;
3441
+ } catch (fallbackError) {
3442
+ throw attachGitWorkflowGenerationError(fallbackError, record);
3443
+ }
3444
+ }
3445
+ await finishGitWorkflowGeneration(tab, record, { successful: false });
3446
+ throw attachGitWorkflowGenerationError(primaryError, record);
3447
+ }
3181
3448
  } catch (error) {
3182
- if (messageGeneration && tab.gitWorkflowMessageGeneration?.id === messageGeneration.id) {
3183
- tab.gitWorkflowMessageGeneration = previousMessageGeneration;
3449
+ if (tab.gitWorkflowGeneration === record && !record.finishing) {
3450
+ if (record.restore) await finishGitWorkflowGeneration(tab, record, { successful: false });
3451
+ else tab.gitWorkflowGeneration = null;
3184
3452
  }
3185
- markTabIdle(tab);
3186
- await restoreGitWorkflowGenerationProfile(tab);
3187
3453
  throw error;
3188
3454
  }
3189
3455
  }
@@ -7403,7 +7669,17 @@ function commitMessagePaths(baseDir) {
7403
7669
  };
7404
7670
  }
7405
7671
 
7406
- async function readGitWorkflowBranchName(cwd) {
7672
+ function assertGitWorkflowArtifactGenerationReady(generationId, generation, kind) {
7673
+ if (!generationId) return;
7674
+ if (!generation || generation.id !== generationId || generation.kind !== kind) {
7675
+ throw new Error(`This ${kind} generation is no longer active. Regenerate the artifact.`);
7676
+ }
7677
+ if (!generation.terminal) throw new Error(`The correlated ${kind} generation is still running.`);
7678
+ if (!generation.successful) throw new Error(`The correlated ${kind} generation did not finish successfully. Regenerate the artifact.`);
7679
+ }
7680
+
7681
+ async function readGitWorkflowBranchName(cwd, { generationId = "", generation = null } = {}) {
7682
+ assertGitWorkflowArtifactGenerationReady(generationId, generation, "branch");
7407
7683
  const root = await getGitRoot(cwd);
7408
7684
  const messageCwd = gitWorkflowMessageCwd(root, cwd);
7409
7685
  const { branchPath } = commitMessagePaths(messageCwd);
@@ -7446,6 +7722,12 @@ async function readGitWorkflowMessages(cwd, { generationId = "", generation = nu
7446
7722
  if (generationId && (!generation || generation.id !== generationId || generation.kind !== "commit" || generation.cwd !== messageCwd)) {
7447
7723
  return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "This commit-message generation is no longer active. Regenerate the message files.", { expired: true });
7448
7724
  }
7725
+ if (generationId && !generation.terminal) {
7726
+ return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "The correlated commit-message generation is still running.", { running: true });
7727
+ }
7728
+ if (generationId && !generation.successful) {
7729
+ return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "The correlated commit-message generation did not finish successfully. Regenerate the message files.", { expired: true });
7730
+ }
7449
7731
  try {
7450
7732
  let pair = await readStableGitMessageArtifactPair(paths);
7451
7733
  if (generationId) {
@@ -8188,7 +8470,8 @@ function prDescriptionPath(root, branch) {
8188
8470
  return { base, prPath: target };
8189
8471
  }
8190
8472
 
8191
- async function readGitWorkflowPrDescription(cwd) {
8473
+ async function readGitWorkflowPrDescription(cwd, { generationId = "", generation = null } = {}) {
8474
+ assertGitWorkflowArtifactGenerationReady(generationId, generation, "pr");
8192
8475
  const root = await getGitRoot(cwd);
8193
8476
  const branch = await currentGitBranch(root);
8194
8477
  const { prPath } = prDescriptionPath(root, branch);
@@ -8345,14 +8628,18 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
8345
8628
  case "/api/git-workflow/message": {
8346
8629
  const generationId = String(body.generationId || "").trim();
8347
8630
  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 }) };
8631
+ return { ok: true, data: await readGitWorkflowMessages(cwd, { generationId, generation: tab?.gitWorkflowArtifactGeneration || null }) };
8349
8632
  }
8350
8633
  case "/api/git-workflow/default-commit-message":
8351
8634
  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) };
8635
+ case "/api/git-workflow/branch-name": {
8636
+ const generationId = String(body.generationId || "").trim();
8637
+ return { ok: true, data: await readGitWorkflowBranchName(cwd, { generationId, generation: tab?.gitWorkflowArtifactGeneration || null }) };
8638
+ }
8639
+ case "/api/git-workflow/pr-description": {
8640
+ const generationId = String(body.generationId || "").trim();
8641
+ return { ok: true, data: await readGitWorkflowPrDescription(cwd, { generationId, generation: tab?.gitWorkflowArtifactGeneration || null }) };
8642
+ }
8356
8643
  case "/api/git-workflow/init":
8357
8644
  await ensureOutsideGitRepository(cwd);
8358
8645
  return gitMutationPayload(await runGitMutationCommand(["init"], { cwd }));
@@ -8485,7 +8772,9 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
8485
8772
  return payload;
8486
8773
  }
8487
8774
  case "/api/git-workflow/cancel": {
8488
- const cancelled = !!activeGitWorkflowProcess;
8775
+ const generation = tab?.gitWorkflowGeneration || null;
8776
+ if (generation) generation.cancelled = true;
8777
+ const cancelled = !!activeGitWorkflowProcess || !!generation;
8489
8778
  if (activeGitWorkflowProcess) activeGitWorkflowProcess.cancel();
8490
8779
  return { ok: true, data: { cancelled } };
8491
8780
  }
@@ -9891,6 +10180,65 @@ function extensionStatusMap(tab) {
9891
10180
  return tab.extensionStatuses;
9892
10181
  }
9893
10182
 
10183
+ function isGuidedGitWorkflowCommandMessage(message) {
10184
+ return GUIDED_GIT_COMMAND_MESSAGE.test(String(message || "").trim());
10185
+ }
10186
+
10187
+ function prunePendingGuidedGitLaunch(tab, nowMs = Date.now()) {
10188
+ const pending = tab?.guidedGitPendingLaunch;
10189
+ if (pending && nowMs - pending.acceptedAt > GUIDED_GIT_LAUNCH_TTL_MS) tab.guidedGitPendingLaunch = null;
10190
+ return tab?.guidedGitPendingLaunch || null;
10191
+ }
10192
+
10193
+ function clearPendingGuidedGitLaunch(tab, launchId) {
10194
+ if (!tab?.guidedGitPendingLaunch) return;
10195
+ if (!launchId || tab.guidedGitPendingLaunch.launchId === launchId) tab.guidedGitPendingLaunch = null;
10196
+ }
10197
+
10198
+ function validGuidedGitStartStatusText(statusText) {
10199
+ if (typeof statusText !== "string" || !statusText || Buffer.byteLength(statusText, "utf8") > 1024) return false;
10200
+ try {
10201
+ const payload = JSON.parse(statusText);
10202
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false;
10203
+ const keys = Object.keys(payload).sort();
10204
+ if (keys.length !== 4 || keys.join(",") !== "action,requestId,type,version") return false;
10205
+ return payload.type === GUIDED_GIT_START_PAYLOAD_TYPE
10206
+ && payload.version === GUIDED_GIT_START_PAYLOAD_VERSION
10207
+ && payload.action === "start"
10208
+ && GUIDED_GIT_UUID_V4.test(String(payload.requestId || ""));
10209
+ } catch {
10210
+ return false;
10211
+ }
10212
+ }
10213
+
10214
+ function scopedGuidedGitLaunchEvent(tab, event, nowMs = Date.now()) {
10215
+ if (event?.type !== "extension_ui_request" || event.method !== "setStatus" || event.statusKey !== GUIDED_GIT_START_STATUS_KEY) return event;
10216
+ if (!event.statusText) {
10217
+ clearPendingGuidedGitLaunch(tab);
10218
+ return event;
10219
+ }
10220
+ if (!validGuidedGitStartStatusText(event.statusText)) return event;
10221
+ const pending = prunePendingGuidedGitLaunch(tab, nowMs);
10222
+ if (!pending) return event;
10223
+ tab.guidedGitPendingLaunch = null;
10224
+ return { ...event, guidedGitLaunchId: pending.launchId };
10225
+ }
10226
+
10227
+ async function authoritativeGuidedGitLaunchAdmission(tab, { launchId = "", reserve = false } = {}) {
10228
+ const pending = prunePendingGuidedGitLaunch(tab);
10229
+ if (pending) throw makeHttpError(409, "A Guided Git activation is already pending for this tab.");
10230
+ if (reserve && !GUIDED_GIT_UUID_V4.test(String(launchId || ""))) throw makeHttpError(400, "guidedGitLaunchId must be a UUID v4");
10231
+ const state = await currentSessionState(tab);
10232
+ if (state.isStreaming) throw makeHttpError(409, "Wait for the current agent run to finish before starting Guided Git.");
10233
+ if (state.isCompacting) throw makeHttpError(409, "Wait for compaction to finish before starting Guided Git.");
10234
+ if (Number(state.pendingMessageCount || 0) > 0 || compactionQueueForTab(tab).length > 0) {
10235
+ throw makeHttpError(409, "Wait for pending messages to finish before starting Guided Git.");
10236
+ }
10237
+ if (prunePendingGuidedGitLaunch(tab)) throw makeHttpError(409, "A Guided Git activation is already pending for this tab.");
10238
+ if (reserve) tab.guidedGitPendingLaunch = { launchId, acceptedAt: Date.now() };
10239
+ return { admitted: true };
10240
+ }
10241
+
9894
10242
  function extensionWidgetMap(tab) {
9895
10243
  if (!tab.extensionWidgets) tab.extensionWidgets = new Map();
9896
10244
  return tab.extensionWidgets;
@@ -10996,14 +11344,22 @@ function attachRpcToTab(tab, rpc) {
10996
11344
  tab.rpcUnsubscribe = rpc.onEvent((rawEvent) => {
10997
11345
  const event = tab.thinkingStreamRecovery.ingest(rawEvent);
10998
11346
  if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event) || consumeSessionSummaryRpcEvent(tab, event)) return;
11347
+ const gitWorkflowFinalError = event?.type === "agent_settled" && tab.pendingTurnFailure === true;
10999
11348
  updateTabActivityFromEvent(tab, event);
11000
- let scopedEvent = eventForTabClients(tab, event);
11349
+ let scopedEvent = scopedGuidedGitLaunchEvent(tab, eventForTabClients(tab, event));
11001
11350
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
11351
+ if (tab.gitWorkflowGeneration) tab.gitWorkflowGeneration.processLost = true;
11352
+ if (tab.gitWorkflowArtifactGeneration) {
11353
+ tab.gitWorkflowArtifactGeneration.terminal = true;
11354
+ tab.gitWorkflowArtifactGeneration.successful = false;
11355
+ }
11356
+ tab.gitWorkflowGeneration = null;
11002
11357
  tab.gitWorkflowGenerationRestore = null;
11003
11358
  tab.gitWorkflowMessageGeneration = null;
11004
11359
  clearPendingExtensionUiRequests(tab);
11005
11360
  clearExtensionStatuses(tab);
11006
11361
  clearExtensionWidgets(tab);
11362
+ clearPendingGuidedGitLaunch(tab);
11007
11363
  clearWebuiSubagents(tab);
11008
11364
  resetNaturalConversationMode(tab);
11009
11365
  resetCodexFastMode(tab);
@@ -11017,7 +11373,7 @@ function attachRpcToTab(tab, rpc) {
11017
11373
  recordEvent(scopedEvent);
11018
11374
  for (const client of tab.sseClients) sendSseToClient(client, scopedEvent);
11019
11375
  if (event?.type === "compaction_end") void flushCompactionQueue(tab, event);
11020
- if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
11376
+ consumeGitWorkflowGenerationEvent(tab, event, { finalError: gitWorkflowFinalError });
11021
11377
  });
11022
11378
  }
11023
11379
 
@@ -11035,8 +11391,11 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
11035
11391
  lastState: null,
11036
11392
  pendingThinkingLevel: undefined,
11037
11393
  thinkingStreamRecovery: new ThinkingStreamRecovery(),
11394
+ gitWorkflowGeneration: null,
11038
11395
  gitWorkflowGenerationRestore: null,
11039
11396
  gitWorkflowMessageGeneration: null,
11397
+ gitWorkflowArtifactGeneration: null,
11398
+ gitWorkflowFallbackLifecycle: null,
11040
11399
  activity: createTabActivity(createdAt),
11041
11400
  pendingExtensionUiRequests: new Map(),
11042
11401
  extensionStatuses: new Map(),
@@ -11058,6 +11417,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
11058
11417
  rpcUnsubscribe: undefined,
11059
11418
  sseClients: new Set(),
11060
11419
  browserPromptRequests: new Map(),
11420
+ guidedGitPendingLaunch: null,
11061
11421
  };
11062
11422
  resetNaturalConversationMode(tab);
11063
11423
  resetCodexFastMode(tab);
@@ -14577,6 +14937,7 @@ async function getSessionTreeData(tab) {
14577
14937
  cwd: manager.getCwd(),
14578
14938
  leafId,
14579
14939
  nodes: flattenSessionTree(manager.getTree(), { leafId }),
14940
+ eventTargets: sessionTreeEventTargets(manager.getEntries()),
14580
14941
  };
14581
14942
  }
14582
14943
 
@@ -15723,30 +16084,45 @@ async function handlePromptRequest(tab, body, req) {
15723
16084
  if (isNaturalConversationActive(tab) && naturalConversationSlashCommandName(body.message) && !isNaturalConversationSlashCommand(body.message)) {
15724
16085
  blockNaturalConversationAction("slash commands are blocked from the Web UI shell");
15725
16086
  }
15726
- const nativeResponse = await handleNativeSlashCommand(tab, body, req);
15727
- if (nativeResponse) {
15728
- return { status: nativeResponse.success === false ? 400 : 200, payload: responseWithTab(nativeResponse, tab) };
15729
- }
15730
- const command = commandFromPost("/api/prompt", body);
15731
- enforceNaturalConversationCommandAllowed(tab, command);
15732
- const queuedForCompaction = maybeQueueCommandDuringCompaction(tab, command);
15733
- if (queuedForCompaction) return { status: 202, payload: responseWithTab(queuedForCompaction, tab) };
15734
- const naturalConversationSafetyResponse = await ensureNaturalConversationPromptSafety(tab, command);
15735
- if (naturalConversationSafetyResponse?.success === false) {
15736
- return { status: 400, payload: responseWithTab(naturalConversationSafetyResponse, tab) };
15737
- }
15738
- const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
15739
- if (pendingThinkingResponse?.success === false) {
15740
- return { status: 400, payload: responseWithTab(pendingThinkingResponse, tab) };
15741
- }
15742
- const startsVisibleWork = commandStartsVisibleWork(command);
15743
- if (startsVisibleWork) {
15744
- maybeNameTabForConversation(tab, command);
15745
- markTabWorking(tab);
16087
+ const guidedGitLaunch = isGuidedGitWorkflowCommandMessage(body.message);
16088
+ const guidedGitLaunchId = guidedGitLaunch ? String(body.guidedGitLaunchId || "") : "";
16089
+ if (guidedGitLaunch) await authoritativeGuidedGitLaunchAdmission(tab, { launchId: guidedGitLaunchId, reserve: true });
16090
+ const releaseGuidedGitLaunch = () => clearPendingGuidedGitLaunch(tab, guidedGitLaunchId);
16091
+ try {
16092
+ const nativeResponse = await handleNativeSlashCommand(tab, body, req);
16093
+ if (nativeResponse) {
16094
+ if (nativeResponse.success === false) releaseGuidedGitLaunch();
16095
+ return { status: nativeResponse.success === false ? 400 : 200, payload: responseWithTab(nativeResponse, tab) };
16096
+ }
16097
+ const command = commandFromPost("/api/prompt", body);
16098
+ enforceNaturalConversationCommandAllowed(tab, command);
16099
+ const queuedForCompaction = guidedGitLaunch ? null : maybeQueueCommandDuringCompaction(tab, command);
16100
+ if (queuedForCompaction) return { status: 202, payload: responseWithTab(queuedForCompaction, tab) };
16101
+ const naturalConversationSafetyResponse = await ensureNaturalConversationPromptSafety(tab, command);
16102
+ if (naturalConversationSafetyResponse?.success === false) {
16103
+ releaseGuidedGitLaunch();
16104
+ return { status: 400, payload: responseWithTab(naturalConversationSafetyResponse, tab) };
16105
+ }
16106
+ const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
16107
+ if (pendingThinkingResponse?.success === false) {
16108
+ releaseGuidedGitLaunch();
16109
+ return { status: 400, payload: responseWithTab(pendingThinkingResponse, tab) };
16110
+ }
16111
+ const startsVisibleWork = commandStartsVisibleWork(command);
16112
+ if (startsVisibleWork) {
16113
+ maybeNameTabForConversation(tab, command);
16114
+ markTabWorking(tab);
16115
+ }
16116
+ const response = await tab.rpc.send(command, PROMPT_REQUEST_TIMEOUT_MS);
16117
+ if (response.success === false) {
16118
+ releaseGuidedGitLaunch();
16119
+ if (startsVisibleWork) markTabIdle(tab);
16120
+ }
16121
+ return { status: response.success === false ? 400 : 200, payload: responseWithTab(response, tab) };
16122
+ } catch (error) {
16123
+ releaseGuidedGitLaunch();
16124
+ throw error;
15746
16125
  }
15747
- const response = await tab.rpc.send(command, PROMPT_REQUEST_TIMEOUT_MS);
15748
- if (response.success === false && startsVisibleWork) markTabIdle(tab);
15749
- return { status: response.success === false ? 400 : 200, payload: responseWithTab(response, tab) };
15750
16126
  }
15751
16127
 
15752
16128
  const server = createServer(async (req, res) => {
@@ -16148,6 +16524,7 @@ const server = createServer(async (req, res) => {
16148
16524
  }
16149
16525
  replayExtensionStatuses(tab, client);
16150
16526
  replayExtensionWidgets(tab, client);
16527
+ replayGitWorkflowFallbackLifecycle(tab, client);
16151
16528
  if (tab.sessionSummary) {
16152
16529
  sendSseToClient(client, {
16153
16530
  type: "webui_session_summary",
@@ -16903,6 +17280,13 @@ const server = createServer(async (req, res) => {
16903
17280
  return;
16904
17281
  }
16905
17282
 
17283
+ if (url.pathname === "/api/git-workflow/launch-admission" && req.method === "POST") {
17284
+ const body = await readJsonBody(req);
17285
+ const tab = getRequestedTab(req, url, body);
17286
+ sendJson(res, 200, { ok: true, data: await authoritativeGuidedGitLaunchAdmission(tab) });
17287
+ return;
17288
+ }
17289
+
16906
17290
  if (url.pathname === "/api/git-workflow/preferences" && req.method === "POST") {
16907
17291
  const body = await readJsonBody(req);
16908
17292
  const tab = getRequestedTab(req, url, body);