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): fence pending notifications and retain worker entry state

Chris62e206052013
diff --git a/apps/desktop/src/main/__tests__/deepLink.test.ts b/apps/desktop/src/main/__tests__/deepLink.test.ts
index d2bc2bc4de..2e6d9d32ff 100644
--- a/apps/desktop/src/main/__tests__/deepLink.test.ts
+++ b/apps/desktop/src/main/__tests__/deepLink.test.ts
@@ -20,6 +20,11 @@ vi.mock('electron', () => ({
// logger 依赖 electron-log + app path, 在测试里要么 mock 要么吞日志。给个 noop logger。
const logs = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }));
vi.mock('../logger', () => ({ createLogger: () => logs }));
+const owner = vi.hoisted(() => ({ generation: 1 }));
+vi.mock('../device-link/broadcast-tap', () => ({
+ captureDataOwnerBroadcastScope: () => ({ ownerScopeKey: String(owner.generation) }),
+ isDataOwnerBroadcastScopeCurrent: (scope: { ownerScopeKey?: string }) => scope.ownerScopeKey === String(owner.generation),
+}));
import { vi } from 'vitest';
import {
@@ -431,6 +436,18 @@ describe('dual scheme (cindy primary + legacy xdt-maker)', () => {
expect(takePendingDeepLink()).toBeNull();
});
+ // Notification clicks can be buffered during reload, then pulled after another
+ // account logs in. The public main-window entry must reject that stale intent.
+ it('drops an old owner notification from the pending queue without dropping later external links', () => {
+ setDeepLinkMainWindow(null);
+ openMainWindowSession('account-a-task', { deviceId: 'studio', messageClientId: 'reply' });
+ owner.generation += 1;
+ expect(takePendingDeepLink()).toBeNull();
+ handleIncomingDeepLink('cindy://session/external-task', 'open-url');
+ owner.generation += 1;
+ expect(takePendingDeepLink()).toEqual({ type: 'session', id: 'external-task' });
+ });
+
it('buffers only the opaque provider import id during cold start', () => {
setDeepLinkMainWindow(null);
handleIncomingDeepLink(providerImportUrl('cindy'), 'test');
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 e0a5c189e7..c825a2c52c 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -168,6 +168,8 @@ vi.mock('../layoutPreferenceStore.js', () => ({
}));
vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({ ownerStamp: { dataOwnerId: 'test-owner', ownerGeneration: 1 } }),
+ isDataOwnerBroadcastScopeCurrent: () => true,
getSafeDataOwnerPushStamp: vi.fn(() => undefined),
tapWindowBroadcast: mocks.tapWindowBroadcast,
}));
diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.ts
index a62db49aa7..7afce996de 100644
--- a/apps/desktop/src/main/deepLink.ts
+++ b/apps/desktop/src/main/deepLink.ts
@@ -54,6 +54,7 @@ import {
matchDeepLinkPrefix,
} from '../shared/deepLinkSchemes';
import { cancelProviderImport, createProviderImportDraftFromRest } from './provider-import/providerImport';
+import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent, type DataOwnerBroadcastScope } from './device-link/broadcast-tap';
const log = createLogger('deepLink');
@@ -301,6 +302,9 @@ export function buildFocusDeepLink(source: string): string {
// - mainWindow 已存在 + MainLayout 必然已 mount (用户已登录),dispatchDeepLink
// 直接 webContents.send,不进 pending
let pendingDeepLink: DeepLinkPayload | null = null;
+// Internal notification ownership stays in Main; external URLs keep their
+// existing ability to survive login without binding to the signed-out owner.
+let pendingDeepLinkOwner: DataOwnerBroadcastScope | undefined;
// Invitation targets must survive unrelated navigation and login focus callbacks.
const pendingChatInvitations: Array<Extract<DeepLinkPayload, { type: 'chat-invite' | 'chat-invite-malformed' }>> = [];
let mainWindowRef: BrowserWindow | null = null;
@@ -443,6 +447,7 @@ export function openMainWindowSession(
...(options?.messageClientId ? { messageClientId: options.messageClientId } : {}),
},
options?.focus !== false,
+ captureDataOwnerBroadcastScope(),
);
}
@@ -472,7 +477,7 @@ function safeDeepLinkLog(payload: DeepLinkPayload) {
return payload.type === 'chat-invite' || payload.type === 'shared-task-join' || payload.type === 'provider-share-join' ? { type: payload.type } : payload;
}
-function dispatchDeepLink(payload: DeepLinkPayload, shouldFocus = true): void {
+function dispatchDeepLink(payload: DeepLinkPayload, shouldFocus = true, owner?: DataOwnerBroadcastScope): void {
// 纯前台意图:main 进程内消化。冷启动时窗口还没建,app 启动流程本身会前台,直接丢弃。
if (payload.type === 'focus') {
if (shouldFocus) focusMainWindow();
@@ -506,6 +511,7 @@ function dispatchDeepLink(payload: DeepLinkPayload, shouldFocus = true): void {
});
}
pendingDeepLink = payload;
+ pendingDeepLinkOwner = owner;
log.debug('buffered pending deep link until renderer pull', safeDeepLinkLog(payload));
// Agent-key first tap may switch in the background. A buffered deep link
// from that path must not steal the frontmost app.
@@ -545,7 +551,10 @@ export function takePendingDeepLink(): DeepLinkPayload | null {
if (invitation) return invitation;
if (!pendingDeepLink) return null;
const payload = pendingDeepLink;
+ const owner = pendingDeepLinkOwner;
pendingDeepLink = null;
+ pendingDeepLinkOwner = undefined;
+ if (owner && !isDataOwnerBroadcastScopeCurrent(owner)) return null;
log.info('renderer pulled pending deep link', safeDeepLinkLog(payload));
return payload;
}
diff --git a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
index 0eab204b55..f6773831cf 100644
--- a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
@@ -6,6 +6,7 @@ import {
getSessionRouteOwnerId,
isOrcaLeadSession,
isOrcaWorkerSession,
+ orcaWorkerSessionRoute,
resolveSessionRoute,
} from '@/lib/orcaSessionIdentity';
import { registerLoadedBotProfilesReader } from '@/features/bots/botSessionOwners';
@@ -80,6 +81,16 @@ describe('orcaSessionIdentity', () => {
expect(getSessionRouteOwnerId('/cc-agent')).toBeNull();
});
+ // A notification may reach the Worker before its Lead's device origin is
+ // cached. The redirect must carry the device into the Lead origin gate.
+ it('retains the original device and query when a Worker entry redirects to its Lead', () => {
+ const target = new URL(orcaWorkerSessionRoute('lead/1', 'worker/1', '?device=studio&worker=stale&source=notification'), 'https://cindy.invalid');
+ expect(target.pathname).toBe('/cc-agent/lead%2F1');
+ expect(target.searchParams.get('device')).toBe('studio');
+ expect(target.searchParams.get('worker')).toBe('worker/1');
+ expect(target.searchParams.get('source')).toBe('notification');
+ });
+
it('resolves canonical routes from a known session row', async () => {
const api = electronApiMock();
api.localDb.orcaWorkflows.getByWorkerSession.mockResolvedValue({
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 0d1bb3d01e..492afbeead 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -556,10 +556,8 @@ export function MainLayout() {
currentPathRef.current = `${location.pathname}${location.search}`;
const navigateToOrdinarySession = useCallback(
(sessionId: string, messageClientId?: string, isLatest: () => boolean = () => true, deviceId?: string) => {
- // device-link 远程会话本地无 row:resolveSessionRoute 内部的 sessionService.get
- // 会 miss → 远程 Orca lead/worker 被当普通会话路由,CCAgentSessionView 再
- // redirect 到 orca 路由时会丢 searchJump 锚点。传入远程镜像的 session 对象,
- // 让 Orca 路由一步到位(Codex review P2,与 SessionLinkChip 同款处理)。
+ // 已知镜像可提前解析 Orca 角色;明确指定电脑时,先由任务入口恢复并校验
+ // 来源,避免读到本机同 ID。Worker 后续转到 Lead 时保留 device 和 searchJump。
const remoteSession =
remoteProjectsStore.getVisibleMergedRemoteSessions().find((s) =>
s.id === sessionId && (!deviceId || s.deviceLinkDeviceId === deviceId)) ?? null;
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index c6b2f8887d..03e228f3cf 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -282,6 +282,7 @@ import {
getSessionRouteOwnerId,
isOrcaLeadSession,
isOrcaWorkerSession,
+ orcaWorkerSessionRoute,
resolveSessionRoute,
} from '@/lib/orcaSessionIdentity';
import type { Effort, PermissionMode } from '@/lib/userPreferences.types';
@@ -1420,9 +1421,15 @@ function CCAgentSessionContent({
}, [session?.status, sessionId, navigate, ownsWindowRoute]);
const vendorAuthGate = useVendorAuthGate();
const { confirmWithCheckbox } = useConfirmDialog();
+ const [workerRouteChecked, setWorkerRouteChecked] = useState<string | null>(null);
useEffect(() => {
if (!sessionId || !searchJump) return;
+ if (ownsWindowRoute && !session) return;
+ // The route owner hands Worker jumps to the Lead sidebar. Do not consume
+ // the anchor in this temporary view while its workflow read is in flight.
+ if (ownsWindowRoute && !isOrcaMode && !isCompactRail && session
+ && isOrcaWorkerSession(session) && workerRouteChecked !== location.key) return;
if (searchJump.sessionId !== sessionId) {
if (!session) return;
// 仅路由主权实例回收「跳转目标 ≠ 当前会话」的陈旧状态:分屏的嵌入 pane
@@ -1491,12 +1498,15 @@ function CCAgentSessionContent({
clearSearchJumpState,
isOrcaLeadSessionView,
isOrcaMode,
+ isCompactRail,
+ location.key,
ownsWindowRoute,
requestFocusMessage,
searchJump,
session,
sessionId,
t,
+ workerRouteChecked,
]);
// 后台任务面板行点击 → 聊天流定位对应任务卡:sessionId 匹配当前会话才消费;
@@ -1542,15 +1552,21 @@ function CCAgentSessionContent({
void orcaWorkflowsFor(session.id)
.getByWorkerSession(session.id)
.then((workflow) => {
- if (!cancelled && workflow) {
- navigate(`/cc-agent/${workflow.leadSessionId}?worker=${sessionId}`, { replace: true });
+ if (cancelled) return;
+ if (workflow) {
+ navigate(orcaWorkerSessionRoute(workflow.leadSessionId, sessionId, location.search), {
+ replace: true,
+ state: location.state,
+ });
+ } else {
+ setWorkerRouteChecked(location.key);
}
})
- .catch(() => undefined);
+ .catch(() => { if (!cancelled) setWorkerRouteChecked(location.key); });
return () => {
cancelled = true;
};
- }, [isOrcaMode, isCompactRail, navigate, ownsWindowRoute, session, sessionId]);
+ }, [isOrcaMode, isCompactRail, location.key, location.search, location.state, navigate, ownsWindowRoute, session, sessionId]);
// F2: controlled folder picker open state
const [folderPickerOpen, setFolderPickerOpen] = useState(false);
diff --git a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts b/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts
index fbbb4e11c4..9a7871f3ea 100644
--- a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts
+++ b/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts
@@ -32,6 +32,13 @@ export function getSessionRouteOwnerId(route: string): string | null {
}
}
+/** Keep the owning device when a Worker entry moves into its Lead's sidebar. */
+export function orcaWorkerSessionRoute(leadSessionId: string, workerSessionId: string, search = ''): string {
+ const params = new URLSearchParams(search);
+ params.set('worker', workerSessionId);
+ return `/cc-agent/${encodeURIComponent(leadSessionId)}?${params}`;
+}
+
/**
* 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
@@ -67,7 +74,7 @@ export async function resolveSessionRoute(
const workflow = await orcaWorkflowsFor(sessionId)
.getByWorkerSession(sessionId)
.catch(() => null);
- return workflow ? `/cc-agent/${workflow.leadSessionId}?worker=${sessionId}` : '/cc-agent';
+ return workflow ? orcaWorkerSessionRoute(workflow.leadSessionId, sessionId) : '/cc-agent';
}
// Notifications, task cards and the main sidebar agree on one page per task.
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 467002bece..c1725bc873 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -790,7 +790,8 @@ Session 任务遵守同一套机制与呈现契约:
打开原任务的普通页面;路由不授予权限,仍经本机或指定远程电脑的访问检查。真实任务不存在或访问被拒绝
时保留原地址,明确提示原因并提供任务列表出口;普通读取失败可以重试,不重建任务或上下文。
- 已读与灵动岛可见回执等原任务数据和消息实际加载后再处理,不能因 URL 已提交或进入错误页提前清提醒。
- 系统通知点击复用主窗口深链队列,窗口重载时也保留任务、电脑和回复锚点;账号切换后旧通知点击失效。
+ 系统通知点击复用主窗口深链队列,窗口重载时也保留任务、电脑和回复锚点;账号切换后旧通知点击失效,
+ 已排队但尚未交付的通知也在取出时复核原账号代次并丢弃过期项。
- 点击先使用现有伙伴投影;尚未认识的任务先开普通页面,并后台重读投影,仅发现它是主任务时校正页面。
新点击、切换账号或用户已去别处都会取消较早的异步跳转,不能把用户拉回去。
- macOS 灵动岛把伙伴的主任务、历史任务、群专线与渠道任务显示为伙伴本人:名字与头像代替任务标题和