diff --git a/app/api/cwd/pick/route.ts b/app/api/cwd/pick/route.ts new file mode 100644 index 000000000..9a2db36d2 --- /dev/null +++ b/app/api/cwd/pick/route.ts @@ -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); + } +} diff --git a/app/api/cwd/picker/route.ts b/app/api/cwd/picker/route.ts new file mode 100644 index 000000000..cec556278 --- /dev/null +++ b/app/api/cwd/picker/route.ts @@ -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) }); +} diff --git a/components/DirectoryPicker.tsx b/components/DirectoryPicker.tsx index f15f3ad22..47c9c42fc 100644 --- a/components/DirectoryPicker.tsx +++ b/components/DirectoryPicker.tsx @@ -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; @@ -74,6 +75,8 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, const [directories, setDirectories] = useState([]); const [drives, setDrives] = useState(null); const [loadError, setLoadError] = useState(null); + const [nativePickerAvailable, setNativePickerAvailable] = useState(false); + const [nativePickerBusy, setNativePickerBusy] = useState(false); const [profile, setProfile] = useState(""); const [advisor, setAdvisor] = useState(false); const [extraArgs, setExtraArgs] = useState(""); @@ -87,7 +90,7 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, const cloneLogRef = useRef(null); const browseAbortRef = useRef(null); const cloning = cloneId !== null; - const locked = busy || cloning; + const locked = busy || cloning || nativePickerBusy; const dialogRef = useModalDialog({ onClose: () => { if (!locked) onCancel(); }, active: portalTarget !== null, @@ -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(() => { @@ -302,6 +334,20 @@ export function DirectoryPicker({ onCancel, onSelect, busy = false, error, host, > {t("directoryPicker.go")} + {nativePickerAvailable && !pool && ( + + )}
diff --git a/lib/cwd-picker.test.mjs b/lib/cwd-picker.test.mjs new file mode 100644 index 000000000..67ed40e22 --- /dev/null +++ b/lib/cwd-picker.test.mjs @@ -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); +}); diff --git a/lib/cwd-picker.ts b/lib/cwd-picker.ts new file mode 100644 index 000000000..a19d48f6f --- /dev/null +++ b/lib/cwd-picker.ts @@ -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 { + 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); + }); + }); +} diff --git a/lib/hosts/host-login.test.mjs b/lib/hosts/host-login.test.mjs index b06dcfaed..a8d7a5324 100644 --- a/lib/hosts/host-login.test.mjs +++ b/lib/hosts/host-login.test.mjs @@ -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(() => { @@ -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); + } +}); diff --git a/lib/hosts/host-login.ts b/lib/hosts/host-login.ts index cf905b57d..08d22f4aa 100644 --- a/lib/hosts/host-login.ts +++ b/lib/hosts/host-login.ts @@ -15,7 +15,8 @@ export type HostLink = { url: string; token: string }; type SavedLink = HostLink & Record; type HostConfig = Record & { 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 { diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 7013dc26b..4b5056479 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -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", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 93da3edf9..ab50953bc 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -653,6 +653,7 @@ "subagentTranscript.completionTruncated": "出力は切り捨てられました", "codeBlock.copied": "コピーしました", "codeBlock.copy": "コピー", + "directoryPicker.browse": "参照…", "directoryPicker.cancel": "キャンセル", "directoryPicker.checking": "確認中…", "directoryPicker.close": "閉じる", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index cf8d7e4fe..8f523f04f 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -653,6 +653,7 @@ "subagentTranscript.completionTruncated": "输出已被截断", "codeBlock.copied": "已复制", "codeBlock.copy": "复制", + "directoryPicker.browse": "浏览…", "directoryPicker.cancel": "取消", "directoryPicker.checking": "检查中…", "directoryPicker.close": "关闭", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index 8ae164ba8..c29b24ad1 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -669,6 +669,7 @@ "subagentTranscript.completionTruncated": "輸出已截斷", "codeBlock.copied": "已複製", "codeBlock.copy": "複製", + "directoryPicker.browse": "瀏覽…", "directoryPicker.cancel": "取消", "directoryPicker.checking": "檢查中…", "directoryPicker.close": "關閉", diff --git a/server/app.ts b/server/app.ts index 5b87e2c65..f04d7537e 100644 --- a/server/app.ts +++ b/server/app.ts @@ -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"; @@ -56,7 +57,7 @@ function decodable(pathname: string): boolean { async function handle( request: Request, server: Bun.Server, - respond: (context: { gate: "public" | "authenticated"; disableIdleTimeout: () => void }) => Response | undefined | Promise, + respond: (context: { gate: "public" | "authenticated"; disableIdleTimeout: () => void; localPeer: boolean }) => Response | undefined | Promise, ): Promise { let pathname: string; try { @@ -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); @@ -76,6 +81,7 @@ async function handle( try { response = await respond({ gate, + localPeer, disableIdleTimeout: () => { keepOpen = true; server.timeout(request, 0); @@ -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); @@ -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; diff --git a/server/routes.ts b/server/routes.ts index d6cfea353..a2d3a1428 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -12,6 +12,8 @@ import * as authApiKeyProvider from "@/app/api/auth/api-key/[provider]/route"; import * as authLoginProvider from "@/app/api/auth/login/[provider]/route"; import * as authProviders from "@/app/api/auth/providers/route"; import * as cwdBrowse from "@/app/api/cwd/browse/route"; +import * as cwdPick from "@/app/api/cwd/pick/route"; +import * as cwdPicker from "@/app/api/cwd/picker/route"; import * as cwdValidate from "@/app/api/cwd/validate/route"; import * as defaultCwd from "@/app/api/default-cwd/route"; import * as events from "@/app/api/events/route"; @@ -95,9 +97,10 @@ type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; // its socket; see handle() in server/app.ts. // upgrade: makes the request a WebSocket (server.upgrade), a host link or a browser link; a handler that upgraded // returns undefined. +// localPeer: the connection came from this machine's loopback interface. Taken from the socket, never from Host. export type RouteHandler = ( request: Request, - context: { params: Promise; disableIdleTimeout: () => void; upgrade: (data: ServerSocketData) => boolean }, + context: { params: Promise; disableIdleTimeout: () => void; upgrade: (data: ServerSocketData) => boolean; localPeer: boolean }, ) => Response | undefined | Promise; export type RouteModule = Partial>; @@ -115,6 +118,8 @@ export const ROUTE_MODULES: Record = { "auth/login/[provider]": authLoginProvider, "auth/providers": authProviders, "cwd/browse": cwdBrowse, + "cwd/pick": cwdPick, + "cwd/picker": cwdPicker, "cwd/validate": cwdValidate, "default-cwd": defaultCwd, "events": events, @@ -205,6 +210,7 @@ export async function dispatch( params: Record, disableIdleTimeout: () => void = () => {}, upgrade: (data: ServerSocketData) => boolean = () => false, + localPeer = false, ): Promise { const handler = mod[request.method as Method] ?? (request.method === "HEAD" ? mod.GET : undefined); if (!handler) { @@ -214,7 +220,7 @@ export async function dispatch( return new Response(null, { status: 204, headers: { allow } }); } try { - return await handler(request, { params: Promise.resolve(params) as Promise, disableIdleTimeout, upgrade }); + return await handler(request, { params: Promise.resolve(params) as Promise, disableIdleTimeout, upgrade, localPeer }); } catch (error) { console.error(error); return Response.json({ error: "Internal Server Error" }, { status: 500 });