diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index b3c65a1..d196011 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -81,6 +81,11 @@ android { } buildTypes { + // idealchat2001: debug builds install next to the release app + // (different id, no clash with the release signature or its data). + debug { + applicationIdSuffix = ".dev" + } release { // idealchat2001: without key.properties (Mac build machine) sign with // the debug key; the release key is applied on the server (apksigner). diff --git a/integration_test/ai_directory_device_test.dart b/integration_test/ai_directory_device_test.dart new file mode 100644 index 0000000..960b71f --- /dev/null +++ b/integration_test/ai_directory_device_test.dart @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Runs test/ai_directory_test.dart and test/reply_mode_api_test.dart on a +// device/emulator (host `flutter test` needs full Xcode for webcrypto). +import 'package:integration_test/integration_test.dart'; + +import '../test/ai_directory_test.dart' as ai_directory; +import '../test/reply_mode_api_test.dart' as reply_mode_api; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + ai_directory.main(); + reply_mode_api.main(); +} diff --git a/integration_test/reply_mode_api_device_test.dart b/integration_test/reply_mode_api_device_test.dart new file mode 100644 index 0000000..f5efd3d --- /dev/null +++ b/integration_test/reply_mode_api_device_test.dart @@ -0,0 +1,14 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Runs test/reply_mode_api_test.dart on a device/emulator (host `flutter test` +// needs full Xcode for the webcrypto native asset on macOS). +import 'package:integration_test/integration_test.dart'; + +import '../test/reply_mode_api_test.dart' as reply_mode_api; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + reply_mode_api.main(); +} diff --git a/lib/config/routes.dart b/lib/config/routes.dart index c804ab9..93e9eca 100644 --- a/lib/config/routes.dart +++ b/lib/config/routes.dart @@ -17,11 +17,14 @@ import 'package:fluffychat/pages/chat_members/chat_members.dart'; import 'package:fluffychat/pages/chat_permissions_settings/chat_permissions_settings.dart'; import 'package:fluffychat/pages/chat_search/chat_search_page.dart'; import 'package:fluffychat/pages/device_settings/device_settings.dart'; +import 'package:fluffychat/pages/idealchat/ai_status_page.dart'; +import 'package:fluffychat/pages/idealchat/task_board_page.dart'; import 'package:fluffychat/pages/intro/intro_page_presenter.dart'; import 'package:fluffychat/pages/invitation_selection/invitation_selection.dart'; import 'package:fluffychat/pages/login/login.dart'; import 'package:fluffychat/pages/new_group/new_group.dart'; import 'package:fluffychat/pages/new_private_chat/new_private_chat.dart'; +import 'package:fluffychat/pages/reply_mode/reply_mode_page.dart'; import 'package:fluffychat/pages/settings/settings.dart'; import 'package:fluffychat/pages/settings_3pid/settings_3pid.dart'; import 'package:fluffychat/pages/settings_chat/settings_chat.dart'; @@ -33,6 +36,7 @@ import 'package:fluffychat/pages/settings_password/settings_password.dart'; import 'package:fluffychat/pages/settings_security/settings_security.dart'; import 'package:fluffychat/pages/settings_style/settings_style.dart'; import 'package:fluffychat/pages/sign_in/sign_in_page.dart'; +import 'package:fluffychat/utils/idealchat/reply_mode_api.dart'; import 'package:fluffychat/widgets/config_viewer.dart'; import 'package:fluffychat/widgets/layouts/empty_page.dart'; import 'package:fluffychat/widgets/layouts/two_column_layout.dart'; @@ -430,6 +434,25 @@ abstract class AppRoutes { ), redirect: loggedOutRedirect, ), + // IdealChat: room ⋮ → task list / AI status (web parity) + GoRoute( + path: 'tasks', + pageBuilder: (context, state) => defaultPageBuilder( + context, + state, + TaskBoardPage(roomId: state.pathParameters['roomid']!), + ), + redirect: loggedOutRedirect, + ), + GoRoute( + path: 'ai_status', + pageBuilder: (context, state) => defaultPageBuilder( + context, + state, + AiStatusPage(roomId: state.pathParameters['roomid']!), + ), + redirect: loggedOutRedirect, + ), GoRoute( path: 'details', pageBuilder: (context, state) => defaultPageBuilder( @@ -460,6 +483,20 @@ abstract class AppRoutes { ), redirect: loggedOutRedirect, ), + GoRoute( + path: 'reply_mode', + pageBuilder: (context, state) => defaultPageBuilder( + context, + state, + ReplyModePage( + roomId: state.pathParameters['roomid']!, + api: ReplyModeApi.forClient( + Matrix.of(context).client, + ), + ), + ), + redirect: loggedOutRedirect, + ), GoRoute( path: 'permissions', pageBuilder: (context, state) => defaultPageBuilder( diff --git a/lib/config/setting_keys.dart b/lib/config/setting_keys.dart index 884f42c..7415cd7 100644 --- a/lib/config/setting_keys.dart +++ b/lib/config/setting_keys.dart @@ -66,6 +66,8 @@ enum AppSettings { '登录 ideal2001.com。只填用户名和密码,不用填服务器。', ), website('chat.fluffy.website_url', 'https://ideal2001.com'), + // IdealChat: '' = follow system, 'zh' or 'en' + icLocale('chat.ideal.locale', ''), logoUrl( 'chat.fluffy.logo_url', 'https://ideal2001.com/assets/icon-192.png', diff --git a/lib/l10n/intl_en.arb b/lib/l10n/intl_en.arb index e631ff2..50286eb 100644 --- a/lib/l10n/intl_en.arb +++ b/lib/l10n/intl_en.arb @@ -2832,5 +2832,105 @@ } }, "mentionEveryone": "Everyone (@room)", - "@mentionEveryone": {} + "@mentionEveryone": {}, + "aiReplyMode": "AI reply mode", + "@aiReplyMode": {}, + "aiReplyModeQuiet": "Only when @mentioned", + "@aiReplyModeQuiet": {}, + "aiReplyModeLead": "Lead AI replies", + "@aiReplyModeLead": {}, + "aiReplyModeAll": "Every AI decides", + "@aiReplyModeAll": {}, + "aiReplyModeAuto": "Auto (AI picks)", + "@aiReplyModeAuto": {}, + "aiReplyModeQuietHint": "AIs skip messages that don't @mention them. To ask an AI something, @mention it.", + "@aiReplyModeQuietHint": {}, + "aiReplyModeLeadHint": "One lead AI picks up messages that don't @mention anyone. Other AIs reply only when @mentioned.", + "@aiReplyModeLeadHint": {}, + "aiReplyModeAllHint": "Every AI reads each message and decides for itself whether to reply.", + "@aiReplyModeAllHint": {}, + "aiReplyModeAutoHint": "The AI picks one of the three above based on how many people and AIs are in the group, and says why in the group whenever it switches.", + "@aiReplyModeAutoHint": {}, + "aiReplyModeNow": "This group now: {mode}", + "@aiReplyModeNow": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModeAutoPicked": "Currently picked: {mode}", + "@aiReplyModeAutoPicked": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModeReason": "Why: {reason}", + "@aiReplyModeReason": {"type": "String", "placeholders": {"reason": {"type": "String"}}}, + "aiReplyModeLeadAi": "Lead AI", + "@aiReplyModeLeadAi": {}, + "aiReplyModeNoLead": "Not specified", + "@aiReplyModeNoLead": {}, + "aiReplyModeIsDefault": "Not set for this group yet, using the default.", + "@aiReplyModeIsDefault": {}, + "aiReplyModeReadOnly": "Only group admins and the owner can change this. You can see the current setting.", + "@aiReplyModeReadOnly": {}, + "aiReplyModeDm": "No need in private chats: the AI always replies there.", + "@aiReplyModeDm": {}, + "aiReplyModeNotJoined": "The task steward isn't in this group yet, so this can't be set for now.", + "@aiReplyModeNotJoined": {}, + "aiReplyModeUnsupported": "Not available in this group yet", + "@aiReplyModeUnsupported": {}, + "aiReplyModeSwitchBack": "Switch back to “{mode}”", + "@aiReplyModeSwitchBack": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModePending": "Submitted. It takes effect in a few seconds.", + "@aiReplyModePending": {}, + "aiReplyModeSaved": "Saved. The AIs follow it within about a minute.", + "@aiReplyModeSaved": {}, + "aiReplyModeRecent": "Recent changes", + "@aiReplyModeRecent": {}, + "aiReplyModeByAi": "AI picked", + "@aiReplyModeByAi": {}, + "aiReplyModeLoadFailed": "Couldn't load. Tap to try again.", + "@aiReplyModeLoadFailed": {}, + "icTaskList": "Task list", + "@icTaskList": {}, + "icAiStatus": "AI status", + "@icAiStatus": {}, + "icOnline": "Online", + "@icOnline": {}, + "icOffline": "Offline", + "@icOffline": {}, + "icQuota": "Quota used up / paused", + "@icQuota": {}, + "icAway": "Away", + "@icAway": {}, + "icUnknown": "Unknown", + "@icUnknown": {}, + "icExamPassed": "Passed", + "@icExamPassed": {}, + "icExamPending": "Exam pending", + "@icExamPending": {}, + "icExamLocked": "Locked", + "@icExamLocked": {}, + "icInvitedBy": "Invited by", + "@icInvitedBy": {}, + "icNameHere": "Name here", + "@icNameHere": {}, + "icExam": "Exam", + "@icExam": {}, + "icGroupRules": "Group rules", + "@icGroupRules": {}, + "icRulesNotConfirmed": "Not confirmed", + "@icRulesNotConfirmed": {}, + "icRulesConfirmed": "Confirmed {version}", + "@icRulesConfirmed": {"type": "String", "placeholders": {"version": {"type": "String"}}}, + "icRulesOld": "Old version {version} (rules not updated)", + "@icRulesOld": {"type": "String", "placeholders": {"version": {"type": "String"}}}, + "icPrivacyWarnings": "Privacy warnings", + "@icPrivacyWarnings": {}, + "icNoDataYet": "No data yet", + "@icNoDataYet": {}, + "icPowerLevel": "Power level", + "@icPowerLevel": {}, + "icAiStatusSummary": "{count} AIs in this group · rules {rules} · updated {time}", + "@icAiStatusSummary": {"type": "String", "placeholders": {"count": {"type": "int"}, "rules": {"type": "String"}, "time": {"type": "String"}}}, + "icNoAiHere": "No AI members in this group", + "@icNoAiHere": {}, + "icLoadFailed": "Couldn't load:", + "@icLoadFailed": {}, + "aiReplyModeReset": "Reset to default ({mode})", + "@aiReplyModeReset": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModeResetHint": "Remove this group's own setting and follow the site default from now on.", + "@aiReplyModeResetHint": {} } diff --git a/lib/l10n/intl_zh.arb b/lib/l10n/intl_zh.arb index e967c97..f423c2e 100644 --- a/lib/l10n/intl_zh.arb +++ b/lib/l10n/intl_zh.arb @@ -2842,5 +2842,63 @@ } }, "download": "下载", - "mentionEveryone": "所有人(@room)" + "mentionEveryone": "所有人(@room)", + "aiReplyMode": "AI 回答方式", + "aiReplyModeQuiet": "只@才回", + "aiReplyModeLead": "主管 AI 接话", + "aiReplyModeAll": "全部 AI 判断", + "aiReplyModeAuto": "自动(AI 帮选)", + "aiReplyModeQuietHint": "没 @ 的消息 AI 都不接;想问哪个 AI 就 @ 它。", + "aiReplyModeLeadHint": "没 @ 人的消息由主管 AI 接;其他 AI 被 @ 才回。", + "aiReplyModeAllHint": "每条消息每个 AI 都会看,自己判断要不要接话。", + "aiReplyModeAutoHint": "AI 按群里人数和 AI 数量,从上面三种里帮你选;每次换都会在群里说理由。", + "aiReplyModeNow": "本群现在:{mode}", + "@aiReplyModeNow": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModeAutoPicked": "现在选的是:{mode}", + "@aiReplyModeAutoPicked": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModeReason": "理由:{reason}", + "@aiReplyModeReason": {"type": "String", "placeholders": {"reason": {"type": "String"}}}, + "aiReplyModeLeadAi": "主管 AI", + "aiReplyModeNoLead": "不指定", + "aiReplyModeIsDefault": "本群还没单独设置,用的是默认方式。", + "aiReplyModeReadOnly": "只有本群管理员和主人可以改,你可以看到现在的设置。", + "aiReplyModeDm": "私聊不用设:私聊里 AI 总会回。", + "aiReplyModeNotJoined": "任务管家还不在这个群,暂时不能设置。", + "aiReplyModeUnsupported": "本群暂不支持", + "aiReplyModeSwitchBack": "改回「{mode}」", + "@aiReplyModeSwitchBack": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModePending": "已提交,几秒后生效。", + "aiReplyModeSaved": "已保存,AI 大约 1 分钟内按新方式回答。", + "aiReplyModeRecent": "最近的改动", + "aiReplyModeByAi": "AI 帮选", + "aiReplyModeLoadFailed": "没加载出来,点一下重试。", + "icTaskList": "任务清单", + "icAiStatus": "AI 状态", + "icOnline": "在线", + "icOffline": "离线", + "icQuota": "额度用尽/暂停", + "icAway": "离开", + "icUnknown": "未知", + "icExamPassed": "已通过", + "icExamPending": "待考", + "icExamLocked": "锁定", + "icInvitedBy": "邀请人", + "icNameHere": "本群昵称", + "icExam": "考试", + "icGroupRules": "群规确认", + "icRulesNotConfirmed": "未确认", + "icRulesConfirmed": "已确认 {version}", + "@icRulesConfirmed": {"type": "String", "placeholders": {"version": {"type": "String"}}}, + "icRulesOld": "旧版 {version}(未更新群规)", + "@icRulesOld": {"type": "String", "placeholders": {"version": {"type": "String"}}}, + "icPrivacyWarnings": "隐私警告", + "icNoDataYet": "暂无数据", + "icPowerLevel": "权限等级", + "icAiStatusSummary": "本群 {count} 个 AI · 当前群规 {rules} · 更新于 {time}", + "@icAiStatusSummary": {"type": "String", "placeholders": {"count": {"type": "int"}, "rules": {"type": "String"}, "time": {"type": "String"}}}, + "icNoAiHere": "本群没有 AI 成员", + "icLoadFailed": "没加载出来:", + "aiReplyModeReset": "恢复默认({mode})", + "@aiReplyModeReset": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModeResetHint": "去掉本群的单独设置,以后跟着全站默认走。" } diff --git a/lib/l10n/intl_zh_Hant.arb b/lib/l10n/intl_zh_Hant.arb index 1465d5a..52f1a96 100644 --- a/lib/l10n/intl_zh_Hant.arb +++ b/lib/l10n/intl_zh_Hant.arb @@ -2424,5 +2424,63 @@ } } }, - "mentionEveryone": "所有人(@room)" + "mentionEveryone": "所有人(@room)", + "aiReplyMode": "AI 回答方式", + "aiReplyModeQuiet": "只@才回", + "aiReplyModeLead": "主管 AI 接話", + "aiReplyModeAll": "全部 AI 判斷", + "aiReplyModeAuto": "自動(AI 幫選)", + "aiReplyModeQuietHint": "沒 @ 的訊息 AI 都不接;想問哪個 AI 就 @ 它。", + "aiReplyModeLeadHint": "沒 @ 人的訊息由主管 AI 接;其他 AI 被 @ 才回。", + "aiReplyModeAllHint": "每則訊息每個 AI 都會看,自己判斷要不要接話。", + "aiReplyModeAutoHint": "AI 依群裡人數和 AI 數量,從上面三種裡幫你選;每次換都會在群裡說理由。", + "aiReplyModeNow": "本群現在:{mode}", + "@aiReplyModeNow": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModeAutoPicked": "現在選的是:{mode}", + "@aiReplyModeAutoPicked": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModeReason": "理由:{reason}", + "@aiReplyModeReason": {"type": "String", "placeholders": {"reason": {"type": "String"}}}, + "aiReplyModeLeadAi": "主管 AI", + "aiReplyModeNoLead": "不指定", + "aiReplyModeIsDefault": "本群還沒單獨設定,用的是預設方式。", + "aiReplyModeReadOnly": "只有本群管理員和主人可以改,你可以看到現在的設定。", + "aiReplyModeDm": "私聊不用設:私聊裡 AI 總會回。", + "aiReplyModeNotJoined": "任務管家還不在這個群,暫時不能設定。", + "aiReplyModeUnsupported": "本群暫不支援", + "aiReplyModeSwitchBack": "改回「{mode}」", + "@aiReplyModeSwitchBack": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModePending": "已送出,幾秒後生效。", + "aiReplyModeSaved": "已儲存,AI 大約 1 分鐘內按新方式回答。", + "aiReplyModeRecent": "最近的變動", + "aiReplyModeByAi": "AI 幫選", + "aiReplyModeLoadFailed": "沒載入成功,點一下重試。", + "icTaskList": "任務清單", + "icAiStatus": "AI 狀態", + "icOnline": "在線", + "icOffline": "離線", + "icQuota": "額度用盡/暫停", + "icAway": "離開", + "icUnknown": "未知", + "icExamPassed": "已通過", + "icExamPending": "待考", + "icExamLocked": "鎖定", + "icInvitedBy": "邀請人", + "icNameHere": "本群暱稱", + "icExam": "考試", + "icGroupRules": "群規確認", + "icRulesNotConfirmed": "未確認", + "icRulesConfirmed": "已確認 {version}", + "@icRulesConfirmed": {"type": "String", "placeholders": {"version": {"type": "String"}}}, + "icRulesOld": "舊版 {version}(未更新群規)", + "@icRulesOld": {"type": "String", "placeholders": {"version": {"type": "String"}}}, + "icPrivacyWarnings": "隱私警告", + "icNoDataYet": "暫無資料", + "icPowerLevel": "權限等級", + "icAiStatusSummary": "本群 {count} 個 AI · 目前群規 {rules} · 更新於 {time}", + "@icAiStatusSummary": {"type": "String", "placeholders": {"count": {"type": "int"}, "rules": {"type": "String"}, "time": {"type": "String"}}}, + "icNoAiHere": "本群沒有 AI 成員", + "icLoadFailed": "沒載入成功:", + "aiReplyModeReset": "恢復預設({mode})", + "@aiReplyModeReset": {"type": "String", "placeholders": {"mode": {"type": "String"}}}, + "aiReplyModeResetHint": "去掉本群的單獨設定,以後跟著全站預設走。" } diff --git a/lib/pages/chat/chat_app_bar_title.dart b/lib/pages/chat/chat_app_bar_title.dart index e937054..ed89b3d 100644 --- a/lib/pages/chat/chat_app_bar_title.dart +++ b/lib/pages/chat/chat_app_bar_title.dart @@ -7,6 +7,7 @@ import 'package:fluffychat/config/themes.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/chat/chat.dart'; import 'package:fluffychat/utils/date_time_extension.dart'; +import 'package:fluffychat/utils/idealchat/member_counts.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart'; import 'package:fluffychat/utils/sync_status_localization.dart'; import 'package:fluffychat/utils/verified_room_extension.dart'; @@ -124,17 +125,19 @@ class ChatAppBarTitle extends StatelessWidget { ) : Row( children: [ - Text( - L10n.of(context).countParticipants( - (room.summary.mJoinedMemberCount ?? - 1) + - (room - .summary - .mInvitedMemberCount ?? - 0), - ), - maxLines: 1, - style: style, + // IdealChat: server count, none until known + IcMemberCount( + room: room, + builder: (context, count) => + count == null + ? const SizedBox.shrink() + : Text( + L10n.of( + context, + ).countParticipants(count), + maxLines: 1, + style: style, + ), ), if (room.topic.isNotEmpty) ...[ Text(' ◦ ', style: style), diff --git a/lib/pages/chat/chat_view.dart b/lib/pages/chat/chat_view.dart index 5247f70..750e712 100644 --- a/lib/pages/chat/chat_view.dart +++ b/lib/pages/chat/chat_view.dart @@ -14,7 +14,9 @@ import 'package:fluffychat/pages/chat/chat_app_bar_title.dart'; import 'package:fluffychat/pages/chat/chat_event_list.dart'; import 'package:fluffychat/pages/chat/pinned_events.dart'; import 'package:fluffychat/pages/chat/reply_display.dart'; +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; import 'package:fluffychat/utils/account_config.dart'; +import 'package:fluffychat/utils/idealchat/add_to_emotes.dart'; import 'package:fluffychat/utils/localized_exception_extension.dart'; import 'package:fluffychat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart'; import 'package:fluffychat/widgets/chat_settings_popup_menu.dart'; @@ -196,6 +198,30 @@ class ChatView extends StatelessWidget { ], ), ), + // IdealChat P8: add image to own sticker pack + if (canAddToEmotes(controller.selectedEvents.single)) + PopupMenuItem( + onTap: () { + final event = controller.selectedEvents.single; + controller.clearSelectedEvents(); + addEventToEmotes(context, event); + }, + value: null, + child: Row( + mainAxisSize: .min, + children: [ + const Icon(Icons.add_reaction_outlined), + const SizedBox(width: 12), + Text( + icT( + context, + '添加到表情包', + 'Add to my stickers', + ), + ), + ], + ), + ), PopupMenuItem( value: _EventContextAction.info, child: Row( diff --git a/lib/pages/chat/events/html_message.dart b/lib/pages/chat/events/html_message.dart index df73036..086892e 100644 --- a/lib/pages/chat/events/html_message.dart +++ b/lib/pages/chat/events/html_message.dart @@ -320,13 +320,23 @@ class HtmlMessage extends StatelessWidget { ), ); case 'blockquote': + // IdealChat P9 (web RED_ALERT_BOX): a quote with data-mx-color is + // drawn as a box in that color (e.g. red warnings from the system). + final alertColor = node.attributes['data-mx-color']?.hexToColor; return WidgetSpan( child: Container( - padding: const EdgeInsetsDirectional.only(start: 8.0), + padding: alertColor != null + ? const EdgeInsets.all(8.0) + : const EdgeInsetsDirectional.only(start: 8.0), decoration: BoxDecoration( - border: BorderDirectional( - start: BorderSide(color: textColor, width: 5), - ), + border: alertColor != null + ? Border.all(color: alertColor, width: 2) + : BorderDirectional( + start: BorderSide(color: textColor, width: 5), + ), + borderRadius: alertColor != null + ? BorderRadius.circular(6) + : null, ), child: Text.rich( TextSpan( @@ -337,9 +347,9 @@ class HtmlMessage extends StatelessWidget { ), ), style: TextStyle( - fontStyle: FontStyle.italic, + fontStyle: alertColor != null ? null : FontStyle.italic, fontSize: fontSize, - color: textColor, + color: alertColor ?? textColor, ), ), ), diff --git a/lib/pages/chat_details/chat_details_view.dart b/lib/pages/chat_details/chat_details_view.dart index c99c27b..b893ec4 100644 --- a/lib/pages/chat_details/chat_details_view.dart +++ b/lib/pages/chat_details/chat_details_view.dart @@ -7,6 +7,11 @@ import 'package:fluffychat/config/app_config.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/chat_details/chat_details.dart'; import 'package:fluffychat/pages/chat_details/participant_list_item.dart'; +import 'package:fluffychat/pages/idealchat/member_groups.dart'; +import 'package:fluffychat/pages/reply_mode/reply_mode_tile.dart'; +import 'package:fluffychat/utils/idealchat/ai_directory.dart'; +import 'package:fluffychat/utils/idealchat/member_counts.dart'; +import 'package:fluffychat/utils/idealchat/reply_mode_api.dart'; import 'package:fluffychat/utils/matrix_sdk_extensions/matrix_locals.dart'; import 'package:fluffychat/utils/verified_room_extension.dart'; import 'package:fluffychat/widgets/avatar.dart'; @@ -45,333 +50,383 @@ class ChatDetailsView extends StatelessWidget { final directChatMatrixID = room.directChatMatrixID; final roomAvatar = room.avatar; - return StreamBuilder( - stream: room.client.onRoomState.stream.where( - (update) => update.roomId == room.id, - ), - builder: (context, snapshot) { - var members = room.getParticipants().toList() - ..sort((b, a) => a.powerLevel.level.compareTo(b.powerLevel.level)); - members = members.take(10).toList(); - final actualMembersCount = - (room.summary.mInvitedMemberCount ?? 0) + - (room.summary.mJoinedMemberCount ?? 0); - final canRequestMoreMembers = members.length < actualMembersCount; - final iconColor = theme.textTheme.bodyLarge!.color; - final displayname = room.getLocalizedDisplayname( - MatrixLocals(L10n.of(context)), - ); - return Scaffold( - appBar: AppBar( - leading: - controller.widget.embeddedCloseButton ?? - const Center(child: BackButton()), - elevation: theme.appBarTheme.elevation, - actions: [ - if (room.canonicalAlias.isNotEmpty) - IconButton( - tooltip: L10n.of(context).share, - icon: const Icon(Icons.qr_code_rounded), - onPressed: () => - showQrCodeViewer(context, room.canonicalAlias), + return ValueListenableBuilder( + valueListenable: IcAiDirectory.changed, + builder: (context, _, _) => StreamBuilder( + stream: room.client.onRoomState.stream.where( + (update) => update.roomId == room.id, + ), + builder: (context, snapshot) { + var members = room.getParticipants().toList() + ..sort((b, a) => a.powerLevel.level.compareTo(b.powerLevel.level)); + // IdealChat P7: in 「我和朋友们」/「我和AI朋友」 all members are shown, + // grouped like the web; elsewhere the first 10 as upstream. + final icGrouped = + !room.isDirectChat && + IcAiDirectory.instance.roomKind( + room.id, + room.getLocalizedDisplayname(), + ) != + IcRoomKind.normal; + if (!icGrouped) members = members.take(10).toList(); + final memberWidgets = icGrouped + ? icGroupedMemberWidgets( + context, + room, + members, + ParticipantListItem.new, ) - else if (directChatMatrixID != null) - IconButton( - tooltip: L10n.of(context).share, - icon: const Icon(Icons.qr_code_rounded), - onPressed: () => - showQrCodeViewer(context, directChatMatrixID), - ), - if (controller.widget.embeddedCloseButton == null) - ChatSettingsPopupMenu(room, false), - ], - title: Text(L10n.of(context).chatDetails), - backgroundColor: theme.appBarTheme.backgroundColor, - ), - body: MaxWidthBody( - child: ListView.builder( - physics: const NeverScrollableScrollPhysics(), - shrinkWrap: true, - itemCount: members.length + 1 + (canRequestMoreMembers ? 1 : 0), - itemBuilder: (BuildContext context, int i) => i == 0 - ? Column( - crossAxisAlignment: .stretch, - children: [ - Center( - child: Stack( - children: [ - Hero( - tag: - controller.widget.embeddedCloseButton != - null - ? 'embedded_content_banner' - : 'content_banner', - child: Avatar( - mxContent: room.avatar, - name: displayname, - size: Avatar.defaultSize * 2.5, - onTap: roomAvatar != null - ? () => showDialog( - context: context, - builder: (_) => - MxcImageViewer(roomAvatar), - ) - : null, + : [for (final m in members) ParticipantListItem(m)]; + if (icGrouped) _icLoadAllMembers(room); + final actualMembersCount = + (room.summary.mInvitedMemberCount ?? 0) + + (room.summary.mJoinedMemberCount ?? 0); + final canRequestMoreMembers = members.length < actualMembersCount; + final iconColor = theme.textTheme.bodyLarge!.color; + final displayname = room.getLocalizedDisplayname( + MatrixLocals(L10n.of(context)), + ); + return Scaffold( + appBar: AppBar( + leading: + controller.widget.embeddedCloseButton ?? + const Center(child: BackButton()), + elevation: theme.appBarTheme.elevation, + actions: [ + if (room.canonicalAlias.isNotEmpty) + IconButton( + tooltip: L10n.of(context).share, + icon: const Icon(Icons.qr_code_rounded), + onPressed: () => + showQrCodeViewer(context, room.canonicalAlias), + ) + else if (directChatMatrixID != null) + IconButton( + tooltip: L10n.of(context).share, + icon: const Icon(Icons.qr_code_rounded), + onPressed: () => + showQrCodeViewer(context, directChatMatrixID), + ), + if (controller.widget.embeddedCloseButton == null) + ChatSettingsPopupMenu(room, false), + ], + title: Text(L10n.of(context).chatDetails), + backgroundColor: theme.appBarTheme.backgroundColor, + ), + body: MaxWidthBody( + child: ListView.builder( + physics: const NeverScrollableScrollPhysics(), + shrinkWrap: true, + itemCount: + memberWidgets.length + 1 + (canRequestMoreMembers ? 1 : 0), + itemBuilder: (BuildContext context, int i) => i == 0 + ? Column( + crossAxisAlignment: .stretch, + children: [ + Center( + child: Stack( + children: [ + Hero( + tag: + controller.widget.embeddedCloseButton != + null + ? 'embedded_content_banner' + : 'content_banner', + child: Avatar( + mxContent: room.avatar, + name: displayname, + size: Avatar.defaultSize * 2.5, + onTap: roomAvatar != null + ? () => showDialog( + context: context, + builder: (_) => + MxcImageViewer(roomAvatar), + ) + : null, + ), ), - ), - if (!room.isDirectChat && - room.canChangeStateEvent( - EventTypes.RoomAvatar, - )) - Positioned( - bottom: 0, - right: 0, - child: FloatingActionButton.small( - onPressed: controller.setAvatarAction, - heroTag: null, - child: const Icon( - Icons.camera_alt_outlined, + if (!room.isDirectChat && + room.canChangeStateEvent( + EventTypes.RoomAvatar, + )) + Positioned( + bottom: 0, + right: 0, + child: FloatingActionButton.small( + onPressed: controller.setAvatarAction, + heroTag: null, + child: const Icon( + Icons.camera_alt_outlined, + ), ), ), - ), - ], + ], + ), ), - ), - Padding( - padding: const EdgeInsets.all(8.0), - child: Center( - child: TextButton.icon( - onPressed: - room.isDirectChat || - !room.canChangeStateEvent( - EventTypes.RoomName, - ) - ? null - : controller.setDisplaynameAction, - icon: - room.isDirectChat || - !room.canChangeStateEvent( - EventTypes.RoomName, - ) - ? null - : Icon(Icons.edit_outlined, size: 16), + Padding( + padding: const EdgeInsets.all(8.0), + child: Center( + child: TextButton.icon( + onPressed: + room.isDirectChat || + !room.canChangeStateEvent( + EventTypes.RoomName, + ) + ? null + : controller.setDisplaynameAction, + icon: + room.isDirectChat || + !room.canChangeStateEvent( + EventTypes.RoomName, + ) + ? null + : Icon(Icons.edit_outlined, size: 16), - style: TextButton.styleFrom( - foregroundColor: theme.colorScheme.onSurface, - iconColor: theme.colorScheme.onSurface, - disabledForegroundColor: - theme.colorScheme.onSurface, - ), - label: Row( - mainAxisSize: .min, - spacing: 4, - children: [ - if (room.allUsersVerified) - Icon( - Icons.verified, - color: Theme.of( - context, - ).colorScheme.primary, - size: 18, - ), - Text( - displayname, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle( - fontSize: 18, - fontWeight: FontWeight.normal, + style: TextButton.styleFrom( + foregroundColor: theme.colorScheme.onSurface, + iconColor: theme.colorScheme.onSurface, + disabledForegroundColor: + theme.colorScheme.onSurface, + ), + label: Row( + mainAxisSize: .min, + spacing: 4, + children: [ + if (room.allUsersVerified) + Icon( + Icons.verified, + color: Theme.of( + context, + ).colorScheme.primary, + size: 18, + ), + Text( + displayname, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.normal, + ), ), - ), - ], + ], + ), ), ), ), - ), - StreamBuilder( - stream: room.client.onSync.stream.where( - (s) => - s.accountData?.any( - (data) => data.type == 'm.push_rules', - ) ?? - false, - ), - builder: (context, _) => Wrap( - alignment: .center, - spacing: 16, - runSpacing: 16, - children: [ - _MainChatDetailsButton( - onPressed: () => - context.go('/rooms/${room.id}/search'), - label: L10n.of(context).search, - icon: Icons.search, - ), - _MainChatDetailsButton( - onPressed: () => context.push( - '/rooms/${room.id}/details/emotes', + StreamBuilder( + stream: room.client.onSync.stream.where( + (s) => + s.accountData?.any( + (data) => data.type == 'm.push_rules', + ) ?? + false, + ), + builder: (context, _) => Wrap( + alignment: .center, + spacing: 16, + runSpacing: 16, + children: [ + _MainChatDetailsButton( + onPressed: () => + context.go('/rooms/${room.id}/search'), + label: L10n.of(context).search, + icon: Icons.search, ), - label: L10n.of(context).stickers, - icon: Icons.emoji_emotions_outlined, - ), - if (room.pushRuleState == PushRuleState.notify) _MainChatDetailsButton( - onPressed: () => showFutureLoadingDialog( - context: context, - future: () => room.setPushRuleState( - PushRuleState.mentionsOnly, - ), + onPressed: () => context.push( + '/rooms/${room.id}/details/emotes', ), - label: L10n.of(context).mute, - icon: Icons.notifications_on_outlined, - ) - else - _MainChatDetailsButton( - onPressed: () => showFutureLoadingDialog( - context: context, - future: () => room.setPushRuleState( - PushRuleState.notify, + label: L10n.of(context).stickers, + icon: Icons.emoji_emotions_outlined, + ), + if (room.pushRuleState == PushRuleState.notify) + _MainChatDetailsButton( + onPressed: () => showFutureLoadingDialog( + context: context, + future: () => room.setPushRuleState( + PushRuleState.mentionsOnly, + ), + ), + label: L10n.of(context).mute, + icon: Icons.notifications_on_outlined, + ) + else + _MainChatDetailsButton( + onPressed: () => showFutureLoadingDialog( + context: context, + future: () => room.setPushRuleState( + PushRuleState.notify, + ), ), + label: L10n.of(context).unmuteChat, + icon: Icons.notifications_off_outlined, ), - label: L10n.of(context).unmuteChat, - icon: Icons.notifications_off_outlined, - ), - ], - ), - ), - const SizedBox(height: 16), - if (room.canChangeStateEvent(EventTypes.RoomTopic) || - room.topic.isNotEmpty) ...[ - ListTile( - title: Text( - L10n.of(context).chatDescription, - style: TextStyle( - color: theme.colorScheme.secondary, - fontWeight: FontWeight.bold, - ), + ], ), - trailing: - room.canChangeStateEvent(EventTypes.RoomTopic) - ? IconButton( - onPressed: controller.setTopicAction, - tooltip: L10n.of( - context, - ).setChatDescription, - icon: const Icon(Icons.edit_outlined), - ) - : null, ), - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16.0, + const SizedBox(height: 16), + if (room.canChangeStateEvent(EventTypes.RoomTopic) || + room.topic.isNotEmpty) ...[ + ListTile( + title: Text( + L10n.of(context).chatDescription, + style: TextStyle( + color: theme.colorScheme.secondary, + fontWeight: FontWeight.bold, + ), + ), + trailing: + room.canChangeStateEvent(EventTypes.RoomTopic) + ? IconButton( + onPressed: controller.setTopicAction, + tooltip: L10n.of( + context, + ).setChatDescription, + icon: const Icon(Icons.edit_outlined), + ) + : null, ), - child: SelectableLinkify( - text: room.topic.isEmpty - ? L10n.of(context).noChatDescriptionYet - : room.topic, - textScaleFactor: MediaQuery.textScalerOf( - context, - ).scale(1), - options: const LinkifyOptions(humanize: false), - linkStyle: const TextStyle( - color: Colors.blueAccent, - decorationColor: Colors.blueAccent, + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16.0, ), - style: TextStyle( - fontSize: 14, - fontStyle: room.topic.isEmpty - ? FontStyle.italic - : FontStyle.normal, - color: theme.textTheme.bodyMedium!.color, - decorationColor: - theme.textTheme.bodyMedium!.color, + child: SelectableLinkify( + text: room.topic.isEmpty + ? L10n.of(context).noChatDescriptionYet + : room.topic, + textScaleFactor: MediaQuery.textScalerOf( + context, + ).scale(1), + options: const LinkifyOptions(humanize: false), + linkStyle: const TextStyle( + color: Colors.blueAccent, + decorationColor: Colors.blueAccent, + ), + style: TextStyle( + fontSize: 14, + fontStyle: room.topic.isEmpty + ? FontStyle.italic + : FontStyle.normal, + color: theme.textTheme.bodyMedium!.color, + decorationColor: + theme.textTheme.bodyMedium!.color, + ), + onOpen: (url) => + UrlLauncher(context, url.url).launchUrl(), ), - onOpen: (url) => - UrlLauncher(context, url.url).launchUrl(), ), - ), - const SizedBox(height: 16), - ], - if (!room.isDirectChat) ...[ - Divider(color: theme.dividerColor), - ListTile( - leading: CircleAvatar( - backgroundColor: - theme.colorScheme.surfaceContainer, - foregroundColor: iconColor, - child: const Icon( - Icons.admin_panel_settings_outlined, + const SizedBox(height: 16), + ], + if (!room.isDirectChat) ...[ + Divider(color: theme.dividerColor), + ListTile( + leading: CircleAvatar( + backgroundColor: + theme.colorScheme.surfaceContainer, + foregroundColor: iconColor, + child: const Icon( + Icons.admin_panel_settings_outlined, + ), + ), + title: Text(L10n.of(context).accessAndVisibility), + subtitle: Text( + L10n.of(context).accessAndVisibilityDescription, + ), + onTap: () => context.push( + '/rooms/${room.id}/details/access', + ), + trailing: const Icon( + Icons.chevron_right_outlined, ), ), - title: Text(L10n.of(context).accessAndVisibility), - subtitle: Text( - L10n.of(context).accessAndVisibilityDescription, + ListTile( + title: Text(L10n.of(context).chatPermissions), + subtitle: Text( + L10n.of(context).whoCanPerformWhichAction, + ), + leading: CircleAvatar( + backgroundColor: + theme.colorScheme.surfaceContainer, + foregroundColor: iconColor, + child: const Icon(Icons.tune_outlined), + ), + trailing: const Icon( + Icons.chevron_right_outlined, + ), + onTap: () => context.push( + '/rooms/${room.id}/details/permissions', + ), ), - onTap: () => context.push( - '/rooms/${room.id}/details/access', + ReplyModeTile( + key: ValueKey(room.id), + roomId: room.id, + api: ReplyModeApi.forClient(room.client), ), - trailing: const Icon(Icons.chevron_right_outlined), - ), + ], + Divider(color: theme.dividerColor), ListTile( - title: Text(L10n.of(context).chatPermissions), - subtitle: Text( - L10n.of(context).whoCanPerformWhichAction, - ), - leading: CircleAvatar( - backgroundColor: - theme.colorScheme.surfaceContainer, - foregroundColor: iconColor, - child: const Icon(Icons.tune_outlined), - ), - trailing: const Icon(Icons.chevron_right_outlined), - onTap: () => context.push( - '/rooms/${room.id}/details/permissions', + title: IcMemberCount( + room: room, + builder: (context, count) => Text( + count == null + ? L10n.of(context).participant + : L10n.of(context).countParticipants(count), + style: TextStyle( + color: theme.colorScheme.secondary, + fontWeight: FontWeight.bold, + ), + ), ), + trailing: !room.isDirectChat && room.canInvite + ? TextButton.icon( + icon: Icon(Icons.add), + label: Text(L10n.of(context).invite), + onPressed: () => + context.go('/rooms/${room.id}/invite'), + ) + : null, ), ], - Divider(color: theme.dividerColor), - ListTile( - title: Text( - L10n.of( - context, - ).countParticipants(actualMembersCount), - style: TextStyle( - color: theme.colorScheme.secondary, - fontWeight: FontWeight.bold, - ), + ) + : i < memberWidgets.length + 1 + ? memberWidgets[i - 1] + : ListTile( + title: Text( + L10n.of(context).loadCountMoreParticipants( + (actualMembersCount - members.length), ), - trailing: !room.isDirectChat && room.canInvite - ? TextButton.icon( - icon: Icon(Icons.add), - label: Text(L10n.of(context).invite), - onPressed: () => - context.go('/rooms/${room.id}/invite'), - ) - : null, ), - ], - ) - : i < members.length + 1 - ? ParticipantListItem(members[i - 1]) - : ListTile( - title: Text( - L10n.of(context).loadCountMoreParticipants( - (actualMembersCount - members.length), + onTap: () => context.push( + '/rooms/${controller.roomId!}/details/members', ), + trailing: const Icon(Icons.chevron_right_outlined), ), - onTap: () => context.push( - '/rooms/${controller.roomId!}/details/members', - ), - trailing: const Icon(Icons.chevron_right_outlined), - ), + ), ), - ), - ); - }, + ); + }, + ), ); } } +final _icMembersRequested = {}; + +/// Loads all joined/invited members once per room (lazy loading only has a +/// few), then rebuilds via [IcAiDirectory.changed]. +void _icLoadAllMembers(Room room) { + if (!_icMembersRequested.add(room.id)) return; + room + .requestParticipants([Membership.join, Membership.invite]) + .then((_) => IcAiDirectory.changed.value++) + .catchError((e) { + _icMembersRequested.remove(room.id); + Logs().v('[IC] could not load members of ${room.id}', e); + return 0; + }); +} + class _MainChatDetailsButton extends StatelessWidget { final VoidCallback onPressed; final String label; diff --git a/lib/pages/chat_details/participant_list_item.dart b/lib/pages/chat_details/participant_list_item.dart index 94c3ea6..da9aff0 100644 --- a/lib/pages/chat_details/participant_list_item.dart +++ b/lib/pages/chat_details/participant_list_item.dart @@ -3,8 +3,10 @@ // // SPDX-License-Identifier: AGPL-3.0-or-later -import 'package:fluffychat/config/app_config.dart'; import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/idealchat/member_groups.dart'; +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/idealchat/ai_directory.dart'; import 'package:fluffychat/widgets/member_actions_popup_menu_button.dart'; import 'package:material_ui/material_ui.dart'; import 'package:matrix/matrix.dart'; @@ -18,7 +20,26 @@ class ParticipantListItem extends StatelessWidget { @override Widget build(BuildContext context) { + final dir = IcAiDirectory.instance..ensureLoaded(user.room.client); + return ValueListenableBuilder( + valueListenable: IcAiDirectory.changed, + builder: (context, _, _) => _build(context, dir), + ); + } + + Widget _build(BuildContext context, IcAiDirectory dir) { final theme = Theme.of(context); + // IdealChat P6/P7: AI 🤖 suffix, gender mark, category chip, role badge + // (所有者/管理员/参与者) and model line, like the web member list. + final isAi = dir.isAi(user.id); + var displayname = user.calcDisplayname(); + if (isAi && !displayname.contains('🤖')) displayname += '🤖'; + displayname = displayname.replaceAll(RegExp(r'\s+🤖'), '🤖'); + final roomKind = dir.roomKind( + user.room.id, + user.room.getLocalizedDisplayname(), + ); + final model = isAi ? dir.modelOf(user.id) : null; final membershipBatch = switch (user.membership) { Membership.ban => L10n.of(context).banned, @@ -28,17 +49,6 @@ class ParticipantListItem extends StatelessWidget { Membership.leave => L10n.of(context).leftTheChat, }; - final permissionBatch = switch (user.powerLevel.role) { - PowerLevelRole.user => null, - PowerLevelRole.moderator => L10n.of(context).moderator, - PowerLevelRole.admin => L10n.of(context).admin, - PowerLevelRole.owner => L10n.of(context).owner, - }; - - final isAdminOrOwner = - user.powerLevel.role == PowerLevelRole.admin || - user.powerLevel.role == PowerLevelRole.owner; - return ListTile( onTap: () => showMemberActionsPopupMenu(context: context, user: user), title: Row( @@ -53,30 +63,8 @@ class ParticipantListItem extends StatelessWidget { size: 16, ), ), - Expanded( - child: Text( - user.calcDisplayname(), - overflow: TextOverflow.ellipsis, - ), - ), - if (permissionBatch != null) - Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration( - color: isAdminOrOwner - ? theme.colorScheme.tertiary - : theme.colorScheme.tertiaryContainer, - borderRadius: BorderRadius.circular(AppConfig.borderRadius), - ), - child: Text( - permissionBatch, - style: theme.textTheme.labelSmall?.copyWith( - color: isAdminOrOwner - ? theme.colorScheme.onTertiary - : theme.colorScheme.onTertiaryContainer, - ), - ), - ), + Expanded(child: Text(displayname, overflow: TextOverflow.ellipsis)), + if (!isAi) IcGenderMark(gender: dir.genderOf(user.id)), membershipBatch == null ? const SizedBox.shrink() : Container( @@ -100,7 +88,33 @@ class ParticipantListItem extends StatelessWidget { ), ], ), - subtitle: Text(user.id, maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (roomKind != IcRoomKind.ai) + Text( + model == null + ? user.id + : model.isEmpty + ? icT(context, '模型未知', 'Model unknown') + : model, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + Padding( + padding: const EdgeInsets.only(top: 4), + child: Wrap( + spacing: 6, + runSpacing: 4, + children: [ + IcRoleBadge(level: user.powerLevel.level), + IcCategoryChip(userId: user.id), + ], + ), + ), + ], + ), leading: Opacity( opacity: user.membership == Membership.join ? 1 : 0.5, child: Avatar( diff --git a/lib/pages/chat_list/chat_list_body.dart b/lib/pages/chat_list/chat_list_body.dart index 5dadb06..42f030b 100644 --- a/lib/pages/chat_list/chat_list_body.dart +++ b/lib/pages/chat_list/chat_list_body.dart @@ -11,6 +11,7 @@ import 'package:fluffychat/pages/chat_list/chat_list_item.dart'; import 'package:fluffychat/pages/chat_list/dummy_chat_list_item.dart'; import 'package:fluffychat/pages/chat_list/search_title.dart'; import 'package:fluffychat/pages/chat_list/space_view.dart'; +import 'package:fluffychat/pages/idealchat/recommend.dart'; import 'package:fluffychat/utils/stream_extension.dart'; import 'package:fluffychat/widgets/adaptive_dialogs/public_room_dialog.dart'; import 'package:fluffychat/widgets/avatar.dart'; @@ -128,6 +129,8 @@ class ChatListViewBody extends StatelessWidget { ), ), ], + // IdealChat: recommended family / AIs (web ic_rec.js) + if (!controller.isSearchMode) const IcRecommendButtons(), if (client.rooms.isNotEmpty && !controller.isSearchMode) Container( height: 36 + 8 + 8, diff --git a/lib/pages/chat_members/chat_members_view.dart b/lib/pages/chat_members/chat_members_view.dart index 87d18d6..3d1cfdd 100644 --- a/lib/pages/chat_members/chat_members_view.dart +++ b/lib/pages/chat_members/chat_members_view.dart @@ -4,6 +4,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/idealchat/member_groups.dart'; +import 'package:fluffychat/utils/idealchat/ai_directory.dart'; +import 'package:fluffychat/utils/idealchat/member_counts.dart'; import 'package:fluffychat/utils/localized_exception_extension.dart'; import 'package:go_router/go_router.dart'; import 'package:material_ui/material_ui.dart'; @@ -45,7 +48,11 @@ class ChatMembersView extends StatelessWidget { return Scaffold( appBar: AppBar( leading: const Center(child: BackButton()), - title: Text(L10n.of(context).countParticipants(roomCount)), + title: IcMemberCount( + room: room, + builder: (context, count) => + Text(L10n.of(context).countParticipants(count ?? roomCount)), + ), actions: [ if (room.canInvite) IconButton( @@ -83,107 +90,134 @@ class ChatMembersView extends StatelessWidget { child: CircularProgressIndicator.adaptive(), ), ) - : ListView.builder( - shrinkWrap: true, - itemCount: members.length + 1, - itemBuilder: (context, i) { - if (i == 0) { - final availableFilters = Membership.values - .where( - (membership) => - controller.members?.any( - (member) => member.membership == membership, - ) ?? - false, - ) - .toList(); - availableFilters.sort( - (a, b) => a == Membership.join ? -1 : 1, - ); - return Column( - mainAxisSize: .min, - children: [ - Padding( - padding: const EdgeInsets.all(16.0), - child: TextField( - controller: controller.filterController, - onChanged: controller.setFilter, - decoration: InputDecoration( - filled: true, - fillColor: theme.colorScheme.secondaryContainer, - border: OutlineInputBorder( - borderSide: BorderSide.none, - borderRadius: BorderRadius.circular(99), - ), - hintStyle: TextStyle( - color: theme.colorScheme.onPrimaryContainer, - fontWeight: FontWeight.normal, + : ValueListenableBuilder( + valueListenable: IcAiDirectory.changed, + builder: (context, _, _) => ListView( + shrinkWrap: true, + children: [ + Builder( + builder: (context) { + final availableFilters = Membership.values + .where( + (membership) => + controller.members?.any( + (member) => member.membership == membership, + ) ?? + false, + ) + .toList(); + availableFilters.sort( + (a, b) => a == Membership.join ? -1 : 1, + ); + return Column( + mainAxisSize: .min, + children: [ + Padding( + padding: const EdgeInsets.all(16.0), + child: TextField( + controller: controller.filterController, + onChanged: controller.setFilter, + decoration: InputDecoration( + filled: true, + fillColor: + theme.colorScheme.secondaryContainer, + border: OutlineInputBorder( + borderSide: BorderSide.none, + borderRadius: BorderRadius.circular(99), + ), + hintStyle: TextStyle( + color: theme.colorScheme.onPrimaryContainer, + fontWeight: FontWeight.normal, + ), + prefixIcon: const Icon(Icons.search_outlined), + hintText: L10n.of(context).search, + ), ), - prefixIcon: const Icon(Icons.search_outlined), - hintText: L10n.of(context).search, ), - ), - ), - if (availableFilters.length > 1) - SizedBox( - height: 64, - child: ListView.builder( - padding: const EdgeInsets.all(12.0), - scrollDirection: Axis.horizontal, - itemCount: availableFilters.length, - itemBuilder: (context, i) => Padding( - padding: const EdgeInsets.symmetric( - horizontal: 4.0, - ), - child: FilterChip( - label: Text(switch (availableFilters[i]) { - Membership.ban => L10n.of(context).banned, - Membership.invite => - L10n.of(context).countInvited( - room.summary.mInvitedMemberCount ?? - controller.members - ?.where( - (member) => - member.membership == - Membership.invite, - ) - .length ?? - 0, - ), - Membership.join => - L10n.of(context).countParticipants( - room.summary.mJoinedMemberCount ?? - controller.members - ?.where( - (member) => - member.membership == - Membership.join, - ) - .length ?? - 0, - ), - Membership.knock => L10n.of( - context, - ).knocking, - Membership.leave => L10n.of( - context, - ).leftTheChat, - }), - selected: - controller.membershipFilter == - availableFilters[i], - onSelected: (_) => controller - .setMembershipFilter(availableFilters[i]), + if (availableFilters.length > 1) + SizedBox( + height: 64, + child: ListView.builder( + padding: const EdgeInsets.all(12.0), + scrollDirection: Axis.horizontal, + itemCount: availableFilters.length, + itemBuilder: (context, i) => Padding( + padding: const EdgeInsets.symmetric( + horizontal: 4.0, + ), + child: FilterChip( + label: Text(switch (availableFilters[i]) { + Membership.ban => L10n.of( + context, + ).banned, + Membership.invite => + L10n.of(context).countInvited( + IcMemberCounts.invited( + room.client, + room.id, + ) ?? + room + .summary + .mInvitedMemberCount ?? + controller.members + ?.where( + (member) => + member.membership == + Membership.invite, + ) + .length ?? + 0, + ), + Membership.join => + L10n.of(context).countParticipants( + // IdealChat P1: server count first. + IcMemberCounts.count( + room.client, + room.id, + ) ?? + room + .summary + .mJoinedMemberCount ?? + controller.members + ?.where( + (member) => + member.membership == + Membership.join, + ) + .length ?? + 0, + ), + Membership.knock => L10n.of( + context, + ).knocking, + Membership.leave => L10n.of( + context, + ).leftTheChat, + }), + selected: + controller.membershipFilter == + availableFilters[i], + onSelected: (_) => + controller.setMembershipFilter( + availableFilters[i], + ), + ), + ), ), ), - ), - ), - ], - ); - } - i--; - return ParticipantListItem(members[i]); - }, + ], + ); + }, + ), + // IdealChat P7: grouped like the web member list. + ...icGroupedMemberWidgets( + context, + room, + members, + ParticipantListItem.new, + ), + ], + ), ), ), ); diff --git a/lib/pages/idealchat/ai_status_page.dart b/lib/pages/idealchat/ai_status_page.dart new file mode 100644 index 0000000..d2355ea --- /dev/null +++ b/lib/pages/idealchat/ai_status_page.dart @@ -0,0 +1,216 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat: room ⋮ → "AI status" (same data as the web ai_status.js, +// GET /ai-status/api?room=). Read only. + +import 'package:fluffychat/config/app_config.dart'; +import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/widgets/layouts/max_width_body.dart'; +import 'package:fluffychat/widgets/matrix.dart'; +import 'package:material_ui/material_ui.dart'; + +class AiStatusPage extends StatefulWidget { + final String roomId; + + const AiStatusPage({required this.roomId, super.key}); + + @override + State createState() => _AiStatusPageState(); +} + +class _AiStatusPageState extends State { + Map? _data; + Object? _error; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + setState(() => _error = null); + try { + final json = await Matrix.of( + context, + ).client.icGet('/ai-status/api', query: {'room': widget.roomId}); + if (!mounted) return; + setState( + () => _data = json is Map ? json.cast() : const {}, + ); + } catch (e) { + if (mounted) setState(() => _error = e); + } + } + + (String, Color) _online(L10n l10n, String? state) => switch (state) { + 'online' => (l10n.icOnline, const Color(0xFF2E7D32)), + 'offline' => (l10n.icOffline, const Color(0xFF757575)), + 'quota' => (l10n.icQuota, const Color(0xFFC62828)), + 'unavailable' => (l10n.icAway, const Color(0xFFF9A825)), + _ => (l10n.icUnknown, const Color(0xFF9E9E9E)), + }; + + String _exam(L10n l10n, Map exam) { + final state = exam['state']?.toString(); + final label = switch (state) { + 'passed' => l10n.icExamPassed, + 'pending' => l10n.icExamPending, + 'readonly' => l10n.icExamLocked, + _ => state ?? '—', + }; + return [ + label, + if (exam['note'] != null && exam['note'].toString().isNotEmpty) + exam['note'].toString(), + if (state == 'passed' && exam['ts'] != null) exam['ts'].toString(), + ].join(' · '); + } + + @override + Widget build(BuildContext context) { + final l10n = L10n.of(context); + final theme = Theme.of(context); + final data = _data; + final ais = (data?['ais'] as List?)?.whereType().toList() ?? []; + final rulesCurrent = data?['rules_current']?.toString(); + + Widget row(String key, String value) => Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Row( + crossAxisAlignment: .start, + children: [ + SizedBox( + width: 88, + child: Text( + key, + style: TextStyle(color: theme.colorScheme.onSurfaceVariant), + ), + ), + Expanded(child: SelectableText(value)), + ], + ), + ); + + final Widget body; + if (data == null) { + body = _error != null + ? ListTile( + leading: const Icon(Icons.refresh_outlined), + title: Text('${l10n.icLoadFailed} $_error'), + onTap: _load, + ) + : const Padding( + padding: EdgeInsets.all(32), + child: Center(child: CircularProgressIndicator.adaptive()), + ); + } else { + body = Column( + crossAxisAlignment: .stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Text( + l10n.icAiStatusSummary( + ais.length, + rulesCurrent ?? '—', + data['generated']?.toString() ?? '—', + ), + style: TextStyle(color: theme.colorScheme.onSurfaceVariant), + ), + ), + if (ais.isEmpty) + Padding( + padding: const EdgeInsets.all(16), + child: Text(l10n.icNoAiHere), + ), + for (final ai in ais) + Card( + margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppConfig.borderRadius), + ), + child: Padding( + padding: const EdgeInsets.all(14), + child: Builder( + builder: (context) { + final (onlineText, onlineColor) = _online( + l10n, + ai['online']?.toString(), + ); + final ack = ai['rules_ack']?.toString(); + final pw = ai['privacy_warnings']; + return Column( + crossAxisAlignment: .start, + children: [ + Row( + children: [ + Expanded( + child: Text( + (ai['name'] ?? ai['id']).toString(), + style: theme.textTheme.titleMedium, + ), + ), + Icon(Icons.circle, size: 10, color: onlineColor), + const SizedBox(width: 4), + Text( + onlineText, + style: TextStyle(color: onlineColor), + ), + ], + ), + const SizedBox(height: 6), + row('ID', ai['id']?.toString() ?? '—'), + row( + l10n.icInvitedBy, + ai['inviter']?.toString() ?? l10n.icUnknown, + ), + row(l10n.icNameHere, ai['name']?.toString() ?? '—'), + row( + l10n.icExam, + ai['exam'] is Map + ? _exam(l10n, ai['exam'] as Map) + : '—', + ), + row( + l10n.icGroupRules, + ack == null || ack.isEmpty + ? l10n.icRulesNotConfirmed + : ack == rulesCurrent + ? l10n.icRulesConfirmed(ack) + : l10n.icRulesOld(ack), + ), + row( + l10n.icPrivacyWarnings, + pw == null ? l10n.icNoDataYet : '$pw/3', + ), + row(l10n.icPowerLevel, ai['power']?.toString() ?? '—'), + ], + ); + }, + ), + ), + ), + const SizedBox(height: 16), + ], + ); + } + + return Scaffold( + appBar: AppBar( + leading: const Center(child: BackButton()), + title: Text(l10n.icAiStatus), + actions: [ + IconButton( + icon: const Icon(Icons.refresh_outlined), + onPressed: _load, + ), + ], + ), + body: MaxWidthBody(child: body), + ); + } +} diff --git a/lib/pages/idealchat/member_groups.dart b/lib/pages/idealchat/member_groups.dart new file mode 100644 index 0000000..31e16ed --- /dev/null +++ b/lib/pages/idealchat/member_groups.dart @@ -0,0 +1,230 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat P6/P7: member list grouping and badges, same rules as the web +// member list (ic63/ic64/ic69): +// - 「我和朋友们」: owner / @system on top, then AI朋友 and 人类朋友 +// - 「我和AI朋友」: people and @system on top, then 附属AI and 独立AI +// - other rooms: 我的AI, then 我邀请的朋友 +// Headings show the count ("(零名)" when empty, as on the web). + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/idealchat/ai_directory.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +String icSectionTitle(BuildContext context, IcMemberSection section) => + switch (section) { + IcMemberSection.aiFriends => icT(context, 'AI朋友', 'AI friends'), + IcMemberSection.humanFriends => icT(context, '人类朋友', 'Human friends'), + IcMemberSection.affiliatedAi => icT(context, '附属AI', 'Affiliated AIs'), + IcMemberSection.independentAi => icT(context, '独立AI', 'Independent AIs'), + IcMemberSection.myAi => icT(context, '我的AI', 'My AIs'), + IcMemberSection.invitedFriends => icT( + context, + '我邀请的朋友', + 'Friends I invited', + ), + IcMemberSection.top || IcMemberSection.plain => '', + }; + +String icSectionHeading(BuildContext context, IcMemberSection section, int n) { + final title = icSectionTitle(context, section); + return icT(context, '$title(${n == 0 ? '零' : n}名)', '$title ($n)'); +} + +/// The member list of [room], grouped like the web. [itemBuilder] builds one +/// member row. +List icGroupedMemberWidgets( + BuildContext context, + Room room, + List members, + Widget Function(User user) itemBuilder, +) { + final dir = IcAiDirectory.instance..ensureLoaded(room.client); + final kind = dir.roomKind(room.id, room.getLocalizedDisplayname()); + final groups = dir.group( + members: members, + kind: kind, + id: (u) => u.id, + power: (u) => u.powerLevel.level, + joined: (u) => u.membership == Membership.join, + ); + final theme = Theme.of(context); + Widget heading(IcMemberSection section, int n) => Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Text( + icSectionHeading(context, section, n), + style: theme.textTheme.titleSmall?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), + ); + final widgets = []; + final columns = >[]; + for (final group in groups) { + switch (group.section) { + case IcMemberSection.top || IcMemberSection.plain: + widgets.addAll(group.members.map(itemBuilder)); + case IcMemberSection.myAi || IcMemberSection.invitedFriends: + if (group.members.isEmpty) break; + widgets.add(heading(group.section, group.members.length)); + widgets.addAll(group.members.map(itemBuilder)); + default: + columns.add(group); + } + } + if (columns.isNotEmpty) { + // Web shows the two groups side by side; on a phone they are stacked. + final pairWidgets = [ + for (final group in columns) + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + heading(group.section, group.members.length), + ...group.members.map(itemBuilder), + ], + ), + ]; + final insertAt = groups.first.section == IcMemberSection.top + ? groups.first.members.length + : 0; + widgets.insert( + insertAt, + LayoutBuilder( + builder: (context, constraints) => constraints.maxWidth >= 640 + ? Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [for (final w in pairWidgets) Expanded(child: w)], + ) + : Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: pairWidgets, + ), + ), + ); + } + return widgets; +} + +class _Pill extends StatelessWidget { + final Widget child; + final Color background; + + const _Pill({required this.child, required this.background}); + + @override + Widget build(BuildContext context) => Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(18), + ), + child: child, + ); +} + +/// 所有者 (≥100) / 管理员 (≥50) / 参与者, colours as on the web. +class IcRoleBadge extends StatelessWidget { + final int level; + + const IcRoleBadge({required this.level, super.key}); + + @override + Widget build(BuildContext context) { + final (text, icon, fg, bg) = level >= 100 + ? ( + icT(context, '所有者', 'Owner'), + Icons.workspace_premium_outlined, + const Color(0xFFB26A00), + const Color(0xFFFFF4D6), + ) + : level >= 50 + ? ( + icT(context, '管理员', 'Admin'), + Icons.shield_outlined, + const Color(0xFF2F5FB3), + const Color(0xFFE3F2FF), + ) + : ( + icT(context, '参与者', 'Member'), + Icons.person_outline, + const Color(0xFF616161), + const Color(0xFFEEEEEE), + ); + return _Pill( + background: bg, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 14, color: fg), + const SizedBox(width: 4), + Text(text, style: TextStyle(fontSize: 12, color: fg, height: 1.4)), + ], + ), + ); + } +} + +/// AI / 人类 chip (member_categories.json). AI is blue when affiliated, +/// red otherwise, as on the web. +class IcCategoryChip extends StatelessWidget { + final String userId; + + const IcCategoryChip({required this.userId, super.key}); + + @override + Widget build(BuildContext context) { + final dir = IcAiDirectory.instance; + final isAi = dir.isAi(userId); + final zh = icT(context, 'zh', 'en') == 'zh'; + final label = + dir.categoryOverride(userId) ?? + (isAi + ? (zh ? dir.aiLabel : null) ?? 'AI' + : (zh ? dir.humanLabel : null) ?? icT(context, '人类', 'Human')); + final color = isAi + ? (dir.isAffiliated(userId) + ? const Color(0xFF1E88E5) + : const Color(0xFFE53935)) + : const Color(0xFF696969); + return _Pill( + background: const Color(0xFFEBEEEF), + child: Text( + label, + style: TextStyle(fontSize: 11, color: color, height: 1.6), + ), + ); + } +} + +/// ♂ / ♀ / hidden / unknown (user_gender.json), people only. +class IcGenderMark extends StatelessWidget { + final String? gender; + + const IcGenderMark({required this.gender, super.key}); + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: switch (gender) { + 'm' => const Text( + '♂', + style: TextStyle(fontSize: 14, color: Color(0xFF2196F3)), + ), + 'f' => const Text( + '♀', + style: TextStyle(fontSize: 14, color: Color(0xFFE91E63)), + ), + 'secret' => const Opacity( + opacity: 0.35, + child: Icon(Icons.person_outline, size: 16, color: Color(0xFFB9B9B9)), + ), + _ => const Icon(Icons.person_outline, size: 16, color: Color(0xFF9E9E9E)), + }, + ); +} diff --git a/lib/pages/idealchat/member_invite.dart b/lib/pages/idealchat/member_invite.dart new file mode 100644 index 0000000..49a30d3 --- /dev/null +++ b/lib/pages/idealchat/member_invite.dart @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat (web ic_rec.js): member menu 「邀请」 (/api/ai_panel/member_invite) +// and the settings entry 「推荐」 (/api/ai_panel/optin, SETTINGS_REC_1750). +// Permissions and results are decided by the server; the app only shows them. + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +String icMemberInviteMessage(BuildContext context, String? status, bool dup) { + final text = switch (status) { + 'requested' => icT( + context, + '已发送好友邀请,等对方在「推荐家人」里同意', + 'Friend request sent; waiting for them to accept in "Recommended family"', + ), + 'invited' => icT( + context, + '已发送邀请,等 AI 自己决定', + 'Invitation sent; the AI will decide', + ), + 'pending_owner' => icT( + context, + '已发送邀请,等这个 AI 的主人同意', + 'Invitation sent; waiting for the AI\'s owner', + ), + 'joined' => icT(context, '已经加入', 'Already joined'), + 'friend' => icT( + context, + '你们已经是好友(已有私聊)', + 'You are already friends (private chat exists)', + ), + 'accepted' => icT(context, '你们已经是好友', 'You are already friends'), + 'incoming' => icT( + context, + '对方已经邀请你了,请到「推荐家人」里接受', + 'They already invited you; accept in "Recommended family"', + ), + _ => icT(context, '已发送', 'Sent'), + }; + return dup ? text + icT(context, '(之前已发过)', ' (sent before)') : text; +} + +Future icInviteMember(BuildContext context, User user) async { + final messenger = ScaffoldMessenger.of(context); + String message; + try { + final json = await user.room.client.icPost('/api/ai_panel/member_invite', { + 'u': user.id, + 'room': user.room.id, + }); + final map = json is Map ? json : const {}; + if (!context.mounted) return; + message = icMemberInviteMessage( + context, + map['status']?.toString(), + map['dup'] == true, + ); + } catch (e) { + if (!context.mounted) return; + message = icT(context, '邀请没发出去:$e', 'Invitation not sent: $e'); + } + messenger.showSnackBar(SnackBar(content: Text(message))); +} + +Future showRecommendSettings(BuildContext context, Client client) => + showDialog( + context: context, + builder: (context) => _RecommendSettingsDialog(client), + ); + +class _RecommendSettingsDialog extends StatefulWidget { + final Client client; + + const _RecommendSettingsDialog(this.client); + + @override + State<_RecommendSettingsDialog> createState() => + _RecommendSettingsDialogState(); +} + +class _RecommendSettingsDialogState extends State<_RecommendSettingsDialog> { + Map? _optin; + Object? _error; + bool _busy = false; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + final json = await widget.client.icGet('/api/ai_panel/optin'); + if (!mounted) return; + setState(() { + _optin = json is Map ? json : const {}; + _error = null; + }); + } catch (e) { + if (mounted) setState(() => _error = e); + } + } + + Future _change(Future Function() action) async { + setState(() => _busy = true); + try { + await action(); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(e.toString()))); + } + } + await _load(); + if (mounted) setState(() => _busy = false); + } + + @override + Widget build(BuildContext context) { + final o = _optin; + final ais = [ + for (final a in (o?['my_ais'] as List? ?? const [])) + if (a is Map) a, + ]; + final allOn = ais.isNotEmpty && ais.every((a) => a['allow'] == true); + final selfLocked = o?['is_ai'] == true && o?['independent'] != true; + return AlertDialog( + title: Text(icT(context, '推荐', 'Recommendations')), + content: _error != null + ? Text(_error.toString()) + : o == null + ? const SizedBox( + height: 64, + child: Center(child: CircularProgressIndicator.adaptive()), + ) + : SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SwitchListTile.adaptive( + contentPadding: EdgeInsets.zero, + value: o['public'] == true, + onChanged: _busy || selfLocked + ? null + : (v) => _change( + () => widget.client.icPost('/api/ai_panel/optin', { + 'public': v, + }), + ), + title: Text(icT(context, '把自己作为推荐者', 'Recommend me')), + subtitle: Text( + icT( + context, + '公开接受别人的邀请:出现在邀请链家人的「推荐家人」里', + 'Accept invitations publicly: appear in "Recommended family" of your invite chain', + ), + ), + ), + SwitchListTile.adaptive( + contentPadding: EdgeInsets.zero, + value: allOn, + onChanged: _busy || ais.isEmpty + ? null + : (v) => _change(() async { + for (final a in ais) { + await widget.client.icPost( + '/api/ai_panel/optin', + {'ai': a['mxid'], 'allow': v}, + ); + } + }), + title: Text(icT(context, '把自己的AI推荐出去', 'Recommend my AIs')), + subtitle: Text( + ais.isEmpty + ? icT(context, '你名下还没有 AI', 'You have no AIs yet') + : icT( + context, + '一次设置你名下全部 ${ais.length} 个 AI', + 'Sets all ${ais.length} of your AIs at once', + ), + ), + ), + // Web 「⚙ 推荐设置」: one switch per AI. + for (final a in ais) + SwitchListTile.adaptive( + contentPadding: const EdgeInsets.only(left: 16), + dense: true, + value: a['allow'] == true, + onChanged: _busy + ? null + : (v) => _change( + () => widget.client.icPost( + '/api/ai_panel/optin', + {'ai': a['mxid'], 'allow': v}, + ), + ), + title: Text( + icT( + context, + '${a['name'] ?? a['mxid']} 允许被推荐', + '${a['name'] ?? a['mxid']} may be recommended', + ), + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(icT(context, '完成', 'Done')), + ), + ], + ); + } +} diff --git a/lib/pages/idealchat/member_panel_page.dart b/lib/pages/idealchat/member_panel_page.dart new file mode 100644 index 0000000..703eec1 --- /dev/null +++ b/lib/pages/idealchat/member_panel_page.dart @@ -0,0 +1,709 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat: member panel like the web ai_panel.js — full AI panel (status, +// model, usage, quota, rooms, rules; editable fields marked ✎), human +// profile, and the all-AI overview. Data and permissions come from the +// server (/api/ai_panel/member, /list, /edit, /pause); the app only shows. + +import 'package:fluffychat/config/app_config.dart'; +import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart'; +import 'package:fluffychat/widgets/adaptive_dialogs/show_text_input_dialog.dart'; +import 'package:fluffychat/widgets/avatar.dart'; +import 'package:fluffychat/widgets/layouts/max_width_body.dart'; +import 'package:fluffychat/widgets/matrix.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +/// zh / en text for IdealChat-only pages; follows the app language. +String icT(BuildContext context, String zh, String en) => + L10n.of(context).localeName.startsWith('zh') ? zh : en; + +Future showMemberPanel(BuildContext context, String userId) => + Navigator.of( + context, + rootNavigator: true, + ).push(MaterialPageRoute(builder: (_) => MemberPanelPage(userId: userId))); + +Future showAiOverview(BuildContext context) => Navigator.of( + context, + rootNavigator: true, +).push(MaterialPageRoute(builder: (_) => const AiOverviewPage())); + +String _v(Object? v, [String dash = '—']) => + v == null || (v is String && v.isEmpty) ? dash : v.toString(); + +class MemberPanelPage extends StatefulWidget { + final String userId; + + const MemberPanelPage({required this.userId, super.key}); + + @override + State createState() => _MemberPanelPageState(); +} + +class _MemberPanelPageState extends State { + Map? _data; + Object? _error; + + @override + void initState() { + super.initState(); + _load(); + } + + Client get _client => Matrix.of(context).client; + + Future _load() async { + setState(() => _error = null); + try { + final json = await _client.icGet( + '/api/ai_panel/member', + query: {'u': widget.userId}, + ); + if (mounted) { + setState(() => _data = json is Map ? json.cast() : {}); + } + } catch (e) { + if (mounted) setState(() => _error = e); + } + } + + String _presence(Object? p) { + final m = p is Map ? p : const {}; + final state = switch (m['state']) { + 'online' => icT(context, '在线', 'Online'), + 'offline' => icT(context, '离线', 'Offline'), + 'unavailable' => icT(context, '离开', 'Away'), + _ => icT(context, '未知', 'Unknown'), + }; + final last = m['last_active']?.toString(); + return last == null + ? state + : '$state · ${icT(context, '最后活跃', 'last active')} ${last.replaceFirst('T', ' ').substring(0, last.length < 16 ? last.length : 16)}'; + } + + String _rules(Map rl, Object? current) { + final state = switch (rl['state']) { + 'current' => icT(context, '已是最新', 'Up to date'), + 'behind' => icT(context, '落后', 'Behind'), + 'never_reported' => icT(context, '从未上报', 'Never reported'), + 'not_tracked' => icT(context, '未纳入上报', 'Not tracked'), + 'current_stale' => icT(context, '最新(久未上报)', 'Up to date (stale)'), + 'behind_stale' => icT(context, '落后(久未上报)', 'Behind (stale)'), + _ => _v(rl['state']), + }; + return '$state${rl['version'] != null ? ' · ${rl['version']}' : ''}' + ' (${icT(context, '当前', 'current')} ${_v(current)})'; + } + + String _rooms(Object? rooms, Object? scope) { + if (rooms is List && rooms.isNotEmpty) { + return rooms + .whereType() + .map( + (r) => + '${r['name']}(${r['role']}${r['power'] != null ? ' ${r['power']}' : ''})', + ) + .join('\n'); + } + return scope == 'owner_all' + ? icT(context, '暂不在任何群', 'Not in any group') + : icT(context, '(没有你也在的群)', '(No shared groups)'); + } + + Future _edit(String field, String label, String? current) async { + final value = await showTextInputDialog( + context: context, + title: label, + initialText: current ?? '', + maxLines: field == 'persona' ? 5 : 1, + ); + if (value == null || !mounted) return; + final messenger = ScaffoldMessenger.of(context); + try { + final res = await _client.icPost('/api/ai_panel/edit', { + 'u': widget.userId, + 'field': field, + 'value': value, + }); + if (!mounted) return; + messenger.showSnackBar( + SnackBar( + content: Text( + res is Map && res['applied'] == true + ? icT(context, '已保存', 'Saved') + : icT(context, '已记录,等网关生效', 'Recorded, takes effect soon'), + ), + ), + ); + _load(); + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text(e.toString()))); + } + } + + Future _togglePause(Map ai) async { + final paused = ai['paused'] == true; + final name = _v(ai['nickname']); + final ok = await showOkCancelAlertDialog( + context: context, + title: paused + ? icT(context, '恢复 $name 的回复?', 'Resume replies from $name?') + : icT(context, '暂停 $name 的回复?', 'Pause replies from $name?'), + message: paused + ? null + : icT( + context, + '可随时恢复,会记录日志。', + 'You can resume any time; this is logged.', + ), + ); + if (ok != OkCancelResult.ok || !mounted) return; + final messenger = ScaffoldMessenger.of(context); + try { + await _client.icPost('/api/ai_panel/pause', { + 'u': widget.userId, + 'paused': !paused, + }); + _load(); + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text(e.toString()))); + } + } + + Future _editOwnName(String? current) async { + final value = await showTextInputDialog( + context: context, + title: icT(context, '新昵称(只能改你自己的)', 'New display name'), + initialText: current ?? '', + ); + if (value == null || value.isEmpty || !mounted) return; + final messenger = ScaffoldMessenger.of(context); + try { + await _client.request( + RequestType.PUT, + '/client/v3/profile/${Uri.encodeComponent(_client.userID!)}/displayname', + data: {'displayname': value}, + ); + _load(); + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text(e.toString()))); + } + } + + Widget _section(String title) { + final theme = Theme.of(context); + return Padding( + padding: const EdgeInsets.fromLTRB(16, 18, 16, 4), + child: Text( + title, + style: TextStyle( + color: theme.colorScheme.secondary, + fontWeight: FontWeight.bold, + ), + ), + ); + } + + Widget _row(String key, String value, {VoidCallback? onEdit}) { + final theme = Theme.of(context); + final editable = onEdit != null; + return InkWell( + onTap: onEdit, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 5), + child: Row( + crossAxisAlignment: .start, + children: [ + SizedBox( + width: 110, + child: Text( + key, + style: TextStyle(color: theme.colorScheme.onSurfaceVariant), + ), + ), + Expanded( + child: Text( + value, + style: TextStyle( + color: editable + ? theme.colorScheme.onSurface + : theme.colorScheme.onSurfaceVariant, + ), + ), + ), + if (editable) + Text('✎', style: TextStyle(color: theme.colorScheme.primary)), + ], + ), + ), + ); + } + + Widget _head(String? avatarUrl, String name, String subtitle) => ListTile( + leading: Avatar( + mxContent: avatarUrl == null ? null : Uri.tryParse(avatarUrl), + name: name, + size: 56, + ), + title: Text(name, style: Theme.of(context).textTheme.titleLarge), + subtitle: Text(subtitle), + ); + + Widget _legend() => Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + icT( + context, + '带 ✎ 的是你可以改的;灰色是系统生成,只读。', + 'Items with ✎ can be changed by you; grey items are read-only.', + ), + style: Theme.of(context).textTheme.bodySmall, + ), + ); + + List _human(Map m) { + final mine = + (m['can_edit'] is Map) && (m['can_edit'] as Map)['nickname'] == true; + return [ + _head( + m['avatar_url']?.toString(), + _v(m['nickname']), + icT(context, '人类成员', 'Human member'), + ), + _legend(), + _section(icT(context, '资料', 'Profile')), + _row( + icT(context, '昵称', 'Name'), + _v(m['nickname']), + onEdit: mine ? () => _editOwnName(m['nickname']?.toString()) : null, + ), + _row( + icT(context, '头像', 'Avatar'), + m['avatar_url'] != null + ? icT(context, '已设置', 'Set') + : icT(context, '未设置', 'Not set'), + ), + _row(icT(context, '账号', 'Account'), _v(m['account'])), + _row(icT(context, '状态', 'Status'), _presence(m['presence'])), + _section( + '${icT(context, '共同所在的群', 'Shared groups')}(${_v(m['rooms_count'], '0')})', + ), + _row(icT(context, '群/权限', 'Groups'), _rooms(m['rooms'], null)), + ]; + } + + List _ai(Map r) { + final a = (r['ai'] as Map?) ?? const {}; + final c = (a['can_edit'] as Map?) ?? const {}; + final q = (a['quota'] as Map?) ?? const {}; + final cap = (a['capabilities'] as Map?) ?? const {}; + final h = (a['health'] as Map?) ?? const {}; + final pending = (a['pending_edits'] as Map?) ?? const {}; + final trend = (a['trend_7d'] as List?)?.whereType().toList() ?? []; + final maxAnswers = trend.fold( + 1, + (m, t) => (t['answers'] as num? ?? 0) > m ? t['answers'] as num : m, + ); + final theme = Theme.of(context); + final paused = a['paused'] == true; + return [ + _head( + a['avatar_url']?.toString(), + _v(a['nickname']), + 'AI · ${_v(a['activity'])}${paused ? ' · ${icT(context, '已暂停', 'Paused')}' : ''}', + ), + _legend(), + _section(icT(context, '基本资料', 'Basics')), + _row( + icT(context, '昵称', 'Name'), + _v(a['nickname']) + + (pending['nickname'] is Map + ? '(${icT(context, '待生效', 'pending')}:${(pending['nickname'] as Map)['value']})' + : ''), + onEdit: c['nickname'] == true + ? () => _edit( + 'nickname', + icT(context, '新昵称', 'New name'), + a['nickname']?.toString(), + ) + : null, + ), + _row( + icT(context, '头像', 'Avatar'), + a['avatar_url'] != null + ? icT(context, '已设置', 'Set') + : icT(context, '未设置', 'Not set'), + onEdit: c['avatar'] == true + ? () => _edit( + 'avatar_url', + icT(context, '头像 mxc:// 地址', 'Avatar mxc:// URL'), + a['avatar_url']?.toString(), + ) + : null, + ), + _row( + icT(context, '性格简介', 'Persona'), + _v(a['persona'], icT(context, '(未填写)', '(empty)')), + onEdit: c['persona'] == true + ? () => _edit( + 'persona', + icT(context, '性格简介(300 字内)', 'Persona (max 300 chars)'), + a['persona']?.toString(), + ) + : null, + ), + _row(icT(context, '账号', 'Account'), _v(a['account'])), + _row( + icT(context, '类型 / 归属', 'Type / owner'), + 'AI · ${_v(a['owner_label'])} · ${icT(context, '所有者', 'owner')} ${_v(a['owner'])}', + ), + _row(icT(context, '连接方式', 'Connection'), _v(a['connection'])), + _section(icT(context, '状态与健康', 'Status & health')), + _row(icT(context, '在线状态', 'Presence'), _presence(a['presence'])), + _row(icT(context, '当前活动', 'Activity'), _v(a['activity'])), + _row( + icT(context, '响应时间 / 错误率', 'Latency / errors'), + '${h['avg_latency_s'] == null ? '—' : '${h['avg_latency_s']} ${icT(context, '秒', 's')}'} / ${_v(h['error_rate'])}', + ), + _row( + icT(context, '最近错误', 'Last error'), + _v(h['last_error'] ?? h['note']), + ), + if (a['model_hidden'] != true && a.containsKey('model')) ...[ + _section(icT(context, '模型', 'Model')), + _row( + icT(context, '模型 / 版本', 'Model / version'), + '${_v(a['model'])} / ${_v(a['version'])}', + ), + _row( + icT(context, '版本上报', 'Reported'), + a['model_self_reported'] == true + ? '${icT(context, '自动上报', 'Auto-reported')} ${_v(a['model_reported_at'])}' + : icT(context, '未自动上报', 'Not auto-reported'), + ), + ], + _section(icT(context, '回答与消耗(今天)', 'Answers & usage (today)')), + _row(icT(context, '回答次数', 'Answers'), _v(a['today_answers'])), + _row( + 'token ${icT(context, '入 / 出', 'in / out')}', + '${_v(a['tokens_in'])} / ${_v(a['tokens_out'])}', + ), + _row(icT(context, '费用', 'Cost'), _v(a['today_cost'])), + _row( + icT(context, '每分钟额度', 'Per-minute quota'), + q['minute_limit'] == null + ? '—' + : '${q['minute_used']} / ${q['minute_limit']}(${icT(context, '剩', 'left')} ${q['minute_remaining']})', + ), + _row( + icT(context, '每天额度', 'Daily quota'), + q['day_limit'] == null + ? '—' + : '${q['day_used']} / ${q['day_limit']}(${icT(context, '剩', 'left')} ${q['day_remaining']})', + ), + if (trend.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + child: Column( + crossAxisAlignment: .start, + children: [ + SizedBox( + height: 52, + child: Row( + crossAxisAlignment: .end, + spacing: 4, + children: [ + for (final t in trend) + Expanded( + child: Tooltip( + message: + '${t['day']} ${t['answers']} · ${t['tokens']} token · ${t['cost']}', + child: Container( + height: + (48 * + ((t['answers'] as num? ?? 0) / + maxAnswers)) + .clamp(2, 48) + .toDouble(), + decoration: BoxDecoration( + color: theme.colorScheme.primary, + borderRadius: BorderRadius.circular(3), + ), + ), + ), + ), + ], + ), + ), + Text( + icT( + context, + '最近 7 天回答次数(长按看 token/费用)', + 'Answers, last 7 days (long-press for tokens/cost)', + ), + style: theme.textTheme.bodySmall, + ), + ], + ), + ), + _row( + icT(context, '按群(今天)', 'By group (today)'), + (a['by_room_today'] as List?) + ?.whereType() + .map( + (x) => + '${x['room_name']}:${x['answers']} / ${x['total_tokens']} token', + ) + .join('\n') ?? + '—', + ), + _section(icT(context, '群与权限', 'Groups & power')), + _row( + a['rooms_scope'] == 'owner_all' + ? icT(context, '所在群(全部)', 'Groups (all)') + : icT(context, '所在群', 'Groups'), + _rooms(a['rooms'], a['rooms_scope']), + ), + _row(icT(context, '最高权限', 'Max power'), _v(a['max_power'])), + _section(icT(context, '规则与能力', 'Rules & capabilities')), + _row( + icT(context, '群规版本', 'Rules version'), + _rules((a['rules'] as Map?) ?? const {}, r['rules_current']), + ), + _row( + icT(context, '适用规则层', 'Rule layers'), + ((a['rule_layers'] as List?) ?? const []).join(' > '), + ), + _row( + icT(context, '能力 / 后端', 'Backend'), + '${_v(cap['backend'])}${cap['rooms_allow_count'] != null ? ' · ${icT(context, '允许', 'allowed in')} ${cap['rooms_allow_count']} ${icT(context, '个群', 'groups')}' : ''}', + ), + _row( + icT(context, '工具 / 白名单', 'Tools / allowlist'), + '${_v(cap['tools'], icT(context, '工具列表未上报', 'not reported'))} · ${_v(cap['allowlist_mode'])}', + ), + _row(icT(context, '隐私打码', 'Privacy masking'), _v(a['privacy_mask'])), + _row( + icT(context, '凭证最近轮换', 'Credentials rotated'), + _v(a['credential_rotated']), + ), + _section(icT(context, '记忆与最近互动', 'Memory & recent')), + _row(icT(context, '记忆', 'Memory'), _v((a['memory'] as Map?)?['note'])), + _row( + icT(context, '最近互动', 'Recent'), + (a['recent'] as List?) + ?.whereType() + .map( + (x) => + '${x['time']} · ${x['room']} · ${x['model'] != null ? '${x['model']} · ' : ''}${x['tokens']} token', + ) + .join('\n') ?? + '—', + ), + Padding( + padding: const EdgeInsets.all(16), + child: Wrap( + spacing: 12, + runSpacing: 8, + children: [ + if (c['pause'] == true) + FilledButton.tonal( + onPressed: () => _togglePause(a), + child: Text( + paused + ? icT(context, '恢复回复', 'Resume replies') + : icT(context, '暂停回复', 'Pause replies'), + ), + ), + OutlinedButton( + onPressed: () => showAiOverview(context), + child: Text(icT(context, '所有 AI 总览', 'All AIs overview')), + ), + ], + ), + ), + if (paused && a['pause_effective'] != true) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + icT( + context, + '暂停开关已记录;网关按开关停回复的接线还在进行中。', + 'Pause recorded; the gateway does not enforce it yet.', + ), + style: theme.textTheme.bodySmall, + ), + ), + ]; + } + + @override + Widget build(BuildContext context) { + final data = _data; + final List children; + if (data == null) { + children = [ + _error != null + ? ListTile( + leading: const Icon(Icons.refresh_outlined), + title: Text('${L10n.of(context).icLoadFailed} $_error'), + onTap: _load, + ) + : const Padding( + padding: EdgeInsets.all(32), + child: Center(child: CircularProgressIndicator.adaptive()), + ), + ]; + } else if (data['kind'] == 'ai') { + children = _ai(data); + } else { + children = _human((data['member'] as Map?) ?? const {}); + } + return Scaffold( + appBar: AppBar( + title: Text(icT(context, '详细信息', 'Details')), + actions: [ + IconButton( + icon: const Icon(Icons.refresh_outlined), + onPressed: _load, + ), + ], + ), + body: MaxWidthBody( + child: Column( + crossAxisAlignment: .stretch, + children: [...children, const SizedBox(height: 24)], + ), + ), + ); + } +} + +class AiOverviewPage extends StatefulWidget { + const AiOverviewPage({super.key}); + + @override + State createState() => _AiOverviewPageState(); +} + +class _AiOverviewPageState extends State { + Map? _data; + Object? _error; + String _sort = 'today_answers'; + bool _asc = false; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + final json = await Matrix.of(context).client.icGet('/api/ai_panel/list'); + if (mounted) { + setState(() => _data = (json as Map).cast()); + } + } catch (e) { + if (mounted) setState(() => _error = e); + } + } + + Object? _val(Map a, String k) => switch (k) { + 'presence' => (a['presence'] as Map?)?['state'], + 'min_left' => (a['quota'] as Map?)?['minute_remaining'], + 'day_left' => (a['quota'] as Map?)?['day_remaining'], + 'rules' => (a['rules'] as Map?)?['state'], + _ => a[k], + }; + + @override + Widget build(BuildContext context) { + final cols = <(String, String)>[ + ('nickname', icT(context, '昵称', 'Name')), + ('presence', icT(context, '状态', 'Status')), + ('activity', icT(context, '活动', 'Activity')), + ('model', icT(context, '模型', 'Model')), + ('today_answers', icT(context, '今日回答', 'Answers today')), + ('today_tokens', icT(context, '今日 token', 'Tokens today')), + ('today_cost', icT(context, '今日费用', 'Cost today')), + ('min_left', icT(context, '分钟额度剩', 'Min quota left')), + ('day_left', icT(context, '日额度剩', 'Day quota left')), + ('rooms_count', icT(context, '群数', 'Groups')), + ('max_power', icT(context, '最高权限', 'Max power')), + ('rules', icT(context, '群规', 'Rules')), + ('connection', icT(context, '连接', 'Connection')), + ('owner_label', icT(context, '归属', 'Owner')), + ('account', icT(context, '账号', 'Account')), + ]; + final data = _data; + Widget body; + if (data == null) { + body = _error != null + ? ListTile( + title: Text('${L10n.of(context).icLoadFailed} $_error'), + onTap: _load, + ) + : const Center(child: CircularProgressIndicator.adaptive()); + } else { + final ais = ((data['ais'] as List?) ?? const []).whereType().toList() + ..sort((x, y) { + final a = _val(x, _sort), b = _val(y, _sort); + final c = a is num && b is num + ? a.compareTo(b) + : _v(a, '').compareTo(_v(b, '')); + return _asc ? c : -c; + }); + body = ListView( + children: [ + Padding( + padding: const EdgeInsets.all(12), + child: Text( + '${ais.length} · ${_v(data['generated_at']).replaceFirst('T', ' ')} · ${icT(context, '群规当前', 'rules')} ${_v(data['rules_current'])} · ${_v(data['note'], '')}', + ), + ), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + sortColumnIndex: cols.indexWhere((c) => c.$1 == _sort), + sortAscending: _asc, + showCheckboxColumn: false, + columns: [ + for (final c in cols) + DataColumn( + label: Text(c.$2), + onSort: (_, _) => setState(() { + _asc = _sort == c.$1 && !_asc; + _sort = c.$1; + }), + ), + ], + rows: [ + for (final a in ais) + DataRow( + onSelectChanged: (_) => + showMemberPanel(context, a['user_id'].toString()), + cells: [ + for (final c in cols) DataCell(Text(_v(_val(a, c.$1)))), + ], + ), + ], + ), + ), + ], + ); + } + return Scaffold( + appBar: AppBar(title: Text(icT(context, '所有 AI 总览', 'All AIs overview'))), + body: body, + ); + } +} + +// Kept for borderRadius consistency with other IdealChat pages. +const icRadius = AppConfig.borderRadius; diff --git a/lib/pages/idealchat/optional_members_dialog.dart b/lib/pages/idealchat/optional_members_dialog.dart new file mode 100644 index 0000000..c05b6cb --- /dev/null +++ b/lib/pages/idealchat/optional_members_dialog.dart @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat (web ic_optm.js parity): when creating a group, ask which AIs +// should join too (none checked unless the server says so). After the +// group exists, the choice goes to /api/optional_members/apply, where the +// server checks the creator. + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +/// Returns the chosen user ids, an empty list when there is nothing to +/// choose, or null when the user cancelled group creation. +Future?> askOptionalMembers( + BuildContext context, + Client client, +) async { + List catalog; + try { + final json = await client.icGet('/api/optional_members/catalog'); + catalog = ((json is Map ? json['members'] : null) as List? ?? const []) + .whereType() + .where((m) => m['enabled'] != false && m['user_id'] is String) + .toList(); + } catch (e) { + Logs().w('[IC] optional members catalog unavailable', e); + return const []; + } + if (catalog.isEmpty || !context.mounted) return const []; + final selected = { + for (final m in catalog) + if (m['default_checked'] == true) m['user_id'] as String, + }; + return showDialog>( + context: context, + builder: (context) => StatefulBuilder( + builder: (context, setState) => AlertDialog( + title: Text(icT(context, '可选成员', 'Optional members')), + content: SizedBox( + width: 360, + child: ListView( + shrinkWrap: true, + children: [ + Text( + icT( + context, + '勾选要一起加入新群的 AI(默认都不加入)。系统管家会照常自动加入。', + 'Tick the AIs that should join the new group (none by default). The system steward joins as usual.', + ), + ), + const SizedBox(height: 8), + for (final m in catalog) + CheckboxListTile( + contentPadding: EdgeInsets.zero, + value: selected.contains(m['user_id']), + onChanged: (v) => setState( + () => v == true + ? selected.add(m['user_id'] as String) + : selected.remove(m['user_id']), + ), + title: Text( + '${m['label'] ?? m['user_id']} ${(m['user_id'] as String).split(':').first}', + ), + subtitle: m['desc'] == null + ? null + : Text(m['desc'].toString()), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(null), + child: Text(icT(context, '取消建群', 'Cancel')), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(selected.toList()), + child: Text(icT(context, '建群', 'Create group')), + ), + ], + ), + ), + ); +} + +Future applyOptionalMembers( + Client client, + String roomId, + List members, +) async { + if (members.isEmpty) return; + try { + await client.icPost('/api/optional_members/apply', { + 'room_id': roomId, + 'members': members, + }); + } catch (e) { + Logs().w('[IC] optional members apply failed', e); + } +} diff --git a/lib/pages/idealchat/recommend.dart b/lib/pages/idealchat/recommend.dart new file mode 100644 index 0000000..d44e753 --- /dev/null +++ b/lib/pages/idealchat/recommend.dart @@ -0,0 +1,311 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat (web ic_rec.js parity): chat list buttons "Recommended family" +// and "Recommended AIs" with counts. Data, order and explanation come from +// /api/ai_panel/recommend (single source); actions are server calls. + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/widgets/avatar.dart'; +import 'package:fluffychat/widgets/matrix.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +class IcRecommendData { + static final notifier = ValueNotifier?>(null); + static DateTime? _last; + + static int family(Map? d) { + final f = d?['family']; + if (f is! Map) return 0; + return ((f['items'] as List?)?.length ?? 0) + + ((f['incoming'] as List?)?.length ?? 0); + } + + static int ai(Map? d) => (d?['ai'] as List?)?.length ?? 0; + + static Future load(Client client, {bool force = false}) async { + final last = _last; + if (!force && + last != null && + DateTime.now().difference(last) < const Duration(seconds: 30)) { + return; + } + _last = DateTime.now(); + try { + final json = await client.icGet('/api/ai_panel/recommend'); + if (json is Map) notifier.value = json.cast(); + } catch (e) { + Logs().v('[IC] recommend unavailable', e); + } + } +} + +/// The two buttons for the chat list header. +class IcRecommendButtons extends StatelessWidget { + const IcRecommendButtons({super.key}); + + @override + Widget build(BuildContext context) { + final client = Matrix.of(context).client; + IcRecommendData.load(client); + return ValueListenableBuilder( + valueListenable: IcRecommendData.notifier, + builder: (context, data, _) => Padding( + padding: const EdgeInsets.fromLTRB(12, 4, 12, 0), + child: Row( + spacing: 8, + children: [ + Expanded( + child: OutlinedButton.icon( + icon: const Icon(Icons.family_restroom_outlined, size: 18), + label: Text( + '${icT(context, '推荐家人', 'Family')} ${IcRecommendData.family(data)}${icT(context, '人', '')}', + overflow: TextOverflow.ellipsis, + ), + onPressed: () => _open(context, false), + ), + ), + Expanded( + child: OutlinedButton.icon( + icon: const Icon(Icons.smart_toy_outlined, size: 18), + label: Text( + '${icT(context, '推荐AI', 'AIs')} ${IcRecommendData.ai(data)}${icT(context, '人', '')}', + overflow: TextOverflow.ellipsis, + ), + onPressed: () => _open(context, true), + ), + ), + ], + ), + ), + ); + } + + void _open(BuildContext context, bool ai) => Navigator.of( + context, + rootNavigator: true, + ).push(MaterialPageRoute(builder: (_) => RecommendPage(ai: ai))); +} + +class RecommendPage extends StatefulWidget { + final bool ai; + + const RecommendPage({required this.ai, super.key}); + + @override + State createState() => _RecommendPageState(); +} + +class _RecommendPageState extends State { + final _busy = {}; + bool _explain = false; + + Client get _client => Matrix.of(context).client; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback( + (_) => IcRecommendData.load(_client, force: true), + ); + } + + Future _act(String path, Map body, String key) async { + setState(() => _busy.add(key)); + final messenger = ScaffoldMessenger.of(context); + try { + await _client.icPost('/api/ai_panel/$path', body); + await IcRecommendData.load(_client, force: true); + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text(e.toString()))); + } finally { + if (mounted) setState(() => _busy.remove(key)); + } + } + + String _friendLabel(String? status) => switch (status) { + 'requested' => icT(context, '已发送请求', 'Requested'), + 'accepted' => icT(context, '已是好友', 'Friends'), + 'declined' => icT(context, '已拒绝', 'Declined'), + 'incoming' => icT(context, '对方已请求', 'Wants to add you'), + _ => icT(context, '加好友', 'Add friend'), + }; + + String _aiLabel(String? status) => switch (status) { + 'invited' => icT(context, '已发送邀请', 'Invited'), + 'pending_owner' => icT(context, '等待主人同意', 'Waiting for owner'), + 'joined' => icT(context, '已加入', 'Joined'), + 'rejected' => icT(context, '已拒绝·再邀', 'Declined · ask again'), + 'blocked' => icT(context, '主群暂不开放', 'Not open'), + _ => icT(context, '发起私聊', 'Start chat'), + }; + + Widget _person(Map a, Widget action) => ListTile( + leading: Avatar( + mxContent: a['avatar_url'] == null + ? null + : Uri.tryParse(a['avatar_url'].toString()), + name: a['name']?.toString(), + ), + title: Text(a['name']?.toString() ?? a['mxid'].toString()), + onTap: a['mxid'] == null + ? null + : () => showMemberPanel(context, a['mxid'].toString()), + trailing: action, + ); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text( + widget.ai + ? icT(context, '推荐AI', 'Recommended AIs') + : icT(context, '推荐家人', 'Recommended family'), + ), + ), + body: ValueListenableBuilder( + valueListenable: IcRecommendData.notifier, + builder: (context, data, _) { + if (data == null) { + return const Center(child: CircularProgressIndicator.adaptive()); + } + final explain = data['explain']?.toString(); + final children = [ + if (explain != null && explain.isNotEmpty) + ListTile( + leading: const Icon(Icons.info_outline), + title: Text(icT(context, '怎么排序?', 'How is this sorted?')), + subtitle: _explain ? Text(explain) : null, + onTap: () => setState(() => _explain = !_explain), + ), + ]; + if (!widget.ai) { + final fam = (data['family'] as Map?) ?? const {}; + final incoming = (fam['incoming'] as List?)?.whereType() ?? []; + final items = (fam['items'] as List?)?.whereType() ?? []; + for (final a in incoming) { + final key = 'in:${a['mxid']}'; + children.add( + _person( + { + ...a, + 'name': icT( + context, + '${a['name']} 想加你', + '${a['name']} wants to add you', + ), + }, + Row( + mainAxisSize: .min, + children: [ + TextButton( + onPressed: _busy.contains(key) + ? null + : () => _act('recommend/friend_answer', { + 'u': a['mxid'], + 'accept': false, + }, key), + child: Text(icT(context, '拒绝', 'Decline')), + ), + FilledButton( + onPressed: _busy.contains(key) + ? null + : () => _act('recommend/friend_answer', { + 'u': a['mxid'], + 'accept': true, + }, key), + child: Text(icT(context, '接受', 'Accept')), + ), + ], + ), + ), + ); + } + for (final a in items) { + final key = 'f:${a['mxid']}'; + final status = a['status']?.toString(); + children.add( + _person( + a, + OutlinedButton( + onPressed: + status != 'none' && status != null || + _busy.contains(key) + ? null + : () => _act('recommend/friend', {'u': a['mxid']}, key), + child: Text(_friendLabel(status)), + ), + ), + ); + } + if (incoming.isEmpty && items.isEmpty) { + children.add( + ListTile( + title: Text( + icT(context, '还没有愿意被推荐的家人朋友', 'Nobody to recommend yet'), + ), + ), + ); + } + } else { + children.add( + ListTile( + dense: true, + title: Text( + icT( + context, + '点「发起私聊」会和这个 AI 开私聊', + '"Start chat" opens a private chat with the AI', + ), + ), + ), + ); + final ais = (data['ai'] as List?)?.whereType() ?? []; + for (final a in ais) { + final key = 'a:${a['mxid']}'; + final status = a['status']?.toString(); + final done = const { + 'invited', + 'pending_owner', + 'joined', + 'blocked', + }.contains(status); + children.add( + _person( + a, + OutlinedButton( + onPressed: done || _busy.contains(key) + ? null + : () => _act('recommend/invite', {'u': a['mxid']}, key), + child: Text( + _busy.contains(key) + ? icT(context, '发送中…', 'Sending…') + : _aiLabel(status), + ), + ), + ), + ); + } + if (ais.isEmpty) { + children.add( + ListTile( + title: Text( + icT(context, '还没有愿意被推荐的 AI', 'No AIs to recommend yet'), + ), + ), + ); + } + } + return RefreshIndicator.adaptive( + onRefresh: () => IcRecommendData.load(_client, force: true), + child: ListView(children: children), + ); + }, + ), + ); + } +} diff --git a/lib/pages/idealchat/task_board_page.dart b/lib/pages/idealchat/task_board_page.dart new file mode 100644 index 0000000..4c7b036 --- /dev/null +++ b/lib/pages/idealchat/task_board_page.dart @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat T-0122/T-0123: room ⋮ → "Task list". Shows the same task board +// page as the web version (/board/tasks?room=…&embed=1), so the app always +// matches the board the task steward maintains. Login is the board's own +// password-free flow (Matrix OpenID token → /board/api/sso); the session +// cookie lives only in the WebView. + +import 'dart:convert'; + +import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:fluffychat/widgets/matrix.dart'; +import 'package:go_router/go_router.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; +import 'package:webview_flutter/webview_flutter.dart'; + +class TaskBoardPage extends StatefulWidget { + final String roomId; + + const TaskBoardPage({required this.roomId, super.key}); + + @override + State createState() => _TaskBoardPageState(); +} + +class _TaskBoardPageState extends State { + WebViewController? _controller; + Object? _error; + int _progress = 0; + + @override + void initState() { + super.initState(); + _open(); + } + + @override + void didUpdateWidget(TaskBoardPage oldWidget) { + super.didUpdateWidget(oldWidget); + // Switched groups: reload for the new room, never keep the old list. + if (oldWidget.roomId != widget.roomId) _open(); + } + + Future _open() async { + setState(() { + _controller = null; + _error = null; + }); + final roomId = widget.roomId; + try { + final client = Matrix.of(context).client; + final session = await client.icBoardSession(); + final base = client.icBase; + await WebViewCookieManager().setCookie( + WebViewCookie( + name: 'ic_board', + value: session, + domain: base.host, + path: '/board', + ), + ); + final url = client.icUri('/board/tasks', { + 'room': roomId, + 'embed': '1', + 'panel_version': '3', + 'app': 'android', + }); + final controller = WebViewController() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..addJavaScriptChannel('ICApp', onMessageReceived: _onMessage) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (p) => mounted ? setState(() => _progress = p) : null, + onPageStarted: (_) => _applyTheme(), + onPageFinished: (_) => _applyTheme().then( + (_) => _controller?.runJavaScript( + // The board talks to its parent with postMessage; as a + // top-level page the parent is itself, so forward to the app. + "window.addEventListener('message',function(e){try{ICApp.postMessage(JSON.stringify(e.data))}catch(_){}});", + ), + ), + onNavigationRequest: (request) { + final uri = Uri.tryParse(request.url); + if (uri != null && + uri.host == base.host && + uri.path.startsWith('/board')) { + return NavigationDecision.navigate; + } + return NavigationDecision.prevent; + }, + ), + ) + ..loadRequest(url); + if (!mounted || roomId != widget.roomId) return; + setState(() => _controller = controller); + } catch (e, s) { + Logs().w('Unable to open task board', e, s); + if (mounted && roomId == widget.roomId) setState(() => _error = e); + } + } + + /// The board follows prefers-color-scheme, which in a WebView comes from + /// the native Android theme; pin it to the app's own light/dark choice. + Future _applyTheme() async { + if (!mounted) return; + final dark = Theme.of(context).brightness == Brightness.dark; + await _controller?.runJavaScript( + "document.documentElement.setAttribute('data-theme','${dark ? 'dark' : 'light'}');", + ); + } + + void _onMessage(JavaScriptMessage message) { + Object? data; + try { + data = jsonDecode(message.message); + } catch (_) { + return; + } + if (data is! Map) return; + switch (data['type']) { + case 'idealchat-task-close': + if (mounted) Navigator.of(context).maybePop(); + break; + case 'idealchat-jump': + final room = data['room']?.toString() ?? widget.roomId; + final event = data['event']?.toString(); + if (!mounted) return; + context.go( + '/rooms/$room${event == null ? '' : '?event=${Uri.encodeQueryComponent(event)}'}', + ); + break; + } + } + + @override + Widget build(BuildContext context) { + final l10n = L10n.of(context); + final controller = _controller; + return Scaffold( + appBar: AppBar( + leading: const Center(child: BackButton()), + title: Text(l10n.icTaskList), + actions: [ + IconButton( + icon: const Icon(Icons.refresh_outlined), + onPressed: _open, + ), + ], + bottom: controller != null && _progress < 100 + ? PreferredSize( + preferredSize: const Size.fromHeight(2), + child: LinearProgressIndicator(value: _progress / 100), + ) + : null, + ), + body: controller != null + ? WebViewWidget(controller: controller) + : _error != null + ? Center( + child: ListTile( + leading: const Icon(Icons.refresh_outlined), + title: Text('${l10n.icLoadFailed} $_error'), + onTap: _open, + ), + ) + : const Center(child: CircularProgressIndicator.adaptive()), + ); + } +} diff --git a/lib/pages/invitation_selection/invitation_selection.dart b/lib/pages/invitation_selection/invitation_selection.dart index f3687f1..58ae39d 100644 --- a/lib/pages/invitation_selection/invitation_selection.dart +++ b/lib/pages/invitation_selection/invitation_selection.dart @@ -42,10 +42,25 @@ class InvitationSelectionController extends State { participants.removeWhere( (u) => ![Membership.join, Membership.invite].contains(u.membership), ); - final contacts = client.rooms - .where((r) => r.isDirectChat) - .map((r) => r.unsafeGetUserFromMemoryOrFallback(r.directChatMatrixID!)) - .toList(); + // IdealChat (web __icPick/__icInviteVisible): private chats plus people + // from your other groups; skip yourself and current members. + final exclude = {client.userID, for (final u in participants) u.id}; + final seen = {}; + final contacts = []; + void add(User u) { + if (exclude.contains(u.id) || !seen.add(u.id)) return; + contacts.add(u); + } + + for (final r in client.rooms.where((r) => r.isDirectChat)) { + add(r.unsafeGetUserFromMemoryOrFallback(r.directChatMatrixID!)); + } + for (final r in client.rooms) { + if (r.membership != Membership.join || r.isDirectChat) continue; + for (final u in r.getParticipants([Membership.join])) { + add(u); + } + } contacts.sort( (a, b) => a.calcDisplayname().toLowerCase().compareTo( b.calcDisplayname().toLowerCase(), diff --git a/lib/pages/invitation_selection/invitation_selection_view.dart b/lib/pages/invitation_selection/invitation_selection_view.dart index f67cbed..7da0651 100644 --- a/lib/pages/invitation_selection/invitation_selection_view.dart +++ b/lib/pages/invitation_selection/invitation_selection_view.dart @@ -5,6 +5,7 @@ import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/invitation_selection/invitation_selection.dart'; +import 'package:fluffychat/utils/idealchat/ai_directory.dart'; import 'package:fluffychat/widgets/avatar.dart'; import 'package:fluffychat/widgets/layouts/max_width_body.dart'; import 'package:fluffychat/widgets/matrix.dart'; @@ -185,7 +186,9 @@ class _InviteContactListTile extends StatelessWidget { onTap: () => UserDialog.show(context: context, profile: profile), ), title: Text( - profile.displayName ?? profile.userId.localpart ?? l10n.user, + // IdealChat (web __icAiTag): mark AIs in the invite list. + (profile.displayName ?? profile.userId.localpart ?? l10n.user) + + (IcAiDirectory.instance.isAi(profile.userId) ? ' · AI' : ''), maxLines: 1, overflow: TextOverflow.ellipsis, ), diff --git a/lib/pages/new_group/new_group.dart b/lib/pages/new_group/new_group.dart index 7e2bc06..8d98fde 100644 --- a/lib/pages/new_group/new_group.dart +++ b/lib/pages/new_group/new_group.dart @@ -7,6 +7,7 @@ import 'dart:typed_data'; import 'package:file_picker/file_picker.dart'; import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/idealchat/optional_members_dialog.dart'; import 'package:fluffychat/pages/new_group/new_group_view.dart'; import 'package:fluffychat/utils/file_selector.dart'; import 'package:fluffychat/utils/matrix_live_kit_calls/matrix_live_kit_call_member.dart'; @@ -73,6 +74,13 @@ class NewGroupController extends State { Future _createGroup() async { if (!mounted) return; final client = Matrix.of(context).client; + // IdealChat: optional AI members step (web ic_optm.js) + final optional = await askOptionalMembers(context, client); + if (optional == null) { + if (mounted) setState(() => loading = false); + return; + } + if (!mounted) return; final roomId = await client.createGroupChat( visibility: groupCanBeFound @@ -96,6 +104,7 @@ class NewGroupController extends State { ], ); await _addToSpace(roomId); + await applyOptionalMembers(client, roomId, optional); if (!mounted) return; context.go('/rooms/$roomId/invite'); diff --git a/lib/pages/reply_mode/reply_mode_page.dart b/lib/pages/reply_mode/reply_mode_page.dart new file mode 100644 index 0000000..2103fb0 --- /dev/null +++ b/lib/pages/reply_mode/reply_mode_page.dart @@ -0,0 +1,459 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat: chat details → "AI reply mode" (REPLYMODE_20261029). + +import 'dart:async'; + +import 'package:fluffychat/config/app_config.dart'; +import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/utils/idealchat/reply_mode_api.dart'; +import 'package:fluffychat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart'; +import 'package:fluffychat/widgets/layouts/max_width_body.dart'; +import 'package:material_ui/material_ui.dart'; + +extension ReplyModeL10n on ReplyMode { + String label(L10n l10n) => switch (this) { + ReplyMode.quiet => l10n.aiReplyModeQuiet, + ReplyMode.lead => l10n.aiReplyModeLead, + ReplyMode.all => l10n.aiReplyModeAll, + ReplyMode.auto => l10n.aiReplyModeAuto, + }; + + String hint(L10n l10n) => switch (this) { + ReplyMode.quiet => l10n.aiReplyModeQuietHint, + ReplyMode.lead => l10n.aiReplyModeLeadHint, + ReplyMode.all => l10n.aiReplyModeAllHint, + ReplyMode.auto => l10n.aiReplyModeAutoHint, + }; +} + +extension _Paren on L10n { + /// Full-width brackets for Chinese, ASCII ones otherwise. + String paren(String text) => + localeName.startsWith('zh') ? '($text)' : ' ($text)'; +} + +extension ReplyModeStateL10n on ReplyModeState { + /// One line for the chat details tile. + String summary(L10n l10n) { + if (!enabled) return disabledText(l10n); + final mode = this.mode; + if (mode == null) return ''; + final effective = this.effective; + final picked = mode == ReplyMode.auto && effective != null + ? ' · ${l10n.aiReplyModeAutoPicked(effective.label(l10n))}' + : ''; + final lead = effective == ReplyMode.lead && leadName != null + ? l10n.paren(leadName!) + : ''; + return '${mode.label(l10n)}$picked$lead'; + } + + String disabledText(L10n l10n) => switch (disabledReason) { + 'dm' => l10n.aiReplyModeDm, + 'not_joined' => l10n.aiReplyModeNotJoined, + _ => l10n.aiReplyModeUnsupported, + }; +} + +class ReplyModePage extends StatefulWidget { + final String roomId; + final ReplyModeApi api; + + const ReplyModePage({required this.roomId, required this.api, super.key}); + + @override + State createState() => _ReplyModePageState(); +} + +class _ReplyModePageState extends State { + ReplyModeState? _state; + Object? _error; + bool _loading = false; + bool _saving = false; + ReplyMode? _selected; + String? _selectedLead; + Timer? _pendingTimer; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void didUpdateWidget(ReplyModePage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.roomId != widget.roomId) { + // Switched groups: clear first, never show the previous group's setting. + _pendingTimer?.cancel(); + setState(() { + _state = null; + _error = null; + _selected = null; + _selectedLead = null; + }); + _load(); + } + } + + @override + void dispose() { + _pendingTimer?.cancel(); + super.dispose(); + } + + void _apply(ReplyModeState state) { + _state = state; + _selected = state.mode; + _selectedLead = state.lead; + } + + Future _load() async { + final roomId = widget.roomId; + setState(() { + _loading = true; + _error = null; + }); + try { + final state = await widget.api.get(roomId); + if (!mounted || roomId != widget.roomId) return; + setState(() => _apply(state)); + } on ReplyModeRoomMismatch { + return; + } catch (e) { + if (!mounted || roomId != widget.roomId) return; + setState(() => _error = e); + } finally { + if (mounted && roomId == widget.roomId) { + setState(() => _loading = false); + } + } + } + + Future _save(ReplyMode mode, String? lead) => _submit( + () => widget.api.set( + widget.roomId, + mode, + lead: lead, + requestId: ReplyModeApi.newRequestId(), + ), + ); + + Future _reset(ReplyModeState state) async { + final l10n = L10n.of(context); + final ok = await showOkCancelAlertDialog( + context: context, + title: l10n.aiReplyModeReset(state.defaultMode?.label(l10n) ?? ''), + message: l10n.aiReplyModeResetHint, + ); + if (ok != OkCancelResult.ok || !mounted) return; + await _submit( + () => widget.api.reset( + widget.roomId, + requestId: ReplyModeApi.newRequestId(), + ), + ); + } + + Future _submit(Future Function() request) async { + final roomId = widget.roomId; + final l10n = L10n.of(context); + final messenger = ScaffoldMessenger.of(context); + setState(() => _saving = true); + try { + final result = await request(); + if (!mounted || roomId != widget.roomId) return; + final state = result.state; + if (state != null) { + setState(() => _apply(state)); + } + messenger.showSnackBar( + SnackBar( + content: Text( + result.done ? l10n.aiReplyModeSaved : l10n.aiReplyModePending, + ), + ), + ); + if (!result.done || state == null) { + _pendingTimer?.cancel(); + _pendingTimer = Timer(const Duration(seconds: 3), _load); + } + } catch (e) { + if (!mounted) return; + messenger.showSnackBar( + SnackBar( + content: Text( + e is ReplyModeException + ? e.toString() + : l10n.oopsSomethingWentWrong, + ), + ), + ); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + String _time(DateTime time) { + String two(int n) => n.toString().padLeft(2, '0'); + return '${time.month}-${time.day} ${two(time.hour)}:${two(time.minute)}'; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = L10n.of(context); + final state = _state; + + final Widget body; + if (state == null) { + body = _error != null && !_loading + ? ListTile( + leading: const Icon(Icons.refresh_outlined), + title: Text(l10n.aiReplyModeLoadFailed), + onTap: _load, + ) + : const Padding( + padding: EdgeInsets.all(32.0), + child: Center(child: CircularProgressIndicator.adaptive()), + ); + } else if (!state.enabled) { + body = Padding( + padding: const EdgeInsets.all(16.0), + child: _InfoCard(text: state.disabledText(l10n)), + ); + } else { + final selected = _selected; + final changed = + selected != state.mode || + (selected == ReplyMode.lead && _selectedLead != state.lead); + final effective = state.effective; + final autoPrev = state.autoPrev; + body = Column( + crossAxisAlignment: .stretch, + children: [ + Padding( + padding: const EdgeInsets.all(16.0), + child: _InfoCard( + title: l10n.aiReplyModeNow( + '${state.mode?.label(l10n) ?? ''}' + '${state.mode == ReplyMode.lead && state.leadName != null ? l10n.paren(state.leadName!) : ''}', + ), + lines: [ + if (state.mode == ReplyMode.auto && effective != null) + l10n.aiReplyModeAutoPicked(effective.label(l10n)), + if (state.mode == ReplyMode.auto && state.autoReason != null) + l10n.aiReplyModeReason(state.autoReason!), + if (state.isDefault) l10n.aiReplyModeIsDefault, + if (!state.canEdit) l10n.aiReplyModeReadOnly, + ], + ), + ), + // RESET_20261029: back to the site default (only if the server + // offers it). + if (state.canEdit && state.canReset) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Column( + crossAxisAlignment: .start, + spacing: 4, + children: [ + OutlinedButton.icon( + icon: const Icon(Icons.settings_backup_restore_outlined), + label: Text( + l10n.aiReplyModeReset( + state.defaultMode?.label(l10n) ?? '', + ), + ), + onPressed: _saving ? null : () => _reset(state), + ), + Text( + l10n.aiReplyModeResetHint, + style: theme.textTheme.bodySmall, + ), + ], + ), + ), + if (state.mode == ReplyMode.auto && autoPrev != null && state.canEdit) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: OutlinedButton.icon( + icon: const Icon(Icons.undo_outlined), + label: Text(l10n.aiReplyModeSwitchBack(autoPrev.label(l10n))), + onPressed: _saving + ? null + : () => _save( + autoPrev, + autoPrev == ReplyMode.lead ? state.lead : null, + ), + ), + ), + ), + RadioGroup( + groupValue: selected, + onChanged: (mode) { + if (!state.canEdit || _saving || mode == null) return; + setState(() => _selected = mode); + }, + child: Column( + children: [ + for (final mode in ReplyMode.values) ...[ + RadioListTile( + value: mode, + enabled: state.canEdit && !_saving, + title: Text(mode.label(l10n)), + subtitle: Text(mode.hint(l10n)), + ), + if (mode == ReplyMode.lead && selected == ReplyMode.lead) + Padding( + padding: const EdgeInsets.fromLTRB(72, 0, 16, 8), + child: DropdownButtonFormField( + initialValue: + state.ais.any((ai) => ai.id == _selectedLead) + ? _selectedLead + : null, + isExpanded: true, + decoration: InputDecoration( + labelText: l10n.aiReplyModeLeadAi, + ), + items: [ + DropdownMenuItem( + value: null, + child: Text(l10n.aiReplyModeNoLead), + ), + for (final ai in state.ais) + DropdownMenuItem( + value: ai.id, + child: Text( + ai.name, + overflow: TextOverflow.ellipsis, + ), + ), + ], + onChanged: state.canEdit && !_saving + ? (lead) => setState(() => _selectedLead = lead) + : null, + ), + ), + ], + ], + ), + ), + if (state.canEdit) + Padding( + padding: const EdgeInsets.all(16.0), + child: FilledButton( + onPressed: changed && !_saving && selected != null + ? () => _save( + selected, + selected == ReplyMode.lead ? _selectedLead : null, + ) + : null, + child: _saving + ? const SizedBox.square( + dimension: 20, + child: CircularProgressIndicator.adaptive( + strokeWidth: 2, + ), + ) + : Text(l10n.save), + ), + ), + if (state.log.isNotEmpty) ...[ + Divider(color: theme.dividerColor), + ListTile( + title: Text( + l10n.aiReplyModeRecent, + style: TextStyle( + color: theme.colorScheme.secondary, + fontWeight: FontWeight.bold, + ), + ), + ), + for (final entry in state.log) + ListTile( + dense: true, + leading: Icon( + entry.byAuto + ? Icons.auto_mode_outlined + : Icons.person_outline, + ), + title: Text( + entry.reason == '恢复默认' + ? '${entry.byAuto ? l10n.aiReplyModeByAi : entry.byName}' + ' → ${l10n.aiReplyModeReset(entry.effective?.label(l10n) ?? entry.mode?.label(l10n) ?? '')}' + : '${entry.byAuto ? l10n.aiReplyModeByAi : entry.byName}' + ' → ${entry.mode?.label(l10n) ?? ''}' + '${entry.mode == ReplyMode.auto && entry.effective != null ? l10n.paren(entry.effective!.label(l10n)) : ''}', + ), + subtitle: Text( + [ + _time(entry.time), + if (entry.reason != null && entry.reason!.isNotEmpty) + entry.reason!, + ].join(' · '), + ), + ), + ], + const SizedBox(height: 16), + ], + ); + } + + return Scaffold( + appBar: AppBar( + leading: const Center(child: BackButton()), + title: Text(l10n.aiReplyMode), + ), + body: RefreshIndicator.adaptive( + onRefresh: _load, + child: MaxWidthBody(child: body), + ), + ); + } +} + +class _InfoCard extends StatelessWidget { + final String? title; + final String? text; + final List lines; + + const _InfoCard({this.title, this.text, this.lines = const []}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Material( + color: theme.colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(AppConfig.borderRadius), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: .start, + spacing: 6, + children: [ + if (title != null) + Text( + title!, + style: theme.textTheme.titleMedium?.copyWith( + color: theme.colorScheme.onSurface, + ), + ), + if (text != null) + Text(text!, style: TextStyle(color: theme.colorScheme.onSurface)), + for (final line in lines) + Text( + line, + style: TextStyle(color: theme.colorScheme.onSurfaceVariant), + ), + ], + ), + ), + ); + } +} diff --git a/lib/pages/reply_mode/reply_mode_tile.dart b/lib/pages/reply_mode/reply_mode_tile.dart new file mode 100644 index 0000000..3acd26d --- /dev/null +++ b/lib/pages/reply_mode/reply_mode_tile.dart @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat: "AI reply mode" row on the group details page. +// Hidden while loading and when the API is unreachable (not deployed yet, +// network error); shows "not available" when the group isn't covered. + +import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/reply_mode/reply_mode_page.dart'; +import 'package:fluffychat/utils/idealchat/reply_mode_api.dart'; +import 'package:go_router/go_router.dart'; +import 'package:material_ui/material_ui.dart'; + +class ReplyModeTile extends StatefulWidget { + final String roomId; + final ReplyModeApi api; + + const ReplyModeTile({required this.roomId, required this.api, super.key}); + + @override + State createState() => _ReplyModeTileState(); +} + +class _ReplyModeTileState extends State { + ReplyModeState? _state; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void didUpdateWidget(ReplyModeTile oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.roomId != widget.roomId) { + setState(() => _state = null); + _load(); + } + } + + Future _load() async { + final roomId = widget.roomId; + try { + final state = await widget.api.get(roomId); + if (!mounted || roomId != widget.roomId) return; + setState(() => _state = state); + } catch (_) { + // Unreachable or not deployed: keep the row hidden. + } + } + + @override + Widget build(BuildContext context) { + final state = _state; + if (state == null || state.disabledReason == 'dm') { + return const SizedBox.shrink(); + } + final theme = Theme.of(context); + final l10n = L10n.of(context); + return ListTile( + leading: CircleAvatar( + backgroundColor: theme.colorScheme.surfaceContainer, + foregroundColor: theme.textTheme.bodyLarge!.color, + child: const Icon(Icons.smart_toy_outlined), + ), + title: Text(l10n.aiReplyMode), + subtitle: Text(state.summary(l10n)), + enabled: state.enabled, + trailing: state.enabled ? const Icon(Icons.chevron_right_outlined) : null, + onTap: state.enabled + ? () async { + await context.push('/rooms/${widget.roomId}/details/reply_mode'); + if (mounted) _load(); + } + : null, + ); + } +} diff --git a/lib/pages/settings/settings_view.dart b/lib/pages/settings/settings_view.dart index 702e2e1..bd62300 100644 --- a/lib/pages/settings/settings_view.dart +++ b/lib/pages/settings/settings_view.dart @@ -6,6 +6,8 @@ import 'package:async/async.dart'; import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/idealchat/member_invite.dart'; +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; import 'package:fluffychat/utils/fluffy_share.dart'; import 'package:fluffychat/utils/platform_infos.dart'; import 'package:fluffychat/widgets/avatar.dart'; @@ -174,6 +176,13 @@ class SettingsView extends StatelessWidget { ? theme.colorScheme.surfaceContainerHigh : null, ), + // IdealChat (web SETTINGS_REC_1750): 「推荐」 opt-in switches. + ListTile( + leading: const Icon(Icons.recommend_outlined), + title: Text(icT(context, '推荐', 'Recommendations')), + onTap: () => + showRecommendSettings(context, Matrix.of(context).client), + ), ListTile( leading: const Icon(Icons.shield_outlined), title: Text(L10n.of(context).security), diff --git a/lib/pages/settings_style/settings_style_view.dart b/lib/pages/settings_style/settings_style_view.dart index c4bbb26..69df0e3 100644 --- a/lib/pages/settings_style/settings_style_view.dart +++ b/lib/pages/settings_style/settings_style_view.dart @@ -10,8 +10,10 @@ import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/config/themes.dart'; import 'package:fluffychat/l10n/l10n.dart'; import 'package:fluffychat/pages/chat/events/state_message.dart'; +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; import 'package:fluffychat/utils/account_config.dart'; import 'package:fluffychat/utils/color_value.dart'; +import 'package:fluffychat/utils/idealchat/app_locale.dart'; import 'package:fluffychat/widgets/avatar.dart'; import 'package:fluffychat/widgets/layouts/max_width_body.dart'; import 'package:fluffychat/widgets/matrix.dart'; @@ -69,6 +71,32 @@ class SettingsStyleView extends StatelessWidget { ], ), ), + // IdealChat: interface language (web parity) + Divider(color: theme.dividerColor), + ListTile( + title: Text( + icT(context, '界面语言', 'Language'), + style: TextStyle( + color: theme.colorScheme.secondary, + fontWeight: FontWeight.bold, + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: SegmentedButton( + selected: {IcAppLocale.value}, + onSelectionChanged: (s) => IcAppLocale.set(s.single), + segments: [ + ButtonSegment( + value: '', + label: Text(icT(context, '跟随系统', 'System')), + ), + const ButtonSegment(value: 'zh', label: Text('中文')), + const ButtonSegment(value: 'en', label: Text('English')), + ], + ), + ), Divider(color: theme.dividerColor), ListTile( title: Text( diff --git a/lib/utils/idealchat/add_to_emotes.dart b/lib/utils/idealchat/add_to_emotes.dart new file mode 100644 index 0000000..2892fb5 --- /dev/null +++ b/lib/utils/idealchat/add_to_emotes.dart @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat P8 (web parity): image message ⋮ → "Add to my stickers". +// Asks for a short name, warns before overwriting, and writes the user's +// own pack (account data im.ponies.user_emotes). Encrypted images are +// decrypted and uploaded again, because a pack needs a plain mxc:// URL. + +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; +import 'package:fluffychat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart'; +import 'package:fluffychat/widgets/adaptive_dialogs/show_text_input_dialog.dart'; +import 'package:fluffychat/widgets/future_loading_dialog.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +bool canAddToEmotes(Event event) => + {MessageTypes.Image, EventTypes.Sticker}.contains(event.messageType) || + event.type == EventTypes.Sticker; + +Future addEventToEmotes(BuildContext context, Event event) async { + final client = event.room.client; + final messenger = ScaffoldMessenger.of(context); + final suggested = (event.body.split('.').first) + .replaceAll(RegExp(r'[^\w一-鿿-]'), '') + .toLowerCase(); + final shortcode = await showTextInputDialog( + context: context, + title: icT(context, '给这个表情起个短名', 'Short name for this sticker'), + initialText: suggested, + hintText: icT(context, '例如 haha', 'e.g. haha'), + ); + if (shortcode == null || shortcode.trim().isEmpty || !context.mounted) { + return; + } + final name = shortcode.trim().replaceAll(RegExp(r'\s+'), '_'); + final content = Map.from( + client.accountData['im.ponies.user_emotes']?.content ?? const {}, + ); + final images = Map.from( + (content['images'] as Map?)?.cast() ?? const {}, + ); + if (images.containsKey(name)) { + final ok = await showOkCancelAlertDialog( + context: context, + title: icT(context, '短名已存在,要覆盖吗?', 'This short name exists. Replace it?'), + message: ':$name:', + ); + if (ok != OkCancelResult.ok || !context.mounted) return; + } + final result = await showFutureLoadingDialog( + context: context, + future: () async { + Uri url; + final plain = event.content.tryGet('url'); + if (plain != null && !event.isAttachmentEncrypted) { + url = Uri.parse(plain); + } else { + final file = await event.downloadAndDecryptAttachment(); + url = await client.uploadContent( + file.bytes, + filename: file.name, + contentType: file.mimeType, + ); + } + final info = event.content.tryGetMap('info'); + images[name] = {'url': url.toString(), 'info': ?info}; + content['images'] = images; + await client.setAccountData( + client.userID!, + 'im.ponies.user_emotes', + content, + ); + }, + ); + if (result.error == null && context.mounted) { + messenger.showSnackBar( + SnackBar( + content: Text(icT(context, '已添加到表情包 :$name:', 'Added as :$name:')), + ), + ); + } +} diff --git a/lib/utils/idealchat/ai_directory.dart b/lib/utils/idealchat/ai_directory.dart new file mode 100644 index 0000000..1ad5de0 --- /dev/null +++ b/lib/utils/idealchat/ai_directory.dart @@ -0,0 +1,265 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat P7 (web ic17/ic18/ic19/ic25/ic30/ic31/ic44, ic63/ic64/ic69): who is +// an AI, affiliated vs independent AIs, special rooms ("我和朋友们", +// "我和AI朋友"), member categories, gender and model names. Same server +// files as the web: /app/ai_accounts.json, ai_classes.json, ai_rooms.json, +// room_types.json, member_categories.json, user_gender.json and +// /api/ai_panel/models (Bearer). Missing data falls back to the web's +// built-in rules; nothing is written. + +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +enum IcRoomKind { friends, ai, normal } + +/// Section of the member list. [title] is null for the top block (owner, +/// @system) and for members without a heading. +enum IcMemberSection { + top, + aiFriends, + humanFriends, + affiliatedAi, + independentAi, + myAi, + invitedFriends, + plain, +} + +class IcMemberGroup { + final IcMemberSection section; + final List members; + + const IcMemberGroup(this.section, this.members); +} + +class IcAiDirectory { + static const systemUser = '@system:ideal2001.com'; + static const _builtinAi = [ + 'system', + 'grokbot', + 'chatgpt', + 'cursor', + 'gemini', + 'kimi', + 'kimi_work', + 'muse', + 'task_bot', + ]; + + static final instance = IcAiDirectory(); + static final changed = ValueNotifier(0); + + List? aiList; + Map classes = {}; + List aiRooms = ['!MloEDx_zpv2gyQbO5KlZdA9KF9SRqAJjm12U8_2IINg']; + Map roomTypes = { + '!bQuh7_jlE6Kix61kerFrdkSF6HYMbmrN8W2zAuPBld0': 'friends', + '!MloEDx_zpv2gyQbO5KlZdA9KF9SRqAJjm12U8_2IINg': 'ai', + }; + String? aiLabel; + String? humanLabel; + Map categoryUsers = {}; + Map gender = {}; + Map models = {}; + + DateTime? _loadedAt; + Future? _inflight; + + bool isAi(String id) { + if (aiList?.contains(id) ?? false) return true; + final local = id.replaceFirst('@', '').split(':').first.toLowerCase(); + return local.startsWith('bot_') || + local.endsWith('_ai') || + _builtinAi.contains(local); + } + + bool isIndependent(String id) => classes[id] == 'independent'; + + bool isAffiliated(String id) => classes[id] == 'affiliated'; + + IcRoomKind roomKind(String roomId, String roomName) { + if (roomTypes[roomId] == 'friends' || roomName.startsWith('我和朋友们')) { + return IcRoomKind.friends; + } + if (aiRooms.contains(roomId) || + roomTypes[roomId] == 'ai' || + roomName.startsWith('我和AI朋友')) { + return IcRoomKind.ai; + } + return IcRoomKind.normal; + } + + /// Category label override from member_categories.json, or null to use + /// the localized default (AI / human). + String? categoryOverride(String id) => categoryUsers[id]; + + /// 'm', 'f', 'secret' or null. + String? genderOf(String id) => gender[id]; + + /// Model line for an AI: version, else model, else null when unknown. + /// Returns '' when the AI is listed but both are unknown ("模型未知"). + String? modelOf(String id) { + final m = models[id]; + if (m == null) return null; + bool known(Object? v) => + v != null && v.toString().isNotEmpty && v != '未知' && v != '无'; + final version = m['version'], model = m['model']; + var s = known(version) + ? version.toString() + : known(model) + ? model.toString() + : ''; + if (s.length > 28) s = '${s.substring(0, 27)}…'; + return s; + } + + /// Groups joined members like the web member list (ic63/ic64/ic69). + /// Non-joined members are returned last in a [IcMemberSection.plain] group. + List> group({ + required List members, + required IcRoomKind kind, + required String Function(T) id, + required int Function(T) power, + required bool Function(T) joined, + }) { + final joinedMembers = members.where(joined).toList(); + final others = members.where((m) => !joined(m)).toList(); + final groups = >[]; + switch (kind) { + case IcRoomKind.friends: + bool top(T m) => + id(m) == systemUser || (!isAi(id(m)) && power(m) >= 100); + final rest = joinedMembers.where((m) => !top(m)); + groups.addAll([ + IcMemberGroup(IcMemberSection.top, joinedMembers.where(top).toList()), + IcMemberGroup( + IcMemberSection.aiFriends, + rest.where((m) => isAi(id(m))).toList(), + ), + IcMemberGroup( + IcMemberSection.humanFriends, + rest.where((m) => !isAi(id(m))).toList(), + ), + ]); + case IcRoomKind.ai: + bool top(T m) => !isAi(id(m)) || id(m) == systemUser; + final ais = joinedMembers.where((m) => !top(m)); + groups.addAll([ + IcMemberGroup(IcMemberSection.top, joinedMembers.where(top).toList()), + IcMemberGroup( + IcMemberSection.affiliatedAi, + ais.where((m) => !isIndependent(id(m))).toList(), + ), + IcMemberGroup( + IcMemberSection.independentAi, + ais.where((m) => isIndependent(id(m))).toList(), + ), + ]); + case IcRoomKind.normal: + groups.addAll([ + IcMemberGroup( + IcMemberSection.myAi, + joinedMembers.where((m) => isAi(id(m))).toList(), + ), + IcMemberGroup( + IcMemberSection.invitedFriends, + joinedMembers.where((m) => !isAi(id(m))).toList(), + ), + ]); + } + if (others.isNotEmpty) { + groups.add(IcMemberGroup(IcMemberSection.plain, others)); + } + return groups; + } + + void applyJson(String name, Object? json) { + switch (name) { + case 'ai_accounts': + if (json is Map && json['ai'] is List) { + aiList = [for (final e in json['ai'] as List) e.toString()]; + } + case 'ai_classes': + if (json is Map) { + classes = { + for (final e in json.entries) + if (e.value is String) e.key.toString(): e.value as String, + }; + } + case 'ai_rooms': + if (json is Map && json['rooms'] is List) { + for (final r in json['rooms'] as List) { + if (!aiRooms.contains(r.toString())) aiRooms.add(r.toString()); + } + } + case 'room_types': + if (json is Map) { + for (final e in json.entries) { + if (e.value is String) roomTypes[e.key.toString()] = e.value; + } + } + case 'member_categories': + if (json is Map) { + if (json['ai'] is String) aiLabel = json['ai']; + if (json['human'] is String) humanLabel = json['human']; + if (json['users'] is Map) { + categoryUsers = { + for (final e in (json['users'] as Map).entries) + e.key.toString(): e.value.toString(), + }; + } + } + case 'user_gender': + if (json is Map) { + gender = { + for (final e in json.entries) e.key.toString(): e.value.toString(), + }; + } + case 'models': + if (json is Map && json['error'] == null) { + models = { + for (final e in json.entries) + if (e.value is Map) e.key.toString(): e.value as Map, + }; + } + } + } + + /// Loads the server files (at most every 5 minutes). + void ensureLoaded(Client client) { + final last = _loadedAt; + if (last != null && + DateTime.now().difference(last) < const Duration(minutes: 5)) { + return; + } + _inflight ??= () async { + Future load(String name, String path) async { + try { + applyJson(name, await client.icGet(path)); + } catch (e) { + Logs().v('[IC] $path unavailable', e); + } + } + + await Future.wait([ + for (final name in [ + 'ai_accounts', + 'ai_classes', + 'ai_rooms', + 'room_types', + 'member_categories', + 'user_gender', + ]) + load(name, '/app/$name.json'), + load('models', '/api/ai_panel/models'), + ]); + _loadedAt = DateTime.now(); + _inflight = null; + changed.value++; + }(); + } +} diff --git a/lib/utils/idealchat/app_locale.dart b/lib/utils/idealchat/app_locale.dart new file mode 100644 index 0000000..9cbcd54 --- /dev/null +++ b/lib/utils/idealchat/app_locale.dart @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat (web ic_lang.js parity): interface language follows the system +// by default and can be set to 中文 or English inside the app. + +import 'package:fluffychat/config/setting_keys.dart'; +import 'package:material_ui/material_ui.dart'; + +abstract class IcAppLocale { + static ValueNotifier? _notifier; + + static ValueNotifier get notifier => + _notifier ??= ValueNotifier(_parse(AppSettings.icLocale.value)); + + static String get value => AppSettings.icLocale.value; + + static Locale? _parse(String value) => switch (value) { + 'zh' => const Locale('zh'), + 'en' => const Locale('en'), + _ => null, + }; + + static Future set(String value) async { + await AppSettings.icLocale.setItem(value); + notifier.value = _parse(value); + } +} diff --git a/lib/utils/idealchat/ic_api.dart b/lib/utils/idealchat/ic_api.dart new file mode 100644 index 0000000..17e2a97 --- /dev/null +++ b/lib/utils/idealchat/ic_api.dart @@ -0,0 +1,96 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat: small helpers for the IdealChat server APIs the web version +// uses (/ai-status, /api/members, /api/ai_panel, /board …). Auth is the +// user's own Matrix access token (Bearer); nothing is stored by the app. + +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:matrix/matrix.dart'; + +class IcApiException implements Exception { + final int statusCode; + final String? message; + + const IcApiException(this.statusCode, this.message); + + @override + String toString() => message ?? 'HTTP $statusCode'; +} + +extension IcApi on Client { + /// https://ideal2001.com (falls back to the homeserver of this client). + Uri get icBase => homeserver ?? Uri.parse('https://ideal2001.com'); + + Uri icUri(String path, [Map? query]) => + icBase.replace(path: path, queryParameters: query); + + Map get _icHeaders => { + 'Authorization': 'Bearer ${accessToken ?? ''}', + 'Accept': 'application/json', + }; + + static Object? _decode(http.Response response) { + try { + return jsonDecode(utf8.decode(response.bodyBytes)); + } catch (_) { + return null; + } + } + + static String? _message(Object? json) => + json is Map ? (json['message'] ?? json['error'])?.toString() : null; + + Future icGet(String path, {Map? query}) async { + final response = await httpClient + .get(icUri(path, query), headers: _icHeaders) + .timeout(const Duration(seconds: 20)); + final json = _decode(response); + if (response.statusCode != 200) { + throw IcApiException(response.statusCode, _message(json)); + } + return json; + } + + Future icPost(String path, Object body) async { + final response = await httpClient + .post( + icUri(path), + headers: {..._icHeaders, 'Content-Type': 'application/json'}, + body: jsonEncode(body), + ) + .timeout(const Duration(seconds: 20)); + final json = _decode(response); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw IcApiException(response.statusCode, _message(json)); + } + return json; + } + + /// Task board login without password (same as the web board): a one-time + /// Matrix OpenID token is exchanged at /board/api/sso for the board session + /// cookie value. Returns the `ic_board` cookie value. + Future icBoardSession() async { + final openId = await requestOpenIdToken(userID!, {}); + final response = await httpClient + .post( + icUri('/board/api/sso'), + headers: { + 'Content-Type': 'application/json', + 'Origin': icBase.origin, + }, + body: jsonEncode({'openid_token': openId.accessToken}), + ) + .timeout(const Duration(seconds: 20)); + if (response.statusCode != 200) { + throw IcApiException(response.statusCode, _message(_decode(response))); + } + final cookie = response.headers['set-cookie'] ?? ''; + final match = RegExp(r'ic_board=([^;]+)').firstMatch(cookie); + if (match == null) throw const IcApiException(500, 'no session'); + return match.group(1)!; + } +} diff --git a/lib/utils/idealchat/member_counts.dart b/lib/utils/idealchat/member_counts.dart new file mode 100644 index 0000000..1b17270 --- /dev/null +++ b/lib/utils/idealchat/member_counts.dart @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat P1/P2 (web ic_mc.js, MEMBERSSOT): group member counts come only +// from the server (/api/members, membership=join). Until the server has +// answered, no number is shown — never a wrong local count or a fake 0. + +import 'package:fluffychat/utils/idealchat/ic_api.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:matrix/matrix.dart'; + +abstract class IcMemberCounts { + static final changed = ValueNotifier(0); + static final _counts = {}; + static final _invited = {}; + static DateTime? _lastAll; + static Future? _inflight; + + /// Joined members of [roomId] as counted by the server, or null if unknown. + static int? count(Client client, String roomId) { + final last = _lastAll; + if (last == null || + DateTime.now().difference(last) > const Duration(seconds: 30)) { + _loadAll(client); + } + return _counts[roomId]; + } + + /// Invited members of [roomId] as counted by the server, or null. + static int? invited(Client client, String roomId) { + count(client, roomId); + return _invited[roomId]; + } + + static Future refresh(Client client, String roomId) async { + try { + final json = await client.icGet( + '/api/members/${Uri.encodeComponent(roomId)}', + query: {'refresh': '1'}, + ); + if (json is Map && json['count'] is int) { + _counts[roomId] = json['count'] as int; + if (json['invited'] is int) _invited[roomId] = json['invited'] as int; + changed.value++; + } + } catch (e) { + Logs().v('[IC] member count for $roomId unavailable', e); + } + } + + static void _loadAll(Client client) { + _inflight ??= () async { + try { + final json = await client.icGet('/api/members/mine'); + final rooms = json is Map ? json['rooms'] : null; + if (rooms is Map) { + for (final entry in rooms.entries) { + final count = entry.value is Map ? entry.value['count'] : null; + if (count is int) _counts[entry.key.toString()] = count; + final invited = entry.value is Map ? entry.value['invited'] : null; + if (invited is int) _invited[entry.key.toString()] = invited; + } + changed.value++; + } + _lastAll = DateTime.now(); + } catch (e) { + Logs().v('[IC] member counts unavailable', e); + _lastAll = DateTime.now(); + } finally { + _inflight = null; + } + }(); + } +} + +/// Rebuilds with the server member count of [room] (null until known). +class IcMemberCount extends StatelessWidget { + final Room room; + final Widget Function(BuildContext context, int? count) builder; + + const IcMemberCount({required this.room, required this.builder, super.key}); + + @override + Widget build(BuildContext context) => ValueListenableBuilder( + valueListenable: IcMemberCounts.changed, + builder: (context, _, _) => + builder(context, IcMemberCounts.count(room.client, room.id)), + ); +} diff --git a/lib/utils/idealchat/reply_mode_api.dart b/lib/utils/idealchat/reply_mode_api.dart new file mode 100644 index 0000000..b80fd23 --- /dev/null +++ b/lib/utils/idealchat/reply_mode_api.dart @@ -0,0 +1,293 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// IdealChat: per-group AI reply mode (REPLYMODE_20261029). +// Server side: task steward board API, GET/POST /board/api/reply_mode. +// Auth: Bearer with the user's own Matrix access token (never stored here). + +import 'dart:convert'; +import 'dart:math'; + +import 'package:http/http.dart' as http; +import 'package:matrix/matrix.dart'; + +enum ReplyMode { + quiet, + lead, + all, + auto; + + static ReplyMode? tryParse(Object? value) { + for (final mode in values) { + if (mode.name == value) return mode; + } + return null; + } +} + +class ReplyModeAi { + final String id; + final String name; + + const ReplyModeAi(this.id, this.name); +} + +class ReplyModeLogEntry { + final DateTime time; + final String by; + final String byName; + final ReplyMode? mode; + final ReplyMode? effective; + final String? reason; + + const ReplyModeLogEntry({ + required this.time, + required this.by, + required this.byName, + this.mode, + this.effective, + this.reason, + }); + + bool get byAuto => by == 'auto'; +} + +class ReplyModeState { + final String room; + final bool enabled; + + /// dm | excluded | readonly | not_joined | not_ready (only when !enabled) + final String? disabledReason; + final ReplyMode? mode; + final ReplyMode? effective; + final String? lead; + final ReplyMode? autoApplied; + final String? autoReason; + final ReplyMode? autoPrev; + final bool isDefault; + final List ais; + final bool canEdit; + final List log; + final bool pending; + + /// The group has its own setting and can go back to the site default + /// (RESET_20261029). Missing field (older server) → false. + final bool canReset; + final ReplyMode? defaultMode; + + const ReplyModeState({ + required this.room, + required this.enabled, + this.disabledReason, + this.mode, + this.effective, + this.lead, + this.autoApplied, + this.autoReason, + this.autoPrev, + this.isDefault = false, + this.ais = const [], + this.canEdit = false, + this.log = const [], + this.pending = false, + this.canReset = false, + this.defaultMode, + }); + + factory ReplyModeState.fromJson(Map json) { + final auto = json['auto']; + final autoMap = auto is Map ? auto.cast() : null; + final ais = json['ais']; + final log = json['log']; + return ReplyModeState( + room: json['room'] as String? ?? '', + enabled: json['enabled'] == true, + disabledReason: json['reason'] as String?, + mode: ReplyMode.tryParse(json['mode']), + effective: ReplyMode.tryParse(json['effective']), + lead: json['lead'] as String?, + autoApplied: ReplyMode.tryParse(autoMap?['applied']), + autoReason: autoMap?['reason'] as String?, + autoPrev: ReplyMode.tryParse(autoMap?['prev']), + isDefault: json['is_default'] == true, + ais: [ + if (ais is List) + for (final ai in ais.whereType()) + if (ai['id'] is String) + ReplyModeAi( + ai['id'] as String, + ai['name'] as String? ?? ai['id'] as String, + ), + ], + canEdit: json['can_edit'] == true, + log: [ + if (log is List) + for (final entry in log.whereType()) + ReplyModeLogEntry( + time: DateTime.fromMillisecondsSinceEpoch( + ((entry['ts'] as num? ?? 0) * 1000).round(), + ), + by: entry['by'] as String? ?? '', + byName: + entry['by_name'] as String? ?? entry['by'] as String? ?? '', + mode: ReplyMode.tryParse(entry['mode']), + effective: ReplyMode.tryParse(entry['effective']), + reason: entry['reason'] as String?, + ), + ], + pending: json['pending'] != null, + canReset: json['can_reset'] == true, + defaultMode: ReplyMode.tryParse(json['default']), + ); + } + + String? get leadName { + final lead = this.lead; + if (lead == null) return null; + for (final ai in ais) { + if (ai.id == lead) return ai.name; + } + return lead.localpart ?? lead; + } +} + +/// The room id in the response does not belong to the room we asked about +/// (the user switched groups meanwhile). The caller drops it. +class ReplyModeRoomMismatch implements Exception {} + +class ReplyModeException implements Exception { + final int statusCode; + + /// Plain-language message from the server, if any. + final String? message; + + const ReplyModeException(this.statusCode, this.message); + + @override + String toString() => message ?? 'HTTP $statusCode'; +} + +class ReplyModeSaveResult { + /// true: written (state is fresh). false: accepted, takes effect shortly. + final bool done; + final String? message; + final ReplyModeState? state; + + const ReplyModeSaveResult({required this.done, this.message, this.state}); +} + +class ReplyModeApi { + /// For local stub testing only: --dart-define=IC_BOARD_API=http://127.0.0.1:8787/board/api + static const _override = String.fromEnvironment('IC_BOARD_API'); + + final Uri baseUri; + final String? Function() accessToken; + final http.Client httpClient; + + ReplyModeApi({ + required this.baseUri, + required this.accessToken, + required this.httpClient, + }); + + factory ReplyModeApi.forClient(Client client) => ReplyModeApi( + baseUri: _override.isNotEmpty + ? Uri.parse(_override) + : (client.homeserver ?? Uri.parse('https://ideal2001.com')).resolve( + '/board/api', + ), + accessToken: () => client.accessToken, + httpClient: client.httpClient, + ); + + Uri _endpoint([Map? query]) => baseUri.replace( + path: '${baseUri.path}/reply_mode', + queryParameters: query, + ); + + Map get _headers => { + 'Authorization': 'Bearer ${accessToken() ?? ''}', + 'Accept': 'application/json', + }; + + static Map _decode(http.Response response) { + try { + final json = jsonDecode(utf8.decode(response.bodyBytes)); + if (json is Map) return json.cast(); + } catch (_) {} + return const {}; + } + + static String? _message(Map json) => + (json['message'] ?? json['error']) as String?; + + Future get(String roomId) async { + final response = await httpClient + .get(_endpoint({'room': roomId}), headers: _headers) + .timeout(const Duration(seconds: 15)); + final json = _decode(response); + if (response.statusCode != 200) { + throw ReplyModeException(response.statusCode, _message(json)); + } + final state = ReplyModeState.fromJson(json); + if (state.room != roomId) throw ReplyModeRoomMismatch(); + return state; + } + + static String newRequestId() { + final random = Random.secure(); + return List.generate( + 16, + (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); + } + + Future set( + String roomId, + ReplyMode mode, { + String? lead, + required String requestId, + }) => _post(roomId, { + 'room': roomId, + 'mode': mode.name, + 'lead': lead, + 'request_id': requestId, + }); + + /// Removes the group's own setting; the group follows the site default. + Future reset( + String roomId, { + required String requestId, + }) => _post(roomId, {'room': roomId, 'reset': true, 'request_id': requestId}); + + Future _post( + String roomId, + Map body, + ) async { + final response = await httpClient + .post( + _endpoint(), + headers: {..._headers, 'Content-Type': 'application/json'}, + body: jsonEncode(body), + ) + .timeout(const Duration(seconds: 20)); + final json = _decode(response); + switch (response.statusCode) { + case 200: + final state = json['state']; + final parsed = state is Map + ? ReplyModeState.fromJson(state.cast()) + : null; + return ReplyModeSaveResult( + done: true, + message: _message(json), + state: parsed != null && parsed.room == roomId ? parsed : null, + ); + case 202: + return ReplyModeSaveResult(done: false, message: _message(json)); + default: + throw ReplyModeException(response.statusCode, _message(json)); + } + } +} diff --git a/lib/widgets/chat_settings_popup_menu.dart b/lib/widgets/chat_settings_popup_menu.dart index 73974a2..2f81e47 100644 --- a/lib/widgets/chat_settings_popup_menu.dart +++ b/lib/widgets/chat_settings_popup_menu.dart @@ -14,7 +14,16 @@ import 'package:matrix/matrix.dart'; import 'matrix.dart'; -enum ChatPopupMenuActions { details, encryption, leave, search } +enum ChatPopupMenuActions { + details, + encryption, + leave, + search, + // IdealChat: same extra items as the web ⋮ menu + tasks, + aiStatus, + replyMode, +} class ChatSettingsPopupMenu extends StatefulWidget { final Room room; @@ -85,6 +94,15 @@ class ChatSettingsPopupMenuState extends State { case ChatPopupMenuActions.encryption: context.go('/rooms/${widget.room.id}/encryption'); break; + case ChatPopupMenuActions.tasks: + context.push('/rooms/${widget.room.id}/tasks'); + break; + case ChatPopupMenuActions.aiStatus: + context.push('/rooms/${widget.room.id}/ai_status'); + break; + case ChatPopupMenuActions.replyMode: + context.push('/rooms/${widget.room.id}/details/reply_mode'); + break; } }, itemBuilder: (BuildContext context) => [ @@ -99,6 +117,38 @@ class ChatSettingsPopupMenuState extends State { ], ), ), + if (!widget.room.isDirectChat) ...[ + PopupMenuItem( + value: ChatPopupMenuActions.tasks, + child: Row( + children: [ + const Icon(Icons.checklist_outlined), + const SizedBox(width: 12), + Text(L10n.of(context).icTaskList), + ], + ), + ), + PopupMenuItem( + value: ChatPopupMenuActions.aiStatus, + child: Row( + children: [ + const Icon(Icons.smart_toy_outlined), + const SizedBox(width: 12), + Text(L10n.of(context).icAiStatus), + ], + ), + ), + PopupMenuItem( + value: ChatPopupMenuActions.replyMode, + child: Row( + children: [ + const Icon(Icons.forum_outlined), + const SizedBox(width: 12), + Text(L10n.of(context).aiReplyMode), + ], + ), + ), + ], PopupMenuItem( value: ChatPopupMenuActions.search, child: Row( diff --git a/lib/widgets/fluffy_chat_app.dart b/lib/widgets/fluffy_chat_app.dart index 0e875e8..6afb186 100644 --- a/lib/widgets/fluffy_chat_app.dart +++ b/lib/widgets/fluffy_chat_app.dart @@ -9,6 +9,7 @@ import 'package:fluffychat/config/routes.dart'; import 'package:fluffychat/config/setting_keys.dart'; import 'package:fluffychat/config/themes.dart'; import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/utils/idealchat/app_locale.dart'; import 'package:fluffychat/widgets/app_lock.dart'; import 'package:fluffychat/widgets/layouts/call_overlay.dart'; import 'package:fluffychat/widgets/theme_builder.dart'; @@ -65,34 +66,42 @@ class FluffyChatApp extends StatelessWidget { @override Widget build(BuildContext context) { return ThemeBuilder( - builder: (context, themeMode, primaryColor) => MaterialApp.router( - title: AppSettings.applicationName.value, - themeMode: themeMode, - theme: FluffyThemes.buildTheme(context, Brightness.light, primaryColor), - darkTheme: FluffyThemes.buildTheme( - context, - Brightness.dark, - primaryColor, - ), - scrollBehavior: CustomScrollBehavior(), - localizationsDelegates: [ - ...L10n.localizationsDelegates, - ...GlobalMaterialLocalizations.delegates, - ...GlobalCupertinoLocalizations.delegates, - ], - supportedLocales: L10n.supportedLocales, - routerConfig: router, - builder: (context, child) => AppLockWidget( - pincode: appLockSettings.pincode, - useBiometrics: appLockSettings.useBiometrics, - isLoggedIn: clients.any((client) => client.isLogged()), - // Need a navigator above the Matrix widget for - // displaying dialogs - child: Matrix( - clients: clients, - store: store, - child: CallOverlay( - child: testWidget ?? child ?? const SizedBox.shrink(), + builder: (context, themeMode, primaryColor) => ValueListenableBuilder( + valueListenable: IcAppLocale.notifier, + builder: (context, locale, _) => MaterialApp.router( + locale: locale, + title: AppSettings.applicationName.value, + themeMode: themeMode, + theme: FluffyThemes.buildTheme( + context, + Brightness.light, + primaryColor, + ), + darkTheme: FluffyThemes.buildTheme( + context, + Brightness.dark, + primaryColor, + ), + scrollBehavior: CustomScrollBehavior(), + localizationsDelegates: [ + ...L10n.localizationsDelegates, + ...GlobalMaterialLocalizations.delegates, + ...GlobalCupertinoLocalizations.delegates, + ], + supportedLocales: L10n.supportedLocales, + routerConfig: router, + builder: (context, child) => AppLockWidget( + pincode: appLockSettings.pincode, + useBiometrics: appLockSettings.useBiometrics, + isLoggedIn: clients.any((client) => client.isLogged()), + // Need a navigator above the Matrix widget for + // displaying dialogs + child: Matrix( + clients: clients, + store: store, + child: CallOverlay( + child: testWidget ?? child ?? const SizedBox.shrink(), + ), ), ), ), diff --git a/lib/widgets/member_actions_popup_menu_button.dart b/lib/widgets/member_actions_popup_menu_button.dart index 567e647..e0c2ba3 100644 --- a/lib/widgets/member_actions_popup_menu_button.dart +++ b/lib/widgets/member_actions_popup_menu_button.dart @@ -4,6 +4,8 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/idealchat/member_invite.dart'; +import 'package:fluffychat/pages/idealchat/member_panel_page.dart'; import 'package:fluffychat/widgets/permission_slider_dialog.dart'; import 'package:material_ui/material_ui.dart'; import 'package:matrix/matrix.dart'; @@ -63,6 +65,31 @@ Future showMemberActionsPopupMenu({ ], ), ), + // IdealChat: web parity — "Details" opens the member panel + PopupMenuItem( + value: _MemberActions.icDetails, + child: Row( + children: [ + const Icon(Icons.badge_outlined), + const SizedBox(width: 18), + Text(icT(context, '详细信息', 'Details')), + ], + ), + ), + // IdealChat (web ic_rec.js icInviteMember): friend request / AI invite + // for members you have no private chat with yet. + if (user.id != user.room.client.userID && + user.room.client.getDirectChatFromUserId(user.id) == null) + PopupMenuItem( + value: _MemberActions.icInvite, + child: Row( + children: [ + const Icon(Icons.person_add_alt_outlined), + const SizedBox(width: 18), + Text(icT(context, '邀请', 'Invite')), + ], + ), + ), if (onMention != null) PopupMenuItem( value: _MemberActions.mention, @@ -302,6 +329,12 @@ Future showMemberActionsPopupMenu({ SnackBar(content: Text(l10n.contentHasBeenReported)), ); return; + case _MemberActions.icDetails: + await showMemberPanel(context, user.id); + return; + case _MemberActions.icInvite: + await icInviteMember(context, user); + return; case _MemberActions.info: await UserDialog.show( context: context, @@ -363,6 +396,8 @@ Future showMemberActionsPopupMenu({ enum _MemberActions { info, + icDetails, + icInvite, mention, setPowerLevel, makeAdmin, diff --git a/pubspec.lock b/pubspec.lock index 1545b54..f325b54 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1288,7 +1288,7 @@ packages: dependency: "direct main" description: path: "." - ref: main + ref: "355bf1d2d471ef2ab578d83a14a684cea7c07a1c" resolved-ref: "355bf1d2d471ef2ab578d83a14a684cea7c07a1c" url: "https://github.com/famedly/matrix-dart-sdk.git" source: git @@ -2434,6 +2434,38 @@ packages: url: "https://pub.dev" source: hosted version: "1.5.1" + webview_flutter: + dependency: "direct main" + description: + name: webview_flutter + sha256: d53e1ccf5516f25017e3c9d44c39034db352d20fa34fe200674270242c2c5111 + url: "https://pub.dev" + source: hosted + version: "4.14.1" + webview_flutter_android: + dependency: transitive + description: + name: webview_flutter_android + sha256: "4de8b3d1ff4ebe1bdb42e68a5e4f809194a3cb0117a8f495f590004f00da3964" + url: "https://pub.dev" + source: hosted + version: "4.14.1" + webview_flutter_platform_interface: + dependency: transitive + description: + name: webview_flutter_platform_interface + sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04" + url: "https://pub.dev" + source: hosted + version: "2.15.1" + webview_flutter_wkwebview: + dependency: transitive + description: + name: webview_flutter_wkwebview + sha256: acac45e0a8d7beb1d0805521f44842f406c46eb5a69410f53d935e3c62138afc + url: "https://pub.dev" + source: hosted + version: "3.27.2" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index db41e6a..e778428 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -9,7 +9,7 @@ publish_to: none # On version bump please also increase: # 1. The build number (for F-Droid) # 2. The version in /snap/snapcraft.yaml -version: 2.10.2+3570 +version: 2.10.3+3571 environment: sdk: ">=3.11.1 <4.0.0" @@ -66,7 +66,8 @@ dependencies: matrix: #^11.0.0 git: url: https://github.com/famedly/matrix-dart-sdk.git - ref: main + # IdealChat: pinned to the commit 2.10.1/2.10.2 were built with + ref: 355bf1d2d471ef2ab578d83a14a684cea7c07a1c media_kit_libs_linux: ^1.2.1 media_kit_libs_windows_audio: ^1.0.9 mime: ^2.1.0 @@ -98,6 +99,7 @@ dependencies: uuid: ^4.6.0 video_player: ^2.14.0 wakelock_plus: ^1.8.0 + webview_flutter: ^4.14.1 dev_dependencies: dart_code_linter: ^4.4.0 diff --git a/test/ai_directory_test.dart b/test/ai_directory_test.dart new file mode 100644 index 0000000..f84ecdd --- /dev/null +++ b/test/ai_directory_test.dart @@ -0,0 +1,142 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +import 'package:fluffychat/utils/idealchat/ai_directory.dart'; +import 'package:flutter_test/flutter_test.dart'; + +typedef _M = ({String id, int power, bool joined}); + +List> _group( + IcAiDirectory dir, + IcRoomKind kind, + List<_M> m, +) => dir.group<_M>( + members: m, + kind: kind, + id: (x) => x.id, + power: (x) => x.power, + joined: (x) => x.joined, +); + +List _ids(IcMemberGroup<_M> g) => [for (final m in g.members) m.id]; + +void main() { + IcAiDirectory dir() => IcAiDirectory() + ..applyJson('ai_accounts', { + 'ai': ['@helper:x', '@indep:x'], + }) + ..applyJson('ai_classes', { + '@helper:x': 'affiliated', + '@indep:x': 'independent', + }) + ..applyJson('room_types', {'!f:x': 'friends', '!a:x': 'ai'}) + ..applyJson('ai_rooms', { + 'rooms': ['!a2:x'], + }); + + const owner = (id: '@owner:x', power: 100, joined: true); + const system = (id: IcAiDirectory.systemUser, power: 100, joined: true); + const human = (id: '@bob:x', power: 0, joined: true); + const helper = (id: '@helper:x', power: 0, joined: true); + const indep = (id: '@indep:x', power: 50, joined: true); + const bot = (id: '@bot_new:x', power: 0, joined: true); + const invited = (id: '@carol:x', power: 0, joined: false); + + test('AI detection: list, classes and web fallback rules', () { + final d = dir(); + expect(d.isAi('@helper:x'), isTrue); + expect(d.isAi('@bot_new:x'), isTrue); + expect(d.isAi('@doubao_ai:x'), isTrue); + expect(d.isAi('@gemini:x'), isTrue); + expect(d.isAi('@bob:x'), isFalse); + expect(d.isIndependent('@indep:x'), isTrue); + expect(d.isAffiliated('@helper:x'), isTrue); + }); + + test('room kind by id, room_types and name prefix', () { + final d = dir(); + expect(d.roomKind('!f:x', 'whatever'), IcRoomKind.friends); + expect(d.roomKind('!z:x', '我和朋友们(我邀请的人)'), IcRoomKind.friends); + expect(d.roomKind('!a:x', ''), IcRoomKind.ai); + expect(d.roomKind('!a2:x', ''), IcRoomKind.ai); + expect(d.roomKind('!z:x', '我和AI朋友'), IcRoomKind.ai); + expect(d.roomKind('!z:x', '测试群'), IcRoomKind.normal); + }); + + test('friends room: owner and @system on top, then AI / human friends', () { + final g = _group(dir(), IcRoomKind.friends, [ + owner, + system, + human, + helper, + indep, + bot, + invited, + ]); + expect(g.map((e) => e.section), [ + IcMemberSection.top, + IcMemberSection.aiFriends, + IcMemberSection.humanFriends, + IcMemberSection.plain, + ]); + expect(_ids(g[0]), ['@owner:x', IcAiDirectory.systemUser]); + expect(_ids(g[1]), ['@helper:x', '@indep:x', '@bot_new:x']); + expect(_ids(g[2]), ['@bob:x']); + expect(_ids(g[3]), ['@carol:x']); + }); + + test('AI room: people on top, affiliated vs independent AIs', () { + final g = _group(dir(), IcRoomKind.ai, [owner, system, helper, indep, bot]); + expect(_ids(g[0]), ['@owner:x', IcAiDirectory.systemUser]); + expect(g[1].section, IcMemberSection.affiliatedAi); + // Not in ai_classes → affiliated, as on the web. + expect(_ids(g[1]), ['@helper:x', '@bot_new:x']); + expect(g[2].section, IcMemberSection.independentAi); + expect(_ids(g[2]), ['@indep:x']); + }); + + test('empty groups are kept (heading shows 零名)', () { + final g = _group(dir(), IcRoomKind.ai, [owner]); + expect(g[1].members, isEmpty); + expect(g[2].members, isEmpty); + }); + + test('normal room: my AIs, then invited friends; order kept', () { + final g = _group(dir(), IcRoomKind.normal, [owner, helper, human, bot]); + expect(g[0].section, IcMemberSection.myAi); + expect(_ids(g[0]), ['@helper:x', '@bot_new:x']); + expect(_ids(g[1]), ['@owner:x', '@bob:x']); + }); + + test('model line: version, else model, else empty; long cut', () { + final d = IcAiDirectory() + ..applyJson('models', { + '@a:x': {'model': 'gpt', 'version': 'gpt-9'}, + '@b:x': {'model': 'claude', 'version': '未知'}, + '@c:x': {'model': '未知', 'version': '无'}, + '@d:x': {'model': 'x' * 40}, + }); + expect(d.modelOf('@a:x'), 'gpt-9'); + expect(d.modelOf('@b:x'), 'claude'); + expect(d.modelOf('@c:x'), ''); + expect(d.modelOf('@d:x')!.length, 28); + expect(d.modelOf('@none:x'), isNull); + final err = IcAiDirectory()..applyJson('models', {'error': 'no'}); + expect(err.models, isEmpty); + }); + + test('categories and gender files', () { + final d = IcAiDirectory() + ..applyJson('member_categories', { + 'ai': 'AI', + 'human': '人类', + 'users': {'@vip:x': '贵宾'}, + }) + ..applyJson('user_gender', {'@bob:x': 'm'}); + expect(d.categoryOverride('@vip:x'), '贵宾'); + expect(d.categoryOverride('@bob:x'), isNull); + expect(d.humanLabel, '人类'); + expect(d.genderOf('@bob:x'), 'm'); + }); +} diff --git a/test/reply_mode_api_test.dart b/test/reply_mode_api_test.dart new file mode 100644 index 0000000..d8b8935 --- /dev/null +++ b/test/reply_mode_api_test.dart @@ -0,0 +1,168 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +import 'dart:convert'; + +import 'package:fluffychat/utils/idealchat/reply_mode_api.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; + +ReplyModeApi _api(MockClientHandler handler) => ReplyModeApi( + baseUri: Uri.parse('https://ideal2001.com/board/api'), + accessToken: () => 'tok', + httpClient: MockClient(handler), +); + +http.Response _json(int code, Object body) => http.Response.bytes( + utf8.encode(jsonEncode(body)), + code, + headers: {'content-type': 'application/json; charset=utf-8'}, +); + +void main() { + const room = '!a:ideal2001.com'; + + test('GET parses state and sends Bearer to /board/api/reply_mode', () async { + late http.Request seen; + final state = await _api((request) async { + seen = request; + return _json(200, { + 'room': room, + 'enabled': true, + 'mode': 'auto', + 'effective': 'all', + 'lead': null, + 'auto': {'applied': 'all', 'reason': '人少', 'prev': 'lead'}, + 'is_default': false, + 'ais': [ + {'id': '@bot:ideal2001.com', 'name': 'Bot 🤖'}, + ], + 'can_edit': true, + 'log': [ + {'ts': 1761700000.5, 'by': 'auto', 'by_name': 'AI', 'mode': 'auto'}, + ], + 'pending': null, + }); + }).get(room); + expect(seen.url.path, '/board/api/reply_mode'); + expect(seen.url.queryParameters['room'], room); + expect(seen.headers['Authorization'], 'Bearer tok'); + expect(state.mode, ReplyMode.auto); + expect(state.effective, ReplyMode.all); + expect(state.autoPrev, ReplyMode.lead); + expect(state.autoReason, '人少'); + expect(state.canEdit, isTrue); + expect(state.ais.single.name, 'Bot 🤖'); + expect(state.log.single.byAuto, isTrue); + }); + + test('GET for another room is dropped', () async { + final api = _api( + (_) async => _json(200, {'room': '!b:x', 'enabled': true}), + ); + expect(api.get(room), throwsA(isA())); + }); + + test('disabled group keeps reason', () async { + final state = await _api( + (_) async => _json(200, {'room': room, 'enabled': false, 'reason': 'dm'}), + ).get(room); + expect(state.enabled, isFalse); + expect(state.disabledReason, 'dm'); + }); + + test('unknown mode values are ignored', () async { + final state = await _api( + (_) async => _json(200, {'room': room, 'enabled': true, 'mode': 'weird'}), + ).get(room); + expect(state.mode, isNull); + }); + + test('POST 200 returns fresh state; 202 pending; 403 message', () async { + late Map body; + final ok = await _api((request) async { + body = jsonDecode(request.body) as Map; + return _json(200, { + 'ok': true, + 'status': 'done', + 'message': '已改为:只@才回', + 'state': {'room': room, 'enabled': true, 'mode': 'quiet'}, + }); + }).set(room, ReplyMode.quiet, requestId: 'r1'); + expect(body, { + 'room': room, + 'mode': 'quiet', + 'lead': null, + 'request_id': 'r1', + }); + expect(ok.done, isTrue); + expect(ok.state?.mode, ReplyMode.quiet); + + final pending = await _api( + (_) async => _json(202, {'ok': true, 'status': 'pending'}), + ).set(room, ReplyMode.all, requestId: 'r2'); + expect(pending.done, isFalse); + expect(pending.state, isNull); + + final denied = _api( + (_) async => _json(403, {'ok': false, 'error': '只有本群管理员和主人可以改'}), + ).set(room, ReplyMode.lead, lead: '@bot:x', requestId: 'r3'); + expect( + denied, + throwsA( + isA() + .having((e) => e.statusCode, 'code', 403) + .having((e) => e.message, 'message', '只有本群管理员和主人可以改'), + ), + ); + }); + + test('can_reset and default parse; missing field means no reset', () async { + final withReset = await _api( + (_) async => _json(200, { + 'room': room, + 'enabled': true, + 'mode': 'all', + 'default': 'lead', + 'can_reset': true, + }), + ).get(room); + expect(withReset.canReset, isTrue); + expect(withReset.defaultMode, ReplyMode.lead); + final older = await _api( + (_) async => _json(200, {'room': room, 'enabled': true, 'mode': 'all'}), + ).get(room); + expect(older.canReset, isFalse); + }); + + test('reset posts {room, reset:true, request_id}', () async { + late Map body; + final res = await _api((request) async { + body = jsonDecode(request.body) as Map; + return _json(200, { + 'ok': true, + 'status': 'done', + 'message': '已恢复默认:主管 AI 接话', + 'state': { + 'room': room, + 'enabled': true, + 'mode': 'lead', + 'is_default': true, + 'can_reset': false, + }, + }); + }).reset(room, requestId: 'r9'); + expect(body, {'room': room, 'reset': true, 'request_id': 'r9'}); + expect(res.done, isTrue); + expect(res.state?.isDefault, isTrue); + expect(res.state?.canReset, isFalse); + }); + + test('request ids are random 32-hex', () { + final a = ReplyModeApi.newRequestId(); + expect(a, matches(RegExp(r'^[0-9a-f]{32}$'))); + expect(a, isNot(ReplyModeApi.newRequestId())); + }); +} diff --git a/test_driver/reply_mode_preview.dart b/test_driver/reply_mode_preview.dart new file mode 100644 index 0000000..b8d09e2 --- /dev/null +++ b/test_driver/reply_mode_preview.dart @@ -0,0 +1,142 @@ +// SPDX-FileCopyrightText: 2026 IdealChat contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Dev-only preview of the "AI reply mode" row and page against a local stub +// (test_driver/reply_mode_stub.py). Not part of any release build. +// +// flutter build apk --debug -t test_driver/reply_mode_preview.dart \ +// --dart-define=IC_BOARD_API=http://127.0.0.1:8787/board/api +// adb reverse tcp:8787 tcp:8787 + +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:fluffychat/config/themes.dart'; +import 'package:fluffychat/l10n/l10n.dart'; +import 'package:fluffychat/pages/reply_mode/reply_mode_page.dart'; +import 'package:fluffychat/pages/reply_mode/reply_mode_tile.dart'; +import 'package:fluffychat/utils/idealchat/reply_mode_api.dart'; +import 'package:go_router/go_router.dart'; +import 'package:http/http.dart' as http; +import 'package:material_ui/material_ui.dart'; + +const _base = String.fromEnvironment( + 'IC_BOARD_API', + defaultValue: 'http://127.0.0.1:8787/board/api', +); + +final _api = ReplyModeApi( + baseUri: Uri.parse(_base), + accessToken: () => 'stub-token', + httpClient: http.Client(), +); + +const _rooms = { + '!admin:stub': '管理员的群(可改)', + '!member:stub': '普通成员的群(只读)', + '!auto:stub': 'AI 帮选的群', + '!off:stub': '任务管家不在的群', + '!down:stub': '接口出错的群', +}; + +final _themeMode = ValueNotifier(ThemeMode.light); +final _locale = ValueNotifier(null); + +void main() => runApp(const _PreviewApp()); + +final _router = GoRouter( + routes: [ + GoRoute(path: '/', builder: (context, state) => const _Home()), + GoRoute( + path: '/rooms/:roomid/details/reply_mode', + builder: (context, state) => + ReplyModePage(roomId: state.pathParameters['roomid']!, api: _api), + ), + ], +); + +class _PreviewApp extends StatelessWidget { + const _PreviewApp(); + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: Listenable.merge([_themeMode, _locale]), + builder: (context, _) => MaterialApp.router( + title: 'ReplyMode preview', + themeMode: _themeMode.value, + locale: _locale.value, + theme: FluffyThemes.buildTheme( + context, + Brightness.light, + const Color(0xFF18C6BE), + ), + darkTheme: FluffyThemes.buildTheme( + context, + Brightness.dark, + const Color(0xFF18C6BE), + ), + localizationsDelegates: [ + ...L10n.localizationsDelegates, + ...GlobalMaterialLocalizations.delegates, + ...GlobalCupertinoLocalizations.delegates, + ], + supportedLocales: L10n.supportedLocales, + routerConfig: _router, + ), + ); +} + +class _Home extends StatefulWidget { + const _Home(); + + @override + State<_Home> createState() => _HomeState(); +} + +class _HomeState extends State<_Home> { + String _room = _rooms.keys.first; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Scaffold( + appBar: AppBar( + title: Text(L10n.of(context).chatDetails), + actions: [ + IconButton( + icon: const Icon(Icons.dark_mode_outlined), + onPressed: () => + _themeMode.value = _themeMode.value == ThemeMode.dark + ? ThemeMode.light + : ThemeMode.dark, + ), + IconButton( + icon: const Icon(Icons.translate_outlined), + onPressed: () => _locale.value = _locale.value == null + ? const Locale('en') + : null, + ), + ], + ), + body: ListView( + children: [ + for (final entry in _rooms.entries) + RadioListTile( + value: entry.key, + groupValue: _room, + title: Text(entry.value), + dense: true, + onChanged: (room) => setState(() => _room = room!), + ), + Divider(color: theme.dividerColor), + ListTile( + leading: const CircleAvatar(child: Icon(Icons.tune_outlined)), + title: Text(L10n.of(context).chatPermissions), + subtitle: Text(L10n.of(context).whoCanPerformWhichAction), + ), + ReplyModeTile(key: ValueKey(_room), roomId: _room, api: _api), + Divider(color: theme.dividerColor), + ], + ), + ); + } +} diff --git a/test_driver/reply_mode_stub.py b/test_driver/reply_mode_stub.py new file mode 100644 index 0000000..06bad46 --- /dev/null +++ b/test_driver/reply_mode_stub.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2026 IdealChat contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Local stub of GET/POST /board/api/reply_mode (API_ReplyMode 20261029). + +Dev only, binds 127.0.0.1. Never logs request headers (no tokens in logs). +Rooms: !admin:stub (can_edit), !member:stub (read-only), !auto:stub (auto with +prev), !off:stub (enabled:false not_joined), !down:stub (HTTP 500). +The first POST of each run answers 202 (pending) to exercise the re-GET path. +""" +import json +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +LABELS = {"quiet": "只@才回", "lead": "主管 AI 接话", "all": "全部 AI 判断", "auto": "AI 帮选"} +AIS = [ + {"id": "@bot_claude_mac:ideal2001.com", "name": "Claude-mac 🤖"}, + {"id": "@bot_gpt:ideal2001.com", "name": "GPT 助手 🤖"}, + {"id": "@bot_qwen_with_a_very_long_display_name:ideal2001.com", "name": "通义千问(名字很长很长的一个 AI 账号)🤖"}, +] +NOW = time.time() +STATE = { + "!admin:stub": {"mode": "lead", "effective": "lead", "lead": AIS[0]["id"], "can_edit": True, "is_default": True, "log": []}, + "!member:stub": {"mode": "quiet", "effective": "quiet", "lead": None, "can_edit": False, "is_default": False, + "log": [{"ts": NOW - 86400, "by": "@zhangmacmini:ideal2001.com", "by_name": "zhangsir", "mode": "quiet", "effective": "quiet", "lead": None, "reason": None}]}, + "!auto:stub": {"mode": "auto", "effective": "all", "lead": None, "can_edit": True, "is_default": False, + "auto": {"applied": "all", "lead": None, "reason": "人少(2 人)、AI 少(3 个),每个 AI 都可以判断要不要接话", "since": NOW - 3600, "prev": "lead", "by": "@zhangmacmini:ideal2001.com"}, + "log": [ + {"ts": NOW - 3600, "by": "auto", "by_name": "AI 帮选", "mode": "auto", "effective": "all", "lead": None, "reason": "人少(2 人)、AI 少(3 个),每个 AI 都可以判断要不要接话"}, + {"ts": NOW - 7200, "by": "@zhangmacmini:ideal2001.com", "by_name": "zhangsir", "mode": "auto", "effective": "lead", "lead": None, "reason": None}, + ]}, +} +PENDING = {"first": True, "queued": None} + + +def view(room): + if room == "!off:stub": + return {"room": room, "enabled": False, "reason": "not_joined"} + s = STATE[room] + return { + "room": room, "enabled": True, "mode": s["mode"], "effective": s["effective"], "lead": s["lead"], + "auto": s.get("auto") if s["mode"] == "auto" else None, "default": "lead", "is_default": s["is_default"], + "ais": AIS, "can_edit": s["can_edit"], "choices": list(LABELS), "labels": LABELS, "hints": {}, + "log": s["log"][:5], "pending": None, "updated": NOW, + "can_reset": not s["is_default"], + } + + +def apply(room, mode, lead, by="@zhangmacmini:ideal2001.com"): + s = STATE[room] + prev = s["mode"] + s["mode"], s["is_default"] = mode, False + s["effective"] = "all" if mode == "auto" else mode + s["lead"] = lead if mode == "lead" else None + if mode == "auto": + s["auto"] = {"applied": "all", "lead": None, "reason": "(桩数据)人不多,让每个 AI 自己判断", "since": time.time(), "prev": prev, "by": by} + s["log"].insert(0, {"ts": time.time(), "by": by, "by_name": "zhangsir", "mode": mode, "effective": s["effective"], "lead": s["lead"], "reason": None}) + + +class H(BaseHTTPRequestHandler): + def log_message(self, fmt, *args): # method + path only, never headers + print(f"{self.command} {urlparse(self.path).path} -> {args[1] if len(args) > 1 else ''}", flush=True) + + def send(self, code, body): + data = json.dumps(body, ensure_ascii=False).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def authed(self): + if not self.headers.get("Authorization", "").startswith("Bearer "): + self.send(401, {"error": "令牌无效"}) + return False + return True + + def do_GET(self): + u = urlparse(self.path) + if u.path != "/board/api/reply_mode" or not self.authed(): + return self.send(404, {"error": "not found"}) if u.path != "/board/api/reply_mode" else None + if PENDING["queued"]: + apply(*PENDING["queued"]) + PENDING["queued"] = None + room = parse_qs(u.query).get("room", [""])[0] + if room == "!down:stub": + return self.send(500, {"error": "桩:服务出错"}) + if room not in STATE and room != "!off:stub": + return self.send(200, {"room": room, "enabled": False, "reason": "excluded"}) + self.send(200, view(room)) + + def do_POST(self): + if urlparse(self.path).path != "/board/api/reply_mode": + return self.send(404, {"error": "not found"}) + if not self.authed(): + return + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + room, mode, lead = body.get("room"), body.get("mode"), body.get("lead") + if body.get("reset") is True or mode == "default": # RESET_20261029 + if room not in STATE or not STATE[room]["can_edit"]: + return self.send(403, {"ok": False, "error": "只有本群管理员(权限 ≥50)和主人可以改,普通成员只能看。"}) + s = STATE[room] + if s["is_default"]: + return self.send(200, {"ok": True, "status": "done", "message": "没有变化", "id": 3, "state": view(room)}) + s.update(mode="lead", effective="lead", lead=None, is_default=True) + s.pop("auto", None) + s["log"].insert(0, {"ts": time.time(), "by": "@zhangmacmini:ideal2001.com", "by_name": "zhangsir", "mode": "lead", "effective": "lead", "lead": None, "reason": "恢复默认"}) + return self.send(200, {"ok": True, "status": "done", "message": "已恢复默认:主管 AI 接话", "id": 3, "state": view(room)}) + if room not in STATE: + return self.send(403, {"ok": False, "error": "只有本群管理员(权限 ≥50)和主人可以改,普通成员只能看。"}) + if mode not in LABELS: + return self.send(400, {"ok": False, "error": "模式不对"}) + if lead and lead not in {a["id"] for a in AIS}: + return self.send(400, {"ok": False, "error": "主管 AI 不在本群"}) + if not STATE[room]["can_edit"]: + return self.send(403, {"ok": False, "error": "只有本群管理员(权限 ≥50)和主人可以改,普通成员只能看。"}) + if PENDING["first"]: + PENDING["first"] = False + PENDING["queued"] = (room, mode, lead) + return self.send(202, {"ok": True, "status": "pending", "id": 1, "message": "已提交,几秒后生效"}) + apply(room, mode, lead) + self.send(200, {"ok": True, "status": "done", "message": f"已改为:{LABELS[mode]}", "id": 2, "state": view(room)}) + + +if __name__ == "__main__": + ThreadingHTTPServer(("127.0.0.1", 8787), H).serve_forever()