Skip to content
Merged
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: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ The new-session view offers the current root's recent saved conversations above

Use **Create workspace** or **Edit workspace** in the sidebar to name a group and select its roots. **Add root** chooses an existing folder. Each session runs in one root; the composer shows its path. Switching roots leaves open sessions running and makes them available under **Open sessions**. Files, Changes, History and defaults remain scoped to the selected root. A missing folder retains readable history, but cannot start or resume Pi until its original path is available. Adding another folder does not relocate a session. Group membership does not change Pi's tool permissions or load sibling roots into its context.

Open sessions shows **Unread activity** when a turn finishes or Pi exits while its transcript is out of view. Opening that session clears the marker, including when returning to a root restores its transcript. The marker tracks activity within this app window and does not persist after quitting.

Existing `workspaces.json` and `session-defaults.json` records migrate to `workspace-registry.json` in Electron userData. Original files and `.bak` copies remain intact. Workspace groups and selection persist; live processes and drafts do not restart after app quit. A package folder shares its Git worktree's index: pidex refuses its commit when staged changes exist outside that folder. Open the repository top level to review the whole index.

Active sessions and history use a virtualized transcript. A local development benchmark with 4,500 mixed entries opened in about 1.4 seconds, down from 8.3 seconds, and mounted fewer than 100 transcript DOM nodes instead of 39,000. Timings vary by machine and load; see [ADR 0011](docs/adr/0011-virtualized-transcript.md) for the method and limits.
Expand Down
2 changes: 2 additions & 0 deletions docs/pidex-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ New sessions start a Pi subprocess in the selected root and apply its saved mode

Groups organize roots for navigation. Switching group/root leaves processes running and restores the target root's view and drafts. A launch finishing after navigation becomes a background tab; its original unsent prompt is not submitted elsewhere. Open sessions are reachable across groups. Late root requests cannot replace another root's files/defaults/history. No simultaneous multi-cwd execution or sibling instruction loading is added.

Each open tab tracks unread activity in memory. A running-to-idle transition or first runtime exit marks the tab unread when its transcript is not the current view. Opening the transcript acknowledges it; repeated end/exit events do not create another marker. This tracks navigation inside the window, without OS focus detection or desktop notifications.

Main requests `get_state`, `get_messages`, and available commands. The renderer converts the returned messages into user, assistant, and tool entries. Subsequent Pi events arrive through `pidex:session:event`; `timeline.ts` applies text/thinking deltas and tool start/update/end events. Main forwards the RPC events rather than translating them into a second event protocol.

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.
Expand Down
6 changes: 6 additions & 0 deletions src/renderer/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,15 @@ function App() {
type="button"
className={`wb-session-item${active?.runtimeId === t.runtimeId && view === 'session' ? ' is-active' : ''}`}
title={t.cwd}
aria-current={active?.runtimeId === t.runtimeId && view === 'session' ? 'page' : undefined}
onClick={() => b.activateTab(t)}
>
<span>{t.title}</span>
{t.unread && (
<small className="wb-session-unread" title="Open this session to read its latest activity.">
Unread activity
</small>
)}
<small>
{t.exited ? 'Exited' : t.running ? 'Running' : 'Ready'} /
this window
Expand Down
22 changes: 22 additions & 0 deletions src/renderer/useWorkbench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type SessionTab = {
commands: SlashCommand[];
running: boolean;
exited: boolean;
unread: boolean;
};
type Preview = {
info: SessionInfo;
Expand Down Expand Up @@ -100,6 +101,9 @@ export function useWorkbench() {
const ws = workspaces.find((w) => w.dirName === selected);
const active =
tabs.find((t) => t.runtimeId === activeId && t.cwd === ws?.cwd) ?? null;
const visibleSessionId = view === 'session' ? active?.runtimeId : undefined;
const visibleSession = useRef(visibleSessionId);
visibleSession.current = visibleSessionId;
const draftKey =
view === 'history'
? `preview:${preview?.info.file ?? ''}:${preview?.entryId ?? ''}`
Expand Down Expand Up @@ -155,6 +159,7 @@ export function useWorkbench() {
useEffect(() => {
if (!api) return;
const offEvent = api.onSessionEvent(({ sessionId, event }) => {
const visible = visibleSession.current;
setTabs((prev) =>
prev.map((tab) => {
if (tab.runtimeId !== sessionId) return tab;
Expand All @@ -163,11 +168,15 @@ export function useWorkbench() {
...tab,
entries: next.entries,
running: next.running ?? tab.running,
unread: tab.runtimeId === visible
? false
: tab.unread || (tab.running && next.running === false),
};
}),
);
});
const offExit = api.onSessionExit(({ sessionId }) => {
const visible = visibleSession.current;
exitedSessions.current.add(sessionId);
setTabs((prev) =>
prev.map((tab) =>
Expand All @@ -177,6 +186,9 @@ export function useWorkbench() {
entries: applyEvent(tab.entries, { type: 'agent_end' }).entries,
running: false,
exited: true,
unread: tab.runtimeId === visible
? false
: tab.unread || !tab.exited,
}
: tab,
),
Expand All @@ -188,6 +200,15 @@ export function useWorkbench() {
};
}, [api]);

useEffect(() => {
if (!visibleSessionId) return;
setTabs((prev) => prev.map((tab) =>
tab.runtimeId === visibleSessionId && tab.unread
? { ...tab, unread: false }
: tab,
));
}, [visibleSessionId]);

useEffect(() => {
let cancelled = false;
setDetails(EMPTY_DETAILS);
Expand Down Expand Up @@ -450,6 +471,7 @@ export function useWorkbench() {
commands: [],
running: Boolean(result.state?.isStreaming),
exited: exitedSessions.current.has(id),
unread: false,
};
setTabs((prev) =>
prev.some((t) => t.runtimeId === id)
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/workbench.css
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,9 @@ html[data-reduced-motion='true'] .wb-shell *::after {
font-size: 12px;
line-height: 18px;
}
.wb-session-item small.wb-session-unread {
color: var(--accent);
}
.wb-connection {
color: var(--copy);
white-space: nowrap;
Expand Down
126 changes: 126 additions & 0 deletions tests/e2e/session-activity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { afterAll, beforeAll, describe, expect, inject, it } from 'vitest';
import { _electron as electron, type ElectronApplication, type Page } from 'playwright-core';
import { execFileSync } from 'node:child_process';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

const ROOT = path.resolve(__dirname, '../..');
let app: ElectronApplication;
let page: Page;
let fixture: string;
let rpcLog: string;
const errors: string[] = [];
const task = 'Review API changes';
const session = () => page.locator('.wb-sidebar .wb-session-item')
.filter({ hasText: 'this window' }).filter({ hasText: task });
async function resize(width: number, height: number) {
const window = await app.browserWindow(page);
await window.evaluate((window, size) => window.setContentSize(size.width, size.height), { width, height });
const [actualWidth, actualHeight] = await window.evaluate((window) => window.getContentSize());
await page.waitForFunction(({ width, height }) => innerWidth === width && innerHeight === height,
{ width: actualWidth, height: actualHeight });
}
async function capture(name: string) {
for (const directory of ['.tmp/proof', 'test-results/session-activity']) {
await fs.mkdir(path.join(ROOT, directory), { recursive: true });
await page.screenshot({ scale: 'css', path: path.join(ROOT, directory, name) });
}
}
async function prompts() {
const text = await fs.readFile(rpcLog, 'utf8');
return text.split('\n').filter(Boolean).map((line) => JSON.parse(line))
.filter((record) => record.type === 'prompt');
}

describe('background session activity in Electron', () => {
beforeAll(async () => {
fixture = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'pidex-activity-')));
const api = path.join(fixture, 'api');
const web = path.join(fixture, 'web');
const userData = path.join(fixture, 'user-data');
const sessions = path.join(fixture, 'sessions');
rpcLog = path.join(fixture, 'rpc.jsonl');
await Promise.all([api, web, userData, sessions].map((dir) => fs.mkdir(dir)));
for (const cwd of [api, web]) {
const git = (...args: string[]) => execFileSync('git', args, { cwd, stdio: 'pipe' });
git('init', '-b', 'main');
await fs.writeFile(path.join(cwd, 'app.ts'), 'export const ready = true;\n');
git('add', '.');
git('-c', 'user.name=Test', '-c', 'user.email=test@example.test', '-c', 'commit.gpgsign=false', 'commit', '-m', 'Prepare workspace');
}
await fs.writeFile(path.join(userData, 'workspaces.json'), JSON.stringify([api, web]));
app = await electron.launch({
executablePath: require('electron'), args: ['.'], cwd: ROOT,
env: {
...process.env, NODE_ENV: 'development', PIDEX_E2E_CWD: api,
PIDEX_E2E_RENDERER_URL: inject('rendererUrl'), PIDEX_E2E_USER_DATA: userData,
PIDEX_SESSIONS_ROOT: sessions, PIDEX_RPC_LOG: rpcLog,
PIDEX_PI: path.join(ROOT, 'tests/fixtures/pi-rpc.cjs'),
},
});
page = await app.firstWindow();
page.on('pageerror', (error) => errors.push(error.message));
await resize(1280, 840);
await page.getByRole('heading', { name: 'Start a session', exact: true }).waitFor();
await page.getByLabel('Workspace group').selectOption({ label: 'api' });
await page.evaluate(() => document.fonts.ready);
});
afterAll(async () => {
await app?.close();
if (fixture) await fs.rm(fixture, { recursive: true, force: true });
});

it('marks a completion in another root and acknowledges it on opening at native window sizes', async () => {
await page.getByLabel('Message pi').fill(task);
await page.getByRole('button', { name: 'Send', exact: true }).click();
await page.getByRole('button', { name: 'Stop', exact: true }).waitFor();
expect(await session().locator('.wb-session-unread').count()).toBe(0);
await page.getByLabel('Workspace group').selectOption({ label: 'web' });
await session().getByText('Unread activity', { exact: true }).waitFor();
expect(await session().textContent()).toContain('Ready');
expect(await page.getByLabel('Workspace group').locator('option:checked').textContent()).toBe('web');
await session().scrollIntoViewIfNeeded();
await capture('background-completion.png');
await resize(900, 600);
const unread = session().getByText('Unread activity', { exact: true });
await unread.scrollIntoViewIfNeeded();
const bounds = await unread.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);
await capture('background-completion-minimum.png');
const before = await prompts();
await session().focus();
await page.keyboard.press('Enter');
await page.getByRole('heading', { name: task, exact: true }).waitFor();
await expect.poll(() => session().locator('.wb-session-unread').count()).toBe(0);
expect(await session().getAttribute('aria-current')).toBe('page');
expect(await page.getByLabel('Workspace group').locator('option:checked').textContent()).toBe('api');
expect(await prompts()).toEqual(before);
await capture('acknowledged-completion-minimum.png');
await resize(1280, 840);
await capture('acknowledged-completion.png');
expect(errors).toEqual([]);
});

it('marks a runtime exit while Changes is open and preserves the exited transcript on acknowledgement', async () => {
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)!;
process.kill(runtime.runtimePid, 'SIGTERM');
await session().getByText('Unread activity', { exact: true }).waitFor();
expect(await session().textContent()).toContain('Exited');
await session().scrollIntoViewIfNeeded();
await capture('background-exit.png');
await session().click();
await page.getByRole('heading', { name: task, exact: true }).waitFor();
await expect.poll(() => session().locator('.wb-session-unread').count()).toBe(0);
expect(await session().textContent()).toContain('Exited');
expect(await prompts()).toHaveLength(1);
expect(errors).toEqual([]);
});
});
Loading
Loading