Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 从群设置配置伙伴能力时留在原群

shenjiacheng49bb104ebbe0
diff --git a/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx b/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx
index 0ac7c06963..cff82fb5ea 100644
--- a/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx
@@ -27,12 +27,19 @@ export function BotSettingsDrawer() {
(item) =>
item.id === remoteMatch?.params.botId && item.deviceId === remoteMatch?.params.deviceId,
);
+ // Group routes stay on /bots/groups/:id. A generic /bots/:botId match would
+ // treat "groups" as a teammate and replace the chat with a private route.
+ const groupMatch = matchPath('/bots/groups/:groupId', location.pathname);
const match =
- matchPath('/bots/:botId/*', location.pathname) ?? matchPath('/bots/:botId', location.pathname);
+ remoteMatch || groupMatch
+ ? null
+ : (matchPath('/bots/:botId/*', location.pathname) ??
+ matchPath('/bots/:botId', location.pathname));
const cloud = useCompanionCloud();
+ const settingsBotId = groupMatch ? searchParams.get('settingsBot') : null;
const localBot = remoteMatch
? null
- : (bots.find((candidate) => candidate.id === match?.params.botId) ?? null);
+ : (bots.find((candidate) => candidate.id === (settingsBotId ?? match?.params.botId)) ?? null);
// A demoted copy (the companion runs on another computer) is read-only: edits here would never
// reach the companion. Its settings live on the main computer (the banner on its task links there).
const bot = localBot && cloud.demotedBotIds.includes(localBot.id) ? null : localBot;
@@ -85,9 +92,27 @@ export function BotSettingsDrawer() {
};
}, [blocker]);
+ const clearSettingsParams = () => {
+ setSearchParams(
+ (current) => {
+ const next = new URLSearchParams(current);
+ next.delete('settings');
+ next.delete('settingsPage');
+ next.delete('settingsBot');
+ return next;
+ },
+ { replace: true },
+ );
+ };
const performClose = (alreadyChecked = true) => {
// These callers already passed BotSettings' async save/draft guard.
allowNavigation.current = alreadyChecked;
+ // Opened over a group: the chat underneath is the group, not this teammate's
+ // private page. Closing must not follow the paused/archived redirects.
+ if (groupMatch) {
+ clearSettingsParams();
+ return;
+ }
if (bot?.status === 'archived') {
navigate('/bots', { replace: true });
return;
@@ -98,15 +123,7 @@ export function BotSettingsDrawer() {
navigate('/bots/list', { replace: true });
return;
}
- setSearchParams(
- (current) => {
- const next = new URLSearchParams(current);
- next.delete('settings');
- next.delete('settingsPage');
- return next;
- },
- { replace: true },
- );
+ clearSettingsParams();
};
// Header, Escape and overlay dismissal take the same route guard as Back
@@ -143,6 +160,11 @@ export function BotSettingsDrawer() {
<X size={17} />
</Dialog.Close>
</header>
+ {groupMatch && bot ? (
+ <p className="shrink-0 border-b border-[var(--border-default)] px-5 py-3 text-12 leading-5 text-[var(--text-secondary)]">
+ {t('bots.groupChat.server.settings.capabilityScope', { name: bot.name })}
+ </p>
+ ) : null}
{remoteBot ? (
<RemoteBotSettings
key={`${remoteBot.deviceId}:${remoteBot.id}:${open}:${initialPage}`}
diff --git a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx
index 25b03b661e..635e9f5f81 100644
--- a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ChevronDown, ChevronUp, Crown, Shield } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router-dom';
+import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select } from '@/components/ui/select';
@@ -16,6 +16,7 @@ import { BotAvatar } from './BotAvatar';
import { chatErrorKey } from './ChatServerControls';
import { refreshBotGroups } from './botGroupStore';
import { chatGroupMembership } from '@cindy/maker-shared/botGroupPresentation';
+import { BOT_GROUP_SETTINGS_PARAM } from './botGroupPresentation';
const key = (name: string) => `bots.groupChat.server.settings.${name}`;
/** Labels shared with the local group settings, so both read the same. */
@@ -28,6 +29,7 @@ const api = () => window.electronAPI.maker.chatServer;
export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {
const { t } = useTranslation();
const navigate = useNavigate();
+ const [searchParams, setSearchParams] = useSearchParams();
const { confirm } = useConfirmDialog();
const profiles = useBotProfiles();
const companions = group.members.filter(member => member.actorKind === 'bot');
@@ -176,10 +178,19 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {
</div>
</div>
<ChatBotAccessField groupId={group.id} member={member} disabled={busy || !!group.dissolvedAt} />
- {member.isOwned && profiles.some(bot => bot.id === member.botId) && <Button size="sm" variant="secondary"
- onClick={() => navigate(`/bots/${encodeURIComponent(member.botId)}?settings=1&settingsPage=capabilities`)}>
- {t(key('configureCapabilities'))}
- </Button>}
+ {member.isOwned && profiles.some(bot => bot.id === member.botId) && <div className="space-y-2">
+ <Button size="sm" variant="secondary" onClick={() => {
+ const next = new URLSearchParams(searchParams);
+ next.delete(BOT_GROUP_SETTINGS_PARAM);
+ next.set('settings', '1');
+ next.set('settingsPage', 'capabilities');
+ next.set('settingsBot', member.botId);
+ setSearchParams(next);
+ }}>
+ {t(key('configureCapabilities'))}
+ </Button>
+ <p className="text-12 leading-5 text-[var(--text-secondary)]">{t(key('capabilityScope'), { name: member.name })}</p>
+ </div>}
</div>)}
</section>}
<section className="space-y-3 border-t border-[var(--border-default)] pt-5">
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx
index 7da9c3c21f..92bdc93a32 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx
@@ -1,14 +1,34 @@
// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
+import type { ReactNode } from 'react';
+import { MemoryRouter, RouterProvider, createMemoryRouter, useLocation } from 'react-router-dom';
+import { transferableAbortController } from 'node:util';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { ChatGroupSettings } from '../ChatGroupSettings';
+import { BotSettingsDrawer } from '../BotSettingsDrawer';
import type { BotGroupSummary } from '../../../../shared/botGroupChat';
const mocks = vi.hoisted(() => ({ manage: vi.fn(), ownedBots: vi.fn(), refresh: vi.fn(), confirm: vi.fn() }));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+const profiles = vi.hoisted(() => ({
+ list: [{ id: 'bot', name: 'Partner', status: 'active', sessions: [] as Array<{ id: string }>, capabilities: {}, skills: [] as string[] }],
+}));
+const translate = (key: string, options?: { name?: string }) =>
+ typeof options?.name === 'string' ? `${key}:${options.name}` : key;
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));
+vi.mock('../botPronounContext', () => ({
+ useBotTranslation: () => ({ t: translate }),
+ BotPronounProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => [] }));
+vi.mock('../RemoteBotSettings', () => ({ RemoteBotSettings: () => null }));
+vi.mock('../companionCloudStore', () => ({ useCompanionCloud: () => ({ demotedBotIds: [] as string[] }) }));
+vi.mock('../BotsHomeView', () => ({
+ BotSettings: ({ bot, initialPage }: { bot: { id: string; name: string }; initialPage?: string }) => (
+ <div data-testid="bot-settings" data-bot-id={bot.id} data-initial-page={initialPage}>{bot.name}</div>
+ ),
+}));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => ({ confirm: mocks.confirm }) }));
vi.mock('@/components/settings/ProfileEditDialog', () => ({ ProfileEditDialog: () => null }));
-vi.mock('../botStore', () => ({ useBotProfiles: () => [{ id: 'bot' }] }));
+vi.mock('../botStore', () => ({ useBotProfiles: () => profiles.list }));
vi.mock('../BotAvatar', () => ({ BotAvatar: () => null }));
vi.mock('../botGroupStore', () => ({ refreshBotGroups: mocks.refresh }));
vi.mock('@/contexts/dataOwnerGeneration', () => ({ getDataOwnerGeneration: () => 1, isDataOwnerGenerationCurrent: () => true }));
@@ -19,11 +39,30 @@ function group(owned = false): BotGroupSummary {
{ actorId: 'bot', botId: 'bot', actorKind: 'bot', name: 'Partner', role: 'owner', isOwned: owned, guestAccess: 'chat', accessRevision: 1 },
] } as BotGroupSummary;
}
+function activeProfile(id: string, name: string, status = 'active') {
+ return { id, name, status, sessions: [] as Array<{ id: string }>, capabilities: {}, skills: [] as string[] };
+}
beforeEach(() => {
+ const nativeAbortController = transferableAbortController();
+ vi.stubGlobal('AbortController', nativeAbortController.constructor);
+ vi.stubGlobal('AbortSignal', nativeAbortController.signal.constructor);
+ profiles.list = [activeProfile('bot', 'Partner')];
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 } } });
});
+function LocationProbe() {
+ const location = useLocation();
+ return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;
+}
+function renderGroupEntry(groupValue: BotGroupSummary) {
+ return render(<RouterProvider router={createMemoryRouter([
+ { path: '/bots/groups/:groupId', element: <><div data-testid="group-chat" /><LocationProbe /><ChatGroupSettings group={groupValue} /><BotSettingsDrawer /></> },
+ { path: '/bots/list', element: <LocationProbe /> },
+ { path: '/bots/:botId', element: <><LocationProbe /><BotSettingsDrawer /></> },
+ { path: '*', element: <LocationProbe /> },
+ ], { initialEntries: ['/bots/groups/room?groupSettings=1'] })} />);
+}
it('guides a sole owner to archive instead of offering an impossible leave', async () => {
const alone = group();
@@ -53,7 +92,7 @@ it('keeps a sole archived owner in the group and offers restoring its history',
action: { type: 'archive', archived: false, expectedRevision: 1 },
}));
});
-afterEach(cleanup);
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
it('lets a member change their own nickname while keeping another owner’s grant read-only', async () => {
render(<MemoryRouter><ChatGroupSettings group={group()} /></MemoryRouter>);
expect((screen.getByRole('textbox', { name: key('name') }) as HTMLInputElement).disabled).toBe(true);
@@ -135,3 +174,69 @@ it('does not refresh or remove the list on failed personal removal', async () =>
await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy());
expect(mocks.refresh).not.toHaveBeenCalled();
});
+
+// 测试价值
+// - 生产入口与可观察结果:群设置里真实的「工具与授权设置」按钮,以及 BotSettingsDrawer 的关闭按钮。
+// 打开后应看到所选伙伴的能力页,路由仍是原群;关闭后群聊页还在。
+// - Bug/规则依据:#6809。修前该按钮会进入 /bots/<id> 私聊,关闭只去掉设置参数。
+// - 现有覆盖缺口:本组用例只断言按钮是否出现;抽屉用例只覆盖私聊路由上的开关。
+// - 最小失败输入:群里两位已拥有且在本机名单中的伙伴,从 /bots/groups/room?groupSettings=1 打开后者。
+// - tier:unit。真实组件加 React Router,不启动 Electron。
+it('keeps the original group mounted when opening and closing another owned companion’s capability settings', async () => {
+ profiles.list = [activeProfile('bot', 'Partner'), activeProfile('other', 'Other')];
+ const room = group(true);
+ room.members = [...room.members, {
+ actorId: 'other', botId: 'other', actorKind: 'bot', name: 'Other', role: 'member', isOwned: true, guestAccess: 'chat', accessRevision: 1,
+ }];
+ renderGroupEntry(room);
+ const buttons = screen.getAllByRole('button', { name: key('configureCapabilities') });
+ expect(buttons).toHaveLength(2);
+ fireEvent.click(buttons[1]!);
+ const opened = screen.getByTestId('location').textContent ?? '';
+ const settings = screen.queryByTestId('bot-settings');
+ const dialog = screen.queryByRole('dialog');
+ fireEvent.click(screen.getByRole('button', { name: 'bots.close' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect({
+ opened,
+ botId: settings?.getAttribute('data-bot-id'),
+ page: settings?.getAttribute('data-initial-page'),
+ scope: dialog?.textContent?.includes(`${key('capabilityScope')}:Other`) ?? false,
+ closed: screen.getByTestId('location').textContent,
+ groupMounted: screen.queryByTestId('group-chat') !== null,
+ }).toEqual({
+ opened: expect.stringContaining('/bots/groups/room?'),
+ botId: 'other',
+ page: 'capabilities',
+ scope: true,
+ closed: '/bots/groups/room',
+ groupMounted: true,
+ });
+});
+
+it('returns a paused companion’s capability settings to the original group instead of the teammate list', async () => {
+ profiles.list = [activeProfile('bot', 'Partner', 'paused')];
+ renderGroupEntry(group(true));
+ fireEvent.click(screen.getByRole('button', { name: key('configureCapabilities') }));
+ fireEvent.click(screen.getByRole('button', { name: 'bots.close' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(screen.getByTestId('location').textContent).toBe('/bots/groups/room');
+ expect(screen.getByTestId('group-chat')).toBeTruthy();
+});
+
+it('keeps the private chat settings entry on that companion', async () => {
+ profiles.list = [activeProfile('bot', 'Partner'), activeProfile('other', 'Other')];
+ render(<RouterProvider router={createMemoryRouter([
+ { path: '/bots/:botId', element: <><LocationProbe /><BotSettingsDrawer /></> },
+ { path: '/bots/groups/:groupId', element: <LocationProbe /> },
+ ], { initialEntries: ['/bots/bot?settings=1&settingsPage=capabilities&settingsBot=other'] })} />);
+ expect(screen.getByTestId('bot-settings').getAttribute('data-bot-id')).toBe('bot');
+ expect(screen.getByTestId('bot-settings').getAttribute('data-initial-page')).toBe('capabilities');
+ expect(screen.queryByText(`${key('capabilityScope')}:Other`)).toBeNull();
+ expect(screen.queryByText(`${key('capabilityScope')}:Partner`)).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'bots.close' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ const closed = new URL(screen.getByTestId('location').textContent ?? '', 'https://cindy.local');
+ expect(closed.pathname).toBe('/bots/bot');
+ expect(closed.searchParams.get('settings')).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e5e321e289..47ac58347a 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9767,7 +9767,8 @@
"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",
- "configureCapabilities": "Tools and access settings"
+ "configureCapabilities": "Tools and access settings",
+ "capabilityScope": "These are {{name}}’s own tools and access, not settings for this group only."
}
},
"lifecycle": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c634b6c660..67e7d3dc8c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9733,7 +9733,8 @@
"archived": "アーカイブ済みです。履歴は引き続き閲覧できます。",
"noneHint": "このグループでは仲間の所有者だけが応答を依頼できます。",
"companionPermissions": "仲間の権限",
- "configureCapabilities": "ツールと利用権限の設定"
+ "configureCapabilities": "ツールと利用権限の設定",
+ "capabilityScope": "これは{{name}}自身のツールと利用権限で、このグループだけの設定ではありません。"
}
},
"lifecycle": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 66f9c9d783..9a700f6116 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9733,7 +9733,8 @@
"archived": "보관된 그룹입니다. 기록은 계속 볼 수 있습니다.",
"noneHint": "이 그룹에서는 동료의 소유자만 응답을 요청할 수 있습니다.",
"companionPermissions": "동료 권한",
- "configureCapabilities": "도구 및 사용 권한 설정"
+ "configureCapabilities": "도구 및 사용 권한 설정",
+ "capabilityScope": "이것은 {{name}}의 도구와 사용 권한이며, 이 그룹에만 적용되는 설정이 아닙니다."
}
},
"lifecycle": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 0f0fe7389c..cb75de4e79 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9733,7 +9733,8 @@
"archived": "本群已归档,可继续查看历史记录。",
"noneHint": "本群只有伙伴的主人可以让伙伴回应。",
"companionPermissions": "伙伴权限",
- "configureCapabilities": "工具与授权设置"
+ "configureCapabilities": "工具与授权设置",
+ "capabilityScope": "这是 {{name}} 自己的工具与授权,不是仅限本群的设置。"
}
},
"lifecycle": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index d6cdcbde1a..551ebf419c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9733,7 +9733,8 @@
"archived": "本群已封存,可繼續查看歷史記錄。",
"noneHint": "本群只有夥伴的主人可以讓夥伴回應。",
"companionPermissions": "夥伴權限",
- "configureCapabilities": "工具與授權設定"
+ "configureCapabilities": "工具與授權設定",
+ "capabilityScope": "這是 {{name}} 自己的工具與授權,不是僅限本群的設定。"
}
},
"lifecycle": {