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

address review (claude): untracked count, stuck rebase, and a test that broke CI

[._.]/ Adam Eivy460a21f42e82
diff --git a/client/src/components/apps/tabs/GitTab.jsx b/client/src/components/apps/tabs/GitTab.jsx
index 6050494588..9ad953a87f 100644
--- a/client/src/components/apps/tabs/GitTab.jsx
+++ b/client/src/components/apps/tabs/GitTab.jsx
@@ -448,6 +448,9 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
? ` from ${result.previousBranch}`
: '';
toast.success(`Reset to origin/${result.branch}${from} — discarded ${result.discardedFiles} file change${result.discardedFiles === 1 ? '' : 's'}`);
+ if (result.clearedOperations?.length) {
+ toast(`Also cleared an in-progress ${result.clearedOperations.join(' and ')}`, { icon: '🧹' });
+ }
if (result.previousHead) {
toast(`Previous state was ${result.previousHead.slice(0, 7)} — git reset --hard ${result.previousHead.slice(0, 7)} to undo`, { icon: '↩️' });
}
@@ -458,7 +461,9 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
}
};
- const dirtyCount = gitInfo?.status?.files?.length || 0;
+ // Untracked files are the ones a reset KEEPS, so they must not be counted in
+ // what it says it will discard — the dialog claims both things two rows apart.
+ const dirtyCount = gitInfo?.status?.files?.filter(f => f.status !== 'untracked').length || 0;
const getStatusIcon = (file) => {
if (file.added) return <Plus size={14} className="text-port-success" />;
diff --git a/client/src/components/apps/tabs/GitTab.test.jsx b/client/src/components/apps/tabs/GitTab.test.jsx
index f3f6a404f5..4905014a00 100644
--- a/client/src/components/apps/tabs/GitTab.test.jsx
+++ b/client/src/components/apps/tabs/GitTab.test.jsx
@@ -168,6 +168,27 @@ describe('GitTab reset to origin', () => {
expect(api.resetToDefaultBranch).not.toHaveBeenCalled();
});
+ it('does not count untracked files among what it says it will discard', async () => {
+ // The dialog promises "Keeps untracked files" two rows below this number,
+ // so counting them there contradicts the same dialog.
+ api.getGitInfo.mockResolvedValue({
+ ...GIT_INFO,
+ status: {
+ files: [
+ { path: 'a.js', status: 'modified', staged: false },
+ { path: 'b.js', status: 'added', staged: true },
+ { path: 'scratch.log', status: 'untracked', staged: false },
+ ],
+ },
+ });
+ render(<GitTab appId="x" appName="App" repoPath="/repo" />);
+
+ fireEvent.click(await screen.findByText('Reset to origin'));
+
+ const dialog = await screen.findByRole('dialog');
+ expect(dialog).toHaveTextContent('Discards 2 uncommitted file changes');
+ });
+
it('does not reset when the confirmation is cancelled', async () => {
render(<GitTab appId="x" appName="App" repoPath="/repo" />);
diff --git a/scripts/checkNpmVersion.test.js b/scripts/checkNpmVersion.test.js
index fa02591f84..5be99cd096 100644
--- a/scripts/checkNpmVersion.test.js
+++ b/scripts/checkNpmVersion.test.js
@@ -45,11 +45,24 @@ describe('parseNpmUserAgent', () => {
expect(parseNpmUserAgent('yarn/4.1.0 npm/? node/v24.10.0 linux x64')).toBeNull();
});
- it('returns null when not running under npm', () => {
- expect(parseNpmUserAgent(undefined)).toBeNull();
+ it('returns null when there is no npm user agent to read', () => {
+ // NOT `parseNpmUserAgent(undefined)`: the parameter defaults to
+ // `process.env.npm_config_user_agent`, and passing an explicit `undefined`
+ // is indistinguishable from omitting the argument — so under `npm test`
+ // that call reads the ambient agent and returns a version, not null.
expect(parseNpmUserAgent('')).toBeNull();
expect(parseNpmUserAgent(null)).toBeNull();
});
+
+ it('falls back to the ambient npm_config_user_agent, and to null without one', () => {
+ vi.stubEnv('npm_config_user_agent', 'npm/10.9.0 node/v22.12.0 linux x64');
+ expect(parseNpmUserAgent()).toBe('10.9.0');
+ // The "not running under npm" case the default parameter exists for. Stubbed
+ // rather than assumed, because the suite itself usually runs under npm.
+ vi.stubEnv('npm_config_user_agent', '');
+ expect(parseNpmUserAgent()).toBeNull();
+ vi.unstubAllEnvs();
+ });
});
describe('readBundledNpmVersion', () => {
diff --git a/server/services/git.js b/server/services/git.js
index 633f206594..92242a215d 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -1163,6 +1163,60 @@ export async function checkoutRemoteBranch(dir, branchName) {
return { success: true, branch: branchName };
}
+/**
+ * How many entries in raw `git status --porcelain` output a hard reset would
+ * actually destroy — i.e. everything except untracked (`??`) files, which
+ * survive because nothing here runs `git clean`.
+ * @param {string} porcelain - Raw `git status --porcelain` stdout
+ * @returns {number}
+ */
+export function countDiscardable(porcelain) {
+ return String(porcelain || '')
+ .split('\n')
+ .filter(line => line.trim() && !line.startsWith('??'))
+ .length;
+}
+
+/**
+ * Sequencer state files a forced checkout does NOT clear, mapped to the command
+ * that drops each. `--quit` rather than `--abort`: abort rewinds to the
+ * pre-operation HEAD, which is the very state a reset is discarding, while
+ * `--quit` removes the bookkeeping and leaves the tree the checkout just
+ * restored alone. (`MERGE_HEAD` is absent here on purpose — a plain conflicted
+ * merge IS cleared by `checkout --force`.)
+ */
+const SEQUENCER_STATE = [
+ ['rebase-merge', 'rebase'],
+ ['rebase-apply', 'rebase'],
+ ['CHERRY_PICK_HEAD', 'cherry-pick'],
+ ['REVERT_HEAD', 'revert']
+];
+
+/**
+ * Drop any half-finished rebase / cherry-pick / revert.
+ *
+ * Without this a checkout left mid-rebase still reports "You are currently
+ * rebasing" after the reset, and every later `git rebase` in that repo dies on
+ * "there is already a rebase-merge directory" until someone deletes it by hand
+ * — so the reset would report success while leaving the repo in exactly the
+ * stuck state it is advertised to fix.
+ *
+ * @param {string} dir - Repo root
+ * @param {string} gitDirPath - Absolute path to the repo's git dir
+ * @returns {Promise<string[]>} - The operations that were cleared
+ */
+async function clearSequencerState(dir, gitDirPath) {
+ const stuck = [...new Set(
+ SEQUENCER_STATE
+ .filter(([marker]) => existsSync(join(gitDirPath, marker)))
+ .map(([, command]) => command)
+ )];
+ for (const command of stuck) {
+ await execGitSafe([command, '--quit'], dir);
+ }
+ return stuck;
+}
+
/**
* The id of a running CoS agent whose workspace IS `dir`, or null when none is.
* Paths are compared after `resolve` so a trailing slash or a `..` segment on
@@ -1199,8 +1253,13 @@ async function findActiveAgentInWorkspace(dir) {
* recovers them (the commits stay in the reflog for git's gc window).
* - Untracked files stay. There is no `git clean` here: a checkout's
* untracked set is where `.env` files, build output, and scratch work live,
- * and losing those is not recoverable from a reflog.
+ * and losing those is not recoverable from a reflog. `discardedFiles`
+ * excludes them for the same reason — it counts what was destroyed, not
+ * what was merely dirty.
* - Other local branches are untouched — this moves the default branch only.
+ * - A half-finished rebase / cherry-pick / revert IS cleared (`clearedOperations`
+ * names which), because leaving one behind is the stuck state this exists
+ * to escape.
*
* A fetch failure is not fatal: the reset falls back to the cached
* `origin/<default>` ref so an offline machine can still get back to a known
@@ -1208,7 +1267,8 @@ async function findActiveAgentInWorkspace(dir) {
*
* @param {string} dir - Working directory (a repo root, not a linked worktree)
* @returns {Promise<{success: boolean, branch: string, previousBranch: string|null,
- * previousHead: string|null, discardedFiles: number, fetched: boolean}>}
+ * previousHead: string|null, discardedFiles: number, clearedOperations: string[],
+ * fetched: boolean}>}
*/
export async function resetToDefaultBranch(dir) {
// A linked worktree cannot check out the default branch — the main checkout
@@ -1270,6 +1330,11 @@ export async function resetToDefaultBranch(dir) {
const previousHead = head || null;
const previousBranch = branchName || null;
+ // A half-finished rebase/cherry-pick survives the checkout below, so drop it
+ // first — otherwise the reset "succeeds" into a repo that still refuses every
+ // later rebase.
+ const clearedOperations = await clearSequencerState(dir, resolve(dir, gitDir || '.git'));
+
// `checkout --force -B` is the whole operation: `-B` repoints the local branch
// at the remote ref and `--force` resets index AND working tree to it, so a
// trailing `reset --hard` would re-walk every tracked file to change nothing.
@@ -1280,7 +1345,12 @@ export async function resetToDefaultBranch(dir) {
branch,
previousBranch,
previousHead,
- discardedFiles: dirty ? dirty.split('\n').filter(Boolean).length : 0,
+ // Untracked files (`??`) are the ones this reset deliberately KEEPS, so
+ // counting them would tell the user more was destroyed than actually was —
+ // directly contradicting the "keeps untracked files" line the confirm
+ // dialog shows two rows above this number.
+ discardedFiles: countDiscardable(dirty),
+ clearedOperations,
fetched
};
}
diff --git a/server/services/git.resetToDefault.test.js b/server/services/git.resetToDefault.test.js
index 42cc6d78de..ad78c9720d 100644
--- a/server/services/git.resetToDefault.test.js
+++ b/server/services/git.resetToDefault.test.js
@@ -12,11 +12,19 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const execGitMock = vi.hoisted(() => vi.fn());
const getAgentsMock = vi.hoisted(() => vi.fn());
+const existsSyncMock = vi.hoisted(() => vi.fn());
vi.mock('../lib/execGit.js', () => ({
execGit: execGitMock
}));
+// Only the sequencer-state probe reads the filesystem here; everything else in
+// git.js reaches git through the mock above.
+vi.mock('fs', async (importOriginal) => ({
+ ...(await importOriginal()),
+ existsSync: existsSyncMock
+}));
+
vi.mock('./cosAgentLifecycle.js', () => ({
getAgents: getAgentsMock
}));
@@ -60,6 +68,9 @@ beforeEach(() => {
execGitMock.mockReset();
getAgentsMock.mockReset();
getAgentsMock.mockResolvedValue([]);
+ // Default: no rebase/cherry-pick/revert in progress.
+ existsSyncMock.mockReset();
+ existsSyncMock.mockReturnValue(false);
clearFetchCache();
});
@@ -118,6 +129,47 @@ describe('resetToDefaultBranch', () => {
expect(calledCommands().some((cmd) => cmd.startsWith('clean'))).toBe(false);
});
+ it('excludes untracked files from the discarded count, since it keeps them', async () => {
+ // Counting `??` entries would claim more was destroyed than was — the
+ // confirm dialog promises "keeps untracked files" two rows above the number.
+ routeGit({
+ ...HAPPY_PATH,
+ 'status --porcelain': ok(' M tracked.js\nA staged.js\n?? scratch.log\n?? build/')
+ });
+
+ const result = await resetToDefaultBranch('/repo');
+
+ expect(result.discardedFiles).toBe(2);
+ });
+
+ it('clears a half-finished rebase, which the forced checkout leaves behind', async () => {
+ // Verified against real git: `checkout --force` empties the tree and index
+ // but leaves .git/rebase-merge, so the reset "succeeds" into a repo where
+ // every later `git rebase` dies on "already a rebase-merge directory".
+ existsSyncMock.mockImplementation((path) => String(path).endsWith('rebase-merge'));
+ routeGit(HAPPY_PATH);
+
+ const result = await resetToDefaultBranch('/repo');
+
+ expect(result.clearedOperations).toEqual(['rebase']);
+ expect(calledCommands()).toContain('rebase --quit');
+ // --quit, never --abort: abort rewinds to the pre-rebase HEAD, which is the
+ // state the reset is deliberately discarding.
+ expect(calledCommands().some((cmd) => cmd.includes('--abort'))).toBe(false);
+ // And it runs BEFORE the checkout, so the checkout lands on a normal repo.
+ expect(calledCommands().indexOf('rebase --quit'))
+ .toBeLessThan(calledCommands().indexOf('checkout --force -B main origin/main'));
+ });
+
+ it('leaves the sequencer alone when no operation is in progress', async () => {
+ routeGit(HAPPY_PATH);
+
+ const result = await resetToDefaultBranch('/repo');
+
+ expect(result.clearedOperations).toEqual([]);
+ expect(calledCommands().some((cmd) => cmd.includes('--quit'))).toBe(false);
+ });
+
it('refuses to reset a linked worktree', async () => {
routeGit({
...HAPPY_PATH,