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.

πŸ› fix(git): resolve a topic's remote branch instead of trusting the local name (#17150)

Arvin Xuc9c2e90dd5b6
diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.ts
index 60d8892067c..0a080d11ddf 100644
--- a/packages/electron-client-ipc/src/types/git.ts
+++ b/packages/electron-client-ipc/src/types/git.ts
@@ -1,8 +1,22 @@
+/**
+ * The remote ref a local branch publishes to β€” the only branch identity that means
+ * anything off this machine. A worktree's generated branch name or a push with an
+ * explicit refspec makes the local name differ from the remote one.
+ */
+export interface GitUpstreamRef {
+ /** Branch name ON the remote (`feat/x`), never the local name */
+ branch: string;
+ /** Remote name (`origin`) */
+ remote: string;
+}
+
export interface GitBranchInfo {
/** Branch short name, or short SHA when in detached HEAD state */
branch?: string;
/** True when HEAD is detached (no branch ref) */
detached?: boolean;
+ /** Remote ref the branch publishes to. Absent when unpushed or unresolvable */
+ upstream?: GitUpstreamRef;
}
export type GitPullRequestCiStatus = 'failure' | 'pending' | 'success' | 'unknown';
@@ -29,6 +43,8 @@ export interface GitLinkedPullRequestResult {
pullRequest: GitLinkedPullRequest | null;
/** 'ok' β€” lookup succeeded; 'gh-missing' β€” gh CLI unavailable / not authed; 'error' β€” other failure */
status: GitLinkedPullRequestLookupStatus;
+ /** Remote ref the lookup queried under β€” the PR's own head ref when one was found */
+ upstream?: GitUpstreamRef;
}
export interface GitBranchListItem {
diff --git a/packages/local-file-shell/src/git/__tests__/info.test.ts b/packages/local-file-shell/src/git/__tests__/info.test.ts
index 81f716914db..c0f6332822d 100644
--- a/packages/local-file-shell/src/git/__tests__/info.test.ts
+++ b/packages/local-file-shell/src/git/__tests__/info.test.ts
@@ -1,6 +1,8 @@
+import { readdir, readFile } from 'node:fs/promises';
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { getLinkedPullRequest } from '../info';
+import { getGitBranch, getLinkedPullRequest } from '../info';
const childProcessMocks = vi.hoisted(() => ({
execFileAsync: vi.fn(),
@@ -14,60 +16,151 @@ vi.mock('node:child_process', () => {
return { execFile };
});
+vi.mock('node:fs/promises', () => ({
+ readdir: vi.fn(),
+ readFile: vi.fn(),
+}));
+
+const ok = (stdout: string) => ({ stderr: '', stdout });
+
+const PULL_REQUEST = {
+ headRefName: 'feat/hetero-session-import-ui',
+ isDraft: false,
+ mergeStateStatus: 'CLEAN',
+ mergeable: 'MERGEABLE',
+ mergedAt: '2026-07-07T09:00:00Z',
+ number: 17_101,
+ reviewDecision: 'APPROVED',
+ state: 'MERGED',
+ statusCheckRollup: [{ conclusion: 'SUCCESS' }],
+ title: 'feat: import local sessions',
+ url: 'https://github.com/lobehub/lobehub/pull/17101',
+};
+
+const NORMALIZED_PULL_REQUEST = {
+ ciStatus: 'success',
+ isDraft: false,
+ mergeStateStatus: 'CLEAN',
+ mergeable: 'MERGEABLE',
+ mergedAt: '2026-07-07T09:00:00Z',
+ number: 17_101,
+ reviewDecision: 'APPROVED',
+ state: 'MERGED',
+ title: 'feat: import local sessions',
+ url: 'https://github.com/lobehub/lobehub/pull/17101',
+};
+
+interface ShellFixture {
+ /** `for-each-ref refs/heads/<branch>` β†’ `<sha>\t<upstream remote>\t<upstream ref>`. */
+ branchRef?: string;
+ /** The branch's commit is already contained in the remote default branch (fork point). */
+ commitOnDefault?: boolean;
+ /** `gh api repos/{owner}/{repo}/commits/<sha>/pulls`. */
+ commitPulls?: unknown[];
+ defaultBranch?: Record<string, string>;
+ /** `gh pr list --head`. */
+ prList?: unknown[];
+ /** `gh pr view <n>`. */
+ prView?: unknown;
+ /** Refs this repo pushed to β€” git writes `update by push` into their reflog. */
+ pushedRefs?: string[];
+ refsAt?: string[];
+ remotes?: string[];
+ /** Remote refs a local branch tracks (`for-each-ref --format=%(upstream)`). */
+ trackedRefs?: string[];
+}
+
+/**
+ * A branch published under a different remote name, with every signal real git would
+ * leave behind: the tracking ref sits on the commit, its reflog records the push, and
+ * the branch tracks it.
+ */
+const publishedAs = (ref: string) => ({
+ branchRef: `sha1\torigin\t${ref}`,
+ pushedRefs: [ref],
+ refsAt: [ref],
+ trackedRefs: [ref],
+});
+
+const mockShell = ({
+ branchRef = '',
+ commitOnDefault = false,
+ commitPulls,
+ defaultBranch = { origin: 'origin/canary' },
+ prList = [],
+ prView,
+ pushedRefs = [],
+ refsAt = [],
+ remotes = ['origin'],
+ trackedRefs = [],
+}: ShellFixture) => {
+ childProcessMocks.execFileAsync.mockImplementation(async (cmd: string, args: string[]) => {
+ if (cmd === 'git') {
+ const [subcommand] = args;
+ if (subcommand === 'remote') return ok(remotes.join('\n'));
+ if (subcommand === 'merge-base') {
+ // `--is-ancestor` reports through the exit status: 0 = contained, 1 = not.
+ if (!commitOnDefault) throw Object.assign(new Error('not an ancestor'), { code: 1 });
+ return ok('');
+ }
+ if (subcommand === 'reflog') {
+ const ref = args[2];
+ return ok(pushedRefs.includes(ref) ? `abc1234 ${ref}@{0}: update by push` : '');
+ }
+ if (subcommand === 'symbolic-ref') {
+ const remote = args[2].replace('refs/remotes/', '').replace('/HEAD', '');
+ const target = defaultBranch[remote];
+ if (!target) throw new Error('fatal: not a symbolic ref');
+ return ok(target);
+ }
+ if (subcommand === 'for-each-ref') {
+ if (args.includes('--points-at')) return ok(refsAt.join('\n'));
+ if (args.includes('--format=%(upstream)')) return ok(trackedRefs.join('\n'));
+ return ok(branchRef);
+ }
+ }
+
+ if (cmd === 'gh') {
+ if (args[0] === 'api') {
+ if (!commitPulls) throw new Error('gh api failed');
+ return ok(JSON.stringify(commitPulls));
+ }
+ if (args[1] === 'list') return ok(JSON.stringify(prList));
+ if (args[1] === 'view') return ok(JSON.stringify(prView ?? {}));
+ }
+
+ throw new Error(`unexpected: ${cmd} ${args.join(' ')}`);
+ });
+};
+
+/** Args of every `gh` invocation, so a test can assert what was β€” and wasn't β€” asked. */
+const ghCalls = (): string[][] =>
+ childProcessMocks.execFileAsync.mock.calls
+ .filter(([cmd]) => cmd === 'gh')
+ .map(([, args]) => args as string[]);
+
describe('getLinkedPullRequest', () => {
beforeEach(() => {
childProcessMocks.execFileAsync.mockReset();
});
it('queries the preserved PR number directly when provided', async () => {
- childProcessMocks.execFileAsync.mockResolvedValue({
- stderr: '',
- stdout: JSON.stringify({
- isDraft: false,
- mergeStateStatus: 'CLEAN',
- mergeable: 'MERGEABLE',
- mergedAt: '2026-07-07T09:00:00Z',
- number: 123,
- reviewDecision: 'APPROVED',
- state: 'MERGED',
- statusCheckRollup: [{ conclusion: 'SUCCESS' }],
- title: 'fix: stop stale running topics',
- url: 'https://github.com/lobehub/lobehub/pull/123',
- }),
- });
+ mockShell({ branchRef: 'sha1\t\t', prView: PULL_REQUEST });
const result = await getLinkedPullRequest({
branch: 'fix/topic-running',
path: '/repo',
- pullRequestNumber: 123,
+ pullRequestNumber: 17_101,
});
- expect(childProcessMocks.execFileAsync).toHaveBeenCalledWith(
- 'gh',
- expect.arrayContaining(['pr', 'view', '123', '--json']),
- { cwd: '/repo', timeout: 8000 },
- );
- expect(childProcessMocks.execFileAsync.mock.calls[0]![1]).not.toContain('--head');
- expect(result.pullRequest).toMatchObject({ mergedAt: '2026-07-07T09:00:00Z', number: 123 });
+ expect(ghCalls()).toEqual([['pr', 'view', '17101', '--json', expect.any(String)]]);
+ expect(result.pullRequest).toMatchObject({ mergedAt: '2026-07-07T09:00:00Z', number: 17_101 });
});
it('queries all PR states so merged pull requests can refresh topic metadata', async () => {
- childProcessMocks.execFileAsync.mockResolvedValue({
- stderr: '',
- stdout: JSON.stringify([
- {
- isDraft: false,
- mergeStateStatus: 'CLEAN',
- mergeable: 'MERGEABLE',
- mergedAt: '2026-07-07T09:00:00Z',
- number: 123,
- reviewDecision: 'APPROVED',
- state: 'MERGED',
- statusCheckRollup: [{ conclusion: 'SUCCESS' }],
- title: 'fix: stop stale running topics',
- url: 'https://github.com/lobehub/lobehub/pull/123',
- },
- ]),
+ mockShell({
+ branchRef: 'sha1\torigin\trefs/remotes/origin/fix/topic-running',
+ prList: [{ ...PULL_REQUEST, headRefName: 'fix/topic-running' }],
});
const result = await getLinkedPullRequest({ branch: 'fix/topic-running', path: '/repo' });
@@ -79,19 +172,179 @@ describe('getLinkedPullRequest', () => {
);
expect(result).toEqual({
extraCount: 0,
- pullRequest: {
- ciStatus: 'success',
- isDraft: false,
- mergeStateStatus: 'CLEAN',
- mergeable: 'MERGEABLE',
- mergedAt: '2026-07-07T09:00:00Z',
- number: 123,
- reviewDecision: 'APPROVED',
- state: 'MERGED',
- title: 'fix: stop stale running topics',
- url: 'https://github.com/lobehub/lobehub/pull/123',
- },
+ pullRequest: NORMALIZED_PULL_REQUEST,
status: 'ok',
+ upstream: { branch: 'fix/topic-running', remote: 'origin' },
});
});
+
+ // The reported bug. The local branch name never existed on the remote, so asking
+ // `gh` about it returned an empty list forever and the PR silently never linked.
+ it('queries the head branch that exists on the REMOTE, not the local branch name', async () => {
+ mockShell({
+ ...publishedAs('refs/remotes/origin/feat/hetero-session-import-ui'),
+ prList: [PULL_REQUEST],
+ });
+
+ const result = await getLinkedPullRequest({
+ branch: 'worktree-feat+claude-code-session-import',
+ path: '/repo',
+ });
+
+ const listArgs = ghCalls().find((args) => args[1] === 'list')!;
+ expect(listArgs).toContain('feat/hetero-session-import-ui');
+ expect(listArgs).not.toContain('worktree-feat+claude-code-session-import');
+
+ expect(result.pullRequest).toMatchObject({ number: 17_101 });
+ expect(result.upstream).toEqual({
+ branch: 'feat/hetero-session-import-ui',
+ remote: 'origin',
+ });
+ });
+
+ it('recovers the PR by commit when the push left no local trace of the remote branch', async () => {
+ mockShell({
+ branchRef: 'sha1\t\t',
+ commitPulls: [{ head: { ref: 'feat/hetero-session-import-ui' }, number: 17_101 }],
+ prList: [],
+ prView: PULL_REQUEST,
+ });
+
+ const result = await getLinkedPullRequest({ branch: 'worktree-feat+x', path: '/repo' });
+
+ expect(ghCalls()).toContainEqual(['api', 'repos/{owner}/{repo}/commits/sha1/pulls']);
+ expect(result).toEqual({
+ pullRequest: NORMALIZED_PULL_REQUEST,
+ status: 'ok',
+ upstream: { branch: 'feat/hetero-session-import-ui', remote: 'origin' },
+ });
+ });
+
+ // An empty list under a RESOLVED remote ref is a real answer β€” the branch has no PR.
+ // Spending a network call to re-ask by commit on every poll would be pure waste.
+ it('skips the commit lookup when a remote ref was resolved and the branch has no PR', async () => {
+ mockShell({ ...publishedAs('refs/remotes/origin/feat/y'), prList: [] });
+
+ const result = await getLinkedPullRequest({ branch: 'worktree-feat+x', path: '/repo' });
+
+ expect(ghCalls().some((args) => args[0] === 'api')).toBe(false);
+ expect(result).toEqual({
+ pullRequest: null,
+ status: 'ok',
+ upstream: { branch: 'feat/y', remote: 'origin' },
+ });
+ });
+
+ it('takes the remote ref from the PR itself when resolving a saved PR number', async () => {
+ mockShell({ branchRef: 'sha1\t\t', prView: PULL_REQUEST });
+
+ const result = await getLinkedPullRequest({
+ branch: 'worktree-feat+x',
+ path: '/repo',
+ pullRequestNumber: 17_101,
+ });
+
+ expect(result.upstream).toEqual({
+ branch: 'feat/hetero-session-import-ui',
+ remote: 'origin',
+ });
+ });
+
+ // `/commits/{sha}/pulls` answers "which PR INTRODUCED this commit". A branch with no
+ // commits of its own sits on the commit it forked from β€” already merged into canary β€”
+ // so asking about it would staple a stranger's merged PR onto a brand-new topic.
+ it('never asks GitHub about a commit that is just the fork point', async () => {
+ mockShell({
+ branchRef: 'sha1\t\t',
+ commitOnDefault: true,
+ commitPulls: [{ head: { ref: 'someone-elses-branch' }, number: 999 }],
+ prList: [],
+ });
+
+ const result = await getLinkedPullRequest({ branch: 'worktree-fresh', path: '/repo' });
+
+ expect(ghCalls().some((args) => args[0] === 'api')).toBe(false);
+ expect(result).toEqual({ pullRequest: null, status: 'ok' });
+ });
+
+ // `refs/remotes/<remote>/HEAD` is only written by `git clone`. Without it the fork
+ // point cannot be ruled out, and a wrong PR is worse than no PR.
+ it('never asks GitHub when the remote default branch is unknown', async () => {
+ mockShell({
+ branchRef: 'sha1\t\t',
+ commitPulls: [{ head: { ref: 'someone-elses-branch' }, number: 999 }],
+ defaultBranch: {},
+ prList: [],
+ });
+
+ const result = await getLinkedPullRequest({ branch: 'worktree-fresh', path: '/repo' });
+
+ expect(ghCalls().some((args) => args[0] === 'api')).toBe(false);
+ expect(result).toEqual({ pullRequest: null, status: 'ok' });
+ });
+
+ // `gh pr list` already proved gh is healthy, so a failing fallback means "no PR",
+ // not "lookup broken" β€” reporting an error would surface a false failure in the UI.
+ it('degrades a failing commit lookup to "no PR" rather than an error', async () => {
+ mockShell({ branchRef: 'sha1\t\t', prList: [] });
+
+ expect(await getLinkedPullRequest({ branch: 'worktree-feat+x', path: '/repo' })).toEqual({
+ pullRequest: null,
+ status: 'ok',
+ });
+ });
+
+ it('reports gh-missing when the gh CLI is unavailable', async () => {
+ childProcessMocks.execFileAsync.mockRejectedValue(
+ Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' }),
+ );
+
+ expect(await getLinkedPullRequest({ branch: 'feat/x', path: '/repo' })).toEqual({
+ pullRequest: null,
+ status: 'gh-missing',
+ });
+ });
+});
+
+describe('getGitBranch', () => {
+ beforeEach(() => {
+ childProcessMocks.execFileAsync.mockReset();
+ vi.mocked(readdir).mockReset();
+ vi.mocked(readFile).mockReset();
+ });
+
+ const mockHead = (head: string) => {
+ vi.mocked(readdir).mockResolvedValue(['HEAD'] as never);
+ vi.mocked(readFile).mockImplementation(async (target) => {
+ if (String(target) === '/repo/.git/HEAD') return head;
+ // `.git` is a directory, not a worktree pointer file.
+ throw Object.assign(new Error('EISDIR'), { code: 'EISDIR' });
+ });
+ };
+
+ it('carries the remote ref alongside the branch', async () => {
+ mockHead('ref: refs/heads/worktree-feat+x\n');
+ mockShell(publishedAs('refs/remotes/origin/feat/y'));
+
+ expect(await getGitBranch('/repo')).toEqual({
+ branch: 'worktree-feat+x',
+ upstream: { branch: 'feat/y', remote: 'origin' },
+ });
+ });
+
+ it('omits the remote ref for an unpushed branch', async () => {
+ mockHead('ref: refs/heads/worktree-feat+x\n');
+ mockShell({ branchRef: 'sha1\t\t' });
+
+ expect(await getGitBranch('/repo')).toEqual({ branch: 'worktree-feat+x' });
+ });
+
+ // A detached HEAD has no branch to publish, so it must not pay for a git subprocess.
+ it('stays a pure filesystem read for a detached HEAD', async () => {
+ mockHead('a'.repeat(40));
+ mockShell({});
+
+ expect(await getGitBranch('/repo')).toEqual({ branch: 'aaaaaaa', detached: true });
+ expect(childProcessMocks.execFileAsync).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/local-file-shell/src/git/__tests__/upstream.test.ts b/packages/local-file-shell/src/git/__tests__/upstream.test.ts
new file mode 100644
index 00000000000..f18c5861be1
--- /dev/null
+++ b/packages/local-file-shell/src/git/__tests__/upstream.test.ts
@@ -0,0 +1,284 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resolveUpstream } from '../upstream';
+
+const childProcessMocks = vi.hoisted(() => ({
+ execFileAsync: vi.fn(),
+}));
+
+vi.mock('node:child_process', () => {
+ const execFile = Object.assign(vi.fn(), {
+ [Symbol.for('nodejs.util.promisify.custom')]: childProcessMocks.execFileAsync,
+ });
+
+ return { execFile };
+});
+
+const ok = (stdout: string) => ({ stderr: '', stdout });
+
+interface GitFixture {
+ /** `for-each-ref refs/heads/<branch>` β†’ `<sha>\t<upstream remote>\t<upstream ref>`. */
+ branchRef?: string;
+ /**
+ * Remote β†’ its `refs/remotes/<remote>/HEAD` target, e.g. `origin` β†’ `origin/canary`.
+ * Absent for any repo not created by `git clone`, so nothing may depend on it alone.
+ */
+ defaultBranch?: Record<string, string>;
+ /** Refs this repo pushed to β€” git writes `update by push` into their reflog. */
+ pushedRefs?: string[];
+ /** Remote-tracking refs whose tip is the branch's commit. */
+ refsAt?: string[];
+ remotes?: string[];
+ /** Remote refs a local branch already tracks (`for-each-ref --format=%(upstream)`). */
+ trackedRefs?: string[];
+}
+
+const mockGit = ({
+ branchRef = '',
+ defaultBranch = {},
+ pushedRefs = [],
+ refsAt = [],
+ remotes = [],
+ trackedRefs = [],
+}: GitFixture) => {
+ childProcessMocks.execFileAsync.mockImplementation(async (_cmd: string, args: string[]) => {
+ const [subcommand] = args;
+
+ if (subcommand === 'remote') return ok(remotes.join('\n'));
+
+ if (subcommand === 'reflog') {
+ const ref = args[2];
+ // A fetched / cloned ref has no reflog at all β€” git prints nothing.
+ return ok(pushedRefs.includes(ref) ? `abc1234 ${ref}@{0}: update by push` : '');
+ }
+
+ if (subcommand === 'symbolic-ref') {
+ const remote = args[2].replace('refs/remotes/', '').replace('/HEAD', '');
+ const target = defaultBranch[remote];
+ // `origin/HEAD` unset β€” git exits non-zero.
+ if (!target) throw new Error('fatal: ref refs/remotes/origin/HEAD is not a symbolic ref');
+ return ok(target);
+ }
+
+ if (subcommand === 'for-each-ref') {
+ if (args.includes('--points-at')) return ok(refsAt.join('\n'));
+ if (args.includes('--format=%(upstream)')) return ok(trackedRefs.join('\n'));
+ return ok(branchRef);
+ }
+
+ throw new Error(`unexpected: git ${args.join(' ')}`);
+ });
+};
+
+describe('resolveUpstream', () => {
+ beforeEach(() => {
+ childProcessMocks.execFileAsync.mockReset();
+ });
+
+ it('uses the configured upstream when it carries the branch’s own name', async () => {
+ mockGit({ branchRef: 'sha1\torigin\trefs/remotes/origin/feat/x' });
+
+ expect(await resolveUpstream('/repo', 'feat/x')).toEqual({
+ sha: 'sha1',
+ upstream: { branch: 'feat/x', remote: 'origin' },
+ });
+ // The common shape must not pay for the ownership probes.
+ expect(childProcessMocks.execFileAsync).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a slashed remote branch name intact', async () => {
+ mockGit({ branchRef: 'sha1\torigin\trefs/remotes/origin/feat/deep/nested' });
+
+ expect((await resolveUpstream('/repo', 'feat/deep/nested')).upstream).toEqual({
+ branch: 'feat/deep/nested',
+ remote: 'origin',
+ });
+ });
+
+ // `git checkout -b feat/x origin/canary` auto-sets @{upstream} to the branch it was
+ // forked FROM, and leaves it there forever. Taken at face value it would send the PR
+ // lookup hunting for a PR whose head is `canary`. Caught end-to-end against real git.
+ it('refuses an auto-set fork-base upstream, which is a pull source not a push target', async () => {
+ mockGit({
+ // @{upstream} = origin/canary, but the branch is feat/x.
+ branchRef: 'sha1\torigin\trefs/remotes/origin/canary',
+ defaultBranch: { origin: 'origin/canary' },
+ remotes: ['origin'],
+ trackedRefs: ['refs/remotes/origin/canary'],
+ });
+
+ expect(await resolveUpstream('/repo', 'feat/x')).toEqual({ sha: 'sha1' });
+ });
+
+ // Same stale fork-base upstream, but the branch HAS since been pushed β€” under a
+ // different name. The pushed ref must win over the fork base.
+ it('ignores the fork base and takes the ref the branch was actually pushed to', async () => {
+ mockGit({
+ branchRef: 'sha1\torigin\trefs/remotes/origin/canary',
+ defaultBranch: { origin: 'origin/canary' },
+ pushedRefs: ['refs/remotes/origin/feat/renamed'],
+ refsAt: ['refs/remotes/origin/feat/renamed'],
+ remotes: ['origin'],
+ trackedRefs: ['refs/remotes/origin/canary'],
+ });
+
+ expect((await resolveUpstream('/repo', 'worktree-x')).upstream).toEqual({
+ branch: 'feat/renamed',
+ remote: 'origin',
+ });
+ });
+
+ // `git push -u origin wt-x:feat/y` β€” a real publication under a different name. Its
+ // own ref shows up in the tracked set (the branch tracks it), which must not
+ // disqualify it: "tracked" only rules out refs owned by ANOTHER local branch.
+ it('trusts a differently-named configured upstream that this repo pushed to', async () => {
+ mockGit({
+ branchRef: 'sha1\torigin\trefs/remotes/origin/feat/y',
+ defaultBranch: { origin: 'origin/canary' },
+ pushedRefs: ['refs/remotes/origin/feat/y'],
+ refsAt: ['refs/remotes/origin/feat/y'],
+ remotes: ['origin'],
+ trackedRefs: ['refs/remotes/origin/feat/y'],
+ });
+
+ expect((await resolveUpstream('/repo', 'worktree-x')).upstream).toEqual({
+ branch: 'feat/y',
+ remote: 'origin',
+ });
+ });
+
+ // The reported bug: `git push origin worktree-x:feat/y` sets no upstream, but it
+ // DOES move `refs/remotes/origin/feat/y` onto the branch's commit.
+ it('recovers the remote branch from a tracking ref this repo pushed to', async () => {
+ mockGit({
+ branchRef: 'sha1\t\t',
+ defaultBranch: { origin: 'origin/canary' },
+ pushedRefs: ['refs/remotes/origin/feat/y'],
+ refsAt: ['refs/remotes/origin/feat/y'],
+ remotes: ['origin'],
+ });
+
+ expect(await resolveUpstream('/repo', 'worktree-feat+x')).toEqual({
+ sha: 'sha1',
+ upstream: { branch: 'feat/y', remote: 'origin' },
+ });
+ });
+
+ it('prefers the identically-named remote branch over any other candidate', async () => {
+ mockGit({
+ branchRef: 'sha1\t\t',
+ defaultBranch: { origin: 'origin/canary' },
+ refsAt: ['refs/remotes/origin/someone-elses-ref', 'refs/remotes/origin/feat/x'],
+ remotes: ['origin'],
+ });
+
+ expect((await resolveUpstream('/repo', 'feat/x')).upstream).toEqual({
+ branch: 'feat/x',
+ remote: 'origin',
+ });
+ });
+
+ // A branch with no commits of its own still points at the commit it forked from, so
+ // the base branch's remote ref sits at that SHA too. Inferring it would bind the
+ // topic to canary's PR. Caught end-to-end: the repo had no `origin/HEAD` to guard on.
+ it('refuses to infer the fork point, even with no origin/HEAD to recognise it by', async () => {
+ mockGit({
+ branchRef: 'sha1\t\t',
+ // `git init` + `remote add` never writes origin/HEAD β€” only `git clone` does.
+ defaultBranch: {},
+ refsAt: ['refs/remotes/origin/canary'],
+ remotes: ['origin'],
+ // Fetched, not pushed from here β†’ no reflog. And local canary already claims it.
+ trackedRefs: ['refs/remotes/origin/canary'],
+ });
+
+ expect(await resolveUpstream('/repo', 'worktree-feat+x')).toEqual({ sha: 'sha1' });
+ });
+
+ // Same fork point, but this repo DID push canary earlier, so the reflog attests a
+ // push. Only "another local branch already tracks it" separates the two.
+ it('refuses a ref that another local branch already tracks', async () => {
+ mockGit({
+ branchRef: 'sha1\t\t',
+ pushedRefs: ['refs/remotes/origin/canary'],
+ refsAt: ['refs/remotes/origin/canary'],
+ remotes: ['origin'],
+ trackedRefs: ['refs/remotes/origin/canary'],
+ });
+
+ expect((await resolveUpstream('/repo', 'worktree-feat+x')).upstream).toBeUndefined();
+ });
+
+ // Forked from a ref that arrived by fetch/clone: it has no push reflog, which is
+ // what proves the commit got there by someone else's push, not ours.
+ it('refuses a ref this repo never pushed to', async () => {
+ mockGit({
+ branchRef: 'sha1\t\t',
+ refsAt: ['refs/remotes/origin/colleagues-branch'],
+ remotes: ['origin'],
+ });
+
+ expect((await resolveUpstream('/repo', 'worktree-feat+x')).upstream).toBeUndefined();
+ });
+
+ it('still refuses a remote default branch it happens to have pushed', async () => {
+ mockGit({
+ branchRef: 'sha1\t\t',
+ defaultBranch: { origin: 'origin/canary' },
+ pushedRefs: ['refs/remotes/origin/canary'],
+ refsAt: ['refs/remotes/origin/canary'],
+ remotes: ['origin'],
+ });
+
+ expect((await resolveUpstream('/repo', 'worktree-feat+x')).upstream).toBeUndefined();
+ });
+
+ it('refuses to guess between several differently-named candidates', async () => {
+ mockGit({
+ branchRef: 'sha1\t\t',
+ defaultBranch: { origin: 'origin/canary' },
+ pushedRefs: ['refs/remotes/origin/feat/a', 'refs/remotes/origin/feat/b'],
+ refsAt: ['refs/remotes/origin/feat/a', 'refs/remotes/origin/feat/b'],
+ remotes: ['origin'],
+ });
+
+ expect((await resolveUpstream('/repo', 'worktree-feat+x')).upstream).toBeUndefined();
+ });
+
+ it('ignores the symbolic origin/HEAD pointer as a candidate', async () => {
+ mockGit({
+ branchRef: 'sha1\t\t',
+ pushedRefs: ['refs/remotes/origin/HEAD'],
+ refsAt: ['refs/remotes/origin/HEAD'],
+ remotes: ['origin'],
+ });
+
+ expect((await resolveUpstream('/repo', 'worktree-feat+x')).upstream).toBeUndefined();
+ });
+
+ // The whole point of the field: an unpushed branch has NO remote ref, and the local
+ // name is not a stand-in for one.
+ it('never falls back to the local branch name for an unpushed branch', async () => {
+ mockGit({ branchRef: 'sha1\t\t', remotes: ['origin'] });
+
+ expect(await resolveUpstream('/repo', 'worktree-feat+x')).toEqual({ sha: 'sha1' });
+ });
+
+ it('yields nothing for a branch that does not exist locally', async () => {
+ mockGit({ branchRef: '' });
+
+ expect(await resolveUpstream('/repo', 'gone')).toEqual({});
+ });
+
+ it('degrades silently in a repo with no remotes', async () => {
+ mockGit({ branchRef: 'sha1\t\t', remotes: [] });
+
+ expect(await resolveUpstream('/repo', 'feat/x')).toEqual({ sha: 'sha1' });
+ });
+
+ it('degrades silently when git itself fails', async () => {
+ childProcessMocks.execFileAsync.mockRejectedValue(new Error('not a git repository'));
+
+ expect(await resolveUpstream('/nowhere', 'feat/x')).toEqual({});
+ });
+});
diff --git a/packages/local-file-shell/src/git/index.ts b/packages/local-file-shell/src/git/index.ts
index 8d8f0adcac4..ec6b6d43237 100644
--- a/packages/local-file-shell/src/git/index.ts
+++ b/packages/local-file-shell/src/git/index.ts
@@ -2,5 +2,6 @@ export * from './branches';
export * from './info';
export * from './repoType';
export * from './types';
+export * from './upstream';
export * from './workingTree';
export * from './worktrees';
diff --git a/packages/local-file-shell/src/git/info.ts b/packages/local-file-shell/src/git/info.ts
index 89687958c1a..eb5e908430a 100644
--- a/packages/local-file-shell/src/git/info.ts
+++ b/packages/local-file-shell/src/git/info.ts
@@ -11,8 +11,10 @@ import type {
GitLinkedPullRequest,
GitLinkedPullRequestResult,
GitPullRequestCiStatus,
+ GitUpstreamRef,
GitWorkingTreeStatus,
} from './types';
+import { getDefaultRemote, isCommitSafeForPullRequestLookup, resolveUpstream } from './upstream';
const log = createLogger('local-file-shell:git');
const execFileAsync = promisify(execFile);
@@ -24,6 +26,8 @@ type GithubStatusCheckRollupNode = {
};
type GithubPullRequestPayload = {
+ /** The PR's head branch ON GitHub β€” the authoritative remote ref for this branch. */
+ headRefName?: string | null;
isDraft?: boolean;
mergeable?: string | null;
mergeStateStatus?: string | null;
@@ -37,7 +41,7 @@ type GithubPullRequestPayload = {
};
const GITHUB_PULL_REQUEST_FIELDS =
- 'number,url,title,state,isDraft,mergeable,mergeStateStatus,mergedAt,reviewDecision,statusCheckRollup';
+ 'number,url,title,state,isDraft,mergeable,mergeStateStatus,mergedAt,reviewDecision,statusCheckRollup,headRefName';
const failureConclusions = new Set([
'action_required',
@@ -117,7 +121,15 @@ const normalizeGithubPullRequest = (pr: GithubPullRequestPayload): GitLinkedPull
};
};
-/** Current branch short name, or short SHA + `detached` for detached HEAD. */
+/**
+ * Current branch short name, or short SHA + `detached` for detached HEAD, plus the
+ * remote ref the branch publishes to.
+ *
+ * The branch itself stays a pure `.git/HEAD` read β€” this is the cheap leg, split
+ * from the `gh` lookup so the branch label can revalidate on every working-directory
+ * switch. Upstream resolution adds local git reads (never network, never `gh`) and
+ * only for an attached HEAD, so a detached checkout costs exactly what it did before.
+ */
export const getGitBranch = async (dirPath: string): Promise<GitBranchInfo> => {
try {
const gitDir = await resolveGitDir(dirPath);
@@ -125,7 +137,11 @@ export const getGitBranch = async (dirPath: string): Promise<GitBranchInfo> => {
const head = (await readFile(`${gitDir}/HEAD`, 'utf8')).trim();
const refMatch = /^ref:\s*refs\/heads\/(.+)$/.exec(head);
- if (refMatch) return { branch: refMatch[1] };
+ if (refMatch) {
+ const branch = refMatch[1];
+ const { upstream } = await resolveUpstream(dirPath, branch);
+ return { branch, ...(upstream ? { upstream } : {}) };
+ }
// Detached HEAD β€” HEAD file contains the full sha
if (/^[\da-f]{40}$/i.test(head)) return { branch: head.slice(0, 7), detached: true };
return {};
@@ -135,10 +151,71 @@ export const getGitBranch = async (dirPath: string): Promise<GitBranchInfo> => {
};
/**
- * Query `gh` CLI for a saved PR number when present; otherwise fall back to the
- * PR whose head branch matches `branch`, including merged/closed PRs so stale
- * topic snapshots can refresh lifecycle state after GitHub changes outside the
- * app. Returns `status: 'gh-missing'` when `gh` is unavailable / not authed.
+ * Ask GitHub which PR carries this exact commit. The last resort of the lookup
+ * chain: it needs no local trace of the push at all, so it is what recovers a PR
+ * on a fresh clone or a second device β€” and, with it, the remote branch name the
+ * commit was pushed under.
+ *
+ * `{owner}/{repo}` is substituted by `gh` from the working directory's remote.
+ * Returns only the PR number + head ref; the caller re-reads the PR through the
+ * normal `gh pr view` path so every result shares one shape.
+ */
+const findPullRequestByCommit = async (
+ dirPath: string,
+ sha: string,
+): Promise<{ headRefName?: string; number: number } | undefined> => {
+ try {
+ const { stdout } = await execFileAsync(
+ 'gh',
+ ['api', `repos/{owner}/{repo}/commits/${sha}/pulls`],
+ { cwd: dirPath, timeout: 8000 },
+ );
+ const parsed = JSON.parse(stdout.trim() || '[]') as {
+ head?: { ref?: string };
+ number?: number;
+ }[];
+ const [primary] = parsed;
+ if (!primary?.number) return undefined;
+
+ return { headRefName: primary.head?.ref, number: primary.number };
+ } catch (error: any) {
+ // A failing fallback must not turn "this branch has no PR" into an error: the
+ // `gh pr list` leg already proved `gh` is healthy by the time we get here.
+ log.debug('[findPullRequestByCommit] failed', { code: error?.code, sha });
+ return undefined;
+ }
+};
+
+/** Name the remote of a ref GitHub reported, where only the branch crosses the wire. */
+const toUpstreamRef = async (
+ dirPath: string,
+ branch: string | undefined | null,
+ fallback?: GitUpstreamRef,
+): Promise<GitUpstreamRef | undefined> => {
+ if (!branch) return fallback;
+ if (fallback?.branch === branch) return fallback;
+
+ const remote = fallback?.remote ?? (await getDefaultRemote(dirPath));
+ return remote ? { branch, remote } : fallback;
+};
+
+/**
+ * The PR linked to a branch, resolved cheapest-signal-first:
+ *
+ * 1. a saved PR number β†’ `gh pr view` (the strongest link once one is known);
+ * 2. the branch's REMOTE ref β†’ `gh pr list --head`, including merged/closed PRs so
+ * stale topic snapshots refresh lifecycle state after GitHub changes outside the app;
+ * 3. nothing found and no remote ref was ever established → `gh` commit→PR lookup.
+ *
+ * Step 2 is the fix for the bug this chain existed to have: the head passed to
+ * `gh` is the branch that exists ON THE REMOTE, not the local branch name. The two
+ * diverge routinely β€” a worktree generates its own local name, and a push with an
+ * explicit refspec (`git push origin local:remote`) renames the branch in flight β€”
+ * and querying the local name in that state returns an empty list forever, so the
+ * PR silently never links. Step 3 then covers the case where the local repo holds
+ * no trace of the push at all.
+ *
+ * Returns `status: 'gh-missing'` when `gh` is unavailable / not authed.
*/
export const getLinkedPullRequest = async (payload: {
branch: string;
@@ -148,15 +225,30 @@ export const getLinkedPullRequest = async (payload: {
const { path: dirPath, branch, pullRequestNumber } = payload;
if (!branch && pullRequestNumber === undefined) return { pullRequest: null, status: 'ok' };
+ const viewPullRequest = async (number: number): Promise<GithubPullRequestPayload> => {
+ const { stdout } = await execFileAsync(
+ 'gh',
+ ['pr', 'view', String(number), '--json', GITHUB_PULL_REQUEST_FIELDS],
+ { cwd: dirPath, timeout: 8000 },
+ );
+ return JSON.parse(stdout.trim() || '{}') as GithubPullRequestPayload;
+ };
+
try {
+ // Resolved for the NAMED branch rather than HEAD, so a caller holding a topic's
+ // persisted branch gets that branch's remote ref even if the directory moved on.
+ const { sha, upstream: localUpstream } = branch
+ ? await resolveUpstream(dirPath, branch)
+ : { sha: undefined, upstream: undefined };
+
if (pullRequestNumber !== undefined) {
- const { stdout } = await execFileAsync(
- 'gh',
- ['pr', 'view', String(pullRequestNumber), '--json', GITHUB_PULL_REQUEST_FIELDS],
- { cwd: dirPath, timeout: 8000 },
- );
- const parsed = JSON.parse(stdout.trim() || '{}') as GithubPullRequestPayload;
- return { pullRequest: normalizeGithubPullRequest(parsed), status: 'ok' };
+ const parsed = await viewPullRequest(pullRequestNumber);
+ const upstream = await toUpstreamRef(dirPath, parsed.headRefName, localUpstream);
+ return {
+ pullRequest: normalizeGithubPullRequest(parsed),
+ status: 'ok',
+ ...(upstream ? { upstream } : {}),
+ };
}
const { stdout } = await execFileAsync(
@@ -165,7 +257,7 @@ export const getLinkedPullRequest = async (payload: {
'pr',
'list',
'--head',
- branch,
+ localUpstream?.branch ?? branch,
'--state',
'all',
'--limit',
@@ -176,10 +268,39 @@ export const getLinkedPullRequest = async (payload: {
{ cwd: dirPath, timeout: 8000 },
);
const parsed = JSON.parse(stdout.trim() || '[]') as GithubPullRequestPayload[];
- if (parsed.length === 0) return { pullRequest: null, status: 'ok' };
- const [primaryRaw, ...rest] = parsed;
- const primary = normalizeGithubPullRequest(primaryRaw);
- return { extraCount: rest.length, pullRequest: primary, status: 'ok' };
+
+ if (parsed.length > 0) {
+ const [primaryRaw, ...rest] = parsed;
+ const upstream = await toUpstreamRef(dirPath, primaryRaw.headRefName, localUpstream);
+ return {
+ extraCount: rest.length,
+ pullRequest: normalizeGithubPullRequest(primaryRaw),
+ status: 'ok',
+ ...(upstream ? { upstream } : {}),
+ };
+ }
+
+ // Empty. With a resolved remote ref that is a real answer β€” the branch has no PR.
+ // Without one, the head we just queried was only the local NAME, a guess, so the
+ // empty list proves nothing: ask GitHub by commit instead β€” but only about a commit
+ // that is the branch's own work, never one it merely forked from.
+ if (!localUpstream && sha && (await isCommitSafeForPullRequestLookup(dirPath, sha))) {
+ const recovered = await findPullRequestByCommit(dirPath, sha);
+ if (recovered) {
+ const upstream = await toUpstreamRef(dirPath, recovered.headRefName);
+ return {
+ pullRequest: normalizeGithubPullRequest(await viewPullRequest(recovered.number)),
+ status: 'ok',
+ ...(upstream ? { upstream } : {}),
+ };
+ }
+ }
+
+ return {
+ pullRequest: null,
+ status: 'ok',
+ ...(localUpstream ? { upstream: localUpstream } : {}),
+ };
} catch (error: any) {
const code = error?.code;
const stderr: string = error?.stderr ?? '';
@@ -307,9 +428,9 @@ export const gitInfo = async (params: {
scope: string;
}): Promise<DeviceGitInfo> => {
const dirPath = params.scope;
- const { branch, detached } = await getGitBranch(dirPath);
+ const { branch, detached, upstream } = await getGitBranch(dirPath);
- let info: DeviceGitInfo['info'] = { branch, detached };
+ let info: DeviceGitInfo['info'] = { branch, detached, upstream };
if (branch && !detached && params.isGithub) {
const pr = await getLinkedPullRequest({ branch, path: dirPath });
info = {
@@ -318,6 +439,9 @@ export const gitInfo = async (params: {
extraCount: pr.extraCount,
ghMissing: pr.status === 'gh-missing',
pullRequest: pr.pullRequest,
+ // The PR's own head ref outranks the locally-inferred one, and is the only
+ // ref available at all when the push left no local trace.
+ upstream: pr.upstream ?? upstream,
};
}
diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.ts
index af484c83ebf..eddc932c6f5 100644
--- a/packages/local-file-shell/src/git/types.ts
+++ b/packages/local-file-shell/src/git/types.ts
@@ -1,7 +1,23 @@
+/**
+ * The remote ref a local branch publishes to. Stored instead of (not as well as)
+ * relying on the local branch name, which is a device-local label β€” a worktree's
+ * generated name or an explicit-refspec push makes it differ from the branch that
+ * actually exists on the remote, and only the remote ref means anything off this
+ * machine.
+ */
+export interface GitUpstreamRef {
+ /** Branch name ON the remote (`feat/x`), never the local name. */
+ branch: string;
+ /** Remote name (`origin`). */
+ remote: string;
+}
+
/** Branch short name (or short SHA when detached). */
export interface GitBranchInfo {
branch?: string;
detached?: boolean;
+ /** Remote ref the branch publishes to. Absent when unpushed or unresolvable. */
+ upstream?: GitUpstreamRef;
}
export type GitPullRequestCiStatus = 'failure' | 'pending' | 'success' | 'unknown';
@@ -28,6 +44,13 @@ export interface GitLinkedPullRequestResult {
pullRequest: GitLinkedPullRequest | null;
/** 'ok' β€” succeeded; 'gh-missing' β€” gh CLI unavailable / not authed; 'error' β€” other. */
status: GitLinkedPullRequestLookupStatus;
+ /**
+ * Remote ref the lookup actually queried under. Reported back so a caller can
+ * persist it β€” the PR's own head ref is the most authoritative answer available,
+ * and it is the only one that survives a commit→PR recovery on a machine with no
+ * local trace of the push.
+ */
+ upstream?: GitUpstreamRef;
}
export interface GitWorkingTreeStatus {
@@ -74,6 +97,7 @@ export interface DeviceGitInfo {
extraCount?: number;
ghMissing?: boolean;
pullRequest?: GitLinkedPullRequest | null;
+ upstream?: GitUpstreamRef;
};
workingStatus: GitWorkingTreeStatus;
}
diff --git a/packages/local-file-shell/src/git/upstream.ts b/packages/local-file-shell/src/git/upstream.ts
new file mode 100644
index 00000000000..d2844d7e949
--- /dev/null
+++ b/packages/local-file-shell/src/git/upstream.ts
@@ -0,0 +1,310 @@
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+
+import type { GitUpstreamRef } from './types';
+
+const execFileAsync = promisify(execFile);
+
+const GIT_TIMEOUT = 5000;
+
+/** Local-only git read. Every step of the resolver degrades to "unknown", never throws. */
+const runGit = async (args: string[], cwd: string): Promise<string | undefined> => {
+ try {
+ const { stdout } = await execFileAsync('git', args, { cwd, timeout: GIT_TIMEOUT });
+ return stdout;
+ } catch {
+ return undefined;
+ }
+};
+
+interface RemoteRefCandidate extends GitUpstreamRef {
+ /** Full refname (`refs/remotes/origin/feat/y`). */
+ ref: string;
+}
+
+const toUpstreamRef = ({ branch, remote }: RemoteRefCandidate): GitUpstreamRef => ({
+ branch,
+ remote,
+});
+
+/**
+ * `refs/remotes/origin/feat/x` β†’ `{ remote: 'origin', branch: 'feat/x' }`.
+ *
+ * The remote name is matched against the repo's real remote list rather than
+ * assumed to be the first path segment, because a remote may itself contain a
+ * slash. Longest name first so `origin/fork` wins over `origin` when both exist.
+ */
+const parseRemoteRef = (ref: string, remotes: string[]): RemoteRefCandidate | undefined => {
+ for (const remote of [...remotes].sort((a, b) => b.length - a.length)) {
+ const prefix = `refs/remotes/${remote}/`;
+ if (!ref.startsWith(prefix)) continue;
+
+ const branch = ref.slice(prefix.length);
+ // `refs/remotes/<remote>/HEAD` is the symbolic default-branch pointer, not a branch.
+ if (!branch || branch === 'HEAD') return undefined;
+ return { branch, ref, remote };
+ }
+};
+
+const listRemotes = async (dirPath: string): Promise<string[]> => {
+ const stdout = await runGit(['remote'], dirPath);
+ return (stdout ?? '')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+};
+
+/** The remote's default branch (`origin/canary`), or undefined when `origin/HEAD` is unset. */
+const getDefaultRemoteBranch = async (
+ dirPath: string,
+ remote: string,
+): Promise<string | undefined> => {
+ const stdout = await runGit(['symbolic-ref', '--short', `refs/remotes/${remote}/HEAD`], dirPath);
+ return stdout?.trim() || undefined;
+};
+
+interface LocalBranchRef {
+ /**
+ * `@{upstream}` β€” the branch's configured PULL source. Emphatically not a push
+ * target: `git checkout -b feat/x origin/canary` sets it to `origin/canary`, and
+ * it STAYS there after `feat/x` is pushed. Treated as a candidate, never a fact.
+ */
+ configured?: RemoteRefCandidate;
+ /** Commit the local branch points at. */
+ sha: string;
+}
+
+/**
+ * Read a local branch's commit + configured upstream in one shot. Scoped to the
+ * NAMED branch rather than HEAD, so a caller holding a topic's persisted branch
+ * resolves that branch's ref even when the working directory has moved on.
+ */
+const readLocalBranchRef = async (
+ dirPath: string,
+ branch: string,
+): Promise<LocalBranchRef | undefined> => {
+ const stdout = await runGit(
+ [
+ 'for-each-ref',
+ '--format=%(objectname)%09%(upstream:remotename)%09%(upstream)',
+ `refs/heads/${branch}`,
+ ],
+ dirPath,
+ );
+
+ const [sha, remote, upstreamRef] = (stdout?.split('\n')[0] ?? '').split('\t');
+ if (!sha) return undefined;
+
+ const prefix = `refs/remotes/${remote}/`;
+ if (remote && upstreamRef?.startsWith(prefix)) {
+ return {
+ configured: { branch: upstreamRef.slice(prefix.length), ref: upstreamRef, remote },
+ sha,
+ };
+ }
+ return { sha };
+};
+
+/**
+ * Remote branches whose tip is exactly `sha`. A push updates
+ * `refs/remotes/<remote>/<branch>` even without `-u`, so this recovers the remote
+ * branch for an explicit-refspec push (`git push origin local:remote`) with zero
+ * network and no `gh` dependency.
+ */
+const listRemoteRefsAt = async (dirPath: string, sha: string): Promise<string[]> => {
+ const stdout = await runGit(
+ ['for-each-ref', '--points-at', sha, '--format=%(refname)', 'refs/remotes'],
+ dirPath,
+ );
+ return (stdout ?? '')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+};
+
+/**
+ * Remote refs some local branch already claims as its upstream. Such a ref belongs
+ * to THAT branch β€” reaching this code means ours has no configured upstream at all.
+ */
+const listTrackedRemoteRefs = async (dirPath: string): Promise<Set<string>> => {
+ const stdout = await runGit(['for-each-ref', '--format=%(upstream)', 'refs/heads'], dirPath);
+ return new Set(
+ (stdout ?? '')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean),
+ );
+};
+
+/**
+ * Whether THIS repository is what put the commit on that remote ref.
+ *
+ * Git records the provenance in the remote-tracking ref's reflog: a push writes
+ * `update by push`, while a ref that merely arrived by fetch or clone has no reflog
+ * at all. That distinction is the whole game here β€” see {@link inferUpstreamFromSha}.
+ */
+const wasPushedFromHere = async (dirPath: string, ref: string): Promise<boolean> => {
+ const stdout = await runGit(['reflog', 'show', ref], dirPath);
+ return !!stdout?.includes('update by push');
+};
+
+/**
+ * Does remote ref `candidate` hold THIS branch's published work?
+ *
+ * The question git cannot answer directly, and the crux of this module. Two refs can
+ * both look plausible for a branch β€” the one it forked from and the one it was pushed
+ * to β€” and picking the wrong one binds the topic to another branch's PR. So a
+ * candidate has to earn it, one of two ways:
+ *
+ * 1. It carries the branch's own name. Unambiguous, and covers nearly every branch.
+ * 2. Failing that, git must attest that THIS repo put the commit there β€” a push
+ * writes `update by push` into the remote-tracking ref's reflog, while a ref that
+ * arrived by fetch or clone has no reflog at all. That alone still is not enough:
+ * a ref another local branch already tracks is that branch's, and a remote's
+ * default branch is a fork base, never a feature branch's publication.
+ */
+const isPublicationOfBranch = (
+ candidate: RemoteRefCandidate,
+ branch: string,
+ ownership: { defaultRefs: Set<string>; pushed: Set<string>; tracked: Set<string> },
+): boolean => {
+ if (candidate.branch === branch) return true;
+
+ return (
+ ownership.pushed.has(candidate.ref) &&
+ !ownership.tracked.has(candidate.ref) &&
+ !ownership.defaultRefs.has(`${candidate.remote}/${candidate.branch}`)
+ );
+};
+
+export interface ResolvedUpstream {
+ /** Commit the local branch points at — the key for a `gh` commit→PR lookup. */
+ sha?: string;
+ /** Remote ref the branch publishes to, when one could be established locally. */
+ upstream?: GitUpstreamRef;
+}
+
+/**
+ * Resolve the remote ref a local branch publishes to, from local git state alone.
+ *
+ * Two sources offer a candidate β€” the configured `@{upstream}`, and any remote-tracking
+ * ref sitting on the branch's commit (a push moves one of those even without `-u`,
+ * which is what an explicit refspec always does). NEITHER is trusted on its face:
+ *
+ * - `@{upstream}` is a PULL source. `git checkout -b feat/x origin/canary` sets it to
+ * `origin/canary` and leaves it there even after `feat/x` is pushed, so taking it at
+ * face value would hunt for a PR whose head is `canary`.
+ * - A SHA match is not proof of a push either: a branch with no commits of its own
+ * still sits on the commit it forked from, so the base branch's ref matches too.
+ *
+ * Both are therefore put through {@link isPublicationOfBranch}, and anything that
+ * cannot earn it is dropped. Ambiguity records nothing rather than guess, because the
+ * local branch NAME is never a stand-in for a remote ref β€” it is a device-local label,
+ * and passing it off as one is the exact bug this resolver exists to kill. A caller
+ * left with nothing still has {@link ResolvedUpstream.sha}, the handle for asking
+ * GitHub directly.
+ */
+export const resolveUpstream = async (
+ dirPath: string,
+ branch: string,
+): Promise<ResolvedUpstream> => {
+ const local = await readLocalBranchRef(dirPath, branch);
+ if (!local) return {};
+
+ // The overwhelmingly common shape (`git push -u`, same name both ends). Settled
+ // without a single extra git call β€” the ownership probes below are never paid for.
+ if (local.configured?.branch === branch) {
+ return { sha: local.sha, upstream: toUpstreamRef(local.configured) };
+ }
+
+ const remotes = await listRemotes(dirPath);
+ if (remotes.length === 0) return { sha: local.sha };
+
+ const atSha = (await listRemoteRefsAt(dirPath, local.sha))
+ .map((ref) => parseRemoteRef(ref, remotes))
+ .filter((candidate): candidate is RemoteRefCandidate => !!candidate);
+
+ const candidates = [...(local.configured ? [local.configured] : []), ...atSha].filter(
+ (candidate, index, all) => all.findIndex((other) => other.ref === candidate.ref) === index,
+ );
+ if (candidates.length === 0) return { sha: local.sha };
+
+ const [tracked, defaults, pushed] = await Promise.all([
+ listTrackedRemoteRefs(dirPath),
+ Promise.all(
+ [...new Set(candidates.map((candidate) => candidate.remote))].map((remote) =>
+ getDefaultRemoteBranch(dirPath, remote),
+ ),
+ ),
+ Promise.all(
+ candidates.map(async (candidate) =>
+ (await wasPushedFromHere(dirPath, candidate.ref)) ? candidate.ref : undefined,
+ ),
+ ),
+ ]);
+
+ const ownership = {
+ defaultRefs: new Set(defaults.filter((ref): ref is string => !!ref)),
+ pushed: new Set(pushed.filter((ref): ref is string => !!ref)),
+ // A branch's own configured upstream is not "another branch's" β€” exempt it.
+ tracked: new Set([...tracked].filter((ref) => ref !== local.configured?.ref)),
+ };
+
+ const owned = candidates.filter((candidate) =>
+ isPublicationOfBranch(candidate, branch, ownership),
+ );
+
+ return { sha: local.sha, upstream: owned.length === 1 ? toUpstreamRef(owned[0]) : undefined };
+};
+
+/**
+ * The remote `gh` resolves `{owner}/{repo}` against β€” `origin` when present, else
+ * the first configured remote. Used to name the remote of a ref recovered from
+ * GitHub, where only the branch name comes back over the wire.
+ */
+export const getDefaultRemote = async (dirPath: string): Promise<string | undefined> => {
+ const remotes = await listRemotes(dirPath);
+ if (remotes.includes('origin')) return 'origin';
+ return remotes[0];
+};
+
+/** Exit-status-only probe β€” `runGit` cannot tell success-with-no-output from failure. */
+const gitSucceeds = async (args: string[], cwd: string): Promise<boolean> => {
+ try {
+ await execFileAsync('git', args, { cwd, timeout: GIT_TIMEOUT });
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * May GitHub be asked which PR carries this commit?
+ *
+ * Only for a commit that is the branch's OWN work. GitHub's
+ * `/commits/{sha}/pulls` answers "which PR introduced this commit", so for a commit
+ * already contained in the default branch it hands back the PR that merged it β€” a
+ * stranger's. And a branch carrying no commits of its own still points at the commit
+ * it forked from, which is exactly such a commit: asking about it would staple an
+ * unrelated merged PR onto a brand-new topic.
+ *
+ * Answers `false` whenever that cannot be ruled out β€” including when the default
+ * branch is unknown (`refs/remotes/<remote>/HEAD` is only written by `git clone`).
+ * The cost of a false negative is the status quo, no PR link; the cost of a false
+ * positive is a topic showing someone else's PR.
+ */
+export const isCommitSafeForPullRequestLookup = async (
+ dirPath: string,
+ sha: string,
+): Promise<boolean> => {
+ const remote = await getDefaultRemote(dirPath);
+ if (!remote) return false;
+
+ const defaultBranch = await getDefaultRemoteBranch(dirPath, remote);
+ if (!defaultBranch) return false;
+
+ return !(await gitSucceeds(
+ ['merge-base', '--is-ancestor', sha, `refs/remotes/${defaultBranch}`],
+ dirPath,
+ ));
+};
diff --git a/packages/types/src/device.test.ts b/packages/types/src/device.test.ts
index df002145bfc..c45259385b9 100644
--- a/packages/types/src/device.test.ts
+++ b/packages/types/src/device.test.ts
@@ -1,8 +1,21 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, expectTypeOf, it } from 'vitest';
+import type { z } from 'zod';
+import type { WorkingDirConfig } from './device';
import { workingDirConfigSchema } from './device';
describe('workingDirConfigSchema', () => {
+ /**
+ * `WorkingDirConfig` is declared twice β€” once as the interface everything is typed
+ * against, once as the zod schema the TRPC routes validate through. Zod STRIPS what
+ * it does not declare, so a field added to only the interface type-checks perfectly
+ * and is then silently dropped on every write. This pins the two together, and fails
+ * to compile the moment they drift.
+ */
+ it('stays structurally identical to the WorkingDirConfig interface', () => {
+ expectTypeOf<z.infer<typeof workingDirConfigSchema>>().toEqualTypeOf<WorkingDirConfig>();
+ });
+
it('preserves GitHub PR metadata under git.github', () => {
const value = {
git: {
@@ -32,4 +45,20 @@ describe('workingDirConfigSchema', () => {
expect(workingDirConfigSchema.parse(value)).toEqual(value);
});
+
+ // The remote ref is the whole point of recording git state that outlives this
+ // machine β€” and zod STRIPS what it does not declare, so a field missing from the
+ // schema is not just unvalidated, it never survives a write at all.
+ it('preserves the upstream remote ref under git.upstream', () => {
+ const value = {
+ git: {
+ branch: 'worktree-feat+claude-code-session-import',
+ upstream: { branch: 'feat/hetero-session-import-ui', remote: 'origin' },
+ },
+ path: '/repo',
+ repoType: 'github',
+ };
+
+ expect(workingDirConfigSchema.parse(value)).toEqual(value);
+ });
});
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index 60032572d59..18d45221b2c 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -95,6 +95,23 @@ export interface WorkingDirGithubState {
pullRequestStatus?: DeviceGitLinkedPullRequestLookupStatus;
}
+/**
+ * The remote ref a local branch publishes to.
+ *
+ * Recorded because the local branch name is a DEVICE-LOCAL label: a worktree
+ * generates its own (`worktree-feat+foo`), and a push with an explicit refspec
+ * (`git push origin local:remote`) renames the branch in flight. Carrying the
+ * local name to another machine β€” or to `gh pr list --head` β€” yields nothing.
+ * The remote ref is the only branch identity that survives leaving this machine,
+ * which also makes it the handle for re-fetching the topic's output elsewhere.
+ */
+export interface DeviceGitUpstreamRef {
+ /** Branch name ON the remote (`feat/x`), never the local name. */
+ branch: string;
+ /** Remote name (`origin`). */
+ remote: string;
+}
+
export interface WorkingDirGitState {
/**
* Active checkout selected under this git source. When absent, the source
@@ -115,6 +132,12 @@ export interface WorkingDirGitState {
* the source path itself.
*/
isWorktree?: boolean;
+ /**
+ * Remote ref {@link branch} publishes to. Dropped alongside {@link github}
+ * whenever the branch changes β€” a stale remote ref would bind the topic to
+ * another branch's PR, which is worse than having none.
+ */
+ upstream?: DeviceGitUpstreamRef;
}
export interface WorkingDirConfig {
@@ -305,6 +328,8 @@ export interface DeviceGitBranchInfo {
branch?: string;
/** True when HEAD is detached (no branch ref). */
detached?: boolean;
+ /** Remote ref the branch publishes to. Absent when unpushed or unresolvable. */
+ upstream?: DeviceGitUpstreamRef;
}
/**
@@ -318,6 +343,8 @@ export interface DeviceGitLinkedPullRequestResult {
pullRequest: DeviceGitLinkedPullRequest | null;
/** 'ok' β€” lookup succeeded; 'gh-missing' β€” gh CLI unavailable; 'error' β€” other failure. */
status: DeviceGitLinkedPullRequestLookupStatus;
+ /** Remote ref the lookup queried under β€” the PR's own head ref when one was found. */
+ upstream?: DeviceGitUpstreamRef;
}
/**
@@ -664,6 +691,14 @@ export const workingDirConfigSchema = z.object({
})
.optional(),
isWorktree: z.boolean().optional(),
+ // Mirrors `WorkingDirGitState.upstream`. A field missing here is not merely
+ // unvalidated β€” zod strips it, so it would never survive a write.
+ upstream: z
+ .object({
+ branch: z.string(),
+ remote: z.string(),
+ })
+ .optional(),
})
.optional(),
path: z.string(),
diff --git a/src/services/git.ts b/src/services/git.ts
index 712ec63596b..30ea5a70fe9 100644
--- a/src/services/git.ts
+++ b/src/services/git.ts
@@ -16,6 +16,7 @@ import type {
DeviceGitRemoveWorktreeResult,
DeviceGitRenameBranchResult,
DeviceGitSyncResult,
+ DeviceGitUpstreamRef,
DeviceGitWorkingTreeStatus,
DeviceGitWorktreeListItem,
} from '@lobechat/types';
@@ -27,6 +28,7 @@ import { electronGitService } from '@/services/electron/git';
export interface GitBranchSummary {
branch?: string;
detached?: boolean;
+ upstream?: DeviceGitUpstreamRef;
}
/** Linked-PR summary for a branch β€” the result of the expensive `gh` leg. */
@@ -35,6 +37,7 @@ export interface GitLinkedPRSummary {
ghMissing?: boolean;
pullRequest?: DeviceGitLinkedPullRequest | null;
pullRequestStatus?: DeviceGitLinkedPullRequestLookupStatus;
+ upstream?: DeviceGitUpstreamRef;
}
/**
@@ -186,14 +189,18 @@ class GitService {
const info = deviceId
? await lambdaClient.device.gitBranch.query({ deviceId, path })
: await electronGitService.getGitBranch(path);
- return { branch: info?.branch, detached: info?.detached };
+ return { branch: info?.branch, detached: info?.detached, upstream: info?.upstream };
}
/**
- * PR linked to `branch` on a GitHub repo. Shells out to `gh pr list` (8s
- * timeout), so callers throttle this far more aggressively than the branch
- * read. Includes merged/closed PRs so persisted snapshots can refresh after
- * GitHub changes outside the app.
+ * PR linked to `branch` on a GitHub repo. Shells out to `gh` (8s timeout), so
+ * callers throttle this far more aggressively than the branch read. Includes
+ * merged/closed PRs so persisted snapshots can refresh after GitHub changes
+ * outside the app.
+ *
+ * `branch` is the LOCAL branch; the device resolves the remote ref it publishes
+ * to and queries GitHub under that, falling back to a commit→PR lookup. It
+ * reports the ref it landed on as `upstream` β€” persist that, not the local name.
*/
async getLinkedPullRequest({
branch,
@@ -220,6 +227,7 @@ class GitService {
ghMissing: pr.status === 'gh-missing',
pullRequest: pr.pullRequest,
pullRequestStatus: pr.status,
+ upstream: pr.upstream,
};
}
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
index 0b2f1398b67..6d0a4012c75 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts
@@ -92,6 +92,9 @@ export const snapshotTopicWorkingDirGit = async (
currentConfig,
github,
path,
+ // The PR lookup's ref outranks the branch read's: it carries the PR's own head
+ // ref, and it is the only one that lands when the push left no local trace.
+ upstream: prData?.upstream ?? branchInfo?.upstream,
});
if (isEqual(currentConfig, nextConfig)) return;
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 88311d9012c..15ccf55c718 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -1410,6 +1410,7 @@ export class ChatTopicActionImpl {
currentConfig: base.currentConfig,
github,
path: base.path,
+ upstream: prData?.upstream,
});
if (isEqual(base.currentConfig, nextConfig)) return;
diff --git a/src/store/chat/utils/topicWorkingDirGit.ts b/src/store/chat/utils/topicWorkingDirGit.ts
index e000f2bd568..12b264112a7 100644
--- a/src/store/chat/utils/topicWorkingDirGit.ts
+++ b/src/store/chat/utils/topicWorkingDirGit.ts
@@ -1,5 +1,10 @@
import { isDesktop } from '@lobechat/const';
-import type { ChatTopicMetadata, WorkingDirConfig, WorkingDirGithubState } from '@lobechat/types';
+import type {
+ ChatTopicMetadata,
+ DeviceGitUpstreamRef,
+ WorkingDirConfig,
+ WorkingDirGithubState,
+} from '@lobechat/types';
import { getWorkingDirEffectivePath } from '@lobechat/types';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
@@ -82,11 +87,13 @@ export const mergeWorkingDirGithubState = ({
currentConfig,
github,
path,
+ upstream,
}: {
branch: string;
currentConfig?: WorkingDirConfig;
github: WorkingDirGithubState;
path: string;
+ upstream?: DeviceGitUpstreamRef;
}): WorkingDirConfig => {
const source = currentConfig?.path ?? path;
const isWorktree = source !== path;
@@ -101,6 +108,12 @@ export const mergeWorkingDirGithubState = ({
if (isWorktree) git.activeWorktree = path;
else delete git.activeWorktree;
+ // A probe that resolved no remote ref means the branch is unpushed or its trace is
+ // gone β€” not that a previously recorded ref is wrong. Keep the old one rather than
+ // erase the topic's only cross-device handle on a transient miss; the writers that
+ // know the branch MOVED (switch / worktree / push-to-a-new-ref) clear it explicitly.
+ if (upstream) git.upstream = upstream;
+
return {
...currentConfig,
git,
diff --git a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts
index f7a45000373..c24ba40d01d 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts
@@ -830,3 +830,256 @@ describe('recordWorktreeExit', () => {
expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
});
});
+
+describe('recordGitCommandEffects β€” git push', () => {
+ /** The topic from the reported case: a worktree branch that never existed on the remote. */
+ const WORKTREE_TOPIC = {
+ metadata: {
+ workingDirectoryConfig: {
+ git: { branch: 'worktree-feat+claude-code-session-import' },
+ path: '/repo',
+ repoType: 'github',
+ },
+ },
+ };
+
+ const pushOutput = (table: string) =>
+ ['Enumerating objects: 5, done.', 'To github.com:lobehub/lobehub.git', table].join('\n');
+
+ const upstreamOf = () =>
+ chatMocks.updateTopicMetadata.mock.calls.at(-1)?.[1].workingDirectoryConfig.git.upstream;
+
+ // The exact push that broke PR linkage: an explicit refspec renames the branch in
+ // flight and sets no upstream, so only the push's own output states the mapping.
+ it('records the remote branch an explicit-refspec push landed on', async () => {
+ chatMocks.topics = { t1: WORKTREE_TOPIC };
+
+ await recordGitCommandEffects({
+ command:
+ 'git push origin worktree-feat+claude-code-session-import:feat/hetero-session-import-ui --force',
+ resultContent: pushOutput(
+ ' + 031bf96...f6b1c2a worktree-feat+claude-code-session-import -> feat/hetero-session-import-ui (forced update)',
+ ),
+ topicId: 't1',
+ });
+
+ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {
+ workingDirectoryConfig: {
+ git: {
+ branch: 'worktree-feat+claude-code-session-import',
+ upstream: { branch: 'feat/hetero-session-import-ui', remote: 'origin' },
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ });
+ });
+
+ it('resolves a HEAD refspec against the topic branch', async () => {
+ chatMocks.topics = { t1: WORKTREE_TOPIC };
+
+ await recordGitCommandEffects({
+ command: 'git push -u origin HEAD',
+ resultContent: pushOutput(
+ ' * [new branch] HEAD -> worktree-feat+claude-code-session-import',
+ ),
+ topicId: 't1',
+ });
+
+ expect(upstreamOf()).toEqual({
+ branch: 'worktree-feat+claude-code-session-import',
+ remote: 'origin',
+ });
+ });
+
+ it('reads a bare push, whose mapping only appears as a SHA range', async () => {
+ chatMocks.topics = { t1: WORKTREE_TOPIC };
+
+ await recordGitCommandEffects({
+ command: 'git push',
+ resultContent: pushOutput(
+ ' 031bf96..f6b1c2a worktree-feat+claude-code-session-import -> feat/hetero-session-import-ui',
+ ),
+ topicId: 't1',
+ });
+
+ expect(upstreamOf()).toEqual({
+ branch: 'feat/hetero-session-import-ui',
+ remote: 'origin',
+ });
+ });
+
+ it('names the remote from the command rather than assuming origin', async () => {
+ chatMocks.topics = { t1: WORKTREE_TOPIC };
+
+ await recordGitCommandEffects({
+ command: 'git push -o ci.skip fork worktree-feat+claude-code-session-import:feat/y',
+ resultContent: pushOutput(
+ ' * [new branch] worktree-feat+claude-code-session-import -> feat/y',
+ ),
+ topicId: 't1',
+ });
+
+ expect(upstreamOf()).toEqual({ branch: 'feat/y', remote: 'fork' });
+ });
+
+ it('ignores a rejected push', async () => {
+ chatMocks.topics = { t1: WORKTREE_TOPIC };
+
+ await recordGitCommandEffects({
+ command: 'git push origin worktree-feat+claude-code-session-import:feat/y',
+ resultContent: pushOutput(
+ ' ! [rejected] worktree-feat+claude-code-session-import -> feat/y (fetch first)',
+ ),
+ topicId: 't1',
+ });
+
+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('ignores tag and branch-deletion lines', async () => {
+ chatMocks.topics = { t1: WORKTREE_TOPIC };
+
+ await recordGitCommandEffects({
+ command: 'git push origin --tags',
+ resultContent: pushOutput(' * [new tag] v1.2.3 -> v1.2.3'),
+ topicId: 't1',
+ });
+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
+
+ await recordGitCommandEffects({
+ command: 'git push origin :feat/y',
+ resultContent: pushOutput(' - [deleted] (none) -> feat/y'),
+ topicId: 't1',
+ });
+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('records nothing from a multi-ref push that never names the topic branch', async () => {
+ chatMocks.topics = { t1: WORKTREE_TOPIC };
+
+ await recordGitCommandEffects({
+ command: 'git push origin feat/a feat/b',
+ resultContent: pushOutput(
+ [' * [new branch] feat/a -> feat/a', ' * [new branch] feat/b -> feat/b'].join(
+ '\n',
+ ),
+ ),
+ topicId: 't1',
+ });
+
+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ it('never mistakes prose in the output for a push mapping', async () => {
+ chatMocks.topics = { t1: WORKTREE_TOPIC };
+
+ await recordGitCommandEffects({
+ command: 'git push origin worktree-feat+claude-code-session-import:feat/y',
+ resultContent: 'renaming worktree-feat+claude-code-session-import -> feat/y in the docs',
+ topicId: 't1',
+ });
+
+ expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ // Re-pointing the branch at a new remote ref orphans the PR bound to the old one.
+ it('drops the linked PR when the branch is re-pushed to a different remote ref', async () => {
+ chatMocks.topics = {
+ t1: {
+ metadata: {
+ workingDirectoryConfig: {
+ git: {
+ branch: 'worktree-feat+x',
+ github: {
+ pullRequest: {
+ number: 1,
+ state: 'OPEN',
+ title: 'old',
+ url: 'https://github.com/lobehub/lobehub/pull/1',
+ },
+ pullRequestStatus: 'ok',
+ },
+ upstream: { branch: 'feat/old', remote: 'origin' },
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ },
+ },
+ };
+
+ await recordGitCommandEffects({
+ command: 'git push origin worktree-feat+x:feat/new',
+ resultContent: pushOutput(' * [new branch] worktree-feat+x -> feat/new'),
+ topicId: 't1',
+ });
+
+ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {
+ workingDirectoryConfig: {
+ git: {
+ branch: 'worktree-feat+x',
+ upstream: { branch: 'feat/new', remote: 'origin' },
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ });
+ });
+
+ // `gh pr create` then `git push` in one run must not erase the PR it just recorded.
+ it('keeps a freshly created PR on the first push to that ref', async () => {
+ const pullRequest = {
+ number: 17_101,
+ state: 'OPEN',
+ title: 'feat: import sessions',
+ url: 'https://github.com/lobehub/lobehub/pull/17101',
+ };
+ chatMocks.topics = {
+ t1: {
+ metadata: {
+ workingDirectoryConfig: {
+ git: {
+ branch: 'worktree-feat+x',
+ github: { pullRequest, pullRequestStatus: 'ok' },
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ },
+ },
+ };
+
+ await recordGitCommandEffects({
+ command: 'git push origin worktree-feat+x:feat/y',
+ resultContent: pushOutput(' * [new branch] worktree-feat+x -> feat/y'),
+ topicId: 't1',
+ });
+
+ expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {
+ workingDirectoryConfig: {
+ git: {
+ branch: 'worktree-feat+x',
+ github: { pullRequest, pullRequestStatus: 'ok' },
+ upstream: { branch: 'feat/y', remote: 'origin' },
+ },
+ path: '/repo',
+ repoType: 'github',
+ },
+ });
+ });
+
+ it('refreshes the branch cache, which now carries the remote ref', async () => {
+ chatMocks.topics = { t1: WORKTREE_TOPIC };
+
+ await recordGitCommandEffects({
+ command: 'git push origin worktree-feat+claude-code-session-import:feat/y',
+ resultContent: pushOutput(
+ ' * [new branch] worktree-feat+claude-code-session-import -> feat/y',
+ ),
+ topicId: 't1',
+ });
+
+ expect(swrMocks.mutate).toHaveBeenCalledWith(['device:gitBranch', 'local', '/repo']);
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.ts
index d4f106d2c15..f7f77291a07 100644
--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts
+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts
@@ -1,5 +1,9 @@
import { isDesktop } from '@lobechat/const';
-import type { DeviceGitLinkedPullRequest, WorkingDirConfig } from '@lobechat/types';
+import type {
+ DeviceGitLinkedPullRequest,
+ DeviceGitUpstreamRef,
+ WorkingDirConfig,
+} from '@lobechat/types';
import { getWorkingDirSourcePath } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
@@ -412,6 +416,126 @@ const parseGhPrCreate = (
): PullRequestCreateInfo | undefined =>
findInCommand(command, (tokens, env) => parseGhPrCreateTokens(tokens, resultContent, env));
+/**
+ * One ref a `git push` moved, as the push itself reported it.
+ * `local` is the ref that was pushed (a branch name, or `HEAD`); `remote` the
+ * branch it landed on.
+ */
+interface PushRefMapping {
+ local: string;
+ remote: string;
+}
+
+/** `git push` options that consume the following token as their value. */
+const GIT_PUSH_VALUE_FLAGS = new Set(['--exec', '--push-option', '--receive-pack', '--repo', '-o']);
+
+/**
+ * A ref line from `git push`'s status table:
+ *
+ * ```
+ * * [new branch] worktree-feat+x -> feat/y
+ * + 031bf96...f6b1c2a worktree-feat+x -> feat/y (forced update)
+ * 031bf96..f6b1c2a worktree-feat+x -> feat/y
+ * ```
+ *
+ * Anchored to that exact shape (flag, then a bracketed status or a SHA range, then
+ * the mapping) so prose in a compound command's output β€” `git commit && git push`,
+ * a diff, a log line β€” can never be mistaken for a push result.
+ */
+const PUSH_REF_LINE =
+ /^\s*(?:\S\s+)?(\[[^\]]*\]|[\da-f]{4,40}\.{2,3}[\da-f]{4,40})\s+(\S+)\s+->\s+(\S+)(?:\s+\(.*\))?\s*$/i;
+
+/**
+ * Bracketed statuses that mean a branch is now published at the mapped ref. A SHA
+ * range says the same. Everything else β€” `[rejected]`, `[remote rejected]`,
+ * `[deleted]`, `[new tag]`, `[tag update]` β€” either failed or is not a branch, and
+ * an allowlist keeps a future git status from being silently read as a success.
+ */
+const PUSH_SUCCESS_STATUS = /^\[(?:new branch|new reference|up to date)\]$/i;
+
+const REMOTE_URL_PATTERN = /^\w[\w+.-]*:\/\/|^[^\s/][^\s/@]*@[^\s/]+:/;
+
+/** A `git push <target>` positional that is a URL, not a named remote β€” unnameable. */
+const isRemoteUrl = (value: string): boolean =>
+ REMOTE_URL_PATTERN.test(value) || value.startsWith('/') || value.startsWith('.');
+
+/**
+ * `git push` mappings, read out of the command's own output. This is the ONE place
+ * the local→remote mapping is stated for every push form — bare `git push`, `push -u
+ * origin HEAD`, and `push origin local:remote` alike. Parsing the command instead
+ * would only ever cover the explicit-refspec form.
+ */
+const parsePushRefMappings = (content?: string): PushRefMapping[] => {
+ if (!content) return [];
+
+ const mappings: PushRefMapping[] = [];
+ for (const line of content.split('\n')) {
+ const match = PUSH_REF_LINE.exec(line);
+ if (!match) continue;
+
+ const [, status, local, remote] = match;
+ if (status.startsWith('[') && !PUSH_SUCCESS_STATUS.test(status)) continue;
+ // `(none) -> x` is a branch deletion; a tag ref is not a branch.
+ if (local === '(none)' || local.startsWith('refs/tags/') || remote.startsWith('refs/tags/'))
+ continue;
+
+ mappings.push({ local, remote: remote.replace(/^refs\/heads\//, '') });
+ }
+ return mappings;
+};
+
+const parseGitPushTokens = (tokens: string[], env?: ShellEnv): { remote?: string } | undefined => {
+ const git = parseGitSubcommand(tokens);
+ if (!git || git.subcommand !== 'push') return undefined;
+
+ for (let i = 0; i < git.args.length; i += 1) {
+ const token = git.args[i];
+
+ const optionValue = getOptionValue(git.args, i, [...GIT_PUSH_VALUE_FLAGS], env);
+ if (optionValue.skipNext) {
+ i += 1;
+ continue;
+ }
+ if (optionValue.value !== undefined) continue;
+ if (token.startsWith('-')) continue;
+
+ // First positional is the push target. A URL target has no name we could record.
+ const target = resolveToken(token, env);
+ if (!target) continue;
+ return isRemoteUrl(target) ? {} : { remote: target };
+ }
+
+ // Bare `git push` β€” the remote is whatever the branch tracks, conventionally origin.
+ return {};
+};
+
+/**
+ * The remote ref a successful `git push` published the topic's branch to.
+ *
+ * Fails closed on ambiguity: when the branch is known, a mapping must name it (or
+ * `HEAD`), and a multi-ref push that leaves more than one candidate records nothing
+ * rather than pick.
+ */
+const parseGitPush = (
+ command: string | string[],
+ resultContent?: string,
+ branch?: string,
+): DeviceGitUpstreamRef | undefined => {
+ const push = findInCommand(command, parseGitPushTokens);
+ if (!push) return undefined;
+
+ const mappings = parsePushRefMappings(resultContent);
+ const candidates = branch
+ ? mappings.filter((mapping) => mapping.local === branch || mapping.local === 'HEAD')
+ : mappings;
+ if (candidates.length !== 1) return undefined;
+
+ const remoteBranch = normalizeBranch(candidates[0].remote);
+ if (!remoteBranch) return undefined;
+
+ return { branch: remoteBranch, remote: push.remote ?? 'origin' };
+};
+
const applyBranchToConfig = (
currentConfig: WorkingDirConfig | undefined,
source: string,
@@ -424,7 +548,12 @@ const applyBranchToConfig = (
};
delete git.detached;
- if (branchChanged) delete git.github;
+ // The old branch's remote ref and PR describe a branch the topic has left. Held
+ // onto, `upstream` would aim the PR lookup at the wrong head β€” worse than none.
+ if (branchChanged) {
+ delete git.github;
+ delete git.upstream;
+ }
return {
...currentConfig,
@@ -445,6 +574,7 @@ const applyDetachedToConfig = (
delete git.branch;
delete git.github;
+ delete git.upstream;
return {
...currentConfig,
@@ -479,6 +609,35 @@ const applyPullRequestToConfig = (
};
};
+/**
+ * Record where the branch now publishes to. This is what makes the PR lookup work at
+ * all for a worktree: its local branch name (`worktree-feat+x`) never exists on the
+ * remote, so only the ref the push actually created (`feat/y`) can find the PR.
+ */
+const applyPushToConfig = (
+ currentConfig: WorkingDirConfig | undefined,
+ source: string,
+ upstream: DeviceGitUpstreamRef,
+): WorkingDirConfig => {
+ const previous = currentConfig?.git?.upstream?.branch;
+ const git: NonNullable<WorkingDirConfig['git']> = {
+ ...currentConfig?.git,
+ upstream,
+ };
+
+ // Re-pointing the branch at a DIFFERENT remote ref orphans the PR bound to the old
+ // one. Only a change invalidates it β€” a first push must not drop a PR that a
+ // preceding `gh pr create` in the same run just recorded.
+ if (previous && previous !== upstream.branch) delete git.github;
+
+ return {
+ ...currentConfig,
+ git,
+ path: source,
+ ...(currentConfig?.repoType ? { repoType: currentConfig.repoType } : {}),
+ };
+};
+
const applyWorktreeAddToConfig = (
currentConfig: WorkingDirConfig | undefined,
source: string,
@@ -493,7 +652,10 @@ const applyWorktreeAddToConfig = (
};
if (info.branch) delete git.detached;
- if (branchChanged) delete git.github;
+ if (branchChanged) {
+ delete git.github;
+ delete git.upstream;
+ }
return {
...currentConfig,
@@ -504,10 +666,11 @@ const applyWorktreeAddToConfig = (
};
/**
- * The session left the worktree and is back in the source repo. `branch` and the
- * linked `github` PR described the worktree's branch, not the source repo's, so they
- * are dropped rather than left pointing at a branch the topic is no longer on β€” the
- * source branch is unknown until the next `git switch` / `checkout` refreshes it.
+ * The session left the worktree and is back in the source repo. `branch`, its
+ * `upstream` ref and the linked `github` PR described the worktree's branch, not the
+ * source repo's, so they are dropped rather than left pointing at a branch the topic
+ * is no longer on β€” the source branch is unknown until the next `git switch` /
+ * `checkout` refreshes it.
*/
const applyWorktreeExitToConfig = (
currentConfig: WorkingDirConfig | undefined,
@@ -522,6 +685,7 @@ const applyWorktreeExitToConfig = (
if (currentConfig?.git?.isWorktree) {
delete git.branch;
delete git.github;
+ delete git.upstream;
}
return {
@@ -838,6 +1002,7 @@ export const recordWorktreeAdd = async (params: {
* Record successful heterogeneous CLI shell side effects onto the run topic:
* - `git worktree add` selects the created worktree and explicit branch.
* - `git switch` / confirmed `git checkout` updates the branch snapshot.
+ * - `git push` records the remote ref the branch publishes to.
* - `gh pr create` binds the created PR URL to the topic.
*/
export const recordGitCommandEffects = async (params: {
@@ -872,6 +1037,13 @@ export const recordGitCommandEffects = async (params: {
: applyBranchToConfig(nextConfig, source, branchSwitch.branch);
}
+ // After the branch switch, so a `git switch -c x && git push` chain matches the
+ // push against the branch it actually pushed rather than the one it left.
+ const pushUpstream = parseGitPush(command, resultContent, nextConfig?.git?.branch);
+ if (pushUpstream) {
+ nextConfig = applyPushToConfig(nextConfig, source, pushUpstream);
+ }
+
const prCreate = parseGhPrCreate(command, resultContent);
if (prCreate) {
nextConfig = applyPullRequestToConfig(nextConfig, source, prCreate);
@@ -884,8 +1056,9 @@ export const recordGitCommandEffects = async (params: {
// A checkout performed inside the heterogeneous CLI bypasses ChatInput's
// BranchSwitcher, which normally refreshes this cache itself. Revalidate the
// shared branch key so the control bar (and its branch-keyed PR lookup) follows
- // the repository's actual HEAD immediately after the tool call completes.
- if (branchSwitch) {
+ // the repository's actual HEAD immediately after the tool call completes. A push
+ // is refreshed too: it establishes the branch's remote ref, which this key carries.
+ if (branchSwitch || pushUpstream) {
const boundDeviceId = topic?.metadata?.boundDeviceId;
const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
const cacheDeviceId =