Skip to content

Commit f4fd7a6

Browse files
johnnyhuycodex
andauthored
feat: show workspace Git status before starting a session (#58)
Co-authored-by: OpenAI Codex <[email protected]>
1 parent a60c439 commit f4fd7a6

8 files changed

Lines changed: 309 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ These are captures of real Electron interactions with a temporary Git workspace
5151
- Switch roots while sessions run in the background; retain per-root drafts, views and model defaults.
5252
- Use quick switch for roots, sessions, files, and commands.
5353

54+
The new-session view shows the selected root's branch and changed-file counts before you send a task. A partially staged file counts once overall and appears in both staged and unstaged totals. Use **Review workspace changes** to open Changes and keep your task draft. Counts follow the existing refresh on focus, navigation and every 15 seconds; unavailable folders and failed inspections never appear clean.
55+
5456
Expanded tool cards show output first. Open Input or close Output independently, and copy either section while it is closed. These choices stay with each card while scrolling through the transcript; reopening the transcript resets them.
5557

5658
Session history shows source/fork relationships and an entry tree with selected and archive-tip markers. Select a branch tip or an earlier entry to preview its parent chain. Resume at the archive tip continues in place; **Resume in new fork** continues a historical selection in a separate archive and preserves the source. **Fork from here** uses the selected entry. Pi 1.5.0 RPC does not expose arbitrary-entry navigation, so forks extract a native branch archive before launching Pi so even runtime startup writes preserve the source. Continuation requires an intact Pi v3 archive within the 16 MiB browsing limit. See [ADR 0013](docs/adr/0013-session-branch-selection.md) for runtime semantics and limits.

‎src/renderer/App.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { SessionTree, EntryTree } from './components/SessionTree';
33
import { HistorySummary } from './components/HistorySummary';
44
import { HistoryExport } from './components/HistoryExport';
55
import { HistoryHandoff } from './components/HistoryHandoff';
6+
import { WorkspaceStatus } from './components/WorkspaceStatus';
67
import { useEffect, useState } from 'react';
78
import { PidexMark } from './components/PidexMark';
89
import welcomeMark from './assets/workbench/welcome-mark.svg';
@@ -388,6 +389,12 @@ function App() {
388389
</label>
389390
<span className="wb-meta">{ws.cwd}</span>
390391
</div>
392+
<WorkspaceStatus
393+
workspace={ws}
394+
details={details}
395+
ready={b.detailsRoot === ws.dirName}
396+
onReview={() => b.navigate('changes')}
397+
/>
391398
{composer()}
392399
<div className="wb-starters">
393400
<button
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import type { WorkspaceDetails, WorkspaceInfo } from '../api';
2+
import { BracketButton } from './BracketButton';
3+
4+
export function WorkspaceStatus({
5+
workspace,
6+
details,
7+
ready,
8+
onReview,
9+
}: {
10+
workspace: WorkspaceInfo;
11+
details: WorkspaceDetails;
12+
ready: boolean;
13+
onReview: () => void;
14+
}) {
15+
const unavailable = workspace.availability !== 'available';
16+
const changes = details.changes;
17+
const count = new Set(changes.map((change) => change.path)).size;
18+
const staged = changes.filter((change) => change.staged).length;
19+
const unstaged = changes.filter((change) => !change.staged && !change.untracked).length;
20+
const untracked = changes.filter((change) => change.untracked).length;
21+
const message = unavailable
22+
? 'Restore this folder to inspect Git changes.'
23+
: !ready
24+
? 'Checking Git changes…'
25+
: details.gitError
26+
? details.gitError
27+
: count
28+
? `${count} changed ${count === 1 ? 'file' : 'files'}`
29+
: 'No changes in this root';
30+
const inspected = !unavailable && ready && !details.gitError;
31+
32+
return (
33+
<section className="wb-workspace-status" aria-label="Workspace Git status">
34+
<div>
35+
<h3>Workspace changes</h3>
36+
<p role="status">{message}</p>
37+
{inspected && (
38+
<p className="wb-meta">
39+
{details.branch || 'Detached HEAD'} · {staged} staged · {unstaged} unstaged · {untracked} untracked
40+
</p>
41+
)}
42+
</div>
43+
<BracketButton disabled={!inspected} onClick={onReview}>
44+
Review workspace changes
45+
</BracketButton>
46+
</section>
47+
);
48+
}

‎src/renderer/useWorkbench.ts‎

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ export const DEFAULTS: Defaults = {
4242
thinking: 'medium',
4343
};
4444
const EMPTY_DETAILS: WorkspaceDetails = { branch: '', changes: [], files: [] };
45+
const UNAVAILABLE_DETAILS: WorkspaceDetails = {
46+
...EMPTY_DETAILS,
47+
gitError: 'Workspace inspection is unavailable. Return to this root to try again.',
48+
};
4549

4650
export function timeAgo(iso: string): string {
4751
if (!iso || !Number.isFinite(Date.parse(iso))) return 'local';
@@ -73,6 +77,7 @@ export function useWorkbench() {
7377
const generation = useRef(0);
7478
const [sessions, setSessions] = useState<SessionInfo[]>([]);
7579
const [details, setDetails] = useState(EMPTY_DETAILS);
80+
const [detailsRoot, setDetailsRoot] = useState('');
7681
const [view, setView] = useState<View>('new');
7782
const [tabs, setTabs] = useState<SessionTab[]>([]);
7883
const [activeId, setActiveId] = useState<string | null>(null);
@@ -186,6 +191,7 @@ export function useWorkbench() {
186191
useEffect(() => {
187192
let cancelled = false;
188193
setDetails(EMPTY_DETAILS);
194+
setDetailsRoot('');
189195
setSessions([]);
190196
setPreviewLoading(false);
191197
setModels([]);
@@ -222,10 +228,17 @@ export function useWorkbench() {
222228
api
223229
.inspectWorkspace(ws.cwd)
224230
.then((r) => {
225-
if (!cancelled) setDetails(unwrap(r));
231+
if (!cancelled) {
232+
setDetails(unwrap(r));
233+
setDetailsRoot(ws.dirName);
234+
}
226235
})
227236
.catch((error) => {
228-
if (!cancelled) report(error);
237+
if (!cancelled) {
238+
setDetails(UNAVAILABLE_DETAILS);
239+
setDetailsRoot(ws.dirName);
240+
report(error);
241+
}
229242
});
230243
api
231244
.models(ws.cwd)
@@ -262,9 +275,19 @@ export function useWorkbench() {
262275
if (currentCwd.current === ws.cwd && token === generation.current)
263276
setSessions(list);
264277
if (ws.availability !== 'available') return;
265-
const result = await api.inspectWorkspace(ws.cwd);
266-
if (currentCwd.current === ws.cwd && token === generation.current)
267-
setDetails(unwrap(result));
278+
try {
279+
const result = await api.inspectWorkspace(ws.cwd);
280+
if (currentCwd.current === ws.cwd && token === generation.current) {
281+
setDetails(unwrap(result));
282+
setDetailsRoot(ws.dirName);
283+
}
284+
} catch (error) {
285+
if (currentCwd.current === ws.cwd && token === generation.current) {
286+
setDetails(UNAVAILABLE_DETAILS);
287+
setDetailsRoot(ws.dirName);
288+
}
289+
throw error;
290+
}
268291
}, [api, ws]);
269292
useEffect(() => {
270293
if (!ws) return;
@@ -700,12 +723,15 @@ export function useWorkbench() {
700723
ws,
701724
sessions,
702725
details,
726+
detailsRoot,
703727
setDetails: (next: WorkspaceDetails) => {
704728
if (
705729
currentCwd.current === ws?.cwd &&
706730
generation.current === renderGeneration
707-
)
731+
) {
708732
setDetails(next);
733+
setDetailsRoot(ws?.dirName ?? '');
734+
}
709735
},
710736
view,
711737
navigate,

‎src/renderer/workbench.css‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,32 @@ html[data-reduced-motion='true'] .wb-shell *::after {
389389
gap: 16px;
390390
min-height: 80px;
391391
}
392+
.wb-workspace-status {
393+
display: flex;
394+
align-items: center;
395+
justify-content: space-between;
396+
gap: 12px;
397+
flex-wrap: wrap;
398+
padding: 16px;
399+
border: 1px solid var(--line);
400+
border-radius: 4px;
401+
}
402+
.wb-workspace-status h3 {
403+
margin: 0 0 6px;
404+
font-size: 13px;
405+
}
406+
.wb-workspace-status > div {
407+
flex: 1 1 300px;
408+
min-width: 0;
409+
overflow-wrap: anywhere;
410+
}
411+
.wb-workspace-status > button {
412+
max-width: 100%;
413+
white-space: normal;
414+
}
415+
.wb-workspace-status p {
416+
margin: 4px 0 0;
417+
}
392418
.wb-start-title > svg {
393419
flex-shrink: 0;
394420
}

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

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import { afterAll, beforeAll, describe, expect, inject, it } from 'vitest';
2+
import { _electron as electron, type ElectronApplication, type Page } from 'playwright-core';
3+
import { execFileSync } from 'node:child_process';
4+
import fs from 'node:fs/promises';
5+
import os from 'node:os';
6+
import path from 'node:path';
7+
8+
const ROOT = path.resolve(__dirname, '../..');
9+
let app: ElectronApplication;
10+
let page: Page;
11+
let fixture: string;
12+
let project: string;
13+
let clean: string;
14+
const errors: string[] = [];
15+
const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
16+
const status = () => page.getByRole('region', { name: 'Workspace Git status' });
17+
async function capture(name: string) {
18+
for (const directory of ['.tmp/proof', 'test-results/workspace-status']) {
19+
await fs.mkdir(path.join(ROOT, directory), { recursive: true });
20+
await page.screenshot({ path: path.join(ROOT, directory, name) });
21+
}
22+
}
23+
async function select(name: string) {
24+
await page.getByLabel('Workspace group').selectOption({ label: name });
25+
await page.getByRole('heading', { name: 'Start a session', exact: true }).waitFor();
26+
}
27+
28+
describe('workspace status in Electron', () => {
29+
beforeAll(async () => {
30+
fixture = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'pidex-status-')));
31+
project = path.join(fixture, 'project');
32+
clean = path.join(fixture, 'clean');
33+
const plain = path.join(fixture, 'plain');
34+
const userData = path.join(fixture, 'user-data');
35+
await Promise.all([project, clean, plain, userData].map((dir) => fs.mkdir(dir)));
36+
await fs.mkdir(path.join(fixture, 'sessions'));
37+
for (const cwd of [project, clean]) {
38+
git(cwd, 'init', '-b', 'main');
39+
await fs.writeFile(path.join(cwd, 'app.ts'), 'export const value = 1;\n');
40+
git(cwd, 'add', '.');
41+
git(cwd, '-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '-m', 'fixture');
42+
}
43+
git(project, 'switch', '-c', 'feature/workspace-status');
44+
await fs.writeFile(path.join(project, 'app.ts'), 'export const value = 2;\n');
45+
git(project, 'add', 'app.ts');
46+
await fs.writeFile(path.join(project, 'app.ts'), 'export const value = 3;\n');
47+
await fs.writeFile(path.join(project, 'notes.txt'), 'Review before starting Pi.\n');
48+
await fs.writeFile(path.join(userData, 'workspaces.json'), JSON.stringify([project, clean, plain, path.join(fixture, 'missing')]));
49+
app = await electron.launch({
50+
executablePath: require('electron'), args: ['.'], cwd: ROOT,
51+
env: {
52+
...process.env, NODE_ENV: 'development', PIDEX_E2E_CWD: project,
53+
PIDEX_E2E_RENDERER_URL: inject('rendererUrl'), PIDEX_E2E_USER_DATA: userData,
54+
PIDEX_SESSIONS_ROOT: path.join(fixture, 'sessions'),
55+
PIDEX_PI: path.join(ROOT, 'tests/fixtures/pi-rpc.cjs'),
56+
},
57+
});
58+
page = await app.firstWindow();
59+
page.on('pageerror', (error) => errors.push(error.message));
60+
await page.setViewportSize({ width: 1440, height: 1000 });
61+
await page.getByRole('heading', { name: 'Start a session', exact: true }).waitFor();
62+
await select('project');
63+
});
64+
afterAll(async () => {
65+
await app?.close();
66+
if (fixture) await fs.rm(fixture, { recursive: true, force: true });
67+
});
68+
69+
it('shows mixed Git changes before starting Pi and opens Changes without losing the task draft', async () => {
70+
await expect.poll(() => status().textContent()).toContain('2 changed files');
71+
expect(await status().textContent()).toContain('feature/workspace-status · 1 staged · 1 unstaged · 1 untracked');
72+
await page.getByLabel('Message pi').fill('Review the existing changes before editing.');
73+
await page.evaluate(() => document.fonts.ready);
74+
await capture('workspace-status.png');
75+
await page.setViewportSize({ width: 760, height: 900 });
76+
await status().scrollIntoViewIfNeeded();
77+
const bounds = await status().boundingBox();
78+
const button = await status().getByRole('button').boundingBox();
79+
if (!bounds || !button) throw new Error('Workspace status is not visible.');
80+
expect(button.x + button.width).toBeLessThanOrEqual(bounds.x + bounds.width);
81+
await capture('workspace-status-narrow.png');
82+
await page.setViewportSize({ width: 1440, height: 1000 });
83+
await status().getByRole('button', { name: 'Review workspace changes' }).click();
84+
await page.getByRole('heading', { name: 'Changes review', exact: true }).waitFor();
85+
expect(await page.getByLabel('Message pi').inputValue()).toBe('Review the existing changes before editing.');
86+
await page.getByLabel('Commit message').waitFor();
87+
await page.getByRole('button', { name: 'New session', exact: true }).click();
88+
expect(await page.getByLabel('Message pi').inputValue()).toBe('Review the existing changes before editing.');
89+
expect(await page.locator('.wb-sidebar .wb-session-item').filter({ hasText: 'this window' }).count()).toBe(0);
90+
});
91+
92+
it('refreshes changed counts on focus and keeps clean and detached roots distinct', async () => {
93+
await fs.unlink(path.join(project, 'notes.txt'));
94+
git(project, 'add', 'app.ts');
95+
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
96+
await expect.poll(() => status().textContent()).toContain('1 changed file');
97+
expect(await status().textContent()).toContain('1 staged · 0 unstaged · 0 untracked');
98+
await select('clean');
99+
await expect.poll(() => status().textContent()).toContain('No changes in this root');
100+
expect(await status().textContent()).toContain('main · 0 staged · 0 unstaged · 0 untracked');
101+
git(clean, 'checkout', '--detach');
102+
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
103+
await expect.poll(() => status().textContent()).toContain('Detached HEAD');
104+
expect(await status().textContent()).not.toContain('feature/workspace-status');
105+
});
106+
107+
it('does not describe non-Git folders or missing roots as clean', async () => {
108+
await select('plain');
109+
await expect.poll(() => status().textContent()).toContain('Git changes are unavailable for this folder.');
110+
expect(await status().getByRole('button').isDisabled()).toBe(true);
111+
await select('missing');
112+
await expect.poll(() => status().textContent()).toContain('Restore this folder to inspect Git changes.');
113+
expect(await status().getByRole('button').isDisabled()).toBe(true);
114+
expect(await status().textContent()).not.toContain('No changes in this root');
115+
expect(errors).toEqual([]);
116+
});
117+
});
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { afterEach, describe, expect, it, vi } from 'vitest';
2+
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
3+
import { WorkspaceStatus } from '../../src/renderer/components/WorkspaceStatus';
4+
import type { GitChange, WorkspaceDetails, WorkspaceInfo } from '../../src/renderer/api';
5+
6+
const workspace: WorkspaceInfo = {
7+
dirName: 'api', name: 'api', cwd: '/repo/api', branch: 'old-branch',
8+
availability: 'available', sessionCount: 0, lastActive: '',
9+
};
10+
const details: WorkspaceDetails = { branch: 'feature/status', changes: [], files: [] };
11+
const change: GitChange = {
12+
path: 'app.ts', additions: 1, deletions: 1, staged: false, untracked: false,
13+
};
14+
afterEach(cleanup);
15+
16+
describe('workspace Git status', () => {
17+
it('counts a partially staged file once overall and in both change groups', () => {
18+
const onReview = vi.fn();
19+
render(<WorkspaceStatus workspace={workspace} ready details={{
20+
...details,
21+
changes: [change, { ...change, staged: true }, { ...change, path: 'new.ts', untracked: true }],
22+
}} onReview={onReview} />);
23+
expect(screen.getByRole('status')).toHaveTextContent('2 changed files');
24+
expect(screen.getByText('feature/status · 1 staged · 1 unstaged · 1 untracked')).toBeVisible();
25+
fireEvent.click(screen.getByRole('button', { name: 'Review workspace changes' }));
26+
expect(onReview).toHaveBeenCalledOnce();
27+
});
28+
29+
it('shows a clean root only after inspection and explains detached HEAD', () => {
30+
const { rerender } = render(<WorkspaceStatus workspace={workspace} details={details} ready onReview={vi.fn()} />);
31+
expect(screen.getByRole('status')).toHaveTextContent('No changes in this root');
32+
expect(screen.getByRole('button')).toBeEnabled();
33+
rerender(<WorkspaceStatus workspace={workspace} details={{ ...details, branch: '', changes: [change] }} ready onReview={vi.fn()} />);
34+
expect(screen.getByRole('status')).toHaveTextContent('1 changed file');
35+
expect(screen.getByText('Detached HEAD · 0 staged · 1 unstaged · 0 untracked')).toBeVisible();
36+
});
37+
38+
it.each([
39+
{ ready: false, availability: 'available' as const, gitError: undefined, message: 'Checking Git changes…' },
40+
{ ready: true, availability: 'missing' as const, gitError: undefined, message: 'Restore this folder to inspect Git changes.' },
41+
{ ready: true, availability: 'unavailable' as const, gitError: undefined, message: 'Restore this folder to inspect Git changes.' },
42+
{ ready: true, availability: 'available' as const, gitError: 'Git changes are unavailable for this folder.', message: 'Git changes are unavailable for this folder.' },
43+
])('does not claim a clean root when $message', ({ ready, availability, gitError, message }) => {
44+
render(<WorkspaceStatus workspace={{ ...workspace, availability }} details={{ ...details, gitError }} ready={ready} onReview={vi.fn()} />);
45+
expect(screen.getByRole('status')).toHaveTextContent(message);
46+
expect(screen.getByRole('button')).toBeDisabled();
47+
expect(screen.queryByText('No changes in this root')).not.toBeInTheDocument();
48+
expect(screen.queryByText(/old-branch|feature\/status/)).not.toBeInTheDocument();
49+
});
50+
});

0 commit comments

Comments
 (0)