Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 补齐群归档和搜索找回 (#6068)
nanaco4ac0afe092e4
diff --git a/apps/desktop/src/renderer/__tests__/AppBadgeAttentionSync.test.tsx b/apps/desktop/src/renderer/__tests__/AppBadgeAttentionSync.test.tsxindex 640f195f0c..bf1ed258e6 100644--- a/apps/desktop/src/renderer/__tests__/AppBadgeAttentionSync.test.tsx+++ b/apps/desktop/src/renderer/__tests__/AppBadgeAttentionSync.test.tsx@@ -20,10 +20,21 @@ const state = vi.hoisted(() => ({isLoading: false,publish: vi.fn().mockResolvedValue(undefined),}));-const botState = vi.hoisted(() => ({ bots: [] as any[], unread: {} as Record<string, number>, groups: [] as any[], remote: [] as any[] }));+const botState = vi.hoisted(() => ({+ bots: [] as unknown[],+ unread: {} as Record<string, number>,+ groups: [] as unknown[],+ unreadGroups: new Set<string>(),+ remote: [] as unknown[],+}));vi.mock('@/features/bots/useBotUnreadSync', () => ({ useBotUnreadSync: () => {} }));vi.mock('@/features/bots/botStore', () => ({ useBotProfiles: () => botState.bots, useBotUnreadCounts: () => botState.unread }));vi.mock('@/features/bots/botGroupStore', () => ({ useBotGroupList: () => ({ groups: botState.groups }) }));+vi.mock('@/features/bots/botReadState', () => ({+ isBotGroupUnread: (group: { id: string }) => botState.unreadGroups.has(group.id),+ subscribeBotReadState: () => () => {},+ getBotLastReadAtMap: () => ({}),+}));vi.mock('@/features/bots/useRemoteBots', () => ({ useRemoteBotSync: () => {}, useRemoteBots: () => botState.remote }));vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({}) }));vi.mock('@/contexts/dataOwnerGeneration', () => ({@@ -70,7 +81,7 @@ import { useSessionDisplayRunningState } from '../features/cc-agent/hooks/useSesafterEach(() => {cleanup();- botState.bots = []; botState.unread = {}; botState.groups = []; botState.remote = [];+ botState.bots = []; botState.unread = {}; botState.groups = []; botState.unreadGroups = new Set(); botState.remote = [];vi.unstubAllGlobals();state.publish.mockClear();state.isLoading = false;@@ -231,3 +242,14 @@ it('maps each unread chat once and fences all Bot lanes out of event-backed Dockview.rerender(<AppBadgeAttentionSync />);expect(state.publish).toHaveBeenLastCalledWith(expect.objectContaining({ count: 3 }));});++it('excludes archived group unread state from the app badge', () => {+ vi.stubGlobal('electronAPI', { notificationSetAppAttentionCount: state.publish });+ botState.groups = [+ { id: 'active-group', archived: false },+ { id: 'archived-group', archived: true },+ ];+ botState.unreadGroups = new Set(['active-group', 'archived-group']);+ render(<AppBadgeAttentionSync />);+ expect(state.publish).toHaveBeenLastCalledWith(expect.objectContaining({ count: 4 }));+});diff --git a/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx b/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsxindex 3afe53a9c5..5ff4144c3c 100644--- a/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx+++ b/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx@@ -34,7 +34,7 @@ export function AppBadgeAttentionSync() {const remoteBots = useRemoteBots();useSyncExternalStore(subscribeBotReadState, readRevision, readRevision);const localTeammates = bots.filter(bot => bot.status !== 'archived' && bot.status !== 'deleting' && !bot.hiddenAt && (unread[bot.id] ?? 0) > 0).length- + groups.filter(isBotGroupUnread).length;+ + groups.filter(group => !group.archived && isBotGroupUnread(group)).length;const teammates = localTeammates + remoteBots.filter(isRemoteBotUnread).length;const owner = getDataOwnerGeneration();const { sessions, isLoading, error } = useCCSessions({ includeArchived: 'active' });diff --git a/apps/desktop/src/renderer/components/layout/__tests__/MainEntryRedirect.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/MainEntryRedirect.test.tsxindex d9b534793b..6b1debefad 100644--- a/apps/desktop/src/renderer/components/layout/__tests__/MainEntryRedirect.test.tsx+++ b/apps/desktop/src/renderer/components/layout/__tests__/MainEntryRedirect.test.tsx@@ -1,16 +1,23 @@// @vitest-environment jsdomimport { transferableAbortController } from 'node:util';+import { createInstance } from 'i18next';+import { I18nextProvider } from 'react-i18next';import { cleanup, render, screen, act, fireEvent } from '@testing-library/react';import { createMemoryRouter, Outlet, RouterProvider, useLocation } from 'react-router-dom';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { MainViewHistoryProvider } from '@/contexts/MainViewHistoryContext';import { readMainEntryRoute, rememberMainEntry } from '@/lib/mainEntryPreference';import { useActiveMainView } from '@/hooks/useActiveMainView';import { BotsListView } from '@/features/bots/BotsListView';+import en from '@/i18n/locales/en/common.json';import { MainEntryRedirect, useRememberMainEntry } from '../MainEntryRedirect';const auth = vi.hoisted(() => ({ dataOwnerId: 'account-a' as string | null }));vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => auth }));+const i18n = createInstance();+beforeAll(async () => {+ await i18n.init({ lng: 'en', resources: { en: { translation: en } } });+});function Layout() {useRememberMainEntry();@@ -24,9 +31,9 @@ function launch(path = '/') {{ path: '/bots', children: [{ path: 'list', element: <BotsListView /> }] },{ path: '*', element: <div /> },] }], { initialEntries: [path] });- const tree = () => <MainViewHistoryProvider ownerKey={auth.dataOwnerId ?? 'signed-out'} locationKey={router.state.location.key}>+ const tree = () => <I18nextProvider i18n={i18n}><MainViewHistoryProvider ownerKey={auth.dataOwnerId ?? 'signed-out'} locationKey={router.state.location.key}><RouterProvider key={auth.dataOwnerId} router={router} />- </MainViewHistoryProvider>;+ </MainViewHistoryProvider></I18nextProvider>;const view = render(tree());return { router, rerender: () => view.rerender(tree()) };}@@ -45,7 +52,7 @@ describe('main entry startup', () => {cleanup();launch();expect(screen.getByTestId('route').textContent).toBe('/bots/list');- expect(screen.getByRole('main').childElementCount).toBe(0);+ expect(screen.getByRole('main').textContent).toBe(en.bots.list.selectChat);expect(screen.queryByRole('dialog')).toBeNull();expect(JSON.stringify(localStorage)).not.toContain('private-bot');expect(JSON.stringify(localStorage)).not.toContain('private-task');@@ -58,7 +65,7 @@ describe('main entry startup', () => {launch();fireEvent.click(screen.getByText('Partners'));expect(screen.getByTestId('route').textContent).toBe('/bots/list');- expect(screen.getByRole('main').childElementCount).toBe(0);+ expect(screen.getByRole('main').textContent).toBe(en.bots.list.selectChat);});it('returns to the selected partner when switching areas without restarting', () => {launch('/bots/dash/session/dash-main');diff --git a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsxindex b9e27e5a58..dd01f1438a 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx@@ -10,7 +10,7 @@* 某一步进行中写「分工 k/n · 谁 正在做」,两者同样用运行中标记;安排待开始、做完一步* 等继续或没做完时,第二行换成对应的提示,提醒用户回来看看。*/-import type { ReactNode } from 'react';+import type { KeyboardEventHandler, MouseEventHandler, ReactNode } from 'react';import { Sparkles } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -54,6 +54,9 @@ export function BotGroupSidebarRow({now,selected,onOpenGroup,+ onContextMenu,+ onKeyDown,+ children,}: {group: BotGroupSummary;bots: readonly BotProfile[];@@ -61,6 +64,9 @@ export function BotGroupSidebarRow({now: number;selected: boolean;onOpenGroup: (groupId: string) => void;+ onContextMenu?: MouseEventHandler<HTMLButtonElement>;+ onKeyDown?: KeyboardEventHandler<HTMLButtonElement>;+ children?: ReactNode;}) {const { t } = useTranslation();@@ -88,6 +94,9 @@ export function BotGroupSidebarRow({};const renderSubtitle = (group: BotGroupSummary, mutedClass: string): ReactNode => {+ if (group.archived) return <span className={cn('min-w-0 flex-1 truncate text-12 leading-4', mutedClass)}>+ {previewText(group, null)}+ </span>;// Several Bots may think at once in a broadcast round's first circle.const speakers = group.speakingBotIds.map((botId) => group.members.find((member) => member.botId === botId))@@ -155,15 +164,20 @@ export function BotGroupSidebarRow({const mutedClass = selected ? 'opacity-70' : 'text-[var(--sidebar-list-muted)]';const timestamp = formatBotListTimestamp(- group.speakingBotIds.length > 0 ? now : group.lastMessage?.createdAt ?? group.updatedAt,+ !group.archived && group.speakingBotIds.length > 0 ? now : group.lastMessage?.createdAt ?? group.updatedAt,now,);return (+ <div className="relative"><buttonkey={group.id}type="button"+ data-bot-group-id={group.id}aria-current={selected ? 'page' : undefined}onClick={() => onOpenGroup(group.id)}+ onContextMenu={onContextMenu}+ onKeyDown={onKeyDown}+ aria-haspopup={onContextMenu ? 'menu' : undefined}className={cn('group flex w-full min-w-0 items-center gap-2.5 rounded-xl px-2.5 py-2 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring',selected@@ -173,8 +187,9 @@ export function BotGroupSidebarRow({><BotGroupDuoAvatar members={group.members} selected={selected} /><span className="flex min-w-0 flex-1 flex-col gap-0.5">- <span className="min-w-0 truncate text-14 leading-5" title={group.name}>- {group.name}+ <span className="flex min-w-0 items-center gap-1.5">+ <span className="min-w-0 truncate text-14 leading-5" title={group.name}>{group.name}</span>+ {group.archived && <span className={cn('shrink-0 text-11 leading-4', mutedClass)}>{t('bots.archived')}</span>}</span><span className="flex min-w-0 items-center gap-2">{renderSubtitle(group, mutedClass)}</span></span>@@ -188,5 +203,7 @@ export function BotGroupSidebarRow({<NavigationCountBadge count={isBotGroupUnread(group) ? 1 : 0} label={t('sidebar.teammateUnreadCount', { count: 1 })} className="ml-auto mt-1 w-fit" /></span></button>+ {children}+ </div>);}diff --git a/apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx b/apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsxindex decb2fde25..41a4c06e2f 100644--- a/apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx@@ -1,19 +1,32 @@-import { useContext, useEffect } from 'react';+import { useContext, useEffect, useRef } from 'react';import { MainViewHistoryContext } from '@/contexts/MainViewHistoryContext';-import { Outlet, useOutletContext, useParams, useLocation } from 'react-router-dom';+import { Outlet, useOutletContext, useParams, useLocation, useNavigate } from 'react-router-dom';import { useOwnTopNavScrollableRows } from '../feature-context';import { BotsSidebar } from './BotsSidebar';import { BotSettingsDrawer } from './BotSettingsDrawer';import { BotGroupSettingsDrawer } from './BotGroupSettingsDrawer';import { useBotProfiles } from './botStore';+import { useBotGroupSummary } from './botGroupStore';export function BotsFeatureLayout() {useOwnTopNavScrollableRows(false);const history = useContext(MainViewHistoryContext);- const { botId, deviceId } = useParams();+ const { botId, deviceId, groupId } = useParams();const location = useLocation();+ const navigate = useNavigate();const bots = useBotProfiles();+ const selectedGroup = useBotGroupSummary(groupId ?? null);+ const previousGroup = useRef(selectedGroup);+ useEffect(() => {+ const previous = previousGroup.current;+ previousGroup.current = selectedGroup;+ // Both archive entry points refresh this summary. Only clear a group that+ // became archived while selected; opening archived history stays supported.+ if (selectedGroup?.archived && previous?.id === selectedGroup.id && !previous.archived) {+ navigate('/bots/list', { replace: true });+ }+ }, [selectedGroup, navigate]);useEffect(() => {if (!history || deviceId || !botId || history.current.ignoredLocationKey === location.key) return;const bot = bots.find(candidate => candidate.id === botId);diff --git a/apps/desktop/src/renderer/features/bots/BotsListView.tsx b/apps/desktop/src/renderer/features/bots/BotsListView.tsxindex 90a89b512f..3c659e8c9e 100644--- a/apps/desktop/src/renderer/features/bots/BotsListView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsListView.tsx@@ -1,8 +1,18 @@+import { useTranslation } from 'react-i18next';+/*** BotsFeatureLayout already supplies the partner list in its sidebar. Leave the* content pane unselected on startup: /bots selects Cindy and /bots/roster opens* the creation dialog. Neither belongs to passive navigation restoration.*/export function BotsListView() {- return <main className="h-full" />;+ const { t } = useTranslation();++ return (+ <main className="flex h-full items-center justify-center p-6">+ <p className="text-center text-14 leading-[1.43] text-[var(--text-tertiary)]">+ {t('bots.list.selectChat')}+ </p>+ </main>+ );}diff --git a/apps/desktop/src/renderer/features/bots/BotsSidebar.tsx b/apps/desktop/src/renderer/features/bots/BotsSidebar.tsxindex a564c5a77b..b9f8504937 100644--- a/apps/desktop/src/renderer/features/bots/BotsSidebar.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsSidebar.tsx@@ -2,9 +2,11 @@ import { useNavigationAttention } from '@/lib/navigationAttentionStore';import { NavigationCountBadge } from '@/components/sidebar/NavigationCountBadge';import { BotGenerationLabel } from './BotGenerationLabel';import { botRosterLabel } from '../../../shared/botCreation';-import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';import {AlertTriangle,+ Archive,+ ArchiveRestore,ArrowLeft,Bot,Copy,@@ -12,13 +14,17 @@ import {EyeOff,Pin,Search,+ Settings,Trash2,} from 'lucide-react';-import { useLocation, useNavigate, useParams } from 'react-router-dom';+import { matchPath, useLocation, useNavigate, useParams } from 'react-router-dom';import { useTranslation } from 'react-i18next';import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';import { cn } from '@/lib/utils';+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';+import type { BotGroupSummary } from '../../../shared/botGroupChat';import * as sessionService from '@/lib/sessionService';import { isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';import {@@ -50,7 +56,9 @@ import { BotAvatar } from './BotAvatar';import { BotCreateMenu } from './BotCreateMenu';import { BotDeleteDialog } from './BotDeleteDialog';import { BotGroupSidebarRow } from './BotGroupSidebarRow';-import { useBotGroupList } from './botGroupStore';+import { refreshBotGroups, useBotGroupList } from './botGroupStore';+import { BOT_GROUP_SETTINGS_PARAM } from './botGroupPresentation';+import { chatErrorKey } from './chatError';import { subscribeBotReadState, getBotLastReadAtMap } from './botReadState';import { ChatJoinButton } from './ChatServerControls';import { isBotGroupLaneSession, withoutBotGroupLanes } from './botGroupLane';@@ -85,10 +93,13 @@ const UNREAD_BADGE_CLASS =function BotsSidebarContent() {const { navigateToView } = useActiveMainView();const { t } = useTranslation();+ const { confirm } = useConfirmDialog();const navigationCounts = useNavigationAttention();const navigate = useNavigate();const { pathname } = useLocation();const { botId, sessionId, deviceId, groupId } = useParams();+ // The registered sidebar slot can sit outside the group's route context.+ const selectedGroupId = matchPath('/bots/groups/:groupId', pathname)?.params.groupId;const cloud = useCompanionCloud();const rosterRemoteBots = useRemoteBots();// One row per companion, on its main computer (offline rows for computers never listed here).@@ -109,10 +120,15 @@ function BotsSidebarContent() {const archivedBots = bots.filter((bot) => bot.status === 'archived');const collapsed = useSidebarCollapsedState();const [query, setQuery] = useState('');+ const [searchFocused, setSearchFocused] = useState(false);const [showHidden, setShowHidden] = useState(false);+ const [archiveBusy, setArchiveBusy] = useState(false);+ const archiveBusyRef = useRef(false);+ const [archiveError, setArchiveError] = useState('');const [now, setNow] = useState(() => Date.now());const [contextMenu, setContextMenu] = useState<{- botId: string;+ kind: 'bot' | 'group';+ id: string;x: number;y: number;} | null>(null);@@ -120,12 +136,51 @@ function BotsSidebarContent() {const menuOriginRef = useRef<HTMLButtonElement | null>(null);const menuPointerDownRef = useRef(false);const menuRestoreFocusRef = useRef(true);+ const searchInputRef = useRef<HTMLInputElement | null>(null);+ const sidebarRef = useRef<HTMLDivElement | null>(null);+ const previousSelectedGroupRef = useRef(groups.find(group => group.id === selectedGroupId));+ const pendingArchiveFocusRef = useRef<{ groupId: string; archived: boolean; origin: HTMLElement | null } | null>(null);- const openBotContextMenu = (botId: string, origin: HTMLButtonElement, x: number, y: number) => {+ const openContextMenu = (kind: 'bot' | 'group', id: string, origin: HTMLButtonElement, x: number, y: number) => {menuOriginRef.current = origin;menuPointerDownRef.current = false;menuRestoreFocusRef.current = true;- setContextMenu({ botId, x, y });+ setContextMenu({ kind, id, x, y });+ };++ const changeGroupArchive = async (group: BotGroupSummary) => {+ if (archiveBusyRef.current) return;+ archiveBusyRef.current = true;+ setArchiveBusy(true);+ setArchiveError('');+ const owner = getDataOwnerGeneration();+ const origin = menuOriginRef.current;+ let focusArchived = !!group.archived;+ const actionKey = 'bots.groupChat.server.settings.' + (group.archived ? 'unarchive' : 'archive');+ try {+ const accepted = await confirm({ presentation: 'standard', title: t(actionKey),+ description: t(actionKey + 'Hint'), confirmText: t(actionKey),+ cancelText: t('bots.cancel'), confirmVariant: 'destructive' });+ if (!accepted || !isDataOwnerGenerationCurrent(owner)) return;+ const result = await window.electronAPI.maker.chatServer.manage({ groupId: group.id,+ action: { type: 'archive', archived: !group.archived, expectedRevision: group.revision! } });+ if (!isDataOwnerGenerationCurrent(owner)) return;+ if (!result.ok) setArchiveError(t(chatErrorKey(result.errorCode)));+ else {+ focusArchived = !group.archived;+ refreshBotGroups();+ }+ } catch {+ if (isDataOwnerGenerationCurrent(owner)) setArchiveError(t(chatErrorKey('REQUEST_FAILED')));+ } finally {+ // Cancelled and failed confirmations also lose their menu-item opener.+ // Recover to the unchanged row after the dialog releases focus.+ if (isDataOwnerGenerationCurrent(owner)) {+ pendingArchiveFocusRef.current = { groupId: group.id, archived: focusArchived, origin };+ }+ archiveBusyRef.current = false;+ setArchiveBusy(false);+ }};/*@@ -174,9 +229,84 @@ function BotsSidebarContent() {...remoteBots.filter(bot => (!hasMultipleCindys || !isCindyDeviceBot(bot)) && (!normalizedQuery || `${bot.name} ${bot.description} ${bot.deviceName}`.toLocaleLowerCase().includes(normalizedQuery))),];const rosterSize = groups.length + rosterBots.length + remoteBots.length - (hasMultipleCindys ? cindyOptions.length - 1 : 0);- const showSearch = rosterSize >= 8 || normalizedQuery.length > 0;- const visibleGroups = groups.filter(group => !normalizedQuery ||- `${group.name} ${group.members.map(member => member.name).join(' ')}`.toLocaleLowerCase().includes(normalizedQuery));+ const hasArchivedGroups = groups.some(group => group.archived);+ const showSearch = searchFocused || rosterSize >= 8 || normalizedQuery.length > 0 ||+ hasArchivedGroups;+ const matchesGroup = (group: BotGroupSummary) => !normalizedQuery ||+ `${group.name} ${group.members.map(member => member.name).join(' ')}`.toLocaleLowerCase().includes(normalizedQuery);+ const visibleGroups = groups.filter(group =>+ (!group.archived || normalizedQuery.length > 0) && matchesGroup(group));++ useEffect(() => {+ const previous = previousSelectedGroupRef.current;+ previousSelectedGroupRef.current = groups.find(group => group.id === selectedGroupId);+ // Settings can archive the selected group without going through the row+ // menu. Reuse its recovery after the drawer and confirmation release focus.+ if (previous && !previous.archived && !pendingArchiveFocusRef.current &&+ (selectedGroupId === previous.id || pathname === '/bots/list') &&+ groups.some(group => group.id === previous.id && group.archived)) {+ pendingArchiveFocusRef.current = { groupId: previous.id, archived: true, origin: null };+ }+ }, [groups, selectedGroupId, pathname]);++ useEffect(() => {+ const pending = pendingArchiveFocusRef.current;+ if (!pending) return;+ const updatedGroup = groups.find(group => group.id === pending.groupId);+ if (!updatedGroup || updatedGroup.archived !== pending.archived) return;++ let timer: number | undefined;+ let cancelled = false;+ const restoreFocus = () => {+ if (cancelled) return;+ // The confirmation dialog keeps its AlertDialog mounted for its closing+ // animation. Wait until Radix has released focus before moving it to the+ // row that replaced the original trigger.+ if (document.querySelector('[role="alertdialog"]')) {+ timer = window.setTimeout(restoreFocus, 50);+ return;+ }++ // Focus recovery is only for the original keyboard path. If the user+ // has already moved focus to another row, the search field, or any+ // other control while the refresh was in flight, leave that choice+ // untouched. A body focus means the original row was unmounted.+ const active = document.activeElement;+ if (active !== pending.origin && active !== document.body) {+ pendingArchiveFocusRef.current = null;+ return;+ }++ const row = Array.from(document.querySelectorAll<HTMLElement>('[data-bot-group-id]'))+ .find(element => element.dataset.botGroupId === pending.groupId);+ const rowIsVisible = visibleGroups.some(group => group.id === pending.groupId);+ if (row && rowIsVisible) {+ pendingArchiveFocusRef.current = null;+ row.focus();+ return;+ }++ // Archived groups disappear from the default list and remain searchable.+ // Keep focus on that visible recovery path when the row is removed.+ if (pending.archived) {+ pendingArchiveFocusRef.current = null;+ const target = searchInputRef.current ?? sidebarRef.current?.querySelector<HTMLButtonElement>('button');+ target?.focus();+ return;+ }++ // The user may have changed the search while the request was in flight.+ // Do not keep a stale request that could steal focus later when the filter+ // is cleared.+ pendingArchiveFocusRef.current = null;+ };++ timer = window.setTimeout(restoreFocus, 0);+ return () => {+ cancelled = true;+ if (timer !== undefined) window.clearTimeout(timer);+ };+ }, [groups, visibleGroups]);const visibleChats = [...visibleBots.map(bot => ({ kind: 'bot' as const, bot,pinned: 'pinnedAt' in bot && Boolean(bot.pinnedAt),@@ -274,9 +404,9 @@ function BotsSidebarContent() {// 曾经这里还按 bot 逐个拉 `getBotHealth` 只为在行尾画一个状态图标。图标下线之后// 这一轮 N 次 IPC 也一起下线——列表不再为一个不显示的东西查询。- const renderBotContextMenu = (bot: BotProfile, selected: boolean) => (+ const renderContextMenu = (kind: 'bot' | 'group', id: string, children: ReactNode) => (<DropdownMenu- open={contextMenu?.botId === bot.id}+ open={contextMenu?.kind === kind && contextMenu.id === id}onOpenChange={(open) => { if (!open) setContextMenu(null); }}><DropdownMenuTrigger asChild>@@ -312,6 +442,12 @@ function BotsSidebarContent() {}}}>+ {children}+ </DropdownMenuContent>+ </DropdownMenu>+ );++ const renderBotContextMenu = (bot: BotProfile, selected: boolean) => renderContextMenu('bot', bot.id, <><DropdownMenuItem onSelect={() => void setBotPinned(bot.id, !bot.pinnedAt)}><Pin size={14} className="mr-2" />{t(bot.pinnedAt ? 'bots.list.unpin' : 'bots.list.pin')}@@ -351,13 +487,40 @@ function BotsSidebarContent() {<Trash2 size={14} className="mr-2" />{t('bots.lifecycle.delete')}</DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ </>);++ const renderGroupRow = (group: BotGroupSummary) => (+ <BotGroupSidebarRow key={'group:' + group.id} group={group} bots={bots}+ islandActivity={islandActivity} now={now} selected={group.id === groupId}+ onOpenGroup={id => navigate('/bots/groups/' + encodeURIComponent(id))}+ onContextMenu={event => {+ event.preventDefault(); event.stopPropagation();+ openContextMenu('group', group.id, event.currentTarget, event.clientX, event.clientY);+ }}+ onKeyDown={event => {+ if (event.key !== 'ContextMenu' && !(event.key === 'F10' && event.shiftKey)) return;+ event.preventDefault();+ const rect = event.currentTarget.getBoundingClientRect();+ openContextMenu('group', group.id, event.currentTarget, rect.left + 10, rect.bottom);+ }}>+ {renderContextMenu('group', group.id, <>+ <DropdownMenuItem onSelect={() => navigate('/bots/groups/' + encodeURIComponent(group.id) + '?' + BOT_GROUP_SETTINGS_PARAM + '=1')}>+ <Settings size={14} className="mr-2" />{t('bots.groupChat.settings.title')}+ </DropdownMenuItem>+ {group.serverBacked && group.members.some(member => member.isOwned && (member.role === 'owner' || member.role === 'admin')) && <>+ <DropdownMenuSeparator />+ <DropdownMenuItem disabled={archiveBusy} onSelect={() => void changeGroupArchive(group)}>+ {group.archived ? <ArchiveRestore size={14} className="mr-2" /> : <Archive size={14} className="mr-2" />}+ {t('bots.groupChat.server.settings.' + (group.archived ? 'unarchive' : 'archive'))}+ </DropdownMenuItem>+ </>}+ </>)}+ </BotGroupSidebarRow>);if (collapsed) {return (- <div className="flex flex-col items-center gap-2 px-2 pt-3">+ <div ref={sidebarRef} className="flex flex-col items-center gap-2 px-2 pt-3">{(pathname === '/bots' || pathname.startsWith('/bots/')) && (<SidebarIconButtonicon={ArrowLeft}@@ -404,8 +567,11 @@ function BotsSidebarContent() {className="pointer-events-none absolute left-5 top-1/2 -translate-y-1/2 text-[var(--sidebar-list-muted)]"/><input+ ref={searchInputRef}value={query}onChange={(event) => setQuery(event.target.value)}+ onFocus={() => setSearchFocused(true)}+ onBlur={() => setSearchFocused(false)}placeholder={t('bots.list.searchPlaceholder')}aria-label={t('bots.list.search')}className="h-7 w-full rounded-lg border border-[var(--border-default)] bg-transparent pl-7 pr-2 text-11 text-[var(--sidebar-nav-text)] outline-none placeholder:text-[var(--sidebar-list-muted)] focus:border-[var(--focus-ring)]"@@ -413,17 +579,18 @@ function BotsSidebarContent() {</label>) : null}+ {archiveError && <p role="alert" className="mb-2 px-2.5 text-12 text-[var(--error-fg)]">{archiveError}</p>}+<div className="min-h-0 flex-1 overflow-y-auto pb-3">- {roster.visible.length === 0 && roster.hidden.length === 0 && archivedBots.length === 0 && remoteBots.length === 0 && groups.length === 0 ? (+ {roster.visible.length === 0 && roster.hidden.length === 0 && archivedBots.length === 0 && remoteBots.length === 0 && visibleGroups.length === 0 ? (<div className="px-3 py-3">- <BotCreateMenu label={t('bots.add')} />+ {normalizedQuery ? <p className="text-12 text-[var(--sidebar-list-muted)]">{t('bots.list.noResults')}</p>+ : <BotCreateMenu label={t('bots.add')} />}</div>) : (<div className="flex flex-col gap-1">{visibleChats.map(entry => {- if (entry.kind === 'group') return <BotGroupSidebarRow key={`group:${entry.group.id}`} group={entry.group}- bots={bots} islandActivity={islandActivity} now={now} selected={entry.group.id === groupId}- onOpenGroup={id => navigate(`/bots/groups/${encodeURIComponent(id)}`)} />;+ if (entry.kind === 'group') return renderGroupRow(entry.group);if (entry.kind === 'cindy') {if (!currentCindy) return null;const bot = currentCindy.bot;@@ -444,13 +611,13 @@ function BotsSidebarContent() {onSelect={option => navigate(option.route)}onContextMenu={local ? event => {event.preventDefault(); event.stopPropagation();- openBotContextMenu(local.id, event.currentTarget, event.clientX, event.clientY);+ openContextMenu('bot', local.id, event.currentTarget, event.clientX, event.clientY);} : undefined}onKeyDown={local ? event => {if (event.key !== 'ContextMenu' && !(event.key === 'F10' && event.shiftKey)) return;event.preventDefault();const rect = event.currentTarget.getBoundingClientRect();- openBotContextMenu(local.id, event.currentTarget, rect.left + 10, rect.bottom);+ openContextMenu('bot', local.id, event.currentTarget, rect.left + 10, rect.bottom);} : undefined}>{local ? renderBotContextMenu(local, selected) : null}</CindyDeviceRow>;@@ -521,7 +688,7 @@ function BotsSidebarContent() {onContextMenu={(event) => {event.preventDefault();event.stopPropagation();- openBotContextMenu(bot.id, event.currentTarget, event.clientX, event.clientY);+ openContextMenu('bot', bot.id, event.currentTarget, event.clientX, event.clientY);}}onKeyDown={(event) => {if (event.key !== 'ContextMenu' && !(event.key === 'F10' && event.shiftKey)) {@@ -529,7 +696,7 @@ function BotsSidebarContent() {}event.preventDefault();const rect = event.currentTarget.getBoundingClientRect();- openBotContextMenu(bot.id, event.currentTarget, rect.left + 10, rect.bottom);+ openContextMenu('bot', bot.id, event.currentTarget, rect.left + 10, rect.bottom);}}className="flex min-w-0 flex-1 items-center gap-2.5 rounded-xl px-2.5 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">diff --git a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsxindex ebe3e0f1dd..6ee4bd7229 100644--- a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx@@ -29,6 +29,7 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {const me = group.members.find(m => m.isSelf);const owner = group.members.some(m => m.isOwned && m.role === 'owner');const manager = owner || group.members.some(m => m.isOwned && m.role === 'admin');+ const soleOwner = me?.role === 'owner' && group.members.length === 1;const [name, setName] = useState(group.name);const [topic, setTopic] = useState(group.topic ?? '');const [description, setDescription] = useState(group.description ?? '');@@ -68,9 +69,9 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {} catch { if (isDataOwnerGenerationCurrent(owner)) setError(t(chatErrorKey('REQUEST_FAILED'))); return false; }finally { busyRef.current = false; setBusy(false); }}- async function confirmed(action: ChatGroupAction, title: string, note: string, exit = false) {+ async function confirmed(action: ChatGroupAction, title: string, note: string, exit = false, confirmText = t(key('confirm'))) {const owner = getDataOwnerGeneration();- if (await confirm({ presentation: 'standard', title, description: note, confirmText: t(key('confirm')),+ if (await confirm({ presentation: 'standard', title, description: note, confirmText,cancelText: t('bots.cancel'), confirmVariant: 'destructive' }) && isDataOwnerGenerationCurrent(owner)) await mutate(action, exit);}const profileOpenChange = useCallback((open: boolean) => {@@ -202,9 +203,12 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {options={addable.map(bot => ({ value: bot.actorId, label: bot.name }))}onValueChange={actorId => void mutate({ type: 'member', actorId, action: 'invite' })} />}</section>- <div className="flex flex-wrap gap-2 border-t border-[var(--border-default)] pt-5">- <Button variant="secondary" size="sm" disabled={busy || !me} onClick={() => void confirmed({ type: 'member', actorId: me!.actorId!, action: 'leave' }, t(key('leave')), t(key('leaveHint')), true)}>{t(key('leave'))}</Button>- {manager && <Button variant="secondary" size="sm" disabled={busy} onClick={() => void confirmed({ type: 'archive', archived: !group.archived, expectedRevision: group.revision! }, t(key(group.archived ? 'unarchive' : 'archive')), t(key(group.archived ? 'unarchiveHint' : 'archiveHint')))}>{t(key(group.archived ? 'unarchive' : 'archive'))}</Button>}+ <div className="space-y-3 border-t border-[var(--border-default)] pt-5">+ {soleOwner && !group.archived && <p className="text-13 text-[var(--text-secondary)]">{t(key('soleOwnerHint'))}</p>}+ <div className="flex flex-wrap gap-2">+ {!soleOwner && <Button variant="secondary" size="sm" disabled={busy || !me} onClick={() => void confirmed({ type: 'member', actorId: me!.actorId!, action: 'leave' }, t(key('leave')), t(key('leaveHint')), true)}>{t(key('leave'))}</Button>}+ {manager && <Button variant="secondary" size="sm" disabled={busy} onClick={() => void confirmed({ type: 'archive', archived: !group.archived, expectedRevision: group.revision! }, t(key(group.archived ? 'unarchive' : 'archive')), t(key(group.archived ? 'unarchiveHint' : 'archiveHint')), false, t(key(group.archived ? 'unarchive' : 'archive')))}>{t(key(group.archived ? 'unarchive' : 'archive'))}</Button>}+ </div></div></div><ProfileEditDialog open={editingProfile} onOpenChange={profileOpenChange} />diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex d1a192e7ef..7cd8105437 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@ -327,6 +327,22 @@ beforeEach(() => {afterEach(() => { cleanup(); vi.unstubAllGlobals(); });describe('BotGroupChatView', () => {+ it('keeps archived history readable and restores the composer only after the group is unarchived', async () => {+ const archived = detail({ serverBacked: true, archived: true,+ messages: [msg({ content: 'Preserved group history' })],+ });+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: archived });+ renderView();+ await screen.findByText('Preserved group history');+ expect(screen.getByText('bots.groupChat.server.settings.archived')).toBeTruthy();+ expect(screen.queryByRole('textbox')).toBeNull();+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: { ...archived, archived: false } });+ act(() => { mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'updated' })); });+ await screen.findByRole('textbox');+ expect(screen.getByText('Preserved group history')).toBeTruthy();+ expect(screen.queryByText('bots.groupChat.server.settings.archived')).toBeNull();+ });+function mockThreadMotion(duration: string) {const style = document.createElement('style');style.textContent = `aside { --motion-base: ${duration}; --motion-ease-move: linear; }`;diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsxindex ad11d8bf9d..38a7b331aa 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx@@ -21,8 +21,38 @@ function group(owned = false): BotGroupSummary {}beforeEach(() => {vi.clearAllMocks(); mocks.manage.mockResolvedValue({ ok: true }); mocks.ownedBots.mockResolvedValue({ ok: true, bots: [] });+ mocks.confirm.mockResolvedValue(true);Object.defineProperty(window, 'electronAPI', { configurable: true, value: { maker: { chatServer: mocks } } });});++it('guides a sole owner to archive instead of offering an impossible leave', async () => {+ const alone = group();+ alone.members = [{ ...alone.members[0]!, role: 'owner' }];+ render(<MemoryRouter><ChatGroupSettings group={alone} /></MemoryRouter>);+ expect(screen.queryByRole('button', { name: key('leave') })).toBeNull();+ expect(screen.getByText(key('soleOwnerHint'))).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: key('archive') }));+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledWith({ groupId: 'room',+ action: { type: 'archive', archived: true, expectedRevision: 1 },+ }));+ expect(mocks.confirm).toHaveBeenCalledWith(expect.objectContaining({+ description: key('archiveHint'), confirmText: key('archive'),+ }));+ expect(mocks.refresh).toHaveBeenCalledOnce();+});++it('keeps a sole archived owner in the group and offers restoring its history', async () => {+ const alone = group();+ alone.archived = true;+ alone.members = [{ ...alone.members[0]!, role: 'owner' }];+ render(<MemoryRouter><ChatGroupSettings group={alone} /></MemoryRouter>);+ expect(screen.queryByRole('button', { name: key('leave') })).toBeNull();+ expect(screen.queryByText(key('soleOwnerHint'))).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: key('unarchive') }));+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledWith({ groupId: 'room',+ action: { type: 'archive', archived: false, expectedRevision: 1 },+ }));+});afterEach(cleanup);it('lets a member change their own nickname while keeping another owner’s grant read-only', async () => {render(<MemoryRouter><ChatGroupSettings group={group()} /></MemoryRouter>);diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsxindex 5ac012815b..c659828f08 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupSidebar.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { cloneElement, type ReactElement, type ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -29,6 +29,8 @@ const mocks = vi.hoisted(() => ({profiles: [] as unknown[],groups: [] as BotGroupSummary[],params: {} as { botId?: string; groupId?: string },+ pathname: '/bots',+ collapsed: false,registered: { node: null as ReactNode },islandActivity: new Map<string, { sessionId: string; phase: string; workingPhase?: string }>(),runningStatusOptions: null as null | {@@ -39,6 +41,18 @@ const mocks = vi.hoisted(() => ({laneSentinel: Symbol('lane'),ownedTitle: vi.fn(),getSession: vi.fn(),+ confirm: vi.fn(),+ manage: vi.fn(),+ refreshGroups: vi.fn(),+ ownerGeneration: 1,+}));++vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useConfirmDialog: () => ({ confirm: mocks.confirm }),+}));+vi.mock('@/contexts/dataOwnerGeneration', () => ({+ getDataOwnerGeneration: () => mocks.ownerGeneration,+ isDataOwnerGenerationCurrent: (generation: number) => generation === mocks.ownerGeneration,}));vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => [] }));@@ -60,13 +74,14 @@ vi.mock('@/lib/sessionEventNotification', () => ({sendSessionEventNotification: (...args: unknown[]) => mocks.sendNotification(...args),}));vi.mock('@/lib/sessionService', () => ({ get: (...args: unknown[]) => mocks.getSession(...args) }));-vi.mock('react-router-dom', () => ({+vi.mock('react-router-dom', async importOriginal => ({+ ...await importOriginal<typeof import('react-router-dom')>(),useNavigate: () => mocks.navigate,- useLocation: () => ({ pathname: '/bots', search: '', hash: '' }),+ useLocation: () => ({ pathname: mocks.pathname, search: '', hash: '' }),useParams: () => mocks.params,}));vi.mock('../../feature-context', () => ({- useSidebarCollapsedState: () => false,+ useSidebarCollapsedState: () => mocks.collapsed,useRegisterSidebarUpper: (node: ReactNode) => {mocks.registered.node = node;},@@ -83,6 +98,7 @@ vi.mock('../botStore', () => ({}));vi.mock('../botGroupStore', () => ({useBotGroupList: () => ({ groups: mocks.groups, loaded: true }),+ refreshBotGroups: mocks.refreshGroups,}));vi.mock('../BotDeleteDialog', () => ({ BotDeleteDialog: () => null }));vi.mock('../BotGroupCreateDialog', () => ({@@ -160,7 +176,13 @@ beforeEach(() => {mocks.sendNotification.mockReset();mocks.ownedTitle.mockReset().mockResolvedValue(null);mocks.getSession.mockReset();+ mocks.confirm.mockReset().mockResolvedValue(true);+ mocks.manage.mockReset().mockResolvedValue({ ok: true });+ mocks.refreshGroups.mockReset();+ mocks.ownerGeneration = 1;mocks.params = {};+ mocks.pathname = '/bots';+ mocks.collapsed = false;mocks.groups = [];mocks.islandActivity = new Map();mocks.runningStatusOptions = null;@@ -171,13 +193,320 @@ beforeEach(() => {Object.defineProperty(window, 'electronAPI', {configurable: true,writable: true,- value: { localDb: { messages: { onCreated: () => () => undefined } } },+ value: { localDb: { messages: { onCreated: () => () => undefined } }, maker: { chatServer: {+ manage: mocks.manage, status: async () => ({ enabled: false }),+ } } },});});-afterEach(cleanup);+afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});describe('BotsSidebar group chats', () => {+ it('hides archived groups without an archive entry and finds their history through search', async () => {+ mocks.groups = [group(), group({ id: 'saved', name: '已完成的旅行', archived: true })];+ const view = await renderSidebar();+ expect(screen.getByText('周末出游')).toBeTruthy();+ expect(screen.queryByText('已完成的旅行')).toBeNull();+ expect(screen.queryByTestId('bot-archived-groups-toggle')).toBeNull();+ const input = screen.getByRole('textbox', { name: 'bots.list.search' });+ fireEvent.change(input, { target: { value: '已完成的旅行' } });+ expect(screen.getByText('bots.archived')).toBeTruthy();+ fireEvent.click(screen.getByText('已完成的旅行'));+ expect(mocks.navigate).toHaveBeenCalledWith('/bots/groups/saved');+ fireEvent.change(input, { target: { value: '' } });+ expect(screen.queryByText('已完成的旅行')).toBeNull();+ mocks.groups = mocks.groups.map(item => ({ ...item, archived: false }));+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ expect(screen.getByText('已完成的旅行')).toBeTruthy();+ });++ it('searches archived group names and members without showing them in the default list', async () => {+ mocks.profiles = [];+ mocks.groups = Array.from({ length: 8 }, (_, i) => group({ id: 'saved-' + i,+ name: '历史群 ' + i, archived: true, members: i === 0 ? group().members : [],+ }));+ await renderSidebar();+ const input = screen.getByRole('textbox', { name: 'bots.list.search' });+ fireEvent.change(input, { target: { value: '历史群 0' } });+ expect(screen.getByText('历史群 0')).toBeTruthy();+ expect(screen.queryByText('历史群 1')).toBeNull();+ fireEvent.change(input, { target: { value: '小满' } });+ expect(screen.getByText('历史群 0')).toBeTruthy();+ fireEvent.change(input, { target: { value: 'missing' } });+ expect(screen.queryByText('历史群 0')).toBeNull();+ expect(screen.getByText('bots.list.noResults')).toBeTruthy();+ });++ it('keeps an empty default list searchable when only one archived group remains and no bots exist', async () => {+ mocks.profiles = [];+ mocks.groups = [group({ archived: true, members: [{ ...group().members[0]!, name: 'Research Lead' }] })];+ await renderSidebar();+ expect(screen.queryByText('周末出游')).toBeNull();+ expect(document.querySelector('[data-bot-group-id]')).toBeNull();+ expect(screen.queryByTestId('bot-archived-groups-toggle')).toBeNull();+ const input = screen.getByRole('textbox', { name: 'bots.list.search' });+ fireEvent.change(input, { target: { value: ' RESEARCH ' } });+ expect(screen.getByText('周末出游')).toBeTruthy();+ expect(screen.getByText('bots.archived')).toBeTruthy();+ fireEvent.change(input, { target: { value: ' ' } });+ expect(screen.queryByText('周末出游')).toBeNull();+ });++ const managedGroup = (archived = false) => group({ serverBacked: true, archived, revision: 7,+ members: [{ ...group().members[0]!, isOwned: true, role: 'owner' }],+ });+ const archiveKey = (archived = false) => 'bots.groupChat.server.settings.' + (archived ? 'unarchive' : 'archive');+ async function selectArchive(archived = false) {+ fireEvent.contextMenu(screen.getByText('周末出游').closest('button')!, { clientX: 20, clientY: 30 });+ fireEvent.click(await screen.findByRole('menuitem', { name: archiveKey(archived) }));+ }++ it.each([false, true])('confirms archive change (%s) with the current revision and waits for refresh', async archived => {+ mocks.groups = [managedGroup(archived)];+ const view = await renderSidebar();+ if (archived) fireEvent.change(screen.getByRole('textbox', { name: 'bots.list.search' }), { target: { value: '周末' } });+ await selectArchive(archived);+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledWith({ groupId: 'g1', action: {+ type: 'archive', archived: !archived, expectedRevision: 7,+ } }));+ expect(mocks.confirm).toHaveBeenCalledWith(expect.objectContaining({ title: archiveKey(archived),+ confirmText: archiveKey(archived),+ description: 'bots.groupChat.server.settings.' + (archived ? 'unarchiveHint' : 'archiveHint'),+ }));+ expect(mocks.refreshGroups).toHaveBeenCalledOnce();+ expect(screen.getByText('周末出游')).toBeTruthy();+ mocks.groups = [managedGroup(!archived)];+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ if (!archived) expect(screen.queryByText('周末出游')).toBeNull();+ else expect(screen.getByText('周末出游')).toBeTruthy();+ });++ it('restores visible search focus after keyboard archive removes a default row', async () => {+ const focus = vi.spyOn(HTMLElement.prototype, 'focus');+ mocks.groups = [managedGroup()];+ const view = await renderSidebar();+ const row = screen.getByText('周末出游').closest('button')!;+ fireEvent.keyDown(row, { key: 'F10', shiftKey: true });+ fireEvent.click(await screen.findByRole('menuitem', { name: archiveKey() }));+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledOnce());++ mocks.groups = [managedGroup(true)];+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'bots.list.search' })));+ // Let the browser reveal the search field if needed.+ expect(focus).toHaveBeenLastCalledWith();+ });++ it.each([false, true])('recovers focus when settings archives the selected group (route already cleared: %s)', async cleared => {+ mocks.params = { groupId: 'g1' };+ mocks.pathname = '/bots/groups/g1';+ mocks.groups = [managedGroup()];+ const view = await renderSidebar();+ mocks.groups = [managedGroup(true)];+ if (cleared) { mocks.params = {}; mocks.pathname = '/bots/list'; }+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'bots.list.search' })));+ });++ it('keeps a new sidebar selection when settings archive finishes', async () => {+ mocks.params = { groupId: 'g1' };+ mocks.pathname = '/bots/groups/g1';+ mocks.groups = [managedGroup()];+ const view = await renderSidebar();+ const next = screen.getByText('咪咪').closest('button')!;+ act(() => next.focus());+ mocks.groups = [managedGroup(true)];+ mocks.params = {};+ mocks.pathname = '/bots/list';+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 60)); });+ expect(document.activeElement).toBe(next);+ });++ it('recovers to an existing sidebar button when settings archive finishes with a collapsed sidebar', async () => {+ mocks.params = { groupId: 'g1' };+ mocks.pathname = '/bots/groups/g1';+ mocks.groups = [managedGroup()];+ mocks.collapsed = true;+ const view = await renderSidebar();+ mocks.groups = [managedGroup(true)];+ mocks.params = {};+ mocks.pathname = '/bots/list';+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ await waitFor(() => expect(document.activeElement).toBe(view.container.querySelector('button')));+ });++ it('restores focus to the moved group row after keyboard unarchive', async () => {+ const focus = vi.spyOn(HTMLElement.prototype, 'focus');+ mocks.groups = [managedGroup(true)];+ const view = await renderSidebar();+ fireEvent.change(screen.getByRole('textbox', { name: 'bots.list.search' }), { target: { value: '周末' } });+ const row = screen.getByText('周末出游').closest('button')!;+ fireEvent.keyDown(row, { key: 'F10', shiftKey: true });+ fireEvent.click(await screen.findByRole('menuitem', { name: archiveKey(true) }));+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledOnce());++ mocks.groups = [managedGroup(false)];+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ await waitFor(() => expect(document.activeElement).toBe(screen.getByText('周末出游').closest('button')));+ expect(focus).toHaveBeenLastCalledWith();+ });++ it('keeps the search input focused when its last archived result is restored and the query is cleared', async () => {+ mocks.profiles = [];+ mocks.groups = [managedGroup(true)];+ const view = await renderSidebar();+ const input = screen.getByRole('textbox', { name: 'bots.list.search' });+ fireEvent.change(input, { target: { value: '周末' } });+ await selectArchive(true);+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledOnce());+ act(() => input.focus());+ mocks.groups = [managedGroup(false)];+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ fireEvent.change(input, { target: { value: '' } });+ expect(screen.getByRole('textbox', { name: 'bots.list.search' })).toBe(input);+ expect(document.activeElement).toBe(input);++ const row = screen.getByText('周末出游').closest('button')!;+ act(() => row.focus());+ expect(screen.queryByRole('textbox', { name: 'bots.list.search' })).toBeNull();+ expect(document.activeElement).toBe(row);+ });++ it('does not steal search focus when unarchive moves a filtered-out group', async () => {+ mocks.groups = [managedGroup(true)];+ const view = await renderSidebar();+ fireEvent.change(screen.getByRole('textbox', { name: 'bots.list.search' }), { target: { value: '周末' } });+ const input = screen.getByRole('textbox', { name: 'bots.list.search' });+ await selectArchive(true);+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledOnce());++ fireEvent.change(input, { target: { value: 'missing' } });+ input.focus();+ mocks.groups = [managedGroup(false)];+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ await waitFor(() => expect(document.activeElement).toBe(input));+ });++ it.each([false, true])('restores the original row after archive confirmation is cancelled (%s)', async archived => {+ let settle!: (accepted: boolean) => void;+ mocks.confirm.mockImplementationOnce(() => new Promise<boolean>(resolve => { settle = resolve; }));+ mocks.groups = [managedGroup(archived)];+ await renderSidebar();+ if (archived) fireEvent.change(screen.getByRole('textbox', { name: 'bots.list.search' }), { target: { value: '周末' } });+ const row = screen.getByText('周末出游').closest('button')!;+ row.focus();+ await selectArchive(archived);+ await waitFor(() => expect(document.activeElement).toBe(row));++ // Closing the real confirmation leaves body focused because its menu item+ // opener has already unmounted. The group row itself still exists.+ row.blur();+ await act(async () => { settle(false); });+ await waitFor(() => expect(document.activeElement).toBe(row));+ expect(mocks.manage).not.toHaveBeenCalled();+ expect(mocks.refreshGroups).not.toHaveBeenCalled();+ });++ it.each([false, true])('restores the original row after archive request failure (%s)', async archived => {+ let settle!: (result: { ok: false; errorCode: string }) => void;+ mocks.manage.mockImplementationOnce(() => new Promise(resolve => { settle = resolve; }));+ mocks.groups = [managedGroup(archived)];+ await renderSidebar();+ if (archived) fireEvent.change(screen.getByRole('textbox', { name: 'bots.list.search' }), { target: { value: '周末' } });+ const row = screen.getByText('周末出游').closest('button')!;+ row.focus();+ await selectArchive(archived);+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledOnce());+ await waitFor(() => expect(document.activeElement).toBe(row));++ row.blur();+ await act(async () => { settle({ ok: false, errorCode: 'REVISION_CONFLICT' }); });+ await waitFor(() => expect(document.activeElement).toBe(row));+ expect(screen.getByRole('alert').textContent).toBe('bots.groupChat.server.settings.conflict');+ expect(mocks.refreshGroups).not.toHaveBeenCalled();+ });++ it('does not steal search focus when unarchive keeps the group visible', async () => {+ mocks.groups = [managedGroup(true)];+ const view = await renderSidebar();+ fireEvent.change(screen.getByRole('textbox', { name: 'bots.list.search' }), { target: { value: '周末' } });+ const input = screen.getByRole('textbox', { name: 'bots.list.search' });+ await selectArchive(true);+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledOnce());++ fireEvent.change(input, { target: { value: '周末' } });+ input.focus();+ mocks.groups = [managedGroup(false)];+ view.rerender(cloneElement(mocks.registered.node as ReactElement));+ await waitFor(() => expect(document.activeElement).toBe(input));+ });++ it('keeps cancelled archives untouched and blocks old-account confirmations', async () => {+ mocks.groups = [managedGroup()];+ mocks.confirm.mockResolvedValueOnce(false);+ await renderSidebar();+ await selectArchive();+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledOnce());+ expect(mocks.manage).not.toHaveBeenCalled();+ expect(screen.getByText('周末出游')).toBeTruthy();+ mocks.confirm.mockImplementationOnce(async () => { mocks.ownerGeneration += 1; return true; });+ await selectArchive();+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(2));+ expect(mocks.manage).not.toHaveBeenCalled();+ expect(mocks.refreshGroups).not.toHaveBeenCalled();+ });++ it('blocks duplicate archive triggers while a confirmation is pending', async () => {+ mocks.groups = [managedGroup()];+ let accept!: (value: boolean) => void;+ mocks.confirm.mockImplementationOnce(() => new Promise(resolve => { accept = resolve; }));+ await renderSidebar();+ await selectArchive();+ fireEvent.contextMenu(screen.getByText('周末出游').closest('button')!);+ const action = await screen.findByRole('menuitem', { name: archiveKey() });+ expect(action.getAttribute('aria-disabled')).toBe('true');+ fireEvent.click(action);+ expect(mocks.confirm).toHaveBeenCalledOnce();+ await act(async () => { accept(true); });+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledOnce());+ });++ it('shows archived history rather than stale speaking or plan prompts', async () => {+ mocks.groups = [group({ archived: true, speakingBotIds: ['mimi'], openPlan: openPlan() })];+ await renderSidebar();+ fireEvent.change(screen.getByRole('textbox', { name: 'bots.list.search' }), { target: { value: '周末' } });+ expect(screen.queryByTestId('bot-group-running')).toBeNull();+ expect(screen.queryByText(/sidebar.planStepDone/)).toBeNull();+ expect(screen.getByText('bots.groupChat.sidebar.preview:{"name":"阿布","text":"下午 有小概率阵雨"}')).toBeTruthy();+ });++ it('keeps failed archives visible and ignores old-account responses', async () => {+ mocks.groups = [managedGroup()];+ mocks.manage.mockResolvedValueOnce({ ok: false, errorCode: 'REVISION_CONFLICT' });+ await renderSidebar();+ await selectArchive();+ await waitFor(() => expect(screen.getByRole('alert').textContent).toBe('bots.groupChat.server.settings.conflict'));+ expect(screen.getByText('周末出游')).toBeTruthy();+ expect(mocks.refreshGroups).not.toHaveBeenCalled();+ mocks.manage.mockImplementationOnce(async () => { mocks.ownerGeneration += 1; return { ok: true }; });+ await selectArchive();+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledTimes(2));+ expect(mocks.refreshGroups).not.toHaveBeenCalled();+ });++ it('offers settings but no archive for ordinary members, with keyboard access', async () => {+ mocks.groups = [group({ serverBacked: true, revision: 1 })];+ await renderSidebar();+ fireEvent.keyDown(screen.getByText('周末出游').closest('button')!, { key: 'F10', shiftKey: true });+ expect(screen.queryByRole('menuitem', { name: archiveKey() })).toBeNull();+ fireEvent.click(await screen.findByRole('menuitem', { name: 'bots.groupChat.settings.title' }));+ expect(mocks.navigate).toHaveBeenCalledWith('/bots/groups/g1?groupSettings=1');+ });+it('lists groups alongside teammates with an author preview and opens them', async () => {mocks.groups = [group(), group({ id: 'g2', name: '读书会', lastMessage: null, updatedAt: 1 })];mocks.params = { groupId: 'g1' };diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botsFeatureLayout.archive.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botsFeatureLayout.archive.test.tsxnew file mode 100644index 0000000000..03a10a28f8--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/botsFeatureLayout.archive.test.tsx@@ -0,0 +1,107 @@+// @vitest-environment jsdom+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { createMemoryRouter, RouterProvider } from 'react-router-dom';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { BotGroupSummary } from '../../../../shared/botGroupChat';+import { BotsFeatureLayout } from '../BotsFeatureLayout';+import { BotsListView } from '../BotsListView';+import { refreshBotGroups, resetBotGroupStoreForTests } from '../botGroupStore';++vi.mock('../botStore', () => ({ useBotProfiles: () => [] }));+vi.mock('../BotsSidebar', () => ({ BotsSidebar: () => null }));+vi.mock('../BotSettingsDrawer', () => ({ BotSettingsDrawer: () => null }));+vi.mock('../BotGroupSettingsDrawer', () => ({ BotGroupSettingsDrawer: () => null }));+vi.mock('../../feature-context', () => ({ useOwnTopNavScrollableRows: vi.fn() }));++let groups: BotGroupSummary[];+function group(id = 'room', archived = false): BotGroupSummary {+ return { id, name: id, archived, serverBacked: true, revision: 1, members: [],+ replyMode: 'all', speakingMode: 'auto', organizerBotId: '', projectDir: null,+ lastMessage: null, speakingBotIds: [], planningBotId: null, openPlan: null, createdAt: 1, updatedAt: 1 };+}++beforeEach(() => {+ resetBotGroupStoreForTests();+ groups = [group()];+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { maker: {+ listBotGroups: vi.fn(async () => ({ ok: true, groups })),+ } } });+});+afterEach(() => { cleanup(); resetBotGroupStoreForTests(); });++async function refresh() {+ await act(async () => { refreshBotGroups(); });+}+async function mount(path = '/bots/groups/room') {+ const router = createMemoryRouter([{ path: '/bots', element: <BotsFeatureLayout />, children: [+ { path: 'list', element: <BotsListView /> },+ { path: 'groups/:groupId', element: <main data-testid="group-content">Selected group</main> },+ { path: ':botId', element: <main data-testid="private-chat">Private chat</main> },+ ] }], { initialEntries: ['/bots/one', path], initialIndex: 1 });+ render(<RouterProvider router={router} />);+ await refresh();+ return router;+}++it.each(['/bots/groups/room', '/bots/groups/room?groupSettings=1'])(+ 'clears the selected group to the unselected pane after archiving at %s', async path => {+ const router = await mount(path);+ expect(screen.getByTestId('group-content')).toBeTruthy();+ groups = [group('room', true)];+ await refresh();+ await waitFor(() => expect(router.state.location.pathname).toBe('/bots/list'));+ expect(router.state.location.search).toBe('');+ expect(screen.queryByTestId('group-content')).toBeNull();+ expect(screen.queryByTestId('private-chat')).toBeNull();+ // Back must not reopen the group just removed from the selection.+ await act(async () => { await router.navigate(-1); });+ expect(router.state.location.pathname).toBe('/bots/one');+ },+);++it('keeps the current chat when another group is archived', async () => {+ groups = [group(), group('other')];+ const router = await mount();+ groups = [group(), group('other', true)];+ await refresh();+ expect(router.state.location.pathname).toBe('/bots/groups/room');+ expect(screen.getByTestId('group-content')).toBeTruthy();+});++it('keeps the selected group while its archive state is unchanged', async () => {+ const router = await mount('/bots/groups/room?groupSettings=1');+ groups = [{ ...group(), updatedAt: 2 }];+ await refresh();+ expect(router.state.location.pathname + router.state.location.search).toBe('/bots/groups/room?groupSettings=1');+});++it('does not leave a different chat when an earlier archive finishes', async () => {+ groups = [group(), group('other')];+ const router = await mount();+ await act(async () => { await router.navigate('/bots/groups/other'); });+ groups = [group('room', true), group('other')];+ await refresh();+ expect(router.state.location.pathname).toBe('/bots/groups/other');+ await act(async () => { await router.navigate('/bots/one'); });+ await refresh();+ expect(router.state.location.pathname).toBe('/bots/one');+});++it('opens an already archived history and keeps it open when restored', async () => {+ groups = [group('room', true)];+ const router = await mount();+ expect(router.state.location.pathname).toBe('/bots/groups/room');+ expect(screen.getByTestId('group-content')).toBeTruthy();+ groups = [group()];+ await refresh();+ expect(router.state.location.pathname).toBe('/bots/groups/room');+});++it('can switch directly from an active group to another archived history', async () => {+ groups = [group(), group('saved', true)];+ const router = await mount();+ await act(async () => { await router.navigate('/bots/groups/saved'); });+ await refresh();+ expect(router.state.location.pathname).toBe('/bots/groups/saved');+ expect(screen.getByTestId('group-content')).toBeTruthy();+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botsSidebar.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botsSidebar.test.tsxindex 29c497bfa6..3746275a94 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botsSidebar.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botsSidebar.test.tsx@@ -1,6 +1,10 @@// @vitest-environment jsdomimport { useBotUnreadSync } from '../useBotUnreadSync';+vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useConfirmDialog: () => ({ confirm: vi.fn() }),+}));+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { cloneElement, type ReactElement, type ReactNode } from 'react';import { afterAll, beforeAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -67,7 +71,8 @@ vi.mock('@/hooks/useSessionRunningStatus', () => ({},}));-vi.mock('react-router-dom', () => ({+vi.mock('react-router-dom', async importOriginal => ({+ ...await importOriginal<typeof import('react-router-dom')>(),useNavigate: () => mocks.navigate,useLocation: () => ({ pathname: mocks.pathname, search: '', hash: '' }),useParams: () => mocks.params,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 52e30cb48e..1aa63e3594 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8757,6 +8757,7 @@"createMenu": "Create","createTeammate": "New teammate","startChat": "Start the conversation",+ "selectChat": "Select a teammate or group chat to start chatting","typing": "Typing…","unread": "{{count}} unread messages","search": "Search teammates or group chats",@@ -8771,7 +8772,8 @@"pinned": "Pinned","needsAttention": "Needs attention","duplicate": "Duplicate teammate",- "moreActions": "More actions for {{name}}"+ "moreActions": "More actions for {{name}}",+ "noResults": "No matching teammates or groups"},"cancel": "Cancel","save": "Save",@@ -9240,8 +9242,9 @@"addCompanion": "Invite my companion","leave": "Leave group","leaveHint": "You and your companions will leave. Transfer ownership first if you own the group.",- "archive": "Archive group",- "archiveHint": "Keep history, stop new messages and companion activity.",+ "soleOwnerHint": "You’re the only member left. Archive this group to keep its history and restore it later.",+ "archive": "Archive Group",+ "archiveHint": "Archiving disables this group for all members, stopping new messages and teammate runs. History is kept. Search for the group to view its history or unarchive it.","confirm": "Confirm","lastOwner": "Transfer ownership to another member before leaving or removing the current owner.","conflict": "Someone updated this group. Refresh and try again.",@@ -9251,8 +9254,8 @@"mentioned": "Only when mentioned","auto": "Together","sequential": "One at a time",- "unarchive": "Unarchive group",- "unarchiveHint": "Resume messages and companion activity.",+ "unarchive": "Unarchive Group",+ "unarchiveHint": "Unarchiving resumes messages and teammate activity for everyone in this group.","archived": "This group is archived. History is still available.","noneHint": "Only the companion’s owner can ask it to respond in this group.","companionPermissions": "Companion permissions",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 9d9db26407..a5e42bfb1a 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8720,6 +8720,7 @@"createMenu": "新規作成","createTeammate": "パートナーを作成","startChat": "会話を始める",+ "selectChat": "パートナーやグループチャットを選んで、会話を始めましょう","typing": "入力中…","unread": "{{count}} 件の未読メッセージ","search": "パートナーやグループチャットを検索",@@ -8734,7 +8735,8 @@"pinned": "固定済み","needsAttention": "対応が必要","duplicate": "仲間を複製",- "moreActions": "{{name}} のその他の操作"+ "moreActions": "{{name}} のその他の操作",+ "noResults": "一致するパートナーやグループはありません"},"cancel": "キャンセル","save": "保存",@@ -9203,8 +9205,9 @@"addCompanion": "自分のパートナーを招待","leave": "グループを退出","leaveHint": "あなたとあなたのパートナーが退出します。オーナーは先に所有権を譲渡してください。",+ "soleOwnerHint": "メンバーはあなただけです。グループをアーカイブすると履歴が残り、後で再開できます。","archive": "グループをアーカイブ",- "archiveHint": "履歴を残し、新しいメッセージとパートナーの実行を停止します。",+ "archiveHint": "アーカイブすると、すべてのメンバーに対して新しいメッセージとパートナーの実行が停止します。履歴は保持されます。グループを検索して履歴を閲覧したり、アーカイブを解除したりできます。","confirm": "確認","lastOwner": "退出またはオーナーを削除する前に、別のメンバーに所有権を譲渡してください。","conflict": "設定が更新されました。再読み込みしてお試しください。",@@ -9215,7 +9218,7 @@"auto": "同時に発言","sequential": "順番に発言","unarchive": "アーカイブを解除",- "unarchiveHint": "メッセージとパートナーの実行を再開します。",+ "unarchiveHint": "アーカイブを解除すると、すべてのメンバーに対してメッセージとパートナーの実行が再開します。","archived": "アーカイブ済みです。履歴は引き続き閲覧できます。","noneHint": "このグループでは仲間の所有者だけが応答を依頼できます。","companionPermissions": "仲間の権限",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex ec8141ff3d..4523238f17 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8720,6 +8720,7 @@"createMenu": "새로 만들기","createTeammate": "새 파트너","startChat": "대화 시작하기",+ "selectChat": "파트너 또는 그룹 채팅을 선택해 대화를 시작하세요","typing": "입력 중…","unread": "읽지 않은 메시지 {{count}}개","search": "파트너 또는 그룹 채팅 검색",@@ -8734,7 +8735,8 @@"pinned": "고정됨","needsAttention": "확인 필요","duplicate": "동료 복제",- "moreActions": "{{name}} 추가 작업"+ "moreActions": "{{name}} 추가 작업",+ "noResults": "검색과 일치하는 파트너나 그룹이 없어요"},"cancel": "취소","save": "저장",@@ -9203,8 +9205,9 @@"addCompanion": "내 파트너 초대","leave": "그룹 나가기","leaveHint": "본인과 자신의 파트너가 그룹을 나갑니다. 소유자는 먼저 소유권을 이전해야 합니다.",+ "soleOwnerHint": "그룹에 나만 남았어요. 그룹을 보관하면 기록을 유지하고 나중에 다시 사용할 수 있어요.","archive": "그룹 보관",- "archiveHint": "기록을 보존하고 새 메시지와 파트너 실행을 중단합니다.",+ "archiveHint": "그룹을 보관하면 모든 멤버의 새 메시지와 파트너 실행이 중지돼요. 기록은 유지돼요. 그룹을 검색해 기록을 보거나 보관을 해제할 수 있어요.","confirm": "확인","lastOwner": "나가거나 소유자를 내보내기 전에 다른 멤버에게 소유권을 이전하세요.","conflict": "다른 멤버가 설정을 변경했습니다. 새로 고침 후 다시 시도하세요.",@@ -9215,7 +9218,7 @@"auto": "동시에 발언","sequential": "차례로 발언","unarchive": "그룹 보관 해제",- "unarchiveHint": "메시지와 파트너 실행을 재개합니다.",+ "unarchiveHint": "보관을 해제하면 모든 멤버의 메시지와 파트너 실행이 재개돼요.","archived": "보관된 그룹입니다. 기록은 계속 볼 수 있습니다.","noneHint": "이 그룹에서는 동료의 소유자만 응답을 요청할 수 있습니다.","companionPermissions": "동료 권한",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 07101dfa4d..7938047253 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8720,6 +8720,7 @@"createMenu": "新建","createTeammate": "新建伙伴","startChat": "开始对话",+ "selectChat": "选择伙伴或群聊,开始对话","typing": "正在输入…","unread": "{{count}} 条未读消息","search": "搜索伙伴或群聊",@@ -8734,7 +8735,8 @@"pinned": "已置顶","needsAttention": "需要处理","duplicate": "复制伙伴",- "moreActions": "{{name}} 的更多操作"+ "moreActions": "{{name}} 的更多操作",+ "noResults": "没有匹配的伙伴或群聊"},"cancel": "取消","save": "保存",@@ -9203,8 +9205,9 @@"addCompanion": "邀请我的伙伴","leave": "退出群","leaveHint": "你和你带来的伙伴将退出群。群主需要先转让身份。",+ "soleOwnerHint": "群里只剩你。可以归档群,保留历史记录,以后再恢复使用。","archive": "归档群",- "archiveHint": "归档后保留群聊记录,停止新消息和伙伴执行。",+ "archiveHint": "归档会对所有成员停用本群,停止新消息和伙伴执行。历史记录保留,之后可通过搜索找到本群、查看历史并取消归档。","confirm": "确认","lastOwner": "请先将群主转让给其他成员,再退出或移除当前群主。","conflict": "群设置已被其他成员更新,请刷新后重试。",@@ -9215,7 +9218,7 @@"auto": "同时发言","sequential": "依次发言","unarchive": "取消归档",- "unarchiveHint": "恢复新消息和伙伴执行。",+ "unarchiveHint": "取消归档后,本群对所有成员恢复新消息和伙伴执行。","archived": "本群已归档,可继续查看历史记录。","noneHint": "本群只有伙伴的主人可以让伙伴回应。","companionPermissions": "伙伴权限",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 271b703d50..ef76f7d9f6 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -8720,6 +8720,7 @@"createMenu": "新增","createTeammate": "新增夥伴","startChat": "開始對話",+ "selectChat": "選擇夥伴或群聊,開始對話","typing": "正在輸入…","unread": "{{count}} 則未讀訊息","search": "搜尋夥伴或群聊",@@ -8734,7 +8735,8 @@"pinned": "已置頂","needsAttention": "需要處理","duplicate": "複製夥伴",- "moreActions": "{{name}} 的更多操作"+ "moreActions": "{{name}} 的更多操作",+ "noResults": "找不到符合的夥伴或群組"},"cancel": "取消","save": "儲存",@@ -9203,8 +9205,9 @@"addCompanion": "邀請我的夥伴","leave": "退出群組","leaveHint": "你和你帶來的夥伴將退出群組。群主需要先轉讓身分。",+ "soleOwnerHint": "群組裡只剩你。可以封存群組,保留歷史記錄,以後再恢復使用。","archive": "封存群組",- "archiveHint": "封存後保留群聊記錄,停止新訊息和夥伴執行。",+ "archiveHint": "封存會對所有成員停用本群組,停止新訊息與夥伴執行。歷史記錄保留,之後可透過搜尋找到本群組、查看歷史並取消封存。","confirm": "確認","lastOwner": "請先將群主轉讓給其他成員,再退出或移除目前的群主。","conflict": "群組設定已更新,請重新整理後再試。",@@ -9215,7 +9218,7 @@"auto": "同時發言","sequential": "依序發言","unarchive": "取消封存",- "unarchiveHint": "恢復新訊息與夥伴執行。",+ "unarchiveHint": "取消封存後,本群組對所有成員恢復新訊息與夥伴執行。","archived": "本群已封存,可繼續查看歷史記錄。","noneHint": "本群只有夥伴的主人可以讓夥伴回應。","companionPermissions": "夥伴權限",diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 4e2f237baf..789cb1ec2e 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -361,6 +361,17 @@ Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授当前本地验收与正式切源边界见 [Chat Server 本地联调](../dev-rules/chat-server-local-test.md)。+### 群归档与找回(2026-10-14,Issue #6039)++- 群主或管理员可从 Desktop 群行右键菜单或群设置归档群;确认框明确归档会对全群停止新消息与伙伴执行,保留群历史。+- 默认侧栏只显示未归档群,不放常驻归档入口。输入群名或成员搜索时,结果包含已归档群并标明归档状态,可直接打开历史;即使没有任何伙伴、只剩归档群,也保留搜索能力。有管理权限的成员可从搜索结果的群行菜单或群设置取消归档,恢复默认列表中的群行与群内使用。+- 当前选中的群归档成功后,右侧回到未选中聊天的空态,居中显示「选择伙伴或群聊,开始对话」,群设置同时关闭;归档其他群不切换当前页面。取消、失败或等待期间已切到其他聊天时保留当前选择。通过搜索主动打开已归档群可继续查看历史,取消归档也不退出历史页。+- 只剩当前群主一个成员时,群设置提供归档引导,不再提供要求转让给不存在成员的退出操作。已有多人群的退出与群主转让规则不变。+- 归档沿用服务器已有的全群停用语义,不删除群消息或任何群专线 Session。群列表镜像仍保留归档群,隐藏只发生在默认侧栏的展示层。+- 此次不提供永久删除、个人收起,也不增加「新消息自动取消归档」行为。归档期间服务器拒绝新消息;取消归档后才恢复。++实现见 Desktop 的 BotsSidebar、ChatGroupSettings、BotsFeatureLayout;回归见对应群侧栏、群设置与 `botsFeatureLayout.archive.test.tsx` 测试。+### Thread 内唤醒伙伴的上下文伙伴要回答的是服务端执行指定的那条源消息,不是「群里最新的一条」。执行端按源消息 ID 定位当前请求;