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
4 changes: 4 additions & 0 deletions apps/frontend/src/renderer/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ import { KanbanPilotView } from './components/KanbanPilotView';
import { ChangelogPilotView } from './components/ChangelogPilotView';
import { GitHubPRsPilotView } from './components/GitHubPRsPilotView';
import { GitHubIssuesPilotView } from './components/GitHubIssuesPilotView';
import { PatternsPilotView } from './components/PatternsPilotView';
import { useSettingsStore, loadSettings, loadProfiles, saveSettings } from './stores/settings-store';
import { useClaudeProfileStore } from './stores/claude-profile-store';
import { useTerminalStore, restoreTerminalSessions } from './stores/terminal-store';
Expand Down Expand Up @@ -1119,6 +1120,9 @@ export function App() {
{activeView === 'patterns' && (activeProjectId || selectedProjectId) && (
<PatternsPage projectId={activeProjectId || selectedProjectId!} />
)}
{activeView === 'patterns-next' && (activeProjectId || selectedProjectId) && (
<PatternsPilotView projectId={(activeProjectId || selectedProjectId)!} />
)}
{activeView === 'agent-tools' && <AgentTools />}
{activeView === 'plugins' && selectedProject?.path && (
<PluginManager projectPath={selectedProject.path} />
Expand Down
105 changes: 105 additions & 0 deletions apps/frontend/src/renderer/__tests__/patterns-ui.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* Tests for the Pattern → PatternLibrary mapping helpers.
*/

import { describe, expect, it } from 'vitest';
import {
aggregatePatterns,
filterPatterns,
mapPatternToUi,
} from '../lib/patterns-ui';
import type { Pattern } from '../../preload/api/modules/pattern-api';

const LABELS = { high: 'high confidence', medium: 'medium confidence', low: 'low confidence' };

function makePattern(overrides: Partial<Pattern> = {}): Pattern {
return {
index: 1,
id: '1',
text: 'Prefer typed nav config from a string-literal union',
category: 'code-organization',
confidence: 'high',
reasoning: 'A typo then fails at compile time.',
...overrides,
};
}

describe('mapPatternToUi', () => {
it('maps a backend pattern onto a sparse card with a spec-qualified id', () => {
const ui = mapPatternToUi(makePattern(), '001-auth', LABELS);
expect(ui).toEqual({
id: '001-auth#1',
kind: 'pattern',
title: 'Prefer typed nav config from a string-literal union',
lang: 'code-organization',
description: 'A typo then fails at compile time.',
footer: [{ text: 'high confidence' }],
});
});

it('omits the confidence footer and empty description when unknown', () => {
const ui = mapPatternToUi(
makePattern({ confidence: undefined, reasoning: '', category: undefined }),
'002',
LABELS,
);
expect(ui.footer).toBeUndefined();
expect(ui.description).toBeUndefined();
expect(ui.lang).toBeUndefined();
});

it('drops the footer when no confidence labels are supplied', () => {
expect(mapPatternToUi(makePattern(), '003').footer).toBeUndefined();
});
});

describe('aggregatePatterns', () => {
it('flattens per-spec patterns and dedupes identical texts, first wins', () => {
const shared = makePattern({ text: 'Branches stay local until pushed' });
const result = aggregatePatterns(
[
{ specId: '001', patterns: [makePattern({ index: 1, text: 'A' }), shared] },
{ specId: '002', patterns: [{ ...shared, index: 5 }, makePattern({ index: 2, text: 'B' })] },
],
LABELS,
);
expect(result.map((p) => p.title)).toEqual([
'A',
'Branches stay local until pushed',
'B',
]);
// The deduped entry keeps the first spec's id.
expect(result[1].id).toBe('001#1');
});

it('returns an empty list for no specs', () => {
expect(aggregatePatterns([])).toEqual([]);
expect(aggregatePatterns([{ specId: '001', patterns: [] }])).toEqual([]);
});

it('is case- and whitespace-insensitive when deduping', () => {
const result = aggregatePatterns([
{ specId: '001', patterns: [makePattern({ text: 'Same Rule' })] },
{ specId: '002', patterns: [makePattern({ text: ' same rule ' })] },
]);
expect(result).toHaveLength(1);
});
});

describe('filterPatterns', () => {
const patterns = [
mapPatternToUi(makePattern({ index: 1, text: 'Typed nav config', category: 'code-organization' }), 's1', LABELS),
mapPatternToUi(makePattern({ index: 2, text: 'Retry with backoff', category: 'error-handling', reasoning: 'exponential jitter' }), 's1', LABELS),
];

it('matches title, lang, and description, case-insensitively', () => {
expect(filterPatterns(patterns, 'NAV').map((p) => p.title)).toEqual(['Typed nav config']);
expect(filterPatterns(patterns, 'error-handling').map((p) => p.title)).toEqual(['Retry with backoff']);
expect(filterPatterns(patterns, 'jitter').map((p) => p.title)).toEqual(['Retry with backoff']);
expect(filterPatterns(patterns, 'zzz')).toEqual([]);
});

it('returns everything for a blank query', () => {
expect(filterPatterns(patterns, ' ')).toHaveLength(2);
});
});
185 changes: 185 additions & 0 deletions apps/frontend/src/renderer/components/PatternsPilotView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/**
* Patterns library pilot on the shared design system (U5 B1).
*
* The backend stores learned patterns per spec, so this pilot aggregates
* across the project's known specs (from the task store) via the existing
* `window.electronAPI.pattern.listPatterns` IPC and renders them through
* `libs/ui`'s PatternLibrary. Read-only — the approve/override/delete
* flows stay on the legacy Patterns view. Reachable via the "Patterns
* (new UI)" sidebar item.
*/

import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PatternLibrary } from '@auto-code/ui';
import type { UiMetaSection, UiPattern } from '@auto-code/ui';
import { useTaskStore } from '../stores/task-store';
import {
aggregatePatterns,
filterPatterns,
type SpecPatterns,
} from '../lib/patterns-ui';

interface PatternsPilotViewProps {
projectId: string;
}

interface PilotState {
patterns: UiPattern[] | null;
specCount: number;
loading: boolean;
error: Error | null;
}

export function PatternsPilotView({
projectId,
}: Readonly<PatternsPilotViewProps>) {
const { t } = useTranslation(['patterns']);
const [state, setState] = useState<PilotState>({
patterns: null,
specCount: 0,
loading: true,
error: null,
});
const [reloadKey, setReloadKey] = useState(0);
const [query, setQuery] = useState('');

// Subscribe reactively so patterns refetch when the project's tasks load
// after mount (reading getState() once would strand the empty state). The
// effect depends on a stable string key, not the fresh-per-render array,
// so unrelated task updates don't trigger a refetch.
const tasks = useTaskStore((store) => store.tasks);
const specKey = useMemo(
() =>
Array.from(
new Set(
tasks
.filter((task) => task.projectId === projectId)
.map((task) => task.specId),
),
).join('|'),
[tasks, projectId],
);

const confidenceLabels = useMemo(
() => ({
high: t('patterns:patternsPilot.confidence.high'),
medium: t('patterns:patternsPilot.confidence.medium'),
low: t('patterns:patternsPilot.confidence.low'),
}),
[t],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
);

useEffect(() => {
let active = true;
setState({ patterns: null, specCount: 0, loading: true, error: null });

// Patterns are stored per spec; load each spec's patterns, tolerating
// per-spec failures (a spec may have none / an unreadable file).
const specIds = specKey === '' ? [] : specKey.split('|');
Promise.all(
specIds.map((specId) =>
window.electronAPI.pattern
.listPatterns(projectId, specId)
.then((result): SpecPatterns => ({
specId,
patterns: result.success ? (result.data ?? []) : [],
}))
.catch((err: unknown): SpecPatterns => {
console.warn(
'[PatternsPilotView] Failed to load patterns for spec',
specId,
err,
);
return { specId, patterns: [] };
}),
),
)
.then((perSpec) => {
if (!active) return;
setState({
patterns: aggregatePatterns(perSpec, confidenceLabels),
specCount: specIds.length,
loading: false,
error: null,
});
})
.catch((err: unknown) => {
if (!active) return;
console.error('[PatternsPilotView] Failed to load patterns:', err);
setState({
patterns: null,
specCount: 0,
loading: false,
error: new Error(t('patterns:patternsPilot.error')),
});
});
return () => {
active = false;
};
}, [projectId, specKey, reloadKey, confidenceLabels, t]);

const reload = useCallback(() => setReloadKey((key) => key + 1), []);

const visible = useMemo(
() =>
state.patterns == null ? null : filterPatterns(state.patterns, query),
[state.patterns, query],
);

const metaSections = useMemo<UiMetaSection[] | undefined>(() => {
if (state.patterns == null) return undefined;
return [
{
title: t('patterns:patternsPilot.meta.title'),
rows: [
{
label: t('patterns:patternsPilot.meta.total'),
value: String(state.patterns.length),
},
{
label: t('patterns:patternsPilot.meta.specs'),
value: String(state.specCount),
},
],
},
];
}, [state.patterns, state.specCount, t]);

const stateLabels = useMemo(
() => ({
loading: t('patterns:patternsPilot.states.loading'),
retry: t('patterns:patternsPilot.states.retry'),
empty: t('patterns:patternsPilot.states.empty'),
}),
[t],
);

const kindLabels = useMemo(
() => ({
pattern: t('patterns:patternsPilot.kinds.pattern'),
gotcha: t('patterns:patternsPilot.kinds.gotcha'),
decision: t('patterns:patternsPilot.kinds.decision'),
rule: t('patterns:patternsPilot.kinds.rule'),
}),
[t],
);

return (
<div className="h-full overflow-hidden">
<PatternLibrary
patterns={visible}
loading={state.loading}
error={state.error}
onRetry={reload}
searchValue={query}
onSearchChange={setQuery}
searchPlaceholder={t('patterns:patternsPilot.searchPlaceholder')}
searchLabel={t('patterns:patternsPilot.searchLabel')}
stateLabels={stateLabels}
kindLabels={kindLabels}
metaSections={metaSections}
/>
</div>
);
}
3 changes: 2 additions & 1 deletion apps/frontend/src/renderer/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ import { SessionContextIndicator } from './SessionContextIndicator';
import { NavIndicator } from './NavIndicator';
import type { Project, AutoBuildVersionInfo, GitStatus, ProjectEnvConfig } from '../../shared/types';

export type SidebarView = 'kanban' | 'kanban-next' | 'terminals' | 'roadmap' | 'context' | 'ideation' | 'webhooks' | 'github-issues' | 'github-issues-next' | 'gitlab-issues' | 'github-prs' | 'github-prs-next' | 'gitlab-merge-requests' | 'changelog' | 'changelog-next' | 'insights' | 'worktrees' | 'agent-tools' | 'plugins' | 'analytics' | 'productivity' | 'merge-analytics' | 'sessions' | 'scheduler' | 'feedback' | 'patterns' | 'model-usage' | 'agent-inspector';
export type SidebarView = 'kanban' | 'kanban-next' | 'terminals' | 'roadmap' | 'context' | 'ideation' | 'webhooks' | 'github-issues' | 'github-issues-next' | 'gitlab-issues' | 'github-prs' | 'github-prs-next' | 'gitlab-merge-requests' | 'changelog' | 'changelog-next' | 'insights' | 'worktrees' | 'agent-tools' | 'plugins' | 'analytics' | 'productivity' | 'merge-analytics' | 'sessions' | 'scheduler' | 'feedback' | 'patterns' | 'patterns-next' | 'model-usage' | 'agent-inspector';

interface SidebarProps {
onSettingsClick: () => void;
Expand Down Expand Up @@ -103,6 +103,7 @@ const baseNavItems: NavItem[] = [
{ id: 'analytics', labelKey: 'navigation:items.analytics', icon: BarChart3, shortcut: 'Y' },
{ id: 'productivity', labelKey: 'navigation:items.productivity', icon: TrendingUp, shortcut: 'P' },
{ id: 'patterns', labelKey: 'navigation:items.patterns', icon: Code, shortcut: 'Z' },
{ id: 'patterns-next', labelKey: 'navigation:items.patternsNext', icon: Code },
{ id: 'agent-tools', labelKey: 'navigation:items.agentTools', icon: Wrench, shortcut: 'M' },
{ id: 'plugins', labelKey: 'navigation:items.plugins', icon: Puzzle, shortcut: 'U' },
{ id: 'worktrees', labelKey: 'navigation:items.worktrees', icon: GitBranch, shortcut: 'W' },
Expand Down
Loading
Loading