Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/pidex-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Main requests `get_state`, `get_messages`, and available commands. The renderer

Pi requests carry IDs and have 30-second timeouts. Stdout is split on newline only. A missing executable produces an error in the window; `PIDEX_PI` can select an absolute executable path. Discovery also checks common Bun, Homebrew, mise, and PATH directories.

Closing a session terminates its process. Window closure and app shutdown dispose of all active processes. Process exits are reported to the renderer. The UI remains available, but automatic process restart is not implemented.
Closing a session terminates its process. Window closure and app shutdown dispose of all active processes. Process exits are reported to the renderer. An exited transcript keeps its unsent draft and offers a read-only preview of its exact saved archive before explicit resume or fork. Recovery refreshes archive metadata and reports missing history without choosing another conversation. The UI remains available, but automatic process restart is not implemented.

## IPC

Expand Down
20 changes: 19 additions & 1 deletion src/renderer/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -477,9 +477,27 @@ function App() {
</EmptyState>
)}
</Transcript>
{active.exited && (
<section className="wb-exited-recovery" aria-label="Session recovery">
<p className="wb-meta">
{active.file
? 'Pi exited. Preview saved history to resume or fork. This tab keeps your transcript and unsent draft.'
: 'Pi exited without providing a saved archive. Your transcript and unsent draft remain in this tab.'}
</p>
{active.file && (
<BracketButton
primary
disabled={b.busy}
onClick={() => void b.previewExitedSession()}
>
Preview saved session
</BracketButton>
)}
</section>
)}
{composer(
active.exited
? 'Session exited. Start a new session to continue.'
? 'Session exited. Your unsent draft is kept here.'
: active.running
? 'Add a follow-up while pi works…'
: 'Continue this session…',
Expand Down
26 changes: 26 additions & 0 deletions src/renderer/useWorkbench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export function useWorkbench() {
const currentCwd = useRef('');
const previewSeq = useRef(0);
const opening = useRef(false);
const recovering = useRef(false);
const sending = useRef(false);
const exitedSessions = useRef(new Set<string>());
const ws = workspaces.find((w) => w.dirName === selected);
Expand Down Expand Up @@ -561,6 +562,30 @@ export function useWorkbench() {
navigate('history');
return showPreview(info);
};
const previewExitedSession = async () => {
if (
view !== 'session' || !active?.exited || !active.file || !ws ||
busy || opening.current || recovering.current
) return;
const token = generation.current;
recovering.current = true;
setBusy(true);
setError('');
try {
const list = await api.sessions(ws.dirName);
if (token !== generation.current) return;
setSessions(list);
const saved = list.find((info) => info.file === active.file && info.cwd === active.cwd);
if (!saved)
throw new Error('The saved archive for this exited session could not be found. Its transcript and unsent draft are still available in this tab.');
await previewSavedSession(saved);
} catch (error) {
if (token === generation.current) report(error);
} finally {
recovering.current = false;
setBusy(false);
}
};
useEffect(() => {
if (view !== 'history' || previewLoading) return;
if (preview && !preview.loaded)
Expand Down Expand Up @@ -802,6 +827,7 @@ export function useWorkbench() {
selectWorkspace,
addWorkspace,
previewSavedSession,
previewExitedSession,
closeSession,
forkSession,
prepareHandoff,
Expand Down
14 changes: 14 additions & 0 deletions src/renderer/workbench.css
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,20 @@ html[data-reduced-motion='true'] .wb-shell *::after {
min-height: 0;
min-width: 0;
}
.wb-exited-recovery {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
flex-shrink: 0;
padding: 10px;
border: 1px solid var(--line);
border-radius: 4px;
}
.wb-exited-recovery p {
flex: 1 1 220px;
margin: 0;
}
.wb-transcript {
display: flex;
flex: 1;
Expand Down
77 changes: 77 additions & 0 deletions tests/e2e/session-activity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
});

it('marks a runtime exit while Changes is open and preserves the exited transcript on acknowledgement', async () => {
await page.getByLabel('Message pi').fill('Keep my unsent recovery draft');
await page.getByRole('button', { name: /^Changes/ }).click();
// Terminate only the deterministic subprocess created by this test.
const runtime = (await prompts()).find((record) => record.message === task)!;
Expand All @@ -123,4 +124,80 @@
expect(await prompts()).toHaveLength(1);
expect(errors).toEqual([]);
});

it('previews the exited archive at native desktop and minimum sizes without relaunching Pi', async () => {
const runtime = (await prompts())[0];
const original = await fs.readFile(runtime.sessionFile, 'utf8');
const preview = page.getByRole('button', { name: 'Preview saved session', exact: true });
await preview.waitFor();
await capture('exited-session-recovery.png');
await resize(900, 600);
const bounds = await preview.boundingBox();
const viewport = await page.evaluate(() => ({ width: innerWidth, height: innerHeight }));
expect(bounds).not.toBeNull();
expect(bounds!.x).toBeGreaterThanOrEqual(0);
expect(bounds!.y).toBeGreaterThanOrEqual(0);
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(viewport.width);
expect(bounds!.y + bounds!.height).toBeLessThanOrEqual(viewport.height);
expect((await page.locator('.wb-transcript').boundingBox())!.height).toBeGreaterThan(60);
expect(await page.getByLabel('Message pi').isDisabled()).toBe(true);
expect(await page.getByLabel('Message pi').inputValue()).toBe('Keep my unsent recovery draft');
await capture('exited-session-recovery-minimum.png');
await preview.focus();
await page.keyboard.press('Enter');
await page.getByRole('button', { name: 'Resume', exact: true }).waitFor();
await page.locator('.wb-transcript').getByText(task, { exact: true }).waitFor();
expect(await page.getByLabel('Message pi').inputValue()).toBe('');
expect(await fs.readFile(runtime.sessionFile, 'utf8')).toBe(original);
expect(await prompts()).toHaveLength(1);
const records = (await fs.readFile(rpcLog, 'utf8')).split('\n').filter(Boolean).map((line) => JSON.parse(line));
expect(new Set(records.map((record) => record.runtimePid)).size).toBe(1);

Check failure on line 154 in tests/e2e/session-activity.test.ts

View workflow job for this annotation

GitHub Actions / electron e2e

[e2e] tests/e2e/session-activity.test.ts > background session activity in Electron > previews the exited archive at native desktop and minimum sizes without relaunching Pi

AssertionError: expected 3 to be 1 // Object.is equality - Expected + Received - 1 + 3 ❯ tests/e2e/session-activity.test.ts:154:70
await capture('exited-session-saved-preview-minimum.png');
await session().click();
await page.getByRole('region', { name: 'Session recovery' }).waitFor();
expect(await page.getByLabel('Message pi').inputValue()).toBe('Keep my unsent recovery draft');
await resize(1280, 840);
expect(errors).toEqual([]);
});

it('reports a missing exited archive without previewing unrelated saved history', async () => {
const runtime = (await prompts())[0];
const original = await fs.readFile(runtime.sessionFile, 'utf8');
const unrelated = path.join(path.dirname(runtime.sessionFile), 'unrelated.jsonl');
await fs.writeFile(unrelated, original.replaceAll(task, 'Unrelated saved task'));
await fs.unlink(runtime.sessionFile);
try {
await page.getByRole('button', { name: 'Preview saved session', exact: true }).click();

Check failure on line 170 in tests/e2e/session-activity.test.ts

View workflow job for this annotation

GitHub Actions / electron e2e

[e2e] tests/e2e/session-activity.test.ts > background session activity in Electron > reports a missing exited archive without previewing unrelated saved history

TimeoutError: locator.click: Timeout 30000ms exceeded. Call log: - waiting for getByRole('button', { name: 'Preview saved session', exact: true }) ❯ tests/e2e/session-activity.test.ts:170:86 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Serialized Error: { log: [ ' - waiting for getByRole(\'button\', { name: \'Preview saved session\', exact: true })' ] }
await page.getByRole('alert').getByText('The saved archive for this exited session could not be found.', { exact: false }).waitFor();
expect(await page.getByRole('region', { name: 'Session recovery' }).isVisible()).toBe(true);
expect(await page.getByLabel('Message pi').inputValue()).toBe('Keep my unsent recovery draft');
expect(await page.locator('.wb-transcript').textContent()).not.toContain('Unrelated saved task');
expect(await prompts()).toHaveLength(1);
await capture('exited-session-missing-archive.png');
} finally {
await fs.writeFile(runtime.sessionFile, original);
await fs.unlink(unrelated);
}
expect(errors).toEqual([]);
});

it('resumes the exact exited archive only after explicit continuation', async () => {
const runtime = (await prompts())[0];
await page.getByRole('button', { name: 'Preview saved session', exact: true }).click();

Check failure on line 186 in tests/e2e/session-activity.test.ts

View workflow job for this annotation

GitHub Actions / electron e2e

[e2e] tests/e2e/session-activity.test.ts > background session activity in Electron > resumes the exact exited archive only after explicit continuation

TimeoutError: locator.click: Timeout 30000ms exceeded. Call log: - waiting for getByRole('button', { name: 'Preview saved session', exact: true }) ❯ tests/e2e/session-activity.test.ts:186:84 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Serialized Error: { log: [ ' - waiting for getByRole(\'button\', { name: \'Preview saved session\', exact: true })' ] }
await page.getByRole('button', { name: 'Resume', exact: true }).waitFor();
await page.getByLabel('Message pi').fill('Continue the recovered API task');
await capture('exited-session-saved-preview.png');
await page.getByRole('button', { name: 'Resume', exact: true }).click();
await page.getByRole('button', { name: 'Stop', exact: true }).waitFor();
await expect.poll(async () => (await prompts()).length).toBe(2);
const continued = (await prompts())[1];
expect(continued).toMatchObject({
message: 'Continue the recovered API task', cwd: runtime.cwd, sessionFile: runtime.sessionFile,
});
expect(continued.runtimePid).not.toBe(runtime.runtimePid);
await page.getByRole('button', { name: 'Stop', exact: true }).click();
await session().filter({ hasText: 'Exited' }).click();
expect(await page.getByLabel('Message pi').inputValue()).toBe('Keep my unsent recovery draft');
expect(errors).toEqual([]);
});
});
95 changes: 95 additions & 0 deletions tests/integration/useWorkbench.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,101 @@ afterEach(() => {
vi.unstubAllGlobals();
});

describe('exited session recovery', () => {
const source = {
cwd: '/code/api', id: 'saved', file: '/sessions/exited.jsonl',
title: 'Saved task', model: '', timestamp: '', messageCount: 1,
};
async function exitedFixture(file: string | undefined = source.file) {
const fixture = Object.assign(apiFixture(), {
openSession: vi.fn<PidexApi['openSession']>().mockResolvedValue({
sessionId: 'runtime', state: { sessionFile: file },
}),
sessionCommands: vi.fn().mockResolvedValue({ commands: [] }),
sendPrompt: vi.fn().mockResolvedValue({ success: true }),
});
fixture.sessionTree.mockResolvedValue({ data: { leafId: 'latest', canContinue: true, nodes: [] } });
fixture.previewSession.mockResolvedValue({ data: [
{ role: 'user', content: [{ type: 'text', text: 'Saved request' }] },
] });
const hook = renderHook(useWorkbench);
await waitFor(() => expect(hook.result.current.detailsRoot).toBe('api'));
await act(async () => { await hook.result.current.send('Original task'); });
await waitFor(() => expect(hook.result.current.busy).toBe(false));
act(() => {
hook.result.current.onDraft('Keep this unsent follow-up');
fixture.onSessionExit.mock.calls[0][0]({ sessionId: 'runtime' });
});
await waitFor(() => expect(hook.result.current.tabs[0].exited).toBe(true));
// Let the exit-triggered workspace refresh settle before arranging lookup results.
await act(async () => {});
return { ...hook, fixture };
}

it('refreshes and previews only the exited archive without starting Pi or losing drafts', async () => {
const { result, fixture } = await exitedFixture();
fixture.sessions.mockResolvedValue([{ ...source, file: '/sessions/unrelated.jsonl' }, source]);
await act(async () => { await result.current.previewExitedSession(); });
expect(result.current.view).toBe('history');
expect(result.current.preview).toMatchObject({ info: source, entryId: 'latest', ready: true });
expect(fixture.sessionTree).toHaveBeenCalledExactlyOnceWith(source.file);
expect(fixture.previewSession).toHaveBeenCalledExactlyOnceWith(source.file, 'latest');
expect(fixture.openSession).toHaveBeenCalledTimes(1);
expect(fixture.sendPrompt).toHaveBeenCalledTimes(1);
act(() => result.current.onDraft('Separate saved-history draft'));
act(() => result.current.activateTab(result.current.tabs[0]));
expect(result.current.draft).toBe('Keep this unsent follow-up');
await act(async () => { await result.current.previewExitedSession(); });
expect(result.current.draft).toBe('Separate saved-history draft');
});

it.each(['missing', 'wrong root', 'failed lookup', 'unreadable'])(
'keeps the transcript and draft when the saved archive is %s', async (kind) => {
const { result, fixture } = await exitedFixture();
if (kind === 'failed lookup') fixture.sessions.mockRejectedValue(new Error('History unavailable'));
else fixture.sessions.mockResolvedValue(kind === 'missing'
? [{ ...source, file: '/sessions/unrelated.jsonl' }]
: [{ ...source, cwd: kind === 'wrong root' ? '/code/web' : source.cwd }]);
if (kind === 'unreadable') fixture.sessionTree.mockResolvedValue({ error: 'Archive unreadable' });
await act(async () => { await result.current.previewExitedSession(); });
expect(result.current.error).toContain(kind === 'failed lookup' ? 'History unavailable'
: kind === 'unreadable' ? 'Archive unreadable' : 'could not be found');
expect(result.current.preview?.ready).not.toBe(true);
act(() => result.current.activateTab(result.current.tabs[0]));
expect(result.current.draft).toBe('Keep this unsent follow-up');
expect(result.current.active?.entries).toContainEqual(expect.objectContaining({ kind: 'user', text: 'Original task' }));
expect(result.current.busy).toBe(false);
expect(fixture.openSession).toHaveBeenCalledTimes(1);
expect(fixture.sendPrompt).toHaveBeenCalledTimes(1);
},
);

it.each(['root', 'view', 'tab'])('ignores delayed recovery after switching %s', async (destination) => {
const { result, fixture } = await exitedFixture();
const pending = deferred<Awaited<ReturnType<PidexApi['sessions']>>>();
fixture.sessions.mockReturnValueOnce(pending.promise);
let lookup!: Promise<void>;
act(() => { lookup = result.current.previewExitedSession(); });
if (destination === 'root') act(() => result.current.selectWorkspace(catalog.roots[1]));
else if (destination === 'view') act(() => result.current.navigate('changes'));
else act(() => result.current.activateTab(result.current.tabs[0]));
await act(async () => { pending.resolve([source]); await lookup; });
expect(result.current.view).toBe(destination === 'root' ? 'new' : destination === 'view' ? 'changes' : 'session');
expect(result.current.error).toBe('');
expect(fixture.sessionTree).not.toHaveBeenCalled();
expect(result.current.busy).toBe(false);
});

it('does not guess an archive when Pi provided no path', async () => {
const { result, fixture } = await exitedFixture('');
fixture.sessions.mockClear().mockResolvedValue([source]);
await act(async () => { await result.current.previewExitedSession(); });
expect(fixture.sessions).not.toHaveBeenCalled();
expect(result.current.view).toBe('session');
expect(fixture.sessionTree).not.toHaveBeenCalled();
});
});

describe('unread session activity', () => {
function runtimeFixture() {
const fixture = apiFixture();
Expand Down
Loading