Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(sessions): preserve original task identity through notification entry routes

Chris79cc71a3d5b3
diff --git a/apps/desktop/src/main/__tests__/deepLink.test.ts b/apps/desktop/src/main/__tests__/deepLink.test.ts
index 1da7e334b7..d2bc2bc4de 100644
--- a/apps/desktop/src/main/__tests__/deepLink.test.ts
+++ b/apps/desktop/src/main/__tests__/deepLink.test.ts
@@ -39,6 +39,7 @@ import {
focusMainWindow,
handleIncomingDeepLink,
openMainWindowVoiceSettings,
+ openMainWindowSession,
openMainWindowRemoteControlSettings,
setDeepLinkMainWindow,
takePendingDeepLink,
@@ -423,6 +424,13 @@ describe('dual scheme (cindy primary + legacy xdt-maker)', () => {
},
);
+ it('retains the original task host and reply anchor while the main renderer is unavailable', () => {
+ setDeepLinkMainWindow(null);
+ openMainWindowSession('original', { deviceId: 'studio', messageClientId: 'reply', islandEntryId: 'entry' });
+ expect(takePendingDeepLink()).toEqual({ type: 'session', id: 'original', deviceId: 'studio', messageClientId: 'reply', islandEntryId: 'entry' });
+ expect(takePendingDeepLink()).toBeNull();
+ });
+
it('buffers only the opaque provider import id during cold start', () => {
setDeepLinkMainWindow(null);
handleIncomingDeepLink(providerImportUrl('cindy'), 'test');
diff --git a/apps/desktop/src/main/__tests__/notificationService.test.ts b/apps/desktop/src/main/__tests__/notificationService.test.ts
index 026ac5e009..1ec92741c0 100644
--- a/apps/desktop/src/main/__tests__/notificationService.test.ts
+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts
@@ -28,6 +28,7 @@ const chatWindow = vi.hoisted(() => ({ url: 'file:///app/index.html#/bots/groups
vi.mock('../deepLink', () => ({
getDeepLinkMainWindow: () => ({ isFocused: () => true, isVisible: () => true, webContents: { getURL: () => chatWindow.url } }),
openMainWindowChatMessage: vi.fn(),
+ openMainWindowSession: vi.fn(),
}));
vi.mock('../agent-island/companionIdentity', () => ({ companionAvatarThumbnail: async () => undefined }));
@@ -38,6 +39,7 @@ const registeredHandlers = new Map<string, IpcHandler>();
// Notification 构造调用计数(每条 toast 一次)。
const notificationCtor = vi.fn();
+const notificationClicks: Array<() => void> = [];
// Notification.isSupported() — 默认 true; 单独用例需改成 false 时,setMock 之前覆盖。
let notificationSupported = true;
@@ -55,6 +57,7 @@ class FakeNotification {
}
on(evt: string, cb: (...args: unknown[]) => void): this {
if (evt === 'close') this.closeCb = cb;
+ if (evt === 'click') notificationClicks.push(cb);
return this;
}
show(): void {
@@ -156,6 +159,7 @@ async function freshService() {
vi.resetModules();
registeredHandlers.clear();
notificationCtor.mockClear();
+ notificationClicks.length = 0;
warn.mockClear();
notificationSupported = true;
ownerScopeCurrent = true;
@@ -199,6 +203,28 @@ const baseDeps = (feishuIm: FakeFeishuIM) => ({
});
describe('notificationService — channels 分发', () => {
+ // Regression: OS click must keep host + original task + reply anchor through reload,
+ // and a notification from the previous account must not navigate the new account.
+ it('routes desktop notification clicks with their original host and message, fenced by owner', async () => {
+ const { showDesktopSessionEvent, initNotificationService } = await freshService();
+ const { openMainWindowSession } = await import('../deepLink');
+ vi.mocked(openMainWindowSession).mockClear();
+ showDesktopSessionEvent(() => null, {
+ sessionId: 'remote-task', deviceId: 'studio', messageClientId: 'answer', title: 'Reply', kind: 'done',
+ });
+ notificationClicks[0]!();
+ expect(openMainWindowSession).toHaveBeenLastCalledWith('remote-task', { deviceId: 'studio', messageClientId: 'answer' });
+ ownerScopeCurrent = false;
+ notificationClicks[0]!();
+ expect(openMainWindowSession).toHaveBeenCalledTimes(1);
+ ownerScopeCurrent = true;
+ initNotificationService(baseDeps(makeFeishuIm(null)));
+ readSessionNotificationPreview.mockResolvedValue({ reply: { clientId: 'reply-original', text: 'Answer' } });
+ await invokeHandler({ sessionId: 'original', title: 'Reply', kind: 'done' });
+ notificationClicks.at(-1)!();
+ expect(openMainWindowSession).toHaveBeenLastCalledWith('original', { messageClientId: 'reply-original' });
+ });
+
it('does not suppress an unread thread merely because its group is focused', async () => {
const { showDesktopChatMessage } = await freshService();
const payload = { groupId: 'group-1', groupName: 'Group', messageId: 'message-1', senderName: 'Other', avatar: '', preview: 'Reply' };
@@ -909,6 +935,7 @@ describe('notificationService — channels 分发', () => {
);
notificationCtor.mockClear();
+ notificationClicks.length = 0;
showDesktopSessionEvent(() => null, { sessionId: '', title: '', kind: 'error' });
expect(notificationCtor).toHaveBeenCalledWith(
expect.objectContaining({
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
index 701439f22b..e0a5c189e7 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -7092,6 +7092,16 @@ describe('Agent Island device sessions', () => {
expect(channels).not.toContain(AGENT_ISLAND_SET_SOUND_SETTINGS_CHANNEL);
});
+ it('keeps the originating device when a remote island card opens its task', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ setDeepLinkMainWindow(null);
+ const service = new AgentIslandService({ getMainWindow: () => null, nativeHost: { failed: false, publish: () => true } });
+ service.setDeviceSessions([deviceSession('completed')]);
+ (service as unknown as { focusSession(id: string): void }).focusSession('remote-1');
+ expect(takePendingDeepLink()).toMatchObject({ type: 'session', id: 'remote-1', deviceId: 'device-a' });
+ service.resetRuntimeState();
+ });
+
it('hands observed transitions to desktop notifications when the island is off', async () => {
const { AgentIslandService } = await import('../service.js');
const publish = vi.fn(() => true);
@@ -7110,6 +7120,7 @@ describe('Agent Island device sessions', () => {
expect(onDeviceSessionEvent).toHaveBeenCalledTimes(1);
expect(onDeviceSessionEvent).toHaveBeenCalledWith({
sessionId: 'remote-1',
+ deviceId: 'device-a',
title: 'Fix login',
deviceName: 'Studio Mac',
kind: 'done',
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index 9b69c5b688..40e2545ef6 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -2741,13 +2741,16 @@ export class AgentIslandService {
if (!nextSessionId) return;
const now = Date.now();
const islandEntryId = this.recordIslandEntryAlert(nextSessionId, now);
+ const deviceId = this.state.sessions.get(nextSessionId)?.sourceDeviceId
+ ?? this.companionChats.get(nextSessionId)?.input.deviceId;
+ const target = { ...(islandEntryId ? { islandEntryId } : {}), ...(deviceId ? { deviceId } : {}) };
this.playConfiguredSound('select', now);
if (this.state.appFocused && this.state.visibleSessionIds.has(nextSessionId)) {
const focusChanged = requestAgentIslandSessionFocus(this.state, nextSessionId, now);
if (focusChanged) this.publish();
// 已在看的目标未必能处置这张卡(如只读历史):这次点击仍要交给 renderer,
// 入口导航器发现目标地址已提交时直接按点击编号申请处置,不会再导航一次。
- if (islandEntryId) openMainWindowSession(nextSessionId, { islandEntryId });
+ if (islandEntryId) openMainWindowSession(nextSessionId, target);
return;
}
@@ -2756,7 +2759,7 @@ export class AgentIslandService {
// Reuse the primary-window handoff: it retains navigation while the
// renderer reloads and restores macOS app focus. A one-shot notification
// sent during loading is lost before MainLayout can acknowledge the task.
- openMainWindowSession(nextSessionId, islandEntryId ? { islandEntryId } : undefined);
+ openMainWindowSession(nextSessionId, Object.keys(target).length ? target : undefined);
}
private readonly completionActionsPending = new Set<string>();
diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.ts
index 24dac51323..575425abcc 100644
--- a/apps/desktop/src/main/agent-island/state.ts
+++ b/apps/desktop/src/main/agent-island/state.ts
@@ -1136,6 +1136,7 @@ export type AgentIslandDeviceSessionEventKind = 'done' | 'error' | 'needs-reply'
export interface AgentIslandDeviceSessionEvent {
sessionId: string;
+ deviceId: string;
title: string | null;
deviceName: string | null;
kind: AgentIslandDeviceSessionEventKind;
@@ -1203,6 +1204,7 @@ export function syncAgentIslandDeviceSessions(
if (transition.event) {
result.events.push({
sessionId: input.sessionId,
+ deviceId: input.deviceId,
title: input.title,
deviceName: input.deviceName,
kind: transition.event,
diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.ts
index ed466bf6b0..a62db49aa7 100644
--- a/apps/desktop/src/main/deepLink.ts
+++ b/apps/desktop/src/main/deepLink.ts
@@ -434,12 +434,14 @@ export function openMainWindowBillingTopUp(): void {
*/
export function openMainWindowSession(
sessionId: string,
- options?: { focus?: boolean; islandEntryId?: string },
+ options?: { focus?: boolean; islandEntryId?: string; deviceId?: string; messageClientId?: string },
): void {
dispatchDeepLink(
- options?.islandEntryId
- ? { type: 'session', id: sessionId, islandEntryId: options.islandEntryId }
- : { type: 'session', id: sessionId },
+ { type: 'session', id: sessionId,
+ ...(options?.islandEntryId ? { islandEntryId: options.islandEntryId } : {}),
+ ...(options?.deviceId ? { deviceId: options.deviceId } : {}),
+ ...(options?.messageClientId ? { messageClientId: options.messageClientId } : {}),
+ },
options?.focus !== false,
);
}
diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.ts
index 712373f009..d4bc07b8ed 100644
--- a/apps/desktop/src/main/notificationService.ts
+++ b/apps/desktop/src/main/notificationService.ts
@@ -3,8 +3,7 @@
* ---------------------------------------------------------------------------
* 主进程层。提供单一 IPC handler `notification:show-session-event`:
* - macOS / Linux / Windows:统一走 Electron 原生 `Notification`。
- * - 点通知后把窗口拉到前台,并通过 `notification:focus-session` 把 sessionId
- * 广播给 renderer,由 renderer 路由跳转。
+ * - 点通知后通过持久到 renderer 就绪的 deep-link 队列打开原任务及其所属电脑。
* - 飞书通道:payload.channels.feishu === true 时通过 feishuIm 给当前 owner
* 私聊发通知。伙伴回复用纯文本,普通任务沿用 markdown;复用现有 IM API。
*
@@ -30,7 +29,7 @@ import { markSessionNeedsAttention } from './appBadgeService';
import { getMobileNotifyGeneration, sendMobileSessionNotify } from './device-link';
import { notificationPreview } from './notificationPreview';
import { companionAvatarThumbnail } from './agent-island/companionIdentity';
-import { getDeepLinkMainWindow, openMainWindowChatMessage } from './deepLink';
+import { getDeepLinkMainWindow, openMainWindowChatMessage, openMainWindowSession } from './deepLink';
import type { ChatMessageNotification } from './maker-ipc/chatMessageNotifications';
import { readSessionNotificationPreview, type SessionNotificationPreview } from './localDb/sessionNotificationPreview';
import { drainSessionActiveTurnWrites, getSessionNotificationTurnSignal } from './localDb/sessionActiveTurn';
@@ -175,29 +174,6 @@ function isFeishuReplyPending(key: string, eventId: string | undefined): boolean
// A slow transcript must not indefinitely hide a completion or an action request.
const NOTIFICATION_PREVIEW_WAIT_MS = 1_000;
-/**
- * 把窗口拉到前台并广播 sessionId 给 renderer 路由跳转。
- *
- * Windows 防焦点劫持:非前台进程直接 `focus()` 会被系统拒绝,只让任务栏图标
- * 闪烁不抢前台。绕过办法:先 `setAlwaysOnTop(true)` 触发系统允许该窗口前置,
- * `show() + focus()` 之后立刻 `setAlwaysOnTop(false)` 回到正常 z-order,但
- * 焦点已经成功转移过来了。这是 Electron 社区在 Windows 上的稳定 hack。
- *
- * macOS 的 SetForegroundWindow 等价物是 `app.focus({ steal: true })`,但 Mac
- * 默认 `focus()` 行为已经够强,不需要多余处理;这里的 alwaysOnTop 在 Mac 上
- * 是无害 no-op(窗口本来就允许前置)。
- */
-function focusWindow(getWindow: () => BrowserWindow | null, sessionId: string): void {
- const win = getWindow();
- if (!win) return;
- if (win.isMinimized()) win.restore();
- win.setAlwaysOnTop(true);
- win.show();
- win.focus();
- win.setAlwaysOnTop(false);
- if (sessionId) win.webContents.send('notification:focus-session', sessionId);
-}
-
/**
* 从 main 内其它模块发送与会话通知同语义的桌面 toast。
* Scheduler 运行在 main,必须直接调用此入口;`webContents.send` 同名 IPC 只会
@@ -206,6 +182,8 @@ function focusWindow(getWindow: () => BrowserWindow | null, sessionId: string):
export function showDesktopSessionEvent(
getWindow: () => BrowserWindow | null,
payload: Pick<ShowSessionEventPayload, 'sessionId' | 'title' | 'kind'> & {
+ deviceId?: string;
+ messageClientId?: string;
body?: string;
teammate?: boolean;
avatarJpeg?: string;
@@ -216,7 +194,14 @@ export function showDesktopSessionEvent(
const { sessionId, title, kind } = payload;
if (sessionId && payload.markAttention !== false) markSessionNeedsAttention(sessionId);
const safeTitle = title?.trim() || sessionId.slice(0, 8) || getSessionNotificationUntitled();
- return showDesktopToast(safeTitle, kind, () => focusWindow(getWindow, sessionId), payload.body, payload.teammate, payload.avatarJpeg);
+ const owner = captureDataOwnerBroadcastScope();
+ return showDesktopToast(safeTitle, kind, () => {
+ if (!isDataOwnerBroadcastScopeCurrent(owner)) return;
+ if (sessionId) openMainWindowSession(sessionId, {
+ ...(payload.deviceId ? { deviceId: payload.deviceId } : {}),
+ ...(payload.messageClientId ? { messageClientId: payload.messageClientId } : {}),
+ });
+ }, payload.body, payload.teammate, payload.avatarJpeg);
}
/**
@@ -225,11 +210,12 @@ export function showDesktopSessionEvent(
*/
export function showDeviceSessionDesktopEvent(
getWindow: () => BrowserWindow | null,
- event: { sessionId: string; title: string | null; deviceName: string | null; kind: SessionEventKind },
+ event: { sessionId: string; deviceId: string; title: string | null; deviceName: string | null; kind: SessionEventKind },
): void {
if (!desktopNotificationsEnabled) return;
showDesktopSessionEvent(getWindow, {
sessionId: event.sessionId,
+ deviceId: event.deviceId,
title: [event.title ?? getSessionNotificationUntitled(), event.deviceName].filter(Boolean).join(' · '),
kind: event.kind,
markAttention: false,
@@ -390,6 +376,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {
try {
const accepted = showDesktopSessionEvent(getWindow, {
sessionId, title: notificationTitle, kind, teammate, markAttention, avatarJpeg,
+ messageClientId: preview?.reply?.clientId,
body: teammate ? notificationPreview(detail ?? '', 240, getNotificationImageLabel()) || fallbackBody : undefined,
});
if (kind === 'done' && accepted) {
diff --git a/apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.ts b/apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.ts
index 8ab1d66971..0bee157794 100644
--- a/apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.ts
+++ b/apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.ts
@@ -7,7 +7,6 @@ import {
isAgentIslandVisibleSessionOwnedByWorkdirBrowseRoute,
isAgentIslandVisibleSessionOwnedByBotRoute,
resolveAgentIslandVisibleSessionsFromPath,
- resolveAgentIslandVisibleSessionFromRouteTarget,
resolveAgentIslandVisibleSessionIdForWorkdirBrowseRail,
resolveAgentIslandVisibleSessionIdFromPath,
} from '@/lib/agentIslandVisibleSessionRoute';
@@ -41,6 +40,8 @@ describe('bot and split route visibility', () => {
it.each([
['/bots/bot-a/session/chat-a', true],
['/bots/bot-a/history/history-a', true],
+ ['/bots/remote/device-a/bot-a/session/chat-a', true],
+ ['/bots/remote/device-a/bot-a', true],
['/bots/bot-a', false],
['/bots', false],
['/bots/roster', false],
@@ -93,19 +94,6 @@ describe('resolveAgentIslandVisibleSessionIdFromPath', () => {
expect(resolveAgentIslandVisibleSessionIdFromPath('/cc-agent/orca/new')).toBeNull();
});
- it('preserves Orca worker targets when acknowledging a complete route target', () => {
- expect(
- resolveAgentIslandVisibleSessionFromRouteTarget(
- '/cc-agent/lead-a?worker=worker-b&source=notification',
- ),
- ).toEqual(['lead-a', 'worker-b']);
- expect(resolveAgentIslandVisibleSessionFromRouteTarget('/cc-agent/lead-a')).toBe('lead-a');
- expect(resolveAgentIslandVisibleSessionFromRouteTarget('/cc-agent/lead-a?worker=new')).toBe(
- 'lead-a',
- );
- expect(resolveAgentIslandVisibleSessionFromRouteTarget('/settings?worker=worker-b')).toBeNull();
- });
-
it('lets the workdir browse route own visible-session reports for doc-mode rails', () => {
expect(isAgentIslandVisibleSessionOwnedByWorkdirBrowseRoute('/cc-agent/files/session-a')).toBe(true);
expect(isAgentIslandVisibleSessionOwnedByWorkdirBrowseRoute('/cc-agent/files')).toBe(false);
@@ -155,15 +143,6 @@ describe('resolveAgentIslandVisibleSessionIdFromPath', () => {
);
});
- it('acknowledges notification focus navigation to collapse Agent Island after jumping', () => {
- expect(mainLayoutSource).toContain(
- 'const visibleSession = resolveAgentIslandVisibleSessionFromRouteTarget(target);',
- );
- expect(mainLayoutSource).toContain(`if (isAgentIslandSupported()) {
- void window.electronAPI.agentIsland?.setVisibleSession?.(visibleSession);
- }`);
- });
-
it('routes plugin setup navigation through the owning session view', () => {
expect(mainLayoutSource).not.toContain('ghosts.onSetupNavigate');
expect(ccAgentSessionViewSource).toContain(
diff --git a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
index c7ba058bb6..0eab204b55 100644
--- a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
@@ -127,7 +127,7 @@ describe('orcaSessionIdentity', () => {
{ id: 'bot-legacy-lane', role: 'group', kind: 'group' },
],
}];
- await expect(resolveSessionRoute('bot-main', { orcaRole: null, source: 'bot' })).resolves.toBe('/bots/bot-a');
+ await expect(resolveSessionRoute('bot-main', { orcaRole: null, source: 'bot' })).resolves.toBe('/bots/bot-a/session/bot-main');
await expect(resolveSessionRoute('bot-old', { orcaRole: null })).resolves.toBe('/cc-agent/bot-old');
await expect(resolveSessionRoute('bot-task', { orcaRole: null, source: 'desktop' })).resolves.toBe('/cc-agent/bot-task');
await expect(resolveSessionRoute('bot-lane', { orcaRole: null })).resolves.toBe('/cc-agent/bot-lane');
@@ -144,7 +144,7 @@ describe('orcaSessionIdentity', () => {
it('does not redirect an explicitly remote task to a same-id local Bot', async () => {
bots.profiles = [{ id: 'local', sessions: [{ id: 'same', role: 'canonical', kind: 'chat' }] }];
await expect(resolveSessionRoute('same', { orcaRole: null }, { remote: true })).resolves.toBe('/cc-agent/same');
- await expect(resolveSessionRoute('same', { orcaRole: null })).resolves.toBe('/bots/local');
+ await expect(resolveSessionRoute('same', { orcaRole: null })).resolves.toBe('/bots/local/session/same');
});
it('routes orphaned Orca workers back through the index fallback', async () => {
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 820ea75897..0d1bb3d01e 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -1,3 +1,4 @@
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { drainPendingDeepLinks } from '@/lib/pendingDeepLinks';
import { ChatInviteHost, reportMalformedChatInvite, requestChatInvite } from '@/features/bots/ChatInviteHost';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
@@ -134,7 +135,6 @@ import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore'
import {
isAgentIslandVisibleSessionOwnedByWorkdirBrowseRoute,
isAgentIslandVisibleSessionOwnedByBotRoute,
- resolveAgentIslandVisibleSessionFromRouteTarget,
resolveAgentIslandVisibleSessionsFromPath,
resolveAgentIslandVisibleSessionIdFromPath,
} from '@/lib/agentIslandVisibleSessionRoute';
@@ -491,6 +491,8 @@ export function MainLayout() {
if (!document.hasFocus()) return;
if (isAgentIslandVisibleSessionOwnedByWorkdirBrowseRoute(location.pathname)) return;
if (isAgentIslandVisibleSessionOwnedByBotRoute(location.pathname)) return;
+ // The task view confirms metadata and rendered history before acknowledging a single task.
+ if (typeof visibleSessions === 'string') return;
void window.electronAPI.agentIsland?.setVisibleSession?.(
visibleSessions,
);
@@ -554,7 +556,6 @@ export function MainLayout() {
currentPathRef.current = `${location.pathname}${location.search}`;
const navigateToOrdinarySession = useCallback(
(sessionId: string, messageClientId?: string, isLatest: () => boolean = () => true, deviceId?: string) => {
- if (deviceId) remoteProjectsStore.pinSessionOrigin(deviceId, sessionId);
// device-link 远程会话本地无 row:resolveSessionRoute 内部的 sessionService.get
// 会 miss → 远程 Orca lead/worker 被当普通会话路由,CCAgentSessionView 再
// redirect 到 orca 路由时会丢 searchJump 锚点。传入远程镜像的 session 对象,
@@ -562,9 +563,17 @@ export function MainLayout() {
const remoteSession =
remoteProjectsStore.getVisibleMergedRemoteSessions().find((s) =>
s.id === sessionId && (!deviceId || s.deviceLinkDeviceId === deviceId)) ?? null;
- void resolveSessionRoute(sessionId, remoteSession, { remote: !!deviceId }).then((target) => {
+ const route = deviceId
+ ? Promise.resolve(remoteBotRouteForSession(readRemoteBots().filter(bot => bot.deviceId === deviceId), sessionId)?.route
+ ?? `/cc-agent/${encodeURIComponent(sessionId)}`)
+ : resolveSessionRoute(sessionId, remoteSession);
+ void route.then((target) => {
if (!isLatest()) return;
- const visibleSession = resolveAgentIslandVisibleSessionFromRouteTarget(target);
+ if (deviceId && target !== '/cc-agent') {
+ const url = new URL(target, 'https://cindy.invalid');
+ url.searchParams.set('device', deviceId);
+ target = `${url.pathname}${url.search}`;
+ }
if (messageClientId) {
// 带消息锚点:即使已在目标路由也要 navigate——新的 location.state 才能
// 触发 CCAgentSessionView 的 searchJump 消费 effect(定位 + 高亮)。
@@ -582,17 +591,7 @@ export function MainLayout() {
} else if (currentPathRef.current !== target) {
navigate(target);
}
- // 通知点击跳转专用的 visible-session 上报:故意只 gate isAgentIslandSupported(),
- // 不像上面的 syncAgentIslandVisibleSession / OrcaSplitView 那样加 document.hasFocus()
- // 或 orca-split / workdir-browse 归属守卫。原因:通知触发跳转时主窗口 focus 往往还
- // 没稳定(见 main 端 isAgentIslandPendingFocusAck 放宽),本路径是唯一能在这段 focus
- // 竞态里把灵动岛收起的上报来源。若把 orca / files 路由交还各自 owner 组件,它们都带
- // document.hasFocus() 守卫、竞态期不会上报,首个权限卡片会退回"必须先点窗口才收起"
- // 的旧 bug。worker deep link 直接按 route query 上报 [Lead, Worker],普通会话
- // 上报单个 session;窗口 focus 稳定后 owner 组件继续维护同一份可见集合。
- if (isAgentIslandSupported()) {
- void window.electronAPI.agentIsland?.setVisibleSession?.(visibleSession);
- }
+
});
},
[navigate],
@@ -602,6 +601,10 @@ export function MainLayout() {
// One navigator for the layout's lifetime: its sequence must span re-renders so a
// late lookup for an earlier notification cannot override a newer click.
const [navigateToSession] = useState(() => createSessionEntryNavigator({
+ captureOwner: () => {
+ const owner = getDataOwnerGeneration();
+ return () => isDataOwnerGenerationCurrent(owner);
+ },
isRemoteDevice: async (deviceId) => deviceId !== await window.electronAPI.getDeviceId(),
readKnownBotRoute: (sessionId) => botRouteForOwnedSession(getBotProfiles(), sessionId)
?? remoteBotRouteForSession(readRemoteBots(), sessionId),
@@ -609,7 +612,14 @@ export function MainLayout() {
readProfiles: getBotProfiles,
loadProfiles: ensureBotProfilesLoaded,
}),
- openBotRoute: (route, islandEntryId) => {
+ openBotRoute: (route, islandEntryId, messageClientId, sessionId) => {
+ if (messageClientId && sessionId) {
+ sessionEntryDepsRef.current.navigate(route, { state: {
+ ...(islandEntryId ? islandEntryRouteState(islandEntryId) : {}),
+ searchJump: { kind: 'conversation-search', sessionId, messageId: messageClientId, messageIdKind: 'clientId', messageClientId },
+ } });
+ return;
+ }
// 只读历史由自己的归属门禁在显示后处置被点的卡:点击编号随路由状态交过去,已在该页也要重新交一次。
if (islandEntryId) {
sessionEntryDepsRef.current.navigate(route, {
diff --git a/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx b/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx
index 9b827900bb..9e1bca394d 100644
--- a/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx
@@ -4,6 +4,9 @@ import { standardSessionRoute } from '@/lib/orcaSessionIdentity';
/** Keep existing history links valid without a second task skin or read-only wrapper. */
export function BotHistorySessionView() {
const { sessionId, deviceId } = useParams();
- const { state } = useLocation();
- return <Navigate to={sessionId ? standardSessionRoute(sessionId, deviceId) : '/cc-agent'} state={state} replace />;
+ const { state, search } = useLocation();
+ const query = new URLSearchParams(search);
+ if (deviceId) query.set('device', deviceId);
+ const suffix = query.size ? `?${query}` : '';
+ return <Navigate to={sessionId ? `${standardSessionRoute(sessionId)}${suffix}` : '/cc-agent'} state={state} replace />;
}
diff --git a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
index 80144fffff..aaafb5903c 100644
--- a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
@@ -1,10 +1,9 @@
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
-import { Button } from '@/components/ui/button';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { ArrowLeft, CircleAlert, RefreshCcw } from 'lucide-react';
-import { useNavigate, useParams } from 'react-router-dom';
+import { Navigate, useLocation, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
+import { SessionEntryError, sessionEntryFailure } from '@/features/cc-agent/SessionEntryError';
import { Spinner } from '@/components/ui/spinner';
import { CCAgentSessionView } from '@/features/cc-agent/CCAgentSessionView';
import { useCompanionCloud } from './companionCloudStore';
@@ -16,9 +15,10 @@ import { getBotLastReadAt, markBotRead } from './botReadState';
import { useBotProfiles } from './botStore';
import type { BotChatIdentity } from './BotSessionContentHeader';
import type { BotChatBinding } from './botChatPresentation';
-import { useBotIslandVisibleSession } from './useBotIslandVisibleSession';
import { BotDmThreadHost } from './BotDmThreadHost';
import { useBotPluginFocusedSession } from './useBotPluginFocusedSession';
+import { canonicalBotSession } from './botSessionOwners';
+import { standardSessionRoute } from '@/lib/orcaSessionIdentity';
type BotSessionGate =
| { kind: 'loading' }
@@ -32,7 +32,8 @@ type BotSessionGate =
unreadBoundaryAt: number | null;
}
| { kind: 'unavailable' }
- | { kind: 'error'; message: string };
+ | { kind: 'ordinary' }
+ | { kind: 'error'; reason: ReturnType<typeof sessionEntryFailure> };
function readBotChatIdentity(bot: unknown, botId: string): BotChatIdentity {
const candidate = (bot ?? {}) as { name?: unknown; avatar?: unknown; avatarColor?: unknown; templateId?: unknown };
@@ -84,7 +85,7 @@ export function BotSessionView() {
function BotSessionGateView() {
const readOwner = useRef(getDataOwnerGeneration());
const { t } = useTranslation();
- const navigate = useNavigate();
+ const location = useLocation();
const { botId, sessionId } = useParams();
const [reloadVersion, setReloadVersion] = useState(0);
const [gate, setGate] = useState<BotSessionGate>({ kind: 'loading' });
@@ -96,7 +97,6 @@ function BotSessionGateView() {
const readyMentions = gate.kind === 'ready' ? gate.mentions : null;
const mentions = useMemo(() => (readyMentions ? withoutShadowedBots(readyMentions, cloud) : []), [readyMentions, cloud]);
const ownedSessionId = gate.kind === 'ready' ? sessionId ?? null : null;
- useBotIslandVisibleSession(ownedSessionId);
useBotPluginFocusedSession(ownedSessionId);
// The gate proves ownership once; name and avatar edited in settings must
// still reach the open chat's header and composer.
@@ -138,7 +138,10 @@ function BotSessionGateView() {
setGate({ kind: 'loading' });
const lastReadAt = getBotLastReadAt(botId);
void Promise.all([
- window.electronAPI.localDb.bots.get(botId),
+ window.electronAPI.localDb.bots.get(botId).catch((error: unknown) => {
+ if (sessionEntryFailure(error) === 'missing') return null;
+ throw error;
+ }),
window.electronAPI.localDb.bots.list(
lastReadAt === null ? undefined : { lastReadAtByBotId: { [botId]: lastReadAt } },
),
@@ -146,24 +149,18 @@ function BotSessionGateView() {
.then(([bot, bots]) => {
if (cancelled || !isDataOwnerGenerationCurrent(owner)) return;
if (!bot || typeof bot !== 'object') {
- setGate({ kind: 'unavailable' });
+ setGate({ kind: 'ordinary' });
return;
}
const sessions = (bot as { sessions?: unknown }).sessions;
const profileStatus = (bot as { status?: unknown }).status;
const activeProjection = Array.isArray(sessions)
- ? sessions.find((row): row is { role?: unknown } => {
- if (!row || typeof row !== 'object') return false;
- const projection = row as { id?: unknown; kind?: unknown; status?: unknown };
- return (
- projection.id === sessionId &&
- projection.kind === 'chat' &&
- projection.status === 'active'
- );
- })
+ ? canonicalBotSession({ sessions: sessions.filter((row) => row && typeof row === 'object') })
: undefined;
- if (profileStatus !== 'active' || !activeProjection) {
- setGate({ kind: 'unavailable' });
+ if (profileStatus !== 'active' || activeProjection?.id !== sessionId || activeProjection?.status !== 'active') {
+ // The URL is an old presentation, not evidence that the task disappeared.
+ // Ordinary task access still passes through the host's authorization checks.
+ setGate({ kind: 'ordinary' });
return;
}
const listedBot = Array.isArray(bots)
@@ -200,7 +197,7 @@ function BotSessionGateView() {
if (cancelled || !isDataOwnerGenerationCurrent(owner)) return;
setGate({
kind: 'error',
- message: error instanceof Error ? error.message : String(error),
+ reason: sessionEntryFailure(error),
});
});
return () => {
@@ -212,6 +209,9 @@ function BotSessionGateView() {
if (isDataOwnerGenerationCurrent(readOwner.current) && gate.kind === 'ready' && gate.isCanonical && botId && gate.identity.sessionId === sessionId) markBotRead(botId, at);
}, [botId, gate, sessionId]);
+ if (gate.kind === 'ordinary' && sessionId) {
+ return <Navigate to={`${standardSessionRoute(sessionId)}${location.search ?? ''}`} state={location.state} replace />;
+ }
if (gate.kind === 'loading') {
return (
<main className="flex h-full items-center justify-center bg-[var(--surface)]">
@@ -225,49 +225,8 @@ function BotSessionGateView() {
);
}
if (gate.kind !== 'ready' || !sessionId) {
- const failed = gate.kind === 'error';
- return (
- <main className="flex h-full items-center justify-center bg-[var(--surface)] p-6">
- <section className="w-full max-w-md rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-5 text-center">
- <CircleAlert size={24} className="mx-auto text-[var(--text-danger)]" aria-hidden />
- <h1 className="mt-3 text-16 font-medium text-[var(--text-primary)]">
- {t(failed ? 'bots.sessionLoadFailedTitle' : 'bots.sessionUnavailableTitle')}
- </h1>
- <p className="mt-2 break-words text-12 leading-5 text-[var(--text-secondary)] [overflow-wrap:anywhere]">
- {failed
- ? t('bots.sessionLoadFailedDescription')
- : t('bots.sessionUnavailableDescription')}
- </p>
- {failed && gate.message ? (
- <p className="mt-3 max-h-24 overflow-y-auto whitespace-pre-wrap rounded-lg bg-[var(--surface)] px-3 py-2 text-left text-11 text-[var(--text-danger)] [overflow-wrap:anywhere]">
- {gate.message}
- </p>
- ) : null}
- <div className="mt-4 flex flex-wrap justify-center gap-2">
- <button
- type="button"
- onClick={() => navigate(botId ? `/bots/${botId}` : '/bots')}
- className="inline-flex h-9 items-center gap-2 rounded-lg border border-[var(--border-default)] px-3 text-12 text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]"
- >
- <ArrowLeft size={14} />
- {t('bots.backToBot')}
- </button>
- {failed ? (
- <Button
- variant="cta"
- size="lg"
- compact
- type="button"
- onClick={() => setReloadVersion((value) => value + 1)}
- >
- <RefreshCcw size={14} />
- {t('bots.retry')}
- </Button>
- ) : null}
- </div>
- </section>
- </main>
- );
+ return <SessionEntryError reason={gate.kind === 'error' ? gate.reason : 'missing'}
+ onRetry={() => setReloadVersion((value) => value + 1)} />;
}
const readOnly = shadowed && gate.isCanonical;
return (
diff --git a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
index 8488bedbf1..117cf33e15 100644
--- a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
@@ -2,7 +2,8 @@ import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts
import { Button } from '@/components/ui/button';
import { REMOTE_RESOURCE_GET_CHANNEL, type RemoteResourceGetRequest } from '@cindy/device-link';
import { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';
-import { useParams } from 'react-router-dom';
+import { Navigate, useLocation, useParams } from 'react-router-dom';
+import { standardSessionRoute } from '@/lib/orcaSessionIdentity';
import { useTranslation } from 'react-i18next';
import { CCAgentSessionView } from '@/features/cc-agent/CCAgentSessionView';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
@@ -11,7 +12,6 @@ import { Spinner } from '@/components/ui/spinner';
import { BotAvatar } from './BotAvatar';
import { parseRemoteBots, type RemoteBot } from './remoteBotRoster';
import { markRemoteBotRead, useRemoteBots } from './useRemoteBots';
-import { useBotIslandVisibleSession } from './useBotIslandVisibleSession';
import { useCompanionCloud } from './companionCloudStore';
import { cloudCompanionAt, homeControlOff } from './companionCloudPresentation';
import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';
@@ -23,9 +23,11 @@ const CloudCompanionOfflineView = lazy(() => import('./CloudCompanionOfflineView
/** How long an open chat stays in place while its main computer cannot be reached. */
export const CLOUD_HOME_GRACE_MS = 15_000;
-/** The session id comes from the host's collection, never from an arbitrary URL. */
+/** Verify companion identity with its host; pinned task links never adopt a replacement chat. */
export function RemoteBotSessionView() {
- const { deviceId, botId } = useParams();
+ const { deviceId, botId, sessionId: requestedSessionId } = useParams();
+ const location = useLocation();
+ const [originalTask, setOriginalTask] = useState(false);
const { t } = useTranslation();
const bots = useRemoteBots();
const bot = bots.find((row) => row.id === botId && row.deviceId === deviceId);
@@ -42,6 +44,7 @@ export function RemoteBotSessionView() {
let disposed = false;
const owner = getDataOwnerGeneration();
setFailed(false);
+ setOriginalTask(false);
if (!deviceId || !bot?.online) return;
const request: RemoteResourceGetRequest = {
client: { protocolVersion: 1, primitives: ['status', 'session-link'] },
@@ -61,6 +64,10 @@ export function RemoteBotSessionView() {
);
if (resolved.id !== bot.id || !resolved.sessionId) throw new Error('Companion is not ready');
const canonicalId = resolved.sessionId;
+ if (requestedSessionId && canonicalId !== requestedSessionId) {
+ setOriginalTask(true);
+ return;
+ }
const existingOrigin = remoteProjectsStore.getSessionDeviceId(canonicalId);
if (existingOrigin && existingOrigin !== deviceId)
throw new Error('Conflicting remote session owner');
@@ -87,27 +94,30 @@ export function RemoteBotSessionView() {
setReady({ ...resolved, sessionId: canonicalId, canonicalChat: true });
setValidatedSessionId(sessionId);
})().catch(() => {
- if (!disposed) setFailed(true);
+ if (!disposed && isDataOwnerGenerationCurrent(owner)) setFailed(true);
});
return () => {
disposed = true;
};
- }, [deviceId, botId, sessionId, bot?.online, bot?.deviceName, retry]);
+ }, [deviceId, botId, sessionId, bot?.online, bot?.deviceName, retry, requestedSessionId]);
const acknowledge = useCallback((at: number) => {
- if (isDataOwnerGenerationCurrent(readOwner.current) && bot?.online && !failed && ready?.id === bot.id && ready.deviceId === bot.deviceId
+ if ((!requestedSessionId || ready?.sessionId === requestedSessionId) && !originalTask && isDataOwnerGenerationCurrent(readOwner.current) && bot?.online && !failed && ready?.id === bot.id && ready.deviceId === bot.deviceId
&& validatedSessionId === bot.sessionId) {
markRemoteBotRead(bot.deviceId, bot.id, Math.min(at, bot.lastReplyAt ?? 0));
}
- }, [bot, failed, ready, validatedSessionId]);
+ }, [bot, failed, ready, validatedSessionId, requestedSessionId, originalTask]);
- const liveChat = !!bot && !failed && !!ready?.sessionId && ready.id === botId && ready.deviceId === deviceId;
- // Like a local companion chat: once the chat is shown, the island card for this Session is read.
- useBotIslandVisibleSession(liveChat ? ready!.sessionId : null);
+ const liveChat = !originalTask && (!requestedSessionId || requestedSessionId === ready?.sessionId) && !!bot && !failed && !!ready?.sessionId && ready.id === botId && ready.deviceId === deviceId;
const homeAway = !!cloudActor && !!deviceId && !!botId && cloudActor.homeDeviceId !== cloud.selfDeviceId
&& (!bot || (!bot.online && bot.connectionKnown !== false));
// Like IM, a brief drop keeps the open chat in place (cloud-companions.md §3.1).
const homeAwayLong = useDelayedFlag(homeAway && liveChat, CLOUD_HOME_GRACE_MS);
+ if (requestedSessionId && deviceId && (originalTask || failed || !bot?.online || bot.sessionId !== requestedSessionId)) {
+ const query = new URLSearchParams(location.search);
+ query.set('device', deviceId);
+ return <Navigate to={`${standardSessionRoute(requestedSessionId)}?${query}`} state={location.state} replace />;
+ }
// Its main computer is offline (or never reachable here): read the cloud conversation
// and offer to continue on this computer instead of a stale read-only mirror.
if (cloudActor && deviceId && botId && homeAway && (!liveChat || homeAwayLong)) {
@@ -126,7 +136,7 @@ export function RemoteBotSessionView() {
</Suspense>
);
}
- if (bot && !failed && ready?.sessionId && ready.id === botId && ready.deviceId === deviceId) {
+ if (liveChat && bot && ready) {
return (
<CCAgentSessionView
key={`${deviceId}:${ready.sessionId}`}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx
index 0e4624e438..ea84974728 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botIslandVisibility.test.tsx
@@ -6,12 +6,13 @@ const mocks = vi.hoisted(() => ({
params: { botId: 'bot-a', sessionId: 'chat-a' },
location: { state: null as unknown },
supported: true,
+ historyLoaded: false,
}));
vi.mock('react-router-dom', () => ({
useParams: () => mocks.params,
useLocation: () => mocks.location,
useNavigate: () => vi.fn(),
- Navigate: () => null,
+ Navigate: () => <div data-testid="original-task" />,
}));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (s: string) => s }) }));
vi.mock('@/hooks/useAgentIslandSettings', () => ({
@@ -20,10 +21,14 @@ vi.mock('@/hooks/useAgentIslandSettings', () => ({
// The private-chat topic host belongs to the chat surface these tests isolate.
vi.mock('../BotDmThreadHost', () => ({ BotDmThreadHost: ({ children }: { children: import('react').ReactNode }) => <>{children}</> }));
vi.mock('@/features/cc-agent/CCAgentSessionView', () => ({
- CCAgentSessionView: ({ readOnly }: { readOnly?: boolean }) => <div data-testid="chat" data-readonly={String(!!readOnly)} />,
+ CCAgentSessionView: ({ readOnly }: { readOnly?: boolean }) => {
+ useBotIslandVisibleSession(mocks.historyLoaded ? mocks.params.sessionId : null);
+ return <div data-testid="chat" data-readonly={String(!!readOnly)} />;
+ },
}));
vi.mock('../botReadState', () => ({ getBotLastReadAt: () => null, markBotRead: vi.fn() }));
+import { useBotIslandVisibleSession } from '../useBotIslandVisibleSession';
import { BotSessionView } from '../BotSessionView';
import { BotHistorySessionView } from '../BotHistorySessionView';
@@ -34,7 +39,7 @@ const get = vi.fn();
const history = vi.fn();
const profile = {
id: 'bot-a', status: 'active',
- sessions: [{ id: 'chat-a', kind: 'chat', status: 'active' }],
+ sessions: [{ id: 'chat-a', kind: 'chat', status: 'active', role: 'canonical' }],
};
beforeEach(() => {
@@ -42,6 +47,7 @@ beforeEach(() => {
mocks.params = { botId: 'bot-a', sessionId: 'chat-a' };
mocks.location = { state: null };
mocks.supported = true;
+ mocks.historyLoaded = true;
vi.spyOn(document, 'hasFocus').mockReturnValue(true);
get.mockResolvedValue(profile);
history.mockResolvedValue([{ id: 'chat-a' }]);
@@ -138,7 +144,7 @@ describe('unavailable Bot task page never disposes island alerts by itself', ()
sessions: [...profile.sessions, { id: 'delegated-a', kind: 'worker', role: 'delegation', status: 'active' }],
});
const view = render(<BotSessionView />);
- await waitFor(() => expect(view.getByText('bots.sessionUnavailableTitle')).toBeTruthy());
+ await waitFor(() => expect(view.getByTestId('original-task')).toBeTruthy());
view.rerender(<BotSessionView />);
await act(async () => {});
expect(consumeEntryAlert).not.toHaveBeenCalled();
@@ -151,7 +157,7 @@ describe('unavailable Bot task page never disposes island alerts by itself', ()
live.unmount();
get.mockRejectedValue(new Error('db busy'));
const failed = render(<BotSessionView />);
- await waitFor(() => expect(failed.getByText('bots.sessionLoadFailedTitle')).toBeTruthy());
+ await waitFor(() => expect(failed.getByText('ccAgent.sessionEntry.failed')).toBeTruthy());
expect(consumeEntryAlert).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts
index 0adf1b7353..dd54cd0170 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts
@@ -68,6 +68,19 @@ describe('伙伴归属表', () => {
});
});
+ // Regression: kind=chat used to win over the unique durable canonical role.
+ // Unit, production route; the older fixture put canonical first and missed this ordering.
+ it('keeps old chat links and ambiguous canonical projections on their original task', () => {
+ const bot = profile({ sessions: [
+ { id: 'old', kind: 'chat', role: 'history' },
+ { id: 'current', kind: 'chat', role: 'canonical' },
+ ] as BotProfile['sessions'] });
+ expect(botRouteForOwnedSession([bot], 'old')?.route).toBe('/cc-agent/old');
+ expect(botRouteForOwnedSession([bot], 'current')?.route).toBe('/bots/bot-a/session/current');
+ bot.sessions.push({ id: 'duplicate', role: 'canonical' } as BotProfile['sessions'][number]);
+ expect(botRouteForOwnedSession([bot], 'current')?.route).toBe('/cc-agent/current');
+ });
+
it('主对话、渠道任务、归档历史三种都收', () => {
const owners = buildBotSessionOwners([profile()]);
expect([...owners.keys()].sort()).toEqual(['s-main', 's-old', 's-telegram']);
@@ -103,7 +116,7 @@ describe('伙伴归属表', () => {
{ id: 's-lane', role: 'group', kind: 'group' },
] as unknown as BotProfile['sessions'],
});
- expect(botRouteForOwnedSession([bot], 's-main')).toEqual({ route: '/bots/bot%2Fa', consumesAlert: false });
+ expect(botRouteForOwnedSession([bot], 's-main')).toEqual({ route: '/bots/bot%2Fa/session/s-main', consumesAlert: false });
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 });
@@ -114,7 +127,7 @@ describe('伙伴归属表', () => {
it('通知点击把主任务送回伙伴页,子任务保留自己的任务地址', () => {
const bot = profile({ id: 'bot/a' });
- expect(botRouteForOwnedSession([bot], 's-main')).toEqual({ route: '/bots/bot%2Fa', consumesAlert: false });
+ expect(botRouteForOwnedSession([bot], 's-main')).toEqual({ route: '/bots/bot%2Fa/session/s-main', consumesAlert: false });
expect(botRouteForOwnedSession([bot], 's-telegram')).toEqual({
route: '/cc-agent/s-telegram',
consumesAlert: false,
@@ -149,7 +162,7 @@ describe('伙伴归属表', () => {
it('主力电脑在别的设备上的伙伴,点击回到那台设备的伙伴页', () => {
const remote = [{ id: 'opus', deviceId: 'mac studio', sessionId: 's-remote' }];
expect(remoteBotRouteForSession(remote, 's-remote')).toEqual({
- route: '/bots/remote/mac%20studio/opus',
+ route: '/bots/remote/mac%20studio/opus/session/s-remote',
consumesAlert: false,
});
expect(remoteBotRouteForSession(remote, 's-other')).toBeNull();
@@ -191,7 +204,7 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
expect(readKnownBotRoute).not.toHaveBeenCalled();
expect(openBotRoute).not.toHaveBeenCalled();
} else {
- expect(openBotRoute).toHaveBeenCalledWith('/bots/local', undefined);
+ expect(openBotRoute).toHaveBeenCalledWith('/bots/local', undefined, 'message-1', 'same');
expect(openOrdinary).not.toHaveBeenCalled();
}
});
@@ -229,7 +242,7 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
it('投影已含该任务时直接回伙伴页,不重载', async () => {
const { deps: d, loadProfiles } = deps({ current: [profile()] });
await expect(resolveBotRouteForSessionEntry('s-main', d)).resolves.toEqual({
- route: '/bots/bot-a',
+ route: '/bots/bot-a/session/s-main',
consumesAlert: false,
});
expect(loadProfiles).not.toHaveBeenCalled();
@@ -312,6 +325,34 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
expect(isSecondLatest()).toBe(false);
});
+ it('preserves message anchors through a late companion correction and cancels on owner change or manual navigation', async () => {
+ let currentOwner = true;
+ let resolve!: (value: BotSessionEntryTarget | null) => void;
+ const openOrdinary = vi.fn();
+ const openBotRoute = vi.fn();
+ const open = createSessionEntryNavigator({
+ captureOwner: () => () => currentOwner,
+ readKnownBotRoute: () => null,
+ resolveBotRoute: () => new Promise(done => { resolve = done; }),
+ openOrdinary, openBotRoute, consumeAlert: vi.fn(),
+ });
+ open('original', 'reply');
+ resolve({ route: '/bots/b/session/original', consumesAlert: false });
+ await Promise.resolve();
+ expect(openBotRoute).toHaveBeenLastCalledWith('/bots/b/session/original', undefined, 'reply', 'original');
+ openBotRoute.mockClear();
+ open('old-owner', 'reply');
+ currentOwner = false;
+ resolve({ route: '/bots/b/session/old-owner', consumesAlert: false });
+ await Promise.resolve();
+ expect(openBotRoute).not.toHaveBeenCalled();
+ expect(openOrdinary.mock.lastCall![2]()).toBe(false);
+ currentOwner = true;
+ open('slow');
+ open.locationCommitted('/settings');
+ expect(openOrdinary.mock.lastCall![2]()).toBe(false);
+ });
+
it('后台任务走普通任务入口,保留消息锚点与灵动岛上报,也不重读投影', async () => {
const openBotRoute = vi.fn();
const openOrdinary = vi.fn();
@@ -357,7 +398,7 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
open.locationCommitted('/cc-agent/s-lane');
resolve(lane);
await Promise.resolve();
- expect(openBotRoute).toHaveBeenCalledWith('/bots/groups/g-1', undefined);
+ expect(openBotRoute).toHaveBeenCalledWith('/bots/groups/g-1', undefined, undefined, 's-lane');
open.locationCommitted('/bots/groups/g-1');
expect(consumeAlert).toHaveBeenCalledWith('s-lane', 'entry-1');
});
@@ -368,7 +409,7 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
open('s-lane');
resolve(lane);
await Promise.resolve();
- expect(openBotRoute).toHaveBeenCalledWith('/bots/groups/g-1', undefined);
+ expect(openBotRoute).toHaveBeenCalledWith('/bots/groups/g-1', undefined, undefined, 's-lane');
expect(isOrdinaryLatest()).toBe(false);
});
@@ -411,7 +452,7 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
describe('灵动岛点击的处置等目标地址提交后才发', () => {
const targets: Record<string, BotSessionEntryTarget> = {
's-lane': { route: '/bots/groups/g-1', consumesAlert: true },
- 's-main': { route: '/bots/bot-a', consumesAlert: false },
+ 's-main': { route: '/bots/bot-a/session/s-main', consumesAlert: false },
's-old': { route: '/cc-agent/s-old', consumesAlert: false },
};
function setup(over: { openBotRoute?: (route: string, islandEntryId?: string) => void } = {}) {
@@ -437,7 +478,7 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
open.locationCommitted('/cc-agent/new');
open('s-lane', undefined, 'entry-1');
await settle();
- expect(openBotRoute).toHaveBeenCalledWith('/bots/groups/g-1', undefined);
+ expect(openBotRoute).toHaveBeenCalledWith('/bots/groups/g-1', undefined, undefined, 's-lane');
expect(consumeAlert).not.toHaveBeenCalled();
open.locationCommitted('/bots/groups/g-1');
expect(consumeAlert).toHaveBeenCalledTimes(1);
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx
index 01999e46d6..d7738bdbf2 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx
@@ -79,7 +79,7 @@ it('does not accept an arbitrary task id from a Bot URL', async () => {
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' },
+ { id: 'chat', kind: 'chat', status: 'active', role: 'canonical' },
] });
const view = render(<BotSessionView />);
await screen.findByText('companion:bot');
@@ -89,6 +89,13 @@ it('drops the previous binding synchronously when navigating to a different Bot
expect(screen.queryByText('companion:bot')).toBeNull();
expect(screen.queryByText('task controls')).toBeNull();
});
+it('opens the original task when a stale bot URL rejects with NOT_FOUND, without adopting a bot', async () => {
+ h.get.mockRejectedValue(new Error('[NOT_FOUND] Bot 不存在'));
+ render(<BotSessionView />);
+ await act(async () => {});
+ expect(h.redirect).toHaveBeenCalledWith({ to: '/cc-agent/chat', state: null, replace: true });
+ expect(screen.queryByText('companion:bot')).toBeNull();
+});
it('follows a rename saved from settings while the chat stays open', async () => {
h.get.mockResolvedValue({ id: 'bot', name: 'Melody', status: 'active', sessions: [
{ id: 'chat', kind: 'chat', status: 'active', role: 'canonical' },
@@ -121,14 +128,16 @@ it('never shows the first-hello wait in a channel-routed (non-canonical) task of
] });
h.profiles = [{ id: 'bot', name: 'Melody', avatar: '🎵', avatarColor: 'violet', invitation: { stage: 'welcome' } }];
render(<BotSessionView />);
- expect((await screen.findByText('companion:bot')).getAttribute('data-invitation-stage')).toBe('');
+ await act(async () => {});
+ expect(h.redirect).toHaveBeenCalledWith({ to: '/cc-agent/chat', state: null, replace: true });
+ expect(screen.queryByText('companion:bot')).toBeNull();
});
// 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.redirect).toHaveBeenCalledWith({ to: `/cc-agent/old%2Ftask${deviceId ? '?device=remote%20computer' : ''}`, state: null, replace: true });
+ expect(h.redirect).toHaveBeenCalledWith({ to: `/cc-agent/old%2Ftask${deviceId ? '?device=remote+computer' : ''}`, state: null, replace: true });
expect(h.get).not.toHaveBeenCalled();
expect(h.history).not.toHaveBeenCalled();
expect(h.invoke).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx
index 8da6690314..03855cce08 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx
@@ -20,6 +20,8 @@ vi.mock('../CompanionShadowBanner', () => ({ CompanionShadowBanner: ({ botId }:
vi.mock('react-router-dom', () => ({
useNavigate: () => mocks.navigate,
useParams: () => mocks.params,
+ useLocation: () => ({ search: '', state: null }),
+ Navigate: () => <div data-testid="original-task" />,
}));
// The private-chat topic host belongs to the chat surface these tests isolate.
vi.mock('../BotDmThreadHost', () => ({ BotDmThreadHost: ({ children }: { children: import('react').ReactNode }) => <>{children}</> }));
@@ -72,6 +74,7 @@ const readyBot = {
};
beforeEach(() => {
+ mocks.read = undefined;
messageListeners = [];
window.localStorage.clear();
resetBotReadStateForTests();
@@ -116,8 +119,8 @@ describe('Bot conversation read position', () => {
markBotRead('bot-1', 5_000);
installElectronApi({ ...readyBot, sessions: [{ id: 'session-1', kind: 'chat', role: 'history', status: 'active' }] });
const view = render(<BotSessionView />);
- await waitFor(() => expect(view.getByTestId('chat')).toBeTruthy());
- expect(view.getByTestId('chat').dataset.canonicalChat).toBe('false');
+ await waitFor(() => expect(view.getByTestId('original-task')).toBeTruthy());
+ expect(view.queryByTestId('chat')).toBeNull();
expect(mocks.read).toBeUndefined();
expect(getBotLastReadAt('bot-1')).toBe(5_000);
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotModelSnapshot.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotModelSnapshot.test.tsx
index b06c8ab5b1..ec22a4f0b9 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotModelSnapshot.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotModelSnapshot.test.tsx
@@ -8,7 +8,7 @@ import { makerApiFor } from '@/lib/makerTransport';
import { resolveComposerModelSelection } from '@/components/new-chat/composerModelSelection';
const h = vi.hoisted(() => ({ invoke: vi.fn() }));
-vi.mock('react-router-dom', () => ({ useParams: () => ({ deviceId: 'snapshot-host', botId: 'writer' }) }));
+vi.mock('react-router-dom', () => ({ useLocation: () => ({ search: '', state: null }), Navigate: () => null, useParams: () => ({ deviceId: 'snapshot-host', botId: 'writer' }) }));
vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({ useDeviceLinkDeviceList: () => null }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('../useRemoteBots', () => ({
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
index 9621c3e574..d2e546733e 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
@@ -10,6 +10,8 @@ const h = vi.hoisted(() => ({
pin: vi.fn(),
merge: vi.fn(),
view: vi.fn(),
+ navigate: vi.fn(),
+ requestedSessionId: undefined as string | undefined,
online: true,
listed: true,
lastReplyAt: 0,
@@ -22,7 +24,11 @@ vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({ useDeviceLink
vi.mock('../CloudCompanionOfflineView', () => ({
CloudCompanionOfflineView: (props: unknown) => { h.cloudView(props); return <div>cloud-offline-view</div>; },
}));
-vi.mock('react-router-dom', () => ({ useParams: () => ({ deviceId: 'home', botId: 'writer' }) }));
+vi.mock('react-router-dom', () => ({
+ useLocation: () => ({ search: '?keep=1', state: { searchJump: { messageClientId: 'reply' } } }),
+ Navigate: (props: unknown) => { h.navigate(props); return <div>original-task</div>; },
+ useParams: () => ({ deviceId: 'home', botId: 'writer', sessionId: h.requestedSessionId }),
+}));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('../useRemoteBots', () => ({
markRemoteBotRead: h.markRead,
@@ -58,6 +64,8 @@ vi.mock('@/features/cc-agent/CCAgentSessionView', () => ({
import { CLOUD_HOME_GRACE_MS, RemoteBotSessionView } from '../RemoteBotSessionView';
beforeEach(() => {
h.markRead.mockClear();
+ h.navigate.mockReset();
+ h.requestedSessionId = undefined;
h.online = true;
h.listed = true;
h.lastReplyAt = 0;
@@ -83,6 +91,24 @@ beforeEach(() => {
window.electronAPI = { deviceLink: { invoke: h.invoke } } as unknown as Window['electronAPI'];
});
afterEach(cleanup);
+// Unit regression: an exact notification link must retain its task, host and anchor
+// when the canonical link changed, its host is offline, or the companion lookup fails.
+it.each(['changed', 'offline', 'failed'] as const)('preserves the original task when the companion is %s', async (reason) => {
+ h.requestedSessionId = 'old-canonical';
+ h.cloud = { enabled: true, selfDeviceId: 'desk', humanActorId: 'human', demotedBotIds: [], actors: [
+ { id: 'a-writer', externalId: 'writer', name: 'Writer', avatar: null, homeDeviceId: 'home' }] };
+ if (reason === 'offline') h.online = false;
+ if (reason === 'failed') h.invoke.mockRejectedValue(new Error('Unavailable'));
+ render(<RemoteBotSessionView />);
+ await screen.findByText('original-task');
+ expect(h.navigate).toHaveBeenLastCalledWith({
+ to: '/cc-agent/old-canonical?keep=1&device=home',
+ state: { searchJump: { messageClientId: 'reply' } }, replace: true,
+ });
+ expect(h.view).not.toHaveBeenCalled();
+ expect(h.cloudView).not.toHaveBeenCalled();
+ expect(h.markRead).not.toHaveBeenCalled();
+});
// Unit regression: a host conversation link + active bot session must reach the shared
// parent chat as canonical, or its post-send follow-up invitation can never appear.
it('resolves the latest canonical task and passes its verified identity to writable chat', async () => {
diff --git a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts b/apps/desktop/src/renderer/features/bots/botSessionOwners.ts
index 81eac12aab..d4685feaf0 100644
--- a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts
+++ b/apps/desktop/src/renderer/features/bots/botSessionOwners.ts
@@ -13,6 +13,12 @@ import type { BotSessionOwner } from '@/features/cc-agent/lib/projectGrouping';
import type { BotProfile } from './botStore';
import type { RemoteBot } from './remoteBotRoster';
+/** The durable registry has exactly one canonical link; kind is only presentation. */
+export function canonicalBotSession<T extends { role?: unknown }>(bot: { sessions: readonly T[] }): T | undefined {
+ const matches = bot.sessions.filter((session) => session.role === 'canonical');
+ return matches.length === 1 ? matches[0] : undefined;
+}
+
/**
* Find the Bot that owns a real Cindy Session through the projected
* `bot_session_links` registry. The compatibility mirror on BotProfile is
@@ -47,10 +53,9 @@ export function botRouteForOwnedSession(
const bot = findBotProfileForSession(profiles, sessionId);
if (!bot) return null;
const botRoute = `/bots/${encodeURIComponent(bot.id)}`;
- const canonicalSessionId = bot.sessions.find(
- (session) => session.role === 'canonical' || session.kind === 'chat',
- )?.id;
- if (canonicalSessionId === sessionId) return { route: botRoute, consumesAlert: false };
+ const canonicalSessionId = canonicalBotSession(bot)?.id;
+ // Keep the original id even if the cached link becomes history before the click lands.
+ if (canonicalSessionId === sessionId) return { route: `${botRoute}/session/${encodeURIComponent(sessionId)}`, consumesAlert: false };
return { route: `/cc-agent/${encodeURIComponent(sessionId)}`, consumesAlert: false };
}
@@ -65,7 +70,7 @@ export function remoteBotRouteForSession(
const bot = remoteBots.find((candidate) => candidate.sessionId === sessionId);
if (!bot) return null;
return {
- route: `/bots/remote/${encodeURIComponent(bot.deviceId)}/${encodeURIComponent(bot.id)}`,
+ route: `/bots/remote/${encodeURIComponent(bot.deviceId)}/${encodeURIComponent(bot.id)}/session/${encodeURIComponent(sessionId)}`,
consumesAlert: false,
};
}
@@ -120,7 +125,8 @@ export interface SessionEntryNavigatorDeps {
/** Re-reads the projection for a Session it did not know (see resolveBotRouteForSessionEntry). */
resolveBotRoute: (sessionId: string) => Promise<BotSessionEntryTarget | null>;
/** `islandEntryId` is handed to a route whose gate disposes the card (gateConsumesAlert). */
- openBotRoute: (route: string, islandEntryId?: string) => void;
+ openBotRoute: (route: string, islandEntryId?: string, messageClientId?: string, sessionId?: string) => void;
+ captureOwner?: () => () => boolean;
/** Asks main to dispose the card of this island click (see BotSessionEntryTarget). */
consumeAlert: (sessionId: string, islandEntryId: string) => void;
/** `isLatest` lets the ordinary path drop its own late async route result too. */
@@ -161,7 +167,7 @@ export function createSessionEntryNavigator(
// coming back never counts as "stayed".
let committedSinceOpen = new Set<string>();
let pending: { entry: number; sessionId: string; islandEntryId: string; route: string } | null = null;
- const openBotTarget = (entry: number, sessionId: string, target: BotSessionEntryTarget, disposalId: string | undefined) => {
+ const openBotTarget = (entry: number, sessionId: string, target: BotSessionEntryTarget, disposalId: string | undefined, messageClientId?: string) => {
if (target.consumesAlert && disposalId) {
if (committedPath === target.route) {
deps.consumeAlert(sessionId, disposalId);
@@ -170,7 +176,7 @@ export function createSessionEntryNavigator(
}
}
try {
- deps.openBotRoute(target.route, target.gateConsumesAlert ? disposalId : undefined);
+ deps.openBotRoute(target.route, target.gateConsumesAlert ? disposalId : undefined, messageClientId, sessionId);
} catch (error) {
if (pending?.entry === entry) pending = null;
throw error;
@@ -180,13 +186,14 @@ export function createSessionEntryNavigator(
const entry = ++sequence;
pending = null;
committedSinceOpen = new Set();
- const isLatest = () => sequence === entry;
+ const ownerCurrent = deps.captureOwner?.() ?? (() => true);
+ const isLatest = () => sequence === entry && ownerCurrent();
if (deviceId && deps.isRemoteDevice) {
void deps.isRemoteDevice(deviceId).then((remote) => {
- if (!isLatest()) return;
+ if (!isLatest() || committedSinceOpen.size > 0) return;
if (remote) deps.openOrdinary(sessionId, messageClientId, isLatest, deviceId);
else openLocal();
- });
+ }).catch(() => undefined);
return;
}
openLocal();
@@ -194,11 +201,11 @@ export function createSessionEntryNavigator(
const known = deps.readKnownBotRoute(sessionId);
// Background tasks keep their ordinary page with message anchors and visible-session reporting.
if (known && !known.route.startsWith('/cc-agent/')) {
- openBotTarget(entry, sessionId, known, islandEntryId);
+ openBotTarget(entry, sessionId, known, islandEntryId, messageClientId);
return;
}
let movedToBotPage = false;
- deps.openOrdinary(sessionId, messageClientId, () => isLatest() && !movedToBotPage);
+ deps.openOrdinary(sessionId, messageClientId, () => isLatest() && !movedToBotPage && committedSinceOpen.size === 0);
if (known) return;
const ordinaryRoute = `/cc-agent/${encodeURIComponent(sessionId)}`;
void deps.resolveBotRoute(sessionId).then((target) => {
@@ -209,8 +216,8 @@ export function createSessionEntryNavigator(
if (path !== ordinaryRoute && path !== target.route) return;
}
movedToBotPage = true;
- openBotTarget(entry, sessionId, target, islandEntryId);
- });
+ openBotTarget(entry, sessionId, target, islandEntryId, messageClientId);
+ }).catch(() => undefined);
}
};
return Object.assign(open, {
diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.ts
index 1d918a1a22..38ca263f29 100644
--- a/apps/desktop/src/renderer/features/bots/botStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botStore.ts
@@ -18,6 +18,8 @@ import {
import { getBotLastReadAtMap, pruneBotReadState, seedMissingBotReadState } from './botReadState';
import type { BotAutonomySettingsView } from '../../../shared/botAutonomy';
import { registerLoadedBotProfilesReader } from './botSessionOwners';
+import { canonicalBotSession } from './botSessionOwners';
+export { canonicalBotSession } from './botSessionOwners';
import type { BotGender } from '../../../shared/botGender';
import { BOT_FAILURE_REASONS, type BotFailureReason } from '../../../shared/botFailureReason';
import type { BotCapabilityBaseline } from '../../../shared/botCapabilitySelection';
@@ -224,11 +226,6 @@ export interface BotProfile {
* Resolve canonical ownership from the projected bot_session_links registry.
* The top-level canonicalSessionId remains a migration/output mirror only.
*/
-export function canonicalBotSession(bot: BotProfile): BotSessionProjection | undefined {
- const matches = bot.sessions.filter((session) => session.role === 'canonical');
- return matches.length === 1 ? matches[0] : undefined;
-}
-
export function canonicalBotSessionId(bot: BotProfile): string | undefined {
return canonicalBotSession(bot)?.id;
}
diff --git a/apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts b/apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts
index 97aa1f7dd4..3d5d24b456 100644
--- a/apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts
+++ b/apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts
@@ -1,10 +1,10 @@
import { useEffect } from 'react';
import { isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';
-/** Called by the route's ownership gate, never by URL-only navigation. */
-export function useBotIslandVisibleSession(sessionId: string | null) {
+/** Report only the exact task after metadata and history load, never a URL-only landing. */
+export function useBotIslandVisibleSession(sessionId: string | null, enabled = true) {
useEffect(() => {
- if (!isAgentIslandSupported()) return;
+ if (!enabled || !isAgentIslandSupported()) return;
const sync = () => {
// Main accepts only a focused window or its pending notification target.
// A DOM focus check here can drop that ack before focus has settled.
@@ -16,5 +16,5 @@ export function useBotIslandVisibleSession(sessionId: string | null) {
window.removeEventListener('focus', sync);
void window.electronAPI.agentIsland?.setVisibleSession?.(null);
};
- }, [sessionId]);
+ }, [sessionId, enabled]);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 877dd8777c..c6b2f8887d 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -44,6 +44,7 @@ import {
import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import { CindyMakeSessionGate } from './CindyMakeSessionGate';
import { SessionRouteOriginGate } from './SessionRouteOriginGate';
+import { useBotIslandVisibleSession } from '@/features/bots/useBotIslandVisibleSession';
import { dbToMakerAgentKind, normalizeDbAgentKind } from '../../../shared/agentKindConversion';
import { useTranslation } from 'react-i18next';
import { buildSessionDeepLink } from '@/lib/deepLink';
@@ -1904,6 +1905,10 @@ function CCAgentSessionContent({
updateQueueItemContent,
chatDisplaySnapshot,
} = useCCAgentChat(sessionId, handleTitleUpdate, { chatRealtime });
+ useBotIslandVisibleSession(
+ viewVisible && session?.id === sessionId && historyLoaded ? sessionId ?? null : null,
+ ownsWindowRoute && !isCompactRail && !isOrcaMode,
+ );
const clearQueueComposerEditDraft = useCallback(
(edit: NonNullable<typeof queueComposerEdit>, files: readonly AttachedFile[]) => {
const originalIds = new Set(edit.originalAttachmentIds);
diff --git a/apps/desktop/src/renderer/features/cc-agent/CindyMakeSessionGate.tsx b/apps/desktop/src/renderer/features/cc-agent/CindyMakeSessionGate.tsx
index ecda2b7d55..49c7bf0930 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CindyMakeSessionGate.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CindyMakeSessionGate.tsx
@@ -4,6 +4,8 @@ import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { getSessionFor } from '@/lib/makerTransport';
import { sessionsStore } from '@/lib/sessionsStore';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { SessionEntryError, sessionEntryFailure } from './SessionEntryError';
/** Resolve old links before mounting a chat composer or file browser. */
export function CindyMakeSessionGate({ sessionId, children }: {
@@ -16,23 +18,36 @@ export function CindyMakeSessionGate({ sessionId, children }: {
const localSource = useSyncExternalStore(sessionsStore.subscribe, () =>
sessionId ? sessionsStore.findById(sessionId)?.source : undefined,
);
- const knownSource = remoteSource ?? localSource;
+ const knownSource = remoteSource !== undefined ? remoteSource : localSource;
const [loaded, setLoaded] = useState<{ id: string; source: string | null } | null>(null);
+ const [failure, setFailure] = useState<{ id: string; reason: ReturnType<typeof sessionEntryFailure> } | null>(null);
+ const [retry, setRetry] = useState(0);
useEffect(() => {
if (CINDY_MAKE_ENABLED || !sessionId || knownSource !== undefined) return;
let cancelled = false;
+ const owner = getDataOwnerGeneration();
+ setFailure(null);
void getSessionFor(sessionId).then(session => {
- if (!cancelled && session?.id === sessionId) {
+ if (cancelled || !isDataOwnerGenerationCurrent(owner)) return;
+ if (session?.id === sessionId) {
setLoaded({ id: session.id, source: session.source ?? null });
+ } else {
+ setFailure({ id: sessionId, reason: 'missing' });
}
- }).catch(() => undefined);
+ }).catch(error => {
+ if (!cancelled && isDataOwnerGenerationCurrent(owner)) setFailure({ id: sessionId, reason: sessionEntryFailure(error) });
+ });
return () => { cancelled = true; };
- }, [sessionId, knownSource]);
+ }, [sessionId, knownSource, retry]);
- const source = knownSource ?? (loaded && loaded.id === sessionId ? loaded.source : undefined);
+ const source = knownSource !== undefined ? knownSource : (loaded && loaded.id === sessionId ? loaded.source : undefined);
if (!CINDY_MAKE_ENABLED && isCindyMakeSource(source)) {
return <Navigate to="/cc-agent" replace />;
}
- if (!CINDY_MAKE_ENABLED && sessionId && source === undefined) return null;
+ if (!CINDY_MAKE_ENABLED && sessionId && source === undefined) {
+ return failure?.id === sessionId
+ ? <SessionEntryError reason={failure.reason} onRetry={() => setRetry(value => value + 1)} />
+ : null;
+ }
return children;
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionEntryError.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionEntryError.tsx
new file mode 100644
index 0000000000..04c7553588
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionEntryError.tsx
@@ -0,0 +1,31 @@
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import { Button } from '@/components/ui/button';
+import { extractIpcError } from '@/utils/ipcError';
+
+export function sessionEntryFailure(error: unknown): 'missing' | 'denied' | 'failed' {
+ const code = extractIpcError(error)?.code;
+ if (code === 'NOT_FOUND') return 'missing';
+ if (code === 'PERMISSION_DENIED' || code === 'DEVICE_LINK_ACCESS_REVOKED'
+ || code === 'DEVICE_LINK_REMOTE_DISABLED' || code === 'DEVICE_LINK_CONTROL_DISABLED'
+ || code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED') return 'denied';
+ return 'failed';
+}
+
+/** Keep the original address on failure; returning to the list is an explicit action. */
+export function SessionEntryError({ reason, onRetry }: {
+ reason: 'missing' | 'denied' | 'failed';
+ onRetry?: () => void;
+}) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ return <main className="flex h-full items-center justify-center bg-[var(--surface)] p-6">
+ <section role="alert" className="w-full max-w-md text-center">
+ <p className="text-14 leading-6 text-[var(--text-primary)]">{t(`ccAgent.sessionEntry.${reason}`)}</p>
+ <div className="mt-4 flex flex-wrap justify-center gap-2">
+ <Button variant="secondary" onClick={() => navigate('/cc-agent')}>{t('ccAgent.sessionEntry.back')}</Button>
+ {reason === 'failed' && onRetry ? <Button variant="secondary" onClick={onRetry}>{t('ccAgent.sessionEntry.retry')}</Button> : null}
+ </div>
+ </section>
+ </main>;
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionRouteOriginGate.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionRouteOriginGate.tsx
index b46cf55db3..850b1581a4 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionRouteOriginGate.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionRouteOriginGate.tsx
@@ -1,8 +1,9 @@
import { useEffect, useState, type ReactNode } from 'react';
-import { Navigate, useLocation, useParams } from 'react-router-dom';
+import { useLocation, useParams } from 'react-router-dom';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { getSessionFor } from '@/lib/makerTransport';
+import { SessionEntryError, sessionEntryFailure } from './SessionEntryError';
/** Restore a route's host before any nested metadata read or composer mounts. */
export function SessionRouteOriginGate({ sessionId, ownsWindowRoute, children }: {
@@ -16,7 +17,8 @@ export function SessionRouteOriginGate({ sessionId, ownsWindowRoute, children }:
const deviceId = ownsWindowRoute && sessionId === routeSessionId
? new URLSearchParams(search).get('device') : null;
const key = deviceId && sessionId ? JSON.stringify([sessionId, deviceId]) : null;
- const [registered, setRegistered] = useState<{ key: string; unavailable: boolean } | null>(null);
+ const [registered, setRegistered] = useState<{ key: string; failure?: ReturnType<typeof sessionEntryFailure> } | null>(null);
+ const [retry, setRetry] = useState(0);
useEffect(() => {
if (!key || !sessionId || !deviceId) return;
let disposed = false;
@@ -24,7 +26,7 @@ export function SessionRouteOriginGate({ sessionId, ownsWindowRoute, children }:
const valid = () => !disposed && isDataOwnerGenerationCurrent(owner);
const existing = remoteProjectsStore.getSessionDeviceId(sessionId);
if (existing && existing !== deviceId) {
- setRegistered({ key, unavailable: true });
+ setRegistered({ key, failure: 'denied' });
return;
}
// This is only a routing hint. The existing Main invoke boundary still
@@ -37,7 +39,7 @@ export function SessionRouteOriginGate({ sessionId, ownsWindowRoute, children }:
const current = remoteProjectsStore.captureSessionRead(deviceId, sessionId);
const value = await getSessionFor(sessionId);
if (!valid()) return;
- if (!value || value.id !== sessionId) throw new Error('Remote task not found');
+ if (!value || value.id !== sessionId) { setRegistered({ key, failure: 'missing' }); return; }
if (current()) {
remoteProjectsStore.mergeDeviceSessions(deviceId, remoteProjectsStore.getDeviceName(deviceId) ?? '',
[current.mergeActivity(value)]);
@@ -45,12 +47,12 @@ export function SessionRouteOriginGate({ sessionId, ownsWindowRoute, children }:
throw new Error('Remote task read invalidated');
}
}
- if (valid()) setRegistered({ key, unavailable: false });
- })().catch(() => { if (valid()) setRegistered({ key, unavailable: true }); });
+ if (valid()) setRegistered({ key });
+ })().catch(error => { if (valid()) setRegistered({ key, failure: sessionEntryFailure(error) }); });
return () => { disposed = true; };
- }, [key, sessionId, deviceId]);
+ }, [key, sessionId, deviceId, retry]);
if (key && registered?.key !== key) return null;
- if (key && registered?.unavailable) return <Navigate to="/cc-agent" replace />;
+ if (key && registered?.failure) return <SessionEntryError reason={registered.failure} onRetry={() => setRetry(value => value + 1)} />;
return children;
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionGate.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionGate.test.tsx
index 9982cd22ac..bdb2fcd005 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionGate.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CindyMakeSessionGate.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { act, cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, render, screen, fireEvent } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CindyMakeSessionGate } from '../CindyMakeSessionGate';
@@ -7,9 +7,11 @@ import { SessionRouteOriginGate } from '../SessionRouteOriginGate';
import { sideChatTaskRoute } from '../../right-sidebar/plugins/side-chat/state';
import { StrictMode } from 'react';
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
const state = vi.hoisted(() => ({
remote: [] as Array<{ id: string; source: string; model?: string; workingDir?: string }>,
- localSource: undefined as string | undefined,
+ localSource: undefined as string | null | undefined,
getSession: vi.fn(),
localListeners: new Set<() => void>(),
origins: new Map<string, string>(),
@@ -29,7 +31,7 @@ vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: {
state.localListeners.add(listener);
return () => { state.localListeners.delete(listener); };
},
- findById: () => state.localSource ? { source: state.localSource } : null,
+ findById: () => state.localSource !== undefined ? { source: state.localSource } : null,
} }));
vi.mock('@/lib/makerTransport', () => ({ getSessionFor: state.getSession }));
afterEach(cleanup);
@@ -41,6 +43,13 @@ beforeEach(() => {
state.readCurrent = true;
});
+it('opens a legacy cached task with null source instead of waiting forever', () => {
+ state.localSource = null;
+ render(<MemoryRouter><CindyMakeSessionGate sessionId="legacy"><div>Legacy task</div></CindyMakeSessionGate></MemoryRouter>);
+ expect(screen.getByText('Legacy task')).toBeTruthy();
+ expect(state.getSession).not.toHaveBeenCalled();
+});
+
// Unit #6529: the old hidden-task tests only covered warm origins. A route
// surviving a renderer reload must pin its host before the first metadata read,
// even when no mirror has persisted. Exercise the production gates and router.
@@ -83,6 +92,8 @@ describe('remote task route origin', () => {
return result;
});
await act(async () => { mountRoute(sideChatTaskRoute('child', 'host')); });
+ expect(screen.getByRole('alert')).toBeTruthy();
+ fireEvent.click(screen.getByText('ccAgent.sessionEntry.back'));
expect(screen.getByText('Task list')).toBeTruthy();
expect(screen.queryByText('Remote composer')).toBeNull();
});
@@ -112,7 +123,7 @@ describe('remote task route origin', () => {
it('rejects a conflicting route host without reading or changing its known owner', async () => {
state.origins.set('child', 'real-host');
await act(async () => { mountRoute(sideChatTaskRoute('child', 'wrong-host')); });
- expect(screen.getByText('Task list')).toBeTruthy();
+ expect(screen.getByText('ccAgent.sessionEntry.denied')).toBeTruthy();
expect(state.origins.get('child')).toBe('real-host');
expect(state.getSession).not.toHaveBeenCalled();
expect(screen.queryByText('Remote composer')).toBeNull();
@@ -177,6 +188,9 @@ describe('old Cindy Make links', () => {
await act(async () => { mount(<Composer />); });
expect(Composer).not.toHaveBeenCalled();
expect(screen.queryByText('Task list')).toBeNull();
+ expect(screen.getByRole('alert')).toBeTruthy();
+ fireEvent.click(screen.getByText('ccAgent.sessionEntry.back'));
+ expect(screen.getByText('Task list')).toBeTruthy();
});
it.each([undefined, null, 'desktop'])('opens matching ordinary metadata with source %s', async (source) => {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 946fbe7e8b..3c738a88a3 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -12676,6 +12676,7 @@
}
},
"ccAgent": {
+ "sessionEntry": {"missing":"This session could not be found. It may have been deleted.","denied":"This account or computer cannot access this session.","failed":"Could not load this session.","back":"Back to Sessions","retry":"Reload Session"},
"contextWindowBudget": {
"menuTitle": "Task context window",
"triggerLabel": "Task context window, currently {{window}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 4f6beedfe0..16e46c6a5f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -12622,6 +12622,7 @@
}
},
"ccAgent": {
+ "sessionEntry": {"missing":"このセッションが見つかりません。削除された可能性があります。","denied":"このアカウントまたはコンピューターでは、このセッションにアクセスできません。","failed":"このセッションを読み込めませんでした。","back":"セッション一覧に戻る","retry":"セッションを再読み込み"},
"contextWindowBudget": {
"menuTitle": "このタスクのコンテキストウィンドウ",
"triggerLabel": "タスクのコンテキストウィンドウ、現在 {{window}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index df8840ac90..7a3da69507 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -12622,6 +12622,7 @@
}
},
"ccAgent": {
+ "sessionEntry": {"missing":"이 세션을 찾을 수 없습니다. 삭제되었을 수 있습니다.","denied":"현재 계정 또는 컴퓨터에서 이 세션에 접근할 수 없습니다.","failed":"이 세션을 불러오지 못했습니다.","back":"세션 목록으로 돌아가기","retry":"세션 다시 불러오기"},
"contextWindowBudget": {
"menuTitle": "이 작업의 컨텍스트 창",
"triggerLabel": "작업 컨텍스트 창, 현재 {{window}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 527c8e1ccc..cd9abe6c41 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -12622,6 +12622,7 @@
}
},
"ccAgent": {
+ "sessionEntry": {"missing":"找不到这条任务,它可能已被删除。","denied":"当前账号或电脑无法访问这条任务。","failed":"未能加载这条任务。","back":"返回任务列表","retry":"重新加载任务"},
"contextWindowBudget": {
"menuTitle": "任务上下文窗口",
"triggerLabel": "任务上下文窗口,当前 {{window}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 9a36a0369a..88743b15b0 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -12622,6 +12622,7 @@
}
},
"ccAgent": {
+ "sessionEntry": {"missing":"找不到這條任務,它可能已被刪除。","denied":"目前帳號或電腦無法存取這條任務。","failed":"未能載入這條任務。","back":"返回任務列表","retry":"重新載入任務"},
"contextWindowBudget": {
"menuTitle": "任務上下文視窗",
"triggerLabel": "任務上下文視窗,目前 {{window}}",
diff --git a/apps/desktop/src/renderer/lib/agentIslandVisibleSessionRoute.ts b/apps/desktop/src/renderer/lib/agentIslandVisibleSessionRoute.ts
index 4fe8652f43..17d790a028 100644
--- a/apps/desktop/src/renderer/lib/agentIslandVisibleSessionRoute.ts
+++ b/apps/desktop/src/renderer/lib/agentIslandVisibleSessionRoute.ts
@@ -22,9 +22,11 @@ export function resolveAgentIslandVisibleSessionIdFromPath(
export function isAgentIslandVisibleSessionOwnedByBotRoute(pathname: string): boolean {
const sessionMatch = matchPath('/bots/:botId/session/:sessionId', pathname) ??
- matchPath('/bots/:botId/history/:sessionId', pathname);
+ matchPath('/bots/:botId/history/:sessionId', pathname) ??
+ matchPath('/bots/remote/:deviceId/:botId/session/:sessionId', pathname) ??
+ matchPath('/bots/remote/:deviceId/:botId', pathname);
// The matching view must validate ownership before reporting a visible session.
- return Boolean(sessionMatch?.params.sessionId);
+ return Boolean(sessionMatch);
}
export function resolveAgentIslandVisibleSessionsFromPath(
@@ -39,23 +41,6 @@ export function resolveAgentIslandVisibleSessionsFromPath(
return sessionId;
}
-/**
- * 通知/deep link 的目标路由还没渲染时,直接从完整 route target 解析首个可见
- * session payload。Orca worker query 表示 Lead 与 Worker 会同时可见。
- */
-export function resolveAgentIslandVisibleSessionFromRouteTarget(
- target: string,
-): string | string[] | null {
- const url = new URL(target, 'https://xdt-maker.invalid');
- const leadSessionId = resolveAgentIslandVisibleSessionIdFromPath(url.pathname);
- if (!leadSessionId) return null;
- const workerSessionId = url.searchParams.get('worker')?.trim();
- if (!workerSessionId || workerSessionId === 'new' || workerSessionId === leadSessionId) {
- return leadSessionId;
- }
- return [leadSessionId, workerSessionId];
-}
-
export function resolveAgentIslandVisibleSessionIdForWorkdirBrowseRail({
sessionId,
railCollapsed,
diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsx
index 8efc2f14f9..9b7757f56c 100644
--- a/apps/desktop/src/renderer/router.tsx
+++ b/apps/desktop/src/renderer/router.tsx
@@ -132,6 +132,7 @@ export const router = createHashRouter([
// :botId 之前,/bots/groups/<id> 不会被当成一个叫 "groups" 的伙伴。
{ path: 'groups/:groupId', element: <BotGroupChatView /> },
{ path: 'remote/:deviceId/:botId', element: <RemoteBotSessionView /> },
+ { path: 'remote/:deviceId/:botId/session/:sessionId', element: <RemoteBotSessionView /> },
{ path: 'remote/:deviceId/:botId/history/:sessionId', element: <BotHistorySessionView /> },
// 伙伴私聊只从双方时间线里的消息入口打开,不出现在左侧伙伴列表。
{ path: ':botId/direct/:threadId', element: <BotDirectMessageView /> },
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 9748180a32..467002bece 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -266,9 +266,8 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭
侧边栏全文搜索覆盖普通任务及伙伴个人主聊天、历史线程,本机还包含伙伴消息平台的渠道专线,默认包含归档历史。
搜索结果带伙伴姓名,点击后保持命中的线程与消息位置;不依赖伙伴在侧栏是否展开或已加载。
-历史线程以伙伴身份只读打开,不切回当前主任务、不取消归档、不恢复发送队列。
-伙伴群聊内部专线不进入搜索;本机渠道专线的搜索结果沿用历史只读详情与消息定位,仍不进入普通任务列表,
-不因搜索恢复或归档任务。远程搜索继续排除渠道专线;伙伴委派的普通后台任务保持普通任务入口。
+历史线程和本机渠道专线打开原 ID 的普通任务页面,沿用该任务的权限、消息定位与归档状态;不切回当前主任务,
+不因打开页面恢复发送队列。伙伴群聊内部专线不进入搜索;渠道专线仍不进入普通任务列表,不因搜索恢复或归档任务。远程搜索继续排除渠道专线;伙伴委派的普通后台任务保持普通任务入口。
手机首页、设备页与任务抽屉采用同一结果归属与消息定位。远程仍遵守既有伙伴可见性:
整体隐藏或归档的伙伴只在所属电脑本地恢复,不能因新增搜索入口扩大远程权限。
实现见 `localDb/conversationSearch.ts`、`ConversationSearchBox.tsx` 与 Mobile
@@ -784,16 +783,16 @@ Session 任务遵守同一套机制与呈现契约:
- 自主跟进(6.3):内置「跟进」例行任务那一轮的回复不自动外发(`silentWhenIdle`),伙伴要主人知道的事显式调用本轮
通知,沿用例行任务的结果通知通道与开关。已纳入观察范围、但没人跟(跟进者暂停、跟进规则被暂停)的本机任务「等你」满 5 分钟时,
宿主直接发一次系统提醒(桌面 `needs-reply` + 手机推送,事件 id 去重;主窗口在前台不弹桌面通知),不经模型。
-- 点击伙伴任务的通知必须回到伙伴自己的主任务或历史任务路由,不能把隐藏的 `source=bot`
- Session 丢进普通任务列表。群专线回到它所在的群,历史任务进只读历史路由;委派执行进入普通
- 任务页,保留消息定位与页面自己的报错横幅。群专线没有可处置该任务报错的横幅,灵动岛点击的目标
- 地址提交后即处置被点的那张卡;只读历史要等历史页自己的归属校验通过、真正显示出这段历史后才处置。
- 只认最近一次点击时的那张卡:被新点击取代(含同一任务再点一次)、导航被重定向或改去别处(含历史
- 页校验不通过被重定向走)、点击后又开始新一轮、出现新的失败或完成,或只是直接打开地址,都不处置,
- 新的提醒照常出现。处置只清提醒,任务记录、失败状态与错误行不变。主任务仍只由报错横幅处置。
-- 通知、灵动岛与任务深链点击立即按内存里的伙伴投影跳转,不等待重读伙伴列表。投影还不认识的任务先
- 打开普通任务页,同时在后台重读一次投影;若它其实是伙伴的主任务、历史或群专线,再转到对应页面——
- 前提是用户这期间没有去过别处(离开后又回来也算)。新挂上的伙伴任务因此可能先短暂显示普通任务页,换来普通任务点击即达。
+- 通知、灵动岛、搜索和旧链接均保留原任务 ID、原电脑与已有消息锚点。只有唯一 `role=canonical` 链接
+ 对应的任务使用伙伴主任务页面;`kind=chat` 本身不是主任务判据。伙伴路由也携带具体任务 ID,不能因缓存
+ 过期而切到后来创建的主任务。历史、渠道、群专线与委派执行沿用普通任务页面及其权限、报错与历史加载。
+- 旧 `/bots/:botId/session/:sessionId` 或 history 地址发现伙伴不存在、链接已过期或不再是主任务时,继续
+ 打开原任务的普通页面;路由不授予权限,仍经本机或指定远程电脑的访问检查。真实任务不存在或访问被拒绝
+ 时保留原地址,明确提示原因并提供任务列表出口;普通读取失败可以重试,不重建任务或上下文。
+- 已读与灵动岛可见回执等原任务数据和消息实际加载后再处理,不能因 URL 已提交或进入错误页提前清提醒。
+ 系统通知点击复用主窗口深链队列,窗口重载时也保留任务、电脑和回复锚点;账号切换后旧通知点击失效。
+- 点击先使用现有伙伴投影;尚未认识的任务先开普通页面,并后台重读投影,仅发现它是主任务时校正页面。
+ 新点击、切换账号或用户已去别处都会取消较早的异步跳转,不能把用户拉回去。
- macOS 灵动岛把伙伴的主任务、历史任务、群专线与渠道任务显示为伙伴本人:名字与头像代替任务标题和
Agent 标识,群专线在名字后附群名,不显示伙伴工作目录;回复完成时以消息样式呈现(头像跨两行、
不标「完成」),运行中、待处理、报错与未读回复由头像上的光环和角标表示。委派执行仍是普通任务。