@firstpick/pi-package-webui 0.9.5 → 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 (82) hide show
  1. package/README.md +11 -5
  2. package/bin/pi-webui.mjs +457 -77
  3. package/lib/git-workflow-preferences.mjs +21 -1
  4. package/lib/optional-feature-catalog.mjs +1 -1
  5. package/lib/session-actions.mjs +20 -2
  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 +2539 -292
  11. package/public/index.html +87 -31
  12. package/public/service-worker.js +4 -1
  13. package/public/stream-derived-output.mjs +799 -0
  14. package/public/stream-markdown-tail.mjs +204 -0
  15. package/public/stream-output-controller.mjs +193 -51
  16. package/public/stream-render-scheduler.mjs +85 -0
  17. package/public/styles.css +501 -19
  18. package/public/transcript-renderer.mjs +73 -24
  19. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  20. package/tests/browser/composer-action-grid-reorder.spec.mjs +114 -31
  21. package/tests/browser/control-visibility.spec.mjs +141 -2
  22. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  23. package/tests/browser/guided-git-fallback.spec.mjs +153 -0
  24. package/tests/browser/mobile-foundation.spec.mjs +28 -0
  25. package/tests/browser/stream-output-isolation.spec.mjs +308 -3
  26. package/tests/browser/user-noticeable-fixes.spec.mjs +204 -0
  27. package/tests/codex-fast-mode-static.test.mjs +2 -2
  28. package/tests/compact-sections-static.test.mjs +4 -0
  29. package/tests/composer-action-grid-reorder-static.test.mjs +8 -7
  30. package/tests/control-visibility-static.test.mjs +66 -3
  31. package/tests/controls-layout-static.test.mjs +3 -3
  32. package/tests/cwd-footer-reliability-static.test.mjs +1 -1
  33. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  34. package/tests/fast-mode-client-static.test.mjs +5 -2
  35. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  36. package/tests/file-viewer-image-static.test.mjs +3 -3
  37. package/tests/fixtures/fake-pi.mjs +57 -10
  38. package/tests/fixtures/streaming-workloads.mjs +36 -0
  39. package/tests/footer-provider-usage-visual-static.test.mjs +15 -0
  40. package/tests/foreground-transcript-catch-up-static.test.mjs +7 -1
  41. package/tests/git-workflow-preferences.test.mjs +30 -1
  42. package/tests/guided-git-fallback-runtime.test.mjs +418 -0
  43. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  44. package/tests/guided-git-message-reliability-static.test.mjs +8 -7
  45. package/tests/interaction-state-stability-static.test.mjs +3 -1
  46. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  47. package/tests/intercom-conversations-http.test.mjs +16 -0
  48. package/tests/main-output-loading-static.test.mjs +3 -3
  49. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  50. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  51. package/tests/mobile-foundation-static.test.mjs +3 -3
  52. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  53. package/tests/mobile-static.test.mjs +80 -67
  54. package/tests/open-issue-wizard-static.test.mjs +1 -1
  55. package/tests/persistent-ui-layout-static.test.mjs +4 -4
  56. package/tests/prompt-input-vertical-scroll-static.test.mjs +26 -0
  57. package/tests/questionnaire-dialog.test.mjs +3 -3
  58. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  59. package/tests/resource-defaults-helper.test.mjs +12 -0
  60. package/tests/runtime-error-visibility.test.mjs +3 -3
  61. package/tests/session-auth-harness.test.mjs +26 -1
  62. package/tests/session-sampling-helper.test.mjs +1 -0
  63. package/tests/session-sampling-ui-static.test.mjs +3 -3
  64. package/tests/session-tree-event-targets.test.mjs +106 -0
  65. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  66. package/tests/stream-derived-output.test.mjs +121 -0
  67. package/tests/stream-markdown-tail.test.mjs +218 -0
  68. package/tests/stream-output-controller.test.mjs +119 -4
  69. package/tests/stream-output-isolation-static.test.mjs +27 -6
  70. package/tests/stream-output-workloads.test.mjs +40 -3
  71. package/tests/stream-render-scheduler.test.mjs +115 -0
  72. package/tests/streaming-ui-coupling.test.mjs +1 -1
  73. package/tests/subagent-launch-policy.test.mjs +532 -0
  74. package/tests/subagent-observability-static.test.mjs +2 -2
  75. package/tests/subagents-helper.test.mjs +211 -1
  76. package/tests/syntax-highlighting-static.test.mjs +3 -3
  77. package/tests/tab-close-continuity-static.test.mjs +23 -0
  78. package/tests/theme-customizer-static.test.mjs +1 -1
  79. package/tests/thinking-format-parser.test.mjs +15 -0
  80. package/tests/todo-filter-static.test.mjs +148 -0
  81. package/tests/transcript-markdown-tail.test.mjs +137 -0
  82. package/webui-rpc-helper.mjs +220 -3
package/bin/pi-webui.mjs CHANGED
@@ -10,7 +10,7 @@ import path from "node:path";
10
10
  import { StringDecoder } from "node:string_decoder";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
12
12
  import { promisify } from "node:util";
13
- import { brotliCompress, constants as zlibConstants, gzip } from "node:zlib";
13
+ import { brotliCompress, brotliCompressSync, constants as zlibConstants, gzip, gzipSync } from "node:zlib";
14
14
  import { SessionManager, SettingsManager, DefaultPackageManager } from "@earendil-works/pi-coding-agent";
15
15
  import {
16
16
  ThemeContractError,
@@ -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,
@@ -1143,14 +1144,37 @@ class PiRpcProcess {
1143
1144
  }
1144
1145
  }
1145
1146
 
1147
+ // JSON responses are compact and, when the client accepts it, compressed. Boot alone fetches
1148
+ // ~1.5 MB of JSON (models, commands, tools, subagent config); over remote access or a phone the
1149
+ // pretty-printed uncompressed payloads were seconds of transfer per reload.
1150
+ const JSON_COMPRESSION_MIN_BYTES = 2048;
1151
+
1146
1152
  function sendJson(res, statusCode, payload, headers = {}) {
1147
- const body = JSON.stringify(payload, null, 2);
1148
- res.writeHead(statusCode, {
1153
+ const raw = Buffer.from(JSON.stringify(payload));
1154
+ const responseHeaders = {
1149
1155
  "content-type": "application/json; charset=utf-8",
1150
1156
  "cache-control": "no-store",
1151
1157
  "x-content-type-options": "nosniff",
1152
1158
  ...headers,
1153
- });
1159
+ };
1160
+ let body = raw;
1161
+ const encoding = raw.length >= JSON_COMPRESSION_MIN_BYTES ? res.piAcceptedEncoding || "" : "";
1162
+ if (encoding === "br") {
1163
+ body = brotliCompressSync(raw, {
1164
+ params: {
1165
+ [zlibConstants.BROTLI_PARAM_QUALITY]: 4,
1166
+ [zlibConstants.BROTLI_PARAM_SIZE_HINT]: raw.length,
1167
+ },
1168
+ });
1169
+ responseHeaders["content-encoding"] = "br";
1170
+ responseHeaders.vary = "Accept-Encoding";
1171
+ } else if (encoding === "gzip") {
1172
+ body = gzipSync(raw, { level: 5 });
1173
+ responseHeaders["content-encoding"] = "gzip";
1174
+ responseHeaders.vary = "Accept-Encoding";
1175
+ }
1176
+ responseHeaders["content-length"] = body.length;
1177
+ res.writeHead(statusCode, responseHeaders);
1154
1178
  res.end(body);
1155
1179
  }
1156
1180
 
@@ -1161,12 +1185,17 @@ function makeHttpError(statusCode, message) {
1161
1185
  }
1162
1186
 
1163
1187
  function sendError(res, statusCode, error) {
1164
- 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);
1165
1191
  const payload = { ok: false, error: message };
1166
1192
  const isThemeError = typeof error?.code === "string" && error.code.startsWith("THEME_");
1167
1193
  if (isThemeError) payload.code = error.code;
1168
1194
  if (isThemeError && error?.details && typeof error.details === "object") payload.details = error.details;
1169
1195
  if (error?.optionalFeatureInstall) payload.optionalFeatureInstall = error.optionalFeatureInstall;
1196
+ if (error?.gitWorkflowGeneration && typeof error.gitWorkflowGeneration === "object") {
1197
+ payload.gitWorkflowGeneration = error.gitWorkflowGeneration;
1198
+ }
1170
1199
  sendJson(res, statusCode, payload);
1171
1200
  }
1172
1201
 
@@ -2866,6 +2895,7 @@ function requireGitWorkflowBoolean(value, key) {
2866
2895
  async function saveGitWorkflowPreferencesData(tab, body = {}) {
2867
2896
  const submitted = body.preferences && typeof body.preferences === "object" ? body.preferences : body;
2868
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);
2869
2899
  if (submitted.commit?.language !== undefined) requireGitWorkflowChoice(submitted.commit.language, "commit.language", GIT_WORKFLOW_LANGUAGES);
2870
2900
  if (submitted.commit?.defaultVariant !== undefined) requireGitWorkflowChoice(submitted.commit.defaultVariant, "commit.defaultVariant", GIT_WORKFLOW_DEFAULT_VARIANTS);
2871
2901
  if (submitted.commit?.scope !== undefined) requireGitWorkflowChoice(submitted.commit.scope, "commit.scope", GIT_WORKFLOW_SCOPE_POLICIES);
@@ -2888,6 +2918,19 @@ async function saveGitWorkflowPreferencesData(tab, body = {}) {
2888
2918
  throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${next.generation.thinkingLevel}`);
2889
2919
  }
2890
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
+
2891
2934
  await writeGitWorkflowPreferences(next);
2892
2935
  return gitWorkflowPreferencesData(tab);
2893
2936
  }
@@ -3071,27 +3114,79 @@ function gitWorkflowGenerationPrompt(kind, preferences) {
3071
3114
  }
3072
3115
  }
3073
3116
 
3074
- async function restoreGitWorkflowGenerationProfile(tab) {
3075
- 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;
3076
3161
  if (!restore) return;
3077
- tab.gitWorkflowGenerationRestore = null;
3078
- try {
3079
- if (!tab.rpc?.isRunning?.()) return;
3080
- if (restore.model?.provider && restore.model?.id) {
3081
- const modelResponse = await tab.rpc.send({ type: "set_model", provider: restore.model.provider, modelId: restore.model.id });
3082
- if (modelResponse.success === false) throw new Error(modelResponse.error || "Failed to restore model");
3083
- }
3084
- if (restore.thinkingLevel) {
3085
- const thinkingResponse = await setThinkingLevelForTab(tab, restore.thinkingLevel, { allowPending: false });
3086
- 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
+ }
3087
3183
  }
3088
- recordEvent({ type: "git_workflow_generation_profile_restored", tabId: tab.id, tabTitle: tab.title });
3089
- } catch (error) {
3090
- recordEvent({ type: "git_workflow_generation_profile_restore_failed", tabId: tab.id, tabTitle: tab.title, error: sanitizeError(error) });
3091
- }
3184
+ })();
3185
+ if (record) record.restorePromise = operation;
3186
+ return operation;
3092
3187
  }
3093
3188
 
3094
- async function createGitWorkflowMessageGeneration(tab) {
3189
+ async function createGitWorkflowMessageGeneration(tab, generationId) {
3095
3190
  // Keep generation dispatch backward-compatible for tabs whose cwd has not
3096
3191
  // become a repository yet; the Guided Git flow itself still verifies Git
3097
3192
  // state at its staging/review boundaries.
@@ -3099,68 +3194,256 @@ async function createGitWorkflowMessageGeneration(tab) {
3099
3194
  const cwd = gitWorkflowMessageCwd(root, tab.cwd);
3100
3195
  const paths = commitMessagePaths(cwd);
3101
3196
  return {
3102
- id: randomUUID(),
3197
+ id: generationId,
3103
3198
  kind: "commit",
3104
3199
  root,
3105
3200
  cwd,
3106
3201
  createdAt: Date.now(),
3107
3202
  baseline: await readStableGitMessageArtifactPair(paths),
3203
+ terminal: false,
3204
+ successful: false,
3108
3205
  };
3109
3206
  }
3110
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),
3289
+ };
3290
+ }
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
+
3111
3348
  async function startGitWorkflowGeneration(tab, body = {}) {
3112
- if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
3113
- // Browser state is untrusted. When it claims an approved content token,
3114
- // verify the exact current index again at this server action boundary.
3115
- await assertExpectedStagedContentHash(tab, body);
3116
- const preferences = await readGitWorkflowPreferences();
3117
- 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");
3118
3350
  const kind = String(body.kind || "").trim();
3119
- 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: [] };
3120
3376
 
3121
- const state = await currentSessionState(tab);
3122
- if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
3123
- const models = await availableGitWorkflowModels(tab);
3124
- const selectedModel = models.find((model) => model.provider === preferences.generation.provider && model.id === preferences.generation.modelId);
3125
- 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.`);
3126
- const supportedLevels = supportedGitWorkflowThinkingLevels(selectedModel);
3127
- if (!supportedLevels.includes(preferences.generation.thinkingLevel)) {
3128
- throw makeHttpError(409, `Configured thinking level ${preferences.generation.thinkingLevel} is unavailable for ${gitWorkflowModelKey(selectedModel)}. Open Guided Git Setup to update it.`);
3129
- }
3130
-
3131
- const restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
3132
- const previousMessageGeneration = tab.gitWorkflowMessageGeneration || null;
3133
- const messageGeneration = kind === "commit" ? await createGitWorkflowMessageGeneration(tab) : null;
3134
- tab.gitWorkflowGenerationRestore = restore;
3135
- if (messageGeneration) tab.gitWorkflowMessageGeneration = messageGeneration;
3136
3377
  try {
3137
- if (gitWorkflowModelKey(state.model) !== gitWorkflowModelKey(selectedModel)) {
3138
- const modelResponse = await tab.rpc.send({ type: "set_model", provider: selectedModel.provider, modelId: selectedModel.id });
3139
- if (modelResponse.success === false) throw new Error(modelResponse.error || `Failed to select ${gitWorkflowModelKey(selectedModel)}`);
3140
- }
3141
- const thinkingResponse = await setThinkingLevelForTab(tab, preferences.generation.thinkingLevel, { allowPending: false });
3142
- 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;
3143
3410
 
3144
- markTabWorking(tab);
3145
- const response = await tab.rpc.send({ type: "prompt", message });
3146
- if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
3147
- return {
3148
- 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,
3149
3418
  kind,
3150
- message,
3151
- generationId: messageGeneration?.id || "",
3152
- generation: {
3153
- provider: selectedModel.provider,
3154
- modelId: selectedModel.id,
3155
- thinkingLevel: preferences.generation.thinkingLevel,
3156
- },
3419
+ cwd: path.resolve(tab.cwd),
3420
+ createdAt: Date.now(),
3421
+ terminal: false,
3422
+ successful: false,
3157
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
+ }
3158
3442
  } catch (error) {
3159
- if (messageGeneration && tab.gitWorkflowMessageGeneration?.id === messageGeneration.id) {
3160
- 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;
3161
3446
  }
3162
- markTabIdle(tab);
3163
- await restoreGitWorkflowGenerationProfile(tab);
3164
3447
  throw error;
3165
3448
  }
3166
3449
  }
@@ -7380,7 +7663,17 @@ function commitMessagePaths(baseDir) {
7380
7663
  };
7381
7664
  }
7382
7665
 
7383
- 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");
7384
7677
  const root = await getGitRoot(cwd);
7385
7678
  const messageCwd = gitWorkflowMessageCwd(root, cwd);
7386
7679
  const { branchPath } = commitMessagePaths(messageCwd);
@@ -7423,6 +7716,12 @@ async function readGitWorkflowMessages(cwd, { generationId = "", generation = nu
7423
7716
  if (generationId && (!generation || generation.id !== generationId || generation.kind !== "commit" || generation.cwd !== messageCwd)) {
7424
7717
  return gitWorkflowMessagePendingPayload(root, messageCwd, paths, generationId, "This commit-message generation is no longer active. Regenerate the message files.", { expired: true });
7425
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
+ }
7426
7725
  try {
7427
7726
  let pair = await readStableGitMessageArtifactPair(paths);
7428
7727
  if (generationId) {
@@ -8165,7 +8464,8 @@ function prDescriptionPath(root, branch) {
8165
8464
  return { base, prPath: target };
8166
8465
  }
8167
8466
 
8168
- async function readGitWorkflowPrDescription(cwd) {
8467
+ async function readGitWorkflowPrDescription(cwd, { generationId = "", generation = null } = {}) {
8468
+ assertGitWorkflowArtifactGenerationReady(generationId, generation, "pr");
8169
8469
  const root = await getGitRoot(cwd);
8170
8470
  const branch = await currentGitBranch(root);
8171
8471
  const { prPath } = prDescriptionPath(root, branch);
@@ -8322,14 +8622,18 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
8322
8622
  case "/api/git-workflow/message": {
8323
8623
  const generationId = String(body.generationId || "").trim();
8324
8624
  if (generationId && !tab) throw new Error("Fresh commit-message lookup requires a Web UI tab");
8325
- 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 }) };
8326
8626
  }
8327
8627
  case "/api/git-workflow/default-commit-message":
8328
8628
  return { ok: true, data: await readGitWorkflowDefaultCommitMessage(cwd) };
8329
- case "/api/git-workflow/branch-name":
8330
- return { ok: true, data: await readGitWorkflowBranchName(cwd) };
8331
- case "/api/git-workflow/pr-description":
8332
- 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
+ }
8333
8637
  case "/api/git-workflow/init":
8334
8638
  await ensureOutsideGitRepository(cwd);
8335
8639
  return gitMutationPayload(await runGitMutationCommand(["init"], { cwd }));
@@ -8462,7 +8766,9 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
8462
8766
  return payload;
8463
8767
  }
8464
8768
  case "/api/git-workflow/cancel": {
8465
- const cancelled = !!activeGitWorkflowProcess;
8769
+ const generation = tab?.gitWorkflowGeneration || null;
8770
+ if (generation) generation.cancelled = true;
8771
+ const cancelled = !!activeGitWorkflowProcess || !!generation;
8466
8772
  if (activeGitWorkflowProcess) activeGitWorkflowProcess.cancel();
8467
8773
  return { ok: true, data: { cancelled } };
8468
8774
  }
@@ -10973,9 +11279,16 @@ function attachRpcToTab(tab, rpc) {
10973
11279
  tab.rpcUnsubscribe = rpc.onEvent((rawEvent) => {
10974
11280
  const event = tab.thinkingStreamRecovery.ingest(rawEvent);
10975
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;
10976
11283
  updateTabActivityFromEvent(tab, event);
10977
11284
  let scopedEvent = eventForTabClients(tab, event);
10978
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;
10979
11292
  tab.gitWorkflowGenerationRestore = null;
10980
11293
  tab.gitWorkflowMessageGeneration = null;
10981
11294
  clearPendingExtensionUiRequests(tab);
@@ -10994,7 +11307,7 @@ function attachRpcToTab(tab, rpc) {
10994
11307
  recordEvent(scopedEvent);
10995
11308
  for (const client of tab.sseClients) sendSseToClient(client, scopedEvent);
10996
11309
  if (event?.type === "compaction_end") void flushCompactionQueue(tab, event);
10997
- if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
11310
+ consumeGitWorkflowGenerationEvent(tab, event, { finalError: gitWorkflowFinalError });
10998
11311
  });
10999
11312
  }
11000
11313
 
@@ -11012,8 +11325,11 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
11012
11325
  lastState: null,
11013
11326
  pendingThinkingLevel: undefined,
11014
11327
  thinkingStreamRecovery: new ThinkingStreamRecovery(),
11328
+ gitWorkflowGeneration: null,
11015
11329
  gitWorkflowGenerationRestore: null,
11016
11330
  gitWorkflowMessageGeneration: null,
11331
+ gitWorkflowArtifactGeneration: null,
11332
+ gitWorkflowFallbackLifecycle: null,
11017
11333
  activity: createTabActivity(createdAt),
11018
11334
  pendingExtensionUiRequests: new Map(),
11019
11335
  extensionStatuses: new Map(),
@@ -14173,6 +14489,32 @@ async function deleteFileSystemEntryData(tab, body = {}) {
14173
14489
  };
14174
14490
  }
14175
14491
 
14492
+ // Create an empty file or a directory inside the tab's working directory (Files panel
14493
+ // "New file…" / "New folder…"). Never overwrites; parents must already exist.
14494
+ async function createFileSystemEntryData(tab, body = {}) {
14495
+ const kind = body.type === "directory" ? "directory" : "file";
14496
+ const resolved = await resolveWorkspacePath(tab, body.path || body.filePath || "", { mustExist: false });
14497
+ if (resolved.targetPath === resolved.root) throw makeHttpError(400, "A name is required");
14498
+ if (resolved.info) throw makeHttpError(409, `Already exists: ${resolved.relative}`);
14499
+ const parentPath = path.dirname(resolved.targetPath);
14500
+ const parentInfo = await stat(parentPath).catch(() => null);
14501
+ if (!parentInfo?.isDirectory?.()) throw makeHttpError(404, `Parent folder not found: ${workspaceRelativePath(resolved.root, parentPath) || "."}`);
14502
+ const realParent = await realpath(parentPath).catch(() => parentPath);
14503
+ if (realParent !== resolved.realRoot && !pathInside(resolved.realRoot, realParent)) throw makeHttpError(403, "Parent folder escapes the active tab working directory");
14504
+ if (kind === "directory") await mkdir(resolved.targetPath);
14505
+ else await writeFile(resolved.targetPath, "", { encoding: "utf8", flag: "wx" });
14506
+ const nextStats = await stat(resolved.targetPath);
14507
+ return {
14508
+ path: resolved.relative,
14509
+ name: path.basename(resolved.targetPath),
14510
+ type: kind,
14511
+ parentPath: workspaceRelativePath(resolved.root, parentPath),
14512
+ created: true,
14513
+ size: nextStats.size,
14514
+ mtimeMs: nextStats.mtimeMs,
14515
+ };
14516
+ }
14517
+
14176
14518
  async function moveFileSystemEntryData(tab, body = {}) {
14177
14519
  if (body.confirmed !== true) throw makeHttpError(409, "Moving files or directories requires confirmed: true");
14178
14520
  const source = await resolveWorkspacePath(tab, body.path || body.filePath || body.sourcePath || "");
@@ -14334,7 +14676,14 @@ async function getIntercomConversationsData(tab, conversationId = "") {
14334
14676
 
14335
14677
  requireAllowedSessionPath(sessionFile);
14336
14678
  const sessionInfo = await stat(sessionFile).catch(() => null);
14337
- if (!sessionInfo?.isFile()) throw makeHttpError(404, "Persisted session is unavailable");
14679
+ if (!sessionInfo?.isFile()) {
14680
+ // Fresh/empty session: its file is only created on first persist, so there
14681
+ // cannot be any persisted conversations yet. Return an empty projection
14682
+ // instead of erroring out every intercom poll for the tab.
14683
+ const empty = projectIntercomConversations([], projectionOptions);
14684
+ if (conversationId) throw makeHttpError(404, "Intercom conversation not found");
14685
+ return empty;
14686
+ }
14338
14687
 
14339
14688
  let manager;
14340
14689
  try {
@@ -14521,6 +14870,7 @@ async function getSessionTreeData(tab) {
14521
14870
  cwd: manager.getCwd(),
14522
14871
  leafId,
14523
14872
  nodes: flattenSessionTree(manager.getTree(), { leafId }),
14873
+ eventTargets: sessionTreeEventTargets(manager.getEntries()),
14524
14874
  };
14525
14875
  }
14526
14876
 
@@ -15695,6 +16045,7 @@ async function handlePromptRequest(tab, body, req) {
15695
16045
 
15696
16046
  const server = createServer(async (req, res) => {
15697
16047
  try {
16048
+ res.piAcceptedEncoding = acceptedStaticEncoding(req);
15698
16049
  const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
15699
16050
 
15700
16051
  if (url.pathname === "/remote-auth" && req.method === "GET") {
@@ -15991,6 +16342,25 @@ const server = createServer(async (req, res) => {
15991
16342
  return;
15992
16343
  }
15993
16344
 
16345
+ // Reopen a recently closed tab (same cwd, title, and persisted session) — the server-side
16346
+ // record is used so clients cannot point Pi at arbitrary session files.
16347
+ if (url.pathname === "/api/tabs/reopen" && req.method === "POST") {
16348
+ const body = await readJsonBody(req);
16349
+ const wanted = String(body.id || "").trim();
16350
+ const index = closedRestorableTabs.findIndex((item) => item.id === wanted);
16351
+ if (!wanted || index === -1) throw makeHttpError(404, "That closed tab can no longer be reopened");
16352
+ const [descriptor] = closedRestorableTabs.splice(index, 1);
16353
+ const tab = await createTab({
16354
+ title: descriptor.titleSource === "explicit" || descriptor.titleSource === "auto" ? descriptor.title : undefined,
16355
+ titleSource: descriptor.titleSource,
16356
+ conversationStarted: descriptor.conversationStarted,
16357
+ cwd: descriptor.cwd,
16358
+ sessionFile: descriptor.sessionFile,
16359
+ });
16360
+ sendJson(res, 201, { ok: true, data: { tab: tabMeta(tab), tabs: listTabs() } });
16361
+ return;
16362
+ }
16363
+
15994
16364
  if (url.pathname.startsWith("/api/tabs/") && req.method === "PATCH") {
15995
16365
  const id = decodeURIComponent(url.pathname.slice("/api/tabs/".length));
15996
16366
  const body = await readJsonBody(req);
@@ -16072,6 +16442,7 @@ const server = createServer(async (req, res) => {
16072
16442
  }
16073
16443
  replayExtensionStatuses(tab, client);
16074
16444
  replayExtensionWidgets(tab, client);
16445
+ replayGitWorkflowFallbackLifecycle(tab, client);
16075
16446
  if (tab.sessionSummary) {
16076
16447
  sendSseToClient(client, {
16077
16448
  type: "webui_session_summary",
@@ -16467,6 +16838,15 @@ const server = createServer(async (req, res) => {
16467
16838
  return;
16468
16839
  }
16469
16840
 
16841
+ if (url.pathname === "/api/files/create" && req.method === "POST") {
16842
+ requireLocalhostRoute(req, url.pathname);
16843
+ const body = await readJsonBody(req);
16844
+ const tab = getRequestedTab(req, url, body);
16845
+ ensureNaturalConversationRouteAllowed(tab, "file creation is blocked");
16846
+ sendJson(res, 201, { ok: true, data: await createFileSystemEntryData(tab, body) });
16847
+ return;
16848
+ }
16849
+
16470
16850
  if (url.pathname === "/api/files/move" && req.method === "POST") {
16471
16851
  requireLocalhostRoute(req, url.pathname);
16472
16852
  const body = await readJsonBody(req);