Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions app/api/cwd/pick/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { apiErrorResponse } from "@/lib/api-utils";
import { pickDirectory, pickerAvailable } from "@/lib/cwd-picker";
import { LOCAL_HOST_ID } from "@/lib/hosts/registry";

// POST /api/cwd/pick body: { hostId?: string } → { path } | { cancelled: true }
// Opens the OS folder dialog on this machine. A page opened from another machine has no desktop
// here, and another host's paths do not exist here either, so both cases are refused.
export async function POST(req: Request, context: { localPeer: boolean }) {
try {
const body = await req.json().catch(() => ({})) as { hostId?: unknown };
const hostId = typeof body.hostId === "string" && body.hostId ? body.hostId : LOCAL_HOST_ID;
const picked = hostId === LOCAL_HOST_ID && pickerAvailable(context.localPeer) ? await pickDirectory() : null;
if (!picked) {
return Response.json({ error: "The folder dialog is only available on this machine", code: "picker_unavailable" }, { status: 501 });
}
return Response.json(picked);
} catch (error) {
return apiErrorResponse(error);
}
}
9 changes: 9 additions & 0 deletions app/api/cwd/picker/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { pickerAvailable } from "@/lib/cwd-picker";

// GET /api/cwd/picker → { available } — may this page open the server machine's folder dialog?
// Only a page opened on the machine itself: a remote browser has no desktop here. Locality is the
// connection's peer address from the server (context.localPeer), never request.url's host, which the
// client writes through its Host header.
export function GET(_request: Request, context: { localPeer: boolean }) {
return Response.json({ available: pickerAvailable(context.localPeer) });
}
48 changes: 47 additions & 1 deletion components/DirectoryPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useI18n } from "@/lib/i18n";
import { formatApiError } from "@/lib/i18n/api-error";
import { appendProgress, cloneDirectoryName } from "@/lib/git-clone";
import { randomUUID as newCloneId } from "@/lib/random-uuid";
import { LOCAL_HOST_ID } from "@/lib/project-ordering";

interface DirectoryEntry {
name: string;
Expand Down Expand Up @@ -74,6 +75,8 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host,
const [directories, setDirectories] = useState<DirectoryEntry[]>([]);
const [drives, setDrives] = useState<DirectoryEntry[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [nativePickerAvailable, setNativePickerAvailable] = useState(false);
const [nativePickerBusy, setNativePickerBusy] = useState(false);
const [profile, setProfile] = useState("");
const [advisor, setAdvisor] = useState(false);
const [extraArgs, setExtraArgs] = useState("");
Expand All @@ -87,7 +90,7 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host,
const cloneLogRef = useRef<HTMLPreElement>(null);
const browseAbortRef = useRef<AbortController | null>(null);
const cloning = cloneId !== null;
const locked = busy || cloning;
const locked = busy || cloning || nativePickerBusy;
const dialogRef = useModalDialog<HTMLDivElement>({
onClose: () => { if (!locked) onCancel(); },
active: portalTarget !== null,
Expand Down Expand Up @@ -122,6 +125,35 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host,
return () => browseAbortRef.current?.abort();
}, [navigateTo]);

// The OS folder dialog runs on the server's desktop, so it is offered only for this machine.
useEffect(() => {
if (pool || host.id !== LOCAL_HOST_ID) return;
let active = true;
void fetch("/api/cwd/picker")
.then(async (response) => (await response.json()) as { available?: boolean })
.then((data) => { if (active) setNativePickerAvailable(Boolean(data.available)); })
.catch(() => {});
return () => { active = false; };
}, [host.id, pool]);

const pickNativeDirectory = async () => {
if (locked) return;
setNativePickerBusy(true);
setLoadError(null);
try {
const response = await fetch("/api/cwd/pick", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ hostId: host.id }),
});
const data = await response.json() as { path?: string; error?: string; code?: string };
if (!response.ok || data.error) throw new Error(formatApiError({ ...data, error: data.error ?? `HTTP ${response.status}` }));
if (data.path) await navigateTo(data.path);
} catch (cause) {
setLoadError(cause instanceof Error ? cause.message : String(cause));
} finally {
setNativePickerBusy(false);
}
};

useEffect(() => () => { cloneAbortRef.current?.abort(); cloneAbortRef.current = null; }, []);

useEffect(() => {
Expand Down Expand Up @@ -302,6 +334,20 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host,
>
{t("directoryPicker.go")}
</button>
{nativePickerAvailable && !pool && (
<button
className="directory-picker-action"
type="button"
onClick={() => void pickNativeDirectory()}
disabled={locked}
title={t("directoryPicker.browse")}
style={{ minWidth: 66, height: 36, padding: "0 12px", border: "1px solid var(--border)", borderRadius: 6, background: "var(--bg-hover)", color: "var(--text-muted)", cursor: locked ? "default" : "pointer", opacity: nativePickerBusy ? 0.6 : 1, transition: "background-color var(--dur-fast) var(--ease-out-warm), color var(--dur-fast) var(--ease-out-warm), opacity var(--dur-fast) var(--ease-out-warm)" }}
onMouseEnter={(e) => { if (!locked) { e.currentTarget.style.background = "var(--bg-selected)"; e.currentTarget.style.color = "var(--text)"; } }}
onMouseLeave={(e) => { e.currentTarget.style.background = "var(--bg-hover)"; e.currentTarget.style.color = "var(--text-muted)"; }}
>
{t("directoryPicker.browse")}
</button>
)}
</form>

<div className="directory-picker-list" style={{ flex: 1, minHeight: 0, overflow: "auto", padding: "8px 10px" }}>
Expand Down
44 changes: 44 additions & 0 deletions lib/cwd-picker.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import assert from "node:assert/strict";
import test from "node:test";

const { dialogOutcome, hasPicker, pickDirectory, pickerAvailable, pickerCommand } = await import("./cwd-picker.ts");

test("every desktop platform gets a folder dialog, anything else gets none", () => {
const win = pickerCommand("win32");
assert.equal(win?.file, "powershell.exe");
assert.ok(win?.args.includes("-STA"));
assert.ok(win?.args.some((arg) => arg.includes("System.Windows.Forms.FolderBrowserDialog")));
assert.ok(win?.args.some((arg) => arg.includes("[Console]::Out.Write")));
assert.equal(pickerCommand("darwin")?.file, "osascript");
assert.deepEqual(pickerCommand("linux")?.args.slice(0, 2), ["--file-selection", "--directory"]);
assert.equal(pickerCommand("freebsd"), null);
});

test("no chooser means no dialog and no error, and no Browse button either", async () => {
assert.equal(await pickDirectory("freebsd"), null);
assert.equal(hasPicker("freebsd"), false);
// Windows and macOS ship their chooser; Linux is the only platform whose binary can be missing.
assert.equal(hasPicker("win32"), true);
assert.equal(hasPicker("darwin"), true);
});

test("a dismissed dialog is not a failure, and an AppleScript error is not a dismissal", () => {
// The chosen path keeps a meaningful trailing space; only the line terminator goes.
assert.deepEqual(dialogOutcome("win32", 0, "C:\\Users\\me\\a folder \r\n", ""), { path: "C:\\Users\\me\\a folder " });
assert.deepEqual(dialogOutcome("win32", 0, "", ""), { cancelled: true });
assert.deepEqual(dialogOutcome("linux", 1, "", ""), { cancelled: true });
assert.deepEqual(dialogOutcome("darwin", 1, "", "execution error: User canceled. (-128)"), { cancelled: true });
assert.deepEqual(dialogOutcome("darwin", 1, "", "execution error: Can't get application. (-1728)\n"), {
error: "execution error: Can't get application. (-1728)",
});
assert.deepEqual(dialogOutcome("linux", 2, "", "zenity: cannot open display"), { error: "zenity: cannot open display" });
assert.deepEqual(dialogOutcome("win32", 1, "", ""), { error: "The folder dialog exited with code 1" });
});

test("a connection from another machine never gets the dialog, whatever its Host header said", () => {
// context.localPeer comes from the accepted socket, so a remote client cannot reach the dialog.
assert.equal(pickerAvailable(false, "win32"), false);
assert.equal(pickerAvailable(false, "darwin"), false);
assert.equal(pickerAvailable(true, "win32"), true);
assert.equal(pickerAvailable(true, "freebsd"), false);
});
88 changes: 88 additions & 0 deletions lib/cwd-picker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// The OS folder dialog for the machine running the server. Only meaningful when the page is
// opened on that same desktop, so the /api/cwd routes gate on the connection's peer address.
import { spawn, spawnSync } from "node:child_process";

export type PickedDirectory = { path: string } | { cancelled: true };

const DIALOG_TIMEOUT_MS = 5 * 60 * 1000;

/** The folder-dialog command for this platform, or null where we know no chooser. */
export function pickerCommand(platform: NodeJS.Platform = process.platform): { file: string; args: string[] } | null {
if (platform === "win32") {
// ponytail: the classic WinForms dialog, not IFileOpenDialog — it works from a non-console
// parent without COM plumbing; swap in the Vista-style picker if the look ever matters.
return {
file: "powershell.exe",
args: [
"-NoProfile",
"-STA",
"-Command",
[
"Add-Type -AssemblyName System.Windows.Forms | Out-Null",
"$d = New-Object System.Windows.Forms.FolderBrowserDialog",
"$d.Description = 'Select a folder'",
"$d.SelectedPath = $env:USERPROFILE",
"if ($d.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($d.SelectedPath) }",
].join("; "),
],
};
}
if (platform === "darwin") return { file: "osascript", args: ["-e", 'POSIX path of (choose folder with prompt "Select a folder")'] };
if (platform === "linux") return { file: "zenity", args: ["--file-selection", "--directory", "--title", "Select a folder"] };
return null;
}

/** Whether this platform's chooser is installed: Windows and macOS ship theirs, Linux needs zenity. */
export function hasPicker(platform: NodeJS.Platform = process.platform): boolean {
const command = pickerCommand(platform);
if (!command) return false;
if (platform !== "linux") return true;
return spawnSync("which", [command.file], { stdio: "ignore" }).status === 0;
}

/** Both the Browse button and the pick request need this: a chooser on the machine the browser is on. */
export function pickerAvailable(localPeer: boolean, platform: NodeJS.Platform = process.platform): boolean {
return localPeer && hasPicker(platform);
}

/** What a finished dialog means: a chosen path, a dismissal, or a failure worth reporting. */
export type DialogOutcome = PickedDirectory | { error: string };

/** Reads a chooser's exit status: only a real dismissal counts as cancellation. */
export function dialogOutcome(
platform: NodeJS.Platform | string,
code: number | null,
stdout: string,
stderr: string,
): DialogOutcome {
// Only the chooser's own line terminator: a directory name may end in a space.
const path = stdout.replace(/[\r\n]+$/, "");
if (path) return { path };
// Dismissed: zenity exits 1, the Windows dialog exits 0 with no output, and osascript exits 1
// for a cancelled dialog — but every other AppleScript error exits 1 too, so it needs -128.
const dismissed =
code === 0 || (code === 1 && (platform === "linux" || (platform === "darwin" && stderr.includes("(-128)"))));
if (dismissed) return { cancelled: true };
return { error: stderr.replace(/[\r\n]+$/, "") || `The folder dialog exited with code ${code}` };
}

/** Opens the dialog and waits for it; null when this platform has no chooser. */
export function pickDirectory(platform: NodeJS.Platform = process.platform): Promise<PickedDirectory | null> {
const command = pickerCommand(platform);
if (!command) return Promise.resolve(null);
return new Promise((resolve, reject) => {
const child = spawn(command.file, command.args, { windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
let stdout = "";
let stderr = "";
const timer = setTimeout(() => child.kill(), DIALOG_TIMEOUT_MS);
child.stdout.setEncoding("utf8").on("data", (chunk: string) => { stdout += chunk; });
child.stderr.setEncoding("utf8").on("data", (chunk: string) => { stderr += chunk; });
child.on("error", (cause) => { clearTimeout(timer); reject(cause); });
child.on("close", (code) => {
clearTimeout(timer);
const outcome = dialogOutcome(platform, code, stdout, stderr);
if ("error" in outcome) reject(new Error(outcome.error));
else resolve(outcome);
});
});
}
11 changes: 10 additions & 1 deletion lib/hosts/host-login.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const lock = `${file}.lock`;
const primary = { url: "https://production.example", token: "production-token" };
const staging = { url: "http://127.0.0.1:40000", token: "staging-token" };
const other = { url: "https://other.example", token: "other-token" };
const { addHostLink, loginHost, readHostLinks, readHostLogin, removeHostLink } = await import("./host-login.ts");
const { addHostLink, isLoopbackHost, loginHost, readHostLinks, readHostLogin, removeHostLink } = await import("./host-login.ts");
const saved = () => JSON.parse(readFileSync(file, "utf8"));
const seed = (value) => writeFileSync(file, JSON.stringify(value));
beforeEach(() => {
Expand Down Expand Up @@ -209,3 +209,12 @@ test("legacy login and concurrent add retain the additional entry", { timeout: 2
assert.deepEqual(readHostLogin(), other);
assert.deepEqual(new Map(readHostLinks().map((link) => [link.url, link.token])), new Map([staging, other].map((link) => [link.url, link.token])));
});

test("a socket address is loopback only for this machine, IPv4-mapped included", () => {
for (const address of ["127.0.0.1", "127.8.9.10", "::1", "[::1]", "::ffff:127.0.0.1", "localhost"]) {
assert.equal(isLoopbackHost(address), true, address);
}
for (const address of ["10.0.0.5", "::ffff:10.0.0.5", "192.168.1.20", "", "fe80::1"]) {
assert.equal(isLoopbackHost(address), false, address);
}
});
3 changes: 2 additions & 1 deletion lib/hosts/host-login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ export type HostLink = { url: string; token: string };
type SavedLink = HostLink & Record<string, unknown>;
type HostConfig = Record<string, unknown> & { url?: string; token?: string; links?: SavedLink[] };

export const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
/** A loopback name or address, including the IPv4-mapped form a dual-stack socket reports. */
export const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "::1" || hostname === "[::1]" || /^(::ffff:)?127(\.\d{1,3}){3}$/i.test(hostname);

/** Existing configuration must never be confused with a first login. */
export class HostLoginUnreadableError extends Error {
Expand Down
1 change: 1 addition & 0 deletions lib/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,7 @@
"subagentTranscript.completionTruncated": "Output truncated",
"codeBlock.copied": "copied",
"codeBlock.copy": "copy",
"directoryPicker.browse": "Browse…",
"directoryPicker.cancel": "Cancel",
"directoryPicker.checking": "Checking…",
"directoryPicker.close": "Close",
Expand Down
1 change: 1 addition & 0 deletions lib/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,7 @@
"subagentTranscript.completionTruncated": "出力は切り捨てられました",
"codeBlock.copied": "コピーしました",
"codeBlock.copy": "コピー",
"directoryPicker.browse": "参照…",
"directoryPicker.cancel": "キャンセル",
"directoryPicker.checking": "確認中…",
"directoryPicker.close": "閉じる",
Expand Down
1 change: 1 addition & 0 deletions lib/i18n/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,7 @@
"subagentTranscript.completionTruncated": "输出已被截断",
"codeBlock.copied": "已复制",
"codeBlock.copy": "复制",
"directoryPicker.browse": "浏览…",
"directoryPicker.cancel": "取消",
"directoryPicker.checking": "检查中…",
"directoryPicker.close": "关闭",
Expand Down
1 change: 1 addition & 0 deletions lib/i18n/locales/zh-TW.json
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,7 @@
"subagentTranscript.completionTruncated": "輸出已截斷",
"codeBlock.copied": "已複製",
"codeBlock.copy": "複製",
"directoryPicker.browse": "瀏覽…",
"directoryPicker.cancel": "取消",
"directoryPicker.checking": "檢查中…",
"directoryPicker.close": "關閉",
Expand Down
12 changes: 9 additions & 3 deletions server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
import path from "node:path";
import { parseArgs } from "node:util";
import { browserLink, type BrowserLinkData } from "@/lib/browser-link";
import { isLoopbackHost } from "@/lib/hosts/host-login";
import { hostLinkSocket, type LinkSocketData } from "@/lib/hosts/hub";
import { maintenanceSocket, type MaintenanceSocketData } from "@/lib/hosts/maintenance-hub";
import { proxy } from "@/proxy";
Expand Down Expand Up @@ -56,7 +57,7 @@ function decodable(pathname: string): boolean {
async function handle(
request: Request,
server: Bun.Server<ServerSocketData>,
respond: (context: { gate: "public" | "authenticated"; disableIdleTimeout: () => void }) => Response | undefined | Promise<Response | undefined>,
respond: (context: { gate: "public" | "authenticated"; disableIdleTimeout: () => void; localPeer: boolean }) => Response | undefined | Promise<Response | undefined>,
): Promise<Response | undefined> {
let pathname: string;
try {
Expand All @@ -67,6 +68,10 @@ async function handle(
}
const gate = proxy(request);
if (gate instanceof Response) return finalizeResponse(request, gate);
// Locality for routes that act on this desktop: the accepted socket, never request.url's host, which the
// client writes through its Host header.
const address = server.requestIP(request)?.address;
const localPeer = address !== undefined && isLoopbackHost(address);
if (!decodable(pathname)) return finalizeResponse(request, text("Bad Request", 400));
const lifted = gate === "authenticated" && pathname.startsWith("/api/");
if (lifted) server.timeout(request, 0);
Expand All @@ -76,6 +81,7 @@ async function handle(
try {
response = await respond({
gate,
localPeer,
disableIdleTimeout: () => {
keepOpen = true;
server.timeout(request, 0);
Expand Down Expand Up @@ -133,7 +139,7 @@ export function startServer(options: { port: number; hostname: string; dev: bool
for (const [key, mod] of Object.entries(ROUTE_MODULES)) {
const { pattern, rest } = routePattern(key);
const matcher = new URLPattern({ pathname: pattern });
routes[pattern] = (request, server) => handle(request, server, ({ disableIdleTimeout }) => {
routes[pattern] = (request, server) => handle(request, server, ({ disableIdleTimeout, localPeer }) => {
// Bun's router matched the raw path, but the gate and the handler read request.url, where `..` and `%2e%2e`
// are resolved. Answer only when that path is still this route, so no gated route runs under an ungated path.
const { pathname } = new URL(request.url);
Expand All @@ -144,7 +150,7 @@ export function startServer(options: { port: number; hostname: string; dev: bool
if (name !== "0" && value !== undefined) params[name] = decodeURIComponent(value);
}
if (rest) params[rest.name] = pathname.split("/").slice(rest.index).filter(Boolean).map(decodeURIComponent);
return dispatch(mod, request, params, disableIdleTimeout, (data) => server.upgrade(request, { data }));
return dispatch(mod, request, params, disableIdleTimeout, (data) => server.upgrade(request, { data }), localPeer);
});
}
if (html) routes[DEV_INDEX] = html;
Expand Down
Loading
Loading