From fc866b022249fc7e1d421bfde45116aaa0043f04 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 19 Nov 2025 13:49:45 +0800 Subject: [PATCH 01/31] fix: api header for ai chat --- .../src/modules/ai-chat/store/chat-core/chat-actions.ts | 3 +++ 1 file changed, 3 insertions(+) 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 535219dfa..1bb6e7c9d 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 @@ -1,4 +1,6 @@ import { autoBindThis } from "@follow/utils/bind-this" +import { createDesktopAPIHeaders } from "@follow/utils/headers" +import PKG from "@pkg" import type { ChatRequestOptions, ChatStatus } from "ai" import { merge } from "es-toolkit/compat" import { nanoid } from "nanoid" @@ -217,6 +219,7 @@ export class ChatSliceActions { const finalOptions = merge( { body: { scene: this.get().scene }, + headers: createDesktopAPIHeaders({ version: PKG.version }), }, options, ) From 41271111fe92d1c42d82f33b592a608f64132435 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 19 Nov 2025 14:48:42 +0800 Subject: [PATCH 02/31] fix: start free trial notice for upgrade plan --- locales/ai/en.json | 4 ++-- locales/ai/zh-CN.json | 4 ++-- locales/app/en.json | 10 +++++----- locales/app/zh-CN.json | 10 +++++----- locales/mobile/default/en.json | 2 +- locales/mobile/default/zh-CN.json | 2 +- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/locales/ai/en.json b/locales/ai/en.json index bc11fc947..27e5f548a 100644 --- a/locales/ai/en.json +++ b/locales/ai/en.json @@ -186,8 +186,8 @@ "rate_limit.resets_in": "resets in {{value}}", "rate_limit.resets_next_month": "resets at next month", "rate_limit.resets_tomorrow": "resets at tomorrow", - "rate_limit.upgrade_plan_button": "Upgrade Plan", - "rate_limit.upgrade_to_get_more": "Upgrade plan to get more AI credits.", + "rate_limit.upgrade_plan_button": "Free Trial", + "rate_limit.upgrade_to_get_more": "Start free trial to get more AI credits.", "schedule.configuration_label": "Configuration", "schedule.date_time_label": "Date & Time", "schedule.date_time_placeholder": "Select date & time", diff --git a/locales/ai/zh-CN.json b/locales/ai/zh-CN.json index 31ef7ad87..7fb93235c 100644 --- a/locales/ai/zh-CN.json +++ b/locales/ai/zh-CN.json @@ -181,8 +181,8 @@ "rate_limit.resets_in": "将在 {{value}} 后重置", "rate_limit.resets_next_month": "将于下个月重置", "rate_limit.resets_tomorrow": "将于明天重置", - "rate_limit.upgrade_plan_button": "升级套餐", - "rate_limit.upgrade_to_get_more": "升级套餐以获得更多 AI 额度。", + "rate_limit.upgrade_plan_button": "免费试用", + "rate_limit.upgrade_to_get_more": "开启免费试用以获得更多 AI 额度。", "schedule.configuration_label": "配置", "schedule.date_time_label": "日期和时间", "schedule.date_time_placeholder": "选择日期和时间", diff --git a/locales/app/en.json b/locales/app/en.json index 7839980cc..8017af6dd 100644 --- a/locales/app/en.json +++ b/locales/app/en.json @@ -20,13 +20,13 @@ "achievement.product_hunt_vote_description": "You supported Folo on Product Hunt", "activation.activate": "Activate", "activation.description": "During the public testing phase, you need an invitation code to use this feature.", - "activation.plan.description": "You are currently using the free plan. Upgrade the plan to unlock more features.", - "activation.plan.title": "Upgrade Plan", - "activation.plan.upgrade": "Upgrade", + "activation.plan.description": "You are currently using the free plan. Start free trial to unlock more features.", + "activation.plan.title": "Upgrade Plan (Free Trial)", + "activation.plan.upgrade": "Free Trial", "activation.title": "Invitation Code", "ai.summary_not_available": "Summary not available", "ai.summary_upgrade_required_description": "Unlock unlimited AI summaries, translations, and more intelligent features with Pro plan.", - "ai.summary_upgrade_required_title": "Upgrade plan to continue using AI summary", + "ai.summary_upgrade_required_title": "Start free trial to continue using AI summary", "ai.summary_upgrade_view_plans": "View Plans", "app.copy_logo_svg": "Copy Logo SVG", "app.copy_logo_text_svg": "Copy Logo Text SVG", @@ -458,7 +458,7 @@ "signin.continue_with": "Continue with {{provider}}", "signin.sign_in_to": "Sign in to", "signin.sign_up_to": "Sign up to", - "subscription_limit_warning": "Subscription limit reached:
{{feedCount}}/{{feedLimit}} feeds,
{{rsshubCount}}/{{rsshubLimit}} RSSHub.
Please upgrade plan or clean up unused feeds.", + "subscription_limit_warning": "Subscription limit reached:
{{feedCount}}/{{feedLimit}} feeds,
{{rsshubCount}}/{{rsshubLimit}} RSSHub.
Please start free trial to unlock more quota or clean up unused feeds.", "sync_indicator.disabled": "Due to security reasons, sync is disabled.", "sync_indicator.offline": "Offline", "sync_indicator.synced": "Synced with server", diff --git a/locales/app/zh-CN.json b/locales/app/zh-CN.json index d3d2e38a6..1e861e7f2 100644 --- a/locales/app/zh-CN.json +++ b/locales/app/zh-CN.json @@ -20,13 +20,13 @@ "achievement.product_hunt_vote_description": "在 Product Hunt 上给 Folo 投票", "activation.activate": "激活", "activation.description": "在公测阶段,预览版用户使用此功能会受限。", - "activation.plan.description": "您当前正在使用免费版本。升级以解锁更多功能。", - "activation.plan.title": "升级计划", - "activation.plan.upgrade": "升级", + "activation.plan.description": "您当前正在使用免费版本。开启免费试用以解锁更多功能。", + "activation.plan.title": "升级套餐(免费试用)", + "activation.plan.upgrade": "免费试用", "activation.title": "邀请码", "ai.summary_not_available": "摘要不可用", "ai.summary_upgrade_required_description": "升级到 Pro 计划,解锁无限 AI 摘要、翻译和更多智能功能。", - "ai.summary_upgrade_required_title": "升级计划以继续使用 AI 摘要", + "ai.summary_upgrade_required_title": "开启免费试用以继续使用 AI 摘要", "ai.summary_upgrade_view_plans": "查看计划", "app.copy_logo_svg": "复制 Logo SVG", "app.copy_logo_text_svg": "复制徽标 SVG 文本", @@ -457,7 +457,7 @@ "signin.continue_with": "使用 {{provider}} 登录", "signin.sign_in_to": "登录", "signin.sign_up_to": "注册", - "subscription_limit_warning": "订阅数量已达上限:
{{feedCount}}/{{feedLimit}} 个订阅源,
{{rsshubCount}}/{{rsshubLimit}} 个 RSSHub。
请升级套餐或清理未使用的订阅源。", + "subscription_limit_warning": "订阅数量已达上限:
{{feedCount}}/{{feedLimit}} 个订阅源,
{{rsshubCount}}/{{rsshubLimit}} 个 RSSHub。
请开启免费试用以解锁更多订阅额度,或清理未使用的订阅源。", "sync_indicator.disabled": "出于安全原因,已禁用同步", "sync_indicator.offline": "离线", "sync_indicator.synced": "已同步至云端", diff --git a/locales/mobile/default/en.json b/locales/mobile/default/en.json index 5c17ad614..081d79aac 100644 --- a/locales/mobile/default/en.json +++ b/locales/mobile/default/en.json @@ -1,7 +1,7 @@ { "ai.summary_not_available": "Summary not available", "ai.summary_upgrade_required_description": "Unlock unlimited AI summaries, translations, and more intelligent features with Pro plan.", - "ai.summary_upgrade_required_title": "Upgrade plan to continue using AI summary", + "ai.summary_upgrade_required_title": "Start free trial to continue using AI summary", "ai.summary_upgrade_view_plans": "View Plans", "entry.pull_up_to_next_entry": "Pull up to go to the next entry", "entry.release_to_next_entry": "Release to go to the next entry", diff --git a/locales/mobile/default/zh-CN.json b/locales/mobile/default/zh-CN.json index 0e1df4476..d50f16d6c 100644 --- a/locales/mobile/default/zh-CN.json +++ b/locales/mobile/default/zh-CN.json @@ -1,7 +1,7 @@ { "ai.summary_not_available": "摘要不可用", "ai.summary_upgrade_required_description": "升级到 Pro 计划,解锁无限 AI 摘要、翻译和更多智能功能。", - "ai.summary_upgrade_required_title": "升级计划以继续使用 AI 摘要", + "ai.summary_upgrade_required_title": "开启免费试用以继续使用 AI 摘要", "ai.summary_upgrade_view_plans": "查看计划", "entry.pull_up_to_next_entry": "继续上拉查看下一条内容", "entry.release_to_next_entry": "松开查看下一条内容", From 9a638b509cf16a357036dd30a6224034c96dd983 Mon Sep 17 00:00:00 2001 From: Whitewater Date: Wed, 19 Nov 2025 16:00:10 +0800 Subject: [PATCH 03/31] fix: update command type handling in entry actions (#4737) Refactor commandId type to ensure proper type usage and remove unnecessary string handling for custom integrations. --- .../src/hooks/biz/useEntryActions.tsx | 4 +-- .../renderer/src/modules/command/types.ts | 2 +- .../entry-content/actions/more-actions.tsx | 30 ++----------------- 3 files changed, 5 insertions(+), 31 deletions(-) diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx index 7f48a4206..d50f97add 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx @@ -27,7 +27,7 @@ import { COMMAND_ID } from "~/modules/command/commands/id" import { getCommand, useRunCommandFn } from "~/modules/command/hooks/use-command" import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding" import { isMutationCommandId } from "~/modules/command/mutation-command-ids" -import type { FollowCommandId } from "~/modules/command/types" +import type { FollowCommandId, UnknownCommand } from "~/modules/command/types" import { useToolbarOrderMap } from "~/modules/customize-toolbar/hooks" import { useRouteParams } from "./useRouteParams" @@ -446,7 +446,7 @@ export const useEntryActions = ({ entryId, view }: { entryId: string; view: Feed onClick: runCmdFn(COMMAND_ID.integration.custom, [{ entryId }]), entryId, children: enabledIntegrations.map((integration) => { - const virtualId = `integration:custom:${integration.id}` as FollowCommandId + const virtualId = `integration:custom:${integration.id}` as UnknownCommand["id"] return new EntryActionMenuItem({ id: virtualId, onClick: () => { diff --git a/apps/desktop/layer/renderer/src/modules/command/types.ts b/apps/desktop/layer/renderer/src/modules/command/types.ts index 3f8d03978..ef802f4fb 100644 --- a/apps/desktop/layer/renderer/src/modules/command/types.ts +++ b/apps/desktop/layer/renderer/src/modules/command/types.ts @@ -66,4 +66,4 @@ export type UnknownCommand = Command<{ }> export type FollowCommandId = FollowCommand["id"] -export type FollowCommand = BasicCommand // | UnknownCommand +export type FollowCommand = BasicCommand | UnknownCommand diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx index 839b25e2a..3b0db2320 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx @@ -179,39 +179,13 @@ export const CommandDropdownMenuItem = ({ asSubTrigger = false, disabled = false, }: { - commandId: FollowCommandId | string + commandId: FollowCommandId onClick: () => void active?: boolean asSubTrigger?: boolean disabled?: boolean }) => { - const command = useCommand(commandId as any) - - // For custom integration items - if (typeof commandId === "string" && commandId.startsWith("integration:custom:")) { - const content = ( - <> - - Custom Integration - - ) - - if (asSubTrigger) { - return content - } - - return ( - - {content} - - ) - } + const command = useCommand(commandId) if (!command) return null From 8ba1bef397b7c331d1a3d24ec43616aaa3353c5a Mon Sep 17 00:00:00 2001 From: Whitewater Date: Wed, 19 Nov 2025 16:00:41 +0800 Subject: [PATCH 04/31] fix: correct jsonEscape logic and trim headers in fetch template processing (#4736) * fix: correct jsonEscape logic in fetch template processing * fix: trim processed headers keys and values in fetch template processing --- .../src/modules/integration/custom-integration-manager.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts b/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts index d780b4db8..86c54abf2 100644 --- a/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts +++ b/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts @@ -182,13 +182,13 @@ export class CustomIntegrationManager { const processedKey = this.replacePlaceholders(key, context) const processedValue = this.replacePlaceholders(value, context) // Field names are case-insensitive. - processedHeaders[processedKey.toLowerCase()] = processedValue + processedHeaders[processedKey.toLowerCase().trim()] = processedValue.trim() }) // Process body without URL encoding let processedBody: string | undefined if (fetchTemplate.body) { - const jsonEscape = fetchTemplate.headers["content-type"]?.toLowerCase() === "application/json" + const jsonEscape = processedHeaders["content-type"]?.toLowerCase() === "application/json" processedBody = this.replacePlaceholders(fetchTemplate.body, context, { jsonEscape }) } From 44a0a405722cf04961df1a711c73270688202d20 Mon Sep 17 00:00:00 2001 From: Innei Date: Wed, 19 Nov 2025 16:03:48 +0800 Subject: [PATCH 05/31] fix: update innerGlow styles for dropdown-menu, context-menu, and tooltip components Signed-off-by: Innei --- .../renderer/src/components/ui/dropdown-menu/dropdown-menu.tsx | 2 +- .../internal/components/src/ui/context-menu/context-menu.tsx | 2 +- packages/internal/components/src/ui/tooltip/styles.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/desktop/layer/renderer/src/components/ui/dropdown-menu/dropdown-menu.tsx b/apps/desktop/layer/renderer/src/components/ui/dropdown-menu/dropdown-menu.tsx index 94b0cc244..10ca607e7 100644 --- a/apps/desktop/layer/renderer/src/components/ui/dropdown-menu/dropdown-menu.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/dropdown-menu/dropdown-menu.tsx @@ -18,7 +18,7 @@ const styles = { } as React.CSSProperties, innerGlow: { background: - "linear-gradient(to bottom right, hsl(var(--fo-a) / 0.05), transparent, hsl(var(--fo-a) / 0.05))", + "linear-gradient(to bottom right, hsl(var(--fo-a) / 0.01), transparent, hsl(var(--fo-a) / 0.01))", } as React.CSSProperties, } diff --git a/packages/internal/components/src/ui/context-menu/context-menu.tsx b/packages/internal/components/src/ui/context-menu/context-menu.tsx index fc6573dae..e42e4256b 100644 --- a/packages/internal/components/src/ui/context-menu/context-menu.tsx +++ b/packages/internal/components/src/ui/context-menu/context-menu.tsx @@ -14,7 +14,7 @@ const styles = { } as React.CSSProperties, innerGlow: { background: - "linear-gradient(to bottom right, hsl(var(--fo-a) / 0.05), transparent, hsl(var(--fo-a) / 0.05))", + "linear-gradient(to bottom right, hsl(var(--fo-a) / 0.01), transparent, hsl(var(--fo-a) / 0.01))", } as React.CSSProperties, } diff --git a/packages/internal/components/src/ui/tooltip/styles.ts b/packages/internal/components/src/ui/tooltip/styles.ts index f2e8d05c4..63da77ae5 100644 --- a/packages/internal/components/src/ui/tooltip/styles.ts +++ b/packages/internal/components/src/ui/tooltip/styles.ts @@ -24,7 +24,7 @@ export const tooltipStyles: { }, innerGlow: { background: - "linear-gradient(to bottom right, hsl(var(--fo-a) / 0.05), transparent, hsl(var(--fo-a) / 0.05))", + "linear-gradient(to bottom right, hsl(var(--fo-a) / 0.01), transparent, hsl(var(--fo-a) / 0.01))", }, arrow: { fill: "hsl(var(--fo-a) / 0.2)", From 1281e8ebb4601b33560c8eb1047e3c8881f07a1f Mon Sep 17 00:00:00 2001 From: Innei Date: Wed, 19 Nov 2025 16:06:03 +0800 Subject: [PATCH 06/31] fix: conditionally render close button in LoginModalContent for non-Electron environments Signed-off-by: Innei --- .../src/modules/auth/LoginModalContent.tsx | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx b/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx index 56b492407..aeacb90ca 100644 --- a/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx @@ -4,6 +4,7 @@ import { Folo } from "@follow/components/icons/folo.js" import { Logo } from "@follow/components/icons/logo.js" import { MotionButtonBase } from "@follow/components/ui/button/index.js" import { useIsDark } from "@follow/hooks" +import { IN_ELECTRON } from "@follow/shared" import type { LoginRuntime } from "@follow/shared/auth" import { stopPropagation } from "@follow/utils/dom" import { cn } from "@follow/utils/utils" @@ -119,15 +120,15 @@ export const LoginModalContent = (props: LoginModalContentProps) => { - - - - - + {!IN_ELECTRON && ( + + + + )} {isEmail ? ( Date: Wed, 19 Nov 2025 16:16:41 +0800 Subject: [PATCH 07/31] fix: enhance token usage display and rate limit messaging for free users, resolves FOL-2808 - Updated TokenUsagePill to conditionally render token details based on user role. - Modified computeRateLimitMessage to include an option for hiding reset details. - Adjusted ChatInterface to utilize user role for displaying reset details in rate limit messages. Signed-off-by: Innei --- .../src/components/ui/modal/stacked/modal.tsx | 8 - .../components/layouts/ChatInterface.tsx | 11 +- .../components/message/TokenUsagePill.tsx | 139 ++++++++++-------- .../src/modules/ai-chat/utils/rate-limit.ts | 20 ++- 4 files changed, 104 insertions(+), 74 deletions(-) diff --git a/apps/desktop/layer/renderer/src/components/ui/modal/stacked/modal.tsx b/apps/desktop/layer/renderer/src/components/ui/modal/stacked/modal.tsx index 988ea6861..1201fc53a 100644 --- a/apps/desktop/layer/renderer/src/components/ui/modal/stacked/modal.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/modal/stacked/modal.tsx @@ -369,14 +369,6 @@ export const ModalInternal = memo(function Modal({ cursor: "grabbing", }} > - {/* Inner glow layer */} -
{ const error = useChatError() const messages = useMessages() const { ensureLogin } = useRequireLogin() + const userRole = useUserRole() const isFocusWithIn = useFocusable() @@ -325,6 +328,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const { handleScroll } = useAttachScrollBeyond() const { data: configuration } = useAIConfiguration() + const shouldHideResetDetails = userRole ? isFreeRole(userRole) : false const isRateLimited = useMemo( () => computeIsRateLimited(error, configuration), @@ -332,8 +336,11 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { ) const rateLimitMessage = useMemo( - () => computeRateLimitMessage(error, configuration), - [error, configuration], + () => + computeRateLimitMessage(error, configuration, { + hideResetDetails: shouldHideResetDetails, + }), + [error, configuration, shouldHideResetDetails], ) return ( diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/TokenUsagePill.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/TokenUsagePill.tsx index 6e7bd5dfd..f583f8067 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/TokenUsagePill.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/TokenUsagePill.tsx @@ -4,6 +4,8 @@ import { TooltipPortal, TooltipTrigger, } from "@follow/components/ui/tooltip/index.js" +import { isFreeRole } from "@follow/constants" +import { useUserRole } from "@follow/store/user/hooks" import type { BizUIMetadata } from "@folo-services/ai-tools" import * as React from "react" @@ -21,7 +23,15 @@ const formatDuration = (ms: number): string => { } export const TokenUsagePill: React.FC = ({ metadata, children }) => { + const userRole = useUserRole() if (!metadata) return null + const isFreeUser = userRole ? isFreeRole(userRole) : false + const summarizedTokens = + metadata.billedTokens ?? + metadata.totalTokens ?? + metadata.outputTokens ?? + metadata.contextTokens ?? + null const hasReasoningTokens = metadata.reasoningTokens != null && metadata.reasoningTokens > 0 const hasCachedInputTokens = metadata.cachedInputTokens != null && metadata.cachedInputTokens > 0 @@ -42,75 +52,88 @@ export const TokenUsagePill: React.FC = ({ metadata, childr
AI Credits Usage
-
- {metadata.totalTokens != null && ( -
- Total: - - {formatTokenCountString(metadata.totalTokens)} - -
- )} - {metadata.billedTokens != null && ( -
- Billed: - - {formatTokenCountString(metadata.billedTokens)} - -
- )} - {metadata.contextTokens != null && ( -
- Context: - - {formatTokenCountString(metadata.contextTokens)} - -
- )} - {metadata.outputTokens != null && ( -
- Output: - - {formatTokenCountString(metadata.outputTokens)} - -
- )} - {hasReasoningTokens && ( -
- Reasoning: - - {formatTokenCountString(metadata.reasoningTokens!)} - -
- )} - {hasCachedInputTokens && ( -
- Cached: - - {formatTokenCountString(metadata.cachedInputTokens!)} - -
- )} -
- {(hasDuration || hasBillingMultiplier) && ( + {isFreeUser ? ( +
+ Credits: + + {summarizedTokens != null ? formatTokenCountString(summarizedTokens) : "—"} + +
+ ) : ( <> -
- {hasDuration && ( + {metadata.totalTokens != null && (
- Duration: + Total: - {formatDuration(metadata.duration!)} + {formatTokenCountString(metadata.totalTokens)}
)} - {hasBillingMultiplier && ( + {metadata.billedTokens != null && (
- Multiplier: - {metadata.billingMultiplier!}× + Billed: + + {formatTokenCountString(metadata.billedTokens)} + +
+ )} + {metadata.contextTokens != null && ( +
+ Context: + + {formatTokenCountString(metadata.contextTokens)} + +
+ )} + {metadata.outputTokens != null && ( +
+ Output: + + {formatTokenCountString(metadata.outputTokens)} + +
+ )} + {hasReasoningTokens && ( +
+ Reasoning: + + {formatTokenCountString(metadata.reasoningTokens!)} + +
+ )} + {hasCachedInputTokens && ( +
+ Cached: + + {formatTokenCountString(metadata.cachedInputTokens!)} +
)}
+ {(hasDuration || hasBillingMultiplier) && ( + <> +
+
+ {hasDuration && ( +
+ Duration: + + {formatDuration(metadata.duration!)} + +
+ )} + {hasBillingMultiplier && ( +
+ Multiplier: + + {metadata.billingMultiplier!}× + +
+ )} +
+ + )} )}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/rate-limit.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/rate-limit.ts index 6e3f6158f..56d058b78 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/rate-limit.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/rate-limit.ts @@ -9,6 +9,10 @@ export interface AIConfigLike { freeQuota?: FreeQuota } +export interface RateLimitMessageOptions { + hideResetDetails?: boolean +} + const formatResetTime = (windowResetTime: Date) => { const i18n = getI18n() const { t } = i18n @@ -56,9 +60,11 @@ export function computeIsRateLimited( export function computeRateLimitMessage( error: Error | string | undefined, configuration?: AIConfigLike | null, + options?: RateLimitMessageOptions, ): string | null { const i18n = getI18n() const { t } = i18n + const hideResetDetails = options?.hideResetDetails ?? false const aiNs = { ns: "ai" } as const if (error) { @@ -84,7 +90,7 @@ export function computeRateLimitMessage( parts.push(t("rate_limit.upgrade_to_get_more", aiNs)) } - if (resetText) { + if (resetText && !hideResetDetails) { parts.push(resetText) } @@ -102,10 +108,12 @@ export function computeRateLimitMessage( if (!daily || !monthly) { const parts: string[] = [] parts.push(t("rate_limit.depleted", aiNs)) - if (!daily && monthly) { - parts.push(t("rate_limit.resets_tomorrow", aiNs)) - } else { - parts.push(t("rate_limit.resets_next_month", aiNs)) + if (!hideResetDetails) { + if (!daily && monthly) { + parts.push(t("rate_limit.resets_tomorrow", aiNs)) + } else { + parts.push(t("rate_limit.resets_next_month", aiNs)) + } } parts.push(t("rate_limit.upgrade_to_get_more", aiNs)) return parts.join(" · ") @@ -124,7 +132,7 @@ export function computeRateLimitMessage( } else { parts.push(t("rate_limit.credits_left", { ns: "ai", count: remaining })) } - if (formattedResetText) { + if (formattedResetText && !hideResetDetails) { parts.push(formattedResetText) } if (parts.length < 2) { From 5cbfb50df0204cc5e95f9f1793811fef3e3b1b53 Mon Sep 17 00:00:00 2001 From: Innei Date: Wed, 19 Nov 2025 16:40:26 +0800 Subject: [PATCH 08/31] fix: chat session delete loading state - Updated session deletion logic in ChatHistoryDropdown and TaskReportDropdown to use an options object for event handling and pre-delete actions. - Refactored ChatInterface to streamline focus handling and error logging, introducing new hooks for managing chat input focus and logging errors. - Enhanced chat scroller functionality to better manage content height and scrolling behavior. - Introduced utility hooks for managing chat drafts and rate limit information. Signed-off-by: Innei --- .../layouts/ChatHistoryDropdown.tsx | 9 +- .../components/layouts/ChatInterface.tsx | 288 +++++++++++------- .../components/layouts/TaskReportDropdown.tsx | 6 +- .../layouts/shared/ChatSessionComponents.tsx | 6 +- .../layouts/shared/useChatSessionHandlers.tsx | 13 +- 5 files changed, 205 insertions(+), 117 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHistoryDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHistoryDropdown.tsx index ca21ddde9..5e3392922 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHistoryDropdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHistoryDropdown.tsx @@ -160,8 +160,7 @@ export const ChatHistoryDropdown = ({ session={session} onClick={() => handleSessionSelect(session)} onDelete={(e) => { - setLoadingChatId(session.chatId) - handleDeleteSession(session.chatId, e).finally(() => { + handleDeleteSession(session.chatId, { event: e }).finally(() => { setLoadingChatId(null) }) }} @@ -183,8 +182,10 @@ export const ChatHistoryDropdown = ({ session={session} onClick={() => handleSessionSelect(session)} onDelete={(e) => { - setLoadingChatId(session.chatId) - handleDeleteSession(session.chatId, e).finally(() => { + handleDeleteSession(session.chatId, { + event: e, + onBeforeDelete: () => setLoadingChatId(session.chatId), + }).finally(() => { setLoadingChatId(null) }) }} 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 aad1fb02c..9c239170a 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,4 +1,5 @@ import { useFocusable } from "@follow/components/common/Focusable/hooks.js" +import type { LexicalRichEditorRef } from "@follow/components/ui/lexical-rich-editor/types.js" import { convertLexicalToMarkdown, getEditorStateJSONString, @@ -9,10 +10,12 @@ import { usePrefetchSummary } from "@follow/store/summary/hooks" import { useUserRole } from "@follow/store/user/hooks" import { tracker } from "@follow/tracker" import { detectIsEditableElement, nextFrame } from "@follow/utils" +import type { ConfigResponse } from "@follow-app/client-sdk" import { ErrorBoundary } from "@sentry/react" import type { EditorState } from "lexical" import { createEditor } from "lexical" import { nanoid } from "nanoid" +import type { RefObject } from "react" import { use, useEffect, useMemo, useRef, useState } from "react" import { useEventCallback, useEventListener } from "usehooks-ts" @@ -60,30 +63,12 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const { ensureLogin } = useRequireLogin() const userRole = useUserRole() - const isFocusWithIn = useFocusable() + const isFocusWithin = useFocusable() const aiPanelRefs = use(AIPanelRefsContext) - useEventListener("keydown", (e) => { - if (isFocusWithIn) { - const currentActiveElement = document.activeElement - - if (detectIsEditableElement(currentActiveElement as HTMLElement)) { - return - } - - if (e.shiftKey || e.metaKey || e.ctrlKey) { - return - } - aiPanelRefs.inputRef?.current?.focus() - } - }) - - useEffect(() => { - if (error) { - console.error("AIChat Error:", error) - } - }, [error]) + useChatInputFocusHandler(isFocusWithin, aiPanelRefs.inputRef) + useLogChatError(error) const currentChatId = useCurrentChatId() const mainEntryId = useMainEntryId() @@ -96,15 +81,16 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { enabled: !!mainEntryId && !hasMessages, }) - const [scrollAreaRef, setScrollAreaRef] = useState(null) - const [messageContainerMinHeight, setMessageContainerMinHeight] = useState() - const previousMinHeightRef = useRef(0) - const messagesContentRef = useRef(null) - - useEffect(() => { - setMessageContainerMinHeight(undefined) - previousMinHeightRef.current = 0 - }, [currentChatId]) + const { + scrollAreaRef, + setScrollAreaRef, + messageContainerMinHeight, + messagesContentRef, + scrollContainerParentRef, + captureContentHeightBeforeSend, + handleScrollPositioning, + updateContentHeightSnapshot, + } = useChatScroller(currentChatId) const { isLoading: isLoadingHistory, isSyncingRemote } = useLoadMessages(currentChatId || "", { onLoad: () => { @@ -123,27 +109,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const autoScrollWhenStreaming = useAISettingKey("autoScrollWhenStreaming") - const { shouldShowInterruptionNotice, lastUserMessage } = useMemo(() => { - if (messages.length === 0) { - return { - shouldShowInterruptionNotice: false, - lastUserMessage: null as BizUIMessage | null, - } - } - - const lastMessage = messages.at(-1)! - - const shouldShow = - lastMessage.role === "user" && - status !== "streaming" && - status !== "error" && - status !== "submitted" - - return { - shouldShowInterruptionNotice: shouldShow, - lastUserMessage: shouldShow ? lastMessage : null, - } - }, [messages, status]) + const { shouldShowInterruptionNotice, lastUserMessage } = useInterruptionNotice(messages, status) const { resetScrollState } = useAutoScroll( scrollAreaRef, @@ -152,32 +118,6 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const blockActions = useBlockActions() - const scrollHeightBeforeSendingRef = useRef(0) - const scrollContainerParentRef = useRef(null) - const handleScrollPositioning = useEventCallback(() => { - const $scrollContainerParent = scrollContainerParentRef.current - if (!scrollAreaRef || !$scrollContainerParent) return - - const parentClientHeight = $scrollContainerParent.clientHeight - // Use actual content height captured before send (messages container height), not inflated by minHeight - const currentScrollHeight = scrollHeightBeforeSendingRef.current - - // Calculate new minimum height based on actual content height - // Use previousMinHeightRef which tracks the real content height, not reserved space - const baseHeight = Math.max(previousMinHeightRef.current, currentScrollHeight) - const newMinHeight = baseHeight + parentClientHeight - 250 - - setMessageContainerMinHeight(newMinHeight) - - // Scroll to the end immediately to position user message at top - nextFrame(() => { - scrollAreaRef.scrollTo({ - top: scrollAreaRef.scrollHeight, - behavior: "instant", - }) - }) - }) - const staticEditor = useMemo(() => { return createEditor({ nodes: LexicalAIEditorNodes, @@ -247,8 +187,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { }) } - // Capture actual content height (messages container), not including reserved minHeight - scrollHeightBeforeSendingRef.current = messagesContentRef.current?.scrollHeight ?? 0 + captureContentHeightBeforeSend() const messageId = prefixMessageIdWithShortcut(nanoid(), shortcutIdFromMessage) const sendMessage: SendingUIMessage = { parts, @@ -259,9 +198,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { tracker.aiChatMessageSent() // Clear draft message after sending - if (currentChatId) { - draftMessages.delete(currentChatId) - } + clearDraft() nextFrame(() => { // Calculate and adjust scroll positioning immediately @@ -288,7 +225,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const retryShortcutId = extractShortcutIdFromMessageParts(retryMessage.parts) retryMessage.id = prefixMessageIdWithShortcut(retryMessage.id, retryShortcutId) - scrollHeightBeforeSendingRef.current = messagesContentRef.current?.scrollHeight ?? 0 + captureContentHeightBeforeSend() chatActions.popMessage() void chatActions.sendMessage(retryMessage) @@ -299,15 +236,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { }) }) - // Save draft message when input changes - const handleDraftChange = useEventCallback((editorState: EditorState) => { - if (currentChatId) { - draftMessages.set(currentChatId, editorState) - } - }) - - // Get initial draft message for current chat - const initialDraft = currentChatId ? draftMessages.get(currentChatId) : undefined + const { handleDraftChange, initialDraft, clearDraft } = useChatDraft(currentChatId) const [bottomPanelHeight, setBottomPanelHeight] = useState(0) @@ -320,27 +249,20 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { // This avoids CLS while ensuring next calculation is based on actual content if (status === "ready" && scrollAreaRef && messagesContentRef.current) { // Update the reference to actual content height for next calculation (use messages container) - previousMinHeightRef.current = messagesContentRef.current.scrollHeight + updateContentHeightSnapshot() // Keep the current minHeight unchanged to avoid CLS } - }, [status, resetScrollState, messageContainerMinHeight, scrollAreaRef]) + }, [status, resetScrollState, scrollAreaRef, updateContentHeightSnapshot, messagesContentRef]) const { handleScroll } = useAttachScrollBeyond() const { data: configuration } = useAIConfiguration() const shouldHideResetDetails = userRole ? isFreeRole(userRole) : false - const isRateLimited = useMemo( - () => computeIsRateLimited(error, configuration), - [error, configuration], - ) - - const rateLimitMessage = useMemo( - () => - computeRateLimitMessage(error, configuration, { - hideResetDetails: shouldHideResetDetails, - }), - [error, configuration, shouldHideResetDetails], + const { isRateLimited, rateLimitMessage } = useRateLimitInfo( + error, + configuration, + shouldHideResetDetails, ) return ( @@ -388,3 +310,159 @@ export const ChatInterface = (props: ChatInterfaceProps) => ( ) + +const useChatInputFocusHandler = ( + isFocusWithin: boolean, + inputRef?: RefObject, +) => { + useEventListener("keydown", (event) => { + if (!isFocusWithin) { + return + } + const currentActiveElement = document.activeElement + + if (detectIsEditableElement(currentActiveElement as HTMLElement)) { + return + } + + if (event.shiftKey || event.metaKey || event.ctrlKey) { + return + } + + inputRef?.current?.focus() + }) +} + +const useLogChatError = (error: unknown) => { + useEffect(() => { + if (error) { + console.error("AIChat Error:", error) + } + }, [error]) +} + +const useInterruptionNotice = ( + messages: BizUIMessage[], + status: ReturnType, +) => { + return useMemo(() => { + if (messages.length === 0) { + return { + shouldShowInterruptionNotice: false, + lastUserMessage: null as BizUIMessage | null, + } + } + + const lastMessage = messages.at(-1)! + const shouldShow = + lastMessage.role === "user" && + status !== "streaming" && + status !== "error" && + status !== "submitted" + + return { + shouldShowInterruptionNotice: shouldShow, + lastUserMessage: shouldShow ? lastMessage : null, + } + }, [messages, status]) +} + +const useChatDraft = (currentChatId?: string | null) => { + const handleDraftChange = useEventCallback((editorState: EditorState) => { + if (currentChatId) { + draftMessages.set(currentChatId, editorState) + } + }) + + const clearDraft = useEventCallback(() => { + if (currentChatId) { + draftMessages.delete(currentChatId) + } + }) + + const initialDraft = currentChatId ? draftMessages.get(currentChatId) : undefined + + return { + handleDraftChange, + initialDraft, + clearDraft, + } +} + +const useRateLimitInfo = ( + error: Error | string | undefined, + configuration: ConfigResponse | undefined, + shouldHideResetDetails: boolean, +) => { + const isRateLimited = useMemo( + () => computeIsRateLimited(error, configuration), + [error, configuration], + ) + + const rateLimitMessage = useMemo( + () => + computeRateLimitMessage(error, configuration, { + hideResetDetails: shouldHideResetDetails, + }), + [error, configuration, shouldHideResetDetails], + ) + + return { + isRateLimited, + rateLimitMessage, + } +} + +const useChatScroller = (currentChatId?: string | null) => { + const [scrollAreaRef, setScrollAreaRef] = useState(null) + const [messageContainerMinHeight, setMessageContainerMinHeight] = useState() + const messagesContentRef = useRef(null) + const scrollContainerParentRef = useRef(null) + const scrollHeightBeforeSendingRef = useRef(0) + const previousMinHeightRef = useRef(0) + + useEffect(() => { + setMessageContainerMinHeight(undefined) + previousMinHeightRef.current = 0 + }, [currentChatId]) + + const captureContentHeightBeforeSend = useEventCallback(() => { + scrollHeightBeforeSendingRef.current = messagesContentRef.current?.scrollHeight ?? 0 + }) + + const handleScrollPositioning = useEventCallback(() => { + const $scrollContainerParent = scrollContainerParentRef.current + if (!scrollAreaRef || !$scrollContainerParent) return + + const parentClientHeight = $scrollContainerParent.clientHeight + const currentScrollHeight = scrollHeightBeforeSendingRef.current + const baseHeight = Math.max(previousMinHeightRef.current, currentScrollHeight) + const newMinHeight = baseHeight + parentClientHeight - 250 + + setMessageContainerMinHeight(newMinHeight) + + nextFrame(() => { + scrollAreaRef.scrollTo({ + top: scrollAreaRef.scrollHeight, + behavior: "instant", + }) + }) + }) + + const updateContentHeightSnapshot = useEventCallback(() => { + if (scrollAreaRef && messagesContentRef.current) { + previousMinHeightRef.current = messagesContentRef.current.scrollHeight + } + }) + + return { + scrollAreaRef, + setScrollAreaRef, + messageContainerMinHeight, + messagesContentRef, + scrollContainerParentRef, + captureContentHeightBeforeSend, + handleScrollPositioning, + updateContentHeightSnapshot, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/TaskReportDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/TaskReportDropdown.tsx index 62eb6d22a..01708df67 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/TaskReportDropdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/TaskReportDropdown.tsx @@ -111,8 +111,10 @@ export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskRepor session={session} onClick={() => handleSessionSelect(session)} onDelete={(e) => { - setLoadingChatId(session.chatId) - handleDeleteSession(session.chatId, e).finally(() => { + handleDeleteSession(session.chatId, { + event: e, + onBeforeDelete: () => setLoadingChatId(session.chatId), + }).finally(() => { setLoadingChatId(null) }) }} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/shared/ChatSessionComponents.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/shared/ChatSessionComponents.tsx index 1d5d79d66..d20b831bb 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/shared/ChatSessionComponents.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/shared/ChatSessionComponents.tsx @@ -21,12 +21,12 @@ export interface EmptyStateProps { icon?: ReactNode } -// Components export const SessionItem = ({ session, onClick, onDelete, - isLoading, + + isLoading = false, hasUnread = false, }: SessionItemProps) => { const hasUnreadMessages = isUnreadSession(session) @@ -56,8 +56,8 @@ export const SessionItem = ({ + {/* Inner glow layer */} +
- {/* Play/Pause Button */} - - - {/* Skip Forward 10s */} - -
- - {/* Progress Bar Container */} -
-
-
+ {/* Control buttons and progress bar */} +
+ {/* Control buttons */} +
+ {/* Skip Back 10s */} + + + {/* Play/Pause Button */} + + + {/* Skip Forward 10s */} + +
+ + {/* Progress Bar Container */} +
+ {displayHasValidDuration ? ( + { + if (isCurrentAudio) { + setIsDragging(true) + setDragValue(displayCurrentTime) + } + }} + onValueChange={handleSliderValueChange} + onValueCommit={handleSliderValueCommit} + > + + + + + + + ) : ( +
+ )} +
+ + {/* Time Display and Download */} +
+
+ {currentTimeDisplay} + / + {durationDisplay}
-
-
- {/* Time Display and Download */} -
-
- {currentTimeDisplay} - / - {durationDisplay} -
+ {/* Divider */} +
- {/* Download Button */} - + {/* Download Button */} + +
From f207cc328d687e4ce5b4e45a786042fbde8fde3b Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 19 Nov 2025 21:54:29 +0800 Subject: [PATCH 12/31] feat: secure image proxy in plan --- .../src/components/ui/media/Media.tsx | 2 +- .../layer/renderer/src/lib/img-proxy.ts | 16 ++++++++++++- .../entry-column/Items/media-gallery.tsx | 2 +- .../renderer/src/modules/feed/feed-icon.tsx | 3 ++- apps/mobile/src/components/ui/image/utils.ts | 3 ++- apps/mobile/src/lib/img-proxy.ts | 23 +++++++++++++++++++ locales/settings/en.json | 1 + locales/settings/ja.json | 1 + locales/settings/zh-CN.json | 1 + locales/settings/zh-TW.json | 1 + packages/internal/utils/src/img-proxy.ts | 22 ++++++++++++++++-- 11 files changed, 68 insertions(+), 7 deletions(-) create mode 100644 apps/mobile/src/lib/img-proxy.ts diff --git a/apps/desktop/layer/renderer/src/components/ui/media/Media.tsx b/apps/desktop/layer/renderer/src/components/ui/media/Media.tsx index c2f54629d..d93c8cfdd 100644 --- a/apps/desktop/layer/renderer/src/components/ui/media/Media.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/media/Media.tsx @@ -1,5 +1,4 @@ import { nextFrame } from "@follow/utils/dom" -import { getImageProxyUrl } from "@follow/utils/img-proxy" import { cn } from "@follow/utils/utils" import { ErrorBoundary } from "@sentry/react" import { useForceUpdate } from "motion/react" @@ -9,6 +8,7 @@ import { memo, use, useEffect, useMemo, useRef, useState } from "react" import { Blurhash, BlurhashCanvas } from "react-blurhash" import { useEventCallback } from "usehooks-ts" +import { getImageProxyUrl } from "~/lib/img-proxy" import { saveImageDimensionsToDb } from "~/store/image/db" import { useMediaContainerWidth, usePreviewMedia } from "./hooks" diff --git a/apps/desktop/layer/renderer/src/lib/img-proxy.ts b/apps/desktop/layer/renderer/src/lib/img-proxy.ts index b186c51d0..195f657d7 100644 --- a/apps/desktop/layer/renderer/src/lib/img-proxy.ts +++ b/apps/desktop/layer/renderer/src/lib/img-proxy.ts @@ -1,9 +1,23 @@ import { WEB_BUILD } from "@follow/shared/constants" -import { replaceImgUrlIfNeed as replaceImgUrlIfNeedUtils } from "@follow/utils/img-proxy" +import { role as getUserRole } from "@follow/store/user/getters" +import { + getImageProxyUrl as getImageProxyUrlUtils, + replaceImgUrlIfNeed as replaceImgUrlIfNeedUtils, +} from "@follow/utils/img-proxy" export const replaceImgUrlIfNeed = (url?: string) => { return replaceImgUrlIfNeedUtils({ url, inBrowser: WEB_BUILD, + userRole: getUserRole(), + }) +} + +export const getImageProxyUrl = ( + params: Omit[0], "userRole">, +) => { + return getImageProxyUrlUtils({ + ...params, + userRole: getUserRole(), }) } diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/Items/media-gallery.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/Items/media-gallery.tsx index a72b1a77b..319952462 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/Items/media-gallery.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/Items/media-gallery.tsx @@ -1,10 +1,10 @@ import { useEntry } from "@follow/store/entry/hooks" -import { getImageProxyUrl } from "@follow/utils/img-proxy" import { cn } from "@follow/utils/utils" import { useMemo } from "react" import { usePreviewMedia } from "~/components/ui/media/hooks" import { Media } from "~/components/ui/media/Media" +import { getImageProxyUrl } from "~/lib/img-proxy" import { jotaiStore } from "~/lib/jotai" import { socialMediaContentWidthAtom } from "../atoms/social-media-content-width" diff --git a/apps/desktop/layer/renderer/src/modules/feed/feed-icon.tsx b/apps/desktop/layer/renderer/src/modules/feed/feed-icon.tsx index fd62bc16b..d865bea80 100644 --- a/apps/desktop/layer/renderer/src/modules/feed/feed-icon.tsx +++ b/apps/desktop/layer/renderer/src/modules/feed/feed-icon.tsx @@ -2,13 +2,14 @@ import { PlatformIcon } from "@follow/components/ui/platform-icon/index.jsx" import type { FeedModel } from "@follow/store/feed/types" import { getBackgroundGradient } from "@follow/utils/color" -import { getImageProxyUrl } from "@follow/utils/img-proxy" import { cn, getUrlIcon } from "@follow/utils/utils" import * as AvatarPrimitive from "@radix-ui/react-avatar" import { m } from "motion/react" import type { ReactNode } from "react" import { useMemo } from "react" +import { getImageProxyUrl } from "~/lib/img-proxy" + const { Avatar, AvatarFallback, AvatarImage } = AvatarPrimitive // Size-responsive border radius utility function diff --git a/apps/mobile/src/components/ui/image/utils.ts b/apps/mobile/src/components/ui/image/utils.ts index 1f10bb744..4631a7da1 100644 --- a/apps/mobile/src/components/ui/image/utils.ts +++ b/apps/mobile/src/components/ui/image/utils.ts @@ -1,5 +1,5 @@ import { createBuildSafeHeaders } from "@follow/utils/headers" -import { getImageProxyUrl, IMAGE_PROXY_URL } from "@follow/utils/img-proxy" +import { IMAGE_PROXY_URL } from "@follow/utils/img-proxy" import ImageEditor from "@react-native-community/image-editor" import * as FileSystem from "expo-file-system" import type { ImageProps, ImageSource } from "expo-image" @@ -8,6 +8,7 @@ import * as Sharing from "expo-sharing" import { useCallback } from "react" import { Image } from "react-native" +import { getImageProxyUrl } from "@/src/lib/img-proxy" import { isAndroid, isNative } from "@/src/lib/platform" import { proxyEnv } from "@/src/lib/proxy-env" import { toast } from "@/src/lib/toast" diff --git a/apps/mobile/src/lib/img-proxy.ts b/apps/mobile/src/lib/img-proxy.ts new file mode 100644 index 000000000..3f97566ba --- /dev/null +++ b/apps/mobile/src/lib/img-proxy.ts @@ -0,0 +1,23 @@ +import { role as getUserRole } from "@follow/store/user/getters" +import { + getImageProxyUrl as getImageProxyUrlUtils, + replaceImgUrlIfNeed as replaceImgUrlIfNeedUtils, +} from "@follow/utils/img-proxy" + +export const getImageProxyUrl = ( + params: Omit[0], "userRole">, +) => { + return getImageProxyUrlUtils({ + ...params, + userRole: getUserRole(), + }) +} + +export const replaceImgUrlIfNeed = ( + params: Omit[0], "userRole">, +) => { + return replaceImgUrlIfNeedUtils({ + ...params, + userRole: getUserRole(), + }) +} diff --git a/locales/settings/en.json b/locales/settings/en.json index e502bea10..68a5546d2 100644 --- a/locales/settings/en.json +++ b/locales/settings/en.json @@ -583,6 +583,7 @@ "plan.features.MAX_SUBSCRIPTIONS": "Feed Subscriptions", "plan.features.PRIORITY_SUPPORT": "Priority Support", "plan.features.PRIVATE_SUBSCRIPTION": "Private Subscriptions", + "plan.features.SECURE_IMAGE_PROXY": "Secure Image Proxy", "privacy.privacy": "Privacy", "privacy.terms": "Terms", "profile.avatar.cropInstructions": "Drag the crop area to adjust your avatar", diff --git a/locales/settings/ja.json b/locales/settings/ja.json index e3f8d6050..869653624 100644 --- a/locales/settings/ja.json +++ b/locales/settings/ja.json @@ -578,6 +578,7 @@ "plan.features.MAX_SUBSCRIPTIONS": "フィードサブスクリプション", "plan.features.PRIORITY_SUPPORT": "優先サポート", "plan.features.PRIVATE_SUBSCRIPTION": "プライベートサブスクリプション", + "plan.features.SECURE_IMAGE_PROXY": "セキュア画像プロキシ", "privacy.privacy": "プライバシー", "privacy.terms": "利用規約", "profile.avatar.cropInstructions": "ドラッグしてトリミングエリアを調整します", diff --git a/locales/settings/zh-CN.json b/locales/settings/zh-CN.json index 10f3f2d54..c5dab244a 100644 --- a/locales/settings/zh-CN.json +++ b/locales/settings/zh-CN.json @@ -577,6 +577,7 @@ "plan.features.MAX_SUBSCRIPTIONS": "订阅源数量", "plan.features.PRIORITY_SUPPORT": "优先支持", "plan.features.PRIVATE_SUBSCRIPTION": "私有订阅", + "plan.features.SECURE_IMAGE_PROXY": "安全图片代理", "privacy.privacy": "隐私政策", "privacy.terms": "服务条款", "profile.avatar.cropInstructions": "拖动裁剪区域以调整头像", diff --git a/locales/settings/zh-TW.json b/locales/settings/zh-TW.json index 2e24b705c..42be8ae47 100644 --- a/locales/settings/zh-TW.json +++ b/locales/settings/zh-TW.json @@ -583,6 +583,7 @@ "plan.features.MAX_SUBSCRIPTIONS": "訂閱源數量", "plan.features.PRIORITY_SUPPORT": "優先支援", "plan.features.PRIVATE_SUBSCRIPTION": "私有訂閱", + "plan.features.SECURE_IMAGE_PROXY": "安全圖片代理", "privacy.privacy": "隱私政策", "privacy.terms": "服務條款", "profile.avatar.cropInstructions": "拖曳裁切區域以調整你的頭像", diff --git a/packages/internal/utils/src/img-proxy.ts b/packages/internal/utils/src/img-proxy.ts index 62494173d..ac4c1fb0e 100644 --- a/packages/internal/utils/src/img-proxy.ts +++ b/packages/internal/utils/src/img-proxy.ts @@ -1,5 +1,10 @@ export const IMAGE_PROXY_URL = "https://webp.follow.is" +const canUseImageProxy = (userRole?: string | null): boolean => { + if (!userRole) return false + return userRole === "plus" || userRole === "pro" +} + export const imageRefererMatches = [ { url: /^https:\/\/\w+\.sinaimg\.cn/, @@ -40,15 +45,28 @@ export const getImageProxyUrl = ({ url, width, height, + userRole, }: { url: string width?: number height?: number + userRole?: string | null }) => { + if (!canUseImageProxy(userRole)) { + return url + } return `${IMAGE_PROXY_URL}?url=${encodeURIComponent(url)}&width=${width ? Math.round(width) : ""}&height=${height ? Math.round(height) : ""}` } -export const replaceImgUrlIfNeed = ({ url, inBrowser }: { url?: string; inBrowser?: boolean }) => { +export const replaceImgUrlIfNeed = ({ + url, + inBrowser, + userRole, +}: { + url?: string + inBrowser?: boolean + userRole?: string | null +}) => { if (!url) return url for (const rule of webpCloudPublicServicesMatches) { @@ -59,7 +77,7 @@ export const replaceImgUrlIfNeed = ({ url, inBrowser }: { url?: string; inBrowse for (const rule of imageRefererMatches) { if ((inBrowser || rule.force) && rule.url.test(url)) { - return getImageProxyUrl({ url, width: 0, height: 0 }) + return getImageProxyUrl({ url, width: 0, height: 0, userRole }) } } return url From 043b5a02c4d374e313503605912cde042f351310 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 19 Nov 2025 22:01:07 +0800 Subject: [PATCH 13/31] fix: mark as read on top for list context menu --- .../renderer/src/hooks/biz/useFeedActions.tsx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useFeedActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useFeedActions.tsx index 6ea997819..7aeb473b8 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useFeedActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useFeedActions.tsx @@ -331,6 +331,15 @@ export const useListActions = ({ listId, view }: { listId: string; view?: FeedVi if (!list) return [] const items: MenuItemInput[] = [ + new MenuItemText({ + label: t("sidebar.feed_actions.mark_all_as_read"), + shortcut: shortcuts[COMMAND_ID.subscription.markAllAsRead], + click: () => { + unreadSyncService.markFeedAsRead(list.feedIds) + }, + requiresLogin: true, + }), + MenuItemSeparator.default, new MenuItemText({ label: t("sidebar.feed_actions.edit"), shortcut: "E", @@ -349,15 +358,6 @@ export const useListActions = ({ listId, view }: { listId: string; view?: FeedVi requiresLogin: true, }), MenuItemSeparator.default, - new MenuItemText({ - label: t("sidebar.feed_actions.mark_all_as_read"), - shortcut: shortcuts[COMMAND_ID.subscription.markAllAsRead], - click: () => { - unreadSyncService.markFeedAsRead(list.feedIds) - }, - requiresLogin: true, - }), - MenuItemSeparator.default, ...(list.ownerUserId === whoami()?.id ? [ new MenuItemText({ From 26c842751af733fef79048781854620c07c27bbf Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 19 Nov 2025 20:07:15 +0800 Subject: [PATCH 14/31] feat: add AI timeline sorting feature with customizable prompt settings --- .../modules/entry-column/atoms/ai-timeline.ts | 3 + .../entry-column/hooks/useEntriesByView.ts | 8 + .../entry-column/layouts/EntryListHeader.tsx | 78 ++++++++-- .../settings/modal/SettingModalContent.tsx | 2 +- .../renderer/src/modules/settings/tabs/ai.tsx | 8 + .../tabs/ai/TimelinePromptSection.tsx | 143 ++++++++++++++++++ locales/ai/en.json | 4 + locales/ai/zh-CN.json | 4 + locales/app/en.json | 2 + locales/app/ja.json | 2 + locales/app/zh-CN.json | 2 + locales/app/zh-TW.json | 2 + .../internal/shared/src/settings/defaults.ts | 1 + .../internal/shared/src/settings/interface.ts | 1 + .../internal/store/src/modules/entry/hooks.ts | 3 + .../internal/store/src/modules/entry/store.ts | 3 + .../internal/store/src/modules/entry/types.ts | 1 + 17 files changed, 251 insertions(+), 16 deletions(-) create mode 100644 apps/desktop/layer/renderer/src/modules/entry-column/atoms/ai-timeline.ts create mode 100644 apps/desktop/layer/renderer/src/modules/settings/tabs/ai/TimelinePromptSection.tsx diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/atoms/ai-timeline.ts b/apps/desktop/layer/renderer/src/modules/entry-column/atoms/ai-timeline.ts new file mode 100644 index 000000000..36b0a017c --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-column/atoms/ai-timeline.ts @@ -0,0 +1,3 @@ +import { atom } from "jotai" + +export const aiTimelineEnabledAtom = atom(false) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts index 3dea405c1..6e2e82852 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts +++ b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts @@ -18,14 +18,17 @@ import { nextFrame } from "@follow/utils" import { isBizId } from "@follow/utils/utils" import { useMutation } from "@tanstack/react-query" import { debounce } from "es-toolkit/compat" +import { useAtomValue } from "jotai" import { useCallback, useEffect, useMemo, useState } from "react" import { useGeneralSettingKey } from "~/atoms/settings/general" import { ROUTE_FEED_PENDING } from "~/constants/app" +import { useFeature } from "~/hooks/biz/useFeature" import { useRouteParams } from "~/hooks/biz/useRouteParams" import { useAuthQuery } from "~/hooks/common" import { entries } from "~/queries/entries" +import { aiTimelineEnabledAtom } from "../atoms/ai-timeline" import { useIsPreviewFeed } from "./useIsPreviewFeed" const useRemoteEntries = (): UseEntriesReturn => { @@ -36,6 +39,8 @@ const useRemoteEntries = (): UseEntriesReturn => { const hidePrivateSubscriptionsInTimeline = useGeneralSettingKey( "hidePrivateSubscriptionsInTimeline", ) + const aiTimelineEnabled = useAtomValue(aiTimelineEnabledAtom) + const aiEnabled = useFeature("ai") const folderIds = useFolderFeedsByFeedId({ feedId, @@ -53,6 +58,7 @@ const useRemoteEntries = (): UseEntriesReturn => { hidePrivateSubscriptionsInTimeline: true, }), ...(view === FeedViewType.All && { limit: 40 }), + ...(aiTimelineEnabled && aiEnabled && { aiSort: true }), } if (feedId && listId && isBizId(feedId)) { @@ -69,6 +75,8 @@ const useRemoteEntries = (): UseEntriesReturn => { isPreview, view, hidePrivateSubscriptionsInTimeline, + aiTimelineEnabled, + aiEnabled, ]) const query = useEntriesQuery(entriesOptions) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx index 47261d43a..2c904a4aa 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx @@ -10,13 +10,15 @@ import { useFeedById } from "@follow/store/feed/hooks" import { useIsLoggedIn, useWhoami } from "@follow/store/user/hooks" import { stopPropagation } from "@follow/utils/dom" import { clsx, cn, isBizId } from "@follow/utils/utils" -import { useAtomValue } from "jotai" +import { useAtom, useAtomValue } from "jotai" import type { FC } from "react" import { useCallback } from "react" import { useTranslation } from "react-i18next" import { useNavigate } from "react-router" +import { toast } from "sonner" import { previewBackPath } from "~/atoms/preview" +import { useAISettingKey } from "~/atoms/settings/ai" import { useGeneralSettingKey } from "~/atoms/settings/general" import { useSubscriptionColumnShow } from "~/atoms/sidebar" import { ROUTE_ENTRY_PENDING } from "~/constants" @@ -30,9 +32,12 @@ import { useRunCommandFn } from "~/modules/command/hooks/use-command" import { useCommandShortcut } from "~/modules/command/hooks/use-command-binding" import { EntryHeader } from "~/modules/entry-content/components/entry-header" import { FeedIcon } from "~/modules/feed/feed-icon" +import { useSettingModal } from "~/modules/settings/modal/useSettingModal" +import { AI_SETTING_SECTION_IDS } from "~/modules/settings/tabs/ai" import { useRefreshFeedMutation } from "~/queries/feed" import { useFeedHeaderIcon, useFeedHeaderTitle } from "~/store/feed/hooks" +import { aiTimelineEnabledAtom } from "../atoms/ai-timeline" import { MarkAllReadButton } from "../components/mark-all-button" import { useIsPreviewFeed } from "../hooks/useIsPreviewFeed" import { useEntryRootState } from "../store/EntryColumnContext" @@ -48,7 +53,10 @@ export const EntryListHeader: FC<{ const { t } = useTranslation() const unreadOnly = useGeneralSettingKey("unreadOnly") + const [aiTimelineEnabled, setAiTimelineEnabled] = useAtom(aiTimelineEnabledAtom) const aiEnabled = useFeature("ai") + const aiTimelinePrompt = useAISettingKey("aiTimelinePrompt") + const showSettings = useSettingModal() const { feedId, entryId, view, isCollection } = routerParams const isPreview = useIsPreviewFeed() @@ -102,6 +110,45 @@ export const EntryListHeader: FC<{ }, [sendAIShortcut]) const showEntryHeader = isWideMode && !!entryId && entryId !== ROUTE_ENTRY_PENDING const showTimelineSummaryButton = isWideMode && aiEnabled + const showAiTimelineToggle = aiEnabled + + const handleAiTimelineButtonClick = useCallback(() => { + const hasTimelinePrompt = !!aiTimelinePrompt?.trim() + + if (!aiTimelineEnabled && !hasTimelinePrompt) { + toast.info(t("entry_list_header.ai_timeline_prompt_required")) + showSettings({ tab: "ai", section: AI_SETTING_SECTION_IDS.timelinePrompt }) + return + } + + setAiTimelineEnabled((prev) => !prev) + }, [aiTimelineEnabled, aiTimelinePrompt, setAiTimelineEnabled, showSettings, t]) + + const renderAiTimelineButton = () => { + if (!showAiTimelineToggle) return null + return ( + + {aiTimelineEnabled ? ( + + ) : ( + + )} + + ) + } + + const renderTimelineSummaryButton = () => { + if (!showTimelineSummaryButton) return null + return ( + + + + ) + } return (
- {isWideMode && (showEntryHeader || showTimelineSummaryButton) && ( - <> - {showEntryHeader && } - {showTimelineSummaryButton && ( - - - - )} - - - )} + {isWideMode && + (showEntryHeader || showTimelineSummaryButton || showAiTimelineToggle) && ( + <> + {showEntryHeader && } + {(showAiTimelineToggle || showTimelineSummaryButton) && ( +
+ {renderAiTimelineButton()} + {renderTimelineSummaryButton()} +
+ )} + + + )} + + {!isWideMode && renderAiTimelineButton()} {view === FeedViewType.Pictures && } 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 70c23e1eb..b12f6e2a8 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx @@ -137,7 +137,7 @@ const Content: FC<{ const elementTop = element.offsetTop const scrollerTop = scroller.scrollTop - const delta = elementTop - scrollerTop + const delta = elementTop - scrollerTop - 20 scroller.scrollTo({ top: delta, 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 894dbad3a..f90916b7c 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx @@ -12,6 +12,7 @@ import { PanelStyleSection } from "./ai/PanelStyleSection" import { PersonalizePromptSection } from "./ai/PersonalizePromptSection" import { AIShortcutsSection } from "./ai/shortcuts/AIShortcutsSection" import { TaskSchedulingSection } from "./ai/tasks" +import { TimelinePromptSection } from "./ai/TimelinePromptSection" import { UsageAnalysisSection } from "./ai/usage" const SettingBuilder = createSettingBuilder(useAISettingValue) @@ -20,6 +21,7 @@ const defineSettingItem = createDefineSettingItem("ai", useAISettingValue, setAI export const AI_SETTING_SECTION_IDS = { shortcuts: "settings-ai-shortcuts", tasks: "settings-ai-tasks", + timelinePrompt: "settings-ai-timeline-prompt", } as const export const SettingAI = () => { @@ -50,6 +52,12 @@ export const SettingAI = () => { }, PersonalizePromptSection, + { + type: "title", + value: t("timeline_prompt.title"), + id: AI_SETTING_SECTION_IDS.timelinePrompt, + }, + TimelinePromptSection, { type: "title", diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai/TimelinePromptSection.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai/TimelinePromptSection.tsx new file mode 100644 index 000000000..27af07d3c --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai/TimelinePromptSection.tsx @@ -0,0 +1,143 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { Button } from "@follow/components/ui/button/index.js" +import { TextArea } from "@follow/components/ui/input/index.js" +import { AnimatePresence } from "motion/react" +import { useEffect, useRef, useState } from "react" +import { useTranslation } from "react-i18next" +import { toast } from "sonner" + +import { setAISetting, useAISettingValue } from "~/atoms/settings/ai" +import { m } from "~/components/common/Motion" + +import { SettingDescription } from "../../control" +import { SettingModalContentPortal } from "../../modal/layout" + +export const TimelinePromptSection = () => { + const { t } = useTranslation("ai") + const aiSettings = useAISettingValue() + const promptRef = useRef("") + const [isSaving, setIsSaving] = useState(false) + const [currentLength, setCurrentLength] = useState(0) + const [hasChanges, setHasChanges] = useState(false) + const [promptValue, setPromptValue] = useState(aiSettings.aiTimelinePrompt) + + const MAX_CHARACTERS = 500 + const isOverLimit = currentLength > MAX_CHARACTERS + + useEffect(() => { + promptRef.current = aiSettings.aiTimelinePrompt + setPromptValue(aiSettings.aiTimelinePrompt) + setCurrentLength(aiSettings.aiTimelinePrompt.length) + setHasChanges(false) + }, [aiSettings.aiTimelinePrompt]) + + const handleEditorChange = (value: string) => { + promptRef.current = value + setPromptValue(value) + setCurrentLength(value.length) + setHasChanges(value !== aiSettings.aiTimelinePrompt) + } + + const handleSave = async () => { + if (isOverLimit) { + toast.error(`Prompt must be ${MAX_CHARACTERS} characters or less`) + return + } + + if (!promptRef.current) return + + setIsSaving(true) + try { + setAISetting("aiTimelinePrompt", promptRef.current) + toast.success(t("timeline_prompt.saved")) + setHasChanges(false) + } finally { + setIsSaving(false) + } + } + + return ( +
+
+
+