Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add rebase and push for ahead app default branches

Adam Eivy741d068ed0ff
diff --git a/client/src/components/apps/tabs/GitTab.jsx b/client/src/components/apps/tabs/GitTab.jsx
index c9a78f0a3b..607ef95c95 100644
--- a/client/src/components/apps/tabs/GitTab.jsx
+++ b/client/src/components/apps/tabs/GitTab.jsx
@@ -153,6 +153,7 @@ export default function GitTab({ appId, appName, repoPath }) {
const [pushing, setPushing] = useState(null);
const [syncing, setSyncing] = useState(null);
const [pushingAll, setPushingAll] = useState(false);
+ const [rebasingAndPushing, setRebasingAndPushing] = useState(false);
const [openingPullRequest, setOpeningPullRequest] = useState(false);
const [reconciling, setReconciling] = useState(false);
const [remoteBranches, setRemoteBranches] = useState([]);
@@ -356,6 +357,19 @@ export default function GitTab({ appId, appName, repoPath }) {
await loadGitInfo();
};
+ const handleRebaseAndPush = async () => {
+ if (!repoPath || rebasingAndPushing) return;
+ setRebasingAndPushing(true);
+ const result = await api.rebaseAndPushDefaultBranch(repoPath, { silent: true }).catch(error => {
+ toast.error(error.message || 'Rebase & push failed');
+ return null;
+ });
+ if (result?.success) toast.success(`Rebased and pushed ${result.branch}`);
+ else if (result?.error) toast.error(result.error);
+ await loadGitInfo();
+ setRebasingAndPushing(false);
+ };
+
const handleOpenPullRequest = async () => {
if (!appId || !repoPath || openingPullRequest) return;
setOpeningPullRequest(true);
@@ -564,7 +578,7 @@ export default function GitTab({ appId, appName, repoPath }) {
}
return (
- <div className="space-y-6">
+ <fieldset disabled={rebasingAndPushing} className="min-w-0 space-y-6">
<RepositorySourcePanel
appId={appId}
appName={appName}
@@ -577,6 +591,16 @@ export default function GitTab({ appId, appName, repoPath }) {
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-semibold text-white">Git Status</h2>
<div className="flex flex-wrap items-center gap-2">
+ <button
+ onClick={handleRebaseAndPush}
+ disabled={rebasingAndPushing || loading || updating || pushingAll || Boolean(syncing || pushing || checkingOut || merging || checkingOutRemote) || committing || resetting
+ || !gitInfo?.status?.clean || gitInfo?.branch !== gitInfo?.baseBranch || !(gitInfo?.originComparison?.ahead > 0)}
+ title="Rebase local default-branch commits onto origin, then push; requires a clean checkout ahead of origin"
+ className="flex min-h-[40px] items-center gap-1.5 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-50"
+ >
+ {rebasingAndPushing ? <Loader2 size={16} className="animate-spin" /> : <ArrowUpDown size={16} />}
+ {rebasingAndPushing ? 'Rebasing & pushing...' : 'Rebase & push'}
+ </button>
{branches.some(b => b.tracking && b.ahead > 0) && (
<button
onClick={handlePushAll}
@@ -1185,6 +1209,6 @@ export default function GitTab({ appId, appName, repoPath }) {
The commit you are on now is reported after the reset, so <code>git reset --hard &lt;sha&gt;</code> can undo this.
</p>
</ConfirmModal>
- </div>
+ </fieldset>
);
}
diff --git a/client/src/components/apps/tabs/GitTab.test.jsx b/client/src/components/apps/tabs/GitTab.test.jsx
index 1fbad96fb9..9636ac04a2 100644
--- a/client/src/components/apps/tabs/GitTab.test.jsx
+++ b/client/src/components/apps/tabs/GitTab.test.jsx
@@ -14,6 +14,7 @@ vi.mock('../../../services/api', () => ({
getRemoteBranches: vi.fn(),
updateBranches: vi.fn(),
pushAllBranches: vi.fn(),
+ rebaseAndPushDefaultBranch: vi.fn(),
getGitDiff: vi.fn(),
cleanupMergedBranches: vi.fn(),
resetToDefaultBranch: vi.fn(),
@@ -64,6 +65,40 @@ afterEach(() => {
vi.clearAllMocks();
});
+describe('GitTab rebase and push', () => {
+ const aheadDefault = {
+ ...GIT_INFO, branch: 'main', status: { clean: true, files: [] }, originComparison: { ahead: 1, behind: 11 },
+ };
+
+ it('rebases and pushes a clean diverged default branch and refreshes the source counts', async () => {
+ api.getGitInfo.mockResolvedValue(aheadDefault);
+ let finish;
+ api.rebaseAndPushDefaultBranch.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
+ render(<GitTab appId="app-example" appName="Example App" repoPath="/repo" />);
+ const button = await screen.findByRole('button', { name: 'Rebase & push' });
+ await waitFor(() => expect(button).toBeEnabled());
+ fireEvent.click(button);
+ expect(await screen.findByRole('button', { name: 'Rebasing & pushing...' })).toBeDisabled();
+ expect(api.rebaseAndPushDefaultBranch).toHaveBeenCalledWith('/repo', { silent: true });
+ api.getGitInfo.mockResolvedValue({ ...aheadDefault, originComparison: { ahead: 0, behind: 0 } });
+ await act(async () => finish({ success: true, branch: 'main' }));
+ await waitFor(() => expect(screen.getByTestId('repository-source-panel')).toHaveAttribute('data-refresh-key', '1'));
+ expect(screen.getByRole('button', { name: 'Rebase & push' })).toBeDisabled();
+ });
+
+ it.each([
+ { branch: 'feature/work' },
+ { status: { clean: false, files: [{ path: 'a.js', status: 'M' }] } },
+ { originComparison: { ahead: 0, behind: 3 } },
+ { originComparison: null },
+ ])('does not enable recovery outside a clean ahead default branch: %j', async (override) => {
+ api.getGitInfo.mockResolvedValue({ ...aheadDefault, ...override });
+ render(<GitTab appId="app-example" appName="Example App" repoPath="/repo" />);
+ await screen.findByText('View Diff');
+ expect(screen.getByRole('button', { name: 'Rebase & push' })).toBeDisabled();
+ });
+});
+
describe('GitTab managed repository sources', () => {
it('queues an agent to deliver current work through a reviewed pull request', async () => {
render(<GitTab appId="app-example" appName="Example App" repoPath="/srv/example-app" />);
diff --git a/client/src/services/apiGit.js b/client/src/services/apiGit.js
index 9b949060b6..2c9c3350d9 100644
--- a/client/src/services/apiGit.js
+++ b/client/src/services/apiGit.js
@@ -37,6 +37,11 @@ export const pushAllBranches = (path) => request('/git/push-all', {
method: 'POST',
body: JSON.stringify({ path })
});
+export const rebaseAndPushDefaultBranch = (path, options = {}) => request('/git/rebase-push', {
+ method: 'POST',
+ body: JSON.stringify({ path }),
+ ...options
+});
export const getBranches = (path, options = {}) => request('/git/branches', {
method: 'POST',
body: JSON.stringify({ path }),
diff --git a/server/routes/git.js b/server/routes/git.js
index 4bccdb7570..5d39a9ed05 100644
--- a/server/routes/git.js
+++ b/server/routes/git.js
@@ -179,6 +179,12 @@ router.post('/push-all', asyncHandler(async (req, res) => {
res.json(result);
}));
+router.post('/rebase-push', asyncHandler(async (req, res) => {
+ const { path } = validateRequest(gitPathBodySchema, req.body);
+ assertAllowedWorkspace(path);
+ res.json(await git.rebaseAndPushDefaultBranch(path));
+}));
+
// POST /api/git/info - Get full git info for a path
router.post('/info', asyncHandler(async (req, res) => {
const { path } = validateRequest(gitPathBodySchema, req.body);
diff --git a/server/routes/git.test.js b/server/routes/git.test.js
index c784bff736..d69d9fb17f 100644
--- a/server/routes/git.test.js
+++ b/server/routes/git.test.js
@@ -17,6 +17,7 @@ vi.mock('../services/git.js', () => ({
updateBranches: vi.fn().mockResolvedValue({}),
getBranchComparison: vi.fn().mockResolvedValue({}),
pushAll: vi.fn().mockResolvedValue({}),
+ rebaseAndPushDefaultBranch: vi.fn().mockResolvedValue({ success: true }),
getDefaultBranch: vi.fn().mockResolvedValue('main'),
checkout: vi.fn().mockResolvedValue({}),
pull: vi.fn().mockResolvedValue({}),
@@ -89,6 +90,7 @@ describe('git routes — workspace root validation', () => {
['POST /diff', '/diff', { path: '/etc' }],
['POST /commits', '/commits', { path: '/etc' }],
['POST /push', '/push', { path: '/etc' }],
+ ['POST /rebase-push', '/rebase-push', { path: '/etc' }],
['POST /pull', '/pull', { path: '/etc' }],
['POST /info', '/info', { path: '/etc' }],
['POST /branches', '/branches', { path: '/etc' }]
@@ -113,6 +115,7 @@ describe('git routes — workspace root validation', () => {
['POST /diff', '/diff', { path: '/Users/me/project' }],
['POST /commits', '/commits', { path: '/Users/me/project' }],
['POST /push', '/push', { path: '/Users/me/project' }],
+ ['POST /rebase-push', '/rebase-push', { path: '/Users/me/project' }],
['POST /pull', '/pull', { path: '/Users/me/project' }],
['POST /info', '/info', { path: '/Users/me/project' }],
['POST /branches', '/branches', { path: '/Users/me/project' }]
diff --git a/server/services/git.js b/server/services/git.js
index 25eab9e8a7..b479455c77 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -1,4 +1,4 @@
-import { existsSync } from 'fs';
+import { existsSync, realpathSync } from 'fs';
import { randomUUID } from 'node:crypto';
import { mkdtemp } from 'fs/promises';
import { tmpdir } from 'os';
@@ -1144,6 +1144,66 @@ export async function syncBranch(dir, branch = null) {
return withCheckoutPublication(dir, () => syncBranchAdmitted(dir, branch));
}
+const rebasePushCheckouts = new Set();
+
+/** Reconcile local default-branch commits with origin without stashing or force-pushing. */
+export async function rebaseAndPushDefaultBranch(dir) {
+ const key = realpathSync(dir);
+ if (rebasePushCheckouts.has(key)) {
+ throw new ServerError('Rebase & push is already running for this checkout', { status: 409, code: 'GIT_BUSY' });
+ }
+ rebasePushCheckouts.add(key);
+ try {
+ const { withCheckoutPublication } = await import('../lib/checkoutRetirementAdmission.js');
+ return await withCheckoutPublication(dir, () => rebaseAndPushDefaultBranchAdmitted(dir));
+ } finally {
+ rebasePushCheckouts.delete(key);
+ }
+}
+
+async function rebaseAndPushDefaultBranchAdmitted(dir) {
+ const refused = (error) => ({ success: false, pulled: false, pushed: false, error });
+ const gitDir = (await execGit(['rev-parse', '--absolute-git-dir'], dir)).stdout.trim();
+ if ([...SEQUENCER_STATE.map(([marker]) => marker), 'MERGE_HEAD', 'sequencer']
+ .some(marker => existsSync(join(gitDir, marker)))) {
+ return refused('Finish the Git operation already in progress before rebasing and pushing.');
+ }
+ const branch = await getBranch(dir);
+ const defaultBranch = await getDefaultBranch(dir, { strict: true });
+ if (!defaultBranch || branch !== defaultBranch) {
+ return refused('Check out the default branch before rebasing and pushing.');
+ }
+ assertSafeRef(branch);
+ if (!(await getStatus(dir)).clean) {
+ return refused('Commit or stash local changes before rebasing and pushing.');
+ }
+ await fetchOrigin(dir);
+ const remoteRef = `refs/remotes/origin/${branch}`;
+ const counts = await execGit(['rev-list', '--left-right', '--count', `HEAD...${remoteRef}`], dir);
+ if (!(Number(counts.stdout.trim().split(/\s+/)[0]) > 0)) {
+ return refused('The default branch has no local commits ahead of origin.');
+ }
+ // Fetch + rebase is the explicit-origin equivalent of pull --rebase. Avoid
+ // pull.ff / upstream configuration and never move dirty work via autostash.
+ const rebased = await execGit(['rebase', '--no-autostash', remoteRef], dir, { ignoreExitCode: true });
+ if (rebased.exitCode !== 0) {
+ const aborted = await rebaseInProgress(dir)
+ ? await execGit(['rebase', '--abort'], dir, { ignoreExitCode: true }) : null;
+ const recovery = aborted && aborted.exitCode !== 0
+ ? ` Rebase abort failed: ${gitResultError(aborted, 'Inspect the checkout before retrying.')}` : '';
+ return refused(`${gitResultError(rebased, 'Rebase failed; nothing was pushed.')}${recovery}`);
+ }
+ const pushed = await execGit(['push', 'origin', `HEAD:refs/heads/${branch}`], dir, { ignoreExitCode: true });
+ return {
+ success: pushed.exitCode === 0,
+ branch,
+ pulled: true,
+ pushed: pushed.exitCode === 0,
+ output: gitResultOutput(rebased) + gitResultOutput(pushed),
+ error: pushed.exitCode === 0 ? null : gitResultError(pushed, 'Push failed; rebased commits remain local.'),
+ };
+}
+
async function syncBranchAdmitted(dir, branch = null) {
if (branch) assertSafeRef(branch);
const currentBranch = branch || await getBranch(dir);
@@ -2089,6 +2149,14 @@ export async function getGitInfo(dir) {
getRepoBranches(dir).catch(() => ({ baseBranch: null, devBranch: null }))
]);
+ const originComparison = branch && branch !== 'HEAD'
+ ? await execGit(['rev-list', '--left-right', '--count', `HEAD...refs/remotes/origin/${branch}`], dir)
+ .then(({ stdout }) => {
+ const [ahead, behind] = stdout.trim().split(/\s+/).map(Number);
+ return Number.isFinite(ahead) && Number.isFinite(behind) ? { ahead, behind } : null;
+ }).catch(() => null)
+ : null;
+
return {
isRepo: isGit,
branch,
@@ -2096,6 +2164,7 @@ export async function getGitInfo(dir) {
recentCommits: commits,
diffStats,
remote,
+ originComparison,
baseBranch: repoBranches.baseBranch,
devBranch: repoBranches.devBranch,
hasChangelog: hasChangelogDir(dir)
diff --git a/server/services/git.rebasePush.test.js b/server/services/git.rebasePush.test.js
new file mode 100644
index 0000000000..96c3e1e134
--- /dev/null
+++ b/server/services/git.rebasePush.test.js
@@ -0,0 +1,105 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { readFile, writeFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { execGit } from '../lib/execGit.js';
+import { makeGitSandbox, destroyGitSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
+import { getGitInfo, rebaseAndPushDefaultBranch } from './git.js';
+
+// Real Git pins preservation, rebase conflict cleanup and the exact push target.
+describe.skipIf(SKIP_HEAVY_INTEGRATION)('rebase and push the default branch', () => {
+ let sandbox;
+ afterEach(async () => {
+ if (sandbox) await destroyGitSandbox(sandbox.scratch);
+ sandbox = null;
+ });
+ const commitFile = async (repo, file, body) => {
+ await writeFile(join(repo, file), body);
+ await execGit(['add', file], repo);
+ await execGit(['commit', '-m', `Update ${file}`], repo);
+ };
+ const head = async repo => (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();
+ const prepare = async ({ conflict = false } = {}) => {
+ sandbox = await makeGitSandbox({ origin: true });
+ const { repo, scratch, origin } = sandbox;
+ const other = join(scratch, 'other');
+ await execGit(['clone', origin, other], scratch);
+ await execGit(['config', 'user.email', '[email protected]'], other);
+ await execGit(['config', 'user.name', 'Example Agent'], other);
+ await execGit(['config', 'commit.gpgsign', 'false'], other);
+ await commitFile(other, conflict ? 'initial.txt' : 'remote.txt', 'remote change\n');
+ await execGit(['push', 'origin', 'HEAD:main'], other);
+ await commitFile(repo, conflict ? 'initial.txt' : 'local.txt', 'local change\n');
+ return repo;
+ };
+
+ it('reports origin divergence independently of tracking and publishes both sides without a merge commit', async () => {
+ const repo = await prepare();
+ await execGit(['fetch', 'origin'], repo);
+ await execGit(['branch', '--unset-upstream'], repo);
+ expect(await getGitInfo(repo)).toMatchObject({ originComparison: { ahead: 1, behind: 1 } });
+ const result = await rebaseAndPushDefaultBranch(repo);
+ expect(result).toMatchObject({ success: true, pulled: true, pushed: true, branch: 'main' });
+ expect(await head(sandbox.origin)).toBe(await head(repo));
+ expect(await readFile(join(repo, 'remote.txt'), 'utf8')).toBe('remote change\n');
+ expect(await readFile(join(repo, 'local.txt'), 'utf8')).toBe('local change\n');
+ expect((await execGit(['rev-list', '--count', '--merges', 'HEAD'], repo)).stdout.trim()).toBe('0');
+ });
+
+ it('pushes an ahead-only default branch', async () => {
+ sandbox = await makeGitSandbox({ origin: true });
+ await commitFile(sandbox.repo, 'local.txt', 'local change\n');
+ expect(await rebaseAndPushDefaultBranch(sandbox.repo)).toMatchObject({ success: true, pushed: true });
+ expect(await head(sandbox.origin)).toBe(await head(sandbox.repo));
+ });
+
+ it('refuses overlapping requests and permits a later retry after completion', async () => {
+ const repo = await prepare();
+ const first = rebaseAndPushDefaultBranch(repo);
+ await expect(rebaseAndPushDefaultBranch(repo)).rejects.toMatchObject({ code: 'GIT_BUSY' });
+ expect(await first).toMatchObject({ success: true });
+ expect(await rebaseAndPushDefaultBranch(repo)).toMatchObject({ success: false, error: expect.stringContaining('no local commits') });
+ });
+
+ it('aborts its conflicting rebase, preserving local and remote heads', async () => {
+ const repo = await prepare({ conflict: true });
+ const [local, remote] = await Promise.all([head(repo), head(sandbox.origin)]);
+ const result = await rebaseAndPushDefaultBranch(repo);
+ expect(result).toMatchObject({ success: false, pushed: false });
+ expect(result.error).toMatch(/CONFLICT|could not apply/);
+ expect(await head(repo)).toBe(local);
+ expect(await head(sandbox.origin)).toBe(remote);
+ expect(existsSync(join(repo, '.git', 'rebase-merge'))).toBe(false);
+ expect((await execGit(['status', '--porcelain'], repo)).stdout).toBe('');
+ });
+
+ it('leaves another in-progress rebase untouched', async () => {
+ const repo = await prepare({ conflict: true });
+ await execGit(['fetch', 'origin'], repo);
+ await execGit(['rebase', 'origin/main'], repo, { ignoreExitCode: true });
+ expect(await rebaseAndPushDefaultBranch(repo)).toMatchObject({ success: false, error: expect.stringContaining('already in progress') });
+ expect(existsSync(join(repo, '.git', 'rebase-merge'))).toBe(true);
+ });
+
+ it('refuses dirty work and a feature branch without modifying either', async () => {
+ const repo = await prepare();
+ await writeFile(join(repo, 'untracked.txt'), 'keep me');
+ expect(await rebaseAndPushDefaultBranch(repo)).toMatchObject({ success: false, error: expect.stringContaining('local changes') });
+ expect(await readFile(join(repo, 'untracked.txt'), 'utf8')).toBe('keep me');
+ await execGit(['checkout', '-b', 'feature/work'], repo);
+ expect(await rebaseAndPushDefaultBranch(repo)).toMatchObject({ success: false, error: expect.stringContaining('default branch') });
+ });
+
+ it('reports a rejected push and preserves rebased commits locally', async () => {
+ const repo = await prepare();
+ const remote = await head(sandbox.origin);
+ // A repository without the requested push destination provides a portable
+ // rejection without shell hooks (including on Windows).
+ await execGit(['remote', 'set-url', '--push', 'origin', join(sandbox.scratch, 'missing.git')], repo);
+ const result = await rebaseAndPushDefaultBranch(repo);
+ expect(result).toMatchObject({ success: false, pulled: true, pushed: false });
+ expect(result.error).toBeTruthy();
+ expect(await head(sandbox.origin)).toBe(remote);
+ expect(await readFile(join(repo, 'local.txt'), 'utf8')).toBe('local change\n');
+ });
+});