Skip to content

Commit 0048d05

Browse files
author
Peter Steinberger
committed
fix(wizard): reuse canonical completion profile hints
1 parent 0dc3f2b commit 0048d05

5 files changed

Lines changed: 291 additions & 60 deletions

File tree

‎src/cli/completion-runtime.test.ts‎

Lines changed: 169 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { spawnSync, type SpawnSyncReturns } from "node:child_process";
33
import fs from "node:fs/promises";
44
import path from "node:path";
5-
import { afterEach, describe, expect, it } from "vitest";
5+
import { afterEach, describe, expect, it, vi } from "vitest";
66
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
77
import { withEnvAsync } from "../test-utils/env.js";
88
import {
@@ -11,6 +11,7 @@ import {
1111
installCompletion,
1212
isCompletionInstalled,
1313
resolveCompletionCachePath,
14+
resolveCompletionProfileHint,
1415
resolveCompletionProfilePath,
1516
resolveShellFromEnv,
1617
usesSlowDynamicCompletion,
@@ -113,6 +114,154 @@ describe("completion-runtime", () => {
113114
).toBe(path.join(path.sep, ".zshrc"));
114115
});
115116

117+
it.skipIf(process.platform === "win32")(
118+
"preserves Zsh and Fish symlink traversal before parent path components",
119+
async () => {
120+
for (const testCase of [
121+
{ shell: "zsh" as const, variable: "ZDOTDIR", profileName: ".zshrc" },
122+
{
123+
shell: "fish" as const,
124+
variable: "XDG_CONFIG_HOME",
125+
profileName: path.join("fish", "config.fish"),
126+
},
127+
]) {
128+
await withBashCompletionHome(async ({ homeDir }) => {
129+
const profileParent = tempDirs.make(`openclaw-${testCase.shell}-symlink-profiles-`);
130+
const nestedProfiles = path.join(profileParent, "nested");
131+
const linkedProfiles = path.join(homeDir, "linked-profiles");
132+
await fs.mkdir(nestedProfiles, { recursive: true });
133+
await fs.symlink(nestedProfiles, linkedProfiles, "dir");
134+
135+
await withEnvAsync(
136+
{ [testCase.variable]: `${linkedProfiles}${path.sep}..` },
137+
async () => {
138+
const cachePath = resolveCompletionCachePath(testCase.shell, "openclaw");
139+
await fs.mkdir(path.dirname(cachePath), { recursive: true });
140+
await fs.writeFile(cachePath, "OPENCLAW_COMPLETION_LOADED=ready\n", "utf8");
141+
142+
await installCompletion(testCase.shell, true, "openclaw");
143+
144+
const profilePath = path.join(profileParent, testCase.profileName);
145+
await expect(fs.readFile(profilePath, "utf8")).resolves.toContain(cachePath);
146+
expect(resolveCompletionProfileHint(testCase.shell)).toBe(
147+
`~${path.sep}linked-profiles${path.sep}..${path.sep}${testCase.profileName}`,
148+
);
149+
},
150+
);
151+
});
152+
}
153+
},
154+
);
155+
156+
it.skipIf(process.platform === "win32")(
157+
"preserves every shell's default profile traversal through a symlinked HOME",
158+
async () => {
159+
const fixtureRoot = tempDirs.make("openclaw-completion-home-symlink-");
160+
const realHome = path.join(fixtureRoot, "real-home");
161+
const nestedHome = path.join(realHome, "nested");
162+
const linkedHome = path.join(fixtureRoot, "linked-home");
163+
await fs.mkdir(nestedHome, { recursive: true });
164+
await fs.symlink(nestedHome, linkedHome, "dir");
165+
166+
for (const testCase of [
167+
{ shell: "zsh" as const, profileName: ".zshrc" },
168+
{ shell: "bash" as const, profileName: ".bash_profile" },
169+
{ shell: "fish" as const, profileName: path.join(".config", "fish", "config.fish") },
170+
{
171+
shell: "powershell" as const,
172+
profileName: path.join(".config", "powershell", "Microsoft.PowerShell_profile.ps1"),
173+
},
174+
]) {
175+
const stateDir = tempDirs.make(`openclaw-${testCase.shell}-home-symlink-state-`);
176+
await withEnvAsync(
177+
{
178+
HOME: `${linkedHome}${path.sep}..`,
179+
USERPROFILE: `${linkedHome}${path.sep}..`,
180+
OPENCLAW_STATE_DIR: stateDir,
181+
XDG_CONFIG_HOME: undefined,
182+
ZDOTDIR: undefined,
183+
},
184+
async () => {
185+
const cachePath = resolveCompletionCachePath(testCase.shell, "openclaw");
186+
await fs.mkdir(path.dirname(cachePath), { recursive: true });
187+
await fs.writeFile(cachePath, `# cached ${testCase.shell} completion\n`, "utf8");
188+
189+
await installCompletion(testCase.shell, true, "openclaw");
190+
191+
const actualStartupProfile = path.join(realHome, testCase.profileName);
192+
await expect(fs.readFile(actualStartupProfile, "utf8")).resolves.toContain(cachePath);
193+
expect(resolveCompletionProfileHint(testCase.shell)).toBe(
194+
testCase.shell === "powershell"
195+
? `${linkedHome}${path.sep}..${path.sep}${testCase.profileName}`
196+
: `~/${testCase.profileName}`,
197+
);
198+
},
199+
);
200+
}
201+
},
202+
);
203+
204+
it.each(["relative-xdg", "~/relative-xdg"])(
205+
"ignores invalid relative Fish XDG configuration roots: %s",
206+
(configHome) => {
207+
const homeDir = path.join(path.sep, "tmp", "openclaw-home");
208+
expect(
209+
resolveCompletionProfilePath("fish", {
210+
env: { HOME: homeDir, XDG_CONFIG_HOME: configHome },
211+
homeDir: () => homeDir,
212+
}),
213+
).toBe(path.join(homeDir, ".config", "fish", "config.fish"));
214+
},
215+
);
216+
217+
it("preserves significant trailing whitespace in an absolute Fish XDG directory", () => {
218+
const homeDir = path.join(path.sep, "tmp", "openclaw-home");
219+
const configHome = path.join(path.sep, "tmp", "Fish Config ");
220+
expect(
221+
resolveCompletionProfilePath("fish", {
222+
env: { HOME: homeDir, XDG_CONFIG_HOME: configHome },
223+
homeDir: () => homeDir,
224+
}),
225+
).toBe(path.join(configHome, "fish", "config.fish"));
226+
});
227+
228+
it.each([
229+
{
230+
configHome: "C:\\Users\\Ada\\Fish Config",
231+
expected: "C:\\Users\\Ada\\Fish Config\\fish\\config.fish",
232+
},
233+
{
234+
configHome: "relative-fish",
235+
expected: "C:\\Users\\Ada\\.config\\fish\\config.fish",
236+
},
237+
{
238+
configHome: "\\\\fileserver\\profiles\\Fish Config",
239+
expected: "\\\\fileserver\\profiles\\Fish Config\\fish\\config.fish",
240+
},
241+
])("resolves Windows Fish profiles with Windows separators: $configHome", (testCase) => {
242+
const homeDir = "C:\\Users\\Ada";
243+
expect(
244+
resolveCompletionProfilePath("fish", {
245+
env: { HOME: homeDir, XDG_CONFIG_HOME: testCase.configHome },
246+
homeDir: () => homeDir,
247+
platform: "win32",
248+
}),
249+
).toBe(testCase.expected);
250+
});
251+
252+
it.each(["~/literal startup", "~root/startup", "-startup", "../startup"])(
253+
"keeps relative Zsh profile hints literal: %s",
254+
async (profileRoot) => {
255+
await withEnvAsync({ HOME: "/tmp/openclaw-home", ZDOTDIR: profileRoot }, async () => {
256+
const profilePath = path.join(profileRoot, ".zshrc");
257+
const expected = profilePath.startsWith(`..${path.sep}`)
258+
? profilePath
259+
: `.${path.sep}${profilePath}`;
260+
expect(resolveCompletionProfileHint("zsh")).toBe(expected);
261+
});
262+
},
263+
);
264+
116265
it("resolves the documented Bash login profile when .bashrc is absent", async () => {
117266
await withBashCompletionHome(async ({ homeDir }) => {
118267
expect(resolveCompletionProfilePath("bash")).toBe(path.join(homeDir, ".bash_profile"));
@@ -150,6 +299,25 @@ describe("completion-runtime", () => {
150299
});
151300
});
152301

302+
it("prints the same canonical reload hint used by Doctor and onboarding", async () => {
303+
await withBashCompletionHome(async ({ homeDir }) => {
304+
const cachePath = resolveCompletionCachePath("zsh", "openclaw");
305+
await fs.mkdir(path.dirname(cachePath), { recursive: true });
306+
await fs.writeFile(cachePath, "OPENCLAW_COMPLETION_LOADED=ready\n", "utf8");
307+
await fs.writeFile(path.join(homeDir, ".zshrc"), "", "utf8");
308+
const log = vi.spyOn(console, "log").mockImplementation(() => {});
309+
310+
try {
311+
await installCompletion("zsh", false, "openclaw");
312+
expect(log).toHaveBeenCalledWith(
313+
"Completion installed. Restart your shell or run: source ~/.zshrc",
314+
);
315+
} finally {
316+
log.mockRestore();
317+
}
318+
});
319+
});
320+
153321
it("detects slow dynamic Bash completion in the login profile", async () => {
154322
await withBashCompletionHome(async ({ homeDir }) => {
155323
await fs.writeFile(

‎src/cli/completion-runtime.ts‎

Lines changed: 52 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,17 @@ function formatCompletionSourceLine(shell: CompletionShell, cachePath: string):
9595
return `[ -f "${cachePath}" ] && source "${cachePath}"`;
9696
}
9797

98+
function appendCompletionProfilePath(
99+
directory: string,
100+
pathApi: typeof path.posix,
101+
...segments: string[]
102+
): string {
103+
// Shell startup resolves symlinks before `..`; path.join would select a different profile.
104+
const nativeDirectory = pathApi.sep === "\\" ? directory.replaceAll("/", pathApi.sep) : directory;
105+
const separator = nativeDirectory.endsWith(pathApi.sep) ? "" : pathApi.sep;
106+
return `${nativeDirectory}${separator}${segments.join(pathApi.sep)}`;
107+
}
108+
98109
/** Formats the command users can run to reload the shell profile after installation. */
99110
export function formatCompletionReloadCommand(shell: CompletionShell, profilePath: string): string {
100111
if (shell === "powershell") {
@@ -272,31 +283,64 @@ export function resolveCompletionProfilePath(
272283
const env = options.env ?? process.env;
273284
const homeDir = options.homeDir ?? os.homedir;
274285
const platform = options.platform ?? process.platform;
286+
const pathApi = platform === "win32" ? path.win32 : path.posix;
275287
const home = env.HOME || homeDir();
276288
if (shell === "zsh") {
277-
return path.join(env.ZDOTDIR === undefined ? home : env.ZDOTDIR || path.sep, ".zshrc");
289+
const profileDirectory = env.ZDOTDIR === undefined ? home : env.ZDOTDIR || pathApi.sep;
290+
return appendCompletionProfilePath(profileDirectory, pathApi, ".zshrc");
278291
}
279292
if (shell === "bash") {
280293
// Installation, status, and repairs must inspect the same real Bash profile.
281-
const bashrc = path.join(home, ".bashrc");
282-
return existsSync(bashrc) ? bashrc : path.join(home, ".bash_profile");
294+
const bashrc = appendCompletionProfilePath(home, pathApi, ".bashrc");
295+
return existsSync(bashrc)
296+
? bashrc
297+
: appendCompletionProfilePath(home, pathApi, ".bash_profile");
283298
}
284299
if (shell === "fish") {
285-
const configHome = normalizeOptionalString(env.XDG_CONFIG_HOME) ?? path.join(home, ".config");
286-
return path.join(configHome, "fish", "config.fish");
300+
const configuredHome = env.XDG_CONFIG_HOME;
301+
const configHome =
302+
configuredHome && pathApi.isAbsolute(configuredHome)
303+
? configuredHome
304+
: appendCompletionProfilePath(home, pathApi, ".config");
305+
return appendCompletionProfilePath(configHome, pathApi, "fish", "config.fish");
287306
}
288307
if (platform === "win32") {
289308
const shellPath = normalizeOptionalString(env.SHELL) ?? "";
290309
const shellName = shellPath ? resolveShellBasename(shellPath, platform) : "";
291310
const profileDirectory = shellName === "powershell" ? "WindowsPowerShell" : "PowerShell";
292-
return path.win32.join(
311+
return appendCompletionProfilePath(
293312
env.USERPROFILE || home,
313+
pathApi,
294314
"Documents",
295315
profileDirectory,
296316
"Microsoft.PowerShell_profile.ps1",
297317
);
298318
}
299-
return path.join(home, ".config", "powershell", "Microsoft.PowerShell_profile.ps1");
319+
return appendCompletionProfilePath(
320+
home,
321+
pathApi,
322+
".config",
323+
"powershell",
324+
"Microsoft.PowerShell_profile.ps1",
325+
);
326+
}
327+
328+
/** Formats the resolved startup profile relative to HOME when that preserves its actual location. */
329+
export function resolveCompletionProfileHint(shell: CompletionShell): string {
330+
const profilePath = resolveCompletionProfilePath(shell);
331+
if (shell === "powershell") {
332+
return profilePath;
333+
}
334+
if (!path.isAbsolute(profilePath)) {
335+
return profilePath.startsWith(`.${path.sep}`) || profilePath.startsWith(`..${path.sep}`)
336+
? profilePath
337+
: `.${path.sep}${profilePath}`;
338+
}
339+
const home = process.env.HOME;
340+
// Keep lexical parent components so reload follows the same symlink path as installation.
341+
return home && profilePath.startsWith(`${home}${path.sep}`)
342+
? `~/${profilePath.slice(home.length + 1)}`
343+
: profilePath;
300344
}
301345

302346
/** Returns whether a shell profile already contains an OpenClaw completion block or source line. */
@@ -387,7 +431,7 @@ export async function installCompletion(shell: string, yes: boolean, binName = "
387431
await fs.writeFile(profilePath, update.next, "utf-8");
388432
if (!yes) {
389433
console.log(
390-
`Completion installed. Restart your shell or run: ${formatCompletionReloadCommand(shell, profilePath)}`,
434+
`Completion installed. Restart your shell or run: ${formatCompletionReloadCommand(shell, resolveCompletionProfileHint(shell))}`,
391435
);
392436
}
393437
} catch (err) {

‎src/commands/doctor-completion.ts‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
installCompletion,
1111
isCompletionInstalled,
1212
resolveCompletionCachePath,
13+
resolveCompletionProfileHint,
1314
resolveCompletionProfilePath,
1415
resolveShellFromEnv,
1516
usesSlowDynamicCompletion,
@@ -40,30 +41,18 @@ function findProfileWriteError(err: unknown): NodeJS.ErrnoException | undefined
4041
return err instanceof Error ? findProfileWriteError(err.cause) : undefined;
4142
}
4243

43-
function resolveCompletionReloadPath(shell: CompletionShell): string {
44-
const profilePath = resolveCompletionProfilePath(shell);
45-
const home = process.env.HOME;
46-
return shell !== "powershell" && home && profilePath.startsWith(`${home}${path.sep}`)
47-
? `~/${path.relative(home, profilePath)}`
48-
: profilePath;
49-
}
50-
51-
function formatCompletionReloadNote(
52-
shell: CompletionShell,
53-
action: "installed" | "upgraded",
54-
): string {
55-
const profilePath = resolveCompletionReloadPath(shell);
56-
return `Shell completion ${action}. Restart your shell or run: ${formatCompletionReloadCommand(shell, profilePath)}`;
57-
}
58-
5944
async function installCompletionForDoctor(
6045
shell: CompletionShell,
6146
cliName: string,
6247
action: "installed" | "upgraded",
6348
): Promise<void> {
6449
try {
6550
await installCompletion(shell, true, cliName);
66-
note(formatCompletionReloadNote(shell, action), "Shell completion");
51+
const reloadCommand = formatCompletionReloadCommand(shell, resolveCompletionProfileHint(shell));
52+
note(
53+
`Shell completion ${action}. Restart your shell or run: ${reloadCommand}`,
54+
"Shell completion",
55+
);
6756
} catch (err) {
6857
// Completion is optional, but only profile permission failures are safe to downgrade.
6958
const writeError = findProfileWriteError(err);

0 commit comments

Comments
 (0)