Merge pull request #4364 from RSSNext/release/mobile/0.2.6

release(mobile): Release v0.2.6
This commit is contained in:
Innei
2025-08-24 23:16:58 +08:00
committed by GitHub
304 changed files with 9542 additions and 3605 deletions
+5 -1
View File
@@ -4,7 +4,7 @@ inputs:
xcode-version:
description: "Xcode version to use"
required: false
default: "16.2.0"
default: "16.4.0"
runs:
using: "composite"
@@ -12,3 +12,7 @@ runs:
- uses: maxim-lobanov/setup-xcode@v1
with:
xcode-version: ${{ inputs.xcode-version }}
- name: Download iOS Platform
run: xcodebuild -downloadPlatform iOS
shell: bash
+1 -1
View File
@@ -1 +1 @@
Before you start, you need to read and follow the rules in @claude.md
Before you start, you need to read and follow the rules in @../CLAUDE.md
+4 -5
View File
@@ -33,7 +33,7 @@ jobs:
steps:
- name: 📦 Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: 📦 Setup pnpm
uses: pnpm/action-setup@v4
@@ -92,16 +92,15 @@ jobs:
id: version
uses: ./.github/actions/setup-version
with:
# We don't want to create a new release for mobile
type: "desktop"
type: "mobile"
- name: Create Release Draft
if: github.event.inputs.release == 'true'
uses: softprops/action-gh-release@v2
with:
name: v${{ steps.version.outputs.APP_VERSION }}
name: Mobile v${{ steps.version.outputs.APP_VERSION }}
draft: false
prerelease: true
tag_name: v${{ steps.version.outputs.APP_VERSION }}
tag_name: mobile/v${{ steps.version.outputs.APP_VERSION }}
# .aab cannot be installed directly on your Android Emulator or device.
files: ${{ github.workspace }}/build.apk
+5 -5
View File
@@ -56,13 +56,13 @@ jobs:
steps:
- name: Check out Git repository Fully
uses: actions/checkout@v4
uses: actions/checkout@v5
if: env.PROD == 'true'
with:
fetch-depth: 0
lfs: true
- name: Check out Git repository
uses: actions/checkout@v4
uses: actions/checkout@v5
if: env.PROD == 'false'
with:
fetch-depth: 1
@@ -222,7 +222,7 @@ jobs:
apps/desktop/out/make/**/latest.yml
retention-days: 90
- uses: signpath/github-action-submit-signing-request@v1.2
- uses: signpath/github-action-submit-signing-request@v1.3
continue-on-error: true
if: runner.os == 'windows' && env.RELEASE == 'true'
with:
@@ -297,10 +297,10 @@ jobs:
if: env.RELEASE == 'true'
uses: softprops/action-gh-release@v2
with:
name: v${{ steps.version.outputs.APP_VERSION }}
name: Desktop v${{ steps.version.outputs.APP_VERSION }}
draft: false
prerelease: true
tag_name: v${{ steps.version.outputs.APP_VERSION }}
tag_name: desktop/v${{ steps.version.outputs.APP_VERSION }}
files: |
apps/desktop/out/make/**/Folo-*.dmg
apps/desktop/out/make/**/Folo-*.zip
+3 -3
View File
@@ -40,7 +40,7 @@ jobs:
steps:
- name: 📦 Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: 📱 Setup EAS
uses: expo/expo-github-action@v8
@@ -77,7 +77,7 @@ jobs:
steps:
- name: 📦 Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: 🔧 Setup Xcode
uses: ./.github/actions/setup-xcode
@@ -121,7 +121,7 @@ jobs:
steps:
- name: 📦 Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: 🔧 Setup Xcode
uses: ./.github/actions/setup-xcode
+6 -3
View File
@@ -1,4 +1,4 @@
name: Build iOS
name: 🍎 Build iOS
on:
push:
@@ -47,7 +47,7 @@ jobs:
steps:
- name: 📦 Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: 📱 Setup EAS
uses: expo/expo-github-action@v8
@@ -89,7 +89,10 @@ jobs:
steps:
- name: 📦 Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: 🔧 Setup Xcode
uses: ./.github/actions/setup-xcode
- name: 📦 Setup pnpm
uses: pnpm/action-setup@v4
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
node-version: [lts/*]
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
lfs: true
- name: Cache turbo build setup
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 1
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 1
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Parse issue form
uses: stefanbuck/github-issue-parser@v3
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
node-version: [lts/*]
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
lfs: true
- name: Cache turbo build setup
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0
+75 -40
View File
@@ -4,55 +4,90 @@ on:
push:
branches:
- main
env:
NODE_OPTIONS: --max-old-space-size=8192
jobs:
create_tag:
name: Create Release Tag
runs-on: ubuntu-latest
outputs:
tag_version: ${{ env.tag_version }}
platform: ${{ env.platform }}
version: ${{ env.version }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Use Node.js
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
node-version: lts/*
- name: Extract SemVer using Node.js
id: extract_semver
- name: Make script executable
run: |
node -e '
const execSync = require("child_process").execSync;
const fs = require("fs");
const commitMessage = execSync("git log -1 --pretty=%B").toString("utf-8");
const semverRegex = /release\(desktop\): Release (v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-.]+)?)/;
const match = commitMessage.match(semverRegex);
if (match) {
fs.appendFileSync(process.env.GITHUB_ENV, `tag_version=${match[1]}\n`);
} else {
console.log("No SemVer found in commit body.");
process.exit(0);
}
'
chmod +x .github/scripts/extract-release-info.mjs
- name: Create a new tag
if: ${{ env.tag_version }}
run: |
git tag ${{ env.tag_version }}
git push origin ${{ env.tag_version }}
- name: Trigger Build Desktop Workflow
if: ${{ env.tag_version }}
run: |
curl -X POST \
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
-H "Accept: application/vnd.github+json" \
https://api.github.com/repos/${{ github.repository }}/actions/workflows/build-desktop.yml/dispatches \
-d '{"ref":"main", "inputs": {"tag_version": "true"}}'
- name: Extract release information
id: extract_info
run: .github/scripts/extract-release-info.mjs
continue-on-error: false
- name: Trigger Build Android Workflow
if: ${{ env.tag_version }}
- name: Validate git configuration
if: env.tag_version
run: |
curl -X POST \
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
-H "Accept: application/vnd.github+json" \
https://api.github.com/repos/${{ github.repository }}/actions/workflows/build-android.yml/dispatches \
-d '{"ref":"main", "inputs": {"release": "true"}}'
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
- name: Create and push tag
if: env.tag_version
run: |
echo "Creating tag: ${{ env.tag_version }}"
if git rev-parse "${{ env.tag_version }}" >/dev/null 2>&1; then
echo "Tag ${{ env.tag_version }} already exists, skipping creation"
exit 0
fi
git tag "${{ env.tag_version }}"
git push origin "${{ env.tag_version }}"
echo "Successfully created and pushed tag: ${{ env.tag_version }}"
trigger_builds:
name: Trigger Platform Builds
needs: create_tag
if: needs.create_tag.outputs.tag_version
runs-on: ubuntu-latest
steps:
- name: Trigger Desktop Build
if: needs.create_tag.outputs.platform == 'desktop'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const response = await github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'build-desktop.yml',
ref: 'main',
inputs: {
tag_version: 'true'
}
});
console.log('Desktop build triggered successfully');
- name: Trigger Mobile Build
if: needs.create_tag.outputs.platform == 'mobile'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const response = await github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'build-android.yml',
ref: 'main',
inputs: {
release: 'true'
}
});
console.log('Mobile build triggered successfully');
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: lizheming/github-translate-action@c55aac477e98562d4faed9f77c54ab8306ae6ebf
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+44 -93
View File
@@ -10,18 +10,49 @@ Follow (Folo) is a modern RSS aggregator and content management platform with mu
### Applications (`apps/`)
- **`apps/desktop/`** - Electron desktop application with main and renderer processes
- **`apps/desktop/`** - Electron desktop application
- `layer/main/` - Electron main process
- `layer/renderer/` - Vite + React renderer (primary web app)
- `plugins/` - Custom Electron plugins
- `resources/` - Application resources and assets
- **`apps/mobile/`** - React Native mobile app for iOS and Android
- **`apps/ssr/`** - Server-side rendered web application
- **`apps/mobile/web-app/`** - HTML renderer for mobile web views
- `src/` - React Native source code
- `native/` - Native module implementations
- `web-app/` - HTML renderer for mobile web views
- `android/` - Android-specific configuration
- `ios/` - iOS-specific configuration
- **`apps/ssr/`** - Server-side rendered web application (minimal, for external sharing)
### Packages (`packages/`)
- **`packages/internal/`** - Internal shared packages (components, database, hooks, store, etc.)
- **`packages/configs/`** - Shared configuration files (Tailwind, TypeScript)
- **`packages/utils/`** - Utility functions and helpers
- **`packages/readability/`** - Content readability parsing
- **`packages/vite-plugin-route-builder/`** - Custom Vite plugin for route generation
- **`packages/internal/`** - Core shared packages
- `atoms/` - Jotai atomic state definitions
- `components/` - Shared UI components
- `constants/` - Application constants
- `database/` - Drizzle ORM database layer
- `hooks/` - Shared React hooks
- `models/` - Data models and schemas
- `shared/` - Cross-platform shared utilities
- `store/` - Zustand stores
- `types/` - TypeScript type definitions
- `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
- **`packages/readability/`** - Content readability parsing and extraction
- **`packages/changelog-cli/`** - CLI tool for changelog generation
### Supporting Directories
- **`scripts/`** - Build and development scripts
- **`plugins/`** - Custom development plugins
- **`locales/`** - Internationalization files organized by feature
- **`icons/`** - Icon assets (MingCute and custom icons)
- **`.github/`** - GitHub workflows, issue templates, and CI/CD
- **`patches/`** - Package patches for dependency modifications
## Essential Commands
@@ -69,19 +100,6 @@ pnpm run typecheck
pnpm run test
```
### Package Management
```bash
# Build shared packages
pnpm run build:packages
# Generate i18n templates
pnpm run generator:i18n-template
# Sync icons from SVG to React Native
pnpm run icons:sync
```
## Architecture Guidelines
### Multi-Platform Architecture
@@ -102,45 +120,9 @@ pnpm run icons:sync
- **Tailwind CSS** for styling across all platforms
- Platform-specific Tailwind configs in each app
- Shared Tailwind utilities in `packages/configs/tailwindcss/`
- **UI Design Style**: Follow Vercel and Linear SaaS UI aesthetics - clean, modern, minimal design with subtle shadows, rounded corners, and excellent typography
#### UIKit Colors for Desktop Components
For desktop components (`apps/desktop/**/*`) and shared UI components (`packages/internal/components/**/*`), use Apple UIKit color system with Tailwind classes. **Important**: Always use the correct Tailwind prefix for each color category:
**System Colors**: `text-red`, `bg-red`, `border-red` (same for `orange`, `yellow`, `green`, `mint`, `teal`, `cyan`, `blue`, `indigo`, `purple`, `pink`, `brown`, `gray`)
**Fill Colors**:
- Background: `bg-fill`, `bg-fill-secondary`, `bg-fill-tertiary`, `bg-fill-quaternary`, `bg-fill-quinary`, `bg-fill-vibrant`, `bg-fill-vibrant-secondary`, `bg-fill-vibrant-tertiary`, `bg-fill-vibrant-quaternary`, `bg-fill-vibrant-quinary`
- Border: `border-fill`, `border-fill-secondary`, etc.
**Text Colors**: `text-text`, `text-text-secondary`, `text-text-tertiary`, `text-text-quaternary`, `text-text-quinary`, `text-text-vibrant`, `text-text-vibrant-secondary`, `text-text-vibrant-tertiary`, `text-text-vibrant-quaternary`, `text-text-vibrant-quinary`
**Material Colors**: `bg-material-ultra-thick`, `bg-material-thick`, `bg-material-medium`, `bg-material-thin`, `bg-material-ultra-thin`, `bg-material-opaque`
**Control Colors**: `bg-control-enabled`, `bg-control-disabled`
**Interface Colors**: `bg-menu`, `bg-popover`, `bg-titlebar`, `bg-sidebar`, `bg-selection-focused`, `bg-selection-focused-fill`, `bg-selection-unfocused`, `bg-selection-unfocused-fill`, `bg-header-view`, `bg-tooltip`, `bg-under-window-background`
These colors automatically adapt to light/dark mode following Apple's design system. Remember to use the appropriate prefix (`text-`, `bg-`, `border-`) based on the CSS property you're styling.
#### Icons
For icon usage, prioritize the MingCute icon library with the `i-mgc-` prefix. Icons are available in the format `i-mgc-[icon-name]-[style]` where style can be `re` (regular), `fi` (filled), etc.
**Important**: Always try to find an appropriate icon with the `i-mgc-` prefix first. Only use the `i-mingcute-` prefix as a fallback when no suitable `i-mgc-` icon exists.
Examples:
- Preferred: `i-mgc-copy-cute-re`, `i-mgc-external-link-cute-re`
- Fallback only: `i-mingcute-copy-line` (only if no mgc equivalent exists)
### Database
- **Drizzle ORM** with SQLite for local data storage
- Platform-specific database implementations in `packages/internal/database/`
- Migration system with versioned SQL files
For desktop, see @apps/desktop/CLAUDE.md
For mobile, see @apps/mobile/CLAUDE.md
### Internationalization
@@ -154,6 +136,7 @@ Examples:
2. **Use flat keys only** - Use `.` notation for separation, no nested objects
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/`
Example:
@@ -166,25 +149,6 @@ Example:
}
```
## Development Setup Notes
### Prerequisites
- Enable Corepack: `corepack enable && corepack prepare`
- For mobile development: macOS with Xcode required
### Environment Setup
- Copy `.env.example` to `.env` in relevant app directories
- For development, use `VITE_API_URL=https://api.follow.is`
- Browser development uses `https://app.folo.is/__debug_proxy` for API access
### Mobile Development
- iOS development requires Xcode and iOS simulator
- Native module development in `apps/mobile/native/`
- Use `pnpm expo prebuild --clean` for clean builds
## Code Organization Patterns
### Import Conventions
@@ -198,26 +162,13 @@ Example:
- Shared UI components in `packages/internal/components/`
- Platform-specific components in respective app directories
- Use TypeScript interfaces for component props
- **Detailed guidelines**: See @packages/internal/CLAUDE.md for component development patterns
### Error Handling
- Custom error parsing utilities in `packages/internal/utils/`
- Sentry integration for error reporting across platforms
## Build and Deployment
### Build Outputs
- Desktop: `apps/desktop/out/` for packaged applications
- Web: `apps/desktop/out/web/` for static web assets
- Mobile: Platform-specific build directories
### Turbo Configuration
- Build orchestration via `turbo.json`
- Dependency-aware builds with output caching
- Parallel execution for independent packages
## Testing Strategy
- Vitest for unit testing across packages
@@ -348,7 +299,7 @@ Claude Code has access to specialized agents for different development tasks. **
## Agent Usage Notes
- **Primary web app is at `@apps/desktop/layer/renderer`** - A Vite + React SPA, not full Electron features
- **Primary web app is at `apps/desktop/layer/renderer`** - A Vite + React SPA, not full Electron features
- **SSR app is minimal** - Only for external sharing pages, not main development focus
- **Mobile app** - React Native with Expo for iOS/Android
- **Always use Task tool with appropriate agent** - Don't implement complex features directly, delegate to specialized agents
+113
View File
@@ -0,0 +1,113 @@
# Desktop App Development Guide
This file provides specific guidance for developing the Electron desktop application.
## Architecture
- **Main Process** (`layer/main/`) - Electron main process handling system integration
- **Renderer Process** (`layer/renderer/`) - Vite + React renderer (primary web app)
The renderer is the **primary web application** - a Vite + React SPA that can run both in Electron and as a standalone web app.
## UI Style
- **UI Design Style**: Follow Vercel and Linear SaaS UI aesthetics - clean, modern, minimal design with subtle shadows, rounded corners, and excellent typography
- **Tailwind CSS** for styling across all platforms
- Platform-specific Tailwind configs in each app
## Development Commands
```bash
# Recommended: Browser development (faster)
pnpm run dev:web
# Full Electron development
pnpm run dev:electron
# Build web version
pnpm run build:web
```
## UIKit Colors for Desktop Components
For desktop components (`apps/desktop/**/*`) and shared UI components (`packages/internal/components/**/*`), use Apple UIKit color system with Tailwind classes. **Important**: Always use the correct Tailwind prefix for each color category:
**System Colors**: `text-red`, `bg-red`, `border-red` (same for `orange`, `yellow`, `green`, `mint`, `teal`, `cyan`, `blue`, `indigo`, `purple`, `pink`, `brown`, `gray`)
**Fill Colors**:
- Background: `bg-fill`, `bg-fill-secondary`, `bg-fill-tertiary`, `bg-fill-quaternary`, `bg-fill-quinary`, `bg-fill-vibrant`, `bg-fill-vibrant-secondary`, `bg-fill-vibrant-tertiary`, `bg-fill-vibrant-quaternary`, `bg-fill-vibrant-quinary`
- Border: `border-fill`, `border-fill-secondary`, etc.
**Text Colors**: `text-text`, `text-text-secondary`, `text-text-tertiary`, `text-text-quaternary`, `text-text-quinary`, `text-text-vibrant`, `text-text-vibrant-secondary`, `text-text-vibrant-tertiary`, `text-text-vibrant-quaternary`, `text-text-vibrant-quinary`
**Material Colors**: `bg-material-ultra-thick`, `bg-material-thick`, `bg-material-medium`, `bg-material-thin`, `bg-material-ultra-thin`, `bg-material-opaque`
**Control Colors**: `bg-control-enabled`, `bg-control-disabled`
**Interface Colors**: `bg-menu`, `bg-popover`, `bg-titlebar`, `bg-sidebar`, `bg-selection-focused`, `bg-selection-focused-fill`, `bg-selection-unfocused`, `bg-selection-unfocused-fill`, `bg-header-view`, `bg-tooltip`, `bg-under-window-background`
These colors automatically adapt to light/dark mode following Apple's design system. Remember to use the appropriate prefix (`text-`, `bg-`, `border-`) based on the CSS property you're styling.
## Icons
For icon usage, prioritize the MingCute icon library with the `i-mgc-` prefix. Icons are available in the format `i-mgc-[icon-name]-[style]` where style can be `re` (regular), `fi` (filled), etc.
**Important**: Always try to find an appropriate icon with the `i-mgc-` prefix first. Only use the `i-mingcute-` prefix as a fallback when no suitable `i-mgc-` icon exists.
Examples:
- Preferred: `i-mgc-copy-cute-re`, `i-mgc-external-link-cute-re`
- Fallback only: `i-mingcute-copy-line` (only if no mgc equivalent exists)
## Using Framer Motion
- **LazyMotion Integration**: Project uses Framer Motion with LazyMotion for optimized bundle size
- **Usage Rule**: Always use `m.` instead of `motion.` when creating animated components
- **Import**: `import { m } from 'motion/react'`
- **Examples**: `m.div`, `m.button`, `m.span` (not `motion.div`, `motion.button`, etc.)
- **Benefits**: Reduces bundle size while maintaining all Framer Motion functionality
- **Prefer Spring Presets**: Use predefined spring animations from `@follow/components/constants/spring.js`
- **Available Presets Constants**: `Spring.presets.smooth`, `Spring.presets.snappy`, `Spring.presets.bouncy` (extracted from Apple's spring parameters)
- **Usage Example**: `transition={Spring.presets.smooth}` or `transition={Spring.snappy(0.3, 0.1)}`
- **Customization**: All presets accept optional `duration` and `extraBounce` parameters
## Reusable UI Components
When building UI components, follow this hierarchy:
1. **Check Existing Components First**: Look in `apps/desktop/layer/renderer/src/modules/renderer/components` for app-specific components
2. **Create Reusable Components**: If the component doesn't exist and is **generic/reusable** (not tied to specific app business logic), create it in `packages/internal/components`
### Guidelines for Reusable Components (`packages/internal/components`)
- **Purpose**: Components should be generic and reusable across different apps/contexts
- **No Business Logic**: Avoid coupling with specific app business logic, APIs, or state management
- **Follow All Style Rules**: Must adhere to UIKit colors, MingCute icons (`i-mgc-` prefix), and Framer Motion (`m.` prefix) guidelines
- **Export Pattern**: Export components from appropriate index files for clean imports
- **TypeScript**: Use proper TypeScript interfaces for props and maintain type safety
**Example Structure**:
```
packages/internal/components/
├── ui/ # Basic UI primitives (Button, Input, Modal)
├── layout/ # Layout components (Grid, Stack, Container)
├── feedback/ # User feedback (Toast, Loading, Alert)
└── index.ts # Main exports
```
**Import Examples**:
```tsx
// Correct - from shared components
import { Button, Modal } from "@follow/components"
// App-specific components stay in name/components
import { FeedList } from "~/modules/name/components"
```
## Build Outputs
- Desktop: `apps/desktop/out/` for packaged applications
- Web: `apps/desktop/out/web/` for static web assets
+11 -5
View File
@@ -22,9 +22,13 @@ import { loadDynamicRenderEntry } from "~/updater/hot-updater"
const __dirname = fileURLToPath(new URL(".", import.meta.url))
class WindowManagerStatic {
static readonly mainWindowDefaultSize = {
height: 900,
width: 1600,
static get mainWindowDefaultSize() {
const primaryDisplay = screen.getPrimaryDisplay()
const { workAreaSize } = primaryDisplay
return {
height: workAreaSize.height,
width: workAreaSize.width,
}
}
// Window configuration properties for better DX
@@ -346,8 +350,10 @@ class WindowManagerStatic {
const defaultSize = WindowManagerStatic.mainWindowDefaultSize
const width = Math.min(windowState?.width || defaultSize.width, maxWidth)
const height = Math.min(windowState?.height || defaultSize.height, maxHeight)
const width = windowState?.width ? Math.min(windowState.width, maxWidth) : defaultSize.width
const height = windowState?.height
? Math.min(windowState.height, maxHeight)
: defaultSize.height
const ensureInBounds = (value: number, min: number, max: number): number => {
return Math.max(min, Math.min(value, max))
+1 -1
View File
@@ -118,7 +118,7 @@
"@follow/models": "workspace:*",
"@follow/types": "workspace:*",
"@follow/utils": "workspace:*",
"@folo-services/ai-tools": "0.2.19",
"@folo-services/ai-tools": "0.2.20",
"@types/node": "24.0.10",
"@vite-pwa/assets-generator": "1.0.0",
"fake-indexeddb": "6.0.1",
@@ -2,6 +2,14 @@ import { createAtomHooks } from "@follow/utils/jotai"
import { getStorageNS } from "@follow/utils/ns"
import { atomWithStorage } from "jotai/utils"
export const [, , useDebugFeatureValue, getDebugFeatureValue, ,] = createAtomHooks(
atomWithStorage(getStorageNS("debug-feature"), {}),
)
// Shape: { __override?: boolean, [featureKey: string]: boolean }
export const [
,
,
useDebugFeatureValue,
useSetDebugFeatureValue,
getDebugFeatureValue,
setDebugFeatureValue,
] = createAtomHooks(atomWithStorage<Record<string, unknown>>(getStorageNS("debug-feature"), {}))
export { useDebugFeatureValue as useDebugFeatures }
@@ -1,11 +1,19 @@
import { getStorageNS } from "@follow/utils/ns"
import type { ExtractResponseData, GetStatusConfigsResponse } from "@follow-app/client-sdk"
import PKG from "@pkg"
import { atom } from "jotai"
import { atomWithStorage } from "jotai/utils"
import { createAtomHooks } from "~/lib/jotai"
export const [, , useServerConfigs, , getServerConfigs, setServerConfigs] = createAtomHooks(
atom<Nullable<ExtractResponseData<GetStatusConfigsResponse>>>(null),
atomWithStorage<Nullable<ExtractResponseData<GetStatusConfigsResponse>>>(
getStorageNS("server-configs"),
null,
undefined,
{
getOnInit: true,
},
),
)
export const useIsInMASReview = () => {
@@ -1,27 +1,114 @@
import { createSettingAtom } from "@follow/atoms/helper/setting.js"
import { defaultAISettings } from "@follow/shared/settings/defaults"
import type { AISettings } from "@follow/shared/settings/interface"
import type { AISettings, MCPService } from "@follow/shared/settings/interface"
import { jotaiStore } from "@follow/utils"
import { clamp } from "es-toolkit"
import { atom, useAtomValue } from "jotai"
export const createDefaultSettings = (): AISettings => defaultAISettings
export interface WebAISettings extends AISettings {
panelStyle: AIChatPanelStyle
}
export const createDefaultSettings = (): WebAISettings => ({
...defaultAISettings,
panelStyle: AIChatPanelStyle.Fixed,
})
export const {
useSettingKey: useAISettingKey,
useSettingSelector: useAISettingSelector,
setSetting: setAISetting,
clearSettings: clearAISettings,
initializeDefaultSettings: initializeDefaultAISettings,
initializeDefaultSettings,
getSettings: getAISettings,
useSettingValue: useAISettingValue,
settingAtom: __aiSettingAtom,
} = createSettingAtom("ai", createDefaultSettings)
export const aiServerSyncWhiteListKeys = []
// Local Setting for ai
const aiChatPinnedAtom = atom<boolean>(false)
export const useAIChatPinned = () => useAtomValue(aiChatPinnedAtom)
export const setAIChatPinned = (pinned: boolean) => {
jotaiStore.set(aiChatPinnedAtom, pinned)
////////// AI Panel Style
export enum AIChatPanelStyle {
Fixed = "fixed",
Floating = "floating",
}
export const useAIChatPanelStyle = () => useAISettingKey("panelStyle")
export const setAIChatPanelStyle = (style: AIChatPanelStyle) => {
setAISetting("panelStyle", style)
}
export const getAIChatPanelStyle = () => getAISettings().panelStyle
// Floating panel state atoms
interface FloatingPanelState {
width: number
height: number
x: number
y: number
}
const DEFAULT_FLOATING_PANEL_WIDTH = 500
const DEFAULT_FLOATING_PANEL_HEIGHT = clamp(window.innerHeight * 0.9, 600, 1000)
const DEFAULT_FLOATING_PANEL_X = window.innerWidth - DEFAULT_FLOATING_PANEL_WIDTH - 20
const DEFAULT_FLOATING_PANEL_Y = window.innerHeight - DEFAULT_FLOATING_PANEL_HEIGHT - 20
const defaultFloatingPanelState: FloatingPanelState = {
width: DEFAULT_FLOATING_PANEL_WIDTH,
height: DEFAULT_FLOATING_PANEL_HEIGHT,
x: DEFAULT_FLOATING_PANEL_X,
y: DEFAULT_FLOATING_PANEL_Y,
}
const floatingPanelStateAtom = atom<FloatingPanelState>(defaultFloatingPanelState)
export const useFloatingPanelState = () => useAtomValue(floatingPanelStateAtom)
export const setFloatingPanelState = (state: Partial<FloatingPanelState>) => {
const currentState = jotaiStore.get(floatingPanelStateAtom)
jotaiStore.set(floatingPanelStateAtom, { ...currentState, ...state })
}
export const getFloatingPanelState = () => jotaiStore.get(floatingPanelStateAtom)
////////// AI Panel Visibility
const aiPanelVisibilityAtom = atom<boolean>(false)
export const useAIPanelVisibility = () => useAtomValue(aiPanelVisibilityAtom)
export const setAIPanelVisibility = (visibility: boolean) => {
jotaiStore.set(aiPanelVisibilityAtom, visibility)
}
export const getAIPanelVisibility = () => jotaiStore.get(aiPanelVisibilityAtom)
////////// MCP Services
export const useMCPEnabled = () => useAISettingKey("mcpEnabled")
export const setMCPEnabled = (enabled: boolean) => {
setAISetting("mcpEnabled", enabled)
}
export const useMCPServices = () => useAISettingKey("mcpServices")
export const addMCPService = (service: Omit<MCPService, "id">) => {
const services = getAISettings().mcpServices
const newService = {
...service,
id: Date.now().toString(),
}
setAISetting("mcpServices", [...services, newService])
return newService.id
}
export const updateMCPService = (id: string, updates: Partial<MCPService>) => {
const services = getAISettings().mcpServices
const updatedServices = services.map((service) =>
service.id === id ? { ...service, ...updates } : service,
)
setAISetting("mcpServices", updatedServices)
}
export const removeMCPService = (id: string) => {
const services = getAISettings().mcpServices
const filteredServices = services.filter((service) => service.id !== id)
setAISetting("mcpServices", filteredServices)
}
//// Enhance Init Ai Settings
export const initializeDefaultAISettings = () => {
initializeDefaultSettings()
if (getAISettings().panelStyle === AIChatPanelStyle.Fixed) setAIPanelVisibility(true)
}
export const getAIChatPinned = () => jotaiStore.get(aiChatPinnedAtom)
@@ -0,0 +1,120 @@
import { jotaiStore } from "@follow/utils"
import { atom } from "jotai"
import { useEffect } from "react"
const LCPEndAtom = atom(false)
/**
* To skip page transition when first load, improve LCP
*/
export const LCPEndDetector = () => {
useEffect(() => {
let hasEnded = false
const timeoutIds: Array<ReturnType<typeof setTimeout>> = []
const rafIds: number[] = []
const idleCallbackIds: number[] = []
const scheduleRaf = (cb: FrameRequestCallback) => {
if (typeof window !== "undefined" && window.requestAnimationFrame) {
const id = window.requestAnimationFrame(cb)
rafIds.push(id)
} else {
const id = setTimeout(() => cb(performance.now()), 16)
timeoutIds.push(id)
}
}
const markEnded = () => {
if (hasEnded) return
hasEnded = true
// Defer to ensure layout/paint and initial CSS transitions settle
scheduleRaf(() => {
scheduleRaf(() => {
// Prefer idle if available to avoid jank
const ric = (typeof window !== "undefined" && (window as any).requestIdleCallback) as
| ((cb: () => void, opts?: { timeout?: number }) => number)
| undefined
if (ric) {
const id = ric(() => jotaiStore.set(LCPEndAtom, true), {
timeout: 200,
}) as unknown as number
idleCallbackIds.push(id)
} else {
const id = setTimeout(() => jotaiStore.set(LCPEndAtom, true), 0)
timeoutIds.push(id)
}
})
})
}
// If PerformanceObserver for LCP is available, prefer it
const supportsPO = typeof PerformanceObserver !== "undefined"
let po: PerformanceObserver | undefined
const onHidden = () => markEnded()
const onVisibilityChange = () => {
if (document.visibilityState === "hidden") onHidden()
}
const onPageHide = onHidden
const onLoad = () => markEnded()
let safetyTimer: ReturnType<typeof setTimeout> | undefined
let fallbackEndTimer: ReturnType<typeof setTimeout> | undefined
if (supportsPO) {
try {
po = new PerformanceObserver((list) => {
const entries = list.getEntries()
if (entries && entries.length > 0) {
// Any LCP entry indicates a meaningful paint; we can mark end soon
markEnded()
}
})
// buffered: true ensures we get entries that occurred before observer creation
po.observe({ type: "largest-contentful-paint", buffered: true } as PerformanceObserverInit)
} catch {
// Ignore observer errors and rely on fallback
}
// When the page is hidden or unloaded, LCP is finalized
window.addEventListener("visibilitychange", onVisibilityChange, { once: true })
window.addEventListener("pagehide", onPageHide, { once: true })
window.addEventListener("load", onLoad, { once: true })
// Absolute safety net: if nothing fires, end after 3s
safetyTimer = setTimeout(() => markEnded(), 3000)
timeoutIds.push(safetyTimer)
} else {
// Ultimate fallback for environments without PO
fallbackEndTimer = setTimeout(() => {
jotaiStore.set(LCPEndAtom, true)
}, 2000)
timeoutIds.push(fallbackEndTimer)
}
return () => {
if (po) po.disconnect()
const caf = typeof window !== "undefined" && window.cancelAnimationFrame
if (caf) {
rafIds.forEach((id) => (window.cancelAnimationFrame as (h: number) => void)(id))
}
const cic = (typeof window !== "undefined" && (window as any).cancelIdleCallback) as
| ((id: number) => void)
| undefined
if (cic) idleCallbackIds.forEach((id) => cic(id))
timeoutIds.forEach((id) => clearTimeout(id))
if (safetyTimer) clearTimeout(safetyTimer)
if (fallbackEndTimer) clearTimeout(fallbackEndTimer)
window.removeEventListener("visibilitychange", onVisibilityChange)
window.removeEventListener("pagehide", onPageHide)
window.removeEventListener("load", onLoad)
}
}, [])
return null
}
// eslint-disable-next-line react-refresh/only-export-components
export const isLCPEnded = () => jotaiStore.get(LCPEndAtom)
@@ -4,15 +4,25 @@ import { createElement } from "react"
import { useReduceMotion } from "~/hooks/biz/useReduceMotion"
import { isLCPEnded } from "./LCPEndDetector"
type WithLCPOptimization<P> = P & { lcpOptimization?: boolean }
// Narrow exported proxy type so each motion component accepts `lcpOptimization`
export type MotionProxy = {
[K in keyof typeof M]: (typeof M)[K] extends React.ComponentType<infer P>
? React.ComponentType<WithLCPOptimization<P>>
: (typeof M)[K]
}
const cacheMap = new Map<string, any>()
export const m: typeof M = new Proxy(M, {
export const m: MotionProxy = new Proxy(M, {
get(target, p: string) {
const Component = target[p]
if (cacheMap.has(p)) {
return cacheMap.get(p)
}
const MotionComponent = ({ ref, ...props }) => {
const MotionComponent = ({ ref, lcpOptimization, ...props }) => {
const shouldReduceMotion = useReduceMotion()
const nextProps = { ...props }
if (shouldReduceMotion) {
@@ -33,6 +43,11 @@ export const m: typeof M = new Proxy(M, {
}
}
// Disable initial animation before hydration ends to optimize LCP
if (lcpOptimization && !isLCPEnded()) {
nextProps.initial = false
}
return createElement(Component, { ...nextProps, ref })
}
@@ -155,7 +155,7 @@ export const GlassButton: FC<GlassButtonProps> = ({
tapScale = 0.95,
size = "md",
theme = "auto",
variant = "glass",
variant = "flat",
}) => {
return (
<Tooltip>
@@ -2,7 +2,7 @@ import { ELECTRON_BUILD } from "@follow/shared/constants"
import { cn } from "@follow/utils/utils"
import { useIsomorphicLayoutEffect } from "foxact/use-isomorphic-layout-effect"
import type { FC } from "react"
import { useInsertionEffect, useMemo, useRef, useState } from "react"
import { memo, useInsertionEffect, useMemo, useRef, useState } from "react"
import type {
BundledLanguage,
BundledTheme,
@@ -155,6 +155,7 @@ export const ShikiHighLighter: FC<ShikiProps> = (props) => {
return <ShikiCode {...props} language={currentLanguage} codeTheme={codeTheme} />
}
export const MemoizedShikiCode = memo(ShikiHighLighter)
const ShikiCode: FC<
ShikiProps & {
codeTheme: string
@@ -377,7 +377,12 @@ export const AvatarUploadModal = ({
<div className="flex flex-col gap-4">
{!selectedImage ? (
<div className="aspect-square h-[400px] space-y-4">
<DropZone onDrop={handleFileSelect} className="size-full">
<DropZone
id="upload-avatar"
onDrop={handleFileSelect}
accept="image/*"
className="size-full"
>
<div className="flex flex-col items-center gap-2 p-8">
<i className="i-mgc-file-upload-cute-re text-text-secondary text-4xl" />
<div className="text-center">
@@ -121,6 +121,7 @@ const DropdownMenuItem = ({
active,
highlightColor = "accent",
shortcut,
checked,
...props
}: React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
@@ -128,6 +129,7 @@ const DropdownMenuItem = ({
active?: boolean
highlightColor?: "accent" | "gray"
shortcut?: string
checked?: boolean
} & { ref?: React.Ref<React.ElementRef<typeof DropdownMenuPrimitive.Item> | null> }) => (
<DropdownMenuPrimitive.Item
ref={ref}
@@ -161,6 +163,14 @@ const DropdownMenuItem = ({
</Kbd>
</>
)}
{checked && !shortcut && (
<>
<span className="ml-4" />
<span className="ml-auto inline-flex size-4 items-center justify-center">
<i className="i-mgc-check-filled size-3" />
</span>
</>
)}
</DropdownMenuPrimitive.Item>
)
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
@@ -35,13 +35,23 @@ export function SwipeMedia({
const [emblaRef, emblaApi] = useEmblaCarousel({ loop: true }, [WheelGesturesPlugin()])
const scrollPrev = useCallback(() => {
if (emblaApi) emblaApi.scrollPrev()
}, [emblaApi])
const scrollPrev = useCallback(
(e) => {
e.preventDefault()
e.stopPropagation()
if (emblaApi) emblaApi.scrollPrev()
},
[emblaApi],
)
const scrollNext = useCallback(() => {
if (emblaApi) emblaApi.scrollNext()
}, [emblaApi])
const scrollNext = useCallback(
(e) => {
e.preventDefault()
e.stopPropagation()
if (emblaApi) emblaApi.scrollNext()
},
[emblaApi],
)
if (!media) return null
@@ -70,6 +80,8 @@ export function SwipeMedia({
loading="lazy"
proxy={proxySize || undefined}
blurhash={med.blurhash}
width={med.width}
height={med.height}
onClick={(e) => {
if (onPreview) {
e.stopPropagation()
@@ -21,7 +21,6 @@ import {
setReadabilityStatus,
useEntryIsInReadability,
} from "~/atoms/readability"
import { useAIChatPinned } from "~/atoms/settings/ai"
import { useIntegrationSettingValue } from "~/atoms/settings/integration"
import { useShowSourceContent } from "~/atoms/source-content"
import { ipcServices } from "~/lib/client"
@@ -31,7 +30,6 @@ import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding
import type { FollowCommandId } from "~/modules/command/types"
import { useToolbarOrderMap } from "~/modules/customize-toolbar/hooks"
import { useFeature } from "./useFeature"
import { useRouteParams } from "./useRouteParams"
export const enableEntryReadability = async ({ id, url }: { id: string; url: string }) => {
@@ -212,7 +210,7 @@ export const HIDE_ACTIONS_IN_ENTRY_CONTEXT_MENU = [
COMMAND_ID.entry.viewSourceContent,
COMMAND_ID.entry.toggleAISummary,
COMMAND_ID.entry.toggleAITranslation,
COMMAND_ID.global.toggleAIChatPinned,
COMMAND_ID.settings.customizeToolbar,
COMMAND_ID.entry.readability,
COMMAND_ID.entry.exportAsPDF,
@@ -249,8 +247,7 @@ export const useEntryActions = ({
const isShowAISummaryOnce = useShowAISummaryOnce()
const isShowAITranslationAuto = useShowAITranslationAuto(!!entry?.translation)
const isShowAITranslationOnce = useShowAITranslationOnce()
const isShowAIChatPinned = useAIChatPinned()
const aiEnabled = useFeature("ai")
const runCmdFn = useRunCommandFn()
const hasEntry = !!entry
@@ -441,14 +438,6 @@ export const useEntryActions = ({
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.global.toggleAIChatPinned,
onClick: runCmdFn(COMMAND_ID.global.toggleAIChatPinned, [{ entryId }]),
entryId,
active: isShowAIChatPinned,
hide: !aiEnabled,
}),
// Custom Integration with sub-menu
...(() => {
const customIntegrations = integrationSettings.customIntegration || []
@@ -513,8 +502,7 @@ export const useEntryActions = ({
isCollection,
compact,
isEntryInReadability,
isShowAIChatPinned,
aiEnabled,
integrationSettings.customIntegration,
integrationSettings.enableCustomIntegration,
])
@@ -1,12 +1,58 @@
import { useDebugFeatureValue } from "~/atoms/debug-feature"
import { useServerConfigs } from "~/atoms/server-configs"
import { getDebugFeatureValue, useDebugFeatureValue } from "~/atoms/debug-feature"
import { getServerConfigs, useServerConfigs } from "~/atoms/server-configs"
import { featureConfigMap } from "~/lib/features"
export const useFeature = (feature: keyof typeof featureConfigMap) => {
const debugFeatureValue = useDebugFeatureValue()
const serverConfigs = useServerConfigs()
const isEnabled =
(featureConfigMap[feature] && serverConfigs?.[featureConfigMap[feature]]) ||
debugFeatureValue[feature]
return isEnabled
// Define debug feature value structure
interface DebugFeatureValue {
__override?: boolean
[key: string]: boolean | undefined
}
// Define feature key type
export type FeatureKey = keyof typeof featureConfigMap
/**
* Core feature checking logic to avoid code duplication
* @param feature - Feature key name
* @param debugFeatureValue - Debug feature values
* @param serverConfigs - Server configuration
* @returns Whether the feature is enabled
*/
const checkFeatureEnabled = (
feature: FeatureKey,
debugFeatureValue: DebugFeatureValue,
serverConfigs: ReturnType<typeof getServerConfigs>,
): boolean => {
const override = !!debugFeatureValue.__override
if (override) {
return !!debugFeatureValue[feature]
}
const serverConfigKey = featureConfigMap[feature]
return !!(serverConfigKey && serverConfigs?.[serverConfigKey])
}
/**
* React Hook: Check if a specific feature is enabled
* @param feature - Feature key name
* @returns Whether the feature is enabled
*/
export const useFeature = (feature: FeatureKey): boolean => {
const debugFeatureValue = useDebugFeatureValue() as DebugFeatureValue
const serverConfigs = useServerConfigs()
return checkFeatureEnabled(feature, debugFeatureValue, serverConfigs)
}
/**
* Non-Hook function: Check if a specific feature is enabled
* @param feature - Feature key name
* @returns Whether the feature is enabled
*/
export const getFeature = (feature: FeatureKey): boolean => {
const debugFeatureValue = getDebugFeatureValue() as DebugFeatureValue
const serverConfigs = getServerConfigs()
return checkFeatureEnabled(feature, debugFeatureValue, serverConfigs)
}
@@ -14,9 +14,9 @@ import { subscribeNetworkStatus } from "../atoms/network"
import { appLog } from "../lib/log"
import { initAnalytics } from "./analytics"
import { registerHistoryStack } from "./history"
import { hydrateSettings } from "./hydrate"
import { doMigration } from "./migrates"
import { initSentry } from "./sentry"
import { initializeSettings } from "./settings"
declare global {
interface Window {
@@ -80,7 +80,7 @@ export const initializeApp = async () => {
subscribeNetworkStatus()
apm("hydrateSettings", hydrateSettings)
apm("initializeSettings", initializeSettings)
initSentry()
await apm("i18n", initI18n)
@@ -1,9 +1,11 @@
import { initializeDefaultAISettings } from "~/atoms/settings/ai"
import { initializeDefaultGeneralSettings } from "~/atoms/settings/general"
import { initializeDefaultIntegrationSettings } from "~/atoms/settings/integration"
import { initializeDefaultUISettings } from "~/atoms/settings/ui"
export const hydrateSettings = () => {
export const initializeSettings = () => {
initializeDefaultUISettings()
initializeDefaultGeneralSettings()
initializeDefaultIntegrationSettings()
initializeDefaultAISettings()
}
@@ -1,6 +1,6 @@
import { toast } from "sonner"
import { apiClient, apiFetch } from "./api-fetch"
import { followApi } from "./api-client"
import { getFetchErrorMessage } from "./error-parser"
/**
@@ -10,19 +10,14 @@ import { getFetchErrorMessage } from "./error-parser"
* @returns Promise<string> - The uploaded image URL
*/
export async function uploadAvatarBlob(blob: Blob): Promise<string> {
const formData = new FormData()
formData.append("file", blob, "avatar.jpg")
const { url } = await followApi.upload
.uploadAvatar({
file: blob,
})
.catch((err) => {
toast.error(getFetchErrorMessage(err))
throw err
})
const res = await apiFetch<{
url: string
}>(apiClient.upload.avatar.$url().toString(), {
method: "POST",
body: formData,
}).catch((err) => {
toast.error(getFetchErrorMessage(err))
throw err
})
return res.url
return url
}
@@ -3,10 +3,9 @@ import type { FC } from "react"
import { useFeature } from "~/hooks/biz/useFeature"
export const featureConfigMap: Record<string, keyof ExtractResponseData<GetStatusConfigsResponse>> =
{
ai: "AI_CHAT_ENABLED",
}
export const featureConfigMap = {
ai: "AI_CHAT_ENABLED",
} satisfies Record<string, keyof ExtractResponseData<GetStatusConfigsResponse>>
export const withFeature =
(feature: keyof typeof featureConfigMap) =>
@@ -25,9 +25,13 @@ export function addTextSelectionListener(
if (!selection) return
// Check if selection is within our shadow root
const range = selection.getRangeAt(0)
if (!shadowRoot.contains(range.commonAncestorContainer)) return
try {
const range = selection.getRangeAt(0)
if (!shadowRoot.contains(range.commonAncestorContainer)) return
} catch {
// Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index.
return
}
if (!selection.isCollapsed) {
const selectedText = selection.toString().trim()
if (selectedText) {
@@ -3,7 +3,7 @@ import { stopPropagation } from "@follow/utils/dom"
import { useCallback } from "react"
import { useTranslation } from "react-i18next"
import { useSettingModal } from "../settings/modal/useSettingModal"
import { useSettingModal } from "../settings/modal/use-setting-modal-hack"
export const NeedActivationToast = (props: { dimiss: () => void }) => {
const settingModalPresent = useSettingModal()
@@ -0,0 +1,207 @@
import { clsx, cn } from "@follow/utils/utils"
import type { FC } from "react"
import { memo } from "react"
import { ImageThumbnail } from "~/modules/ai-chat/components/layouts/ImageThumbnail"
import { CircularProgress } from "~/modules/ai-chat/components/ui/UploadProgress"
import { useChatBlockActions } from "~/modules/ai-chat/store/hooks"
import type { AIChatContextBlock } from "~/modules/ai-chat/store/types"
import {
getFileCategoryFromMimeType,
getFileIconName,
} from "~/modules/ai-chat/utils/file-validation"
import { EntryTitle, FeedTitle } from "./TitleComponents"
export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block }) => {
const blockActions = useChatBlockActions()
const getBlockIcon = () => {
switch (block.type) {
case "mainEntry": {
return "i-mgc-star-cute-fi"
}
case "referEntry": {
return "i-mgc-paper-cute-fi"
}
case "referFeed": {
return "i-mgc-rss-cute-fi"
}
case "selectedText": {
return "i-mgc-quill-pen-cute-re"
}
case "fileAttachment": {
const { type, dataUrl, previewUrl } = block.attachment
const fileCategory = getFileCategoryFromMimeType(type)
// Don't show icon for images with thumbnails, as the thumbnail serves as the icon
if (fileCategory === "image" && (dataUrl || previewUrl)) {
return null
}
return getFileIconName(fileCategory)
}
default: {
return "i-mgc-paper-cute-fi"
}
}
}
const getDisplayContent = () => {
switch (block.type) {
case "mainEntry":
case "referEntry": {
return <EntryTitle entryId={block.value} fallback={block.value} />
}
case "referFeed": {
return <FeedTitle feedId={block.value} fallback={block.value} />
}
case "selectedText": {
return `"${block.value}"`
}
case "fileAttachment": {
const { type, name, dataUrl, previewUrl, uploadStatus, errorMessage, uploadProgress } =
block.attachment
const fileCategory = getFileCategoryFromMimeType(type)
if (fileCategory === "image" && (dataUrl || previewUrl)) {
return (
<div className="flex items-center gap-1.5">
<div className="relative">
<ImageThumbnail
previewUrl={previewUrl || dataUrl}
originalUrl={dataUrl}
alt={name}
filename={name}
className={"m-0.5 size-5 rounded-md"}
/>
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="absolute inset-0 flex items-center justify-center rounded-md bg-black/50">
<CircularProgress
progress={uploadProgress}
size={16}
strokeWidth={2}
variant="default"
className="text-white"
/>
</div>
)}
{uploadStatus === "error" && (
<div
className="bg-red/80 absolute inset-0 flex items-center justify-center rounded-md"
title={errorMessage}
>
<i className="i-mgc-close-cute-re size-3 text-white" />
</div>
)}
</div>
<div className="flex min-w-0 flex-1">
<span className="truncate">
{name}{" "}
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="text-text-tertiary text-xs">
({Math.round(uploadProgress)}%)
</div>
)}
</span>
{uploadStatus === "error" && <div className="text-red text-xs">Upload failed</div>}
</div>
</div>
)
}
// For non-image files
return (
<div className="flex items-center gap-1.5">
<span className="min-w-0 flex-1 truncate">{name}</span>
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="flex items-center gap-1">
<CircularProgress
progress={uploadProgress}
size={14}
strokeWidth={2}
variant="default"
/>
<span className="text-text-tertiary text-xs">{Math.round(uploadProgress)}%</span>
</div>
)}
{uploadStatus === "error" && (
<i className="i-mgc-close-cute-re text-red size-3" title={errorMessage} />
)}
</div>
)
}
default: {
// This should never happen with proper discriminated union
return ""
}
}
}
const getBlockLabel = () => {
switch (block.type) {
case "mainEntry": {
return "Current"
}
case "referEntry": {
return "Ref"
}
case "referFeed": {
return "Feed"
}
case "selectedText": {
return "Text"
}
case "fileAttachment": {
return "File"
}
default: {
return ""
}
}
}
const canRemove = block.type !== "mainEntry"
return (
<div
className={cn(
"group relative flex h-7 min-w-0 max-w-[calc(50%-0.5rem)] flex-shrink-0 items-center gap-2 overflow-hidden rounded-lg px-2.5",
"bg-fill-tertiary border-border border",
)}
>
<div
className={clsx(
"min-w-0",
canRemove
? "group-hover:[mask-image:linear-gradient(to_right,black_0%,black_calc(100%-3rem),rgba(0,0,0,0.8)_calc(100%-2rem),rgba(0,0,0,0.3)_calc(100%-1rem),transparent_100%)]"
: void 0,
)}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<div className="flex items-center gap-1">
{getBlockIcon() && <i className={cn("size-3.5 flex-shrink-0", getBlockIcon())} />}
<span className="text-text-tertiary text-xs font-medium">{getBlockLabel()}</span>
</div>
<span className={"text-text min-w-0 flex-1 truncate text-xs"}>{getDisplayContent()}</span>
</div>
</div>
{canRemove && (
<button
type="button"
onClick={() => blockActions.removeBlock(block.id)}
className="text-text/90 cursor-button hover:text-text absolute inset-y-0 right-2 flex-shrink-0 opacity-0 transition-all ease-in group-hover:opacity-100"
>
<i className="i-mgc-close-cute-re size-3" />
</button>
)}
</div>
)
})
@@ -0,0 +1,22 @@
import { useEntry } from "@follow/store/entry/hooks"
import { useFeedById } from "@follow/store/feed/hooks"
import type { FC } from "react"
export const EntryTitle: FC<{ entryId?: string; fallback: string }> = ({ entryId, fallback }) => {
const entryTitle = useEntry(entryId!, (e) => e?.title)
if (!entryId || !entryTitle) {
return <span className="text-text-tertiary">{fallback}</span>
}
return <span>{entryTitle}</span>
}
export const FeedTitle: FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => {
const feed = useFeedById(feedId, (feed) => ({ title: feed?.title }))
if (!feedId || !feed) {
return <span className="text-text-tertiary">{fallback}</span>
}
return <span>{feed.title}</span>
}
@@ -0,0 +1,2 @@
export * from "./ContextBlock"
export * from "./TitleComponents"
@@ -0,0 +1,3 @@
export * from "./blocks"
export * from "./menus"
export * from "./pickers"
@@ -0,0 +1,71 @@
import type { FC } from "react"
import {
DropdownMenuContent,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
} from "~/components/ui/dropdown-menu/dropdown-menu"
import { useChatBlockActions } from "~/modules/ai-chat/store/hooks"
import { CurrentFeedEntriesPickerList, FeedPickerList, RecentEntriesPickerList } from "../pickers"
export const ContextMenuContent: FC = () => {
const blockActions = useChatBlockActions()
return (
<DropdownMenuContent align="start">
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<i className="i-mgc-paper-cute-fi mr-1.5 size-4" />
Current Feed Entries
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<CurrentFeedEntriesPickerList
onSelect={(entryId) =>
blockActions.addBlock({
type: "referEntry",
value: entryId,
})
}
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<i className="i-mgc-paper-cute-fi mr-1.5 size-4" />
Reference Entry
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<RecentEntriesPickerList
onSelect={(entryId) =>
blockActions.addBlock({
type: "referEntry",
value: entryId,
})
}
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<i className="i-mgc-rss-cute-fi mr-1.5 size-4" />
Reference Feed
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<FeedPickerList
onSelect={(feedId) =>
blockActions.addBlock({
type: "referFeed",
value: feedId,
})
}
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
</DropdownMenuContent>
)
}
@@ -0,0 +1,50 @@
import type { FC } from "react"
import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "~/components/ui/dropdown-menu/dropdown-menu"
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
interface ShortcutsMenuContentProps {
shortcuts: Array<{
id: string
name: string
prompt: string
enabled: boolean
}>
onSendShortcut?: (prompt: string) => void
}
export const ShortcutsMenuContent: FC<ShortcutsMenuContentProps> = ({
shortcuts,
onSendShortcut,
}) => {
const showSettingModal = useSettingModal()
const enabledShortcuts = shortcuts.filter((shortcut) => shortcut.enabled)
return (
<DropdownMenuContent align="start">
{enabledShortcuts.length === 0 ? (
<div className="text-text-tertiary p-3 text-center text-xs">No shortcuts configured</div>
) : (
enabledShortcuts.map((shortcut) => (
<DropdownMenuItem key={shortcut.id} onClick={() => onSendShortcut?.(shortcut.prompt)}>
<i className="i-mgc-magic-2-cute-re mr-1.5 size-3.5" />
<span className="truncate">{shortcut.name}</span>
</DropdownMenuItem>
))
)}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => {
showSettingModal("ai")
}}
>
<i className="i-mgc-settings-7-cute-re mr-1.5 size-3.5" />
<span>Manage Shortcut</span>
</DropdownMenuItem>
</DropdownMenuContent>
)
}
@@ -0,0 +1,2 @@
export * from "./ContextMenuContent"
export * from "./ShortcutsMenuContent"
@@ -0,0 +1,57 @@
import { useEntry, useEntryIdsByFeedId, useEntryIdsByView } from "@follow/store/entry/hooks"
import { useEntryStore } from "@follow/store/entry/store"
import type { FC } from "react"
import { useMemo } from "react"
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext"
import type { PickerItem } from "./PickerList"
import { PickerList } from "./PickerList"
export const CurrentFeedEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({
onSelect,
}) => {
const mainEntryId = useAIChatStore()((s) => {
const block = s.blocks.find((b) => b.type === "mainEntry")
return block && block.type === "mainEntry" ? block.value : undefined
})
const feedId = useEntry(mainEntryId, (e) => e?.feedId)
const entryIds = useEntryIdsByFeedId(feedId!)
return <BaseEntryPickerList items={entryIds || []} onSelect={onSelect} />
}
export const RecentEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({
onSelect,
}) => {
const view = useRouteParamsSelector((route) => route.view)
const recentEntryIds = useEntryIdsByView(view, false)
return <BaseEntryPickerList items={(recentEntryIds || []).slice(0, 20)} onSelect={onSelect} />
}
const BaseEntryPickerList: FC<{ items: string[]; onSelect: (entryId: string) => void }> = ({
items,
onSelect,
}) => {
const entryStore = useEntryStore((state) => state.data)
const entries = useMemo(() => {
return items
.map((entryId) => {
const entry = entryStore[entryId]
return entry ? { id: entryId, title: entry.title || "Untitled" } : null
})
.filter(Boolean) as PickerItem[]
}, [items, entryStore])
return (
<PickerList
items={entries}
placeholder="Search entries..."
onSelect={onSelect}
noResultsText="No entries found"
/>
)
}
@@ -0,0 +1,59 @@
import { getFeedById } from "@follow/store/feed/getter"
import { useFeedById } from "@follow/store/feed/hooks"
import { useAllFeedSubscription } from "@follow/store/subscription/hooks"
import type { FC } from "react"
import { useMemo } from "react"
import { DropdownMenuItem } from "~/components/ui/dropdown-menu/dropdown-menu"
import type { PickerItem } from "./PickerList"
import { PickerList } from "./PickerList"
export const FeedPickerList: FC<{ onSelect: (feedId: string) => void }> = ({ onSelect }) => {
const allSubscriptions = useAllFeedSubscription()
// Get feeds with their details
const feeds = useMemo(() => {
return allSubscriptions
.filter((subscription) => subscription.feedId)
.map((subscription) => {
const customTitle = subscription.title
if (!subscription.feedId) return null
const feed = getFeedById(subscription.feedId!)
return {
id: subscription.feedId!,
title: customTitle || feed?.title || `Feed ${subscription.feedId}`,
} as PickerItem
})
.filter(Boolean) as PickerItem[]
}, [allSubscriptions])
return (
<PickerList
items={feeds}
placeholder="Search feeds..."
onSelect={onSelect}
noResultsText="No feeds found"
renderItem={(feed, onSelect) => (
<FeedPickerItem key={feed.id} feedId={feed.id} title={feed.title} onSelect={onSelect} />
)}
/>
)
}
// Individual Feed Picker Item that shows real feed title
const FeedPickerItem: FC<{
feedId: string
title: string
onSelect: (feedId: string) => void
}> = ({ feedId, title, onSelect }) => {
const feed = useFeedById(feedId, (feed) => ({ title: feed?.title }))
const displayTitle = feed?.title || title || "Untitled Feed"
return (
<DropdownMenuItem onClick={() => onSelect(feedId)} className="text-xs">
<span className="truncate">{displayTitle}</span>
</DropdownMenuItem>
)
}
@@ -0,0 +1,75 @@
import { stopPropagation } from "@follow/utils"
import Fuse from "fuse.js"
import { useMemo, useState } from "react"
import { useDebounceCallback } from "usehooks-ts"
import { DropdownMenuItem } from "~/components/ui/dropdown-menu/dropdown-menu"
import { SearchInput } from "./SearchInput"
// Generic Picker Component
export interface PickerItem {
id: string
title: string
}
export interface PickerListProps<T extends PickerItem> {
items: T[]
placeholder: string
onSelect: (id: string) => void
renderItem?: (item: T, onSelect: (id: string) => void) => React.ReactNode
noResultsText?: string
}
export const PickerList = <T extends PickerItem>({
items,
placeholder,
onSelect,
renderItem,
noResultsText = "No items found",
}: PickerListProps<T>) => {
const [searchTerm, setSearchTerm] = useState("")
const fuse = useMemo(() => {
return new Fuse(items, {
keys: ["title", "id"],
threshold: 0.3,
})
}, [items])
const filteredItems = useMemo(() => {
if (!searchTerm) return items
const results = fuse.search(searchTerm)
return results.map((result) => result.item)
}, [items, fuse, searchTerm])
const debouncedSetSearchTerm = useDebounceCallback(setSearchTerm, 300)
const defaultRenderItem = (item: T, onSelect: (id: string) => void) => (
<DropdownMenuItem key={item.id} onClick={() => onSelect(item.id)} className="text-xs">
<span className="truncate">{item.title}</span>
</DropdownMenuItem>
)
return (
<div className="max-h-64 w-56">
<SearchInput
placeholder={placeholder}
onKeyDown={stopPropagation}
onKeyUp={stopPropagation}
onChange={(e) => {
debouncedSetSearchTerm(e.target.value)
}}
/>
<div className="max-h-48 overflow-y-auto pt-2">
{filteredItems.length === 0 ? (
<div className="text-text-tertiary p-2 text-xs">{noResultsText}</div>
) : (
filteredItems.map((item) =>
renderItem ? renderItem(item, onSelect) : defaultRenderItem(item, onSelect),
)
)}
</div>
</div>
)
}
@@ -0,0 +1,14 @@
import type { FC } from "react"
export const SearchInput: FC<React.ComponentProps<"input">> = (props) => {
return (
<div className="-mx-1 flex items-center border-b py-1">
<i className="i-mgc-search-2-cute-re text-text-secondary ml-3 mr-1.5 size-4" />
<input
type="text"
{...props}
className="placeholder:text-text-tertiary w-full bg-transparent py-1 pl-0 pr-4 text-xs"
/>
</div>
)
}
@@ -0,0 +1,4 @@
export * from "./EntryPickers"
export * from "./FeedPickers"
export * from "./PickerList"
export * from "./SearchInput"
@@ -1,11 +1,46 @@
import "@xyflow/react/dist/style.css"
import { useIsDark } from "@follow/hooks"
import { Background, ReactFlow } from "@xyflow/react"
import { cn } from "@follow/utils/utils"
import { Background, Controls, ReactFlow } from "@xyflow/react"
import { useCallback } from "react"
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
import type { AIDisplayFlowTool } from "../../store/types"
import { toolMemo } from "./share"
const FlowPreviewModal = ({
nodes,
edges,
colorMode,
}: {
nodes: any[]
edges: any[]
colorMode: "light" | "dark"
}) => {
return (
<div className="flex size-full flex-col">
<ReactFlow
colorMode={colorMode}
nodes={nodes}
edges={edges}
fitView
nodesDraggable={true}
nodesConnectable={false}
nodesFocusable={true}
edgesFocusable={true}
elementsSelectable={true}
preventScrolling={false}
className="size-full"
>
<Background />
<Controls />
</ReactFlow>
</div>
)
}
export const AIDisplayFlowPart = toolMemo(
({ part, loadingElement }: { part: AIDisplayFlowTool; loadingElement: React.ReactNode }) => {
if (!part.input) return loadingElement
@@ -15,8 +50,22 @@ export const AIDisplayFlowPart = toolMemo(
const { nodes, edges } = part.input.flowChart as any
const colorMode = useIsDark() ? "dark" : "light"
const { present } = useModalStack()
const handleOpenModal = useCallback(() => {
present({
title: "Flow Chart Preview",
content: () => <FlowPreviewModal nodes={nodes} edges={edges} colorMode={colorMode} />,
max: true,
canClose: true,
clickOutsideToDismiss: false,
modalContentClassName: "p-0 h-full",
modalClassName: "h-[90vh] w-[90vw]",
})
}, [nodes, edges, colorMode, present])
return (
<div className="my-2 aspect-[4/3] w-full overflow-hidden rounded-md">
<div className="group relative my-2 aspect-[4/3] w-[calc(var(--ai-chat-layout-width,65ch)-120px)] max-w-prose overflow-hidden rounded-md">
<ReactFlow
colorMode={colorMode}
nodes={nodes}
@@ -27,14 +76,28 @@ export const AIDisplayFlowPart = toolMemo(
nodesFocusable={false}
edgesFocusable={false}
elementsSelectable={false}
panOnDrag={false}
zoomOnScroll={false}
zoomOnPinch={false}
zoomOnDoubleClick={false}
preventScrolling={false}
>
<Background />
<Controls />
</ReactFlow>
{/* Expand/Preview button */}
<button
type="button"
onClick={handleOpenModal}
className={cn(
"absolute right-2 top-2 flex items-center gap-1.5 rounded-lg px-2.5 py-1.5",
"bg-material-thick text-text-secondary text-sm font-medium",
"opacity-0 transition-all duration-200 group-hover:opacity-100",
"hover:bg-material-medium hover:text-text focus:opacity-100",
"focus:ring-blue focus:outline-none focus:ring-2 focus:ring-offset-1",
)}
title="Open in full screen"
>
<i className="i-mgc-external-link-cute-re size-4" />
<span>Preview</span>
</button>
</div>
)
},
@@ -0,0 +1,146 @@
import { Spring } from "@follow/components/constants/spring.js"
import { cn } from "@follow/utils"
import { AnimatePresence, m } from "motion/react"
import type { FC, PropsWithChildren } from "react"
import { memo, useCallback, useRef, useState } from "react"
import { useFileUploadWithDefaults } from "../../hooks/useFileUpload"
interface GlobalFileDropZoneProps extends PropsWithChildren {
className?: string
}
export const GlobalFileDropZone: FC<GlobalFileDropZoneProps> = memo(({ children, className }) => {
const { handleFileDrop } = useFileUploadWithDefaults()
const [isDragOver, setIsDragOver] = useState(false)
const [isProcessing, setIsProcessing] = useState(false)
const dragCounterRef = useRef(0)
const handleDragEnter = useCallback((e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
dragCounterRef.current += 1
if (e.dataTransfer.types.includes("Files")) {
setIsDragOver(true)
}
}, [])
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
dragCounterRef.current -= 1
if (dragCounterRef.current === 0) {
setIsDragOver(false)
}
}, [])
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
}, [])
const handleDrop = useCallback(
async (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
dragCounterRef.current = 0
setIsDragOver(false)
const { files } = e.dataTransfer
if (!files || files.length === 0) return
setIsProcessing(true)
try {
await handleFileDrop(files)
} catch (error) {
console.error("Error processing files:", error)
} finally {
setIsProcessing(false)
}
},
[handleFileDrop],
)
return (
<div
className={cn("relative size-full", className)}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
{children}
{/* Global Drag Overlay */}
<AnimatePresence>
{isDragOver && (
<m.div className="pointer-events-none absolute inset-0 z-50 flex items-center justify-center">
{/* Glass morphism backdrop */}
<m.div
className="bg-material-thin/80 absolute inset-0 backdrop-blur-xl"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={Spring.presets.smooth}
/>
{/* Content */}
<m.div
initial={{ scale: 0.9, y: 20, opacity: 0 }}
animate={{ scale: 1, y: 0, opacity: 1 }}
exit={{ scale: 0.9, y: 20, opacity: 0 }}
transition={Spring.presets.snappy}
className="bg-background/95 border-accent/20 shadow-accent/10 relative flex max-w-md flex-col items-center gap-4 rounded-2xl border p-8 shadow-2xl"
>
{isProcessing ? (
<>
<div className="border-accent size-12 animate-spin rounded-full border-4 border-t-transparent" />
<div className="text-center">
<p className="text-text text-lg font-medium">Processing files...</p>
<p className="text-text-secondary text-sm">
Please wait while we process your files
</p>
</div>
</>
) : (
<>
<div className="text-accent relative">
<i className="i-mgc-file-upload-cute-re size-16" />
<m.div
className="text-accent absolute inset-0 blur-lg"
animate={{
scale: [1, 1.1, 1],
opacity: [0.5, 1, 0.5],
}}
transition={{
duration: 2,
repeat: Number.POSITIVE_INFINITY,
ease: "easeInOut",
}}
>
<i className="i-mgc-file-upload-cute-re size-16" />
</m.div>
</div>
<div className="text-center">
<p className="text-text text-lg font-medium">Drop files to attach</p>
<p className="text-text-secondary text-sm">
Images, PDFs, text files, and audio files are supported
</p>
</div>
</>
)}
</m.div>
</m.div>
)}
</AnimatePresence>
</div>
)
})
GlobalFileDropZone.displayName = "GlobalFileDropZone"
@@ -1,38 +1,21 @@
import { useEntry, useEntryIdsByFeedId, useEntryIdsByView } from "@follow/store/entry/hooks"
import { useEntryStore } from "@follow/store/entry/store"
import { getFeedById } from "@follow/store/feed/getter"
import { useFeedById } from "@follow/store/feed/hooks"
import { useAllFeedSubscription } from "@follow/store/subscription/hooks"
import { stopPropagation } from "@follow/utils"
import { cn } from "@follow/utils/utils"
import Fuse from "fuse.js"
import type { FC } from "react"
import { memo, useMemo, useState } from "react"
import { useDebounceCallback } from "usehooks-ts"
import { memo, useCallback, useMemo, useRef } from "react"
import { useAISettingValue } from "~/atoms/settings/ai"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu/dropdown-menu"
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
import { DropdownMenu, DropdownMenuTrigger } from "~/components/ui/dropdown-menu/dropdown-menu"
import { useFileUploadWithDefaults } from "~/modules/ai-chat/hooks/useFileUpload"
import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext"
import type { AIChatContextBlock } from "~/modules/ai-chat/store/types"
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
import { SUPPORTED_MIME_ACCEPT } from "~/modules/ai-chat/utils/file-validation"
import { useChatBlockActions } from "../../store/hooks"
import { ContextBlock } from "../context-bar/blocks"
import { ContextMenuContent, ShortcutsMenuContent } from "../context-bar/menus"
export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => void }> = memo(
({ className, onSendShortcut }) => {
const blocks = useAIChatStore()((s) => s.blocks)
const blockActions = useChatBlockActions()
const { shortcuts } = useAISettingValue()
const fileInputRef = useRef<HTMLInputElement>(null)
const { handleFileInputChange } = useFileUploadWithDefaults()
// Filter enabled shortcuts
const enabledShortcuts = useMemo(
@@ -40,85 +23,9 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) =>
[shortcuts],
)
const showSettingModal = useSettingModal()
const contextMenuContent = (
<DropdownMenuContent align="start">
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<i className="i-mgc-paper-cute-fi mr-1.5 size-4" />
Current Feed Entries
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<CurrentFeedEntriesPickerList
onSelect={(entryId) =>
blockActions.addBlock({
type: "referEntry",
value: entryId,
})
}
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSeparator />
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<i className="i-mgc-paper-cute-fi mr-1.5 size-4" />
Reference Entry
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<RecentEntriesPickerList
onSelect={(entryId) =>
blockActions.addBlock({
type: "referEntry",
value: entryId,
})
}
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<i className="i-mgc-rss-cute-fi mr-1.5 size-4" />
Reference Feed
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<FeedPickerList
onSelect={(feedId) =>
blockActions.addBlock({
type: "referFeed",
value: feedId,
})
}
/>
</DropdownMenuSubContent>
</DropdownMenuSub>
</DropdownMenuContent>
)
const shortcutsMenuContent = (
<DropdownMenuContent align="start">
{enabledShortcuts.length === 0 ? (
<div className="text-text-tertiary p-3 text-center text-xs">No shortcuts configured</div>
) : (
enabledShortcuts.map((shortcut) => (
<DropdownMenuItem key={shortcut.id} onClick={() => onSendShortcut?.(shortcut.prompt)}>
<i className="i-mgc-magic-2-cute-re mr-1.5 size-3.5" />
<span className="truncate">{shortcut.name}</span>
</DropdownMenuItem>
))
)}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => {
showSettingModal("ai")
}}
>
<i className="i-mgc-settings-7-cute-re mr-1.5 size-3.5" />
<span>Manage Shortcut</span>
</DropdownMenuItem>
</DropdownMenuContent>
)
const handleAttachFile = useCallback(() => {
fileInputRef.current?.click()
}, [])
return (
<div className={cn("flex flex-wrap items-center gap-2 px-4 py-3", className)}>
@@ -132,9 +39,29 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) =>
<i className="i-mgc-add-cute-re size-3.5" />
</button>
</DropdownMenuTrigger>
{contextMenuContent}
<ContextMenuContent />
</DropdownMenu>
{/* File Upload Button */}
<button
type="button"
onClick={handleAttachFile}
className="bg-fill-secondary hover:bg-fill-tertiary border-border text-text-tertiary hover:text-text-secondary flex size-7 items-center justify-center rounded-md border transition-colors"
title="Upload Files"
>
<i className="i-mgc-attachment-cute-re size-3.5" />
</button>
{/* Hidden File Input */}
<input
ref={fileInputRef}
type="file"
multiple
accept={SUPPORTED_MIME_ACCEPT}
onChange={handleFileInputChange}
className="hidden"
/>
{/* AI Shortcuts Button */}
{enabledShortcuts.length > 0 && (
<DropdownMenu>
@@ -147,7 +74,7 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) =>
<i className="i-mgc-magic-2-cute-re size-3.5" />
</button>
</DropdownMenuTrigger>
{shortcutsMenuContent}
<ShortcutsMenuContent shortcuts={shortcuts} onSendShortcut={onSendShortcut} />
</DropdownMenu>
)}
@@ -160,284 +87,3 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) =>
},
)
AIChatContextBar.displayName = "AIChatContextBar"
// Generic Picker Component
interface PickerItem {
id: string
title: string
}
interface PickerListProps<T extends PickerItem> {
items: T[]
placeholder: string
onSelect: (id: string) => void
renderItem?: (item: T, onSelect: (id: string) => void) => React.ReactNode
noResultsText?: string
}
const PickerList = <T extends PickerItem>({
items,
placeholder,
onSelect,
renderItem,
noResultsText = "No items found",
}: PickerListProps<T>) => {
const [searchTerm, setSearchTerm] = useState("")
const fuse = useMemo(() => {
return new Fuse(items, {
keys: ["title", "id"],
threshold: 0.3,
})
}, [items])
const filteredItems = useMemo(() => {
if (!searchTerm) return items
const results = fuse.search(searchTerm)
return results.map((result) => result.item)
}, [items, fuse, searchTerm])
const debouncedSetSearchTerm = useDebounceCallback(setSearchTerm, 300)
const defaultRenderItem = (item: T, onSelect: (id: string) => void) => (
<DropdownMenuItem key={item.id} onClick={() => onSelect(item.id)} className="text-xs">
<span className="truncate">{item.title}</span>
</DropdownMenuItem>
)
return (
<div className="max-h-64 w-56">
<SearchInput
placeholder={placeholder}
onKeyDown={stopPropagation}
onKeyUp={stopPropagation}
onChange={(e) => {
debouncedSetSearchTerm(e.target.value)
}}
/>
<div className="max-h-48 overflow-y-auto pt-2">
{filteredItems.length === 0 ? (
<div className="text-text-tertiary p-2 text-xs">{noResultsText}</div>
) : (
filteredItems.map((item) =>
renderItem ? renderItem(item, onSelect) : defaultRenderItem(item, onSelect),
)
)}
</div>
</div>
)
}
const CurrentFeedEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({
onSelect,
}) => {
const mainEntryId = useAIChatStore()((s) => s.blocks.find((b) => b.type === "mainEntry")?.value)
const feedId = useEntry(mainEntryId, (e) => e?.feedId)
const entryIds = useEntryIdsByFeedId(feedId!)
return <BaseEntryPickerList items={entryIds || []} onSelect={onSelect} />
}
const RecentEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({ onSelect }) => {
const view = useRouteParamsSelector((route) => route.view)
const recentEntryIds = useEntryIdsByView(view, false)
return <BaseEntryPickerList items={(recentEntryIds || []).slice(0, 20)} onSelect={onSelect} />
}
const BaseEntryPickerList: FC<{ items: string[]; onSelect: (entryId: string) => void }> = ({
items,
onSelect,
}) => {
const entryStore = useEntryStore((state) => state.data)
const entries = useMemo(() => {
return items
.map((entryId) => {
const entry = entryStore[entryId]
return entry ? { id: entryId, title: entry.title || "Untitled" } : null
})
.filter(Boolean) as PickerItem[]
}, [items, entryStore])
return (
<PickerList
items={entries}
placeholder="Search entries..."
onSelect={onSelect}
noResultsText="No entries found"
/>
)
}
const FeedPickerList: FC<{ onSelect: (feedId: string) => void }> = ({ onSelect }) => {
const allSubscriptions = useAllFeedSubscription()
// Get feeds with their details
const feeds = useMemo(() => {
return allSubscriptions
.filter((subscription) => subscription.feedId)
.map((subscription) => {
const customTitle = subscription.title
if (!subscription.feedId) return null
const feed = getFeedById(subscription.feedId!)
return {
id: subscription.feedId!,
title: customTitle || feed?.title || `Feed ${subscription.feedId}`,
} as PickerItem
})
.filter(Boolean) as PickerItem[]
}, [allSubscriptions])
return (
<PickerList
items={feeds}
placeholder="Search feeds..."
onSelect={onSelect}
noResultsText="No feeds found"
renderItem={(feed, onSelect) => (
<FeedPickerItem key={feed.id} feedId={feed.id} title={feed.title} onSelect={onSelect} />
)}
/>
)
}
const SearchInput: FC<React.ComponentProps<"input">> = (props) => {
return (
<div className="-mx-1 flex items-center border-b py-1">
<i className="i-mgc-search-2-cute-re text-text-secondary ml-3 mr-1.5 size-4" />
<input
type="text"
{...props}
className="placeholder:text-text-tertiary w-full bg-transparent py-1 pl-0 pr-4 text-xs"
/>
</div>
)
}
// Individual Feed Picker Item that shows real feed title
const FeedPickerItem: FC<{
feedId: string
title: string
onSelect: (feedId: string) => void
}> = ({ feedId, title, onSelect }) => {
const feed = useFeedById(feedId, (feed) => ({ title: feed?.title }))
const displayTitle = feed?.title || title || "Untitled Feed"
return (
<DropdownMenuItem onClick={() => onSelect(feedId)} className="text-xs">
<span className="truncate">{displayTitle}</span>
</DropdownMenuItem>
)
}
const ContextBlock: FC<{ block: AIChatContextBlock }> = ({ block }) => {
const blockActions = useChatBlockActions()
const getBlockIcon = () => {
switch (block.type) {
case "mainEntry": {
return "i-mgc-star-cute-fi"
}
case "referEntry": {
return "i-mgc-paper-cute-fi"
}
case "referFeed": {
return "i-mgc-rss-cute-fi"
}
case "selectedText": {
return "i-mgc-quill-pen-cute-re"
}
default: {
return "i-mgc-paper-cute-fi"
}
}
}
const getDisplayContent = () => {
switch (block.type) {
case "mainEntry":
case "referEntry": {
return <EntryTitle entryId={block.value} fallback={block.value} />
}
case "referFeed": {
return <FeedTitle feedId={block.value} fallback={block.value} />
}
case "selectedText": {
return `"${block.value}"`
}
default: {
return block.value
}
}
}
const getBlockLabel = () => {
switch (block.type) {
case "mainEntry": {
return "Current"
}
case "referEntry": {
return "Ref"
}
case "referFeed": {
return "Feed"
}
case "selectedText": {
return "Text"
}
default: {
return ""
}
}
}
const canRemove = block.type !== "mainEntry"
return (
<div className="bg-fill-tertiary border-border group relative flex h-7 max-w-[calc(50%-0.5rem)] flex-shrink-0 items-center gap-2 rounded-lg border px-2.5">
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<div className="flex items-center gap-1">
<i className={cn("size-3.5 flex-shrink-0", getBlockIcon())} />
<span className="text-text-tertiary text-xs font-medium">{getBlockLabel()}</span>
</div>
<span className={cn("text-text min-w-0 flex-1 truncate text-xs")}>
{getDisplayContent()}
</span>
</div>
{canRemove && (
<button
type="button"
onClick={() => blockActions.removeBlock(block.id)}
className="text-text-tertiary hover:text-text-secondary flex-shrink-0 opacity-0 transition-all group-hover:opacity-100"
>
<i className="i-mgc-close-cute-re size-3" />
</button>
)}
</div>
)
}
const EntryTitle: FC<{ entryId?: string; fallback: string }> = ({ entryId, fallback }) => {
const entryTitle = useEntry(entryId!, (e) => e?.title)
if (!entryId || !entryTitle) {
return <span className="text-text-tertiary">{fallback}</span>
}
return <span>{entryTitle}</span>
}
const FeedTitle: FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => {
const feed = useFeedById(feedId, (feed) => ({ title: feed?.title }))
if (!feedId || !feed) {
return <span className="text-text-tertiary">{fallback}</span>
}
return <span>{feed.title}</span>
}
@@ -14,14 +14,11 @@ interface AIChatRootProps extends PropsWithChildren {
chatId?: string
}
// Inner component that has access to the AI chat store context
const AIChatRootInner: FC<AIChatRootProps> = ({ children, chatId: externalChatId }) => {
// Use the new internal hooks
const currentChatId = useCurrentChatId()
const chatActions = useChatActions()
// Initialize room ID on mount
useMemo(() => {
if (!currentChatId && !externalChatId) {
chatActions.newChat()
@@ -0,0 +1,104 @@
import { cn } from "@follow/utils"
import { memo, useMemo } from "react"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu/dropdown-menu"
import { useAIModel } from "../../hooks/useAIModel"
interface AIModelIndicatorProps {
className?: string
onModelChange?: (model: string) => void
}
type ProviderType = "openai" | "anthropic" | "google" | "meta"
const providerIcons: Record<ProviderType, string> = {
openai: "i-simple-icons-openai",
anthropic: "i-simple-icons-anthropic",
google: "i-simple-icons-google",
meta: "i-simple-icons-meta",
}
const parseModelString = (modelString: string) => {
if (!modelString || !modelString.includes("/")) {
return { provider: "openai" as ProviderType, modelName: modelString || "Unknown" }
}
const [provider, ...modelParts] = modelString.split("/")
const modelName = modelParts.join("/")
return {
provider: (provider as ProviderType) || "openai",
modelName: modelName || "Unknown",
}
}
export const AIModelIndicator = memo(({ className, onModelChange }: AIModelIndicatorProps) => {
const { data } = useAIModel()
const { currentModel, availableModels = [] } = data || {}
const { provider, modelName } = useMemo(() => {
return parseModelString(currentModel || "")
}, [currentModel])
const iconClass = providerIcons[provider] || providerIcons.openai
const hasMultipleModels = availableModels && availableModels.length > 1
const modelContent = (
<div
className={cn(
"inline-flex items-center rounded-full border font-medium backdrop-blur-sm transition-colors",
hasMultipleModels
? "hover:bg-material-medium cursor-pointer"
: "hover:bg-material-medium/50",
"duration-200",
"gap-1.5 px-2 py-1 text-xs",
"bg-material-ultra-thin border-border/50",
"text-text-secondary",
className,
)}
>
<i className={cn("size-3", iconClass)} />
<span className="max-w-20 truncate">{modelName}</span>
{hasMultipleModels && <i className="i-mingcute-down-line size-3 opacity-60" />}
</div>
)
if (!hasMultipleModels) {
return modelContent
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>{modelContent}</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-48">
{availableModels.map((model) => {
const { provider: itemProvider, modelName: itemModelName } = parseModelString(model)
const itemIconClass = providerIcons[itemProvider] || providerIcons.openai
const isSelected = model === currentModel
return (
<DropdownMenuItem
key={model}
className="gap-2"
onClick={() => onModelChange?.(model)}
checked={isSelected}
>
<i className={cn("size-3", itemIconClass)} />
<span className="truncate">{itemModelName}</span>
{isSelected && <i className="i-mgc-check-cute-re text-accent ml-auto size-3" />}
</DropdownMenuItem>
)
})}
</DropdownMenuContent>
</DropdownMenu>
)
})
AIModelIndicator.displayName = "AIModelIndicator"
@@ -2,17 +2,20 @@ import { ActionButton } from "@follow/components/ui/button/index.js"
import { useCallback } from "react"
import { useTranslation } from "react-i18next"
import { AIChatPanelStyle, setAIPanelVisibility, useAIChatPanelStyle } from "~/atoms/settings/ai"
import { useDialog } from "~/components/ui/modal/stacked/hooks"
import { useChatActions, useCurrentTitle } from "~/modules/ai-chat/store/hooks"
import { useBlockActions, useChatActions, useCurrentTitle } from "~/modules/ai-chat/store/hooks"
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
import { ChatMoreDropdown } from "./ChatMoreDropdown"
import { EditableTitle } from "./EditableTitle"
export const ChatHeader = () => {
const currentTitle = useCurrentTitle()
const settingModalPresent = useSettingModal()
const chatActions = useChatActions()
const blockActions = useBlockActions()
const { ask } = useDialog()
const { t } = useTranslation("ai")
@@ -22,16 +25,18 @@ export const ChatHeader = () => {
return
}
ask({
title: t("clear_chat"),
message: t("clear_chat_message"),
variant: "danger",
onConfirm: () => {
chatActions.newChat()
},
})
}, [chatActions, currentTitle, ask, t])
chatActions.newChat()
blockActions.clearBlocks({ keepSpecialTypes: true })
}, [chatActions, currentTitle, ask, t, blockActions])
const handleTitleSave = useCallback(
async (newTitle: string) => {
await chatActions.editChatTitle(newTitle)
},
[chatActions],
)
const panelStyle = useAIChatPanelStyle()
const maskImage = `linear-gradient(to bottom, black 0%, black 75%, transparent 100%)`
return (
<div className="absolute inset-x-0 top-0 z-[1] h-12">
@@ -44,15 +49,8 @@ export const ChatHeader = () => {
/>
<div className="relative z-10 flex h-full items-center justify-between px-4">
{/* Left side - Title */}
<div className="mr-2 min-w-0 flex-1">
{currentTitle && (
<h1 key={currentTitle} className="text-text truncate font-bold">
<span className="animate-mask-left-to-right [--animation-duration:1s]">
{currentTitle}
</span>
</h1>
)}
<div className="mr-2 flex min-w-0 flex-1 items-center">
<EditableTitle title={currentTitle} onSave={handleTitleSave} placeholder="New Chat" />
</div>
{/* Right side - Actions */}
@@ -66,6 +64,15 @@ export const ChatHeader = () => {
</ActionButton>
<ChatMoreDropdown />
{panelStyle === AIChatPanelStyle.Floating && (
<>
<div className="bg-border h-5 w-px" />
<ActionButton tooltip="Close" onClick={() => setAIPanelVisibility(false)}>
<i className="i-mgc-close-cute-re text-text-secondary size-5" />
</ActionButton>
</>
)}
</div>
</div>
</div>
@@ -4,19 +4,21 @@ import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js"
import { cn, stopPropagation } from "@follow/utils"
import type { VariantProps } from "class-variance-authority"
import { cva } from "class-variance-authority"
import { noop } from "es-toolkit"
import type { EditorState, LexicalEditor } from "lexical"
import { $getRoot } from "lexical"
import { memo, useCallback, useRef, useState } from "react"
import { AIChatContextBar } from "~/modules/ai-chat/components/layouts/AIChatContextBar"
import { MentionPlugin } from "../../editor"
import { FileUploadPlugin, MentionPlugin } from "../../editor"
import { useChatActions, useChatStatus } from "../../store/hooks"
import { AIChatSendButton } from "./AIChatSendButton"
import { AIModelIndicator } from "./AIModelIndicator"
const chatInputVariants = cva(
[
"bg-background/60 focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80",
"bg-background focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80",
"relative overflow-hidden rounded-2xl border backdrop-blur-xl duration-200 focus-within:ring-2",
],
{
@@ -95,7 +97,7 @@ export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => {
onChange={handleEditorChange}
onKeyDown={handleKeyDown}
autoFocus
plugins={[MentionPlugin]}
plugins={[MentionPlugin, FileUploadPlugin]}
namespace="AIChatRichEditor"
/>
</ScrollArea>
@@ -111,10 +113,19 @@ export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => {
{/* Context Bar - Always shown, positioned below the input area */}
<div className="border-border/20 relative z-10 border-t bg-transparent">
<AIChatContextBar
className="border-0 bg-transparent px-4 py-2.5"
onSendShortcut={(prompt) => onSend(prompt, null)}
/>
<div className="flex items-center justify-between px-4 py-2.5">
<div className="flex-1">
<AIChatContextBar
className="border-0 bg-transparent p-0"
onSendShortcut={(prompt) => onSend(prompt, null)}
/>
</div>
<AIModelIndicator
className="-mr-1.5 ml-3 translate-y-[2px] self-start"
// Current not support switch model, will open this feature later
onModelChange={noop}
/>
</div>
</div>
</div>
)
@@ -1,22 +1,25 @@
import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js"
import { usePrefetchSummary } from "@follow/store/summary/hooks"
import { tracker } from "@follow/tracker"
import { clsx, cn, nextFrame } from "@follow/utils"
import { springScrollTo } from "@follow/utils/scroller"
import type { BizUIMessage } from "@folo-services/ai-tools"
import { ErrorBoundary } from "@sentry/react"
import type { EditorState, LexicalEditor } from "lexical"
import { AnimatePresence } from "motion/react"
import { nanoid } from "nanoid"
import type { FC } from "react"
import { useCallback, useEffect, useState } from "react"
import { Suspense, useEffect, useState } from "react"
import { useEventCallback } from "usehooks-ts"
import { useAISettingKey } from "~/atoms/settings/ai"
import { useActionLanguage } from "~/atoms/settings/general"
import {
AIChatMessage,
AIChatWaitingIndicator,
} from "~/modules/ai-chat/components/message/AIChatMessage"
import { useAutoScroll } from "~/modules/ai-chat/hooks/useAutoScroll"
import { useLoadMessages } from "~/modules/ai-chat/hooks/useLoadMessages"
import { useMainEntryId } from "~/modules/ai-chat/hooks/useMainEntryId"
import {
useBlockActions,
useChatActions,
@@ -28,12 +31,13 @@ import {
} from "~/modules/ai-chat/store/hooks"
import { convertLexicalToMarkdown } from "../../utils/lexical-markdown"
import { GlobalFileDropZone } from "../file/GlobalFileDropZone"
import { AIErrorFallback } from "./AIErrorFallback"
import { ChatInput } from "./ChatInput"
import { CollapsibleError } from "./CollapsibleError"
import { WelcomeScreen } from "./WelcomeScreen"
const SCROLL_BOTTOM_THRESHOLD = window.innerHeight / 2
const SCROLL_BOTTOM_THRESHOLD = 100
const ChatInterfaceContent = () => {
const hasMessages = useHasMessages()
@@ -41,12 +45,26 @@ const ChatInterfaceContent = () => {
const chatActions = useChatActions()
const error = useChatError()
useEffect(() => {
if (error) {
console.error("AIChat Error:", error)
}
}, [error])
const currentChatId = useCurrentChatId()
const mainEntryId = useMainEntryId()
const actionLanguage = useActionLanguage()
usePrefetchSummary({
entryId: mainEntryId || "",
target: "content",
actionLanguage,
enabled: !!mainEntryId && !hasMessages,
})
const [scrollAreaRef, setScrollAreaRef] = useState<HTMLDivElement | null>(null)
const [isAtBottom, setIsAtBottom] = useState(true)
// Reset handlers when chatId changes
useEffect(() => {
setIsAtBottom(true)
}, [currentChatId])
@@ -67,7 +85,12 @@ const ChatInterfaceContent = () => {
},
})
const { resetScrollState } = useAutoScroll(scrollAreaRef, status === "streaming")
const autoScrollWhenStreaming = useAISettingKey("autoScrollWhenStreaming")
const { resetScrollState } = useAutoScroll(
scrollAreaRef,
autoScrollWhenStreaming && status === "streaming",
)
useEffect(() => {
const scrollElement = scrollAreaRef
@@ -90,25 +113,34 @@ const ChatInterfaceContent = () => {
}
}, [scrollAreaRef])
const scrollToBottom = useCallback(() => {
const scrollElement = scrollAreaRef
if (!scrollElement) return
springScrollTo(scrollElement.scrollHeight, scrollElement)
}, [scrollAreaRef])
const blockActions = useBlockActions()
const handleSendMessage = useEventCallback(
(message: string | EditorState, editor: LexicalEditor | null) => {
resetScrollState()
const blocks = [] as any[]
for (const block of blockActions.getBlocks()) {
if (block.type === "fileAttachment" && block.attachment.serverUrl) {
blocks.push({
...block,
attachment: {
id: block.attachment.id,
name: block.attachment.name,
type: block.attachment.type,
size: block.attachment.size,
serverUrl: block.attachment.serverUrl,
},
})
} else {
blocks.push(block)
}
}
const parts: BizUIMessage["parts"] = [
{
type: "data-block",
data: blockActions.getBlocks().map((b) => ({
type: b.type,
value: b.value,
})),
data: blocks,
},
]
@@ -121,7 +153,7 @@ const ChatInterfaceContent = () => {
parts.push({
type: "data-rich-text",
data: {
state: message.toJSON(),
state: JSON.stringify(message.toJSON()),
text: convertLexicalToMarkdown(editor),
},
})
@@ -145,13 +177,15 @@ const ChatInterfaceContent = () => {
const shouldShowScrollToBottom = hasMessages && !isAtBottom && !isLoadingHistory
return (
<div className="flex size-full flex-col">
<GlobalFileDropZone className="flex size-full flex-col">
<div className="flex min-h-0 flex-1 flex-col">
<AnimatePresence>
{!hasMessages && !isLoadingHistory ? (
<WelcomeScreen onSend={handleSendMessage} />
) : (
<ScrollArea
flex
scrollbarClassName="mb-40 mt-12"
ref={setScrollAreaRef}
rootClassName="flex-1"
viewportClassName={cn("pt-12 pb-32", error && "pb-48")}
@@ -161,9 +195,10 @@ const ChatInterfaceContent = () => {
<i className="i-mgc-loading-3-cute-re text-text size-8 animate-spin" />
</div>
) : (
<div className="mx-auto max-w-4xl px-6 py-8">
<div className="mx-auto w-full max-w-4xl px-6 py-8">
<Messages />
{status === "submitted" && <AIChatWaitingIndicator />}
{(status === "submitted" || status === "streaming") && <AIChatWaitingIndicator />}
</div>
)}
</ScrollArea>
@@ -172,24 +207,18 @@ const ChatInterfaceContent = () => {
</div>
{shouldShowScrollToBottom && (
<div className="absolute inset-x-0 bottom-32 z-10">
<div className="mx-auto max-w-[300px] p-6 pb-3">
<button
type="button"
onClick={scrollToBottom}
className="bg-accent/10 border-accent/20 shadow-accent/5 dark:shadow-accent/10 hover:bg-accent/15 backdrop-blur-background group relative w-full overflow-hidden rounded-xl border shadow-lg transition-colors"
>
{/* Glass effect overlay */}
<div className="from-accent/5 absolute inset-0 bg-gradient-to-r to-transparent" />
{/* Content */}
<div className="relative z-10 flex items-center justify-center gap-2 p-3">
<i className="i-mingcute-arrow-down-circle-fill text-accent size-3" />
<span className="text-accent text-sm font-medium">Scroll to Bottom</span>
</div>
</button>
</div>
<div className={clsx("absolute right-1/2 z-40 translate-x-1/2", "bottom-44")}>
<button
type="button"
onClick={() => resetScrollState()}
className={cn(
"center bg-background group flex size-8 items-center gap-2 rounded-full border transition-all",
"border-border/40",
"hover:border-border/60 active:scale-[0.98]",
)}
>
<i className="i-mingcute-arrow-down-line text-text/90" />
</button>
</div>
)}
@@ -197,13 +226,13 @@ const ChatInterfaceContent = () => {
className={clsx(
"absolute mx-auto duration-200 ease-in-out",
hasMessages && "inset-x-0 bottom-0 max-w-4xl px-6 pb-6",
!hasMessages && "inset-x-0 bottom-1/2 max-w-3xl translate-y-[calc(100%-2rem)] px-6 pb-6",
!hasMessages && "inset-x-0 bottom-0 max-w-3xl px-6 pb-6",
)}
>
{error && <CollapsibleError error={error} />}
<ChatInput onSend={handleSendMessage} variant={!hasMessages ? "minimal" : "default"} />
</div>
</div>
</GlobalFileDropZone>
)
}
@@ -216,5 +245,13 @@ export const ChatInterface = () => (
const Messages: FC = () => {
const messages = useMessages()
return messages.map((message) => <AIChatMessage key={message.id} message={message} />)
return (
<div className="relative flex min-w-0 flex-1 flex-col">
{messages.map((message) => (
<Suspense key={message.id}>
<AIChatMessage message={message} />
</Suspense>
))}
</div>
)
}
@@ -3,6 +3,7 @@ import { useCallback, useState } from "react"
import { useTranslation } from "react-i18next"
import { toast } from "sonner"
import { AIChatPanelStyle, setAIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai"
import { RelativeDay } from "~/components/ui/datetime"
import {
DropdownMenu,
@@ -23,6 +24,7 @@ import { downloadMarkdown, exportChatToMarkdown } from "~/modules/ai-chat/utils/
export const ChatMoreDropdown = () => {
const currentTitle = useCurrentTitle()
const currentChatId = useCurrentChatId()
const panelStyle = useAIChatPanelStyle()
const chatActions = useChatActions()
const { t } = useTranslation("ai")
@@ -91,6 +93,12 @@ export const ChatMoreDropdown = () => {
}
}, [chatActions, currentTitle, t])
const handleToggleMode = useCallback(() => {
const newStyle =
panelStyle === AIChatPanelStyle.Fixed ? AIChatPanelStyle.Floating : AIChatPanelStyle.Fixed
setAIChatPanelStyle(newStyle)
}, [panelStyle])
return (
<DropdownMenu onOpenChange={handleDropdownOpen}>
<DropdownMenuTrigger asChild>
@@ -129,8 +137,8 @@ export const ChatMoreDropdown = () => {
</p>
</div>
<div className="relative flex min-w-0 items-center">
<span className="text-text-secondary group-hover:text-text-secondary-dark ml-2 shrink-0 text-xs">
<RelativeDay date={session.createdAt} />
<span className="text-text-secondary group-hover:text-text-secondary-dark ml-2 shrink-0 cursor-help text-xs">
<RelativeDay date={session.updatedAt} />
</span>
<button
type="button"
@@ -147,14 +155,6 @@ export const ChatMoreDropdown = () => {
</div>
</DropdownMenuItem>
))}
<DropdownMenuSeparator className="my-1.5" />
<DropdownMenuItem
onClick={chatActions.newChat}
className="flex cursor-pointer items-center gap-2 rounded-md px-1 py-2.5"
>
<i className="i-mgc-add-cute-re size-4" />
<span className="text-sm">New Chat</span>
</DropdownMenuItem>
</>
) : (
<div className="flex flex-col items-center py-8 text-center">
@@ -169,6 +169,19 @@ export const ChatMoreDropdown = () => {
<i className="i-mgc-download-2-cute-re mr-2 size-4" />
<span>Export Chat</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleToggleMode}>
<i
className={`mr-2 size-4 ${panelStyle === AIChatPanelStyle.Fixed ? "i-mingcute-rectangle-vertical-line" : "i-mingcute-layout-right-line"}`}
/>
<span>
{panelStyle === AIChatPanelStyle.Fixed
? "Switch to Floating Panel"
: "Switch to Fixed Panel"}
</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
@@ -0,0 +1,139 @@
import { Input } from "@follow/components/ui/input/Input.js"
import { cn } from "@follow/utils/utils"
import { useCallback, useEffect, useState } from "react"
interface EditableTitleProps {
title?: string
onSave: (newTitle: string) => Promise<void>
className?: string
placeholder?: string
maxLength?: number
}
export const EditableTitle = ({
title = "",
onSave,
className,
placeholder = "Untitled Chat",
maxLength = 100,
}: EditableTitleProps) => {
const [isEditing, setIsEditing] = useState(false)
const [editValue, setEditValue] = useState("")
const [isSaving, setIsSaving] = useState(false)
const [originalTitle, setOriginalTitle] = useState("")
const [saveSuccess, setSaveSuccess] = useState(false)
const displayTitle = title || placeholder
const handleStartEdit = useCallback(() => {
setOriginalTitle(title)
setEditValue(title)
setIsEditing(true)
}, [title])
const handleSave = useCallback(async () => {
if (isSaving) return
const trimmedValue = editValue.trim()
// If no changes, just exit edit mode
if (trimmedValue === originalTitle) {
setIsEditing(false)
return
}
try {
setIsSaving(true)
await onSave(trimmedValue)
// Show success feedback briefly
setSaveSuccess(true)
setTimeout(() => setSaveSuccess(false), 2000)
setIsEditing(false)
} catch (error) {
console.error("Failed to save title:", error)
// Keep in edit mode on error to allow retry
} finally {
setIsSaving(false)
}
}, [editValue, originalTitle, onSave, isSaving])
const handleCancel = useCallback(() => {
setEditValue(originalTitle)
setIsEditing(false)
setIsSaving(false)
}, [originalTitle])
const handleKeyDown = useCallback(
(event: React.KeyboardEvent) => {
if (event.key === "Enter") {
event.preventDefault()
handleSave()
} else if (event.key === "Escape") {
event.preventDefault()
handleCancel()
}
},
[handleSave, handleCancel],
)
const handleBlur = useCallback(() => {
if (!isSaving) {
handleSave()
}
}, [handleSave, isSaving])
// Auto-focus input when entering edit mode
useEffect(() => {
if (isEditing) {
const input = document.activeElement as HTMLInputElement
if (input?.select) {
input.select()
}
}
}, [isEditing])
if (isEditing) {
return (
<div className="relative min-w-0 flex-1">
<Input
ref={(ref) => ref?.focus()}
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
maxLength={maxLength}
disabled={isSaving}
className={cn(
"text-text border-accent/50 focus:border-accent bg-transparent font-bold",
"h-auto p-2 text-base leading-none",
isSaving && "cursor-not-allowed opacity-60",
className,
)}
placeholder={placeholder}
/>
{isSaving && (
<div className="animate-in fade-in zoom-in-75 absolute right-2 top-1/2 -translate-y-1/2 duration-200">
<i className="i-mgc-loading-3-cute-re text-text-secondary size-4 animate-spin" />
</div>
)}
</div>
)
}
return (
<div
className={cn("group flex min-w-0 flex-1 cursor-pointer items-center gap-2", className)}
onClick={handleStartEdit}
>
<h1 className="text-text truncate font-bold transition-opacity group-hover:opacity-80">
<span className="animate-mask-left-to-right [--animation-duration:1s]">{displayTitle}</span>
</h1>
{saveSuccess && (
<i className="i-mgc-check-cute-re text-green animate-in fade-in zoom-in-50 size-4 transition-all duration-300" />
)}
<i className="i-mgc-edit-cute-re text-text-secondary group-hover:animate-in group-hover:fade-in group-hover:zoom-in-75 size-4 opacity-0 transition-all duration-150 hover:opacity-100 group-hover:opacity-60" />
</div>
)
}
@@ -0,0 +1,120 @@
import { cn } from "@follow/utils"
import * as HoverCard from "@radix-ui/react-hover-card"
import { m } from "motion/react"
import type { FC } from "react"
import * as React from "react"
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
export const ImageThumbnail: FC<{
previewUrl: string
originalUrl: string
alt: string
filename: string
className?: string
}> = ({ previewUrl, originalUrl, alt, filename, className }) => {
const [imageError, setImageError] = React.useState(false)
const { present } = useModalStack()
return (
<HoverCard.Root openDelay={300} closeDelay={100}>
<HoverCard.Trigger
className="cursor-pointer"
onClick={() =>
present({
max: true,
title: "Preview Image",
content: () => (
<div className="flex max-h-full max-w-full items-center justify-center">
<img src={originalUrl} className="max-h-full max-w-full" />
</div>
),
})
}
>
<ImageThumbnailInner className={className} src={previewUrl} alt={alt} />
</HoverCard.Trigger>
<HoverCard.Portal>
<HoverCard.Content
className="bg-material-thick border-border w-fit rounded-md border shadow-lg"
sideOffset={8}
>
<div className="relative overflow-hidden rounded-md">
{imageError ? (
<div className="bg-fill-secondary border-border flex h-32 w-40 items-center justify-center rounded-md border">
<div className="text-text-tertiary flex flex-col items-center gap-2">
<i className="i-mgc-photo-album-cute-fi size-6" />
<span className="text-xs">{filename}</span>
</div>
</div>
) : (
<m.img
src={previewUrl}
alt={alt}
onError={() => setImageError(true)}
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.2 }}
className="max-h-[300px] max-w-[400px] rounded-md"
/>
)}
</div>
</HoverCard.Content>
</HoverCard.Portal>
</HoverCard.Root>
)
}
export const ImageThumbnailInner: React.FC<{
src: string
alt: string
className?: string
}> = ({ src, alt, className }) => {
const [imageError, setImageError] = React.useState(false)
const [imageLoaded, setImageLoaded] = React.useState(false)
const handleError = React.useCallback(() => {
setImageError(true)
}, [])
const handleLoad = React.useCallback(() => {
setImageLoaded(true)
}, [])
if (imageError) {
return (
<div
className={cn(
"bg-fill-secondary border-border flex items-center justify-center border",
className,
)}
>
<i className="i-mgc-photo-album-cute-re text-text-tertiary size-3" />
</div>
)
}
return (
<div className={cn("relative overflow-hidden", className)}>
{!imageLoaded && (
<div
className={
"bg-fill-secondary border-border absolute inset-0 flex items-center justify-center border"
}
>
<i className="i-mgc-loading-3-cute-re text-text-tertiary size-3 animate-spin" />
</div>
)}
<m.img
src={src}
alt={alt}
onError={handleError}
onLoad={handleLoad}
initial={{ opacity: 0 }}
animate={{ opacity: imageLoaded ? 1 : 0 }}
transition={{ duration: 0.2 }}
className={"size-full object-cover"}
/>
</div>
)
}
@@ -1,95 +1,66 @@
import type { EditorState, LexicalEditor } from "lexical"
import { m } from "motion/react"
import { AnimatePresence, m } from "motion/react"
import { useTranslation } from "react-i18next"
import { useAISettingValue } from "~/atoms/settings/ai"
import { AISpline } from "~/modules/ai-chat/components/3d-models/AISpline"
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
import { useMainEntryId } from "../../hooks/useMainEntryId"
import { DefaultWelcomeContent, EntrySummaryCard } from "../welcome"
interface WelcomeScreenProps {
onSend: (message: EditorState | string, editor: LexicalEditor | null) => void
}
const DEFAULT_SHORTCUTS = [
"Generate today daily report",
"Analyze my reading patterns",
"Summarize recent articles",
"What happened today",
]
export const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => {
const { t } = useTranslation("ai")
const aiSettings = useAISettingValue()
const settingModalPresent = useSettingModal()
const mainEntryId = useMainEntryId()
const hasCustomPrompt = aiSettings.personalizePrompt?.trim()
const hasEntryContext = !!mainEntryId
const enabledShortcuts = aiSettings.shortcuts?.filter((shortcut) => shortcut.enabled) || []
return (
<div className="flex flex-1 flex-col items-center justify-center px-6">
<div className="w-full max-w-2xl space-y-8">
<div className="space-y-6 text-center">
<div className="flex flex-1 flex-col items-center px-6 pb-32">
<div className="flex w-full max-w-2xl flex-1 flex-col justify-center space-y-8">
{/* Header Section - Always Present */}
<m.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
className="space-y-6 text-center"
>
<div className="mx-auto size-16">
<AISpline />
</div>
<div className="flex flex-col gap-2">
<h1 className="text-text text-2xl font-semibold">{APP_NAME} AI</h1>
<p className="text-text-secondary text-balance text-sm">{t("welcome_description")}</p>
<p className="text-text-secondary text-balance text-sm">
{hasEntryContext
? t("welcome_description_contextual", {
defaultValue: "Let's discuss this entry together",
})
: t("welcome_description")}
</p>
</div>
</div>
</m.div>
<div className="relative mx-auto h-36 max-w-2xl" />
<div className="relative flex flex-wrap items-center justify-center gap-2">
{/* Custom shortcuts first */}
{enabledShortcuts.slice(0, 6).map((shortcut, index) => (
<m.button
key={shortcut.id}
className="bg-material-medium hover:bg-material-thick border-border text-text-secondary hover:text-text whitespace-nowrap rounded-full border px-4 py-2 text-xs transition-colors"
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, y: 10 }}
transition={{ delay: index * 0.1 }}
onClick={() => onSend(shortcut.prompt, null)}
title={shortcut.hotkey ? `${shortcut.name} (${shortcut.hotkey})` : shortcut.name}
>
{shortcut.name}
</m.button>
))}
{/* Default suggestions if no custom shortcuts or to fill remaining space */}
{enabledShortcuts.length < 4 &&
DEFAULT_SHORTCUTS.slice(0, 4 - enabledShortcuts.length).map((suggestion, index) => (
<m.button
key={suggestion}
className="bg-material-medium hover:bg-material-thick border-border text-text-secondary hover:text-text whitespace-nowrap rounded-full border px-4 py-2 text-xs transition-colors"
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, y: 10 }}
transition={{ delay: (enabledShortcuts.length + index) * 0.1 }}
onClick={() => onSend(suggestion, null)}
>
{suggestion}
</m.button>
))}
{hasCustomPrompt && (
<div className="bg-material-medium border-border absolute -bottom-4 mx-auto mt-2 w-full max-w-2xl translate-y-full rounded-lg border p-3 text-left">
<div className="flex items-center justify-between">
<div className="text-text-secondary mb-1 text-xs font-medium">Personal Prompt:</div>
<button
type="button"
onClick={() => settingModalPresent("ai")}
className="text-text-tertiary hover:text-text-secondary flex size-5 items-center justify-center rounded transition-colors"
title="Edit in Settings"
>
<i className="i-mgc-edit-cute-re size-3.5" />
</button>
</div>
<p className="text-text-secondary text-xs leading-relaxed">
{aiSettings.personalizePrompt}
</p>
</div>
)}
{/* Dynamic Content Area */}
<div className="relative flex items-start justify-center">
<AnimatePresence mode="wait">
{hasEntryContext ? (
<EntrySummaryCard
key="entry-summary"
entryId={mainEntryId}
onSend={(message) => onSend(message, null)}
/>
) : (
<DefaultWelcomeContent
key="default-welcome"
onSend={onSend}
shortcuts={enabledShortcuts}
/>
)}
</AnimatePresence>
</div>
</div>
</div>
@@ -1,5 +1,5 @@
import { createDefaultLexicalEditor } from "@follow/components/ui/lexical-rich-editor/editor.js"
import { stopPropagation } from "@follow/utils"
import { cn, stopPropagation, thenable } from "@follow/utils"
import type { UIDataTypes, UIMessage } from "ai"
import type { LexicalEditor, SerializedEditorState } from "lexical"
import { m } from "motion/react"
@@ -11,6 +11,7 @@ import { useEditingMessageId, useSetEditingMessageId } from "~/modules/ai-chat/a
import { useChatActions } from "~/modules/ai-chat/store/hooks"
import type { BizUIMetadata, BizUITools } from "~/modules/ai-chat/store/types"
import { MentionPlugin } from "../../editor"
import type { RichTextPart } from "../../types/ChatSession"
import { convertLexicalToMarkdown } from "../../utils/lexical-markdown"
import { AIMessageParts } from "./AIMessageParts"
@@ -30,6 +31,9 @@ interface AIChatMessageProps {
}
export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message }) => {
if (message.parts.length === 0) {
throw thenable
}
const chatActions = useChatActions()
const messageId = message.id
@@ -56,7 +60,7 @@ export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message
break
}
case "data-rich-text": {
lexicalEditor ||= createDefaultLexicalEditor()
lexicalEditor ||= createDefaultLexicalEditor([MentionPlugin])
lexicalEditor.setEditorState(
lexicalEditor.parseEditorState((part as RichTextPart).data.state),
)
@@ -122,28 +126,13 @@ export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message
}, [chatActions, messageId])
return (
<m.div
<div
onContextMenu={stopPropagation}
className={`flex ${message.role === "user" ? "justify-end" : "justify-start"} group`}
initial={{
opacity: 0,
y: 20,
scale: 0.95,
}}
animate={{
opacity: 1,
y: 0,
scale: 1,
}}
transition={{
duration: 0.3,
ease: [0.25, 0.46, 0.45, 0.94],
delay: message.role === "user" ? 0.1 : 0.2,
}}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<div className="relative flex max-w-[calc(100%-1rem)] flex-col gap-2">
<div className="text-text relative flex max-w-[calc(100%-1rem)] flex-col gap-2">
{/* Show editable message if editing */}
{isEditing && isUserMessage ? (
<EditableMessage
@@ -156,46 +145,22 @@ export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message
<>
{/* Normal message display */}
<div
className={`rounded-xl px-3 py-2.5 backdrop-blur-sm ${
message.role === "user"
? "dark:bg-accent/30 bg-accent/90 text-white"
: "text-text border border-gray-200/60 bg-gradient-to-br from-white/80 to-gray-50/90 shadow-lg shadow-black/5 dark:border-zinc-700/60 dark:from-zinc-800/80 dark:to-zinc-900/90 dark:shadow-black/20"
}`}
>
{message.role === "assistant" && (
<div className="mb-2 flex items-center gap-2">
<div className="from-folo flex size-5 items-center justify-center rounded-full bg-gradient-to-r to-red-500 shadow-sm">
<i className="i-mgc-ai-cute-fi size-3 text-white" />
</div>
<span className="text-text-secondary text-xs font-medium">{APP_NAME} AI</span>
</div>
className={cn(
`text-text backdrop-blur-sm`,
message.role === "user" && "rounded-2xl bg-gray-100 px-4 py-2.5 dark:bg-gray-800",
)}
<div
className={`select-text gap-2 text-[0.95rem] ${
message.role === "user" ? "text-white" : "text-text"
} flex flex-col`}
>
>
<div className={`flex select-text flex-col gap-2 text-sm`}>
<AIMessageParts message={message} />
</div>
{message.metadata?.finishTime && (
<div
className={`mt-2 text-xs ${message.role === "user" ? "text-text-secondary-dark text-right" : "text-text-tertiary"}`}
>
{new Date(message.metadata.finishTime).toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
})}
</div>
)}
</div>
{/* Action buttons */}
<m.div
className={`absolute bottom-0 flex ${message.role === "user" ? "right-0" : "left-0"} gap-1`}
initial={{ opacity: 0, scale: 0.8 }}
className={`absolute bottom-1 flex ${message.role === "user" ? "right-0" : "left-0"} gap-1`}
initial={{ opacity: 0 }}
animate={{
opacity: isHovered ? 1 : 0,
scale: isHovered ? 1 : 0.8,
}}
transition={{ duration: 0.2, ease: "easeOut" }}
>
@@ -204,7 +169,7 @@ export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message
<button
type="button"
onClick={handleEdit}
className="text-text-tertiary hover:bg-fill hover:text-text flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
className="text-text hover:bg-fill-secondary flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
title="Edit message"
>
<i className="i-mgc-edit-cute-re size-3" />
@@ -213,7 +178,7 @@ export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message
<button
type="button"
onClick={handleRetry}
className="text-text-tertiary hover:bg-fill hover:text-text flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
className="text-text hover:bg-fill-secondary flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
title="Retry"
>
<i className="i-mgc-refresh-2-cute-re size-3" />
@@ -224,7 +189,7 @@ export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message
<button
type="button"
onClick={handleCopy}
className="text-text-tertiary hover:bg-fill hover:text-text flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
className="text-text hover:bg-fill-tertiary flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
title="Copy message"
>
<i className="i-mgc-copy-2-cute-re size-3" />
@@ -237,14 +202,22 @@ export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message
</>
)}
</div>
</m.div>
</div>
)
})
export const AIChatWaitingIndicator: React.FC = () => {
return (
<span className="text-text-tertiary text-xs">
<i className="i-mgc-loading-3-cute-re size-3 animate-spin" />
</span>
<m.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 8 }}
transition={{ duration: 0.2, ease: [0.25, 0.46, 0.45, 0.94] }}
>
<div className="text-text-secondary flex items-center gap-2 rounded-full text-xs">
<i className="i-mgc-loading-3-cute-re size-3 animate-spin" />
<span className="font-medium">Thinking…</span>
</div>
</m.div>
)
}
@@ -0,0 +1,119 @@
import { cn } from "@follow/utils/utils"
import * as React from "react"
import type { AIChatContextBlock } from "~/modules/ai-chat/store/types"
import {
getBlockIcon,
getBlockLabel,
getBlockStyles,
getFileDisplayContent,
isImageAttachment,
} from "./ai-block-constants"
import { EntryTitle, FeedTitle } from "./BlockTitleComponents"
import { ImageThumbnail } from "./ImageThumbnail"
interface AIDataBlockItemProps {
block: AIChatContextBlock
index: number
}
/**
* Gets the display content for a context block
*/
const getDisplayContent = (block: AIChatContextBlock): React.ReactNode => {
switch (block.type) {
case "mainEntry":
case "referEntry": {
return <EntryTitle entryId={block.value} fallback={block.value} />
}
case "referFeed": {
return <FeedTitle feedId={block.value} fallback={block.value} />
}
case "selectedText": {
return `"${block.value}"`
}
case "fileAttachment": {
if (!block.attachment) {
return "[File: Unknown]"
}
return getFileDisplayContent(block.attachment)
}
default: {
return ""
}
}
}
/**
* Renders the appropriate icon or image thumbnail for a block
*/
const BlockIcon: React.FC<{
block: AIChatContextBlock
styles: ReturnType<typeof getBlockStyles>
}> = React.memo(({ block, styles }) => {
// Handle image thumbnails for file attachments
if (block.type === "fileAttachment" && block.attachment && isImageAttachment(block)) {
return (
<div
className={cn(
"flex size-5 flex-shrink-0 items-center justify-center rounded-md",
styles.icon,
)}
>
<ImageThumbnail attachment={block.attachment} />
</div>
)
}
const iconClass = getBlockIcon(block)
return (
<div
className={cn(
"flex size-5 flex-shrink-0 items-center justify-center rounded-md",
styles.icon,
)}
>
<i className={cn("size-3", iconClass)} />
</div>
)
})
BlockIcon.displayName = "BlockIcon"
/**
* Individual block item component with optimized rendering and animations
*/
export const AIDataBlockItem: React.FC<AIDataBlockItemProps> = React.memo(({ block }) => {
const styles = React.useMemo(() => getBlockStyles(block.type), [block.type])
const label = React.useMemo(() => getBlockLabel(block.type), [block.type])
const displayContent = React.useMemo(() => getDisplayContent(block), [block])
return (
<div
key={block.id}
className={cn(
"inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5",
"border bg-gradient-to-r backdrop-blur-sm",
styles.container,
)}
>
<BlockIcon block={block} styles={styles} />
{/* Label and content */}
<div className="flex min-w-0 items-center gap-1">
<span className={cn("text-xs font-medium", styles.label)}>{label}</span>
<span className="text-text-secondary text-xs">·</span>
<span
className="text-text max-w-32 truncate text-xs font-medium"
title={typeof displayContent === "string" ? displayContent : undefined}
>
{displayContent}
</span>
</div>
</div>
)
})
AIDataBlockItem.displayName = "AIDataBlockItem"
@@ -1,136 +1,21 @@
import { useEntry } from "@follow/store/entry/hooks"
import { useFeedById } from "@follow/store/feed/hooks"
import { cn } from "@follow/utils/utils"
import { m } from "motion/react"
import * as React from "react"
import type { AIChatContextBlock } from "~/modules/ai-chat/store/types"
import { AIDataBlockItem } from "./AIDataBlockItem"
interface AIDataBlockPartProps {
blocks: AIChatContextBlock[]
}
// Helper components for displaying titles
const EntryTitle: React.FC<{ entryId?: string; fallback: string }> = ({ entryId, fallback }) => {
const entryTitle = useEntry(entryId!, (e) => e?.title)
if (!entryId || !entryTitle) {
return <span className="text-text-tertiary">{fallback}</span>
}
return <span>{entryTitle}</span>
}
const FeedTitle: React.FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => {
const feed = useFeedById(feedId, (feed) => ({ title: feed?.title }))
if (!feedId || !feed) {
return <span className="text-text-tertiary">{fallback}</span>
}
return <span>{feed.title}</span>
}
// Data Block Component
/**
* Main component for rendering AI chat context blocks
* Displays various types of context (entries, feeds, text, files) with animations
*/
export const AIDataBlockPart: React.FC<AIDataBlockPartProps> = React.memo(({ blocks }) => {
const getBlockIcon = (type: AIChatContextBlock["type"]) => {
switch (type) {
case "mainEntry": {
return "i-mgc-star-cute-fi"
}
case "referEntry": {
return "i-mgc-paper-cute-fi"
}
case "referFeed": {
return "i-mgc-rss-cute-fi"
}
case "selectedText": {
return "i-mgc-quill-pen-cute-re"
}
default: {
return "i-mgc-paper-cute-fi"
}
}
}
const getBlockLabel = (type: AIChatContextBlock["type"]) => {
switch (type) {
case "mainEntry": {
return "Current"
}
case "referEntry": {
return "Ref"
}
case "referFeed": {
return "Feed"
}
case "selectedText": {
return "Text"
}
default: {
return ""
}
}
}
const getBlockStyles = (type: AIChatContextBlock["type"]) => {
switch (type) {
case "mainEntry": {
return {
container: "from-orange/5 to-orange/10 border-orange/20 hover:border-orange/30",
icon: "bg-orange/10 text-orange",
label: "text-orange",
}
}
case "referEntry": {
return {
container: "from-blue/5 to-blue/10 border-blue/20 hover:border-blue/30",
icon: "bg-blue/10 text-blue",
label: "text-blue",
}
}
case "referFeed": {
return {
container: "from-green/5 to-green/10 border-green/20 hover:border-green/30",
icon: "bg-green/10 text-green",
label: "text-green",
}
}
case "selectedText": {
return {
container: "from-purple/5 to-purple/10 border-purple/20 hover:border-purple/30",
icon: "bg-purple/10 text-purple",
label: "text-purple",
}
}
default: {
return {
container: "from-gray/5 to-gray/10 border-gray/20 hover:border-gray/30",
icon: "bg-gray/10 text-gray",
label: "text-gray",
}
}
}
}
const getDisplayContent = (block: AIChatContextBlock) => {
switch (block.type) {
case "mainEntry":
case "referEntry": {
return <EntryTitle entryId={block.value} fallback={block.value} />
}
case "referFeed": {
return <FeedTitle feedId={block.value} fallback={block.value} />
}
case "selectedText": {
return `"${block.value}"`
}
default: {
return block.value
}
}
}
if (!blocks || blocks.length === 0) {
// Early return for empty blocks
if (!blocks?.length) {
return null
}
@@ -148,50 +33,10 @@ export const AIDataBlockPart: React.FC<AIDataBlockPartProps> = React.memo(({ blo
<span className="text-xs font-medium">Context:</span>
</div>
{/* Blocks */}
{blocks.map((block, index) => {
const styles = getBlockStyles(block.type)
return (
<m.div
key={block.id}
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{
duration: 0.3,
delay: index * 0.05,
ease: [0.25, 0.1, 0.25, 1],
}}
className={cn(
"inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5",
"border bg-gradient-to-r backdrop-blur-sm transition-all duration-200",
"hover:scale-105 hover:shadow-md",
styles.container,
)}
>
{/* Icon */}
<div
className={cn(
"flex size-5 flex-shrink-0 items-center justify-center rounded-md",
styles.icon,
)}
>
<i className={cn("size-3", getBlockIcon(block.type))} />
</div>
{/* Label and content */}
<div className="flex min-w-0 items-center gap-1">
<span className={cn("text-xs font-medium", styles.label)}>
{getBlockLabel(block.type)}
</span>
<span className="text-text-secondary text-xs">·</span>
<span className="text-text max-w-32 truncate text-xs font-medium">
{getDisplayContent(block)}
</span>
</div>
</m.div>
)
})}
{/* Render individual block items */}
{blocks.map((block, index) => (
<AIDataBlockItem key={block.id} block={block} index={index} />
))}
</div>
)
})
@@ -13,7 +13,7 @@ import {
useSyncExternalStore,
} from "react"
import { ShikiHighLighter } from "~/components/ui/code-highlighter"
import { MemoizedShikiCode } from "~/components/ui/code-highlighter"
import { MarkdownLink } from "~/components/ui/markdown/renderers/MarkdownLink"
import { usePeekModal } from "~/hooks/biz/usePeekModal"
@@ -26,6 +26,11 @@ interface BufferConfig {
maxBufferTime: number
semanticTimeout: number
emergencyTimeout: number
// Ensure a cool-down between flushes to avoid overlapping animations
minFlushInterval: number
// Initial burst controls for faster first paint
initialMinBufferSize: number
initialMaxWait: number
}
// Buffer endpoint patterns by priority
@@ -118,12 +123,21 @@ class StreamingMessageBuffer {
const now = Date.now()
const timeSinceLastFlush = now - this.lastFlushTime
// Accelerate first paint: show something quickly at the very beginning
if (this.displayedText.length === 0) {
if (bufferedText.length >= this.config.initialMinBufferSize) return true
if (timeSinceLastFlush > this.config.initialMaxWait && bufferedText.length > 0) return true
}
// Emergency timeout - always flush
if (timeSinceLastFlush > this.config.emergencyTimeout) return true
// Buffer size limit - prevent OOM
if (bufferedText.length > this.config.maxBufferSize) return true
// Avoid overlapping animations by enforcing a minimal interval between flushes
if (timeSinceLastFlush < this.config.minFlushInterval) return false
// Minimum buffer size not met
if (bufferedText.length < this.config.minBufferSize) return false
@@ -225,7 +239,13 @@ const BUFFER_CONFIG = {
maxBufferSize: 10000, // Prevent OOM with 10KB limit
maxBufferTime: 100,
semanticTimeout: 300,
emergencyTimeout: 500,
// Keep emergency slightly larger than animation duration to prevent overlap
emergencyTimeout: 1200,
// Match animation duration in animatedPlugin (duration-1000) with a small buffer
minFlushInterval: 1000,
// Ensure very fast first paint
initialMinBufferSize: 2,
initialMaxWait: 80,
} as const
// Hook to use streaming text buffer
@@ -327,15 +347,18 @@ export const AIMarkdownStreamingMessage = memo(
prose-li:list-disc prose-li:marker:text-accent prose-hr:border-border prose-hr:mx-8`
// Use intelligent streaming buffer for semantic text rendering
const bufferedText = useStreamingTextBuffer(text, isProcessing ?? false)
const bufferedTextRaw = useStreamingTextBuffer(text, isProcessing ?? false)
// Use deferred value for lower priority rendering during streaming
const deferredText = useDeferredValue(bufferedText)
const deferredText = useDeferredValue(bufferedTextRaw)
// For small snippets (common at the very beginning), avoid deferring so text appears instantly
const effectiveBufferedText = bufferedTextRaw.length < 20 ? bufferedTextRaw : deferredText
// Use our optimized parsing hook with buffered text
const parsedContent = useThrottledMarkdownParsing(
// During streaming, use deferred buffered text for optimal rendering
isProcessing ? deferredText : text,
// During streaming, use non-deferred value for tiny snippets to improve first paint
isProcessing ? effectiveBufferedText : text,
isProcessing ?? false,
)
@@ -363,7 +386,7 @@ export const AIMarkdownStreamingMessage = memo(
}
// Default comparison
return false
return prevProps === nextProps
},
)
@@ -411,7 +434,7 @@ function baseAIMarkdownParser(content: string, isProcessing: boolean) {
const language = className.replace("language-", "")
const code = children
return <ShikiHighLighter code={code} language={language} showCopy />
return <MemoizedShikiCode code={code} language={language} showCopy />
}
}
@@ -1,8 +1,6 @@
import "@xyflow/react/dist/style.css"
import type { ToolUIPart } from "ai"
import type { SerializedEditorState } from "lexical"
import { m } from "motion/react"
import * as React from "react"
import type {
@@ -21,7 +19,6 @@ import {
AIDisplayFeedsPart,
AIDisplaySubscriptionsPart,
} from "../displays"
// import { AIDisplayFlowPart } from "../displays/AIDisplayFlowPart"
import { AIDataBlockPart } from "./AIDataBlockPart"
import { AIMarkdownMessage, AIMarkdownStreamingMessage } from "./AIMarkdownMessage"
import { AIRichTextMessage } from "./AIRichTextMessage"
@@ -34,32 +31,8 @@ const LazyAIDisplayFlowPart = React.lazy(() =>
interface MessagePartsProps {
message: BizUIMessage
}
const ThinkingIndicator: React.FC = () => {
return (
<div className="flex w-24 items-center">
<m.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="relative inline-block"
>
<span className="from-text-tertiary via-text to-text-tertiary animate-[shimmer_5s_linear_infinite] bg-gradient-to-r bg-[length:200%_100%] bg-clip-text text-sm font-medium text-transparent">
Thinking...
</span>
</m.div>
</div>
)
}
export const AIMessageParts: React.FC<MessagePartsProps> = React.memo(({ message }) => {
if (!message.parts || message.parts.length === 0) {
// In AI SDK v5, messages should always have parts
if (message.role === "assistant") {
return <ThinkingIndicator />
}
return null
}
const isUser = message.role === "user"
return message.parts.map((part, index) => {
const partKey = `${message.id}-${index}`
@@ -74,7 +47,7 @@ export const AIMessageParts: React.FC<MessagePartsProps> = React.memo(({ message
className={"text-text"}
/>
)
return <AIMarkdownMessage key={partKey} text={part.text} className={"text-white"} />
return <AIMarkdownMessage key={partKey} text={part.text} />
}
case "data-block": {
@@ -85,8 +58,8 @@ export const AIMessageParts: React.FC<MessagePartsProps> = React.memo(({ message
return (
<AIRichTextMessage
key={partKey}
data={part.data as { state: SerializedEditorState; text: string }}
className={isUser ? "text-white" : "text-text"}
data={part.data as { state: string; text: string }}
className="text-text"
/>
)
}
@@ -108,7 +81,7 @@ export const AIMessageParts: React.FC<MessagePartsProps> = React.memo(({ message
case "tool-displayFlowChart": {
const loadingElement = (
<div className="my-2 flex aspect-[4/3] w-full items-center justify-center">
<div className="my-2 flex aspect-[4/3] w-[calc(var(--ai-chat-layout-width,65ch)-120px)] max-w-prose items-center justify-center">
<div className="flex flex-col items-center gap-4">
<div className="flex items-center gap-2">
<i className="i-mgc-loading-3-cute-re text-text-secondary size-4 animate-spin" />
@@ -9,6 +9,7 @@ import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin"
import type { SerializedEditorState } from "lexical"
import * as React from "react"
import { FileAttachmentNode } from "../../editor"
import { MentionNode } from "../../editor/plugins/mention/MentionNode"
function onError(error: Error) {
@@ -17,7 +18,7 @@ function onError(error: Error) {
interface AIRichTextMessageProps {
data: {
state: SerializedEditorState
state: SerializedEditorState | string // Serialized editor state as a JSON string
text: string
}
className?: string
@@ -25,15 +26,17 @@ interface AIRichTextMessageProps {
export const AIRichTextMessage: React.FC<AIRichTextMessageProps> = React.memo(
({ data, className }) => {
const initialConfig: InitialConfigType = {
namespace: "AIRichTextDisplay",
theme: defaultLexicalTheme,
onError,
editable: false, // Read-only mode
editorState: JSON.stringify(data.state),
nodes: [...LexicalRichEditorNodes, MentionNode],
let initialConfig: InitialConfigType = null!
if (!initialConfig) {
initialConfig = {
namespace: "AIRichTextDisplay",
theme: defaultLexicalTheme,
onError,
editable: false,
editorState: typeof data.state === "object" ? JSON.stringify(data.state) : data.state,
nodes: [...LexicalRichEditorNodes, MentionNode, FileAttachmentNode],
}
}
return (
<div className={cn("text-text relative text-sm", className)}>
<LexicalComposer initialConfig={initialConfig}>
@@ -0,0 +1,45 @@
import { useEntry } from "@follow/store/entry/hooks"
import { useFeedById } from "@follow/store/feed/hooks"
import * as React from "react"
interface TitleProps {
fallback: string
}
interface EntryTitleProps extends TitleProps {
entryId?: string
}
interface FeedTitleProps extends TitleProps {
feedId?: string
}
/**
* Displays entry title with fallback handling
*/
export const EntryTitle: React.FC<EntryTitleProps> = React.memo(({ entryId, fallback }) => {
const entryTitle = useEntry(entryId!, (e) => e?.title)
if (!entryId || !entryTitle) {
return <span className="text-text-tertiary">{fallback}</span>
}
return <span title={entryTitle}>{entryTitle}</span>
})
EntryTitle.displayName = "EntryTitle"
/**
* Displays feed title with fallback handling
*/
export const FeedTitle: React.FC<FeedTitleProps> = React.memo(({ feedId, fallback }) => {
const feed = useFeedById(feedId, (feed) => ({ title: feed?.title }))
if (!feedId || !feed?.title) {
return <span className="text-text-tertiary">{fallback}</span>
}
return <span title={feed.title}>{feed.title}</span>
})
FeedTitle.displayName = "FeedTitle"
@@ -0,0 +1,70 @@
import { cn } from "@follow/utils/utils"
import * as React from "react"
import type { FileAttachment } from "~/modules/ai-chat/store/types"
import { getImageUrl } from "./ai-block-constants"
interface ImageThumbnailProps {
attachment: FileAttachment
className?: string
fallbackIcon?: string
}
/**
* A robust image thumbnail component with proper error handling and fallback states
*/
export const ImageThumbnail: React.FC<ImageThumbnailProps> = React.memo(
({
attachment,
className = "size-3 rounded object-cover",
fallbackIcon = "i-mgc-pic-cute-re",
}) => {
const [hasError, setHasError] = React.useState(false)
const [isLoading, setIsLoading] = React.useState(true)
const imageUrl = React.useMemo(() => getImageUrl(attachment), [attachment])
const handleError = React.useCallback(() => {
setHasError(true)
setIsLoading(false)
}, [])
const handleLoad = React.useCallback(() => {
setIsLoading(false)
}, [])
// Reset error state when imageUrl changes
React.useEffect(() => {
if (imageUrl) {
setHasError(false)
setIsLoading(true)
}
}, [imageUrl])
// If no image URL or there was an error, show fallback icon
if (!imageUrl || hasError) {
return <i className={cn("size-3", fallbackIcon)} />
}
return (
<div className="relative">
<img
src={imageUrl}
alt={attachment.name}
className={cn(className, isLoading && "opacity-50")}
onError={handleError}
onLoad={handleLoad}
loading="lazy"
/>
{isLoading && (
<div className="absolute inset-0 flex items-center justify-center">
<i className="i-mgc-loading-3-cute-re size-2 animate-spin opacity-50" />
</div>
)}
</div>
)
},
)
ImageThumbnail.displayName = "ImageThumbnail"
@@ -0,0 +1,17 @@
import { m } from "motion/react"
export const ThinkingIndicator: React.FC = () => {
return (
<div className="flex w-24 items-center">
<m.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="relative inline-block"
>
<span className="from-text-tertiary via-text to-text-tertiary animate-[shimmer_5s_linear_infinite] bg-gradient-to-r bg-[length:200%_100%] bg-clip-text text-sm font-medium text-transparent">
Thinking...
</span>
</m.div>
</div>
)
}
@@ -1,10 +1,3 @@
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@follow/components/ui/accordion/index.js"
import { JsonHighlighter } from "@follow/components/ui/json-highlighter/index.js"
import type { ToolUIPart } from "ai"
import { getToolName } from "ai"
import * as React from "react"
@@ -16,46 +9,24 @@ interface ToolInvocationComponentProps {
export const ToolInvocationComponent: React.FC<ToolInvocationComponentProps> = React.memo(
({ part }) => {
const toolName = getToolName(part)
const hasError = "errorText" in part && part.errorText
return (
<div className="bg-material-medium border-border size-full min-w-0 max-w-prose rounded-lg border text-left">
<div
className={`min-w-0 max-w-prose text-left ${hasError ? "border-red/30" : "border-border"}`}
>
<div className="w-[9999px] max-w-[calc(var(--ai-chat-layout-width,65ch)_-120px)]" />
<Accordion type="single" collapsible>
<AccordionItem value="tool-invocation">
<AccordionTrigger className="flex w-full cursor-pointer items-center gap-3 py-1 pl-4 pr-2 hover:no-underline">
{/* Tool Info */}
<div className="flex h-6 min-w-0 flex-1 items-center">
<div className="flex items-center gap-2 text-xs">
<i className="i-mingcute-tool-line" />
<span className="text-text-secondary">Tool Calling:</span>
<h4 className="text-text truncate font-medium">{toolName}</h4>
</div>
</div>
</AccordionTrigger>
<AccordionContent className="min-w-0 border-t border-zinc-200/50 bg-zinc-50/50 p-4 dark:border-zinc-700/50 dark:bg-zinc-800/50">
<div className="space-y-3">
{"input" in part && (
<div>
<div className="text-text-tertiary mb-2 text-xs font-semibold uppercase tracking-wide">
Arguments
</div>
<JsonHighlighter json={JSON.stringify(part.input, null, 2)} />
</div>
)}
{"output" in part && (
<div>
<div className="text-text-tertiary mb-2 text-xs font-semibold uppercase tracking-wide">
Result
</div>
<JsonHighlighter json={JSON.stringify(part.output, null, 2)} />
</div>
)}
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
<div className="flex h-6 min-w-0 flex-1 items-center">
<div className="flex items-center gap-2 text-xs">
<i className={hasError ? "i-mgc-close-cute-re text-red" : "i-mingcute-tool-line"} />
<span className="text-text-secondary">
{hasError ? "Tool Failed:" : "Tool Calling:"}
</span>
<h4 className={`truncate font-medium ${hasError ? "text-red" : "text-text"}`}>
{toolName}
</h4>
</div>
</div>
</div>
)
},
@@ -0,0 +1,128 @@
import type { AIChatContextBlock, FileAttachment } from "~/modules/ai-chat/store/types"
import {
getFileCategoryFromMimeType,
getFileIconName,
} from "~/modules/ai-chat/utils/file-validation"
/**
* Block style configurations for different context block types
*/
export const BLOCK_STYLES = {
mainEntry: {
container: "from-orange/5 to-orange/10 border-orange/20 hover:border-orange/30",
icon: "bg-orange/10 text-orange",
label: "text-orange",
},
referEntry: {
container: "from-blue/5 to-blue/10 border-blue/20 hover:border-blue/30",
icon: "bg-blue/10 text-blue",
label: "text-blue",
},
referFeed: {
container: "from-green/5 to-green/10 border-green/20 hover:border-green/30",
icon: "bg-green/10 text-green",
label: "text-green",
},
selectedText: {
container: "from-purple/5 to-purple/10 border-purple/20 hover:border-purple/30",
icon: "bg-purple/10 text-purple",
label: "text-purple",
},
fileAttachment: {
container: "from-pink/5 to-pink/10 border-pink/20 hover:border-pink/30",
icon: "bg-pink/10 text-pink",
label: "text-pink",
},
} as const
/**
* Default fallback styles for unknown block types
*/
export const DEFAULT_BLOCK_STYLES = {
container: "from-gray/5 to-gray/10 border-gray/20 hover:border-gray/30",
icon: "bg-gray/10 text-gray",
label: "text-gray",
} as const
/**
* Block icons for different context block types
*/
export const BLOCK_ICONS = {
mainEntry: "i-mgc-star-cute-fi",
referEntry: "i-mgc-paper-cute-fi",
referFeed: "i-mgc-rss-cute-fi",
selectedText: "i-mgc-quill-pen-cute-re",
fileAttachment: "i-mgc-file-upload-cute-re",
} as const
/**
* Block labels for different context block types
*/
export const BLOCK_LABELS = {
mainEntry: "Current",
referEntry: "Ref",
referFeed: "Feed",
selectedText: "Text",
fileAttachment: "File",
} as const
/**
* File upload status labels
*/
export const FILE_STATUS_LABELS = {
uploading: "Uploading...",
error: "Failed",
processing: "Processing...",
completed: "",
} as const
/**
* Gets the appropriate styles for a block type
*/
export function getBlockStyles(type: AIChatContextBlock["type"]) {
return BLOCK_STYLES[type] || DEFAULT_BLOCK_STYLES
}
/**
* Gets the appropriate icon for a block
*/
export function getBlockIcon(block: AIChatContextBlock): string {
if (block.type === "fileAttachment" && block.attachment) {
const fileCategory = getFileCategoryFromMimeType(block.attachment.type)
return getFileIconName(fileCategory)
}
return BLOCK_ICONS[block.type] || BLOCK_ICONS.fileAttachment
}
/**
* Gets the appropriate label for a block type
*/
export function getBlockLabel(type: AIChatContextBlock["type"]): string {
return BLOCK_LABELS[type] || ""
}
/**
* Gets the best available image URL for a file attachment
*/
export function getImageUrl(attachment: FileAttachment): string | null {
return attachment.previewUrl || attachment.dataUrl || attachment.serverUrl || null
}
/**
* Checks if a block represents an image attachment
*/
export function isImageAttachment(block: AIChatContextBlock): boolean {
return (
block.type === "fileAttachment" &&
!!block.attachment &&
getFileCategoryFromMimeType(block.attachment.type) === "image"
)
}
/**
* Gets display content for file attachments based on upload status
*/
export function getFileDisplayContent(attachment: FileAttachment): string {
const statusLabel = FILE_STATUS_LABELS[attachment.uploadStatus]
return statusLabel || attachment.name
}
@@ -0,0 +1,154 @@
import { cn } from "@follow/utils"
import { m } from "motion/react"
import type { FC } from "react"
import { memo } from "react"
export interface UploadProgressProps {
/** Progress percentage (0-100) */
progress: number
/** Progress bar size variant */
size?: "sm" | "md" | "lg"
/** Show percentage text */
showPercentage?: boolean
/** Custom className */
className?: string
/** Progress bar color */
variant?: "default" | "success" | "error"
}
export const UploadProgress: FC<UploadProgressProps> = memo(
({ progress, size = "md", showPercentage = false, className, variant = "default" }) => {
const progressValue = Math.max(0, Math.min(100, progress))
const sizeClasses = {
sm: "h-1",
md: "h-2",
lg: "h-3",
}
const colorClasses = {
default: "bg-blue",
success: "bg-green",
error: "bg-red",
}
return (
<div className={cn("w-full", className)}>
{/* Progress Bar */}
<div
className={cn(
"bg-fill-secondary relative overflow-hidden rounded-full",
sizeClasses[size],
)}
>
<m.div
className={cn("h-full rounded-full transition-colors", colorClasses[variant])}
initial={{ width: 0 }}
animate={{ width: `${progressValue}%` }}
transition={{
type: "spring",
damping: 20,
stiffness: 100,
}}
/>
</div>
{/* Percentage Text */}
{showPercentage && (
<div className="text-text-tertiary mt-1 text-center text-xs">
{Math.round(progressValue)}%
</div>
)}
</div>
)
},
)
UploadProgress.displayName = "UploadProgress"
export interface CircularProgressProps {
/** Progress percentage (0-100) */
progress: number
/** Circle size */
size?: number
/** Stroke width */
strokeWidth?: number
/** Show percentage text in center */
showPercentage?: boolean
/** Custom className */
className?: string
/** Progress color */
variant?: "default" | "success" | "error"
}
export const CircularProgress: FC<CircularProgressProps> = memo(
({
progress,
size = 20,
strokeWidth = 2,
showPercentage = false,
className,
variant = "default",
}) => {
const progressValue = Math.max(0, Math.min(100, progress))
const radius = (size - strokeWidth) / 2
const circumference = 2 * Math.PI * radius
const strokeDashoffset = circumference - (progressValue / 100) * circumference
const colorClasses = {
default: "text-blue",
success: "text-green",
error: "text-red",
}
return (
<div className={cn("relative inline-flex items-center justify-center", className)}>
<svg
width={size}
height={size}
className="-rotate-90 transform"
viewBox={`0 0 ${size} ${size}`}
>
{/* Background circle */}
<circle
cx={size / 2}
cy={size / 2}
r={radius}
stroke="currentColor"
strokeWidth={strokeWidth}
fill="none"
className="text-fill-tertiary"
/>
{/* Progress circle */}
<m.circle
cx={size / 2}
cy={size / 2}
r={radius}
stroke="currentColor"
strokeWidth={strokeWidth}
fill="none"
className={colorClasses[variant]}
strokeLinecap="round"
initial={{ strokeDasharray: circumference, strokeDashoffset: circumference }}
animate={{ strokeDashoffset }}
transition={{
type: "spring",
damping: 20,
stiffness: 100,
}}
/>
</svg>
{/* Percentage text */}
{showPercentage && (
<div className="text-text-tertiary absolute inset-0 flex items-center justify-center text-xs font-medium">
{Math.round(progressValue)}%
</div>
)}
</div>
)
},
)
CircularProgress.displayName = "CircularProgress"
@@ -0,0 +1,67 @@
import { AIShortcutButton } from "@follow/components/ui/ai-shortcut-button/index.js"
import type { EditorState, LexicalEditor } from "lexical"
import { m } from "motion/react"
import { useTranslation } from "react-i18next"
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
interface DefaultWelcomeContentProps {
onSend: (message: EditorState | string, editor: LexicalEditor | null) => void
shortcuts: Array<{ id: string; name: string; prompt: string; enabled: boolean; hotkey?: string }>
}
const DEFAULT_SHORTCUTS = ["Generate today daily report"]
export const DefaultWelcomeContent: React.FC<DefaultWelcomeContentProps> = ({
onSend,
shortcuts: enabledShortcuts,
}) => {
const { t } = useTranslation("ai")
const showSettings = useSettingModal()
return (
<m.div
initial={{ opacity: 0, y: 20, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: -20, scale: 0.98 }}
className="w-full space-y-8"
>
<div className="relative flex flex-wrap items-center justify-center gap-2">
{/* Custom shortcuts first */}
{enabledShortcuts.slice(0, 6).map((shortcut, index) => (
<AIShortcutButton
key={shortcut.id}
onClick={() => onSend(shortcut.prompt, null)}
animationDelay={index * 0.1}
title={shortcut.hotkey ? `${shortcut.name} (${shortcut.hotkey})` : shortcut.name}
>
{shortcut.name}
</AIShortcutButton>
))}
{/* Show customize button when no shortcuts are available */}
{enabledShortcuts.length === 0 && (
<>
{DEFAULT_SHORTCUTS.slice(0, 4 - enabledShortcuts.length).map((suggestion, index) => (
<AIShortcutButton
key={suggestion}
onClick={() => onSend(suggestion, null)}
animationDelay={(enabledShortcuts.length + index) * 0.1}
>
{suggestion}
</AIShortcutButton>
))}
<AIShortcutButton
key="customize-shortcuts"
onClick={() => showSettings("ai")}
animationDelay={0}
variant="outline"
title={t("customize_shortcuts_title")}
>
{t("customize_shortcuts")}
</AIShortcutButton>
</>
)}
</div>
</m.div>
)
}
@@ -0,0 +1,160 @@
import { Spring } from "@follow/components/constants/spring.js"
import { AIShortcutButton } from "@follow/components/ui/ai-shortcut-button/index.js"
import { AutoResizeHeight } from "@follow/components/ui/auto-resize-height/index.js"
import { usePrefetchSummary } from "@follow/store/summary/hooks"
import { cn } from "@follow/utils/utils"
import { m } from "motion/react"
import { useTranslation } from "react-i18next"
import { useEntryIsInReadabilitySuccess } from "~/atoms/readability"
import { useActionLanguage } from "~/atoms/settings/general"
import { CopyButton } from "~/components/ui/button/CopyButton"
import { Markdown } from "~/components/ui/markdown/Markdown"
import { useSmartQuickActions } from "../../hooks/useSmartQuickActions"
interface EntrySummaryCardProps {
entryId: string
onSend: (message: string) => void
className?: string
}
const SummaryLoadingState = () => (
<div className="space-y-2">
<div className="bg-material-ultra-thick h-3 w-full animate-pulse rounded-lg" />
<div className="bg-material-ultra-thick h-3 w-[92%] animate-pulse rounded-lg" />
<div className="bg-material-ultra-thick h-3 w-[85%] animate-pulse rounded-lg" />
</div>
)
export const EntrySummaryCard: React.FC<EntrySummaryCardProps> = ({
entryId,
onSend,
className,
}) => {
const { t } = useTranslation("ai")
const actionLanguage = useActionLanguage()
const isInReadabilitySuccess = useEntryIsInReadabilitySuccess(entryId)
const summary = usePrefetchSummary({
entryId,
target: isInReadabilitySuccess ? "readabilityContent" : "content",
actionLanguage,
enabled: true,
})
const quickActions = useSmartQuickActions(summary.data || null, entryId)
return (
<m.div
initial={{ opacity: 0, y: 20, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={Spring.presets.smooth}
className={cn(
// Reuse AISummary visual patterns but optimized for chat context
"group relative w-full max-w-2xl overflow-hidden rounded-2xl border p-6 backdrop-blur-xl",
"bg-gradient-to-b from-neutral-50/80 to-white/40 dark:from-neutral-900/80 dark:to-neutral-900/40",
"border-neutral-200/50 dark:border-neutral-800/50",
"shadow-[0_8px_32px_rgba(0,0,0,0.08)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.3)]",
summary.isLoading &&
"before:absolute before:inset-0 before:-z-10 before:animate-[pulse_2s_cubic-bezier(0.4,0,0.6,1)_infinite] before:bg-gradient-to-r before:from-purple-100/0 before:via-purple-300/10 before:to-purple-100/0 dark:before:from-purple-900/0 dark:before:via-purple-600/10 dark:before:to-purple-900/0",
className,
)}
>
{/* Animated background gradient */}
<div
className={cn(
"absolute inset-0 -z-10 bg-gradient-to-br opacity-50",
"from-purple-100/20 via-transparent to-blue-100/20",
"dark:from-purple-900/20 dark:to-blue-900/20",
summary.isLoading && "animate-[glow_4s_ease-in-out_infinite]",
)}
/>
{/* Header with entry context */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="center relative">
<i
className={cn(
"i-mgc-ai-cute-re text-lg",
summary.isLoading
? "text-purple-500/70 dark:text-purple-400/70"
: "text-purple-600 dark:text-purple-400",
)}
/>
<div
className={cn(
"absolute inset-0 rounded-full blur-sm",
summary.isLoading
? "animate-[pulse_2s_infinite] bg-purple-400/30 dark:bg-purple-500/30"
: "animate-pulse bg-purple-400/20 dark:bg-purple-500/20",
)}
/>
</div>
<span
className={cn(
"bg-gradient-to-r bg-clip-text font-medium text-transparent",
summary.isLoading
? "from-purple-500/70 to-blue-500/70 dark:from-purple-400/70 dark:to-blue-400/70"
: "from-purple-600 to-blue-600 dark:from-purple-400 dark:to-blue-400",
)}
>
{t("ai_summary", { defaultValue: "AI Summary" })}
</span>
</div>
{summary.data && (
<CopyButton
value={summary.data}
variant="outline"
className={cn(
"!bg-white/10 !text-purple-600 dark:!text-purple-400",
"hover:!bg-white/20 dark:hover:!bg-neutral-800/30",
"!border-purple-200/30 dark:!border-purple-800/30",
"sm:opacity-0 sm:duration-300 sm:group-hover:translate-y-0 sm:group-hover:opacity-100",
"backdrop-blur-sm",
)}
/>
)}
</div>
{/* Summary Content */}
<AutoResizeHeight className="mt-4 text-sm leading-relaxed text-neutral-700 dark:text-neutral-300">
{summary.isLoading ? (
<SummaryLoadingState />
) : summary.data ? (
<div className="animate-in fade-in-0 duration-500">
<Markdown className="prose-sm prose-p:m-0 max-w-none">{String(summary.data)}</Markdown>
</div>
) : (
<div className="py-4 text-center">
<i className="i-mgc-document-cute-re text-text-tertiary mb-2 text-2xl" />
<p className="text-text-secondary text-sm">
{t("summary_not_available", { defaultValue: "Summary not available" })}
</p>
</div>
)}
</AutoResizeHeight>
{/* Smart Quick Actions */}
{summary.data && quickActions.length > 0 && (
<div className="mt-6 space-y-3">
<div className="text-text-secondary text-xs font-medium">
{t("conversation_starters", { defaultValue: "Conversation starters" })}
</div>
<div className="flex flex-wrap gap-2">
{quickActions.map((action, index) => (
<AIShortcutButton
key={action.id}
onClick={() => onSend(action.prompt)}
animationDelay={index * 0.1}
>
{action.label}
</AIShortcutButton>
))}
</div>
</div>
)}
</m.div>
)
}
@@ -0,0 +1,2 @@
export { DefaultWelcomeContent } from "./DefaultWelcomeContent"
export { EntrySummaryCard } from "./EntrySummaryCard"
@@ -0,0 +1,168 @@
import type {
DOMConversionMap,
DOMConversionOutput,
DOMExportOutput,
LexicalNode,
NodeKey,
SerializedLexicalNode,
Spread,
} from "lexical"
import { DecoratorNode } from "lexical"
import * as React from "react"
import { useShallow } from "zustand/shallow"
import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext"
export type SerializedFileAttachmentNode = Spread<
{
attachmentId: string
},
SerializedLexicalNode
>
function convertFileAttachmentElement(domNode: Node): null | DOMConversionOutput {
const element = domNode as HTMLElement
const { attachmentId } = element.dataset
if (attachmentId) {
const node = $createFileAttachmentNode(attachmentId)
return { node }
}
return null
}
export class FileAttachmentNode extends DecoratorNode<React.ReactElement> {
__attachmentId: string
static override getType(): string {
return "file-attachment"
}
static override clone(node: FileAttachmentNode): FileAttachmentNode {
return new FileAttachmentNode(node.__attachmentId, node.__key)
}
static override importJSON(serializedNode: SerializedFileAttachmentNode): FileAttachmentNode {
const { attachmentId } = serializedNode
const node = $createFileAttachmentNode(attachmentId)
return node
}
static override importDOM(): DOMConversionMap | null {
return {
span: () => ({
conversion: convertFileAttachmentElement,
priority: 1,
}),
}
}
constructor(attachmentId: string, key?: NodeKey) {
super(key)
this.__attachmentId = attachmentId
}
override exportJSON(): SerializedFileAttachmentNode {
return {
attachmentId: this.__attachmentId,
type: "file-attachment",
version: 1,
}
}
override exportDOM(): DOMExportOutput {
const element = document.createElement("span")
element.dataset.attachmentId = this.__attachmentId
element.textContent = `[File: ${this.__attachmentId}]`
return { element }
}
override createDOM(): HTMLElement {
const span = document.createElement("span")
span.style.display = "inline-block"
span.dataset.attachmentId = this.__attachmentId
return span
}
override updateDOM(): false {
return false
}
getAttachmentId(): string {
return this.__attachmentId
}
setAttachmentId(attachmentId: string): void {
const writable = this.getWritable()
writable.__attachmentId = attachmentId
}
override decorate(): React.ReactElement {
return <FileAttachmentComponent node={this} />
}
override isInline(): boolean {
return true
}
}
interface FileAttachmentComponentProps {
node: FileAttachmentNode
}
function FileAttachmentComponent({ node }: FileAttachmentComponentProps) {
const attachmentId = node.getAttachmentId()
const fileAttachment = useAIChatStore()(
useShallow((state) => {
const block = state.blocks.find(
(block) => block.type === "fileAttachment" && block.attachment.id === attachmentId,
)
return block?.type === "fileAttachment" ? block.attachment : null
}),
)
if (!fileAttachment) {
return (
<span className="bg-fill border-border text-gray inline-flex items-center gap-1 rounded border px-2 py-1 text-xs">
<i className="i-mgc-attachment-cute-re" />
<span className="max-w-32 truncate">File not found</span>
</span>
)
}
return (
<span
className="bg-fill border-border inline-flex items-center gap-1 rounded border px-2 py-1 text-xs"
style={{
backgroundColor: "var(--fill)",
color: "var(--text)",
border: "1px solid var(--border)",
}}
>
<i className="i-mgc-attachment-cute-re" />
<span className="max-w-32 truncate" title={fileAttachment.name}>
{fileAttachment.name}
</span>
{fileAttachment.uploadStatus === "uploading" && (
<i className="i-mgc-loading-3-cute-re text-accent animate-spin" />
)}
{fileAttachment.uploadStatus === "processing" && (
<i className="i-mgc-loading-3-cute-re text-accent animate-spin" />
)}
{fileAttachment.uploadStatus === "error" && <i className="i-mgc-close-cute-re text-red" />}
{fileAttachment.uploadStatus === "completed" && (
<i className="i-mgc-check-cute-re text-green" />
)}
</span>
)
}
export function $createFileAttachmentNode(attachmentId: string): FileAttachmentNode {
return new FileAttachmentNode(attachmentId)
}
export function $isFileAttachmentNode(
node: LexicalNode | null | undefined,
): node is FileAttachmentNode {
return node instanceof FileAttachmentNode
}
@@ -0,0 +1,157 @@
import type { LexicalPluginFC } from "@follow/components/ui/lexical-rich-editor/types.js"
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
import type { RefObject } from "react"
import { useCallback, useEffect, useRef } from "react"
import { FileAttachmentNode } from "./FileAttachmentNode"
import { useFileAttachmentBlockSync } from "./hooks/useFileAttachmentBlockSync"
import { useFileUploadIntegration } from "./hooks/useFileUploadIntegration"
import type { FileUploadPluginConfig } from "./types"
import {
clipboardEventHasFiles,
createDragCounter,
dragEventHasFiles,
getFilesFromDrop,
getFilesFromPaste,
preventDefaultDrag,
} from "./utils/file-handling"
const defaultConfig: FileUploadPluginConfig = {
enableDragDrop: true,
enablePaste: true,
}
export const FileUploadPlugin: LexicalPluginFC = () => {
const [editor] = useLexicalComposerContext()
// Initialize file attachment block synchronization
const { handleFileAttachmentInsert } = useFileAttachmentBlockSync()
// Initialize file upload integration with sync callback
const { handleFileDrop, handlePaste } = useFileUploadIntegration(handleFileAttachmentInsert)
const dragCounterRef: RefObject<ReturnType<typeof createDragCounter>> = useRef(undefined) as any
if (!dragCounterRef.current) {
dragCounterRef.current = createDragCounter()
}
const finalConfig = defaultConfig
// Handle drag enter
const handleDragEnter = useCallback(
(event: DragEvent) => {
if (!finalConfig.enableDragDrop || !dragEventHasFiles(event)) return
preventDefaultDrag(event)
},
[finalConfig.enableDragDrop],
)
// Handle drag over
const handleDragOver = useCallback(
(event: DragEvent) => {
if (!finalConfig.enableDragDrop || !dragEventHasFiles(event)) return
preventDefaultDrag(event)
},
[finalConfig.enableDragDrop],
)
// Handle drag leave
const handleDragLeave = useCallback(
(event: DragEvent) => {
if (!finalConfig.enableDragDrop) return
preventDefaultDrag(event)
const newCounter = dragCounterRef.current.decrement()
if (newCounter <= 0) {
dragCounterRef.current.reset()
}
},
[finalConfig.enableDragDrop],
)
// Handle drop
const handleDrop = useCallback(
async (event: DragEvent) => {
if (!finalConfig.enableDragDrop) return
preventDefaultDrag(event)
dragCounterRef.current.reset()
const files = getFilesFromDrop(event)
if (files && files.length > 0) {
await handleFileDrop(files)
}
},
[finalConfig.enableDragDrop, handleFileDrop],
)
// Handle paste
const handlePasteEvent = useCallback(
async (event: ClipboardEvent) => {
if (!finalConfig.enablePaste || !clipboardEventHasFiles(event)) return
event.preventDefault()
const files = getFilesFromPaste(event)
if (files && files.length > 0) {
await handlePaste(event.clipboardData!)
}
},
[finalConfig.enablePaste, handlePaste],
)
// Set up event listeners
useEffect(() => {
const removeRootListener = editor.registerRootListener((rootElement, prevRootElement) => {
// Remove previous listeners
if (prevRootElement) {
if (finalConfig.enableDragDrop) {
prevRootElement.removeEventListener("dragenter", handleDragEnter)
prevRootElement.removeEventListener("dragover", handleDragOver)
prevRootElement.removeEventListener("dragleave", handleDragLeave)
prevRootElement.removeEventListener("drop", handleDrop)
}
if (finalConfig.enablePaste) {
prevRootElement.removeEventListener("paste", handlePasteEvent)
}
}
// Add new listeners
if (rootElement) {
if (finalConfig.enableDragDrop) {
rootElement.addEventListener("dragenter", handleDragEnter, { passive: false })
rootElement.addEventListener("dragover", handleDragOver, { passive: false })
rootElement.addEventListener("dragleave", handleDragLeave, { passive: false })
rootElement.addEventListener("drop", handleDrop, { passive: false })
}
if (finalConfig.enablePaste) {
rootElement.addEventListener("paste", handlePasteEvent, { passive: false })
}
}
})
return removeRootListener
}, [
editor,
finalConfig,
handleDragEnter,
handleDragOver,
handleDragLeave,
handleDrop,
handlePasteEvent,
])
return null
}
FileUploadPlugin.id = "file-upload"
FileUploadPlugin.nodes = [FileAttachmentNode]
@@ -0,0 +1,73 @@
import { Spring } from "@follow/components/constants/spring.js"
import { cn } from "@follow/utils"
import { AnimatePresence, m } from "motion/react"
import { memo } from "react"
interface FileDropZoneProps {
isVisible: boolean
isDragOver: boolean
className?: string
}
export const FileDropZone = memo(({ isVisible, isDragOver, className }: FileDropZoneProps) => {
return (
<AnimatePresence>
{isVisible && (
<m.div
className={cn(
"pointer-events-none absolute inset-0 z-50 flex items-center justify-center",
className,
)}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={Spring.presets.smooth}
>
{/* Backdrop */}
<m.div
className={cn(
"absolute inset-0 backdrop-blur-sm transition-colors duration-200",
isDragOver ? "bg-material-thin/90" : "bg-material-thin/60",
)}
/>
{/* Drop zone content */}
<m.div
initial={{ scale: 0.9, y: 10 }}
animate={{ scale: 1, y: 0 }}
exit={{ scale: 0.9, y: 10 }}
transition={Spring.presets.snappy}
className={cn(
"bg-background/95 rounded-xl border-2 border-dashed p-6 text-center transition-all duration-200",
isDragOver
? "border-accent bg-accent/5 shadow-accent/20 shadow-lg"
: "border-border/50 shadow-sm",
)}
>
<m.div
className="text-accent mb-3 flex justify-center"
animate={isDragOver ? { scale: [1, 1.1, 1] } : {}}
transition={{
duration: 0.6,
repeat: isDragOver ? Number.POSITIVE_INFINITY : 0,
ease: "easeInOut",
}}
>
<i className="i-mgc-file-upload-cute-re size-8" />
</m.div>
<p className={cn("text-text font-medium", isDragOver && "text-accent")}>
{isDragOver ? "Drop files to upload" : "Drag files here to upload"}
</p>
<p className="text-text-secondary mt-1 text-sm">
Images, PDFs, and text files supported
</p>
</m.div>
</m.div>
)}
</AnimatePresence>
)
})
FileDropZone.displayName = "FileDropZone"
@@ -0,0 +1,231 @@
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
import { $getNodeByKey } from "lexical"
import { useCallback, useEffect, useRef } from "react"
import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext"
import { useChatBlockActions } from "~/modules/ai-chat/store/hooks"
import type { FileAttachmentContextBlock } from "~/modules/ai-chat/store/types"
import { $isFileAttachmentNode, FileAttachmentNode } from "../FileAttachmentNode"
interface FileAttachmentBlockReference {
fileNodeKey: string
blockId: string
fileId: string // unique identifier for the file
}
/**
* Hook that manages bidirectional synchronization between file attachment nodes and context blocks
* - When a file attachment is added, corresponding block is created
* - When a block is removed, corresponding file nodes are removed
* - When a file node is removed, corresponding block is removed
*/
export const useFileAttachmentBlockSync = () => {
const [editor] = useLexicalComposerContext()
const blockActions = useChatBlockActions()
const blocks = useAIChatStore()((state) => state.blocks)
// Reference tracking maps
const nodeToBlockRef = useRef<Map<string, FileAttachmentBlockReference>>(undefined!)
if (!nodeToBlockRef.current) {
nodeToBlockRef.current = new Map()
}
const fileToNodeRef = useRef<Map<string, Set<string>>>(undefined!)
if (!fileToNodeRef.current) {
fileToNodeRef.current = new Map()
}
const blockToFileRef = useRef<Map<string, string>>(undefined!)
if (!blockToFileRef.current) {
blockToFileRef.current = new Map()
}
// Add file attachment reference
const addFileReference = useCallback(
(attachmentId: string, fileNodeKey: string, blockId: string) => {
const reference: FileAttachmentBlockReference = {
fileNodeKey,
blockId,
fileId: attachmentId,
}
// Update tracking maps
nodeToBlockRef.current.set(fileNodeKey, reference)
if (!fileToNodeRef.current.has(attachmentId)) {
fileToNodeRef.current.set(attachmentId, new Set())
}
fileToNodeRef.current.get(attachmentId)!.add(fileNodeKey)
blockToFileRef.current.set(blockId, attachmentId)
},
[],
)
// Remove file attachment reference
const removeFileReference = useCallback((fileNodeKey: string) => {
const reference = nodeToBlockRef.current.get(fileNodeKey)
if (!reference) return null
const { fileId, blockId } = reference
// Clean up tracking maps
nodeToBlockRef.current.delete(fileNodeKey)
const nodeSet = fileToNodeRef.current.get(fileId)
if (nodeSet) {
nodeSet.delete(fileNodeKey)
if (nodeSet.size === 0) {
fileToNodeRef.current.delete(fileId)
}
}
blockToFileRef.current.delete(blockId)
return reference
}, [])
// Handle file attachment insertion - create block and track reference
const handleFileAttachmentInsert = useCallback(
(attachmentId: string, fileNodeKey: string) => {
// Check if block already exists for this file
const existingBlock = blocks.find(
(block): block is FileAttachmentContextBlock =>
block.type === "fileAttachment" &&
blockToFileRef.current.get(block.attachment.id) === attachmentId,
)
let blockId: string
if (existingBlock) {
// Use existing block
blockId = existingBlock.id
} else {
// Find the file attachment in the current blocks state
const currentBlocks = blockActions.getBlocks()
const addedBlock = currentBlocks.find(
(block): block is FileAttachmentContextBlock =>
block.type === "fileAttachment" && block.attachment.id === attachmentId,
)
if (addedBlock) {
blockId = addedBlock.id
} else {
// Fallback to a predictable ID pattern
blockId = `fileAttachment-${attachmentId}-${fileNodeKey}`
}
}
// Track the reference
addFileReference(attachmentId, fileNodeKey, blockId)
},
[blocks, blockActions, addFileReference],
)
// Handle file attachment removal - remove block if no other nodes reference it
const handleFileAttachmentRemove = useCallback(
(fileNodeKey: string) => {
const reference = removeFileReference(fileNodeKey)
if (!reference) return
const { fileId } = reference
// Check if any other nodes still reference this file
const remainingNodes = fileToNodeRef.current.get(fileId)
if (!remainingNodes || remainingNodes.size === 0) {
// No more nodes reference this file, remove the block
blockActions.removeFileAttachment(fileId)
}
},
[blockActions, removeFileReference],
)
// Handle block removal - remove corresponding file nodes
const handleBlockRemove = useCallback(
(blockId: string) => {
const fileId = blockToFileRef.current.get(blockId)
if (!fileId) return
const nodeKeys = fileToNodeRef.current.get(fileId)
if (!nodeKeys) return
// Remove all file attachment nodes for this file
editor.update(() => {
Array.from(nodeKeys).forEach((nodeKey) => {
const node = $getNodeByKey(nodeKey)
if (node && $isFileAttachmentNode(node)) {
node.remove()
}
})
})
// Clean up references
Array.from(nodeKeys).forEach((nodeKey) => {
removeFileReference(nodeKey)
})
},
[editor, removeFileReference],
)
// Monitor block changes
useEffect(() => {
const currentBlockIds = new Set(blocks.map((block) => block.id))
const trackedBlockIds = new Set(blockToFileRef.current.keys())
// Find removed blocks
for (const trackedBlockId of trackedBlockIds) {
if (!currentBlockIds.has(trackedBlockId)) {
handleBlockRemove(trackedBlockId)
}
}
}, [blocks, handleBlockRemove])
// Monitor file attachment node changes using mutation observer
useEffect(() => {
const removedNodeKeys = new Set<string>()
const unregisterMutationListener = editor.registerMutationListener(
FileAttachmentNode,
(mutatedNodes) => {
for (const [nodeKey, mutation] of mutatedNodes) {
// Only track destroyed mutations for nodes we're actually tracking
if (mutation === "destroyed" && nodeToBlockRef.current.has(nodeKey)) {
removedNodeKeys.add(nodeKey)
}
}
// Process removed nodes in next tick to avoid state conflicts
if (removedNodeKeys.size > 0) {
const timeoutId = setTimeout(() => {
Array.from(removedNodeKeys).forEach((nodeKey) => {
handleFileAttachmentRemove(nodeKey)
})
removedNodeKeys.clear()
}, 100)
return () => clearTimeout(timeoutId)
}
},
)
return unregisterMutationListener
}, [editor, handleFileAttachmentRemove])
// Cleanup on unmount
useEffect(() => {
const nodeToBlock = nodeToBlockRef.current
const fileToNode = fileToNodeRef.current
const blockToFile = blockToFileRef.current
return () => {
nodeToBlock.clear()
fileToNode.clear()
blockToFile.clear()
}
}, [])
return {
handleFileAttachmentInsert,
handleFileAttachmentRemove,
}
}
@@ -0,0 +1,96 @@
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"
import {
$createParagraphNode,
$getRoot,
$getSelection,
$insertNodes,
$isElementNode,
} from "lexical"
import { useCallback } from "react"
import { useFileUploadWithDefaults } from "../../../../hooks/useFileUpload"
import { $createFileAttachmentNode } from "../FileAttachmentNode"
export function useFileUploadIntegration(
onFileNodeInsert?: (attachmentId: string, nodeKey: string) => void,
) {
const [editor] = useLexicalComposerContext()
const { uploadFiles } = useFileUploadWithDefaults()
const insertFileAttachmentNode = useCallback(
(attachmentId: string) => {
editor.update(() => {
const selection = $getSelection()
const root = $getRoot()
const fileNode = $createFileAttachmentNode(attachmentId)
if (selection) {
// Insert at current selection
$insertNodes([fileNode])
} else {
// No selection - append to the end
const lastChild = root.getLastChild()
if (lastChild && $isElementNode(lastChild)) {
lastChild.append(fileNode)
} else {
// Create a paragraph and add the file node to it
const paragraph = $createParagraphNode()
paragraph.append(fileNode)
root.append(paragraph)
}
}
// Notify the sync handler
const nodeKey = fileNode.getKey()
if (onFileNodeInsert) {
onFileNodeInsert(attachmentId, nodeKey)
}
})
},
[editor, onFileNodeInsert],
)
const handleMultipleFileUpload = useCallback(
async (files: File[] | FileList) => {
try {
const results = await uploadFiles(files)
// Insert successful uploads into the editor
results.forEach((result) => {
if (result.success && result.fileAttachment) {
insertFileAttachmentNode(result.fileAttachment.id)
}
})
} catch (error) {
console.error("Multiple file upload failed:", error)
}
},
[uploadFiles, insertFileAttachmentNode],
)
const handleFileDrop = useCallback(
async (files: FileList) => {
if (files && files.length > 0) {
await handleMultipleFileUpload(files)
}
},
[handleMultipleFileUpload],
)
const handlePaste = useCallback(
async (clipboardData: DataTransfer) => {
const files = Array.from(clipboardData.files)
if (files.length > 0) {
await handleMultipleFileUpload(files)
}
},
[handleMultipleFileUpload],
)
return {
handleMultipleFileUpload,
handleFileDrop,
handlePaste,
}
}
@@ -0,0 +1,3 @@
export { FileAttachmentNode } from "./FileAttachmentNode"
export { FileUploadPlugin } from "./FileUploadPlugin"
export type * from "./types"
@@ -0,0 +1,15 @@
export interface FileUploadPluginConfig {
/**
* Enable drag and drop file upload
*/
enableDragDrop?: boolean
/**
* Enable paste file upload
*/
enablePaste?: boolean
}
export interface FileDropZoneState {
isDragOver: boolean
dragCounter: number
}
@@ -0,0 +1,52 @@
/**
* Check if drag event contains files
*/
export function dragEventHasFiles(event: DragEvent): boolean {
return event.dataTransfer?.types.includes("Files") ?? false
}
/**
* Check if clipboard event contains files
*/
export function clipboardEventHasFiles(event: ClipboardEvent): boolean {
return !!(event.clipboardData?.files && event.clipboardData.files.length > 0)
}
/**
* Prevent default drag behaviors
*/
export function preventDefaultDrag(event: DragEvent): void {
event.preventDefault()
event.stopPropagation()
}
/**
* Get files from drop event
*/
export function getFilesFromDrop(event: DragEvent): FileList | null {
return event.dataTransfer?.files ?? null
}
/**
* Get files from paste event
*/
export function getFilesFromPaste(event: ClipboardEvent): FileList | null {
return event.clipboardData?.files ?? null
}
/**
* Debounce drag counter for proper drag leave handling
*/
export function createDragCounter() {
let counter = 0
return {
increment: () => ++counter,
decrement: () => --counter,
get: () => counter,
reset: () => {
counter = 0
return counter
},
}
}
@@ -1 +1,2 @@
export * from "./file-upload"
export * from "./mention"
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useRef } from "react"
import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext"
import { useChatBlockActions } from "~/modules/ai-chat/store/hooks"
import type { AIChatContextBlock } from "~/modules/ai-chat/store/types"
import type { AIChatContextBlock, ValueContextBlock } from "~/modules/ai-chat/store/types"
import { $isMentionNode, MentionNode } from "../MentionNode"
import type { MentionData } from "../types"
@@ -18,7 +18,7 @@ interface MentionBlockReference {
const getResourceId = (type: string, value: string) => `${type}:${value}`
const getBlockType = (mentionType: string): AIChatContextBlock["type"] => {
const getBlockType = (mentionType: string): ValueContextBlock["type"] => {
return mentionType === "feed" ? "referFeed" : "referEntry"
}
@@ -34,9 +34,20 @@ export const useMentionBlockSync = () => {
const blocks = useAIChatStore()((state) => state.blocks)
// Reference tracking maps
const mentionToBlockRef = useRef(new Map<string, MentionBlockReference>()) // mentionNodeKey -> reference
const resourceToMentionsRef = useRef(new Map<string, Set<string>>()) // resourceId -> Set<mentionNodeKey>
const blockToResourceRef = useRef(new Map<string, string>()) // blockId -> resourceId
const mentionToBlockRef = useRef<Map<string, MentionBlockReference>>(undefined!)
if (!mentionToBlockRef.current) {
mentionToBlockRef.current = new Map()
}
const resourceToMentionsRef = useRef<Map<string, Set<string>>>(undefined!)
if (!resourceToMentionsRef.current) {
resourceToMentionsRef.current = new Map()
}
const blockToResourceRef = useRef<Map<string, string>>(undefined!)
if (!blockToResourceRef.current) {
blockToResourceRef.current = new Map()
}
// Add mention-block reference
const addMentionReference = useCallback(
@@ -105,7 +116,7 @@ export const useMentionBlockSync = () => {
const blockType = getBlockType(mentionData.type)
// Generate block ID (mimicking the block slice logic)
const newBlock: Omit<AIChatContextBlock, "id"> = {
const newBlock: Omit<ValueContextBlock, "id"> = {
type: blockType,
value: mentionData.value as string,
}
@@ -115,7 +126,8 @@ export const useMentionBlockSync = () => {
// Use current blocks state directly from store instead of stale closure
const currentBlocks = blockActions.getBlocks()
const addedBlock = currentBlocks.find(
(block) => block.type === blockType && block.value === mentionData.value,
(block): block is Extract<AIChatContextBlock, { type: typeof blockType }> =>
block.type === blockType && block.value === mentionData.value,
)
if (addedBlock) {
@@ -239,11 +251,5 @@ export const useMentionBlockSync = () => {
return {
handleMentionInsert,
handleMentionRemove,
// Debug helpers
getMentionReferences: () => ({
mentionToBlock: new Map(mentionToBlockRef.current),
resourceToMentions: new Map(resourceToMentionsRef.current),
blockToResource: new Map(blockToResourceRef.current),
}),
}
}
@@ -1,6 +1,6 @@
import { useMemo } from "react"
import { useFeedEntrySearchService } from "~/modules/ai-chat/services/feedEntrySearchService"
import { useFeedEntrySearchService } from "~/modules/ai-chat/hooks/useFeedEntrySearchService"
import type { MentionData, MentionType } from "../types"
@@ -0,0 +1,26 @@
import { useQuery } from "@tanstack/react-query"
import { followApi } from "~/lib/api-client"
const useAIConfiguration = () => {
return useQuery({
queryKey: ["aiConfiguration"],
queryFn: async () => {
return followApi.ai.config()
},
staleTime: 5 * 60 * 1000,
retry: false,
})
}
export const useAIModel = () => {
const { data: configuration, isLoading } = useAIConfiguration()
return {
data: {
currentModel: configuration?.currentModel,
availableModels: configuration?.availableModels,
},
isLoading,
}
}
@@ -1,26 +1,22 @@
import { springScrollTo } from "@follow/utils/scroller"
import { debounce } from "es-toolkit/compat"
import { debounce, throttle } from "es-toolkit/compat"
import { useCallback, useEffect, useRef, useState } from "react"
const BOTTOM_THRESHOLD = 50
export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => {
const [isAtBottom, setIsAtBottom] = useState(true)
const [isUserInteracting, setIsUserInteracting] = useState(false)
const scrollAnimationRef = useRef<{ stop: () => void } | null>(null)
const interactionTimeoutRef = useRef<number | null>(null)
const isAutoScrollingRef = useRef(false)
const isUserInteractingRef = useRef(isUserInteracting)
useEffect(() => {
isUserInteractingRef.current = isUserInteracting
}, [isUserInteracting])
const isAutoScrollCancelledRef = useRef(false)
const isAtBottomRef = useRef(isAtBottom)
useEffect(() => {
isAtBottomRef.current = isAtBottom
}, [isAtBottom])
// cancellation is tracked purely via ref to avoid re-renders while user interacts
const scrollToBottom = useCallback(
(force = false) => {
if (!viewport) return
@@ -29,7 +25,7 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) =>
scrollAnimationRef.current.stop()
}
if (force || (!isUserInteractingRef.current && isAtBottomRef.current)) {
if (force || (isAtBottomRef.current && !isAutoScrollCancelledRef.current)) {
isAutoScrollingRef.current = true
const targetScrollTop = viewport.scrollHeight - viewport.clientHeight
const animation = springScrollTo(targetScrollTop, viewport)
@@ -52,55 +48,43 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) =>
useEffect(() => {
if (!viewport) return
if (!enabled) return
if (!enabled) {
return
}
const handleScroll = () => {
const handleScroll = throttle(() => {
if (isAutoScrollingRef.current) {
return
}
}, 100)
const { scrollTop, scrollHeight, clientHeight } = viewport
const atBottom = scrollHeight - scrollTop - clientHeight <= BOTTOM_THRESHOLD
if (!isUserInteractingRef.current) {
setIsAtBottom(atBottom)
}
}
const handleWheel = () => {
const cancelAutoScroll = () => {
isAutoScrollingRef.current = false
setIsUserInteracting(true)
if (scrollAnimationRef.current) {
scrollAnimationRef.current.stop()
}
if (interactionTimeoutRef.current) {
window.clearTimeout(interactionTimeoutRef.current)
}
interactionTimeoutRef.current = window.setTimeout(() => {
setIsUserInteracting(false)
handleScroll() // Re-check position after interaction ends
}, 150)
isAutoScrollCancelledRef.current = true
handleScroll()
}
const handleWheel = throttle(cancelAutoScroll, 100)
const handleTouchStart = handleWheel
const handleTouchMove = handleWheel
viewport.addEventListener("scroll", handleScroll, { passive: true })
viewport.addEventListener("wheel", handleWheel, { passive: true })
viewport.addEventListener("touchstart", handleTouchStart, { passive: true })
viewport.addEventListener("touchmove", handleTouchMove, { passive: true })
return () => {
viewport.removeEventListener("scroll", handleScroll)
viewport.removeEventListener("wheel", handleWheel)
if (interactionTimeoutRef.current) {
window.clearTimeout(interactionTimeoutRef.current)
}
viewport.removeEventListener("touchstart", handleTouchStart)
viewport.removeEventListener("touchmove", handleTouchMove)
if (scrollAnimationRef.current) {
scrollAnimationRef.current.stop()
}
}
}, [viewport])
}, [viewport, enabled])
useEffect(() => {
if (!viewport || !enabled) return
@@ -110,7 +94,7 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) =>
const resizeObserver = new ResizeObserver(
debounce(() => {
if (!isUserInteractingRef.current && isAtBottomRef.current) {
if (isAtBottomRef.current && !isAutoScrollCancelledRef.current) {
requestAnimationFrame(() => {
scrollToBottom()
})
@@ -126,7 +110,7 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) =>
}, [viewport, enabled, scrollToBottom])
const resetScrollState = useCallback(() => {
setIsUserInteracting(false)
isAutoScrollCancelledRef.current = false
setIsAtBottom(true)
scrollToBottom(true)
}, [scrollToBottom])
@@ -16,6 +16,7 @@ export const useChatHistory = () => {
chatId: row.chatId,
title: row.title || "New Chat",
createdAt: new Date(row.createdAt),
updatedAt: new Date(row.updatedAt),
messageCount: row.messageCount,
}))
@@ -0,0 +1,215 @@
import { nanoid } from "nanoid"
import { useCallback } from "react"
import { toast } from "sonner"
import { useChatBlockActions } from "../store/hooks"
import type { FileAttachment } from "../store/types"
import type { ProcessFileOptions, ProcessFileResult } from "../utils/file-processing"
import { processAndUploadFile } from "../utils/file-processing"
export interface UseFileUploadOptions extends ProcessFileOptions {
/**
* Show success toast on successful upload
*/
showSuccessToast?: boolean
/**
* Show error toast on upload failure
*/
showErrorToast?: boolean
/**
* Custom success message for toast
*/
successMessage?: string
/**
* Custom error message prefix for toast
*/
errorMessagePrefix?: string
}
export interface FileUploadHandlers {
/**
* Upload a single file with progress tracking
*/
uploadFile: (file: File, id?: string) => Promise<ProcessFileResult>
/**
* Upload multiple files with progress tracking
*/
uploadFiles: (files: File[] | FileList) => Promise<ProcessFileResult[]>
/**
* Handle file input change event
*/
handleFileInputChange: (event: React.ChangeEvent<HTMLInputElement>) => Promise<void>
/**
* Handle drag and drop files
*/
handleFileDrop: (files: FileList) => Promise<void>
}
/**
* Hook for handling file uploads with progress tracking and block management
*/
export function useFileUpload(options: UseFileUploadOptions = {}): FileUploadHandlers {
const {
showSuccessToast = false,
showErrorToast = true,
successMessage = "File uploaded successfully",
errorMessagePrefix = "File upload error",
...processOptions
} = options
const blockActions = useChatBlockActions()
const uploadFile = useCallback(
async (file: File, id?: string): Promise<ProcessFileResult> => {
// Create initial file attachment for immediate UI feedback
const initialFileAttachment: FileAttachment = {
id: id || nanoid(),
name: file.name,
type: file.type,
size: file.size,
dataUrl: "", // Will be filled during processing
uploadStatus: "processing",
uploadProgress: 0,
}
// Add the initial block immediately for real-time UI feedback
blockActions.addFileAttachment(initialFileAttachment)
try {
const result = await processAndUploadFile(file, processOptions, (updatedAttachment) => {
// Update the attachment with the same ID to maintain consistency
const syncedAttachment = {
...updatedAttachment,
id: initialFileAttachment.id, // Keep the same ID
}
blockActions.updateFileAttachment(initialFileAttachment.id, syncedAttachment)
})
if (result.success && result.fileAttachment) {
// Update the final completed state with the same ID
const finalAttachment = {
...result.fileAttachment,
id: initialFileAttachment.id, // Keep the same ID
}
blockActions.updateFileAttachment(initialFileAttachment.id, finalAttachment)
if (showSuccessToast) {
toast.success(`${successMessage}: ${file.name}`)
}
// Return result with consistent ID
return {
...result,
fileAttachment: finalAttachment,
}
} else {
// Update to error state
const errorAttachment: FileAttachment = {
...initialFileAttachment,
uploadStatus: "error",
errorMessage: result.error || "Upload failed",
uploadProgress: undefined,
}
blockActions.updateFileAttachment(initialFileAttachment.id, errorAttachment)
if (showErrorToast && result.error) {
toast.error(`${errorMessagePrefix}: ${result.error}`)
}
return {
...result,
fileAttachment: errorAttachment,
}
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error"
// Update to error state
const errorAttachment: FileAttachment = {
...initialFileAttachment,
uploadStatus: "error",
errorMessage,
uploadProgress: undefined,
}
blockActions.updateFileAttachment(initialFileAttachment.id, errorAttachment)
if (showErrorToast) {
toast.error(`${errorMessagePrefix}: ${errorMessage}`)
}
console.error("File upload failed:", error)
return {
success: false,
error: errorMessage,
fileAttachment: errorAttachment,
}
}
},
[
blockActions,
processOptions,
showSuccessToast,
showErrorToast,
successMessage,
errorMessagePrefix,
],
)
const uploadFiles = useCallback(
async (files: File[] | FileList): Promise<ProcessFileResult[]> => {
const results: ProcessFileResult[] = []
const fileArray = Array.from(files)
// Process files sequentially to avoid overwhelming the server
for (const file of fileArray) {
const result = await uploadFile(file)
results.push(result)
}
return results
},
[uploadFile],
)
const handleFileInputChange = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const { files } = event.target
if (files && files.length > 0) {
await uploadFiles(files)
}
// Reset file input
event.target.value = ""
},
[uploadFiles],
)
const handleFileDrop = useCallback(
async (files: FileList) => {
if (files && files.length > 0) {
await uploadFiles(files)
}
},
[uploadFiles],
)
return {
uploadFile,
uploadFiles,
handleFileInputChange,
handleFileDrop,
}
}
/**
* Convenience hook for file upload with default settings
*/
export function useFileUploadWithDefaults(): FileUploadHandlers {
return useFileUpload({
showErrorToast: true,
showSuccessToast: false,
})
}
@@ -0,0 +1,15 @@
import { useAIChatStore } from "../store/AIChatContext"
/**
* Hook to get the current main entry ID from the AI chat store.
* Returns undefined if no entry context is available.
*
* This hook accesses the mainEntry block that gets set when viewing an entry,
* enabling context-aware AI chat features.
*/
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
})
}
@@ -0,0 +1,88 @@
import { useEntry } from "@follow/store/entry/hooks"
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
interface QuickAction {
id: string
label: string
prompt: string
icon: string
priority: number
}
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,
},
]
/**
* Hook to generate contextual conversation starters based on summary content and entry metadata.
* Returns an array of quick actions that provide intelligent prompts for starting AI conversations.
*/
export const useSmartQuickActions = (
summaryData: string | null,
entryId: string,
): QuickAction[] => {
const entry = useEntry(entryId, (state) => ({ url: state.url }))
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") || "Simplify this",
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") || "Discuss insights",
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") || "Ask 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") || "Key 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])
}
@@ -1,69 +0,0 @@
import { useMemo } from "react"
import type { SearchItem } from "./feedEntrySearchService"
import { useFeedEntrySearchService } from "./feedEntrySearchService"
/**
* Picker item interface for context bar compatibility
*/
export interface PickerItem {
id: string
title: string
}
/**
* Hook that provides search functionality for context bar
* Uses the shared feed/entry search service and converts results to PickerItem format
*/
export const useContextBarSearchService = () => {
const { search, feedItems, entryItems } = useFeedEntrySearchService({
maxRecentEntries: 50,
fuseOptions: {
keys: ["title", "id"],
threshold: 0.3,
},
})
// Convert search items to picker items
const convertToPickerItems = useMemo(() => {
return (items: SearchItem[]): PickerItem[] => {
return items.map((item) => ({
id: item.id,
title: item.title,
}))
}
}, [])
// Search function for feeds
const searchFeeds = useMemo(() => {
return (query: string): PickerItem[] => {
const results = search(query, "feed", 20)
return convertToPickerItems(results)
}
}, [search, convertToPickerItems])
// Search function for entries
const searchEntries = useMemo(() => {
return (query: string): PickerItem[] => {
const results = search(query, "entry", 20)
return convertToPickerItems(results)
}
}, [search, convertToPickerItems])
// Get all feeds as picker items
const allFeeds = useMemo(() => {
return convertToPickerItems(feedItems)
}, [feedItems, convertToPickerItems])
// Get all recent entries as picker items
const allRecentEntries = useMemo(() => {
return convertToPickerItems(entryItems)
}, [entryItems, convertToPickerItems])
return {
searchFeeds,
searchEntries,
allFeeds,
allRecentEntries,
}
}
@@ -74,7 +74,7 @@ class AIPersistServiceStatic {
* Returns both session details and messages to avoid redundant queries
*/
async loadSessionWithMessages(chatId: string): Promise<{
session: { chatId: string; title?: string; createdAt: Date } | null
session: { chatId: string; title?: string; createdAt: Date; updatedAt: Date } | null
messages: BizUIMessage[]
}> {
// Load both session and messages in parallel
@@ -154,23 +154,25 @@ class AIPersistServiceStatic {
await db
.insert(aiChatMessagesTable)
.values(
messages.map((message) => {
const convertedParts = message.parts as any[]
messages
.filter((message) => message.parts.length > 0)
.map((message) => {
const convertedParts = message.parts as any[]
return {
id: message.id,
chatId,
role: message.role,
contentFormat: "plaintext" as const,
createdAt: new Date(),
status: "completed" as const,
finishedAt: message.metadata?.finishTime
? new Date(message.metadata.finishTime)
: undefined,
messageParts: convertedParts,
metadata: message.metadata,
} as typeof aiChatMessagesTable.$inferInsert
}),
return {
id: message.id,
chatId,
role: message.role,
contentFormat: "plaintext" as const,
createdAt: new Date(),
status: "completed" as const,
finishedAt: message.metadata?.finishTime
? new Date(message.metadata.finishTime)
: undefined,
messageParts: convertedParts,
metadata: message.metadata,
} as typeof aiChatMessagesTable.$inferInsert
}),
)
.onConflictDoUpdate({
target: [aiChatMessagesTable.id],
@@ -244,6 +246,7 @@ class AIPersistServiceStatic {
chatId: true,
title: true,
createdAt: true,
updatedAt: true,
},
})
@@ -265,8 +268,9 @@ class AIPersistServiceStatic {
chatId: true,
title: true,
createdAt: true,
updatedAt: true,
},
orderBy: (t, { desc }) => desc(t.createdAt),
orderBy: (t, { desc }) => desc(t.updatedAt),
limit,
})
@@ -291,6 +295,7 @@ class AIPersistServiceStatic {
chatId: chat.chatId,
title: chat.title,
createdAt: chat.createdAt,
updatedAt: chat.updatedAt,
messageCount: messageCountMap.get(chat.chatId) || 0,
}))
.filter((chat) => chat.messageCount > 0)
@@ -313,6 +318,15 @@ class AIPersistServiceStatic {
.where(eq(aiChatTable.chatId, chatId))
}
async updateSessionTime(chatId: string) {
await db
.update(aiChatTable)
.set({
updatedAt: new Date(Date.now()),
})
.where(eq(aiChatTable.chatId, chatId))
}
async cleanupEmptySessions() {
const emptySessions = await db.values<[string]>(
sql`
@@ -92,6 +92,35 @@ export class ChatSliceActions {
return this.get().chatId
}
// Edit chat title
editChatTitle = async (newTitle: string) => {
const currentChatId = this.getCurrentChatId()
if (!currentChatId) {
throw new Error("No active chat to edit title for")
}
const trimmedTitle = newTitle.trim()
const currentTitle = this.getCurrentTitle()
// If no changes, return early
if (trimmedTitle === currentTitle) {
return
}
try {
// Optimistic update
this.setCurrentTitle(trimmedTitle)
// Persist to database
await AIPersistService.updateSessionTitle(currentChatId, trimmedTitle)
} catch (error) {
// Rollback on error
this.setCurrentTitle(currentTitle)
console.error("Failed to update chat title:", error)
throw error
}
}
// Core chat actions using AI SDK AbstractChat methods
sendMessage = async (message: string | BizUIMessage) => {
try {
@@ -145,6 +145,8 @@ export class ZustandChatState<UI_MESSAGE extends BizUIMessage> implements ChatSt
await AIPersistService.ensureSession(this.chatId, "New Chat")
// Save messages using incremental updates
await AIPersistService.upsertMessages(this.chatId, this.#messages)
// Update session time after successfully saving messages
await AIPersistService.updateSessionTime(this.chatId)
} catch (error) {
console.error("Failed to persist messages:", error)
}
@@ -16,28 +16,6 @@ export const useCurrentTitle = () => {
return store((state) => state.currentTitle)
}
/**
* Hook to get the setter for current room ID
*/
export const useSetCurrentChatId = () => {
const store = useAIChatStore()
return (chatId: string | null) => {
const actions = store.getState().chatActions
if (chatId && chatId !== actions.getCurrentChatId()) {
// If we need to switch to a different room, create a new chat
actions.newChat()
}
}
}
/**
* Hook to get the setter for current title
*/
export const useSetCurrentTitle = () => {
const store = useAIChatStore()
return store.getState().chatActions.setCurrentTitle
}
/**
* Hook to get the chat actions
*/
@@ -54,14 +32,6 @@ export const useBlockActions = () => {
return store((state) => state.blockActions)
}
/**
* Hook to get the chat instance
*/
export const useChatInstance = () => {
const store = useAIChatStore()
return store((state) => state.chatInstance)
}
/**
* Hook to get the current messages
*/
@@ -94,11 +64,3 @@ export const useChatError = () => {
const store = useAIChatStore()
return store((state) => state.error)
}
/**
* Hook to get the streaming status
*/
export const useIsStreaming = () => {
const store = useAIChatStore()
return store((state) => state.isStreaming)
}
@@ -3,7 +3,8 @@ import { produce } from "immer"
import { nanoid } from "nanoid"
import type { StateCreator } from "zustand"
import type { AIChatContextBlock } from "../types"
import { cleanupFileAttachment } from "../../utils/file-processing"
import type { AIChatContextBlock, AIChatContextBlockInput, FileAttachment } from "../types"
export interface BlockSlice {
blocks: AIChatContextBlock[]
@@ -39,7 +40,7 @@ export class BlockSliceAction {
get get() {
return this.params[1]
}
addBlock(block: Omit<AIChatContextBlock, "id">) {
addBlock(block: AIChatContextBlockInput) {
const currentBlocks = this.get().blocks
// Only allow one SPECIAL_TYPES
@@ -60,6 +61,10 @@ export class BlockSliceAction {
removeBlock(id: string) {
this.set(
produce((state: BlockSlice) => {
const blockToRemove = state.blocks.find((block) => block.id === id)
if (blockToRemove && blockToRemove.type === "fileAttachment") {
cleanupFileAttachment(blockToRemove.attachment)
}
state.blocks = state.blocks.filter((block) => block.id !== id)
}),
)
@@ -68,9 +73,18 @@ export class BlockSliceAction {
updateBlock(id: string, updates: Partial<AIChatContextBlock>) {
this.set(
produce((state: BlockSlice) => {
state.blocks = state.blocks.map((block) =>
block.id === id ? { ...block, ...updates } : block,
)
state.blocks = state.blocks.map((block) => {
if (block.id !== id) return block
// Handle discriminated union updates carefully
if (updates.type && updates.type !== block.type) {
// Type change - need to replace the entire block
return { ...updates, id } as AIChatContextBlock
} else {
// Same type - safe to spread
return { ...block, ...updates } as AIChatContextBlock
}
})
}),
)
}
@@ -84,10 +98,20 @@ export class BlockSliceAction {
}
}
clearBlocks() {
clearBlocks({ keepSpecialTypes = false }: { keepSpecialTypes?: boolean } = {}) {
this.set(
produce((state: BlockSlice) => {
state.blocks = []
// Clean up file attachments before clearing
state.blocks.forEach((block) => {
if (block.type === "fileAttachment") {
cleanupFileAttachment(block.attachment)
}
})
state.blocks = keepSpecialTypes
? state.blocks.filter((b) =>
Object.values(BlockSliceAction.SPECIAL_TYPES).includes(b.type),
)
: []
}),
)
}
@@ -95,6 +119,12 @@ export class BlockSliceAction {
resetContext() {
this.set(
produce((state: BlockSlice) => {
// Clean up file attachments before resetting
state.blocks.forEach((block) => {
if (block.type === "fileAttachment") {
cleanupFileAttachment(block.attachment)
}
})
state.blocks = []
}),
)
@@ -103,4 +133,49 @@ export class BlockSliceAction {
getBlocks() {
return this.get().blocks
}
// File attachment specific methods
addFileAttachment(fileAttachment: FileAttachment) {
const fileBlock: AIChatContextBlock = {
id: fileAttachment.id,
type: "fileAttachment",
attachment: fileAttachment,
}
this.addBlock(fileBlock)
}
updateFileAttachment(attachmentId: string, updatedAttachment: FileAttachment) {
this.set(
produce((state: BlockSlice) => {
const block = state.blocks.find(
(b) => b.type === "fileAttachment" && b.attachment.id === attachmentId,
)
if (block && block.type === "fileAttachment") {
block.attachment = updatedAttachment
}
}),
)
}
updateFileAttachmentStatus(
fileId: string,
status: FileAttachment["uploadStatus"],
errorMessage?: string,
) {
this.set(
produce((state: BlockSlice) => {
const block = state.blocks.find((b) => b.id === fileId)
if (block && block.type === "fileAttachment") {
block.attachment.uploadStatus = status
if (errorMessage) {
block.attachment.errorMessage = errorMessage
}
}
}),
)
}
removeFileAttachment(fileId: string) {
this.removeBlock(fileId)
}
}
@@ -1,11 +1,40 @@
import type { BizUITools, ToolWithState } from "@folo-services/ai-tools"
export interface AIChatContextBlock {
export interface FileAttachment {
id: string
name: string
type: string
size: number
dataUrl: string
previewUrl?: string
uploadStatus: "processing" | "uploading" | "completed" | "error"
serverUrl?: string
errorMessage?: string
/** Upload progress percentage (0-100) */
uploadProgress?: number
}
interface BaseContextBlock {
id: string
}
export interface ValueContextBlock extends BaseContextBlock {
type: "mainEntry" | "referEntry" | "referFeed" | "selectedText"
value: string
}
export interface FileAttachmentContextBlock extends BaseContextBlock {
type: "fileAttachment"
attachment: FileAttachment
}
export type AIChatContextBlock = ValueContextBlock | FileAttachmentContextBlock
// Helper type for creating new blocks without id
export type AIChatContextBlockInput =
| Omit<ValueContextBlock, "id">
| Omit<FileAttachmentContextBlock, "id">
export interface AIChatStoreInitial {
blocks: AIChatContextBlock[]
}

Some files were not shown because too many files have changed in this diff Show More