Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 稳定伙伴输入区与聊天界面身份 (#4588)
Chris Zhangb0d43b389add
diff --git a/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx b/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsxindex cf45ac5fa6..38ab7b5d38 100644--- a/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx@@ -60,7 +60,7 @@ function BotHistorySessionGateView() {.catch(() => {if (!cancelled) setAllowed(false);});- // 身份是装饰,拿不到就退回没有头像的只读历史——不因为它失败挡住整页。+ // Profile 装饰可异步补齐;已验证的伙伴历史始终保持伙伴界面。void window.electronAPI.localDb.bots.get(botId).then((bot) => {@@ -81,8 +81,13 @@ function BotHistorySessionGateView() {</main>);}- if (!allowed || !sessionId) {+ if (!allowed || !botId || !sessionId) {return <Navigate to={botId ? `/bots/${botId}?settings=1` : '/bots'} replace />;}- return <CCAgentSessionView readOnly {...(identity ? { botIdentity: identity } : {})} />;+ return (+ <CCAgentSessionView+ readOnly+ botIdentity={{ ...(identity ?? { id: botId, name: '' }), sessionId }}+ />+ );}diff --git a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx b/apps/desktop/src/renderer/features/bots/BotSessionView.tsxindex 3895f683de..7c4236afe8 100644--- a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx@@ -8,6 +8,7 @@ import { CCAgentSessionView } from '@/features/cc-agent/CCAgentSessionView';import type { ComposerBotMention } from '@/lib/fileTypes';import { getBotLastReadAt, markBotRead } from './botReadState';import type { BotChatIdentity } from './BotSessionContentHeader';+import type { BotChatBinding } from './botChatPresentation';import { useBotIslandVisibleSession } from './useBotIslandVisibleSession';type BotSessionGate =@@ -15,7 +16,7 @@ type BotSessionGate =| {kind: 'ready';mentions: ComposerBotMention[];- identity: BotChatIdentity;+ identity: BotChatBinding;/** True only for the Bot's own canonical chat (not a mounted channel route). */isCanonical: boolean;/** Read position captured before opening advances it; null when entry had no unread replies. */@@ -138,7 +139,7 @@ function BotSessionGateView() {isCanonical: activeProjection?.role === 'canonical',unreadBoundaryAt:activeProjection?.role === 'canonical' && unreadCount > 0 ? lastReadAt : null,- identity: readBotChatIdentity(bot, botId),+ identity: { ...readBotChatIdentity(bot, botId), sessionId },mentions: Array.isArray(bots)? bots.map((candidate) => readBotMention(candidate, botId))diff --git a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsxindex 5ac28bc256..0fe0be4249 100644--- a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx@@ -16,7 +16,7 @@ export function RemoteBotSessionView() {const { t } = useTranslation();const bots = useRemoteBots();const bot = bots.find((row) => row.id === botId && row.deviceId === deviceId);- const [ready, setReady] = useState<RemoteBot | null>(null);+ const [ready, setReady] = useState<(RemoteBot & { sessionId: string }) | null>(null);const [validatedSessionId, setValidatedSessionId] = useState<string | null | undefined>(null);const [failed, setFailed] = useState(false);const [retry, setRetry] = useState(0);@@ -65,7 +65,7 @@ export function RemoteBotSessionView() {if (readIsCurrent) remoteProjectsStore.mergeDeviceSessions(deviceId, currentMirror?.deviceLinkDeviceName ?? bot.deviceName, [isSessionReadCurrent.mergeActivity(session),]);- setReady(resolved);+ setReady({ ...resolved, sessionId: canonicalId });setValidatedSessionId(sessionId);})().catch(() => {if (!disposed) setFailed(true);diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChatPresentation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botChatPresentation.test.tsindex da139a1fa1..42f69163c3 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botChatPresentation.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChatPresentation.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { botComposerPlaceholderKey, isLatinBotName } from '../botChatPresentation';+import { botComposerPlaceholderKey, isLatinBotName, resolveBotChatIdentity } from '../botChatPresentation';describe('伙伴对话的输入框占位符', () => {it('西文名字两侧留空格,中文名不留', () => {@@ -23,3 +23,24 @@ describe('伙伴对话的输入框占位符', () => {expect(isLatinBotName('')).toBe(false);});});++describe('validated companion presentation binding', () => {+ const bot = { id: 'bot-1', name: 'Melody', sessionId: 'chat-1' };++ it('uses the validated route binding without requiring a hydrated runtime snapshot', () => {+ expect(resolveBotChatIdentity(bot, 'chat-1')).toBe(bot);+ expect(resolveBotChatIdentity({ ...bot, deviceId: 'remote' }, 'chat-1'))+ .toEqual({ ...bot, deviceId: 'remote' });+ });++ it('does not carry a companion identity into another task or an unbound route', () => {+ expect(resolveBotChatIdentity(bot, 'ordinary-task')).toBeNull();+ expect(resolveBotChatIdentity(bot, undefined)).toBeNull();+ expect(resolveBotChatIdentity(undefined, 'chat-1')).toBeNull();+ });++ it('keeps validated history simplified before the optional profile arrives', () => {+ const history = { id: 'bot-1', name: '', sessionId: 'history-1' };+ expect(resolveBotChatIdentity(history, 'history-1')).toBe(history);+ });+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.tsindex bb85249826..d624476da4 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChatSurface.test.ts@@ -4,7 +4,7 @@* 这三处判定都长在超大组件里(CCAgentSessionView 5k 行 / MessageStream 5.8k 行 /* ChatInput 8k 行),在 jsdom 里整棵挂起来既慢又脆。真正要锁死的是**判定条件本身**:* 头像与收控件只能对 Bot 会话生效,普通任务的渲染必须一字不改。所以这里锁源码契约,- * 纯逻辑部分(占位符选词、欢迎语幂等)另有真实单测。+ * 归属与状态稳定性由 botSessionPresentation / botChatPresentation 的行为测试覆盖。*/import { readFileSync } from 'node:fs';import { resolve } from 'node:path';@@ -20,12 +20,6 @@ const chatInput = read('components/new-chat/ChatInput.tsx');const botSettings = read('features/bots/BotsHomeView.tsx');describe('Bot 对话的判定条件', () => {- it('「这是跟伙伴的对话」需要路由身份与 session.source 同时成立', () => {- // URL 只是导航投影。少了 source 这一半,任何 /bots/... 链接都能把普通任务- // 伪装成伙伴对话。- expect(sessionView).toContain("botIdentity && session?.source === 'bot' ? botIdentity : null");- });-it('气泡头像只在 Bot 对话下传给消息流', () => {expect(sessionView).toContain('assistantAvatar={botAssistantAvatar}');expect(sessionView).toContain('<BotAvatar bot={botChatIdentity} size="sm" />');diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.tsindex 0b9f8ffe10..4cf117ac67 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.ts@@ -176,7 +176,7 @@ describe('Bot task route recovery', () => {// 只读历史也带头像与伙伴 lockup:这个视图本来就已经查过 history(botId) 确认归属。expect(history).toMatch(/window\.electronAPI\.localDb\.bots\s*\.get\(botId\)/);expect(history).toContain(- '<CCAgentSessionView readOnly {...(identity ? { botIdentity: identity } : {})} />',+ "botIdentity={{ ...(identity ?? { id: botId, name: '' }), sessionId }}",);});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsxnew file mode 100644index 0000000000..3bbdbef7a0--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx@@ -0,0 +1,70 @@+// @vitest-environment jsdom+import { act, cleanup, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { resolveBotChatIdentity, type BotChatBinding } from '../botChatPresentation';++const h = vi.hoisted(() => ({+ params: { botId: 'bot', sessionId: 'chat' },+ get: vi.fn(), list: vi.fn(), history: vi.fn(),+}));+vi.mock('react-router-dom', () => ({+ useParams: () => h.params,+ useNavigate: () => vi.fn(),+ Navigate: () => <div>unavailable</div>,+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('../useBotIslandVisibleSession', () => ({ useBotIslandVisibleSession: () => {} }));+vi.mock('@/features/cc-agent/CCAgentSessionView', () => ({+ CCAgentSessionView: ({ botIdentity }: { botIdentity?: BotChatBinding }) => {+ const identity = resolveBotChatIdentity(botIdentity, h.params.sessionId);+ return <div>{identity ? `companion:${identity.id}` : 'task controls'}</div>;+ },+}));+import { BotSessionView } from '../BotSessionView';+import { BotHistorySessionView } from '../BotHistorySessionView';++beforeEach(() => {+ h.params = { botId: 'bot', sessionId: 'chat' };+ h.get.mockReset(); h.list.mockReset().mockResolvedValue([]); h.history.mockReset();+ window.electronAPI = { localDb: { bots: { get: h.get, list: h.list, history: h.history } } } as unknown as Window['electronAPI'];+});+afterEach(cleanup);+it('mounts the simplified chat only after verifying the durable link, without another session GET', async () => {+ let resolve!: (value: unknown) => void;+ h.get.mockReturnValue(new Promise((done) => { resolve = done; }));+ render(<BotSessionView />);+ expect(screen.queryByText('task controls')).toBeNull();+ await act(async () => resolve({ id: 'bot', name: 'Melody', status: 'active', sessions: [+ { id: 'chat', kind: 'chat', status: 'active', role: 'canonical' },+ ] }));+ expect(screen.getByText('companion:bot')).toBeTruthy();+});+it('does not accept an arbitrary task id from a Bot URL', async () => {+ h.get.mockResolvedValue({ id: 'bot', status: 'active', sessions: [+ { id: 'different', kind: 'chat', status: 'active' },+ ] });+ await act(async () => { render(<BotSessionView />); });+ expect(screen.queryByText('companion:bot')).toBeNull();+ expect(screen.queryByText('task controls')).toBeNull();+});+it('retains companion presentation while history profile loading is pending or fails', async () => {+ let reject!: (reason: Error) => void;+ h.get.mockReturnValue(new Promise((_done, fail) => { reject = fail; }));+ h.history.mockResolvedValue([{ id: 'chat' }]);+ await act(async () => { render(<BotHistorySessionView />); });+ expect(screen.getByText('companion:bot')).toBeTruthy();+ await act(async () => reject(new Error('temporarily unavailable')));+ expect(screen.getByText('companion:bot')).toBeTruthy();+});+it('drops the previous binding synchronously when navigating to a different Bot task', async () => {+ h.get.mockResolvedValue({ id: 'bot', status: 'active', sessions: [+ { id: 'chat', kind: 'chat', status: 'active' },+ ] });+ const view = render(<BotSessionView />);+ await screen.findByText('companion:bot');+ h.get.mockReturnValue(new Promise(() => {}));+ h.params = { botId: 'other', sessionId: 'other-chat' };+ view.rerender(<BotSessionView />);+ expect(screen.queryByText('companion:bot')).toBeNull();+ expect(screen.queryByText('task controls')).toBeNull();+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsxindex 22599640f3..b81832e54e 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx@@ -8,6 +8,7 @@ const h = vi.hoisted(() => ({merge: vi.fn(),view: vi.fn(),online: true,+ lastReplyAt: 0,}));vi.mock('react-router-dom', () => ({ useParams: () => ({ deviceId: 'home', botId: 'writer' }) }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));@@ -23,6 +24,7 @@ vi.mock('../useRemoteBots', () => ({avatarColor: '',sessionId: 'old-canonical',online: h.online,+ lastReplyAt: h.lastReplyAt,},],}));@@ -44,6 +46,7 @@ vi.mock('@/features/cc-agent/CCAgentSessionView', () => ({import { RemoteBotSessionView } from '../RemoteBotSessionView';beforeEach(() => {h.online = true;+ h.lastReplyAt = 0;h.pin.mockReset();h.merge.mockReset();h.view.mockReset();@@ -70,13 +73,23 @@ it('resolves the latest canonical task and pins its host before mounting writablexpect.objectContaining({ id: 'new-canonical' }),]);expect(h.view).toHaveBeenLastCalledWith(- expect.objectContaining({ sessionIdProp: 'new-canonical', routeOwner: true, readOnly: false }),+ expect.objectContaining({+ sessionIdProp: 'new-canonical', routeOwner: true, readOnly: false,+ botIdentity: expect.objectContaining({ id: 'writer', sessionId: 'new-canonical' }),+ }),);+ const identity = h.view.mock.lastCall![0].botIdentity;+ const requestCount = h.invoke.mock.calls.length;+ h.lastReplyAt = 123;+ rerender(<RemoteBotSessionView />);+ expect(h.view.mock.lastCall![0].botIdentity).toBe(identity);+ expect(h.invoke).toHaveBeenCalledTimes(requestCount);h.online = false;rerender(<RemoteBotSessionView />);await waitFor(() =>expect(h.view).toHaveBeenLastCalledWith(expect.objectContaining({ readOnly: true })),);+ expect(h.view.mock.lastCall![0].botIdentity).toBe(identity);});it('never mounts a task with a mismatched authoritative source', async () => {h.invokediff --git a/apps/desktop/src/renderer/features/bots/botChatPresentation.ts b/apps/desktop/src/renderer/features/bots/botChatPresentation.tsindex 1771a0a7fa..cb2df0fa7e 100644--- a/apps/desktop/src/renderer/features/bots/botChatPresentation.ts+++ b/apps/desktop/src/renderer/features/bots/botChatPresentation.ts@@ -1,3 +1,5 @@+import type { BotChatIdentity } from './BotSessionContentHeader';+/*** Pure presentation rules for a teammate's chat, kept out of the 5k-line session* view so they are cheap to test.@@ -21,3 +23,14 @@ export function botComposerPlaceholderKey(name: string): string {? 'bots.chat.composerPlaceholderLatin': 'bots.chat.composerPlaceholder';}++/** The route gate supplies this only after checking the durable Bot/session link. */+export type BotChatBinding = BotChatIdentity & { sessionId: string };++/** Runtime snapshots can disappear during hydration/reconnect; ownership does not. */+export function resolveBotChatIdentity(+ binding: BotChatBinding | undefined,+ sessionId: string | undefined,+): BotChatIdentity | null {+ return binding && binding.sessionId === sessionId ? binding : null;+}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 8e7331a671..60b22e0791 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -201,11 +201,12 @@ import {import { openBackgroundTasksTab } from '@/features/right-sidebar/lib/openBackgroundTasksTab';import { openSubagentsTab } from '@/features/right-sidebar/lib/openSubagentsTab';import { BotAvatar } from '@/features/bots/BotAvatar';+import { BotSessionContentHeaderRegistration } from '@/features/bots/BotSessionContentHeader';import {- BotSessionContentHeaderRegistration,- type BotChatIdentity,-} from '@/features/bots/BotSessionContentHeader';-import { botComposerPlaceholderKey } from '@/features/bots/botChatPresentation';+ botComposerPlaceholderKey,+ resolveBotChatIdentity,+ type BotChatBinding,+} from '@/features/bots/botChatPresentation';import { isCurrentSubagentRunsChange } from '@/features/right-sidebar/plugins/subagents/subagentChangeFence';import { startSubagentTabDiscovery } from './subagentTabDiscovery';import { subscribeChatTaskFocus } from '@/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent';@@ -486,9 +487,9 @@ interface CCAgentSessionViewProps {/*** 本对话所属的伙伴身份(仅 Bot 路由传)。传入即把这个聊天当成「跟 TA 聊天」渲染:* 顶栏换成伙伴 lockup、assistant 气泡挂 TA 的头像、输入框使用伙伴称呼,保留标准权限入口。- * 判定仍与 `session.source === 'bot'` 双重成立才生效——URL 不是身份。+ * 调用方须先验证持久归属并绑定 sessionId;运行快照不决定伙伴界面身份。*/- botIdentity?: BotChatIdentity;+ botIdentity?: BotChatBinding;/** Entry-time read boundary for a Bot chat; preserved after the live read position advances. */botUnreadBoundaryAt?: number | null;}@@ -942,10 +943,9 @@ export function CCAgentSessionView({: null;const isOrcaLeadSessionView = session?.orcaRole === 'lead';- // 「这是一场跟伙伴的对话」的单一判据:路由声明的身份 + 任务自己的 source 双重成立。- // 只有 URL 说了不算 —— 那是导航投影,不是身份。- const botChatIdentity: BotChatIdentity | null =- botIdentity && session?.source === 'bot' ? botIdentity : null;+ // Bot route gates have already checked durable ownership. The async runtime+ // snapshot may be absent during load/reconnect; it must never change the skin.+ const botChatIdentity = resolveBotChatIdentity(botIdentity, sessionId);// 伙伴没有 RunningStatusBar,折叠呼吸灯继续留在输入框上方,不能随状态行一起消失。const showCenteredControlledBanner =hasControlledBanner && (!controlledBannerCollapsed || Boolean(botChatIdentity));diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex ddb23f66b2..209f7ef4ff 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -180,7 +180,7 @@ import {} from '@/session/SessionMenuSheet';import type { SessionMenuView } from '@/session/sessionMenu';import { SessionSearchNative } from '@/session/SessionSearchNative';-import { isHostManagedSession } from '@/session/hostManagedSession';+import { useHostManagedSession } from '@/session/hostManagedSession';import {interactionKind,isPendingInteractionCollapsed,@@ -2029,7 +2029,10 @@ export default function SessionScreen() {() => sessions.find((item) => item.id === sessionId) ?? null,[sessionId, sessions],);- const sessionManagedByHost = isHostManagedSession(currentSession);+ const sessionManagedByHost = useHostManagedSession(+ JSON.stringify([auth.accountGeneration, deviceId, sessionId]),+ currentSession,+ );const composerDeviceProviders = useDeviceProviders(deviceId || undefined, modelSheetOpen);const accountProvider = composerDeviceProviders.ready? composerDeviceProviders.providers.find((provider) => provider.id === currentSession?.providerId)diff --git a/apps/mobile/src/__tests__/hostManagedSession.test.ts b/apps/mobile/src/__tests__/hostManagedSession.test.tsindex 9fd365065e..97e4a182a3 100644--- a/apps/mobile/src/__tests__/hostManagedSession.test.ts+++ b/apps/mobile/src/__tests__/hostManagedSession.test.ts@@ -13,7 +13,7 @@ describe('host-managed Session presentation', () => {it('hides host-owned settings while preserving permission controls and the composer', () => {const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');- expect(source).toContain('const sessionManagedByHost = isHostManagedSession(currentSession);');+ expect(source).toContain('const sessionManagedByHost = useHostManagedSession(');expect(source).toContain('messageOnly={sessionManagedByHost}');const details = readFileSync(resolve(process.cwd(), 'src/session/SessionMenuSheet.tsx'), 'utf8');expect(details).toContain('visible && !messageOnly');diff --git a/apps/mobile/src/__tests__/useHostManagedSession.test.tsx b/apps/mobile/src/__tests__/useHostManagedSession.test.tsxnew file mode 100644index 0000000000..2773d526d9--- /dev/null+++ b/apps/mobile/src/__tests__/useHostManagedSession.test.tsx@@ -0,0 +1,40 @@+// @vitest-environment jsdom+import { act, createElement, StrictMode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { useHostManagedSession } from '@/session/hostManagedSession';++let container: HTMLDivElement;+let root: Root;+function Controls({ scope, session }: { scope: string; session: { source?: string } | null }) {+ const managed = useHostManagedSession(scope, session);+ return createElement('div', null, managed ? 'companion controls' : 'task controls');+}+const render = (scope: string, session: { source?: string } | null) => {+ act(() => root.render(createElement(StrictMode, null, createElement(Controls, { scope, session }))));+ return container.textContent;+};+beforeEach(() => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ container = document.createElement('div');+ document.body.append(container);+ root = createRoot(container);+});+afterEach(() => { act(() => root.unmount()); container.remove(); });++describe('mobile companion control lifetime', () => {+ it('does not flash task controls during first load, runtime refresh or reconnect', () => {+ expect(render('owner/device/bot', null)).toBe('companion controls');+ expect(render('owner/device/bot', { source: 'bot' })).toBe('companion controls');+ expect(render('owner/device/bot', null)).toBe('companion controls');+ expect(render('owner/device/bot', {})).toBe('companion controls');+ expect(render('owner/device/bot', { source: 'bot' })).toBe('companion controls');+ });+ it('restores ordinary controls and does not carry ownership across task/device/account changes', () => {+ for (const scope of ['owner/device/a', 'owner/device/b', 'owner/other/b', 'other/other/b']) {+ expect(render(scope, { source: 'desktop' })).toBe('task controls');+ expect(render(scope, null)).toBe('task controls');+ expect(render(scope, { source: 'bot' })).toBe('companion controls');+ }+ });+});diff --git a/apps/mobile/src/session/hostManagedSession.ts b/apps/mobile/src/session/hostManagedSession.tsindex d703a2b41c..5ceeceba3a 100644--- a/apps/mobile/src/session/hostManagedSession.ts+++ b/apps/mobile/src/session/hostManagedSession.ts@@ -1,3 +1,4 @@+import { useState } from 'react';import type { RemoteSession } from '@/session/types';/**@@ -9,3 +10,21 @@ export function isHostManagedSession(): boolean {return session?.source === 'bot';}++/** Keep presentation stable while the same task's remote snapshot is unavailable. */+export function useHostManagedSession(+ scope: string,+ session: Pick<RemoteSession, 'source'> | null | undefined,+): boolean {+ const [observed, setObserved] = useState<{ scope: string; managed: boolean | null }>(+ () => ({ scope, managed: session ? isHostManagedSession(session) : null }),+ );+ const previous = observed.scope === scope ? observed.managed : null;+ // A Bot's ownership cannot turn into an ordinary task during a runtime refresh.+ const managed = previous === true ? true : session ? isHostManagedSession(session) : previous;+ if (observed.scope !== scope || observed.managed !== managed) {+ setObserved({ scope, managed });+ }+ // Before the first authoritative snapshot, do not flash task-only controls.+ return managed !== false;+}diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex eff8c090fd..0bca7c0c04 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -67,6 +67,8 @@ Cindy Session,以父任务关系回到发起伙伴,但不冒充该伙伴或### 3.3 用户界面+伙伴界面由入口验证过的持久归属与任务 ID 决定,不随异步运行快照的缺失、刷新或重连回退为普通任务界面。历史资料尚未加载或暂时失败时也保留伙伴呈现;手机保留同一账号、设备与任务内已确认的伙伴身份。切换任务、设备或账号时不得复用旧身份。此呈现规则不替代宿主的权限与归属校验。+普通设置不显示“永久 Session”“手动压缩”“自动换 Session”或运行时 fallback 开关。健康、归档和故障信息可以在需要时呈现,但维护动作默认由系统完成。用户只管理伙伴,不管理容器。