Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sessions): open companion tasks in standard session UI on all clients
Chrisc33d0e0da22f
diff --git a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.tsindex 96cbf77d17..fa4850d0dc 100644--- a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts@@ -208,7 +208,7 @@ it('does not let another computer message a hidden teammate task through session// A cached search reply must respect a later hide just like a fresh query. Unit tier.it('rechecks companion search snippets on queued delivery without hiding ordinary tasks', async () => {let hidden = false;- setRemoteBotSessionLookup(async () => hidden ? 'hidden' : 'visible');+ setRemoteBotSessionLookup(async id => id === 'task' ? 'ordinary' : hidden ? 'hidden' : 'background');const ordinary = { session: { id: 'task' } };const personal = { session: { id: 'chat', companion: { id: 'bot' } }, contentHit: { preview: 'private' } };const page = { results: [ordinary, personal] };diff --git a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.tsindex 59f5d9564f..8d7663d476 100644--- a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts+++ b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts@@ -2,9 +2,9 @@ import { DL_HISTORY_QUERY_CHANNEL } from '@cindy/device-link';import { currentDbRpcAdmissionClass, type DbRpcAdmissionClass } from '../localDb/client/rpcAdmission.js';/**- * - ordinary / visible:正常可见;hidden:伙伴隐藏,任何远端读写都按不存在处理;- * - background:插件后台隐藏任务,只从列表类结果(任务列表、运行中列表)中排除,单任务读取- * 与操作照常,手机插件页可深链打开(未结束提示只回 id,已在源查询排除);missing:不存在。+ * ordinary / visible: listed tasks; background: owner-readable tasks omitted from+ * default lists (including hidden companion and plugin tasks). hidden: denied by+ * the current owner scope; missing: no record. Account/device authorization is upstream.*/export type RemoteBotSessionAccess = 'ordinary' | 'visible' | 'hidden' | 'background' | 'missing';@@ -182,18 +182,19 @@ export async function projectRemoteSessionResult(channel: string, value: unknownif (!lookup) throw new Error('[HOST_NOT_READY] History visibility is not ready');const row = record(value);if (!row || !Array.isArray(row.results)) return value;- // Search pages can wait in the transport cache while a companion is hidden.- // Re-check personal ownership before returning snippets or identity metadata.+ // Recheck exact records at delivery; a companion's sidebar visibility is not+ // permission to read this owner's task. The device/account boundary is upstream.const ids = [...new Set(row.results.flatMap(item => {- const id = record(record(record(item)?.session)?.companion)?.id;+ const id = record(record(item)?.session)?.id;return typeof id === 'string' ? [id] : [];}))];const access = batchLookup- ? await batchLookup(ids, 'bot')- : new Map(await Promise.all(ids.map(async id => [id, await lookup!(id, 'bot')] as const)));+ ? await batchLookup(ids, 'session')+ : new Map(await Promise.all(ids.map(async id => [id, await lookup!(id, 'session')] as const)));const results = row.results.filter(item => {- const id = record(record(record(item)?.session)?.companion)?.id;- return typeof id !== 'string' || access.get(id) === 'visible';+ const id = record(record(item)?.session)?.id;+ const status = typeof id === 'string' ? access.get(id) : undefined;+ return status === 'ordinary' || status === 'visible' || status === 'background';});return { ...row, results };}diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.tsindex c8bb8b03df..6e5bfd054a 100644--- a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts@@ -51,10 +51,6 @@ describe('conversationSearch source invariants', () => {expect(conversationSearchSource).toContain('normalizeWorkingDirForGrouping');});- it('excludes Orca workers from searchable sessions', () => {- expect(conversationSearchSource).toContain("ne(sessions.orcaRole, 'worker')");- });-it('scopes content retrieval to searchable session ids including global search', () => {expect(conversationSearchSource).toContain('sessionIds: allowedSessionIds');expect(conversationSearchSource).not.toContain(@@ -272,7 +268,7 @@ describe('conversationSearch recent activity SQL filtering', () => {});describe('conversationSearch plugin background tasks', () => {- it('excludes hidden tasks from title and content candidates', async () => {+ it('includes hidden tasks in title and content candidates', async () => {const db = createSearchDb();const client = makeSearchDbClient(db);setCurrentDbClient(client, 'test-user');@@ -285,9 +281,9 @@ describe('conversationSearch plugin background tasks', () => {insertSearchSession(db, 'background', 20, null);db.prepare('UPDATE sessions SET hidden_at = 5 WHERE id = ?').run('background');const response = await searchConversations({ query: 'needle', semanticMode: 'keyword' });- expect(response.results.map((result) => result.session.id)).toEqual(['shown']);+ expect(response.results.map((result) => result.session.id).sort()).toEqual(['background', 'shown']);expect(mocks.searchChatHistoryHybrid).toHaveBeenCalledWith(- expect.objectContaining({ sessionIds: ['shown'] }),+ expect.objectContaining({ sessionIds: expect.arrayContaining(['background', 'shown']) }),);} finally {clearCurrentDbClient(client);@@ -297,11 +293,11 @@ describe('conversationSearch plugin background tasks', () => {});// Production search entry + real SQLite. The prior source-only test could not-// catch missing companion transcripts and accidentally exposed remote lanes. DB tier.+// catch missing companion transcripts. Owner search now covers all sources. DB tier.describe('conversationSearch personal companion chats', () => {// 测试价值: searchConversations 必须返回本机渠道记录并标成只读, 旧覆盖只验证渠道被排除。- // 最小输入: 一条渠道链接(含迁移来源)及同词消息; 验证远程、删除与群专线仍不放行。DB tier。- it('finds local channel transcripts like history while retaining remote and deletion boundaries', async () => {+ // 最小输入: 渠道、群专线、后台任务及同词消息; 主人跨电脑可读,删除记录仍排除。DB tier。+ it('finds every owner task locally and remotely while retaining deletion boundaries', async () => {const db = createSearchDb();const client = makeSearchDbClient(db);setCurrentDbClient(client, 'test-user');@@ -329,7 +325,7 @@ describe('conversationSearch personal companion chats', () => {if (role) db.prepare('INSERT INTO bot_session_links VALUES (?, ?, ?)').run(id, 'bot', role);}const result = await searchConversations({ query: 'needle', semanticMode: 'keyword' });- const localIds = ['channel', 'feishu-channel', 'imported', 'main', 'old', 'old-channel', 'task'];+ const localIds = ['channel', 'feishu-channel', 'group', 'imported', 'main', 'old', 'old-channel', 'review', 'task'];expect(result.results.map(item => item.session.id).sort()).toEqual(localIds);expect(result.results.find(item => item.session.id === 'old')?.session.companion).toEqual({id: 'bot', name: 'Melody', role: 'history', readOnly: true,@@ -344,10 +340,10 @@ describe('conversationSearch personal companion chats', () => {const archived = await searchConversations({ query: 'needle', filters: { status: 'archived' } });expect(archived.results.map(item => item.session.id).sort()).toEqual(['imported', 'old', 'old-channel']);const remote = await searchConversations({ query: 'needle' }, { remoteVisibleOnly: true });- expect(remote.results.map(item => item.session.id)).toEqual(['task']);+ expect(remote.results.map(item => item.session.id).sort()).toEqual(localIds);db.exec("UPDATE bot_profiles SET hidden_at = NULL");const visibleRemote = await searchConversations({ query: 'needle', filters: { status: 'archived' } }, { remoteVisibleOnly: true });- expect(visibleRemote.results.map(item => item.session.id).sort()).toEqual(['imported', 'old']);+ expect(visibleRemote.results.map(item => item.session.id).sort()).toEqual(['imported', 'old', 'old-channel']);// A content-only hit must retain its client id and read-only owner so the// existing result handler can open history at the exact message.@@ -368,7 +364,7 @@ describe('conversationSearch personal companion chats', () => {contentHit: { messageId: 'channel-message', messageClientId: 'channel-client' },});const remoteContent = await searchConversations({ query: 'contentneedle' }, { remoteVisibleOnly: true });- expect(remoteContent.results).toEqual([]);+ expect(remoteContent.results).toEqual(content.results);db.exec("UPDATE bot_profiles SET status = 'deleting'");const deleting = await searchConversations({ query: 'needle' });expect(deleting.results.some(item => ['channel', 'feishu-channel', 'old-channel'].includes(item.session.id))).toBe(false);diff --git a/apps/desktop/src/main/localDb/conversationSearch.ts b/apps/desktop/src/main/localDb/conversationSearch.tsindex 58eed3ee17..4696a22ab6 100644--- a/apps/desktop/src/main/localDb/conversationSearch.ts+++ b/apps/desktop/src/main/localDb/conversationSearch.ts@@ -14,7 +14,6 @@ import type {ConversationSearchStatusFilter,} from '../../shared/conversationSearch.js';import { conversationSearchTitle } from '../../shared/conversationSearch.js';-import { DESKTOP_TASK_LIST_SESSION_SOURCES } from '../../shared/sessionSource.js';import type { SessionSource } from '../../shared/sessionSource.js';import { normalizeWorkingDirForGrouping } from '../../shared/workingDir.js';import { getDbClient } from './client/current.js';@@ -58,9 +57,8 @@ type SessionRow = typeof sessions.$inferSelect & {export interface ConversationSearchHostScope {/**- * Main-owned source scope. Undefined includes normal tasks and linked personal- * companion chats; null permits every source only when another authoritative- * filter (for example Bot-owned Session ids) already constrains the query.+ * Optional host-owned source restriction. Global owner search includes every+ * task source, including records omitted from the default sidebar.*/sessionSources?: readonly SessionSource[] | null;remoteVisibleOnly?: boolean;@@ -101,7 +99,7 @@ export async function searchConversations(// Read the host's local aliases alongside the full, already-authorized candidate// set, before ranking/limiting. Local renderer search keeps its existing behavior.const [candidates, aliasRows] = await Promise.all([- listSearchableSessions(filters, hostScope.sessionSources, hostScope.remoteVisibleOnly),+ listSearchableSessions(filters, hostScope.sessionSources),hostScope.remoteVisibleOnly? getDbClient().drizzle.select().from(projectAliases).orderBy(desc(projectAliases.updatedAt)): Promise.resolve([]),@@ -351,28 +349,18 @@ function normalizeSortBy(value: ConversationSearchSortBy | undefined): Conversatasync function listSearchableSessions(filters: NormalizedConversationSearchFilters,sessionSources: readonly SessionSource[] | null | undefined,- remoteVisibleOnly = false,): Promise<SessionRow[]> {if (sessionSources != null && sessionSources.length === 0) return [];const db = getDbClient().drizzle;const statusCond = statusCondition(filters.status);const agentCond = filters.agentKind === 'all' ? undefined : eq(sessions.agentKind, filters.agentKind);const sessionIdsCond = filters.sessionIds ? inArray(sessions.id, filters.sessionIds) : undefined;- const workerCond = or(isNull(sessions.orcaRole), ne(sessions.orcaRole, 'worker'));- // 插件后台隐藏任务不进入任何会话搜索;用户从插件详情页「后台任务」查看与接手。- const visibleCond = isNull(sessions.hiddenAt);const activityCutoff = cutoffForLastActivity(filters.lastActivity);// 兼容存量 DB 行:旧版 touchUserSendInDb 只写 user_send_at 不 bump updated_at,// 侧栏排序用 max(userSendAt, updatedAt),这里也同步用 OR 避免漏掉这些行。const activityCond = activityCutoff === null? undefined: or(gte(sessions.updatedAt, activityCutoff), gte(sessions.userSendAt, activityCutoff));- const personalChat = and(- inArray(botSessionLinks.role, remoteVisibleOnly- ? ['canonical', 'history']- : ['canonical', 'history', 'channel']),- ne(botProfiles.status, 'deleting'),- );return db.select({...getTableColumns(sessions),@@ -385,29 +373,12 @@ async function listSearchableSessions(.leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id)).leftJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId)).where(and(- sessionSources === undefined- ? or(inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES), personalChat)- : sessionSources === null ? undefined : inArray(sessions.source, sessionSources),- // Group lanes remain private to their group. IM lanes are searchable on- // their own computer only, including migrated lanes with ordinary sources.- or(- isNull(botSessionLinks.role),- and(ne(botSessionLinks.role, 'group'), ne(botSessionLinks.role, 'channel')),- remoteVisibleOnly ? undefined : and(- eq(botSessionLinks.role, 'channel'),- ne(botProfiles.status, 'deleting'),- ),- ),- remoteVisibleOnly ? or(isNull(botProfiles.id), eq(botSessionLinks.role, 'delegation'), and(- or(isNull(botProfiles.hiddenAt), eq(botProfiles.hiddenAt, 0)),- ne(botProfiles.status, 'archived'),- ne(botProfiles.status, 'deleting'),- )) : undefined,+ // Search is an explicit owner read, independent of the default sidebar scope.+ sessionSources == null ? undefined : inArray(sessions.source, sessionSources),+ or(isNull(botProfiles.id), ne(botProfiles.status, 'deleting')),statusCond,agentCond,sessionIdsCond,- workerCond,- visibleCond,activityCond,)).orderBy(desc(sessions.updatedAt));diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.db.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.db.test.tsindex a8ebbfc1a5..3f7f9bd48b 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.db.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.db.test.ts@@ -59,12 +59,12 @@ describe('remote visibility batch SQL', () => {it('preserves ordinary, visible, hidden, archived, orphan and missing access semantics', async () => {const ids = ['ordinary', 'visible', 'hidden', 'archived', 'orphan', 'missing'];expect(Object.fromEntries(await readRemoteBotSessionAccessBatch(ids))).toEqual({- ordinary: 'ordinary', visible: 'visible', hidden: 'hidden', archived: 'hidden', orphan: 'hidden', missing: 'missing',+ ordinary: 'ordinary', visible: 'visible', hidden: 'background', archived: 'background', orphan: 'background', missing: 'missing',});expect(Object.fromEntries(await readRemoteBotSessionAccessBatch(ids, 'bot'))).toEqual({ordinary: 'missing', visible: 'visible', hidden: 'hidden', archived: 'hidden', orphan: 'missing', missing: 'missing',});- expect(await readRemoteBotSessionAccess('hidden')).toBe('hidden');+ expect(await readRemoteBotSessionAccess('hidden')).toBe('background');});it('returns 1,000 authorized tasks in order without a per-row RPC burst or interactive admission', async () => {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.tsindex 1740ea5907..b762eb4a87 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.ts@@ -26,8 +26,8 @@ describe('batch DB visibility', () => {const select = vi.spyOn(h.db!, 'select');const ids = ['ordinary','visible','hidden','archived','orphan','missing','visible'];const result = await readRemoteBotSessionAccessBatch(ids, 'session');- expect(Object.fromEntries(result)).toEqual({ ordinary: 'ordinary', visible: 'visible', hidden: 'hidden',- archived: 'hidden', orphan: 'hidden', missing: 'missing' });+ expect(Object.fromEntries(result)).toEqual({ ordinary: 'ordinary', visible: 'visible', hidden: 'background',+ archived: 'background', orphan: 'background', missing: 'missing' });expect(select).toHaveBeenCalledTimes(1);for (const id of ids) expect(await readRemoteBotSessionAccess(id)).toBe(result.get(id));expect(Object.fromEntries(await readRemoteBotSessionAccessBatch(['v','h','a','no'], 'bot')))diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts b/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.tsindex aed02f980d..61ffc80b4b 100644--- a/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts+++ b/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts@@ -39,9 +39,10 @@ export async function readRemoteBotSessionAccessBatch(.where(inArray(sessions.id, chunk));if (!isDataOwnerBroadcastScopeCurrent(owner)) return denyAll();for (const row of rows) {- // 插件后台隐藏任务:列表类结果不返回,单任务读取/操作仍允许(插件页深链打开)。+ // Hidden is a listing preference, not an owner access boundary.+ // Companion history and orphaned transcripts remain readable by exact ID.access.set(row.id, row.source !== 'bot' ? (row.hiddenAt != null ? 'background' : 'ordinary')- : row.visible ? 'visible' : 'hidden');+ : row.visible && row.hiddenAt == null ? 'visible' : 'background');}}}diff --git a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.tsindex 392dfc2a8d..da5f65ddae 100644--- a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts+++ b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts@@ -31,7 +31,8 @@ vi.mock('@/lib/conversationSearchService', () => ({searchConversations: vi.fn(),}));-vi.mock('@/lib/orcaSessionIdentity', () => ({+vi.mock('@/lib/orcaSessionIdentity', async (importOriginal) => ({+ ...await importOriginal<typeof import('@/lib/orcaSessionIdentity')>(),resolveSessionRoute: vi.fn(),}));@@ -752,9 +753,8 @@ describe('ConversationSearchBox live search', () => {});});-// Real search control: a hidden/unloaded companion must not fall back to an-// ordinary writable task, and the selected message anchor must survive. Unit tier.-// 渠道结果同样必须使用现有历史路由与消息锚点; 不增加新 UI。既有个人历史覆盖缺少 channel。+// Explicit search opens the exact ordinary task regardless of companion role;+// the selected message anchor survives even without a loaded roster. Unit tier.it.each(['canonical', 'history', 'channel'] as const)('opens %s companion search results without the loaded roster', async role => {const hit = { messageId: 'message', messageClientId: 'client', role: 'assistant' as const,createdAt: '2026-10-20T00:00:00Z', snippet: null, preview: 'needle reply', score: 1, ftsRank: 1, vectorRank: null };@@ -772,7 +772,7 @@ it.each(['canonical', 'history', 'channel'] as const)('opens %s companion searchexpect(result.textContent).toContain('Melody');fireEvent.click(result);await waitFor(() => expect(navigate).toHaveBeenCalledWith(- role !== 'canonical' ? '/bots/bot/history/chat' : '/bots/bot/session/chat',+ '/cc-agent/chat',{ state: { searchJump: { kind: 'conversation-search', sessionId: 'chat', messageId: 'message', messageClientId: 'client' } } },));});diff --git a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsxindex 847879e6b5..e03f2d82a8 100644--- a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx+++ b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx@@ -1,3 +1,4 @@+import { standardSessionRoute } from '@/lib/orcaSessionIdentity';/*** 伙伴设置 →「消息平台」: 这位伙伴自己的 IM 机器人。*@@ -230,8 +231,8 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {<ConnectionGroups api={im} connectionId={view.id} botName={bot.name} />) : null}{view.botContextId && botImConnectionLanesSupported(im) ? (- <ConnectionLanes api={im} connectionId={view.id} botId={bot.id} botName={bot.name}- platform={platformName(view)} canOpenHistory={target.kind === 'local'} />+ <ConnectionLanes api={im} connectionId={view.id} botName={bot.name}+ platform={platformName(view)} deviceId={target.deviceId} />) : null}</li>);@@ -378,12 +379,11 @@ const LANE_KIND_KEY: Record<BotImConnectionLane['kind'], string> = {/*** 一条连接的「隐藏任务」小节: 主人私聊(伙伴主任务)、每个群 / 话题与其他人的私聊各一行,* 显示状态、最近活动和当前上下文里的消息数; 卡住时可以让某一条重新开始(同一条任务,- * 记录保留, 下一条消息换干净的上下文)。点击记录复用主界面的只读历史页, 不取消隐藏。+ * 记录保留, 下一条消息换干净的上下文)。点击记录打开原任务的普通界面, 不取消隐藏。*/-function ConnectionLanes({ api, connectionId, botId, botName, platform, canOpenHistory }: {- api: BotImConnectionApi | null; connectionId: string; botId: string; botName: string; platform: string;- /** The read-only history page lives on the teammate's computer; a remote teammate's lanes only list. */- canOpenHistory: boolean;+function ConnectionLanes({ api, connectionId, botName, platform, deviceId }: {+ api: BotImConnectionApi | null; connectionId: string; botName: string; platform: string;+ deviceId?: string;}) {const { t } = useBotTranslation();const navigate = useNavigate();@@ -552,8 +552,7 @@ function ConnectionLanes({ api, connectionId, botId, botName, platform, canOpenH<div key={lane.sessionId} className="flex items-center gap-3"><buttontype="button"- disabled={!canOpenHistory}- onClick={() => navigate(`/bots/${encodeURIComponent(botId)}/history/${encodeURIComponent(lane.sessionId)}`)}+ onClick={() => navigate(standardSessionRoute(lane.sessionId, deviceId))}className="min-w-0 flex-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"><span className="flex min-w-0 items-center gap-1.5">diff --git a/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx b/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsxindex 03bfe25ad3..a204b92ad5 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx@@ -1,3 +1,5 @@+import { useNavigate } from 'react-router-dom';+import { standardSessionRoute } from '@/lib/orcaSessionIdentity';/*** 群聊的「正在进行」:*@@ -44,6 +46,7 @@ function pendingBot(speaker: BotGroupLiveSpeaker) {export function BotGroupSpeakingLine({ speaker, showStatus = true }: { speaker: BotGroupLiveSpeaker; showStatus?: boolean }) {const { t } = useTranslation();const { member, sessionId, activity: speakerActivity } = speaker;+ const navigate = useNavigate();const live = useAgentIslandActivity(sessionId ?? '');const waiting = live?.phase === 'needs-interaction';return (@@ -77,6 +80,9 @@ export function BotGroupSpeakingLine({ speaker, showStatus = true }: { speaker:) : null}</p>) : null}+ {sessionId ? <Button type="button" variant="secondary" tone="quiet" size="sm" compact className="self-start" onClick={() => navigate(standardSessionRoute(sessionId))}>+ {t('bots.groupChat.progress.viewProcess')}+ </Button> : null}{sessionId && live?.phase === 'running' ? <BotGroupLivePreview sessionId={sessionId} /> : null}{sessionId ? <BotGroupPendingInteraction sessionId={sessionId} bot={pendingBot(speaker)} /> : null}</div>@@ -115,7 +121,7 @@ export function BotGroupProgressStrip({}) {const { t } = useTranslation();const [mountedAt] = useState(() => Date.now());- const [expanded, setExpanded] = useState(false);+ const navigate = useNavigate();const stepSpeaker = step? speakers.find((speaker) => speaker.activity === 'step' && speaker.member.botId === step.step.botId)?? speakers.find((speaker) => speaker.member.botId === step.step.botId)@@ -136,17 +142,15 @@ export function BotGroupProgressStrip({// that is not an action anyone should read.const rawAction = live?.compactDetail?.trim() || '';const action = isBotGroupNoReplyText(rawAction) ? '' : rawAction;- const canView = !!sessionId && live?.phase === 'running';+ const canView = !!sessionId;return (<div className="shrink-0 px-5 pt-2"><divdata-testid="bot-group-progress"- data-expanded={expanded && canView ? '' : undefined}- // A content-width capsule above the composer; opening the process turns it into a panel.- className={cn('mx-auto flex min-w-0 flex-col border border-[var(--border-default)] bg-[var(--surface-elevated)]',- expanded && canView ? 'w-full max-w-[760px] rounded-xl' : 'w-fit max-w-[min(760px,100%)] rounded-full')}+ // Process opens the existing task page; the strip stays compact.+ className="mx-auto flex min-w-0 flex-col border border-[var(--border-default)] bg-[var(--surface-elevated)] w-fit max-w-[min(760px,100%)] rounded-full">- <div className={cn('flex min-h-9 min-w-0 items-center gap-2 py-1', expanded && canView ? 'px-3' : 'pl-2 pr-1')}>+ <div className="flex min-h-9 min-w-0 items-center gap-2 py-1 pl-2 pr-1">{member ? <BotAvatar bot={member} size="xs" /> : null}<p role="status" aria-live="polite" className="flex min-w-0 flex-1 items-center gap-1 truncate text-12 leading-5 text-[var(--text-secondary)]">{workStep ? (@@ -167,8 +171,8 @@ export function BotGroupProgressStrip({</p><span className="flex shrink-0 items-center gap-1">{canView ? (- <Button type="button" variant="secondary" tone="quiet" size="sm" compact aria-expanded={expanded} onClick={() => setExpanded((value) => !value)}>- {t(expanded ? 'bots.groupChat.progress.hideProcess' : 'bots.groupChat.progress.viewProcess')}+ <Button type="button" variant="secondary" tone="quiet" size="sm" compact onClick={() => sessionId && navigate(standardSessionRoute(sessionId))}>+ {t('bots.groupChat.progress.viewProcess')}</Button>) : null}{canStopAll ? (@@ -206,14 +210,6 @@ export function BotGroupProgressStrip({)}</span></div>- {expanded && canView && sessionId ? (- <div className="flex min-w-0 flex-col gap-1 border-t border-[var(--border-default)] px-3 py-2">- {action ? (- <p className="min-w-0 truncate text-12 text-[var(--status-bar-accent)]">{action}</p>- ) : null}- <BotGroupLivePreview sessionId={sessionId} lines={8} className="text-12" />- </div>- ) : null}</div></div>);diff --git a/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx b/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsxindex 5ea7b02913..9b827900bb 100644--- a/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx@@ -1,144 +1,9 @@-import { useEffect, useState } from 'react';import { Navigate, useLocation, useParams } from 'react-router-dom';-import { useTranslation } from 'react-i18next';+import { standardSessionRoute } from '@/lib/orcaSessionIdentity';-import { CCAgentSessionView } from '@/features/cc-agent/CCAgentSessionView';-import type { BotChatIdentity } from './BotSessionContentHeader';-import { readIslandEntryRouteState, requestIslandEntryAlertDisposal } from './islandEntryAlert';-import { useBotIslandVisibleSession } from './useBotIslandVisibleSession';-import { useBotPluginFocusedSession } from './useBotPluginFocusedSession';-import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';-import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';-import type { Session } from '@/lib/ccAgent.types';--function readBotChatIdentity(bot: unknown, botId: string): BotChatIdentity | null {- if (!bot || typeof bot !== 'object') return null;- const candidate = bot as { name?: unknown; avatar?: unknown; avatarColor?: unknown };- return {- id: botId,- name: typeof candidate.name === 'string' ? candidate.name : '',- avatar: typeof candidate.avatar === 'string' ? candidate.avatar : null,- avatarColor: typeof candidate.avatarColor === 'string' ? candidate.avatarColor : null,- };-}--/** History and hidden IM transcripts share the main-window read-only task view. */+/** Keep existing history links valid without a second task skin or read-only wrapper. */export function BotHistorySessionView() {- const { botId, sessionId, deviceId } = useParams();- return <BotHistorySessionGateView key={JSON.stringify([deviceId, botId, sessionId])} />;-}--function BotHistorySessionGateView() {- const { t } = useTranslation();- const { botId, sessionId, deviceId } = useParams();- const [allowed, setAllowed] = useState<boolean | null>(null);- useBotPluginFocusedSession(allowed === true && !deviceId ? sessionId ?? null : null);- useBotIslandVisibleSession(allowed === true ? sessionId ?? null : null);- // 灵动岛点进来的那张卡,只在本门禁确认并显示了这段历史后才处置;被重定向走则保留。- const islandEntryId = readIslandEntryRouteState(useLocation().state);- useEffect(() => {- if (allowed === true && sessionId && islandEntryId) requestIslandEntryAlertDisposal(sessionId, islandEntryId);- }, [allowed, sessionId, islandEntryId]);- /**- * 归档的对话里,那个伙伴仍然是那个伙伴:气泡挂 TA 的头像,顶栏是 TA 的 lockup。- * 这个视图本来就已经查过 `bots.history(botId)` 确认归属,顺手把身份取回来即可- * ——只读路径,不影响任何写入。- */- const [identity, setIdentity] = useState<BotChatIdentity | null>(null);-- useEffect(() => {- let cancelled = false;- const owner = getDataOwnerGeneration();- const current = () => !cancelled && isDataOwnerGenerationCurrent(owner);- if (!botId || !sessionId) {- setAllowed(false);- return () => {- cancelled = true;- };- }- const profile = deviceId- ? window.electronAPI.deviceLink.invoke(deviceId, 'local-db:bots:get', [botId])- : window.electronAPI.localDb.bots.get(botId);- const personalLink = (bot: unknown) => {- const rows = (bot as { sessions?: Array<{ id: string; role?: string; status?: string }> } | null)?.sessions;- return rows?.some(row => row.id === sessionId && row.status !== 'deleted'- && (row.role === 'history' || row.role === 'canonical'- || (!deviceId && row.role === 'channel'))) ?? false;- };- const history = deviceId- ? profile.then(bot => personalLink(bot) ? [{ id: sessionId }] : [])- : window.electronAPI.localDb.bots.history(botId).then(async rows =>- rows.some(row => (row as { id?: string })?.id === sessionId)- ? rows- : personalLink(await profile) ? [{ id: sessionId }] : []);- void history- .then(async (rows) => {- if (!current()) return;- const found = rows.some(- (row) =>- !!row &&- typeof row === 'object' &&- 'id' in row &&- typeof (row as { id?: unknown }).id === 'string' &&- (row as { id: string }).id === sessionId,- );- if (found && deviceId) {- const origin = remoteProjectsStore.getSessionDeviceId(sessionId);- if (origin && origin !== deviceId) throw new Error('Conflicting remote session owner');- remoteProjectsStore.pinSessionOrigin(deviceId, sessionId);- const isReadCurrent = remoteProjectsStore.captureSessionRead(deviceId, sessionId);- const value = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:get', [sessionId]);- if (!current()) return;- const readIsCurrent = isReadCurrent();- const mirror = remoteProjectsStore.getDeviceSessions(deviceId).find(row => row.id === sessionId);- const session = readIsCurrent ? value as Session | null : mirror;- if (!session || session.id !== sessionId- || (session.status !== 'active' && session.status !== 'archived')- || (!readIsCurrent && session.deviceLinkConnectionStatus !== 'connected')) {- throw new Error('Invalid remote companion history');- }- // The shared chat reads remote metadata only from this mirror, including- // the header. Preserve the status bucket and any newer push/activity.- if (readIsCurrent) remoteProjectsStore.mergeDeviceSessions(- deviceId, remoteProjectsStore.getDeviceName(deviceId) ?? deviceId,- [isReadCurrent.mergeActivity(session)], session.status,- );- }- setAllowed(found);- })- .catch(() => {- if (current()) setAllowed(false);- });- // Profile 装饰可异步补齐;已验证的伙伴历史始终保持伙伴界面。- void profile- .then((bot) => {- if (current()) setIdentity(readBotChatIdentity(bot, botId));- })- .catch(() => {- if (current()) setIdentity(null);- });- return () => {- cancelled = true;- };- }, [botId, sessionId, deviceId]);-- if (allowed === null) {- return (- <main className="flex h-full items-center justify-center bg-[var(--surface)]">- <p className="text-13 text-[var(--text-secondary)]">{t('ccAgent.common.loading')}</p>- </main>- );- }- if (!allowed || !botId || !sessionId) {- return <Navigate to={botId- ? deviceId ? `/bots/remote/${encodeURIComponent(deviceId)}/${encodeURIComponent(botId)}`- : `/bots/${encodeURIComponent(botId)}?settings=1`- : '/bots'} replace />;- }- return (- <CCAgentSessionView- readOnly- botIdentity={{ ...(identity ?? { id: botId, name: '' }), sessionId, ...(deviceId ? { deviceId } : {}) }}- />- );+ const { sessionId, deviceId } = useParams();+ const { state } = useLocation();+ return <Navigate to={sessionId ? standardSessionRoute(sessionId, deviceId) : '/cc-agent'} state={state} replace />;}diff --git a/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx b/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsxindex 0a2941428f..af2fb9c510 100644--- a/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx+++ b/apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx@@ -9,8 +9,7 @@ import { BotPronounProvider, useBotTranslation } from './botPronounContext';import { BotSettings } from './BotsHomeView';import { useBotProfiles } from './botStore';import { useCompanionCloud } from './companionCloudStore';-import { isBotChannelLaneSession } from './botGroupLane';-import { BOT_DM_THREAD_PARAM } from './botDmThreadRoute';+import { standardSessionRoute } from '@/lib/orcaSessionIdentity';import { useRemoteBots } from './useRemoteBots';import { RemoteTeammateSettings } from './RemoteTeammateSettings';@@ -186,16 +185,7 @@ export function BotSettingsDrawer() {bot={bot}onBack={performClose}onOpenSession={(sessionId, searchJump) => {- const projection = bot.sessions.find((item) => item.id === sessionId);- // IM 专线的记录在 IM 里,不在伙伴页面打开。- if (isBotChannelLaneSession(projection)) return;- const route =- projection?.kind === 'history'- ? `/bots/${bot.id}/history/${sessionId}`- : projection?.kind === 'thread' && projection.threadRoot- ? `/bots/${bot.id}/session/${projection.threadRoot.rootSessionId}?${BOT_DM_THREAD_PARAM}=${sessionId}`- : `/bots/${bot.id}/session/${sessionId}`;- navigate(route, { state: searchJump ? { searchJump } : undefined });+ navigate(standardSessionRoute(sessionId), { state: searchJump ? { searchJump } : undefined });}}/></BotPronounProvider>diff --git a/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsx b/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsxindex 3f218d7876..f5cdeebd3e 100644--- a/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/RemoteTeammateSettings.tsx@@ -8,6 +8,7 @@ import { Spinner } from '@/components/ui/spinner';import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { extractIpcError } from '@/utils/ipcError';+import { standardSessionRoute } from '@/lib/orcaSessionIdentity';import type { BotSettingsOp } from '../../../shared/botRemoteSettings';import { BotPronounProvider } from './botPronounContext';import { BotSettings } from './BotsHomeView';@@ -153,12 +154,9 @@ function RemoteSettingsPages({ bot, ops, initialPage: requestedPage = 'home', beconst onOpenSession = useCallback((sessionId: string, searchJump?: ConversationSearchJump) => {- const projection = profile?.sessions.find((item) => item.id === sessionId);- const base = `/bots/remote/${encodeURIComponent(bot.deviceId)}/${encodeURIComponent(bot.id)}`;- if (projection?.kind === 'history') navigate(`${base}/history/${encodeURIComponent(sessionId)}`, { state: searchJump ? { searchJump } : undefined });- else if (projection?.role === 'canonical') navigate(base, { state: searchJump ? { searchJump } : undefined });+ navigate(standardSessionRoute(sessionId, bot.deviceId), { state: searchJump ? { searchJump } : undefined });},- [bot.deviceId, bot.id, navigate, profile],+ [bot.deviceId, navigate],);if (!profile) {diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex 85f374d2fd..ca96db7d8d 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@ -3183,7 +3183,8 @@ describe('Telegram / Slack-grade timeline', () => {expect(strip.textContent).not.toContain('NO_REPLY');mocks.activity = { compactDetail: '正在读 README.md', startedAtMs: Date.now() - 5_000, phase: 'running' };fireEvent.click(within(strip).getByRole('button', { name: 'bots.groupChat.progress.viewProcess' }));- await waitFor(() => expect(screen.getByTestId('bot-group-progress').textContent).toContain('正在读 README.md'));+ expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/plan-mimi');+ expect(mocks.stopBotGroupRound).not.toHaveBeenCalled();} finally {mocks.activity = null;}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsxindex e368128e54..97e39cec45 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx@@ -135,9 +135,9 @@ describe('BotChannelsPage', () => {expect(mocks.navigate).not.toHaveBeenCalled();});- // 测试价值: 真实列表点击应打开主界面只读详情, 旧覆盖只有重启; 最小输入为一条渠道记录。+ // 测试价值: 真实列表点击应打开普通任务页, 旧覆盖只有重启; 最小输入为一条渠道记录。// unit: 校验路由与副作用, 不需真实飞书连接。- it('opens each IM record in the existing history page without restarting it', async () => {+ it('opens each IM record in the ordinary task page without restarting it', async () => {const lanes = ['owner-dm', 'group', 'topic', 'guest-dm'].map((kind) => ({sessionId: `s/${kind}`, kind, chatId: '-1001', threadId: 'thread-1', name: kind,state: 'idle', lastActivityAt: null, contextMessageCount: 0,@@ -153,7 +153,7 @@ describe('BotChannelsPage', () => {const name = lane.kind === 'owner-dm' ? 'bots.channels.lanes.ownerName' : lane.name;const open = await screen.findByRole('button', { name: new RegExp(`^${name}`) });fireEvent.click(open);- expect(mocks.navigate).toHaveBeenLastCalledWith(`/bots/bot%2F1/history/${encodeURIComponent(lane.sessionId)}`);+ expect(mocks.navigate).toHaveBeenLastCalledWith(`/cc-agent/${encodeURIComponent(lane.sessionId)}`);}expect(lanesApi.resetLane).not.toHaveBeenCalled();expect(mocks.confirm).not.toHaveBeenCalled();@@ -579,14 +579,18 @@ describe('BotChannelsPage for a teammate on another computer', () => {state: 'idle', lastActivityAt: null, contextMessageCount: 0 };lanesApi = { listLanes: vi.fn(), resetLane: vi.fn(), archiveLane: vi.fn() };const archiveLane = vi.fn(async () => ({ connectionId: 'a1b2c3d4e5f6', lanes: [] }));+ const resetLane = vi.fn();const api = remoteApi({listLanes: vi.fn(async () => ({ connectionId: 'a1b2c3d4e5f6', lanes: [lane] })),- resetLane: vi.fn(),+ resetLane,...(supported ? { archiveLane } : {}),});const own = renderRemote(api);await expandTaskList();- expect((await screen.findByRole('button', { name: /^Remote room/ }) as HTMLButtonElement).disabled).toBe(true);+ const open = await screen.findByRole('button', { name: /^Remote room/ });+ expect((open as HTMLButtonElement).disabled).toBe(false);+ fireEvent.click(open);+ expect(mocks.navigate).toHaveBeenLastCalledWith('/cc-agent/remote-lane?device=mac');const archive = screen.queryByRole('button', { name: 'bots.channels.lanes.archiveAria:{"lane":"Remote room"}' });if (supported) {expect(archive).toBeTruthy();@@ -596,7 +600,7 @@ describe('BotChannelsPage for a teammate on another computer', () => {} else expect(archive).toBeNull();expect(own.listLanes).not.toHaveBeenCalled();expect(own.archiveLane).not.toHaveBeenCalled();- expect(mocks.navigate).not.toHaveBeenCalled();+ expect(resetLane).not.toHaveBeenCalled();});it('asks for credentials only on the other computer', async () => {diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsxindex 8e7d431cc3..0e4624e438 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx@@ -54,7 +54,7 @@ beforeEach(() => {afterEach(() => { cleanup(); vi.restoreAllMocks(); });describe.each([- ['chat', BotSessionView], ['history', BotHistorySessionView],+ ['chat', BotSessionView],] as const)('%s ownership and visibility', (_, View) => {it('waits for validation and discards the previous grant on route changes', async () => {let resolveGate!: (value: never) => void;@@ -156,80 +156,17 @@ describe('unavailable Bot task page never disposes island alerts by itself', ()});});-// 只读历史的提醒由它自己的归属门禁处置:灵动岛入口把点击编号放进路由状态,门禁确认并显示-// 这段历史后才请 main 处置;门禁不放行(会被重定向走)或没有点击编号都不处置。-describe('history ownership gate disposes the clicked island card', () => {- beforeEach(() => {- mocks.params = { botId: 'bot-a', sessionId: 'old-a' };- mocks.location = { state: { islandEntryId: '42' } };- });-- // 测试价值: 渠道专线不在 history() 中, 旧门禁无法显示; 最小输入是 get() 的 channel 投影。- // unit: 复用真实历史页验证只读挂载和归属失败时不处置提醒, 补齐既有历史用例的角色缺口。- it.each(['active', 'archived'])('shows an owned %s IM lane in the same read-only view', async (status) => {- history.mockResolvedValue([]);- get.mockResolvedValue({ ...profile, sessions: [{ id: 'old-a', kind: 'channel', role: 'channel', status }] });- const view = render(<BotHistorySessionView />);- // Flush the ownership promises and passive disposal effect, not just the DOM- // mutation (which can be observed before that effect commits on a busy runner).- await act(async () => {});- expect(view.getByTestId('chat').dataset.readonly).toBe('true');- expect(consumeEntryAlert).toHaveBeenCalledExactlyOnceWith('old-a', '42');- });-- it.each([- { id: 'other', role: 'channel', status: 'active' },- { id: 'old-a', role: 'channel', status: 'deleted' },- { id: 'old-a', role: 'group', status: 'active' },- { id: 'old-a', role: 'delegation', status: 'active' },- ])('does not grant IM transcript access from an unrelated/deleted projection: %j', async (projection) => {- history.mockResolvedValue([]);- get.mockResolvedValue({ ...profile, sessions: [projection] });- const view = render(<BotHistorySessionView />);- await act(async () => {});- expect(view.queryByTestId('chat')).toBeNull();- expect(consumeEntryAlert).not.toHaveBeenCalled();- });-- it('disposes only once its gate has shown the transcript', async () => {- let resolveGate!: (rows: unknown[]) => void;- history.mockReturnValueOnce(new Promise((resolve) => { resolveGate = resolve; }));- const view = render(<BotHistorySessionView />);- await act(async () => {});- expect(consumeEntryAlert).not.toHaveBeenCalled();- await act(async () => resolveGate([{ id: 'old-a' }]));- expect(view.getByTestId('chat')).toBeTruthy();- expect(consumeEntryAlert).toHaveBeenCalledExactlyOnceWith('old-a', '42');- // Re-rendering the same entry does not ask again; a new click on the open page does.- view.rerender(<BotHistorySessionView />);- mocks.location = { state: { islandEntryId: '43' } };- view.rerender(<BotHistorySessionView />);- expect(consumeEntryAlert).toHaveBeenLastCalledWith('old-a', '43');- expect(consumeEntryAlert).toHaveBeenCalledTimes(2);- });-- it('keeps the card when its gate redirects away (record gone or read failed)', async () => {- history.mockResolvedValueOnce([{ id: 'other' }]);- const gone = render(<BotHistorySessionView />);- await act(async () => {});- expect(gone.queryByTestId('chat')).toBeNull();- gone.unmount();- history.mockRejectedValueOnce(new Error('db busy'));- render(<BotHistorySessionView />);- await act(async () => {});- expect(consumeEntryAlert).not.toHaveBeenCalled();- });-- it('never disposes without an island click id', async () => {- mocks.location = { state: null };- history.mockResolvedValueOnce([{ id: 'old-a' }]);- const view = render(<BotHistorySessionView />);- await waitFor(() => expect(view.getByTestId('chat')).toBeTruthy());- expect(consumeEntryAlert).not.toHaveBeenCalled();- });+// The retired history wrapper only redirects; the standard task page owns alert recovery.+it('does not consume an error or acknowledge visibility merely by following a history URL', async () => {+ mocks.location = { state: { islandEntryId: '42' } };+ render(<BotHistorySessionView />);+ await act(async () => {});+ expect(consumeEntryAlert).not.toHaveBeenCalled();+ expect(report).not.toHaveBeenCalled();+ expect(get).not.toHaveBeenCalled();});-describe.each([BotSessionView, BotHistorySessionView])('validated task in front for plugins', (View) => {+describe.each([BotSessionView])('validated task in front for plugins', (View) => {// A companion chat is where someone uses the simulator; plugins were told "no task"// there, so "open in the current task" failed. Report it once ownership is proven.it('reports the validated chat, never an unowned route, and clears it on leave', async () => {diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.tsindex db15b0a741..61242d9e3b 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts@@ -59,12 +59,12 @@ function profile(over: Partial<BotProfile> = {}): BotProfile {describe('伙伴归属表', () => {// 测试价值: 灵动岛/通知统一入口遇到 IM channel 原先落入不可用的可写页。// 最小失败输入: 只有一条 channel 投影; unit, 直接验证生产路由结果。- it('opens hidden IM tasks through the read-only history gate', () => {+ it('opens hidden IM tasks in the ordinary task page', () => {const bot = profile({ sessions: [{ id: 's/feishu', role: 'channel', kind: 'channel', status: 'active' },] as BotProfile['sessions'] });expect(botRouteForOwnedSession([bot], 's/feishu')).toEqual({- route: '/bots/bot-a/history/s%2Ffeishu', consumesAlert: false, gateConsumesAlert: true,+ route: '/cc-agent/s%2Ffeishu', consumesAlert: false,});});@@ -104,11 +104,11 @@ describe('伙伴归属表', () => {] as unknown as BotProfile['sessions'],});expect(botRouteForOwnedSession([bot], 's-main')).toEqual({ route: '/bots/bot%2Fa', consumesAlert: false });- expect(botRouteForOwnedSession([bot], 's-telegram')).toEqual({ route: '/bots/bot%2Fa/session/s-telegram', consumesAlert: false });- expect(botRouteForOwnedSession([bot], 's-old')).toEqual({ route: '/bots/bot%2Fa/history/s-old', consumesAlert: false, gateConsumesAlert: true });+ expect(botRouteForOwnedSession([bot], 's-telegram')).toEqual({ route: '/cc-agent/s-telegram', consumesAlert: false });+ expect(botRouteForOwnedSession([bot], 's-old')).toEqual({ route: '/cc-agent/s-old', consumesAlert: false });expect(botRouteForOwnedSession([bot], 's-task')).toEqual({ route: '/cc-agent/s-task', consumesAlert: false });expect(botRouteForOwnedSession([bot], 's-worker')).toEqual({ route: '/cc-agent/s-worker', consumesAlert: false });- expect(botRouteForOwnedSession([bot], 's-lane')).toEqual({ route: '/bots/bot%2Fa', consumesAlert: true });+ expect(botRouteForOwnedSession([bot], 's-lane')).toEqual({ route: '/cc-agent/s-lane', consumesAlert: false });expect(botRouteForOwnedSession([bot], 'not-owned')).toBeNull();});@@ -116,7 +116,7 @@ describe('伙伴归属表', () => {const bot = profile({ id: 'bot/a' });expect(botRouteForOwnedSession([bot], 's-main')).toEqual({ route: '/bots/bot%2Fa', consumesAlert: false });expect(botRouteForOwnedSession([bot], 's-telegram')).toEqual({- route: '/bots/bot%2Fa/session/s-telegram',+ route: '/cc-agent/s-telegram',consumesAlert: false,});expect(botRouteForOwnedSession([bot], 'not-owned')).toBeNull();@@ -124,11 +124,10 @@ describe('伙伴归属表', () => {// 伙伴任务页只挂活的主对话;其它角色送过去只会落到「这个伙伴任务已不可用」,// 那里没有能处置报错的横幅,灵动岛上的报错卡就永远消不掉。- it('历史任务走只读历史路由,由历史页自己的归属门禁处置它的提醒', () => {+ it('历史任务走普通任务路由,由任务页处理提醒', () => {expect(botRouteForOwnedSession([profile()], 's-old')).toEqual({- route: '/bots/bot-a/history/s-old',+ route: '/cc-agent/s-old',consumesAlert: false,- gateConsumesAlert: true,});});@@ -165,9 +164,9 @@ describe('伙伴归属表', () => {{ id: 's-legacy-lane', role: 'group', kind: 'group' },] as unknown as BotProfile['sessions'],});- expect(botRouteForOwnedSession([bot], 's-lane')).toEqual({ route: '/bots/groups/g%2F1', consumesAlert: true });- expect(botRouteForOwnedSession([bot], 's-plan')).toEqual({ route: '/bots/groups/g-2', consumesAlert: true });- expect(botRouteForOwnedSession([bot], 's-legacy-lane')).toEqual({ route: '/bots/bot-a', consumesAlert: true });+ expect(botRouteForOwnedSession([bot], 's-lane')).toEqual({ route: '/cc-agent/s-lane', consumesAlert: false });+ expect(botRouteForOwnedSession([bot], 's-plan')).toEqual({ route: '/cc-agent/s-plan', consumesAlert: false });+ expect(botRouteForOwnedSession([bot], 's-legacy-lane')).toEqual({ route: '/cc-agent/s-legacy-lane', consumesAlert: false });});});@@ -196,12 +195,11 @@ describe('通知入口在伙伴投影未加载时的路由', () => {expect(loadProfiles).not.toHaveBeenCalled();});- it('启动后从未进过伙伴页时先加载投影,再回伙伴页', async () => {+ it('启动后从未进过伙伴页时先加载投影,再打开原历史任务', async () => {const { deps: d, loadProfiles } = deps({ loaded: [profile()] });await expect(resolveBotRouteForSessionEntry('s-old', d)).resolves.toEqual({- route: '/bots/bot-a/history/s-old',+ route: '/cc-agent/s-old',consumesAlert: false,- gateConsumesAlert: true,});expect(loadProfiles).toHaveBeenCalledWith(true);});@@ -374,19 +372,20 @@ describe('通知入口在伙伴投影未加载时的路由', () => {const targets: Record<string, BotSessionEntryTarget> = {'s-lane': { route: '/bots/groups/g-1', consumesAlert: true },'s-main': { route: '/bots/bot-a', consumesAlert: false },- 's-old': { route: '/bots/bot-a/history/s-old', consumesAlert: false, gateConsumesAlert: true },+ 's-old': { route: '/cc-agent/s-old', consumesAlert: false },};function setup(over: { openBotRoute?: (route: string, islandEntryId?: string) => void } = {}) {const openBotRoute = vi.fn(over.openBotRoute ?? (() => undefined));const consumeAlert = vi.fn();+ const openOrdinary = vi.fn();const open = createSessionEntryNavigator({readKnownBotRoute: (sessionId) => targets[sessionId] ?? null,resolveBotRoute: async () => null,openBotRoute,consumeAlert,- openOrdinary: vi.fn(),+ openOrdinary,});- return { open, openBotRoute, consumeAlert };+ return { open, openBotRoute, consumeAlert, openOrdinary };}const settle = async () => {await Promise.resolve();@@ -434,24 +433,12 @@ describe('通知入口在伙伴投影未加载时的路由', () => {expect(consumeAlert).not.toHaveBeenCalled();});- it('历史目标把点击编号交给历史页的归属门禁,导航器自己不处置', async () => {- const { open, openBotRoute, consumeAlert } = setup();+ it('历史任务交给普通任务页处理错误,不提前消除提醒', async () => {+ const { open, openOrdinary, consumeAlert } = setup();open.locationCommitted('/cc-agent/new');open('s-old', undefined, 'entry-6');await settle();- expect(openBotRoute).toHaveBeenLastCalledWith('/bots/bot-a/history/s-old', 'entry-6');- open.locationCommitted('/bots/bot-a/history/s-old');- // Already open: the click id is handed over again rather than consumed here.- open('s-old', undefined, 'entry-7');- await settle();- expect(openBotRoute).toHaveBeenLastCalledWith('/bots/bot-a/history/s-old', 'entry-7');- // Entries without a click id, and other targets, hand nothing over.- open('s-old');- await settle();- expect(openBotRoute).toHaveBeenLastCalledWith('/bots/bot-a/history/s-old', undefined);- open('s-lane', undefined, 'entry-8');- await settle();- expect(openBotRoute).toHaveBeenLastCalledWith('/bots/groups/g-1', undefined);+ expect(openOrdinary).toHaveBeenCalledWith('s-old', undefined, expect.any(Function));expect(consumeAlert).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsxindex f4f54d6f5c..01999e46d6 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx@@ -6,6 +6,7 @@ import { remoteProjectsStore, useRemoteProjectSessions } from '@/features/deviceconst h = vi.hoisted(() => ({params: { botId: 'bot', sessionId: 'chat', deviceId: undefined as string | undefined },+ redirect: vi.fn(),get: vi.fn(), list: vi.fn(), history: vi.fn(), invoke: vi.fn(),profiles: [] as Array<{ id: string; name: string; avatar: string; avatarColor: string; invitation?: { stage: string } }>,profileListeners: new Set<() => void>(),@@ -29,7 +30,7 @@ vi.mock('react-router-dom', () => ({useParams: () => h.params,useLocation: () => ({ state: null }),useNavigate: () => vi.fn(),- Navigate: () => <div>unavailable</div>,+ Navigate: (props: unknown) => { h.redirect(props); return <div>unavailable</div>; },}));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('../useBotIslandVisibleSession', () => ({ useBotIslandVisibleSession: () => {} }));@@ -50,6 +51,7 @@ import { BotHistorySessionView } from '../BotHistorySessionView';beforeEach(() => {h.params = { botId: 'bot', sessionId: 'chat', deviceId: undefined };+ h.redirect.mockClear();h.get.mockReset(); h.list.mockReset().mockResolvedValue([]); h.history.mockReset();h.invoke.mockReset(); remoteProjectsStore.clear(); remoteProjectsStore.__resetPinnedOriginsForTest();h.profiles = []; h.profileListeners.clear(); h.cloud = null;@@ -74,15 +76,7 @@ it('does not accept an arbitrary task id from a Bot URL', async () => {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' },@@ -130,45 +124,14 @@ it('never shows the first-hello wait in a channel-routed (non-canonical) task ofexpect((await screen.findByText('companion:bot')).getAttribute('data-invitation-stage')).toBe('');});-// Search can open archived canonical transcripts outside the history menu.-it('opens an archived canonical link read-only when absent from the history list', async () => {- h.history.mockResolvedValue([]);- h.get.mockResolvedValue({ id: 'bot', name: 'Melody', avatar: '🎵', sessions: [- { id: 'chat', role: 'canonical', status: 'archived' },- ] });- await act(async () => { render(<BotHistorySessionView />); });- const chat = screen.getByText('companion:bot');- expect(h.get).toHaveBeenCalledWith('bot');- expect(chat.getAttribute('data-name')).toBe('Melody');- expect(chat.getAttribute('data-avatar')).toBe('🎵');- expect(chat.getAttribute('data-device-id')).toBeNull();- expect(chat.getAttribute('data-read-only')).toBe('true');-});--it.each(['history', 'channel'])('checks remote %s links before displaying a searched transcript', async role => {- h.params.deviceId = 'remote';- h.invoke.mockResolvedValueOnce({ id: 'bot', name: 'Melody', avatar: '🎵', sessions: [- { id: 'chat', role, status: 'archived' },- ] }).mockResolvedValue({ id: 'chat', source: 'bot', title: 'Old conversation', status: 'archived' });+// Legacy URLs retain the exact task and host; the ordinary page owns access and recovery.+it.each([undefined, 'remote computer'])('redirects history to the ordinary task page (%s)', async deviceId => {+ h.params = { botId: 'bot', sessionId: 'old/task', deviceId };await act(async () => { render(<BotHistorySessionView />); });- expect(h.invoke).toHaveBeenCalledWith('remote', 'local-db:bots:get', ['bot']);+ expect(h.redirect).toHaveBeenCalledWith({ to: `/cc-agent/old%2Ftask${deviceId ? '?device=remote%20computer' : ''}`, state: null, replace: true });+ expect(h.get).not.toHaveBeenCalled();expect(h.history).not.toHaveBeenCalled();- if (role === 'history') {- const chat = screen.getByText('companion:bot');- expect(chat.getAttribute('data-name')).toBe('Melody');- expect(chat.getAttribute('data-avatar')).toBe('🎵');- expect(chat.getAttribute('data-device-id')).toBe('remote');- expect(chat.getAttribute('data-read-only')).toBe('true');- expect(h.invoke).toHaveBeenCalledWith('remote', 'local-db:sessions:get', ['chat']);- expect(remoteProjectsStore.getSessionDeviceId('chat')).toBe('remote');- expect(remoteProjectsStore.getDeviceSessions('remote', 'archived')).toEqual([- expect.objectContaining({ id: 'chat', status: 'archived', title: 'Old conversation' }),- ]);- } else {- expect(screen.getByText('unavailable')).toBeTruthy();- expect(remoteProjectsStore.getSessionDeviceId('chat')).toBeUndefined();- expect(h.invoke).toHaveBeenCalledTimes(1);- }+ expect(h.invoke).not.toHaveBeenCalled();});it('offers only teammates that run here to send to or delegate to, not copies that run elsewhere or were retired there', async () => {h.get.mockResolvedValue({ id: 'bot', name: 'Melody', status: 'active', sessions: [{ id: 'chat', kind: 'chat', status: 'active', role: 'canonical' }] });diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteTeammateSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteTeammateSettings.test.tsxindex afa5e5f132..faedc386af 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteTeammateSettings.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteTeammateSettings.test.tsx@@ -8,10 +8,10 @@* - 最小失败输入:主机未声明 management:settings;caps 被旧主机拒绝;离线且从未探测;同一伙伴/其它伙伴的推送。* - tier:unit(jsdom + 假的主机客户端)。*/-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { REMOTE_RESOURCE_CHANGED_CHANNEL } from '@cindy/device-link';-import { MemoryRouter } from 'react-router-dom';+import { MemoryRouter, useLocation } from 'react-router-dom';import { createIpcError } from '../../../../shared/ipc-errors';const h = vi.hoisted(() => ({@@ -34,9 +34,9 @@ vi.mock('../RemoteBotSettings', () => ({ RemoteBotSettings: ({ bot }: { bot: { dvi.mock('../BotsHomeView', async () => {const { useOptionalBotSettingsTarget } = await import('../botSettingsTarget');return {- BotSettings: ({ bot, initialPage }: { bot: { name: string }; initialPage: string }) => {+ BotSettings: ({ bot, initialPage, onOpenSession }: { bot: { name: string }; initialPage: string; onOpenSession(id: string): void }) => {const target = useOptionalBotSettingsTarget();- return <div data-testid="pages" data-page={initialPage} data-target={`${target?.kind}:${target?.deviceId}`}>{bot.name}</div>;+ return <div data-testid="pages" data-page={initialPage} data-target={`${target?.kind}:${target?.deviceId}`}>{bot.name}<button aria-label="Open channel task" onClick={() => onOpenSession('channel-task')} /></div>;},};});@@ -47,6 +47,10 @@ const bot = { id: 'bot-1', deviceId: 'mac', deviceName: 'Studio', name: 'Sora',const profile = (name: string) => ({ profile: { id: 'bot-1', name, description: '', avatar: '🙂', avatarColor: 'teal', status: 'active', skills: [], currentVersion: 1, createdAt: 1, sessions: [], capabilities: { harness: 'pi', model: 'm', modelChain: [], memory: true, permissions: 'ask' } } });const renderSettings = (ui: React.ReactElement) => render(<MemoryRouter>{ui}</MemoryRouter>);const props = { beforeCloseRef: { current: null }, onBack: vi.fn(), onDeleted: vi.fn() };+function LocationProbe() {+ const location = useLocation();+ return <output data-testid="route">{location.pathname}{location.search}</output>;+}beforeEach(() => {vi.useFakeTimers({ shouldAdvanceTime: true });@@ -78,6 +82,14 @@ it('falls back to the home page when the host cannot serve the requested page',expect((await screen.findByTestId('pages')).getAttribute('data-page')).toBe('home');});+// A channel selected from settings previously did nothing unless it was canonical/history.+// Unit tier: the actual settings consumer must navigate to the original device's ordinary task.+it('opens a selected task without requiring it in the loaded profile projection', async () => {+ renderSettings(<><LocationProbe /><RemoteTeammateSettings bot={bot} {...props} /></>);+ fireEvent.click(await screen.findByRole('button', { name: 'Open channel task' }));+ expect(screen.getByTestId('route').textContent).toBe('/cc-agent/channel-task?device=mac');+});+it('keeps the generic form page for a host that predates teammate settings', async () => {h.declares.mockResolvedValue(false);renderSettings(<RemoteTeammateSettings bot={bot} {...props} />);diff --git a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts b/apps/desktop/src/renderer/features/bots/botSessionOwners.tsindex 7bc6100bca..241f2f9ec0 100644--- a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts+++ b/apps/desktop/src/renderer/features/bots/botSessionOwners.ts@@ -12,8 +12,6 @@import type { BotSessionOwner } from '@/features/cc-agent/lib/projectGrouping';import type { BotProfile } from './botStore';import type { RemoteBot } from './remoteBotRoster';-import { isBotGroupLaneSession } from './botGroupLane';-import { BOT_DM_THREAD_PARAM } from './botDmThreadRoute';/*** Find the Bot that owns a real Cindy Session through the projected@@ -30,21 +28,7 @@ export function findBotProfileForSession();}-/**- * Where a session-only entry (notification / Agent Island click, task deep- * link) lands for a Bot-owned Session, and whether that target can dispose the- * clicked Agent Island card itself.- *- * Targets that render no disposal control for this Session's error dispose the- * clicked card instead: a hidden group lane lives inside its group chat (`consumesAlert`,- * once the route commits); a read-only history transcript re-checks ownership- * after it commits and may redirect away, so its gate disposes it once shown- * (`gateConsumesAlert`). Unread errors are immune to passive visibility acks,- * so without this the island card could never be cleared. Main only honours it- * for the card that was actually clicked, and only while that card is unchanged- * (see AgentIslandService.consumeIslandEntryAlert). A live chat keeps its own- * ErrorBanner as the only disposal path.- */+/** Destination of a session-only entry and ownership of its error acknowledgement. */export interface BotSessionEntryTarget {route: string;/** The entry navigator disposes the clicked card once this route has committed. */@@ -53,13 +37,8 @@ export interface BotSessionEntryTarget {gateConsumesAlert?: boolean;}-/**- * Resolve the public Bot route for a notification or other session-only entry.- * The stable main task stays on the short Bot route; history keeps its own- * read-only route, a group lane returns to its group and a private-chat topic- * opens beside its private chat.- * Background tasks keep their ordinary `/cc-agent/:sessionId` route with its- * message anchors and error controls; other live chats use the Bot session route.+/** The companion's main chat keeps its chat entry; every other task opens its ordinary page.+ * The task page owns error recovery, so navigation must not consume its alert.*/export function botRouteForOwnedSession(profiles: readonly BotProfile[],@@ -68,34 +47,11 @@ export function botRouteForOwnedSession(const bot = findBotProfileForSession(profiles, sessionId);if (!bot) return null;const botRoute = `/bots/${encodeURIComponent(bot.id)}`;- const projection = bot.sessions.find((session) => session.id === sessionId);- if (isBotGroupLaneSession(projection)) {- return {- route: projection?.groupId ? `/bots/groups/${encodeURIComponent(projection.groupId)}` : botRoute,- consumesAlert: true,- };- }- if ((projection?.kind === 'thread' || projection?.role === 'thread') && projection.threadRoot) {- // A private-chat topic has no page of its own: open the private chat with the topic beside it.- return {- route: `${botRoute}/session/${encodeURIComponent(projection.threadRoot.rootSessionId)}?${BOT_DM_THREAD_PARAM}=${encodeURIComponent(sessionId)}`,- consumesAlert: false,- };- }- if (projection?.kind === 'history' || projection?.role === 'history'- || projection?.kind === 'channel' || projection?.role === 'channel') {- // Its ownership gate re-checks after the route commits and may redirect away, so the- // gate itself disposes the card once it shows the transcript.- return { route: `${botRoute}/history/${encodeURIComponent(sessionId)}`, consumesAlert: false, gateConsumesAlert: true };- }const canonicalSessionId = bot.sessions.find((session) => session.role === 'canonical' || session.kind === 'chat',)?.id;if (canonicalSessionId === sessionId) return { route: botRoute, consumesAlert: false };- if (projection?.kind === 'worker' || projection?.role === 'delegation') {- return { route: `/cc-agent/${encodeURIComponent(sessionId)}`, consumesAlert: false };- }- return { route: `${botRoute}/session/${encodeURIComponent(sessionId)}`, consumesAlert: false };+ return { route: `/cc-agent/${encodeURIComponent(sessionId)}`, consumesAlert: false };}/**diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsxindex 233e67a0b8..194cf90ab0 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx@@ -1,3 +1,4 @@+import { standardSessionRoute } from '@/lib/orcaSessionIdentity';import { Button } from '@/components/ui/button';import { ErrorNotice } from '@/components/ui/error-notice';import {@@ -70,7 +71,6 @@ import { conversationSearchTitle } from '../../../../shared/conversationSearch';import { highlightSegments } from '../lib/highlightSegments';import { keywordRanges } from './keywordRanges';import { FilterReminderDot } from './FilterReminderDot';-import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';import { conversationSearchResultKey } from '@/lib/conversationSearchFanout';import {@@ -550,17 +550,7 @@ export function useConversationSearch({if (remoteDeviceId) {remoteProjectsStore.pinSessionOrigin(remoteDeviceId, item.session.id);}- const companion = item.session.companion;- const companionRoute = companion- ? remoteDeviceId- ? `/bots/remote/${encodeURIComponent(remoteDeviceId)}/${encodeURIComponent(companion.id)}`- : `/bots/${encodeURIComponent(companion.id)}`- : null;- const baseRoute = companionRoute- ? companion?.readOnly- ? `${companionRoute}/history/${encodeURIComponent(item.session.id)}`- : remoteDeviceId ? companionRoute : `${companionRoute}/session/${encodeURIComponent(item.session.id)}`- : await resolveSessionRoute(item.session.id, item.session);+ const baseRoute = standardSessionRoute(item.session.id, remoteDeviceId);const hit = hitOverride ?? item.contentHit;// popover 形态:onResultChosen 关闭面板并通知托盘(SidebarActionBar 减 openChildCount),// 其 reset() 会清空 query。内联展开态不传 onResultChosen——选中结果后**刻意保留 query**,diff --git a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts b/apps/desktop/src/renderer/lib/orcaSessionIdentity.tsindex 63acaaab08..ed8a191721 100644--- a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts+++ b/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts@@ -33,7 +33,7 @@ export function getSessionRouteOwnerId(route: string): string | null {}/**- * The Bot page for a Bot's own chat (main task, history, channel chat), read from+ * The companion entry for its main chat, or the ordinary page for other tasks, read from* the in-memory profile projection only: no IPC and no module load on a click. A* background task stays on its ordinary `/cc-agent/:id` route; an unloaded projection* falls back to the ordinary route too (the notification entry reloads it first).@@ -75,3 +75,8 @@ export async function resolveSessionRoute(return `/cc-agent/${sessionId}`;}++/** Open the exact task with the ordinary UI, without resolving its parent or companion. */+export function standardSessionRoute(sessionId: string, deviceId?: string | null): string {+ return `/cc-agent/${encodeURIComponent(sessionId)}${deviceId ? `?device=${encodeURIComponent(deviceId)}` : ''}`;+}diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsxindex 4518a2e162..5776e4c3f6 100644--- a/apps/mobile/app/devices/[deviceId].tsx+++ b/apps/mobile/app/devices/[deviceId].tsx@@ -76,7 +76,6 @@ import { useConversationSearchFilterMenu } from '@/session/useConversationSearchimport { HomeSearchBar } from '@/session/HomeSearchBar';import {conversationSearchAllowsLocalWrites,- conversationSearchCompanionParams,listConversationSearchProjects,shouldReplaceListWithSearchResults,} from '@/session/conversationSearch';@@ -548,7 +547,7 @@ function DeviceDetailScreenContent() {setBulkNotice(null);}, []);- const openSession = useCallback((targetSessionId: string, focusClientId?: string, companionParams?: Record<string, string>) => {+ const openSession = useCallback((targetSessionId: string, focusClientId?: string) => {if (swipeRegistry.closeOpenRow()) return;// 打开会话是远端交互,用当前(可达)设备 endpoint = 页面级 deviceId(对被认领会话即 canonical 当前设备,// 其物理机就是当前设备、可达)。不用会话物理旧 shard id:re-link 后旧设备不可达会导致会话根本打不开。@@ -561,7 +560,6 @@ function DeviceDetailScreenContent() {deviceId,deviceName,...(focusClientId ? { focusClientId } : {}),- ...companionParams,},});}, [deviceId, deviceName, guardedPush, swipeRegistry]);@@ -803,7 +801,6 @@ function DeviceDetailScreenContent() {onOpenSession={(it) => openSession(it.session.id,'searchFocusClientId' in it ? (it as { searchFocusClientId?: string }).searchFocusClientId : undefined,- conversationSearchCompanionParams(it),)}swipe={sessionSwipeControls}testID={`deviceDetail.automationRunRow.${item.session.id}`}@@ -940,7 +937,6 @@ function DeviceDetailScreenContent() {onOpenSession={(it) => openSession(it.session.id,'searchFocusClientId' in it ? (it as { searchFocusClientId?: string }).searchFocusClientId : undefined,- conversationSearchCompanionParams(it),)}onToggleAutomationGroup={toggleAutomationGroup}suppressBlockTopBorder={!!section.data[index - 1]?.automationGroup}@@ -1313,7 +1309,6 @@ function DeviceDetailScreenContent() {onOpenSession={(it) => openSession(it.session.id,'searchFocusClientId' in it ? (it as { searchFocusClientId?: string }).searchFocusClientId : undefined,- conversationSearchCompanionParams(it),)}onPressSelection={conversationSearchAllowsLocalWrites(item)? () => toggleSelection(sessionIdsForListItem(item))diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex c164bb3e14..b5adfcd011 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -11,7 +11,6 @@ import { getCachedDeviceProviders } from '@/device-link/deviceProvidersCache';import { MountOnFirstOpen } from '@/session/MountOnFirstOpen';import { RunningTokenRatePopover } from '@/session/RunningTokenRatePopover';import { companionConversationItems } from '@/session/companionConversationPresentation';-import { conversationSearchCompanionParams } from '@/session/conversationSearch';import { useRunningTokenRateHistory } from '@/session/useRunningTokenRateHistory';import { HomeHeaderGlassButton } from '@/session/HomeHeaderGlassButton';import { HomeNewTaskButton } from '@/session/HomeNewTaskButton';@@ -3125,7 +3124,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: Sconst focusClientId = 'searchFocusClientId' in item? (item as { searchFocusClientId?: string }).searchFocusClientId: undefined;- if (targetSession.id === sessionId && !focusClientId) {+ if (targetSession.id === sessionId && !focusClientId && !('searchLocallyCached' in item)) {closeSessionListDrawer();return;}@@ -3154,7 +3153,6 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: SdeviceName: targetSession.deviceLinkDeviceName ?? targetDeviceId,sessionId: targetSession.id,...(focusClientId ? { focusClientId } : {}),- ...conversationSearchCompanionParams(item),});});}, [closeSessionListDrawer, navigation, queueDrawerNavigation, sessionId, t]);diff --git a/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsx b/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsxindex 2e0a9a1a68..37f585eb3a 100644--- a/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupSpeakerRow.test.tsx@@ -4,6 +4,7 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';const h = vi.hoisted(() => ({+ push: vi.fn(),invoke: vi.fn(),subscribe: vi.fn(async () => undefined),unsubscribe: vi.fn(async () => undefined),@@ -18,7 +19,8 @@ vi.mock('react-native', () => ({View: ({ children, testID, accessibilityLabel }: any) => el('div', { 'data-testid': testID, 'aria-label': accessibilityLabel }, children),StyleSheet: { create: (value: unknown) => value },}));-vi.mock('expo-router', () => ({ useFocusEffect: (effect: () => void) => useEffect(effect, [effect]) }));+vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: ({ action }: any) => el('button', { onClick: action.onPress }, action.label) }));+vi.mock('expo-router', () => ({ useRouter: () => ({ push: h.push }), useFocusEffect: (effect: () => void) => useEffect(effect, [effect]) }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, options?: { name?: string }) => options?.name ? `${key}:${options.name}` : key }) }));vi.mock('lucide-react-native', () => ({ CircleAlert: () => null, Sparkles: () => null }));vi.mock('@/theme', () => ({ useThemedStyles: () => ({}), useTheme: () => ({ colors: {} }) }));@@ -102,3 +104,12 @@ it('does not subscribe without a lane or while the computer is offline', async (expect(h.subscribe).not.toHaveBeenCalled();expect(h.invoke).not.toHaveBeenCalled();});++// Regression: a group lane must open its original task on the correct computer.+it('opens the ordinary task with no companion wrapper or new execution', async () => {+ await render({ sessionId: 'group-lane', deviceId: 'studio', online: false });+ h.invoke.mockClear();+ await act(async () => node.querySelector('button')!.click());+ expect(h.push).toHaveBeenCalledWith({ pathname: '/sessions/[sessionId]', params: { sessionId: 'group-lane', deviceId: 'studio' } });+ expect(h.invoke).not.toHaveBeenCalled();+});diff --git a/apps/mobile/src/__tests__/CompanionChannelTasks.test.tsx b/apps/mobile/src/__tests__/CompanionChannelTasks.test.tsxnew file mode 100644index 0000000000..bccfea08e0--- /dev/null+++ b/apps/mobile/src/__tests__/CompanionChannelTasks.test.tsx@@ -0,0 +1,47 @@+// @vitest-environment jsdom+// Regression: IM records were inaccessible on both mobile presentations. Exercise the+// shared record picker with the real request envelope; opening must not reset a lane. Unit tier.+import { act, createElement } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import { CompanionChannelTasks } from '@/session/CompanionChannelTasks';+const h = vi.hoisted(() => ({ requests: [] as any[], supported: true, fail: false, refresh: vi.fn() }));+vi.mock('@/session/useRemoteCompanionQuery', () => ({ useRemoteCompanionQuery: (device: string, channel: string, args: any[], options: any) => {+ const request = args[0];+ if (options.enabled) h.requests.push({ device, channel, request });+ const op = request.input.op;+ const value = op === 'caps' ? { ops: h.supported ? ['channels.im.list', 'channels.im.listLanes'] : [] }+ : op === 'channels.im.list' ? { connections: [{ id: 'connection', botId: 'bot', channel: 'telegram' }, { id: 'other', botId: 'other-bot', channel: 'discord' }] }+ : { lanes: [{ sessionId: 'original-lane', name: 'Release group', chatId: 'group', kind: 'group' }] };+ return { value: options.enabled ? { result: { ok: !h.fail, value } } : null, error: false, refresh: h.refresh };+} }));+vi.mock('react-native', () => ({ View: ({ children }: any) => createElement('div', {}, children), StyleSheet: { create: (s: unknown) => s } }));+vi.mock('@/components/AppText', () => ({ Text: 'span' }));+vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: ({ action }: any) => createElement('button', { disabled: action.disabled, onClick: action.onPress }, action.label) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/theme', async () => { const tokens = await import('@/theme/tokens'); return { ...tokens, useThemedStyles: (make: any) => make(tokens.lightColors) }; });+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+const host = document.createElement('div');+let root = createRoot(host);+const open = vi.fn();+const render = (online = true) => act(async () => root.render(<CompanionChannelTasks deviceId="studio" botId="bot" online={online} onOpenTask={open} />));+afterEach(() => { act(() => root.unmount()); root = createRoot(host); h.requests = []; h.supported = true; h.fail = false; vi.clearAllMocks(); });+it('opens the exact channel task and only reads the selected connection on its computer', async () => {+ await render();+ expect(host.querySelectorAll('button')).toHaveLength(1);+ expect(h.requests.some(row => row.request.input.op === 'channels.im.listLanes')).toBe(false);+ await act(async () => host.querySelector('button')!.click());+ expect(h.requests.at(-1)).toMatchObject({ device: 'studio', channel: 'maker:remote-resources:invoke', request: {+ resourceRef: { id: 'bot' }, input: { v: 1, op: 'channels.im.listLanes', args: { id: 'connection' } },+ } });+ await act(async () => host.querySelectorAll('button')[1]!.click());+ expect(open).toHaveBeenCalledWith('original-lane');+ expect(h.requests.every(row => ['caps', 'channels.im.list', 'channels.im.listLanes'].includes(row.request.input.op))).toBe(true);+});+it('explains offline, unsupported hosts and logical failures instead of an empty picker', async () => {+ await render(false); expect(host.textContent).toContain('devices.resources.hostOffline');+ expect(h.requests).toHaveLength(0);+ h.supported = false; await render(); expect(host.textContent).toContain('devices.companionProfile.hostUpgrade');+ h.fail = true; await render(); expect(host.textContent).toContain('devices.companionProfile.readFailed');+ await act(async () => host.querySelector('button')!.click()); expect(h.refresh).toHaveBeenCalled();+});diff --git a/apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsx b/apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsxindex a32cb5a84f..4f8a7c4203 100644--- a/apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsx+++ b/apps/mobile/src/__tests__/CompanionProfileSheet.android.test.tsx@@ -18,7 +18,7 @@ vi.mock('expo-router', () => ({ useRouter: () => ({ push: vi.fn() }) }));vi.mock('expo-crypto', () => ({ randomUUID: () => 'test-id' }));vi.mock('@/platform/chrome', () => ({ NativeSwitch: () => null }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));-vi.mock('lucide-react-native', () => Object.fromEntries(['Brain', 'Camera', 'FileText', 'Hand', 'History', 'Info', 'Link2', 'Settings2', 'Sparkles']+vi.mock('lucide-react-native', () => Object.fromEntries(['Brain', 'Camera', 'FileText', 'Hand', 'History', 'Info', 'Link2', 'MessageCircle', 'Settings2', 'Sparkles'].map(name => [name, Object.assign(() => null, { displayName: name })])));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: 1 }) }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: h.invoke, openLink: h.openLink }) }));@@ -87,7 +87,7 @@ it('lays out the iOS identity, entry groups, icons and host-ordered management aexpect(avatar.closest('button')).toBeNull();expect(container.textContent).toContain('Cindy'); expect(container.textContent).not.toContain('Teammate on Mac');const rows = buttons().map(node => node.dataset.testid ?? '').filter(id => /^companionProfile\.[a-z]+$/.test(id));- expect(rows).toEqual(['profile', 'memory', 'models', 'skills', 'artifacts', 'search', 'permissions'].map(id => `companionProfile.${id}`));+ expect(rows).toEqual(['profile', 'memory', 'models', 'skills', 'channels', 'artifacts', 'search', 'permissions'].map(id => `companionProfile.${id}`));const icons = Object.fromEntries(rows.map(id => [id.split('.')[1], byTest(id)!.dataset.icon]));// 图标与桌面 BotsHomeView 同一动作同一 lucide 图标(mobile-design-guide §6)。expect(icons).toMatchObject({ profile: 'Info', memory: 'Brain', models: 'Sparkles', skills: 'Settings2', artifacts: 'FileText', search: 'History', permissions: 'Hand' });diff --git a/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx b/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsxindex a4e07a4b0d..12086b8168 100644--- a/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx+++ b/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx@@ -363,3 +363,14 @@ it.each([true, false])('mobile follow-up invitation saves the explicit choice, e}, 'en');expect(container.querySelectorAll('button')).toHaveLength(0);});++// Both platform views share dismissal/navigation: no resource binding may follow an IM task.+it('opens the original IM task on its computer after the settings sheet closes', async () => {+ await render();+ await act(async () => h.view.channels.props.onOpenTask('channel-original'));+ expect(h.close).toHaveBeenCalledOnce();+ expect(h.push).not.toHaveBeenCalled();+ await act(async () => h.view.onClosed());+ expect(h.push).toHaveBeenCalledWith({ pathname: '/sessions/[sessionId]', params: { sessionId: 'channel-original', deviceId: 'host' } });+ expect(h.invoke).not.toHaveBeenCalled();+});diff --git a/apps/mobile/src/__tests__/conversationSearch.test.ts b/apps/mobile/src/__tests__/conversationSearch.test.tsindex 6a7d3f22fc..9005bb2f8f 100644--- a/apps/mobile/src/__tests__/conversationSearch.test.ts+++ b/apps/mobile/src/__tests__/conversationSearch.test.ts@@ -3,7 +3,6 @@ import {cachedSessionForSearchResult,conversationSearchActiveFilterCount,conversationSearchAllowsLocalWrites,- conversationSearchCompanionParams,conversationSearchOriginsFromDeviceModels,conversationSearchSessionCacheKey,isConversationSearchChannelNotAllowed,@@ -219,7 +218,7 @@ describe('searchConversationsAcrossDevices', () => {],},);- expect(page.results.map((item) => item.session.id)).toEqual(['hit']);+ expect(page.results.map((item) => item.session.id)).toEqual(['hit', 'worker']);});it('does not invoke a device that is offline or unresponsive', async () => {@@ -539,7 +538,4 @@ it('preserves companion identity and the selected archived transcript', () => {hit.session.companion = { id: 'bot', name: 'Melody', role: 'history', readOnly: true };const item = toSearchListItem(hit, Date.now());expect(item.title).toBe('Melody · Remote planning');- expect(conversationSearchCompanionParams(item)).toEqual({- resourceCollectionId: 'teammates', resourceKind: 'bot', resourceId: 'bot', resourceHistorySessionId: 'old',- });});diff --git a/apps/mobile/src/__tests__/sideChatTaskBoundary.test.tsx b/apps/mobile/src/__tests__/sideChatTaskBoundary.test.tsxindex 507b41d074..e1cab3a53e 100644--- a/apps/mobile/src/__tests__/sideChatTaskBoundary.test.tsx+++ b/apps/mobile/src/__tests__/sideChatTaskBoundary.test.tsx@@ -17,7 +17,7 @@ const state = vi.hoisted(() => ({replace: vi.fn(),dismissKeyboard: vi.fn(),listeners: new Set<(deviceId: string, sessionId: string) => void>(),- route: { deviceId: 'host', sessionId: 'child' },+ route: { deviceId: 'host', sessionId: 'child' } as Record<string, string>,sidebar: null as ComponentProps<typeof SessionListDrawer> | null,source: 'local',replaceParams: vi.fn(),@@ -64,7 +64,6 @@ vi.mock('@/platform/AdaptiveWindowContext', () => ({}));vi.mock('@/theme', () => ({ useTheme: () => ({ colors: { surface: 'white' } }) }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));-vi.mock('../session/conversationSearch', () => ({ conversationSearchCompanionParams: () => ({}) }));vi.mock('../session/SessionListDrawer', () => ({ SessionListDrawer: (props: ComponentProps<typeof SessionListDrawer>) => {state.sidebar = props;return <textarea aria-label="Sidebar search" />;@@ -218,6 +217,13 @@ describe('side chat task lifecycle', () => {expect(host.textContent).toBe('current task failed');});+ it('normalizes old history links before mounting the task contents', () => {+ state.route = { deviceId: 'host', sessionId: 'old', resourceHistorySessionId: 'old', resourceId: 'bot', resourceKind: 'bot', focusClientId: 'message' };+ act(() => root.render(<SessionTaskLayout>{() => <textarea aria-label="Legacy history" />}</SessionTaskLayout>));+ expect(host.querySelector('textarea')).toBeNull();+ expect(state.replaceParams).toHaveBeenCalledWith({ deviceId: 'host', deviceName: 'host', sessionId: 'old', focusClientId: 'message' });+ });+it('discards the outgoing attachment scope before sidebar navigation and preserves search focus', () => {const order: string[] = [];state.replaceParams.mockImplementation(() => order.push('navigate'));diff --git a/apps/mobile/src/debug/teammateVisualFixture.ts b/apps/mobile/src/debug/teammateVisualFixture.tsindex 72d78a50f6..ca30eb08ea 100644--- a/apps/mobile/src/debug/teammateVisualFixture.ts+++ b/apps/mobile/src/debug/teammateVisualFixture.ts@@ -1,5 +1,7 @@import {REMOTE_RESOURCE_LIST_CHANNEL,+ REMOTE_RESOURCE_GET_CHANNEL,+ REMOTE_RESOURCE_INVOKE_CHANNEL,REMOTE_RESOURCE_MANIFEST_CHANNEL,REMOTE_RESOURCE_PROTOCOL_VERSION,type RemoteCollectionItem,@@ -7,12 +9,14 @@ import {type RemoteResourceManifestResponse,} from '@cindy/device-link';import { UI_MOCK_ID_PREFIX } from '@cindy/maker-shared/ui-mock';+import { BOT_GROUP_CHAT_PRIMITIVE, BOT_GROUP_REMOTE_COLLECTION_ID, BOT_GROUP_REMOTE_RESOURCE_KIND } from '@cindy/maker-shared/botGroupChat';/*** `--mock` teammates (docs/dev-rules/ui-mock-data.md): the roster the teammate home and the task* home's teammate section read. Invented names and previews only; the three presets ship with the app.*/const TEAMMATES = 'teammates';+export const VISUAL_TEAMMATE_SESSION_ID = 'visual-teammate-session';const MINUTE = 60_000;const teammates: ReadonlyArray<{ id: string; name: string; preview: string; minutesAgo: number; avatar: RemoteCollectionItem['display']['avatar']; working?: boolean; following?: string[] }> = [{ id: 'visual-bot-cindy', name: 'Cindy', preview: '登录页窄窗口的错位已经修好,截图放在任务里了。', minutesAgo: 2,@@ -41,7 +45,38 @@ export function teammateVisualFixture(channel: string, args: unknown[], now = FIcollections: [{ id: TEAMMATES, resourceKind: 'bot', title: 'Teammates', placement: 'home-scope',actions: [{ id: 'open-create', label: 'New teammate' }] }],} satisfies RemoteResourceManifestResponse;- const request = args[0] as { collectionId?: string } | undefined;+ const request = args[0] as { collectionId?: string; ref?: { collectionId?: string; id?: string }; resourceRef?: { id?: string }; input?: { op?: string; args?: { id?: string } } } | undefined;+ if (channel === REMOTE_RESOURCE_GET_CHANNEL && request?.ref?.collectionId === BOT_GROUP_REMOTE_COLLECTION_ID+ && request.ref.id === 'visual-session-process') return {+ ref: { collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, kind: BOT_GROUP_REMOTE_RESOURCE_KIND, id: request.ref.id },+ revision: 'visual-1', display: { title: '任务入口演示群' }, actions: [], links: [],+ blocks: [{ id: 'chat', primitive: BOT_GROUP_CHAT_PRIMITIVE, fallbackMarkdown: 'Cindy 正在工作', data: {+ id: request.ref.id, name: '任务入口演示群', members: [{ botId: 'visual-bot-cindy', name: 'Cindy', status: 'active' }],+ messages: [], plans: [], createdAt: now, updatedAt: now,+ round: { status: 'running', canContinue: false, speakers: [{ botId: 'visual-bot-cindy', activity: 'reply', sessionId: VISUAL_TEAMMATE_SESSION_ID }] },+ } }],+ };+ // Existing connection/session records for exercising both native settings entries.+ if (channel === REMOTE_RESOURCE_INVOKE_CHANNEL && request?.collectionId === TEAMMATES) {+ const op = request.input?.op;+ const botId = request.resourceRef?.id;+ const value = op === 'caps' ? { version: 1, ops: ['channels.im.list', 'channels.im.listLanes'] }+ : op === 'channels.im.list' ? { connections: [{ id: 'visual-im', botId, channel: 'telegram', identity: { username: 'demo_partner' } }] }+ : op === 'channels.im.listLanes' && request.input?.args?.id === 'visual-im'+ ? { connectionId: 'visual-im', lanes: [{ sessionId: VISUAL_TEAMMATE_SESSION_ID, kind: 'group', name: '演示群任务', chatId: 'demo-group', state: 'idle', lastActivityAt: now, contextMessageCount: 2 }] }+ : undefined;+ if (value !== undefined) return { result: { ok: true, value }, effects: [] };+ }+ if (channel === REMOTE_RESOURCE_GET_CHANNEL && request?.ref?.collectionId === TEAMMATES) {+ const id = request.ref.id?.replace(/^settings:/, '');+ const bot = teammates.find(item => item.id === id);+ if (bot) return {+ ref: { collectionId: TEAMMATES, kind: 'bot', id: request.ref.id }, revision: 'visual-1',+ display: { title: bot.name, avatar: bot.avatar },+ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: VISUAL_TEAMMATE_SESSION_ID } }],+ actions: [], blocks: [{ id: 'profile', primitive: 'markdown', fallbackMarkdown: bot.preview }],+ };+ }if (channel !== REMOTE_RESOURCE_LIST_CHANNEL || request?.collectionId !== TEAMMATES) return undefined;return {collectionId: TEAMMATES,diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.tsindex 6866cb55a6..448147d2ab 100644--- a/apps/mobile/src/debug/visualMock.ts+++ b/apps/mobile/src/debug/visualMock.ts@@ -22,7 +22,7 @@ import type {} from '@/device-link/mobileMakerTransport';import { remoteSessionStore } from '@/session/remoteSessionStore';import { pluginVisualFixture } from '@/debug/pluginVisualFixture';-import { teammateVisualFixture } from '@/debug/teammateVisualFixture';+import { teammateVisualFixture, VISUAL_TEAMMATE_SESSION_ID } from '@/debug/teammateVisualFixture';import { markdownPreviewFixture } from '@/debug/markdownPreviewFixture';import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';@@ -535,6 +535,9 @@ function catalogSession(row: UiMockSessionRow): RemoteSession {}function visualMockSession(id: string): RemoteSession {+ if (id === VISUAL_TEAMMATE_SESSION_ID) return {+ ...visualMockSession('ui-mock-rich-answer'), id, source: 'bot', title: 'Cindy · 演示群任务',+ };return visualMockSessions('all').find((session) => session.id === id) ?? visualMockSessions()[0];}@@ -556,6 +559,9 @@ function sessionFromShared(}function visualMockMessages(sessionId: string): RemoteMessage[] {+ if (sessionId === VISUAL_TEAMMATE_SESSION_ID) return visualMockMessages('ui-mock-rich-answer').map(row => ({+ ...row, id: `${sessionId}-${row.id}`, clientId: `${sessionId}-${row.clientId}`, sessionId,+ }));if (sessionId === VISUAL_MOCK_SESSION_ID) {return SHARED_REMOTE_CONTROL_FIXTURE.rawMessages.map((message) => ({...message,diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.jsonindex 10cdf9261f..ebbf61bfb0 100644--- a/apps/mobile/src/i18n/locales/en/devices.json+++ b/apps/mobile/src/i18n/locales/en/devices.json@@ -760,7 +760,18 @@"home": "Main Computer","chat": "Chat","showReplyTarget": "Show which message a reply answers",- "showReplyTargetHint": "Above a teammate’s reply, show which of your messages it answers. Applies to all teammates. Older replies don’t show this."+ "showReplyTargetHint": "Above a teammate’s reply, show which of your messages it answers. Applies to all teammates. Older replies don’t show this.",+ "channels": "Messaging platforms",+ "channelsEmpty": "No messaging platforms connected",+ "channelTasksEmpty": "No tasks yet",+ "channelPlatforms": {+ "telegram": "Telegram",+ "feishu": "Feishu",+ "lark": "Lark",+ "wecom": "WeCom",+ "dingtalk": "DingTalk",+ "discord": "Discord"+ }},"companionImport": {"title": "Import a teammate",diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.jsonindex 0aed0bf0c8..8563b01e86 100644--- a/apps/mobile/src/i18n/locales/ja/devices.json+++ b/apps/mobile/src/i18n/locales/ja/devices.json@@ -760,7 +760,18 @@"home": "メインのパソコン","chat": "チャット","showReplyTarget": "返信の対象メッセージを表示",- "showReplyTargetHint": "チームメイトの返信の上に、どのメッセージへの返信かを表示します。すべてのチームメイトに適用されます。以前の返信には表示されません。"+ "showReplyTargetHint": "チームメイトの返信の上に、どのメッセージへの返信かを表示します。すべてのチームメイトに適用されます。以前の返信には表示されません。",+ "channels": "メッセージサービス",+ "channelsEmpty": "接続されたサービスはありません",+ "channelTasksEmpty": "タスクはまだありません",+ "channelPlatforms": {+ "telegram": "Telegram",+ "feishu": "Feishu",+ "lark": "Lark",+ "wecom": "WeCom",+ "dingtalk": "DingTalk",+ "discord": "Discord"+ }},"companionImport": {"title": "仲間をインポート",diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.jsonindex 96783150a4..13d37b0f86 100644--- a/apps/mobile/src/i18n/locales/ko/devices.json+++ b/apps/mobile/src/i18n/locales/ko/devices.json@@ -760,7 +760,18 @@"home": "주 컴퓨터","chat": "채팅","showReplyTarget": "답장 대상 메시지 표시",- "showReplyTargetHint": "팀원 답장 위에 어떤 메시지에 대한 답장인지 표시합니다. 모든 팀원에게 적용되며, 이전 답장에는 표시되지 않습니다."+ "showReplyTargetHint": "팀원 답장 위에 어떤 메시지에 대한 답장인지 표시합니다. 모든 팀원에게 적용되며, 이전 답장에는 표시되지 않습니다.",+ "channels": "메시지 플랫폼",+ "channelsEmpty": "연결된 메시지 플랫폼이 없습니다",+ "channelTasksEmpty": "아직 작업 기록이 없습니다",+ "channelPlatforms": {+ "telegram": "Telegram",+ "feishu": "Feishu",+ "lark": "Lark",+ "wecom": "WeCom",+ "dingtalk": "DingTalk",+ "discord": "Discord"+ }},"companionImport": {"title": "동료 가져오기",diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.jsonindex b4837fd482..7da5fdd4fb 100644--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json@@ -760,7 +760,18 @@"home": "主力电脑","chat": "对话","showReplyTarget": "显示回复对应的消息",- "showReplyTargetHint": "伙伴回复上方标出它回的是你哪条消息。对所有伙伴生效,较早的回复不显示。"+ "showReplyTargetHint": "伙伴回复上方标出它回的是你哪条消息。对所有伙伴生效,较早的回复不显示。",+ "channels": "消息平台",+ "channelsEmpty": "还没有连接消息平台",+ "channelTasksEmpty": "还没有任务记录",+ "channelPlatforms": {+ "telegram": "Telegram",+ "feishu": "飞书",+ "lark": "Lark",+ "wecom": "企业微信",+ "dingtalk": "钉钉",+ "discord": "Discord"+ }},"companionImport": {"title": "导入伙伴",diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.jsonindex c85a98331b..05ed3b3833 100644--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json@@ -760,7 +760,18 @@"home": "主力電腦","chat": "對話","showReplyTarget": "顯示回覆對應的訊息",- "showReplyTargetHint": "夥伴回覆上方標出它回的是你哪則訊息。對所有夥伴生效,較早的回覆不顯示。"+ "showReplyTargetHint": "夥伴回覆上方標出它回的是你哪則訊息。對所有夥伴生效,較早的回覆不顯示。",+ "channels": "訊息平台",+ "channelsEmpty": "尚未連接訊息平台",+ "channelTasksEmpty": "尚無任務紀錄",+ "channelPlatforms": {+ "telegram": "Telegram",+ "feishu": "Feishu",+ "lark": "Lark",+ "wecom": "WeCom",+ "dingtalk": "DingTalk",+ "discord": "Discord"+ }},"companionImport": {"title": "匯入夥伴",diff --git a/apps/mobile/src/session/BotGroupSpeakerRow.tsx b/apps/mobile/src/session/BotGroupSpeakerRow.tsxindex 159a1f4bad..d076e582fb 100644--- a/apps/mobile/src/session/BotGroupSpeakerRow.tsx+++ b/apps/mobile/src/session/BotGroupSpeakerRow.tsx@@ -8,11 +8,12 @@*/import { useCallback, useSyncExternalStore } from 'react';import { StyleSheet, View } from 'react-native';-import { useFocusEffect } from 'expo-router';+import { useFocusEffect, useRouter } from 'expo-router';import { useTranslation } from 'react-i18next';import { readWorkingPhase } from '@cindy/maker-shared';import type { BotGroupSpeakerActivity } from '@cindy/maker-shared/botGroupChat';import { Text } from '@/components/AppText';+import { MainWindowActionButton } from '@/components/MobilePrimitives';import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';import { useThemedStyles, type ThemeColors } from '@/theme';@@ -40,6 +41,7 @@ export function BotGroupSpeakerRow({ deviceId, identity, sessionId, activity, ononError(message: string | null): void;}) {const { t } = useTranslation();+ const router = useRouter();const styles = useThemedStyles(makeStyles);const { invoke, subscribe, unsubscribe } = useDeviceLink();const lane = sessionId ?? '';@@ -80,6 +82,7 @@ export function BotGroupSpeakerRow({ deviceId, identity, sessionId, activity, on<ThinkingDots /><WorkingStatusText key={`${lane}:${activity}`} text={label} style={styles.statusText} /></View> : null}+ {sessionId ? <MainWindowActionButton action={{ label: t('devices.companions.openTask'), onPress: () => router.push({ pathname: '/sessions/[sessionId]', params: { sessionId, deviceId } }) }} /> : null}{pending.length > 0 && lane ? <InteractionPanel embedded companioncompanionIdentity={{ name: identity.name, avatar: <BotGroupAvatar deviceId={deviceId} identity={identity} size={BOT_GROUP_INLINE_AVATAR_SIZE} online={online} /> }}deviceId={deviceId} sessionId={lane} interactions={pending} onError={onError} />diff --git a/apps/mobile/src/session/CompanionChannelTasks.tsx b/apps/mobile/src/session/CompanionChannelTasks.tsxnew file mode 100644index 0000000000..d4fe2deee2--- /dev/null+++ b/apps/mobile/src/session/CompanionChannelTasks.tsx@@ -0,0 +1,56 @@+import { useState } from 'react';+import { StyleSheet, View } from 'react-native';+import { useTranslation } from 'react-i18next';+import { REMOTE_RESOURCE_INVOKE_CHANNEL, REMOTE_RESOURCE_PROTOCOL_VERSION } from '@cindy/device-link';+import { Text } from '@/components/AppText';+import { MainWindowActionButton } from '@/components/MobilePrimitives';+import { lineHeight, spacing, typeScale, useThemedStyles, type ThemeColors } from '@/theme';+import { useRemoteCompanionQuery } from './useRemoteCompanionQuery';++type Result<T> = { result?: { ok: boolean; value?: T } };+type Connection = { id: string; botId: string; channel: string; service?: string; identity?: { username?: string | null } };+type Lane = { sessionId: string; name: string | null; chatId: string | null; kind: string };+const client = { protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION, primitives: [] };+function request(op: string, botId?: string, args?: Record<string, unknown>) {+ return [{ client, collectionId: 'teammates', actionId: 'management:settings',+ ...(botId ? { resourceRef: { collectionId: 'teammates', kind: 'bot', id: botId } } : {}),+ input: { v: 1, op, ...(args ? { args } : {}) } }];+}++/** Read existing channel tasks; opening one never resets its context or starts a turn. */+export function CompanionChannelTasks({ deviceId, botId, online, onOpenTask }: {+ deviceId: string; botId: string; online: boolean; onOpenTask(id: string): void;+}) {+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ const [expanded, setExpanded] = useState<string | null>(null);+ const caps = useRemoteCompanionQuery<Result<{ ops: string[] }>>(deviceId, REMOTE_RESOURCE_INVOKE_CHANNEL, request('caps'), { enabled: online });+ const supported = caps.value?.result?.ok && ['channels.im.list', 'channels.im.listLanes'].every(op => caps.value?.result?.value?.ops?.includes(op));+ const connections = useRemoteCompanionQuery<Result<{ connections: Connection[] }>>(deviceId, REMOTE_RESOURCE_INVOKE_CHANNEL, request('channels.im.list', botId), { enabled: online && !!supported });+ const lanes = useRemoteCompanionQuery<Result<{ lanes: Lane[] }>>(deviceId, REMOTE_RESOURCE_INVOKE_CHANNEL, request('channels.im.listLanes', botId, { id: expanded }), { enabled: online && !!supported && !!expanded });+ const rows = connections.value?.result?.value?.connections?.filter(row => row.botId === botId) ?? [];+ const failed = caps.error || caps.value?.result?.ok === false || connections.error || connections.value?.result?.ok === false;+ const retry = () => { caps.refresh(); connections.refresh(); lanes.refresh(); };+ return <View style={styles.content}>+ {!online ? <Text style={styles.note}>{t('devices.resources.hostOffline')}</Text> : failed ? <>+ <Text style={styles.note}>{t('devices.companionProfile.readFailed')}</Text>+ <MainWindowActionButton action={{ label: t('devices.resources.retry'), onPress: retry }} />+ </> : caps.value && !supported ? <Text style={styles.note}>{t('devices.companionProfile.hostUpgrade')}</Text>+ : !connections.value ? <Text style={styles.note}>{t('devices.resources.loading')}</Text>+ : rows.length === 0 ? <Text style={styles.note}>{t('devices.companionProfile.channelsEmpty')}</Text> : null}+ {rows.map(row => <View key={row.id} style={styles.content}>+ <MainWindowActionButton action={{ label: `${t(`devices.companionProfile.channelPlatforms.${row.service === 'lark' ? 'lark' : row.channel}`, { defaultValue: row.channel })}${row.identity?.username ? ` · ${row.identity.username}` : ''}`, onPress: () => setExpanded(expanded === row.id ? null : row.id) }} />+ {expanded === row.id ? lanes.error || lanes.value?.result?.ok === false ? <>+ <Text style={styles.note}>{t('devices.companionProfile.readFailed')}</Text>+ <MainWindowActionButton action={{ label: t('devices.resources.retry'), onPress: lanes.refresh }} />+ </> : !lanes.value ? <Text style={styles.note}>{t('devices.resources.loading')}</Text>+ : lanes.value.result?.value?.lanes?.length ? lanes.value.result.value.lanes.map(lane => <MainWindowActionButton key={lane.sessionId} action={{+ label: lane.name || lane.chatId || t('devices.companions.openTask'), onPress: () => onOpenTask(lane.sessionId),+ }} />) : <Text style={styles.note}>{t('devices.companionProfile.channelTasksEmpty')}</Text> : null}+ </View>)}+ </View>;+}+const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ content: { gap: spacing.md },+ note: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },+});diff --git a/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx b/apps/mobile/src/session/CompanionProfileNativeView.ios.tsxindex 63cc42c750..ba3ab79ebd 100644--- a/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx+++ b/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx@@ -65,7 +65,7 @@ export function CompanionProfileNativeView(p: CompanionProfileNativeViewProps) {modifiers={[tint(colors.inputCaret)]} testID="companionProfile.showReplyTarget" /></Section>{p.data?.panels.filter(item => item.id === 'projects' || item.id === 'followUp').flatMap(item => item.entries ?? [])?.map(entry => <Section key={entry.id}>{action(label(entry.title), () => p.onEditor(entry.resourceId), !p.online)}</Section>)}- <Section>{row('artifacts', 'doc.text')}{p.onSearch ? row('search', 'magnifyingglass', p.onSearch) : null}{row('permissions', 'hand.raised')}</Section>+ <Section>{row('channels', 'bubble.left.and.bubble.right')}{row('artifacts', 'doc.text')}{p.onSearch ? row('search', 'magnifyingglass', p.onSearch) : null}{row('permissions', 'hand.raised')}</Section>{p.onHome ? <Section>{row('home', 'desktopcomputer', p.onHome)}</Section> : null}<Section>{p.data?.panels.filter(item => ['restart', 'resume', 'delete'].includes(item.id) && item.action).map(item => <Button key={item.id} onPress={() => p.onConfirm(item)} modifiers={[buttonStyle('plain'), listRowInsets({ top: 4, bottom: 4, leading: 16, trailing: 16 }), disabled(p.busy || !p.online), frame({ minHeight: 44 }), ...(item.id === 'delete' ? [foregroundStyle(colors.destructive)] : [])]}><HStack modifiers={[frame({ maxWidth: Infinity, minHeight: 44 }), contentShape(shapes.rectangle())]}><Text>{label(item.action!.label)}</Text><Spacer /></HStack></Button>)}</Section>{/* Same as Android: a host without the settings forms asks for a Cindy update on that computer. */}@@ -87,6 +87,7 @@ export function CompanionProfileNativeView(p: CompanionProfileNativeViewProps) {: p.page === 'models' ? <>{p.panel?.action ? <Section><CompanionNativeContent>{p.models}</CompanionNativeContent></Section> : null}{p.panel?.action ? <Section>{action(tr('save'), () => p.onSubmit(p.panel!), !p.dirty || !p.online || p.conflict)}</Section> : note(p.panel?.text || tr('hostUpgrade'))}</>: p.page === 'settings' ? <Section>{row('permissions', 'hand.raised')}</Section>: p.page === 'skills' ? <>{p.data?.panels.find(item => item.id === 'skills')?.entries?.length ? <Section>{row('personalSkills', 'sparkles')}</Section> : note(p.data?.panels.find(item => item.id === 'skills')?.text || tr('skillsEmpty'))}{p.data?.panels.find(item => item.id === 'connections')?.entries?.length ? <Section>{row('connections', 'link')}</Section> : note(p.data?.panels.find(item => item.id === 'connections')?.text || tr('emptyEditor'))}</>+ : p.page === 'channels' ? <Section><CompanionNativeContent>{p.channels}</CompanionNativeContent></Section>: p.page === 'artifacts' ? <Section><CompanionNativeContent>{p.artifacts}</CompanionNativeContent></Section> : p.page === 'memoryEntries' ? p.memoryPage: <>{p.page === 'profile' && p.data?.panels.find(item => item.id === 'avatar')?.entries?.length ? <Section>{row('avatar', 'person.crop.circle')}</Section> : null}{panel(p.panel)}{(p.page === 'profile' || p.page === 'memory') && p.panel && !p.panel.action ? note(tr('largeProfileRecovery')) : null}diff --git a/apps/mobile/src/session/CompanionProfileNativeView.tsx b/apps/mobile/src/session/CompanionProfileNativeView.tsxindex 2a0c12be11..f0f978b5d4 100644--- a/apps/mobile/src/session/CompanionProfileNativeView.tsx+++ b/apps/mobile/src/session/CompanionProfileNativeView.tsx@@ -6,7 +6,7 @@ export interface CompanionProfileNativeViewProps {resource: RemoteResource | null; data: CompanionProfileData | null; editor: CompanionProfileData | null;panel?: ProfilePanel; values: ProfileValues; busy: boolean; online: boolean; dirty: boolean;loading: boolean; error: boolean; errorLabel?: string; conflict: boolean; receipt: string | null;- confirmation: ProfilePanel | null; deleted: boolean; artifacts: ReactNode; models: ReactNode;+ confirmation: ProfilePanel | null; deleted: boolean; channels: ReactNode; artifacts: ReactNode; models: ReactNode;/** Saved-memories page (list / detail / edit), and whether the host offers it. */memoryPage: ReactNode; hasMemoryEntries: boolean;onClose(): void; onClosed?(): void; onBack?(): void; onOpen(page: string): void;diff --git a/apps/mobile/src/session/CompanionProfileSheet.tsx b/apps/mobile/src/session/CompanionProfileSheet.tsxindex 56262a16d3..74dc6abfc8 100644--- a/apps/mobile/src/session/CompanionProfileSheet.tsx+++ b/apps/mobile/src/session/CompanionProfileSheet.tsx@@ -5,7 +5,7 @@ import { useRouter } from 'expo-router';import { randomUUID } from 'expo-crypto';import { ActivityIndicator, Alert, Image, Platform, Pressable, StyleSheet, View } from 'react-native';import { useTranslation } from 'react-i18next';-import { Brain, Camera, FileText, Hand, History, Info, Link2, Monitor, Settings2, Sparkles } from 'lucide-react-native';+import { Brain, Camera, FileText, Hand, History, Info, Link2, MessageCircle, Monitor, Settings2, Sparkles } from 'lucide-react-native';import { resolveRemoteText, type RemoteResource, type RemoteResourceRef, type RemoteText } from '@cindy/device-link';import { useAuth } from '@/auth/AuthContext';import { Text, TextInput } from '@/components/AppText';@@ -23,6 +23,7 @@ import { CompanionModelChain, CompanionModelPicker, readCompanionModelChain } frimport { CompanionCreateNativeView } from './CompanionCreateNativeView';import { CompanionPortraitPicker, randomCompanionPortrait } from './CompanionPortraitPicker';import { CompanionProfileNativeView } from './CompanionProfileNativeView';+import { CompanionChannelTasks } from './CompanionChannelTasks';import { CompanionProfileArtifacts } from './CompanionProfileArtifacts';import { loadCompanionProfile, profileFormDirty, type CompanionProfileData, type ProfilePanel, type ProfileValues } from './companionProfileData';import { CompanionMemoryPage } from './CompanionMemoryPage';@@ -356,6 +357,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {name={name} page={page} deviceId={deviceId} deviceName={deviceName} resource={resource} data={data} editor={editor} panel={panel}values={editing ? values : panel?.values ?? values} busy={busy || memory.busy} online={online} dirty={dirty || memory.dirty} loading={editorLoading}error={error} errorLabel={deleteFailure ? t('devices.companionProfile.deleteFailed') : nameTakenOnSave ? t('devices.companionProfile.nameTaken') : undefined} conflict={conflict?.page === page} receipt={receipt && !confirmation ? label(receipt) : null} confirmation={confirmation} deleted={deleted}+ channels={resource ? <CompanionChannelTasks deviceId={deviceId} botId={resource.ref.id} online={online} onOpenTask={openArtifactTask} /> : null}artifacts={sessionId && resource ? <CompanionProfileArtifacts deviceId={deviceId} botId={resource.ref.id} sessionId={sessionId} online={online} onOpenTask={openArtifactTask} /> : note('artifactsRecovery')}memoryPage={memoryPage} hasMemoryEntries={!!memoryList}onClose={dismiss} onClosed={afterClosed} onBack={page !== 'home' || confirmation ? () => void leave(false) : undefined}@@ -396,7 +398,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {{note('showReplyTargetHint')}</View>{data?.panels.filter(item => item.id === 'projects' || item.id === 'followUp').flatMap(item => item.entries ?? [])?.map(entry => <View style={styles.group} key={entry.id}><ContextSheetRow icon={null} trailing="chevron" label={label(entry.title)} onPress={() => void openEditor(entry.resourceId)} disabled={!online} /></View>)}- <View style={styles.group}>{row('artifacts', FileText)}{onOpenSearch ? row('search', History, onOpenSearch) : null}{row('permissions', Hand)}</View>+ <View style={styles.group}>{row('channels', MessageCircle)}{row('artifacts', FileText)}{onOpenSearch ? row('search', History, onOpenSearch) : null}{row('permissions', Hand)}</View>{onOpenHome ? <View style={styles.group}>{row('home', Monitor, onOpenHome)}</View> : null}{/* Host order, like iOS: restart / resume / delete are whatever the computer offers now. */}{management.length ? <View style={styles.group}>{management.map(item => actionRow(item, () => confirm(item), item.id === 'delete'))}</View> : null}@@ -434,6 +436,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {{skills?.entries?.length ? <View style={styles.group}>{row('personalSkills', Settings2)}</View> : noteText(skills?.text || t('devices.companionProfile.skillsEmpty'))}{connections?.entries?.length ? <View style={styles.group}>{row('connections', Link2)}</View> : noteText(connections?.text || t('devices.companionProfile.emptyEditor'))}</>+ : page === 'channels' ? resource ? <CompanionChannelTasks deviceId={deviceId} botId={resource.ref.id} online={online} onOpenTask={openArtifactTask} /> : null: page === 'artifacts' ? sessionId && resource ? <CompanionProfileArtifacts deviceId={deviceId} botId={resource.ref.id} sessionId={sessionId} online={online} onOpenTask={openArtifactTask} /> : note('artifactsRecovery'): page === 'memoryEntries' ? memoryPage : <>{page === 'profile' && actionPanel('avatar')?.entries?.length ? <View style={styles.group}>{row('avatar', Camera)}</View> : null}diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsxindex d6ffda3d13..2fee2f0fca 100644--- a/apps/mobile/src/session/HomeSurface.tsx+++ b/apps/mobile/src/session/HomeSurface.tsx@@ -173,7 +173,6 @@ import {import { ConversationSearchFilterSheet } from '@/session/ConversationSearchFilterSheet';import {conversationSearchAllowsLocalWrites,- conversationSearchCompanionParams,conversationSearchOriginsFromDeviceModels,listConversationSearchProjects,shouldReplaceListWithSearchResults,@@ -2385,7 +2384,6 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falsedeviceName: session.deviceLinkDeviceName ?? deviceId,sessionId: session.id,...(focusClientId ? { focusClientId } : {}),- ...conversationSearchCompanionParams(item),},} as const;rememberTask(href);diff --git a/apps/mobile/src/session/SessionTaskLayout.tsx b/apps/mobile/src/session/SessionTaskLayout.tsxindex 5cd5bb4992..1cb88a2ddd 100644--- a/apps/mobile/src/session/SessionTaskLayout.tsx+++ b/apps/mobile/src/session/SessionTaskLayout.tsx@@ -1,10 +1,9 @@-import { useCallback, useRef, type ReactNode, type RefObject } from 'react';+import { useCallback, useEffect, useRef, type ReactNode, type RefObject } from 'react';import { Alert, Platform, StyleSheet, View } from 'react-native';import { useLocalSearchParams, useNavigation } from 'expo-router';import { useTranslation } from 'react-i18next';import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';import { CindyMakeSessionGate } from './CindyMakeSessionGate';-import { conversationSearchCompanionParams } from './conversationSearch';import { MessageHistoryOverlay } from './RecentMessageHistories';import { useSessionPaneLayout } from './ResidentHomeList';import { remoteSessionStore, useRemoteSessionDetail } from './remoteSessionStore';@@ -24,12 +23,19 @@ export interface SessionTaskChrome {export function SessionTaskLayout({ children }: {children(chrome: SessionTaskChrome): ReactNode;}) {- const params = useLocalSearchParams<{ sessionId: string; deviceId?: string }>();+ const params = useLocalSearchParams<{ sessionId: string; deviceId?: string; deviceName?: string; resourceHistorySessionId?: string; focusClientId?: string }>();const sessionId = readRouteParam(params.sessionId) ?? '';const deviceId = readRouteParam(params.deviceId)?? remoteSessionStore.getSessionDeviceId(sessionId) ?? '';const session = useRemoteSessionDetail(deviceId, sessionId);const navigation = useNavigation<SessionRouteParamsNavigation>();+ const legacyHistory = readRouteParam(params.resourceHistorySessionId) === sessionId && !!sessionId;+ useEffect(() => {+ if (legacyHistory && deviceId) switchDrawerSessionInPlace(navigation, {+ sessionId, deviceId, deviceName: readRouteParam(params.deviceName) ?? deviceId,+ focusClientId: readRouteParam(params.focusClientId) ?? undefined,+ });+ }, [legacyHistory, deviceId, sessionId, navigation, params.deviceName, params.focusClientId]);const paneLayout = useSessionPaneLayout();const adaptiveWindow = useAdaptiveWindow();const { t } = useTranslation();@@ -39,7 +45,7 @@ export function SessionTaskLayout({ children }: {const target = item.session as RemoteSession;const focusClientId = 'searchFocusClientId' in item? (item as { searchFocusClientId?: string }).searchFocusClientId : undefined;- if (target.id === sessionId && !focusClientId) return;+ if (target.id === sessionId && !focusClientId && !('searchLocallyCached' in item)) return;const targetDeviceId = target.canonicalDeviceId ?? target.deviceLinkDeviceId?? remoteSessionStore.getSessionDeviceId(target.id);if (!targetDeviceId) {@@ -52,9 +58,9 @@ export function SessionTaskLayout({ children }: {deviceName: target.deviceLinkDeviceName ?? targetDeviceId,sessionId: target.id,...(focusClientId ? { focusClientId } : {}),- ...conversationSearchCompanionParams(item),});}, [navigation, sessionId, t]);+ if (legacyHistory && deviceId) return null;return <View style={styles.root}><SideChatTaskBoundary key={JSON.stringify([deviceId, sessionId])} deviceId={deviceId}sessionId={sessionId} enabled={session?.source === 'side-chat'}>diff --git a/apps/mobile/src/session/conversationSearch.ts b/apps/mobile/src/session/conversationSearch.tsindex 5d7c699aa9..c2d538ad10 100644--- a/apps/mobile/src/session/conversationSearch.ts+++ b/apps/mobile/src/session/conversationSearch.ts@@ -201,7 +201,7 @@ export function searchCachedDeviceSessions(const hits: ConversationSearchResultItem[] = [];sessions.forEach((session, index) => {- if ((!CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) || session.orcaRole === 'worker') return;+ if (!CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) return;if (!sessionBelongsToDevice(session, origin.deviceId)) return;const alias = session.workspaceKind === 'project'? resolveProjectAliasForSessions([session], projectAliases, origin.deviceId ?? undefined) : undefined;@@ -273,20 +273,6 @@ export type ConversationSearchListItem = RemoteSessionListItem & {searchLocallyCached: boolean;};-/** Keep the exact transcript selected by search, including an archived personal thread. */-export function conversationSearchCompanionParams(item: object): Record<string, string> {- const companion = (item as Partial<ConversationSearchListItem>).searchCompanion;- if (!companion) return {};- return {- resourceCollectionId: 'teammates',- resourceKind: 'bot',- resourceId: companion.id,- ...(companion.readOnly- ? { resourceHistorySessionId: (item as ConversationSearchListItem).session.id }- : {}),- };-}-export function conversationSearchSessionCacheKey(session: Pick<RemoteSession, 'id'> & {canonicalDeviceId?: string | null;diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex d3fd7804b6..2214bdee47 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -637,7 +637,7 @@ Chat prose and compact code use the existing `chatChrome.ts` presentation entry;([group chat §5](../product-rules/bot-group-chat.md#5-界面)). Its collapsed outer frame usesthe **Desktop group progress capsule** registered in §5: a centered, content-width capsulecontaining the speaker/step status, elapsed time, current action and separate process/stop controls.-Opening the process changes that outer frame into a panel, using the ordinary container tier.+The process action opens the exact task in the ordinary Session UI (2026-10-25). It no longer expands an inline panel.The registration covers only the collapsed outer frame; the inner buttons retain their owncontrol-tier treatment. Keep semantic surface/border/text colors in both Light and Dark.It does not authorize pill-shaped toolbars or other status panels.@@ -768,7 +768,7 @@ There is one mobile home, as on Desktop (owner decision, 2026-10-24): no separat| **Keyboard keycap** | Every visible keyboard shortcut frame, whether rendered as `<kbd>` or as an interactive button that accepts the shortcut. Border, fill, padding and text colors stay appropriate to the surrounding surface; the radius is the shared cross-surface rule. *(Registered 2026-09-06, #4001.)* | 4px || **Data mark** | A visible layer inside a chart or visualization whose shape belongs to the data rather than to the control. Members below. *(Registered 2026-09-07.)* | 0px or 2px, pinned per member || **Bot Market opening bubble tail** | Only the opening-line bubble in the Bot Market detail header (`BotMarketDialog`): 12px bubble with a square bottom-left corner joined to a curved SVG tail on the left that follows the bubble fill and border. Not a general chat-bubble shape; any other bubble needs its own adjudication. *(User ruling 2026-10-15; decision log 10-15.)* | 12px, bottom-left square + tail |-| **Desktop group progress capsule** | Only the collapsed outer status-and-controls frame of `BotGroupProgressStrip`, centered above the group composer at content width. The expanded process panel uses the ordinary container tier; child controls keep their own assignments. See §4 component entry and decision log 10-20, [#6549](https://github.com/makecindy/cindy/pull/6549). | Pill (9999px) while collapsed |+| **Desktop group progress capsule** | Only the collapsed outer status-and-controls frame of `BotGroupProgressStrip`, centered above the group composer at content width. The process action opens the ordinary task page; child controls keep their own assignments. See §4 component entry and decision log 10-20, [#6549](https://github.com/makecindy/cindy/pull/6549). | Pill (9999px) while collapsed |**Overlap.** A keyboard shortcut frame retains its registered 4px treatment when another channel, such as colour, also encodes data. Data encoding alone does not override the keycap entry. Other overlaps must be resolved explicitly in the registration; listing order alone does not grant precedence.diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex cc65673949..5afd2fda2b 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -254,7 +254,7 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下左上),≤3 人时显示头像;话题入口是气泡下方与气泡左缘对齐的一行(回复者头像、N 条回复、最后回复时间);轮次结束、分工结束与系统提示是居中的一行小字。多人群里别人带来的伙伴显示「伙伴名 (主人昵称)」,人类成员名字旁带「某某的主人」。- 进行中:正在发言的伙伴在时间线末尾一行「X 正在想…」,本机能读到流式正文时下面跟最后两行;分工某一步在做,- 或某位伙伴说了超过三秒时,输入框上方出现固定的、按内容宽的进行中胶囊(不随时间线滚走;展开「看过程」时变为面板;外层形状见 [DESIGN.md §5 的 Desktop group progress capsule 登记](../design-rules/DESIGN.md#step-1--registered-shapes)):「第 k/n 步 · 谁 做什么 · 已做多久 ·+ 或某位伙伴说了超过三秒时,输入框上方出现固定的、按内容宽的进行中胶囊(不随时间线滚走;「看过程」直接打开该专线的普通任务页,不展开独立过程面板;外层形状见 [DESIGN.md §5 的 Desktop group progress capsule 登记](../design-rules/DESIGN.md#step-1--registered-shapes)):「第 k/n 步 · 谁 做什么 · 已做多久 ·当前动作」,带「看过程」(本机能读到这条专线时)与「停止」;分工进行中它替代时间线末尾的发言行,等确认的卡仍在时间线里。- 输入框支持 @ 伙伴,候选第一项为「所有人」;支持附件(见 3.1)。服务器群的话题回复用同一个输入框的话题模式,@ 候选也是同一套(`useBotGroupMentionPicker`):候选、筛选、键盘与鼠标选择、Esc 收起和同名伙伴按选中身份区分都与主群一致;候选与点名diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex a783ede618..acbc33d3b7 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -191,10 +191,12 @@ Discord 传输层只放行主人,钉钉群里被 @ 时成员也能触发(成「消息平台」页每条连接下有「隐藏任务」小节:列出这条连接名下的主人私聊(伙伴主任务)与各群 / 话题 / 外部用户私聊专线,每条可「重新开始」——复用伙伴已有的 `restartBotCanonicalRuntime` 交接(同一条任务、记录与记忆不删,下一条消息换干净的原生会话),不另写换会话逻辑,见 `im/shared/botImLaneRuntime.ts`。-点击小节里的记录或灵动岛上的渠道任务,在主界面复用归档历史的只读详情页-(`/bots/:id/history/:sid`),不另开窗口,不恢复或归档任务,也不让渠道专线进入左侧普通任务列表。-打开前按伙伴的持久归属投影校验;仍在运行的专线继续显示消息更新。「重新开始」与打开详情是独立操作,-继续沿用同一条任务保留完整记录。+点击记录、搜索结果或灵动岛上的渠道任务,直接打开普通任务页(Desktop `/cc-agent/:sid`,+iOS / Android `/sessions/:sessionId`),完整复用已有任务界面与操作,不增加只读历史外壳或过程面板。+远程入口携带原电脑与原任务 ID;打开不发消息、不重新开始、不创建替代任务。旧历史地址重定向到普通任务页。+「隐藏」只影响默认列表:主人仍可搜索并打开群专线、渠道、后台和归档记录;账号与共享访客权限仍由原边界校验。+手机伙伴设置的「消息平台」可读取已有连接及任务记录,旧电脑不支持时明确提示升级。+「重新开始」仍是独立操作,继续沿用同一条任务保留完整记录。本机 Hermes / OpenClaw 导入(见文末同名一节)把来源的消息机器人(Telegram / Discord / 飞书,Hermes 另有企业微信 / 钉钉)列成单独一行「消息机器人」、默认勾选;导入时先用来源自己的命令把它在原 Agent 里停掉并确认停下,再用同一个`addBotImConnection` 建成这位伙伴的连接,连不上就把原开关还原。主人不明、停不下或连不上时导入照常完成,该项标「需处理」,@@ -634,7 +636,7 @@ Session 任务遵守同一套机制与呈现契约:只在本轮执行结束后由伙伴明确选择切换。切换不自动重放工作;伙伴结合原目标和已完成动作,再决定是否向同一任务发补充消息。未配置的供应商或型号不可擅自加入候选。- **任务入口(2026-10-15 改为一张卡)**:Desktop 发起方消息流里,一条后台任务从开始到结束只有一张状态卡(`BotTaskCard`),状态原地变化,不再是下划线文本链接加独立结果卡。卡的第一行是状态字形(排队/运行转圈、等确认蓝点、完成绿点、失败红点)、任务标题(点击进入原任务)与「后台任务 · 引擎 · 用时」;第二行按状态写当前动作与已做时长、等你确认什么、结果摘要或错误;操作收成小胶囊:看看/看过程、补一句(运行中、本机任务才有;回车发送,等同 `message_session_task`)、文件数、PR 状态标、展开/收起结果、停止。标题与 harness 读取同一个 Session;运行状态来自原任务的真实运行信号,不从委派终态推断事项完成。远端伙伴的卡只读。Mobile 保留既有任务卡布局,查询与打开使用消息列表已解析的所属电脑;标题、运行和等待信号复用普通任务列表的原 Session,列表外任务按原 ID 单条补读。委派读取失败不抹去已知任务状态或禁止进入原任务,无法核实的状态仍显示未知;不同电脑的同 ID 记录不得混用。冻结结果不随续跑改写,存储与绑定合同不变。- **同一个后台任务只有一张脸**:通知、聊天里的卡片与主侧栏进入伙伴开的后台任务都走工程视图 `/cc-agent/:id`(diff、模型选择照常),顶部多一枚「<伙伴> 的后台任务」小标回到该伙伴(只认伙伴自己发起的委派子任务,主人的任务被伙伴接手只有侧栏「在跟进」标记;后台任务归档后从近况的输出内容或聊天卡片打开仍带这枚小标;结果里的相对链接按该后台任务自己的工作目录解析,不按伙伴主任务目录);伙伴主任务始终 `/bots/:id`,归档历史 `/bots/:id/history/:sid`,群专线回到所属群,不单独开任务页。路由由 `botRouteForOwnedSession` 统一给出,`resolveSessionRoute` 只读已加载的伙伴投影、不等 IPC。+ **同一个后台任务只有一张脸**:通知、聊天里的卡片与主侧栏进入伙伴开的后台任务都走工程视图 `/cc-agent/:id`(diff、模型选择照常),顶部多一枚「<伙伴> 的后台任务」小标回到该伙伴(只认伙伴自己发起的委派子任务,主人的任务被伙伴接手只有侧栏「在跟进」标记;后台任务归档后从近况的输出内容或聊天卡片打开仍带这枚小标;结果里的相对链接按该后台任务自己的工作目录解析,不按伙伴主任务目录);伙伴主聊天入口保留 `/bots/:id`;查看原任务时统一普通任务页,归档历史、IM 和群专线也一样。路由由 `botRouteForOwnedSession` 统一给出,`resolveSessionRoute` 只读已加载的伙伴投影、不等 IPC。- **执行结果入口**:Desktop 的冻结结果用同一张后台任务卡呈现(附在收尾回复下时结果默认展开,独立回执默认收起);完成结果属于伙伴收尾回复末尾的紧凑附件,正文先读,卡片与该条回复同列、同一容器归属。宿主以本轮实际消费的完成信号绑定冻结结果,成功收尾后随回复持久保存;同轮多结果分别附上,不按相邻消息、时间或正文猜配,不把所有卡移到时间线末尾。忙时尚未消费的队列不参与当前回复;每个结果还必须有该完成输入持久化之后生成的新正文,旧正文延迟落库、同毫秒无法确认顺序或输入记录缺失时保留独立入口。重复信号不重复绑定,续跑按执行代次保留独立结果。原任务卡和消息顺序不变。结果先按既有机制独立持久化;没有最终正文、失败或中断、关联读取失败、旧记录没有关联、或仅加载到原回执时,保留独立结果入口,不伪造总结、不改用户历史库。关联回复加载后,其对应独立回执只在伙伴展示投影中收起。旧客户端忽略新增的可选 `botTaskResults`,继续显示独立回执。新回执保存当次子任务标题;旧回执只读回退到已有任务标题,再回退到目标首行。附件冻结的状态、正文、文件与错误不从当前任务覆盖。普通任务、执行调度与自动化静默不改变。Desktop 流式展示透传 provider 的 `final_answer` phase,首个 final delta 即可见;commentary 继续隐藏。未知 phase 不凭文本猜测,仍遵守既有收尾兜底。未绑定的新回执在当前流式期间不插队,结束且无对应正文时保留轻入口;不靠模型编造任务 URL。diff --git a/packages/maker-shared/src/__tests__/conversationSearch.test.ts b/packages/maker-shared/src/__tests__/conversationSearch.test.tsindex ee15370de0..c4c51cd17a 100644--- a/packages/maker-shared/src/__tests__/conversationSearch.test.ts+++ b/packages/maker-shared/src/__tests__/conversationSearch.test.ts@@ -209,7 +209,7 @@ describe('filterResultsByRequestFilters', () => {},},);- expect(page.results.map((item) => item.session.id)).toEqual(['keep']);+ expect(page.results.map((item) => item.session.id)).toEqual(['keep', 'worker']);});it('keeps a remote hit when updatedAt is recent but userSendAt is old', () => {diff --git a/packages/maker-shared/src/conversationSearch.ts b/packages/maker-shared/src/conversationSearch.tsindex c25086f2a8..ab258b558d 100644--- a/packages/maker-shared/src/conversationSearch.ts+++ b/packages/maker-shared/src/conversationSearch.ts@@ -243,7 +243,6 @@ export function filterResultsByRequestFilters(results: response.results.filter((item) => {if (!CINDY_MAKE_ENABLED && isCindyMakeSource(item.session.source)) return false;if (!matchesWorkingDirSet(item.session.workingDir, allowedDirs)) return false;- if (item.session.orcaRole === 'worker') return false;if (!matchesStatus(item.session.status, status)) return false;if (agentKind !== 'all' && item.session.agentKind !== agentKind) return false;if (activityCutoff !== null && sessionActivityMs(item.session) < activityCutoff) {