From 9a12198d23630e18276b60358b85171b63508618 Mon Sep 17 00:00:00 2001 From: Innei Date: Thu, 7 Aug 2025 18:06:55 +0800 Subject: [PATCH 01/73] fix(ai): handle chat export mention syntax --- .../components/message/AIChatMessage.tsx | 3 ++- .../src/modules/ai-chat/utils/export.ts | 25 ++++++++++++++----- .../src/ui/lexical-rich-editor/editor.tsx | 8 ++++-- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx index 888dd4f24..422c848dd 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx @@ -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" @@ -56,7 +57,7 @@ export const AIChatMessage: React.FC = React.memo(({ message break } case "data-rich-text": { - lexicalEditor ||= createDefaultLexicalEditor() + lexicalEditor ||= createDefaultLexicalEditor([MentionPlugin]) lexicalEditor.setEditorState( lexicalEditor.parseEditorState((part as RichTextPart).data.state), ) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/export.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/export.ts index c85bdb3c9..3367a50b6 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/export.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/export.ts @@ -1,6 +1,7 @@ import type { UIDataTypes, UIMessage } from "ai" import type { BizUIMetadata, BizUITools } from "../store/types" +import type { RichTextPart } from "../types/ChatSession" export const exportChatToMarkdown = ( messages: UIMessage[], @@ -19,11 +20,17 @@ export const exportChatToMarkdown = ( markdown += `## 👤 User\n` if (timestamp) markdown += `*${timestamp}*\n\n` - // Extract text content from parts + // Extract text content from parts in single pass const textContent = message.parts - ?.filter((part) => part.type === "text") - .map((part) => part.text) + ?.reduce((acc, part) => { + if (part.type === "text") { + acc.push(part.text) + } else if (part.type === "data-rich-text") { + acc.push((part as RichTextPart).data.text) + } + return acc + }, [] as string[]) .join("\n") || "" markdown += `${textContent}\n\n` @@ -31,11 +38,17 @@ export const exportChatToMarkdown = ( markdown += `## 🤖 ${APP_NAME} AI\n` if (timestamp) markdown += `*${timestamp}*\n\n` - // Extract text content from parts + // Extract text content from parts in single pass const textContent = message.parts - ?.filter((part) => part.type === "text") - .map((part) => part.text) + ?.reduce((acc, part) => { + if (part.type === "text") { + acc.push(part.text) + } else if (part.type === "data-rich-text") { + acc.push((part as RichTextPart).data.text) + } + return acc + }, [] as string[]) .join("\n") || "" markdown += `${textContent}\n\n` diff --git a/packages/internal/components/src/ui/lexical-rich-editor/editor.tsx b/packages/internal/components/src/ui/lexical-rich-editor/editor.tsx index 4116e32b8..abf8c6ebc 100644 --- a/packages/internal/components/src/ui/lexical-rich-editor/editor.tsx +++ b/packages/internal/components/src/ui/lexical-rich-editor/editor.tsx @@ -3,6 +3,7 @@ import { createEditor } from "lexical" import { LexicalRichEditorNodes } from "./nodes" import { defaultLexicalTheme } from "./theme" +import type { LexicalPluginFC } from "./types" export const createLexicalEditor = (options: CreateEditorArgs) => { const editor = createEditor({ @@ -13,10 +14,13 @@ export const createLexicalEditor = (options: CreateEditorArgs) => { return editor } -export const createDefaultLexicalEditor = () => { +export const createDefaultLexicalEditor = (plugins?: LexicalPluginFC[]) => { + const pluginNodes = plugins?.flatMap((plugin) => plugin.nodes || []) || [] + + const allNodes = [...LexicalRichEditorNodes, ...pluginNodes] return createLexicalEditor({ namespace: "LexicalRichEditor", theme: defaultLexicalTheme, - nodes: LexicalRichEditorNodes, + nodes: allNodes, }) } From c654ca176cbc3b408eaf71cd1e83fd8350383d83 Mon Sep 17 00:00:00 2001 From: Innei Date: Thu, 7 Aug 2025 19:21:13 +0800 Subject: [PATCH 02/73] feat(ai): preview react flow modal - Expand CLAUDE.md with detailed app/package structure - Add full-screen flow chart preview modal to AIDisplayFlowPart - Improve flow chart display and loading element sizing --- CLAUDE.md | 48 ++++++------ .../components/displays/AIDisplayFlowPart.tsx | 75 +++++++++++++++++-- .../components/message/AIMessageParts.tsx | 2 +- 3 files changed, 97 insertions(+), 28 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4a91dad20..f67ec33e3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,18 +10,37 @@ 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) - **`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 ## Essential Commands @@ -69,19 +88,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 diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx index b731e0f69..b55435f09 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx @@ -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 ( +
+ + + + +
+ ) +} + 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: () => , + max: true, + canClose: true, + clickOutsideToDismiss: false, + modalContentClassName: "p-0 h-full", + modalClassName: "h-[90vh] w-[90vw]", + }) + }, [nodes, edges, colorMode, present]) + return ( -
+
+ + + {/* Expand/Preview button */} +
) }, diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx index 8e8f851ca..c48dbcdb3 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx @@ -108,7 +108,7 @@ export const AIMessageParts: React.FC = React.memo(({ message case "tool-displayFlowChart": { const loadingElement = ( -
+
From cb5a2cd1146b116ff7e5ff86d5c10672b9cfa6d3 Mon Sep 17 00:00:00 2001 From: Innei Date: Thu, 7 Aug 2025 20:57:12 +0800 Subject: [PATCH 03/73] feat(ai): support customize chat title --- .github/copilot-instructions.md | 2 +- CLAUDE.md | 88 ++--------- apps/desktop/CLAUDE.md | 116 +++++++++++++++ .../ai-chat/components/layouts/ChatHeader.tsx | 20 ++- .../components/layouts/EditableTitle.tsx | 139 ++++++++++++++++++ .../ai-chat/store/chat-core/chat-actions.ts | 29 ++++ apps/mobile/CLAUDE.md | 44 ++++++ packages/internal/CLAUDE.md | 42 ++++++ 8 files changed, 400 insertions(+), 80 deletions(-) create mode 100644 apps/desktop/CLAUDE.md create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/EditableTitle.tsx create mode 100644 apps/mobile/CLAUDE.md create mode 100644 packages/internal/CLAUDE.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 3ae653d30..449d5945b 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -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 diff --git a/CLAUDE.md b/CLAUDE.md index f67ec33e3..3bc1b586a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,6 +13,8 @@ Follow (Folo) is a modern RSS aggregator and content management platform with mu - **`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 - `src/` - React Native source code - `native/` - Native module implementations @@ -41,6 +43,16 @@ Follow (Folo) is a modern RSS aggregator and content management platform with mu - `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 @@ -108,45 +120,9 @@ pnpm run test - **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 @@ -172,25 +148,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 @@ -204,26 +161,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 @@ -354,7 +298,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 diff --git a/apps/desktop/CLAUDE.md b/apps/desktop/CLAUDE.md new file mode 100644 index 000000000..6c12b5cec --- /dev/null +++ b/apps/desktop/CLAUDE.md @@ -0,0 +1,116 @@ +# 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) + +## Animation with 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 + +**Animation Presets**: + +- **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 diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx index f9b92189a..0cff73f70 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx @@ -7,6 +7,7 @@ import { 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() @@ -32,6 +33,13 @@ export const ChatHeader = () => { }) }, [chatActions, currentTitle, ask, t]) + const handleTitleSave = useCallback( + async (newTitle: string) => { + await chatActions.editChatTitle(newTitle) + }, + [chatActions], + ) + const maskImage = `linear-gradient(to bottom, black 0%, black 75%, transparent 100%)` return (
@@ -46,13 +54,11 @@ export const ChatHeader = () => {
{/* Left side - Title */}
- {currentTitle && ( -

- - {currentTitle} - -

- )} +
{/* Right side - Actions */} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/EditableTitle.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/EditableTitle.tsx new file mode 100644 index 000000000..63f01453a --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/EditableTitle.tsx @@ -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 + 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 ( +
+ 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 && ( +
+ +
+ )} +
+ ) + } + + return ( +
+

+ {displayTitle} +

+ {saveSuccess && ( + + )} + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts index 94e93ae7d..c2f67fe79 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts @@ -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 { diff --git a/apps/mobile/CLAUDE.md b/apps/mobile/CLAUDE.md new file mode 100644 index 000000000..1fb9409bf --- /dev/null +++ b/apps/mobile/CLAUDE.md @@ -0,0 +1,44 @@ +# Mobile App Development Guide + +This file provides specific guidance for developing the React Native mobile application. + +## Architecture + +- **React Native** with Expo for cross-platform mobile development +- **Native modules** in `native/` for platform-specific functionality +- **Web views** in `web-app/` for HTML rendering within the mobile app +- **Shared components** with the desktop app through `packages/internal/` + +## Development Commands + +```bash +# Start Expo development server +pnpm run dev + +# Start with specific platform +pnpm run ios +pnpm run android + +# Clean rebuild (useful for native module changes) +pnpm expo prebuild --clean +``` + +## UIKit Colors for React Native Components + +For react native components (`apps/mobile/**/*`), use Apple UIKit color system with Tailwind classes. **Important**: Always use the correct Tailwind prefix for each color category: + +### System Colors + +- Background: `system-background`, `secondary-system-background`, `tertiary-system-background` +- Grouped: `system-grouped-background`, `secondary-system-grouped-background`, `tertiary-system-grouped-background` +- Labels: `label`, `secondary-label`, `tertiary-label`, `quaternary-label` +- Fills: `system-fill`, `secondary-system-fill`, `tertiary-system-fill`, `quaternary-system-fill` +- Separators: `separator`, `opaque-separator`, `non-opaque-separator` + +### Semantic Colors + +- Core: `red`, `orange`, `yellow`, `green`, `mint`, `teal`, `cyan`, `blue`, `indigo`, `purple`, `pink`, `brown` +- Grays: `gray`, `gray2`, `gray3`, `gray4`, `gray5`, `gray6` +- Interactive: `link`, `placeholder-text` + +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. diff --git a/packages/internal/CLAUDE.md b/packages/internal/CLAUDE.md new file mode 100644 index 000000000..307144e6f --- /dev/null +++ b/packages/internal/CLAUDE.md @@ -0,0 +1,42 @@ +# Internal Packages Development Guide + +This file provides specific guidance for developing shared packages used across all platforms. + +## Overview + +The `packages/internal/` directory contains core shared packages that provide common functionality across desktop, mobile, and SSR applications. + +## Package Structure + +- `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 + +## State Management + +- **Jotai** for atomic state management across all platforms +- **Zustand** for complex state stores (in `packages/internal/store/`) +- **React Query** for server state management + +## Database + +- **Drizzle ORM** with SQLite for local data storage +- Platform-specific database implementations in `packages/internal/database/` +- Migration system with versioned SQL files + +## Component Development Guidelines + +- Shared UI components in `packages/internal/components/` +- Platform-specific components in respective app directories +- Use TypeScript interfaces for component props +- Follow cross-platform compatibility patterns From ab540b23d1f45608db499f19058b9ec57b7aabd1 Mon Sep 17 00:00:00 2001 From: Innei Date: Thu, 7 Aug 2025 22:12:00 +0800 Subject: [PATCH 04/73] feat(ai): chat session sort by updated --- .../components/layouts/ChatMoreDropdown.tsx | 4 ++-- .../src/modules/ai-chat/hooks/useChatHistory.ts | 1 + .../src/modules/ai-chat/services/index.ts | 16 ++++++++++++++-- .../ai-chat/store/chat-core/chat-state.ts | 2 ++ .../src/modules/ai-chat/types/ChatSession.ts | 1 + 5 files changed, 20 insertions(+), 4 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx index 5dd31dd74..2abf265e6 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx @@ -129,8 +129,8 @@ export const ChatMoreDropdown = () => {

- - + + + + {/* Hidden File Input */} + + {/* AI Shortcuts Button */} {enabledShortcuts.length > 0 && ( @@ -231,7 +261,10 @@ const PickerList = ({ const CurrentFeedEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({ onSelect, }) => { - const mainEntryId = useAIChatStore()((s) => s.blocks.find((b) => b.type === "mainEntry")?.value) + 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!) @@ -332,7 +365,7 @@ const FeedPickerItem: FC<{ ) } -const ContextBlock: FC<{ block: AIChatContextBlock }> = ({ block }) => { +const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block }) => { const blockActions = useChatBlockActions() const getBlockIcon = () => { @@ -349,6 +382,17 @@ const ContextBlock: FC<{ block: AIChatContextBlock }> = ({ block }) => { 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" @@ -368,8 +412,80 @@ const ContextBlock: FC<{ block: AIChatContextBlock }> = ({ block }) => { 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 ( +
+
+ + {uploadStatus === "uploading" && uploadProgress !== undefined && ( +
+ +
+ )} + {uploadStatus === "error" && ( +
+ +
+ )} +
+ +
+ {name} + {uploadStatus === "uploading" && uploadProgress !== undefined && ( +
+ Uploading {Math.round(uploadProgress)}% +
+ )} + {uploadStatus === "error" &&
Upload failed
} +
+
+ ) + } + + // For non-image files + return ( +
+ {name} + {uploadStatus === "uploading" && uploadProgress !== undefined && ( +
+ + {Math.round(uploadProgress)}% +
+ )} + {uploadStatus === "error" && ( + + )} +
+ ) + } default: { - return block.value + // This should never happen with proper discriminated union + return "" } } } @@ -388,6 +504,9 @@ const ContextBlock: FC<{ block: AIChatContextBlock }> = ({ block }) => { case "selectedText": { return "Text" } + case "fileAttachment": { + return "File" + } default: { return "" @@ -398,30 +517,43 @@ const ContextBlock: FC<{ block: AIChatContextBlock }> = ({ block }) => { const canRemove = block.type !== "mainEntry" return ( -
-
-
- - {getBlockLabel()} -
+
+
+
+
+ {getBlockIcon() && } + {getBlockLabel()} +
- - {getDisplayContent()} - + + {getDisplayContent()} + +
{canRemove && ( )}
) -} +}) const EntryTitle: FC<{ entryId?: string; fallback: string }> = ({ entryId, fallback }) => { const entryTitle = useEntry(entryId!, (e) => e?.title) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx index cd782d48a..dda33ed26 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx @@ -84,7 +84,13 @@ export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => { }, []) return ( -
+
{/* Input Area */}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx index b4cdce21b..b79d83751 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx @@ -8,7 +8,7 @@ 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, useCallback, useEffect, useState } from "react" import { useEventCallback } from "usehooks-ts" import { @@ -28,6 +28,7 @@ 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" @@ -102,13 +103,29 @@ const ChatInterfaceContent = () => { (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, }, ] @@ -145,7 +162,7 @@ const ChatInterfaceContent = () => { const shouldShowScrollToBottom = hasMessages && !isAtBottom && !isLoadingHistory return ( -
+
{!hasMessages && !isLoadingHistory ? ( @@ -203,7 +220,7 @@ const ChatInterfaceContent = () => { {error && }
-
+ ) } @@ -216,5 +233,9 @@ export const ChatInterface = () => ( const Messages: FC = () => { const messages = useMessages() - return messages.map((message) => ) + return messages.map((message) => ( + + + + )) } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx new file mode 100644 index 000000000..0936a072f --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx @@ -0,0 +1,119 @@ +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 ( + + + present({ + max: true, + title: "Preview Image", + content: () => ( +
+ +
+ ), + }) + } + > + +
+ + +
+ {imageError ? ( +
+
+ + {filename} +
+
+ ) : ( + 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" + /> + )} +
+
+
+
+ ) +} + +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 ( +
+ +
+ ) + } + + return ( +
+ {!imageLoaded && ( +
+ +
+ )} + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx index 422c848dd..14b9cb827 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx @@ -1,5 +1,5 @@ import { createDefaultLexicalEditor } from "@follow/components/ui/lexical-rich-editor/editor.js" -import { stopPropagation } from "@follow/utils" +import { stopPropagation, thenable } from "@follow/utils" import type { UIDataTypes, UIMessage } from "ai" import type { LexicalEditor, SerializedEditorState } from "lexical" import { m } from "motion/react" @@ -31,6 +31,9 @@ interface AIChatMessageProps { } export const AIChatMessage: React.FC = React.memo(({ message }) => { + if (message.parts.length === 0) { + throw thenable + } const chatActions = useChatActions() const messageId = message.id diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockItem.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockItem.tsx new file mode 100644 index 000000000..7fe266a5a --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockItem.tsx @@ -0,0 +1,120 @@ +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 + } + case "referFeed": { + return + } + 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 +}> = React.memo(({ block, styles }) => { + // Handle image thumbnails for file attachments + if (block.type === "fileAttachment" && block.attachment && isImageAttachment(block)) { + return ( +
+ +
+ ) + } + + const iconClass = getBlockIcon(block) + + return ( +
+ +
+ ) +}) + +BlockIcon.displayName = "BlockIcon" + +/** + * Individual block item component with optimized rendering and animations + */ +export const AIDataBlockItem: React.FC = 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 ( +
+ + + {/* Label and content */} +
+ {label} + · + + {displayContent} + +
+
+ ) +}) + +AIDataBlockItem.displayName = "AIDataBlockItem" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockPart.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockPart.tsx index 511cc9b3e..edd09fc5f 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockPart.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockPart.tsx @@ -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 {fallback} - } - - return {entryTitle} -} - -const FeedTitle: React.FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => { - const feed = useFeedById(feedId, (feed) => ({ title: feed?.title })) - if (!feedId || !feed) { - return {fallback} - } - - return {feed.title} -} - -// 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 = 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 - } - case "referFeed": { - return - } - 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 = React.memo(({ blo Context:
- {/* Blocks */} - {blocks.map((block, index) => { - const styles = getBlockStyles(block.type) - - return ( - - {/* Icon */} -
- -
- - {/* Label and content */} -
- - {getBlockLabel(block.type)} - - · - - {getDisplayContent(block)} - -
-
- ) - })} + {/* Render individual block items */} + {blocks.map((block, index) => ( + + ))}
) }) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx index c48dbcdb3..0875fa900 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx @@ -2,7 +2,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 { @@ -34,30 +33,8 @@ const LazyAIDisplayFlowPart = React.lazy(() => interface MessagePartsProps { message: BizUIMessage } -const ThinkingIndicator: React.FC = () => { - return ( -
- - - Thinking... - - -
- ) -} export const AIMessageParts: React.FC = React.memo(({ message }) => { - if (!message.parts || message.parts.length === 0) { - // In AI SDK v5, messages should always have parts - if (message.role === "assistant") { - return - } - return null - } const isUser = message.role === "user" return message.parts.map((part, index) => { diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx index 3227f698b..e639b0d60 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx @@ -25,15 +25,17 @@ interface AIRichTextMessageProps { export const AIRichTextMessage: React.FC = 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, // Read-only mode + editorState: JSON.stringify(data.state), + nodes: [...LexicalRichEditorNodes, MentionNode], + } } - return (
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/BlockTitleComponents.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/BlockTitleComponents.tsx new file mode 100644 index 000000000..27e93f959 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/BlockTitleComponents.tsx @@ -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 = React.memo(({ entryId, fallback }) => { + const entryTitle = useEntry(entryId!, (e) => e?.title) + + if (!entryId || !entryTitle) { + return {fallback} + } + + return {entryTitle} +}) + +EntryTitle.displayName = "EntryTitle" + +/** + * Displays feed title with fallback handling + */ +export const FeedTitle: React.FC = React.memo(({ feedId, fallback }) => { + const feed = useFeedById(feedId, (feed) => ({ title: feed?.title })) + + if (!feedId || !feed?.title) { + return {fallback} + } + + return {feed.title} +}) + +FeedTitle.displayName = "FeedTitle" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ImageThumbnail.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ImageThumbnail.tsx new file mode 100644 index 000000000..b3326b453 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ImageThumbnail.tsx @@ -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 = 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 + } + + return ( +
+ {attachment.name} + {isLoading && ( +
+ +
+ )} +
+ ) + }, +) + +ImageThumbnail.displayName = "ImageThumbnail" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ThinkingIndicator.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ThinkingIndicator.tsx new file mode 100644 index 000000000..2a8d71027 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ThinkingIndicator.tsx @@ -0,0 +1,17 @@ +import { m } from "motion/react" + +export const ThinkingIndicator: React.FC = () => { + return ( +
+ + + Thinking... + + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts new file mode 100644 index 000000000..83fca3284 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts @@ -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 +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/ui/UploadProgress.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/ui/UploadProgress.tsx new file mode 100644 index 000000000..8ddf0f395 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/ui/UploadProgress.tsx @@ -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 = 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 ( +
+ {/* Progress Bar */} +
+ +
+ + {/* Percentage Text */} + {showPercentage && ( +
+ {Math.round(progressValue)}% +
+ )} +
+ ) + }, +) + +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 = 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 ( +
+ + {/* Background circle */} + + + {/* Progress circle */} + + + + {/* Percentage text */} + {showPercentage && ( +
+ {Math.round(progressValue)}% +
+ )} +
+ ) + }, +) + +CircularProgress.displayName = "CircularProgress" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts index f58d78eb4..e0a98af81 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts @@ -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" } @@ -105,7 +105,7 @@ export const useMentionBlockSync = () => { const blockType = getBlockType(mentionData.type) // Generate block ID (mimicking the block slice logic) - const newBlock: Omit = { + const newBlock: Omit = { type: blockType, value: mentionData.value as string, } @@ -115,7 +115,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 => + block.type === blockType && block.value === mentionData.value, ) if (addedBlock) { diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts new file mode 100644 index 000000000..5022b0653 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts @@ -0,0 +1,159 @@ +import { useCallback } from "react" +import { toast } from "sonner" + +import { useChatBlockActions } from "../store/hooks" +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) => Promise + /** + * Upload multiple files with progress tracking + */ + uploadFiles: (files: File[] | FileList) => Promise + /** + * Handle file input change event + */ + handleFileInputChange: (event: React.ChangeEvent) => Promise + /** + * Handle drag and drop files + */ + handleFileDrop: (files: FileList) => Promise +} + +/** + * 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): Promise => { + try { + const result = await processAndUploadFile(file, processOptions, (updatedAttachment) => { + // Update block during upload progress + blockActions.updateFileAttachment(updatedAttachment.id, updatedAttachment) + }) + + if (result.success && result.fileAttachment) { + // Add the completed file attachment to blocks + blockActions.addFileAttachment(result.fileAttachment) + + if (showSuccessToast) { + toast.success(`${successMessage}: ${file.name}`) + } + } else if (showErrorToast && result.error) { + toast.error(`${errorMessagePrefix}: ${result.error}`) + console.error("File upload error:", result.error) + } + + return result + } catch (error) { + const errorMessage = error instanceof Error ? error.message : "Unknown error" + + if (showErrorToast) { + toast.error(`${errorMessagePrefix}: ${errorMessage}`) + } + + console.error("File upload failed:", error) + + return { + success: false, + error: errorMessage, + } + } + }, + [ + blockActions, + processOptions, + showSuccessToast, + showErrorToast, + successMessage, + errorMessagePrefix, + ], + ) + + const uploadFiles = useCallback( + async (files: File[] | FileList): Promise => { + 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) => { + 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, + }) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts index 7f0162dfd..0ca5df28f 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts @@ -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) { + 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) { 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 + } + }) }), ) } @@ -87,6 +101,12 @@ export class BlockSliceAction { clearBlocks() { this.set( produce((state: BlockSlice) => { + // Clean up file attachments before clearing + state.blocks.forEach((block) => { + if (block.type === "fileAttachment") { + cleanupFileAttachment(block.attachment) + } + }) state.blocks = [] }), ) @@ -95,6 +115,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 +129,55 @@ 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(fileId: string, updatedAttachment: FileAttachment) { + this.set( + produce((state: BlockSlice) => { + const block = state.blocks.find((b) => b.id === fileId) + 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) + } + + getFileAttachments() { + return this.get().blocks.filter((block) => block.type === "fileAttachment") + } + + hasFileAttachments() { + return this.get().blocks.some((block) => block.type === "fileAttachment") + } } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts index b2d9a5adc..79567486f 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts @@ -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 + | Omit + export interface AIChatStoreInitial { blocks: AIChatContextBlock[] } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts new file mode 100644 index 000000000..0d5bbd22d --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts @@ -0,0 +1,292 @@ +import { nanoid } from "nanoid" + +import { followApi } from "~/lib/api-client" + +import type { FileAttachment } from "../store/types" +import type { FileValidationResult } from "./file-validation" +import { validateFile } from "./file-validation" + +export interface ProcessFileOptions { + maxImageWidth?: number + maxImageHeight?: number + imageQuality?: number +} + +export interface ProcessFileResult { + success: boolean + fileAttachment?: FileAttachment + error?: string +} + +export async function processFile( + file: File, + options: ProcessFileOptions = {}, +): Promise { + const { maxImageWidth = 1920, maxImageHeight = 1080, imageQuality = 0.85 } = options + + // Validate file + const validation: FileValidationResult = validateFile(file) + if (!validation.isValid) { + return { + success: false, + error: validation.error?.message || "File validation failed", + } + } + + try { + const fileId = nanoid() + let dataUrl: string + let previewUrl: string | undefined + + if (validation.fileInfo?.category === "image") { + // Process image: compress and generate preview + const processedImage = await processImage(file, { + maxWidth: maxImageWidth, + maxHeight: maxImageHeight, + quality: imageQuality, + }) + + dataUrl = processedImage.dataUrl + previewUrl = processedImage.previewUrl + } else { + // For non-images, just convert to data URL + dataUrl = await fileToDataUrl(file) + } + + const fileAttachment: FileAttachment = { + id: fileId, + name: file.name, + type: file.type, + size: file.size, + dataUrl, + previewUrl, + uploadStatus: "completed", + } + + return { + success: true, + fileAttachment, + } + } catch (error) { + return { + success: false, + error: `Failed to process file: ${error instanceof Error ? error.message : "Unknown error"}`, + } + } +} + +interface ProcessImageResult { + dataUrl: string + previewUrl: string +} + +async function processImage( + file: File, + options: { maxWidth: number; maxHeight: number; quality: number }, +): Promise { + return new Promise((resolve, reject) => { + const img = new Image() + const canvas = document.createElement("canvas") + const ctx = canvas.getContext("2d") + + if (!ctx) { + reject(new Error("Could not get canvas context")) + return + } + + img.onload = () => { + // Calculate new dimensions + let { width, height } = img + const { maxWidth, maxHeight, quality } = options + + if (width > maxWidth || height > maxHeight) { + const ratio = Math.min(maxWidth / width, maxHeight / height) + width *= ratio + height *= ratio + } + + // Set canvas dimensions + canvas.width = width + canvas.height = height + + // Draw and compress image + ctx.drawImage(img, 0, 0, width, height) + + const dataUrl = canvas.toDataURL(file.type, quality) + + // Create smaller preview (thumbnail) + const previewCanvas = document.createElement("canvas") + const previewCtx = previewCanvas.getContext("2d") + + if (previewCtx) { + const previewSize = 150 + const previewRatio = Math.min(previewSize / width, previewSize / height) + previewCanvas.width = width * previewRatio + previewCanvas.height = height * previewRatio + + previewCtx.drawImage(img, 0, 0, previewCanvas.width, previewCanvas.height) + const previewUrl = previewCanvas.toDataURL(file.type, 0.7) + + resolve({ dataUrl, previewUrl }) + } else { + resolve({ dataUrl, previewUrl: dataUrl }) + } + } + + img.onerror = () => { + reject(new Error("Failed to load image")) + } + + img.src = URL.createObjectURL(file) + }) +} + +function fileToDataUrl(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader() + + reader.onload = () => { + resolve(reader.result as string) + } + + reader.onerror = () => { + reject(new Error("Failed to read file")) + } + + reader.readAsDataURL(file) + }) +} + +export async function processFileList( + files: FileList, + options?: ProcessFileOptions, +): Promise { + const results: ProcessFileResult[] = [] + + for (const file of files) { + if (file) { + const result = await processFile(file, options) + results.push(result) + } + } + + return results +} + +export function createFileAttachmentBlock(fileAttachment: FileAttachment) { + return { + id: fileAttachment.id, + type: "fileAttachment" as const, + attachment: fileAttachment, + } +} + +// Utility to clean up object URLs to prevent memory leaks +export function cleanupFileAttachment(fileAttachment: FileAttachment) { + if (fileAttachment.previewUrl?.startsWith("blob:")) { + URL.revokeObjectURL(fileAttachment.previewUrl) + } +} + +export async function uploadFileAttachment( + fileAttachment: FileAttachment, + onProgressUpdate?: (attachment: FileAttachment) => void, +): Promise { + try { + // Update status to uploading with 0% progress + let currentAttachment: FileAttachment = { + ...fileAttachment, + uploadStatus: "uploading" as const, + uploadProgress: 0, + } + onProgressUpdate?.(currentAttachment) + + const { dataUrl } = fileAttachment + const blob = await fetch(dataUrl).then((r) => r.blob()) + + // TODO: Replace with real progress tracking when followApi supports it + // Currently followApi.upload.uploadChatAttachment doesn't provide progress callbacks + // Future implementation could use XMLHttpRequest or a custom fetch wrapper + + // Simulate realistic progress updates during upload + // This mimics a realistic upload progression pattern + const progressInterval = setInterval(() => { + if (currentAttachment.uploadProgress! < 85) { + // Start faster, then slow down (realistic network behavior) + const currentProgress = currentAttachment.uploadProgress || 0 + const increment = + currentProgress < 50 + ? Math.random() * 20 + 5 // Fast initial progress + : Math.random() * 8 + 2 // Slower progress as it approaches completion + + currentAttachment = { + ...currentAttachment, + uploadProgress: Math.min(85, currentProgress + increment), + } + onProgressUpdate?.(currentAttachment) + } + }, 150) + + try { + // Actual upload + const response = await followApi.upload.uploadChatAttachment({ file: blob }) + const serverUrl = response.data.url + + // Clear progress interval + clearInterval(progressInterval) + + // Update to 100% and completed status + const completedAttachment: FileAttachment = { + ...fileAttachment, + serverUrl, + uploadStatus: "completed", + uploadProgress: 100, + errorMessage: undefined, + } + + // Show 100% briefly before final callback + onProgressUpdate?.(completedAttachment) + + return completedAttachment + } catch (uploadError) { + clearInterval(progressInterval) + throw uploadError + } + } catch (error) { + // Return attachment with error status + const errorAttachment: FileAttachment = { + ...fileAttachment, + uploadStatus: "error", + uploadProgress: undefined, + errorMessage: error instanceof Error ? error.message : "Upload failed", + } + + return errorAttachment + } +} + +export async function processAndUploadFile( + file: File, + options: ProcessFileOptions = {}, + onProgressUpdate?: (attachment: FileAttachment) => void, +): Promise { + // First process the file locally + const localResult = await processFile(file, options) + + if (!localResult.success || !localResult.fileAttachment) { + return localResult + } + + // Then upload to server + const uploadedAttachment = await uploadFileAttachment( + localResult.fileAttachment, + onProgressUpdate, + ) + + return { + success: uploadedAttachment.uploadStatus === "completed", + fileAttachment: uploadedAttachment, + error: + uploadedAttachment.uploadStatus === "error" ? uploadedAttachment.errorMessage : undefined, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts new file mode 100644 index 000000000..04d53fcc2 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts @@ -0,0 +1,129 @@ +const MAX_IMAGE_ALLOWED_SIZE = 3 * 1024 * 1024 +const MAX_DOCUMENT_ALLOWED_SIZE = 1 * 1024 * 1024 +export const SUPPORTED_FILE_TYPES = { + // Images + "image/png": { extension: "png", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + "image/jpeg": { extension: "jpg", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + "image/jpg": { extension: "jpg", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + "image/webp": { extension: "webp", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + "image/gif": { extension: "gif", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + + // Documents + "application/pdf": { extension: "pdf", category: "document", maxSize: MAX_DOCUMENT_ALLOWED_SIZE }, + "text/plain": { extension: "txt", category: "text", maxSize: MAX_DOCUMENT_ALLOWED_SIZE }, + "text/markdown": { extension: "md", category: "text", maxSize: MAX_DOCUMENT_ALLOWED_SIZE }, +} as const + +export type SupportedFileType = keyof typeof SUPPORTED_FILE_TYPES +export type FileCategory = (typeof SUPPORTED_FILE_TYPES)[SupportedFileType]["category"] + +export interface FileValidationError { + type: "unsupported" | "too_large" | "invalid" + message: string +} + +export interface FileValidationResult { + isValid: boolean + error?: FileValidationError + fileInfo?: { + type: SupportedFileType + category: FileCategory + extension: string + maxSize: number + } +} + +export function validateFile(file: File): FileValidationResult { + const fileType = file.type as SupportedFileType + const fileInfo = SUPPORTED_FILE_TYPES[fileType] + + if (!fileInfo) { + return { + isValid: false, + error: { + type: "unsupported", + message: `File type "${file.type}" is not supported. Supported types: images, PDFs, text files.`, + }, + } + } + + if (file.size > fileInfo.maxSize) { + const maxSizeMB = Math.round(fileInfo.maxSize / (1024 * 1024)) + const fileSizeMB = Math.round((file.size / (1024 * 1024)) * 100) / 100 + return { + isValid: false, + error: { + type: "too_large", + message: `File size (${fileSizeMB}MB) exceeds the maximum allowed size of ${maxSizeMB}MB for ${fileInfo.category} files.`, + }, + } + } + + if (file.size === 0) { + return { + isValid: false, + error: { + type: "invalid", + message: "File appears to be empty or corrupted.", + }, + } + } + + return { + isValid: true, + fileInfo: { + type: fileType, + category: fileInfo.category, + extension: fileInfo.extension, + maxSize: fileInfo.maxSize, + }, + } +} + +export function formatFileSize(bytes: number): string { + if (bytes === 0) return "0 Bytes" + + const k = 1024 + const sizes = ["Bytes", "KB", "MB", "GB"] + const i = Math.floor(Math.log(bytes) / Math.log(k)) + + return `${Number.parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}` +} + +export function getFileCategoryFromMimeType(mimeType: string): FileCategory { + // Images + if (mimeType.startsWith("image/")) { + return "image" + } + + // Documents + if (mimeType === "application/pdf") { + return "document" + } + + // Text files + if (mimeType.startsWith("text/")) { + return "text" + } + + // Default fallback + return "image" +} + +export function getFileIconName(category: FileCategory): string { + switch (category) { + case "image": { + return "i-mgc-pic-cute-re" + } + case "document": { + return "i-mgc-file-cute-re" + } + case "text": { + return "i-mgc-document-cute-re" + } + + default: { + return "i-mgc-attachment-cute-re" + } + } +} diff --git a/apps/mobile/src/icons/add_cute_fi.tsx b/apps/mobile/src/icons/add_cute_fi.tsx index d52502e93..71bd6081c 100644 --- a/apps/mobile/src/icons/add_cute_fi.tsx +++ b/apps/mobile/src/icons/add_cute_fi.tsx @@ -13,10 +13,11 @@ export const AddCuteFiIcon = ({ color = "#10161F", }: AddCuteFiIconProps) => { return ( - + ) diff --git a/apps/mobile/src/icons/ai_cute_fi.tsx b/apps/mobile/src/icons/ai_cute_fi.tsx new file mode 100644 index 000000000..262005ab2 --- /dev/null +++ b/apps/mobile/src/icons/ai_cute_fi.tsx @@ -0,0 +1,20 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface AiCuteFiIconProps { + width?: number + height?: number + color?: string +} + +export const AiCuteFiIcon = ({ width = 24, height = 24, color = "#10161F" }: AiCuteFiIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/arrow_up_circle_cute_fi.tsx b/apps/mobile/src/icons/arrow_up_circle_cute_fi.tsx new file mode 100644 index 000000000..33e7b137f --- /dev/null +++ b/apps/mobile/src/icons/arrow_up_circle_cute_fi.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface ArrowUpCircleCuteFiIconProps { + width?: number + height?: number + color?: string +} + +export const ArrowUpCircleCuteFiIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: ArrowUpCircleCuteFiIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/at_cute_re.tsx b/apps/mobile/src/icons/at_cute_re.tsx new file mode 100644 index 000000000..29da143a6 --- /dev/null +++ b/apps/mobile/src/icons/at_cute_re.tsx @@ -0,0 +1,20 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface AtCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const AtCuteReIcon = ({ width = 24, height = 24, color = "#10161F" }: AtCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/attachment_cute_re.tsx b/apps/mobile/src/icons/attachment_cute_re.tsx new file mode 100644 index 000000000..e350c551c --- /dev/null +++ b/apps/mobile/src/icons/attachment_cute_re.tsx @@ -0,0 +1,25 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface AttachmentCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const AttachmentCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: AttachmentCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/bookmark_cute_re.tsx b/apps/mobile/src/icons/bookmark_cute_re.tsx new file mode 100644 index 000000000..628e2f187 --- /dev/null +++ b/apps/mobile/src/icons/bookmark_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface BookmarkCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const BookmarkCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: BookmarkCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/comment_2_cute_re.tsx b/apps/mobile/src/icons/comment_2_cute_re.tsx new file mode 100644 index 000000000..5cb0c6a65 --- /dev/null +++ b/apps/mobile/src/icons/comment_2_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface Comment2CuteReIconProps { + width?: number + height?: number + color?: string +} + +export const Comment2CuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: Comment2CuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/comment_cute_fi.tsx b/apps/mobile/src/icons/comment_cute_fi.tsx new file mode 100644 index 000000000..b551b9f4b --- /dev/null +++ b/apps/mobile/src/icons/comment_cute_fi.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface CommentCuteFiIconProps { + width?: number + height?: number + color?: string +} + +export const CommentCuteFiIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: CommentCuteFiIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/comment_cute_li.tsx b/apps/mobile/src/icons/comment_cute_li.tsx new file mode 100644 index 000000000..5d3a74c45 --- /dev/null +++ b/apps/mobile/src/icons/comment_cute_li.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface CommentCuteLiIconProps { + width?: number + height?: number + color?: string +} + +export const CommentCuteLiIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: CommentCuteLiIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/comment_cute_re.tsx b/apps/mobile/src/icons/comment_cute_re.tsx new file mode 100644 index 000000000..18b4ede3b --- /dev/null +++ b/apps/mobile/src/icons/comment_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface CommentCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const CommentCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: CommentCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/documents_cute_re.tsx b/apps/mobile/src/icons/documents_cute_re.tsx new file mode 100644 index 000000000..5ee84333f --- /dev/null +++ b/apps/mobile/src/icons/documents_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface DocumentsCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const DocumentsCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: DocumentsCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/history_cute_re.tsx b/apps/mobile/src/icons/history_cute_re.tsx new file mode 100644 index 000000000..3a48d5c53 --- /dev/null +++ b/apps/mobile/src/icons/history_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface HistoryCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const HistoryCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: HistoryCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/mic_cute_re.tsx b/apps/mobile/src/icons/mic_cute_re.tsx new file mode 100644 index 000000000..d135189e1 --- /dev/null +++ b/apps/mobile/src/icons/mic_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface MicCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const MicCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: MicCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/mind_map_cute_re.tsx b/apps/mobile/src/icons/mind_map_cute_re.tsx new file mode 100644 index 000000000..b20c5ac48 --- /dev/null +++ b/apps/mobile/src/icons/mind_map_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface MindMapCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const MindMapCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: MindMapCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/pic_cute_re.tsx b/apps/mobile/src/icons/pic_cute_re.tsx new file mode 100644 index 000000000..2272821a1 --- /dev/null +++ b/apps/mobile/src/icons/pic_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface PicCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const PicCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: PicCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/save_cute_re.tsx b/apps/mobile/src/icons/save_cute_re.tsx new file mode 100644 index 000000000..57e985004 --- /dev/null +++ b/apps/mobile/src/icons/save_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface SaveCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const SaveCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: SaveCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/search_cute_re.tsx b/apps/mobile/src/icons/search_cute_re.tsx new file mode 100644 index 000000000..3b5816352 --- /dev/null +++ b/apps/mobile/src/icons/search_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface SearchCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const SearchCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: SearchCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/send_plane_cute_fi.tsx b/apps/mobile/src/icons/send_plane_cute_fi.tsx new file mode 100644 index 000000000..4bbb772d1 --- /dev/null +++ b/apps/mobile/src/icons/send_plane_cute_fi.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface SendPlaneCuteFiIconProps { + width?: number + height?: number + color?: string +} + +export const SendPlaneCuteFiIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: SendPlaneCuteFiIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/send_plane_cute_re.tsx b/apps/mobile/src/icons/send_plane_cute_re.tsx new file mode 100644 index 000000000..bdad54ca5 --- /dev/null +++ b/apps/mobile/src/icons/send_plane_cute_re.tsx @@ -0,0 +1,24 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface SendPlaneCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const SendPlaneCuteReIcon = ({ + width = 24, + height = 24, + color = "#10161F", +}: SendPlaneCuteReIconProps) => { + return ( + + + + ) +} diff --git a/apps/mobile/src/icons/up_cute_re.tsx b/apps/mobile/src/icons/up_cute_re.tsx new file mode 100644 index 000000000..0c31fa2df --- /dev/null +++ b/apps/mobile/src/icons/up_cute_re.tsx @@ -0,0 +1,20 @@ +import * as React from "react" +import Svg, { Path } from "react-native-svg" + +interface UpCuteReIconProps { + width?: number + height?: number + color?: string +} + +export const UpCuteReIcon = ({ width = 24, height = 24, color = "#10161F" }: UpCuteReIconProps) => { + return ( + + + + ) +} diff --git a/icons/mgc/attachment_cute_re.svg b/icons/mgc/attachment_cute_re.svg new file mode 100644 index 000000000..e0e6a58ae --- /dev/null +++ b/icons/mgc/attachment_cute_re.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5a6f780cb..3466db906 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,8 +7,8 @@ settings: catalogs: default: '@follow-app/client-sdk': - specifier: 0.3.27 - version: 0.3.27 + specifier: 0.3.29 + version: 0.3.29 typescript: specifier: 5.8.3 version: 5.8.3 @@ -462,7 +462,7 @@ importers: version: 3.0.2(electron@37.2.0) '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.27(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.29(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/database': specifier: workspace:* version: link:../../../../packages/internal/database @@ -762,8 +762,8 @@ importers: specifier: workspace:* version: link:../../../../packages/internal/utils '@folo-services/ai-tools': - specifier: 0.2.19 - version: 0.2.19(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + specifier: 0.2.20 + version: 0.2.20(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@types/node': specifier: 24.0.10 version: 24.0.10 @@ -1670,7 +1670,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.27(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.29(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/configs': specifier: workspace:* version: link:../../configs @@ -1682,7 +1682,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.27(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.29(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/constants': specifier: workspace:* version: link:../constants @@ -1760,7 +1760,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.27(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.29(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/constants': specifier: workspace:* version: link:../constants @@ -1824,7 +1824,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.27(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.29(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/configs': specifier: workspace:* version: link:../../configs @@ -4048,23 +4048,23 @@ packages: '@floating-ui/utils@0.2.10': resolution: {integrity: sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==} - '@follow-app/client-sdk@0.3.27': - resolution: {integrity: sha512-Zr4XtFpZ+Gx+CFxcqJwNTSqv0UaKfb5WKMxbHrJ/a9dzdL1MvkAnvO50sx5ViOCLur+bimgz9Epx8+4qGq5VTg==} + '@follow-app/client-sdk@0.3.29': + resolution: {integrity: sha512-bQgY0S6xrWO0iLO4eeptU4vxcmQ36iSrLl6omNscK6SCXzlebCYRmqQy7dsFHU4+bditADjjLulCGWmbDX9IJQ==} - '@folo-services/ai-tools@0.2.19': - resolution: {integrity: sha512-izmFV5zz7HvlyvMGQQS2xNZS/H6QjH+Uvw0n7AywTwkBsvAR1qHsuOGfNTEhb0mRr3EZumk0g9NlA73nmG6v2g==} + '@folo-services/ai-tools@0.2.20': + resolution: {integrity: sha512-1AJI48H2g64JhuTruSqQKUrn4Tc353hMFdKAbohh65AxTAMN/1pIw9w17Dtjm+g5BVlZUXYKaiIvaN9tHsXLNA==} - '@folo-services/constants@0.1.17': - resolution: {integrity: sha512-IR+X76A/ScNj9jvgKdHv9Q1ozGlRo6ayEOpEAG3mwy1adlJdyG2eDlwHsUSMj9kiQUTwDF2JryG0GF32KkmUMw==} + '@folo-services/constants@0.1.18': + resolution: {integrity: sha512-3LDxX4Ebvr6GLdL5Ce2ZkAJwfNjfsdqOLpuFRZ3bq2gVwQZbIGsln+qYnInmR5+1i3DtebglrAj/IktnT3BsIg==} - '@folo-services/drizzle@0.1.12': - resolution: {integrity: sha512-CZmid9EyOi2DDGW3s/lQWNTNt1wPHUqTSDDPZqpC3mlou/m/N4e+kZxpDJ+LY1cmXyP7cPQO9H1tDlXesmItiw==} + '@folo-services/drizzle@0.1.13': + resolution: {integrity: sha512-h6tndGnTLrAmfvxK5XsXGdZaMi2GBmFZBFiBqtabC7Y05A1ZSOaWg/d9f60Ydh586LmVonz5VGrhvzTdn5ukhg==} - '@folo-services/exceptions@0.1.10': - resolution: {integrity: sha512-54ShG+RYYnXarjdxPyC1SSqIeAIbQimB/iBBRgt+LzHp9jMTenjU2CfP7RiYpgwCrS5tNz6eH+cNjZdWa6jTag==} + '@folo-services/exceptions@0.1.11': + resolution: {integrity: sha512-OMKat8KcIxjw9pBfG3pC1kRcIs0YiuaYmMDA2MRy8AEGcki8F9u5e5QH7OKgP/LlNR7Fs2Csz1XetvcC4nB+RQ==} - '@folo-services/shared@0.0.7': - resolution: {integrity: sha512-Tb94/bSFU2vXwg/JUSjeGFoDhPyv9NANa19P0L/ohNsEvymSXyjdmkpKowkw4+CQEhNiSkROTDjPJylO6nIm8g==} + '@folo-services/shared@0.0.8': + resolution: {integrity: sha512-rfl1vvGMxUnchckGSKOkeT5hS1NAzZTJ8gPF6yFR+TuSe2SZzq1a10/66nK9OxmqaDFaHdOpQfNXz2vp0gRJpg==} '@fontsource/sn-pro@5.2.5': resolution: {integrity: sha512-rBdBv/0ygj6bkO7xDMMFpwobLdSrcQ2Jncb6DIwdeYGoAgeWkQRwVYhGDKasfLjEYCNYxrqr6wsXsM9+aU39RA==} @@ -18921,12 +18921,12 @@ snapshots: '@floating-ui/utils@0.2.10': {} - '@follow-app/client-sdk@0.3.27(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3)': + '@follow-app/client-sdk@0.3.29(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3)': dependencies: - '@folo-services/constants': 0.1.17 - '@folo-services/drizzle': 0.1.12(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2) - '@folo-services/exceptions': 0.1.10 - '@folo-services/shared': 0.0.7(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + '@folo-services/constants': 0.1.18 + '@folo-services/drizzle': 0.1.13(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2) + '@folo-services/exceptions': 0.1.11 + '@folo-services/shared': 0.0.8(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) zod: 3.25.76 transitivePeerDependencies: - '@aws-sdk/client-rds-data' @@ -18960,10 +18960,10 @@ snapshots: - sql.js - sqlite3 - '@folo-services/ai-tools@0.2.19(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3)': + '@folo-services/ai-tools@0.2.20(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3)': dependencies: '@ai-sdk/openai': 2.0.2(zod@3.25.76) - '@folo-services/drizzle': 0.1.12(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2) + '@folo-services/drizzle': 0.1.13(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2) ai: 5.0.4(zod@3.25.76) drizzle-orm: 0.44.3(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) zod: 3.25.76 @@ -18999,13 +18999,13 @@ snapshots: - sql.js - sqlite3 - '@folo-services/constants@0.1.17': + '@folo-services/constants@0.1.18': dependencies: zod: 3.25.76 - '@folo-services/drizzle@0.1.12(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)': + '@folo-services/drizzle@0.1.13(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)': dependencies: - '@folo-services/exceptions': 0.1.10 + '@folo-services/exceptions': 0.1.11 drizzle-orm: 0.44.3(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) drizzle-zod: 0.7.1(drizzle-orm@0.44.3(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3))(zod@3.25.76) nanoid: 5.1.5 @@ -19042,11 +19042,11 @@ snapshots: - sql.js - sqlite3 - '@folo-services/exceptions@0.1.10': {} + '@folo-services/exceptions@0.1.11': {} - '@folo-services/shared@0.0.7(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3)': + '@folo-services/shared@0.0.8(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3)': dependencies: - '@folo-services/drizzle': 0.1.12(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2) + '@folo-services/drizzle': 0.1.13(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2) drizzle-orm: 0.44.3(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) drizzle-zod: 0.7.1(drizzle-orm@0.44.3(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3))(zod@3.25.76) zod: 3.25.76 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 1abc59877..aa757362d 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -58,4 +58,4 @@ overrides: catalog: typescript: "5.8.3" - "@follow-app/client-sdk": "0.3.27" + "@follow-app/client-sdk": "0.3.29" From 53ef23074b062693c51f5131ba346ce560ab08a9 Mon Sep 17 00:00:00 2001 From: Innei Date: Sat, 9 Aug 2025 00:17:40 +0800 Subject: [PATCH 07/73] refactor(ai-file): cleanup and re-structure codebase - Added FileAttachmentNode to handle file attachments in the editor. - Introduced FileUploadPlugin to manage file uploads via drag-and-drop and paste. - Created hooks for file upload integration and synchronization with chat blocks. - Implemented UI components for file drop zone and file attachment display. - Enhanced error handling and progress tracking during file uploads. - Updated existing components to support new file attachment features. Signed-off-by: Innei --- .../context-bar/blocks/ContextBlock.tsx | 208 ++++++++ .../context-bar/blocks/TitleComponents.tsx | 22 + .../components/context-bar/blocks/index.ts | 2 + .../ai-chat/components/context-bar/index.ts | 3 + .../context-bar/menus/ContextMenuContent.tsx | 71 +++ .../menus/ShortcutsMenuContent.tsx | 50 ++ .../components/context-bar/menus/index.ts | 2 + .../context-bar/pickers/EntryPickers.tsx | 57 ++ .../context-bar/pickers/FeedPickers.tsx | 59 ++ .../context-bar/pickers/PickerList.tsx | 75 +++ .../context-bar/pickers/SearchInput.tsx | 14 + .../components/context-bar/pickers/index.ts | 4 + .../components/file/GlobalFileDropZone.tsx | 53 -- .../components/layouts/AIChatContextBar.tsx | 504 +----------------- .../ai-chat/components/layouts/ChatHeader.tsx | 6 +- .../ai-chat/components/layouts/ChatInput.tsx | 12 +- .../components/layouts/ChatInterface.tsx | 8 +- .../components/layouts/ImageThumbnail.tsx | 1 + .../components/message/AIDataBlockItem.tsx | 3 +- .../components/message/AIMessageParts.tsx | 3 +- .../components/message/AIRichTextMessage.tsx | 9 +- .../file-upload/FileAttachmentNode.tsx | 168 ++++++ .../plugins/file-upload/FileUploadPlugin.tsx | 157 ++++++ .../file-upload/components/FileDropZone.tsx | 73 +++ .../hooks/useFileAttachmentBlockSync.ts | 231 ++++++++ .../hooks/useFileUploadIntegration.ts | 96 ++++ .../editor/plugins/file-upload/index.ts | 3 + .../editor/plugins/file-upload/types.ts | 15 + .../file-upload/utils/file-handling.ts | 52 ++ .../modules/ai-chat/editor/plugins/index.tsx | 1 + .../mention/hooks/useMentionBlockSync.ts | 23 +- .../modules/ai-chat/hooks/useFileUpload.ts | 78 ++- .../src/modules/ai-chat/store/hooks.ts | 38 -- .../ai-chat/store/slices/block.slice.ts | 14 +- .../modules/ai-chat/utils/file-processing.ts | 7 +- .../modules/ai-chat/utils/file-validation.ts | 1 + 36 files changed, 1482 insertions(+), 641 deletions(-) create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/TitleComponents.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/index.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/index.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ContextMenuContent.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ShortcutsMenuContent.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/index.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/EntryPickers.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/FeedPickers.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/PickerList.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/SearchInput.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/index.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileAttachmentNode.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileUploadPlugin.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/components/FileDropZone.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileAttachmentBlockSync.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileUploadIntegration.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/index.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/types.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/utils/file-handling.ts diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx new file mode 100644 index 000000000..6551f1415 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx @@ -0,0 +1,208 @@ +import { 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 + } + case "referFeed": { + return + } + 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 ( +
+
+ + {uploadStatus === "uploading" && uploadProgress !== undefined && ( +
+ +
+ )} + {uploadStatus === "error" && ( +
+ +
+ )} +
+ +
+ + {name}{" "} + {uploadStatus === "uploading" && uploadProgress !== undefined && ( +
+ ({Math.round(uploadProgress)}%) +
+ )} +
+ + {uploadStatus === "error" &&
Upload failed
} +
+
+ ) + } + + // For non-image files + return ( +
+ {name} + {uploadStatus === "uploading" && uploadProgress !== undefined && ( +
+ + {Math.round(uploadProgress)}% +
+ )} + {uploadStatus === "error" && ( + + )} +
+ ) + } + 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 ( +
+
+
+
+ {getBlockIcon() && } + {getBlockLabel()} +
+ + + {getDisplayContent()} + +
+
+ + {canRemove && ( + + )} +
+ ) +}) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/TitleComponents.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/TitleComponents.tsx new file mode 100644 index 000000000..5dae8b520 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/TitleComponents.tsx @@ -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 {fallback} + } + + return {entryTitle} +} + +export const FeedTitle: FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => { + const feed = useFeedById(feedId, (feed) => ({ title: feed?.title })) + if (!feedId || !feed) { + return {fallback} + } + + return {feed.title} +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/index.ts new file mode 100644 index 000000000..a56ac358c --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/index.ts @@ -0,0 +1,2 @@ +export * from "./ContextBlock" +export * from "./TitleComponents" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/index.ts new file mode 100644 index 000000000..c738c4322 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/index.ts @@ -0,0 +1,3 @@ +export * from "./blocks" +export * from "./menus" +export * from "./pickers" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ContextMenuContent.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ContextMenuContent.tsx new file mode 100644 index 000000000..26e84e174 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ContextMenuContent.tsx @@ -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 ( + + + + + Current Feed Entries + + + + blockActions.addBlock({ + type: "referEntry", + value: entryId, + }) + } + /> + + + + + + + + Reference Entry + + + + blockActions.addBlock({ + type: "referEntry", + value: entryId, + }) + } + /> + + + + + + Reference Feed + + + + blockActions.addBlock({ + type: "referFeed", + value: feedId, + }) + } + /> + + + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ShortcutsMenuContent.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ShortcutsMenuContent.tsx new file mode 100644 index 000000000..60c8ce996 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ShortcutsMenuContent.tsx @@ -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 = ({ + shortcuts, + onSendShortcut, +}) => { + const showSettingModal = useSettingModal() + const enabledShortcuts = shortcuts.filter((shortcut) => shortcut.enabled) + + return ( + + {enabledShortcuts.length === 0 ? ( +
No shortcuts configured
+ ) : ( + enabledShortcuts.map((shortcut) => ( + onSendShortcut?.(shortcut.prompt)}> + + {shortcut.name} + + )) + )} + + { + showSettingModal("ai") + }} + > + + Manage Shortcut + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/index.ts new file mode 100644 index 000000000..40b4ecebe --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/index.ts @@ -0,0 +1,2 @@ +export * from "./ContextMenuContent" +export * from "./ShortcutsMenuContent" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/EntryPickers.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/EntryPickers.tsx new file mode 100644 index 000000000..e23e1e361 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/EntryPickers.tsx @@ -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 +} + +export const RecentEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({ + onSelect, +}) => { + const view = useRouteParamsSelector((route) => route.view) + const recentEntryIds = useEntryIdsByView(view, false) + + return +} + +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 ( + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/FeedPickers.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/FeedPickers.tsx new file mode 100644 index 000000000..0fb147d92 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/FeedPickers.tsx @@ -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 ( + ( + + )} + /> + ) +} + +// 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 ( + onSelect(feedId)} className="text-xs"> + {displayTitle} + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/PickerList.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/PickerList.tsx new file mode 100644 index 000000000..fc2902ae8 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/PickerList.tsx @@ -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 { + items: T[] + placeholder: string + onSelect: (id: string) => void + renderItem?: (item: T, onSelect: (id: string) => void) => React.ReactNode + noResultsText?: string +} + +export const PickerList = ({ + items, + placeholder, + onSelect, + renderItem, + noResultsText = "No items found", +}: PickerListProps) => { + 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) => ( + onSelect(item.id)} className="text-xs"> + {item.title} + + ) + + return ( +
+ { + debouncedSetSearchTerm(e.target.value) + }} + /> +
+ {filteredItems.length === 0 ? ( +
{noResultsText}
+ ) : ( + filteredItems.map((item) => + renderItem ? renderItem(item, onSelect) : defaultRenderItem(item, onSelect), + ) + )} +
+
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/SearchInput.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/SearchInput.tsx new file mode 100644 index 000000000..0ff5b2813 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/SearchInput.tsx @@ -0,0 +1,14 @@ +import type { FC } from "react" + +export const SearchInput: FC> = (props) => { + return ( +
+ + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/index.ts new file mode 100644 index 000000000..58a4b8075 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/index.ts @@ -0,0 +1,4 @@ +export * from "./EntryPickers" +export * from "./FeedPickers" +export * from "./PickerList" +export * from "./SearchInput" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/file/GlobalFileDropZone.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/file/GlobalFileDropZone.tsx index 8b4342f51..7b126bdc0 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/file/GlobalFileDropZone.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/file/GlobalFileDropZone.tsx @@ -5,8 +5,6 @@ import type { FC, PropsWithChildren } from "react" import { memo, useCallback, useRef, useState } from "react" import { useFileUploadWithDefaults } from "../../hooks/useFileUpload" -import { useAIChatStore } from "../../store/AIChatContext" -import { UploadProgress } from "../ui/UploadProgress" interface GlobalFileDropZoneProps extends PropsWithChildren { className?: string @@ -18,15 +16,6 @@ export const GlobalFileDropZone: FC = memo(({ children, const [isProcessing, setIsProcessing] = useState(false) const dragCounterRef = useRef(0) - // Get uploading files from the store - const blocks = useAIChatStore()((s) => s.blocks) - const uploadingFiles = blocks - .filter( - (block): block is Extract => - block.type === "fileAttachment" && block.attachment.uploadStatus === "uploading", - ) - .map((block) => block.attachment) - const handleDragEnter = useCallback((e: React.DragEvent) => { e.preventDefault() e.stopPropagation() @@ -150,48 +139,6 @@ export const GlobalFileDropZone: FC = memo(({ children, )} - - {/* Upload Progress Overlay */} - - {uploadingFiles.length > 0 && ( - - -
- - - Uploading {uploadingFiles.length} file{uploadingFiles.length !== 1 ? "s" : ""} - -
- -
- {uploadingFiles.map((file) => ( -
-
- - {file.name} - - - {file.uploadProgress ? Math.round(file.uploadProgress) : 0}% - -
- -
- ))} -
-
-
- )} -
) }) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatContextBar.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatContextBar.tsx index 9e5311181..814709fec 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatContextBar.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatContextBar.tsx @@ -1,41 +1,18 @@ -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, useCallback, useMemo, useRef, 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 { useFileUploadWithDefaults } from "../../hooks/useFileUpload" -import { useChatBlockActions } from "../../store/hooks" -import { getFileCategoryFromMimeType, getFileIconName } from "../../utils/file-validation" -import { CircularProgress } from "../ui/UploadProgress" -import { ImageThumbnail } from "./ImageThumbnail" +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(null) const { handleFileInputChange } = useFileUploadWithDefaults() @@ -46,89 +23,9 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => [shortcuts], ) - const showSettingModal = useSettingModal() - const handleAttachFile = useCallback(() => { fileInputRef.current?.click() }, []) - const contextMenuContent = ( - - - - - Current Feed Entries - - - - blockActions.addBlock({ - type: "referEntry", - value: entryId, - }) - } - /> - - - - - - - - Reference Entry - - - - blockActions.addBlock({ - type: "referEntry", - value: entryId, - }) - } - /> - - - - - - Reference Feed - - - - blockActions.addBlock({ - type: "referFeed", - value: feedId, - }) - } - /> - - - - ) - - const shortcutsMenuContent = ( - - {enabledShortcuts.length === 0 ? ( -
No shortcuts configured
- ) : ( - enabledShortcuts.map((shortcut) => ( - onSendShortcut?.(shortcut.prompt)}> - - {shortcut.name} - - )) - )} - - { - showSettingModal("ai") - }} - > - - Manage Shortcut - -
- ) return (
@@ -142,7 +39,7 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => - {contextMenuContent} + {/* File Upload Button */} @@ -160,7 +57,7 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => ref={fileInputRef} type="file" multiple - accept="image/*,.pdf,.txt,.md" + accept={SUPPORTED_MIME_ACCEPT} onChange={handleFileInputChange} className="hidden" /> @@ -177,7 +74,7 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => - {shortcutsMenuContent} + )} @@ -190,386 +87,3 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => }, ) AIChatContextBar.displayName = "AIChatContextBar" - -// Generic Picker Component -interface PickerItem { - id: string - title: string -} - -interface PickerListProps { - items: T[] - placeholder: string - onSelect: (id: string) => void - renderItem?: (item: T, onSelect: (id: string) => void) => React.ReactNode - noResultsText?: string -} - -const PickerList = ({ - items, - placeholder, - onSelect, - renderItem, - noResultsText = "No items found", -}: PickerListProps) => { - 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) => ( - onSelect(item.id)} className="text-xs"> - {item.title} - - ) - - return ( -
- { - debouncedSetSearchTerm(e.target.value) - }} - /> -
- {filteredItems.length === 0 ? ( -
{noResultsText}
- ) : ( - filteredItems.map((item) => - renderItem ? renderItem(item, onSelect) : defaultRenderItem(item, onSelect), - ) - )} -
-
- ) -} - -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 -} - -const RecentEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({ onSelect }) => { - const view = useRouteParamsSelector((route) => route.view) - const recentEntryIds = useEntryIdsByView(view, false) - - return -} - -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 ( - - ) -} - -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 ( - ( - - )} - /> - ) -} - -const SearchInput: FC> = (props) => { - return ( -
- - -
- ) -} - -// 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 ( - onSelect(feedId)} className="text-xs"> - {displayTitle} - - ) -} - -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 - } - case "referFeed": { - return - } - 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 ( -
-
- - {uploadStatus === "uploading" && uploadProgress !== undefined && ( -
- -
- )} - {uploadStatus === "error" && ( -
- -
- )} -
- -
- {name} - {uploadStatus === "uploading" && uploadProgress !== undefined && ( -
- Uploading {Math.round(uploadProgress)}% -
- )} - {uploadStatus === "error" &&
Upload failed
} -
-
- ) - } - - // For non-image files - return ( -
- {name} - {uploadStatus === "uploading" && uploadProgress !== undefined && ( -
- - {Math.round(uploadProgress)}% -
- )} - {uploadStatus === "error" && ( - - )} -
- ) - } - 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 ( -
-
-
-
- {getBlockIcon() && } - {getBlockLabel()} -
- - - {getDisplayContent()} - -
-
- - {canRemove && ( - - )} -
- ) -}) - -const EntryTitle: FC<{ entryId?: string; fallback: string }> = ({ entryId, fallback }) => { - const entryTitle = useEntry(entryId!, (e) => e?.title) - - if (!entryId || !entryTitle) { - return {fallback} - } - - return {entryTitle} -} - -const FeedTitle: FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => { - const feed = useFeedById(feedId, (feed) => ({ title: feed?.title })) - if (!feedId || !feed) { - return {fallback} - } - - return {feed.title} -} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx index 0cff73f70..b45c61ec5 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx @@ -3,7 +3,7 @@ import { useCallback } from "react" import { useTranslation } from "react-i18next" 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" @@ -14,6 +14,7 @@ export const ChatHeader = () => { const settingModalPresent = useSettingModal() const chatActions = useChatActions() + const blockActions = useBlockActions() const { ask } = useDialog() const { t } = useTranslation("ai") @@ -29,9 +30,10 @@ export const ChatHeader = () => { variant: "danger", onConfirm: () => { chatActions.newChat() + blockActions.clearBlocks() }, }) - }, [chatActions, currentTitle, ask, t]) + }, [chatActions, currentTitle, ask, t, blockActions]) const handleTitleSave = useCallback( async (newTitle: string) => { diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx index dda33ed26..803121255 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx @@ -10,7 +10,7 @@ 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" @@ -84,13 +84,7 @@ export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => { }, []) return ( -
+
{/* Input Area */}
@@ -101,7 +95,7 @@ export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => { onChange={handleEditorChange} onKeyDown={handleKeyDown} autoFocus - plugins={[MentionPlugin]} + plugins={[MentionPlugin, FileUploadPlugin]} namespace="AIChatRichEditor" /> diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx index b79d83751..b18eb8c04 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx @@ -42,6 +42,12 @@ const ChatInterfaceContent = () => { const chatActions = useChatActions() const error = useChatError() + useEffect(() => { + if (error) { + console.error("AIChat Error:", error) + } + }, [error]) + const currentChatId = useCurrentChatId() const [scrollAreaRef, setScrollAreaRef] = useState(null) @@ -138,7 +144,7 @@ const ChatInterfaceContent = () => { parts.push({ type: "data-rich-text", data: { - state: message.toJSON(), + state: JSON.stringify(message.toJSON()), text: convertLexicalToMarkdown(editor), }, }) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx index 0936a072f..d19c3b9dc 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx @@ -15,6 +15,7 @@ export const ImageThumbnail: FC<{ }> = ({ previewUrl, originalUrl, alt, filename, className }) => { const [imageError, setImageError] = React.useState(false) const { present } = useModalStack() + return ( = React.memo(({ blo 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 transition-all duration-200", - "hover:scale-105 hover:shadow-md", + "border bg-gradient-to-r backdrop-blur-sm", styles.container, )} > diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx index 0875fa900..a0386fa16 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx @@ -1,7 +1,6 @@ import "@xyflow/react/dist/style.css" import type { ToolUIPart } from "ai" -import type { SerializedEditorState } from "lexical" import * as React from "react" import type { @@ -62,7 +61,7 @@ export const AIMessageParts: React.FC = React.memo(({ message return ( ) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx index e639b0d60..ae4167ad6 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx @@ -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 @@ -31,9 +32,9 @@ export const AIRichTextMessage: React.FC = React.memo( namespace: "AIRichTextDisplay", theme: defaultLexicalTheme, onError, - editable: false, // Read-only mode - editorState: JSON.stringify(data.state), - nodes: [...LexicalRichEditorNodes, MentionNode], + editable: false, + editorState: typeof data.state === "object" ? JSON.stringify(data.state) : data.state, + nodes: [...LexicalRichEditorNodes, MentionNode, FileAttachmentNode], } } return ( diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileAttachmentNode.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileAttachmentNode.tsx new file mode 100644 index 000000000..adefffe4f --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileAttachmentNode.tsx @@ -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 { + __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 + } + + 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 ( + + + File not found + + ) + } + + return ( + + + + {fileAttachment.name} + + {fileAttachment.uploadStatus === "uploading" && ( + + )} + {fileAttachment.uploadStatus === "processing" && ( + + )} + {fileAttachment.uploadStatus === "error" && } + {fileAttachment.uploadStatus === "completed" && ( + + )} + + ) +} + +export function $createFileAttachmentNode(attachmentId: string): FileAttachmentNode { + return new FileAttachmentNode(attachmentId) +} + +export function $isFileAttachmentNode( + node: LexicalNode | null | undefined, +): node is FileAttachmentNode { + return node instanceof FileAttachmentNode +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileUploadPlugin.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileUploadPlugin.tsx new file mode 100644 index 000000000..db29fe467 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileUploadPlugin.tsx @@ -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> = 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] diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/components/FileDropZone.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/components/FileDropZone.tsx new file mode 100644 index 000000000..bb7a814a4 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/components/FileDropZone.tsx @@ -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 ( + + {isVisible && ( + + {/* Backdrop */} + + + {/* Drop zone content */} + + + + + +

+ {isDragOver ? "Drop files to upload" : "Drag files here to upload"} +

+ +

+ Images, PDFs, and text files supported +

+
+
+ )} +
+ ) +}) + +FileDropZone.displayName = "FileDropZone" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileAttachmentBlockSync.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileAttachmentBlockSync.ts new file mode 100644 index 000000000..fc4c6b8ae --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileAttachmentBlockSync.ts @@ -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>(undefined!) + if (!nodeToBlockRef.current) { + nodeToBlockRef.current = new Map() + } + + const fileToNodeRef = useRef>>(undefined!) + if (!fileToNodeRef.current) { + fileToNodeRef.current = new Map() + } + + const blockToFileRef = useRef>(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() + + 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, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileUploadIntegration.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileUploadIntegration.ts new file mode 100644 index 000000000..f638981bb --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileUploadIntegration.ts @@ -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, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/index.ts new file mode 100644 index 000000000..555a0ecf6 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/index.ts @@ -0,0 +1,3 @@ +export { FileAttachmentNode } from "./FileAttachmentNode" +export { FileUploadPlugin } from "./FileUploadPlugin" +export type * from "./types" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/types.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/types.ts new file mode 100644 index 000000000..09c873121 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/types.ts @@ -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 +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/utils/file-handling.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/utils/file-handling.ts new file mode 100644 index 000000000..6f67d9838 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/utils/file-handling.ts @@ -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 + }, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx index 880d97c42..14a91d1b3 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx @@ -1 +1,2 @@ +export * from "./file-upload" export * from "./mention" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts index e0a98af81..cf75cb5cb 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts @@ -34,9 +34,20 @@ export const useMentionBlockSync = () => { const blocks = useAIChatStore()((state) => state.blocks) // Reference tracking maps - const mentionToBlockRef = useRef(new Map()) // mentionNodeKey -> reference - const resourceToMentionsRef = useRef(new Map>()) // resourceId -> Set - const blockToResourceRef = useRef(new Map()) // blockId -> resourceId + const mentionToBlockRef = useRef>(undefined!) + if (!mentionToBlockRef.current) { + mentionToBlockRef.current = new Map() + } + + const resourceToMentionsRef = useRef>>(undefined!) + if (!resourceToMentionsRef.current) { + resourceToMentionsRef.current = new Map() + } + + const blockToResourceRef = useRef>(undefined!) + if (!blockToResourceRef.current) { + blockToResourceRef.current = new Map() + } // Add mention-block reference const addMentionReference = useCallback( @@ -240,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), - }), } } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts index 5022b0653..610d35ab4 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts @@ -1,7 +1,9 @@ +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" @@ -28,7 +30,7 @@ export interface FileUploadHandlers { /** * Upload a single file with progress tracking */ - uploadFile: (file: File) => Promise + uploadFile: (file: File, id?: string) => Promise /** * Upload multiple files with progress tracking */ @@ -58,29 +60,82 @@ export function useFileUpload(options: UseFileUploadOptions = {}): FileUploadHan const blockActions = useChatBlockActions() const uploadFile = useCallback( - async (file: File): Promise => { + async (file: File, id?: string): Promise => { + // 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 block during upload progress - blockActions.updateFileAttachment(updatedAttachment.id, 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) { - // Add the completed file attachment to blocks - blockActions.addFileAttachment(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}`) } - } else if (showErrorToast && result.error) { - toast.error(`${errorMessagePrefix}: ${result.error}`) - console.error("File upload error:", result.error) - } - return result + // 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}`) } @@ -90,6 +145,7 @@ export function useFileUpload(options: UseFileUploadOptions = {}): FileUploadHan return { success: false, error: errorMessage, + fileAttachment: errorAttachment, } } }, diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/hooks.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/hooks.ts index b370e100c..70ea45817 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/hooks.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/hooks.ts @@ -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) -} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts index 0ca5df28f..4b003b514 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts @@ -140,10 +140,12 @@ export class BlockSliceAction { this.addBlock(fileBlock) } - updateFileAttachment(fileId: string, updatedAttachment: FileAttachment) { + updateFileAttachment(attachmentId: string, updatedAttachment: FileAttachment) { this.set( produce((state: BlockSlice) => { - const block = state.blocks.find((b) => b.id === fileId) + const block = state.blocks.find( + (b) => b.type === "fileAttachment" && b.attachment.id === attachmentId, + ) if (block && block.type === "fileAttachment") { block.attachment = updatedAttachment } @@ -172,12 +174,4 @@ export class BlockSliceAction { removeFileAttachment(fileId: string) { this.removeBlock(fileId) } - - getFileAttachments() { - return this.get().blocks.filter((block) => block.type === "fileAttachment") - } - - hasFileAttachments() { - return this.get().blocks.some((block) => block.type === "fileAttachment") - } } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts index 0d5bbd22d..3698546a5 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts @@ -232,9 +232,6 @@ export async function uploadFileAttachment( const response = await followApi.upload.uploadChatAttachment({ file: blob }) const serverUrl = response.data.url - // Clear progress interval - clearInterval(progressInterval) - // Update to 100% and completed status const completedAttachment: FileAttachment = { ...fileAttachment, @@ -248,9 +245,9 @@ export async function uploadFileAttachment( onProgressUpdate?.(completedAttachment) return completedAttachment - } catch (uploadError) { + } finally { + // Clear progress interval clearInterval(progressInterval) - throw uploadError } } catch (error) { // Return attachment with error status diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts index 04d53fcc2..3eb4372d2 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts @@ -1,5 +1,6 @@ const MAX_IMAGE_ALLOWED_SIZE = 3 * 1024 * 1024 const MAX_DOCUMENT_ALLOWED_SIZE = 1 * 1024 * 1024 +export const SUPPORTED_MIME_ACCEPT = "image/*,.pdf,.txt,.md" export const SUPPORTED_FILE_TYPES = { // Images "image/png": { extension: "png", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, From 1dceab3046acd95904a6b1a86f84341efa6ab990 Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 11 Aug 2025 16:18:36 +0800 Subject: [PATCH 08/73] chore: update build and tag action Signed-off-by: Innei --- .github/workflows/build-android.yml | 7 +- .github/workflows/build-desktop.yml | 4 +- .github/workflows/build-ios.yml | 2 +- .github/workflows/tag.yml | 113 ++++++++++++++++++---------- 4 files changed, 80 insertions(+), 46 deletions(-) diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index c102ba4a7..b8e3126e7 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -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 diff --git a/.github/workflows/build-desktop.yml b/.github/workflows/build-desktop.yml index 3747fbc99..0c737b225 100644 --- a/.github/workflows/build-desktop.yml +++ b/.github/workflows/build-desktop.yml @@ -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 diff --git a/.github/workflows/build-ios.yml b/.github/workflows/build-ios.yml index 24334ea0b..43b76b75e 100644 --- a/.github/workflows/build-ios.yml +++ b/.github/workflows/build-ios.yml @@ -1,4 +1,4 @@ -name: Build iOS +name: 🍎 Build iOS on: push: diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index b2df7f891..489ab634f 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -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 + + - 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'); From b34a6673d44e5cd220df7d7f819c83a7e0b50aa1 Mon Sep 17 00:00:00 2001 From: Konv Suu <2583695112@qq.com> Date: Mon, 11 Aug 2025 16:29:23 +0800 Subject: [PATCH 09/73] refactor(desktop): enhance drop-zone component flexibility (#4324) * refactor(desktop): enhance drop-zone component flexibility * Update --- .../components/ui/crop/AvatarUploadModal.tsx | 7 ++++- .../src/modules/discover/DiscoverImport.tsx | 26 +++++-------------- .../components/src/ui/drop-zone/index.tsx | 21 +++++++-------- 3 files changed, 23 insertions(+), 31 deletions(-) diff --git a/apps/desktop/layer/renderer/src/components/ui/crop/AvatarUploadModal.tsx b/apps/desktop/layer/renderer/src/components/ui/crop/AvatarUploadModal.tsx index 59c9223b6..00bdb3286 100644 --- a/apps/desktop/layer/renderer/src/components/ui/crop/AvatarUploadModal.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/crop/AvatarUploadModal.tsx @@ -377,7 +377,12 @@ export const AvatarUploadModal = ({
{!selectedImage ? (
- +
diff --git a/apps/desktop/layer/renderer/src/modules/discover/DiscoverImport.tsx b/apps/desktop/layer/renderer/src/modules/discover/DiscoverImport.tsx index 479f7af13..010e18b88 100644 --- a/apps/desktop/layer/renderer/src/modules/discover/DiscoverImport.tsx +++ b/apps/desktop/layer/renderer/src/modules/discover/DiscoverImport.tsx @@ -6,14 +6,7 @@ import { } from "@follow/components/ui/accordion/index.js" import { Button } from "@follow/components/ui/button/index.js" import { DropZone } from "@follow/components/ui/drop-zone/index.js" -import { - Form, - FormControl, - FormField, - FormItem, - FormMessage, -} from "@follow/components/ui/form/index.jsx" -import { Input } from "@follow/components/ui/input/index.js" +import { Form, FormControl, FormField, FormItem } from "@follow/components/ui/form/index.jsx" import type { BizRespose } from "@follow/models" import { zodResolver } from "@hookform/resolvers/zod" import { useMutation } from "@tanstack/react-query" @@ -169,10 +162,14 @@ export function DiscoverImport() { ( + render={({ field: { value, onChange } }) => ( - onChange(fileList[0])}> + onChange(fileList[0])} + > {form.formState.dirtyFields.file ? ( @@ -188,15 +185,6 @@ export function DiscoverImport() { )} - onChange(event.target.files && event.target.files[0])} - /> - )} /> diff --git a/packages/internal/components/src/ui/drop-zone/index.tsx b/packages/internal/components/src/ui/drop-zone/index.tsx index 51e9c6c7c..c42a222a9 100644 --- a/packages/internal/components/src/ui/drop-zone/index.tsx +++ b/packages/internal/components/src/ui/drop-zone/index.tsx @@ -1,6 +1,6 @@ import { cn } from "@follow/utils/utils" import type { DragEvent, ReactNode } from "react" -import { useCallback, useId, useRef, useState } from "react" +import { useCallback, useRef, useState } from "react" // Ported from https://github.com/react-dropzone/react-dropzone/issues/753#issuecomment-774782919 const useDragAndDrop = ({ callback }: { callback: (file: FileList) => void | Promise }) => { @@ -49,18 +49,17 @@ const useDragAndDrop = ({ callback }: { callback: (file: FileList) => void | Pro } } -export const DropZone = ({ - onDrop, - children, - className, -}: { - onDrop: (file: FileList) => void | Promise - className?: string +export interface DropZoneProps { + id?: string + accept?: string children?: ReactNode -}) => { + className?: string + onDrop: (files: FileList) => void | Promise +} + +export const DropZone = ({ id, accept, children, className, onDrop }: DropZoneProps) => { const { isDragging, dragHandlers } = useDragAndDrop({ callback: onDrop }) - const id = useId() return (
+ + {entry.author && ( +
+ + {entry.authorUrl ? ( + + {entry.author} + + ) : ( + {entry.author} + )} +
+ )} +
From dba2461de78e6cebc9cdab9dd9af2c9e1dd0a292 Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 11 Aug 2025 22:44:32 +0800 Subject: [PATCH 11/73] fix(ai): fix auto-scroll logic and improve some ui - Updated the ChatInterface component to improve scrolling behavior and UI elements. - Replaced the scroll-to-bottom button with a more visually appealing design and added functionality to reset scroll state. - Enhanced the AIChatWaitingIndicator with animations for better user feedback during processing. - Refactored the useAutoScroll hook to improve performance and user interaction handling, ensuring smoother scrolling experience. - Filtered out empty message parts before persisting to the database, improving data integrity. These changes collectively enhance the user experience in the AI chat interface. Signed-off-by: Innei --- .../components/layouts/ChatInterface.tsx | 47 ++++++--------- .../components/message/AIChatMessage.tsx | 15 ++++- .../modules/ai-chat/hooks/useAutoScroll.tsx | 60 +++++++------------ .../src/modules/ai-chat/services/index.ts | 34 ++++++----- 4 files changed, 70 insertions(+), 86 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx index b18eb8c04..411db4fc9 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx @@ -1,14 +1,13 @@ import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js" 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 { Suspense, useCallback, useEffect, useState } from "react" +import { Suspense, useEffect, useState } from "react" import { useEventCallback } from "usehooks-ts" import { @@ -34,7 +33,7 @@ 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() @@ -97,13 +96,6 @@ 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) => { @@ -175,6 +167,7 @@ const ChatInterfaceContent = () => { ) : ( { ) : (
- {status === "submitted" && } + + {(status === "submitted" || status === "streaming") && }
)}
@@ -195,24 +189,19 @@ const ChatInterfaceContent = () => {
{shouldShowScrollToBottom && ( -
-
- -
+
+
)} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx index 14b9cb827..db789ba44 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx @@ -247,8 +247,17 @@ export const AIChatMessage: React.FC = React.memo(({ message export const AIChatWaitingIndicator: React.FC = () => { return ( - - - + +
+ + Thinking… +
+
) } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx index 14435fb54..9f3b0ef5f 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx @@ -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(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]) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts index d6e8fdeae..c7eb2414a 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts @@ -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], From bce22113a04ecb56eb506f951cc7c36e643e03b9 Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 11 Aug 2025 23:19:55 +0800 Subject: [PATCH 12/73] refactor: streamline animation handling and improve layout responsiveness - Replaced custom spring transition settings with predefined Spring presets for smoother animations in AIEntryLayout. - Removed unused animation logic and imports in EntryContent to simplify the component structure. - Enhanced ArticleLayout's responsiveness by adjusting padding for better layout on smaller screens. These changes collectively improve code maintainability and user interface responsiveness. Signed-off-by: Innei --- .../modules/entry-column/AIEntryLayout.tsx | 8 ++--- .../entry-content/EntryContent.ai.tsx | 35 +++---------------- .../components/layouts/ArticleLayout.tsx | 2 +- 3 files changed, 7 insertions(+), 38 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx index 276df7b9a..589c6c42a 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx @@ -1,3 +1,4 @@ +import { Spring } from "@follow/components/constants/spring.js" import { Button } from "@follow/components/ui/button/index.js" import { PanelSplitter } from "@follow/components/ui/divider/index.js" import { defaultUISettings } from "@follow/shared/settings/defaults" @@ -144,12 +145,7 @@ const AIEntryLayoutImpl = () => { initial={{ y: "100%" }} animate={{ y: 0 }} exit={{ y: "100%" }} - transition={{ - type: "spring", - damping: 30, - stiffness: 400, - duration: 0.3, - }} + transition={Spring.presets.smooth} className="bg-theme-background absolute inset-0 z-10 border-l" > {/* Scroll hint indicator */} diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx index c4a98afff..4b032bb57 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx @@ -1,4 +1,3 @@ -import { Spring } from "@follow/components/constants/spring.js" import { MotionButtonBase } from "@follow/components/ui/button/index.js" import { RootPortal } from "@follow/components/ui/portal/index.js" import { ScrollArea } from "@follow/components/ui/scroll-area/index.js" @@ -9,11 +8,10 @@ import { useEntry } from "@follow/store/entry/hooks" import { useFeedById } from "@follow/store/feed/hooks" import { useIsInbox } from "@follow/store/inbox/hooks" import { thenable } from "@follow/utils" -import { nextFrame, stopPropagation } from "@follow/utils/dom" +import { stopPropagation } from "@follow/utils/dom" import { EventBus } from "@follow/utils/event-bus" import { clsx, cn } from "@follow/utils/utils" -import type { JSAnimation, Variants } from "motion/react" -import { m, useAnimationControls } from "motion/react" +import type { JSAnimation } from "motion/react" import * as React from "react" import { memo, useEffect, useRef, useState } from "react" @@ -40,12 +38,6 @@ import { EntryNoContent } from "./EntryNoContent" import { EntryScrollingAndNavigationHandler } from "./EntryScrollingAndNavigationHandler.js" import type { EntryContentProps } from "./types" -const pageMotionVariants = { - initial: { opacity: 0, y: 25 }, - animate: { opacity: 1, y: 0 }, - exit: { opacity: 0, y: 25, transition: { duration: 0 } }, -} satisfies Variants - const EntryContentImpl: Component = ({ entryId, noMedia, @@ -78,21 +70,7 @@ const EntryContentImpl: Component = ({ const [panelPortalElement, setPanelPortalElement] = useState(null) - const animationController = useAnimationControls() - const prevEntryId = useRef(undefined) const scrollAnimationRef = useRef | null>(null) - useEffect(() => { - if (prevEntryId.current !== entryId) { - scrollAnimationRef.current?.stop() - nextFrame(() => { - scrollerRef.current?.scrollTo({ top: 0 }) - }) - animationController.start(pageMotionVariants.exit).then(() => { - animationController.start(pageMotionVariants.animate) - }) - prevEntryId.current = entryId - } - }, [animationController, entryId]) const isInHasTimelineView = ![ FeedViewType.Pictures, @@ -138,12 +116,7 @@ const EntryContentImpl: Component = ({ {/* Indicator for the entry */} - +
{!isZenMode && isInHasTimelineView && !isInPeekModal && ( <>
@@ -208,7 +181,7 @@ const EntryContentImpl: Component = ({ /> )} - +
diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx index 7b0a588d2..cedb6f1b9 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx @@ -72,7 +72,7 @@ export const ArticleLayout: React.FC = ({ if (!entry) return null return ( -
+
From 0737300ee4b0314eff751dc38e2efefc8370f3bc Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 11 Aug 2025 23:26:32 +0800 Subject: [PATCH 13/73] feat(ai): implement auto-scroll feature and initialize settings - Updated the AI chat settings to include an auto-scroll feature when streaming messages. - Introduced a new settings initialization function to set default values for various AI settings. - Enhanced the ChatInterface component to utilize the new auto-scroll setting for improved user experience. - Added localization support for the new auto-scroll setting in the English language file. These changes collectively enhance the functionality and usability of the AI chat interface. Signed-off-by: Innei --- .../desktop/layer/renderer/src/atoms/settings/ai.ts | 2 +- apps/desktop/layer/renderer/src/initialize/index.ts | 4 ++-- .../src/initialize/{hydrate.ts => settings.ts} | 4 +++- .../ai-chat/components/layouts/ChatInterface.tsx | 8 +++++++- .../layer/renderer/src/modules/settings/tabs/ai.tsx | 13 +++++++++++++ .../layer/renderer/src/providers/setting-sync.tsx | 1 + locales/ai/en.json | 3 +++ packages/internal/shared/src/settings/defaults.ts | 3 +++ packages/internal/shared/src/settings/interface.ts | 3 +++ 9 files changed, 36 insertions(+), 5 deletions(-) rename apps/desktop/layer/renderer/src/initialize/{hydrate.ts => settings.ts} (70%) diff --git a/apps/desktop/layer/renderer/src/atoms/settings/ai.ts b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts index dad9bdc24..3a10f80ed 100644 --- a/apps/desktop/layer/renderer/src/atoms/settings/ai.ts +++ b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts @@ -19,7 +19,7 @@ export const { export const aiServerSyncWhiteListKeys = [] // Local Setting for ai -const aiChatPinnedAtom = atom(false) +const aiChatPinnedAtom = atom(true) export const useAIChatPinned = () => useAtomValue(aiChatPinnedAtom) export const setAIChatPinned = (pinned: boolean) => { jotaiStore.set(aiChatPinnedAtom, pinned) diff --git a/apps/desktop/layer/renderer/src/initialize/index.ts b/apps/desktop/layer/renderer/src/initialize/index.ts index cdad3c140..5490b53af 100644 --- a/apps/desktop/layer/renderer/src/initialize/index.ts +++ b/apps/desktop/layer/renderer/src/initialize/index.ts @@ -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) diff --git a/apps/desktop/layer/renderer/src/initialize/hydrate.ts b/apps/desktop/layer/renderer/src/initialize/settings.ts similarity index 70% rename from apps/desktop/layer/renderer/src/initialize/hydrate.ts rename to apps/desktop/layer/renderer/src/initialize/settings.ts index 5e3a150c4..ef75d72c4 100644 --- a/apps/desktop/layer/renderer/src/initialize/hydrate.ts +++ b/apps/desktop/layer/renderer/src/initialize/settings.ts @@ -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() } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx index 411db4fc9..f4c1c8fbb 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx @@ -10,6 +10,7 @@ import type { FC } from "react" import { Suspense, useEffect, useState } from "react" import { useEventCallback } from "usehooks-ts" +import { useAISettingKey } from "~/atoms/settings/ai" import { AIChatMessage, AIChatWaitingIndicator, @@ -73,7 +74,12 @@ const ChatInterfaceContent = () => { }, }) - const { resetScrollState } = useAutoScroll(scrollAreaRef, status === "streaming") + const autoScrollWhenStreaming = useAISettingKey("autoScrollWhenStreaming") + + const { resetScrollState } = useAutoScroll( + scrollAreaRef, + autoScrollWhenStreaming && status === "streaming", + ) useEffect(() => { const scrollElement = scrollAreaRef diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx index a8f881ed7..3c10ce130 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx @@ -11,9 +11,11 @@ import { toast } from "sonner" import { setAISetting, useAISettingValue } from "~/atoms/settings/ai" import { SettingActionItem, SettingDescription } from "../control" +import { createDefineSettingItem } from "../helper/builder" import { createSettingBuilder } from "../helper/setting-builder" const SettingBuilder = createSettingBuilder(useAISettingValue) +const defineSettingItem = createDefineSettingItem(useAISettingValue, setAISetting) export const SettingAI = () => { const { t } = useTranslation("ai") @@ -22,11 +24,22 @@ export const SettingAI = () => {
{ useUXSettingSync() useLanguageSync() useGeneralSettingSync() + return null } diff --git a/locales/ai/en.json b/locales/ai/en.json index de1fc40ac..ff70c3a0f 100644 --- a/locales/ai/en.json +++ b/locales/ai/en.json @@ -1,4 +1,6 @@ { + "autoScrollWhenStreaming.description": "Automatically scroll to the bottom of the chat when streaming", + "autoScrollWhenStreaming.label": "Auto scroll when streaming", "clear_chat": "Clear Chat", "clear_chat_message": "Are you sure you want to clear all history? This action will permanently delete all content, including all chat logs and data, and cannot be undone.", "delete_chat": "Delete Chat", @@ -8,6 +10,7 @@ "export_empty_chat": "Cannot export an empty chat", "export_error": "Failed to export chat", "export_success": "Chat exported successfully", + "features.title": "Features", "personalize.description": "Tell me about yourself to get personalized AI responses", "personalize.prompt.help": "This helps AI provide personalized responses based on your preferences.", "personalize.prompt.label": "Personal Prompt", diff --git a/packages/internal/shared/src/settings/defaults.ts b/packages/internal/shared/src/settings/defaults.ts index 54033c9fb..be2158999 100644 --- a/packages/internal/shared/src/settings/defaults.ts +++ b/packages/internal/shared/src/settings/defaults.ts @@ -155,6 +155,9 @@ export const defaultIntegrationSettings: IntegrationSettings = { export const defaultAISettings: AISettings = { personalizePrompt: "", shortcuts: [], + + // Features + autoScrollWhenStreaming: true, } export const defaultSettings = { diff --git a/packages/internal/shared/src/settings/interface.ts b/packages/internal/shared/src/settings/interface.ts index 75025cd1b..c827740b6 100644 --- a/packages/internal/shared/src/settings/interface.ts +++ b/packages/internal/shared/src/settings/interface.ts @@ -181,4 +181,7 @@ export interface AIShortcut { export interface AISettings { personalizePrompt: string shortcuts: AIShortcut[] + + // Features + autoScrollWhenStreaming: boolean } From 3d577699fc0304719394d6f2a95106e472d7b824 Mon Sep 17 00:00:00 2001 From: Innei Date: Tue, 12 Aug 2025 00:24:42 +0800 Subject: [PATCH 14/73] refactor(ai): optimize code rendering and layout adjustments - Introduced memoization for the ShikiHighLighter component to enhance performance during code rendering. - Updated layout properties in AIDisplayFlowPart and AIMessageParts for improved responsiveness and visual consistency. - Enhanced the ChatInterface component with flex properties for better layout management. - Adjusted message rendering logic in AIMarkdownStreamingMessage to improve first paint performance. These changes collectively enhance the efficiency and user experience of the AI chat interface. Signed-off-by: Innei --- .../ui/code-highlighter/shiki/Shiki.tsx | 3 +- .../components/displays/AIDisplayFlowPart.tsx | 2 +- .../components/layouts/ChatInterface.tsx | 17 +++++--- .../components/message/AIMarkdownMessage.tsx | 39 +++++++++++++++---- .../components/message/AIMessageParts.tsx | 3 +- 5 files changed, 46 insertions(+), 18 deletions(-) diff --git a/apps/desktop/layer/renderer/src/components/ui/code-highlighter/shiki/Shiki.tsx b/apps/desktop/layer/renderer/src/components/ui/code-highlighter/shiki/Shiki.tsx index 008bd2c5c..c5379cfc8 100644 --- a/apps/desktop/layer/renderer/src/components/ui/code-highlighter/shiki/Shiki.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/code-highlighter/shiki/Shiki.tsx @@ -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 = (props) => { return } +export const MemoizedShikiCode = memo(ShikiHighLighter) const ShikiCode: FC< ShikiProps & { codeTheme: string diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx index b55435f09..ed9e05a7c 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx @@ -65,7 +65,7 @@ export const AIDisplayFlowPart = toolMemo( }, [nodes, edges, colorMode, present]) return ( -
+
{ ) : ( {
) : ( -
+
{(status === "submitted" || status === "streaming") && } @@ -234,9 +235,13 @@ export const ChatInterface = () => ( const Messages: FC = () => { const messages = useMessages() - return messages.map((message) => ( - - - - )) + return ( +
+ {messages.map((message) => ( + + + + ))} +
+ ) } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx index b32a20d72..d23f8d566 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx @@ -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 + return } } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx index a0386fa16..d283b6312 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx @@ -19,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" @@ -84,7 +83,7 @@ export const AIMessageParts: React.FC = React.memo(({ message case "tool-displayFlowChart": { const loadingElement = ( -
+
From ab537447e87c595e93fd59f5eb32553a264fd0e1 Mon Sep 17 00:00:00 2001 From: Innei Date: Tue, 12 Aug 2025 01:27:57 +0800 Subject: [PATCH 15/73] feat(ai): implement fixed and floating chat panel styles - Introduced a new enum for AI chat panel styles, allowing users to toggle between fixed and floating layouts. - Added state management for the floating panel dimensions and position, ensuring it remains anchored during window resizing. - Updated various components to utilize the new panel style settings, enhancing the user experience with improved layout flexibility. - Implemented UI elements for toggling between fixed and floating modes in the chat interface. These changes collectively enhance the functionality and usability of the AI chat interface, providing users with more control over their layout preferences. Signed-off-by: Innei --- .../layer/renderer/src/atoms/settings/ai.ts | 39 ++++++- .../src/hooks/biz/useEntryActions.tsx | 16 +-- .../ai-chat/components/layouts/ChatHeader.tsx | 3 +- .../components/layouts/ChatMoreDropdown.tsx | 21 ++++ .../app-layout/ai/AIChatFixedPanel.tsx | 23 ++++ .../app-layout/ai/AIChatFloatingPanel.tsx | 110 ++++++++++++++++++ .../modules/app-layout/ai/AIChatLayout.tsx | 31 +++-- .../entry-content/EntryLayoutContent.tsx | 5 +- .../src/modules/customize-toolbar/constant.ts | 1 - .../modules/entry-column/AIEntryLayout.tsx | 41 ++++--- .../accessories/ContainerToc.tsx | 5 +- packages/internal/utils/src/index.ts | 1 + packages/internal/utils/src/resize.ts | 43 +++++++ 13 files changed, 281 insertions(+), 58 deletions(-) create mode 100644 apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFixedPanel.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx create mode 100644 packages/internal/utils/src/resize.ts diff --git a/apps/desktop/layer/renderer/src/atoms/settings/ai.ts b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts index 3a10f80ed..6b8591f7b 100644 --- a/apps/desktop/layer/renderer/src/atoms/settings/ai.ts +++ b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts @@ -19,9 +19,38 @@ export const { export const aiServerSyncWhiteListKeys = [] // Local Setting for ai -const aiChatPinnedAtom = atom(true) -export const useAIChatPinned = () => useAtomValue(aiChatPinnedAtom) -export const setAIChatPinned = (pinned: boolean) => { - jotaiStore.set(aiChatPinnedAtom, pinned) +export enum AIChatPanelStyle { + Fixed = "fixed", + Floating = "floating", } -export const getAIChatPinned = () => jotaiStore.get(aiChatPinnedAtom) + +const aiChatPanelStyleAtom = atom(AIChatPanelStyle.Floating) +export const useAIChatPanelStyle = () => useAtomValue(aiChatPanelStyleAtom) +export const setAIChatPanelStyle = (style: AIChatPanelStyle) => { + jotaiStore.set(aiChatPanelStyleAtom, style) +} +export const getAIChatPanelStyle = () => jotaiStore.get(aiChatPanelStyleAtom) + +// Floating panel state atoms +interface FloatingPanelState { + width: number + height: number + x: number + y: number +} + +const defaultFloatingPanelState: FloatingPanelState = { + width: 500, + height: 600, + x: window.innerWidth - 520, // 20px margin from right + y: window.innerHeight - 620, // 20px margin from bottom +} + +const floatingPanelStateAtom = atom(defaultFloatingPanelState) + +export const useFloatingPanelState = () => useAtomValue(floatingPanelStateAtom) +export const setFloatingPanelState = (state: Partial) => { + const currentState = jotaiStore.get(floatingPanelStateAtom) + jotaiStore.set(floatingPanelStateAtom, { ...currentState, ...state }) +} +export const getFloatingPanelState = () => jotaiStore.get(floatingPanelStateAtom) diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx index 9176c65f6..023556bb1 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx @@ -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 }) => { @@ -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, ]) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx index b45c61ec5..7f4861778 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx @@ -54,8 +54,7 @@ export const ChatHeader = () => { />
- {/* Left side - Title */} -
+
{ 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 ( @@ -169,6 +177,19 @@ export const ChatMoreDropdown = () => { Export Chat + + + + + + + {panelStyle === AIChatPanelStyle.Fixed + ? "Switch to Floating Panel" + : "Switch to Fixed Panel"} + + ) diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFixedPanel.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFixedPanel.tsx new file mode 100644 index 000000000..dd88ef2f0 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFixedPanel.tsx @@ -0,0 +1,23 @@ +import { cn } from "@follow/utils" +import type { FC } from "react" + +import { Focusable } from "~/components/common/Focusable" +import { HotkeyScope } from "~/constants" +import { ChatHeader } from "~/modules/ai-chat/components/layouts/ChatHeader" +import { ChatInterface } from "~/modules/ai-chat/components/layouts/ChatInterface" + +export interface AIChatFixedPanelProps + extends React.DetailedHTMLProps, HTMLDivElement> {} + +export const AIChatFixedPanel: FC = ({ className, ...props }) => { + return ( + + + + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx new file mode 100644 index 000000000..025f0cc61 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx @@ -0,0 +1,110 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { cn, computeAdjustedTopLeftPosition } from "@follow/utils" +import { m } from "motion/react" +import type { ResizeDirection } from "re-resizable" +import { Resizable } from "re-resizable" +import type { FC } from "react" +import { useEffect, useRef } from "react" + +import { + getFloatingPanelState, + setFloatingPanelState, + useFloatingPanelState, +} from "~/atoms/settings/ai" +import { Focusable } from "~/components/common/Focusable" +import { HotkeyScope } from "~/constants" +import { ChatHeader } from "~/modules/ai-chat/components/layouts/ChatHeader" +import { ChatInterface } from "~/modules/ai-chat/components/layouts/ChatInterface" + +export interface AIChatFloatingPanelProps + extends React.DetailedHTMLProps, HTMLDivElement> {} + +export const AIChatFloatingPanel: FC = ({ className, ...props }) => { + const floatingState = useFloatingPanelState() + + // Preserve right/bottom margins to keep panel anchored to bottom-right on window resize + const rightBottomMarginRef = useRef({ right: 0, bottom: 0 }) + useEffect(() => { + rightBottomMarginRef.current = { + right: Math.max(0, window.innerWidth - (floatingState.x + floatingState.width)), + bottom: Math.max(0, window.innerHeight - (floatingState.y + floatingState.height)), + } + }, [floatingState.x, floatingState.y, floatingState.width, floatingState.height]) + + const handleResize = useRef( + (_event: MouseEvent | TouchEvent, direction: ResizeDirection, ref: HTMLElement) => { + const prev = getFloatingPanelState() + const newWidth = ref.offsetWidth + const newHeight = ref.offsetHeight + const { x, y } = computeAdjustedTopLeftPosition( + { x: prev.x, y: prev.y, width: prev.width, height: prev.height }, + { width: newWidth, height: newHeight }, + direction, + ) + + setFloatingPanelState({ width: newWidth, height: newHeight, x, y }) + }, + ).current + + // Keep floating panel anchored to bottom-right on window resize + useEffect(() => { + const handleWindowResize = () => { + const { right, bottom } = rightBottomMarginRef.current + const newX = Math.max(0, window.innerWidth - floatingState.width - right) + const newY = Math.max(0, window.innerHeight - floatingState.height - bottom) + setFloatingPanelState({ x: newX, y: newY }) + } + + window.addEventListener("resize", handleWindowResize) + return () => window.removeEventListener("resize", handleWindowResize) + }, [floatingState.width, floatingState.height]) + + const chatContent = ( + + + + + ) + + return ( + +
+ + {chatContent} + +
+
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx index d1cbf1dca..0c3af6174 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx @@ -1,21 +1,18 @@ import type { FC } from "react" -import { Focusable } from "~/components/common/Focusable" -import { HotkeyScope } from "~/constants" -import { ChatHeader } from "~/modules/ai-chat/components/layouts/ChatHeader" -import { ChatInterface } from "~/modules/ai-chat/components/layouts/ChatInterface" +import { AIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai" -export const AIChatLayout: FC< - React.DetailedHTMLProps, HTMLDivElement> -> = ({ ...props }) => { - return ( - - - - - ) +import { AIChatFixedPanel } from "./AIChatFixedPanel" +import { AIChatFloatingPanel } from "./AIChatFloatingPanel" + +export interface AIChatLayoutProps + extends React.DetailedHTMLProps, HTMLDivElement> {} + +export const AIChatLayout: FC = ({ ...props }) => { + const panelStyle = useAIChatPanelStyle() + + if (panelStyle === AIChatPanelStyle.Floating) { + return + } + return } diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx index 624197fe2..9fedc0d12 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx @@ -7,7 +7,7 @@ import { useMemo } from "react" import { useResizable } from "react-resizable-layout" import { useParams } from "react-router" -import { useAIChatPinned } from "~/atoms/settings/ai" +import { AIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai" import { useRealInWideMode } from "~/atoms/settings/ui" import { useTimelineColumnShow, useTimelineColumnTempShow } from "~/atoms/sidebar" import { m } from "~/components/common/Motion" @@ -102,7 +102,8 @@ const Grid = ({ entryId }) => { const wideMode = !!(settingWideMode && entryId) const feedColumnTempShow = useTimelineColumnTempShow() const feedColumnShow = useTimelineColumnShow() - const aiPinned = useAIChatPinned() + const panelStyle = useAIChatPanelStyle() + const aiPinned = panelStyle === AIChatPanelStyle.Fixed const shouldHeaderPaddingLeft = feedColumnTempShow && !feedColumnShow && settingWideMode const { isDragging, position, separatorProps, separatorCursor } = useResizable({ diff --git a/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts b/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts index 7e06fdab8..1a1ae4c7a 100644 --- a/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts +++ b/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts @@ -19,7 +19,6 @@ const MAIN_ACTIONS = [ COMMAND_ID.entry.toggleAISummary, COMMAND_ID.entry.readability, - COMMAND_ID.global.toggleAIChatPinned, COMMAND_ID.entry.viewSourceContent, COMMAND_ID.entry.share, diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx index 589c6c42a..c7d244329 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx @@ -8,6 +8,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react" import { useResizable } from "react-resizable-layout" import { useParams } from "react-router" +import { AIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai" import { getUISettings, setUISetting } from "~/atoms/settings/ui" import { ROUTE_ENTRY_PENDING } from "~/constants" import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry" @@ -21,6 +22,7 @@ import { EntryColumn } from "./index" const AIEntryLayoutImpl = () => { const { entryId } = useParams() const navigate = useNavigateEntry() + const panelStyle = useAIChatPanelStyle() const realEntryId = entryId === ROUTE_ENTRY_PENDING ? "" : entryId @@ -130,7 +132,7 @@ const AIEntryLayoutImpl = () => { return (
-
+
{/* Entry list - always rendered to prevent animation */} @@ -175,20 +177,29 @@ const AIEntryLayoutImpl = () => {
- { - setUISetting("aiColWidth", defaultUISettings.aiColWidth) - setPosition(defaultUISettings.aiColWidth) - }} - /> - + + {/* Fixed panel layout */} + {panelStyle === AIChatPanelStyle.Fixed && ( + <> + { + setUISetting("aiColWidth", defaultUISettings.aiColWidth) + setPosition(defaultUISettings.aiColWidth) + }} + /> + + + )} + + {/* Floating panel - renders outside layout flow */} + {panelStyle === AIChatPanelStyle.Floating && }
) } diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx index 640e33103..29391844f 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx @@ -9,7 +9,7 @@ import { cn } from "@follow/utils/utils" import { useStore } from "jotai" import { memo, useEffect, useMemo, useState } from "react" -import { useAIChatPinned } from "~/atoms/settings/ai" +import { AIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai" import type { TocRef } from "~/components/ui/markdown/components/Toc" import { Toc } from "~/components/ui/markdown/components/Toc" import { useFeature } from "~/hooks/biz/useFeature" @@ -51,7 +51,8 @@ const BackTopIndicator: Component = memo(({ className }) => { const scrollElement = useScrollViewElement() const aiEnabled = useFeature("ai") - const isAiPanelOpen = useAIChatPinned() + const panelStyle = useAIChatPanelStyle() + const isAiPanelOpen = panelStyle === AIChatPanelStyle.Fixed return ( Date: Tue, 12 Aug 2025 01:35:42 +0800 Subject: [PATCH 16/73] fix: handle potential IndexSizeError in text selection listener --- .../layer/renderer/src/lib/simple-text-selection.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts b/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts index 95853048c..57c3871a5 100644 --- a/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts +++ b/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts @@ -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) { From e528367e8b89ffb9936b395e187c96df9b1dd025 Mon Sep 17 00:00:00 2001 From: Innei Date: Tue, 12 Aug 2025 20:37:48 +0800 Subject: [PATCH 17/73] feat(ai): support AI chat close float panel - Introduced a new interface for WebAISettings, extending AISettings to include panel style options. - Updated default settings creation to include a fixed panel style. - Refactored AI chat panel visibility management, allowing dynamic visibility based on panel style. - Implemented a new hook for managing AI panel visibility and integrated it into the floating panel component. - Removed deprecated context bar search service and replaced it with a unified feed entry search service for improved search functionality. These changes collectively enhance the configurability and usability of the AI chat interface, providing users with better control over their settings and layout preferences. Signed-off-by: Innei --- .../layer/renderer/src/atoms/settings/ai.ts | 35 ++++++++-- .../context-bar/blocks/ContextBlock.tsx | 17 +++-- .../ai-chat/components/layouts/ChatHeader.tsx | 13 +++- .../components/layouts/ChatMoreDropdown.tsx | 8 --- .../mention/hooks/useMentionSearchService.ts | 2 +- .../useFeedEntrySearchService.ts} | 0 .../services/contextBarSearchService.ts | 69 ------------------- .../ai-chat/store/slices/block.slice.ts | 8 ++- .../app-layout/ai/AIChatFloatingPanel.tsx | 46 +++++++------ .../src/modules/command/commands/global.tsx | 19 ----- .../src/modules/command/commands/id.ts | 1 - .../src/modules/customize-toolbar/dnd.tsx | 2 +- .../accessories/ContainerToc.tsx | 5 +- locales/shortcuts/en.json | 2 - locales/shortcuts/ja.json | 2 - 15 files changed, 84 insertions(+), 145 deletions(-) rename apps/desktop/layer/renderer/src/modules/ai-chat/{services/feedEntrySearchService.ts => hooks/useFeedEntrySearchService.ts} (100%) delete mode 100644 apps/desktop/layer/renderer/src/modules/ai-chat/services/contextBarSearchService.ts diff --git a/apps/desktop/layer/renderer/src/atoms/settings/ai.ts b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts index 6b8591f7b..c7a70d733 100644 --- a/apps/desktop/layer/renderer/src/atoms/settings/ai.ts +++ b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts @@ -4,32 +4,38 @@ import type { AISettings } from "@follow/shared/settings/interface" import { jotaiStore } from "@follow/utils" 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 +////////// AI Panel Style export enum AIChatPanelStyle { Fixed = "fixed", Floating = "floating", } -const aiChatPanelStyleAtom = atom(AIChatPanelStyle.Floating) -export const useAIChatPanelStyle = () => useAtomValue(aiChatPanelStyleAtom) +export const useAIChatPanelStyle = () => useAISettingKey("panelStyle") export const setAIChatPanelStyle = (style: AIChatPanelStyle) => { - jotaiStore.set(aiChatPanelStyleAtom, style) + setAISetting("panelStyle", style) } -export const getAIChatPanelStyle = () => jotaiStore.get(aiChatPanelStyleAtom) +export const getAIChatPanelStyle = () => getAISettings().panelStyle // Floating panel state atoms interface FloatingPanelState { @@ -54,3 +60,18 @@ export const setFloatingPanelState = (state: Partial) => { jotaiStore.set(floatingPanelStateAtom, { ...currentState, ...state }) } export const getFloatingPanelState = () => jotaiStore.get(floatingPanelStateAtom) + +////////// AI Panel Visibility + +const aiPanelVisibilityAtom = atom(false) +export const useAIPanelVisibility = () => useAtomValue(aiPanelVisibilityAtom) +export const setAIPanelVisibility = (visibility: boolean) => { + jotaiStore.set(aiPanelVisibilityAtom, visibility) +} +export const getAIPanelVisibility = () => jotaiStore.get(aiPanelVisibilityAtom) + +//// Enhance Init Ai Settings +export const initializeDefaultAISettings = () => { + initializeDefaultSettings() + if (getAISettings().panelStyle === AIChatPanelStyle.Fixed) setAIPanelVisibility(true) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx index 6551f1415..fc587a07f 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx @@ -1,4 +1,4 @@ -import { cn } from "@follow/utils/utils" +import { clsx, cn } from "@follow/utils/utils" import type { FC } from "react" import { memo } from "react" @@ -171,16 +171,17 @@ export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block }) return (
@@ -188,9 +189,7 @@ export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block }) {getBlockLabel()}
- - {getDisplayContent()} - + {getDisplayContent()}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx index 7f4861778..dadd10107 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx @@ -2,6 +2,7 @@ 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 { useBlockActions, useChatActions, useCurrentTitle } from "~/modules/ai-chat/store/hooks" import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack" @@ -30,7 +31,7 @@ export const ChatHeader = () => { variant: "danger", onConfirm: () => { chatActions.newChat() - blockActions.clearBlocks() + blockActions.clearBlocks({ keepSpecialTypes: true }) }, }) }, [chatActions, currentTitle, ask, t, blockActions]) @@ -42,6 +43,7 @@ export const ChatHeader = () => { [chatActions], ) + const panelStyle = useAIChatPanelStyle() const maskImage = `linear-gradient(to bottom, black 0%, black 75%, transparent 100%)` return (
@@ -73,6 +75,15 @@ export const ChatHeader = () => { + + {panelStyle === AIChatPanelStyle.Floating && ( + <> +
+ setAIPanelVisibility(false)}> + + + + )}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx index 3c66e3476..5102cc38a 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx @@ -155,14 +155,6 @@ export const ChatMoreDropdown = () => {
))} - - - - New Chat - ) : (
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSearchService.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSearchService.ts index 91603a943..a9c7525d4 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSearchService.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSearchService.ts @@ -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" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/services/feedEntrySearchService.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFeedEntrySearchService.ts similarity index 100% rename from apps/desktop/layer/renderer/src/modules/ai-chat/services/feedEntrySearchService.ts rename to apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFeedEntrySearchService.ts diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/services/contextBarSearchService.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/services/contextBarSearchService.ts deleted file mode 100644 index 22b4b92b4..000000000 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/services/contextBarSearchService.ts +++ /dev/null @@ -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, - } -} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts index 4b003b514..8a60c6691 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts @@ -98,7 +98,7 @@ export class BlockSliceAction { } } - clearBlocks() { + clearBlocks({ keepSpecialTypes = false }: { keepSpecialTypes?: boolean } = {}) { this.set( produce((state: BlockSlice) => { // Clean up file attachments before clearing @@ -107,7 +107,11 @@ export class BlockSliceAction { cleanupFileAttachment(block.attachment) } }) - state.blocks = [] + state.blocks = keepSpecialTypes + ? state.blocks.filter((b) => + Object.values(BlockSliceAction.SPECIAL_TYPES).includes(b.type), + ) + : [] }), ) } diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx index 025f0cc61..0ad967563 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx @@ -1,6 +1,6 @@ import { Spring } from "@follow/components/constants/spring.js" import { cn, computeAdjustedTopLeftPosition } from "@follow/utils" -import { m } from "motion/react" +import { AnimatePresence, m } from "motion/react" import type { ResizeDirection } from "re-resizable" import { Resizable } from "re-resizable" import type { FC } from "react" @@ -9,6 +9,7 @@ import { useEffect, useRef } from "react" import { getFloatingPanelState, setFloatingPanelState, + useAIPanelVisibility, useFloatingPanelState, } from "~/atoms/settings/ai" import { Focusable } from "~/components/common/Focusable" @@ -19,7 +20,7 @@ import { ChatInterface } from "~/modules/ai-chat/components/layouts/ChatInterfac export interface AIChatFloatingPanelProps extends React.DetailedHTMLProps, HTMLDivElement> {} -export const AIChatFloatingPanel: FC = ({ className, ...props }) => { +const AIChatFloatingPanelInner: FC = ({ className, ...props }) => { const floatingState = useFloatingPanelState() // Preserve right/bottom margins to keep panel anchored to bottom-right on window resize @@ -59,25 +60,11 @@ export const AIChatFloatingPanel: FC = ({ className, . return () => window.removeEventListener("resize", handleWindowResize) }, [floatingState.width, floatingState.height]) - const chatContent = ( - - - - - ) - return ( = ({ className, . topLeft: true, }} > - {chatContent} + + + +
) } + +export const AIChatFloatingPanel: FC = (props) => { + const visibility = useAIPanelVisibility() + return ( + + {visibility && } + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/command/commands/global.tsx b/apps/desktop/layer/renderer/src/modules/command/commands/global.tsx index b046c1f43..fe9da0826 100644 --- a/apps/desktop/layer/renderer/src/modules/command/commands/global.tsx +++ b/apps/desktop/layer/renderer/src/modules/command/commands/global.tsx @@ -12,7 +12,6 @@ declare module "@follow/utils/event-bus" { "global:toggle-corner-play": void "global:quick-add": void "global:toggle-ai-chat": void - "global:toggle-ai-chat-pinned": void } } @@ -72,18 +71,6 @@ export const useRegisterGlobalCommands = () => { icon: aiIcon, category, }, - { - id: COMMAND_ID.global.toggleAIChatPinned, - label: { - title: t("command.global.toggle_ai_chat_pinned.title"), - description: t("command.global.toggle_ai_chat_pinned.description"), - }, - run: () => { - EventBus.dispatch(COMMAND_ID.global.toggleAIChatPinned) - }, - icon: aiIcon, - category, - }, ]) } @@ -107,14 +94,8 @@ export type ToggleAIChatCommand = Command<{ fn: (ctx?: { entryId?: string }) => void }> -export type ToggleAIChatPinnedCommand = Command<{ - id: typeof COMMAND_ID.global.toggleAIChatPinned - fn: (ctx?: { entryId?: string }) => void -}> - export type GlobalCommand = | ShowShortcutsCommand | ToggleCornerPlayCommand | QuickAddCommand | ToggleAIChatCommand - | ToggleAIChatPinnedCommand diff --git a/apps/desktop/layer/renderer/src/modules/command/commands/id.ts b/apps/desktop/layer/renderer/src/modules/command/commands/id.ts index 853dc78c9..e1b03ccc6 100644 --- a/apps/desktop/layer/renderer/src/modules/command/commands/id.ts +++ b/apps/desktop/layer/renderer/src/modules/command/commands/id.ts @@ -50,7 +50,6 @@ export const COMMAND_ID = { toggleCornerPlay: "global:toggle-corner-play", quickAdd: "global:quick-add", toggleAIChat: "global:toggle-ai-chat", - toggleAIChatPinned: "global:toggle-ai-chat-pinned", }, layout: { toggleSubscriptionColumn: "layout:toggle-subscription-column", diff --git a/apps/desktop/layer/renderer/src/modules/customize-toolbar/dnd.tsx b/apps/desktop/layer/renderer/src/modules/customize-toolbar/dnd.tsx index 41b9336e9..e89f3f3de 100644 --- a/apps/desktop/layer/renderer/src/modules/customize-toolbar/dnd.tsx +++ b/apps/desktop/layer/renderer/src/modules/customize-toolbar/dnd.tsx @@ -62,7 +62,7 @@ const warningActionButton: Partial< show: !IN_ELECTRON, info: "entry_actions.warn_info_for_desktop", }, - [COMMAND_ID.global.toggleAIChatPinned]: { + [COMMAND_ID.global.toggleAIChat]: { show: true, info: "entry_actions.warn_info_ai_chat_pinned_tip", }, diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx index 29391844f..1b7de027c 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx @@ -3,13 +3,12 @@ import { CircleProgress } from "@follow/components/icons/Progress.js" import { MotionButtonBase } from "@follow/components/ui/button/index.js" import { RootPortal } from "@follow/components/ui/portal/index.jsx" import { useScrollViewElement } from "@follow/components/ui/scroll-area/hooks.js" -import { EventBus } from "@follow/utils/event-bus" import { springScrollTo } from "@follow/utils/scroller" import { cn } from "@follow/utils/utils" import { useStore } from "jotai" import { memo, useEffect, useMemo, useState } from "react" -import { AIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai" +import { AIChatPanelStyle, setAIPanelVisibility, useAIChatPanelStyle } from "~/atoms/settings/ai" import type { TocRef } from "~/components/ui/markdown/components/Toc" import { Toc } from "~/components/ui/markdown/components/Toc" import { useFeature } from "~/hooks/biz/useFeature" @@ -69,7 +68,7 @@ const BackTopIndicator: Component = memo(({ className }) => { {aiEnabled && !isAiPanelOpen && ( { - EventBus.dispatch("global:toggle-ai-chat-pinned") + setAIPanelVisibility(true) }} className={cn( "mt-1 flex flex-nowrap items-center gap-2 text-sm opacity-50 transition-all duration-500 hover:opacity-100", diff --git a/locales/shortcuts/en.json b/locales/shortcuts/en.json index 2ce350a4f..914f68c36 100644 --- a/locales/shortcuts/en.json +++ b/locales/shortcuts/en.json @@ -22,8 +22,6 @@ "command.global.show_shortcuts.title": "Show Shortcuts", "command.global.toggle_ai_chat.description": "Toggle the AI chat panel", "command.global.toggle_ai_chat.title": "AI Chat", - "command.global.toggle_ai_chat_pinned.description": "Toggle the AI chat panel pinned", - "command.global.toggle_ai_chat_pinned.title": "AI Chat(Pinned)", "command.global.toggle_corner_play.description": "Play/Pause playing status(If there is currently playing audio in the background)", "command.global.toggle_corner_play.title": "Toggle Corner Play", "command.layout.focus_to_entry_render.title": "Focus to Entry Render", diff --git a/locales/shortcuts/ja.json b/locales/shortcuts/ja.json index b50dfc749..d69e69b73 100644 --- a/locales/shortcuts/ja.json +++ b/locales/shortcuts/ja.json @@ -22,8 +22,6 @@ "command.global.show_shortcuts.title": "ショートカットを表示", "command.global.toggle_ai_chat.description": "AI チャットパネルを切り替えます", "command.global.toggle_ai_chat.title": "AI チャット", - "command.global.toggle_ai_chat_pinned.description": "AI チャットパネルをピン留めします", - "command.global.toggle_ai_chat_pinned.title": "AI チャット (ピン留め)", "command.global.toggle_corner_play.description": "再生中のオーディオがある場合、再生/一時停止の状態を切り替えます", "command.global.toggle_corner_play.title": "コーナー再生の切り替え", "command.layout.focus_to_entry_render.title": "エントリー レンダリングにフォーカス", From abd0e28af733dfc62e5088e66409efd051fcfe29 Mon Sep 17 00:00:00 2001 From: Innei Date: Tue, 12 Aug 2025 21:02:55 +0800 Subject: [PATCH 18/73] feat(ai): support switch ai panel style in ai setting - Added a new PanelStyleSegment component to manage AI chat panel styles, allowing users to select between fixed and floating layouts. - Updated localization files to include new strings for panel style settings. - Refactored existing components to integrate the new panel style options, improving user configurability and experience. These changes collectively enhance the flexibility and usability of the AI chat interface, providing users with better control over their layout preferences. Signed-off-by: Innei --- .../components/layouts/ChatMoreDropdown.tsx | 2 +- .../settings/modal/SettingModalContent.tsx | 4 +- .../renderer/src/modules/settings/tabs/ai.tsx | 47 +++++++++++++++++-- locales/ai/en.json | 8 +++- 4 files changed, 51 insertions(+), 10 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx index 5102cc38a..5dc3497a1 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx @@ -174,7 +174,7 @@ export const ChatMoreDropdown = () => { {panelStyle === AIChatPanelStyle.Fixed diff --git a/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx b/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx index 603dca129..11a83d72b 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx @@ -50,9 +50,9 @@ const Content = () => { div]:min-h-full [&>div]:relative", + "px-1 min-h-full [&>div]:min-h-full [&>div]:relative pl-8 pr-7", config.viewportClassName, )} > diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx index 3c10ce130..8b2dcaebf 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx @@ -8,9 +8,15 @@ import { useState } from "react" import { useTranslation } from "react-i18next" import { toast } from "sonner" -import { setAISetting, useAISettingValue } from "~/atoms/settings/ai" +import { + AIChatPanelStyle, + setAIChatPanelStyle, + setAISetting, + useAIChatPanelStyle, + useAISettingValue, +} from "~/atoms/settings/ai" -import { SettingActionItem, SettingDescription } from "../control" +import { SettingActionItem, SettingDescription, SettingTabbedSegment } from "../control" import { createDefineSettingItem } from "../helper/builder" import { createSettingBuilder } from "../helper/setting-builder" @@ -28,9 +34,11 @@ export const SettingAI = () => { type: "title", value: t("features.title"), }, + + PanelStyleSegment, defineSettingItem("autoScrollWhenStreaming", { - label: t("autoScrollWhenStreaming.label"), - description: t("autoScrollWhenStreaming.description"), + label: t("settings.autoScrollWhenStreaming.label"), + description: t("settings.autoScrollWhenStreaming.description"), }), { @@ -87,7 +95,7 @@ const PersonalizePromptSetting = () => {
-
+