Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(desktop): open a directory from the shell with `lh app` (#23508)

Innei861773018cf3
diff --git a/.agents/acceptance/scripts/electron-dev.sh b/.agents/acceptance/scripts/electron-dev.sh
index 575261171c8..78abcdb5c4c 100755
--- a/.agents/acceptance/scripts/electron-dev.sh
+++ b/.agents/acceptance/scripts/electron-dev.sh
@@ -10,6 +10,9 @@
#
# Instance pool (concurrent isolated instances β€” e.g. one git worktree each):
# ./electron-dev.sh start <id> # CDP 9222+id, Vite 5173+id, own userData + IPC id
+# ./electron-dev.sh start <id> -- <app args>
+# # …and hand <app args> to the app itself, e.g.
+# # start 11 -- /Users/me/code/repo (cold start)
# ./electron-dev.sh stop <id> # stop ONLY instance <id> (never touches siblings)
# ./electron-dev.sh stop --all # stop every pool instance
# ./electron-dev.sh status <id>
@@ -71,6 +74,15 @@ ENV_ELECTRON_LOG="${ELECTRON_LOG:-}"
CMD="${1:-help}"
INSTANCE="${2:-}" # empty = legacy single instance; integer = pool member
+# Everything after `start <id> --` reaches the Electron app itself: `pnpm dev`
+# forwards args following `--` to the app, which is how a launch with a real
+# directory argument (cold start) is exercised without a packaged build.
+APP_ARGS=()
+if [ "${3:-}" = "--" ]; then
+ shift 3
+ APP_ARGS=("$@")
+fi
+
CDP_BASE="${CDP_BASE:-9222}"
VITE_BASE="${VITE_BASE:-5173}"
ELECTRON_WAIT_S="${ELECTRON_WAIT_S:-90}"
@@ -409,15 +421,20 @@ do_start() {
: >"$ELECTRON_LOG"
# Values reach `env` as separate argv entries, so labels and paths with spaces
- # or quotes survive without shell re-parsing.
+ # or quotes survive without shell re-parsing. Anything after `--` is the app's
+ # own argv (`pnpm dev -- …` forwards it), which lets a launch be exercised
+ # with a real directory argument.
# shellcheck disable=SC2016 # expanded by the inner bash, not here
- local launch_cmd='cd "$1" && shift && exec env "$@" pnpm dev'
+ local launch_cmd='cd "$1" && shift && env_args=(); while [ "$#" -gt 0 ] && [ "$1" != "--" ]; do env_args+=("$1"); shift; done; if [ "$#" -gt 0 ]; then shift; fi; exec env "${env_args[@]}" pnpm dev -- "$@"'
+ local app_argv=()
+ [ ${#APP_ARGS[@]} -gt 0 ] && app_argv=("--" "${APP_ARGS[@]}")
+
if command -v setsid >/dev/null 2>&1; then
setsid bash -c "$launch_cmd" electron-dev "$PROJECT_ROOT/apps/desktop" "${env_assignments[@]}" \
- >>"$ELECTRON_LOG" 2>&1 </dev/null &
+ ${app_argv[@]+"${app_argv[@]}"} >>"$ELECTRON_LOG" 2>&1 </dev/null &
else
bash -c "$launch_cmd" electron-dev "$PROJECT_ROOT/apps/desktop" "${env_assignments[@]}" \
- >>"$ELECTRON_LOG" 2>&1 </dev/null &
+ ${app_argv[@]+"${app_argv[@]}"} >>"$ELECTRON_LOG" 2>&1 </dev/null &
fi
local launcher_pid=$!
echo "$launcher_pid" >"$PIDFILE"
@@ -545,6 +562,7 @@ case "$CMD" in
echo " start [<id>] β€” Start an instance. No id = legacy single instance (CDP 9222)."
echo " <id> = pool member: CDP 9222+id, Vite 5173+id, own userData"
echo " (login seeded from the saved snapshot) + IPC id."
+ echo " start <id> -- <app args> forwards args to the app"
echo " start-local [<id>] β€” Start pool instance <id> (default 1) signed in to the local dev"
echo " server (SERVER_URL, default http://localhost:3010) as the seeded"
echo " user. No OAuth; the login is never saved to the snapshot."
diff --git a/apps/cli/src/commands/app.ts b/apps/cli/src/commands/app.ts
new file mode 100644
index 00000000000..e792adf4904
--- /dev/null
+++ b/apps/cli/src/commands/app.ts
@@ -0,0 +1,166 @@
+import { existsSync, realpathSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import {
+ type DesktopChannel,
+ type DesktopAppLocation,
+ installShim,
+ isDesktopChannel,
+ launchDesktopApp,
+ resolveDesktopApp,
+ schemeFor,
+ uninstallShim,
+} from '../utils/desktopApp';
+import { outputJson } from '../utils/format';
+import { log } from '../utils/logger';
+
+interface AppCommandOptions {
+ channel?: string;
+ dryRun?: boolean;
+ installCli?: boolean;
+ json?: boolean | string;
+ newWindow?: boolean;
+ scheme?: boolean;
+ uninstallCli?: boolean;
+}
+
+/**
+ * Canonicalize the directory a launch should open.
+ *
+ * Resolving here, in the invoking shell's process, is what makes the feature
+ * work at all: the app itself may be started by launchd with `/` as its
+ * working directory, so a relative `.` would mean nothing by the time it is
+ * read on the other side.
+ */
+export const resolveLaunchDirectory = (input = '.'): null | string => {
+ const absolute = path.resolve(input);
+ if (!existsSync(absolute)) return null;
+ if (!statSync(absolute).isDirectory()) return null;
+ try {
+ return realpathSync(absolute);
+ } catch {
+ return null;
+ }
+};
+
+const describeMissingApp = (channel?: DesktopChannel): string => {
+ const where = channel ? `${channel} channel of ` : '';
+ return [
+ `No ${where}LobeHub Desktop installation was found.`,
+ '',
+ ' Install the desktop app, or point at a build explicitly:',
+ ` ${pc.bold('LOBEHUB_DESKTOP_PATH=/path/to/LobeHub.app')} lh app .`,
+ '',
+ ` Check what is installed: ${pc.bold('lh app --scheme')}`,
+ ].join('\n');
+};
+
+const runInstallCli = (location: DesktopAppLocation, options: AppCommandOptions) => {
+ const result = installShim(location);
+
+ if (options.json !== undefined) {
+ return outputJson({ ...result, executablePath: location.executablePath }, options.json);
+ }
+
+ if (!result.written) {
+ log.error(`Refusing to overwrite ${result.path} β€” it was not written by LobeHub.`);
+ process.exitCode = 1;
+ return;
+ }
+
+ console.log(`Installed ${pc.bold(result.path)} β†’ ${pc.dim(location.executablePath)}`);
+ console.log(`\nNow run ${pc.bold('lobehub .')} to open a directory.`);
+ if (!(process.env.PATH ?? '').split(path.delimiter).includes(path.dirname(result.path))) {
+ console.log(
+ pc.yellow(`\n Note: ${path.dirname(result.path)} is not on your PATH.`),
+ `\n Add it in your shell profile to use the command from anywhere.`,
+ );
+ }
+};
+
+export function registerAppCommand(program: Command) {
+ program
+ .command('app [path]')
+ .description('Open a directory in LobeHub Desktop (like `code .`)')
+ .option('-n, --new-window', 'Start a new conversation instead of revealing the existing one')
+ .option('--channel <channel>', 'Which installed build to use (stable, beta, nightly)')
+ .option('--scheme', 'Print the deep-link scheme of the installed build')
+ .option('--install-cli', 'Install the `lobehub` shell command')
+ .option('--uninstall-cli', 'Remove the `lobehub` shell command')
+ .option('--dry-run', 'Print what would be launched without starting it')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (pathArg: string | undefined, options: AppCommandOptions) => {
+ const channel =
+ options.channel && isDesktopChannel(options.channel) ? options.channel : undefined;
+
+ if (options.channel && !channel) {
+ log.error(`Unknown channel "${options.channel}". Use stable, beta, or nightly.`);
+ process.exitCode = 1;
+ return;
+ }
+
+ if (options.uninstallCli) {
+ const removed = uninstallShim();
+ if (options.json !== undefined) return outputJson({ removed }, options.json);
+ console.log(removed ? 'Removed the `lobehub` command.' : 'No `lobehub` command to remove.');
+ return;
+ }
+
+ const location = resolveDesktopApp(channel);
+ if (!location) {
+ log.error(describeMissingApp(channel));
+ process.exitCode = 1;
+ return;
+ }
+
+ if (options.installCli) return runInstallCli(location, options);
+
+ if (options.scheme) {
+ if (options.json !== undefined)
+ return outputJson(
+ {
+ channel: location.channel,
+ executablePath: location.executablePath,
+ scheme: schemeFor(location),
+ },
+ options.json,
+ );
+ console.log(schemeFor(location));
+ return;
+ }
+
+ // `.` is the default so `lh app` and `lh app .` mean the same thing.
+ const target = pathArg ?? '.';
+ const directory = resolveLaunchDirectory(target);
+ if (!directory) {
+ log.error(`Not a directory: ${target}`);
+ process.exitCode = 1;
+ return;
+ }
+
+ // Positional, like `code .`: Electron reorders argv (switches first,
+ // positionals last), which detaches a flag from its value. A bare
+ // directory always survives that reordering.
+ const args = [directory];
+ if (options.newWindow) args.push('--new-window');
+
+ if (options.dryRun) {
+ if (options.json !== undefined)
+ return outputJson(
+ { args, channel: location.channel, executablePath: location.executablePath },
+ options.json,
+ );
+ console.log(`${location.executablePath} ${args.join(' ')}`);
+ return;
+ }
+
+ await launchDesktopApp(location, args);
+
+ if (options.json !== undefined)
+ return outputJson({ channel: location.channel, opened: directory }, options.json);
+ log.info(`Opened ${pc.bold(directory)} in LobeHub Desktop`);
+ });
+}
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts
index 7b55abfed29..d38c803b573 100644
--- a/apps/cli/src/program.ts
+++ b/apps/cli/src/program.ts
@@ -5,6 +5,7 @@ import { registerVerifyCommand } from './commands/acceptance/deprecatedVerify';
import { registerAgentCommand } from './commands/agent';
import { registerAgentGroupCommand } from './commands/agent-group';
import { registerAgentSignalCommand } from './commands/agent-signal';
+import { registerAppCommand } from './commands/app';
import { registerArtboardCommand } from './commands/artboard';
import { registerArtifactCommand } from './commands/artifact';
import { registerAutomationCommand } from './commands/automation';
@@ -106,6 +107,7 @@ export function createProgram() {
registerAgentCommand(program);
registerAgentGroupCommand(program);
registerAgentSignalCommand(program);
+ registerAppCommand(program);
registerBotCommand(program);
registerArtboardCommand(program);
registerChannelCommand(program);
diff --git a/apps/cli/src/utils/desktopApp.test.ts b/apps/cli/src/utils/desktopApp.test.ts
new file mode 100644
index 00000000000..316ea940217
--- /dev/null
+++ b/apps/cli/src/utils/desktopApp.test.ts
@@ -0,0 +1,126 @@
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ type DesktopAppLocation,
+ CLI_SHIM_NAME,
+ installShim,
+ isDesktopChannel,
+ platformExecutableNames,
+ resolveShimDirectory,
+ resolveShimPath,
+ schemeFor,
+ uninstallShim,
+} from './desktopApp';
+
+const location: DesktopAppLocation = {
+ channel: 'stable',
+ executablePath: '/Applications/LobeHub.app/Contents/MacOS/LobeHub',
+ installPath: '/Applications/LobeHub.app',
+};
+
+describe('desktopApp shim', () => {
+ let tempDir: string;
+ const env = () => ({ LOBE_CLI_SHIM_DIR: tempDir }) as NodeJS.ProcessEnv;
+
+ beforeEach(() => {
+ tempDir = mkdtempSync(path.join(os.tmpdir(), 'lh-app-'));
+ });
+
+ afterEach(() => {
+ rmSync(tempDir, { force: true, recursive: true });
+ });
+
+ it('should write an exec wrapper that forwards arguments', () => {
+ const result = installShim(location, env());
+
+ expect(result.written).toBe(true);
+ expect(result.path).toBe(path.join(tempDir, CLI_SHIM_NAME));
+
+ const script = readFileSync(result.path, 'utf8');
+ // Exec the bundle's binary, not a symlink: a symlink pins the channel that
+ // happened to be installed when the shim was written.
+ expect(script).toContain(`exec "${location.executablePath}" "$@"`);
+ });
+
+ it('should refuse to clobber a foreign binary with the same name', () => {
+ const shimPath = resolveShimPath(env());
+ writeFileSync(shimPath, '#!/bin/sh\necho not ours\n');
+
+ const result = installShim(location, env());
+
+ expect(result.written).toBe(false);
+ expect(readFileSync(shimPath, 'utf8')).toContain('echo not ours');
+ });
+
+ it('should overwrite its own shim', () => {
+ installShim(location, env());
+ const second = installShim({ ...location, executablePath: '/elsewhere/LobeHub' }, env());
+
+ expect(second.written).toBe(true);
+ expect(readFileSync(second.path, 'utf8')).toContain('/elsewhere/LobeHub');
+ });
+
+ it('should only remove a shim it wrote', () => {
+ expect(uninstallShim(env())).toBe(false);
+
+ installShim(location, env());
+ expect(uninstallShim(env())).toBe(true);
+
+ writeFileSync(resolveShimPath(env()), '#!/bin/sh\necho not ours\n');
+ expect(uninstallShim(env())).toBe(false);
+ });
+
+ it('should fall back to ~/.local/bin without an override', () => {
+ expect(resolveShimDirectory({} as NodeJS.ProcessEnv)).toBe(
+ path.join(os.homedir(), '.local', 'bin'),
+ );
+ });
+
+ it('should create the shim directory when missing', () => {
+ const nested = path.join(tempDir, 'a', 'b');
+ const result = installShim(location, { LOBE_CLI_SHIM_DIR: nested } as NodeJS.ProcessEnv);
+
+ expect(result.written).toBe(true);
+ expect(statSync(result.path).isFile()).toBe(true);
+ });
+});
+
+describe('schemeFor', () => {
+ it('should keep stable on the bare scheme and suffix the channels', () => {
+ // A nightly and a stable install coexist; each handoff addresses its own.
+ expect(schemeFor({ ...location, channel: 'stable' })).toBe('lobehub');
+ expect(schemeFor({ ...location, channel: 'beta' })).toBe('lobehub-beta');
+ expect(schemeFor({ ...location, channel: 'nightly' })).toBe('lobehub-nightly');
+ });
+});
+
+describe('isDesktopChannel', () => {
+ it('should accept the known channels and reject anything else', () => {
+ expect(isDesktopChannel('nightly')).toBe(true);
+ expect(isDesktopChannel('canary')).toBe(false);
+ });
+});
+
+describe('platformExecutableNames', () => {
+ it('should use one constant Windows binary for every channel', () => {
+ // electron-builder pins `win.executableName`; only the product β€” and with
+ // it the install directory β€” carries the channel suffix.
+ expect(platformExecutableNames('stable', 'win32')).toEqual(['LobeHub.exe']);
+ expect(platformExecutableNames('beta', 'win32')).toEqual(['LobeHub.exe']);
+ expect(platformExecutableNames('nightly', 'win32')).toEqual(['LobeHub.exe']);
+ });
+
+ it('should follow the product name on Linux', () => {
+ expect(platformExecutableNames('stable', 'linux')).toContain('LobeHub');
+ expect(platformExecutableNames('nightly', 'linux')).toContain('LobeHub-Nightly');
+ });
+
+ it('should not guess a binary name on macOS', () => {
+ // The bundle's Contents/MacOS is read instead.
+ expect(platformExecutableNames('stable', 'darwin')).toEqual([]);
+ });
+});
diff --git a/apps/cli/src/utils/desktopApp.ts b/apps/cli/src/utils/desktopApp.ts
new file mode 100644
index 00000000000..ebf5d465f6a
--- /dev/null
+++ b/apps/cli/src/utils/desktopApp.ts
@@ -0,0 +1,251 @@
+import { spawn } from 'node:child_process';
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+export type DesktopChannel = 'beta' | 'nightly' | 'stable';
+
+export interface DesktopAppLocation {
+ channel: DesktopChannel;
+ /**
+ * What to spawn. On macOS this is the bundle's inner executable rather than
+ * `open -a`: `open` routes the argument through an Apple Event, which can
+ * race the single-instance handoff and delivers the path twice.
+ */
+ executablePath: string;
+ /** `.app` bundle on macOS, install directory elsewhere. */
+ installPath: string;
+}
+
+const CHANNELS: DesktopChannel[] = ['stable', 'beta', 'nightly'];
+
+/** Matches `productName` in scripts/electronWorkflow/setDesktopVersion.ts. */
+const BUNDLE_NAMES: Record<DesktopChannel, string> = {
+ beta: 'LobeHub-Beta',
+ nightly: 'LobeHub-Nightly',
+ stable: 'LobeHub',
+};
+
+/** The shell command `lh app --install-cli` writes. */
+export const CLI_SHIM_NAME = 'lobehub';
+const SHIM_MARKER = '# installed by `lh app --install-cli`';
+
+export const isDesktopChannel = (value: string): value is DesktopChannel =>
+ (CHANNELS as string[]).includes(value);
+
+const macBundleCandidates = (channel: DesktopChannel): string[] =>
+ ['/Applications', path.join(os.homedir(), 'Applications')].map((dir) =>
+ path.join(dir, `${BUNDLE_NAMES[channel]}.app`),
+ );
+
+/**
+ * The executable inside a `.app`. `CFBundleExecutable` is not always the
+ * product name (a downstream build may rename it), so fall back to reading the
+ * single binary out of `Contents/MacOS` instead of guessing again.
+ */
+const macExecutablePath = (bundlePath: string): null | string => {
+ const macosDir = path.join(bundlePath, 'Contents', 'MacOS');
+ const named = path.join(macosDir, BUNDLE_NAMES.stable);
+ if (existsSync(named)) return named;
+
+ try {
+ const entries = readdirSync(macosDir);
+ const binary = entries.find((entry) => {
+ try {
+ return statSync(path.join(macosDir, entry)).isFile();
+ } catch {
+ return false;
+ }
+ });
+ return binary ? path.join(macosDir, binary) : null;
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * Windows and Linux binary names are NOT derived from the channel's product
+ * name. `electron-builder.mjs` pins `win.executableName` to a single constant
+ * for every channel, while only the product (and therefore the install
+ * directory) carries the suffix β€” so beta and nightly both ship
+ * `LobeHub.exe` inside their own folder. Looking for `LobeHub-Beta.exe` finds
+ * nothing and reports a missing installation.
+ *
+ * Linux leaves `executableName` unset, so the binary follows the product name;
+ * the lowercase form covers a build that lowercased it.
+ */
+export const platformExecutableNames = (
+ channel: DesktopChannel,
+ platform: NodeJS.Platform = process.platform,
+): string[] => {
+ if (platform === 'win32') return ['LobeHub.exe'];
+ if (platform === 'linux') return [BUNDLE_NAMES[channel], BUNDLE_NAMES[channel].toLowerCase()];
+ return [];
+};
+
+const toLocation = (
+ channel: DesktopChannel,
+ installPath: string,
+ platform: NodeJS.Platform = process.platform,
+): DesktopAppLocation | null => {
+ if (platform === 'darwin') {
+ const executablePath = macExecutablePath(installPath);
+ return executablePath ? { channel, executablePath, installPath } : null;
+ }
+
+ for (const name of platformExecutableNames(channel, platform)) {
+ const executablePath = path.join(installPath, name);
+ if (existsSync(executablePath)) return { channel, executablePath, installPath };
+ }
+
+ return null;
+};
+
+const candidateInstallPaths = (channel: DesktopChannel): string[] => {
+ if (process.platform === 'darwin') return macBundleCandidates(channel);
+
+ const name = BUNDLE_NAMES[channel];
+ if (process.platform === 'win32') {
+ const localAppData = process.env.LOCALAPPDATA ?? path.join(os.homedir(), 'AppData', 'Local');
+ return [path.join(localAppData, 'Programs', name), path.join(localAppData, name)];
+ }
+
+ return [`/opt/${name}`, path.join(os.homedir(), '.local', 'opt', name), `/usr/lib/${name}`];
+};
+
+/**
+ * Find an installed desktop build.
+ *
+ * `LOBEHUB_DESKTOP_PATH` short-circuits the search so a dev build, a
+ * white-label bundle, or a copy in `~/Downloads` can be used without teaching
+ * the CLI every layout. It accepts either the bundle and the executable.
+ */
+export const resolveDesktopApp = (
+ channel?: DesktopChannel,
+ env: NodeJS.ProcessEnv = process.env,
+): DesktopAppLocation | null => {
+ const override = env.LOBEHUB_DESKTOP_PATH;
+ if (override) {
+ const located = locateFromOverride(override, channel ?? 'stable');
+ if (located) return located;
+ }
+
+ for (const candidateChannel of channel ? [channel] : CHANNELS) {
+ for (const installPath of candidateInstallPaths(candidateChannel)) {
+ if (!existsSync(installPath)) continue;
+ const located = toLocation(candidateChannel, installPath);
+ if (located) return located;
+ }
+ }
+
+ return null;
+};
+
+const locateFromOverride = (
+ override: string,
+ channel: DesktopChannel,
+): DesktopAppLocation | null => {
+ const absolute = path.resolve(override);
+ if (!existsSync(absolute)) return null;
+
+ if (statSync(absolute).isDirectory() && absolute.endsWith('.app')) {
+ return toLocation(channel, absolute);
+ }
+ return { channel, executablePath: absolute, installPath: path.dirname(absolute) };
+};
+
+/**
+ * Scheme the installed build answers to β€” a nightly and a stable install
+ * coexist on one machine, and each handoff has to address its own.
+ */
+export const schemeFor = (location: DesktopAppLocation): string =>
+ location.channel === 'stable' ? 'lobehub' : `lobehub-${location.channel}`;
+
+/**
+ * Start the app detached and return as soon as it is running.
+ *
+ * NOT `--wait`: unlike an editor, the app is the session β€” blocking the shell
+ * until the user quits would leave every terminal that ran `lh app` hanging.
+ */
+export const launchDesktopApp = (location: DesktopAppLocation, args: string[]): Promise<void> =>
+ new Promise((resolve, reject) => {
+ const child = spawn(location.executablePath, args, { detached: true, stdio: 'ignore' });
+ child.once('error', reject);
+ child.once('spawn', () => {
+ child.unref();
+ resolve();
+ });
+ });
+
+/** Where the shim goes: next to the running `lh`, else `~/.local/bin`. */
+export const resolveShimDirectory = (env: NodeJS.ProcessEnv = process.env): string => {
+ const cliDir = env.LOBE_CLI_SHIM_DIR;
+ if (cliDir) return path.resolve(cliDir);
+ return path.join(os.homedir(), '.local', 'bin');
+};
+
+export const resolveShimPath = (env: NodeJS.ProcessEnv = process.env): string =>
+ path.join(resolveShimDirectory(env), CLI_SHIM_NAME);
+
+export interface InstallShimResult {
+ path: string;
+ written: boolean;
+}
+
+/**
+ * Write a one-line `lobehub` launcher.
+ *
+ * It execs the bundle's executable instead of symlinking to it: a symlink
+ * pins whatever channel happened to be installed at the time, so switching
+ * from nightly to stable would silently keep launching the old build.
+ */
+export const installShim = (
+ location: DesktopAppLocation,
+ env: NodeJS.ProcessEnv = process.env,
+): InstallShimResult => {
+ const shimPath = resolveShimPath(env);
+ const directory = path.dirname(shimPath);
+ mkdirSync(directory, { recursive: true });
+
+ if (existsSync(shimPath)) {
+ const existing = readFileSafe(shimPath);
+ // Never clobber someone else's binary that happens to share the name.
+ if (existing !== null && !existing.includes(SHIM_MARKER))
+ return { path: shimPath, written: false };
+ }
+
+ const script = ['#!/bin/sh', SHIM_MARKER, `exec "${location.executablePath}" "$@"`, ''].join(
+ '\n',
+ );
+
+ writeFileSync(shimPath, script, 'utf8');
+ chmodSync(shimPath, 0o755);
+ return { path: shimPath, written: true };
+};
+
+export const uninstallShim = (env: NodeJS.ProcessEnv = process.env): boolean => {
+ const shimPath = resolveShimPath(env);
+ if (!existsSync(shimPath)) return false;
+ const existing = readFileSafe(shimPath);
+ if (existing === null || !existing.includes(SHIM_MARKER)) return false;
+
+ rmSync(shimPath);
+ return true;
+};
+
+const readFileSafe = (filePath: string): null | string => {
+ try {
+ return readFileSync(filePath, 'utf8');
+ } catch {
+ return null;
+ }
+};
diff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjs
index 17e58c6283d..a546bd10838 100644
--- a/apps/desktop/electron-builder.mjs
+++ b/apps/desktop/electron-builder.mjs
@@ -414,6 +414,20 @@ const config = {
}
: {}),
CFBundleIconName: 'AppIcon',
+ /**
+ * Claiming `public.folder` is what puts the app in Finder's "Open With"
+ * for a folder. Without it the only ways in are the shell command and a
+ * drop on the Dock icon β€” which is what a first-time user is least
+ * likely to guess.
+ */
+ CFBundleDocumentTypes: [
+ {
+ CFBundleTypeName: 'Folder',
+ CFBundleTypeRole: 'Viewer',
+ LSHandlerRank: 'Alternate',
+ LSItemContentTypes: ['public.folder'],
+ },
+ ],
CFBundleURLTypes: [
{
CFBundleURLName: `${brandName} Protocol`,
diff --git a/apps/desktop/src/main/controllers/AppLaunchCtr.ts b/apps/desktop/src/main/controllers/AppLaunchCtr.ts
new file mode 100644
index 00000000000..77eddd86a4b
--- /dev/null
+++ b/apps/desktop/src/main/controllers/AppLaunchCtr.ts
@@ -0,0 +1,93 @@
+import { createPathTarget } from '@/utils/launchTarget';
+import { createLogger } from '@/utils/logger';
+
+import { ControllerModule, createProtocolHandler, IpcMethod } from '.';
+
+const logger = createLogger('controllers:AppLaunchCtr');
+
+const protocolHandler = createProtocolHandler('open');
+
+interface OpenDirectoryPayload {
+ newWindow: boolean;
+ path: string;
+}
+
+interface OpenPathParams {
+ newWindow?: boolean;
+ path?: unknown;
+}
+
+/**
+ * Turns an external launch into a renderer instruction.
+ *
+ * The validation deliberately happens here rather than in the CLI: argv, a
+ * deep link and a Finder drop all reach this point, and a path that no longer
+ * exists (a deleted worktree, a stale alias in `~/.zshrc`) must fail loudly in
+ * one place instead of opening an empty workspace from three.
+ *
+ * Delivery is handshaked, not fire-and-forget. On a cold start the target is
+ * drained as soon as the window exists, long before React has mounted the
+ * navigation bridge, and `webContents.send` into a page with no subscriber
+ * leaves no trace β€” the launch would simply be lost. Targets that arrive
+ * before the renderer reports readiness are therefore held and replayed, and
+ * the latest one wins because a launch describes a destination, not a queue.
+ */
+export default class AppLaunchController extends ControllerModule {
+ static override readonly groupName = 'appLaunch';
+
+ private pending: null | OpenDirectoryPayload = null;
+ private rendererReady = false;
+
+ @protocolHandler('path')
+ public async handleOpenPath(params: OpenPathParams): Promise<boolean> {
+ const requested = typeof params?.path === 'string' ? params.path : '';
+ const target = createPathTarget(requested);
+
+ if (!target || target.kind !== 'path') {
+ logger.warn(`πŸš€ [AppLaunch] Ignoring non-directory open request: ${requested || '(empty)'}`);
+ return false;
+ }
+
+ if (!this.app?.browserManager) {
+ logger.error('πŸš€ [AppLaunch] App or browserManager not available');
+ return false;
+ }
+
+ const payload: OpenDirectoryPayload = {
+ newWindow: params?.newWindow === true,
+ path: target.path,
+ };
+
+ if (!this.rendererReady) {
+ logger.debug(`πŸš€ [AppLaunch] Renderer not ready yet, holding directory:`, payload);
+ this.pending = payload;
+ return true;
+ }
+
+ this.broadcast(payload);
+ return true;
+ }
+
+ /**
+ * The renderer has mounted its launch listeners. Replay anything that
+ * arrived while it was still loading.
+ */
+ @IpcMethod()
+ public async clientReady(): Promise<boolean> {
+ this.rendererReady = true;
+ logger.debug('πŸš€ [AppLaunch] Renderer reported ready');
+
+ const pending = this.pending;
+ this.pending = null;
+ if (!pending) return false;
+
+ logger.debug(`πŸš€ [AppLaunch] Renderer ready, replaying held directory:`, pending);
+ this.broadcast(pending);
+ return true;
+ }
+
+ private broadcast(payload: OpenDirectoryPayload) {
+ logger.debug(`πŸš€ [AppLaunch] Broadcasting openDirectory:`, payload);
+ this.app.browserManager.broadcastToWindow('app', 'openDirectory', payload);
+ }
+}
diff --git a/apps/desktop/src/main/controllers/__tests__/AppLaunchCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/AppLaunchCtr.test.ts
new file mode 100644
index 00000000000..1933c378aa9
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/AppLaunchCtr.test.ts
@@ -0,0 +1,90 @@
+import { realpathSync } from 'node:fs';
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import AppLaunchController from '../AppLaunchCtr';
+
+const broadcastToWindow = vi.fn();
+
+// The launch path is canonicalized (`/tmp` is a symlink on macOS), so assert
+// against the resolved form rather than the spelling the caller used.
+const TMP = realpathSync('/tmp');
+
+const fakeApp = {
+ browserManager: { broadcastToWindow },
+} as unknown as App;
+
+const createController = () => new AppLaunchController(fakeApp);
+
+describe('AppLaunchCtr', () => {
+ beforeEach(() => {
+ broadcastToWindow.mockReset();
+ });
+
+ it('should hold a directory that arrives before the renderer subscribes', () => {
+ const controller = createController();
+
+ // Cold start: the target is drained right after the window exists, while
+ // the renderer has not mounted its listeners yet.
+ void controller.handleOpenPath({ path: '/tmp' });
+
+ expect(broadcastToWindow).not.toHaveBeenCalled();
+ });
+
+ it('should replay the held directory once the renderer is ready', async () => {
+ const controller = createController();
+ await controller.handleOpenPath({ newWindow: true, path: '/tmp' });
+
+ const replayed = await controller.clientReady();
+
+ expect(replayed).toBe(true);
+ expect(broadcastToWindow).toHaveBeenCalledWith('app', 'openDirectory', {
+ newWindow: true,
+ path: TMP,
+ });
+ });
+
+ it('should replay only the latest held directory', async () => {
+ const controller = createController();
+ await controller.handleOpenPath({ path: '/tmp' });
+ await controller.handleOpenPath({ path: '/' });
+
+ await controller.clientReady();
+
+ expect(broadcastToWindow).toHaveBeenCalledTimes(1);
+ expect(broadcastToWindow).toHaveBeenCalledWith('app', 'openDirectory', {
+ newWindow: false,
+ path: '/',
+ });
+ });
+
+ it('should deliver immediately once the renderer is ready', async () => {
+ const controller = createController();
+ await controller.clientReady();
+ broadcastToWindow.mockReset();
+
+ await controller.handleOpenPath({ path: '/tmp' });
+
+ expect(broadcastToWindow).toHaveBeenCalledWith('app', 'openDirectory', {
+ newWindow: false,
+ path: TMP,
+ });
+ });
+
+ it('should report nothing to replay when no launch is waiting', async () => {
+ const controller = createController();
+
+ expect(await controller.clientReady()).toBe(false);
+ expect(broadcastToWindow).not.toHaveBeenCalled();
+ });
+
+ it('should reject a path that is not a directory', async () => {
+ const controller = createController();
+
+ expect(await controller.handleOpenPath({ path: '/does/not/exist' })).toBe(false);
+ expect(await controller.handleOpenPath({ path: undefined })).toBe(false);
+ expect(broadcastToWindow).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.ts
index 2f58dbfb360..21f939328c8 100644
--- a/apps/desktop/src/main/controllers/registry.ts
+++ b/apps/desktop/src/main/controllers/registry.ts
@@ -1,5 +1,6 @@
import type { CreateServicesResult, IpcServiceConstructor, MergeIpcService } from '@/utils/ipc';
+import AppLaunchCtr from './AppLaunchCtr';
import AuthCtr from './AuthCtr';
import AuvCtr from './AuvCtr';
import BinaryCtr from './BinaryCtr';
@@ -39,6 +40,7 @@ import WorkspaceCtr from './WorkspaceCtr';
export const controllerIpcConstructors = [
HeterogeneousAgentCtr,
HeteroSessionCtr,
+ AppLaunchCtr,
AuthCtr,
AuvCtr,
BrowserControlCtr,
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index 74f294ab639..1bc3fbf6220 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -323,9 +323,10 @@ export class App {
app.on('activate', this.onActivate);
- // Deep links should be actionable as soon as the main window exists.
- void this.protocolManager.processPendingUrls().catch((error) => {
- logger.error('Failed to process pending protocol URLs:', error);
+ // Deep links and launch directories should be actionable as soon as the
+ // main window exists.
+ void this.protocolManager.processPendingTargets().catch((error) => {
+ logger.error('Failed to process pending launch targets:', error);
});
// Work that can trigger disk, network, native permission, or UI setup is
diff --git a/apps/desktop/src/main/core/__tests__/App.test.ts b/apps/desktop/src/main/core/__tests__/App.test.ts
index 2565bdf3119..c13913875f7 100644
--- a/apps/desktop/src/main/core/__tests__/App.test.ts
+++ b/apps/desktop/src/main/core/__tests__/App.test.ts
@@ -148,7 +148,7 @@ vi.mock('../infrastructure/ProtocolManager', () => ({
ProtocolManager: vi.fn(function () {
return {
initialize: vi.fn(),
- processPendingUrls: vi.fn().mockResolvedValue(undefined),
+ processPendingTargets: vi.fn().mockResolvedValue(undefined),
};
}),
}));
diff --git a/apps/desktop/src/main/core/infrastructure/ProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/ProtocolManager.ts
index de72d65133e..661d29e773a 100644
--- a/apps/desktop/src/main/core/infrastructure/ProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/ProtocolManager.ts
@@ -1,6 +1,7 @@
import { app } from 'electron';
import { isDev } from '@/const/env';
+import { createPathTarget, type LaunchTarget, parseLaunchArgs } from '@/utils/launchTarget';
import { createLogger } from '@/utils/logger';
import { getProtocolScheme, parseProtocolUrl } from '@/utils/protocol';
@@ -15,7 +16,7 @@ const logger = createLogger('core:ProtocolManager');
export class ProtocolManager {
private app: App;
private protocolScheme: string;
- private pendingUrls: string[] = [];
+ private pendingTargets: LaunchTarget[] = [];
constructor(app: App) {
logger.debug('Initializing ProtocolManager');
@@ -24,6 +25,15 @@ export class ProtocolManager {
logger.info(`ProtocolManager initialized for scheme: ${this.protocolScheme}://`);
}
+ /**
+ * Schemes this build answers to. `parseProtocolUrl` validates the real set; a
+ * target only has to be recognised here so a foreign URL is dispatched (and
+ * rejected with a log) instead of being mistaken for a directory.
+ */
+ private get acceptedSchemes(): string[] {
+ return ['lobehub', 'lobehub-beta', 'lobehub-dev', 'lobehub-nightly', this.protocolScheme];
+ }
+
/**
* Register protocol handlers and set up event listeners
*/
@@ -96,28 +106,43 @@ export class ProtocolManager {
* Set up protocol event listeners
*/
private setupEventListeners(): void {
- // Handle protocol URL from cold start (Windows/Linux)
- const protocolUrl = this.getProtocolUrlFromArgs(process.argv);
- if (protocolUrl) {
- logger.debug(`πŸ”— [Protocol] Found protocol URL from cold start: ${protocolUrl}`);
- this.pendingUrls.push(protocolUrl);
+ // Cold start: the launching shell's arguments (deep link, or a directory).
+ const coldStartTarget = this.parseLaunchTarget(process.argv);
+ if (coldStartTarget) {
+ logger.debug(`πŸ”— [Launch] Found target from cold start:`, coldStartTarget);
+ this.pendingTargets.push(coldStartTarget);
}
- // Handle protocol URL from macOS open-url event
+ // macOS delivers links through open-url, never through argv.
app.on('open-url', (event, url) => {
event.preventDefault();
logger.debug(`πŸ”— [Protocol] Received URL from open-url event: ${url}`);
- logger.debug(`πŸ”— [Protocol] App ready state: ${app.isReady()}`);
- logger.debug(`πŸ”— [Protocol] Event prevented, processing URL...`);
- this.handleProtocolUrl(url);
+ this.handleLaunchTarget({ kind: 'url', url });
});
- // Handle protocol URL from second instance (Windows/Linux)
+ /**
+ * macOS also delivers Finder drops, `open -a LobeHub .` and "Open With"
+ * here. Nothing listened to this event before, so every one of those
+ * gestures was silently dropped β€” no log, no window, no hint.
+ */
+ app.on('open-file', (event, filePath) => {
+ event.preventDefault();
+ // `open-file` fires before `ready` on a cold launch; the queue covers it.
+ const target = createPathTarget(filePath);
+ if (!target) {
+ logger.debug(`πŸ”— [Launch] open-file path is not a directory, ignoring: ${filePath}`);
+ return;
+ }
+ logger.debug(`πŸ”— [Launch] Received directory from open-file: ${filePath}`);
+ this.handleLaunchTarget(target);
+ });
+
+ // Windows/Linux re-launch the binary for every new invocation.
app.on('second-instance', (event, commandLine) => {
- const url = this.getProtocolUrlFromArgs(commandLine);
- if (url) {
- logger.debug(`πŸ”— [Protocol] Received protocol URL from second instance: ${url}`);
- this.handleProtocolUrl(url);
+ const target = this.parseLaunchTarget(commandLine);
+ if (target) {
+ logger.debug(`πŸ”— [Launch] Received target from second instance:`, target);
+ this.handleLaunchTarget(target);
}
// Show main window when second instance is triggered
this.app.browserManager.showMainWindow();
@@ -125,46 +150,62 @@ export class ProtocolManager {
}
/**
- * Extract protocol URL from command line arguments
+ * Read the launch target out of a command line. A directory in argv used to
+ * be invisible here β€” only `scheme://` URLs were scanned β€” so `LobeHub .`
+ * started a window that knew nothing about the argument.
*/
- private getProtocolUrlFromArgs(args: string[]): string | null {
- const protocolPrefix = `${this.protocolScheme}://`;
- logger.debug(`πŸ”— [Protocol] Searching for protocol URLs in args: ${JSON.stringify(args)}`);
- logger.debug(`πŸ”— [Protocol] Looking for prefix: ${protocolPrefix}`);
-
- for (const arg of args) {
- if (arg.startsWith(protocolPrefix)) {
- logger.debug(`πŸ”— [Protocol] Found protocol URL in args: ${arg}`);
- return arg;
- }
- }
- logger.debug(`πŸ”— [Protocol] No protocol URL found in args`);
- return null;
+ private parseLaunchTarget(argv: readonly string[]): LaunchTarget | null {
+ return parseLaunchArgs(argv, {
+ // Development launches carry the source tree as argv[1]; a release never does.
+ appPaths: isDev ? [process.cwd()] : [],
+ schemes: this.acceptedSchemes,
+ });
}
/**
- * Handle protocol URL - either immediately or store for later processing
+ * Handle a launch target - either immediately or store for later processing.
+ *
+ * Both a deep link and a directory take this path, so the "app is not ready"
+ * and "startup update is replacing the window" cases only have to be solved
+ * once.
*/
- private handleProtocolUrl(url: string): void {
+ private handleLaunchTarget(target: LaunchTarget): void {
try {
- logger.debug(`πŸ”— [Protocol] handleProtocolUrl called with: ${url}`);
- logger.debug(`πŸ”— [Protocol] App ready state: ${app.isReady()}`);
- logger.debug(`πŸ”— [Protocol] Current pending URLs count: ${this.pendingUrls.length}`);
+ logger.debug(`πŸ”— [Launch] Handling target:`, target);
+ logger.debug(`πŸ”— [Launch] App ready state: ${app.isReady()}`);
if (!app.isReady() || this.app.startupUpdatePending) {
- // App not ready yet, store for later processing
- logger.debug('πŸ”— [Protocol] App not ready, storing protocol URL for later processing');
- this.pendingUrls.push(url);
- logger.debug(`πŸ”— [Protocol] Pending URLs after push: ${this.pendingUrls.length}`);
+ logger.debug('πŸ”— [Launch] App not ready, queueing target for later processing');
+ this.pendingTargets.push(target);
return;
}
- // App is ready, process immediately
- logger.debug('πŸ”— [Protocol] App is ready, processing URL immediately');
- this.processProtocolUrl(url);
+ void this.dispatchLaunchTarget(target);
} catch (error) {
- logger.error('πŸ”— [Protocol] Failed to handle protocol URL:', error);
+ logger.error('πŸ”— [Launch] Failed to handle launch target:', error);
+ }
+ }
+
+ private async dispatchLaunchTarget(target: LaunchTarget): Promise<void> {
+ // A launch is a user asking to see the app, whatever it carries.
+ this.app.browserManager.showMainWindow();
+
+ if (target.kind === 'path') {
+ try {
+ const handled = await this.app.handleProtocolRequest('open', 'path', {
+ newWindow: target.newWindow,
+ path: target.path,
+ });
+ if (!handled) {
+ logger.warn(`πŸ”— [Launch] Directory was not opened (no handler result): ${target.path}`);
+ }
+ } catch (error) {
+ logger.error('πŸ”— [Launch] Failed to open directory:', error);
+ }
+ return;
}
+
+ await this.processProtocolUrl(target.url);
}
/**
@@ -174,17 +215,7 @@ export class ProtocolManager {
try {
logger.debug(`πŸ”— [Protocol] processProtocolUrl called with: ${url}`);
- // Basic URL validation - just check if it's our protocol
- if (!url.startsWith(`${this.protocolScheme}://`)) {
- logger.warn(`πŸ”— [Protocol] Invalid protocol scheme in URL: ${url}`);
- return;
- }
-
- // Show main window
- logger.debug('πŸ”— [Protocol] Showing main window...');
- this.app.browserManager.showMainWindow();
-
- // Parse protocol URL to extract urlType and action
+ // Parse protocol URL to extract urlType and action (validates the scheme too)
const parsed = parseProtocolUrl(url);
if (!parsed) {
@@ -219,30 +250,26 @@ export class ProtocolManager {
}
/**
- * Process any pending protocol URLs after app is ready
+ * Process any targets that arrived before the app was ready
*/
- public async processPendingUrls(): Promise<void> {
- logger.debug(`πŸ”— [Protocol] processPendingUrls called`);
- logger.debug(`πŸ”— [Protocol] Pending URLs count: ${this.pendingUrls.length}`);
+ public async processPendingTargets(): Promise<void> {
+ logger.debug(`πŸ”— [Launch] processPendingTargets called`);
+ logger.debug(`πŸ”— [Launch] Pending targets count: ${this.pendingTargets.length}`);
- if (this.pendingUrls.length === 0) {
- logger.debug(`πŸ”— [Protocol] No pending URLs to process`);
+ if (this.pendingTargets.length === 0) {
+ logger.debug(`πŸ”— [Launch] No pending targets to process`);
return;
}
- logger.debug(
- `πŸ”— [Protocol] Processing ${this.pendingUrls.length} pending protocol URLs:`,
- this.pendingUrls,
- );
+ const targets = this.pendingTargets;
+ // Clear before awaiting: a target that arrives while this loop runs must
+ // dispatch itself, not wait for a queue drain that already read it.
+ this.pendingTargets = [];
- for (const url of this.pendingUrls) {
- logger.debug(`πŸ”— [Protocol] Processing pending URL: ${url}`);
- await this.processProtocolUrl(url);
+ for (const target of targets) {
+ logger.debug(`πŸ”— [Launch] Processing pending target:`, target);
+ await this.dispatchLaunchTarget(target);
}
-
- // Clear pending URLs
- this.pendingUrls = [];
- logger.debug(`πŸ”— [Protocol] All pending URLs processed and cleared`);
}
/**
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts
index 1f8bc51ca01..2dd4a847c68 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/ProtocolManager.test.ts
@@ -44,6 +44,7 @@ describe('ProtocolManager', () => {
// Store event handlers
let openUrlHandler: ((event: any, url: string) => void) | undefined;
+ let openFileHandler: ((event: any, filePath: string) => void) | undefined;
let secondInstanceHandler: ((event: any, commandLine: string[]) => void) | undefined;
beforeEach(() => {
@@ -56,10 +57,13 @@ describe('ProtocolManager', () => {
// Capture event handlers
openUrlHandler = undefined;
+ openFileHandler = undefined;
secondInstanceHandler = undefined;
mockApp.on.mockImplementation((event: string, handler: any) => {
if (event === 'open-url') {
openUrlHandler = handler;
+ } else if (event === 'open-file') {
+ openFileHandler = handler;
} else if (event === 'second-instance') {
secondInstanceHandler = handler;
}
@@ -91,6 +95,8 @@ describe('ProtocolManager', () => {
it('queues deep links while the startup update window is blocking entry', async () => {
mockAppCore.startupUpdatePending = true;
manager.initialize();
+ // The runner's own argv is not part of what this test asserts.
+ manager['pendingTargets'] = [];
openUrlHandler!(
{ preventDefault: vi.fn() },
'lobehub://plugin/install?url=https://example.com',
@@ -98,7 +104,7 @@ describe('ProtocolManager', () => {
expect(mockShowMainWindow).not.toHaveBeenCalled();
expect(mockHandleProtocolRequest).not.toHaveBeenCalled();
mockAppCore.startupUpdatePending = false;
- await manager.processPendingUrls();
+ await manager.processPendingTargets();
expect(mockHandleProtocolRequest).toHaveBeenCalledOnce();
});
@@ -148,55 +154,101 @@ describe('ProtocolManager', () => {
});
});
- describe('getProtocolUrlFromArgs', () => {
+ describe('parseLaunchTarget', () => {
beforeEach(() => {
manager.initialize();
});
it('should extract protocol URL from command line arguments', () => {
// Access private method through prototype
- const result = manager['getProtocolUrlFromArgs']([
+ const result = manager['parseLaunchTarget']([
'/path/to/app',
'lobehub://plugin/install?url=https://example.com',
]);
- expect(result).toBe('lobehub://plugin/install?url=https://example.com');
+ expect(result).toEqual({
+ kind: 'url',
+ url: 'lobehub://plugin/install?url=https://example.com',
+ });
});
- it('should return null when no matching URL found', () => {
- const result = manager['getProtocolUrlFromArgs'](['/path/to/app', '--some-flag']);
+ it('should return null when no target found', () => {
+ const result = manager['parseLaunchTarget'](['/path/to/app', '--some-flag']);
expect(result).toBeNull();
});
it('should return first matching URL when multiple exist', () => {
- const result = manager['getProtocolUrlFromArgs']([
+ const result = manager['parseLaunchTarget']([
+ '/path/to/app',
'lobehub://first/action',
'lobehub://second/action',
]);
- expect(result).toBe('lobehub://first/action');
+ expect(result).toEqual({ kind: 'url', url: 'lobehub://first/action' });
+ });
+
+ it('should read a directory argument instead of dropping it', () => {
+ // Regression: only `scheme://` URLs were scanned, so `LobeHub .` started
+ // a window that knew nothing about the directory it was launched from.
+ const result = manager['parseLaunchTarget'](['/path/to/app', process.cwd()]);
+
+ expect(result).toMatchObject({ kind: 'path', newWindow: false, path: process.cwd() });
+ });
+
+ it('should carry --new-window with a directory target', () => {
+ const result = manager['parseLaunchTarget'](['/path/to/app', '--new-window', process.cwd()]);
+
+ expect(result).toMatchObject({ kind: 'path', newWindow: true });
});
});
- describe('handleProtocolUrl', () => {
+ describe('open-file event', () => {
beforeEach(() => {
manager.initialize();
});
- it('should store URL when app is not ready', () => {
+ it('should open a directory dropped on the app', async () => {
+ expect(openFileHandler).toBeDefined();
+
+ const mockEvent = { preventDefault: vi.fn() };
+ openFileHandler!(mockEvent, process.cwd());
+
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ await vi.waitFor(() => {
+ expect(mockHandleProtocolRequest).toHaveBeenCalledWith('open', 'path', {
+ newWindow: false,
+ path: process.cwd(),
+ });
+ });
+ });
+
+ it('should ignore a dropped file that is not a directory', () => {
+ const mockEvent = { preventDefault: vi.fn() };
+ openFileHandler!(mockEvent, '/definitely/not/a/real/path/file.txt');
+
+ expect(mockHandleProtocolRequest).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('handleLaunchTarget', () => {
+ beforeEach(() => {
+ manager.initialize();
+ });
+
+ it('should store target when app is not ready', () => {
mockApp.isReady.mockReturnValue(false);
- manager['handleProtocolUrl']('lobehub://plugin/install');
+ manager['handleLaunchTarget']({ kind: 'url', url: 'lobehub://plugin/install' });
- expect(manager['pendingUrls']).toContain('lobehub://plugin/install');
+ expect(manager['pendingTargets']).toEqual([{ kind: 'url', url: 'lobehub://plugin/install' }]);
expect(mockShowMainWindow).not.toHaveBeenCalled();
});
it('should process URL immediately when app is ready', async () => {
mockApp.isReady.mockReturnValue(true);
- manager['handleProtocolUrl']('lobehub://plugin/install');
+ manager['handleLaunchTarget']({ kind: 'url', url: 'lobehub://plugin/install' });
// Allow async processing
await vi.waitFor(() => {
@@ -204,10 +256,23 @@ describe('ProtocolManager', () => {
});
});
+ it('should dispatch a directory to the open:path handler', async () => {
+ manager['handleLaunchTarget']({ kind: 'path', newWindow: true, path: process.cwd() });
+
+ await vi.waitFor(() => {
+ expect(mockHandleProtocolRequest).toHaveBeenCalledWith('open', 'path', {
+ newWindow: true,
+ path: process.cwd(),
+ });
+ });
+ expect(mockShowMainWindow).toHaveBeenCalled();
+ });
+
it('should ignore URLs with invalid protocol scheme', async () => {
mockApp.isReady.mockReturnValue(true);
+ vi.mocked(parseProtocolUrl).mockReturnValue(null);
- manager['handleProtocolUrl']('invalid://plugin/install');
+ manager['handleLaunchTarget']({ kind: 'url', url: 'invalid://plugin/install' });
await Promise.resolve(); // Allow any async work
@@ -253,33 +318,36 @@ describe('ProtocolManager', () => {
});
});
- describe('processPendingUrls', () => {
+ describe('processPendingTargets', () => {
beforeEach(() => {
manager.initialize();
});
- it('should process all pending URLs', async () => {
- // Add pending URLs
- manager['pendingUrls'] = ['lobehub://action1', 'lobehub://action2'];
+ it('should process all pending targets', async () => {
+ // Add pending targets
+ manager['pendingTargets'] = [
+ { kind: 'url', url: 'lobehub://action1' },
+ { kind: 'url', url: 'lobehub://action2' },
+ ];
- await manager.processPendingUrls();
+ await manager.processPendingTargets();
- // Should have shown main window for each URL
+ // Should have shown main window for each target
expect(mockShowMainWindow).toHaveBeenCalledTimes(2);
});
- it('should clear pending URLs after processing', async () => {
- manager['pendingUrls'] = ['lobehub://action1'];
+ it('should clear pending targets after processing', async () => {
+ manager['pendingTargets'] = [{ kind: 'url', url: 'lobehub://action1' }];
- await manager.processPendingUrls();
+ await manager.processPendingTargets();
- expect(manager['pendingUrls']).toHaveLength(0);
+ expect(manager['pendingTargets']).toHaveLength(0);
});
- it('should skip when no pending URLs', async () => {
- manager['pendingUrls'] = [];
+ it('should skip when no pending targets', async () => {
+ manager['pendingTargets'] = [];
- await manager.processPendingUrls();
+ await manager.processPendingTargets();
expect(mockShowMainWindow).not.toHaveBeenCalled();
});
@@ -304,7 +372,7 @@ describe('ProtocolManager', () => {
manager.initialize();
});
- it('should show main window and dispatch to handler', async () => {
+ it('should dispatch the parsed request to its handler', async () => {
vi.mocked(parseProtocolUrl).mockReturnValue({
action: 'install',
originalUrl: 'lobehub://plugin/install?url=https://example.com',
@@ -314,7 +382,6 @@ describe('ProtocolManager', () => {
await manager['processProtocolUrl']('lobehub://plugin/install');
- expect(mockShowMainWindow).toHaveBeenCalled();
expect(mockHandleProtocolRequest).toHaveBeenCalledWith('plugin', 'install', {
url: 'https://example.com',
});
@@ -325,7 +392,6 @@ describe('ProtocolManager', () => {
await manager['processProtocolUrl']('lobehub://invalid');
- expect(mockShowMainWindow).toHaveBeenCalled();
expect(mockHandleProtocolRequest).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/utils/__tests__/launchTarget.test.ts b/apps/desktop/src/main/utils/__tests__/launchTarget.test.ts
new file mode 100644
index 00000000000..aad8a248577
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/launchTarget.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest';
+
+import { createPathTarget, parseLaunchArgs } from '../launchTarget';
+
+const directories = new Set(['/repo', '/repo/apps', '/tmp', '/Users/me/Code/app']);
+
+const options = {
+ cwd: '/repo',
+ isDirectory: (candidate: string) => directories.has(candidate),
+ resolveRealPath: (candidate: string) => candidate,
+ schemes: ['lobehub', 'lobehub-nightly'],
+};
+
+describe('parseLaunchArgs', () => {
+ it('should open a bare directory argument', () => {
+ expect(
+ parseLaunchArgs(
+ ['/Applications/LobeHub.app/Contents/MacOS/LobeHub', '/Users/me/Code/app'],
+ options,
+ ),
+ ).toEqual({ kind: 'path', newWindow: false, path: '/Users/me/Code/app' });
+ });
+
+ it('should prefer the explicit --open-path argument', () => {
+ expect(parseLaunchArgs(['/x/LobeHub', '--open-path', '/tmp'], options)).toEqual({
+ kind: 'path',
+ newWindow: false,
+ path: '/tmp',
+ });
+ });
+
+ it('should carry --new-window without treating it as the target', () => {
+ expect(parseLaunchArgs(['/x/LobeHub', '-n', '/tmp'], options)).toEqual({
+ kind: 'path',
+ newWindow: true,
+ path: '/tmp',
+ });
+ });
+
+ it('should resolve a relative path against the caller cwd', () => {
+ expect(parseLaunchArgs(['/x/LobeHub', '.'], options)).toMatchObject({ path: '/repo' });
+ });
+
+ it('should dispatch a deep link instead of resolving it as a path', () => {
+ expect(
+ parseLaunchArgs(['/x/LobeHub', '/tmp', 'lobehub://plugin/install?id=1'], options),
+ ).toEqual({ kind: 'url', url: 'lobehub://plugin/install?id=1' });
+ });
+
+ it('should match the scheme case-insensitively', () => {
+ expect(parseLaunchArgs(['/x/LobeHub', 'LobeHub://agent/open'], options)).toEqual({
+ kind: 'url',
+ url: 'LobeHub://agent/open',
+ });
+ });
+
+ it('should return null when nothing resolves', () => {
+ expect(parseLaunchArgs(['/x/LobeHub'], options)).toBeNull();
+ expect(parseLaunchArgs(['/x/LobeHub', '/does/not/exist'], options)).toBeNull();
+ expect(parseLaunchArgs(['/x/LobeHub', '--some-flag'], options)).toBeNull();
+ });
+
+ it('should drop the app own directory in a development launch', () => {
+ expect(
+ parseLaunchArgs(['/abs/electron', '/repo', '/Users/me/Code/app'], {
+ ...options,
+ appPaths: ['/repo'],
+ }),
+ ).toEqual({ kind: 'path', newWindow: false, path: '/Users/me/Code/app' });
+
+ // A lone self-path must open nothing rather than the source tree.
+ expect(parseLaunchArgs(['/abs/electron', '.'], { ...options, appPaths: ['/repo'] })).toBeNull();
+ });
+
+ it('should refuse network paths', () => {
+ // SMB confuses credential handling and hangs the main process on launch.
+ expect(parseLaunchArgs(['/x/LobeHub', '//server/share/project'], options)).toBeNull();
+ expect(parseLaunchArgs(['/x/LobeHub', '\\\\server\\share\\project'], options)).toBeNull();
+ });
+
+ it('should take the last directory positional', () => {
+ expect(parseLaunchArgs(['/x/LobeHub', '/tmp', '/Users/me/Code/app'], options)).toMatchObject({
+ path: '/Users/me/Code/app',
+ });
+ });
+
+ it('should stop flag parsing after --', () => {
+ expect(parseLaunchArgs(['/x/LobeHub', '--', '/tmp'], options)).toMatchObject({ path: '/tmp' });
+ });
+
+ it('should still open the directory when Electron reorders argv', () => {
+ // Observed on a real second-instance handoff: Electron moves switches ahead
+ // of positionals, which separates `--open-path` from its value and leaves
+ // the directory last. Failing on that must not drop the launch.
+ expect(
+ parseLaunchArgs(
+ [
+ '/Electron',
+ '--open-path',
+ '--allow-file-access-from-files',
+ '--secure-schemes=app,localfile',
+ 'apps/desktop',
+ '/repo/apps',
+ ],
+ options,
+ ),
+ ).toEqual({ kind: 'path', newWindow: false, path: '/repo/apps' });
+ });
+
+ it('should prefer a resolvable --open-path over positionals', () => {
+ expect(parseLaunchArgs(['/x/LobeHub', '--open-path', '/tmp', '/repo'], options)).toMatchObject({
+ path: '/tmp',
+ });
+ });
+});
+
+describe('createPathTarget', () => {
+ it('should build a target from an open-file directory', () => {
+ expect(createPathTarget('/Users/me/Code/app', options)).toEqual({
+ kind: 'path',
+ newWindow: false,
+ path: '/Users/me/Code/app',
+ });
+ });
+
+ it('should ignore a path that is not a directory', () => {
+ expect(createPathTarget('/Users/me/Code/app/README.md', options)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/utils/launchTarget.ts b/apps/desktop/src/main/utils/launchTarget.ts
new file mode 100644
index 00000000000..3d123696d6d
--- /dev/null
+++ b/apps/desktop/src/main/utils/launchTarget.ts
@@ -0,0 +1,197 @@
+import { realpathSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+/**
+ * What a launch asked the app to do.
+ *
+ * Two shapes end up here because two different code paths arrive at the main
+ * process: a deep link (`lobehub://…`) always arrives as a URL, while a
+ * shell-style launch (`LobeHub ~/Code/app`, `lh app .`, Finder's "Open With")
+ * only ever carries a directory. Treating them as one type keeps a single
+ * dispatch point β€” and a single place where "the app was not ready yet" gets
+ * queued instead of dropped.
+ */
+export type LaunchTarget =
+ { kind: 'url'; url: string } | { kind: 'path'; newWindow: boolean; path: string };
+
+export interface ParseLaunchArgsOptions {
+ /**
+ * Absolute paths that identify the app itself rather than a target. In
+ * development Electron receives the project directory as the first
+ * positional argument, and without this it would look like "open the app's
+ * own source tree".
+ *
+ * Empty in a packaged build: a release has no self-path argument, and a
+ * stale entry would silently swallow a real target.
+ */
+ appPaths?: string[];
+ /** Directory relative arguments resolve against. Defaults to `process.cwd()`. */
+ cwd?: string;
+ /** fs seams for tests. */
+ isDirectory?: (absolutePath: string) => boolean;
+ resolveRealPath?: (absolutePath: string) => string;
+ /** URL schemes this build answers to (`lobehub`, `lobehub-nightly`, …). */
+ schemes: string[];
+}
+
+/** Explicit directory argument, far less ambiguous than a bare positional. */
+const OPEN_PATH_FLAG = '--open-path';
+const NEW_WINDOW_FLAGS = new Set(['--new-window', '-n']);
+
+const defaultIsDirectory = (absolutePath: string) => {
+ try {
+ return statSync(absolutePath).isDirectory();
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * `lobehub://x` and `lobehub:x` both reach argv depending on the launcher.
+ * Matching on the colon keeps a Windows drive letter (`C:\…`) out: schemes are
+ * letters only, so `c:` can never collide with `lobehub:`.
+ */
+const isSchemeUrl = (arg: string, schemes: readonly string[]) =>
+ schemes.some((scheme) => arg.toLowerCase().startsWith(`${scheme.toLowerCase()}:`));
+
+/**
+ * A path we refuse to turn into a working directory.
+ *
+ * `\\host\share` and `//host/share` are network paths on every platform we
+ * ship to, and letting one through makes the app stat a remote share on
+ * launch β€” on SMB that leaks NTLM credentials, and on a slow link it hangs the
+ * main process before the first window paints.
+ */
+const isNetworkPath = (input: string) => /^[/\\]{2}/.test(input);
+
+/**
+ * Resolve one candidate into a canonical absolute directory, or null when it
+ * is not one. `realpath` matters: the same folder is routinely reached through
+ * a symlink (`/tmp` on macOS), and a topic bound to the real path must not be
+ * treated as a different directory than the one the shell handed us.
+ */
+export const resolveDirectoryCandidate = (
+ input: string,
+ options: Pick<ParseLaunchArgsOptions, 'cwd' | 'isDirectory' | 'resolveRealPath'> = {},
+): null | string => {
+ const {
+ cwd = process.cwd(),
+ isDirectory = defaultIsDirectory,
+ resolveRealPath = realpathSync,
+ } = options;
+
+ if (!input || input.includes('\0')) return null;
+ if (isNetworkPath(input)) return null;
+
+ const absolute = path.resolve(cwd, input);
+ if (!isDirectory(absolute)) return null;
+
+ try {
+ return resolveRealPath(absolute);
+ } catch {
+ return null;
+ }
+};
+
+interface PositionalScan {
+ /** Value of `--open-path`, when the launcher passed one. */
+ openPath?: string;
+ positional: string[];
+}
+
+const collectArguments = (
+ args: readonly string[],
+ appPaths: readonly string[],
+ cwd: string,
+): PositionalScan => {
+ const positional: string[] = [];
+ const appPathSet = new Set(appPaths.map((appPath) => path.resolve(cwd, appPath)));
+ let afterSeparator = false;
+ let openPath: string | undefined;
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+
+ if (!afterSeparator && arg === '--') {
+ afterSeparator = true;
+ continue;
+ }
+
+ if (!afterSeparator && arg === OPEN_PATH_FLAG) {
+ openPath = args[index + 1];
+ index += 1;
+ continue;
+ }
+
+ if (!afterSeparator && arg.startsWith('-')) continue;
+
+ // `electron .` marks the app's own directory, not a folder to open. The
+ // CLI never relies on this branch β€” it passes `--open-path` β€” so dropping
+ // the resolved match cannot take a real target away.
+ if (appPathSet.has(path.resolve(cwd, arg))) continue;
+
+ positional.push(arg);
+ }
+
+ return { openPath, positional };
+};
+
+/**
+ * Read a launch target out of a command line.
+ *
+ * Order of preference: an explicit `--open-path`, a deep link, then the last
+ * positional that actually is a directory. Every candidate is validated
+ * against the filesystem, so a stray argument can never become a working
+ * directory.
+ *
+ * Last-positional wins because launchers append their own arguments, and
+ * `--open-path` must not be fatal when it does not resolve: Electron REORDERS
+ * argv (switches first, positionals last), which separates `--open-path` from
+ * its value and leaves the real directory at the end of the line. Failing
+ * there instead of falling through silently dropped a launch β€” observed on a
+ * real second-instance handoff before this fallback existed.
+ */
+export const parseLaunchArgs = (
+ argv: readonly string[],
+ options: ParseLaunchArgsOptions,
+): LaunchTarget | null => {
+ // argv[0] is the executable β€” or Electron itself in development.
+ const args = argv.slice(1);
+ const newWindow = args.some((arg) => NEW_WINDOW_FLAGS.has(arg));
+ const cwd = options.cwd ?? process.cwd();
+ const { openPath, positional } = collectArguments(args, options.appPaths ?? [], cwd);
+
+ const resolveOptions = {
+ cwd,
+ isDirectory: options.isDirectory,
+ resolveRealPath: options.resolveRealPath,
+ };
+
+ if (openPath !== undefined) {
+ const resolved = resolveDirectoryCandidate(openPath, resolveOptions);
+ if (resolved) return { kind: 'path', newWindow, path: resolved };
+ }
+
+ const url = positional.find((arg) => isSchemeUrl(arg, options.schemes));
+ if (url) return { kind: 'url', url };
+
+ for (let index = positional.length - 1; index >= 0; index -= 1) {
+ const resolved = resolveDirectoryCandidate(positional[index], resolveOptions);
+ if (resolved) return { kind: 'path', newWindow, path: resolved };
+ }
+
+ return null;
+};
+
+/**
+ * Build a directory target from a path the OS handed us outside argv β€” macOS
+ * delivers Finder drops and "Open With" through the `open-file` event, which
+ * never touches the command line.
+ */
+export const createPathTarget = (
+ input: string,
+ options: Pick<ParseLaunchArgsOptions, 'cwd' | 'isDirectory' | 'resolveRealPath'> = {},
+): LaunchTarget | null => {
+ const resolved = resolveDirectoryCandidate(input, options);
+ return resolved ? { kind: 'path', newWindow: false, path: resolved } : null;
+};
diff --git a/packages/electron-client-ipc/src/events/protocol.ts b/packages/electron-client-ipc/src/events/protocol.ts
index ee2538983fc..a1e6694dc65 100644
--- a/packages/electron-client-ipc/src/events/protocol.ts
+++ b/packages/electron-client-ipc/src/events/protocol.ts
@@ -16,4 +16,22 @@ export interface ProtocolBroadcastEvents {
/** MCP Schema object */
schema: McpInstallSchema;
}) => void;
+
+ /**
+ * A shell launch asked the app to open a directory (`lh app .`, `LobeHub
+ * ~/Code/app`, Finder's "Open With", `lobehub://open/path?path=…`).
+ *
+ * Only the canonical path travels: the renderer decides what "open" means
+ * (reveal the latest conversation bound to it, or start one), because that
+ * decision needs the user's project and topic data, which only it can read.
+ */
+ openDirectory: (data: {
+ /**
+ * Focus a new window instead of the conversation already bound to this
+ * directory. `lh app --new-window` sets it.
+ */
+ newWindow: boolean;
+ /** Absolute, symlink-resolved directory path. */
+ path: string;
+ }) => void;
}
diff --git a/src/features/AppLaunch/openDirectory.ts b/src/features/AppLaunch/openDirectory.ts
new file mode 100644
index 00000000000..28ed38cec71
--- /dev/null
+++ b/src/features/AppLaunch/openDirectory.ts
@@ -0,0 +1,79 @@
+import { getProjectDraftPath, getProjectTopicPath } from '@/features/Projects/Layout/navigation';
+import { projectService } from '@/services/project';
+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+
+import {
+ type BoundDirectoryLike,
+ normalizeComparablePath,
+ pickLatestTopic,
+ resolveDirectoryMatch,
+} from './openDirectorySelection';
+
+export interface OpenDirectoryResult {
+ /** Directory the launch resolved to, when any. */
+ directory?: BoundDirectoryLike;
+ /** Matched by an ancestor rather than the path itself. */
+ matchedParent?: boolean;
+ status: 'directory-not-bound' | 'opened-draft' | 'opened-topic';
+ topicId?: string;
+}
+
+/**
+ * Land a shell launch on the right conversation.
+ *
+ * Reusing the conversation already bound to the directory is what makes the
+ * command feel like `code .`: running it twice focuses the same window instead
+ * of stacking duplicates. Only when the directory has no conversation yet do
+ * we stage a draft β€” the first message creates the topic, the same way a
+ * sidebar "+" does, so a stray launch never leaves an empty topic behind.
+ */
+export const openDirectoryInApp = async ({
+ getDeviceId,
+ navigate,
+ reuseExisting = true,
+ targetPath,
+}: {
+ /** Polled until known: device identity arrives after the renderer boots. */
+ getDeviceId: () => string | undefined;
+ navigate: (path: string) => void;
+ /** `false` for `lh app --new-window`: stage a fresh conversation instead. */
+ reuseExisting?: boolean;
+ targetPath: string;
+}): Promise<OpenDirectoryResult> => {
+ const target = normalizeComparablePath(targetPath);
+ const match = await resolveDirectoryMatch({
+ getDeviceId,
+ list: async () => (await projectWorkingDirectoryService.list()).data,
+ targetPath: target,
+ });
+
+ if (!match) {
+ console.warn(`[openDirectory] No project directory is bound to ${target}`);
+ // Land where binding happens instead of a silent no-op. The list route is
+ // `/projects` β€” `/project` renders the not-found page.
+ navigate('/projects');
+ return { status: 'directory-not-bound' };
+ }
+
+ const { directory, matchedParent } = match;
+ const { data: topics } = await projectWorkingDirectoryService.listTopics(directory.id);
+ const latest = reuseExisting ? pickLatestTopic(topics ?? []) : undefined;
+
+ if (latest) {
+ navigate(getProjectTopicPath(directory.projectId, latest.id));
+ return { directory, matchedParent, status: 'opened-topic', topicId: latest.id };
+ }
+
+ // A draft needs the agent that will answer in it; the project's coordinator
+ // is the same default a fresh project conversation starts on.
+ const { data: project } = await projectService.find(directory.projectId);
+ const agentId = project?.coordinatorAgentId;
+ if (!agentId) {
+ console.warn(`[openDirectory] Project ${directory.projectId} has no coordinator agent`);
+ navigate('/projects');
+ return { directory, matchedParent, status: 'directory-not-bound' };
+ }
+
+ navigate(getProjectDraftPath(directory.projectId, agentId, directory.id));
+ return { directory, matchedParent, status: 'opened-draft' };
+};
diff --git a/src/features/AppLaunch/openDirectorySelection.test.ts b/src/features/AppLaunch/openDirectorySelection.test.ts
new file mode 100644
index 00000000000..c58a9d56eff
--- /dev/null
+++ b/src/features/AppLaunch/openDirectorySelection.test.ts
@@ -0,0 +1,179 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ type BoundDirectoryLike,
+ normalizeComparablePath,
+ pickDirectoryForPath,
+ pickLatestTopic,
+ resolveDirectoryMatch,
+} from './openDirectorySelection';
+
+const LOCAL = 'device-local';
+const REMOTE = 'device-remote';
+
+const directory = (
+ id: string,
+ path: string,
+ extra: Partial<BoundDirectoryLike> = {},
+): BoundDirectoryLike => ({ deviceId: LOCAL, id, path, projectId: `prj_${id}`, ...extra });
+
+const local = { deviceId: LOCAL };
+
+describe('normalizeComparablePath', () => {
+ it('should ignore trailing separators', () => {
+ expect(normalizeComparablePath('/repo/')).toBe('/repo');
+ expect(normalizeComparablePath('/repo')).toBe('/repo');
+ });
+
+ it('should keep the filesystem root as a single separator', () => {
+ expect(normalizeComparablePath('/')).toBe('/');
+ });
+});
+
+describe('pickDirectoryForPath', () => {
+ it('should prefer an exact match over an ancestor binding', () => {
+ expect(
+ pickDirectoryForPath(
+ [directory('root', '/repo'), directory('nested', '/repo/apps')],
+ '/repo/apps',
+ local,
+ ),
+ ).toEqual({ directory: directory('nested', '/repo/apps'), matchedParent: false });
+ });
+
+ it('should match when only the trailing separator differs', () => {
+ expect(pickDirectoryForPath([directory('a', '/repo/')], '/repo', local)).toEqual({
+ directory: directory('a', '/repo/'),
+ matchedParent: false,
+ });
+ });
+
+ it('should fall back to the nearest ancestor when launched from a subfolder', () => {
+ expect(
+ pickDirectoryForPath(
+ [
+ directory('root', '/repo'),
+ directory('nested', '/repo/apps/desktop'),
+ directory('other', '/elsewhere'),
+ ],
+ '/repo/apps/desktop/src',
+ local,
+ ),
+ ).toEqual({ directory: directory('nested', '/repo/apps/desktop'), matchedParent: true });
+ });
+
+ it('should not match a shared name prefix', () => {
+ // `/repo` is not an ancestor of `/repository`.
+ expect(pickDirectoryForPath([directory('a', '/repo')], '/repository', local)).toBeUndefined();
+ });
+
+ it('should prefer a runnable binding of the same path', () => {
+ // A binding whose device went offline must not shadow a live one.
+ expect(
+ pickDirectoryForPath(
+ [directory('stale', '/repo'), directory('live', '/repo', { runnable: true })],
+ '/repo',
+ local,
+ ),
+ ).toEqual({ directory: directory('live', '/repo', { runnable: true }), matchedParent: false });
+ });
+
+ it('should ignore a directory bound on another device', () => {
+ // Two machines can expose the same path; only this one is being launched.
+ expect(
+ pickDirectoryForPath(
+ [directory('remote', '/repo', { deviceId: REMOTE, runnable: true })],
+ '/repo',
+ local,
+ ),
+ ).toBeUndefined();
+ });
+
+ it('should not let a remote exact match beat a local ancestor', () => {
+ expect(
+ pickDirectoryForPath(
+ [
+ directory('local-root', '/repo', { deviceId: LOCAL }),
+ directory('remote-exact', '/repo/apps', { deviceId: REMOTE }),
+ ],
+ '/repo/apps',
+ local,
+ ),
+ ).toEqual({ directory: directory('local-root', '/repo'), matchedParent: true });
+ });
+
+ it('should match nothing without a local device id', () => {
+ // Guessing here could open another machine's project, so the caller falls
+ // back to the project list instead.
+ expect(pickDirectoryForPath([directory('a', '/repo')], '/repo')).toBeUndefined();
+ });
+
+ it('should return undefined for an empty binding list', () => {
+ expect(pickDirectoryForPath([], '/repo', local)).toBeUndefined();
+ });
+});
+
+describe('resolveDirectoryMatch', () => {
+ const base = { pollMs: 1, targetPath: '/repo', timeoutMs: 50 };
+
+ it('should wait for the device identity before deciding it is unbound', async () => {
+ // A cold-start replay outruns `gatewayDeviceInfo`; a snapshot at that moment
+ // would fall through to the project list even though the directory is bound.
+ const getDeviceId = vi.fn().mockReturnValueOnce(undefined).mockReturnValue(LOCAL);
+ const list = vi.fn().mockResolvedValue([directory('a', '/repo')]);
+
+ await expect(resolveDirectoryMatch({ ...base, getDeviceId, list })).resolves.toEqual({
+ directory: directory('a', '/repo'),
+ matchedParent: false,
+ });
+ expect(getDeviceId).toHaveBeenCalledTimes(2);
+ });
+
+ it('should retry an empty list instead of treating it as unbound', async () => {
+ const list = vi
+ .fn()
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([directory('a', '/repo')]);
+
+ await expect(
+ resolveDirectoryMatch({ ...base, getDeviceId: () => LOCAL, list }),
+ ).resolves.toMatchObject({ directory: { id: 'a' } });
+ expect(list).toHaveBeenCalledTimes(2);
+ });
+
+ it('should survive a failing call', async () => {
+ const list = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('401'))
+ .mockResolvedValueOnce([directory('a', '/repo')]);
+
+ await expect(
+ resolveDirectoryMatch({ ...base, getDeviceId: () => LOCAL, list }),
+ ).resolves.toMatchObject({ directory: { id: 'a' } });
+ });
+
+ it('should give up at the deadline and report no match', async () => {
+ const list = vi.fn().mockResolvedValue([]);
+
+ await expect(
+ resolveDirectoryMatch({ ...base, getDeviceId: () => LOCAL, list, timeoutMs: 5 }),
+ ).resolves.toBeUndefined();
+ });
+});
+
+describe('pickLatestTopic', () => {
+ it('should pick the newest topic regardless of list order', () => {
+ // `listTopics` returns ascending `updatedAt`; the rule must not depend on it.
+ expect(
+ pickLatestTopic([
+ { id: 'old', updatedAt: '2026-01-01T00:00:00Z' },
+ { id: 'new', updatedAt: '2026-11-01T00:00:00Z' },
+ { id: 'mid', updatedAt: new Date('2026-06-01T00:00:00Z') },
+ ])?.id,
+ ).toBe('new');
+ });
+
+ it('should return undefined without topics', () => {
+ expect(pickLatestTopic([])).toBeUndefined();
+ });
+});
diff --git a/src/features/AppLaunch/openDirectorySelection.ts b/src/features/AppLaunch/openDirectorySelection.ts
new file mode 100644
index 00000000000..5df0b7cd378
--- /dev/null
+++ b/src/features/AppLaunch/openDirectorySelection.ts
@@ -0,0 +1,143 @@
+/**
+ * Pure selection rules for "open this directory in the app".
+ *
+ * Kept free of services and store imports so the behaviour that decides which
+ * conversation a launch lands on can be tested without a tRPC client β€” this is
+ * the part that is easy to get subtly wrong (wrong folder, duplicated
+ * conversation) and hard to notice afterwards.
+ */
+
+/** The fields of a bound project directory this module matches against. */
+export interface BoundDirectoryLike {
+ /** Desktop device that owns the directory; a path only exists on that machine. */
+ deviceId?: string;
+ id: string;
+ path: string;
+ projectId: string;
+ /** Whether a run can actually start here (linked, enabled, writable). */
+ runnable?: boolean;
+}
+
+export interface BoundTopicLike {
+ id: string;
+ updatedAt: Date | string;
+}
+
+/**
+ * Trailing separators are the one difference that is never meaningful:
+ * `/repo` and `/repo/` are the same folder, and both spellings reach us
+ * depending on whether the path was typed, dropped, or came from `pwd`.
+ *
+ * Case is NOT folded β€” on a case-sensitive volume `/Repo` and `/repo` are two
+ * different directories, and silently merging them would open the wrong
+ * project.
+ */
+export const normalizeComparablePath = (candidate: string): string => {
+ const trimmed = candidate.trim().replace(/[/\\]+$/, '');
+ return trimmed === '' ? '/' : trimmed;
+};
+
+const isAncestor = (parent: string, child: string): boolean => {
+ if (parent === '/') return true;
+ return child.startsWith(`${parent}/`) || child.startsWith(`${parent}\\`);
+};
+
+/**
+ * Pick the bound directory a launch should open.
+ *
+ * Candidates are restricted to `deviceId` first: a workspace can hold several
+ * machines with the same path, and `runnable` only reflects enablement and
+ * write permission β€” not whose disk it is. Without that filter a launch on one
+ * machine can open another machine's project, and a remote exact match even
+ * beats a local ancestor match.
+ *
+ * An exact match wins. Failing that the nearest ancestor does, because `lh app
+ * .` inside `repo/apps/desktop` should land on the conversation bound to
+ * `repo` β€” refusing it would make the command useless from anywhere but the
+ * repository root. Ancestors are compared longest-first so a nested binding
+ * beats the umbrella project around it.
+ *
+ * Between equally good candidates a `runnable` directory wins: a stale binding
+ * whose device is offline must not shadow a live one.
+ */
+export const pickDirectoryForPath = <T extends BoundDirectoryLike>(
+ directories: readonly T[],
+ targetPath: string,
+ options: { deviceId?: string } = {},
+): undefined | { directory: T; matchedParent: boolean } => {
+ const { deviceId } = options;
+ // Without a known local device there is no safe candidate: every match could
+ // belong to another machine, so the caller falls back to the project list.
+ if (!deviceId) return undefined;
+
+ const target = normalizeComparablePath(targetPath);
+ const byPreference = (a: T, b: T) => Number(b.runnable === true) - Number(a.runnable === true);
+ const localDirectories = directories.filter((directory) => directory.deviceId === deviceId);
+
+ const exact = [...localDirectories]
+ .filter((directory) => normalizeComparablePath(directory.path) === target)
+ .sort(byPreference)[0];
+ if (exact) return { directory: exact, matchedParent: false };
+
+ const ancestors = localDirectories
+ .map((directory) => ({ directory, normalized: normalizeComparablePath(directory.path) }))
+ .filter(({ normalized }) => isAncestor(normalized, target))
+ .sort(
+ (a, b) => b.normalized.length - a.normalized.length || byPreference(a.directory, b.directory),
+ );
+
+ const best = ancestors[0];
+ return best ? { directory: best.directory, matchedParent: true } : undefined;
+};
+
+/**
+ * Resolve a launch to a bound directory, tolerating a cold start.
+ *
+ * A launch replays as soon as the navigation bridge mounts, which can beat both
+ * the session's first data fetch and the local device identity β€” and a missing
+ * device id or an empty list is indistinguishable from "nothing is bound" at a
+ * single point in time. This keeps asking until the device is known and the
+ * list has an answer, then stops at the deadline so a genuinely unbound
+ * directory still reaches the project list.
+ */
+export const resolveDirectoryMatch = async <T extends BoundDirectoryLike>({
+ getDeviceId,
+ list,
+ pollMs = 500,
+ targetPath,
+ timeoutMs = 10_000,
+}: {
+ /** Polled until it answers: device identity arrives after the renderer boots. */
+ getDeviceId: () => string | undefined;
+ list: () => Promise<T[] | null | undefined>;
+ pollMs?: number;
+ targetPath: string;
+ timeoutMs?: number;
+}): Promise<undefined | { directory: T; matchedParent: boolean }> => {
+ const deadline = Date.now() + timeoutMs;
+
+ for (;;) {
+ const deviceId = getDeviceId();
+
+ if (deviceId) {
+ try {
+ const directories = await list();
+ const match = pickDirectoryForPath(directories ?? [], targetPath, { deviceId });
+ if (match) return match;
+ } catch (error) {
+ console.warn('[openDirectory] Failed to list project directories', error);
+ }
+ }
+
+ if (Date.now() >= deadline) return undefined;
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
+ }
+};
+
+/**
+ * The conversation to reveal for a directory: the most recently updated one.
+ * `listTopics` returns ascending `updatedAt`, but sorting here keeps the rule
+ * independent of that query detail.
+ */
+export const pickLatestTopic = <T extends BoundTopicLike>(topics: readonly T[]): T | undefined =>
+ [...topics].sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())[0];
diff --git a/src/features/DesktopNavigationBridge/index.test.tsx b/src/features/DesktopNavigationBridge/index.test.tsx
index 3421874fadf..b02249c36c3 100644
--- a/src/features/DesktopNavigationBridge/index.test.tsx
+++ b/src/features/DesktopNavigationBridge/index.test.tsx
@@ -5,14 +5,21 @@ import DesktopNavigationBridge from './index';
type NavigatePayload = { escape?: boolean; path: string; replace?: boolean };
type NavigateHandler = (payload: NavigatePayload) => void;
+type OpenDirectoryPayload = { newWindow: boolean; path: string };
+type OpenDirectoryHandler = (payload: OpenDirectoryPayload) => void;
let registeredHandler: NavigateHandler | null = null;
+let openDirectoryHandler: OpenDirectoryHandler | null = null;
const navigateMock = vi.hoisted(() => vi.fn());
+const openDirectoryInAppMock = vi.hoisted(() => vi.fn());
+const clientReadyMock = vi.hoisted(() => vi.fn());
+const DEVICE_ID = 'device-local';
vi.mock('@lobechat/electron-client-ipc', () => ({
- useWatchBroadcast: (event: string, handler: NavigateHandler) => {
+ useWatchBroadcast: (event: string, handler: any) => {
if (event === 'navigate') registeredHandler = handler;
+ if (event === 'openDirectory') openDirectoryHandler = handler;
},
}));
@@ -20,16 +27,41 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => navigateMock,
}));
+vi.mock('@/features/AppLaunch/openDirectory', () => ({
+ openDirectoryInApp: openDirectoryInAppMock,
+}));
+
+const getStateMock = vi.hoisted(() => vi.fn(() => ({ gatewayDeviceInfo: { deviceId: 'device-local' } })));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: Object.assign(() => undefined, { getState: getStateMock }),
+}));
+
+vi.mock('@/utils/electron/ipc', () => ({
+ ensureElectronIpc: () => ({ appLaunch: { clientReady: clientReadyMock } }),
+}));
+
const emitNavigate = (payload: NavigatePayload) => {
act(() => {
registeredHandler?.(payload);
});
};
+const emitOpenDirectory = (payload: OpenDirectoryPayload) => {
+ act(() => {
+ openDirectoryHandler?.(payload);
+ });
+};
+
describe('DesktopNavigationBridge', () => {
beforeEach(() => {
registeredHandler = null;
+ openDirectoryHandler = null;
navigateMock.mockReset();
+ openDirectoryInAppMock.mockReset();
+ openDirectoryInAppMock.mockResolvedValue({ status: 'opened-topic' });
+ clientReadyMock.mockReset();
+ clientReadyMock.mockResolvedValue(false);
});
it('uses escaped navigation for literal desktop notification paths', () => {
@@ -69,4 +101,52 @@ describe('DesktopNavigationBridge', () => {
expect(navigateMock).not.toHaveBeenCalled();
});
+
+ it('reveals the conversation bound to a launched directory', () => {
+ render(<DesktopNavigationBridge />);
+
+ emitOpenDirectory({ newWindow: false, path: '/repo' });
+
+ expect(openDirectoryInAppMock).toHaveBeenCalledWith({
+ getDeviceId: expect.any(Function),
+ navigate: navigateMock,
+ reuseExisting: true,
+ targetPath: '/repo',
+ });
+ });
+
+ it('starts a fresh conversation when the launch asks for a new window', () => {
+ render(<DesktopNavigationBridge />);
+
+ emitOpenDirectory({ newWindow: true, path: '/repo' });
+
+ // `--new-window` means "do not take over the conversation I already have".
+ expect(openDirectoryInAppMock).toHaveBeenCalledWith({
+ getDeviceId: expect.any(Function),
+ navigate: navigateMock,
+ reuseExisting: false,
+ targetPath: '/repo',
+ });
+ });
+
+ it('tells the main process the launch listeners exist', () => {
+ // A cold start holds the directory until this handshake; without it the
+ // broadcast is sent into a page that has not subscribed and is dropped.
+ render(<DesktopNavigationBridge />);
+
+ expect(clientReadyMock).toHaveBeenCalled();
+ });
+
+ it('reads the device id lazily instead of snapshotting it at mount', () => {
+ // On a cold start the launch replays before the identity resolves.
+ render(<DesktopNavigationBridge />);
+
+ emitOpenDirectory({ newWindow: false, path: '/repo' });
+
+ const { getDeviceId } = openDirectoryInAppMock.mock.calls[0][0];
+ // Nothing is read at mount; the getter answers when the resolver asks.
+ expect(getStateMock).not.toHaveBeenCalled();
+ expect(getDeviceId()).toBe(DEVICE_ID);
+ expect(getStateMock).toHaveBeenCalled();
+ });
});
diff --git a/src/features/DesktopNavigationBridge/index.tsx b/src/features/DesktopNavigationBridge/index.tsx
index ad6ad889fa6..0606c25130a 100644
--- a/src/features/DesktopNavigationBridge/index.tsx
+++ b/src/features/DesktopNavigationBridge/index.tsx
@@ -1,12 +1,23 @@
'use client';
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
-import { memo, useCallback } from 'react';
+import { memo, useCallback, useEffect } from 'react';
+import { openDirectoryInApp } from '@/features/AppLaunch/openDirectory';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useElectronStore } from '@/store/electron';
+import { ensureElectronIpc } from '@/utils/electron/ipc';
const DesktopNavigationBridge = memo(() => {
const navigate = useWorkspaceAwareNavigate();
+ // A shell launch describes a directory on THIS machine; another bound device
+ // can expose the same path, and its conversation is not the one to open.
+ // Read lazily: on a cold start the identity is still resolving when the
+ // launch replays, and a snapshot taken at mount would be `undefined`.
+ const getDeviceId = useCallback(
+ () => useElectronStore.getState().gatewayDeviceInfo?.deviceId,
+ [],
+ );
const handleNavigate = useCallback(
({ escape, path, replace }: { escape?: boolean; path: string; replace?: boolean }) => {
@@ -20,7 +31,44 @@ const DesktopNavigationBridge = memo(() => {
[navigate],
);
+ /**
+ * A shell launch (`lh app .`, `LobeHub ~/Code/app`, Finder's "Open With")
+ * arrives as a canonical directory. It lands here rather than in
+ * `ProtocolUrlHandler` because that component only mounts inside the agent
+ * and group layouts β€” a second `lh app` while the app sits on a project page
+ * would reach no listener at all.
+ */
+ const handleOpenDirectory = useCallback(
+ ({ newWindow, path }: { newWindow: boolean; path: string }) => {
+ void openDirectoryInApp({
+ getDeviceId,
+ navigate,
+ // `--new-window` means "don't take over the conversation I already have".
+ reuseExisting: !newWindow,
+ targetPath: path,
+ }).catch((error) => {
+ console.error('[DesktopNavigationBridge] Failed to open directory:', error);
+ });
+ },
+ [getDeviceId, navigate],
+ );
+
useWatchBroadcast('navigate', handleNavigate);
+ useWatchBroadcast('openDirectory', handleOpenDirectory);
+
+ /**
+ * Tell the main process the listeners above exist. A launch that arrives
+ * during a cold start is held there instead of being sent into a page that
+ * has not subscribed yet β€” without this handshake it was dropped silently and
+ * the app opened its ordinary landing page.
+ */
+ useEffect(() => {
+ void ensureElectronIpc()
+ .appLaunch.clientReady()
+ .catch((error: unknown) => {
+ console.error('[DesktopNavigationBridge] Failed to report readiness:', error);
+ });
+ }, []);
return null;
});
diff --git a/src/services/project.ts b/src/services/project.ts
index 9aa6fc78b3f..04d5b30871f 100644
--- a/src/services/project.ts
+++ b/src/services/project.ts
@@ -52,6 +52,13 @@ class ProjectService {
detail = async (id: string) => lambdaClient.project.detail.query({ id });
+ /**
+ * The project row alone. `detail` also loads agents, tasks, works and the
+ * knowledge bases, which is the wrong weight for a caller that only needs to
+ * know which agent runs in the project.
+ */
+ find = async (id: string) => lambdaClient.project.find.query({ id });
+
delete = async (id: string) => lambdaClient.project.delete.mutate({ id });
move = async (id: string, anchor: { afterId: string } | { beforeId: string }) =>