Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion apps/pi-extension/server/serverReview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
type DiffType,
type GitCommandResult,
type GitContext,
detectRemoteDefaultBranch,
getFileContentsForDiff as getFileContentsForDiffCore,
getGitContext as getGitContextCore,
gitAddFile as gitAddFileCore,
Expand Down Expand Up @@ -106,11 +107,12 @@ export interface ReviewServerResult {
export const reviewRuntime: ReviewGitRuntime = {
async runGit(
args: string[],
options?: { cwd?: string },
options?: { cwd?: string; timeoutMs?: number },
): Promise<GitCommandResult> {
const result = spawnSync("git", args, {
cwd: options?.cwd,
encoding: "utf-8",
...(options?.timeoutMs ? { timeout: options.timeoutMs } : {}),
});
return {
stdout: result.stdout ?? "",
Expand Down Expand Up @@ -207,6 +209,14 @@ export async function startReviewServer(options: {
// the reviewer is currently looking at. Honors an explicit initialBase from
// the caller — e.g. programmatic Pi callers can request a non-detected base.
let currentBase = options.initialBase || options.gitContext?.defaultBranch || "main";
let baseEverSwitched = false;

// Fire-and-forget: query the remote for its actual default branch.
if (options.gitContext && !options.initialBase && !isPRMode) {
detectRemoteDefaultBranch(reviewRuntime, options.gitContext.cwd).then((remote) => {
if (remote && !baseEverSwitched) currentBase = remote;
});
}

// Agent jobs — background process manager (late-binds serverUrl via getter)
let serverUrl = "";
Expand Down Expand Up @@ -547,6 +557,7 @@ export async function startReviewServer(options: {
currentGitRef = result.label;
currentDiffType = newType;
currentBase = base;
baseEverSwitched = true;
currentError = result.error;

// Recompute gitContext for the effective cwd so the client's
Expand Down
9 changes: 8 additions & 1 deletion packages/server/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,27 @@ export type {

async function runGit(
args: string[],
options?: { cwd?: string },
options?: { cwd?: string; timeoutMs?: number },
): Promise<GitCommandResult> {
const proc = Bun.spawn(["git", ...args], {
cwd: options?.cwd,
stdout: "pipe",
stderr: "pipe",
});

let timer: ReturnType<typeof setTimeout> | undefined;
if (options?.timeoutMs) {
timer = setTimeout(() => proc.kill(), options.timeoutMs);
}

const [stdout, stderr, exitCode] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);

if (timer) clearTimeout(timer);

return { stdout, stderr, exitCode };
}

Expand Down
17 changes: 14 additions & 3 deletions packages/server/review.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,9 @@

import { isRemoteSession, getServerHostname, getServerPort } from "./remote";
import type { Origin } from "@plannotator/shared/agents";
import { type DiffType, type GitContext, runVcsDiff, getVcsFileContentsForDiff, canStageFiles, stageFile, unstageFile, resolveVcsCwd, validateFilePath, getVcsContext } from "./vcs";
import { parseWorktreeDiffType } from "@plannotator/shared/review-core";
import { type DiffType, type GitContext, runVcsDiff, getVcsFileContentsForDiff, canStageFiles, stageFile, unstageFile, resolveVcsCwd, validateFilePath, getVcsContext, gitRuntime } from "./vcs";
import { parseWorktreeDiffType, detectRemoteDefaultBranch, resolveBaseBranch } from "@plannotator/shared/review-core";
import type { AgentJobInfo } from "@plannotator/shared/agent-jobs";
import { resolveBaseBranch } from "@plannotator/shared/review-core";
import { getRepoInfo } from "./repo";
import { handleImage, handleUpload, handleAgents, handleServerReady, handleDraftSave, handleDraftLoad, handleDraftDelete, handleFavicon, type OpencodeClient } from "./shared-handlers";
import { contentHash, deleteDraft } from "./draft";
Expand Down Expand Up @@ -144,6 +143,17 @@ export async function startReviewServer(
// the reviewer is currently looking at. Honors an explicit initialBase from
// the caller — e.g. programmatic Pi callers can request a non-detected base.
let currentBase = options.initialBase || gitContext?.defaultBranch || "main";
let baseEverSwitched = false;

// Fire-and-forget: query the remote for its actual default branch. If it
// arrives before the user interacts, quietly upgrade currentBase from the
// local fallback (e.g. "main") to the upstream ref (e.g. "origin/main").
// Non-blocking — the server is already listening by the time this resolves.
if (gitContext && !options.initialBase && !isPRMode) {
detectRemoteDefaultBranch(gitRuntime, gitContext.cwd).then((remote) => {
if (remote && !baseEverSwitched) currentBase = remote;
});
}

// Agent jobs — background process manager (late-binds serverUrl via getter)
let serverUrl = "";
Expand Down Expand Up @@ -496,6 +506,7 @@ export async function startReviewServer(
currentGitRef = result.label;
currentDiffType = newDiffType;
currentBase = base;
baseEverSwitched = true;
currentError = result.error;

// Recompute gitContext for the effective cwd so the client's
Expand Down
34 changes: 33 additions & 1 deletion packages/shared/review-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export interface GitCommandResult {
export interface ReviewGitRuntime {
runGit: (
args: string[],
options?: { cwd?: string },
options?: { cwd?: string; timeoutMs?: number },
) => Promise<GitCommandResult>;
readTextFile: (path: string) => Promise<string | null>;
}
Expand Down Expand Up @@ -111,6 +111,38 @@ export async function getDefaultBranch(
return "master";
}

/**
* Query the remote for its default branch via `ls-remote --symref`. Returns
* `origin/<name>` if the remote answers and the tracking ref exists locally,
* otherwise `null`. Designed to run in the background at server startup — the
* caller fires it with `.then()` and uses the result if/when it arrives.
*
* Timeout-guarded: if the network is slow or absent, the promise resolves
* (with `null`) once the timeout fires. Never throws.
*/
export async function detectRemoteDefaultBranch(
runtime: ReviewGitRuntime,
cwd?: string,
): Promise<string | null> {
try {
const lsRemote = await runtime.runGit(
["ls-remote", "--symref", "origin", "HEAD"],
{ cwd, timeoutMs: 5000 },
);
if (lsRemote.exitCode !== 0) return null;
const match = lsRemote.stdout.match(/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m);
if (!match) return null;
const remoteBranch = `origin/${match[1]}`;
const refExists = await runtime.runGit(
["show-ref", "--verify", "--quiet", `refs/remotes/${remoteBranch}`],
{ cwd },
);
return refExists.exitCode === 0 ? remoteBranch : null;
} catch {
return null;
}
}

export async function listBranches(
runtime: ReviewGitRuntime,
cwd?: string,
Expand Down