Open in → Android Studio opens the file in whichever Studio window was used last, not in the review's checkout

未关闭
#3,671 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
48/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
android, typescript

调研方向

Start with packages/core/open-in-apps.ts and packages/server/open-in.ts, then read the related tests in packages/core/open-in-apps.test.ts. Trace how review routes choose the checkout folder and build Android Studio launch arguments, including the first-open case and calls without a selected line. Done when the correct checkout opens in the intended Studio window and tests cover the changed command behavior.

由索引模型根据 Issue 内容生成。

描述

What happened?

In a PR code review (plannotator review <PR URL>), Plannotator checks the PR out into $TMPDIR/plannotator-pr-<repo>-<n>-<random>/pool/pr-<n>. Open in → Android Studio opens the right file (that checkout's copy), but in whichever Android Studio window I used last, as a loose file outside that window's project. I keep several worktrees of the same repo open in Studio, so it looks as if the file opened in another worktree. Only when Studio has no project open does it build a project around the file and open the checkout.

Steps to reproduce
  1. Have Android Studio running with another project open (for example another clone of the same repo).
  2. Run plannotator review <PR URL> on a PR of an Android/Gradle repo.
  3. On any changed file, choose Open in → Android Studio.
  4. The file opens in the other project's window. Hover its tab: the path is the review's checkout under $TMPDIR.
Why

On macOS the button runs open -a "Android Studio" <file>. Studio's macOS open-file handler puts a lone file in the project of the focused window (the data context's project, else the first open project) through ProjectUtil.openOrImportFilesAsync → OpenFileAction.openFile(file, project), without checking which open project contains it. That happens even when the checkout is open as a project in another window. Studio's log shows No processor found for project in <file> for each click.

Studio's command-line launcher chooses differently. For a file given with --line, CommandLineProcessor.doOpenFile → findBestProject takes the first open project whose base directories contain the file, and only then falls back to the last-focused window.

v0.29.0 added the JetBrains IDEs through their launcher when a line is sent (open -na <App> --args --line <n> <file>; without a line they still get open -a). Android Studio is still a plain open -a entry, and no IDE is given the project folder, so this still happens on 0.29.0.

What helps (tried by hand)

Android Studio 2026.2.2 (Rabbit 2) on macOS, every run with a line:

open -na "Android Studio" --args <checkout> --line 40 <checkout>/app/src/main/java/.../File.kt
  • Checkout already open, another window used last: the file opens in the checkout's window, at the line. ✅ Bringing the window forward, Studio logged an internal Assert: must be called on EDT from AppIcon.requestAttention (via findAndFocusExistingProjectForPath): a Studio bug, harmless here.
  • Checkout closed, but opened once before: Studio asks "This window / New window" (my setting), opens the checkout in its own window, file at the line. ✅
  • Checkout never opened before, which is every new review, since the folder name is random: Studio asks "Trust and Open Project?", opens the checkout, but the file is closed again as the window finishes opening, and README.md shows instead. The next click opens the file. ⚠️ I couldn't separate whether the trust prompt or Studio's first-open README causes this.

So there are two separate pieces:

  1. Android Studio through its launcher with --line, as the other JetBrains IDEs already are. This alone fixes the case where the checkout is already open in Studio, whatever window was used last. It does nothing for a fresh checkout nobody has opened.
  2. The checkout folder passed first. The first click opens the checkout as a project; from the second click on, the file lands there.

Not tried: the form without a line (--args <checkout> <file>, which review sends when no line is selected), the other JetBrains IDEs, Windows and Linux.

Costs of passing the folder
  • The first click in a review opens the repository as a full project: a trust prompt, a Gradle sync, and a window on a folder that is deleted when the review ends. The same goes for a local review of a repo that isn't open in the IDE. If the IDE has a subfolder or a parent of the repo open, the repo root opens as a second project.
  • The trust prompt is a real guard: syncing runs the PR's build scripts. "Trust all projects in 'pool' folder" doesn't carry over, because pool's parent folder is random per review. A fixed checkout folder would let people trust it once, but that would trust every future PR's scripts without asking, so it should stay a choice.
Proposed change

A draft patch against 328b5f9 is below. I couldn't run the test suite or the type check here, so treat it as a sketch.

  • Android Studio gets line: { macArgs: 'line-flag' }: it's IntelliJ-based, and its launcher reads --line (checked in Studio's CommandLineProcessor). This changes Android Studio wherever a line is sent (review, annotate, the Inbox, Pi): it opens at the line, through its launcher.
  • openInMacArgv / openInFileArgv take an optional project folder and put it first, only for line-flag (JetBrains) apps. Every other app's command is unchanged.
  • handleOpenIn gets an optional projectFor(abs), passed only by the review route: the review root when it is a repository (so a file in a submodule still opens in the parent project), else the outermost repository below a workspace root. Annotate, the Inbox and Pi never get the folder; Pi would want the same change.
  • Tests: other catalog entries' commands with and without a folder, and the JetBrains/Android Studio commands. Not covered: openInProjectFolder itself (repo root, workspace, submodule, none), the projectFor wiring, and a folder without a line on Windows/Linux. The line.macArgs doc comment would also need updating, since the flag now gates the folder too.

Related: #3368 (custom editors with a launcher and arguments).

Draft patch
diff --git a/packages/core/open-in-apps.test.ts b/packages/core/open-in-apps.test.ts
index 41cddb3..301a3e9 100644
--- a/packages/core/open-in-apps.test.ts
+++ b/packages/core/open-in-apps.test.ts
@@ -173,3 +173,47 @@ describe("isWindowsExePath", () => {
     expect(isWindowsExePath("C:\\JetBrains\\bin\\idea.bat")).toBe(false);
   });
 });
+
+describe("the project folder (a JetBrains IDE opens the file in that project's window)", () => {
+  const file = "/work/my app/src/a#b.ts";
+  const project = "/work/my app";
+  const takesProject = (app: (typeof OPEN_IN_APPS)[number]) =>
+    app.line?.macArgs === "line-flag" || app.line?.cli === "line-flag";
+
+  test("every other app's command is the same with or without it", () => {
+    const others = OPEN_IN_APPS.filter((app) => !takesProject(app));
+    expect(others.map((app) => app.id)).toContain("vscode");
+    for (const app of others) {
+      for (const line of [undefined, 12]) {
+        if (app.mac) {
+          expect(openInMacArgv(app, app.mac.appName, file, line, project)).toEqual(
+            openInMacArgv(app, app.mac.appName, file, line),
+          );
+        }
+        expect(openInFileArgv(app, file, line, project)).toEqual(openInFileArgv(app, file, line));
+      }
+    }
+  });
+
+  test("the JetBrains IDEs and Android Studio get it first, with or without a line", () => {
+    for (const id of [...JETBRAINS_IDS, "android-studio"]) {
+      const app = getOpenInApp(id)!;
+      const name = app.mac!.appName;
+      expect(openInMacArgv(app, name, file, 42, project)).toEqual([
+        "-na", name, "--args", project, "--line", "42", file,
+      ]);
+      expect(openInMacArgv(app, name, file, undefined, project)).toEqual(["-na", name, "--args", project, file]);
+    }
+    for (const id of JETBRAINS_IDS) {
+      expect(openInFileArgv(getOpenInApp(id)!, file, 42, project)).toEqual([project, "--line", "42", file]);
+    }
+  });
+
+  test("Android Studio takes the line through its launcher; without line or folder it is opened as before", () => {
+    const studio = getOpenInApp("android-studio")!;
+    expect(openInMacArgv(studio, "Android Studio", file, 7)).toEqual([
+      "-na", "Android Studio", "--args", "--line", "7", file,
+    ]);
+    expect(openInMacArgv(studio, "Android Studio", file)).toEqual(["-a", "Android Studio", file]);
+  });
+});
diff --git a/packages/core/open-in-apps.ts b/packages/core/open-in-apps.ts
index c47bb14..11015ee 100644
--- a/packages/core/open-in-apps.ts
+++ b/packages/core/open-in-apps.ts
@@ -179,6 +179,9 @@ export const OPEN_IN_APPS: OpenInApp[] = [
     kind: 'editor',
     icon: 'android-studio',
     mac: { appName: 'Android Studio' },
+    // Built on the IntelliJ platform: its launcher (`Contents/MacOS/studio`) takes
+    // `--line` and a project folder exactly as the JetBrains IDEs below do.
+    line: { macArgs: 'line-flag' },
   },
   // IntelliJ IDEA and PyCharm were two editions until 2025.3 / 2025.1: the older
   // bundles ("IntelliJ IDEA Ultimate" in JetBrains' 2024.3-2025.2 docs, the
@@ -299,15 +302,28 @@ export function checkOpenInAppId(raw: unknown): OpenInAppIdCheck {
   return { ok: true, app };
 }
 
+/**
+ * The IntelliJ-platform launcher's arguments: the project folder first (so the IDE
+ * opens it, or brings its window forward, before placing the file), then the line,
+ * then the file. Without the folder the IDE drops a file that no open project owns
+ * into whichever window was used last.
+ */
+function launcherArgs(target: string, line?: number, project?: string): string[] {
+  return [...(project ? [project] : []), ...(line ? ['--line', String(line)] : []), target];
+}
+
 /**
  * The catalog binary's argv for a file, at `line` when the app's launcher takes one.
+ * `project`: the repository folder the file belongs to; only a JetBrains launcher
+ * (`line.cli === 'line-flag'`) is handed it, every other app ignores it.
  * Shared so the Bun and Pi launchers cannot drift.
  */
-export function openInFileArgv(app: OpenInApp, target: string, line?: number): string[] {
-  if (!line || app.kind !== 'editor') return [target];
+export function openInFileArgv(app: OpenInApp, target: string, line?: number, project?: string): string[] {
+  if (app.kind !== 'editor') return [target];
+  if (app.line?.cli === 'line-flag') return launcherArgs(target, line, project);
+  if (!line) return [target];
   if (app.line?.cli === 'goto') return ['--goto', `${target}:${line}`];
   if (app.line?.cli === 'suffix') return [`${target}:${line}`];
-  if (app.line?.cli === 'line-flag') return ['--line', String(line), target];
   return [target];
 }
 
@@ -327,12 +343,20 @@ export function openInMacOpened(app: OpenInApp, target: string, line?: number):
  *    (JetBrains' documented `open -na "<App>.app" --args …`; `-n` makes `open` start
  *    the app's launcher even when the app runs, and the launcher hands the file
  *    and line to the running instance);
- *  - otherwise `-a <app> <opened>`, `<opened>` from openInMacOpened.
+ *    The same app with a `project` folder: `-na <app> --args <project> [--line <n>] <target>`,
+ *    with or without a line;
+ *  - otherwise `-a <app> <opened>`, `<opened>` from openInMacOpened (`project` ignored).
  * No shell is involved; `target` is the server's validated absolute path.
  */
-export function openInMacArgv(app: OpenInApp, appName: string, target: string, line?: number): string[] {
-  if (line && app.kind === 'editor' && app.line?.macArgs === 'line-flag') {
-    return ['-na', appName, '--args', '--line', String(line), target];
+export function openInMacArgv(
+  app: OpenInApp,
+  appName: string,
+  target: string,
+  line?: number,
+  project?: string,
+): string[] {
+  if ((line || project) && app.kind === 'editor' && app.line?.macArgs === 'line-flag') {
+    return ['-na', appName, '--args', ...launcherArgs(target, line, project)];
   }
   return ['-a', appName, openInMacOpened(app, target, line)];
 }
diff --git a/packages/server/open-in.ts b/packages/server/open-in.ts
index 7af2421..7f2043b 100644
--- a/packages/server/open-in.ts
+++ b/packages/server/open-in.ts
@@ -19,6 +19,7 @@
 
 import { childEnv, childPath } from "@plannotator/shared/child-env";
 import path from "node:path";
+import { existsSync } from "node:fs";
 import { spawn } from "node:child_process";
 import {
   OPEN_IN_APPS,
@@ -204,8 +205,8 @@ export function revealFile(absPath: string): Promise<OpenInLaunchResult> {
 }
 
 /** The catalog binary's argv for a file, at `line` when the app's launcher takes one. */
-function fileArgv(app: OpenInApp, target: string, line?: number): string[] {
-  return openInFileArgv(app, target, line);
+function fileArgv(app: OpenInApp, target: string, line?: number, project?: string): string[] {
+  return openInFileArgv(app, target, line, project);
 }
 
 /**
@@ -217,6 +218,7 @@ export function openWithApp(
   app: OpenInApp,
   absPath: string,
   line?: number,
+  project?: string,
 ): Promise<OpenInLaunchResult> {
   const platform = currentPlatform();
   const target = app.kind === "terminal" ? path.dirname(absPath) : absPath;
@@ -231,7 +233,7 @@ export function openWithApp(
     // The installed bundle's name (an app may install under more than one).
     const appName = locateApp(app, platform) ?? app.mac.appName;
     // A line rides a URL scheme, or the app launcher's own `--line` (openInMacArgv).
-    return runArgv("open", openInMacArgv(app, appName, target, line), app.label);
+    return runArgv("open", openInMacArgv(app, appName, target, line, project), app.label);
   }
 
   if (platform === "win") {
@@ -254,7 +256,7 @@ export function openWithApp(
     if (!winBin) {
       return Promise.resolve({ ok: false, error: `${app.label} not found` });
     }
-    return runArgv(winBin, fileArgv(app, target, line), app.label);
+    return runArgv(winBin, fileArgv(app, target, line, project), app.label);
   }
 
   const bin = app.linux?.bin;
@@ -265,7 +267,7 @@ export function openWithApp(
     });
   }
   // The first of its names on PATH (a snap command, say); else its catalog bin.
-  return runArgv(locateApp(app, platform) ?? bin, fileArgv(app, target, line), app.label);
+  return runArgv(locateApp(app, platform) ?? bin, fileArgv(app, target, line, project), app.label);
 }
 
 /**
@@ -297,6 +299,7 @@ export async function openFileInApp(
   absPath: string,
   appId: string,
   line?: number,
+  project?: string,
 ): Promise<OpenInLaunchResult> {
   const checked = checkOpenInAppId(appId);
   if (!checked.ok) return { ok: false, error: checked.error };
@@ -306,7 +309,31 @@ export async function openFileInApp(
     return revealFile(absPath);
   }
 
-  return openWithApp(app, absPath, line);
+  return openWithApp(app, absPath, line, project);
+}
+
+/**
+ * The repository folder `absPath` belongs to, as the project a JetBrains IDE
+ * should open it in:
+ *  - the server root that contains the file, when it is itself a repository
+ *    (`.git` folder or worktree file, or `.jj`): the PR's checkout, or the repo
+ *    under local review, so a file inside a submodule still opens in the parent;
+ *  - in a multi-repo workspace (a root that is not a repository), the outermost
+ *    repository below the root that holds the file.
+ * Undefined when there is none, and the launch is then the plain one.
+ */
+export function openInProjectFolder(absPath: string, roots: string | string[]): string | undefined {
+  const root = (Array.isArray(roots) ? roots : [roots])
+    .map((r) => path.resolve(r))
+    .find((r) => absPath === r || absPath.startsWith(r + path.sep));
+  if (!root) return undefined;
+  const isRepo = (dir: string) => existsSync(path.join(dir, ".git")) || existsSync(path.join(dir, ".jj"));
+  if (isRepo(root)) return root;
+  let outermost: string | undefined;
+  for (let dir = path.dirname(absPath); dir !== root && dir !== path.dirname(dir); dir = path.dirname(dir)) {
+    if (isRepo(dir)) outermost = dir;
+  }
+  return outermost;
 }
 
 /** Where `app` is installed here (shared with Pi): see locateOpenInApp. */
@@ -399,6 +426,12 @@ export interface HandleOpenInOptions {
    * several roots (annotate passes the session's reference roots).
    */
   resolveRoot?: () => string | string[];
+  /**
+   * The repository folder a resolved file belongs to, handed to a JetBrains
+   * launcher so the file opens in that project's window (openInMacArgv). Only
+   * the review server passes it; omitted, every app launches as before.
+   */
+  projectFor?: (absPath: string) => string | undefined;
   /**
    * This server's stale-tab nonce (packages/core/server-session.ts). A body
    * carrying a different `serverSession` is refused with 409 before anything
@@ -479,7 +512,7 @@ export async function handleOpenIn(
     return Response.json({ ok: false, error: "Access denied" }, { status: 403 });
   }
 
-  const result = await openFileInApp(abs, app.app.id, parseOpenInLine(body.line));
+  const result = await openFileInApp(abs, app.app.id, parseOpenInLine(body.line), options.projectFor?.(abs));
   // A failed launch is a valid request with the result in the body (ok:false),
   // not a server error — return 200 and let the client read `ok`. Matches Pi.
   return Response.json(result);
diff --git a/packages/server/review.ts b/packages/server/review.ts
index 3fe2a82..ca20f5b 100644
--- a/packages/server/review.ts
+++ b/packages/server/review.ts
@@ -204,7 +204,7 @@ import { checkServerSession, createServerSessionNonce, serverSessionMismatchBody
 import { isAIEndpointPath, isLongLivedAIEndpointPath, type AIEndpoints, type SessionBridge } from "@plannotator/ai";
 import { isWSL } from "./browser";
 import { getExtraMarkdownExtensions } from "@plannotator/shared/resolve-file";
-import { handleOpenInApps, handleOpenIn } from "./open-in";
+import { handleOpenInApps, handleOpenIn, openInProjectFolder } from "./open-in";
 import { resolveWorkspaceFilePath, type LocalWorkspaceReview, type WorkspaceDiffType } from "./review-workspace";
 import { handleCodeNavResolve, handleCodeNavHover, extractChangedFiles } from "./code-nav";
 import { readRepoFile, repoFileErrorBody, REPO_FILE_ERROR_STATUS } from "@plannotator/shared/repo-file";
@@ -2651,7 +2651,14 @@ export async function startReviewServer(
                 { status: 400 },
               );
             }
-            return handleOpenIn(req, { resolveRoot: resolveOpenInRoot, serverSession, exposed: options.tailnetPublished === true });
+            return handleOpenIn(req, {
+              resolveRoot: resolveOpenInRoot,
+              // The checkout under review (the PR's own clone or worktree in PR
+              // mode): a JetBrains IDE opens the file in that project's window.
+              projectFor: (abs) => openInProjectFolder(abs, resolveOpenInRoot()),
+              serverSession,
+              exposed: options.tailnetPublished === true,
+            });
           }
 
           // API: cheap staleness probe — has the underlying VCS state changed
Plannotator version

plannotator 0.29.0 (also seen on 0.28.63)

OS

macOS

Agent

Claude Code

Where did it happen?

Code review

主要语言
TypeScript
星标
8.7k
派生
649
平均合并
16 小时 1 分钟
30 天内合并 PR
756

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

backnotprop/plannotator 的其他 Issue

查看 backnotprop/plannotator 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。