diff --git a/.github/actions/setup-xcode/action.yml b/.github/actions/setup-xcode/action.yml index f832ad9c3..67a7e3804 100644 --- a/.github/actions/setup-xcode/action.yml +++ b/.github/actions/setup-xcode/action.yml @@ -13,6 +13,102 @@ runs: with: xcode-version: ${{ inputs.xcode-version }} - - name: Download iOS Platform - run: xcodebuild -downloadPlatform iOS + - name: Setup Xcode Environment + run: | + set -e + + echo "=== Checking CI Environment ===" + echo "Current user: $(whoami)" + echo "User groups: $(groups)" + echo "Sudo available: $(sudo -n true 2>/dev/null && echo 'YES' || echo 'NO')" + echo "Xcode path: $(xcode-select -p 2>/dev/null || echo 'Not set')" + + # Set Xcode path and accept license + echo "=== Setting up Xcode ===" + if command -v sudo >/dev/null && sudo -n true 2>/dev/null; then + sudo xcode-select -s /Applications/Xcode_${{ inputs.xcode-version }}.app/Contents/Developer + sudo xcodebuild -license accept + echo "Using sudo for Xcode setup" + else + xcode-select -s /Applications/Xcode_${{ inputs.xcode-version }}.app/Contents/Developer + xcodebuild -license accept + echo "Using direct access for Xcode setup" + fi + + echo "Final Xcode path: $(xcode-select -p)" + shell: bash + + - name: Start Simulator Service + run: | + echo "=== Starting Simulator Service ===" + # Try to start simulator service (ignore errors if already running) + sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.CoreSimulator.CoreSimulatorService.plist 2>/dev/null || { + echo "CoreSimulator service might already be running or command unavailable" + } + + # Alternative for newer macOS versions + sudo launchctl bootstrap system /System/Library/LaunchDaemons/com.apple.CoreSimulator.CoreSimulatorService.plist 2>/dev/null || { + echo "Bootstrap command failed or service already running" + } + + # Wait a moment for service to start + sleep 3 + shell: bash + + - name: Download iOS Platform + run: | + set -e + + echo "=== Checking Available SDKs ===" + echo "Currently available SDKs:" + xcodebuild -showsdks | grep -E "(iOS|Simulator)" || echo "No iOS SDKs found yet" + + echo "=== Attempting iOS Platform Download ===" + + # Method 1: Try standard download + if xcodebuild -downloadPlatform iOS -quiet 2>/dev/null; then + echo "✅ iOS platform downloaded successfully with xcodebuild" + elif xcrun xcodebuild -downloadPlatform iOS -quiet 2>/dev/null; then + echo "✅ iOS platform downloaded successfully with xcrun xcodebuild" + else + echo "⚠️ Platform download failed, checking if iOS SDK is already available..." + + # Check if iOS SDK is available + if xcodebuild -showsdks | grep -q "iOS"; then + echo "✅ iOS SDK is already available, continuing..." + else + echo "❌ No iOS SDK found and download failed" + echo "Available SDKs:" + xcodebuild -showsdks + + # Try alternative download method + echo "Trying alternative download method..." + xcodebuild -downloadAllPlatforms -quiet || { + echo "❌ All download methods failed" + exit 1 + } + fi + fi + + echo "=== Final SDK Status ===" + echo "Available iOS SDKs:" + xcodebuild -showsdks | grep -E "(iOS|Simulator)" || echo "No iOS SDKs found" + + echo "Available simulators:" + xcrun simctl list devices available | head -20 || echo "No simulators found" + shell: bash + + - name: Verify Setup + run: | + echo "=== Verification ===" + echo "Xcode version: $(xcodebuild -version | head -1)" + echo "Selected Xcode: $(xcode-select -p)" + echo "iOS SDK available: $(xcodebuild -showsdks | grep -c iOS || echo 0)" + + # Test basic functionality + if xcodebuild -showsdks | grep -q "iOS"; then + echo "✅ Setup completed successfully!" + else + echo "⚠️ Setup completed but iOS SDK may not be fully available" + fi shell: bash diff --git a/.github/prompts/similar_issues.prompt.yml b/.github/prompts/similar_issues.prompt.yml new file mode 100644 index 000000000..90baf4ffb --- /dev/null +++ b/.github/prompts/similar_issues.prompt.yml @@ -0,0 +1,46 @@ +messages: + - role: system + content: |- + You are a GitHub assistant with access to GitHub Model Context Protocol (MCP) + tools in read-only mode. Your task is to search this repository's issues to find + previously filed issues similar to the provided issue title and body. Use the + GitHub tools via MCP to perform the search and retrieve real issue data (do not + fabricate results). Consider semantic similarity across title and body. Exclude + the current issue. Return up to 3 of the most similar past issues. If none are + reasonably similar, return an empty list. Output must follow the response schema + exactly and include only data you actually retrieved from GitHub tools. + The current GitHub repository is: "{{repository}}". + - role: user + content: |- + Find similar issues for this new issue: + Title: {{issue_title}} + Body: + {{issue_body}} +model: custom/openai/gpt-5 +responseFormat: json_schema +jsonSchema: |- + { + "name": "similar_issues_result", + "strict": true, + "schema": { + "type": "object", + "properties": { + "matches": { + "type": "array", + "items": { + "type": "object", + "properties": { + "number": { "type": "integer" }, + "title": { "type": "string" }, + "url": { "type": "string" }, + "similarity_score": { "type": "number", "minimum": 0, "maximum": 1 } + }, + "required": ["number", "title", "url", "similarity_score"], + "additionalProperties": false + } + } + }, + "required": ["matches"], + "additionalProperties": false + } + } diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index 73d89f2ff..35258cbbe 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -45,7 +45,7 @@ jobs: cache: "pnpm" - name: Set up JDK 17 - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: java-version: "17" distribution: "zulu" diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml new file mode 100644 index 000000000..21fb3ab01 --- /dev/null +++ b/.github/workflows/similar-issues.yml @@ -0,0 +1,88 @@ +name: Similar Issues via AI MCP + +on: + issues: + types: [opened] + +jobs: + find-similar: + permissions: + contents: read + issues: write + models: read + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Prepare prompt variables + id: prepare_input + uses: actions/github-script@v7 + with: + script: | + const issue = context.payload.issue || {}; + const title = issue.title || ''; + const body = issue.body || ''; + const indent = ' '; + // Indent subsequent lines so YAML block scalar indentation remains valid + const bodyIndented = body.replace(/\n/g, '\n' + indent); + core.setOutput('issue_title_json', JSON.stringify(title)); + core.setOutput('issue_body_indented_json', JSON.stringify(bodyIndented)); + + - name: Find similar issues with AI (MCP) + id: inference + uses: actions/ai-inference@v1 + with: + prompt-file: ./.github/prompts/similar_issues.prompt.yml + input: | + issue_title: ${{ steps.prepare_input.outputs.issue_title_json }} + issue_body: ${{ steps.prepare_input.outputs.issue_body_indented_json }} + repository: ${{ github.repository }} + enable-github-mcp: true + token: ${{ secrets.USER_PAT }} + github-mcp-token: ${{ secrets.USER_PAT }} + endpoint: https://models.github.ai/orgs/RSSNext/inference + + - name: Prepare comment body + id: prepare + uses: actions/github-script@v7 + env: + AI_RESPONSE: ${{ steps.inference.outputs.response }} + with: + script: | + let data; + try { + data = JSON.parse(process.env.AI_RESPONSE || '{}'); + } catch (e) { + core.setOutput('has_matches', 'false'); + return; + } + const matches = Array.isArray(data.matches) ? data.matches : []; + if (!matches.length) { + core.setOutput('has_matches', 'false'); + return; + } + const lines = []; + lines.push('I found similar issues that might help:'); + for (const m of matches.slice(0, 3)) { + const num = m.number != null ? `#${m.number}` : ''; + const title = m.title || 'Untitled'; + const url = m.url || ''; + const score = typeof m.similarity_score === 'number' ? ` (similarity: ${m.similarity_score.toFixed(2)})` : ''; + lines.push(`- ${url}${score}`.trim()); + } + core.setOutput('has_matches', 'true'); + core.setOutput('comment_body', lines.join('\n')); + + - name: Comment similar issues + if: steps.prepare.outputs.has_matches == 'true' + uses: actions/github-script@v7 + with: + script: | + const body = ${{ toJson(steps.prepare.outputs.comment_body) }}; + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.issue.number, + body + }); diff --git a/.gitignore b/.gitignore index 639b493d9..196742530 100644 --- a/.gitignore +++ b/.gitignore @@ -28,4 +28,3 @@ buildServer.json apps/desktop/build/appxmanifest.xml .claude/settings.local.json -PRPS/* diff --git a/.prettierignore b/.prettierignore index 71048663b..1d4f6902f 100644 --- a/.prettierignore +++ b/.prettierignore @@ -9,4 +9,8 @@ apps/mobile/android apps/mobile/ios apps/mobile/native/example +apps/mobile/native/android +apps/mobile/native/ios +apps/mobile/.expo + generated-routes.ts diff --git a/CLAUDE.md b/CLAUDE.md index 9279e1310..fa0566525 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,7 +38,6 @@ Follow (Folo) is a modern RSS aggregator and content management platform with mu - `utils/` - Utility functions and helpers - `tracker/` - Analytics and tracking - `logger/` - Logging utilities - - `legal/` - Legal and compliance utilities - **`packages/configs/`** - Shared configuration files - `tailwindcss/` - Tailwind CSS configurations - TypeScript and build configurations @@ -100,6 +99,12 @@ pnpm run typecheck pnpm run test ``` +You must first use `typecheck` to check if the code types are correct, and after making modifications, you need to use `typecheck` again until it passes. + +After the `typecheck` passes, you can use `lint:fix` to check the code quality. + +This project is a monorepo, and you can use the typecheck and `lint:fix` of sub-packages as needed, but please note that you must follow the above steps in order. + ## Architecture Guidelines ### Multi-Platform Architecture @@ -137,6 +142,7 @@ For mobile, see @apps/mobile/CLAUDE.md 3. For plural-sensitive languages, use `_one` and `_other` suffixes 4. **Avoid conflicting flat keys** - During build, flat dot-separated keys (e.g., 'exif.custom.rendered.custom') are automatically converted to nested objects, which can cause conflicts. For example, 'exif.custom.rendered.custom' conflicts with 'exif.custom.rendered'. Avoid such patterns. 5. **Never use `defaultValue` in translations** - Always add proper translations to all three required language files: `en.json`, `zh-CN.json`, and `ja.json` in the appropriate feature directories under `locales/` +6. **Top-scope variables with translatable content** - Use `const` assertions (`as const`) instead of functions for type safety Example: diff --git a/PRPs/adaptive-entry-content-layouts.md b/PRPs/adaptive-entry-content-layouts.md new file mode 100644 index 000000000..da04e447b --- /dev/null +++ b/PRPs/adaptive-entry-content-layouts.md @@ -0,0 +1,384 @@ +# PRP: Adaptive Entry Content Layouts for Different Media Types + +## Overview + +Transform the entry content display system from a fixed, article-centric layout to an adaptive system that renders different layouts optimized for specific media types (Social Media, Pictures, Videos, Articles). This will provide media-appropriate viewing experiences that match popular platform conventions while leveraging existing component patterns from the entry list items. + +## Current Implementation Analysis + +### Current Architecture + +- **Fixed Entry Content Layout**: `EntryContent.tsx` uses article-centric structure: Header → Title → AI Summary → Content Body → Attachments → Support Creator +- **Entry List Differentiation**: Entry list items already have adaptive layouts via `getItemComponentByView()` mapping +- **View-Type System**: `FeedViewType` enum defines Articles, SocialMedia, Pictures, Videos, Audios, Notifications +- **Template System**: GridItemTemplate and ListItemTemplate provide consistent patterns for different view types + +### Current Entry Content Structure + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx` + +```typescript +// Current fixed structure for all entry types +
+ + // Prominent title display + // AI-generated summary + // Main content + // File attachments + // Creator support section +
+``` + +### Existing Adaptive Patterns in Entry List Items + +#### Social Media Item Pattern (`social-media-item.tsx`) + +- **Layout**: Avatar left, content right with author name → content → media gallery +- **Content Handling**: Collapsible content with "show more", minimal title prominence +- **Media**: Adaptive gallery (horizontal vs grid based on aspect ratios) + +#### Picture Item Pattern (`picture-item.tsx`) + +- **Layout**: Image carousel with footer metadata +- **Media**: SwipeMedia component for multiple images, masonry layout support +- **Content**: Author info and metadata in footer + +#### Video Item Pattern (`video-item.tsx`) + +- **Layout**: Video player/thumbnail → author/title → description +- **Media**: Preview on hover, modal video player, duration overlay +- **Content**: Title and description below video + +### Current Limitations + +1. **EntryContent ignores view type**: All entries use identical article layout regardless of `feedViewType` +2. **Poor UX for non-article content**: Social media posts show unnecessary titles, videos buried in text +3. **Unused adaptive patterns**: Entry list items have perfect media layouts that aren't leveraged in content view +4. **Inconsistent experience**: Different UX between entry list (adaptive) and entry content (fixed) + +## Proposed Solution + +### Architecture Changes + +Create an adaptive entry content system that selects appropriate layout components based on `FeedViewType`, leveraging existing patterns from entry list items while optimizing for full content display. + +### Component Factory Pattern + +Use factory pattern to dynamically select layout components: + +```typescript +const EntryContentLayoutFactory = { + [FeedViewType.Articles]: ArticleLayout, + [FeedViewType.SocialMedia]: SocialMediaLayout, + [FeedViewType.Pictures]: PicturesLayout, + [FeedViewType.Videos]: VideosLayout, + [FeedViewType.Audios]: AudioLayout, + [FeedViewType.Notifications]: ArticleLayout, // fallback +} +``` + +### Layout-Specific Components + +#### 1. SocialMediaLayout + +**Pattern**: Based on `social-media-item.tsx` but optimized for full content view + +```typescript +// Layout: Avatar + Author Info + Content + Media Gallery +
+ {/* Author avatar */} +
+ {/* Author name, handle, timestamp */} + {/* Social media content */} + {/* Adaptive image/video gallery */} + {/* AI summary if available */} +
+
+``` + +#### 2. PicturesLayout + +**Pattern**: Based on `picture-item.tsx` and `PreviewMediaContent.tsx` + +```typescript +// Layout: Image Carousel + Sidebar with metadata +
+
{/* Image area */} + +
+
{/* Sidebar */} + + + + +
+
+``` + +#### 3. VideosLayout + +**Pattern**: Based on `video-item.tsx` but full-sized + +```typescript +// Layout: Video Player + Title/Description below +
+
{/* Video area */} + +
+
{/* Content area */} + + + + +
+
+``` + +#### 4. ArticleLayout (Current) + +**Pattern**: Keep existing layout for articles + +```typescript +// Current article structure preserved + + + + + + +``` + +## Implementation Tasks + +### Phase 1: Core Architecture Setup + +#### 1. Create Layout Factory System + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/factory.ts` + +```typescript +export const getEntryContentLayout = (viewType: FeedViewType) => { + return EntryContentLayoutFactory[viewType] || ArticleLayout +} +``` + +#### 2. Create Base Layout Components + +**Files**: + +- `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx` +- `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx` +- `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/VideosLayout.tsx` +- `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx` + +#### 3. Update EntryContent Component + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx` + +```typescript +// Replace fixed layout with factory-based selection +const LayoutComponent = getEntryContentLayout(entry.feedViewType) +return +``` + +### Phase 2: Layout Implementation + +#### 4. Implement SocialMediaLayout + +- Extract author display logic from `social-media-item.tsx` +- Implement adaptive media gallery +- Handle collapsible content with proper full-view sizing +- Reference: Twitter-like layout patterns + +#### 5. Implement PicturesLayout + +- Integrate `SwipeMedia` component for image carousel +- Create sidebar layout for metadata +- Handle single vs multiple images +- Reference: Instagram-like layout patterns + +#### 6. Implement VideosLayout + +- Integrate video player functionality from `video-item.tsx` +- Add video controls and duration display +- Layout title/description below video +- Reference: YouTube-like layout patterns + +#### 7. Extract ArticleLayout + +- Move current `EntryContent` structure to dedicated `ArticleLayout` +- Ensure no regression in article viewing experience + +### Phase 3: Shared Components + +#### 8. Create Shared UI Components + +- `AuthorHeader`: Consistent author display (avatar, name, timestamp) +- `ContentBody`: Adaptive content rendering with markdown support +- `MediaGallery`: Reusable media gallery component +- `VideoPlayer`: Consistent video player wrapper + +#### 9. Update Entry Context Provider + +- Ensure entry context includes `feedViewType` information +- Add layout-specific metadata handling + +### Phase 4: Testing & Polish + +#### 10. Responsive Design Implementation + +- Mobile layouts for each media type +- Tablet adaptations +- Handle edge cases (missing media, long content) + +#### 11. Animation & Transitions + +- Smooth layout transitions when switching between entries +- Media loading states and placeholders +- Maintain existing animation patterns + +## Context & References + +### Existing Codebase Patterns + +- **Entry List Items**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/` - Perfect reference patterns +- **Media Components**: `SwipeMedia`, `PreviewMediaContent`, `Media` - Reusable media handling +- **Template System**: `GridItemTemplate` - Consistent footer patterns +- **View Type System**: `getItemComponentByView()` - Proven factory pattern implementation + +### External Documentation & Best Practices + +- **Factory Pattern**: https://dev.to/moayad523/stop-using-conditional-rendering-leveraging-the-factory-pattern-for-dynamic-component-creation-740 +- **React Conditional Rendering**: https://react.dev/learn/conditional-rendering +- **Switch Pattern**: https://dev.to/musatov/conditional-rendering-in-react-with-a-switch-component-23ph +- **Social Media Layouts**: https://github.com/thisisadityarao/react-social-media-cards +- **Instagram Layout Patterns**: https://github.com/natividadesusana/instagram-layout-react +- **Adaptive Design**: https://www.interaction-design.org/literature/topics/adaptive-design +- **React Social Media Embed**: https://www.npmjs.com/package/react-social-media-embed + +### UI Reference Platforms + +- **Social Media**: Twitter's post layout with avatar, author info, and content +- **Pictures**: Instagram's image carousel with sidebar metadata +- **Videos**: YouTube's video player with title/description below +- **Articles**: Current Follow article layout (preserve existing UX) + +## Validation Gates + +### Code Quality + +```bash +# TypeScript validation +pnpm run typecheck + +# Linting +pnpm run lint:tsl +pnpm run lint + +# Format validation +pnpm run format + +# Build validation +pnpm run build:web +``` + +### Functional Testing + +```bash +# Manual testing checklist +1. Social Media entries → Avatar left, content right, proper media gallery +2. Picture entries → Image carousel + sidebar metadata, multiple image handling +3. Video entries → Video player + title/description below, controls work +4. Article entries → No regression, identical to current layout +5. Mixed feed → Layout switches appropriately between entry types +6. Mobile responsive → All layouts adapt properly to mobile screens +7. Media loading → Proper loading states and error handling +``` + +### Performance Validation + +- Bundle size impact analysis (should be minimal due to code splitting) +- Layout shift measurement (should be zero) +- Media loading performance maintained +- Memory usage with multiple media types + +## Success Criteria + +- [ ] Social media entries display with Twitter-like layout (avatar + author + content) +- [ ] Picture entries display with Instagram-like layout (carousel + sidebar) +- [ ] Video entries display with YouTube-like layout (player + title below) +- [ ] Article entries maintain identical current layout +- [ ] Factory pattern correctly selects layout based on `FeedViewType` +- [ ] All existing functionality preserved (AI summary, attachments, etc.) +- [ ] Mobile responsive design works across all layouts +- [ ] No performance regression in entry switching +- [ ] No bundle size increase over 5% +- [ ] All media loading states properly handled + +## Risk Mitigation + +### Potential Issues + +1. **Layout Complexity**: Different layouts might conflict with existing entry content container sizing +2. **Media Loading**: Complex media components might impact performance +3. **Mobile Responsiveness**: Desktop-optimized layouts might break on mobile +4. **Bundle Size**: Adding multiple layout components could increase bundle size +5. **Component Dependencies**: Shared components might have circular dependencies + +### Mitigation Strategies + +1. **Container Isolation**: Use CSS containment and absolute positioning where needed +2. **Lazy Loading**: Implement code splitting for layout components +3. **Mobile-First**: Design mobile layouts first, then enhance for desktop +4. **Bundle Analysis**: Use webpack-bundle-analyzer to monitor size impact +5. **Dependency Management**: Clear component hierarchy and shared utilities in separate files + +### Rollback Strategy + +- Feature flag implementation to toggle between old and new layouts +- Gradual rollout by `FeedViewType` (start with least-used types) +- Database flag to disable adaptive layouts per user preference + +## Additional Considerations + +### Accessibility + +- Ensure all layouts maintain proper heading hierarchy +- Video players must support keyboard navigation +- Image carousels need proper ARIA labels +- Screen reader compatibility across all layouts + +### i18n Support + +- All new text elements properly localized +- Layout adjustments for RTL languages +- Consistent translation keys across layouts + +### Future Extensibility + +- Audio layout placeholder implementation +- Plugin system for custom layout types +- Theme system integration for layout variants + +## Confidence Score: 9/10 + +This PRP provides a comprehensive implementation approach with: + +- ✅ **Detailed codebase analysis**: Complete understanding of existing patterns and architecture +- ✅ **Proven patterns**: Leveraging successful entry list item layouts +- ✅ **Factory pattern**: Clean, extensible architecture for layout selection +- ✅ **External research**: Best practices from social media layout implementations +- ✅ **Existing components**: Reusing proven media handling components +- ✅ **Clear implementation path**: Phased approach with specific file references +- ✅ **Risk mitigation**: Identified potential issues with concrete solutions +- ✅ **Executable validation**: Specific testing steps and success criteria + +High confidence is justified because: + +1. **Existing foundation**: Entry list items already demonstrate successful adaptive patterns +2. **Component reuse**: Media components (`SwipeMedia`, `PreviewMediaContent`) are proven +3. **Clear architecture**: Factory pattern is well-established in the codebase +4. **External validation**: Research confirms best practices align with proposed approach +5. **Minimal breaking changes**: Articles maintain existing layout, reducing regression risk + +The main implementation involves connecting existing successful patterns rather than building entirely new systems, significantly reducing complexity and risk. diff --git a/PRPs/adaptive-entry-layouts-fixes.md b/PRPs/adaptive-entry-layouts-fixes.md new file mode 100644 index 000000000..5efef6b4c --- /dev/null +++ b/PRPs/adaptive-entry-layouts-fixes.md @@ -0,0 +1,530 @@ +# PRP: Fix Adaptive Entry Content Layout Issues + +## Overview + +Fix specific layout and functionality issues in the existing adaptive entry content layouts implemented in `PRPs/adaptive-entry-content-layouts.md`. The adaptive layouts are working but have implementation issues that affect user experience across Social Media, Pictures, and Videos layouts. + +## Current Issues Analysis + +### Current Implementation Status + +The adaptive layout factory system is successfully implemented: + +- **Factory System**: `getEntryContentLayout()` in `layouts/factory.ts` correctly routes to layout-specific components +- **Layout Components**: SocialMediaLayout, PicturesLayout, VideosLayout, ArticleLayout are created +- **Integration**: `AdaptiveContentRenderer` in `EntryContent.tsx` properly uses the factory pattern + +### Specific Issues Identified + +#### 1. Social Media Layout Issues + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx` + +**Problem 1**: Duplicate Author Display + +- Lines 47-54: Shows `AuthorHeader` with avatar (48px size) +- Lines 58-62: Shows another `AuthorHeader` without avatar +- **Result**: Author name appears twice in the layout + +**Problem 2**: Show More Button Logic Still Present + +- Lines 40-42: Uses `autoExpandLongSocialMedia` setting to conditionally show `CollapsedSocialMediaItem` +- Lines 96-143: `CollapsedSocialMediaItem` implements "show more" button with LRU cache +- **User Request**: Remove this logic entirely and force full display + +**Problem 3**: AI Summary Position + +- Line 87: `` is at the bottom of the content +- **User Request**: Move AI summary to the top of the layout + +#### 2. Pictures Layout Issues + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx` + +**Problem**: Mixed Media and Text Content + +- Current implementation uses `SwipeMedia` for carousel but doesn't follow "PreviewMediaContent logic" +- Text content mixed with multimedia content +- **User Request**: Separate multimedia content (using PreviewMediaContent) from text content + +#### 3. Videos Layout Issues + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/VideosLayout.tsx` + +**Problem 1**: VideoPlayer Using Mini Player + +- VideoPlayer component (`shared/VideoPlayer.tsx` lines 56-71) creates both `miniIframeSrc` and `iframeSrc` +- Lines 129-133: Uses `miniIframeSrc` for preview/hover (optimized for small sizes) +- **User Request**: Use `iframeSrc` directly for better large-screen experience + +**Problem 2**: Content Duplication + +- `ContentBody` component (lines 61-66) renders with `noMedia={false}` by default +- This includes images/iframes in text content that duplicate what's shown in video player +- **User Request**: Remove multimedia elements from text content, show only text + +## Proposed Solutions + +### 1. Social Media Layout Fixes + +#### 1.1 Fix Duplicate Author Display + +Remove the separate avatar display and use single AuthorHeader with proper positioning: + +```typescript +// Current problematic structure (lines 45-62): +
+ {/* Avatar */} +
+ +
+ {/* Content */} +
+ + // ... rest of content +
+
+ +// Fixed structure - single author header: +
+ +
+ + // ... content follows +
+
+``` + +#### 1.2 Remove Show More Logic + +Replace conditional wrapper with direct content display: + +```typescript +// Remove lines 40-42 autoExpandLongSocialMedia logic +// Remove lines 96-143 CollapsedSocialMediaItem component entirely + +// Replace EntryContentWrapper usage (lines 66-73) with direct ContentBody: + +``` + +#### 1.3 Move AI Summary to Top + +Reorder components to show AI Summary after author header: + +```typescript +
+ + {/* Move to top */} + + +
+``` + +### 2. Pictures Layout Fixes + +#### 2.1 Implement PreviewMediaContent Pattern + +Replace current SwipeMedia carousel with PreviewMediaContent for better multimedia handling: + +```typescript +// Current implementation uses SwipeMedia (lines 52-61) +// Replace with PreviewMediaContent pattern: + +import { usePreviewMedia } from "~/components/ui/media/hooks" + +const PicturesLayout: React.FC = ({ entryId, ... }) => { + const entry = useEntry(entryId, (state) => ({ media: state.media, content: state.content })) + + const textContent = useMemo(() => ( +
+ {/* Text only */} + +
+ ), [entryId, ...]) + + const previewMedia = usePreviewMedia(textContent) + + return ( +
+
+ {entryMedia.length > 0 ? ( + + ) : ( +
No media content
+ )} +
+ +
+
+ +
+
+ + {textContent} {/* Separated text content */} +
+
+
+ ) +} +``` + +### 3. Videos Layout Fixes + +#### 3.1 Use Full-Size iframe Instead of Mini Player + +Modify VideoPlayer to use `iframeSrc` directly for large-screen optimization: + +```typescript +// In VideosLayout.tsx, pass preferFullSize prop to VideoPlayer: + + +// In shared/VideoPlayer.tsx, modify to respect preferFullSize: +export const VideoPlayer: React.FC = ({ + preferFullSize = false, + ...props +}) => { + const displaySrc = preferFullSize ? iframeSrc : miniIframeSrc + + return ( +
+ {displaySrc ? ( + + ) : ( + // Fallback to media preview + )} +
+ ) +} +``` + +#### 3.2 Filter Media from Text Content + +Create text-only version of ContentBody by adding `noMedia` prop: + +```typescript +// In VideosLayout.tsx (lines 61-66), add noMedia={true}: + + +// ContentBody.tsx already supports noMedia prop (line 49) +// This will filter out multimedia elements from HTML content +``` + +## Implementation Tasks + +### Phase 1: Social Media Layout Fixes + +#### Task 1.1: Fix Duplicate Author Headers + +**File**: `SocialMediaLayout.tsx` + +- Remove duplicate AuthorHeader components (lines 47-54 and 58-62) +- Use single FeedIcon + AuthorHeader pattern from original social-media-item.tsx +- Maintain proper spacing and styling + +#### Task 1.2: Remove Show More Logic + +**File**: `SocialMediaLayout.tsx` + +- Remove `autoExpandLongSocialMedia` usage (lines 40-42) +- Delete `CollapsedSocialMediaItem` component entirely (lines 96-143) +- Replace `EntryContentWrapper` with direct `ContentBody` usage + +#### Task 1.3: Reorder AI Summary Position + +**File**: `SocialMediaLayout.tsx` + +- Move `` from line 87 to after AuthorHeader +- Add appropriate spacing and styling for top position + +### Phase 2: Pictures Layout Enhancement + +#### Task 2.1: Implement PreviewMediaContent Integration + +**File**: `PicturesLayout.tsx` + +- Import and use `usePreviewMedia` hook +- Replace SwipeMedia carousel with clickable preview that opens PreviewMediaContent modal +- Separate multimedia and text content rendering + +### Phase 3: Videos Layout Enhancement + +#### Task 3.1: Update VideoPlayer for Large Screen + +**File**: `shared/VideoPlayer.tsx` + +- Add `preferFullSize` prop to use `iframeSrc` instead of `miniIframeSrc` +- Implement proper responsive design for large screens + +#### Task 3.2: Filter Text Content + +**File**: `VideosLayout.tsx` + +- Update ContentBody usage to include `noMedia={true}` prop +- Ensure multimedia elements are filtered from text display + +### Phase 4: Testing and Validation + +#### Task 4.1: Layout Validation + +- Test each layout with various entry types +- Verify author information displays correctly +- Confirm media handling works as expected +- Test responsive behavior on different screen sizes + +#### Task 4.2: Integration Testing + +- Verify factory pattern still routes correctly +- Test layout switching between different entry types +- Confirm no regressions in ArticleLayout + +## Context & References + +### Existing Codebase Components + +#### Key Files to Modify + +- `SocialMediaLayout.tsx` - Main fixes for duplicate author and show more logic +- `PicturesLayout.tsx` - PreviewMediaContent integration +- `VideosLayout.tsx` - Full-size iframe and text filtering +- `shared/VideoPlayer.tsx` - preferFullSize prop support +- `shared/ContentBody.tsx` - Already supports noMedia prop + +#### Key Files to Reference + +- `social-media-item.tsx` - Original social media layout pattern (single author header) +- `PreviewMediaContent.tsx` - Modal-based media preview with sidebar support +- `AuthorHeader.tsx` - Shared author display component +- `MediaGallery.tsx` - Media display patterns + +### External Best Practices + +#### Responsive iframe Guidelines + +- **Modern CSS Approach**: Use `aspect-ratio: 16/9` for responsive video containers +- **Large Screen Optimization**: Implement max-width constraints to prevent oversized displays +- **Performance**: Use appropriate iframe sources based on screen size and context + +**Reference**: https://blog.logrocket.com/best-practices-react-iframes/ +**Reference**: https://cloudinary.com/guides/video-effects/responsive-video-embedding-embed-video-iframe-size-relative-to-screen-size + +#### HTML Content Filtering + +- **Text Extraction**: Use `noMedia` flags to filter multimedia elements from HTML content +- **DOM-based Filtering**: Leverage existing HTML processing to remove specific tags +- **Content Separation**: Maintain clear separation between multimedia and text content + +**Reference**: Server-side content filtering approaches for media removal +**Reference**: https://www.bookstack.cn/read/crawl4ai-0.4-en/dcca2e8c0a744b29.md + +### UI Reference Patterns + +#### Social Media Layout + +- **Single Author Header**: Follow Twitter-like pattern with avatar + name + handle + timestamp +- **Content Flow**: Author → AI Summary → Text Content → Media Gallery +- **No Collapse Logic**: Display full content without truncation in content view + +#### Pictures Layout + +- **Modal Preview**: Use PreviewMediaContent for sophisticated media viewing +- **Sidebar Metadata**: Article-like sidebar with text content separate from media +- **Click to Preview**: Simple click interaction to open full preview modal + +#### Videos Layout + +- **Full-Size Player**: Use appropriate iframe source for screen size +- **Text-Only Content**: Filter multimedia from description to avoid duplication +- **Standard Flow**: Video Player → Title → Author → Description (text only) → AI Summary + +## Validation Gates + +### Code Quality + +```bash +# TypeScript validation +pnpm run typecheck + +# Linting validation +pnpm run lint:tsl +pnpm run lint + +# Format validation +pnpm run format + +# Build validation +pnpm run build:web +``` + +### Functional Testing Checklist + +#### Social Media Layout + +- [ ] Author name appears only once (not duplicated) +- [ ] Author header shows avatar, name, handle (if Twitter), and timestamp +- [ ] AI summary appears at the top, below author header +- [ ] Content displays in full without "show more" button +- [ ] Media gallery displays correctly below content +- [ ] Layout matches original social-media-item.tsx patterns + +#### Pictures Layout + +- [ ] Multimedia content separated from text content +- [ ] Clicking images opens PreviewMediaContent modal +- [ ] Sidebar displays text content with proper overflow handling +- [ ] Author header displays in sidebar +- [ ] AI summary appears in sidebar text content area + +#### Videos Layout + +- [ ] Video player uses full-size iframe (not mini version) +- [ ] Video player displays properly at large screen sizes +- [ ] Text content below video contains no duplicate images/media +- [ ] Author information displays below video +- [ ] AI summary appears at bottom of text content + +### Performance Validation + +- [ ] No layout shift when switching between entry types +- [ ] Video iframe loads appropriately for screen size +- [ ] PreviewMediaContent modal opens smoothly +- [ ] Text content filtering doesn't impact render performance +- [ ] No memory leaks with modal-based media preview + +### Responsive Design + +- [ ] All layouts adapt properly to mobile screens +- [ ] Video player maintains aspect ratio across screen sizes +- [ ] Pictures sidebar stacks properly on narrow screens +- [ ] Social media layout remains readable on all devices + +## Success Criteria + +### Primary Objectives + +- [ ] **Social Media**: Single author header, AI summary at top, no show more button +- [ ] **Pictures**: PreviewMediaContent integration, separated multimedia/text content +- [ ] **Videos**: Full-size iframe player, text-only content descriptions +- [ ] **All Layouts**: Maintain existing functionality while fixing specific issues + +### Quality Standards + +- [ ] Zero regression in ArticleLayout functionality +- [ ] Factory pattern continues to work seamlessly +- [ ] All existing media handling features preserved +- [ ] Mobile responsive design maintained across layouts +- [ ] Performance impact minimal (under 5% bundle increase) + +### User Experience Goals + +- [ ] Cleaner social media content display without duplication +- [ ] Better large-screen video viewing experience +- [ ] Sophisticated image preview with PreviewMediaContent modal +- [ ] Consistent author information display patterns +- [ ] Improved content organization with AI summaries positioned logically + +## Risk Mitigation + +### Potential Issues + +#### Component Dependencies + +**Risk**: Changes to shared components (VideoPlayer, ContentBody) could affect other areas +**Mitigation**: + +- Add new props with default values to maintain backward compatibility +- Test all existing entry list item displays +- Use feature flags if needed for gradual rollout + +#### PreviewMediaContent Integration + +**Risk**: Modal-based media preview might conflict with existing modal systems +**Mitigation**: + +- Test modal stacking behavior thoroughly +- Ensure proper cleanup of modal state +- Verify keyboard navigation continues to work + +#### Performance Impact + +**Risk**: Additional modal components and media filtering might impact performance +**Mitigation**: + +- Implement lazy loading for PreviewMediaContent modal +- Use React.memo for expensive components +- Profile render performance before and after changes + +### Rollback Strategy + +- Maintain existing layout components as backup +- Use git feature branches for each layout fix +- Implement progressive enhancement approach +- Test each layout individually before combining changes + +## Additional Considerations + +### Accessibility + +- Ensure all interactive elements have proper ARIA labels +- Maintain keyboard navigation for new modal interactions +- Preserve screen reader compatibility for author headers +- Test video player controls with assistive technologies + +### i18n Support + +- All new text elements properly localized +- Layout adjustments tested with longer text languages +- RTL language support maintained +- Consistent translation keys across layout components + +### Future Extensibility + +- Pattern established for other media types (Audio layout) +- Plugin system compatibility maintained +- Theme system integration preserved +- Component reusability across different layout contexts + +## Confidence Score: 9/10 + +This PRP provides a comprehensive fix approach with: + +- ✅ **Specific Issue Analysis**: Detailed examination of exact problems and file locations +- ✅ **Targeted Solutions**: Precise fixes for each identified issue without over-engineering +- ✅ **Existing Pattern Leverage**: Uses proven components and patterns already in codebase +- ✅ **External Research**: Incorporates best practices for responsive video and content filtering +- ✅ **Implementation Roadmap**: Clear phase-based approach with specific file changes +- ✅ **Risk Management**: Identified potential issues with concrete mitigation strategies +- ✅ **Comprehensive Testing**: Detailed validation gates and success criteria +- ✅ **Backward Compatibility**: Maintains existing functionality while implementing fixes + +High confidence because: + +1. **Focused Scope**: Addresses specific reported issues without unnecessary system changes +2. **Proven Components**: Leverages existing PreviewMediaContent, AuthorHeader, and ContentBody components +3. **Pattern Following**: Mimics successful patterns from social-media-item.tsx and other working components +4. **External Validation**: Research confirms best practices for responsive video and content filtering +5. **Minimal Risk**: Changes are contained to specific layout files with clear rollback options + +The implementation primarily involves connecting existing working components in better ways rather than building new complex systems, significantly reducing implementation complexity and risk. diff --git a/PRPs/ai-summary-chat-integration.md b/PRPs/ai-summary-chat-integration.md new file mode 100644 index 000000000..43d10cc90 --- /dev/null +++ b/PRPs/ai-summary-chat-integration.md @@ -0,0 +1,735 @@ +# PRP: AI Summary Chat Integration for Enhanced User Engagement + +## Overview + +Transform the AI chat interface from a static welcome screen to a context-aware, engagement-focused experience by integrating AI summary as initial content. This enhancement automatically displays relevant entry summaries when users open the AI chat panel, providing zero-friction conversation starters and increasing AI feature adoption through progressive disclosure patterns. + +## Current Implementation Analysis + +### Current Chat Interface Architecture + +**File**: `apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx` + +**Current Flow**: + +```typescript +// Conditional rendering based on message state +{!hasMessages && !isLoadingHistory ? ( + +) : ( + + + {(status === "submitted" || status === "streaming") && } + +)} +``` + +**WelcomeScreen Structure** (`WelcomeScreen.tsx`): + +```typescript +// Current static welcome screen +
+
+
+ // 3D AI model +

{APP_NAME} AI

// Title +

{t("welcome_description")}

// Description +
+
// Empty space +
+ {enabledShortcuts.map(...)} // Quick action shortcuts + {DEFAULT_SHORTCUTS.map(...)} // Default suggestions +
+
+
+``` + +### Existing AI Summary System + +**Summary Store** (`packages/internal/store/src/modules/summary/store.ts`): + +- **Data Structure**: `Record>` +- **Generation**: `summarySyncService.generateSummary()` with API integration +- **Hooks**: `useSummary()`, `usePrefetchSummary()`, `useSummaryStatus()` +- **Caching**: LRU cleanup with `lastAccessed` tracking + +**Visual AISummary Component** (`apps/desktop/layer/renderer/src/modules/entry-content/AISummary.tsx`): + +```typescript +// Beautiful glass-morphism design with animations +
+
+
+
+ +
+ + {t("entry_content.ai_summary")} + +
+ {summary.data && } +
+ + {summary.isLoading ? : {summary.data}} + +
+``` + +### Entry Context Integration + +**Already Implemented** (`EntryContent.ai.tsx` lines 89-98): + +```typescript +const { addOrUpdateBlock, removeBlock } = useBlockActions() +useEffect(() => { + addOrUpdateBlock({ + id: BlockSliceAction.SPECIAL_TYPES.mainEntry, + type: "mainEntry", + value: entryId, + }) + return () => { + removeBlock(BlockSliceAction.SPECIAL_TYPES.mainEntry) + } +}, [addOrUpdateBlock, entryId, removeBlock]) +``` + +**Entry Context Retrieval** (`EntryPickers.tsx` lines 15-18): + +```typescript +const mainEntryId = useAIChatStore()((s) => { + const block = s.blocks.find((b) => b.type === "mainEntry") + return block && block.type === "mainEntry" ? block.value : undefined +}) +``` + +### Current Limitations + +1. **Zero Context Awareness**: Welcome screen ignores available entry context and summary data +2. **Missed Engagement Opportunity**: Users must initiate conversation without any contextual prompts +3. **Disconnected Experience**: Rich summary data exists but isn't leveraged in chat interface +4. **Static Quick Actions**: Generic shortcuts instead of context-aware conversation starters +5. **Poor Progressive Disclosure**: No smooth transition from passive summary viewing to active conversation + +## Proposed Solution + +### Architecture Overview + +Create a context-aware chat interface that intelligently displays entry summaries as conversation starters while maintaining the existing welcome screen for non-entry contexts. The solution leverages existing summary infrastructure and visual patterns while introducing smart progressive enhancement. + +### Component Architecture + +```typescript +// Enhanced WelcomeScreen with context awareness +const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => { + const mainEntryId = useMainEntryId() + const hasEntryContext = !!mainEntryId + + return ( +
+ {hasEntryContext ? ( + + ) : ( + + )} +
+ ) +} +``` + +### Core Components + +#### 1. EntrySummaryCard Component + +**File**: `apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/EntrySummaryCard.tsx` + +**Purpose**: Display entry summary with chat-optimized styling and smart actions + +```typescript +interface EntrySummaryCardProps { + entryId: string + onSend: (message: string) => void + className?: string +} + +const EntrySummaryCard: React.FC = ({ entryId, onSend, className }) => { + const actionLanguage = useActionLanguage() + const isInReadabilitySuccess = useEntryIsInReadabilitySuccess(entryId) + const summary = usePrefetchSummary({ + entryId, + target: isInReadabilitySuccess ? "readabilityContent" : "content", + actionLanguage, + enabled: true, + }) + + const quickActions = useSmartQuickActions(summary.data, entryId) + + return ( + + {/* Header with entry context */} +
+
+
+ +
+
+
+

AI Summary

+

Ready to discuss this entry

+
+
+ +
+ + {/* Summary Content */} + + {summary.isLoading ? ( + + ) : summary.data ? ( +
+ + {String(summary.data)} + +
+ ) : ( +
+ +

Summary not available

+
+ )} +
+ + {/* Smart Quick Actions */} + {summary.data && ( +
+
+ Ask about this entry +
+
+ {quickActions.map((action, index) => ( + onSend(action.prompt)} + className={cn( + "inline-flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-all", + "bg-material-medium hover:bg-material-thick", + "border border-border/50 hover:border-border", + "text-text-secondary hover:text-text", + "hover:shadow-sm active:scale-95" + )} + > + + {action.label} + + ))} +
+
+ )} + + ) +} +``` + +#### 2. Smart Quick Actions Generator + +**File**: `apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useSmartQuickActions.ts` + +**Purpose**: Generate contextual conversation starters based on summary content and entry metadata + +```typescript +interface QuickAction { + id: string + label: string + prompt: string + icon: string + priority: number +} + +export const useSmartQuickActions = ( + summaryData: string | null, + entryId: string, +): QuickAction[] => { + const entry = useEntry(entryId) + const { t } = useTranslation("ai") + + return useMemo(() => { + if (!summaryData || !entry) return DEFAULT_ENTRY_ACTIONS + + const actions: QuickAction[] = [] + + // Content-based actions + if (summaryData.length > 500) { + actions.push({ + id: "simplify", + label: t("quick_actions.simplify"), + prompt: `Can you simplify this summary in 2-3 sentences? Focus on the main points.`, + icon: "i-mgc-edit-cute-re", + priority: 1, + }) + } + + // Entry type-based actions + if (entry.url) { + actions.push({ + id: "discuss", + label: t("quick_actions.discuss"), + prompt: `What are the key insights from this article? What should I know?`, + icon: "i-mgc-chat-cute-re", + priority: 2, + }) + } + + // Always available actions + actions.push( + { + id: "questions", + label: t("quick_actions.questions"), + prompt: `What questions should I be asking about this content?`, + icon: "i-mgc-question-cute-re", + priority: 3, + }, + { + id: "takeaways", + label: t("quick_actions.takeaways"), + prompt: `What are the most important takeaways from this entry?`, + icon: "i-mgc-star-cute-re", + priority: 4, + }, + ) + + return actions.sort((a, b) => a.priority - b.priority).slice(0, 4) + }, [summaryData, entry, t]) +} + +const DEFAULT_ENTRY_ACTIONS: QuickAction[] = [ + { + id: "analyze", + label: "Analyze this entry", + prompt: "Can you analyze this entry and tell me what it's about?", + icon: "i-mgc-search-cute-re", + priority: 1, + }, + { + id: "explain", + label: "Explain key points", + prompt: "What are the key points I should understand from this entry?", + icon: "i-mgc-lightbulb-cute-re", + priority: 2, + }, +] +``` + +#### 3. Enhanced WelcomeScreen with Context Awareness + +**File**: `apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/WelcomeScreen.tsx` (Modified) + +```typescript +export const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => { + const { t } = useTranslation("ai") + const aiSettings = useAISettingValue() + const mainEntryId = useMainEntryId() + const settingModalPresent = useSettingModal() + + const hasEntryContext = !!mainEntryId + const hasCustomPrompt = aiSettings.personalizePrompt?.trim() + const enabledShortcuts = aiSettings.shortcuts?.filter((shortcut) => shortcut.enabled) || [] + + return ( +
+
+ {/* Header Section - Always Present */} + +
+ +
+
+

{APP_NAME} AI

+

+ {hasEntryContext ? t("welcome_description_contextual") : t("welcome_description")} +

+
+
+ + {/* Dynamic Content Area */} +
+ + {hasEntryContext ? ( + + ) : ( + + )} + +
+ + {/* Personal Prompt - Always at Bottom if Present */} + {hasCustomPrompt && ( + settingModalPresent("ai")} + /> + )} +
+
+ ) +} +``` + +### Data Flow Integration + +#### Summary Prefetching Strategy + +```typescript +// In ChatInterface.tsx - Prefetch summary when entry context available +const ChatInterfaceContent = () => { + const hasMessages = useHasMessages() + const mainEntryId = useMainEntryId() + const actionLanguage = useActionLanguage() + + // Prefetch summary for context-aware welcome screen + usePrefetchSummary({ + entryId: mainEntryId || "", + target: "content", // Start with content, fallback to readability if needed + actionLanguage, + enabled: !!mainEntryId && !hasMessages, // Only when showing welcome screen + }) + + // ... rest of component +} +``` + +#### State Management Integration + +```typescript +// Custom hook for main entry context +export const useMainEntryId = (): string | undefined => { + return useAIChatStore()((state) => { + const block = state.blocks.find((b) => b.type === "mainEntry") + return block && block.type === "mainEntry" ? block.value : undefined + }) +} + +// Hook for entry summary in chat context +export const useEntrySummaryForChat = (entryId: string) => { + const actionLanguage = useActionLanguage() + const isInReadabilitySuccess = useEntryIsInReadabilitySuccess(entryId) + + return usePrefetchSummary({ + entryId, + target: isInReadabilitySuccess ? "readabilityContent" : "content", + actionLanguage, + enabled: !!entryId, + staleTime: 1000 * 60 * 60, // 1 hour - summaries don't change often + }) +} +``` + +### Animation and Visual Design + +#### Micro-interactions and Transitions + +```typescript +// Smooth transitions between welcome states +const welcomeVariants = { + entryContext: { + initial: { opacity: 0, y: 30, scale: 0.95 }, + animate: { opacity: 1, y: 0, scale: 1 }, + exit: { opacity: 0, y: -30, scale: 0.95 }, + }, + defaultWelcome: { + initial: { opacity: 0, y: 20, scale: 0.98 }, + animate: { opacity: 1, y: 0, scale: 1 }, + exit: { opacity: 0, y: -20, scale: 0.98 }, + }, +} + +// Quick action button animations +const quickActionVariants = { + initial: { opacity: 0, scale: 0.9, x: -10 }, + animate: { opacity: 1, scale: 1, x: 0 }, + hover: { scale: 1.02, y: -1 }, + tap: { scale: 0.98 }, +} +``` + +#### Consistent Design Language + +- **Glass-morphism**: Reuse AISummary visual patterns with chat-optimized spacing +- **Purple Gradient**: Maintain AI branding with purple accent colors +- **Spring Animations**: Use Spring.presets.smooth for all major transitions +- **Material Colors**: UIKit material colors for consistent depth and hierarchy +- **Responsive Typography**: Scalable text that works across different panel sizes + +## Implementation Plan + +### Phase 1: Core Functionality (MVP) + +#### Tasks (in order): + +1. **Create EntrySummaryCard Component** + - File: `apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/EntrySummaryCard.tsx` + - Reuse AISummary visual patterns + - Basic summary display with loading states + - Simple click-to-start conversation + +2. **Create useMainEntryId Hook** + - File: `apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useMainEntryId.ts` + - Extract mainEntry block value from AI chat store + - Handle undefined/null states gracefully + +3. **Modify WelcomeScreen Component** + - File: `apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/WelcomeScreen.tsx` + - Add conditional rendering based on entry context + - Integrate EntrySummaryCard component + - Maintain existing functionality for non-entry contexts + +4. **Add Summary Prefetching to ChatInterface** + - File: `apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx` + - Prefetch summary when entry context available + - Only when welcome screen is showing (no messages) + +5. **Basic Smart Quick Actions** + - File: `apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useSmartQuickActions.ts` + - Simple content-based action generation + - Default fallback actions for all entries + +6. **Update Translations** + - Add new translation keys for contextual descriptions + - Quick action labels and prompts + +### Phase 2: UX Optimization + +#### Tasks: + +7. **Enhanced Smart Quick Actions** + - Content analysis for intelligent action generation + - Entry type detection (article, social media, video) + - Priority-based action sorting + +8. **Micro-interaction Animations** + - Smooth state transitions with AnimatePresence + - Quick action button hover/tap effects + - Loading state animations with shimmer effects + +9. **Entry Quick Info Component** + - Display entry metadata (title, source, date) + - Compact design that doesn't compete with summary + - Optional component based on space constraints + +10. **Responsive Layout Adaptation** + - Floating panel vs fixed panel optimization + - Mobile-friendly touch targets + - Adaptive spacing and typography + +### Phase 3: Advanced Features + +#### Tasks: + +11. **First-time User Guidance** + - Onboarding tooltip for new feature + - Progressive disclosure of advanced features + - User preference learning + +12. **Context-aware Optimization** + - Reading progress integration + - Related entries suggestions + - Conversation history awareness + +13. **Performance Optimization** + - Summary caching improvements + - Lazy loading for non-critical components + - Bundle size optimization + +14. **A/B Testing Integration** + - Feature flag support + - Usage analytics + - Engagement metrics tracking + +## Validation Gates + +### Code Quality + +```bash +# TypeScript compilation +pnpm run typecheck + +# Linting +pnpm run lint + +# Code formatting +pnpm run format +``` + +### Testing Strategy + +```bash +# Unit tests for new hooks and components +pnpm run test apps/desktop/layer/renderer/src/modules/ai-chat + +# Integration tests for summary prefetching +pnpm run test:integration + +# E2E tests for chat interaction flows +pnpm run test:e2e -- --grep "AI Chat.*Summary" +``` + +### Manual Testing Checklist + +- [ ] **Entry Context Detection**: AI chat shows summary when viewing an entry +- [ ] **Fallback Behavior**: Default welcome screen when no entry context +- [ ] **Summary Loading**: Proper loading states and error handling +- [ ] **Quick Actions**: Context-appropriate conversation starters +- [ ] **Animations**: Smooth transitions between states +- [ ] **Responsive Design**: Works in both floating and fixed panels +- [ ] **Theme Support**: Proper light/dark mode appearance +- [ ] **Accessibility**: Keyboard navigation and screen reader support + +### Performance Metrics + +- [ ] **First Paint**: Summary content visible within 300ms +- [ ] **Bundle Impact**: <10KB addition to chat module bundle +- [ ] **Memory Usage**: No memory leaks during context switches +- [ ] **Animation Performance**: 60fps during transitions + +## Dependencies and Integration Points + +### Existing Systems Integration + +- **Summary Store**: `packages/internal/store/src/modules/summary/` +- **Entry Store**: Integration with entry context tracking +- **AI Chat Store**: Block system for entry context management +- **Translation System**: New keys for contextual content +- **Theme System**: UIKit colors and material design consistency + +### External Dependencies + +- **React Query**: Already used for summary prefetching +- **Framer Motion**: `m.` prefix components for animations +- **i18next**: Translation key expansion +- **Tailwind CSS**: UIKit color classes and material styles + +### API Integration + +- **Summary Generation**: Existing `/ai/summary` endpoint +- **No new API calls**: Reuses existing summary infrastructure +- **Caching Strategy**: Leverages existing SummaryStore LRU cache + +## Risk Assessment & Mitigation + +### Technical Risks + +1. **Performance Impact** (Low Risk) + - _Risk_: Summary prefetching could slow chat opening + - _Mitigation_: Conditional prefetching only when needed, existing cache strategy + +2. **Animation Jank** (Medium Risk) + - _Risk_: Complex animations could affect performance + - _Mitigation_: Use optimized Framer Motion patterns, test on lower-end devices + +3. **State Synchronization** (Low Risk) + - _Risk_: Entry context out of sync with chat store + - _Mitigation_: Leverage existing mainEntry block system, tested pattern + +### UX Risks + +1. **Feature Discoverability** (Medium Risk) + - _Risk_: Users may not notice the enhanced welcome screen + - _Mitigation_: Subtle onboarding hints, analytics tracking + +2. **Context Mismatch** (Low Risk) + - _Risk_: Summary doesn't match user expectations + - _Mitigation_: Clear visual hierarchy, fallback to default actions + +3. **Information Overload** (Medium Risk) + - _Risk_: Too much information in welcome screen + - _Mitigation_: Progressive disclosure, clean visual design + +## Success Metrics + +### Engagement Metrics + +- **AI Chat Adoption**: 25% increase in chat panel opens from entry context +- **Conversation Initiation**: 40% increase in messages sent from welcome screen +- **Quick Action Usage**: 60% of conversations start with context-aware quick actions +- **Session Duration**: 20% increase in average chat session length + +### Performance Metrics + +- **Load Time**: Summary content visible within 300ms +- **Error Rate**: <1% failure rate for summary loading +- **Cache Hit Rate**: >80% cache hits for recently viewed entries + +### User Satisfaction + +- **User Feedback**: Positive sentiment on enhanced chat experience +- **Feature Retention**: 70% of users who try the feature continue using it +- **Support Tickets**: No increase in AI-related support requests + +## Future Enhancements + +### Short-term (Next Quarter) + +- **Multi-language Summary Support**: Leverage existing i18n infrastructure +- **Summary Quality Feedback**: Allow users to rate summary relevance +- **Conversation Templates**: Pre-built conversation flows for common entry types + +### Medium-term (Next 6 Months) + +- **Cross-entry Conversations**: Enable discussing multiple entries in one chat +- **Smart Follow-ups**: AI-suggested next questions based on conversation context +- **Entry Annotations**: Allow highlighting specific parts of entry for discussion + +### Long-term (Next Year) + +- **Voice Interaction**: Voice commands for summary-based conversations +- **Collaborative Features**: Share AI conversations about entries +- **Advanced Analytics**: ML-driven insights on conversation patterns + +## Confidence Score: 9/10 + +This PRP provides comprehensive implementation guidance with: + +- ✅ **Detailed Architecture**: Clear component structure and data flow +- ✅ **Existing Pattern Reuse**: Leverages proven AISummary and chat patterns +- ✅ **Phased Implementation**: Incremental delivery with clear milestones +- ✅ **Risk Mitigation**: Identified potential issues with solutions +- ✅ **Testing Strategy**: Comprehensive validation approach +- ✅ **Performance Considerations**: Optimized prefetching and caching +- ✅ **UX Best Practices**: Context-aware design with progressive enhancement +- ✅ **Code Examples**: Realistic implementation snippets with proper patterns +- ✅ **Integration Points**: Clear dependencies and system boundaries +- ✅ **Success Metrics**: Measurable outcomes and validation criteria + +The implementation leverages existing, proven infrastructure while introducing meaningful enhancements that align with modern AI chat UX patterns and the application's design system. diff --git a/PRPs/android-shared-webview-image-interception.md b/PRPs/android-shared-webview-image-interception.md new file mode 100644 index 000000000..c141cb3b3 --- /dev/null +++ b/PRPs/android-shared-webview-image-interception.md @@ -0,0 +1,617 @@ +# Android SharedWebView with Image Interception Implementation + +## Objective + +Implement an Android equivalent of the iOS SharedWebView module with advanced image interception capabilities using WebView hooks instead of custom URL schemes. This will provide feature parity between iOS and Android platforms while leveraging Android's superior request interception capabilities. + +## Context + +The iOS implementation uses a custom URL scheme (`follow-image://`) to intercept image requests due to WKWebView limitations. Android WebView offers more powerful request interception through `WebViewClient.shouldInterceptRequest()`, allowing for a more elegant and performant solution. + +### Current iOS Architecture (Reference) + +- **SharedWebViewModule** (apps/mobile/native/ios/Modules/SharedWebView/SharedWebViewModule.swift) +- **WebViewManager** (apps/mobile/native/ios/Modules/SharedWebView/WebViewManager.swift) - Singleton with lifecycle management +- **FOWebView** (apps/mobile/native/ios/Modules/SharedWebView/FOWebView.swift) - Custom WKWebView +- **FollowImageURLSchemeHandler** (apps/mobile/native/ios/Modules/SharedWebView/FollowImageURLSchemeHandler.swift) - Custom scheme handler +- **WebViewState** (apps/mobile/native/ios/Modules/SharedWebView/WebViewState.swift) - Observable state management + +### Existing Android Infrastructure + +- **Module Path**: `apps/mobile/native/android/src/main/java/expo/modules/follownative/` +- **Build Configuration**: Standard Expo modules with Kotlin support +- **Naming Convention**: `expo.modules.follownative.modulename.ModuleName` +- **TypeScript Interface**: Already defined in `apps/mobile/src/components/native/webview/index.ts` + +## Implementation Requirements + +### Core Components to Implement + +1. **SharedWebViewModule.kt** - Main Expo module exposing API to React Native +2. **WebViewManager.kt** - Singleton manager for WebView lifecycle and state +3. **SharedWebViewView.kt** - Expo view component +4. **FOWebView.kt** - Custom WebView with image interception +5. **ImageInterceptClient.kt** - WebViewClient with request interception +6. **ImageCache.kt** - Memory and disk caching system +7. **WebViewState.kt** - Reactive state management with StateFlow +8. **BridgeData.kt** - Message payloads and type definitions + +### API Compatibility Requirements + +Maintain 100% compatibility with existing TypeScript interface: + +```typescript +interface ISharedWebViewModule + extends NativeModule<{ + onContentHeightChanged: ({ height }: { height: number }) => void + onImagePreview: (event: ImagePreviewEvent) => void + onSeekAudio?: (e: { time: number }) => void + }> { + load(url: string): void + evaluateJavaScript(js: string): void + dispatch?(type: string, payload?: string): void + + // Debug helpers + getDebugState?(): WebViewDebugState + destroyForDebug?(): void + reloadLastURL?(): void + flushQueue?(): void +} +``` + +## Technical Architecture + +### Image Interception Strategy (Android Advantage) + +**iOS Approach**: Custom URL scheme with JavaScript injection + +```swift +// JavaScript injection to rewrite image URLs +url.replace(/^https?:/, 'follow-image:') +// Custom WKURLSchemeHandler for follow-image:// +``` + +**Android Approach**: Native request interception (Superior) + +```kotlin +override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? { + if (isImageRequest(request)) { + return handleImageRequest(request) + } + return super.shouldInterceptRequest(view, request) +} +``` + +### Implementation Blueprint + +#### Phase 1: Core Infrastructure (Priority 1) + +```kotlin +// 1. SharedWebViewModule.kt +@ExpoModule(name = "FOSharedWebView") +class SharedWebViewModule : Module() { + private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob()) + + override fun definition() = ModuleDefinition { + Name("FOSharedWebView") + + Function("load") { urlString: String -> + WebViewManager.load(urlString) + } + + Function("evaluateJavaScript") { js: String -> + WebViewManager.evaluateJavaScript(js) + } + + Function("dispatch") { type: String, payload: String? -> + WebViewManager.dispatch(type, payload) + } + + View(SharedWebViewView::class) { + Events("onContentHeightChange", "onSeekAudio") + Prop("url") { view: SharedWebViewView, url: String -> + WebViewManager.load(url) + } + } + + Events("onContentHeightChanged", "onImagePreview", "onSeekAudio") + + OnCreate { + WebViewManager.initializeLifecycleObservers(appContext.currentActivity!!) + } + + OnStartObserving { + // StateFlow subscriptions for reactive events + WebViewManager.state.contentHeight.onEach { height -> + sendEvent("onContentHeightChanged", mapOf("height" to height)) + }.launchIn(coroutineScope) + } + + OnStopObserving { + coroutineScope.cancel() + } + + // Debug functions + Function("getDebugState") { WebViewManager.getDebugState() } + Function("destroyForDebug") { WebViewManager.destroyForDebug() } + Function("reloadLastURL") { WebViewManager.reloadLastURL() } + Function("flushQueue") { WebViewManager.flushQueue() } + } +} +``` + +```kotlin +// 2. WebViewManager.kt - Singleton with lifecycle management +object WebViewManager { + val state = WebViewState() + private var sharedWebView: FOWebView? = null + private var currentHost: ViewGroup? = null + private var isReady = false + private val pendingScripts = mutableListOf() + private var lastUrl: String? = null + private val lastState = mutableMapOf() + + fun initializeLifecycleObservers(activity: Activity) { + val observer = object : DefaultLifecycleObserver { + override fun onPause(owner: LifecycleOwner) { onEnterBackground() } + override fun onResume(owner: LifecycleOwner) { onEnterForeground() } + } + (activity as ComponentActivity).lifecycle.addObserver(observer) + } + + fun load(urlString: String) { + MainScope().launch { + lastUrl = urlString + val webView = getOrCreateWebView() + if (webView.url == urlString && !isLoading(webView)) return@launch + isReady = false + webView.loadUrl(urlString) + } + } + + fun attach(host: ViewGroup) { + MainScope().launch { + val webView = getOrCreateWebView() + (webView.parent as? ViewGroup)?.removeView(webView) + host.addView(webView) + currentHost = host + } + } + + private fun getOrCreateWebView(): FOWebView { + return sharedWebView ?: FOWebView(context, state).also { sharedWebView = it } + } + + private fun onEnterBackground() { + if (currentHost == null) { + MainScope().launch { + delay(3000) + if (currentHost == null) destroyWebView() + } + } + } + + private fun onEnterForeground() { + if (sharedWebView == null) { + getOrCreateWebView() + lastUrl?.let { load(it) } + replayState() + } + } +} +``` + +#### Phase 2: Image Interception System (Priority 1) + +```kotlin +// 3. ImageInterceptClient.kt - Advanced request interception +class ImageInterceptClient( + private val imageCache: ImageCache, + private val baseClient: WebViewClient? = null +) : WebViewClient() { + + companion object { + private val IMAGE_MIME_TYPES = setOf( + "image/jpeg", "image/jpg", "image/png", "image/gif", + "image/webp", "image/svg+xml", "image/avif" + ) + } + + override fun shouldInterceptRequest( + view: WebView?, + request: WebResourceRequest? + ): WebResourceResponse? { + val url = request?.url?.toString() ?: return super.shouldInterceptRequest(view, request) + + if (!isImageRequest(request)) { + return baseClient?.shouldInterceptRequest(view, request) + ?: super.shouldInterceptRequest(view, request) + } + + return handleImageRequest(view, request) + } + + private fun isImageRequest(request: WebResourceRequest): Boolean { + val url = request.url.toString() + val acceptHeader = request.requestHeaders["Accept"] ?: "" + + // Multi-strategy detection + return acceptHeader.contains("image/") || + url.substringAfterLast('.', "").lowercase() in IMAGE_EXTENSIONS || + url.contains(Regex("/(images?|img|pics?|photos?|assets)/", RegexOption.IGNORE_CASE)) + } + + private fun handleImageRequest( + view: WebView?, + request: WebResourceRequest + ): WebResourceResponse? { + val url = request.url.toString() + val cacheKey = url + + // Check cache first + imageCache.get(cacheKey)?.let { cachedData -> + return createImageResponse(cachedData, detectMimeType(cachedData)) + } + + // Network request with proper headers + return try { + val modifiedRequest = buildImageRequest(request) + val response = executeImageRequest(modifiedRequest) + + response?.let { (data, mimeType) -> + imageCache.put(cacheKey, data) + createImageResponse(data, mimeType) + } + } catch (e: Exception) { + Log.w("ImageIntercept", "Failed to load image: $url", e) + null // Fallback to default WebView behavior + } + } + + private fun buildImageRequest(original: WebResourceRequest): HttpURLConnection { + val connection = URL(original.url.toString()).openConnection() as HttpURLConnection + + // Copy original headers + original.requestHeaders.forEach { (key, value) -> + if (!isRestrictedHeader(key)) { + connection.setRequestProperty(key, value) + } + } + + // Optimize for images + connection.setRequestProperty("Accept", "image/webp,image/avif,image/*,*/*;q=0.8") + connection.setRequestProperty("User-Agent", + "Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36 Mobile Safari/537.36") + + // Set referer for CORS compatibility + original.url.let { url -> + val referer = "${url.scheme}://${url.host}" + connection.setRequestProperty("Referer", referer) + } + + connection.connectTimeout = 10000 + connection.readTimeout = 15000 + return connection + } + + private fun createImageResponse(data: ByteArray, mimeType: String): WebResourceResponse { + val headers = mapOf( + "Access-Control-Allow-Origin" to "*", + "Cache-Control" to "public, max-age=3600", + "Content-Length" to data.size.toString() + ) + + return WebResourceResponse(mimeType, "utf-8", 200, "OK", headers, ByteArrayInputStream(data)) + } +} +``` + +```kotlin +// 4. ImageCache.kt - High-performance caching system +class ImageCache(private val context: Context) { + private val memoryCache = LruCache(16 * 1024 * 1024) // 16MB + private val diskCacheDir = File(context.cacheDir, "webview_images") + + init { + if (!diskCacheDir.exists()) diskCacheDir.mkdirs() + } + + fun get(key: String): ByteArray? { + // Memory first, then disk + return memoryCache.get(key) ?: getDiskCache(key)?.also { + memoryCache.put(key, it) + } + } + + fun put(key: String, data: ByteArray) { + memoryCache.put(key, data) + putDiskCache(key, data) + } + + private fun getDiskCache(key: String): ByteArray? = try { + val file = getCacheFile(key) + if (file.exists() && System.currentTimeMillis() - file.lastModified() < 24 * 60 * 60 * 1000) { + file.readBytes() + } else null + } catch (e: Exception) { null } + + private fun putDiskCache(key: String, data: ByteArray) { + try { + getCacheFile(key).writeBytes(data) + } catch (e: Exception) { + Log.w("ImageCache", "Failed to cache image", e) + } + } + + private fun getCacheFile(key: String): File { + val fileName = key.hashCode().toString(16) + ".cache" + return File(diskCacheDir, fileName) + } +} +``` + +#### Phase 3: State Management and Views (Priority 2) + +```kotlin +// 5. WebViewState.kt - Reactive state management +class WebViewState { + private val _contentHeight = MutableStateFlow(Resources.getSystem().displayMetrics.heightPixels.toFloat()) + val contentHeight: StateFlow = _contentHeight.asStateFlow() + + private val _imagePreviewEvent = MutableStateFlow(null) + val imagePreviewEvent: StateFlow = _imagePreviewEvent.asStateFlow() + + private val _audioSeekEvent = MutableStateFlow(null) + val audioSeekEvent: StateFlow = _audioSeekEvent.asStateFlow() + + fun updateContentHeight(height: Float) { _contentHeight.value = height } + fun triggerImagePreview(urls: List, index: Int) { + _imagePreviewEvent.value = ImagePreviewEvent(urls, index) + } + fun triggerAudioSeek(time: Double) { + _audioSeekEvent.value = AudioSeekEvent(time) + } +} + +data class ImagePreviewEvent(val imageUrls: List, val index: Int) +data class AudioSeekEvent(val time: Double) +``` + +```kotlin +// 6. FOWebView.kt - Custom WebView implementation +class FOWebView(context: Context, private val state: WebViewState) : WebView(context) { + + private val imageCache = ImageCache(context) + private val baseWebViewClient = FOWebViewClient() + private val javascriptInterface = JavaScriptInterface(state) + + init { + setupWebView() + webViewClient = ImageInterceptClient(imageCache, baseWebViewClient) + webChromeClient = FOWebChromeClient() + addJavaScriptInterface(javascriptInterface, "Android") + } + + private fun setupWebView() { + settings.apply { + javaScriptEnabled = true + domStorageEnabled = true + allowFileAccess = true + allowContentAccess = true + loadsImagesAutomatically = true + blockNetworkImage = false + cacheMode = WebSettings.LOAD_DEFAULT + setAppCacheEnabled(true) + } + + // Inject JavaScript bridge + injectBridgeScript() + } + + private fun injectBridgeScript() { + val script = """ + ;(() => { + window.__RN__ = true + + function send(data) { + Android.postMessage(JSON.stringify(data)) + } + + window.bridge = { + measure: () => send({ type: "measure" }), + setContentHeight: (height) => send({ type: "setContentHeight", payload: height }), + previewImage: (data) => send({ type: "previewImage", payload: data }), + seekAudio: (time) => send({ type: "audio:seekTo", payload: { time } }) + } + + // Signal readiness + document.addEventListener("DOMContentLoaded", () => { + send({ type: "ready" }) + }) + })() + """ + evaluateJavascript(script, null) + } + + fun clearImageCache() { imageCache.clear() } +} +``` + +#### Phase 4: Integration and Testing (Priority 3) + +### File Structure to Create + +``` +apps/mobile/native/android/src/main/java/expo/modules/follownative/sharedwebview/ +├── SharedWebViewModule.kt # Main Expo module +├── SharedWebViewView.kt # Expo view component +├── WebViewManager.kt # Singleton WebView manager +├── FOWebView.kt # Custom WebView implementation +├── ImageInterceptClient.kt # Request interception logic +├── ImageCache.kt # Caching system +├── WebViewState.kt # State management +├── BridgeData.kt # Message payloads +└── JavaScriptInterface.kt # WebView-to-native bridge +``` + +### Configuration Updates Required + +1. **expo-module.config.json** - Add new Android module: + +```json +{ + "android": { + "modules": [ + "expo.modules.follownative.sharedwebview.SharedWebViewModule" + // ... existing modules + ] + } +} +``` + +2. **Android Gradle Dependencies** - Add to `apps/mobile/native/android/build.gradle`: + +```gradle +dependencies { + implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.6" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0" +} +``` + +## Implementation Tasks + +### Phase 1: Core Infrastructure (Week 1) + +1. Create module structure and base classes +2. Implement SharedWebViewModule.kt with Expo module definition +3. Implement WebViewManager.kt singleton with lifecycle management +4. Implement WebViewState.kt with StateFlow-based reactive state +5. Create basic SharedWebViewView.kt Expo view component + +### Phase 2: Image Interception System (Week 1-2) + +1. Implement ImageInterceptClient.kt with shouldInterceptRequest logic +2. Build ImageCache.kt with memory and disk caching +3. Create image request detection and classification system +4. Implement network request handling with proper headers +5. Add MIME type detection and response creation + +### Phase 3: WebView Integration (Week 2) + +1. Implement FOWebView.kt custom WebView +2. Create JavaScriptInterface.kt for native-JS communication +3. Add JavaScript bridge injection and message handling +4. Implement content height tracking and layout updates +5. Add debug utilities and state inspection tools + +### Phase 4: Testing and Integration (Week 2-3) + +1. Create comprehensive unit tests for each component +2. Implement integration tests with mock WebView scenarios +3. Add performance tests for image caching and request interception +4. Test cross-platform API compatibility with iOS implementation +5. Validate memory management and lifecycle behavior + +### Phase 5: Documentation and Deployment (Week 3) + +1. Update expo-module.config.json with new Android module +2. Add necessary Gradle dependencies and configurations +3. Create comprehensive documentation for the implementation +4. Update TypeScript definitions if needed +5. Perform final testing and validation + +## Validation Gates + +### Build Validation + +```bash +cd apps/mobile/native/android +./gradlew assembleDebug +``` + +### Code Quality Checks + +```bash +cd apps/mobile +npm run typecheck +``` + +### Functional Testing + +```bash +# Test module loading +adb logcat | grep "FOSharedWebView" + +# Test image interception +# Navigate to image-heavy content and verify cache behavior +``` + +### Performance Testing + +```kotlin +// Measure image cache hit rates and memory usage +WebViewManager.getImageCacheStats().let { stats -> + assertTrue("Cache hit rate should be > 80%", stats.hitRate > 0.8) + assertTrue("Memory usage should be < 50MB", stats.memoryUsage < 50 * 1024 * 1024) +} +``` + +### Cross-Platform Compatibility Testing + +```javascript +// Verify identical API behavior across platforms +const debugState = await SharedWebViewModule.getDebugState() +expect(debugState).toHaveProperty("hasWebView") +expect(debugState).toHaveProperty("contentHeight") +``` + +## Documentation and References + +### Essential References + +- [Expo Modules API Documentation](https://docs.expo.dev/modules/overview/) +- [Native View Tutorial](https://docs.expo.dev/modules/native-view-tutorial/) +- [Android WebView Request Interception](https://medium.com/@pouryarezaee76/intercepting-requests-in-android-webview-8eb628b32f2a) +- [WebView Security Best Practices](https://blog.oversecured.com/Android-Exploring-vulnerabilities-in-WebResourceResponse/) + +### Key Implementation Files to Reference + +- `apps/mobile/native/ios/Modules/SharedWebView/` - Complete iOS implementation +- `apps/mobile/native/android/src/main/java/expo/modules/follownative/FollowNativeModule.kt` - Existing module patterns +- `apps/mobile/src/components/native/webview/index.ts` - TypeScript API interface + +### Critical Security Considerations + +1. **Request Validation**: Always validate URLs before processing to prevent malicious requests +2. **Header Sanitization**: Filter restricted headers to prevent security vulnerabilities +3. **File Access Limiting**: Restrict file:// URL access to app bundle resources only +4. **Content Security**: Implement proper CSP headers for loaded content +5. **Bridge Data Validation**: Validate all JavaScript bridge message payloads + +## Expected Outcomes + +### Performance Improvements over iOS + +- **No URL Rewriting Overhead**: Direct request interception vs. JavaScript URL manipulation +- **Better Error Handling**: Graceful fallback to default WebView behavior on failure +- **Enhanced Debugging**: Standard HTTP request debugging vs. custom scheme debugging +- **Improved Reliability**: No dependency on JavaScript injection success + +### Feature Parity Achievement + +- 100% API compatibility with iOS implementation +- Identical event handling and state management +- Same debugging capabilities and state inspection tools +- Consistent caching behavior and memory management + +### Success Metrics + +- Image cache hit rate > 90% +- Memory usage < 64MB for typical usage +- Zero crashes related to WebView lifecycle management +- API response time < 50ms for cached resources +- Cross-platform test suite passing rate > 99% + +## Confidence Score: 9/10 + +This PRP provides comprehensive context, detailed implementation blueprints, existing code patterns to follow, specific file references, security considerations, and executable validation gates. The Android implementation leverages superior platform capabilities while maintaining complete API compatibility with iOS. All necessary technical context, external documentation, and testing patterns are included to enable successful one-pass implementation. diff --git a/PRPs/enhanced-ai-usage-observability-frontend.md b/PRPs/enhanced-ai-usage-observability-frontend.md new file mode 100644 index 000000000..b90edae01 --- /dev/null +++ b/PRPs/enhanced-ai-usage-observability-frontend.md @@ -0,0 +1,938 @@ +name: "Enhanced AI Usage Observability Frontend" +description: | +Frontend implementation for enhanced AI token usage observability with real-time +tracking, predictive analytics, and user-centered visualizations. Integrates with +the backend API from enhanced-ai-usage-observability.md to provide comprehensive +usage insights in both AI settings tab and dedicated analytics page. + +## Purpose + +Implement comprehensive React-based frontend for AI usage observability that transforms raw token statistics into actionable user insights through intuitive visualizations, real-time feedback, and predictive warnings. + +## Core Principles + +1. **Component Reusability**: Build modular components following Follow's SettingBuilder patterns +2. **Real-time Updates**: Use React Query for efficient data synchronization and caching +3. **Progressive Disclosure**: Simple overview in AI tab, detailed analysis in separate page +4. **Visual Clarity**: Use charts and progress indicators for immediate comprehension +5. **Mobile Responsive**: Ensure consistent experience across desktop and mobile + +--- + +## Goal + +Create React frontend components that consume enhanced AI usage analytics APIs to provide users with real-time session tracking, usage pattern insights, predictive warnings, and optimization recommendations through intuitive visualizations. + +## Why + +- **User Empowerment**: Transform technical token counts into actionable usage insights +- **Cost Awareness**: Provide real-time feedback on current session costs and efficiency +- **Proactive Management**: Warn users before hitting rate limits through predictive analytics +- **Usage Optimization**: Help users understand and optimize their AI consumption patterns +- **Seamless Integration**: Integrate naturally into existing AI settings workflow + +## What + +Frontend implementation with: + +1. **AI Tab Integration**: Compact usage analysis section in AI settings +2. **Detailed Analytics Page**: Enhanced token-usage page with comprehensive charts +3. **Real-Time Tracking**: Live session usage and progress indicators +4. **Predictive Warnings**: Visual alerts for approaching rate limits +5. **Usage Visualizations**: Charts for trends, feature distribution, and model efficiency + +### Success Criteria + +- [ ] AI Tab shows simplified usage overview with key metrics and warnings +- [ ] Token usage page displays comprehensive analytics with interactive charts +- [ ] Real-time session tracking updates every 10 seconds +- [ ] Predictive warnings appear when rate limit risk is detected +- [ ] Charts render usage patterns, feature distribution, and efficiency comparisons +- [ ] Mobile responsive design maintains usability on smaller screens +- [ ] Components follow existing Follow UI patterns and design system +- [ ] All user-facing text is properly internationalized + +## All Needed Context + +### Documentation & References + +```yaml +# MUST READ - Include these in your context window +- file: apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx + why: Current AI settings page structure and SettingBuilder pattern + +- file: apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage.tsx + why: Existing token usage component to enhance and reference + +- file: apps/desktop/layer/renderer/src/modules/ai-task/query.ts + why: React Query patterns and query key hierarchies used in Follow + +- file: apps/desktop/layer/renderer/src/modules/settings/tabs/ai/mcp/MCPServicesSection.tsx + why: Component structure patterns, useQuery usage, error handling + +- file: apps/desktop/layer/renderer/src/modules/settings/tabs/ai/PanelStyleSection.tsx + why: SettingTabbedSegment usage and section component patterns + +- file: packages/internal/components/src/ui/progress/index.tsx + why: Progress component for usage indicators + +- file: apps/desktop/layer/renderer/src/lib/api-client.ts + why: followClient usage and API integration patterns + +- doc: https://recharts.org/en-US/api + section: LineChart, PieChart, BarChart components + critical: Follow doesn't have charting library - need to add recharts + +- doc: https://tanstack.com/query/latest/docs/framework/react/guides/query-keys + section: Query key hierarchies and best practices + critical: Follow uses hierarchical query keys pattern + +- doc: https://react-i18next.com/latest/using-with-hooks + section: useTranslation hook usage + critical: All user-facing text must be internationalized +``` + +### Current Codebase tree + +```bash +apps/desktop/layer/renderer/src/modules/settings/tabs/ +├── ai.tsx # Main AI settings page with SettingBuilder +├── token-usage.tsx # Current token usage implementation +└── ai/ + ├── index.ts # Exports AI-related components + ├── PanelStyleSection.tsx # Example section component pattern + ├── PersonalizePromptSection.tsx # Example section component pattern + └── mcp/MCPServicesSection.tsx # Complex section with React Query + +apps/desktop/layer/renderer/src/modules/ai-task/ +└── query.ts # React Query patterns and conventions + +packages/internal/components/src/ui/ +├── progress/index.tsx # Progress bars and indicators +├── card/index.tsx # Card containers +├── tabs/index.tsx # Tab navigation +└── [other UI components...] +``` + +### Desired Codebase tree with files to be added and responsibility + +```bash +apps/desktop/layer/renderer/src/modules/settings/tabs/ +├── ai.tsx # MODIFIED: Add UsageAnalysisSection +├── token-usage.tsx # MODIFIED: Enhanced with analytics +└── ai/ + ├── index.ts # MODIFIED: Export new usage components + └── usage/ # NEW: Usage observability components + ├── UsageAnalysisSection.tsx # AI tab simplified usage overview + ├── hooks/ + │ ├── useEnhancedTokenUsage.ts # Enhanced config API hook + │ ├── useUsageAnalytics.ts # Analytics API hook + │ ├── useSessionTracking.ts # Session tracking hook + │ └── index.ts # Hook exports + └── components/ + ├── UsageProgressRing.tsx # Circular progress component + ├── SessionStatusCard.tsx # Active session display + ├── UsageWarningBanner.tsx # Predictive warning alerts + ├── QuickInsights.tsx # Key metrics display + └── index.ts # Component exports + +apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/ +├── index.tsx # MODIFIED: Export enhanced components +├── TokenUsageEnhanced.tsx # NEW: Enhanced analytics page +├── components/ +│ ├── UsageTrendChart.tsx # Line chart for usage trends +│ ├── FeatureDistributionChart.tsx # Pie chart for feature breakdown +│ ├── ModelEfficiencyChart.tsx # Bar chart for model comparison +│ ├── TimePatternAnalysis.tsx # Time-based usage patterns +│ ├── PredictiveInsights.tsx # Insights and recommendations +│ ├── RealTimeMetrics.tsx # Live usage dashboard +│ └── index.ts # Chart component exports +└── styles/ + └── charts.module.css # Chart-specific styles + +apps/desktop/layer/renderer/src/queries/ +└── ai-analytics.ts # NEW: Centralized analytics query logic +``` + +### Known Gotchas of our codebase & Library Quirks + +```typescript +// CRITICAL: Project-specific patterns and constraints +// REACT_QUERY: Use hierarchical query keys following aiTaskKeys pattern +// REACT_QUERY: Extract data with data?.data pattern, handle loading/error states +// REACT_QUERY: Use proper cache invalidation on mutations +// COMPONENTS: Import UI components from @follow/components/ui/* +// COMPONENTS: Use SettingBuilder for settings pages, SettingTabbedSegment for options +// API: Use followClient.api.* pattern, not direct fetch +// I18N: All user-facing strings must use useTranslation hook +// STYLING: Use Tailwind with UIKit colors (text-text, bg-fill, etc.) +// STYLING: Follow mobile-first responsive design patterns +// ICONS: Use i-mgc-* prefix for MingCute icons, i-mingcute-* as fallback +// MOTION: Use m. instead of motion. for Framer Motion components +// CHARTS: No existing chart library - need to add recharts to dependencies +// MODALS: Use useDialog and useModalStack for modal interactions +// TOASTS: Use toast from "sonner" for notifications +// STATE: Settings state managed through Jotai atoms +// ROUTES: Use React Router Link for navigation +// ERROR_HANDLING: Follow existing error boundary patterns +``` + +## Implementation Blueprint + +### Data models and structure + +Enhanced React Query hooks and TypeScript interfaces: + +```typescript +// apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/hooks/useEnhancedTokenUsage.ts +export interface EnhancedTokenUsage { + defaultModel: string + availableModels: string[] + modelBillingStrategy: Record + rateLimit: { + maxTokens: number + currentTokens: number + remainingTokens: number + windowDuration: number + windowResetTime: number + // Enhanced fields + usageRate: number + projectedLimitTime: number | null + warningLevel: "safe" | "moderate" | "high" | "critical" + } + usage: { + total: number + used: number + remaining: number + resetAt: string + // Enhanced fields + avgTokensPerSession: number + avgSessionDuration: number + mostUsedFeature: string + efficiencyScore: number + } + currentSession: { + sessionId: string | null + tokensUsed: number + messageCount: number + duration: number + isActive: boolean + } + usageHistory: Array<{ + id: string + createdAt: Date + changes: number + comment: string | null + operationType: string | null + modelUsed: string | null + sessionId: string | null + }> +} + +// apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/hooks/useUsageAnalytics.ts +export interface UsageAnalytics { + patterns: { + daily: Array<{ + date: string + totalTokens: number + operationCount: number + peakHour: number | null + }> + byOperation: Array<{ + operationType: string + totalTokens: number + operationCount: number + percentage: number + avgTokensPerOperation: number + }> + byModel: Array<{ + model: string + totalTokens: number + operationCount: number + percentage: number + avgEfficiency: number + }> + } + insights: { + usageTrend: "increasing" | "decreasing" | "stable" + projectedMonthlyUsage: number + recommendations: string[] + efficiencyTips: string[] + } + timePatterns: { + peakHours: number[] + peakDays: number[] + avgSessionDuration: number + avgTokensPerSession: number + } +} + +// Query keys following aiTaskKeys pattern +export const aiAnalyticsKeys = { + all: ["ai-analytics"] as const, + config: () => [...aiAnalyticsKeys.all, "config"] as const, + analytics: () => [...aiAnalyticsKeys.all, "analytics"] as const, + analyticsWithDays: (days: number) => [...aiAnalyticsKeys.analytics(), days] as const, + session: () => [...aiAnalyticsKeys.all, "session"] as const, + sessionCurrent: () => [...aiAnalyticsKeys.session(), "current"] as const, +} +``` + +### List of tasks to be completed to fulfill the PRP in the order they should be completed + +```yaml +Task 1: Add recharts dependency for data visualization +MODIFY package.json (apps/desktop/): + - ADD "recharts": "^2.10.0" to dependencies + - RUN pnpm install to install charting library + +Task 2: Create AI analytics query hooks +CREATE apps/desktop/layer/renderer/src/queries/ai-analytics.ts: + - IMPLEMENT hierarchical query keys following aiTaskKeys pattern + - EXPORT useEnhancedTokenUsage, useUsageAnalytics, useSessionTracking hooks + - USE followClient.api pattern for API calls + - HANDLE loading states and error cases + +Task 3: Create usage progress ring component +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/components/UsageProgressRing.tsx: + - IMPLEMENT circular SVG progress indicator + - SUPPORT different sizes (sm/md/lg) and color coding + - FOLLOW UIKit color system for status indication + +Task 4: Create session status components +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/components/SessionStatusCard.tsx: + - DISPLAY active session information when available + - SHOW real-time token usage and message count + - USE card component from @follow/components/ui/card + +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/components/UsageWarningBanner.tsx: + - IMPLEMENT predictive warning display + - COLOR-CODE warnings by severity level + - SHOW projected limit time and usage rate + +Task 5: Create simplified usage analysis section +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/UsageAnalysisSection.tsx: + - IMPLEMENT compact overview for AI settings tab + - USE UsageProgressRing and SessionStatusCard components + - INCLUDE "View Details" link to full analytics page + - FOLLOW SettingTabbedSegment patterns from existing sections + +Task 6: Create chart components for detailed analytics +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/UsageTrendChart.tsx: + - USE recharts LineChart for 30-day usage trends + - IMPLEMENT responsive container and proper tooltips + - STYLE using Tailwind and UIKit colors + +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/FeatureDistributionChart.tsx: + - USE recharts PieChart for feature usage breakdown + - ADD custom legend with percentages + - IMPLEMENT hover interactions + +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/ModelEfficiencyChart.tsx: + - USE recharts BarChart for model efficiency comparison + - SHOW tokens per operation efficiency + - COLOR-CODE by efficiency levels + +Task 7: Create comprehensive analytics page +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/TokenUsageEnhanced.tsx: + - IMPLEMENT tabbed interface with overview/patterns/efficiency/history + - USE chart components for visualizations + - INCLUDE real-time metrics dashboard + - ADD predictive insights and recommendations section + +Task 8: Create time pattern analysis components +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/TimePatternAnalysis.tsx: + - DISPLAY peak usage hours and days + - SHOW usage patterns and habits + - PROVIDE optimization suggestions based on patterns + +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/PredictiveInsights.tsx: + - RENDER usage trend analysis + - DISPLAY projected monthly usage + - SHOW personalized recommendations and tips + +Task 9: Integrate usage section into AI settings +MODIFY apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx: + - IMPORT UsageAnalysisSection component + - ADD to SettingBuilder array after existing sections + - INCLUDE proper title and divider + +MODIFY apps/desktop/layer/renderer/src/modules/settings/tabs/ai/index.ts: + - EXPORT UsageAnalysisSection from new usage module + +Task 10: Enhance existing token usage page +MODIFY apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage.tsx: + - REPLACE current implementation with TokenUsageEnhanced + - MAINTAIN backward compatibility with existing route + - ADD proper error boundaries and loading states + +Task 11: Add internationalization support +CREATE locales/en/ai.json (add new keys): + - ADD usage_analysis.* keys for simplified section + - ADD analytics.* keys for detailed page + - ADD insights.* keys for recommendations and warnings + +CREATE similar entries in locales/zh-CN/ai.json and locales/ja.json + +Task 12: Add responsive mobile support +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/styles/charts.module.css: + - ADD mobile-responsive chart styles + - IMPLEMENT collapsible sections for mobile + - ENSURE touch-friendly interactions + +Task 13: Implement real-time updates +MODIFY all query hooks: + - ADD refetchInterval: 30000 for config data + - ADD refetchInterval: 10000 for session data + - IMPLEMENT proper error retry logic + +Task 14: Add loading and error states +ENHANCE all components: + - ADD skeleton loading states using @follow/components/ui/skeleton + - IMPLEMENT error boundaries with retry mechanisms + - SHOW proper fallback UI when data unavailable + +Task 15: Create comprehensive component exports +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/index.ts: + - EXPORT all usage-related components and hooks + - MAINTAIN clean import structure + +CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/index.ts: + - EXPORT all chart and analytics components + +Task 16: Add interactive features +ENHANCE chart components: + - ADD click interactions for drill-down views + - IMPLEMENT brush selection for time range filtering + - ADD export functionality for usage reports + +Task 17: Implement accessibility features +ENHANCE all components: + - ADD proper ARIA labels and descriptions + - ENSURE keyboard navigation support + - IMPLEMENT high contrast mode compatibility + - ADD screen reader support for charts +``` + +### Per task pseudocode as needed + +```typescript +// Task 2: AI Analytics Query Hooks +// apps/desktop/layer/renderer/src/queries/ai-analytics.ts + +import { useQuery } from "@tanstack/react-query" +import { followClient } from "~/lib/api-client" + +export const aiAnalyticsKeys = { + all: ["ai-analytics"] as const, + config: () => [...aiAnalyticsKeys.all, "config"] as const, + analytics: () => [...aiAnalyticsKeys.all, "analytics"] as const, + analyticsWithDays: (days: number) => [...aiAnalyticsKeys.analytics(), days] as const, + session: () => [...aiAnalyticsKeys.all, "session"] as const, + sessionCurrent: () => [...aiAnalyticsKeys.session(), "current"] as const, +} + +export const useEnhancedTokenUsage = (options = {}) => { + const { data, isLoading, error } = useQuery({ + queryKey: aiAnalyticsKeys.config(), + queryFn: async () => { + const res = await followClient.api.ai.config() + return res + }, + refetchInterval: 30000, // 30 seconds + refetchOnWindowFocus: true, + retry: 2, + ...options, + }) + return { data: data?.data, isLoading, error } +} + +export const useUsageAnalytics = (days: number = 30) => { + const { data, isLoading, error } = useQuery({ + queryKey: aiAnalyticsKeys.analyticsWithDays(days), + queryFn: async () => { + const res = await followClient.api.ai.analytics({ days }) + return res + }, + refetchInterval: 60000, // 1 minute + ...options, + }) + return { data: data?.data, isLoading, error } +} + +// Task 5: Usage Analysis Section for AI Tab +// apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/UsageAnalysisSection.tsx + +import { Card, CardContent } from "@follow/components/ui/card" +import { cn } from "@follow/utils/utils" +import { useTranslation } from "react-i18next" +import { Link } from "react-router-dom" +import { UsageProgressRing } from "./components/UsageProgressRing" +import { SessionStatusCard } from "./components/SessionStatusCard" +import { UsageWarningBanner } from "./components/UsageWarningBanner" +import { useEnhancedTokenUsage } from "~/queries/ai-analytics" + +export const UsageAnalysisSection = ({ compact = false }) => { + const { t } = useTranslation("ai") + const { data: config, isLoading } = useEnhancedTokenUsage() + + if (isLoading) { + return
+ } + + if (!config) return null + + const { usage, rateLimit, currentSession } = config + const usagePercentage = usage.total === 0 ? 0 : (usage.used / usage.total) * 100 + + return ( +
+ {/* Warning banner for critical states */} + {rateLimit.warningLevel !== "safe" && ( + + )} + + {/* Main usage card */} + + +
+

+ {t("usage_analysis.title")} +

+ + {t("usage_analysis.view_details")} → + +
+ +
+ + +
+
+ + {formatTokenCount(rateLimit.remainingTokens).value} + {formatTokenCount(rateLimit.remainingTokens).unit} + + + {t("usage_analysis.tokens_remaining")} + +
+ +
+ {formatTokenCount(usage.used).value}{formatTokenCount(usage.used).unit} / + {formatTokenCount(usage.total).value}{formatTokenCount(usage.total).unit} used +
+ +
+ {t("usage_analysis.resets_in")} {formatTimeRemaining(rateLimit.windowResetTime - Date.now())} +
+
+
+ + {/* Current session if active */} + {currentSession?.isActive && ( + + )} + + {/* Quick insights */} + {!compact && ( +
+ +
+ )} +
+
+
+ ) +} + +// Task 6: Usage Trend Chart +// apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/UsageTrendChart.tsx + +import { ResponsiveContainer, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip } from "recharts" +import { Card, CardHeader, CardTitle, CardContent } from "@follow/components/ui/card" + +interface UsageTrendChartProps { + data: Array<{ + date: string + totalTokens: number + operationCount: number + }> +} + +export const UsageTrendChart = ({ data }: UsageTrendChartProps) => { + return ( + + + Usage Trends (Last 30 Days) + + + + + + + + [ + name === 'totalTokens' ? `${value.toLocaleString()} tokens` : `${value} operations`, + name === 'totalTokens' ? 'Tokens Used' : 'Operations' + ]} + contentStyle={{ + backgroundColor: 'rgb(var(--color-fill))', + border: '1px solid rgb(var(--color-fill-secondary))', + borderRadius: '6px' + }} + /> + + + + + + ) +} + +// Task 7: Enhanced Token Usage Page +// apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/TokenUsageEnhanced.tsx + +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@follow/components/ui/tabs" +import { useEnhancedTokenUsage, useUsageAnalytics } from "~/queries/ai-analytics" +import { UsageTrendChart } from "./components/UsageTrendChart" +import { FeatureDistributionChart } from "./components/FeatureDistributionChart" +import { ModelEfficiencyChart } from "./components/ModelEfficiencyChart" +import { RealTimeMetrics } from "./components/RealTimeMetrics" + +export const TokenUsageEnhanced = () => { + const { t } = useTranslation("ai") + const { data: config, isLoading: configLoading } = useEnhancedTokenUsage() + const { data: analytics, isLoading: analyticsLoading } = useUsageAnalytics(30) + + if (configLoading || analyticsLoading) { + return ( +
+
+
+ ) + } + + return ( +
+ {/* Real-time metrics overview */} + + + {/* Predictive warnings */} + {config.rateLimit.projectedLimitTime && ( + + )} + + {/* Detailed analytics tabs */} + + + {t("analytics.tabs.overview")} + {t("analytics.tabs.patterns")} + {t("analytics.tabs.efficiency")} + {t("analytics.tabs.history")} + + + + + +
+ + +
+
+ + + + + + + + + + + + +
+
+ ) +} +``` + +### Integration Points + +```yaml +DEPENDENCIES: + - add: "recharts": "^2.10.0" to package.json + - verify: @tanstack/react-query version compatibility + - ensure: React 19 compatibility with recharts + +API_INTEGRATION: + - endpoints: /ai/chat/config (enhanced), /ai/analytics, /ai/session/current + - pattern: followClient.api.ai.* for all API calls + - response: Extract data with data?.data pattern + +UI_COMPONENTS: + - use: @follow/components/ui/* for all UI primitives + - follow: UIKit color system (text-text, bg-fill, etc.) + - icons: i-mgc-* prefix for MingCute icons + +SETTINGS_INTEGRATION: + - modify: apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx + - pattern: Add to SettingBuilder array following existing structure + - export: Update ai/index.ts with new components + +ROUTES: + - existing: /settings/token-usage enhanced with new components + - navigation: Use React Router Link for internal navigation + +STATE_MANAGEMENT: + - queries: React Query for server state + - settings: Jotai atoms for client settings (if needed) + - cache: Proper invalidation on data mutations +``` + +## Validation Loop + +### Level 1: Syntax & Style + +```bash +# Run these FIRST - fix any errors before proceeding +pnpm lint --fix # ESLint auto-fix +pnpm typecheck # TypeScript checking +pnpm --filter=@follow/desktop typecheck # Desktop specific check + +# Expected: No errors. If errors, READ the error and fix. +``` + +### Level 2: Component Tests + +```typescript +// CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/__tests__/UsageAnalysisSection.test.tsx +import { render, screen } from "@testing-library/react" +import { QueryClient, QueryClientProvider } from "@tanstack/react-query" +import { UsageAnalysisSection } from "../UsageAnalysisSection" + +const mockConfig = { + usage: { used: 500000, total: 1000000, efficiencyScore: 85 }, + rateLimit: { remainingTokens: 500000, warningLevel: "safe" }, + currentSession: { isActive: false }, +} + +jest.mock("~/queries/ai-analytics", () => ({ + useEnhancedTokenUsage: () => ({ data: mockConfig, isLoading: false }), +})) + +describe('UsageAnalysisSection', () => { + it('renders usage overview correctly', () => { + const queryClient = new QueryClient() + + render( + + + + ) + + expect(screen.getByText("Token Usage")).toBeInTheDocument() + expect(screen.getByText("View Details →")).toBeInTheDocument() + expect(screen.getByText("500K remaining")).toBeInTheDocument() + }) + + it('shows warning banner for critical states', () => { + const criticalConfig = { + ...mockConfig, + rateLimit: { ...mockConfig.rateLimit, warningLevel: "critical" } + } + + jest.mocked(useEnhancedTokenUsage).mockReturnValue({ + data: criticalConfig, + isLoading: false + }) + + render( + + + + ) + + expect(screen.getByRole("alert")).toBeInTheDocument() + }) +}) + +// CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/__tests__/TokenUsageEnhanced.test.tsx +describe('TokenUsageEnhanced', () => { + it('renders analytics tabs correctly', () => { + render( + + + + ) + + expect(screen.getByRole("tablist")).toBeInTheDocument() + expect(screen.getByRole("tab", { name: "Overview" })).toBeInTheDocument() + expect(screen.getByRole("tab", { name: "Patterns" })).toBeInTheDocument() + }) + + it('displays charts when data is available', async () => { + const mockAnalytics = { + patterns: { + daily: [{ date: "2024-01-01", totalTokens: 1000, operationCount: 5 }], + byOperation: [{ operationType: "chat", totalTokens: 800, percentage: 80 }], + byModel: [{ model: "gpt-4", totalTokens: 600, avgEfficiency: 120 }], + } + } + + jest.mocked(useUsageAnalytics).mockReturnValue({ + data: mockAnalytics, + isLoading: false + }) + + render( + + + + ) + + expect(screen.getByText("Usage Trends")).toBeInTheDocument() + }) +}) +``` + +```bash +# Run component tests: +pnpm test -- apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage +pnpm test -- apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage +# If failing: Read error, understand root cause, fix code, re-run +``` + +### Level 3: Integration Test + +```bash +# Start the development server +pnpm --filter=@follow/desktop dev:web + +# Test AI settings page integration +# Navigate to http://localhost:5173/settings/ai +# Expected: New "Token Usage" section visible with progress ring and metrics + +# Test detailed analytics page +# Navigate to http://localhost:5173/settings/token-usage +# Expected: Enhanced page with tabs, charts, and real-time metrics + +# Test responsive design +# Resize browser window to mobile dimensions +# Expected: Charts stack vertically, components remain usable + +# Test real-time updates +# Keep page open for 30 seconds, observe data refresh +# Expected: Usage data updates automatically +``` + +### Level 4: Chart Rendering Validation + +```bash +# Test chart libraries +# Open browser developer tools, check for console errors +# Expected: No recharts-related errors, proper chart rendering + +# Test chart interactions +# Hover over chart elements, verify tooltips appear +# Click on legend items, verify chart responds +# Expected: Interactive elements work smoothly +``` + +### Level 5: API Integration Validation + +```bash +# Test API calls in Network tab +# Navigate to enhanced pages, verify API requests +# Expected: +# - GET /ai/chat/config calls successfully +# - GET /ai/analytics calls successfully +# - GET /ai/session/current calls when needed +# - Proper error handling for failed requests +``` + +## Final validation Checklist + +- [ ] All tests pass: `pnpm test` +- [ ] No linting errors: `pnpm lint` +- [ ] No type errors: `pnpm typecheck` +- [ ] Recharts dependency installed: `pnpm list recharts` +- [ ] AI settings page shows usage section: Navigate to /settings/ai +- [ ] Token usage page enhanced with charts: Navigate to /settings/token-usage +- [ ] Real-time updates working: Observe 30-second refresh intervals +- [ ] Charts render correctly: All visualizations display properly +- [ ] Mobile responsive: Components work on smaller screens +- [ ] Predictive warnings appear: Test with high usage scenarios +- [ ] Session tracking displays: Active sessions show correctly +- [ ] Navigation works: Links between simple/detailed views function +- [ ] Internationalization complete: All text uses translation keys +- [ ] Error states handled: Network failures show appropriate UI +- [ ] Loading states smooth: Skeleton screens display during data fetch +- [ ] Accessibility compliant: Screen reader and keyboard navigation work + +--- + +## Anti-Patterns to Avoid + +- ❌ Don't fetch chart data on every render - use React Query caching +- ❌ Don't ignore mobile responsive design - ensure charts work on small screens +- ❌ Don't hardcode colors - use UIKit color system throughout +- ❌ Don't skip loading states - users need visual feedback during data fetch +- ❌ Don't break existing AI settings layout - integrate cleanly with SettingBuilder +- ❌ Don't forget internationalization - all user text must use useTranslation +- ❌ Don't implement custom query logic - follow existing React Query patterns +- ❌ Don't ignore error boundaries - handle API failures gracefully +- ❌ Don't make charts inaccessible - include proper ARIA labels +- ❌ Don't pollute global styles - scope chart styles appropriately + +## Confidence Score: 8/10 + +This PRP provides comprehensive context for implementing enhanced AI usage observability frontend with: + +- ✅ Complete analysis of existing Follow frontend patterns and conventions +- ✅ Detailed component hierarchy with specific file structure and responsibilities +- ✅ React Query integration following project's established patterns +- ✅ Chart library integration with proper responsive design considerations +- ✅ Comprehensive testing strategy covering unit and integration scenarios +- ✅ Step-by-step implementation tasks with proper dependency management +- ✅ Clear validation steps with specific commands and expected outcomes +- ✅ Internationalization requirements and integration patterns + +The implementation should succeed with high confidence given the detailed context, existing codebase analysis, and thorough validation approach. The -2 points account for the complexity of chart library integration and potential responsive design edge cases that may require iteration. diff --git a/PRPs/entry-layouts-comprehensive-fixes.md b/PRPs/entry-layouts-comprehensive-fixes.md new file mode 100644 index 000000000..aa7024d04 --- /dev/null +++ b/PRPs/entry-layouts-comprehensive-fixes.md @@ -0,0 +1,577 @@ +# PRP: Comprehensive Entry Content Layout Fixes + +## Overview + +Fix critical issues in the adaptive entry content layouts that prevent proper EntryHeader display, cause inconsistent layout patterns, and implement unwanted popup behaviors. This PRP addresses specific problems identified with SocialMedia, Pictures, and Videos layouts while also fixing entry navigation behavior. + +## Current Issues Analysis + +### Issue Context + +Following the implementation of adaptive entry content layouts in `PRPs/adaptive-entry-content-layouts.md` and `PRPs/adaptive-entry-layouts-fixes.md`, several critical issues remain that affect user experience: + +### 1. Social Media Layout - Blank EntryHeader Issue + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx` +**Root Cause**: EntryHeader component explicitly hides all functionality for SocialMedia view + +**Current Implementation Problem**: + +```typescript +// EntryHeader.tsx lines 72-77 - Explicitly hides actions for SocialMedia +{view !== FeedViewType.SocialMedia && ( +
+ + +
+)} +``` + +**Missing Functionality**: + +- Star/bookmark actions +- Share actions +- More actions menu (read/unread toggle, archive, etc.) +- Entry metadata display when scrolled +- Read status indicators + +**Additional Issue**: SocialMedia entries also use `
` tag instead of `NavLink` in `EntryItemWrapper.tsx:212`, preventing proper navigation. + +### 2. Pictures Layout - Wrong Layout Structure + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx` + +**Current Structure**: Split-screen layout (image left, metadata sidebar right) + +```typescript +
+
{/* Image area */} +
{/* Sidebar */} +``` + +**Requested Structure**: Article-like layout (title/author top, content below) with multimedia separated from text + +### 3. Videos Layout - AI Summary Position + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/VideosLayout.tsx` + +**Current Order**: + +1. EntryTitle +2. AuthorHeader +3. ContentBody +4. AISummary ← Currently at bottom + +**Requested Order**: AI Summary should be above ContentBody (between AuthorHeader and ContentBody) + +### 4. Video Entry Popup Logic + +**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/video-item.tsx` + +**Current Behavior**: Lines 104-126 - Click triggers modal popup instead of navigation + +```typescript +onClick={(e) => { + if (iframeSrc) { + modalStack.present({ + title: "", + content: (props) => (), + }) + } else { + previewMedia(entry.media) // Triggers video preview popup + } +}} +``` + +### 5. Picture Entry Popup Logic + +**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-item.tsx` + +**Current Behavior**: Lines 46-48 - SwipeMedia triggers preview popup + +```typescript + { + previewMedia(media, i) // Triggers picture preview popup instead of navigation + }} +/> +``` + +## Proposed Solutions + +### 1. Social Media Layout Fixes + +#### 1.1 Restore EntryHeader Functionality + +**Strategy**: Remove the SocialMedia exclusion from EntryHeader component and ensure proper integration + +**File Changes**: + +- `EntryHeader.tsx`: Remove `view !== FeedViewType.SocialMedia` condition +- `EntryItemWrapper.tsx`: Change SocialMedia from `
` to `NavLink` like other entry types +- `SocialMediaLayout.tsx`: Ensure layout works with EntryHeader display + +#### 1.2 Layout Integration Pattern + +Follow the same pattern as ArticleLayout: + +```typescript +// EntryContent.tsx integration (lines 120-127) +{!isInPeekModal && ( + +)} +// Then SocialMediaLayout renders below EntryHeader +``` + +### 2. Pictures Layout Restructuring + +#### 2.1 Change to Article-Style Layout + +**New Structure**: Title/Author on top, content below, with multimedia content separated + +```typescript +// New PicturesLayout structure +
+ {/* Title and Author Section */} +
+ + +
+ + {/* Multimedia Content Section */} +
+ +
+ + {/* Text Content Section */} +
+ + +
+
+``` + +#### 2.2 Multimedia Content Separation + +- Use `noMedia={true}` on ContentBody to remove multimedia elements from text +- Display multimedia content separately in dedicated MediaGallery section +- Maintain click-to-preview functionality via `usePreviewMedia` hook + +### 3. Videos Layout - AI Summary Position Fix + +**Simple Reordering**: Move AISummary component above ContentBody + +```typescript +// Current order in VideosLayout.tsx (lines 49-72) + + + {/* Move here - above content */} + +``` + +### 4. Remove Video Entry Popup Logic + +#### 4.1 Update Video Item Click Handler + +**File**: `video-item.tsx` +**Change**: Remove modal popup logic, allow normal entry navigation + +```typescript +// Replace current onClick handler (lines 104-126) with normal entry behavior +// Remove the modal presentation logic entirely +// Let EntryItemWrapper handle navigation naturally +``` + +#### 4.2 Preserve Video Preview in Layout + +**Note**: Users can still preview videos via the VideosLayout which shows the video player properly + +### 5. Remove Picture Entry Popup Logic + +#### 5.1 Update Picture Item OnPreview Handler + +**File**: `picture-item.tsx` +**Change**: Remove `onPreview` prop from SwipeMedia to disable popup behavior + +```typescript +// Remove onPreview prop from SwipeMedia (lines 46-48) + previewMedia(media, i)} // Remove this line + className="aspect-square w-full overflow-hidden rounded-md" +/> +``` + +#### 5.2 Maintain Preview in PicturesLayout + +**Note**: Users can still preview images via the restructured PicturesLayout with proper MediaGallery integration + +## Implementation Plan + +### Phase 1: Fix Social Media Layout EntryHeader (Priority: Critical) + +#### Task 1.1: Remove SocialMedia Exclusion from EntryHeader + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-header/EntryHeader.tsx` + +```typescript +// Remove condition: view !== FeedViewType.SocialMedia +// Lines 72-77: Always show EntryHeaderActions regardless of view type +
+ + +
+``` + +#### Task 1.2: Fix SocialMedia Entry Navigation + +**File**: `apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx` + +```typescript +// Change line 212 from: +const Link = view === FeedViewType.SocialMedia ? "article" : NavLink +// To: +const Link = NavLink // Use NavLink for all entry types including SocialMedia +``` + +#### Task 1.3: Verify SocialMediaLayout Integration + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx` + +- Ensure layout works properly when EntryHeader is displayed above it +- Test star collection overlay positioning doesn't conflict with EntryHeader +- Verify responsive behavior with EntryHeader present + +### Phase 2: Restructure Pictures Layout (Priority: High) + +#### Task 2.1: Implement Article-Style Layout Structure + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx` + +- Replace split-screen layout with vertical article-style layout +- Move title and author to top section +- Create dedicated multimedia content section with MediaGallery +- Separate text content section with `noMedia={true}` + +#### Task 2.2: Update MediaGallery Integration + +- Ensure MediaGallery component supports click-to-preview functionality +- Maintain existing `usePreviewMedia` hook integration for modal previews +- Test multiple image handling and carousel behavior + +### Phase 3: Fix Videos Layout AI Summary Position (Priority: Medium) + +#### Task 3.1: Reorder Components + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/VideosLayout.tsx` + +- Move `` from line 72 to after AuthorHeader (around line 53) +- Maintain proper spacing and styling +- Test responsive behavior and content flow + +### Phase 4: Remove Popup Logic (Priority: Medium) + +#### Task 4.1: Remove Video Entry Popup Logic + +**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/video-item.tsx` + +- Remove or simplify onClick handler (lines 104-126) +- Remove `PreviewVideoModalContent` modal presentation logic +- Allow normal entry navigation through EntryItemWrapper + +#### Task 4.2: Remove Picture Entry Popup Logic + +**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-item.tsx` + +- Remove `onPreview` prop from SwipeMedia component (lines 46-48) +- Test that normal entry navigation still works +- Verify pictures can still be previewed through PicturesLayout + +### Phase 5: Testing and Validation (Priority: High) + +#### Task 5.1: Layout Functionality Testing + +- Test EntryHeader actions work in SocialMedia layout (star, share, more actions) +- Test Pictures layout displays properly with article-style structure +- Test Videos layout shows AI summary in correct position +- Test normal entry navigation works for all layouts + +#### Task 5.2: Integration Testing + +- Test entry factory routing still works correctly +- Test mobile responsive behavior across all layout changes +- Test no regressions in ArticleLayout functionality +- Test modal preview functionality where preserved + +## Context & References + +### Codebase Architecture Understanding + +#### Entry Content System Files + +- **Factory**: `layouts/factory.ts` - Layout component selection +- **Integration**: `EntryContent.tsx` - Main integration point with EntryHeader +- **Layouts**: Individual layout components in `layouts/` directory +- **Entry Wrapper**: `EntryItemWrapper.tsx` - Controls navigation vs article tag usage + +#### Key Components to Modify + +- **EntryHeader.tsx**: Remove SocialMedia exclusion (lines 72-77) +- **EntryItemWrapper.tsx**: Fix SocialMedia navigation (line 212) +- **SocialMediaLayout.tsx**: Verify EntryHeader integration +- **PicturesLayout.tsx**: Complete restructure to article-style layout +- **VideosLayout.tsx**: Simple component reordering +- **video-item.tsx**: Remove popup click logic +- **picture-item.tsx**: Remove SwipeMedia onPreview prop + +#### Existing Patterns to Follow + +- **ArticleLayout**: Reference for proper EntryHeader integration +- **MediaGallery**: Pattern for multimedia content display +- **EntryHeaderActions**: Component providing star, share, more actions +- **usePreviewMedia**: Hook for maintaining preview functionality where appropriate + +### External Best Practices & Documentation + +#### React Component Restructuring + +- **Conditional Rendering Removal**: https://react.dev/learn/conditional-rendering +- **Component Composition**: https://react.dev/learn/passing-props-to-a-component +- **Layout Patterns**: Clean separation of content sections for better UX + +#### Entry Navigation Patterns + +- **React Router NavLink**: https://reactrouter.com/en/main/components/nav-link +- **Navigation vs Modal UX**: Best practices for content discovery vs preview + +#### Layout Design Principles + +- **Article Layout Standards**: Title → Author → Content flow for readability +- **Multimedia Content Separation**: Clear distinction between media and text content +- **Progressive Enhancement**: Maintain preview functionality while improving base navigation + +### UI/UX Reference Standards + +#### Social Media Layout + +- **Standard Pattern**: Avatar + Author info + Actions in header area +- **Content Flow**: Header actions → AI summary → Content → Media gallery +- **Action Accessibility**: All entry actions should be consistently available + +#### Pictures Layout + +- **Article-Style Pattern**: Linear flow from title → author → multimedia → text +- **Content Separation**: Clear visual separation between media and text sections +- **Preview Enhancement**: Click-to-preview maintains advanced image viewing + +#### Videos Layout + +- **Information Hierarchy**: AI summary provides context before content consumption +- **Content Flow**: Video → Title → Author → AI Summary → Description/Content + +## Validation Gates + +### Code Quality Checks + +```bash +# TypeScript validation +pnpm run typecheck + +# Linting validation +pnpm run lint:tsl +pnpm run lint + +# Code formatting +pnpm run format + +# Build validation +pnpm run build:web +``` + +### Functional Testing Checklist + +#### Social Media Layout Validation + +- [ ] EntryHeader displays with all action buttons (star, share, more actions menu) +- [ ] Social media entries navigate properly when clicked (no article tag behavior) +- [ ] Star/bookmark functionality works correctly +- [ ] Share actions function properly +- [ ] More actions menu provides read/unread, archive, etc. options +- [ ] Entry metadata displays when scrolled +- [ ] Layout integrates properly with EntryHeader space allocation + +#### Pictures Layout Validation + +- [ ] Title displays at top of layout +- [ ] Author information displays below title +- [ ] Multimedia content displays in dedicated section +- [ ] Text content displays separately without embedded media +- [ ] AI summary appears in text content section +- [ ] MediaGallery maintains click-to-preview functionality +- [ ] Layout is responsive and readable on all screen sizes + +#### Videos Layout Validation + +- [ ] AI summary displays above main content (after AuthorHeader) +- [ ] Video player displays properly at top +- [ ] Title and author information display correctly +- [ ] Text content excludes multimedia elements (`noMedia={true}`) +- [ ] Component spacing and flow is visually appealing + +#### Entry Navigation Validation + +- [ ] Video entries navigate to content view instead of showing popup +- [ ] Picture entries navigate to content view instead of showing popup +- [ ] Normal entry clicking behavior consistent across all entry types +- [ ] Preview functionality still available within content layouts +- [ ] No regressions in other entry types (Article, Audio, Notifications) + +### Performance & Integration Testing + +- [ ] No layout shift when EntryHeader is displayed with SocialMedia layout +- [ ] Entry factory routing continues to work seamlessly +- [ ] Modal preview functionality works when explicitly triggered +- [ ] Bundle size impact minimal (layout restructuring only) +- [ ] Mobile responsive design maintained across all layouts + +## Success Criteria + +### Primary Objectives + +- [ ] **Social Media**: EntryHeader displays with all actions like other entry types +- [ ] **Pictures**: Article-style layout (title/author top, content below) with multimedia separation +- [ ] **Videos**: AI summary positioned above main content +- [ ] **Navigation**: Entry clicks navigate to content view instead of triggering popups +- [ ] **Functionality**: All existing features preserved (preview, actions, etc.) + +### Quality Standards + +- [ ] Zero regressions in existing ArticleLayout functionality +- [ ] Entry factory system continues routing correctly +- [ ] All EntryHeader actions work consistently across layouts +- [ ] Mobile responsive design maintained +- [ ] Performance impact negligible + +### User Experience Improvements + +- [ ] Consistent action availability across all entry types (star, share, etc.) +- [ ] Better content organization with proper information hierarchy +- [ ] Improved navigation flow (click to view, preview when desired) +- [ ] Cleaner content separation between multimedia and text +- [ ] Maintained advanced preview functionality where appropriate + +## Risk Assessment & Mitigation + +### High-Risk Areas + +#### 1. EntryHeader Integration Changes + +**Risk**: Removing SocialMedia exclusion might break existing layout assumptions +**Mitigation**: + +- Test thoroughly with various social media entry types +- Verify responsive behavior with EntryHeader space allocation +- Implement feature flag for gradual rollout if needed + +#### 2. Navigation Behavior Changes + +**Risk**: Changing from `
` to `NavLink` might affect performance or behavior +**Mitigation**: + +- Profile performance impact of additional NavLink components +- Test keyboard navigation and accessibility compliance +- Verify no conflicts with existing event handlers + +#### 3. Pictures Layout Restructuring + +**Risk**: Complete layout change might break existing user expectations +**Mitigation**: + +- Maintain click-to-preview functionality for advanced image viewing +- Test with various image entry types and content lengths +- Consider user feedback mechanism for layout preference + +### Medium-Risk Areas + +#### Component Dependencies + +**Risk**: Changes to shared components might affect other areas +**Mitigation**: + +- Audit all usage of modified components before changes +- Use backward-compatible prop additions where possible +- Test all entry list item displays remain functional + +#### Preview Functionality + +**Risk**: Removing popup logic might eliminate desired preview features +**Mitigation**: + +- Preserve advanced preview functionality within content layouts +- Ensure MediaGallery and video players provide equivalent experience +- Test that preview modals still work when explicitly triggered + +### Rollback Strategy + +- Implement changes incrementally by layout type +- Use git feature branches for each major change +- Maintain existing layout components as backup during transition +- Feature flag capability for reverting individual layout changes + +## Additional Considerations + +### Accessibility Standards + +- Ensure EntryHeader actions maintain proper ARIA labels and keyboard navigation +- Test screen reader compatibility with restructured layouts +- Maintain proper heading hierarchy across all layout changes +- Verify video player controls remain keyboard accessible + +### Internationalization Support + +- Test all layout changes with RTL languages +- Ensure proper text flow in restructured Pictures layout +- Verify action button layouts work with translated text +- Maintain consistent translation key usage across layouts + +### Future Extensibility + +- Pattern established for other layout types (Audio, Notifications) +- EntryHeader integration approach reusable for new layout types +- Component separation supports future customization options +- Layout factory system ready for additional media types + +## Confidence Score: 8.5/10 + +This PRP provides a comprehensive solution with high implementation confidence: + +### Strengths + +- ✅ **Root Cause Analysis**: Identified exact source of each issue with file and line references +- ✅ **Proven Patterns**: Leverages existing successful EntryHeader and ArticleLayout patterns +- ✅ **Focused Scope**: Addresses specific reported issues without unnecessary complexity +- ✅ **Detailed Implementation**: Clear file-by-file changes with code examples +- ✅ **Risk Management**: Identified potential issues with concrete mitigation strategies +- ✅ **Comprehensive Testing**: Detailed validation steps for each change +- ✅ **External Research**: Incorporates best practices for navigation and layout design + +### Implementation Confidence Factors + +1. **Clear Problem Definition**: Each issue has been thoroughly analyzed with exact file locations +2. **Existing Foundation**: EntryHeader, ArticleLayout, and navigation patterns are already proven +3. **Minimal Breaking Changes**: Most changes involve removing exclusions or simple reordering +4. **Component Reuse**: Leveraging existing tested components rather than creating new ones +5. **Incremental Approach**: Changes can be implemented and tested independently +6. **Fallback Options**: Clear rollback strategy for each component change + +### Minor Risk Factors + +- **Layout Integration**: Need to verify EntryHeader spacing works with each layout type +- **Navigation Changes**: SocialMedia routing change requires thorough cross-platform testing +- **User Experience**: Pictures layout restructuring is most significant UX change + +The high confidence score reflects that this PRP addresses well-defined issues using existing proven components and patterns, with clear implementation steps and comprehensive validation approaches. diff --git a/PRPs/entry-layouts-refinement-fixes.md b/PRPs/entry-layouts-refinement-fixes.md new file mode 100644 index 000000000..1a9bdef28 --- /dev/null +++ b/PRPs/entry-layouts-refinement-fixes.md @@ -0,0 +1,660 @@ +# PRP: Entry Content Layout Refinement Fixes + +## Overview + +Address critical styling and functionality issues in the recently implemented adaptive entry content layouts. This PRP fixes three main areas: Social Media layout typography and avatar styling, Pictures layout carousel integration, and scroll container height calculation issues that cause content truncation. + +## Current Issues Analysis + +### Issue Context + +Following the implementation of adaptive entry content layouts in previous PRPs, user feedback has identified several refinement issues that affect the visual quality and functionality of the layouts. + +### 1. Social Media Layout - Typography and Avatar Issues + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx` + +**Issue 1.1: Author Name Text Size** + +```typescript +// Current AuthorHeader.tsx implementation (lines 64-67) +
+ + + +``` + +**Problem**: Author name uses `text-sm` (14px) which is too small for social media context where author prominence is important. + +**Issue 1.2: Avatar Border Radius Scale Mismatch** + +```typescript +// Current SocialMediaLayout.tsx (line 59) + + +// Current FeedIcon.tsx avatar styling (line 283) + +``` + +**Problem**: Avatar size increased to 48px but border radius remains `rounded-sm` (2px), creating visual inconsistency. + +### 2. Pictures Layout - Carousel Implementation Issues + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx` + +**Issue 2.1: Multiple Image Display** + +```typescript +// Current MediaGallery.tsx implementation (lines 47-113) +if (isAllMediaSameRatio) { + return ( +
+ {media.map((mediaItem, i, mediaList) => { + // Multiple images displayed side by side +``` + +**Problem**: MediaGallery shows multiple images side by side instead of single image with carousel navigation. + +**Issue 2.2: Missing PreviewMediaContent Integration** +**Expected**: Single image display that opens PreviewMediaContent modal on click with carousel functionality. +**Current**: Direct MediaGallery display without modal integration. + +**Issue 2.3: Entry List Click Behavior Not Restored** +**Problem**: Previous fixes removed SwipeMedia `onPreview` prop but didn't properly restore the expected clicking behavior for entry list images. + +### 3. Scroll Container Height Calculation Issues + +**Files**: + +- `packages/internal/components/src/ui/scroll-area/ScrollArea.tsx` +- `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx` + +**Issue 3.1: Height Mismatch** + +```typescript +// EntryContent.tsx ScrollArea usage (lines 242-244) +rootClassName={cn( + "h-0 min-w-0 grow overflow-y-auto print:h-auto print:overflow-visible", + className, +)} +``` + +**Problem**: `h-0 grow` pattern causes height calculation issues where content extends beyond scroll container. + +**Issue 3.2: Flex Container Min-Height Problem** +**Root Cause**: Flexbox containers with implicit minimum size cause scroll containers to not properly calculate their available height. + +## Proposed Solutions + +### 1. Social Media Layout Typography and Avatar Fixes + +#### 1.1 Increase Author Name Font Size + +**Strategy**: Update AuthorHeader to use larger text size for social media context + +**Implementation**: + +```typescript +// AuthorHeader.tsx - Enhanced author name styling +
+ {/* Changed from text-sm */} + + +``` + +#### 1.2 Scale Avatar Border Radius Appropriately + +**Strategy**: Use size-responsive border radius that scales with avatar dimensions + +**Implementation**: + +```typescript +// FeedIcon.tsx - Size-based border radius +const getBorderRadius = (size: number) => { + if (size <= 24) return "rounded-sm" // 2px for small avatars + if (size <= 32) return "rounded-md" // 6px for medium avatars + if (size <= 48) return "rounded-lg" // 8px for large avatars + return "rounded-xl" // 12px for extra large avatars +} + + +``` + +### 2. Pictures Layout Single Image Carousel Implementation + +#### 2.1 Replace MediaGallery with Single Image Display + +**Strategy**: Show only the first image with click-to-carousel functionality using PreviewMediaContent + +**Implementation Pattern**: + +```typescript +// PicturesLayout.tsx - Single image with carousel +const PicturesLayout: React.FC = ({ entryId, ... }) => { + const entry = useEntry(entryId, (state) => ({ media: state.media })) + const previewMedia = usePreviewMedia() + + const handleImageClick = () => { + if (entry?.media && entry.media.length > 0) { + previewMedia( + entry.media.map(m => ({ + url: m.url, + type: m.type, + blurhash: m.blurhash, + fallbackUrl: m.preview_image_url + })), + 0 // Start at first image + ) + } + } + + return ( +
+ {/* Single image display */} + {entry?.media && entry.media.length > 0 && ( +
+
+ + {entry.media.length > 1 && ( +
+ +{entry.media.length - 1} more +
+ )} +
+
+ )} + {/* Rest of content */} +
+ ) +} +``` + +#### 2.2 Restore Entry List Image Click Behavior + +**Strategy**: Re-add proper onPreview functionality to SwipeMedia in entry list contexts + +**Implementation**: + +```typescript +// picture-item.tsx - Restore preview functionality + { + previewMedia( + media.map(m => ({ + url: m.url, + type: m.type, + blurhash: m.blurhash, + fallbackUrl: m.preview_image_url + })), + i + ) + }} +/> +``` + +### 3. Scroll Container Height Fixes + +#### 3.1 Apply Min-Height Fix to Flex Containers + +**Strategy**: Add explicit `min-height: 0` to flex containers to fix height calculation + +**Implementation**: + +```typescript +// EntryContent.tsx - Fix flex container height calculation +
{/* Add min-h-0 */} + + {children} + +
+``` + +#### 3.2 Update ScrollArea Component for Better Height Handling + +**Strategy**: Enhance ScrollArea component to handle flex container height issues + +**Implementation**: + +```typescript +// ScrollArea.tsx - Enhanced flex support +export const ScrollArea = ({ + flex, + rootClassName, + viewportClassName, + ...props +}) => { + return ( + + + div]:!flex [&>div]:!flex-col [&>div]:!min-h-0", // Add min-h-0 to flex children + viewportClassName + )} + // ... rest of props + > + {children} + + + + ) +} +``` + +## Implementation Tasks + +### Phase 1: Social Media Layout Typography and Avatar Fixes (Priority: High) + +#### Task 1.1: Update AuthorHeader Font Sizes + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/AuthorHeader.tsx` + +- Change author name from `text-sm` to `text-base` for better prominence +- Ensure consistency across all AuthorHeader usages +- Test with different author name lengths + +#### Task 1.2: Implement Size-Responsive Avatar Border Radius + +**File**: `apps/desktop/layer/renderer/src/modules/feed/feed-icon/FeedIcon.tsx` + +- Create `getBorderRadius()` utility function based on avatar size +- Update AvatarImage className to use responsive border radius +- Test with different avatar sizes (20px, 32px, 48px, 64px) + +#### Task 1.3: Update SocialMediaLayout Avatar Integration + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx` + +- Verify 48px avatar size works with new border radius +- Test visual consistency with typography changes +- Ensure proper spacing and alignment + +### Phase 2: Pictures Layout Single Image Carousel (Priority: High) + +#### Task 2.1: Replace MediaGallery with Single Image Display + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx` + +- Remove MediaGallery usage +- Implement single image display with first image from media array +- Add click handler for PreviewMediaContent modal +- Add visual indicator for multiple images ("+X more" overlay) + +#### Task 2.2: Create Picture-Specific Media Component + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/SingleImageDisplay.tsx` + +- Create reusable single image display component +- Include click-to-carousel functionality +- Handle edge cases (no images, single image, multiple images) +- Support different aspect ratios and sizing + +#### Task 2.3: Restore Entry List Image Click Behavior + +**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-item.tsx` + +- Re-add `onPreview` prop to SwipeMedia component +- Ensure proper media format for PreviewMediaContent +- Test clicking behavior in entry list vs content view +- Verify no conflicts with entry navigation + +### Phase 3: Scroll Container Height Fixes (Priority: Critical) + +#### Task 3.1: Apply Min-Height Fixes to Entry Content + +**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx` + +- Add `min-h-0` classes to flex containers +- Update ScrollArea usage to include flex height fixes +- Test with different content lengths and screen sizes +- Verify fix applies to all layout types (Social Media, Videos, Articles, Pictures) + +#### Task 3.2: Enhance ScrollArea Component + +**File**: `packages/internal/components/src/ui/scroll-area/ScrollArea.tsx` + +- Add explicit `min-h-0` support for flex contexts +- Update flex child selectors to include min-height fixes +- Ensure backward compatibility with existing usage +- Test across different scroll scenarios + +#### Task 3.3: Test Scroll Fixes Across All Layouts + +**Files**: All layout components + +- Test Social Media layout with long content +- Test Video layout with long descriptions +- Test Articles layout for regressions +- Test Pictures layout after restructuring +- Verify mobile responsive behavior + +### Phase 4: Integration Testing and Polish (Priority: Medium) + +#### Task 4.1: Cross-Layout Consistency Testing + +- Verify typography consistency across all layouts +- Test avatar sizing consistency in different contexts +- Ensure PreviewMediaContent modal works consistently +- Test scroll behavior across all entry types + +#### Task 4.2: Performance and Accessibility Testing + +- Verify no performance regressions with scroll fixes +- Test keyboard navigation with new carousel behavior +- Ensure proper focus management in PreviewMediaContent +- Test screen reader compatibility + +## Context & References + +### Codebase Architecture Understanding + +#### Core Components to Modify + +- **AuthorHeader.tsx**: Typography improvements for author names +- **FeedIcon.tsx**: Size-responsive border radius implementation +- **PicturesLayout.tsx**: Single image display with carousel integration +- **ScrollArea.tsx**: Flex container height calculation fixes +- **EntryContent.tsx**: Scroll container height fixes +- **picture-item.tsx**: Restore image click preview behavior + +#### Existing Patterns to Follow + +- **PreviewMediaContent.tsx**: Modal-based media carousel (Embla carousel integration) +- **usePreviewMedia**: Hook for triggering media preview modals +- **Media component**: Image display with loading states and proxy support +- **UIKit color system**: Consistent with `text-base`, `rounded-lg` etc. + +### External Best Practices & Documentation + +#### CSS Flexbox Height Calculation Fixes + +- **Min-Height Zero Pattern**: https://stackoverflow.com/questions/21515042/scrolling-a-flexbox-with-overflowing-content +- **Flex Container Overflow**: https://moduscreate.com/blog/how-to-fix-overflow-issues-in-css-flex-layouts/ +- **Critical Insight**: "There's a special case where the min-height of flex items defaults to the content size. We have to explicitly set the min height to zero." + +#### React Image Carousel Best Practices + +- **Single Image Display**: https://cloudinary.com/blog/add-a-responsive-image-carousel-to-your-react-app +- **Click Navigation**: Custom controls with callback functions and hasNext/hasPrev state +- **Responsive Design**: Automatic layout adjustment based on screen size +- **Performance**: Lazy loading and video play control on selected slides + +#### Typography and Avatar Scaling + +- **Responsive Avatar Sizing**: Border radius should scale proportionally with avatar size +- **Social Media Typography**: Author names should be prominent (16px+ / text-base) for readability +- **Apple UIKit Standards**: Consistent size relationships (border radius = size/6 to size/4) + +### Implementation Guidelines + +#### Typography Scaling Pattern + +```typescript +// Size-based styling patterns +const getFontSize = (context: "social" | "article" | "compact") => { + switch (context) { + case "social": + return "text-base font-semibold" // 16px for prominence + case "article": + return "text-sm font-semibold" // 14px for articles + case "compact": + return "text-xs font-medium" // 12px for compact + } +} +``` + +#### Border Radius Scaling Pattern + +```typescript +// Size-responsive border radius +const getBorderRadius = (size: number) => { + const ratio = size / 8 // Scale factor + if (ratio <= 3) return "rounded-sm" // 2px + if (ratio <= 4) return "rounded-md" // 6px + if (ratio <= 6) return "rounded-lg" // 8px + return "rounded-xl" // 12px +} +``` + +#### Single Image Carousel Pattern + +```typescript +// Media display with carousel integration +const handleImageClick = useCallback(() => { + if (mediaArray.length > 0) { + previewMedia( + mediaArray.map(transformMediaForPreview), + 0, // Initial index + ) + } +}, [mediaArray, previewMedia]) +``` + +## Validation Gates + +### Code Quality Checks + +```bash +# TypeScript validation +pnpm run typecheck + +# Linting validation +pnpm run lint:tsl +pnpm run lint + +# Code formatting +pnpm run format + +# Build validation +pnpm run build:web +``` + +### Functional Testing Checklist + +#### Social Media Layout Validation + +- [ ] Author name displays with `text-base` font size (16px) +- [ ] Author name maintains proper font weight and color +- [ ] Avatar border radius scales appropriately with 48px size +- [ ] Avatar maintains circular appearance with proper radius +- [ ] Typography is consistent across different author name lengths +- [ ] Layout maintains proper spacing and alignment + +#### Pictures Layout Validation + +- [ ] Single image displays instead of multiple images side by side +- [ ] First image from media array is shown as primary display +- [ ] "+X more" indicator appears when multiple images exist +- [ ] Clicking single image opens PreviewMediaContent modal +- [ ] Carousel navigation works properly in modal (left/right arrows) +- [ ] Image maintains proper aspect ratio and scaling +- [ ] No layout shift when transitioning to/from modal + +#### Entry List Image Click Validation + +- [ ] Clicking images in picture-item triggers PreviewMediaContent modal +- [ ] Modal opens with correct initial image and media array +- [ ] Entry navigation still works when clicking non-image areas +- [ ] No conflicts between image click and entry click behaviors +- [ ] Touch gestures work properly on mobile devices + +#### Scroll Container Height Validation + +- [ ] Long content no longer gets cut off at bottom in Social Media layout +- [ ] Long content no longer gets cut off at bottom in Video layout +- [ ] ScrollArea height matches available container height +- [ ] Content scrolls smoothly to very bottom without truncation +- [ ] No visual glitches or layout shifts during scrolling +- [ ] Fix applies to all entry types (Articles, Social Media, Videos, Pictures) +- [ ] Mobile responsive behavior maintains proper scrolling + +### Performance & Integration Testing + +- [ ] No layout shift when switching between entry types +- [ ] PreviewMediaContent modal opens smoothly without lag +- [ ] Image loading states display properly +- [ ] Scroll performance maintained with height fixes +- [ ] No memory leaks with modal-based image preview +- [ ] Typography rendering remains crisp at all zoom levels + +## Success Criteria + +### Primary Objectives + +- [ ] **Social Media**: Author names display prominently with proper typography +- [ ] **Social Media**: Avatar border radius scales appropriately with size +- [ ] **Pictures**: Single image display with click-to-carousel functionality +- [ ] **Pictures**: Entry list image clicking restored and working properly +- [ ] **Scroll Heights**: Long content fully visible without truncation in all layouts +- [ ] **Performance**: All fixes implemented without performance regression + +### Quality Standards + +- [ ] Zero regressions in existing ArticleLayout functionality +- [ ] All layout types maintain consistent typography patterns +- [ ] PreviewMediaContent modal integration works seamlessly +- [ ] ScrollArea height calculation robust across different content types +- [ ] Mobile responsive design maintained across all fixes + +### User Experience Improvements + +- [ ] Social media author information more readable and prominent +- [ ] Picture viewing experience enhanced with proper carousel integration +- [ ] Content consumption improved with full scroll accessibility +- [ ] Visual consistency improved with proper avatar styling +- [ ] Interaction patterns consistent between entry list and content view + +## Risk Assessment & Mitigation + +### High-Risk Areas + +#### 1. ScrollArea Height Calculation Changes + +**Risk**: Height fixes might break existing scroll behavior in other components +**Mitigation**: + +- Apply changes incrementally with thorough testing +- Maintain backward compatibility with existing ScrollArea usage +- Test all scroll containers across the application +- Use feature flags for gradual rollout if needed + +#### 2. PreviewMediaContent Modal Integration + +**Risk**: Modal stacking conflicts or keyboard navigation issues +**Mitigation**: + +- Test modal behavior with existing modal stack system +- Verify proper cleanup of modal state +- Ensure keyboard navigation (ESC, arrows) works correctly +- Test touch gestures on mobile devices + +#### 3. Typography Changes Impact + +**Risk**: Font size changes might break layout in compact or mobile views +**Mitigation**: + +- Test with various author name lengths and special characters +- Verify responsive behavior across all screen sizes +- Check international character rendering (CJK, Arabic, etc.) +- Maintain proper line height and spacing + +### Medium-Risk Areas + +#### Component Dependencies + +**Risk**: Changes to shared components might affect other features +**Mitigation**: + +- Audit all usage of modified components before changes +- Use backward-compatible prop additions +- Test AuthorHeader and FeedIcon usage across application +- Verify no breaking changes to component APIs + +#### Image Loading Performance + +**Risk**: Single image display might affect loading performance +**Mitigation**: + +- Maintain existing lazy loading behavior +- Test image proxy functionality with new implementation +- Profile image loading performance before and after changes +- Ensure proper loading states and error handling + +### Rollback Strategy + +- Implement changes as separate commits for easy reversal +- Use CSS custom properties for easy typography adjustments +- Maintain original component implementations as backup +- Feature flag capability for critical scroll height fixes + +## Additional Considerations + +### Accessibility Standards + +- Ensure author names maintain proper contrast ratios with larger text +- Test screen reader compatibility with typography changes +- Verify keyboard navigation works properly with image carousel +- Maintain proper heading hierarchy across layout changes + +### Internationalization Support + +- Test typography changes with different language character sets +- Ensure proper text flow with RTL languages +- Verify avatar and text spacing works with longer translated text +- Maintain consistent translation key usage across components + +### Future Extensibility + +- Typography pattern scalable to other layout types +- Border radius pattern reusable for other avatar contexts +- ScrollArea fixes applicable to other scroll containers +- Image carousel pattern extensible to video content + +## Confidence Score: 9/10 + +This PRP provides a comprehensive solution with high implementation confidence: + +### Strengths + +- ✅ **Root Cause Analysis**: Identified exact source of each issue with specific file/line references +- ✅ **Proven External Research**: Incorporates CSS flexbox best practices and React carousel patterns +- ✅ **Focused Scope**: Addresses specific reported issues without unnecessary complexity +- ✅ **Detailed Implementation**: Clear component-by-component changes with code examples +- ✅ **Risk Management**: Identified potential issues with concrete mitigation strategies +- ✅ **Comprehensive Testing**: Detailed validation steps for each change +- ✅ **Existing Pattern Leverage**: Uses established components (PreviewMediaContent, usePreviewMedia) + +### Implementation Confidence Factors + +1. **Clear Problem Definition**: Each issue traced to specific code locations with examples +2. **External Best Practices**: CSS flexbox fixes and React carousel patterns are well-established +3. **Component Reuse**: Leveraging existing PreviewMediaContent rather than building new carousel +4. **Incremental Approach**: Changes can be implemented and tested independently +5. **Minimal Breaking Changes**: Most fixes involve styling adjustments and proper component usage +6. **Established Patterns**: Typography and avatar sizing follow existing codebase conventions + +### Minor Risk Areas + +- **ScrollArea Changes**: Need thorough testing across different content types +- **Typography Impact**: Must verify responsive behavior with larger text +- **Modal Integration**: Ensure smooth interaction with existing modal stack + +The high confidence score reflects that this PRP addresses well-defined styling and functional issues using established patterns and external best practices, with clear implementation steps and comprehensive validation approaches. diff --git a/PRPs/entry-modal-to-routing.md b/PRPs/entry-modal-to-routing.md new file mode 100644 index 000000000..ea9528628 --- /dev/null +++ b/PRPs/entry-modal-to-routing.md @@ -0,0 +1,278 @@ +# PRP: Entry Modal to Routing Refactoring + +## Overview + +Refactor the entry content display system from a full-page modal approach to a scoped, column-based routing approach. This will improve user experience by keeping the modal scoped to the entry list column and make the entry content display reflect in the URL for better navigation. + +## Current Implementation Analysis + +### Current Architecture + +- **Three-column layout**: Feed list (left) → Entry list (center) → AI chat (right) +- **Main layout**: `MainDestopLayout` → `SubscriptionColumnContainer` + `` (`CenterColumnLayout`) +- **Entry list**: Located in `CenterColumnLayout` which contains `EntryColumn` and `AIChatLayout` +- **Modal system**: Uses `usePeekModal` hook to display entry content in a full-page modal + +### Key Files & Components + +#### Current Modal Implementation + +- **`usePeekModal.tsx`**: Hook that creates full-page modal using `PeekModal` component +- **`EntryItemWrapper.tsx:126`**: Click handler calls `peekModal(entry.id, "modal")` instead of navigation +- **`PeekModal` component**: Renders modal with `modalClassName` covering entire viewport + +#### Routing Infrastructure + +- **`useNavigateEntry.ts`**: Contains `getNavigateEntryPath()` function that generates proper entry URLs +- **Route structure**: `/timeline/:timelineId/:feedId/:entryId` +- **Current entry routing**: + - Layout: `/timeline/[timelineId]/[feedId]/layout.tsx` → `CenterColumnLayout` + - Index: `/timeline/[timelineId]/[feedId]/index.tsx` → redirects to `ROUTE_ENTRY_PENDING` + - Entry: `/timeline/[timelineId]/[feedId]/[entryId]/index.tsx` → `EntryLayoutContent` + +#### Layout Components + +- **`CenterColumnLayout.tsx`**: Two-column layout with entry list and AI chat +- **`EntryLayoutContent.tsx`**: Renders entry content when entryId is present in URL +- **`MainDestopLayout.tsx`**: Root layout with feed column and main content outlet + +### Current Flow + +1. User clicks entry in `EntryItemWrapper` +2. `handleClick` calls `peekModal(entry.id, "modal")` +3. Modal covers entire viewport, disrupting three-column layout +4. Entry content not reflected in URL routing + +## Proposed Solution + +### Architecture Changes + +Transform the entry content display from a modal overlay to a proper routing-based approach that renders within the entry column scope. + +### New Flow + +1. User clicks entry in `EntryItemWrapper` +2. `handleClick` calls `navigateEntry()` with `getNavigateEntryPath()` +3. URL changes to `/timeline/:timelineId/:feedId/:entryId` +4. Entry content renders within entry column boundaries via `` + +### Key Modifications + +#### 1. Modify Entry Click Handler + +**File**: `apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx:115-129` + +Replace modal invocation with navigation: + +```typescript +// BEFORE +const handleClick = useCallback( + (e) => { + // ... existing logic + peekModal(entry.id, "modal") + }, + [peekModal], +) + +// AFTER +const handleClick = useCallback( + (e) => { + // ... existing logic + navigateEntry({ entryId: entry.id }) + }, + [navigateEntry], +) +``` + +#### 2. Update CenterColumnLayout for Entry Display + +**File**: `apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/CenterColumnLayout.tsx` + +Add conditional rendering for entry content within the entry column: + +```typescript +// Current: Simple two-column layout +
+ +
+ +// Proposed: Conditional entry content display +
+ + {/* Renders entry content when entryId is present */} +
+``` + +#### 3. Create Column-Scoped Entry Layout + +**New file**: `apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnLayout.tsx` + +```typescript +export const EntryColumnLayout = () => { + const { entryId } = useParams() + const navigate = useNavigateEntry() + + if (!entryId || entryId === ROUTE_ENTRY_PENDING) { + return + } + + return ( +
+ {/* Entry list background */} + + + {/* Entry content overlay within column */} +
+ navigate({ entryId: null })} + /> +
+
+ ) +} +``` + +#### 4. Update Route Configuration + +**File**: `apps/desktop/layer/renderer/src/pages/(main)/(layer)/timeline/[timelineId]/[feedId]/layout.tsx` + +Change from `CenterColumnLayout` to new scoped layout: + +```typescript +// BEFORE +export { CenterColumnLayout as Component } from "~/modules/app-layout/timeline-column/index" + +// AFTER +export { EntryColumnLayout as Component } from "~/modules/entry-column/EntryColumnLayout" +``` + +## Implementation Tasks + +### Phase 1: Core Routing Setup + +1. **Create EntryColumnLayout component** + - Implement conditional rendering for entry content + - Add proper scoping within entry column boundaries + - Handle entry close navigation + +2. **Update CenterColumnLayout route** + - Replace component export in layout.tsx + - Ensure proper outlet rendering + +3. **Modify EntryItemWrapper click handler** + - Replace `peekModal` call with `navigateEntry` + - Import and use existing navigation utilities + +### Phase 2: Layout & Styling + +4. **Style scoped entry content** + - Ensure entry content stays within column boundaries + - Add proper animations for entry open/close + - Handle responsive behavior + +5. **Update entry content close behavior** + - Remove modal-specific close logic + - Implement navigation-based close + +### Phase 3: Testing & Validation + +6. **Test navigation flow** + - Verify URL changes correctly + - Test browser back/forward navigation + - Validate entry content display + +7. **Test edge cases** + - Direct URL access to entry routes + - Entry not found scenarios + - Mobile responsiveness + +## Context & References + +### Existing Patterns + +- **Navigation utilities**: `useNavigateEntry`, `getNavigateEntryPath` already exist +- **Route structure**: Entry routing infrastructure already present +- **Entry content component**: `EntryContent` component already handles rendering + +### External Documentation + +- **React Router Modal Patterns**: https://blog.logrocket.com/building-react-modal-module-with-react-router/ +- **Background Location Pattern**: https://dev.to/unorthodev/how-to-make-routable-modals-in-react-with-react-router-3hgp +- **Scoped Navigation**: https://github.com/remix-run/react-router/discussions/9601 + +### Best Practices Applied + +1. **Nested Route Approach**: Use existing route structure with outlets +2. **Scoped Rendering**: Keep entry content within column boundaries +3. **Persistent Navigation**: URL reflects entry selection state +4. **Smooth Transitions**: Maintain existing animation patterns + +## Validation Gates + +### Code Quality + +```bash +# TypeScript validation +pnpm run typecheck + +# Linting +pnpm run lint + +# Build validation +pnpm run build:web +``` + +### Functional Testing + +```bash +# Manual testing checklist +1. Click entry in list → URL updates → Entry content displays in column +2. Browser back/forward → Entry content appears/disappears correctly +3. Direct URL access → Entry content renders properly +4. Entry close action → Returns to entry list with correct URL +5. Mobile responsiveness → Entry content adapts to smaller screens +``` + +### Performance Validation + +- No increase in bundle size +- Smooth animations maintained +- No layout shifts during entry display + +## Success Criteria + +- [ ] Entry clicks trigger navigation instead of modal +- [ ] Entry content displays within column boundaries +- [ ] URL reflects entry selection state +- [ ] Browser navigation works correctly +- [ ] Entry close returns to proper state +- [ ] All existing functionality preserved +- [ ] No visual regression in three-column layout + +## Risk Mitigation + +### Potential Issues + +1. **Layout disruption**: Entry content might overflow column boundaries +2. **Animation conflicts**: Existing animations might conflict with new approach +3. **Mobile compatibility**: Column-scoped display might not work on mobile + +### Mitigation Strategies + +1. **Absolute positioning**: Use absolute positioning to contain entry content +2. **CSS containment**: Use CSS containment properties for layout isolation +3. **Responsive design**: Implement mobile-specific fallbacks if needed + +## Confidence Score: 8/10 + +This PRP provides a comprehensive approach with: + +- ✅ Detailed analysis of current implementation +- ✅ Clear technical specifications +- ✅ Existing code patterns leveraged +- ✅ External best practices incorporated +- ✅ Executable validation steps +- ✅ Risk mitigation strategies + +The high confidence comes from the existing navigation infrastructure and clear understanding of the current modal system. The main implementation involves connecting existing pieces rather than building from scratch. diff --git a/PRPs/ratio-based-mixing.md b/PRPs/ratio-based-mixing.md new file mode 100644 index 000000000..b2e701017 --- /dev/null +++ b/PRPs/ratio-based-mixing.md @@ -0,0 +1,397 @@ +# PRP: Ratio-Based Color Mixing Tailwind Plugin + +## Project Overview + +This PRP defines the implementation of a Tailwind CSS plugin that provides ratio-based syntax for color mixing as an alternative to lengthy `color-mix()` CSS declarations. The plugin will transform shortened syntax like `bg-mix-accent/background-7/3` into native CSS `color-mix()` functions. + +## Current Problem Analysis + +### Existing Usage Patterns + +The codebase currently uses verbose arbitrary value syntax for color mixing: + +```css +/* Current verbose syntax - 137 characters */ +bg-[color-mix(in_srgb,hsl(var(--fo-a)),hsl(var(--background))_70%)] + +/* Complex nested mixing - 172 characters */ +bg-[color-mix(in_srgb,_color-mix(in_srgb,rgb(var(--color-red)),hsl(var(--background))_80%),transparent_30%)] +``` + +**Found Usage Locations:** + +- `/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserChatMessage.tsx:137` +- `/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/CollapsibleError.tsx:172` + +### Problems Identified + +1. **Readability**: Extremely long class names reduce code clarity +2. **Maintainability**: Hard to modify mixing ratios +3. **Performance**: Arbitrary values prevent CSS optimization +4. **Developer Experience**: No IntelliSense support +5. **Consistency**: No standardized mixing ratios across project + +## Solution Design + +### Ratio-Based Syntax Options + +**Primary Syntax (Recommended):** + +```css +/* Ratio format: color1/color2-ratio1/ratio2 */ +bg-mix-accent/background-7/3 /* 70% accent, 30% background */ +bg-mix-red/background-4/1 /* 80% red, 20% background */ +border-mix-blue/white-3/2 /* 60% blue, 40% white */ +text-mix-accent/background-9/1 /* 90% accent, 10% background */ +``` + +**Alternative Syntax (Percentage-based):** + +```css +bg-mix-accent-70 /* 70% accent, 30% background (implicit) */ +bg-mix-red-80 /* 80% red, 20% background (implicit) */ +``` + +**Generated CSS Output:** + +```css +.bg-mix-accent\/background-7\/3 { + background-color: color-mix(in srgb, hsl(var(--fo-a)) 70%, hsl(var(--background)) 30%); +} +``` + +## Technical Implementation + +### Plugin Architecture + +Based on existing codebase patterns in `/packages/configs/tailwindcss/web.ts`: + +```typescript +// New file: /packages/configs/tailwindcss/ratio-mixing-plugin.js +const plugin = require("tailwindcss/plugin") + +const ratioMixingPlugin = plugin.withOptions( + (options = {}) => { + return ({ addUtilities, theme, e }) => { + const config = { ...defaultConfig, ...options } + const utilities = {} + + // Generate ratio-based utilities + generateRatioBasedUtilities(utilities, config) + + // Generate percentage-based utilities (fallback) + generatePercentageBasedUtilities(utilities, config) + + addUtilities(utilities) + } + }, + (options) => { + return { + theme: { + // Theme extensions if needed + }, + } + }, +) + +module.exports = ratioMixingPlugin +``` + +### Configuration Schema + +```typescript +interface RatioMixingConfig { + colorSpace?: "srgb" | "hsl" | "oklab" | "oklch" + baseColors: { + [key: string]: string // CSS variable or color value + } + ratios?: { + [key: string]: [number, number] // [numerator, denominator] pairs + } + variants?: ("bg" | "border" | "text")[] + prefix?: string + implicitBackground?: string +} + +const defaultConfig: RatioMixingConfig = { + colorSpace: "srgb", + baseColors: { + background: "hsl(var(--background))", + accent: "hsl(var(--fo-a))", + red: "rgb(var(--color-red))", + // Map to existing theme colors from UIKit + }, + ratios: { + "1/1": [1, 1], // 50%/50% + "2/1": [2, 1], // 66.7%/33.3% + "3/1": [3, 1], // 75%/25% + "4/1": [4, 1], // 80%/20% + "7/3": [7, 3], // 70%/30% + "9/1": [9, 1], // 90%/10% + }, + variants: ["bg", "border", "text"], + prefix: "mix", + implicitBackground: "background", +} +``` + +### Core Implementation Functions + +```javascript +function generateRatioBasedUtilities(utilities, config) { + const { baseColors, ratios, variants, colorSpace } = config + + // Generate: bg-mix-accent/background-7/3 + Object.entries(baseColors).forEach(([color1Name, color1Value]) => { + Object.entries(baseColors).forEach(([color2Name, color2Value]) => { + if (color1Name === color2Name) return // Skip same color mixing + + Object.entries(ratios).forEach(([ratioKey, [num, denom]]) => { + const percentage1 = Math.round((num / (num + denom)) * 100) + const percentage2 = 100 - percentage1 + + variants.forEach((variant) => { + const className = `.${variant}-${config.prefix}-${color1Name}\\/${color2Name}-${ratioKey.replace("/", "\\/")}` + const property = getPropertyName(variant) + const mixedColor = `color-mix(in ${colorSpace}, ${color1Value} ${percentage1}%, ${color2Value} ${percentage2}%)` + + utilities[className] = { [property]: mixedColor } + }) + }) + }) + }) +} + +function generatePercentageBasedUtilities(utilities, config) { + // Generate: bg-mix-accent-70 (implicit background mixing) + const { baseColors, variants, colorSpace, implicitBackground } = config + const backgroundValue = baseColors[implicitBackground] + + const percentages = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95] + + Object.entries(baseColors).forEach(([colorName, colorValue]) => { + if (colorName === implicitBackground) return + + percentages.forEach((percentage) => { + variants.forEach((variant) => { + const className = `.${variant}-${config.prefix}-${colorName}-${percentage}` + const property = getPropertyName(variant) + const mixedColor = `color-mix(in ${colorSpace}, ${colorValue} ${percentage}%, ${backgroundValue} ${100 - percentage}%)` + + utilities[className] = { [property]: mixedColor } + }) + }) + }) +} + +function getPropertyName(variant) { + switch (variant) { + case "bg": + return "background-color" + case "border": + return "border-color" + case "text": + return "color" + default: + return "background-color" + } +} +``` + +### Integration with Existing Config + +Update `/packages/configs/tailwindcss/web.ts`: + +```typescript +import ratioMixingPlugin from "./ratio-mixing-plugin" + +const twConfig = { + // ... existing config + plugins: [ + // ... existing plugins + ratioMixingPlugin({ + baseColors: { + background: "hsl(var(--background))", + accent: "hsl(var(--fo-a))", + red: "rgb(var(--color-red))", + // Map to UIKit colors already in theme + }, + }), + ], +} satisfies Config +``` + +## Migration Strategy + +### Before/After Examples + +```jsx +// BEFORE: Verbose arbitrary values +
+ User message +
+ +// AFTER: Clean ratio syntax +
+ User message +
+ +// ALTERNATIVE: Percentage syntax (when mixing with background) +
+ User message +
+``` + +### Migration Steps + +1. Install plugin in Tailwind config +2. Generate new utility classes via build +3. Replace existing arbitrary values with new classes +4. Test visual consistency +5. Run lint/typecheck validation + +## Implementation Tasks + +### Phase 1: Core Plugin Development + +1. **Create plugin file structure** + - Create `/packages/configs/tailwindcss/ratio-mixing-plugin.js` + - Implement core `plugin.withOptions` structure + - Add default configuration schema + +2. **Implement ratio parsing logic** + - Create `generateRatioBasedUtilities()` function + - Handle ratio-to-percentage conversion + - Support escape characters for CSS class names (`/` → `\/`) + +3. **Add percentage fallback** + - Implement `generatePercentageBasedUtilities()` function + - Provide implicit background mixing + - Support common percentage values + +### Phase 2: Integration & Configuration + +4. **Integrate with existing Tailwind config** + - Update `/packages/configs/tailwindcss/web.ts` + - Map to existing UIKit color variables + - Test build process compatibility + +5. **Color mapping to existing theme** + - Extract colors from current theme configuration + - Map `--fo-a`, `--background`, `--color-red` variables + - Ensure compatibility with existing color system + +### Phase 3: Migration & Testing + +6. **Migrate existing usage** + - Update `UserChatMessage.tsx:137` + - Update `CollapsibleError.tsx:172` + - Search for other arbitrary color-mix usages + +7. **Validation & testing** + - Visual regression testing + - CSS output verification + - Build process validation + +## Validation Gates + +### Build Validation + +```bash +# TypeScript compilation +pnpm run typecheck + +# Linting validation +pnpm run lint +pnpm run lint:tsl + +# Tailwind build test +cd packages/configs/tailwindcss && npx tailwindcss build +``` + +### Plugin-Specific Validation + +```bash +# Test plugin registration +node -e "console.log(require('./packages/configs/tailwindcss/ratio-mixing-plugin.js'))" + +# Test CSS generation +echo "@tailwind utilities;" | npx tailwindcss --config packages/configs/tailwindcss/web.ts +``` + +### Visual Validation + +```bash +# Development server test +cd apps/desktop && pnpm run dev:web + +# Build verification +pnpm run build:web +``` + +## Expected Deliverables + +1. **Plugin Implementation** + - `/packages/configs/tailwindcss/ratio-mixing-plugin.js` - Complete plugin + - Updated `/packages/configs/tailwindcss/web.ts` - Integration + +2. **Migration Changes** + - Updated component files with new class syntax + - Removed verbose arbitrary value usage + +3. **Documentation** + - Generated CSS class reference + - Migration guide for future usage + +## Risk Assessment & Mitigation + +### Potential Issues + +1. **CSS Specificity**: New utilities should have same specificity as existing ones +2. **Build Performance**: Plugin should not significantly slow build times +3. **Browser Compatibility**: `color-mix()` requires modern browser support +4. **Class Name Conflicts**: Need to avoid conflicts with existing utilities + +### Mitigation Strategies + +1. Follow Tailwind's utility layer conventions +2. Implement efficient utility generation (avoid nested loops where possible) +3. Document browser support requirements (IE not supported) +4. Use unique prefixes and test for conflicts + +## Success Criteria + +1. **Functionality**: All current color mixing usage successfully migrated +2. **Performance**: No measurable build time increase (< 5% overhead) +3. **Maintainability**: New syntax reduces class name length by >60% +4. **Developer Experience**: IntelliSense support for new utilities +5. **Visual Consistency**: Pixel-perfect visual match with existing styling + +## External References + +### Documentation + +- **Tailwind Plugin API**: https://v3.tailwindcss.com/docs/plugins +- **CSS color-mix() Specification**: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix +- **Existing Plugin Examples**: https://github.com/JavierM42/tailwindcss-color-mix + +### Codebase Files to Reference + +- `/packages/configs/tailwindcss/web.ts` - Main Tailwind configuration +- `/packages/configs/tailwindcss/tw-css-plugin.js` - Existing plugin pattern +- `/packages/configs/tailwindcss/tailwind-extend.css` - Utility examples + +## Confidence Score: 8/10 + +**Rationale**: High confidence due to: + +- ✅ Clear existing patterns in codebase +- ✅ Well-documented Tailwind plugin API +- ✅ Specific usage examples identified +- ✅ CSS color-mix() is well-supported specification +- ✅ Comprehensive implementation plan + +**Potential challenges**: + +- ⚠️ CSS class name escaping complexity +- ⚠️ Color variable mapping accuracy diff --git a/README.md b/README.md index 90d5539ce..4f3c38b2e 100644 --- a/README.md +++ b/README.md @@ -96,12 +96,6 @@ Because we know content is more than just text. From articles to videos, images ![](https://github.com/user-attachments/assets/d1379fd6-8767-476e-b0dc-d61753715e26) -### $POWER An Ownership Economy - -Tip creators across instantly with $POWER, support content you love, and unlock value in your own work. Your content, your power. - -![](https://github.com/user-attachments/assets/23bbcd63-45ca-40c8-83ef-96bd1100b701) - ### More Than Just An App This isn’t just another app. Folo is a community — introducing a new era of openness and community-driven experience. diff --git a/apps/desktop/changelog/next.md b/apps/desktop/changelog/next.md index 8f5eac449..fc6b11e21 100644 --- a/apps/desktop/changelog/next.md +++ b/apps/desktop/changelog/next.md @@ -2,8 +2,18 @@ ## Shiny new things +- AI Chat for RSS (Folo AI): A personalized, context-aware chat built for readers. The assistant understands your feeds, lists, and reading patterns to help you get more from what you follow. + - Summarize articles, translate content, and get quick explanations—without leaving your timeline. + - Ask feed-aware questions (e.g., “What did I miss this week?”) and receive suggestions tailored to your habits. + - Discover what to read next based on your subscriptions and saved items. + - Streamlined chat UI with context pickers for feeds, entries, and more. + - Early preview: we’ll iterate quickly with your feedback. + - Limited rollout: currently available to a subset of users; we’ll expand testing over time. + ## Improvements +- Foundations for richer, feed-aware AI features and future extensibility around the chat module. + ## No longer broken ## Thanks diff --git a/apps/desktop/layer/main/export.ts b/apps/desktop/layer/main/export.ts index 260b06619..567ca07bc 100644 --- a/apps/desktop/layer/main/export.ts +++ b/apps/desktop/layer/main/export.ts @@ -1,5 +1,2 @@ // Export types for renderer to use export type { IpcServices } from "./src/ipc" - -// Export services for potential main process use -export { services } from "./src/ipc" diff --git a/apps/desktop/layer/main/package.json b/apps/desktop/layer/main/package.json index a95d7c90b..c1a7ff4c7 100644 --- a/apps/desktop/layer/main/package.json +++ b/apps/desktop/layer/main/package.json @@ -23,6 +23,7 @@ "@electron-toolkit/preload": "3.0.2", "@electron-toolkit/utils": "4.0.0", "@eneris/push-receiver": "4.3.0", + "@follow-app/client-sdk": "catalog:", "@follow-app/readability": "workspace:*", "@follow/shared": "workspace:*", "@follow/utils": "workspace:*", @@ -30,6 +31,7 @@ "@sentry/electron": "6.8.0", "builder-util-runtime": "9.3.1", "electron-context-menu": "4.0.5", + "electron-ipc-decorator": "0.2.0", "electron-log": "5.4.1", "electron-squirrel-startup": "1.0.1", "electron-store": "10.1.0", diff --git a/apps/desktop/layer/main/src/ipc/base.ts b/apps/desktop/layer/main/src/ipc/base.ts deleted file mode 100644 index 9d14893fb..000000000 --- a/apps/desktop/layer/main/src/ipc/base.ts +++ /dev/null @@ -1,118 +0,0 @@ -import type { IpcMainInvokeEvent, WebContents } from "electron" -import { ipcMain } from "electron" - -// Base context for IPC methods -export interface IpcContext { - sender: WebContents - event: IpcMainInvokeEvent -} - -// Metadata storage for decorated methods -const methodMetadata = new WeakMap>() - -// Decorator for IPC methods -export function IpcMethod(methodName?: string) { - return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { - const { constructor } = target - - if (!methodMetadata.has(constructor)) { - methodMetadata.set(constructor, new Map()) - } - - const methods = methodMetadata.get(constructor)! - const finalMethodName = methodName || propertyKey - methods.set(propertyKey, finalMethodName) - - return descriptor - } -} - -// Handler registry for IPC methods -export class IpcHandler { - private static instance: IpcHandler - private registeredChannels = new Set() - - static getInstance(): IpcHandler { - if (!IpcHandler.instance) { - IpcHandler.instance = new IpcHandler() - } - return IpcHandler.instance - } - - registerMethod( - channel: string, - handler: (context: IpcContext, ...args: any[]) => Promise | TOutput, - ) { - if (this.registeredChannels.has(channel)) { - return // Already registered - } - - this.registeredChannels.add(channel) - - ipcMain.handle(channel, async (event: IpcMainInvokeEvent, ...args: any[]) => { - const context: IpcContext = { - sender: event.sender, - event, - } - - try { - return await handler(context, ...args) - } catch (error) { - console.error(`Error in IPC method ${channel}:`, error) - throw error - } - }) - } - - // Send events to renderer - sendToRenderer(webContents: WebContents, channel: string, data: T) { - webContents.send(channel, data) - } -} - -// Base class for IPC service groups -export abstract class IpcService { - protected handler = IpcHandler.getInstance() - - constructor(protected groupName: string) { - this.registerMethods() - } - - protected registerMethods(): void { - const { constructor } = this - const methods = methodMetadata.get(constructor) - - if (methods) { - for (const [propertyKey, methodName] of methods) { - const method = (this as any)[propertyKey] - if (typeof method === "function") { - this.registerMethod(methodName, method.bind(this)) - } - } - } - } - - protected registerMethod( - methodName: string, - handler: (context: IpcContext, ...args: any[]) => Promise | TOutput, - ) { - const channel = `${this.groupName}.${methodName}` - this.handler.registerMethod(channel, handler) - } -} - -// Extract method signatures from service class, removing context parameter -export type ExtractServiceMethods = { - [K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K] extends ( - context: IpcContext, - ...args: infer Args - ) => infer Output - ? Args extends [] - ? () => AlwaysPromise - : Args extends [infer Input] - ? (input: Input) => AlwaysPromise - : (...args: Args) => AlwaysPromise - : never -} - -type AlwaysPromise = Promise> diff --git a/apps/desktop/layer/main/src/ipc/index.ts b/apps/desktop/layer/main/src/ipc/index.ts index 0d13b8ab2..635c80e0c 100644 --- a/apps/desktop/layer/main/src/ipc/index.ts +++ b/apps/desktop/layer/main/src/ipc/index.ts @@ -1,4 +1,6 @@ -import type { ExtractServiceMethods } from "./base" +import type { MergeIpcService } from "electron-ipc-decorator" +import { createServices } from "electron-ipc-decorator" + import { AppService } from "./services/app" import { AuthService } from "./services/auth" import { DebugService } from "./services/debug" @@ -9,31 +11,22 @@ import { ReaderService } from "./services/reader" import { SettingService } from "./services/setting" // Initialize all services -export const services = { - app: new AppService(), - auth: new AuthService(), - debug: new DebugService(), - dock: new DockService(), - menu: new MenuService(), - reader: new ReaderService(), - setting: new SettingService(), - integration: new IntegrationService(), -} as const - +const services = createServices([ + AppService, + AuthService, + DebugService, + DockService, + MenuService, + ReaderService, + SettingService, + IntegrationService, +]) // Extract method types automatically from services -export type IpcServices = { - app: ExtractServiceMethods - auth: ExtractServiceMethods - debug: ExtractServiceMethods - dock: ExtractServiceMethods - menu: ExtractServiceMethods - reader: ExtractServiceMethods - setting: ExtractServiceMethods - integration: ExtractServiceMethods -} +export type IpcServices = MergeIpcService // Initialize all services (this will register all IPC handlers) export function initializeIpcServices() { // Services are already initialized in the services constant above console.info("IPC services initialized") + void services } diff --git a/apps/desktop/layer/main/src/ipc/services/app.ts b/apps/desktop/layer/main/src/ipc/services/app.ts index 7aea4c05b..a9b654912 100644 --- a/apps/desktop/layer/main/src/ipc/services/app.ts +++ b/apps/desktop/layer/main/src/ipc/services/app.ts @@ -4,8 +4,11 @@ import { fileURLToPath } from "node:url" import { callWindowExpose } from "@follow/shared/bridge" import { DEV } from "@follow/shared/constants" import { app, BrowserWindow, clipboard, dialog, shell } from "electron" +import type { IpcContext } from "electron-ipc-decorator" +import { IpcMethod, IpcService } from "electron-ipc-decorator" import path from "pathe" +import { START_IN_TRAY_ARGS } from "~/constants/app" import { getCacheSize } from "~/lib/cleaner" import { i18n } from "~/lib/i18n" import { store, StoreKey } from "~/lib/store" @@ -17,8 +20,6 @@ import { cleanupOldRender, loadDynamicRenderEntry } from "~/updater/hot-updater" import { downloadFile } from "../../lib/download" import { checkForAppUpdates, quitAndInstall } from "../../updater" -import type { IpcContext } from "../base" -import { IpcMethod, IpcService } from "../base" interface WindowActionInput { action: "close" | "minimize" | "maximum" @@ -34,9 +35,7 @@ interface Sender extends Electron.WebContents { } export class AppService extends IpcService { - constructor() { - super("app") - } + static override readonly groupName = "app" @IpcMethod() getAppVersion(): string { @@ -183,6 +182,16 @@ export class AppService extends IpcService { return path.join(app.getAppPath(), input) } + @IpcMethod() + readyToShowMainWindow(_context: IpcContext) { + const shouldShowWindow = + !app.getLoginItemSettings().wasOpenedAsHidden && !process.argv.includes(START_IN_TRAY_ARGS) + if (shouldShowWindow) { + const window = WindowManager.getMainWindow() + if (window) window.show() + } + } + @IpcMethod() openCacheFolder(_context: IpcContext): void { const dir = path.join(app.getPath("userData"), "cache") @@ -217,22 +226,6 @@ export class AppService extends IpcService { }) } - // getCacheLimit: t.procedure.action(async () => { - // return store.get(StoreKey.CacheSizeLimit) - // }), - - // clearCache: t.procedure.action(async () => { - - // }), - - // limitCacheSize: t.procedure.input().action(async ({ input }) => { - // logger.info("set limitCacheSize", input) - // if (input === 0) { - // store.delete(StoreKey.CacheSizeLimit) - // } else { - // store.set(StoreKey.CacheSizeLimit, input) - // } - // }), @IpcMethod() limitCacheSize(_context: IpcContext, input: number): void { if (input === 0) { diff --git a/apps/desktop/layer/main/src/ipc/services/auth.ts b/apps/desktop/layer/main/src/ipc/services/auth.ts index 5e4ec9380..ec4b27790 100644 --- a/apps/desktop/layer/main/src/ipc/services/auth.ts +++ b/apps/desktop/layer/main/src/ipc/services/auth.ts @@ -1,11 +1,10 @@ +import type { IpcContext } from "electron-ipc-decorator" +import { IpcMethod, IpcService } from "electron-ipc-decorator" + import { deleteNotificationsToken, updateNotificationsToken } from "../../lib/user" -import type { IpcContext } from "../base" -import { IpcMethod, IpcService } from "../base" export class AuthService extends IpcService { - constructor() { - super("auth") - } + static override readonly groupName = "auth" @IpcMethod() async sessionChanged(_context: IpcContext): Promise { diff --git a/apps/desktop/layer/main/src/ipc/services/debug.ts b/apps/desktop/layer/main/src/ipc/services/debug.ts index 42ef0436b..028d61fc4 100644 --- a/apps/desktop/layer/main/src/ipc/services/debug.ts +++ b/apps/desktop/layer/main/src/ipc/services/debug.ts @@ -1,5 +1,5 @@ -import type { IpcContext } from "../base" -import { IpcMethod, IpcService } from "../base" +import type { IpcContext } from "electron-ipc-decorator" +import { IpcMethod, IpcService } from "electron-ipc-decorator" interface InspectElementInput { x: number @@ -7,9 +7,7 @@ interface InspectElementInput { } export class DebugService extends IpcService { - constructor() { - super("debug") - } + static override readonly groupName = "debug" @IpcMethod() inspectElement(context: IpcContext, input: InspectElementInput): void { diff --git a/apps/desktop/layer/main/src/ipc/services/dock.ts b/apps/desktop/layer/main/src/ipc/services/dock.ts index 05e764eb5..1ed1ccafd 100644 --- a/apps/desktop/layer/main/src/ipc/services/dock.ts +++ b/apps/desktop/layer/main/src/ipc/services/dock.ts @@ -1,8 +1,9 @@ +import type { IpcContext } from "electron-ipc-decorator" +import { IpcMethod, IpcService } from "electron-ipc-decorator" + import { UNREAD_BACKGROUND_POLLING_INTERVAL } from "../../constants/app" import { apiClient } from "../../lib/api-client" import { setDockCount } from "../../lib/dock" -import type { IpcContext } from "../base" -import { IpcMethod, IpcService } from "../base" class PollingManager { private abortController: AbortController | null = null @@ -58,9 +59,7 @@ class PollingManager { export class DockService extends IpcService { private unreadPollingManager = new PollingManager() - constructor() { - super("dock") - } + static override readonly groupName = "dock" @IpcMethod() async pollingUpdateUnreadCount(): Promise { @@ -77,7 +76,8 @@ export class DockService extends IpcService { @IpcMethod() async updateUnreadCount(): Promise { - const res = await apiClient.reads["total-count"].$get() + const res = await apiClient.reads.getTotalCount() + setDockCount(res.data.count) } diff --git a/apps/desktop/layer/main/src/ipc/services/integration.ts b/apps/desktop/layer/main/src/ipc/services/integration.ts index 80288d4b5..035fb9035 100644 --- a/apps/desktop/layer/main/src/ipc/services/integration.ts +++ b/apps/desktop/layer/main/src/ipc/services/integration.ts @@ -2,14 +2,13 @@ import { existsSync } from "node:fs" import fsp from "node:fs/promises" import { shell } from "electron" +import type { IpcContext } from "electron-ipc-decorator" +import { IpcMethod, IpcService } from "electron-ipc-decorator" import path from "pathe" import { store } from "~/lib/store" import { logger } from "~/logger" -import type { IpcContext } from "../base" -import { IpcMethod, IpcService } from "../base" - // Taken from https://github.com/rollup/rollup/blob/4f69d33af3b2ec9320c43c9e6c65ea23a02bdde3/src/utils/sanitizeFileName.ts // https://datatracker.ietf.org/doc/html/rfc2396 // eslint-disable-next-line no-control-regex @@ -55,9 +54,7 @@ interface CustomFetchInput { } export class IntegrationService extends IpcService { - constructor() { - super("integration") - } + static override readonly groupName = "integration" @IpcMethod() async saveToObsidian( diff --git a/apps/desktop/layer/main/src/ipc/services/menu.ts b/apps/desktop/layer/main/src/ipc/services/menu.ts index aadcfd1b5..9a01c7c2f 100644 --- a/apps/desktop/layer/main/src/ipc/services/menu.ts +++ b/apps/desktop/layer/main/src/ipc/services/menu.ts @@ -1,8 +1,7 @@ import type { MenuItemConstructorOptions, MessageBoxOptions } from "electron" import { dialog, Menu, ShareMenu } from "electron" - -import type { IpcContext } from "../base" -import { IpcMethod, IpcService } from "../base" +import type { IpcContext } from "electron-ipc-decorator" +import { IpcMethod, IpcService } from "electron-ipc-decorator" type SerializableMenuItem = Omit & { submenu?: SerializableMenuItem[] @@ -19,9 +18,7 @@ interface ShowConfirmDialogInput { } export class MenuService extends IpcService { - constructor() { - super("menu") - } + static override readonly groupName = "menu" private normalizeMenuItems( items: SerializableMenuItem[], diff --git a/apps/desktop/layer/main/src/ipc/services/reader.ts b/apps/desktop/layer/main/src/ipc/services/reader.ts index df84b8841..3c25268d8 100644 --- a/apps/desktop/layer/main/src/ipc/services/reader.ts +++ b/apps/desktop/layer/main/src/ipc/services/reader.ts @@ -3,13 +3,13 @@ import fs from "node:fs" import { callWindowExpose } from "@follow/shared/bridge" import { readability } from "@follow-app/readability" import { app, BrowserWindow } from "electron" +import type { IpcContext } from "electron-ipc-decorator" +import { IpcMethod, IpcService } from "electron-ipc-decorator" import { MsEdgeTTS, OUTPUT_FORMAT } from "msedge-tts" import path from "pathe" import type { ModelResult } from "vscode-languagedetection" import { detectCodeStringLanguage } from "../../modules/language-detection" -import type { IpcContext } from "../base" -import { IpcMethod, IpcService } from "../base" const tts = new MsEdgeTTS() @@ -29,9 +29,7 @@ interface DetectCodeStringLanguageInput { } export class ReaderService extends IpcService { - constructor() { - super("reader") - } + static override readonly groupName = "reader" @IpcMethod() async readability(_context: IpcContext, input: ReadabilityInput) { diff --git a/apps/desktop/layer/main/src/ipc/services/setting.ts b/apps/desktop/layer/main/src/ipc/services/setting.ts index 312c96635..1e943a7b1 100644 --- a/apps/desktop/layer/main/src/ipc/services/setting.ts +++ b/apps/desktop/layer/main/src/ipc/services/setting.ts @@ -1,14 +1,14 @@ import { createRequire } from "node:module" import { app, nativeTheme } from "electron" +import type { IpcContext } from "electron-ipc-decorator" +import { IpcMethod, IpcService } from "electron-ipc-decorator" import { WindowManager } from "~/manager/window" import { setProxyConfig, updateProxy } from "../../lib/proxy" import { store } from "../../lib/store" import { getTrayConfig, setTrayConfig } from "../../lib/tray" -import type { IpcContext } from "../base" -import { IpcMethod, IpcService } from "../base" const require = createRequire(import.meta.url) @@ -20,9 +20,7 @@ interface SetLoginItemSettingsInput { } export class SettingService extends IpcService { - constructor() { - super("setting") - } + static override readonly groupName = "setting" @IpcMethod() getLoginItemSettings(_context: IpcContext): Electron.LoginItemSettings { diff --git a/apps/desktop/layer/main/src/lib/api-client.ts b/apps/desktop/layer/main/src/lib/api-client.ts index f52514d03..cc566ccac 100644 --- a/apps/desktop/layer/main/src/lib/api-client.ts +++ b/apps/desktop/layer/main/src/lib/api-client.ts @@ -1,49 +1,80 @@ -import type { AppType } from "@follow/shared" import { env } from "@follow/shared/env.desktop" import { createDesktopAPIHeaders } from "@follow/utils/headers" +import { FollowClient } from "@follow-app/client-sdk" import PKG from "@pkg" -import { hc } from "hono/client" -import { ofetch } from "ofetch" import { BETTER_AUTH_COOKIE_NAME_SESSION_TOKEN } from "~/constants/app" import { WindowManager } from "~/manager/window" import { logger } from "../logger" -const abortController = new AbortController() -const apiFetch = ofetch.create({ - baseURL: env.VITE_API_URL, +export const followClient = new FollowClient({ credentials: "include", - signal: abortController.signal, - retry: false, - cache: "no-store", - onRequest({ request }) { - logger.info(`API Request: ${request.toString()}`) - }, - onRequestError(context) { - if (context.error.name === "AbortError") { - return - } - }, + timeout: 10000, + + baseURL: env.VITE_API_URL, + fetch: async (input, options = {}) => + fetch(input.toString(), { + ...options, + cache: "no-store", + }), }) -export const apiClient = hc("", { - fetch: async (input, options = {}) => apiFetch(input.toString(), options), - async headers() { - const window = WindowManager.getMainWindow() - const cookies = await window?.webContents.session.cookies.get({ - domain: new URL(env.VITE_API_URL).hostname, - }) - const sessionCookie = cookies?.find((cookie) => - cookie.name.includes(BETTER_AUTH_COOKIE_NAME_SESSION_TOKEN), - ) - const headerCookie = sessionCookie ? `${sessionCookie.name}=${sessionCookie.value}` : "" - const userAgent = window?.webContents.getUserAgent() || `Folo/${PKG.version}` +export const followApi = followClient.api - return { - ...createDesktopAPIHeaders({ version: PKG.version }), - Cookie: headerCookie, - "User-Agent": userAgent, - } - }, +followClient.addRequestInterceptor(async (ctx) => { + const { options } = ctx + const header = options.headers || {} + + const apiHeader = createDesktopAPIHeaders({ version: PKG.version }) + + // Get cookies for authentication + const window = WindowManager.getMainWindow() + const cookies = await window?.webContents.session.cookies.get({ + domain: new URL(env.VITE_API_URL).hostname, + }) + const sessionCookie = cookies?.find((cookie) => + cookie.name.includes(BETTER_AUTH_COOKIE_NAME_SESSION_TOKEN), + ) + const headerCookie = sessionCookie ? `${sessionCookie.name}=${sessionCookie.value}` : "" + const userAgent = window?.webContents.getUserAgent() || `Folo/${PKG.version}` + + options.headers = { + ...header, + ...apiHeader, + Cookie: headerCookie, + "User-Agent": userAgent, + } + return ctx }) + +followClient.addResponseInterceptor(({ response }) => { + logger.info(`API Response: ${response.status} ${response.statusText}`) + return response +}) + +followClient.addErrorInterceptor(async ({ error, response }) => { + if (!response) { + logger.error("API Request failed - no response", error) + return error + } + + logger.error(`API Request failed: ${response.status} ${response.statusText}`, error) + + // Handle specific error cases if needed in main process + if (response.status === 401) { + logger.warn("Authentication failed in main process") + } + + try { + const json = await response.clone().json() + logger.error("API Error details:", json) + } catch { + // ignore JSON parsing errors + } + + return error +}) + +// Legacy export for compatibility +export const apiClient = followApi diff --git a/apps/desktop/layer/main/src/lib/user.ts b/apps/desktop/layer/main/src/lib/user.ts index 0fb03370f..dd6a77161 100644 --- a/apps/desktop/layer/main/src/lib/user.ts +++ b/apps/desktop/layer/main/src/lib/user.ts @@ -21,11 +21,9 @@ export const updateNotificationsToken = async (newCredentials?: Credentials) => const credentials = newCredentials || store.get("notifications-credentials") if (credentials?.fcm?.token) { try { - await apiClient.messaging.$post({ - json: { - token: credentials.fcm.token, - channel: notificationChannel, - }, + await apiClient.messaging.createToken({ + token: credentials.fcm.token, + channel: notificationChannel, }) logger.info("updateNotificationsToken success: ", credentials.fcm.token) } catch (error) { @@ -35,9 +33,7 @@ export const updateNotificationsToken = async (newCredentials?: Credentials) => } export const deleteNotificationsToken = async () => { - await apiClient.messaging.$delete({ - json: { - channel: notificationChannel, - }, + await apiClient.messaging.deleteToken({ + channel: notificationChannel, }) } diff --git a/apps/desktop/layer/main/src/manager/window.ts b/apps/desktop/layer/main/src/manager/window.ts index e214364e8..d5d1530a0 100644 --- a/apps/desktop/layer/main/src/manager/window.ts +++ b/apps/desktop/layer/main/src/manager/window.ts @@ -5,11 +5,10 @@ import { LEGACY_APP_PROTOCOL } from "@follow/shared" import { callWindowExpose, WindowState } from "@follow/shared/bridge" import { APP_PROTOCOL, DEV } from "@follow/shared/constants" import type { BrowserWindowConstructorOptions } from "electron" -import { app, BrowserWindow, screen, shell } from "electron" +import { BrowserWindow, screen, shell } from "electron" import type { Event } from "electron/main" import path from "pathe" -import { START_IN_TRAY_ARGS } from "~/constants/app" import { isMacOS, isWindows, isWindows11 } from "~/env" import { filePathToAppUrl, getIconPath } from "~/helper" import { t } from "~/lib/i18n" @@ -83,12 +82,6 @@ class WindowManagerStatic { refreshBound(window, this.config.refreshBoundDelay) }) - window.on("ready-to-show", () => { - const shouldShowWindow = - !app.getLoginItemSettings().wasOpenedAsHidden && !process.argv.includes(START_IN_TRAY_ARGS) - if (shouldShowWindow) window.show() - }) - window.webContents.setWindowOpenHandler((details) => { shell.openExternal(details.url) return { action: "deny" } diff --git a/apps/desktop/layer/renderer/index.html b/apps/desktop/layer/renderer/index.html index 717d21b2c..5ccea93b4 100644 --- a/apps/desktop/layer/renderer/index.html +++ b/apps/desktop/layer/renderer/index.html @@ -17,17 +17,101 @@ - Folo + Folo - AI-Driven RSS Reader | Follow Everything + + + + + + + + + + + + + - + + - + + + + - + + + + + + + +