Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 对齐群聊连接提示的位置与折叠交互 (#5174)
Chris Zhangfa2b64fa5059
diff --git a/apps/desktop/scripts/check-group-control-layout.mjs b/apps/desktop/scripts/check-group-control-layout.mjsnew file mode 100644index 0000000000..db14bbcee2--- /dev/null+++ b/apps/desktop/scripts/check-group-control-layout.mjs@@ -0,0 +1,319 @@+#!/usr/bin/env node+// Isolated production-component layout regression; no Electron or device connections.+// Run: node apps/desktop/scripts/check-group-control-layout.mjs [Chromium executable] [screenshot directory]+import assert from 'node:assert/strict';+import { readFileSync, mkdtempSync, mkdirSync, rmSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import esbuild from 'esbuild';+import postcss from 'postcss';+import tailwind from 'tailwindcss';+import loadConfig from 'tailwindcss/loadConfig.js';+import { chromium } from 'playwright-core';++const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const renderer = path.join(desktop, 'src/renderer');+const temp = mkdtempSync(path.join(os.tmpdir(), 'cindy-group-control-'));+const screenshots = process.argv[3];+if (screenshots) mkdirSync(screenshots, { recursive: true });+// Stub only host-facing/unrendered dependencies. The page, composer, banner,+// theme tokens and CSS are production implementations.+const stubs = {+ '@/components/chat/MarkdownRenderer': 'export const MarkdownRenderer=({content})=>content;',+ '@/contexts/dataOwnerGeneration':+ 'export const getDataOwnerGeneration=()=>1;export const isDataOwnerGenerationCurrent=()=>true;export const isDataOwnerPushCurrent=()=>true;',+ '@/state/agentIslandActivity': 'export const useAgentIslandActivity=()=>null;',+ '@/lib/logger': 'export const createLogger=()=>({debug(){},info(){},warn(){},error(){}});',+ '@/lib/toast': 'export const toast={error(){},success(){}};',+ './BotGroupPendingInteraction': 'export const BotGroupPendingInteraction=()=>null;',+};+let browser;+try {+ const config = loadConfig(path.join(desktop, 'tailwind.config.ts'));+ config.content = [+ path.join(renderer, 'features/bots/*.tsx'),+ path.join(renderer, 'features/remote-device/ControlledBanner.tsx'),+ path.join(renderer, 'components/ui/*.tsx'),+ path.join(renderer, 'components/new-chat/SendButton.tsx'),+ ];+ const css = (+ await postcss([tailwind(config)]).process(+ readFileSync(path.join(renderer, 'styles/generated/tokens.css'), 'utf8') ++ '\n' ++ readFileSync(path.join(renderer, 'styles/globals.css'), 'utf8').replace(+ /^@import.*$/gm,+ '',+ ),+ { from: undefined },+ )+ ).css;+ const bundle = await esbuild.build({+ entryPoints: [path.join(desktop, 'scripts/fixtures/group-control/group-control-fixture.tsx')],+ write: false,+ outfile: path.join(temp, 'group-control.js'),+ bundle: true,+ format: 'esm',+ platform: 'browser',+ jsx: 'automatic',+ tsconfig: path.join(desktop, 'tsconfig.json'),+ loader: { '.svg': 'dataurl', '.png': 'dataurl' },+ define: { 'import.meta.env.PROD': 'true', 'import.meta.env.DEV': 'false' },+ plugins: [+ {+ name: 'fixture-stubs',+ setup(build) {+ build.onResolve({ filter: /.*/ }, (args) =>+ stubs[args.path] ? { path: args.path, namespace: 'fixture-stub' } : undefined,+ );+ build.onLoad({ filter: /.*/, namespace: 'fixture-stub' }, (args) => ({+ contents: stubs[args.path],+ loader: 'tsx',+ }));+ },+ },+ ],+ });+ const shellCss = `+ body{margin:0;color:var(--text-primary);background:var(--surface);font-family:Inter,-apple-system,sans-serif}+ .fixture-caption{height:36px;padding:8px 16px;font-size:12px;border-bottom:1px solid var(--border-default)}+ .fixture-shell{display:flex;height:calc(100vh - 36px)}+ aside{flex-shrink:0;padding:20px;overflow:hidden;border-right:1px solid var(--border-default)}+ aside[style="width: 0px;"]{padding:0;border:0}+ .fixture-content{flex:1;min-width:0;display:flex;flex-direction:column}+ header{height:52px;flex-shrink:0;display:flex;align-items:center;justify-content:space-between;padding:0 20px;border-bottom:1px solid var(--border-default)}+ .fixture-view{flex:1;min-height:0}`;+ const script = bundle.outputFiles.find((file) => file.path.endsWith('.js')).text;+ const componentCss = bundle.outputFiles+ .filter((file) => file.path.endsWith('.css'))+ .map((file) => file.text)+ .join('');+ browser = await chromium.launch({+ headless: true,+ ...(process.argv[2] ? { executablePath: process.argv[2] } : {}),+ });+ const page = await browser.newPage();+ const errors = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.route('**/*', (route) =>+ route.request().url().startsWith('http://fixture.local/')+ ? route.fulfill({+ contentType: 'text/html',+ body: `<!doctype html><meta charset="utf-8"><style>${css}${componentCss}${shellCss}</style><div id="root"></div><script type="module">${script.replace(/<\/script/gi, '<\\/script')}</script>`,+ })+ : route.abort(),+ );+ const connect = async (connected = true, long = false) => {+ await page.evaluate(+ ({ connected, long }) =>+ window.fixturePush({+ controllers: connected+ ? [+ {+ deviceId: 'fixture',+ name: long+ ? 'Mac Studio · A very long device name for layout verification'+ : 'Mac Studio',+ },+ ]+ : [],+ }),+ { connected, long },+ );+ await page+ .locator('main [data-controlled-banner-chip]')+ .waitFor({ state: connected ? 'visible' : 'detached' });+ };+ const bottomGap = () =>+ page+ .locator('main > div')+ .first()+ .evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop);+ const collapse = async () => {+ await page.locator('[data-controlled-banner-collapse]').click();+ await page.locator('[data-controlled-banner="collapsed"]').waitFor();+ assert.equal(await page.locator('[data-controlled-banner-chip]').count(), 0);+ };+ const expand = async () => {+ await page.locator('[data-controlled-banner="collapsed"]').click();+ await page.locator('[data-controlled-banner-chip]').waitFor();+ };+ const activateWithKeyboard = async (selector, key) => {+ // Reach the notice through normal tab order, not locator.focus().+ await page.locator('textarea').focus();+ await page.keyboard.press('Shift+Tab');+ const target = page.locator(selector);+ assert(+ await target.evaluate((element) => element === document.activeElement),+ `Keyboard cannot reach ${selector}`,+ );+ assert(+ await target.evaluate(+ (element) =>+ Boolean(element.getAttribute('aria-label')) &&+ element.matches(':focus-visible') &&+ getComputedStyle(element).boxShadow !== 'none',+ ),+ `Missing accessible focus: ${selector}`,+ );+ await page.keyboard.press(key);+ };+ let layouts = 0;+ for (const theme of ['light', 'dark']) {+ for (const width of [720, 800, 1280])+ for (const sidebar of [0, 280])+ for (const lines of [1, 8]) {+ const scenario = JSON.stringify({ theme, width, sidebar, lines });+ await page.setViewportSize({ width, height: width === 800 ? 600 : 800 });+ await page.goto(+ `http://fixture.local/?theme=${theme}&sidebar=${sidebar}&stage=regression`,+ );+ await page.locator('textarea').waitFor();+ await connect(true, width === 800);+ await page+ .locator('textarea')+ .fill(Array(lines).fill('只检查布局,不发送消息。').join('\n'));+ const result = await page.evaluate(() => {+ const chip = document.querySelector('[data-controlled-banner-chip]');+ const input = document.querySelector('textarea');+ const send = input.parentElement.querySelector('button[aria-label="发送消息"]');+ const revoke = chip.querySelector('button');+ const cr = chip.getBoundingClientRect(),+ card = input.parentElement.getBoundingClientRect();+ const accessible = (element) => {+ const r = element.getBoundingClientRect();+ return element.contains(+ document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2),+ );+ };+ return {+ centerDelta: Math.abs(cr.x + cr.width / 2 - card.x - card.width / 2),+ noticeAbove: cr.bottom <= card.y,+ actionsAccessible: [+ input,+ send,+ revoke,+ chip.querySelector('[data-controlled-banner-collapse]'),+ ].every(accessible),+ overflow: document.documentElement.scrollWidth > innerWidth,+ };+ });+ assert(result.centerDelta < 1, `Notice is not centered: ${scenario}`);+ assert(+ result.noticeAbove && result.actionsAccessible && !result.overflow,+ `Overlap/overflow: ${scenario}`,+ );+ const capture =+ screenshots &&+ sidebar === 280 &&+ ((theme === 'light' && width === 1280 && lines === 1) ||+ (theme === 'dark' && width === 720 && lines === 8));+ const imageName = `group-control-${theme}-${width === 1280 ? 'wide' : 'narrow'}`;+ if (capture) await page.screenshot({ path: path.join(screenshots, `${imageName}.png`) });+ await collapse();+ const collapsed = await page.evaluate(() => {+ const dot = document.querySelector('[data-controlled-banner="collapsed"]');+ const r = dot.getBoundingClientRect();+ const card = document.querySelector('textarea').parentElement.getBoundingClientRect();+ return {+ centerDelta: Math.abs(r.x + r.width / 2 - card.x - card.width / 2),+ above: r.bottom <= card.y,+ accessible: dot.contains(+ document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2),+ ),+ };+ });+ assert(+ collapsed.centerDelta < 1 && collapsed.above && collapsed.accessible,+ `Collapsed indicator misplaced or blocked: ${scenario}`,+ );+ if (capture)+ await page.screenshot({ path: path.join(screenshots, `${imageName}-collapsed.png`) });+ await expand();+ // Both native button activation keys must preserve the full UI-only cycle.+ for (const key of ['Enter', 'Space']) {+ await activateWithKeyboard('[data-controlled-banner-collapse]', key);+ await page.locator('[data-controlled-banner="collapsed"]').waitFor();+ assert.equal(await page.locator('[data-controlled-banner-chip]').count(), 0);+ await activateWithKeyboard('[data-controlled-banner="collapsed"]', key);+ await page.locator('[data-controlled-banner-chip]').waitFor();+ assert.equal(await page.locator('[data-controlled-banner="collapsed"]').count(), 0);+ }+ // Revocation remains a separate button before X in the tab order.+ await page.locator('textarea').focus();+ await page.keyboard.press('Shift+Tab');+ await page.keyboard.press('Shift+Tab');+ assert(+ await page+ .locator('[data-controlled-banner-chip] button')+ .first()+ .evaluate((element) => element === document.activeElement),+ 'Revoke is not separately reachable',+ );+ assert.deepEqual(+ await page.evaluate(() => window.fixtureMutations),+ [],+ `Folding/restoring invoked a host mutation: ${scenario}`,+ );+ assert.equal(await page.getByRole('dialog').count(), 0);+ layouts++;+ }+ // A real long thread: connecting changes only the scroller viewport, not content.+ await page.setViewportSize({ width: 800, height: 600 });+ await page.goto(`http://fixture.local/?theme=${theme}&sidebar=280&thread=long`);+ await page.locator('textarea').waitFor();+ await page.waitForFunction(() => {+ const el = document.querySelector('main > div');+ return (+ el &&+ el.scrollHeight > el.clientHeight &&+ el.scrollHeight - el.clientHeight - el.scrollTop < 1+ );+ });+ await connect();+ assert((await bottomGap()) < 1, `Connection lost bottom pin (${theme})`);+ await collapse();+ assert((await bottomGap()) < 1, `Collapse lost bottom pin (${theme})`);+ await expand();+ assert((await bottomGap()) < 1, `Expand lost bottom pin (${theme})`);+ await connect(false);+ assert((await bottomGap()) < 1, `Disconnection lost bottom pin (${theme})`);+ const scroller = page.locator('main > div').first();+ const before = await scroller.evaluate((element) => {+ element.scrollTop = 180;+ element.dispatchEvent(new Event('scroll', { bubbles: true }));+ return element.scrollTop;+ });+ await connect();+ assert.equal(+ await scroller.evaluate((element) => element.scrollTop),+ before,+ `Connection jumped away from history (${theme})`,+ );+ await collapse();+ assert.equal(+ await scroller.evaluate((element) => element.scrollTop),+ before,+ `Collapse jumped away from history (${theme})`,+ );+ await expand();+ assert.equal(+ await scroller.evaluate((element) => element.scrollTop),+ before,+ `Expand jumped away from history (${theme})`,+ );+ await connect(false);+ assert.equal(+ await scroller.evaluate((element) => element.scrollTop),+ before,+ `Disconnection jumped away from history (${theme})`,+ );+ }+ assert.deepEqual(errors, []);+ console.log(+ `PASS: ${layouts} expanded/collapsed layouts with click, Tab, Enter and Space; no host mutations; bottom pin and history position survive connection and collapse changes in both themes.`,+ );+} finally {+ await browser?.close();+ rmSync(temp, { recursive: true, force: true });+}diff --git a/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsxnew file mode 100644index 0000000000..ff7e5d9822--- /dev/null+++ b/apps/desktop/scripts/fixtures/group-control/group-control-fixture.tsx@@ -0,0 +1,133 @@+import React from 'react';+import { createRoot } from 'react-dom/client';+import i18next from 'i18next';+import { initReactI18next } from 'react-i18next';+import { MemoryRouter, Routes, Route } from 'react-router-dom';+import zh from '../../../src/renderer/i18n/locales/zh-CN/common.json';+import '../../../src/renderer/themes/colors';+import { ThemeService } from '../../../src/renderer/themes/theme-service';+import { defaultLight } from '../../../src/renderer/themes/builtin/default-light';+import { defaultDark } from '../../../src/renderer/themes/builtin/default-dark';+import {+ FeatureSidebarSlotProvider,+ useFeatureContentHeader,+} from '../../../src/renderer/features/feature-context';+import { BotGroupChatView } from '../../../src/renderer/features/bots/BotGroupChatView';+import { ControlledBanner } from '../../../src/renderer/features/remote-device/ControlledBanner';+import { ConfirmDialogProvider } from '../../../src/renderer/components/ui/confirm-dialog-provider';+const q = new URLSearchParams(location.search);+const dark = q.get('theme') === 'dark';+new ThemeService().applyTheme(dark ? defaultDark : defaultLight);+document.documentElement.classList.toggle('dark', dark);+await i18next+ .use(initReactI18next)+ .init({+ lng: 'zh-CN',+ resources: { 'zh-CN': { translation: zh } },+ interpolation: { escapeValue: false },+ });+const member = (botId: string, name: string) => ({+ botId,+ name,+ avatar: '',+ avatarColor: 'gray',+ status: 'active',+});+const group = {+ id: 'fixture-group',+ name: '设计讨论',+ replyMode: 'all',+ speakingMode: 'auto',+ members: [member('a', 'Aster'), member('b', 'Nova')],+ organizerBotId: 'a',+ projectDir: null,+ lastMessage: null,+ speakingBotIds: [],+ planningBotId: null,+ openPlan: null,+ createdAt: 1,+ updatedAt: 1,+ plans: [],+ messages: q.has('thread')+ ? Array.from({ length: 40 }, (_, i) => ({+ id: `m${i}`,+ sequence: i + 1,+ kind: 'message',+ authorKind: 'user',+ authorBotId: null,+ authorName: '',+ content: `布局回归消息 ${i + 1}`,+ mentions: { all: false, botIds: [] },+ noticeCode: null,+ planId: null,+ files: [],+ createdAt: 1700000000000 + i,+ }))+ : [],+ hasMoreBefore: false,+ round: { status: 'idle', speakers: [], canContinue: false },+};+(window as any).fixtureMutations = [];+const blocked = () => {+ (window as any).fixtureMutations.push('forbidden mutation');+ throw Error('Fixture forbids mutations');+};+window.electronAPI = {+ maker: {+ listBotGroups: async () => ({ ok: true, groups: [] }),+ getBotGroup: async () => ({ ok: true, group }),+ onBotGroupChanged: () => () => {},+ sendBotGroupMessage: blocked,+ stopBotGroupRound: blocked,+ },+ deviceLink: {+ getState: async () => ({ controlledBy: [] }),+ onControlledState: (+ cb: (payload: { controllers: Array<{ deviceId: string; name: string }> }) => void,+ ) => {+ (window as any).fixturePush = cb;+ return () => {};+ },+ revoke: blocked,+ },+} as any;+function Header() {+ return <header>{useFeatureContentHeader()}</header>;+}+createRoot(document.getElementById('root')!).render(+ <MemoryRouter initialEntries={['/bots/groups/fixture-group']}>+ <ConfirmDialogProvider>+ <FeatureSidebarSlotProvider isCollapsed={false}>+ <div className="fixture-caption">+ {q.get('stage')} · {dark ? '深色' : '浅色'} · 生产群聊组件 Fixture,非实机+ </div>+ <div className="fixture-shell">+ <aside style={{ width: Number(q.get('sidebar')) }}>+ 伙伴+ <br />+ <br />+ Aster+ <br />+ <br />+ Nova+ <br />+ <br />+ 群聊+ <br />+ <br />+ 设计讨论+ </aside>+ <section className="fixture-content">+ <Header />+ <div className="fixture-view">+ <Routes>+ <Route path="/bots/groups/:groupId" element={<BotGroupChatView />} />+ </Routes>+ </div>+ </section>+ </div>+ <ControlledBanner />+ </FeatureSidebarSlotProvider>+ </ConfirmDialogProvider>+ </MemoryRouter>,+);diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex b73aee3f69..8889c4da3b 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@ -25,6 +25,7 @@ import {isDataOwnerPushCurrent,} from '@/contexts/dataOwnerGeneration';import { toast } from '@/lib/toast';+import { ControlledBanner, useControlledBy, useComposerCollapsed } from '@/features/remote-device/ControlledBanner';import { useAgentIslandActivity } from '@/state/agentIslandActivity';import type {BotGroupDetail,@@ -102,6 +103,11 @@ export function BotGroupChatView() {function BotGroupChatContent({ groupId }: { groupId: string }) {const { t, i18n } = useTranslation();+ const controlledBy = useControlledBy();+ const hasControlledBanner = controlledBy.length > 0;+ // Groups have no single task session; namespace their existing composer UI state.+ const controlledBannerKey = `bot-group:${groupId}`;+ const controlledBannerCollapsed = useComposerCollapsed(controlledBannerKey);const navigate = useNavigate();const location = useLocation();const [state, setState] = useState<GroupViewState>({ kind: 'loading' });@@ -231,7 +237,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {}, [group?.name, headerMembers, openSettings, separator, settingsLabel]);useRegisterContentHeader(header);- // Follow new messages only while the reader is already at the bottom.+ // Follow new messages and banner viewport changes only while the reader is at the bottom.const lastSequence = messages[messages.length - 1]?.sequence ?? 0;// Several Bots think at once in a broadcast round's first circle; the key follows the set.const speakingKey =@@ -246,7 +252,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {return;}if (stickToBottomRef.current) element.scrollTop = element.scrollHeight;- }, [lastSequence, speakingKey, messages.length]);+ }, [lastSequence, speakingKey, messages.length, hasControlledBanner, controlledBannerCollapsed]);// Markdown, code blocks and avatars finish layout after the first paint; keep a reader// who is at the bottom pinned there while the content grows.@@ -515,6 +521,14 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {))}</div></div>+ {hasControlledBanner && (+ // Like teammate chats, keep the collapsed breathing light above the composer.+ <div className="shrink-0 px-5 pt-2">+ <div className="mx-auto flex w-full max-w-[760px] justify-center px-2">+ <ControlledBanner placement="composer" sessionId={controlledBannerKey} />+ </div>+ </div>+ )}<BotGroupComposergroupId={group.id}members={group.members}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex d9f32f64ee..8fdc200b14 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@ -5,6 +5,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'viteimport { FeatureSidebarSlotProvider, useFeatureContentHeader } from '../../feature-context';import { BotGroupChatView } from '../BotGroupChatView';+import { ControlledBanner, __resetControlledBannerForTests } from '../../remote-device/ControlledBanner';import type {BotGroupChangedPayload,BotGroupDetail,@@ -13,6 +14,7 @@ import type {} from '../../../../shared/botGroupChat';const mocks = vi.hoisted(() => ({+ groupId: 'g1',navigate: vi.fn(),getBotGroup: vi.fn(),sendBotGroupMessage: vi.fn(),@@ -26,6 +28,9 @@ const mocks = vi.hoisted(() => ({openPath: vi.fn(),pushes: [] as Array<(payload: BotGroupChangedPayload, stamp?: unknown) => void>,toastError: vi.fn(),+ controlledPush: null as null | ((payload: { controllers: Array<{ deviceId: string; name: string }> }) => void),+ getControlledState: vi.fn(),+ revoke: vi.fn(),}));vi.mock('react-i18next', () => ({@@ -38,7 +43,7 @@ vi.mock('react-i18next', () => ({vi.mock('react-router-dom', () => ({useLocation: () => ({ pathname: '/bots/groups/g1', search: '' }),useNavigate: () => mocks.navigate,- useParams: () => ({ groupId: 'g1' }),+ useParams: () => ({ groupId: mocks.groupId }),}));vi.mock('@/contexts/dataOwnerGeneration', () => ({getDataOwnerGeneration: () => 1,@@ -46,6 +51,9 @@ vi.mock('@/contexts/dataOwnerGeneration', () => ({isDataOwnerPushCurrent: () => true,}));vi.mock('@/lib/toast', () => ({ toast: { error: mocks.toastError } }));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useConfirmDialog: () => ({ confirm: vi.fn(async () => false) }),+}));vi.mock('@/components/chat/MarkdownRenderer', () => ({MarkdownRenderer: ({ content }: { content: string }) => <div data-markdown>{content}</div>,}));@@ -197,6 +205,11 @@ function renderView() {}beforeEach(() => {+ mocks.groupId = 'g1';+ __resetControlledBannerForTests();+ mocks.controlledPush = null;+ mocks.getControlledState.mockReset().mockResolvedValue({ controlledBy: [] });+ mocks.revoke.mockReset();mocks.navigate.mockReset();mocks.toastError.mockReset();mocks.pushes = [];@@ -213,6 +226,14 @@ beforeEach(() => {Object.defineProperty(window, 'electronAPI', {configurable: true,value: {+ deviceLink: {+ getState: mocks.getControlledState,+ onControlledState: (callback: NonNullable<typeof mocks.controlledPush>) => {+ mocks.controlledPush = callback;+ return () => {};+ },+ revoke: mocks.revoke,+ },openPath: (...args: unknown[]) => mocks.openPath(...args),maker: {listBotGroups: vi.fn(async () => ({ ok: true, groups: [] })),@@ -239,6 +260,115 @@ beforeEach(() => {afterEach(cleanup);describe('BotGroupChatView', () => {+ it.each([true, false])('preserves the reader position when the notice changes (pinned=%s)', async (pinned) => {+ const view = renderView();+ await screen.findByRole('textbox');+ const scroller = view.container.querySelector('main > div') as HTMLDivElement;+ const main = scroller.parentElement!;+ let top = 0;+ // jsdom has no layout. Model a fixed content height and the viewport consumed+ // by the mounted notice; scrollTop follows the browser's clamping behavior.+ Object.defineProperties(scroller, {+ scrollHeight: { configurable: true, get: () => 1600 },+ clientHeight: {+ configurable: true,+ get: () => main.querySelector('[data-controlled-banner-chip]') ? 564+ : main.querySelector('[data-controlled-banner="collapsed"]') ? 572 : 600,+ },+ scrollTop: {+ configurable: true,+ get: () => top,+ set: (value: number) => { top = Math.min(value, scroller.scrollHeight - scroller.clientHeight); },+ },+ });+ scroller.scrollTop = pinned ? 1000 : 180;+ fireEvent.scroll(scroller);+ act(() => mocks.controlledPush?.({ controllers: [{ deviceId: 'studio', name: 'Mac Studio' }] }));+ expect(scroller.scrollTop).toBe(pinned ? 1036 : 180);+ fireEvent.click(screen.getByRole('button', { name: 'remoteDevice.collapseControlledNotice' }));+ expect(scroller.scrollTop).toBe(pinned ? 1028 : 180);+ fireEvent.click(screen.getByRole('button', { name: 'remoteDevice.expandControlledNotice' }));+ expect(scroller.scrollTop).toBe(pinned ? 1036 : 180);+ act(() => mocks.controlledPush?.({ controllers: [] }));+ expect(scroller.scrollTop).toBe(pinned ? 1000 : 180);+ });++ it('reuses the composer close and restore controls with independent group state', async () => {+ mocks.getBotGroup.mockImplementation(async () => ({ ok: true, group: detail({ id: mocks.groupId }) }));+ mocks.getControlledState.mockResolvedValue({+ controlledBy: [{ deviceId: 'studio', name: 'Mac Studio' }],+ });+ const fallback = render(<ControlledBanner />);+ let groupView = renderView();+ fireEvent.click(await screen.findByRole('button', { name: 'remoteDevice.collapseControlledNotice' }));+ expect(groupView.container.querySelector('[data-controlled-banner-chip]')).toBeNull();+ expect(screen.getByRole('button', { name: 'remoteDevice.expandControlledNotice' })).toBeTruthy();+ expect(fallback.container.childElementCount).toBe(0);+ expect(mocks.revoke).not.toHaveBeenCalled();+ expect(mocks.sendBotGroupMessage).not.toHaveBeenCalled();+ groupView.unmount();++ // A task with the same raw ID must not inherit the group's collapse state.+ const task = render(<ControlledBanner placement="composer" sessionId="g1" />);+ expect(task.container.querySelector('[data-controlled-banner-chip]')).toBeTruthy();+ task.unmount();+ mocks.groupId = 'g2';+ groupView = renderView();+ await screen.findByRole('textbox');+ expect(groupView.container.querySelector('[data-controlled-banner-chip]')).toBeTruthy();+ groupView.unmount();++ mocks.groupId = 'g1';+ groupView = renderView();+ await screen.findByRole('textbox');+ expect(groupView.container.querySelector('[data-controlled-banner-chip]')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'remoteDevice.expandControlledNotice' }));+ expect(groupView.container.querySelector('[data-controlled-banner-chip]')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'remoteDevice.revokeAccess' })).toBeTruthy();+ expect(fallback.container.childElementCount).toBe(0);+ });++ it('hosts the connection notice before the composer and restores the global fallback on exit', async () => {+ mocks.getControlledState.mockResolvedValue({+ controlledBy: [{ deviceId: 'studio', name: 'Mac Studio' }],+ });+ const fallback = render(<ControlledBanner />);+ const view = renderView();+ const input = await screen.findByRole('textbox');+ await waitFor(() => expect(fallback.container.childElementCount).toBe(0));+ expect(screen.getAllByText('remoteDevice.controlledBy:Mac Studio')).toHaveLength(1);+ const chip = view.container.querySelector('[data-controlled-banner-chip]')!;+ expect(chip).toBeTruthy();+ expect(chip.compareDocumentPosition(input) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(chip.closest('main')).toBe(input.closest('main'));+ expect(screen.getByRole('button', { name: 'remoteDevice.revokeAccess' })).toBeTruthy();++ fireEvent.change(input, { target: { value: '第一行\n第二行\n第三行' } });+ expect(view.container.querySelector('[data-controlled-banner-chip]')).toBe(chip);+ expect(fallback.container.childElementCount).toBe(0);+ expect(mocks.sendBotGroupMessage).not.toHaveBeenCalled();+ expect(mocks.revoke).not.toHaveBeenCalled();++ view.unmount();+ expect(fallback.container.querySelector('[data-controlled-banner-chip]')).toBeTruthy();+ });++ it('adds and removes the inline notice as connections change without leaving an empty row', async () => {+ const fallback = render(<ControlledBanner />);+ const view = renderView();+ await screen.findByRole('textbox');+ const main = view.container.querySelector('main')!;+ const originalRows = main.childElementCount;+ expect(main.querySelector('[data-controlled-banner-chip]')).toBeNull();+ act(() => mocks.controlledPush?.({ controllers: [{ deviceId: 'studio', name: 'Mac Studio' }] }));+ expect(main.childElementCount).toBe(originalRows + 1);+ expect(main.querySelector('[data-controlled-banner-chip]')).toBeTruthy();+ expect(fallback.container.childElementCount).toBe(0);+ act(() => mocks.controlledPush?.({ controllers: [] }));+ expect(main.childElementCount).toBe(originalRows);+ expect(document.querySelector('[data-controlled-banner-chip]')).toBeNull();+ });+it('renders user, teammate, notice and round-end rows with the header lockup', async () => {renderView();expect(await screen.findByText('周六 8:10 有票')).toBeTruthy();diff --git a/docs/design-evidence/2026-09-28/group-control-notice.md b/docs/design-evidence/2026-09-28/group-control-notice.mdnew file mode 100644index 0000000000..e9a5bce94d--- /dev/null+++ b/docs/design-evidence/2026-09-28/group-control-notice.md@@ -0,0 +1,38 @@+# 群聊连接提示证据索引++- PR:[makecindy/cindy#5174](https://github.com/makecindy/cindy/pull/5174)+- 验证代码提交:`45cde48fc1ee0904581e537e7012d1ceb9f5c625`+- 截图采集代码提交:`f0f8cc06d`(后续仅补测试,产品组件未变)+- 日期:2026-09-28+- 平台:macOS,headless Chromium,生产 BotGroupChatView / BotGroupComposer / ControlledBanner 与主题;IPC 数据和侧栏外壳为 fixture。+- 边界:非 Electron 实机,未操作真实设备、权限或消息。截图不是实机验收。++## 结果++普通聊天与伙伴使用同一 composer 提示;群聊现在复用其 X 收起和呼吸点恢复,撤权入口独立。群聊与伙伴没有 RunningStatusBar,呼吸点保留在输入框上方。++- 39 项定向组件测试通过;Desktop 类型检查通过。+- 24 场景:Light/Dark × 720/800/1280px × 侧栏 0/280px × 输入 1/8 行;800px 场景高度 600px 并使用长设备名。+- 所有场景:展开提示与收起呼吸点相对输入框中心偏差 <1px,位于输入框上方,无横向溢出;输入、发送、撤权和 X 的中心命中检查通过。+- 每个场景均执行鼠标点击及 Tab / Enter / Space 的展开→收起→恢复;无障碍名称与焦点环通过;撤权独立可达,收起/恢复不调用 fixture 写接口,也不弹出撤权确认框。+- 两种主题的长群聊在连接/断连及收起/恢复时保持贴底;已上翻阅读历史时保持位置。+- 既有普通任务/伙伴和全局兜底组件回归通过,共享组件未修改。++## 截图与复现++按 [治理合同 §6](../../design-rules/design-governance.md#6-证据合同),栅格文件只保留在 Git 忽略的临时目录,不提交到仓库。本 PR 尚未上传公开图片附件;下列命令可重建四张供审阅的 PNG,均带 fixture 标记。上传附件后可将对应 PR 评论链接追加到本索引。++```sh+node apps/desktop/scripts/check-group-control-layout.mjs /path/to/chromium tmp/group-control-evidence/review-screenshots+```++已目检:Light 1280px 单行、Dark 720px 八行,侧栏均为 280px;展开和收起各一张。保留的截图 SHA-256 用于核对原始文件;重跑时呼吸动画可能使图片字节不同。++| 文件 | SHA-256 |+| --- | --- |+| `group-control-dark-narrow-collapsed.png` | `47250bfcb855b26d1fc63622208e850b2b46ac0d6ac66b9aa183e54533b11233` |+| `group-control-dark-narrow.png` | `4704ff973e578ba70603e4b34b1a3447b3d8e725495e051ffaacd66fd943fd62` |+| `group-control-light-wide-collapsed.png` | `ed63ca746af94d067483012ba9fffc9fcba3d064bbe6b6faf530bbc8e38e9048` |+| `group-control-light-wide.png` | `74fa0382ef23e3c76a321498b154c355a9f2eecbda06b64f3c04e8162b3539fe` |++[截图存放方式的审核记录](https://github.com/makecindy/cindy/pull/5174#discussion_r4119073079)。