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 docs/pidex-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ Pi session archives live under `~/.pi/agent/sessions`. pidex discovers workspace

History preview follows the selected archive parent chain so abandoned branches are not mixed into the displayed conversation. A collapsible recovery summary derives counts and bounded request/reply excerpts from those same entries, using the tool-card outcome rules shared with Markdown export. It describes saved history and does not infer completion or current filesystem state. Archive metadata scans read a bounded prefix, so displayed message counts and model metadata can be incomplete for large sessions. The full active branch is read separately for preview.

Copied context, Markdown exports and handoff drafts record the Pi session ID, source archive path, selected entry and archive tip at export time. Continuation guidance distinguishes the tip from an earlier selection requiring a fork; readable history that cannot continue receives context-only recovery guidance. These identifiers describe a snapshot and do not guarantee that an archive still exists or remains unchanged.

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.

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.
Expand Down
7 changes: 7 additions & 0 deletions src/renderer/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ function App() {
cwd: preview.info.cwd,
model: preview.info.model,
entries: preview.entries,
source: {
sessionId: preview.info.id,
archivePath: preview.info.file,
entryId: preview.entryId ?? null,
archiveTipId: preview.tree?.leafId ?? null,
canContinue: !!preview.tree?.canContinue,
},
}
: null;

Expand Down
48 changes: 45 additions & 3 deletions src/renderer/export-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,40 @@ export type SessionExportInput = {
model: string;
exportedAt: Date;
entries: Entry[];
source?: {
sessionId: string;
archivePath: string;
entryId: string | null;
archiveTipId: string | null;
canContinue: boolean;
};
};

function inlineCode(text: string): string {
const runs = text.match(/`+/g) ?? [];
const fence = '`'.repeat(runs.reduce((max, run) => Math.max(max, run.length), 0) + 1);
const value = text.replace(/[\r\n]+/g, ' ');
const pad = value.startsWith('`') || value.endsWith('`') ? ' ' : '';
return `${fence}${pad}${value}${pad}${fence}`;
}

function sourceSection(source: NonNullable<SessionExportInput['source']>): string {
return [
'## Saved selection',
'',
`- Pi session ${inlineCode(source.sessionId)}.`,
`- Source archive ${inlineCode(source.archivePath)}.`,
source.entryId
? `- Selected entry ${inlineCode(source.entryId)}${source.entryId === source.archiveTipId ? ' (archive tip)' : ''}.`
: '- This archive has no selected conversation entry.',
source.archiveTipId
? `- Archive tip at export ${inlineCode(source.archiveTipId)}.`
: '- This archive has no conversation tip.',
'',
'These identifiers describe the saved selection at export time. The archive may change before you return.',
].join('\n');
}

function fenced(text: string): string {
let longest = 0;
let run = 0;
Expand All @@ -27,17 +59,26 @@ function toolHeading(entry: Extract<Entry, { kind: 'tool' }>): string {
return `## ${entry.tool}${summary} (${toolStatus(entry)})`;
}

function handoffSection(cwd: string): string {
function handoffSection(cwd: string, source: SessionExportInput['source']): string {
const folder = cwd.trim();
const sameFolder = folder
? `Same folder (\`${folder}\`): open that root in Pidex, go to Sessions, select this session, and choose Resume. Choose Resume in new fork when continuing from an earlier entry.`
: 'Same folder: open the original root in Pidex, go to Sessions, select this session, and choose Resume. Choose Resume in new fork when continuing from an earlier entry.';
let continuation = sameFolder;
if (source) {
if (!source.canContinue || !source.entryId) {
continuation = 'This history was readable, but Pidex could not validate it for continuation. Use this file as context in a new session, or repair the original archive in Pi before trying to resume.';
} else {
const action = source.entryId === source.archiveTipId ? 'Resume' : 'Resume in new fork';
continuation = `To continue this exact selection, open the original root in Pidex, go to Sessions, find the source archive above, select entry ${inlineCode(source.entryId)}, and choose ${action}. If the archive has advanced, continuing this entry creates a new fork and preserves the source.`;
}
}
return [
'## Continue elsewhere',
'',
'This file is portable context, not a restorable Pi session archive.',
'',
`- ${sameFolder}`,
`- ${continuation}`,
'- New folder: open the destination folder as a root in Pidex, start a new session there, and share this file as context for the first message. Attach it or paste its contents.',
'- Saved history stays with the original folder, so Resume will not find this session under a new folder.',
].join('\n');
Expand Down Expand Up @@ -67,9 +108,10 @@ export function sessionExportMarkdown(input: SessionExportInput): string {
];
if (input.cwd.trim()) parts.push(`It ran in \`${input.cwd.trim()}\`.`);
if (input.model.trim()) parts.push(`It used \`${input.model.trim()}\`.`);
if (input.source) parts.push(sourceSection(input.source));
if (input.entries.length > 0) {
parts.push(summarySection(input.entries));
parts.push(handoffSection(input.cwd));
parts.push(handoffSection(input.cwd, input.source));
}
if (input.entries.length === 0) {
parts.push('No messages in this selection.');
Expand Down
7 changes: 7 additions & 0 deletions src/renderer/useWorkbench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,13 @@ export function useWorkbench() {
model: preview.info.model,
entries: preview.entries,
exportedAt: new Date(),
source: {
sessionId: preview.info.id,
archivePath: preview.info.file,
entryId: preview.entryId ?? null,
archiveTipId: preview.tree?.leafId ?? null,
canContinue: !!preview.tree?.canContinue,
},
});
const key = `new:${destination.cwd}`;
setDrafts((prev) => ({
Expand Down
50 changes: 49 additions & 1 deletion tests/e2e/session-tree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const readLog = async () =>

describe('session branches in Electron', () => {
beforeAll(async () => {
fixture = await fs.mkdtemp(path.join(os.tmpdir(), 'pidex-branches-'));
fixture = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'pidex-branches-')));
const project = path.join(fixture, 'project');
const archives = path.join(fixture, 'sessions/workspace');
await Promise.all([
Expand Down Expand Up @@ -98,6 +98,11 @@ describe('session branches in Electron', () => {
}) + '\n',
);
switched = path.join(archives, 'switched.jsonl');
await fs.writeFile(path.join(archives, 'legacy.jsonl'), [
{ type: 'session', version: 2, id: 'legacy', cwd: project, timestamp: '2026-11-01T01:00:00Z' },
message('legacy-task', null, 'user', 'Recover legacy context'),
message('legacy-answer', 'legacy-task', 'assistant', 'A readable older archive.'),
].map((record) => JSON.stringify(record)).join('\n') + '\n');
await fs.writeFile(
path.join(archives, 'recovery.jsonl'),
[
Expand Down Expand Up @@ -237,6 +242,10 @@ describe('session branches in Electron', () => {
expect(latest).toContain('The latest branch uses a buffered parser.');
expect(latest).toContain('## Continue elsewhere');
expect(latest).toContain('It ran in `');
expect(latest).toContain('- Pi session `source`.');
expect(latest).toContain(`- Source archive \`${source}\`.`);
expect(latest).toContain('- Selected entry `new-tip` (archive tip).');
expect(latest).toContain('select entry `new-tip`, and choose Resume.');
expect(latest).not.toContain('Streaming branch is ready.');
await page.getByLabel('Branch tip').selectOption('old-tip');
await page.locator('.wb-transcript').getByText('Streaming branch is ready.').waitFor();
Expand All @@ -246,6 +255,9 @@ describe('session branches in Electron', () => {
const branch = await app.evaluate(({ clipboard }) => clipboard.readText());
expect(branch).toContain('Streaming branch is ready.');
expect(branch).not.toContain('buffered parser');
expect(branch).toContain('- Selected entry `old-tip`.');
expect(branch).toContain('- Archive tip at export `new-tip`.');
expect(branch).toContain('select entry `old-tip`, and choose Resume in new fork.');
await page.getByRole('treeitem', { name: /assistant: The original branch/ }).click();
await page.locator('.wb-transcript').getByText('The original branch uses a streaming parser.').waitFor();
await page.getByRole('button', { name: 'Copy context', exact: true }).click();
Expand All @@ -254,7 +266,22 @@ describe('session branches in Electron', () => {
expect(ancestor).toContain('The original branch uses a streaming parser.');
expect(ancestor).not.toContain('Keep the streaming approach');
expect(ancestor).not.toContain('Streaming branch is ready.');
expect(ancestor).toContain('- Selected entry `old-answer`.');
expect(ancestor).toContain('- Archive tip at export `new-tip`.');
expect(ancestor).toContain('select entry `old-answer`, and choose Resume in new fork.');
await fs.mkdir(path.join(ROOT, '.tmp/proof'), { recursive: true });
const exportedFile = path.join(ROOT, '.tmp/proof/selected-history.md');
await app.evaluate(({ BrowserWindow }, output) => {
BrowserWindow.getAllWindows()[0].webContents.session.once('will-download', (_event, item) => {
item.setSavePath(output);
});
}, exportedFile);
await page.getByRole('button', { name: 'Export', exact: true }).click();
await expect.poll(() => fs.readFile(exportedFile, 'utf8')).toContain('- Selected entry `old-answer`.');
const exported = await fs.readFile(exportedFile, 'utf8');
// Copy and download differ only in the time at which the snapshot was made.
expect(exported.replace(/^Exported from pidex at .*$/m, '')).toBe(ancestor.replace(/^Exported from pidex at .*$/m, ''));
await fs.copyFile(exportedFile, path.join(summaryShots, 'selected-history.md'));
await page.screenshot({ path: path.join(ROOT, '.tmp/proof/copied-history-context.png') });
expect(await fs.readFile(source, 'utf8')).toBe(original);
expect((await readLog()).filter((c) => c.type === 'get_state' || c.type === 'prompt')).toEqual([]);
Expand All @@ -263,6 +290,27 @@ describe('session branches in Electron', () => {
await page.setViewportSize({ width: 1100, height: 700 });
});

it('copies readable legacy history with source identifiers and no unsafe resume instruction', async () => {
const legacy = path.join(path.dirname(source), 'legacy.jsonl');
const original = await fs.readFile(legacy, 'utf8');
await page.getByRole('tree', { name: 'Session archives', exact: true })
.getByRole('treeitem', { name: /Recover legacy context/ }).click();
await page.locator('.wb-transcript').getByText('A readable older archive.').waitFor();
await page.getByRole('button', { name: 'Copy context', exact: true }).click();
await page.getByRole('status').filter({ hasText: 'Context copied.' }).waitFor();
const context = await app.evaluate(({ clipboard }) => clipboard.readText());
expect(context).toContain('- Pi session `legacy`.');
expect(context).toContain('- Selected entry `legacy-answer` (archive tip).');
expect(context).toContain('Pidex could not validate it for continuation');
expect(context).not.toContain('and choose Resume');
expect(await fs.readFile(legacy, 'utf8')).toBe(original);
expect((await readLog()).filter((c) => c.type === 'get_state' || c.type === 'prompt')).toEqual([]);
await fs.writeFile(path.join(summaryShots, 'legacy-history-context.md'), context);
await page.getByRole('tree', { name: 'Session archives', exact: true })
.getByRole('treeitem', { name: /Explore parser branches/ }).click();
await page.locator('.wb-transcript').getByText('The latest branch uses a buffered parser.').waitFor();
});

it('previews selected branch and ancestor, forks exact selection and preserves both source branches', async () => {
const original = await fs.readFile(source, 'utf8');
await page.getByRole('button', { name: /^Sessions/ }).click();
Expand Down
19 changes: 19 additions & 0 deletions tests/e2e/workspaces.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,11 @@ describe('grouped roots in Electron', () => {
expect(draft).toMatch(/^Keep the destination plan\n\n---\n\n# History for api/);
expect(draft).toContain('## You\n\nHistory for api');
expect(draft).not.toContain('Stored answer for api');
expect(draft).toContain('- Pi session `api`.');
expect(draft).toContain(`- Source archive \`${archive}\`.`);
expect(draft).toContain('- Selected entry `u`.');
expect(draft).toContain('- Archive tip at export `a`.');
expect(draft).toContain('select entry `u`, and choose Resume in new fork.');
expect(await page.locator('.wb-execution-root').textContent()).toContain(web);
expect(await runtimeActions()).toEqual(before);
expect(await fs.readFile(archive, 'utf8')).toBe(original);
Expand All @@ -425,6 +430,20 @@ describe('grouped roots in Electron', () => {
await page.mouse.move(composer.x + composer.width - 3, composer.y + composer.height + 120, { steps: 12 });
await page.mouse.up();
await capture('prepared-destination-draft.png');
await fs.writeFile(path.join(shots, 'prepared-history-context.md'), draft);
// Capture the real composer showing the new identifiers at native window size.
const nativeWindow = await app.browserWindow(page);
await nativeWindow.evaluate((window) => window.setContentSize(1280, 840));
const size = await nativeWindow.evaluate((window) => window.getContentSize());
await page.setViewportSize({ width: size[0], height: size[1] });
await page.waitForFunction(([width, height]) => innerWidth === width && innerHeight === height, size);
await page.getByLabel('Message pi').scrollIntoViewIfNeeded();
await page.getByLabel('Message pi').evaluate((textarea) => {
const input = textarea as HTMLTextAreaElement;
const line = input.value.slice(0, input.value.indexOf('## Saved selection')).split('\n').length - 1;
input.scrollTop = line * parseFloat(getComputedStyle(input).lineHeight);
});
await capture('history-context-identifiers.png');
// Review is real editing, with no automatic send.
await page.getByLabel('Message pi').fill(`${draft}\n\nCheck this root first.`);
await page.getByRole('button', { name: 'Send', exact: true }).click();
Expand Down
21 changes: 19 additions & 2 deletions tests/integration/HistoryExport.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { sessionExportMarkdown, type SessionExportInput } from '../../src/render

const input: Omit<SessionExportInput, 'exportedAt'> = {
title: 'Recover the parser', cwd: '/code/api', model: 'test-model',
source: {
sessionId: 'parser', archivePath: '/sessions/parser.jsonl',
entryId: 'earlier', archiveTipId: 'latest', canContinue: true,
},
entries: [
{ key: 'u', kind: 'user', text: 'Fix the parser' },
{ key: 'a', kind: 'assistant', text: 'Use a buffered parser', thinking: 'Check boundaries', streaming: false },
Expand Down Expand Up @@ -43,6 +47,8 @@ describe('<HistoryExport>', () => {
const { getByRole } = render(<HistoryExport input={input} />);
fireEvent.click(getByRole('button', { name: 'Copy context' }));
expect(writeText).toHaveBeenCalledWith(sessionExportMarkdown({ ...input, exportedAt }));
expect(writeText.mock.calls[0][0]).toContain('- Selected entry `earlier`.');
expect(writeText.mock.calls[0][0]).toContain('and choose Resume in new fork.');
await waitFor(() => expect(getByRole('status').textContent).toContain('Paste it into a new session'));
fireEvent.click(getByRole('button', { name: 'Copy context' }));
await waitFor(() => expect(writeText).toHaveBeenCalledTimes(2));
Expand Down Expand Up @@ -90,8 +96,8 @@ describe('<HistoryExport>', () => {
expect(getByRole('button', { name: 'Export' })).toBeEnabled();
});

it('downloads the selected history as a Markdown file', () => {
vi.useFakeTimers();
it('downloads the selected history and exact source identifiers as a Markdown file', async () => {
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] });
const create = vi.fn().mockReturnValue('blob:history');
const revoke = vi.fn();
Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: create });
Expand All @@ -104,6 +110,17 @@ describe('<HistoryExport>', () => {
fireEvent.click(getByRole('button', { name: 'Export' }));
expect(click).toHaveBeenCalledOnce();
expect(create.mock.calls[0][0].type).toBe('text/markdown');
const text = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(reader.error);
reader.readAsText(create.mock.calls[0][0]);
});
expect(text).toContain('- Pi session `parser`.');
expect(text).toContain('- Source archive `/sessions/parser.jsonl`.');
expect(text).toContain('- Selected entry `earlier`.');
expect(text).toContain('- Archive tip at export `latest`.');
expect(text).toContain('and choose Resume in new fork.');
vi.advanceTimersByTime(1000);
expect(revoke).toHaveBeenCalledWith('blob:history');
});
Expand Down
5 changes: 5 additions & 0 deletions tests/integration/useWorkbench.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,11 @@ describe('workbench root switching', () => {
expect(result.current.draft).toMatch(/^Keep this destination task\n\n---\n\n# Source context/);
expect(result.current.draft).toContain('Selected earlier request');
expect(result.current.draft).toContain('It ran in `/code/api`.');
expect(result.current.draft).toContain('- Pi session `source`.');
expect(result.current.draft).toContain('- Source archive `/sessions/source.jsonl`.');
expect(result.current.draft).toContain('- Selected entry `earlier`.');
expect(result.current.draft).toContain('- Archive tip at export `latest`.');
expect(result.current.draft).toContain('and choose Resume in new fork.');
expect(openSession).not.toHaveBeenCalled();
expect(sendPrompt).not.toHaveBeenCalled();
act(() => result.current.selectWorkspace(catalog.roots[0]));
Expand Down
Loading
Loading