diff --git a/docs/desktop-application-capture.md b/docs/desktop-application-capture.md index b26d705cb3..1abd67ad4c 100644 --- a/docs/desktop-application-capture.md +++ b/docs/desktop-application-capture.md @@ -41,7 +41,11 @@ requires, so a relative value leaves the home default in use instead of naming a folder under the working directory. The entry's `Exec` line is expanded with no files; `--argument` values are appended in its place, and the application runs in the -entry's `Path` or the home directory. When the line starts with +entry's `Path` or the home directory. An `env -C` or `env --chdir` prefix +selects the directory for executable lookup and relative arguments. Capture +retains the original argv and launch directory, with the resolved application +directory recorded as `application_working_directory`. Export maps that +directory into the seed before replay. When the line starts with `env NAME=value` or `env -- NAME=value`, the program is found on the `PATH` those assignments set, with an empty or relative entry read from the folder the application runs in, and their XDG folders name the state directories. Otherwise the program is diff --git a/src/application/desktop/DesktopExportLaunch.test.ts b/src/application/desktop/DesktopExportLaunch.test.ts index b332ae35d8..05766c645e 100644 --- a/src/application/desktop/DesktopExportLaunch.test.ts +++ b/src/application/desktop/DesktopExportLaunch.test.ts @@ -11,6 +11,38 @@ const file = (physical: string, role: StatePath["role"]): StatePath => ({ path: physical, role }) as StatePath; describe("planLaunch captured paths", () => { + it("uses the env-selected directory to identify and replay a relative document", () => { + const first = `${HOME}/ambient`; + const selected = `${HOME}/selected`; + const capture = { + host: { home: HOME }, + application: { + argv: ["env", "--chdir=../selected", "--", "./app", "project.txt"], + working_directory: first, + application_working_directory: selected, + desktop_entry: { exec: "env --chdir=../selected -- ./app %f" }, + state_directories: [], + }, + state: { state_directories: [] }, + } as unknown as DesktopApplicationCapture; + const files = new Map([ + [ + "ambient/project.txt", + file(`${first}/project.txt`, "application_state"), + ], + ["selected/project.txt", file(`${selected}/project.txt`, "document")], + ]); + const seeds = new Map([ + ["selected/project.txt", { sha256: "a".repeat(64), format: "text" }], + ]); + const launch = planLaunch(capture, false, seeds, files); + expect(launch.opens).toEqual({ kind: "captured" }); + expect(launch.command[2]).toContain('cd "$HOME"/'); + expect(launch.command[2]).toMatch(/'-C'[^;]+\$HOME[^;]+selected/u); + expect(launch.command[2]).not.toContain("../selected"); + expect(launch.command[2]).toContain("project.txt"); + }); + it.each([ ["/mnt/data/books.db", "/mnt/data/books.db"], ["file:///mnt/data/books.db?mode=edit#page", "/mnt/data/books.db"], diff --git a/src/application/desktop/DesktopExportLaunch.ts b/src/application/desktop/DesktopExportLaunch.ts index d422059047..93101d84b9 100644 --- a/src/application/desktop/DesktopExportLaunch.ts +++ b/src/application/desktop/DesktopExportLaunch.ts @@ -10,6 +10,7 @@ import { type DesktopApplicationState, } from "../../domain/desktop/desktopState.js"; import { isWithinAny } from "../../domain/desktop/desktopStateDiff.js"; +import { unwrapDesktopCommand } from "../../domain/desktop/desktopEntry.js"; import { openSeedDocument } from "../../domain/desktop/seedDocument.js"; import { isTextualFormat } from "../../domain/desktop/stateFormats.js"; import type { SeedVersion } from "./DesktopExportFiles.js"; @@ -118,32 +119,55 @@ export const planLaunch = ( const { application, host } = capture; const isDocument = (home: string) => files.get(home)?.role === "document"; const homeOf = capturedHomePath(capture); - const capturedDirectory = application.working_directory; - const workingDirectory = (() => { - if (!capturedDirectory.startsWith(`${host.home}/`)) - return capturedDirectory; - const relative = capturedDirectory.slice(host.home.length + 1); - const seed = homeOf(capturedDirectory) ?? relative; - return seed === relative ? capturedDirectory : `${host.home}/${seed}`; - })(); - const launch = openSeedDocument( - electronLaunchArguments(application.argv, electron), - { - home: host.home, - // Resolve captured relative arguments against the directory the app used, - // then place the process in the seeded spelling of that directory. - workingDirectory: capturedDirectory, - launchDirectory: workingDirectory, - exec: application.desktop_entry?.exec ?? null, - documents: [...seeds.keys()].filter(isDocument).sort(), - isDocument, - isCaptured: capturedLaunchPaths(capture, files, homeOf), - spell: (path) => homeOf(`${host.home}/${path}`) ?? path, - mapOutside: homeOf, - }, - ); + const capturedDirectory = + application.application_working_directory ?? application.working_directory; + const seedDirectory = (directory: string): string => { + if (!directory.startsWith(`${host.home}/`)) return directory; + const relative = directory.slice(host.home.length + 1); + const seed = homeOf(directory) ?? relative; + return seed === relative ? directory : `${host.home}/${seed}`; + }; + const selectedSeed = + application.application_working_directory === undefined + ? null + : homeOf(capturedDirectory); + const workingDirectory = + selectedSeed === null + ? seedDirectory(capturedDirectory) + : `${host.home}/${selectedSeed}`; + const chdir = + application.application_working_directory === undefined + ? undefined + : unwrapDesktopCommand(application.argv).chdir; + const argv = + chdir !== undefined + ? [ + ...application.argv.slice(0, chdir.start), + "-C", + workingDirectory, + ...application.argv.slice(chdir.end), + ] + : application.argv; + const launch = openSeedDocument(electronLaunchArguments(argv, electron), { + home: host.home, + // Resolve captured relative arguments against the directory the app used, + // then place the process in the seeded spelling of that directory. + workingDirectory: capturedDirectory, + launchDirectory: workingDirectory, + exec: application.desktop_entry?.exec ?? null, + documents: [...seeds.keys()].filter(isDocument).sort(), + isDocument, + isCaptured: capturedLaunchPaths(capture, files, homeOf), + spell: (path) => homeOf(`${host.home}/${path}`) ?? path, + mapOutside: homeOf, + }); return { - command: launchCommand(launch.argv, host.home, workingDirectory), + command: launchCommand( + launch.argv, + host.home, + seedDirectory(application.working_directory), + chdir === undefined ? undefined : workingDirectory, + ), opens: launch.opens, }; }; diff --git a/src/desktop/LinuxApplicationInventory.test.ts b/src/desktop/LinuxApplicationInventory.test.ts index 9037ea94bc..0ea1ec95f9 100644 --- a/src/desktop/LinuxApplicationInventory.test.ts +++ b/src/desktop/LinuxApplicationInventory.test.ts @@ -664,6 +664,69 @@ const inventoryOf = async ( return inspected.value.inventory; }; +describe.skipIf(process.platform === "win32")( + "env chdir desktop launch", + () => { + it("finds the executable from the selected physical directory while preserving argv and launch Path", async () => { + const installed = await fixture(); + const { home, environment } = installed; + const parent = join(home, "selected"); + await mkdir(join(parent, "child"), { recursive: true }); + await symlink(join(parent, "child"), join(home, "alias")); + await writeFile(join(parent, "notes-app"), "#!/bin/sh\nexit 0\n"); + await chmod(join(parent, "notes-app"), 0o755); + await writeFile( + join( + environment.XDG_DATA_DIRS, + "applications/org.example.notes.desktop", + ), + `[Desktop Entry]\nType=Application\nName=Notes\nPath=${home}\nExec=/usr/bin/env -C alias/.. -- ./notes-app project.txt\n`, + ); + const inventory = await inventoryOf("org.example.notes", installed); + expect(inventory).toMatchObject({ + argv: [ + "/usr/bin/env", + "-C", + "alias/..", + "--", + "./notes-app", + "project.txt", + ], + working_directory: home, + application_working_directory: await realpath(parent), + executable: { + resolved_path: await realpath(join(parent, "notes-app")), + }, + }); + }); + + it("rejects an absent chdir directory even with an absolute program", async () => { + const { home, bin, environment } = await fixture(); + const desktopEntry = join( + environment.XDG_DATA_DIRS, + "applications/org.example.notes.desktop", + ); + await writeFile( + desktopEntry, + `[Desktop Entry]\nType=Application\nName=Notes\nPath=${home}\nExec=env --chdir=missing ${bin}/notes-app\n`, + ); + expect( + await inspectLinuxApplication({ + desktopEntry, + executable: undefined, + arguments: [], + environment, + home, + callerDirectory: home, + }), + ).toMatchObject({ + ok: false, + error: { reason: "desktop_entry_invalid" }, + }); + }); + }, +); + describe.skipIf(process.platform === "win32")( "inspectLinuxApplication state and environment", () => { diff --git a/src/desktop/LinuxApplicationInventory.ts b/src/desktop/LinuxApplicationInventory.ts index 2cb23b1706..af7bc83731 100644 --- a/src/desktop/LinuxApplicationInventory.ts +++ b/src/desktop/LinuxApplicationInventory.ts @@ -382,6 +382,31 @@ const launchCommand = async ( }); }; +const envApplicationDirectory = async ( + path: string | undefined, + workingDirectory: string, + signal: AbortSignal | undefined, +): Promise> => { + if (path === undefined) return ok(undefined); + const invalidDirectory = { + reason: "desktop_entry_invalid" as const, + detail: "env chdir does not name a directory", + }; + if (path === "") return err(invalidDirectory); + const selected = absoluteCallerPath(path, { cwd: workingDirectory }); + try { + assertArtifactReadActive(signal); + const physical = await realpath(selected); + assertArtifactReadActive(signal); + const directory = await stat(physical); + assertArtifactReadActive(signal); + return directory.isDirectory() ? ok(physical) : err(invalidDirectory); + } catch (cause: unknown) { + if (!isRefusedRead(cause) || signal?.aborted === true) throw cause; + return err(invalidDirectory); + } +}; + /** Resolve what the request launches, where it came from and where it may keep state. */ export const inspectLinuxApplication = async ( request: LinuxApplicationRequest, @@ -392,13 +417,20 @@ export const inspectLinuxApplication = async ( if (!command.ok) return command; const { argv, workingDirectory, entry } = command.value; const wrapper = unwrapDesktopCommand(argv); + const directory = await envApplicationDirectory( + wrapper.chdir?.path, + workingDirectory, + signal, + ); + if (!directory.ok) return directory; + const applicationDirectory = directory.value; // An `env` prefix's assignments are what the program sees: its PATH finds // the program and its XDG folders hold the program's state. const environment = { ...request.environment, ...wrapper.environment }; const found = await resolveProgram( wrapper.program, environment, - workingDirectory, + applicationDirectory ?? workingDirectory, ); if (found === undefined) return err({ reason: "executable_not_found", program: wrapper.program }); @@ -457,6 +489,9 @@ export const inspectLinuxApplication = async ( desktop_entry: entry, argv: [...argv], working_directory: workingDirectory, + ...(applicationDirectory === undefined + ? {} + : { application_working_directory: applicationDirectory }), executable: { path, resolved_path: resolved, diff --git a/src/domain/desktop/appDownloadDesktop.ts b/src/domain/desktop/appDownloadDesktop.ts index f910b373a0..281a5e0e0d 100644 --- a/src/domain/desktop/appDownloadDesktop.ts +++ b/src/domain/desktop/appDownloadDesktop.ts @@ -59,6 +59,21 @@ def program_span(raw): index = 0 if tokens and tokens[0][0].split("/")[-1] == "env": index = 1 + directory = None + while index < len(tokens): + option = tokens[index][0] + if option in ("-C", "--chdir"): + index += 1 + directory = tokens[index][0] if index < len(tokens) else "" + elif option.startswith("--chdir="): + directory = option[len("--chdir="):] + elif option.startswith("-C"): + directory = option[2:] + else: + break + index += 1 + if directory == "": + raise ValueError("missing env chdir directory in desktop Exec") if index < len(tokens) and tokens[index][0] == "--": index += 1 while index < len(tokens) and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", tokens[index][0]): diff --git a/src/domain/desktop/appExport.ts b/src/domain/desktop/appExport.ts index 01ddb6216f..af9757d53f 100644 --- a/src/domain/desktop/appExport.ts +++ b/src/domain/desktop/appExport.ts @@ -462,12 +462,14 @@ const docText = (value: string): string => value.replace(/["\\]/gu, "'"); * folder, where an open or save dialog would show build files. That * directory, arguments that are or start with a path under the captured home, * and `