diff --git a/docs/pidex-architecture.md b/docs/pidex-architecture.md index 5c608b7..c6f4924 100644 --- a/docs/pidex-architecture.md +++ b/docs/pidex-architecture.md @@ -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. diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index 114efc3..52bf650 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -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; diff --git a/src/renderer/export-session.ts b/src/renderer/export-session.ts index 7aeb419..785095e 100644 --- a/src/renderer/export-session.ts +++ b/src/renderer/export-session.ts @@ -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): 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; @@ -27,17 +59,26 @@ function toolHeading(entry: Extract): 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'); @@ -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.'); diff --git a/src/renderer/useWorkbench.ts b/src/renderer/useWorkbench.ts index df76f5b..663cc5d 100644 --- a/src/renderer/useWorkbench.ts +++ b/src/renderer/useWorkbench.ts @@ -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) => ({ diff --git a/tests/e2e/session-tree.test.ts b/tests/e2e/session-tree.test.ts index 6969e76..9eb08b5 100644 --- a/tests/e2e/session-tree.test.ts +++ b/tests/e2e/session-tree.test.ts @@ -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([ @@ -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'), [ @@ -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(); @@ -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(); @@ -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([]); @@ -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(); diff --git a/tests/e2e/workspaces.test.ts b/tests/e2e/workspaces.test.ts index a3aace7..37c8a16 100644 --- a/tests/e2e/workspaces.test.ts +++ b/tests/e2e/workspaces.test.ts @@ -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); @@ -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(); diff --git a/tests/integration/HistoryExport.test.tsx b/tests/integration/HistoryExport.test.tsx index 5277056..8ca4e96 100644 --- a/tests/integration/HistoryExport.test.tsx +++ b/tests/integration/HistoryExport.test.tsx @@ -5,6 +5,10 @@ import { sessionExportMarkdown, type SessionExportInput } from '../../src/render const input: Omit = { 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 }, @@ -43,6 +47,8 @@ describe('', () => { const { getByRole } = render(); 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)); @@ -90,8 +96,8 @@ describe('', () => { 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 }); @@ -104,6 +110,17 @@ describe('', () => { fireEvent.click(getByRole('button', { name: 'Export' })); expect(click).toHaveBeenCalledOnce(); expect(create.mock.calls[0][0].type).toBe('text/markdown'); + const text = await new Promise((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'); }); diff --git a/tests/integration/useWorkbench.test.tsx b/tests/integration/useWorkbench.test.tsx index 13d63fb..4fd3f8b 100644 --- a/tests/integration/useWorkbench.test.tsx +++ b/tests/integration/useWorkbench.test.tsx @@ -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])); diff --git a/tests/unit/export-session.test.ts b/tests/unit/export-session.test.ts index 8b494ac..5ba72f8 100644 --- a/tests/unit/export-session.test.ts +++ b/tests/unit/export-session.test.ts @@ -19,7 +19,71 @@ const bashDone: Extract = { ok: true, }; +const source = { + sessionId: 'parser-session', archivePath: '/sessions/parser.jsonl', + entryId: 'selected-entry', archiveTipId: 'selected-entry', canContinue: true, +}; + describe('sessionExportMarkdown', () => { + it('identifies the exact saved archive tip and explains that the snapshot can advance', () => { + const markdown = sessionExportMarkdown({ + title: 'Parser', cwd: '/repo', model: '', exportedAt, source, + entries: [{ key: 'u', kind: 'user', text: 'Fix the parser' }], + }); + expect(markdown).toContain('- Pi session `parser-session`.'); + expect(markdown).toContain('- Source archive `/sessions/parser.jsonl`.'); + expect(markdown).toContain('- Selected entry `selected-entry` (archive tip).'); + expect(markdown).toContain('- Archive tip at export `selected-entry`.'); + expect(markdown).toContain('select entry `selected-entry`, and choose Resume.'); + expect(markdown).toContain('If the archive has advanced'); + expect(markdown).toContain('The archive may change before you return.'); + }); + + it('distinguishes a selected ancestor or alternate branch from the archive tip', () => { + const markdown = sessionExportMarkdown({ + title: 'Parser', cwd: '/repo', model: '', exportedAt, + source: { ...source, entryId: 'earlier-entry' }, + entries: [{ key: 'u', kind: 'user', text: 'Fix the parser' }], + }); + expect(markdown).toContain('- Selected entry `earlier-entry`.'); + expect(markdown).toContain('- Archive tip at export `selected-entry`.'); + expect(markdown).toContain('select entry `earlier-entry`, and choose Resume in new fork.'); + expect(markdown).not.toContain('`earlier-entry` (archive tip)'); + }); + + it('preserves readable history identifiers without promising unsafe continuation', () => { + const markdown = sessionExportMarkdown({ + title: 'Legacy parser', cwd: '/repo', model: '', exportedAt, + source: { ...source, canContinue: false }, + entries: [{ key: 'u', kind: 'user', text: 'Fix the parser' }], + }); + expect(markdown).toContain('## Saved selection'); + expect(markdown).toContain('Pidex could not validate it for continuation'); + expect(markdown).toContain('Use this file as context in a new session'); + expect(markdown).not.toContain('and choose Resume'); + }); + + it('records an empty archive without inventing an entry or offering continuation', () => { + const markdown = sessionExportMarkdown({ + title: 'Empty', cwd: '/repo', model: '', exportedAt, entries: [], + source: { ...source, entryId: null, archiveTipId: null }, + }); + expect(markdown).toContain('- Pi session `parser-session`.'); + expect(markdown).toContain('no selected conversation entry'); + expect(markdown).toContain('no conversation tip'); + expect(markdown).not.toContain('Continue elsewhere'); + }); + + it('keeps backticks and line breaks in archive identifiers inside readable inline code', () => { + const markdown = sessionExportMarkdown({ + title: 'Parser', cwd: '', model: '', exportedAt, entries: [], + source: { ...source, archivePath: '/sessions/a`b\n# pretend-heading.jsonl', sessionId: '`parser`' }, + }); + expect(markdown).toContain('- Source archive ``/sessions/a`b # pretend-heading.jsonl``.'); + expect(markdown).toContain('- Pi session `` `parser` ``.'); + expect(markdown).not.toContain('\n# pretend-heading'); + }); + it('exports image result notices and accompanying text without inline image data', () => { const markdown = sessionExportMarkdown({ title: 'Inspect an image', cwd: '/repo/app', model: '', exportedAt,