@firstpick/pi-package-webui 0.9.8 → 0.10.0

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 (59) hide show
  1. package/DEVELOPMENT.md +911 -0
  2. package/README.md +8 -8
  3. package/TECHNICAL.md +415 -0
  4. package/bin/pi-webui.mjs +237 -64
  5. package/index.ts +23 -33
  6. package/lib/git-workflow-preferences.mjs +51 -12
  7. package/lib/tui-model-profile-selector.mjs +183 -0
  8. package/lib/tui-resource-selector.mjs +173 -0
  9. package/lib/windows-drive-roots.mjs +114 -0
  10. package/package.json +3 -1
  11. package/public/app.js +274 -90
  12. package/public/index.html +7 -3
  13. package/public/service-worker.js +1 -1
  14. package/public/styles.css +76 -16
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/intercom-conversation-viewer.spec.mjs +76 -53
  17. package/tests/browser/user-noticeable-fixes.spec.mjs +51 -0
  18. package/tests/browser/windows-drive-parent.spec.mjs +198 -0
  19. package/tests/codex-fast-mode-static.test.mjs +2 -2
  20. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  21. package/tests/control-visibility-static.test.mjs +3 -3
  22. package/tests/controls-layout-static.test.mjs +3 -3
  23. package/tests/durable-rpc-supervisor-harness.test.mjs +9 -0
  24. package/tests/events-tree-context-menu-static.test.mjs +3 -3
  25. package/tests/fast-mode-client-static.test.mjs +1 -1
  26. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  27. package/tests/file-viewer-image-static.test.mjs +3 -3
  28. package/tests/fixtures/fake-pi.mjs +3 -3
  29. package/tests/guided-git-activation-static.test.mjs +24 -12
  30. package/tests/guided-git-fallback-runtime.test.mjs +209 -270
  31. package/tests/guided-git-fallback-ui-static.test.mjs +2 -2
  32. package/tests/guided-git-message-reliability-static.test.mjs +2 -1
  33. package/tests/guided-git-optional-feature.test.mjs +8 -5
  34. package/tests/http-endpoints-harness.test.mjs +22 -4
  35. package/tests/intercom-conversation-viewer-static.test.mjs +7 -6
  36. package/tests/intercom-tag-layout-static.test.mjs +35 -16
  37. package/tests/intercom-tag-overflow-layout.test.mjs +87 -0
  38. package/tests/main-output-loading-static.test.mjs +3 -3
  39. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  40. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  41. package/tests/mobile-foundation-static.test.mjs +3 -3
  42. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  43. package/tests/mobile-static.test.mjs +11 -6
  44. package/tests/open-issue-wizard-static.test.mjs +1 -1
  45. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  46. package/tests/prompt-input-vertical-scroll-static.test.mjs +3 -3
  47. package/tests/questionnaire-dialog.test.mjs +3 -3
  48. package/tests/remote-auth-settings-harness.test.mjs +18 -3
  49. package/tests/resource-tui-extension.test.mjs +2 -1
  50. package/tests/session-sampling-ui-static.test.mjs +3 -3
  51. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  52. package/tests/subagent-observability-static.test.mjs +2 -2
  53. package/tests/syntax-highlighting-static.test.mjs +3 -3
  54. package/tests/theme-customizer-static.test.mjs +1 -1
  55. package/tests/tui-model-profile-selector.test.mjs +102 -0
  56. package/tests/tui-resource-selector.test.mjs +74 -0
  57. package/tests/webui-settings-locking.test.mjs +32 -1
  58. package/tests/windows-drive-cwd-picker-static.test.mjs +81 -0
  59. package/tests/windows-drive-roots.test.mjs +130 -0
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
- import { spawn, spawnSync } from "node:child_process";
3
- import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { execFileSync, spawn } from "node:child_process";
3
+ import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { createServer } from "node:net";
5
5
  import { tmpdir } from "node:os";
6
6
  import path from "node:path";
@@ -9,65 +9,52 @@ import { fileURLToPath } from "node:url";
9
9
 
10
10
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
11
11
  const serverScript = path.join(packageRoot, "bin", "pi-webui.mjs");
12
- const temporaryRoot = await mkdtemp(path.join(tmpdir(), "pi-webui-guided-git-fallback-"));
12
+ const temporaryRoot = await mkdtemp(path.join(tmpdir(), "pi-webui-guided-git-native-"));
13
13
  const fakePi = path.join(temporaryRoot, "fake-guided-git-pi.mjs");
14
14
 
15
15
  await writeFile(fakePi, `#!/usr/bin/env node
16
16
  import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
17
17
  import { join } from "node:path";
18
18
  import { createInterface } from "node:readline";
19
- const scenario = process.env.GUIDED_GIT_SCENARIO || "settled-success";
19
+ const scenario = process.env.GUIDED_GIT_SCENARIO || "success";
20
20
  const logFile = process.env.GUIDED_GIT_LOG_FILE;
21
21
  const artifactRoot = process.env.GUIDED_GIT_ARTIFACT_ROOT;
22
22
  let activeModel = { provider: "fake", id: "original" };
23
23
  let thinkingLevel = "high";
24
24
  function log(value) { appendFileSync(logFile, JSON.stringify(value) + "\\n"); }
25
25
  function send(value) { process.stdout.write(JSON.stringify(value) + "\\n"); }
26
- function event(value) { log({ direction: "event", ...value }); send(value); }
27
- function assistantFailure() { return { role: "assistant", stopReason: "error", content: [{ type: "text", text: "fixture failure" }] }; }
28
26
  function writeCommitArtifacts(prefix) {
29
27
  const directory = join(artifactRoot, "dev", "COMMIT");
30
28
  mkdirSync(directory, { recursive: true });
31
- writeFileSync(join(directory, "staged-commit-short.txt"), prefix + " short\\n");
32
- writeFileSync(join(directory, "staged-commit-long.txt"), prefix + " long\\n");
29
+ writeFileSync(join(directory, "staged-commit-short.txt"), "feat: " + prefix + " native generation\\n");
30
+ writeFileSync(join(directory, "staged-commit-long.txt"), "feat: " + prefix + " native generation\\n- feat: verify direct RPC artifact completion\\n");
33
31
  }
34
- function settle({ failed = false, wait = 20 } = {}) {
35
- setTimeout(() => {
36
- event({ type: "agent_start" });
37
- if (failed) {
38
- const message = assistantFailure();
39
- event({ type: "message_end", message });
40
- event({ type: "agent_end", willRetry: false, messages: [message] });
41
- } else {
42
- event({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "fixture success" }] } });
43
- event({ type: "agent_end" });
44
- }
45
- event({ type: "agent_settled" });
46
- }, wait);
32
+ function writeBranchArtifact() {
33
+ const directory = join(artifactRoot, "dev", "COMMIT");
34
+ mkdirSync(directory, { recursive: true });
35
+ writeFileSync(join(directory, "staged-branch-name.txt"), "feat/native-root-artifacts\\n");
47
36
  }
48
- function settleAfterInternalRetry() {
49
- setTimeout(() => {
50
- const first = assistantFailure();
51
- event({ type: "agent_start" });
52
- event({ type: "message_end", message: first });
53
- event({ type: "agent_end", willRetry: true, messages: [first] });
54
- const final = assistantFailure();
55
- event({ type: "agent_start" });
56
- event({ type: "message_end", message: final });
57
- event({ type: "agent_end", willRetry: false, messages: [final] });
58
- event({ type: "agent_settled" });
59
- }, 20);
37
+ function failNativeCommand(command, error, notificationError = error) {
38
+ const commandName = String(command.message || "").split(/\\s+/u, 1)[0].replace(/^\\//u, "");
39
+ send({
40
+ type: "extension_ui_request",
41
+ id: "notify-" + command.id,
42
+ method: "notify",
43
+ message: "/" + commandName + " failed: " + notificationError + ". No stale success was reported.",
44
+ notifyType: "error",
45
+ });
46
+ send({ type: "extension_error", extensionPath: "command:" + commandName, event: "command", error });
60
47
  }
61
48
  const models = [
62
49
  { provider: "fake", id: "original", name: "Original", reasoning: true },
63
50
  { provider: "fake", id: "primary", name: "Primary", reasoning: true },
64
51
  { provider: "fake", id: "fallback", name: "Fallback", reasoning: false },
65
52
  ];
66
- createInterface({ input: process.stdin }).on("line", (line) => {
53
+ createInterface({ input: process.stdin }).on("line", async (line) => {
67
54
  let command;
68
55
  try { command = JSON.parse(line); } catch { return; }
69
56
  if (!command?.id || !command?.type) return;
70
- log({ direction: "command", type: command.type, provider: command.provider, modelId: command.modelId, level: command.level, message: command.message, activeModel: activeModel.id, thinkingLevel });
57
+ log({ type: command.type, modelId: command.modelId, level: command.level, message: command.message, activeModel: activeModel.id });
71
58
  const response = { type: "response", id: command.id, command: command.type, success: true };
72
59
  switch (command.type) {
73
60
  case "get_state":
@@ -77,78 +64,65 @@ createInterface({ input: process.stdin }).on("line", (line) => {
77
64
  send({ ...response, data: { models } });
78
65
  break;
79
66
  case "get_commands":
80
- send({ ...response, data: { commands: [] } });
67
+ send({ ...response, data: { commands: [
68
+ { name: "git-staged-msg", source: scenario === "prompt-only" ? "prompt" : "extension" },
69
+ { name: "git-branch-name", source: "extension" },
70
+ { name: "pr", source: "extension" },
71
+ ] } });
81
72
  break;
82
73
  case "get_messages":
83
74
  send({ ...response, data: { messages: [] } });
84
75
  break;
85
- case "set_model": {
86
- if ((scenario === "immediate-selection" || scenario === "immediate-double-failure") && command.modelId === "primary") {
87
- send({ ...response, success: false, error: "SECRET primary selection failure at /private/provider/file.mjs:42" });
88
- } else if ((scenario === "cancel-during-fallback-selection" && command.modelId === "fallback")
89
- || (scenario === "cancel-during-primary-selection" && command.modelId === "primary")) {
90
- setTimeout(() => {
91
- activeModel = { provider: command.provider, id: command.modelId };
92
- send({ ...response, data: activeModel });
93
- }, 350);
94
- } else {
95
- activeModel = { provider: command.provider, id: command.modelId };
96
- send({ ...response, data: activeModel });
97
- }
76
+ case "set_model":
77
+ activeModel = { provider: command.provider, id: command.modelId };
78
+ send({ ...response, data: activeModel });
98
79
  break;
99
- }
100
80
  case "set_thinking_level":
101
- if (scenario === "immediate-thinking" && activeModel.id === "primary" && command.level === "low") {
102
- send({ ...response, success: false, error: "fixture primary effort failure" });
103
- } else {
104
- thinkingLevel = command.level;
105
- send({ ...response, data: { level: thinkingLevel } });
106
- }
81
+ thinkingLevel = command.level;
82
+ send({ ...response, data: { level: thinkingLevel } });
107
83
  break;
108
- case "prompt": {
109
- const model = activeModel.id;
110
- if ((scenario === "fallback-prompt-failure" || scenario === "immediate-double-failure") && model === "fallback") {
111
- send({ ...response, success: false, error: "SECRET fallback rejection at /private/provider/file.mjs:99" });
84
+ case "prompt":
85
+ if (scenario === "process-loss") process.exit(12);
86
+ if (scenario === "concurrent" || scenario === "cancellation") await new Promise((resolve) => setTimeout(resolve, 150));
87
+ if (scenario === "provider-failure" && activeModel.id === "primary") {
88
+ failNativeCommand(command, "FIRSTPICK_GUIDED_GIT_PROVIDER_FAILURE: active model generation failed", "The active model provider failed");
89
+ send(response);
112
90
  break;
113
91
  }
114
- if (scenario === "immediate-prompt" && model === "primary") {
115
- send({ ...response, success: false, error: "fixture primary prompt failure" });
92
+ if (scenario === "invalid-output") {
93
+ failNativeCommand(command, "Generated output must not be empty");
94
+ send(response);
116
95
  break;
117
96
  }
118
- if (scenario === "settlement-before-response" && model === "primary") {
119
- const message = assistantFailure();
120
- event({ type: "agent_start" });
121
- event({ type: "message_end", message });
122
- event({ type: "agent_end", willRetry: false, messages: [message] });
123
- event({ type: "agent_settled" });
124
- setTimeout(() => send({ ...response, data: { output: "late prompt acknowledgement" } }), 80);
97
+ if (scenario === "delayed-native-command-error") {
98
+ send(response);
99
+ setTimeout(() => failNativeCommand(command, "Generated chunk summary is empty"), 25);
125
100
  break;
126
101
  }
127
- send({ ...response, data: { output: "fixture prompt accepted" } });
128
- if (scenario === "process-loss" && model === "primary") {
129
- event({ type: "agent_start" });
130
- setTimeout(() => process.exit(7), 30);
102
+ if (scenario === "missing-base") {
103
+ failNativeCommand(command, "No configured upstream base, remote default, main, or master branch is available");
104
+ send(response);
131
105
  break;
132
106
  }
133
- if (scenario === "will-retry-final-failure" && model === "primary") {
134
- settleAfterInternalRetry();
107
+ if (scenario === "git-failure") {
108
+ failNativeCommand(command, "Git command failed while reading staged changes");
109
+ send(response);
135
110
  break;
136
111
  }
137
- if (scenario === "artifact-primary-then-fallback" && model === "primary") {
138
- writeCommitArtifacts("primary");
139
- settle({ failed: true });
112
+ if (scenario === "above-capture-input") {
113
+ failNativeCommand(command, "The complete staged diff exceeds the 16777216-byte generation cap; use a manual message");
114
+ send(response);
140
115
  break;
141
116
  }
142
- if (scenario === "artifact-primary-then-fallback" && model === "fallback") {
143
- setTimeout(() => writeCommitArtifacts("fallback"), 180);
144
- settle({ failed: false, wait: 230 });
145
- break;
117
+ if (!["unsafe-stale-artifact", "cancellation"].includes(scenario)) {
118
+ if (String(command.message || "").startsWith("/git-branch-name")) writeBranchArtifact();
119
+ else writeCommitArtifacts(activeModel.id);
146
120
  }
147
- const fallbackFailsAfterAcceptance = scenario === "fallback-settled-failure" && model === "fallback";
148
- const primaryFails = model === "primary" && !["concurrent", "primary-success"].includes(scenario);
149
- settle({ failed: fallbackFailsAfterAcceptance || primaryFails });
121
+ send({ ...response, data: { output: "native extension command completed" } });
122
+ break;
123
+ case "abort":
124
+ send({ ...response, data: { output: "abort acknowledged" } });
150
125
  break;
151
- }
152
126
  default:
153
127
  send({ ...response, data: {} });
154
128
  }
@@ -156,17 +130,8 @@ createInterface({ input: process.stdin }).on("line", (line) => {
156
130
  `, "utf8");
157
131
  await chmod(fakePi, 0o755);
158
132
 
159
- function lines(text) {
160
- return text.trim().split("\n").filter(Boolean).map((line) => JSON.parse(line));
161
- }
162
-
163
- async function waitFor(check, message, timeoutMs = 8_000) {
164
- const deadline = Date.now() + timeoutMs;
165
- while (Date.now() < deadline) {
166
- if (await check()) return;
167
- await delay(40);
168
- }
169
- assert.fail(message);
133
+ function git(cwd, ...args) {
134
+ return execFileSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, LC_ALL: "C" } }).trim();
170
135
  }
171
136
 
172
137
  async function availablePort() {
@@ -178,41 +143,20 @@ async function availablePort() {
178
143
  const address = server.address();
179
144
  const port = typeof address === "object" && address ? address.port : 0;
180
145
  await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
181
- assert.ok(port > 0, "the OS should allocate a test server port");
182
146
  return port;
183
147
  }
184
148
 
185
- async function readReplayedLifecycle(baseURL) {
186
- const controller = new AbortController();
187
- const response = await fetch(`${baseURL}/api/events`, { signal: controller.signal });
188
- assert.equal(response.status, 200);
189
- const reader = response.body.getReader();
190
- const decoder = new TextDecoder();
191
- let text = "";
192
- const events = [];
193
- const deadline = Date.now() + 3_000;
194
- try {
195
- while (Date.now() < deadline && events.length < 2) {
196
- const result = await Promise.race([
197
- reader.read(),
198
- delay(500).then(() => ({ timeout: true })),
199
- ]);
200
- if (result.timeout) continue;
201
- if (result.done) break;
202
- text += decoder.decode(result.value, { stream: true });
203
- const frames = text.split("\n\n");
204
- text = frames.pop() || "";
205
- for (const frame of frames) {
206
- const data = frame.split("\n").find((line) => line.startsWith("data: "))?.slice(6);
207
- if (!data) continue;
208
- const event = JSON.parse(data);
209
- if (String(event.type || "").startsWith("webui_git_workflow_generation_fallback_")) events.push(event);
210
- }
211
- }
212
- } finally {
213
- controller.abort();
149
+ async function waitFor(check, message, timeoutMs = 10_000) {
150
+ const deadline = Date.now() + timeoutMs;
151
+ while (Date.now() < deadline) {
152
+ if (await check()) return;
153
+ await delay(40);
214
154
  }
215
- return events;
155
+ assert.fail(message);
156
+ }
157
+
158
+ function parseLog(text) {
159
+ return text.trim().split("\n").filter(Boolean).map((line) => JSON.parse(line));
216
160
  }
217
161
 
218
162
  async function runScenario(scenario, verify) {
@@ -220,8 +164,23 @@ async function runScenario(scenario, verify) {
220
164
  const settingsFile = path.join(cwd, "settings.json");
221
165
  const logFile = path.join(cwd, "rpc.jsonl");
222
166
  await mkdir(cwd, { recursive: true });
223
- const git = spawnSync("git", ["init", "--quiet"], { cwd, encoding: "utf8" });
224
- assert.equal(git.status, 0, git.stderr);
167
+ git(cwd, "init", "-b", "main");
168
+ git(cwd, "config", "user.name", "Native RPC Test");
169
+ git(cwd, "config", "user.email", "native-rpc@example.invalid");
170
+ await writeFile(path.join(cwd, "tracked.txt"), "base\n");
171
+ git(cwd, "add", "--", "tracked.txt");
172
+ git(cwd, "commit", "-m", "test: initial");
173
+ const stagedContent = scenario === "oversized-success"
174
+ ? `${"x".repeat(1_430_698)}\n`
175
+ : "staged native change\n";
176
+ await writeFile(path.join(cwd, "tracked.txt"), stagedContent);
177
+ git(cwd, "add", "--", "tracked.txt");
178
+ if (scenario === "unsafe-stale-artifact") {
179
+ const artifactDirectory = path.join(cwd, "dev", "COMMIT");
180
+ await mkdir(artifactDirectory, { recursive: true });
181
+ await writeFile(path.join(artifactDirectory, "staged-commit-short.txt"), "feat: stale native generation\n");
182
+ await writeFile(path.join(artifactDirectory, "staged-commit-long.txt"), "feat: stale native generation\n- feat: preserve the old artifact\n");
183
+ }
225
184
  await writeFile(settingsFile, `${JSON.stringify({
226
185
  version: 8,
227
186
  gitWorkflow: {
@@ -234,14 +193,12 @@ async function runScenario(scenario, verify) {
234
193
  },
235
194
  },
236
195
  }, null, 2)}\n`, "utf8");
237
- if (scenario === "artifact-primary-then-fallback") {
238
- await mkdir(path.join(cwd, "dev", "COMMIT"), { recursive: true });
239
- await writeFile(path.join(cwd, "dev", "COMMIT", "staged-commit-short.txt"), "baseline short\n");
240
- await writeFile(path.join(cwd, "dev", "COMMIT", "staged-commit-long.txt"), "baseline long\n");
241
- }
196
+
197
+ const tabCwd = scenario === "nested-cwd" ? path.join(cwd, "nested", "tab") : cwd;
198
+ await mkdir(tabCwd, { recursive: true });
242
199
  const port = await availablePort();
243
200
  const baseURL = `http://127.0.0.1:${port}`;
244
- const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
201
+ const child = spawn(process.execPath, [serverScript, "--cwd", tabCwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
245
202
  stdio: ["ignore", "pipe", "pipe"],
246
203
  env: {
247
204
  ...process.env,
@@ -255,7 +212,7 @@ async function runScenario(scenario, verify) {
255
212
  let output = "";
256
213
  child.stdout.on("data", (chunk) => { output += String(chunk); });
257
214
  child.stderr.on("data", (chunk) => { output += String(chunk); });
258
- const request = async (pathname, { method = "GET", body, timeoutMs = 5_000 } = {}) => {
215
+ const request = async (pathname, { method = "GET", body, timeoutMs = 8_000 } = {}) => {
259
216
  const response = await fetch(`${baseURL}${pathname}`, {
260
217
  method,
261
218
  headers: body === undefined ? undefined : { "Content-Type": "application/json" },
@@ -266,10 +223,10 @@ async function runScenario(scenario, verify) {
266
223
  };
267
224
  try {
268
225
  await waitFor(async () => {
269
- try { return (await request("/api/health")).status === 200; } catch { return false; }
270
- }, `server did not start for ${scenario}:\n${output}`, 20_000);
271
- const readLog = async () => lines(await readFile(logFile, "utf8").catch(() => ""));
272
- await verify({ request, readLog, baseURL, output: () => output });
226
+ try { return (await request("/api/health", { timeoutMs: 1_000 })).status === 200; } catch { return false; }
227
+ }, `server did not start for ${scenario}:\n${output}`, 30_000);
228
+ const readLog = async () => parseLog(await readFile(logFile, "utf8").catch(() => ""));
229
+ await verify({ request, readLog, cwd, tabCwd });
273
230
  } finally {
274
231
  child.kill("SIGTERM");
275
232
  await delay(120);
@@ -277,143 +234,125 @@ async function runScenario(scenario, verify) {
277
234
  }
278
235
  }
279
236
 
280
- await runScenario("concurrent", async ({ request, readLog }) => {
281
- const [left, right] = await Promise.all([
282
- request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } }),
283
- request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } }),
284
- ]);
285
- assert.deepEqual([left.status, right.status].sort((a, b) => a - b), [200, 409], "one concurrent request must own the tab and one must be rejected");
286
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "the accepted generation should settle and restore");
287
- assert.equal((await readLog()).filter((entry) => entry.type === "prompt").length, 1, "concurrent requests must dispatch exactly one prompt");
288
- });
289
-
290
- await runScenario("immediate-selection", async ({ request, readLog }) => {
291
- const invalidKind = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "invalid" } });
292
- assert.equal(invalidKind.status, 400);
293
- assert.equal((await readLog()).filter((entry) => entry.type === "set_model").length, 0);
294
- const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
295
- assert.equal(result.status, 200);
296
- assert.equal(result.body.data.fallbackUsed, true);
297
- assert.match(result.body.data.generationId, /^[0-9a-f-]{36}$/i);
298
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "immediate fallback should restore");
299
- const restoredLog = await readLog();
300
- const restoredModelIndex = restoredLog.findIndex((entry) => entry.type === "set_model" && entry.modelId === "original");
301
- const restoredEffortIndex = restoredLog.findIndex((entry, index) => index > restoredModelIndex && entry.type === "set_thinking_level" && entry.level === "high");
302
- assert.ok(restoredModelIndex >= 0 && restoredEffortIndex > restoredModelIndex, "restoration should reapply the original reasoning effort after the original model");
303
- assert.equal(restoredLog.filter((entry) => entry.type === "prompt").length, 1);
304
- });
305
-
306
- for (const scenario of ["immediate-thinking", "immediate-prompt"]) {
307
- await runScenario(scenario, async ({ request, readLog }) => {
308
- const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } });
237
+ try {
238
+ await runScenario("success", async ({ request, readLog, cwd }) => {
239
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
309
240
  assert.equal(result.status, 200);
310
- assert.equal(result.body.data.fallbackUsed, true);
311
- assert.match(result.body.data.generationId, /^[0-9a-f-]{36}$/i, "every generation kind must receive a server ID");
312
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), `${scenario} should restore`);
313
- const prompts = (await readLog()).filter((entry) => entry.type === "prompt");
314
- assert.equal(prompts.filter((entry) => entry.activeModel === "fallback").length, 1);
315
- if (scenario === "immediate-prompt") assert.equal(prompts[0].message, prompts[1].message);
241
+ assert.equal(result.body.data.message, "/git-staged-msg en auto");
242
+ assert.equal(result.body.data.fallbackUsed, false);
243
+ assert.equal(await readFile(path.join(cwd, "dev", "COMMIT", "staged-commit-short.txt"), "utf8"), "feat: primary native generation\n");
244
+ const correlated = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(result.body.data.generationId)}`);
245
+ assert.equal(correlated.body.data.ready, true);
246
+ const log = await readLog();
247
+ assert.ok(log.some((entry) => entry.type === "get_commands"));
248
+ assert.equal(log.filter((entry) => entry.type === "prompt").length, 1);
249
+ const primary = log.findIndex((entry) => entry.type === "set_model" && entry.modelId === "primary");
250
+ const restore = log.findIndex((entry) => entry.type === "set_model" && entry.modelId === "original");
251
+ assert.ok(primary >= 0 && restore > primary, "the active model must be restored after native artifact verification");
316
252
  });
317
- }
318
-
319
- await runScenario("will-retry-final-failure", async ({ request, readLog }) => {
320
- const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "pr" } });
321
- assert.equal(result.status, 200);
322
- assert.match(result.body.data.generationId, /^[0-9a-f-]{36}$/i);
323
- await waitFor(async () => (await readLog()).filter((entry) => entry.type === "prompt").length === 2, "fallback should run after final settlement");
324
- const log = await readLog();
325
- const retryEnd = log.findIndex((entry) => entry.type === "agent_end" && entry.willRetry === true);
326
- const fallbackPrompt = log.findIndex((entry) => entry.type === "prompt" && entry.activeModel === "fallback");
327
- assert.ok(retryEnd >= 0 && fallbackPrompt > retryEnd, "Pi internal retry must occur before server fallback");
328
- assert.equal(log.filter((entry) => entry.type === "prompt" && entry.activeModel === "fallback").length, 1);
329
- });
330
253
 
331
- await runScenario("settlement-before-response", async ({ request, readLog }) => {
332
- const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } });
333
- assert.equal(result.status, 200);
334
- await waitFor(async () => (await readLog()).filter((entry) => entry.type === "prompt").length === 2, "pending settlement must start one fallback");
335
- assert.equal((await readLog()).filter((entry) => entry.type === "prompt" && entry.activeModel === "fallback").length, 1);
336
- });
337
-
338
- await runScenario("fallback-settled-failure", async ({ request, readLog }) => {
339
- const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
340
- assert.equal(result.status, 200);
341
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "accepted fallback failure should restore");
342
- const status = await request("/api/webui-status?detailed=true&events=100");
343
- assert.equal(status.body.data.events.filter((event) => event.type === "webui_git_workflow_generation_fallback_failed").length, 1);
344
- assert.equal((await readLog()).filter((entry) => entry.type === "prompt" && entry.activeModel === "fallback").length, 1);
345
- });
254
+ await runScenario("oversized-success", async ({ request, readLog, cwd }) => {
255
+ assert.ok((await stat(path.join(cwd, "tracked.txt"))).size > 1024 * 1024);
256
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
257
+ assert.equal(result.status, 200);
258
+ assert.equal(result.body.data.fallbackUsed, false);
259
+ assert.equal(await readFile(path.join(cwd, "dev", "COMMIT", "staged-commit-short.txt"), "utf8"), "feat: primary native generation\n");
260
+ const correlated = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(result.body.data.generationId)}`);
261
+ assert.equal(correlated.status, 200);
262
+ assert.equal(correlated.body.data.ready, true);
263
+ const log = await readLog();
264
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary"]);
265
+ assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0);
266
+ assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "original").length, 1);
267
+ });
346
268
 
347
- await runScenario("cancel-during-primary-selection", async ({ request, readLog }) => {
348
- const pending = request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } });
349
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "primary"), "primary selection should be delayed");
350
- const cancellation = await request("/api/git-workflow/cancel", { method: "POST", body: {} });
351
- assert.equal(cancellation.body.data.cancelled, true);
352
- const result = await pending;
353
- assert.equal(result.status, 409);
354
- assert.match(result.body.error, /cancelled/i, "primary cancellation should keep its ordinary error instead of masquerading as fallback failure");
355
- await waitFor(async () => (await readLog()).filter((entry) => entry.type === "set_model" && entry.modelId === "original").length >= 1, "cancelled primary selection should restore");
356
- assert.equal((await readLog()).filter((entry) => entry.type === "prompt").length, 0, "cancelled primary selection must never dispatch a prompt");
357
- });
269
+ await runScenario("nested-cwd", async ({ request, cwd, tabCwd }) => {
270
+ const commit = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
271
+ assert.equal(commit.status, 200);
272
+ const messages = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(commit.body.data.generationId)}`);
273
+ assert.equal(messages.body.data.ready, true);
274
+ assert.equal(messages.body.data.root, cwd);
275
+ assert.equal(messages.body.data.cwd, cwd);
276
+ assert.equal(messages.body.data.shortPath, path.join(cwd, "dev", "COMMIT", "staged-commit-short.txt"));
277
+ await assert.rejects(readFile(path.join(tabCwd, "dev", "COMMIT", "staged-commit-short.txt"), "utf8"));
358
278
 
359
- await runScenario("cancel-during-fallback-selection", async ({ request, readLog }) => {
360
- const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } });
361
- assert.equal(result.status, 200);
362
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "fallback"), "fallback selection should be delayed");
363
- const cancellation = await request("/api/git-workflow/cancel", { method: "POST", body: {} });
364
- assert.equal(cancellation.body.data.cancelled, true);
365
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "cancellation should restore ownership profile");
366
- assert.equal((await readLog()).filter((entry) => entry.type === "prompt" && entry.activeModel === "fallback").length, 0, "cancelled fallback selection must never dispatch a prompt");
367
- });
279
+ const branch = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } });
280
+ assert.equal(branch.status, 200);
281
+ const branchArtifact = await request(`/api/git-workflow/branch-name?generationId=${encodeURIComponent(branch.body.data.generationId)}`);
282
+ assert.equal(branchArtifact.status, 200);
283
+ assert.equal(branchArtifact.body.data.root, cwd);
284
+ assert.equal(branchArtifact.body.data.cwd, cwd);
285
+ assert.equal(branchArtifact.body.data.branchPath, path.join(cwd, "dev", "COMMIT", "staged-branch-name.txt"));
286
+ assert.equal(branchArtifact.body.data.branch, "feat/native-root-artifacts");
287
+ await assert.rejects(readFile(path.join(tabCwd, "dev", "COMMIT", "staged-branch-name.txt"), "utf8"));
288
+ });
368
289
 
369
- await runScenario("artifact-primary-then-fallback", async ({ request, readLog }) => {
370
- const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
371
- assert.equal(result.status, 200);
372
- const generationId = result.body.data.generationId;
373
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "fallback"), "fallback should begin after primary artifacts");
374
- const intermediate = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(generationId)}`);
375
- assert.equal(intermediate.body.data.ready, false, "failed-primary artifacts must remain pending while fallback runs");
376
- assert.equal(intermediate.body.data.running, true, "the browser must be told that the correlated fallback generation is still active");
377
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "fallback artifact generation should settle");
378
- const final = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(generationId)}`);
379
- assert.equal(final.body.data.ready, true);
380
- assert.equal(final.body.data.short, "fallback short");
381
- assert.equal(final.body.data.long, "fallback long");
382
- });
290
+ await runScenario("provider-failure", async ({ request, readLog, cwd }) => {
291
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
292
+ assert.equal(result.status, 200);
293
+ assert.equal(result.body.data.fallbackUsed, true);
294
+ assert.equal(await readFile(path.join(cwd, "dev", "COMMIT", "staged-commit-short.txt"), "utf8"), "feat: fallback native generation\n");
295
+ const log = await readLog();
296
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary", "fallback"]);
297
+ assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 1);
298
+ assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "original").length, 1);
299
+ });
383
300
 
384
- await runScenario("immediate-double-failure", async ({ request, baseURL }) => {
385
- const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "pr" } });
386
- assert.equal(result.status, 500);
387
- assert.equal(result.body.error, "Guided Git generation failed after the configured model attempts.");
388
- assert.match(result.body.gitWorkflowGeneration.generationId, /^[0-9a-f-]{36}$/i);
389
- const replayed = await readReplayedLifecycle(baseURL);
390
- assert.deepEqual(replayed.map((event) => event.type), [
391
- "webui_git_workflow_generation_fallback_started",
392
- "webui_git_workflow_generation_fallback_failed",
393
- ]);
394
- for (const event of replayed) {
395
- assert.equal(event.replayed, true);
396
- assert.equal(event.generationId, result.body.gitWorkflowGeneration.generationId);
397
- assert.doesNotMatch(JSON.stringify(event), /SECRET|private\/provider|file\.mjs/i, "lifecycle messages must be bounded and redacted");
301
+ for (const [scenario, kind, expectedError] of [
302
+ ["invalid-output", "commit", /Generated output must not be empty/iu],
303
+ ["delayed-native-command-error", "commit", /Generated chunk summary is empty/iu],
304
+ ["missing-base", "pr", /No configured upstream base/iu],
305
+ ["git-failure", "commit", /Git command failed while reading staged changes/iu],
306
+ ["above-capture-input", "commit", /complete staged diff exceeds the 16777216-byte generation cap/iu],
307
+ ["unsafe-stale-artifact", "commit", /message files? to be refreshed/iu],
308
+ ]) {
309
+ await runScenario(scenario, async ({ request, readLog }) => {
310
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind } });
311
+ assert.notEqual(result.status, 200, `${scenario} must remain terminal without fallback`);
312
+ assert.match(result.body.error, expectedError);
313
+ if (scenario === "above-capture-input") assert.doesNotMatch(result.body.error, /message files? to be refreshed/iu);
314
+ const log = await readLog();
315
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary"]);
316
+ assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0);
317
+ });
398
318
  }
399
- });
400
319
 
401
- await runScenario("process-loss", async ({ request, readLog }) => {
402
- const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
403
- assert.equal(result.status, 200);
404
- await waitFor(async () => (await readLog()).some((entry) => entry.type === "agent_start"), "process-loss run should start");
405
- await delay(250);
406
- const log = await readLog();
407
- assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0, "process loss must not start fallback");
408
- const artifact = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(result.body.data.generationId)}`);
409
- assert.equal(artifact.body.data.ready, false);
410
- assert.equal(artifact.body.data.expired, true);
411
- });
320
+ await runScenario("cancellation", async ({ request, readLog }) => {
321
+ const generation = request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
322
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "prompt"), "native generation did not reach the cancellation barrier");
323
+ const cancelled = await request("/api/git-workflow/cancel", { method: "POST", body: {} });
324
+ assert.equal(cancelled.status, 200);
325
+ assert.equal(cancelled.body.data.cancelled, true);
326
+ assert.notEqual((await generation).status, 200);
327
+ const log = await readLog();
328
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary"]);
329
+ assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0);
330
+ });
412
331
 
413
- const serverSource = await readFile(serverScript, "utf8");
414
- assert.match(serverSource, /tab\.gitWorkflowGeneration = record;[\s\S]*await assertExpectedStagedContentHash/, "tab ownership must be reserved before preflight awaits");
415
- assert.match(serverSource, /modelResponse = await[\s\S]*assertGitWorkflowGenerationOwnership[\s\S]*thinkingResponse = await[\s\S]*assertGitWorkflowGenerationOwnership/, "profile awaits must recheck exact ownership");
416
- assert.match(serverSource, /replayGitWorkflowFallbackLifecycle\(tab, client\)/, "EventSource connections must replay bounded fallback lifecycle state");
332
+ await runScenario("process-loss", async ({ request, readLog }) => {
333
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
334
+ assert.notEqual(result.status, 200);
335
+ const log = await readLog();
336
+ assert.deepEqual(log.filter((entry) => entry.type === "prompt").map((entry) => entry.activeModel), ["primary"]);
337
+ assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0);
338
+ });
417
339
 
418
- await rm(temporaryRoot, { recursive: true, force: true });
419
- console.log("guided-git-fallback-runtime.test.mjs passed");
340
+ await runScenario("prompt-only", async ({ request, readLog }) => {
341
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
342
+ assert.equal(result.status, 409);
343
+ assert.match(result.body.error, /extension command.*Same-named prompt templates are not used/iu);
344
+ const log = await readLog();
345
+ assert.equal(log.filter((entry) => entry.type === "set_model" || entry.type === "prompt").length, 0);
346
+ });
347
+
348
+ await runScenario("concurrent", async ({ request, readLog }) => {
349
+ const [left, right] = await Promise.all([
350
+ request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } }),
351
+ request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } }),
352
+ ]);
353
+ assert.deepEqual([left.status, right.status].sort((a, b) => a - b), [200, 409]);
354
+ assert.equal((await readLog()).filter((entry) => entry.type === "prompt").length, 1);
355
+ });
356
+ } finally {
357
+ await rm(temporaryRoot, { recursive: true, force: true });
358
+ }