Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): align session tree indentation (#3459)
lijialuo3429d8b9c6c7
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionBranchTreeDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionBranchTreeDialog.tsxindex de4de8aa43..97e7eb982e 100644--- a/apps/desktop/src/renderer/features/cc-agent/SessionBranchTreeDialog.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/SessionBranchTreeDialog.tsx@@ -143,10 +143,17 @@ export function SessionBranchTreeDialog({navigate(route);}, [navigate, onOpenChange, session.id]);- const renderPiNode = (node: SessionTreeNode, depth: number): React.ReactNode => {+ const renderPiNode = (node: SessionTreeNode, branchDepth: number, justBranched: boolean): React.ReactNode => {const active = tree?.activePathIds.includes(node.id) === true;const leaf = tree?.leafId === node.id;const branching = node.children.length > 1;+ // Pi groups the first continuation after a fork once; later single-child+ // continuations stay aligned. A nested fork adds one level, not both.+ const childBranchDepth = branching+ ? branchDepth + 1+ : justBranched && branchDepth > 0+ ? branchDepth + 1+ : branchDepth;return (<div key={node.id}><button@@ -158,7 +165,7 @@ export function SessionBranchTreeDialog({'hover:bg-[var(--surface-elevated)] disabled:cursor-default',active && 'bg-[var(--surface-elevated)]',)}- style={{ paddingLeft: `${10 + depth * 18}px` }}+ style={{ paddingLeft: `${10 + branchDepth * 18}px` }}><spanclassName={cn(@@ -181,7 +188,7 @@ export function SessionBranchTreeDialog({</span></span></button>- {node.children.map((child) => renderPiNode(child, depth + 1))}+ {node.children.map((child) => renderPiNode(child, childBranchDepth, branching))}</div>);};@@ -211,7 +218,11 @@ export function SessionBranchTreeDialog({{loading ? (<div className="flex h-16 items-center justify-center"><Spinner size={16} /></div>) : tree && tree.roots.length > 0 ? (- tree.roots.map((root) => renderPiNode(root, depth + 1))+ tree.roots.map((root) => renderPiNode(+ root,+ depth + (tree.roots.length > 1 ? 2 : 1),+ tree.roots.length > 1,+ ))) : (<div className="px-3 py-3 text-12 text-[var(--text-tertiary)]">{t('ccAgent.sidebar.sessionBranches.empty')}diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/SessionBranchTreeDialog.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/SessionBranchTreeDialog.test.tsxnew file mode 100644index 0000000000..61e2ca7d0f--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/SessionBranchTreeDialog.test.tsx@@ -0,0 +1,76 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { SessionTreeNode, SessionTreeSnapshot } from '@cindy/maker-core';+import type { Session } from '@/lib/ccAgent.types';+import { SessionBranchTreeDialog } from '../SessionBranchTreeDialog';++const mocks = vi.hoisted(() => ({+ t: (key: string) => key,+ getSessionTree: vi.fn(), navigateSessionTree: vi.fn(), reloadMessages: vi.fn(),+ saveDraft: vi.fn(), onOpenChange: vi.fn(), navigate: vi.fn(),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: mocks.t }) }));+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.navigate }));+vi.mock('@/lib/makerTransport', () => ({ makerApiFor: () => mocks }));+vi.mock('@/lib/makerChatStore', () => ({ makerChatStore: mocks }));+vi.mock('@/lib/composerDraftStore', () => ({ saveDraft: mocks.saveDraft, plainTextToTiptapDoc: (text: string) => text }));+vi.mock('@/lib/orcaSessionIdentity', () => ({ resolveSessionRoute: vi.fn() }));+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), warning: vi.fn() } }));++function node(id: string, ...children: SessionTreeNode[]): SessionTreeNode {+ return { id, parentId: null, kind: 'message', role: 'user', preview: id, children };+}+function chain(length: number): SessionTreeNode {+ let next = node(`chain-${length - 1}`);+ for (let i = length - 2; i >= 0; i--) next = node(`chain-${i}`, next);+ return next;+}+const current = { id: 'session', agentKind: 'pi', title: 'Pi task' } as Session;+const snapshot = (roots: SessionTreeNode[]): SessionTreeSnapshot => ({ roots, leafId: 'leaf', activePathIds: ['p', 'leaf'] });+const row = (id: string) => screen.getByText(id).closest('button')!;+async function show(roots: SessionTreeNode[], flags = {}, familyDepth = false) {+ mocks.getSessionTree.mockResolvedValue(snapshot(roots));+ const session = familyDepth ? { ...current, parentSessionId: 'parent' } : current;+ render(<SessionBranchTreeDialog open onOpenChange={mocks.onOpenChange} session={session}+ sessions={familyDepth ? [{ id: 'parent', title: 'Parent' } as Session, session] : [session]}+ running={false} writeBlocked={false} {...flags} />);+ if (roots.length) await screen.findByText(roots[0].preview);+}+beforeEach(() => vi.clearAllMocks());+afterEach(cleanup);++describe('Pi tree visible indentation', () => {+ it('keeps a long single chain aligned inside a nested Cindy task', async () => {+ await show([chain(40)], {}, true);+ for (let i = 0; i < 40; i++) expect(row(`chain-${i}`).style.paddingLeft).toBe('46px');+ });+ it('groups forks once, including immediate and later nested forks', async () => {+ await show([node('p', node('a', node('a2', node('a3', node('c', node('c2', node('c3'))), node('d')))), node('b', node('e', node('e2')), node('f')))]);+ const depths = { p: 0, a: 1, a2: 2, a3: 2, c: 3, c2: 4, c3: 4, d: 3, b: 1, e: 2, e2: 3, f: 2 };+ for (const [id, depth] of Object.entries(depths)) expect(row(id).style.paddingLeft).toBe(`${28 + depth * 18}px`);+ });+ it('treats multiple roots as a virtual fork without drifting along their chains', async () => {+ await show([node('a', node('a2', node('a3'))), node('b')]);+ expect(['a', 'a2', 'a3', 'b'].map(id => row(id).style.paddingLeft)).toEqual(['46px', '64px', '64px', '46px']);+ });+ it.each([{ running: true }, { writeBlocked: true }])('keeps navigation blocked for %o', async flags => {+ await show([node('p', node('leaf'))], flags);+ fireEvent.click(row('p'));+ expect(row('p').disabled).toBe(true);+ expect(row('leaf').disabled).toBe(true);+ expect(mocks.navigateSessionTree).not.toHaveBeenCalled();+ });+ it('preserves active/current state and refreshes after navigation', async () => {+ const tree = snapshot([node('p', node('leaf')), node('other')]);+ mocks.navigateSessionTree.mockResolvedValue({ tree, draftText: 'resume this' });+ await show(tree.roots);+ expect(row('p').className).toContain('bg-[var(--surface-elevated)]');+ expect(row('leaf').disabled).toBe(true);+ fireEvent.click(row('other'));+ await waitFor(() => expect(mocks.onOpenChange).toHaveBeenCalledWith(false));+ expect(mocks.navigateSessionTree).toHaveBeenCalledWith('session', 'other', { summarize: false });+ expect(mocks.reloadMessages).toHaveBeenCalledWith('session');+ expect(mocks.saveDraft).toHaveBeenCalledWith('session', { text: 'resume this', attachments: [], focusAtEnd: true });+ });+});diff --git a/apps/mobile/src/__tests__/PiSessionTreeSheet.test.tsx b/apps/mobile/src/__tests__/PiSessionTreeSheet.test.tsxnew file mode 100644index 0000000000..5eba056919--- /dev/null+++ b/apps/mobile/src/__tests__/PiSessionTreeSheet.test.tsx@@ -0,0 +1,93 @@+// @vitest-environment jsdom+import { act, type CSSProperties, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { PiSessionTreeSheet } from '@/session/PiSessionTreeSheet';+import type { MobilePiSessionTreeNode } from '@/session/piSessionTreeModel';+import { darkColors, lightColors, spacing } from '@/theme/tokens';++const state = vi.hoisted(() => ({ dark: false, t: (key: string) => key }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: state.t }) }));+vi.mock('react-native', async () => {+ const { createElement } = await import('react');+ type Props = { children?: ReactNode; style?: unknown; testID?: string; onPress?: () => void; disabled?: boolean };+ const flatten = (value: unknown): CSSProperties => Object.assign({}, ...(Array.isArray(value) ? value.flat(Infinity).filter(Boolean) : [value]));+ const View = ({ children, style }: Props) => createElement('div', { style: flatten(style) }, children);+ const Pressable = ({ children, style, testID, onPress, disabled }: Props) => createElement('button', {+ 'data-testid': testID, onClick: onPress, disabled,+ style: flatten(typeof style === 'function' ? style({ pressed: false }) : style),+ }, children);+ return { View, Text: View, Pressable, ActivityIndicator: () => null,+ StyleSheet: { create: (value: unknown) => value, hairlineWidth: 1 },+ useWindowDimensions: () => ({ width: 390, height: 844 }) };+});+vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text }));+vi.mock('lucide-react-native', () => ({ Check: () => null, GitBranch: () => null, MessageSquare: () => null }));+vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0 }) }));+vi.mock('@/theme', async () => {+ const tokens = await import('@/theme/tokens');+ const colors = () => state.dark ? tokens.darkColors : tokens.lightColors;+ return { ...tokens, useTheme: () => ({ colors: colors() }),+ useThemedStyles: (make: (value: typeof tokens.lightColors) => unknown) => make(colors()) };+});+vi.mock('@/session/SheetModal', () => ({ SheetModal: ({ children }: { children: ReactNode }) => children }));+vi.mock('@/session/SheetSurface', () => ({ SheetSurface: ({ children }: { children: ReactNode }) => children }));++function node(id: string, ...children: MobilePiSessionTreeNode[]): MobilePiSessionTreeNode {+ return { id, role: 'user', preview: id, children };+}+function chain(length: number): MobilePiSessionTreeNode {+ let next = node(`chain-${length - 1}`);+ for (let i = length - 2; i >= 0; i--) next = node(`chain-${i}`, next);+ return next;+}+let host: HTMLDivElement;+let root: Root;+const maker = { getSessionTree: vi.fn(), navigateSessionTree: vi.fn() };+const onNavigated = vi.fn();+const row = (id: string) => host.querySelector<HTMLButtonElement>(`[data-testid="session.branch.${id}"]`)!;+async function show(roots: MobilePiSessionTreeNode[], disabledReason?: string) {+ maker.getSessionTree.mockResolvedValue({ roots, leafId: 'leaf', activePathIds: ['p', 'leaf'] });+ await act(async () => root.render(<PiSessionTreeSheet visible sessionId="session" maker={maker}+ onClose={vi.fn()} onNavigated={onNavigated} disabledReason={disabledReason} />));+}+beforeEach(() => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ vi.clearAllMocks();+ host = document.createElement('div'); root = createRoot(host);+});+afterEach(async () => { await act(async () => root.unmount()); });++describe.each(['light', 'dark'])('Pi tree in %s mode', mode => {+ beforeEach(() => { state.dark = mode === 'dark'; });+ it('keeps a long single chain aligned', async () => {+ await show([chain(40)]);+ for (let i = 0; i < 40; i++) expect(row(`chain-${i}`).style.paddingLeft).toBe(`${spacing.md}px`);+ });+ it('groups forks once, including immediate and later nested forks', async () => {+ await show([node('p', node('a', node('a2', node('a3', node('c', node('c2', node('c3'))), node('d')))), node('b', node('e', node('e2')), node('f')))]);+ const depths = { p: 0, a: 1, a2: 2, a3: 2, c: 3, c2: 4, c3: 4, d: 3, b: 1, e: 2, e2: 3, f: 2 };+ for (const [id, depth] of Object.entries(depths)) expect(row(id).style.paddingLeft).toBe(`${spacing.md + depth * spacing.lg}px`);+ });+ it('treats multiple roots as a virtual fork without drifting along their chains', async () => {+ await show([node('a', node('a2', node('a3'))), node('b')]);+ expect(['a', 'a2', 'a3', 'b'].map(id => row(id).style.paddingLeft)).toEqual([1, 2, 2, 1].map(depth => `${spacing.md + depth * spacing.lg}px`));+ });+ it('retains themed active state, current leaf and navigation result', async () => {+ await show([node('p', node('leaf')), node('other')]);+ const sample = document.createElement('div');+ sample.style.backgroundColor = (state.dark ? darkColors : lightColors).surfaceElevated;+ expect(row('p').style.backgroundColor).toBe(sample.style.backgroundColor);+ expect(row('leaf').disabled).toBe(true);+ maker.navigateSessionTree.mockResolvedValue({ draftText: 'resume this' });+ await act(async () => row('other').click());+ expect(maker.navigateSessionTree).toHaveBeenCalledWith('session', 'other');+ expect(onNavigated).toHaveBeenCalledWith('resume this');+ });+ it('disables branch navigation when the transport is write blocked', async () => {+ await show([node('p', node('leaf'))], 'blocked');+ await act(async () => row('p').click());+ expect(row('p').disabled).toBe(true);+ expect(maker.navigateSessionTree).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/src/session/PiSessionTreeSheet.tsx b/apps/mobile/src/session/PiSessionTreeSheet.tsxindex 1e25cbcc29..77cfc13213 100644--- a/apps/mobile/src/session/PiSessionTreeSheet.tsx+++ b/apps/mobile/src/session/PiSessionTreeSheet.tsx@@ -88,10 +88,18 @@ export function PiSessionTreeSheet({}}, [disabledReason, maker, onNavigated, sessionId, switchingId, t, tree?.leafId]);- const renderNode = (node: MobilePiSessionTreeNode, depth: number): ReactNode => {+ const renderNode = (node: MobilePiSessionTreeNode, branchDepth: number, justBranched: boolean): ReactNode => {const active = tree?.activePathIds.includes(node.id) === true;const current = tree?.leafId === node.id;const busy = switchingId !== null;+ const branching = node.children.length > 1;+ // Pi groups the first continuation after a fork once; later single-child+ // continuations stay aligned. A nested fork adds one level, not both.+ const childBranchDepth = branching+ ? branchDepth + 1+ : justBranched && branchDepth > 0+ ? branchDepth + 1+ : branchDepth;return (<View key={node.id}><Pressable@@ -102,7 +110,7 @@ export function PiSessionTreeSheet({onPress={() => void navigate(node)}style={({ pressed }) => [styles.node,- { paddingLeft: spacing.md + depth * spacing.lg },+ { paddingLeft: spacing.md + branchDepth * spacing.lg },active && styles.nodeActive,pressed && styles.nodePressed,]}@@ -113,7 +121,7 @@ export function PiSessionTreeSheet({<ActivityIndicator color={colors.textPrimary} size="small" />) : current ? (<Check color={colors.textPrimary} size={iconSize.sm} strokeWidth={iconStroke.regular} />- ) : node.children.length > 1 ? (+ ) : branching ? (<GitBranch color={active ? colors.textPrimary : colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />) : (<MessageSquare color={active ? colors.textPrimary : colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />@@ -129,7 +137,7 @@ export function PiSessionTreeSheet({</Text></View></Pressable>- {node.children.map((child) => renderNode(child, depth + 1))}+ {node.children.map((child) => renderNode(child, childBranchDepth, branching))}</View>);};@@ -156,7 +164,7 @@ export function PiSessionTreeSheet({{loading ? (<View style={styles.loading}><ActivityIndicator color={colors.textSecondary} /></View>) : tree && tree.roots.length > 0 ? (- tree.roots.map((node) => renderNode(node, 0))+ tree.roots.map((node) => renderNode(node, tree.roots.length > 1 ? 1 : 0, tree.roots.length > 1))) : !error ? (<Text style={styles.empty}>{t('session.menu.branchEmpty')}</Text>) : null}