mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-12-05 08:15:41 -08:00
Tell a failed macOS folder picker from a cancel, and start Browse at a folder that exists
AI Assisted
This commit is contained in:
1 parent
91479b21a1
commit
ddbc85f73d
5 files changed
+202
-42
No files matched your search
@@ -948,6 +948,34 @@ test("launcher app: modelFrom reads --model, --model= and Codex's -m", () => {
|
|||||||
assert.equal(modelFrom(["--verbose"], "claude"), null);
|
assert.equal(modelFrom(["--verbose"], "claude"), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// osascript exits 1 both on a cancel and on a failure; only the cancel has -128.
|
||||||
|
test("launcher picker: on macOS an exit 1 is a cancel only with osascript's (-128); elsewhere an exit 1 with nothing picked stays a cancel", () => {
|
||||||
|
const { pickerCancelled } = require(LAUNCHER);
|
||||||
|
const cancel = "0:17: execution error: User canceled. (-128)\n";
|
||||||
|
const failure = "0:4: execution error: The variable this is not defined. (-2753)\n";
|
||||||
|
assert.equal(pickerCancelled(1, "", cancel, "darwin"), true);
|
||||||
|
assert.equal(pickerCancelled(1, "", failure, "darwin"), false, "a failure falls through to the typed prompt");
|
||||||
|
assert.equal(pickerCancelled(1, "", "", "darwin"), false);
|
||||||
|
assert.equal(pickerCancelled(1, null, null, "darwin"), false);
|
||||||
|
for (const platform of ["linux", "win32"]) {
|
||||||
|
assert.equal(pickerCancelled(1, "", "", platform), true, platform);
|
||||||
|
assert.equal(pickerCancelled(1, "", "Gtk-WARNING\n", platform), true, platform);
|
||||||
|
assert.equal(pickerCancelled(3, "", "", platform), false, platform);
|
||||||
|
}
|
||||||
|
for (const platform of ["darwin", "linux", "win32"]) {
|
||||||
|
assert.equal(pickerCancelled(0, "", "", platform), true, `${platform}: exit 0 with nothing picked`);
|
||||||
|
assert.equal(pickerCancelled(0, "/some/folder\n", "", platform), false, `${platform}: a pick`);
|
||||||
|
assert.equal(pickerCancelled(1, "/some/folder\n", cancel, platform), false, `${platform}: something printed is no cancel`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("launcher picker: pickFolder decides a cancel through pickerCancelled", () => {
|
||||||
|
const source = fs.readFileSync(require.resolve(LAUNCHER), "utf8");
|
||||||
|
const body = source.slice(source.indexOf("async function pickFolder"), source.indexOf("async function projectCwd"));
|
||||||
|
assert.match(body, /pickerCancelled\(result\.status, result\.stdout, result\.stderr\)/);
|
||||||
|
assert.doesNotMatch(body, /result\.status === 1/, "no cancel rule left beside it");
|
||||||
|
});
|
||||||
|
|
||||||
test("launcher app: an app that starts and then exits with a failure falls back to the terminal flow", (t) => {
|
test("launcher app: an app that starts and then exits with a failure falls back to the terminal flow", (t) => {
|
||||||
const box = sandbox(["claude"]);
|
const box = sandbox(["claude"]);
|
||||||
t.after(box.cleanup);
|
t.after(box.cleanup);
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ import assert from "node:assert/strict";
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { execFileSync, spawnSync } from "node:child_process";
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
||||||
|
import { createRequire } from "node:module";
|
||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
import { PassThrough } from "node:stream";
|
import { PassThrough } from "node:stream";
|
||||||
// The page's pure answer-shaping logic. app.js itself cannot be imported here
|
// The page's pure answer-shaping logic. app.js itself cannot be imported here
|
||||||
@@ -166,6 +167,7 @@ import {
|
|||||||
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
|
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
|
||||||
import {
|
import {
|
||||||
pickerCommand,
|
pickerCommand,
|
||||||
|
pickerOutcome,
|
||||||
pickFolder,
|
pickFolder,
|
||||||
WINDOWS_PICKER_SOURCE,
|
WINDOWS_PICKER_SOURCE,
|
||||||
WORKSPACE_PICKER_PROMPT,
|
WORKSPACE_PICKER_PROMPT,
|
||||||
@@ -187,6 +189,7 @@ import { chatReplyLines } from "../src/web-console/inbox.mjs";
|
|||||||
import {
|
import {
|
||||||
initialWorkspace,
|
initialWorkspace,
|
||||||
pendingWorkspaceChanges,
|
pendingWorkspaceChanges,
|
||||||
|
pickerStart,
|
||||||
readWorkspaceCursor,
|
readWorkspaceCursor,
|
||||||
WORKSPACE_FILE,
|
WORKSPACE_FILE,
|
||||||
writeWorkspaceCursor,
|
writeWorkspaceCursor,
|
||||||
@@ -2351,31 +2354,106 @@ test("picker: the workspace picker cannot drift from the launcher's", () => {
|
|||||||
assert.equal(WORKSPACE_PICKER_PROMPT, "Choose a folder to add to the workspace");
|
assert.equal(WORKSPACE_PICKER_PROMPT, "Choose a folder to add to the workspace");
|
||||||
});
|
});
|
||||||
|
|
||||||
function fakeSpawn(code, output) {
|
test("picker: the launcher and the workspace read a picker's exit the same way", () => {
|
||||||
|
// Two copies of one rule (macOS: only osascript's (-128) is a cancel), each
|
||||||
|
// with its own tests: this keeps an edit to one from leaving the other behind.
|
||||||
|
const { pickerCancelled } = createRequire(import.meta.url)(path.join(ROOT, "src", "launcher", "plan2code.js"));
|
||||||
|
const errors = ["", "0:17: execution error: User canceled. (-128)", "execution error: Not authorized to send Apple events. (-1743)", "(-1280)", "Gtk-WARNING\n"];
|
||||||
|
for (const platform of ["darwin", "linux", "win32"]) {
|
||||||
|
for (const code of [0, 1, 2]) {
|
||||||
|
for (const stdout of ["", "/some/folder\n"]) {
|
||||||
|
for (const stderr of errors) {
|
||||||
|
const workspace = "cancelled" in pickerOutcome(code, stdout, stderr, platform);
|
||||||
|
assert.equal(pickerCancelled(code, stdout, stderr, platform), workspace, JSON.stringify({ platform, code, stdout, stderr }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("picker: stderr is read only on macOS, where it tells a cancel from a failure", { skip: process.platform === "win32" ? "pickerCommand needs a POSIX picker here" : false }, async () => {
|
||||||
|
for (const [platform, expected] of [["darwin", "pipe"], ["linux", "ignore"], ["win32", "ignore"]]) {
|
||||||
|
// Linux's picker is zenity or kdialog, found on PATH: none on this machine, nothing to start.
|
||||||
|
if (!pickerCommand(os.tmpdir(), "p", { platform })) continue;
|
||||||
|
let stdio = null;
|
||||||
|
const spy = (command, args, options) => {
|
||||||
|
stdio = options.stdio;
|
||||||
|
return fakeSpawn(0, "", "", platform)(command, args, options);
|
||||||
|
};
|
||||||
|
await pickFolder(os.tmpdir(), "p", { platform, spawnImpl: spy });
|
||||||
|
assert.ok(stdio, `${platform}: the picker was started`);
|
||||||
|
assert.equal(stdio[2], expected, platform);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function fakeSpawn(code, output, errorText = "", platform = process.platform) {
|
||||||
return (command, args, options) => {
|
return (command, args, options) => {
|
||||||
assert.equal(options.windowsHide, true);
|
assert.equal(options.windowsHide, true);
|
||||||
|
assert.equal(options.stdio[2], platform === "darwin" ? "pipe" : "ignore", "stderr is piped on macOS only, where a cancel is told from a failure");
|
||||||
const child = new EventEmitter();
|
const child = new EventEmitter();
|
||||||
child.stdout = new PassThrough();
|
child.stdout = new PassThrough();
|
||||||
|
child.stderr = new PassThrough();
|
||||||
setImmediate(() => {
|
setImmediate(() => {
|
||||||
if (output) child.stdout.write(output);
|
if (output) child.stdout.write(output);
|
||||||
|
if (errorText) child.stderr.write(errorText);
|
||||||
child.stdout.end();
|
child.stdout.end();
|
||||||
|
child.stderr.end();
|
||||||
setImmediate(() => child.emit("close", code));
|
setImmediate(() => child.emit("close", code));
|
||||||
});
|
});
|
||||||
return child;
|
return child;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// What osascript prints on a cancel, and on a failure (a bad script here; a
|
||||||
|
// missing default folder or a refused permission end the same way, exit 1).
|
||||||
|
const MAC_CANCEL = "0:17: execution error: User canceled. (-128)\n";
|
||||||
|
const MAC_FAILURE = "0:4: execution error: The variable this is not defined. (-2753)\n";
|
||||||
|
|
||||||
test(
|
test(
|
||||||
"picker: pickFolder reads a pick, a cancel and a failure off the picker's exit",
|
"picker: pickFolder reads a pick, a cancel and a failure off the picker's exit",
|
||||||
{ skip: pickerCommand(os.tmpdir(), WORKSPACE_PICKER_PROMPT) ? false : "no folder picker on this machine" },
|
{ skip: pickerCommand(os.tmpdir(), WORKSPACE_PICKER_PROMPT) ? false : "no folder picker on this machine" },
|
||||||
async () => {
|
async () => {
|
||||||
const picked = path.join(os.tmpdir(), "picked");
|
const picked = path.join(os.tmpdir(), "picked");
|
||||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(0, picked + "\n") }), { path: path.resolve(picked) });
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(0, picked + "\n") }), { path: path.resolve(picked) });
|
||||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(1, "") }), { cancelled: true });
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(1, "", MAC_CANCEL) }), { cancelled: true });
|
||||||
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(2, "") }), { error: "picker-failed" });
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { spawnImpl: fakeSpawn(2, "") }), { error: "picker-failed" });
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
test("picker: on macOS only osascript's (-128) makes an exit 1 a cancel; any other exit 1 with no folder is a failure", async () => {
|
||||||
|
const pick = (code, output, errorText) => pickFolder(os.tmpdir(), "p", { platform: "darwin", spawnImpl: fakeSpawn(code, output, errorText, "darwin") });
|
||||||
|
assert.equal(pickerCommand(os.tmpdir(), "p", { platform: "darwin" }).command, "osascript");
|
||||||
|
assert.deepEqual(await pick(1, "", MAC_CANCEL), { cancelled: true });
|
||||||
|
assert.deepEqual(await pick(1, "", MAC_FAILURE), { error: "picker-failed" });
|
||||||
|
assert.deepEqual(await pick(1, "", ""), { error: "picker-failed" }, "no stderr at all is no proof of a cancel");
|
||||||
|
const picked = path.join(os.tmpdir(), "picked");
|
||||||
|
assert.deepEqual(await pick(0, picked + "\n", ""), { path: path.resolve(picked) });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("picker: on Windows and Linux an exit 1 with no folder stays a cancel, whatever stderr says", async () => {
|
||||||
|
assert.equal(pickerCommand(os.tmpdir(), "p", { platform: "win32" }).command, "powershell.exe");
|
||||||
|
for (const errorText of ["", "Gtk-WARNING: some noise\n"]) {
|
||||||
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { platform: "win32", spawnImpl: fakeSpawn(1, "", errorText, "win32") }), { cancelled: true });
|
||||||
|
}
|
||||||
|
// Linux's picker needs a display and zenity or kdialog on this host, so its
|
||||||
|
// rule is checked on the outcome itself.
|
||||||
|
for (const platform of ["linux", "win32"]) {
|
||||||
|
assert.deepEqual(pickerOutcome(1, "", "", platform), { cancelled: true }, platform);
|
||||||
|
assert.deepEqual(pickerOutcome(1, "", "(-2753)", platform), { cancelled: true }, platform);
|
||||||
|
assert.deepEqual(pickerOutcome(0, "", "", platform), { cancelled: true }, platform);
|
||||||
|
assert.deepEqual(pickerOutcome(3, "", "", platform), { error: "picker-failed" }, platform);
|
||||||
|
}
|
||||||
|
assert.deepEqual(pickerOutcome(1, "", MAC_CANCEL, "darwin"), { cancelled: true });
|
||||||
|
assert.deepEqual(pickerOutcome(1, "", MAC_FAILURE, "darwin"), { error: "picker-failed" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("picker: a picker that writes a lot to stderr still finishes, and its last words decide", async () => {
|
||||||
|
// A real child writing far past a pipe's buffer: unread, it would block before exiting.
|
||||||
|
const chatty = (command, args, options) =>
|
||||||
|
spawn(process.execPath, ["-e", "process.stderr.write('Gtk-WARNING\\n'.repeat(100000)); process.stderr.write('User canceled. (-128)'); process.exitCode = 1"], options);
|
||||||
|
assert.deepEqual(await pickFolder(os.tmpdir(), "p", { platform: "darwin", spawnImpl: chatty }), { cancelled: true });
|
||||||
|
});
|
||||||
|
|
||||||
test("ledger: a torn trailing line is skipped, then read once completed; an append after a fragment starts a new line", () => {
|
test("ledger: a torn trailing line is skipped, then read once completed; an append after a fragment starts a new line", () => {
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-ledger-"));
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-ledger-"));
|
||||||
try {
|
try {
|
||||||
@@ -2708,6 +2786,26 @@ test("initialWorkspace names the original folder after itself and marks it origi
|
|||||||
assert.deepEqual([ws.missing, ws.changes, ws.remote], [[], [], ""]);
|
assert.deepEqual([ws.missing, ws.changes, ws.remote], [[], [], ""]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Browse... opens beside the last folder added. When that folder is gone, a missing
|
||||||
|
// start must not read as "Browse is not available here".
|
||||||
|
test("pickerStart opens beside the last folder added, or at its nearest folder still on disk", () => {
|
||||||
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-picker-start-"));
|
||||||
|
try {
|
||||||
|
const project = path.join(root, "project");
|
||||||
|
const kept = path.join(root, "kept");
|
||||||
|
fs.mkdirSync(project);
|
||||||
|
fs.mkdirSync(path.join(kept, "inner"), { recursive: true });
|
||||||
|
assert.equal(pickerStart(initialWorkspace(project), project), project, "the original folder when nothing was added");
|
||||||
|
const ws = initialWorkspace(project);
|
||||||
|
ws.folders.push({ id: "f1", path: path.join(kept, "inner"), name: "inner", description: "" });
|
||||||
|
assert.equal(pickerStart(ws, project), kept, "beside the last folder added");
|
||||||
|
fs.rmSync(kept, { recursive: true, force: true });
|
||||||
|
assert.equal(pickerStart(ws, project), root, "the nearest folder still on disk");
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(root, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// The meter's tables are built from skills.js plus the events that are not a
|
// The meter's tables are built from skills.js plus the events that are not a
|
||||||
// skill's own. Held to their values when they were written by hand.
|
// skill's own. Held to their values when they were written by hand.
|
||||||
test("meter: the weights and labels built from the skill list are the ones written by hand before", () => {
|
test("meter: the weights and labels built from the skill list are the ones written by hand before", () => {
|
||||||
|
|||||||
@@ -1559,6 +1559,17 @@ function isEmptyFolder(dir) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a finished picker means the person canceled. Pickers exit 0 or 1 with nothing printed
|
||||||
|
* when canceled, but osascript also exits 1 when it fails, so on macOS an exit 1 is a cancel
|
||||||
|
* only when stderr carries its "User canceled" number, -128.
|
||||||
|
*/
|
||||||
|
function pickerCancelled(status, stdout, stderr, platform = process.platform) {
|
||||||
|
if ((stdout || '').trim()) return false;
|
||||||
|
if (status === 0) return true;
|
||||||
|
return status === 1 && (platform !== 'darwin' || String(stderr || '').includes('(-128)'));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ask for the project folder: the native picker when there is one, a typed path otherwise.
|
* Ask for the project folder: the native picker when there is one, a typed path otherwise.
|
||||||
* Returns the folder, or null when the person canceled.
|
* Returns the folder, or null when the person canceled.
|
||||||
@@ -1577,10 +1588,10 @@ async function pickFolder() {
|
|||||||
windowsHide: true,
|
windowsHide: true,
|
||||||
});
|
});
|
||||||
const folder = (result.stdout || '').trim();
|
const folder = (result.stdout || '').trim();
|
||||||
// Pickers exit 0 or 1 with nothing printed when canceled; anything else means the picker
|
// Anything but a pick or a cancel means the picker itself failed, so fall through to the
|
||||||
// itself failed, so fall through to the typed prompt rather than giving up.
|
// typed prompt rather than giving up.
|
||||||
if (!result.error && folder && result.status === 0) return path.resolve(folder);
|
if (!result.error && folder && result.status === 0) return path.resolve(folder);
|
||||||
if (!result.error && !folder && (result.status === 0 || result.status === 1)) return null;
|
if (!result.error && pickerCancelled(result.status, result.stdout, result.stderr)) return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const answer = (await ask(`Project folder ${c.green(`[${start}]`)}: `)).trim().replace(/^["']|["']$/g, '');
|
const answer = (await ask(`Project folder ${c.green(`[${start}]`)}: `)).trim().replace(/^["']|["']$/g, '');
|
||||||
@@ -2073,4 +2084,4 @@ async function launch() {
|
|||||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||||
if (require.main === module) launch();
|
if (require.main === module) launch();
|
||||||
|
|
||||||
module.exports = { nodeVersionProblem, usageText, normalizeUpdateTagInput, droppedForApp, bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick, isEmptyFolder };
|
module.exports = { nodeVersionProblem, usageText, normalizeUpdateTagInput, droppedForApp, bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick, isEmptyFolder, pickerCancelled };
|
||||||
+36
-20
@@ -17,8 +17,9 @@ import { spawn } from "node:child_process";
|
|||||||
|
|
||||||
import { findAgent } from "./agent-lookup.mjs";
|
import { findAgent } from "./agent-lookup.mjs";
|
||||||
|
|
||||||
const IS_WINDOWS = process.platform === "win32";
|
// How much of the picker's stderr is kept: the end is where osascript names
|
||||||
const IS_MAC = process.platform === "darwin";
|
// its error.
|
||||||
|
const STDERR_TAIL_BYTES = 2048;
|
||||||
|
|
||||||
export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace";
|
export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace";
|
||||||
|
|
||||||
@@ -160,8 +161,8 @@ public static class Plan2CodeFolderPicker {
|
|||||||
* chosen folder, or nothing when the person cancels. Null when this OS has no
|
* chosen folder, or nothing when the person cancels. Null when this OS has no
|
||||||
* picker we can drive.
|
* picker we can drive.
|
||||||
*/
|
*/
|
||||||
export function pickerCommand(start, prompt) {
|
export function pickerCommand(start, prompt, { platform = process.platform } = {}) {
|
||||||
if (IS_WINDOWS) {
|
if (platform === "win32") {
|
||||||
const script = [
|
const script = [
|
||||||
"$ErrorActionPreference = 'Stop'",
|
"$ErrorActionPreference = 'Stop'",
|
||||||
"try {",
|
"try {",
|
||||||
@@ -203,7 +204,7 @@ export function pickerCommand(start, prompt) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (IS_MAC) {
|
if (platform === "darwin") {
|
||||||
return {
|
return {
|
||||||
command: "osascript",
|
command: "osascript",
|
||||||
args: [
|
args: [
|
||||||
@@ -233,13 +234,26 @@ export function pickerCommand(start, prompt) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Show the picker and settle on what the person did: `{ path }` for a pick,
|
* What a finished picker means: `{ path }` for a pick, `{ cancelled: true }`
|
||||||
* `{ cancelled: true }` when they closed it, `{ error }` when the picker
|
* when the person closed it, `{ error }` when the picker itself failed.
|
||||||
* itself failed or this OS has none. Pickers exit 0 or 1 with nothing printed
|
* Pickers exit 0 or 1 with nothing printed when canceled, but osascript also
|
||||||
* when canceled.
|
* exits 1 when it fails, so on macOS an exit 1 is a cancel only when stderr
|
||||||
|
* carries its "User canceled" number, -128.
|
||||||
*/
|
*/
|
||||||
export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
|
export function pickerOutcome(code, stdout, stderr, platform = process.platform) {
|
||||||
const picker = pickerCommand(start, prompt);
|
const folder = String(stdout || "").trim();
|
||||||
|
if (code === 0 && folder) return { path: path.resolve(folder) };
|
||||||
|
if (!folder && code === 0) return { cancelled: true };
|
||||||
|
if (!folder && code === 1 && (platform !== "darwin" || String(stderr || "").includes("(-128)"))) return { cancelled: true };
|
||||||
|
return { error: "picker-failed" };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show the picker and settle on what the person did (see pickerOutcome), or
|
||||||
|
* `{ error }` when this OS has no picker or it could not start.
|
||||||
|
*/
|
||||||
|
export function pickFolder(start, prompt, { spawnImpl = spawn, platform = process.platform } = {}) {
|
||||||
|
const picker = pickerCommand(start, prompt, { platform });
|
||||||
if (!picker) return Promise.resolve({ error: "picker-failed" });
|
if (!picker) return Promise.resolve({ error: "picker-failed" });
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
let settled = false;
|
let settled = false;
|
||||||
@@ -252,9 +266,11 @@ export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
|
|||||||
try {
|
try {
|
||||||
child = spawnImpl(picker.command, picker.args, {
|
child = spawnImpl(picker.command, picker.args, {
|
||||||
env: { ...process.env, ...(picker.env || {}) },
|
env: { ...process.env, ...(picker.env || {}) },
|
||||||
// stderr is ignored, not piped: a pipe nobody reads fills up and
|
// stderr is piped only on macOS, where osascript's (-128) there is
|
||||||
// blocks a chatty picker (GTK warnings) before it can exit.
|
// what tells a cancel from a failure, and is always read, keeping
|
||||||
stdio: ["ignore", "pipe", "ignore"],
|
// only its end: a pipe nobody reads fills up and blocks a chatty
|
||||||
|
// picker before it can exit. Elsewhere it is not needed.
|
||||||
|
stdio: ["ignore", "pipe", platform === "darwin" ? "pipe" : "ignore"],
|
||||||
windowsHide: true,
|
windowsHide: true,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -265,12 +281,12 @@ export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
|
|||||||
child.stdout.setEncoding?.("utf8");
|
child.stdout.setEncoding?.("utf8");
|
||||||
child.stdout.on("data", (chunk) => (stdout += chunk));
|
child.stdout.on("data", (chunk) => (stdout += chunk));
|
||||||
}
|
}
|
||||||
|
let stderr = "";
|
||||||
|
if (child.stderr) {
|
||||||
|
child.stderr.setEncoding?.("utf8");
|
||||||
|
child.stderr.on("data", (chunk) => (stderr = (stderr + chunk).slice(-STDERR_TAIL_BYTES)));
|
||||||
|
}
|
||||||
child.on("error", () => settle({ error: "picker-failed" }));
|
child.on("error", () => settle({ error: "picker-failed" }));
|
||||||
child.on("close", (code) => {
|
child.on("close", (code) => settle(pickerOutcome(code, stdout, stderr, platform)));
|
||||||
const folder = stdout.trim();
|
|
||||||
if (code === 0 && folder) return settle({ path: path.resolve(folder) });
|
|
||||||
if (!folder && (code === 0 || code === 1)) return settle({ cancelled: true });
|
|
||||||
settle({ error: "picker-failed" });
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -68,6 +68,27 @@ export function specKey(specDir) {
|
|||||||
.replace(/\/+$/, "");
|
.replace(/\/+$/, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isFolder(p) {
|
||||||
|
try {
|
||||||
|
return fs.statSync(p).isDirectory();
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Where the picker opens: beside the last folder added, else the original, else
|
||||||
|
// `fallback`. A start deleted on disk walks up to its nearest folder still there,
|
||||||
|
// since a picker cannot open at a missing folder and would fail as unavailable.
|
||||||
|
export function pickerStart(ws, fallback) {
|
||||||
|
const added = ws.folders.filter((f) => !f.original);
|
||||||
|
const wanted = added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || fallback;
|
||||||
|
for (let dir = wanted; dir; dir = path.dirname(dir)) {
|
||||||
|
if (isFolder(dir)) return dir;
|
||||||
|
if (path.dirname(dir) === dir) break;
|
||||||
|
}
|
||||||
|
return isFolder(fallback) ? fallback : os.homedir();
|
||||||
|
}
|
||||||
|
|
||||||
function readStore() {
|
function readStore() {
|
||||||
const saved = readJson(WORKSPACES_FILE, null);
|
const saved = readJson(WORKSPACES_FILE, null);
|
||||||
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
|
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
|
||||||
@@ -325,14 +346,6 @@ export function serverWorkspace(ctx) {
|
|||||||
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
|
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
|
||||||
}
|
}
|
||||||
|
|
||||||
function isFolder(p) {
|
|
||||||
try {
|
|
||||||
return fs.statSync(p).isDirectory();
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A folder deleted on disk is marked missing, and unmarked when it comes back.
|
// A folder deleted on disk is marked missing, and unmarked when it comes back.
|
||||||
function checkFolders(ws) {
|
function checkFolders(ws) {
|
||||||
ws.missing = ws.missing || [];
|
ws.missing = ws.missing || [];
|
||||||
@@ -432,12 +445,6 @@ export function serverWorkspace(ctx) {
|
|||||||
return [200, { ok: true }];
|
return [200, { ok: true }];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Where the picker opens: beside the last folder added, else the original.
|
|
||||||
function pickerStart(ws) {
|
|
||||||
const added = ws.folders.filter((f) => !f.original);
|
|
||||||
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || sessionWorktree() || project;
|
|
||||||
}
|
|
||||||
|
|
||||||
// One picker at a time. Spawned, never spawnSync: the dialog can sit open for
|
// One picker at a time. Spawned, never spawnSync: the dialog can sit open for
|
||||||
// minutes, and every poll, chat message and `wait` health check has to keep
|
// minutes, and every poll, chat message and `wait` health check has to keep
|
||||||
// being answered meanwhile.
|
// being answered meanwhile.
|
||||||
@@ -452,7 +459,7 @@ export function serverWorkspace(ctx) {
|
|||||||
// Tests only: stands in for the person, so no dialog ever opens.
|
// Tests only: stands in for the person, so no dialog ever opens.
|
||||||
const echo = process.env.PLAN2CODE_PICKER_ECHO;
|
const echo = process.env.PLAN2CODE_PICKER_ECHO;
|
||||||
if (echo) return Promise.resolve([200, echo === "-" ? { cancelled: true } : { path: echo }]);
|
if (echo) return Promise.resolve([200, echo === "-" ? { cancelled: true } : { path: echo }]);
|
||||||
const start = pickerStart(ws);
|
const start = pickerStart(ws, sessionWorktree() || project);
|
||||||
if (!pickerCommand(start, WORKSPACE_PICKER_PROMPT)) return Promise.resolve([404, { reason: "no-picker" }]);
|
if (!pickerCommand(start, WORKSPACE_PICKER_PROMPT)) return Promise.resolve([404, { reason: "no-picker" }]);
|
||||||
pickerBusy = true;
|
pickerBusy = true;
|
||||||
return pickFolder(start, WORKSPACE_PICKER_PROMPT)
|
return pickFolder(start, WORKSPACE_PICKER_PROMPT)
|
||||||
|
|||||||
Reference in new issue
Block a user