Skip to content

Commit 02297cd

Browse files
johnnyhuycodex
andauthored
feat: show local upstream comparison in workspace status (#71)
Co-authored-by: OpenAI Codex <[email protected]>
1 parent c37ccdd commit 02297cd

7 files changed

Lines changed: 169 additions & 2 deletions

File tree

‎docs/pidex-architecture.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ History preview follows the selected archive parent chain so abandoned branches
7575

7676
History handoff uses the same selected entries as Markdown export and appends them to the new-session draft of another available, registered root. It switches the selected group/root through the existing navigation path and preserves the source preview and per-root drafts. Preparing a handoff performs no runtime open, resume or prompt action. The destination composer remains editable and uses its own model defaults. Sending starts a separate session there; no files or Pi archives are relocated.
7777

78-
Workspace inspection reads the file tree, Git branch/status and repository HEAD commit. The new-session view and expanded history status show that commit's hash, subject and committed date. Nested roots show repository HEAD, including commits outside that folder; linked worktrees use their own HEAD. A missing commit does not hide available change counts. Inspection refreshes on focus, view/runtime-state changes, and every 15 seconds. There is no filesystem watcher. File discovery skips common dependency/build directories and symlinks and is capped at 3,000 files and seven directory levels.
78+
Workspace inspection reads the file tree, Git branch/status and repository HEAD commit. The new-session view and expanded history status show that commit's hash, subject and committed date. Nested roots show repository HEAD, including commits outside that folder; linked worktrees use their own HEAD. A missing commit does not hide available change counts. Workspace status also compares HEAD with the configured upstream using local refs, showing ahead/behind counts or explaining an absent/unavailable upstream. It never fetches; counts reflect the refs currently stored in that repository. Inspection refreshes on focus, view/runtime-state changes, and every 15 seconds. There is no filesystem watcher. File discovery skips common dependency/build directories and symlinks and is capped at 3,000 files and seven directory levels.
7979

8080
Per-root views, new-session/history drafts, unsaved settings drafts, open tabs, transcript selection, and expanded rows are in-memory UI state. Restoring an interrupted history load retries the saved archive/entry, while completed error states require explicit retry. Settings cache only dirty drafts; clean views follow saved defaults. Changes views remount per root and late mutation results are checked against their original navigation generation. Scroll position and expansion are not persisted when a transcript is reopened.
8181

‎src/main/workbench.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,13 @@ export type GitChange = {
2424
staged: boolean;
2525
untracked: boolean;
2626
};
27+
export type GitUpstream =
28+
| { state: 'none' }
29+
| { state: 'unavailable'; name?: string }
30+
| { state: 'tracked'; name: string; ahead: number; behind: number };
2731
export type WorkspaceDetails = {
2832
branch: string;
33+
upstream?: GitUpstream;
2934
headCommit?: { hash: string; subject: string; committedAt: string };
3035
changes: GitChange[];
3136
files: string[];
@@ -168,6 +173,26 @@ async function listFiles(
168173
return { files, filesTruncated };
169174
}
170175

176+
async function inspectUpstream(cwd: string, branch: string): Promise<GitUpstream | undefined> {
177+
if (!branch) return undefined;
178+
let name: string | undefined;
179+
try {
180+
const refs = await git(cwd, [
181+
'for-each-ref', '--format=%(upstream:short)%00%(upstream)', `refs/heads/${branch}`,
182+
]);
183+
const [shortName, ref] = refs.trim().split('\0');
184+
if (!ref) return { state: 'none' };
185+
name = shortName;
186+
// Compare full refs, including local-branch upstreams, without network access.
187+
const counts = await git(cwd, ['rev-list', '--left-right', '--count', `HEAD...${ref}`, '--']);
188+
const match = /^(\d+)\s+(\d+)$/.exec(counts.trim());
189+
if (!match) return { state: 'unavailable', name };
190+
return { state: 'tracked', name, ahead: Number(match[1]), behind: Number(match[2]) };
191+
} catch {
192+
return { state: 'unavailable', name };
193+
}
194+
}
195+
171196
export async function inspectWorkspace(cwd: string): Promise<WorkspaceDetails> {
172197
const { files, filesTruncated } = await listFiles(cwd);
173198
try {
@@ -205,6 +230,7 @@ export async function inspectWorkspace(cwd: string): Promise<WorkspaceDetails> {
205230
const [hash, committedAt, subject] = commit.split('\0');
206231
return {
207232
branch: branch.trim(),
233+
upstream: await inspectUpstream(cwd, branch.trim()),
208234
headCommit: commit ? {
209235
hash,
210236
committedAt,

‎src/renderer/components/WorkspaceStatus.tsx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,18 @@ export function WorkspaceStatus({
4747
<p className="wb-meta">
4848
{details.branch || 'Detached HEAD'} · {staged} staged · {unstaged} unstaged · {untracked} untracked
4949
</p>
50+
<p className="wb-meta wb-workspace-upstream" aria-label="Upstream comparison">
51+
{!details.branch
52+
? 'Upstream comparison unavailable for detached HEAD.'
53+
: details.upstream?.state === 'none'
54+
? 'No upstream configured.'
55+
: details.upstream?.state === 'tracked'
56+
? `Upstream ${details.upstream.name} · ${details.upstream.ahead} ahead · ${details.upstream.behind} behind`
57+
: `Upstream ${details.upstream?.state === 'unavailable' && details.upstream.name ? details.upstream.name : 'comparison'} unavailable.`}
58+
{details.branch && details.upstream?.state !== 'none' && (
59+
<span className="wb-workspace-upstream-note">Local refs only. No fetch performed.</span>
60+
)}
61+
</p>
5062
{commit ? (
5163
<div className="wb-workspace-commit" aria-label="Current repository commit">
5264
<p className="wb-meta">

‎src/renderer/workbench.css‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,12 @@ html[data-reduced-motion='true'] .wb-shell *::after {
416416
.wb-workspace-status p {
417417
margin: 4px 0 0;
418418
}
419+
.wb-workspace-upstream {
420+
overflow-wrap: anywhere;
421+
}
422+
.wb-workspace-upstream-note {
423+
display: block;
424+
}
419425
.wb-workspace-commit-subject {
420426
display: -webkit-box;
421427
-webkit-box-orient: vertical;

‎tests/e2e/workspace-status.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,55 @@ describe('workspace status in Electron', () => {
211211
expect(errors).toEqual([]);
212212
});
213213

214+
it('refreshes local upstream comparison, preserves history space and clears stale tracking on root switches', async () => {
215+
await select('project');
216+
git(project, 'remote', 'add', 'origin', path.join(fixture, 'no-remote'));
217+
git(project, 'update-ref', 'refs/remotes/origin/feature/workspace-status', 'HEAD');
218+
git(project, 'branch', '--set-upstream-to=origin/feature/workspace-status');
219+
// An independent commit object models a fetched remote tip without a network request.
220+
const remoteTip = git(project, '-c', 'user.name=Test', '-c', '[email protected]',
221+
'commit-tree', 'HEAD^{tree}', '-p', 'HEAD', '-m', 'Cached upstream tip').toString().trim();
222+
git(project, 'update-ref', 'refs/remotes/origin/feature/workspace-status', remoteTip);
223+
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
224+
await expect.poll(() => status().getByLabel('Upstream comparison').textContent()).toContain('0 ahead · 1 behind');
225+
await status().getByText('Local refs only. No fetch performed.').waitFor();
226+
await capture('workspace-upstream.png');
227+
await resizeWindow(900, 600);
228+
await status().getByLabel('Upstream comparison').scrollIntoViewIfNeeded();
229+
expect(await page.evaluate(() => document.body.scrollWidth <= innerWidth)).toBe(true);
230+
await capture('workspace-upstream-narrow.png');
231+
await resizeWindow(1280, 900);
232+
233+
await page.getByRole('button', { name: /^Sessions/ }).click();
234+
await page.getByRole('tree', { name: 'Session archives', exact: true })
235+
.getByRole('treeitem', { name: /Review saved parser work/ }).click();
236+
await status().locator('summary').click();
237+
await status().getByLabel('Upstream comparison').waitFor();
238+
expect(await status().getByLabel('Upstream comparison').textContent()).toContain('0 ahead · 1 behind');
239+
await status().getByLabel('Upstream comparison').scrollIntoViewIfNeeded();
240+
await capture('history-upstream.png');
241+
await resizeWindow(900, 600);
242+
await status().getByLabel('Upstream comparison').scrollIntoViewIfNeeded();
243+
expect(await page.locator('.wb-transcript').evaluate((el) => el.clientHeight)).toBeGreaterThan(40);
244+
expect(await page.evaluate(() => document.body.scrollWidth <= innerWidth)).toBe(true);
245+
const composerBottom = await page.locator('.wb-composer').evaluate((el) => el.getBoundingClientRect().bottom);
246+
const footerTop = await page.locator('.wb-statusbar').evaluate((el) => el.getBoundingClientRect().top);
247+
expect(composerBottom).toBeLessThanOrEqual(footerTop);
248+
await capture('history-upstream-narrow.png');
249+
git(project, 'update-ref', '-d', 'refs/remotes/origin/feature/workspace-status');
250+
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
251+
await expect.poll(() => status().getByLabel('Upstream comparison').textContent()).toContain('Upstream origin/feature/workspace-status unavailable.');
252+
expect(await status().getByRole('button', { name: 'Review workspace changes' }).isEnabled()).toBe(true);
253+
await resizeWindow(1280, 900);
254+
await select('clean');
255+
await expect.poll(() => status().getByLabel('Upstream comparison').textContent()).toContain('detached HEAD');
256+
expect(await status().textContent()).not.toContain('origin/feature/workspace-status');
257+
git(clean, 'switch', 'main');
258+
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
259+
await expect.poll(() => status().getByLabel('Upstream comparison').textContent()).toBe('No upstream configured.');
260+
expect(errors).toEqual([]);
261+
});
262+
214263
it('does not describe non-Git folders or missing roots as clean', async () => {
215264
await select('plain');
216265
await expect.poll(() => status().textContent()).toContain('Git changes are unavailable for this folder.');

‎tests/integration/WorkspaceStatus.test.tsx‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,41 @@ const change: GitChange = {
1919
afterEach(cleanup);
2020

2121
describe('workspace Git status', () => {
22+
it('shows local upstream counts and refreshes them without claiming to fetch', () => {
23+
const { rerender } = render(<WorkspaceStatus workspace={workspace} details={{ ...details,
24+
upstream: { state: 'tracked', name: 'origin/feature/status', ahead: 2, behind: 3 },
25+
}} ready onReview={vi.fn()} />);
26+
expect(screen.getByLabelText('Upstream comparison')).toHaveTextContent('Upstream origin/feature/status · 2 ahead · 3 behind');
27+
expect(screen.getByText('Local refs only. No fetch performed.')).toBeVisible();
28+
rerender(<WorkspaceStatus workspace={workspace} details={{ ...details,
29+
upstream: { state: 'tracked', name: 'origin/main', ahead: 0, behind: 0 },
30+
}} ready onReview={vi.fn()} />);
31+
expect(screen.getByLabelText('Upstream comparison')).toHaveTextContent('Upstream origin/main · 0 ahead · 0 behind');
32+
expect(screen.queryByText(/origin\/feature/)).not.toBeInTheDocument();
33+
});
34+
35+
it('shows upstream comparison only inside expanded saved-history status', () => {
36+
render(<WorkspaceStatus context="history" workspace={workspace} details={{ ...details,
37+
upstream: { state: 'tracked', name: 'origin/main', ahead: 1, behind: 2 },
38+
}} ready onReview={vi.fn()} />);
39+
expect(screen.getByLabelText('Upstream comparison')).not.toBeVisible();
40+
fireEvent.click(screen.getByText('Current workspace changes'));
41+
expect(screen.getByLabelText('Upstream comparison')).toBeVisible();
42+
expect(screen.getByLabelText('Upstream comparison')).toHaveTextContent('1 ahead · 2 behind');
43+
});
44+
45+
it.each([
46+
{ branch: 'main', upstream: { state: 'none' as const }, message: 'No upstream configured.' },
47+
{ branch: '', upstream: undefined, message: 'Upstream comparison unavailable for detached HEAD.' },
48+
{ branch: 'main', upstream: { state: 'unavailable' as const, name: 'origin/gone' }, message: 'Upstream origin/gone unavailable.' },
49+
{ branch: 'main', upstream: { state: 'unavailable' as const }, message: 'Upstream comparison unavailable.' },
50+
])('explains $message and preserves change review', ({ branch, upstream, message }) => {
51+
render(<WorkspaceStatus workspace={workspace} details={{ ...details, branch, upstream, changes: [change] }} ready onReview={vi.fn()} />);
52+
expect(screen.getByLabelText('Upstream comparison')).toHaveTextContent(message);
53+
expect(screen.getByRole('status')).toHaveTextContent('1 changed file');
54+
expect(screen.getByRole('button')).toBeEnabled();
55+
});
56+
2257
it('shows current repository hash, literal subject and committed date, then refreshes them', () => {
2358
const { container, rerender } = render(<WorkspaceStatus workspace={workspace} details={{ ...details, headCommit }} ready onReview={vi.fn()} />);
2459
expect(screen.getByLabelText('Current repository commit')).toHaveTextContent('Repository HEAD · 12345678');
@@ -83,11 +118,12 @@ describe('workspace Git status', () => {
83118
{ ready: true, availability: 'unavailable' as const, gitError: undefined, message: 'Restore this folder to inspect Git changes.' },
84119
{ ready: true, availability: 'available' as const, gitError: 'Git changes are unavailable for this folder.', message: 'Git changes are unavailable for this folder.' },
85120
])('does not claim a clean root when $message', ({ ready, availability, gitError, message }) => {
86-
render(<WorkspaceStatus workspace={{ ...workspace, availability }} details={{ ...details, gitError, headCommit }} ready={ready} onReview={vi.fn()} />);
121+
render(<WorkspaceStatus workspace={{ ...workspace, availability }} details={{ ...details, gitError, headCommit, upstream: { state: 'tracked', name: 'origin/main', ahead: 1, behind: 2 } }} ready={ready} onReview={vi.fn()} />);
87122
expect(screen.getByRole('status')).toHaveTextContent(message);
88123
expect(screen.getByRole('button')).toBeDisabled();
89124
expect(screen.queryByText('No changes in this root')).not.toBeInTheDocument();
90125
expect(screen.queryByText(/old-branch|feature\/status/)).not.toBeInTheDocument();
91126
expect(screen.queryByLabelText('Current repository commit')).not.toBeInTheDocument();
127+
expect(screen.queryByLabelText('Upstream comparison')).not.toBeInTheDocument();
92128
});
93129
});

‎tests/unit/workbench.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,39 @@ afterEach(async () => {
2929
});
3030

3131
describe('workspace inspection and preview', () => {
32+
it('compares local upstream refs from nested roots and refreshes ahead, behind and diverged counts without fetching', async () => {
33+
const root = await fixture();
34+
const nested = path.join(root, 'package');
35+
await fs.mkdir(nested);
36+
await git(root, ['init', '-b', 'main']);
37+
await git(root, ['config', 'user.name', 'Test']);
38+
await git(root, ['config', 'user.email', '[email protected]']);
39+
await git(root, ['config', 'commit.gpgsign', 'false']);
40+
await git(root, ['commit', '--allow-empty', '-m', 'Shared base']);
41+
await git(root, ['remote', 'add', 'origin', path.join(root, 'nonexistent-remote')]);
42+
await git(root, ['update-ref', 'refs/remotes/origin/main', 'HEAD']);
43+
await git(root, ['branch', '--set-upstream-to=origin/main']);
44+
const tracked = (ahead: number, behind: number) => ({ state: 'tracked', name: 'origin/main', ahead, behind });
45+
expect((await inspectWorkspace(nested)).upstream).toEqual(tracked(0, 0));
46+
await git(root, ['commit', '--allow-empty', '-m', 'Local tip']);
47+
expect((await inspectWorkspace(nested)).upstream).toEqual(tracked(1, 0));
48+
await git(root, ['checkout', '-b', 'remote-tip', 'origin/main']);
49+
await git(root, ['commit', '--allow-empty', '-m', 'Remote tip']);
50+
await git(root, ['update-ref', 'refs/remotes/origin/main', 'HEAD']);
51+
await git(root, ['checkout', 'main']);
52+
expect((await inspectWorkspace(nested)).upstream).toEqual(tracked(1, 1));
53+
await git(root, ['reset', '--hard', 'HEAD~1']);
54+
expect((await inspectWorkspace(nested)).upstream).toEqual(tracked(0, 1));
55+
await git(root, ['update-ref', '-d', 'refs/remotes/origin/main']);
56+
await fs.writeFile(path.join(nested, 'new.ts'), 'pending change');
57+
const gone = await inspectWorkspace(nested);
58+
expect(gone.upstream).toEqual({ state: 'unavailable', name: 'origin/main' });
59+
expect(gone.gitError).toBeUndefined();
60+
expect(gone.changes[0]?.path).toBe('new.ts');
61+
await git(root, ['branch', '--unset-upstream']);
62+
expect((await inspectWorkspace(nested)).upstream).toEqual({ state: 'none' });
63+
});
64+
3265
it('reads repository HEAD from nested roots and refreshes after a commit outside the root', async () => {
3366
const root = await fixture();
3467
const nested = path.join(root, 'package');
@@ -67,11 +100,15 @@ describe('workspace inspection and preview', () => {
67100
await git(root, ['commit', '--allow-empty', '-m', 'Shared base']);
68101
await git(root, ['worktree', 'add', '-b', 'feature/linked', linked]);
69102
await git(linked, ['commit', '--allow-empty', '-m', 'Linked tip']);
103+
await git(linked, ['branch', '--set-upstream-to=main']);
104+
expect((await inspectWorkspace(root)).upstream).toEqual({ state: 'none' });
105+
expect((await inspectWorkspace(linked)).upstream).toEqual({ state: 'tracked', name: 'main', ahead: 1, behind: 0 });
70106
expect((await inspectWorkspace(root)).headCommit?.subject).toBe('Shared base');
71107
expect((await inspectWorkspace(linked)).headCommit?.subject).toBe('Linked tip');
72108
await git(linked, ['checkout', '--detach', 'HEAD~1']);
73109
const detached = await inspectWorkspace(linked);
74110
expect(detached.branch).toBe('');
111+
expect(detached.upstream).toBeUndefined();
75112
expect(detached.headCommit?.subject).toBe('Shared base');
76113
});
77114

@@ -83,6 +120,7 @@ describe('workspace inspection and preview', () => {
83120
expect(result.branch).toBe('main');
84121
expect(result.gitError).toBeUndefined();
85122
expect(result.headCommit).toBeUndefined();
123+
expect(result.upstream).toEqual({ state: 'none' });
86124
expect(result.changes[0]?.path).toBe('new.ts');
87125
});
88126

0 commit comments

Comments
 (0)