mirror of
https://github.com/morluto/rea.git
synced 2026-11-19 21:23:45 +00:00
fix(desktop): honor env working directories in launch commands (#12111)
* fix(desktop): honor env working directories in launch commands * fix(desktop): create the replay working directory before launch --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
1 parent
9b1ffa1f7d
commit
bd5c985b3f
11 files changed
+289
-33
No files matched your search
@@ -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
|
||||
|
||||
@@ -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"],
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
};
|
||||
@@ -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",
|
||||
() => {
|
||||
|
||||
@@ -382,6 +382,31 @@ const launchCommand = async (
|
||||
});
|
||||
};
|
||||
|
||||
const envApplicationDirectory = async (
|
||||
path: string | undefined,
|
||||
workingDirectory: string,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Result<string | undefined, LinuxApplicationRefusal>> => {
|
||||
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,
|
||||
|
||||
@@ -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]):
|
||||
|
||||
@@ -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 `<option>=<path>` values that do, are respelled under the computer
|
||||
* user's `$HOME`.
|
||||
* user's `$HOME`. An explicit env working directory inside that home must
|
||||
* exist even when it has no seed files.
|
||||
*/
|
||||
export const launchCommand = (
|
||||
argv: readonly string[],
|
||||
capturedHome: string,
|
||||
workingDirectory: string,
|
||||
envWorkingDirectory?: string,
|
||||
): readonly string[] => {
|
||||
const homeUrl = (value: string): string | undefined => {
|
||||
const parsed = capturedFileUrl(value);
|
||||
@@ -514,8 +516,17 @@ export const launchCommand = (
|
||||
const respelled = argv.map(respell);
|
||||
const command = `exec ${argv.map((argument, index) => respelled[index] ?? shellQuote(argument)).join(" ")}`;
|
||||
const directory = underHome(workingDirectory) ?? shellQuote(workingDirectory);
|
||||
// A missing working directory must not stop the boot.
|
||||
return ["sh", "-c", `cd ${directory} 2>/dev/null; ${command}`];
|
||||
const requiredDirectory =
|
||||
envWorkingDirectory !== undefined &&
|
||||
isWithinAny(posix.normalize(envWorkingDirectory), [capturedHome])
|
||||
? underHome(envWorkingDirectory)
|
||||
: undefined;
|
||||
const prepare =
|
||||
requiredDirectory === undefined
|
||||
? ""
|
||||
: `mkdir -p -- ${requiredDirectory} && `;
|
||||
// The desktop entry's initial directory is best-effort.
|
||||
return ["sh", "-c", `cd ${directory} 2>/dev/null; ${prepare}${command}`];
|
||||
};
|
||||
|
||||
/** A Python string literal; JSON escapes are valid Python escapes. */
|
||||
|
||||
@@ -263,7 +263,10 @@ const packageSchema = z.strictObject({
|
||||
export const desktopApplicationInventorySchema = z.strictObject({
|
||||
desktop_entry: desktopEntrySchema.nullable(),
|
||||
argv: z.array(z.string()).min(1),
|
||||
/** Directory in which the recorded argv is invoked. */
|
||||
working_directory: z.string().min(1),
|
||||
/** Physical directory selected by an env chdir option, when present. */
|
||||
application_working_directory: z.string().min(1).optional(),
|
||||
executable: z.strictObject({
|
||||
path: z.string().min(1),
|
||||
resolved_path: z.string().nullable(),
|
||||
|
||||
@@ -267,6 +267,12 @@ export type DesktopCommandWrapper = {
|
||||
readonly program: string;
|
||||
/** Variables an `env` prefix sets; its `PATH` is the one that finds the program. */
|
||||
readonly environment: Readonly<Record<string, string>>;
|
||||
/** The last env chdir option and the argv span that carries its operand. */
|
||||
readonly chdir?: {
|
||||
readonly path: string;
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
};
|
||||
/** First argument of the application, after the program or flatpak's app id. */
|
||||
readonly argumentIndex: number;
|
||||
} & (
|
||||
@@ -347,15 +353,31 @@ const flatpakApplication = (argv: readonly string[], start: number) => {
|
||||
return { application_id: null, argumentIndex: argv.length };
|
||||
};
|
||||
|
||||
/** Apply `env [--] NAME=value` prefixes and recognise `flatpak run` launchers. */
|
||||
/** Apply env directory and assignment prefixes and recognise flatpak run launchers. */
|
||||
export const unwrapDesktopCommand = (
|
||||
argv: readonly string[],
|
||||
): DesktopCommandWrapper => {
|
||||
let index = 0;
|
||||
let chdir: DesktopCommandWrapper["chdir"];
|
||||
// No prototype, so an assignment such as `__proto__=x` stays a variable.
|
||||
const environment: Record<string, string> = Object.create(null);
|
||||
if (argv[0]?.split("/").at(-1) === "env") {
|
||||
index = 1;
|
||||
while (index < argv.length) {
|
||||
const option = argv[index]!;
|
||||
const separate = option === "-C" || option === "--chdir";
|
||||
const path = separate
|
||||
? (argv[index + 1] ?? "")
|
||||
: option.startsWith("--chdir=")
|
||||
? option.slice("--chdir=".length)
|
||||
: option.startsWith("-C")
|
||||
? option.slice(2)
|
||||
: undefined;
|
||||
if (path === undefined) break;
|
||||
const start = index;
|
||||
index += separate ? 2 : 1;
|
||||
chdir = { path, start, end: index };
|
||||
}
|
||||
// Only the option terminator before the first operand belongs to env;
|
||||
// a later `--` can name the command or belong to the application.
|
||||
if (argv[index] === "--") index += 1;
|
||||
@@ -367,12 +389,14 @@ export const unwrapDesktopCommand = (
|
||||
}
|
||||
}
|
||||
const program = argv[index] ?? "";
|
||||
const directoryOption = chdir === undefined ? {} : { chdir };
|
||||
if (program.split("/").at(-1) === "flatpak" && argv[index + 1] === "run")
|
||||
return {
|
||||
kind: "flatpak",
|
||||
program,
|
||||
environment,
|
||||
...flatpakApplication(argv, index + 2),
|
||||
...directoryOption,
|
||||
};
|
||||
return {
|
||||
kind: "direct",
|
||||
@@ -380,5 +404,6 @@ export const unwrapDesktopCommand = (
|
||||
environment,
|
||||
index,
|
||||
argumentIndex: index + 1,
|
||||
...directoryOption,
|
||||
};
|
||||
};
|
||||
@@ -140,7 +140,7 @@ describe("download install scripts", () => {
|
||||
expect(failed?.stderr).toContain("drawio.desktop");
|
||||
});
|
||||
|
||||
it.each(["", "-- "])(
|
||||
it.each(["", "-- ", "-C /opt --chdir=/tmp -- ", "--chdir= -C /tmp -- "])(
|
||||
"keeps an env %sprefix and its assignments when it points the AppImage's entry at AppRun",
|
||||
async (delimiter) => {
|
||||
const root = await stage("rea-appimage-env-");
|
||||
|
||||
@@ -1,11 +1,55 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import {
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
realpathSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { launchCommand } from "../../../src/domain/desktop/appExport.js";
|
||||
import { planLaunch } from "../../../src/application/desktop/DesktopExportLaunch.js";
|
||||
import type { DesktopApplicationCapture } from "../../../src/domain/desktop/desktopCapture.js";
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"launches in an empty env-selected directory under the replay home",
|
||||
() => {
|
||||
const home = mkdtempSync(join(tmpdir(), "rea-working-home-"));
|
||||
try {
|
||||
const selected = "Projects/Empty workspace";
|
||||
const capture = {
|
||||
host: { home: "/home/ada" },
|
||||
application: {
|
||||
argv: [
|
||||
"/usr/bin/env",
|
||||
"--chdir",
|
||||
`/home/ada/${selected}`,
|
||||
"/bin/pwd",
|
||||
],
|
||||
working_directory: "/home/ada/ambient",
|
||||
application_working_directory: `/home/ada/${selected}`,
|
||||
state_directories: [],
|
||||
},
|
||||
state: { state_directories: [] },
|
||||
} as unknown as DesktopApplicationCapture;
|
||||
const {
|
||||
command: [program, ...args],
|
||||
} = planLaunch(capture, false, new Map(), new Map());
|
||||
const result = spawnSync(program!, args, {
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, HOME: home },
|
||||
});
|
||||
expect(result.status, result.stderr).toBe(0);
|
||||
expect(result.stdout.trimEnd()).toBe(join(realpathSync(home), selected));
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"does not import seeded Python modules while encoding a file URL",
|
||||
|
||||
Reference in new issue
Block a user