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。

feat(desktop): CC Agent 任务视图支持递归分屏拖拽布局 (#1632)

Kris wangea3ea36c13d5
diff --git a/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts b/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts
index 8c6b0992e7..56c2f14e6b 100644
--- a/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/AgentTaskCard.test.ts
@@ -50,13 +50,17 @@ import { AgentTaskCard } from '@/components/chat/AgentTaskCard';
import { SessionNavigationModeProvider } from '@/features/cc-agent/embeddedSessionNavigation';
/**
- * 面板入口的 affordance 判据是「本会话的右栏 bucket 此刻可见」,由路由主实例经
- * SessionNavigationModeProvider 声明(见 useSidebarPanelReachable)。默认 fail
- * closed:没声明 = 打不开 = 不给假入口,所以断言面板入口的用例要显式声明宿主。
+ * 面板入口的 affordance 判据是「本会话的右栏 bucket 通过当前交互可达」,由路由
+ * 主实例或可见 split pane 经 SessionNavigationModeProvider 声明(见
+ * useSidebarPanelReachable)。默认 fail closed:没声明 = 打不开 = 不给假入口。
*/
-const withPanelHost = (hostSessionId: string, element: React.ReactElement) =>
+const withPanelHost = (
+ hostSessionId: string,
+ element: React.ReactElement,
+ mode: 'route-owner' | 'split-pane' = 'route-owner',
+) =>
React.createElement(SessionNavigationModeProvider, {
- mode: 'route-owner' as const,
+ mode,
sidebarPanelHostSessionId: hostSessionId,
children: element,
});
@@ -275,6 +279,36 @@ describe('AgentTaskCard', () => {
expect(openBackgroundTasksTabMock).toHaveBeenCalledWith('session-1', { focusTaskId: 'wf-1' });
});
+ it('opens the background tasks panel on the first click from a split pane', () => {
+ openBackgroundTasksTabMock.mockClear();
+ const { container } = render(
+ withPanelHost(
+ 'session-b',
+ React.createElement(AgentTaskCard, {
+ sessionId: 'session-b',
+ update: {
+ provider: 'claude-code',
+ taskId: 'wf-split',
+ status: 'running',
+ taskType: 'local_workflow',
+ workflowName: 'Split workflow',
+ },
+ }),
+ 'split-pane',
+ ),
+ );
+
+ const btn = headerButton(container);
+ expect(btn).not.toBeNull();
+ expect(btn!.hasAttribute('aria-expanded')).toBe(false);
+ act(() => {
+ btn!.click();
+ });
+ expect(openBackgroundTasksTabMock).toHaveBeenCalledWith('session-b', {
+ focusTaskId: 'wf-split',
+ });
+ });
+
it('falls back to the expand toggle when sessionId or taskId is missing on a workflow card', () => {
// 历史重载 workflow 卡(无 live taskId / sessionId):面板侧无该任务数据,
// 入口模式退回传统展开交互,description/summary 仍就地可读,不做假入口。
diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
index cebd5b820d..4f0c115087 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
@@ -64,7 +64,7 @@ describe('ChatInput session switch focus contract', () => {
it('enables storageKey refocus for routed session and new-draft views', () => {
expect(sessionViewSource).toContain(
- 'const ownsRoute = !sessionIdProp && !isCompactRail && !isOrcaMode;',
+ 'const ownsRoute = routeOwner ?? (!sessionIdProp && !isCompactRail && !isOrcaMode);',
);
expect(sessionViewSource).toContain('focusOnStorageKeyChange={ownsRoute}');
expect(newMakerDraftRouteSource).toContain('focusOnStorageKeyChange');
diff --git a/apps/desktop/src/renderer/__tests__/errorBannerGatewayQuota.test.tsx b/apps/desktop/src/renderer/__tests__/errorBannerGatewayQuota.test.tsx
index 8739462839..c3a60d2bda 100644
--- a/apps/desktop/src/renderer/__tests__/errorBannerGatewayQuota.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/errorBannerGatewayQuota.test.tsx
@@ -64,7 +64,9 @@ describe('ErrorBanner — Cindy AI 余额不足导流', () => {
expect(screen.getByText('chat.errorBanner.gatewayQuotaExhausted')).toBeTruthy();
expect(screen.queryByText(QUOTA_ERROR)).toBeNull();
- fireEvent.click(screen.getByTitle('chat.errorBanner.viewBalanceTitle'));
+ const viewBalanceButton = screen.getByTitle('chat.errorBanner.viewBalanceTitle');
+ expect(viewBalanceButton.getAttribute('data-split-pane-route-action')).toBe('');
+ fireEvent.click(viewBalanceButton);
expect(onViewBalance).toHaveBeenCalledOnce();
});
diff --git a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
index 58f12e0288..5fdb1986f0 100644
--- a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
formatOrcaLeadTitle,
formatOrcaWorkerTitle,
+ getSessionRouteOwnerId,
isOrcaLeadSession,
isOrcaWorkerSession,
resolveSessionRoute,
@@ -33,16 +34,18 @@ describe('orcaSessionIdentity', () => {
});
function electronApiMock() {
- return (globalThis as unknown as {
- window: {
- electronAPI: {
- localDb: {
- sessions: { get: ReturnType<typeof vi.fn> };
- orcaWorkflows: { getByWorkerSession: ReturnType<typeof vi.fn> };
+ return (
+ globalThis as unknown as {
+ window: {
+ electronAPI: {
+ localDb: {
+ sessions: { get: ReturnType<typeof vi.fn> };
+ orcaWorkflows: { getByWorkerSession: ReturnType<typeof vi.fn> };
+ };
};
};
- };
- }).window.electronAPI;
+ }
+ ).window.electronAPI;
}
it('detects durable Orca identity from session role', () => {
@@ -62,18 +65,27 @@ describe('orcaSessionIdentity', () => {
expect(formatOrcaWorkerTitle('Implement task')).toBe('Orca Worker: Implement task');
});
+ it('extracts the canonical owner from a resolved session route', () => {
+ expect(getSessionRouteOwnerId('/cc-agent/lead-1?worker=worker-1')).toBe('lead-1');
+ expect(getSessionRouteOwnerId('/cc-agent/session%20one#message')).toBe('session one');
+ expect(getSessionRouteOwnerId('/cc-agent')).toBeNull();
+ });
+
it('resolves canonical routes from a known session row', async () => {
const api = electronApiMock();
api.localDb.orcaWorkflows.getByWorkerSession.mockResolvedValue({
leadSessionId: 'lead-1',
});
- await expect(resolveSessionRoute('lead-1', { orcaRole: 'lead' }))
- .resolves.toBe('/cc-agent/lead-1');
- await expect(resolveSessionRoute('worker-1', { orcaRole: 'worker' }))
- .resolves.toBe('/cc-agent/lead-1?worker=worker-1');
- await expect(resolveSessionRoute('plain-1', { orcaRole: null }))
- .resolves.toBe('/cc-agent/plain-1');
+ await expect(resolveSessionRoute('lead-1', { orcaRole: 'lead' })).resolves.toBe(
+ '/cc-agent/lead-1',
+ );
+ await expect(resolveSessionRoute('worker-1', { orcaRole: 'worker' })).resolves.toBe(
+ '/cc-agent/lead-1?worker=worker-1',
+ );
+ await expect(resolveSessionRoute('plain-1', { orcaRole: null })).resolves.toBe(
+ '/cc-agent/plain-1',
+ );
expect(api.localDb.orcaWorkflows.getByWorkerSession).toHaveBeenCalledWith('worker-1');
});
@@ -91,7 +103,8 @@ describe('orcaSessionIdentity', () => {
const api = electronApiMock();
api.localDb.orcaWorkflows.getByWorkerSession.mockResolvedValue(null);
- await expect(resolveSessionRoute('worker-2', { orcaRole: 'worker' }))
- .resolves.toBe('/cc-agent');
+ await expect(resolveSessionRoute('worker-2', { orcaRole: 'worker' })).resolves.toBe(
+ '/cc-agent',
+ );
});
});
diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
index 58e00a0892..b6fd0416e5 100644
--- a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
@@ -294,12 +294,12 @@ describe('OrcaWorkflowRoute source invariants', () => {
it('keeps Orca search jump state available for the target pane', () => {
expect(sessionViewSource).toContain('if (!sessionId || !searchJump) return;');
expect(sessionViewSource).toContain(`if (searchJump.sessionId !== sessionId) {
- if (!session) return;
- if (!isOrcaMode && !isOrcaLeadSessionView) {
+ if (!session) return;`);
+ // 陈旧跳转只由路由主权实例回收:Orca 视图与分屏嵌入 pane 都不得取消
+ // owner 正在消费的跳转。
+ expect(sessionViewSource).toContain(`if (!isOrcaMode && !isOrcaLeadSessionView && ownsWindowRoute) {
clearSearchJumpState();
- }
- return;
- }`);
+ }`);
expect(sessionViewSource).toContain('...(workerSearchJump ? { searchJump: workerSearchJump } : {})');
expect(sessionViewSource).toContain('...(workerSearchJump ? { searchJump: undefined } : {})');
expect(workerPanelSource).toContain('searchJumpProp={searchJump}');
@@ -312,6 +312,9 @@ describe('OrcaWorkflowRoute source invariants', () => {
expect(sessionViewSource).toContain('const hasWorkerSearchJump = Boolean(');
expect(sessionViewSource).toContain('routeWorkerHint.hasWorkerParam || !!orcaWorkersReveal || hasWorkerSearchJump');
expect(sessionViewSource).toContain('const shouldRevealWorkersTab = hasExplicitOrcaWorkersReveal || shouldPassiveRevealWorkersTab;');
+ expect(sessionViewSource).toContain(
+ 'if (!ownsRoute || !collabEnabled || isCompactRail || !sessionId) return;',
+ );
expect(sessionViewSource).toContain('orcaWorkersReveal?.focusWorkerSessionId ??');
expect(sessionViewSource).toMatch(
/hasWorkerSearchJump\s*\?\s*\(?searchJump\?\.sessionId\s*\?\?\s*null\)?\s*:\s*null/,
@@ -405,8 +408,16 @@ describe('OrcaWorkflowRoute source invariants', () => {
expect(sessionViewSource).toContain('sidebarTargetSessionId={sidebarTargetSessionId}');
expect(sessionViewSource).toContain("const ownsWindowRoute = navigationMode === 'route-owner';");
expect(sessionViewSource).toContain('ownsWindowRoute && handoffFrom');
- expect(sessionViewSource).toContain('ownsWindowRoute && session?.parentSessionId');
- expect(sessionViewSource).toContain('onForkStripEncrypted={ownsWindowRoute ? handleForkStripEncrypted : undefined}');
+ expect(sessionViewSource).toContain('canNavigateSession && session?.parentSessionId');
+ expect(sessionViewSource).toContain(
+ "const canNavigateSession = ownsWindowRoute || navigationMode === 'split-pane';",
+ );
+ expect(sessionViewSource).toMatch(
+ /sidebarPanelHostSessionId=\{\s*ownsRoute \|\| navigationMode === 'split-pane' \? sessionId : undefined\s*\}/,
+ );
+ expect(sessionViewSource).toContain(
+ 'onForkStripEncrypted={canNavigateSession ? handleForkStripEncrypted : undefined}',
+ );
});
it('waits for detached bootstrap before mounting or writing the embedded right sidebar', () => {
@@ -427,7 +438,9 @@ describe('OrcaWorkflowRoute source invariants', () => {
});
it('shows the Lead identity bar only in the plain Orca Lead route', () => {
- expect(sessionViewSource).toContain('const ownsRoute = !sessionIdProp && !isCompactRail && !isOrcaMode;');
+ expect(sessionViewSource).toContain(
+ 'const ownsRoute = routeOwner ?? (!sessionIdProp && !isCompactRail && !isOrcaMode);',
+ );
expect(sessionViewSource).toContain('const collabEnabled = isOrcaLeadSessionView;');
expect(sessionViewSource).toContain('const showOrcaLeadIdentityBar = ownsRoute && collabEnabled;');
expect(sessionViewSource).toContain("t('orca.split.leadLabel', {");
diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
index 81b7b69adc..e249d71871 100644
--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx
@@ -59,7 +59,10 @@ import { MessageActionBar } from './MessageActionBar';
import { shareSelectionStore } from './shareSelectionStore';
import { useForkAtMessage } from './useForkAtMessage';
import { useDeleteMessage } from './useDeleteMessage';
-import { useSessionNavigationMode } from '@/features/cc-agent/embeddedSessionNavigation';
+import {
+ isInteractiveSessionNavigationMode,
+ useSessionNavigationMode,
+} from '@/features/cc-agent/embeddedSessionNavigation';
/**
* Streaming 渲染策略开关 (代码级 / 编译期):
@@ -254,7 +257,7 @@ export const AssistantMessage = memo(function AssistantMessage({
});
const navigationMode = useSessionNavigationMode();
const canFork =
- navigationMode === 'route-owner' &&
+ isInteractiveSessionNavigationMode(navigationMode) &&
Boolean(currentSessionId && messageClientId) &&
forkSupported;
// 远程会话的消息深链把归属设备冻进 `?device=`(粘滞解析,relay 重连窗口不丢),
diff --git a/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx b/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx
index e969a5a7fa..530a8f2f9e 100644
--- a/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx
+++ b/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx
@@ -40,6 +40,7 @@ export function AutomationOriginBadge({
return (
<button
type="button"
+ data-split-pane-route-action=""
title={t('chat.userMessage.automationViewTask')}
onClick={() => navigate(scheduleFocusPath(automationOrigin.scheduleId))}
className={cn(
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index e1fc4033e3..6d7616e7f4 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -598,6 +598,7 @@ export function ErrorBanner({
// 与「切换到 Claude.ai 并重试」同一档低打扰内联恢复动作:不弹窗、不抢焦点。
<button
type="button"
+ data-split-pane-route-action=""
onClick={onViewBalance}
className={cn(
'shrink-0 flex select-none items-center gap-1 text-xs font-medium',
@@ -645,6 +646,7 @@ export function ErrorBanner({
{onContinueAfterUsageReset && (
<button
type="button"
+ data-split-pane-route-action=""
onClick={onContinueAfterUsageReset}
className={cn(
'shrink-0 flex items-center gap-1 text-xs font-medium',
@@ -677,6 +679,7 @@ export function ErrorBanner({
{showInvalidEncryptedContentRecovery && onForkStripEncrypted && (
<button
type="button"
+ data-split-pane-route-action=""
onClick={() => void onForkStripEncrypted()}
disabled={forkStripEncryptedRunning}
className={cn(
diff --git a/apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx b/apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx
index d950c729ec..cbf7a4ce37 100644
--- a/apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx
+++ b/apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx
@@ -33,6 +33,8 @@ export interface InlineReferenceChipProps {
ariaLabel?: string;
className?: string;
labelClassName?: string;
+ /** 标记会话路由动作,分屏 pane 不应在点击前抢走路由主权。 */
+ splitPaneRouteAction?: boolean;
/**
* chip 文字能否被 selection 选中并进入剪贴板。默认 `true`——已发送消息里的
* chip 必须能跟着正文一起复制出去。composer 里的 ProseMirror atomic node 传
@@ -55,6 +57,7 @@ export function InlineReferenceChip({
ariaLabel,
className,
labelClassName,
+ splitPaneRouteAction = false,
textSelectable = true,
}: InlineReferenceChipProps) {
const interactive = Boolean(onClick || onContextMenu);
@@ -107,6 +110,7 @@ export function InlineReferenceChip({
className={sharedClassName}
style={style}
data-inline-reference-chip=""
+ data-split-pane-route-action={splitPaneRouteAction ? '' : undefined}
>
{contents}
</span>
diff --git a/apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx b/apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx
index 8649a39c06..7a26f5fcc3 100644
--- a/apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx
@@ -1,11 +1,15 @@
import { ArrowUpRight, CornerDownRight, History } from 'lucide-react';
+import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
-import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
+import { getSessionRouteOwnerId, resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { shortSessionId } from '@/lib/sessionId';
-import { useSessionNavigationMode } from '@/features/cc-agent/embeddedSessionNavigation';
+import {
+ useSessionNavigationIntent,
+ useSessionNavigationMode,
+} from '@/features/cc-agent/embeddedSessionNavigation';
export interface SessionHandoffCardProps {
sessionId: string;
@@ -30,6 +34,8 @@ export function SessionHandoffCard({
}: SessionHandoffCardProps) {
const navigate = useNavigate();
const navigationMode = useSessionNavigationMode();
+ const reportSessionNavigation = useSessionNavigationIntent();
+ const navigationRequestVersionRef = useRef(0);
const { t } = useTranslation();
const displayTitle = title?.trim() || t('ccAgent.handoff.card.unnamedSession');
// created / resumed 用实心强调样式(新建或被唤醒,值得注意);already-active 用描边弱样式。
@@ -41,6 +47,13 @@ export function SessionHandoffCard({
? t('ccAgent.handoff.card.wake.resumed')
: t('ccAgent.handoff.card.wake.alreadyActive');
+ useEffect(
+ () => () => {
+ navigationRequestVersionRef.current += 1;
+ },
+ [sessionId, navigationMode],
+ );
+
const formatLastActive = (value: string): string => {
const ms = new Date(value).getTime();
if (Number.isNaN(ms)) return t('ccAgent.handoff.card.lastActive.recently');
@@ -62,7 +75,10 @@ export function SessionHandoffCard({
};
const handleClick = () => {
+ const navigationRequestVersion = ++navigationRequestVersionRef.current;
void resolveSessionRoute(sessionId).then((target) => {
+ if (navigationRequestVersionRef.current !== navigationRequestVersion) return;
+ reportSessionNavigation?.(sessionId, getSessionRouteOwnerId(target) ?? sessionId);
navigate(target, {
state: dispatcherSessionId
? {
@@ -77,11 +93,12 @@ export function SessionHandoffCard({
});
};
- const interactive = navigationMode === 'route-owner';
+ const interactive = navigationMode !== 'sidebar-embedded';
const Root = interactive ? 'button' : 'div';
return (
<Root
+ data-split-pane-route-action={interactive ? '' : undefined}
{...(interactive ? { type: 'button' as const, onClick: handleClick } : {})}
className={cn(
'my-2 flex w-full min-w-0 items-center gap-[14px] rounded-[12px]',
@@ -123,7 +140,11 @@ export function SessionHandoffCard({
<span className="flex min-w-0 items-center gap-[6px]">
{lastActive ? (
<>
- <History size={12} strokeWidth={2} className="shrink-0 text-[var(--settings-section-desc)]" />
+ <History
+ size={12}
+ strokeWidth={2}
+ className="shrink-0 text-[var(--settings-section-desc)]"
+ />
<span className="truncate text-12 leading-4 text-[var(--settings-section-desc)]">
{formatLastActive(lastActive)}
</span>
diff --git a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx
index 9744fc66d2..919d05887f 100644
--- a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx
+++ b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx
@@ -15,7 +15,7 @@
* inline-flex 不打断文本流;不硬编码颜色(规则 16)。
*/
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { CornerDownRight } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -24,12 +24,15 @@ import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
import { cn } from '@/lib/utils';
import { parseSessionDeepLinkHref } from '@/lib/deepLink';
-import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
+import { getSessionRouteOwnerId, resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { shortSessionId } from '@/lib/sessionId';
import { resolveSessionMessageText } from '@/lib/sessionMessageText';
import * as sessionService from '@/lib/sessionService';
import { useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';
-import { useSessionNavigationMode } from '@/features/cc-agent/embeddedSessionNavigation';
+import {
+ useSessionNavigationIntent,
+ useSessionNavigationMode,
+} from '@/features/cc-agent/embeddedSessionNavigation';
import { InlineReferenceChip } from './InlineReferenceChip';
import { QuoteChip } from './QuoteChip';
import type { PersistedSessionReferenceMetadata } from '../../../shared/sessionReferenceMetadata';
@@ -54,15 +57,24 @@ export function SessionLinkChip({ href, label, referenceMetadata }: SessionLinkC
const { t } = useTranslation();
const navigate = useNavigate();
const navigationMode = useSessionNavigationMode();
+ const reportSessionNavigation = useSessionNavigationIntent();
const target = useMemo(() => parseSessionDeepLinkHref(href), [href]);
const remoteSessions = useRemoteProjectSessions();
const [fetchedTitle, setFetchedTitle] = useState<string | null>(null);
const [messageText, setMessageText] = useState<string | null>(null);
+ const navigationRequestVersionRef = useRef(0);
const sessionId = target?.sessionId ?? null;
const messageClientId = target?.messageClientId ?? null;
const explicitLabel = label?.trim() || null;
+ useEffect(
+ () => () => {
+ navigationRequestVersionRef.current += 1;
+ },
+ [sessionId, messageClientId, navigationMode],
+ );
+
useEffect(() => {
// 先清旧值:同一实例被复用渲染另一个 href(虚拟列表 / 消息 patch)时,
// 不能让上一个会话的标题串到新链接上(Codex review P2)。
@@ -104,10 +116,13 @@ export function SessionLinkChip({ href, label, referenceMetadata }: SessionLinkC
const remoteSession = remoteSessions.find((s) => s.id === sessionId) ?? null;
const remoteTitle = fetchedTitle ? null : remoteSession?.title?.trim() || null;
const handleClick = () => {
+ const navigationRequestVersion = ++navigationRequestVersionRef.current;
// device-link 远程会话本地无 row,resolveSessionRoute 内部的 sessionService.get
// 会 miss → 远程 Orca 会话被当普通会话路由,后续 redirect 会丢 searchJump 锚点。
// 把远程镜像里的 session 对象直接传入,让 Orca 路由一步到位(Codex review P2)。
void resolveSessionRoute(sessionId, remoteSession).then((route) => {
+ if (navigationRequestVersionRef.current !== navigationRequestVersion) return;
+ reportSessionNavigation?.(sessionId, getSessionRouteOwnerId(route) ?? sessionId);
navigate(
route,
target.messageClientId
@@ -128,11 +143,12 @@ export function SessionLinkChip({ href, label, referenceMetadata }: SessionLinkC
};
// 未起名会话过投影再显示:chip 直接摆在消息流里,原样会露出内部哨兵 "New Maker"。
const resolvedTitle = fetchedTitle ?? remoteTitle;
- const display = explicitLabel
- ?? (resolvedTitle
+ const display =
+ explicitLabel ??
+ (resolvedTitle
? projectDraftSessionTitle(resolvedTitle, t('ccAgent.common.unnamedSession'))
- : null)
- ?? shortSessionId(sessionId);
+ : null) ??
+ shortSessionId(sessionId);
const referenceDetails = referenceMetadata
? [
t(
@@ -143,12 +159,11 @@ export function SessionLinkChip({ href, label, referenceMetadata }: SessionLinkC
t('chat.userMessage.sessionReference.messageCount', {
count: referenceMetadata.messageCount,
}),
- ...(referenceMetadata.truncated
- ? [t('chat.userMessage.sessionReference.truncated')]
- : []),
+ ...(referenceMetadata.truncated ? [t('chat.userMessage.sessionReference.truncated')] : []),
]
: [];
- const tooltip = referenceDetails.length > 0 ? `${display}\n${referenceDetails.join(' · ')}` : display;
+ const tooltip =
+ referenceDetails.length > 0 ? `${display}\n${referenceDetails.join(' · ')}` : display;
if (messageClientId) {
const fullText = messageText ?? shortSessionId(messageClientId);
@@ -167,19 +182,24 @@ export function SessionLinkChip({ href, label, referenceMetadata }: SessionLinkC
</span>
);
// summary 单行截断:窄气泡里退化成省略号,完整内容仍在 title / aria-label。
- const referenceSummary = referenceDetails.length > 0 ? (
- <span
- data-session-reference-summary=""
- className="ml-1 min-w-0 truncate text-[11px] text-[var(--text-tertiary)]"
- >
- {referenceDetails.join(' · ')}
- </span>
- ) : null;
+ const referenceSummary =
+ referenceDetails.length > 0 ? (
+ <span
+ data-session-reference-summary=""
+ className="ml-1 min-w-0 truncate text-[11px] text-[var(--text-tertiary)]"
+ >
+ {referenceDetails.join(' · ')}
+ </span>
+ ) : null;
// items-center 保证 pill 保持自身高度(不被 align-items: stretch 撑成椭圆)。
const messageClass = 'inline-flex max-w-full items-center align-middle';
if (navigationMode === 'sidebar-embedded') {
return (
- <span data-session-message-link="" title={tooltip} className={cn(messageClass, 'cursor-default')}>
+ <span
+ data-session-message-link=""
+ title={tooltip}
+ className={cn(messageClass, 'cursor-default')}
+ >
{messageContent}
{referenceSummary}
</span>
@@ -189,6 +209,7 @@ export function SessionLinkChip({ href, label, referenceMetadata }: SessionLinkC
<button
type="button"
data-session-message-link=""
+ data-split-pane-route-action=""
aria-label={
referenceDetails.length > 0
? `${visibleMessageLabel} (${referenceDetails.join(' · ')})`
@@ -223,6 +244,7 @@ export function SessionLinkChip({ href, label, referenceMetadata }: SessionLinkC
tooltip={tooltip}
ariaLabel={display}
onClick={handleClick}
+ splitPaneRouteAction
className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"
/>
);
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 0a3343c747..af6c4d1735 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -74,7 +74,10 @@ import { shareSelectionStore } from './shareSelectionStore';
import { ErrorMessageCard } from './ErrorMessageCard';
import { useForkAtMessage, textToTiptapDoc } from './useForkAtMessage';
import { useDeleteMessage } from './useDeleteMessage';
-import { useSessionNavigationMode } from '@/features/cc-agent/embeddedSessionNavigation';
+import {
+ isInteractiveSessionNavigationMode,
+ useSessionNavigationMode,
+} from '@/features/cc-agent/embeddedSessionNavigation';
import { RewindPreviewDialog } from './RewindPreviewDialog';
import { UserMessageEditBox } from './UserMessageEditBox';
import HookTaskCard from './HookTaskCard';
@@ -1157,7 +1160,7 @@ export function UserMessage({
// 同时按 capabilities.fork.supported gate (Codex 现支持; 未来若 agent 不支持自动隐藏)。
const navigationMode = useSessionNavigationMode();
const canFork =
- navigationMode === 'route-owner' &&
+ isInteractiveSessionNavigationMode(navigationMode) &&
Boolean(sessionId && messageClientId) &&
!isFirstUserMessage &&
forkSupported &&
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
index 080b1b7cfa..0ea263c7e5 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
@@ -810,7 +810,11 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- fireEvent.click(screen.getByRole('button', { name: 'chat.errorBanner.continueAfterReset' }));
+ const continueButton = screen.getByRole('button', {
+ name: 'chat.errorBanner.continueAfterReset',
+ });
+ expect(continueButton.getAttribute('data-split-pane-route-action')).toBe('');
+ fireEvent.click(continueButton);
expect(onContinueAfterUsageReset).toHaveBeenCalledOnce();
rerender(
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx
index 984096b6c9..fbd75d9c82 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx
@@ -1,6 +1,8 @@
// @vitest-environment jsdom
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -15,6 +17,14 @@ const mocks = vi.hoisted(() => ({
resolveSessionMessageText: vi.fn(async () => 'Target message\nfull text'),
}));
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+}
+
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal<typeof import('react-router-dom')>();
return { ...actual, useNavigate: () => mocks.navigate };
@@ -33,9 +43,11 @@ vi.mock('@/lib/sessionMessageText', () => ({
}));
vi.mock('@/lib/orcaSessionIdentity', () => ({
resolveSessionRoute: mocks.resolveSessionRoute,
+ getSessionRouteOwnerId: (route: string) => /^\/cc-agent\/([^/?#]+)/.exec(route)?.[1] ?? null,
}));
import {
+ isInteractiveSessionNavigationMode,
SessionNavigationModeProvider,
useSidebarTargetSessionId,
} from '@/features/cc-agent/embeddedSessionNavigation';
@@ -55,6 +67,17 @@ function embedded(children: ReactNode, sidebarTargetSessionId?: string) {
);
}
+function splitPane(
+ children: ReactNode,
+ onSessionNavigate: (targetSessionId: string, routeOwnerSessionId?: string) => void,
+) {
+ return (
+ <SessionNavigationModeProvider mode="split-pane" onSessionNavigate={onSessionNavigate}>
+ {children}
+ </SessionNavigationModeProvider>
+ );
+}
+
function SidebarTargetProbe({ contentSessionId }: { contentSessionId?: string }) {
return <span data-testid="sidebar-target">{useSidebarTargetSessionId(contentSessionId)}</span>;
}
@@ -88,7 +111,72 @@ describe('sidebar-embedded session navigation boundary', () => {
expect(mocks.navigate).not.toHaveBeenCalled();
});
- it('shows the persisted reference range summary without changing the link label', () => {
+ it('reports split-pane session navigation before changing the route', async () => {
+ const onSessionNavigate = vi.fn();
+ render(
+ splitPane(
+ <SessionLinkChip href="xdt-maker://session/session-target" label="Session target" />,
+ onSessionNavigate,
+ ),
+ );
+
+ fireEvent.click(screen.getByRole('button'));
+
+ await waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/session-target', undefined),
+ );
+ expect(onSessionNavigate).toHaveBeenCalledWith('session-target', 'session-target');
+ expect(onSessionNavigate.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.navigate.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('reports the canonical Lead owner for a worker deep link', async () => {
+ mocks.resolveSessionRoute.mockResolvedValueOnce('/cc-agent/lead-target?worker=worker-target');
+ const onSessionNavigate = vi.fn();
+ render(
+ splitPane(
+ <SessionLinkChip href="xdt-maker://session/worker-target" label="Worker target" />,
+ onSessionNavigate,
+ ),
+ );
+
+ fireEvent.click(screen.getByRole('button'));
+
+ await waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ '/cc-agent/lead-target?worker=worker-target',
+ undefined,
+ ),
+ );
+ expect(onSessionNavigate).toHaveBeenCalledWith('worker-target', 'lead-target');
+ });
+
+ it('cancels pending split-pane link navigation after the source pane unmounts', async () => {
+ const pendingRoute = deferred<string>();
+ mocks.resolveSessionRoute.mockReturnValueOnce(pendingRoute.promise);
+ const onSessionNavigate = vi.fn();
+ const view = render(
+ splitPane(
+ <SessionLinkChip href="xdt-maker://session/session-target" label="Session target" />,
+ onSessionNavigate,
+ ),
+ );
+
+ fireEvent.click(screen.getByRole('button'));
+ expect(mocks.resolveSessionRoute).toHaveBeenCalledWith('session-target', null);
+ view.unmount();
+
+ await act(async () => {
+ pendingRoute.resolve('/cc-agent/session-target');
+ await pendingRoute.promise;
+ });
+
+ expect(onSessionNavigate).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('shows the persisted reference range summary without changing the link label', async () => {
render(
embedded(
<SessionLinkChip
@@ -104,6 +192,9 @@ describe('sidebar-embedded session navigation boundary', () => {
/>,
),
);
+ await act(async () => {
+ await Promise.resolve();
+ });
expect(screen.getByText('Session A')).toBeTruthy();
expect(
@@ -113,7 +204,7 @@ describe('sidebar-embedded session navigation boundary', () => {
).toBeTruthy();
});
- it('keeps the anchored pill and its range summary on a single line', () => {
+ it('keeps the anchored pill and its range summary on a single line', async () => {
const { container } = render(
<SessionLinkChip
href="cindy://session/session-a?message=message-1"
@@ -127,6 +218,9 @@ describe('sidebar-embedded session navigation boundary', () => {
}}
/>,
);
+ await act(async () => {
+ await Promise.resolve();
+ });
// 宽度上限必须留在 pill 一侧:加回外层会让 pill 与 summary 抢同一份 240px,
// summary 被压成逐字竖排、pill 被 stretch 拉成大椭圆。
@@ -160,6 +254,60 @@ describe('sidebar-embedded session navigation boundary', () => {
expect(mocks.navigate).not.toHaveBeenCalled();
});
+ it('reports the canonical Lead owner for a worker handoff', async () => {
+ mocks.resolveSessionRoute.mockResolvedValueOnce('/cc-agent/lead-target?worker=worker-target');
+ const onSessionNavigate = vi.fn();
+ render(
+ splitPane(
+ <SessionHandoffCard
+ sessionId="worker-target"
+ title="Worker target"
+ wake="resumed"
+ lastActive={null}
+ />,
+ onSessionNavigate,
+ ),
+ );
+
+ fireEvent.click(screen.getByRole('button'));
+
+ await waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/lead-target?worker=worker-target', {
+ state: undefined,
+ }),
+ );
+ expect(onSessionNavigate).toHaveBeenCalledWith('worker-target', 'lead-target');
+ });
+
+ it('cancels pending handoff navigation after the source pane unmounts', async () => {
+ const pendingRoute = deferred<string>();
+ mocks.resolveSessionRoute.mockReturnValueOnce(pendingRoute.promise);
+ const onSessionNavigate = vi.fn();
+ const view = render(
+ splitPane(
+ <SessionHandoffCard
+ sessionId="session-target"
+ title="Session target"
+ wake="resumed"
+ lastActive={null}
+ />,
+ onSessionNavigate,
+ ),
+ );
+
+ fireEvent.click(screen.getByRole('button'));
+ expect(mocks.resolveSessionRoute).toHaveBeenCalledWith('session-target');
+ view.unmount();
+
+ await act(async () => {
+ pendingRoute.resolve('/cc-agent/session-target');
+ await pendingRoute.promise;
+ });
+
+ expect(onSessionNavigate).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
it('renders automation origins as static content without scheduling navigation', () => {
render(
embedded(
@@ -180,18 +328,130 @@ describe('sidebar-embedded session navigation boundary', () => {
it('consumes /jump-session without resolving or navigating in embedded mode', async () => {
const t = ((key: string) => key) as never;
+ const onSessionNavigate = vi.fn();
await expect(
tryHandleNavigationCommand('/jump-session session-c', {
navigate: mocks.navigate,
t,
allowNavigation: false,
+ onSessionNavigate,
}),
).resolves.toBe(true);
expect(mocks.getSession).not.toHaveBeenCalled();
+ expect(mocks.resolveSessionRoute).not.toHaveBeenCalled();
+ expect(onSessionNavigate).not.toHaveBeenCalled();
expect(mocks.navigate).not.toHaveBeenCalled();
});
+ it('reports /jump-session replacement before navigating from a split pane', async () => {
+ const t = ((key: string) => key) as never;
+ const onSessionNavigate = vi.fn();
+ mocks.resolveSessionRoute.mockResolvedValueOnce('/cc-agent/lead-target?worker=worker-target');
+
+ await expect(
+ tryHandleNavigationCommand('/jump-session worker-target', {
+ navigate: mocks.navigate,
+ t,
+ allowNavigation: true,
+ onSessionNavigate,
+ }),
+ ).resolves.toBe(true);
+
+ expect(mocks.getSession).toHaveBeenCalledWith('worker-target');
+ expect(mocks.resolveSessionRoute).toHaveBeenCalledWith(
+ 'worker-target',
+ expect.objectContaining({ id: 'worker-target' }),
+ );
+ expect(onSessionNavigate).toHaveBeenCalledWith('worker-target', 'lead-target');
+ expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/lead-target?worker=worker-target');
+ expect(onSessionNavigate.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.navigate.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
+ );
+ });
+
+ it('cancels pending split-pane /jump-session navigation after the source becomes stale', async () => {
+ const pendingRoute = deferred<string>();
+ mocks.resolveSessionRoute.mockReturnValueOnce(pendingRoute.promise);
+ const onSessionNavigate = vi.fn();
+ let navigationCurrent = true;
+ const navigationPromise = tryHandleNavigationCommand('/jump-session session-target', {
+ navigate: mocks.navigate,
+ t: ((key: string) => key) as never,
+ allowNavigation: true,
+ onSessionNavigate,
+ isNavigationCurrent: () => navigationCurrent,
+ });
+
+ await waitFor(() => expect(mocks.resolveSessionRoute).toHaveBeenCalled());
+ navigationCurrent = false;
+ await act(async () => {
+ pendingRoute.resolve('/cc-agent/session-target');
+ await pendingRoute.promise;
+ await navigationPromise;
+ });
+
+ expect(onSessionNavigate).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('cancels stale /jump-session before resolving the route after target lookup', async () => {
+ const pendingSession = deferred<{
+ id: string;
+ title: string;
+ status: 'active';
+ }>();
+ mocks.getSession.mockReturnValueOnce(pendingSession.promise);
+ const onSessionNavigate = vi.fn();
+ let navigationCurrent = true;
+ const navigationPromise = tryHandleNavigationCommand('/jump-session session-target', {
+ navigate: mocks.navigate,
+ t: ((key: string) => key) as never,
+ allowNavigation: true,
+ onSessionNavigate,
+ isNavigationCurrent: () => navigationCurrent,
+ });
+
+ await waitFor(() => expect(mocks.getSession).toHaveBeenCalledWith('session-target'));
+ navigationCurrent = false;
+ await act(async () => {
+ pendingSession.resolve({ id: 'session-target', title: 'Session target', status: 'active' });
+ await pendingSession.promise;
+ await navigationPromise;
+ });
+
+ expect(mocks.resolveSessionRoute).not.toHaveBeenCalled();
+ expect(onSessionNavigate).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('wires split-pane /jump-session handling through the pane navigation reporter', () => {
+ const source = readFileSync(
+ resolve(__dirname, '..', '..', '..', 'features', 'cc-agent', 'CCAgentSessionView.tsx'),
+ 'utf8',
+ );
+
+ expect(source).toContain('allowNavigation: canNavigateSession');
+ expect(source).toContain(
+ "onSessionNavigate: navigationMode === 'split-pane' ? onSessionNavigate : undefined",
+ );
+ expect(source).toContain(
+ 'onSessionNavigate?.(parentSessionId, getSessionRouteOwnerId(target) ?? parentSessionId)',
+ );
+ expect(source).toContain(
+ 'canNavigateSession && session?.parentSessionId && session.forkedAtMessageId',
+ );
+ expect(source).toContain('const sessionNavigationVersionRef = useRef(0);');
+ expect(source).toContain(
+ 'if (sessionNavigationVersionRef.current !== navigationRequestVersion) return;',
+ );
+ expect(source).toContain(
+ 'if (sessionNavigationVersionRef.current !== forkStripNavigationVersion) return;',
+ );
+ expect(source).toContain('isNavigationCurrent:');
+ expect(source).toContain('[navigationMode, sessionId],');
+ });
+
it('keeps route-owner session links interactive', async () => {
render(<SessionLinkChip href="xdt-maker://session/session-d" label="Session D" />);
fireEvent.click(screen.getByRole('button'));
@@ -270,7 +530,9 @@ describe('sidebar-embedded session navigation boundary', () => {
automationOrigin={{ kind: 'scheduler', scheduleId: 'schedule-2', scheduleName: 'Daily' }}
/>,
);
- fireEvent.click(screen.getByRole('button'));
+ const automationButton = screen.getByRole('button');
+ expect(automationButton.getAttribute('data-split-pane-route-action')).toBe('');
+ fireEvent.click(automationButton);
expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/scheduled?focus=schedule-2');
});
@@ -284,6 +546,20 @@ describe('sidebar-embedded session navigation boundary', () => {
).resolves.toBe(true);
expect(mocks.getSession).toHaveBeenCalledWith('session-f');
+ expect(mocks.resolveSessionRoute).toHaveBeenCalledWith(
+ 'session-f',
+ expect.objectContaining({ id: 'session-f' }),
+ );
expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/session-f');
});
});
+
+describe('session navigation interaction policy', () => {
+ it.each([
+ ['route-owner', true],
+ ['split-pane', true],
+ ['sidebar-embedded', false],
+ ] as const)('%s interactive=%s', (mode, expected) => {
+ expect(isInteractiveSessionNavigationMode(mode)).toBe(expected);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/useForkAtMessage.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/useForkAtMessage.test.tsx
index 5ff8a9eacf..8aff594987 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/useForkAtMessage.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/useForkAtMessage.test.tsx
@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({
forkAtMessage: vi.fn(),
navigate: vi.fn(),
emitRefresh: vi.fn(),
+ reportSessionNavigation: vi.fn(),
}));
vi.mock('react-i18next', () => ({
@@ -44,6 +45,7 @@ vi.mock('@/features/device-link/refreshRemoteSessions', () => ({
vi.mock('@/features/cc-agent/embeddedSessionNavigation', () => ({
useSessionNavigationMode: () => 'route-owner',
+ useSessionNavigationIntent: () => mocks.reportSessionNavigation,
}));
vi.mock('@/lib/logger', () => ({
@@ -60,10 +62,12 @@ describe('useForkAtMessage introduction dialog', () => {
it('introduces the feature and only creates a conversation after confirmation', async () => {
mocks.confirm.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
- const { result } = renderHook(() => useForkAtMessage({
- sessionId: 'source-session',
- messageClientId: 'message-1',
- }));
+ const { result } = renderHook(() =>
+ useForkAtMessage({
+ sessionId: 'source-session',
+ messageClientId: 'message-1',
+ }),
+ );
await act(async () => result.current());
expect(mocks.confirm).toHaveBeenLastCalledWith({
@@ -78,6 +82,7 @@ describe('useForkAtMessage introduction dialog', () => {
await act(async () => result.current());
expect(mocks.forkAtMessage).toHaveBeenCalledWith('source-session', 'message-1');
expect(mocks.emitRefresh).toHaveBeenCalledTimes(1);
+ expect(mocks.reportSessionNavigation).toHaveBeenCalledWith('new-session', 'new-session');
expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/new-session');
});
});
diff --git a/apps/desktop/src/renderer/components/chat/useForkAtMessage.ts b/apps/desktop/src/renderer/components/chat/useForkAtMessage.ts
index d092acd62d..05c1966059 100644
--- a/apps/desktop/src/renderer/components/chat/useForkAtMessage.ts
+++ b/apps/desktop/src/renderer/components/chat/useForkAtMessage.ts
@@ -23,7 +23,10 @@ import type { JSONContent } from '@tiptap/core';
import { emitRefresh as emitSessionsRefresh } from '@/lib/sessionsBus';
import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';
import { refreshRemoteDeviceSessions } from '@/features/device-link/refreshRemoteSessions';
-import { useSessionNavigationMode } from '@/features/cc-agent/embeddedSessionNavigation';
+import {
+ useSessionNavigationIntent,
+ useSessionNavigationMode,
+} from '@/features/cc-agent/embeddedSessionNavigation';
import { createLogger } from '@/lib/logger';
import { isCodexResumeNotReadyProjectionError } from '@cindy/maker-shared/agent-input-projection';
@@ -72,6 +75,7 @@ export function useForkAtMessage({
const { confirm } = useConfirmDialog();
const navigate = useNavigate();
const navigationMode = useSessionNavigationMode();
+ const reportSessionNavigation = useSessionNavigationIntent();
return useCallback(async () => {
if (!sessionId || !messageClientId) return;
@@ -115,6 +119,7 @@ export function useForkAtMessage({
// remoteProjectsStore 注册新 sessionId,否则 navigate 会把它当本地会话 404(等轮询太慢)。
const deviceId = getSessionDeviceId(sessionId);
if (deviceId) await refreshRemoteDeviceSessions(deviceId);
+ reportSessionNavigation?.(newSession.id, newSession.id);
navigate(`/cc-agent/${newSession.id}`);
} catch (err) {
const code = err instanceof ApiError ? err.code : 'UNKNOWN';
@@ -140,6 +145,7 @@ export function useForkAtMessage({
sessionId,
messageClientId,
navigationMode,
+ reportSessionNavigation,
forkBlocked,
draftText,
draftDocument,
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index afad6e05e6..f64f415808 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -12,6 +12,10 @@ import { RightSidebar, type RightSidebarHandle } from '@/components/layout/Right
import { RightSidebarMaximize } from '@/components/layout/RightSidebarMaximize';
import { RightSidebarToggle } from '@/components/layout/RightSidebarToggle';
import { Sidebar } from '@/components/sidebar/Sidebar';
+import {
+ getSplitSessionIds,
+ useSplitGroup,
+} from '@/features/cc-agent/splitGroupStore';
import { LayoutRoot } from '@/layout/LayoutRoot';
import { PanelDragController } from '@/layout/PanelDragController';
import { GhostMediaLightboxHost } from '@/cindy-brain/GhostMediaLightboxHost';
@@ -210,6 +214,7 @@ function SidebarPinSpacer({ width }: { width: number }) {
}
export function MainLayout() {
+ const splitGroup = useSplitGroup();
const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(getInitialCollapsed);
const [shareImportRequest, setShareImportRequest] = useState<{
id: number;
@@ -423,14 +428,25 @@ export function MainLayout() {
}
}, [sidebarPeek.peekState, isRailMode, handleRailModeChange]);
+ const routeSessionId = resolveAgentIslandVisibleSessionIdFromPath(location.pathname);
+ const splitVisibleSessionIds = useMemo(
+ () => {
+ const splitSessionIds = getSplitSessionIds(splitGroup.root);
+ return routeSessionId && splitSessionIds.length >= 2
+ ? [...new Set([routeSessionId, ...splitSessionIds])]
+ : [];
+ },
+ [routeSessionId, splitGroup.root],
+ );
+
const syncAgentIslandVisibleSession = useCallback(() => {
if (!isAgentIslandSupported()) return;
if (!document.hasFocus()) return;
if (isAgentIslandVisibleSessionOwnedByWorkdirBrowseRoute(location.pathname)) return;
void window.electronAPI.agentIsland?.setVisibleSession?.(
- resolveAgentIslandVisibleSessionIdFromPath(location.pathname),
+ splitVisibleSessionIds.length >= 2 ? splitVisibleSessionIds : routeSessionId,
);
- }, [location.pathname]);
+ }, [location.pathname, routeSessionId, splitVisibleSessionIds]);
useEffect(() => {
syncAgentIslandVisibleSession();
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx
index 9ed6f207cd..cce309a631 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx
@@ -22,10 +22,13 @@
import { useEffect } from 'react';
import { Outlet, useLocation, matchPath, useOutletContext } from 'react-router-dom';
+import { resolveAgentIslandVisibleSessionIdFromPath } from '@/lib/agentIslandVisibleSessionRoute';
+import { SplitGroup } from './SplitGroup';
import { useRegisterCCAgentSidebar } from './useRegisterCCAgentSidebar';
import { saveLastChatView, saveLastDocView } from './lib/lastViewStore';
export function CCAgentFeatureLayout() {
+ const location = useLocation();
// 注入 CC Agent 项目/对话侧栏到 Shell 上半槽位(SkillHub / IssueTracker 共用同一 hook)。
useRegisterCCAgentSidebar();
@@ -59,7 +62,13 @@ export function CCAgentFeatureLayout() {
deviceLinkDeviceId?: string | null,
) => void;
} | null>();
- return <Outlet context={shellContext} />;
+ return (
+ <SplitGroup
+ activeSessionId={resolveAgentIslandVisibleSessionIdFromPath(location.pathname) ?? undefined}
+ >
+ <Outlet context={shellContext} />
+ </SplitGroup>
+ );
}
/**
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 27c9aac909..94c3a6e102 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -151,6 +151,7 @@ import { getMakerMemoryEnabled } from '@/lib/memorySettingsStore';
import { useWorktreeCreation, worktreeCreationStore } from '@/lib/worktreeCreationStore';
import { useWorktreeForSession } from '@/contexts/WorktreeContext';
import {
+ getSessionRouteOwnerId,
isOrcaLeadSession,
isOrcaWorkerSession,
resolveSessionRoute,
@@ -161,7 +162,7 @@ import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
import { createLogger } from '@/lib/logger';
import { getModelById, getDefaultModelForVendor, getModelsForVendor } from '@/lib/modelDefinitions';
import { resolveDisplayContextWindow } from '@/lib/contextWindow';
-import { tryHandleNavigationCommand } from '@/lib/navigationCommands';
+import { matchNavigationCommandName, tryHandleNavigationCommand } from '@/lib/navigationCommands';
import { extractIpcError } from '@/utils/ipcError';
import { listActiveRunsForSession } from '@/features/learn/useLearnRun';
import { subscribeLearnEvents } from '@/features/learn/learnTransport';
@@ -180,6 +181,8 @@ import {
} from '@/lib/composerDraftStore';
import { setLastWorkingDir } from '@/state/lastWorkingDir';
import { consumeComposerMentionDrop } from '@/lib/composerDrop';
+import { hasSplitGroupSessionType } from './splitGroupDnd';
+import { splitGroupStore } from './splitGroupStore';
import {
attachGhostMediaToSession,
getGhostMediaUriFromDataTransfer,
@@ -250,6 +253,7 @@ import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOr
import { refreshRemoteDeviceSessions } from '@/features/device-link/refreshRemoteSessions';
import {
SessionNavigationModeProvider,
+ type SessionNavigationIntentReporter,
type SessionNavigationMode,
} from './embeddedSessionNavigation';
import {
@@ -328,6 +332,12 @@ function parseOrcaWorkersRevealState(state: unknown): OrcaWorkersRevealState | n
interface CCAgentSessionViewProps {
sessionIdProp?: string;
+ /**
+ * 显式声明内嵌实例是否接管当前窗口路由的 header / 右栏主权。默认不传时沿用
+ * 历史判据:只有无 sessionIdProp 的全屏路由实例拥有主权。SplitGroup 用它在
+ * 多个常驻会话 pane 之间转移主权,避免切活动 pane 时卸载重挂聊天视图。
+ */
+ routeOwner?: boolean;
compact?: boolean;
orcaMode?: boolean;
/** 在输入区显示被控端提示。普通路由自动显示;完整态居中,折叠态位于 token 左侧。 */
@@ -363,8 +373,12 @@ interface CCAgentSessionViewProps {
onSearchJumpConsumed?: () => void;
/** sidebar 子窗口内嵌视图不拥有 router,所有“打开其它会话”入口必须禁用。 */
navigationMode?: SessionNavigationMode;
+ /** split-pane 内部跳转前上报目标任务,让宿主替换发起跳转的 pane。 */
+ onSessionNavigate?: SessionNavigationIntentReporter;
/** 内嵌聊天触发侧栏动作时使用的可见 RSB bucket;消息身份仍由 sessionIdProp 决定。 */
sidebarTargetSessionId?: string;
+ /** 禁止该常驻视图在挂载时抢占键盘焦点(例如非 owner 的分屏 pane)。 */
+ disableAutofocus?: boolean;
}
/**
@@ -473,6 +487,7 @@ function findLatestWorkflowTask(
export function CCAgentSessionView({
sessionIdProp,
+ routeOwner,
compact,
orcaMode,
showControlledBanner = false,
@@ -483,13 +498,23 @@ export function CCAgentSessionView({
searchJumpProp,
onSearchJumpConsumed,
navigationMode = 'route-owner',
+ onSessionNavigate,
sidebarTargetSessionId,
+ disableAutofocus = false,
}: CCAgentSessionViewProps = {}) {
const { t } = useTranslation();
const { sessionId: paramSessionId } = useParams<{ sessionId: string }>();
const sessionId = sessionIdProp ?? paramSessionId;
const navigate = useNavigate();
const ownsWindowRoute = navigationMode === 'route-owner';
+ const canNavigateSession = ownsWindowRoute || navigationMode === 'split-pane';
+ const sessionNavigationVersionRef = useRef(0);
+ useEffect(
+ () => () => {
+ sessionNavigationVersionRef.current += 1;
+ },
+ [navigationMode, sessionId],
+ );
const location = useLocation();
useEffect(() => {
return window.electronAPI.ghosts.onSetupNavigate((payload) => {
@@ -587,10 +612,10 @@ export function CCAgentSessionView({
// 让窄 rail 里的消息和输入框尽量铺满。
const isCompactRail = compact ?? location.pathname.startsWith('/cc-agent/files/');
const isOrcaMode = orcaMode ?? location.pathname.startsWith('/cc-agent/orca/');
- // 路由主实例判据(与 SessionContentHeaderRegistration 同款,见 1259 行):只有
- // 「全屏聊天视图」这个实例拥有右栏开关 / 声明右栏在场;内嵌复用实例(doc 模式
- // chat rail / 协同 worker 面板,带 sessionIdProp 或处于 compact/orca 语境)不参与。
- const ownsRoute = !sessionIdProp && !isCompactRail && !isOrcaMode;
+ // 路由主实例判据(与 SessionContentHeaderRegistration 同款):默认只有全屏路由
+ // 实例拥有右栏 / header 主权。SplitGroup 的常驻 pane 可用 routeOwner 显式转移
+ // 主权;其它内嵌复用实例(doc rail / Orca worker)不传,行为保持不变。
+ const ownsRoute = routeOwner ?? (!sessionIdProp && !isCompactRail && !isOrcaMode);
const showComposerControlledBanner = ownsRoute || showControlledBanner;
const controlledBy = useControlledBy();
const hasControlledBanner = showComposerControlledBanner && controlledBy.length > 0;
@@ -894,6 +919,9 @@ export function CCAgentSessionView({
if (!sessionId) return;
if (session?.status === 'deleted') {
makerChatStore.purgeSession(sessionId);
+ // 分屏树同步收敛:已删任务的 pane 立即塌缩,持久化布局不再保留死节点;
+ // 嵌入 pane 靠这一步退出(下方 return 不导航),owner 导航后也不会恢复它。
+ splitGroupStore.removeSession(sessionId);
if (!ownsWindowRoute) {
log.info('deleted session navigation ignored by embedded sidebar view', { sessionId });
return;
@@ -907,7 +935,10 @@ export function CCAgentSessionView({
if (!sessionId || !searchJump) return;
if (searchJump.sessionId !== sessionId) {
if (!session) return;
- if (!isOrcaMode && !isOrcaLeadSessionView) {
+ // 仅路由主权实例回收「跳转目标 ≠ 当前会话」的陈旧状态:分屏的嵌入 pane
+ // sessionId 固定,跨会话跳转时它们天然不匹配,若也清理会把 owner 正在
+ // 消费的跳转取消掉(异步 loadAround 被 cleanup 置为 cancelled)。
+ if (!isOrcaMode && !isOrcaLeadSessionView && ownsWindowRoute) {
clearSearchJumpState();
}
return;
@@ -970,6 +1001,7 @@ export function CCAgentSessionView({
clearSearchJumpState,
isOrcaLeadSessionView,
isOrcaMode,
+ ownsWindowRoute,
requestFocusMessage,
searchJump,
session,
@@ -1103,14 +1135,17 @@ export function CCAgentSessionView({
}, [handoffFrom?.dispatcherSessionId, navigate, ownsWindowRoute, sessionId]);
const handleOpenForkOrigin = useCallback(() => {
- if (!ownsWindowRoute) {
+ if (!canNavigateSession) {
log.info('fork origin navigation ignored by embedded sidebar view', { sessionId });
return;
}
if (!session?.parentSessionId || !session.forkedAtMessageId) return;
const parentSessionId = session.parentSessionId;
const forkedAtMessageId = session.forkedAtMessageId;
+ const navigationRequestVersion = ++sessionNavigationVersionRef.current;
void resolveSessionRoute(parentSessionId).then((target) => {
+ if (sessionNavigationVersionRef.current !== navigationRequestVersion) return;
+ onSessionNavigate?.(parentSessionId, getSessionRouteOwnerId(target) ?? parentSessionId);
navigate(target, {
state: {
searchJump: {
@@ -1123,18 +1158,25 @@ export function CCAgentSessionView({
},
});
});
- }, [navigate, ownsWindowRoute, session?.forkedAtMessageId, session?.parentSessionId, sessionId]);
+ }, [
+ canNavigateSession,
+ navigate,
+ onSessionNavigate,
+ session?.forkedAtMessageId,
+ session?.parentSessionId,
+ sessionId,
+ ]);
const forkOrigin = useMemo(
() =>
- ownsWindowRoute && session?.parentSessionId && session.forkedAtMessageId
+ canNavigateSession && session?.parentSessionId && session.forkedAtMessageId
? {
parentSessionId: session.parentSessionId,
forkedAtMessageId: session.forkedAtMessageId,
forkedSessionCreatedAt: session.createdAt,
}
: null,
- [ownsWindowRoute, session?.createdAt, session?.forkedAtMessageId, session?.parentSessionId],
+ [canNavigateSession, session?.createdAt, session?.forkedAtMessageId, session?.parentSessionId],
);
// F-CMD /help: 拉三源(desktop + agent-builtin + agent-skill) palette 快照,
@@ -1853,7 +1895,7 @@ export function CCAgentSessionView({
// 已记录为开/关都尊重用户历史,只 ensure tab 存在,不抢 active tab。
// doc rail (isCompactRail) 不在这里打开,由 WorkdirBrowseRoute 的 toggle 布局接管。
useEffect(() => {
- if (!collabEnabled || isCompactRail || !sessionId) return;
+ if (!ownsRoute || !collabEnabled || isCompactRail || !sessionId) return;
const shouldRevealForMissingCollapsedRecord =
passiveOrcaWorkersRevealSessionRef.current !== sessionId &&
shouldRevealOrcaWorkersAfterPaint({
@@ -2460,12 +2502,21 @@ export function CCAgentSessionView({
},
) => {
const deliveryMode = opts?.deliveryMode ?? 'queue';
+ const navigationRequestVersion =
+ deliveryMode !== 'steer' && matchNavigationCommandName(message)
+ ? ++sessionNavigationVersionRef.current
+ : null;
if (
deliveryMode !== 'steer' &&
(await tryHandleNavigationCommand(message, {
navigate,
t,
- allowNavigation: ownsWindowRoute,
+ allowNavigation: canNavigateSession,
+ onSessionNavigate: navigationMode === 'split-pane' ? onSessionNavigate : undefined,
+ isNavigationCurrent:
+ navigationRequestVersion === null
+ ? undefined
+ : () => sessionNavigationVersionRef.current === navigationRequestVersion,
}))
) {
return;
@@ -2602,7 +2653,9 @@ export function CCAgentSessionView({
maybeShowContextUsage,
folderPickerOpen,
isCodex,
- ownsWindowRoute,
+ canNavigateSession,
+ navigationMode,
+ onSessionNavigate,
patchLocalSession,
sendMessage,
steerMessage,
@@ -2787,10 +2840,11 @@ export function CCAgentSessionView({
const handleForkStripEncrypted = useCallback(async () => {
if (!sessionId || session?.agentKind !== 'codex') return;
- if (!ownsWindowRoute) {
+ if (!canNavigateSession) {
log.info('encrypted-session fork ignored by embedded sidebar view', { sessionId });
return;
}
+ const forkStripNavigationVersion = ++sessionNavigationVersionRef.current;
setForkStripEncryptedRunning(true);
try {
const newSession = await sessionService.forkStripEncrypted(sessionId);
@@ -2798,6 +2852,8 @@ export function CCAgentSessionView({
// 远程会话:新会话在被控端,先重拉该设备会话列表注册新 sessionId 再 navigate(否则 404)。
const deviceId = getSessionDeviceId(sessionId);
if (deviceId) await refreshRemoteDeviceSessions(deviceId);
+ if (sessionNavigationVersionRef.current !== forkStripNavigationVersion) return;
+ onSessionNavigate?.(newSession.id, newSession.id);
navigate(`/cc-agent/${newSession.id}`);
} catch (err) {
const ipcError = extractIpcError(err);
@@ -2812,7 +2868,15 @@ export function CCAgentSessionView({
} finally {
setForkStripEncryptedRunning(false);
}
- }, [navigate, ownsWindowRoute, refreshServerSession, session?.agentKind, sessionId, t]);
+ }, [
+ canNavigateSession,
+ navigate,
+ onSessionNavigate,
+ refreshServerSession,
+ session?.agentKind,
+ sessionId,
+ t,
+ ]);
// M35: Vendor fallback —— 会话的 model 与它(固定不变的)agent vendor 明确错配时,
// 回退到该 vendor 的默认模型。守的是「绕过模型选择器写入 session.model」的脏数据路径
@@ -3216,11 +3280,9 @@ export function CCAgentSessionView({
// in that case so the card catches scroll/click events without a wrapper
// swap that would flash the layout.
<>
- {/* ContentHeader 注入:仅路由直挂实例(无 sessionIdProp)注册会话标题
- 到右栏顶栏;内嵌实例(workdir-browse chat rail / Orca 面板)不注册,
- 避免覆盖路由主实例的 header。渲染为 null,不影响布局。
- 见 SessionContentHeaderRegistration。 */}
- {!sessionIdProp && !isCompactRail && !isOrcaMode && session && (
+ {/* ContentHeader 注入:仅 ownsRoute 实例注册。普通路由仍由历史判据获得主权;
+ SplitGroup 则把主权交给活动 pane,非活动 pane 不覆盖 header。 */}
+ {ownsRoute && session && (
<SessionContentHeaderRegistration
session={session}
remoteSessionUnavailable={remoteSessionUnavailable}
@@ -3254,23 +3316,27 @@ export function CCAgentSessionView({
className="relative flex h-full w-full flex-col bg-content-area"
aria-label={t('ccAgent.layout.chatDropAreaAria')}
onDragEnter={(e) => {
+ if (hasSplitGroupSessionType(e.dataTransfer.types)) return;
e.preventDefault();
e.stopPropagation();
dragCounterRef.current += 1;
if (dragCounterRef.current === 1) setIsDragOver(true);
}}
onDragOver={(e) => {
+ if (hasSplitGroupSessionType(e.dataTransfer.types)) return;
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'copy';
}}
onDragLeave={(e) => {
+ if (hasSplitGroupSessionType(e.dataTransfer.types)) return;
e.preventDefault();
e.stopPropagation();
dragCounterRef.current -= 1;
if (dragCounterRef.current === 0) setIsDragOver(false);
}}
onDrop={(e) => {
+ if (hasSplitGroupSessionType(e.dataTransfer.types)) return;
e.preventDefault();
e.stopPropagation();
dragCounterRef.current = 0;
@@ -3558,7 +3624,7 @@ export function CCAgentSessionView({
canSwitchToClaudeSubscription ? handleSwitchToClaudeSubscription : undefined
}
silentEncryptedRetryEnabled={silentEncryptedRetryEnabled}
- onForkStripEncrypted={ownsWindowRoute ? handleForkStripEncrypted : undefined}
+ onForkStripEncrypted={canNavigateSession ? handleForkStripEncrypted : undefined}
forkStripEncryptedRunning={forkStripEncryptedRunning}
style={{ width: inputWidth }}
className="py-1"
@@ -3606,7 +3672,7 @@ export function CCAgentSessionView({
onViewBalance={canAccessBilling ? handleViewBalance : undefined}
errorSourceProviderId={liveErrorSourceProviderId}
silentEncryptedRetryEnabled={silentEncryptedRetryEnabled}
- onForkStripEncrypted={ownsWindowRoute ? handleForkStripEncrypted : undefined}
+ onForkStripEncrypted={canNavigateSession ? handleForkStripEncrypted : undefined}
forkStripEncryptedRunning={forkStripEncryptedRunning}
style={{ width: inputWidth }}
className="py-1"
@@ -3828,7 +3894,7 @@ export function CCAgentSessionView({
// doc 模式右栏:不抢焦点,避免 TipTap contenteditable 激活
// Windows 中文 IME 后,Ctrl+Shift+F 等组合键被 OS 层吞掉。
// 详见 ChatInput 的 disableAutofocus prop 注释。
- disableAutofocus={isCompactRail}
+ disableAutofocus={isCompactRail || disableAutofocus}
focusOnStorageKeyChange={ownsRoute}
// F-COLLAB:「+」菜单里的协同模式项。普通 Lead 的项目/对话会话都渲染,
// 项目级与用户级策略范围由 collabEntry 决定;只排除 Worker 子会话
@@ -4076,11 +4142,14 @@ export function CCAgentSessionView({
能流到。content 内同时包含两者,所以包在外层即可。 */}
<SessionNavigationModeProvider
mode={navigationMode}
+ onSessionNavigate={onSessionNavigate}
sidebarTargetSessionId={sidebarTargetSessionId}
- // 只有声明右栏在场的路由主实例(ownsRoute)才是面板宿主:右栏当前显示的
- // 就是它的 bucket。内嵌实例(worker 面板 / 文件浏览窄 rail / Orca split)
- // 传 undefined → 面板类入口自行降级,见 useSidebarPanelReachable。
- sidebarPanelHostSessionId={ownsRoute ? sessionId : undefined}
+ // 路由主实例的 bucket 当前可见;可见 split pane 会在点击前先接管路由,
+ // 因而自己的 bucket 对本次面板动作同样可达。其它内嵌实例(worker 面板 /
+ // 文件浏览窄 rail / Orca split)仍传 undefined,让入口安全降级。
+ sidebarPanelHostSessionId={
+ ownsRoute || navigationMode === 'split-pane' ? sessionId : undefined
+ }
>
<ChatDisplaySnapshotProvider value={chatDisplaySnapshot}>
<TopRightChipStackProvider>{content}</TopRightChipStackProvider>
diff --git a/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsx b/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsx
new file mode 100644
index 0000000000..a4a2152aac
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsx
@@ -0,0 +1,1038 @@
+/**
+ * SplitGroup — `chat-main` 内部的同窗多任务递归分栏。
+ *
+ * 全局布局树仍只有一个 `chat-main`;本组件在其内部渲染二叉分屏树。每个 pane
+ * 都可再次向四边拆分,因此支持左一右二、左二右二及更深的混合布局。
+ */
+
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type DragEvent,
+ type KeyboardEvent as ReactKeyboardEvent,
+ type PointerEvent as ReactPointerEvent,
+ type ReactNode,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+import { Columns2, Rows2, X } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
+
+import { cn } from '@/lib/utils';
+import { useCCSessions } from '@/hooks/useCCSessions';
+import {
+ useRemoteBootstrapFailedDeviceIds,
+ useRemoteBootstrapLoadingDeviceIds,
+ useRemoteProjectSessions,
+} from '@/features/device-link/remoteProjectsStore';
+import { ApiError } from '@/lib/httpClient';
+import { getSessionFor } from '@/lib/makerTransport';
+import { getSessionRouteOwnerId, resolveSessionRoute } from '@/lib/orcaSessionIdentity';
+import { toast } from '@/lib/toast';
+import { extractIpcError } from '@/utils/ipcError';
+import { getSessionDisplayTitle } from './lib/sessionDisplayTitle';
+import { CCAgentSessionView } from './CCAgentSessionView';
+import { mergeSessionSources } from './lib/mergeSessionSources';
+import {
+ SPLIT_GROUP_SESSION_MIME,
+ hasSplitGroupSessionType,
+ resolveSplitDropSide,
+} from './splitGroupDnd';
+import {
+ getSplitPanes,
+ MAX_SPLIT_PANES,
+ MIN_SPLIT_CHILD_FRACTION,
+ splitGroupStore,
+ useSplitGroup,
+ type DropSide,
+ type SplitGroupAddBlockReason,
+ type SplitBranchNode,
+ type SplitNode,
+ type SplitPaneNode,
+} from './splitGroupStore';
+
+const GUTTER_PX = 6;
+const KEYBOARD_RESIZE_STEP = 0.05;
+const MIN_SPLIT_PANE_WIDTH_PX = 280;
+const MIN_SPLIT_PANE_HEIGHT_PX = 220;
+const DEFAULT_SPLIT_VIEWPORT_WIDTH_PX = 800;
+const DEFAULT_SPLIT_VIEWPORT_HEIGHT_PX = 600;
+
+function isSplitPaneNoFocusTarget(target: EventTarget | null): boolean {
+ const element = target instanceof Element ? target : null;
+ return Boolean(element?.closest('[data-split-pane-no-focus], [data-split-pane-route-action]'));
+}
+
+function showSplitAddBlocked(
+ t: ReturnType<typeof useTranslation>['t'],
+ reason: SplitGroupAddBlockReason | null,
+): void {
+ if (reason === 'limit-reached') {
+ toast.warning(t('splitGroup.limitReached', { count: MAX_SPLIT_PANES }));
+ return;
+ }
+ if (reason === 'duplicate') {
+ toast.warning(t('splitGroup.alreadyOpen'));
+ return;
+ }
+ toast.warning(t('splitGroup.addUnavailable'));
+}
+
+interface SplitGroupProps {
+ children: ReactNode;
+ /** 仅 `/cc-agent/:sessionId` 传值;其它功能路由保持原样,不展示持久分屏。 */
+ activeSessionId?: string;
+}
+
+export function SplitGroup({ children, activeSessionId }: SplitGroupProps) {
+ const { t } = useTranslation();
+ const group = useSplitGroup();
+ const navigate = useNavigate();
+ const paneCount = getSplitPanes(group.root).length;
+ const staleRecoveryActiveSessionIdRef = useRef(activeSessionId);
+ const staleRecoverySequenceRef = useRef(0);
+ // SplitGroupActive 卸载于 `/cc-agent/new`,但外层 layout 仍然常驻。保留最近一次
+ // 真正位于分屏树中的路由 owner,避免新任务创建后重新挂载时退回替换 panes[0]。
+ const lastActiveSessionIdRef = useRef(activeSessionId);
+
+ useLayoutEffect(() => {
+ if (
+ activeSessionId &&
+ getSplitPanes(group.root).some((pane) => pane.sessionId === activeSessionId)
+ ) {
+ lastActiveSessionIdRef.current = activeSessionId;
+ }
+ }, [activeSessionId, group.root]);
+
+ useLayoutEffect(() => {
+ if (staleRecoveryActiveSessionIdRef.current !== activeSessionId) {
+ staleRecoveryActiveSessionIdRef.current = activeSessionId;
+ staleRecoverySequenceRef.current += 1;
+ }
+ }, [activeSessionId]);
+
+ useEffect(
+ () => () => {
+ staleRecoverySequenceRef.current += 1;
+ },
+ [],
+ );
+
+ const focusSession = useCallback(
+ (sessionId: string) => {
+ void resolveSessionRoute(sessionId).then((route) => navigate(route));
+ },
+ [navigate],
+ );
+
+ if (!activeSessionId) return <>{children}</>;
+
+ if (!group.root || paneCount < 2) {
+ return (
+ <SplitDropTarget
+ anchorSessionId={activeSessionId}
+ className="relative flex min-h-0 flex-1 flex-col overflow-hidden"
+ dataAttribute="single"
+ onSessionDropped={(sessionId, side) => {
+ if (splitGroupStore.addSession(sessionId, activeSessionId, side)) {
+ focusSession(sessionId);
+ } else {
+ showSplitAddBlocked(t, splitGroupStore.getAddBlockReason(sessionId, activeSessionId));
+ }
+ }}
+ >
+ {children}
+ </SplitDropTarget>
+ );
+ }
+
+ return (
+ <SplitGroupActive
+ activeSessionId={activeSessionId}
+ root={group.root}
+ previousActiveSessionId={lastActiveSessionIdRef.current}
+ staleRecoverySequenceRef={staleRecoverySequenceRef}
+ />
+ );
+}
+
+interface SplitGroupActiveProps {
+ activeSessionId: string;
+ previousActiveSessionId?: string;
+ root: SplitNode;
+ staleRecoverySequenceRef: { current: number };
+}
+
+function SplitGroupActive({
+ activeSessionId,
+ previousActiveSessionId,
+ root,
+ staleRecoverySequenceRef,
+}: SplitGroupActiveProps) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const {
+ sessions: localSessions,
+ isLoading: localSessionsLoading,
+ error: localSessionsError,
+ } = useCCSessions({ includeArchived: 'all' });
+ const remoteSessions = useRemoteProjectSessions();
+ const remoteBootstrapLoadingDeviceIds = useRemoteBootstrapLoadingDeviceIds();
+ const remoteBootstrapFailedDeviceIds = useRemoteBootstrapFailedDeviceIds();
+ const sessions = useMemo(
+ () => mergeSessionSources(localSessions, remoteSessions),
+ [localSessions, remoteSessions],
+ );
+ const sessionsById = useMemo(
+ () => new Map(sessions.map((session) => [session.id, session])),
+ [sessions],
+ );
+ const panes = useMemo(() => getSplitPanes(root), [root]);
+ const sessionsCatalogReady =
+ !localSessionsLoading &&
+ !localSessionsError &&
+ remoteBootstrapLoadingDeviceIds.size === 0 &&
+ remoteBootstrapFailedDeviceIds.size === 0;
+
+ const previousActiveSessionIdRef = useRef(previousActiveSessionId ?? activeSessionId);
+ const observedActiveSessionIdRef = useRef(activeSessionId);
+ const pendingFocusSessionIdRef = useRef<string | null>(null);
+ const focusRequestSequenceRef = useRef(0);
+ const resolvedRouteOwnersRef = useRef(new Map<number, string>());
+ const confirmedStaleRouteOwnerRef = useRef<string | null>(null);
+ const pendingOwnerCloseRef = useRef<{
+ sourceSessionId: string;
+ targetSessionId: string;
+ requestSequence: number;
+ routeOwnerSessionId?: string;
+ } | null>(null);
+ const pendingPaneNavigationRef = useRef<{
+ sourceSessionId: string;
+ targetSessionId: string;
+ routeOwnerSessionId: string;
+ } | null>(null);
+ const routePane = panes.find((pane) => pane.sessionId === activeSessionId);
+ const previousPane = panes.find((pane) => pane.sessionId === previousActiveSessionIdRef.current);
+ const ownerPaneKey = routePane?.key ?? previousPane?.key ?? panes[0]?.key;
+
+ useEffect(() => {
+ if (!sessionsCatalogReady) return;
+ const missingSessionIds = panes
+ .map((pane) => pane.sessionId)
+ .filter((sessionId) => !sessionsById.has(sessionId));
+ if (missingSessionIds.length === 0) return;
+ let cancelled = false;
+
+ // The merged catalog is eventually consistent while local refreshes and
+ // device-link mirrors rebuild. Only prune after the session's owning side
+ // confirms the pane is no longer active or is absent; getSessionFor
+ // preserves remote routing.
+ void Promise.all(
+ missingSessionIds.map(async (sessionId) => {
+ try {
+ const session = await getSessionFor(sessionId);
+ return session.status === 'archived' || session.status === 'deleted' ? sessionId : null;
+ } catch (error) {
+ const errorCode = error instanceof ApiError ? error.code : extractIpcError(error)?.code;
+ return errorCode === 'NOT_FOUND' ? sessionId : null;
+ }
+ }),
+ ).then((staleSessionIds) => {
+ if (cancelled) return;
+ const confirmedStaleSessionIds = staleSessionIds.filter((sessionId): sessionId is string =>
+ Boolean(sessionId && !sessionsById.has(sessionId)),
+ );
+ if (confirmedStaleSessionIds.includes(activeSessionId)) {
+ confirmedStaleRouteOwnerRef.current = activeSessionId;
+ const survivor = panes.find((pane) => !confirmedStaleSessionIds.includes(pane.sessionId));
+ if (survivor) {
+ const recoverySequence = staleRecoverySequenceRef.current;
+ void resolveSessionRoute(survivor.sessionId, sessionsById.get(survivor.sessionId) ?? null)
+ .then((route) => {
+ if (staleRecoverySequenceRef.current === recoverySequence) {
+ navigate(route, { replace: true });
+ }
+ })
+ .catch(() => {
+ if (staleRecoverySequenceRef.current === recoverySequence) {
+ navigate('/cc-agent', { replace: true });
+ }
+ });
+ } else {
+ navigate('/cc-agent', { replace: true });
+ }
+ }
+ for (const sessionId of confirmedStaleSessionIds) {
+ splitGroupStore.removeSession(sessionId);
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [activeSessionId, navigate, panes, sessionsById, sessionsCatalogReady]);
+
+ useEffect(
+ () => () => {
+ focusRequestSequenceRef.current += 1;
+ pendingFocusSessionIdRef.current = null;
+ pendingOwnerCloseRef.current = null;
+ resolvedRouteOwnersRef.current.clear();
+ confirmedStaleRouteOwnerRef.current = null;
+ },
+ [],
+ );
+
+ const focusSession = useCallback(
+ (sessionId: string) => {
+ if (!sessionId || sessionId === activeSessionId) {
+ return null;
+ }
+ if (pendingFocusSessionIdRef.current === sessionId) {
+ return focusRequestSequenceRef.current;
+ }
+ if (pendingOwnerCloseRef.current?.targetSessionId !== sessionId) {
+ pendingOwnerCloseRef.current = null;
+ }
+ const requestSequence = ++focusRequestSequenceRef.current;
+ pendingFocusSessionIdRef.current = sessionId;
+ const session = sessionsById.get(sessionId) ?? null;
+ void resolveSessionRoute(sessionId, session)
+ .then((route) => {
+ if (focusRequestSequenceRef.current !== requestSequence) return;
+ const routeOwnerSessionId = getSessionRouteOwnerId(route) ?? sessionId;
+ resolvedRouteOwnersRef.current.set(requestSequence, routeOwnerSessionId);
+ if (pendingOwnerCloseRef.current?.requestSequence === requestSequence) {
+ pendingOwnerCloseRef.current.routeOwnerSessionId = routeOwnerSessionId;
+ }
+ navigate(route);
+ })
+ .catch(() => {
+ if (focusRequestSequenceRef.current === requestSequence) {
+ pendingFocusSessionIdRef.current = null;
+ if (pendingOwnerCloseRef.current?.requestSequence === requestSequence) {
+ pendingOwnerCloseRef.current = null;
+ }
+ }
+ });
+ return requestSequence;
+ },
+ [activeSessionId, navigate, sessionsById],
+ );
+
+ useLayoutEffect(() => {
+ if (
+ confirmedStaleRouteOwnerRef.current &&
+ confirmedStaleRouteOwnerRef.current !== activeSessionId
+ ) {
+ confirmedStaleRouteOwnerRef.current = null;
+ }
+ const pendingFocusSessionId = pendingFocusSessionIdRef.current;
+ const activeSessionChanged = observedActiveSessionIdRef.current !== activeSessionId;
+ observedActiveSessionIdRef.current = activeSessionId;
+ const pendingOwnerClose = pendingOwnerCloseRef.current;
+ const matchingResolvedSequences = [...resolvedRouteOwnersRef.current.entries()]
+ .filter(([, routeOwnerSessionId]) => routeOwnerSessionId === activeSessionId)
+ .map(([requestSequence]) => requestSequence);
+ const latestMatchingResolvedSequence =
+ matchingResolvedSequences.length > 0 ? Math.max(...matchingResolvedSequences) : null;
+ const pendingFocusReachedRouteOwner =
+ pendingOwnerClose?.requestSequence === focusRequestSequenceRef.current &&
+ pendingOwnerClose.routeOwnerSessionId === activeSessionId;
+ const currentFocusReachedRouteOwner =
+ latestMatchingResolvedSequence === focusRequestSequenceRef.current;
+ if (
+ pendingFocusSessionId === activeSessionId ||
+ pendingFocusReachedRouteOwner ||
+ currentFocusReachedRouteOwner
+ ) {
+ pendingFocusSessionIdRef.current = null;
+ } else if (pendingFocusSessionId && activeSessionChanged) {
+ const isOlderFocusCommit =
+ latestMatchingResolvedSequence !== null &&
+ latestMatchingResolvedSequence < focusRequestSequenceRef.current;
+ if (!isOlderFocusCommit) {
+ pendingFocusSessionIdRef.current = null;
+ focusRequestSequenceRef.current += 1;
+ }
+ }
+ for (const requestSequence of matchingResolvedSequences) {
+ resolvedRouteOwnersRef.current.delete(requestSequence);
+ }
+
+ if (
+ pendingOwnerClose &&
+ (!panes.some((pane) => pane.sessionId === pendingOwnerClose.targetSessionId) ||
+ pendingOwnerClose.requestSequence !== focusRequestSequenceRef.current)
+ ) {
+ pendingOwnerCloseRef.current = null;
+ if (pendingFocusSessionIdRef.current === pendingOwnerClose.targetSessionId) {
+ pendingFocusSessionIdRef.current = null;
+ focusRequestSequenceRef.current += 1;
+ }
+ } else if (pendingOwnerClose?.routeOwnerSessionId === activeSessionId) {
+ // Keep the route owner in the tree until its navigation request has committed.
+ // Removing it earlier lets route reconciliation restore the pane just closed.
+ pendingOwnerCloseRef.current = null;
+ if (panes.some((pane) => pane.sessionId === pendingOwnerClose.sourceSessionId)) {
+ splitGroupStore.removeSession(pendingOwnerClose.sourceSessionId);
+ }
+ return;
+ }
+
+ if (panes.some((pane) => pane.sessionId === activeSessionId)) {
+ previousActiveSessionIdRef.current = activeSessionId;
+ if (pendingPaneNavigationRef.current?.routeOwnerSessionId === activeSessionId) {
+ pendingPaneNavigationRef.current = null;
+ }
+ return;
+ }
+
+ if (confirmedStaleRouteOwnerRef.current === activeSessionId) return;
+
+ const pendingPaneNavigation = pendingPaneNavigationRef.current;
+ pendingPaneNavigationRef.current = null;
+ const pendingNavigationMatchesRoute =
+ pendingPaneNavigation?.routeOwnerSessionId === activeSessionId;
+ const pendingNavigationSourceExists = Boolean(
+ pendingPaneNavigation &&
+ panes.some((pane) => pane.sessionId === pendingPaneNavigation.sourceSessionId),
+ );
+ if (pendingNavigationMatchesRoute && !pendingNavigationSourceExists) {
+ // The child action resolved after its source pane was removed. Do not let
+ // the stale intent fall through and replace the current owner pane.
+ return;
+ }
+ const pendingSource =
+ pendingNavigationMatchesRoute && pendingNavigationSourceExists
+ ? pendingPaneNavigation.sourceSessionId
+ : null;
+ const replaceTarget =
+ pendingSource ??
+ (panes.some((pane) => pane.sessionId === previousActiveSessionIdRef.current)
+ ? previousActiveSessionIdRef.current
+ : panes[0]?.sessionId);
+ if (replaceTarget) {
+ splitGroupStore.replaceSession(replaceTarget, activeSessionId);
+ previousActiveSessionIdRef.current = activeSessionId;
+ }
+ }, [activeSessionId, panes]);
+
+ const handlePaneSessionNavigate = useCallback(
+ (sourceSessionId: string, targetSessionId: string, routeOwnerSessionId?: string) => {
+ // Child route actions (session links, handoff cards, encrypted recovery) are
+ // allowed to focus their pane on pointer/keyboard entry, but once the child
+ // announces its own target, suppress that pending source-pane navigation so
+ // it cannot race and overwrite the target route.
+ pendingFocusSessionIdRef.current = null;
+ focusRequestSequenceRef.current += 1;
+ pendingOwnerCloseRef.current = null;
+ pendingPaneNavigationRef.current = {
+ sourceSessionId,
+ targetSessionId,
+ routeOwnerSessionId: routeOwnerSessionId ?? targetSessionId,
+ };
+ },
+ [],
+ );
+
+ const handleClosePane = useCallback(
+ (pane: SplitPaneNode, isOwner: boolean) => {
+ if (pendingOwnerCloseRef.current?.targetSessionId === pane.sessionId) {
+ pendingOwnerCloseRef.current = null;
+ }
+ if (pendingFocusSessionIdRef.current === pane.sessionId) {
+ pendingFocusSessionIdRef.current = null;
+ focusRequestSequenceRef.current += 1;
+ }
+ if (isOwner) {
+ const paneIndex = panes.findIndex((candidate) => candidate.key === pane.key);
+ const targetPane = panes[paneIndex + 1] ?? panes[paneIndex - 1];
+ if (targetPane) {
+ const requestSequence = focusSession(targetPane.sessionId);
+ if (requestSequence === null) return;
+ pendingOwnerCloseRef.current = {
+ sourceSessionId: pane.sessionId,
+ targetSessionId: targetPane.sessionId,
+ requestSequence,
+ routeOwnerSessionId: resolvedRouteOwnersRef.current.get(requestSequence),
+ };
+ return;
+ }
+ }
+ splitGroupStore.removeSession(pane.sessionId);
+ },
+ [focusSession, panes],
+ );
+
+ return (
+ <div
+ data-split-group="active"
+ data-split-root-direction={root.type === 'split' ? root.direction : undefined}
+ className="flex min-h-0 flex-1 flex-col overflow-hidden bg-content-area"
+ >
+ <SplitGroupToolbar root={root} />
+ <div className="min-h-0 flex-1 overflow-hidden">
+ <SplitGroupCanvas
+ root={root}
+ activeSessionId={activeSessionId}
+ ownerPaneKey={ownerPaneKey}
+ sessionsById={sessionsById}
+ focusSession={focusSession}
+ onSessionNavigate={handlePaneSessionNavigate}
+ onClosePane={handleClosePane}
+ unnamedTitle={t('ccAgent.common.unnamedSession')}
+ loadingTitle={t('splitGroup.loadingTask')}
+ />
+ </div>
+ </div>
+ );
+}
+
+interface SplitPaneSharedProps {
+ activeSessionId: string;
+ ownerPaneKey?: string;
+ sessionsById: Map<string, ReturnType<typeof useCCSessions>['sessions'][number]>;
+ focusSession: (sessionId: string) => void;
+ onSessionNavigate: (
+ sourceSessionId: string,
+ targetSessionId: string,
+ routeOwnerSessionId?: string,
+ ) => void;
+ onClosePane: (pane: SplitPaneNode, isOwner: boolean) => void;
+ unnamedTitle: string;
+ loadingTitle: string;
+}
+
+interface SplitLayoutRect {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+interface SplitPaneLayout {
+ pane: SplitPaneNode;
+ rect: SplitLayoutRect;
+}
+
+interface SplitBranchLayout {
+ branch: SplitBranchNode;
+ rect: SplitLayoutRect;
+ firstAxisSize: number;
+ displayedFraction: number;
+}
+
+interface SplitRequiredSize {
+ width: number;
+ height: number;
+}
+
+function getSplitRequiredSize(node: SplitNode): SplitRequiredSize {
+ if (node.type === 'pane') {
+ return { width: MIN_SPLIT_PANE_WIDTH_PX, height: MIN_SPLIT_PANE_HEIGHT_PX };
+ }
+ const first = getSplitRequiredSize(node.first);
+ const second = getSplitRequiredSize(node.second);
+ return node.direction === 'row'
+ ? {
+ width: first.width + GUTTER_PX + second.width,
+ height: Math.max(first.height, second.height),
+ }
+ : {
+ width: Math.max(first.width, second.width),
+ height: first.height + GUTTER_PX + second.height,
+ };
+}
+
+function resolveSplitLayout(
+ node: SplitNode,
+ rect: SplitLayoutRect,
+ liveResize: { splitKey: string; fraction: number } | null,
+ paneLayouts: SplitPaneLayout[],
+ branchLayouts: SplitBranchLayout[],
+): void {
+ if (node.type === 'pane') {
+ paneLayouts.push({ pane: node, rect });
+ return;
+ }
+
+ const isRow = node.direction === 'row';
+ const axisSize = Math.max(0, (isRow ? rect.width : rect.height) - GUTTER_PX);
+ const firstRequired = getSplitRequiredSize(node.first);
+ const secondRequired = getSplitRequiredSize(node.second);
+ const firstMinimum = isRow ? firstRequired.width : firstRequired.height;
+ const secondMinimum = isRow ? secondRequired.width : secondRequired.height;
+ const requestedFraction = liveResize?.splitKey === node.key ? liveResize.fraction : node.fraction;
+ const requestedFirstSize = axisSize * requestedFraction;
+ const maximumFirstSize = Math.max(firstMinimum, axisSize - secondMinimum);
+ const firstAxisSize = Math.min(maximumFirstSize, Math.max(firstMinimum, requestedFirstSize));
+ const normalizedFirstAxisSize = Math.max(0, Math.min(axisSize, firstAxisSize));
+ const displayedFraction = axisSize > 0 ? normalizedFirstAxisSize / axisSize : requestedFraction;
+ branchLayouts.push({
+ branch: node,
+ rect,
+ firstAxisSize: normalizedFirstAxisSize,
+ displayedFraction,
+ });
+
+ const firstRect: SplitLayoutRect = isRow
+ ? { ...rect, width: normalizedFirstAxisSize }
+ : { ...rect, height: normalizedFirstAxisSize };
+ const secondRect: SplitLayoutRect = isRow
+ ? {
+ ...rect,
+ left: rect.left + normalizedFirstAxisSize + GUTTER_PX,
+ width: Math.max(0, axisSize - normalizedFirstAxisSize),
+ }
+ : {
+ ...rect,
+ top: rect.top + normalizedFirstAxisSize + GUTTER_PX,
+ height: Math.max(0, axisSize - normalizedFirstAxisSize),
+ };
+ resolveSplitLayout(node.first, firstRect, liveResize, paneLayouts, branchLayouts);
+ resolveSplitLayout(node.second, secondRect, liveResize, paneLayouts, branchLayouts);
+}
+
+function SplitGroupCanvas({ root, ...paneProps }: SplitPaneSharedProps & { root: SplitNode }) {
+ const viewportRef = useRef<HTMLDivElement>(null);
+ const [viewportSize, setViewportSize] = useState({
+ width: DEFAULT_SPLIT_VIEWPORT_WIDTH_PX,
+ height: DEFAULT_SPLIT_VIEWPORT_HEIGHT_PX,
+ });
+ const [liveResize, setLiveResize] = useState<{
+ splitKey: string;
+ fraction: number;
+ } | null>(null);
+
+ useLayoutEffect(() => {
+ const viewport = viewportRef.current;
+ if (!viewport) return;
+ const updateSize = () => {
+ const rect = viewport.getBoundingClientRect();
+ const width = Math.max(0, viewport.clientWidth || rect.width);
+ const height = Math.max(0, viewport.clientHeight || rect.height);
+ if (width === 0 || height === 0) return;
+ setViewportSize((current) =>
+ current.width === width && current.height === height ? current : { width, height },
+ );
+ };
+ updateSize();
+ if (typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(updateSize);
+ observer.observe(viewport);
+ return () => observer.disconnect();
+ }, []);
+
+ const requiredSize = useMemo(() => getSplitRequiredSize(root), [root]);
+ const canvasSize = {
+ width: Math.max(viewportSize.width, requiredSize.width),
+ height: Math.max(viewportSize.height, requiredSize.height),
+ };
+ const { paneLayouts, branchLayouts } = useMemo(() => {
+ const nextPaneLayouts: SplitPaneLayout[] = [];
+ const nextBranchLayouts: SplitBranchLayout[] = [];
+ resolveSplitLayout(
+ root,
+ { left: 0, top: 0, width: canvasSize.width, height: canvasSize.height },
+ liveResize,
+ nextPaneLayouts,
+ nextBranchLayouts,
+ );
+ return { paneLayouts: nextPaneLayouts, branchLayouts: nextBranchLayouts };
+ }, [canvasSize.height, canvasSize.width, liveResize, root]);
+
+ useEffect(() => {
+ if (liveResize && !branchLayouts.some((layout) => layout.branch.key === liveResize.splitKey)) {
+ setLiveResize(null);
+ }
+ }, [branchLayouts, liveResize]);
+
+ return (
+ <div ref={viewportRef} className="h-full min-h-0 w-full min-w-0 overflow-auto">
+ <div
+ data-split-canvas
+ className="relative"
+ style={{ width: canvasSize.width, height: canvasSize.height }}
+ >
+ {paneLayouts.map(({ pane, rect }) => (
+ <div key={pane.key} className="absolute overflow-hidden" style={rect}>
+ <SplitPaneView {...paneProps} pane={pane} />
+ </div>
+ ))}
+ {branchLayouts.map((layout) => (
+ <SplitGutter
+ key={layout.branch.key}
+ {...layout}
+ onLiveFraction={(fraction) => setLiveResize({ splitKey: layout.branch.key, fraction })}
+ onCommit={(fraction) => {
+ setLiveResize(null);
+ splitGroupStore.setSplitFraction(layout.branch.key, fraction);
+ }}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function SplitGutter({
+ branch,
+ rect,
+ firstAxisSize,
+ displayedFraction,
+ onLiveFraction,
+ onCommit,
+}: SplitBranchLayout & {
+ onLiveFraction: (fraction: number) => void;
+ onCommit: (fraction: number) => void;
+}) {
+ const { t } = useTranslation();
+ const containerRef = useRef<HTMLDivElement>(null);
+ const resizeCleanupRef = useRef<(() => void) | null>(null);
+ const liveFractionRef = useRef<number | null>(null);
+ const isRow = branch.direction === 'row';
+
+ useEffect(
+ () => () => {
+ resizeCleanupRef.current?.();
+ document.body.classList.remove('resizing-pane');
+ },
+ [],
+ );
+
+ const handleGutterPointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ const container = containerRef.current;
+ if (!container) return;
+ const rect = container.getBoundingClientRect();
+ const totalAxisSize = (isRow ? rect.width : rect.height) - GUTTER_PX;
+ if (totalAxisSize <= 0) return;
+
+ resizeCleanupRef.current?.();
+ const startPosition = isRow ? event.clientX : event.clientY;
+ const baseFraction = displayedFraction;
+ document.body.classList.add('resizing-pane');
+
+ const handlePointerMove = (pointerEvent: PointerEvent) => {
+ const position = isRow ? pointerEvent.clientX : pointerEvent.clientY;
+ const raw = baseFraction + (position - startPosition) / totalAxisSize;
+ const clamped = Math.min(
+ 1 - MIN_SPLIT_CHILD_FRACTION,
+ Math.max(MIN_SPLIT_CHILD_FRACTION, raw),
+ );
+ liveFractionRef.current = clamped;
+ onLiveFraction(clamped);
+ };
+
+ const finishResize = () => {
+ if (resizeCleanupRef.current !== finishResize) return;
+ document.removeEventListener('pointermove', handlePointerMove);
+ document.removeEventListener('pointerup', finishResize);
+ document.removeEventListener('pointercancel', finishResize);
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
+ window.removeEventListener('blur', finishResize);
+ document.body.classList.remove('resizing-pane');
+ resizeCleanupRef.current = null;
+ const finalFraction = liveFractionRef.current;
+ liveFractionRef.current = null;
+ if (finalFraction !== null) onCommit(finalFraction);
+ };
+
+ const handleVisibilityChange = () => {
+ if (document.visibilityState === 'hidden') finishResize();
+ };
+
+ resizeCleanupRef.current = finishResize;
+ document.addEventListener('pointermove', handlePointerMove);
+ document.addEventListener('pointerup', finishResize);
+ document.addEventListener('pointercancel', finishResize);
+ document.addEventListener('visibilitychange', handleVisibilityChange);
+ window.addEventListener('blur', finishResize);
+ },
+ [displayedFraction, isRow, onCommit, onLiveFraction],
+ );
+
+ const handleGutterKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ const decreaseKey = isRow ? 'ArrowLeft' : 'ArrowUp';
+ const increaseKey = isRow ? 'ArrowRight' : 'ArrowDown';
+ let nextFraction: number | null = null;
+ if (event.key === decreaseKey) nextFraction = displayedFraction - KEYBOARD_RESIZE_STEP;
+ else if (event.key === increaseKey) nextFraction = displayedFraction + KEYBOARD_RESIZE_STEP;
+ else if (event.key === 'Home') nextFraction = 0;
+ else if (event.key === 'End') nextFraction = 1;
+ if (nextFraction === null) return;
+ event.preventDefault();
+ onCommit(nextFraction);
+ },
+ [displayedFraction, isRow, onCommit],
+ );
+
+ return (
+ <div
+ ref={containerRef}
+ data-split-branch={branch.key}
+ data-split-direction={branch.direction}
+ className="pointer-events-none absolute"
+ style={rect}
+ >
+ <div
+ role="separator"
+ tabIndex={0}
+ aria-orientation={isRow ? 'vertical' : 'horizontal'}
+ aria-label={t('splitGroup.resizeAria')}
+ aria-valuemin={Math.round(MIN_SPLIT_CHILD_FRACTION * 100)}
+ aria-valuemax={Math.round((1 - MIN_SPLIT_CHILD_FRACTION) * 100)}
+ aria-valuenow={Math.round(displayedFraction * 100)}
+ onPointerDown={handleGutterPointerDown}
+ onKeyDown={handleGutterKeyDown}
+ className={cn(
+ 'pointer-events-auto absolute shrink-0 bg-border/50 transition-colors hover:bg-foreground/20',
+ 'focus-visible:bg-foreground/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]',
+ isRow ? 'cursor-col-resize' : 'cursor-row-resize',
+ )}
+ style={
+ isRow
+ ? { left: firstAxisSize, top: 0, width: GUTTER_PX, height: rect.height }
+ : { left: 0, top: firstAxisSize, width: rect.width, height: GUTTER_PX }
+ }
+ />
+ </div>
+ );
+}
+
+const SplitPaneView = memo(function SplitPaneView({
+ pane,
+ ownerPaneKey,
+ sessionsById,
+ focusSession,
+ onSessionNavigate,
+ onClosePane,
+ unnamedTitle,
+ loadingTitle,
+}: SplitPaneSharedProps & { pane: SplitPaneNode }) {
+ const { t } = useTranslation();
+ const isOwner = pane.key === ownerPaneKey;
+ const viewSessionId = pane.sessionId;
+ const session = sessionsById.get(viewSessionId) ?? null;
+ const title = session ? getSessionDisplayTitle(session, unnamedTitle) : loadingTitle;
+
+ return (
+ <SplitDropTarget
+ anchorSessionId={pane.sessionId}
+ className="relative h-full min-h-0 min-w-0 overflow-hidden"
+ dataAttribute="pane"
+ onSessionDropped={(sessionId, side) => {
+ if (splitGroupStore.addSession(sessionId, pane.sessionId, side)) {
+ focusSession(sessionId);
+ } else {
+ showSplitAddBlocked(t, splitGroupStore.getAddBlockReason(sessionId, pane.sessionId));
+ }
+ }}
+ >
+ <div
+ data-split-pane-key={pane.key}
+ data-split-pane-session-id={viewSessionId}
+ data-split-pane-owner={isOwner ? 'true' : 'false'}
+ className="flex h-full min-h-0 w-full flex-col overflow-hidden"
+ onPointerDownCapture={(event) => {
+ if (
+ isOwner ||
+ (event.button !== 0 && event.button !== 2) ||
+ isSplitPaneNoFocusTarget(event.target)
+ ) {
+ return;
+ }
+ focusSession(viewSessionId);
+ }}
+ onFocusCapture={(event) => {
+ const focusMovedWithinPane = event.currentTarget.contains(
+ event.relatedTarget as Node | null,
+ );
+ if (
+ isOwner ||
+ isSplitPaneNoFocusTarget(event.target) ||
+ (focusMovedWithinPane && !isSplitPaneNoFocusTarget(event.relatedTarget))
+ ) {
+ return;
+ }
+ focusSession(viewSessionId);
+ }}
+ >
+ <div className="flex h-8 shrink-0 items-center gap-1.5 border-b border-border/40 px-2">
+ <button
+ type="button"
+ onClick={() => focusSession(viewSessionId)}
+ className={cn(
+ 'min-w-0 flex-1 truncate rounded-full px-2 py-1 text-left text-xs transition-colors',
+ isOwner
+ ? 'font-medium text-foreground'
+ : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]',
+ )}
+ title={title}
+ >
+ {title}
+ </button>
+ <button
+ type="button"
+ data-split-pane-no-focus
+ aria-label={t('splitGroup.closeAria', { title })}
+ title={t('splitGroup.closeAria', { title })}
+ onClick={() => onClosePane(pane, isOwner)}
+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <X size={12} />
+ </button>
+ </div>
+ <div className="min-h-0 flex-1">
+ <CCAgentSessionView
+ sessionIdProp={viewSessionId}
+ routeOwner={isOwner}
+ compactToolbar
+ navigationMode={isOwner ? 'route-owner' : 'split-pane'}
+ onSessionNavigate={(targetSessionId, routeOwnerSessionId) =>
+ onSessionNavigate(viewSessionId, targetSessionId, routeOwnerSessionId)
+ }
+ sidebarTargetSessionId={viewSessionId}
+ disableAutofocus={!isOwner}
+ viewVisible
+ chatRealtime
+ />
+ </div>
+ </div>
+ </SplitDropTarget>
+ );
+});
+
+function SplitGroupToolbar({ root }: { root: SplitNode }) {
+ const { t } = useTranslation();
+ const direction = root.type === 'split' ? root.direction : 'row';
+ return (
+ <div
+ data-split-group-toolbar
+ className="flex h-8 shrink-0 items-center justify-end gap-1 border-b border-border/40 px-2"
+ >
+ <button
+ type="button"
+ aria-label={t('splitGroup.toggleDirection')}
+ title={t('splitGroup.toggleDirection')}
+ onClick={() => splitGroupStore.toggleRootDirection()}
+ className="inline-flex h-6 w-6 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {direction === 'row' ? <Rows2 size={13} /> : <Columns2 size={13} />}
+ </button>
+ <button
+ type="button"
+ aria-label={t('splitGroup.closeAll')}
+ title={t('splitGroup.closeAll')}
+ onClick={() => splitGroupStore.clear()}
+ className="inline-flex h-6 w-6 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <X size={13} />
+ </button>
+ </div>
+ );
+}
+
+interface SplitDropTargetProps {
+ anchorSessionId: string;
+ children: ReactNode;
+ className?: string;
+ dataAttribute: 'single' | 'pane';
+ onSessionDropped: (sessionId: string, side: DropSide) => void;
+}
+
+function SplitDropTarget({
+ anchorSessionId,
+ children,
+ className,
+ dataAttribute,
+ onSessionDropped,
+}: SplitDropTargetProps) {
+ const { t } = useTranslation();
+ const [dropSide, setDropSide] = useState<DropSide | null>(null);
+
+ const handleDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {
+ if (!hasSplitGroupSessionType(event.dataTransfer.types)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ event.dataTransfer.dropEffect = 'move';
+ const nextSide = resolveSplitDropSide(
+ event.currentTarget.getBoundingClientRect(),
+ event.clientX,
+ event.clientY,
+ );
+ setDropSide((currentSide) => (currentSide === nextSide ? currentSide : nextSide));
+ }, []);
+
+ const handleDragLeave = useCallback((event: DragEvent<HTMLDivElement>) => {
+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
+ setDropSide(null);
+ }, []);
+
+ const handleDrop = useCallback(
+ (event: DragEvent<HTMLDivElement>) => {
+ if (!hasSplitGroupSessionType(event.dataTransfer.types)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const sessionId = event.dataTransfer.getData(SPLIT_GROUP_SESSION_MIME).trim();
+ const side =
+ dropSide ??
+ resolveSplitDropSide(
+ event.currentTarget.getBoundingClientRect(),
+ event.clientX,
+ event.clientY,
+ );
+ setDropSide(null);
+ if (!sessionId || !side || sessionId === anchorSessionId) return;
+ onSessionDropped(sessionId, side);
+ },
+ [anchorSessionId, dropSide, onSessionDropped],
+ );
+
+ return (
+ <div
+ data-split-drop-target={dataAttribute}
+ className={className}
+ onDragOverCapture={handleDragOver}
+ onDragLeaveCapture={handleDragLeave}
+ onDropCapture={handleDrop}
+ >
+ {children}
+ {dropSide && <DropHighlight side={dropSide} label={t('splitGroup.dropHint')} />}
+ </div>
+ );
+}
+
+function DropHighlight({ side, label }: { side: DropSide; label: string }) {
+ const positionClass =
+ side === 'left'
+ ? 'left-0 top-0 h-full w-1/2'
+ : side === 'right'
+ ? 'right-0 top-0 h-full w-1/2'
+ : side === 'top'
+ ? 'left-0 top-0 h-1/2 w-full'
+ : 'bottom-0 left-0 h-1/2 w-full';
+ return (
+ <div
+ data-split-drop-side={side}
+ className={cn(
+ 'pointer-events-none absolute z-40 flex items-center justify-center',
+ 'border border-foreground/30 bg-foreground/5',
+ positionClass,
+ )}
+ >
+ <span className="rounded-full border border-border bg-content-area px-2 py-1 text-xs text-foreground">
+ {label}
+ </span>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CCAgentFeatureLayout.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/CCAgentFeatureLayout.test.tsx
new file mode 100644
index 0000000000..866d244cdd
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CCAgentFeatureLayout.test.tsx
@@ -0,0 +1,42 @@
+// @vitest-environment jsdom
+
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { CCAgentFeatureLayout } from '../CCAgentFeatureLayout';
+
+const registerSidebar = vi.fn();
+
+vi.mock('../useRegisterCCAgentSidebar', () => ({
+ useRegisterCCAgentSidebar: () => registerSidebar(),
+}));
+
+vi.mock('../SplitGroup', () => ({
+ SplitGroup: ({ activeSessionId }: { activeSessionId?: string }) => (
+ <div data-testid="split-group" data-active-session-id={activeSessionId} />
+ ),
+}));
+
+describe('CCAgentFeatureLayout', () => {
+ beforeEach(() => {
+ registerSidebar.mockClear();
+ localStorage.clear();
+ });
+
+ it('持久分屏不渲染子 Outlet 时仍先注册任务侧栏', () => {
+ render(
+ <MemoryRouter initialEntries={['/cc-agent/session-a']}>
+ <Routes>
+ <Route path="/cc-agent" element={<CCAgentFeatureLayout />}>
+ <Route path=":sessionId" element={<div data-testid="session-outlet" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(registerSidebar).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId('split-group').dataset.activeSessionId).toBe('session-a');
+ expect(screen.queryByTestId('session-outlet')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/SplitGroup.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/SplitGroup.test.tsx
new file mode 100644
index 0000000000..78faca81f1
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/SplitGroup.test.tsx
@@ -0,0 +1,1394 @@
+// @vitest-environment jsdom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useLayoutEffect } from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+import { ApiError } from '@/lib/httpClient';
+import { SplitGroup } from '../SplitGroup';
+import { getSplitPanes, splitGroupStore } from '../splitGroupStore';
+
+const {
+ deferredRouteActionMock,
+ navigateMock,
+ resolveSessionRouteMock,
+ routeActionMock,
+ sessionGetMock,
+ sessionViewRenderMock,
+ useCCSessionsMock,
+} = vi.hoisted(() => ({
+ deferredRouteActionMock: vi.fn(),
+ navigateMock: vi.fn(),
+ resolveSessionRouteMock: vi.fn(async (sessionId: string) => `/cc-agent/${sessionId}`),
+ routeActionMock: vi.fn(),
+ sessionGetMock: vi.fn(),
+ sessionViewRenderMock: vi.fn(),
+ useCCSessionsMock: vi.fn(),
+}));
+
+vi.mock('react-router-dom', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('react-router-dom')>();
+ return { ...actual, useNavigate: () => navigateMock };
+});
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/hooks/useCCSessions', () => ({
+ useCCSessions: useCCSessionsMock,
+}));
+
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ useRemoteProjectSessions: () => [],
+ useRemoteBootstrapLoadingDeviceIds: () => new Set(),
+ useRemoteBootstrapFailedDeviceIds: () => new Set(),
+}));
+
+vi.mock('@/lib/orcaSessionIdentity', () => ({
+ getSessionRouteOwnerId: (route: string) => /^\/cc-agent\/([^/?#]+)/.exec(route)?.[1] ?? null,
+ resolveSessionRoute: resolveSessionRouteMock,
+}));
+
+vi.mock('@/lib/makerTransport', () => ({
+ getSessionFor: sessionGetMock,
+}));
+
+vi.mock('../CCAgentSessionView', () => ({
+ CCAgentSessionView: ({
+ sessionIdProp,
+ routeOwner,
+ sidebarTargetSessionId,
+ onSessionNavigate,
+ disableAutofocus,
+ }: {
+ sessionIdProp: string;
+ routeOwner: boolean;
+ sidebarTargetSessionId: string;
+ onSessionNavigate?: (targetSessionId: string, routeOwnerSessionId?: string) => void;
+ disableAutofocus?: boolean;
+ }) => {
+ sessionViewRenderMock(sessionIdProp);
+ return (
+ <div
+ data-testid={`session-view-${sessionIdProp}`}
+ data-session-id={sessionIdProp}
+ data-route-owner={routeOwner ? 'true' : 'false'}
+ data-sidebar-target-session-id={sidebarTargetSessionId}
+ data-disable-autofocus={disableAutofocus ? 'true' : 'false'}
+ onDragOver={(event) => event.stopPropagation()}
+ onDrop={(event) => event.stopPropagation()}
+ >
+ <button
+ type="button"
+ data-testid={`route-action-${sessionIdProp}`}
+ data-split-pane-route-action=""
+ onClick={() => {
+ onSessionNavigate?.('session-c', 'session-c');
+ routeActionMock();
+ }}
+ >
+ Route action
+ </button>
+ <button
+ type="button"
+ data-testid={`worker-route-action-${sessionIdProp}`}
+ data-split-pane-route-action=""
+ onClick={() => {
+ onSessionNavigate?.('worker-c', 'lead-c');
+ routeActionMock();
+ }}
+ >
+ Worker route action
+ </button>
+ <button
+ type="button"
+ data-testid={`deferred-route-action-${sessionIdProp}`}
+ data-split-pane-route-action=""
+ onClick={() => deferredRouteActionMock(onSessionNavigate)}
+ >
+ Deferred route action
+ </button>
+ <button
+ type="button"
+ data-testid={`composer-action-${sessionIdProp}`}
+ onContextMenu={routeActionMock}
+ >
+ Composer action
+ </button>
+ </div>
+ );
+ },
+}));
+
+function renderSplitGroup(activeSessionId: string) {
+ return render(
+ <MemoryRouter>
+ <SplitGroup activeSessionId={activeSessionId}>
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+}
+
+describe('SplitGroup', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ deferredRouteActionMock.mockClear();
+ navigateMock.mockClear();
+ resolveSessionRouteMock.mockClear();
+ routeActionMock.mockClear();
+ sessionGetMock.mockReset();
+ sessionViewRenderMock.mockClear();
+ useCCSessionsMock.mockReset();
+ useCCSessionsMock.mockReturnValue({ sessions: [], isLoading: true, error: null });
+ splitGroupStore.__resetForTest();
+ });
+
+ afterEach(() => {
+ cleanup();
+ splitGroupStore.__resetForTest();
+ });
+
+ it('未分屏时保留路由内容并提供任务拖入落点', () => {
+ const view = renderSplitGroup('session-a');
+
+ expect(screen.getByTestId('route-outlet')).toBeTruthy();
+ expect(view.container.querySelector('[data-split-drop-target="single"]')).toBeTruthy();
+ });
+
+ it('会话目录加载完成后清理已删除 session 的持久化 pane', async () => {
+ useCCSessionsMock.mockReturnValue({
+ sessions: [{ id: 'session-a', title: 'Session A', status: 'active' }],
+ isLoading: false,
+ error: null,
+ });
+ sessionGetMock.mockResolvedValue({ id: 'session-deleted', status: 'deleted' });
+ act(() => {
+ splitGroupStore.addSession('session-deleted', 'session-a', 'right');
+ });
+
+ renderSplitGroup('session-a');
+
+ await waitFor(() => expect(splitGroupStore.getSnapshot().root).toBeNull());
+ expect(screen.getByTestId('route-outlet')).toBeTruthy();
+ });
+
+ it('权威核验确认远程 session 已归档时清理持久化 pane', async () => {
+ useCCSessionsMock.mockReturnValue({
+ sessions: [{ id: 'session-a', title: 'Session A', status: 'active' }],
+ isLoading: false,
+ error: null,
+ });
+ sessionGetMock.mockResolvedValue({ id: 'remote-session-archived', status: 'archived' });
+ act(() => {
+ splitGroupStore.addSession('remote-session-archived', 'session-a', 'right');
+ });
+
+ renderSplitGroup('session-a');
+
+ await waitFor(() => expect(splitGroupStore.getSnapshot().root).toBeNull());
+ expect(sessionGetMock).toHaveBeenCalledWith('remote-session-archived');
+ expect(screen.getByTestId('route-outlet')).toBeTruthy();
+ });
+
+ it('目录刷新期间会权威核验并保留刚创建的 session pane', async () => {
+ useCCSessionsMock.mockReturnValue({
+ sessions: [{ id: 'session-a', title: 'Session A', status: 'active' }],
+ isLoading: false,
+ error: null,
+ });
+ sessionGetMock.mockResolvedValue({ id: 'session-new', status: 'active' });
+ act(() => {
+ splitGroupStore.addSession('session-new', 'session-a', 'right');
+ });
+
+ renderSplitGroup('session-new');
+
+ await waitFor(() => expect(sessionGetMock).toHaveBeenCalledWith('session-new'));
+ expect(splitGroupStore.isActive()).toBe(true);
+ expect(screen.getByTestId('session-view-session-new')).toBeTruthy();
+ });
+
+ it('权威核验遇到瞬时错误时保留 session pane', async () => {
+ useCCSessionsMock.mockReturnValue({
+ sessions: [{ id: 'session-a', title: 'Session A', status: 'active' }],
+ isLoading: false,
+ error: null,
+ });
+ sessionGetMock.mockRejectedValue(new ApiError('UNKNOWN', 0, 'temporary failure'));
+ act(() => {
+ splitGroupStore.addSession('session-unavailable', 'session-a', 'right');
+ });
+
+ renderSplitGroup('session-a');
+
+ await waitFor(() => expect(sessionGetMock).toHaveBeenCalledWith('session-unavailable'));
+ expect(splitGroupStore.isActive()).toBe(true);
+ expect(screen.getByTestId('session-view-session-unavailable')).toBeTruthy();
+ });
+
+ it('权威核验确认 session 不存在时清理持久化 pane', async () => {
+ useCCSessionsMock.mockReturnValue({
+ sessions: [{ id: 'session-a', title: 'Session A', status: 'active' }],
+ isLoading: false,
+ error: null,
+ });
+ sessionGetMock.mockRejectedValue(new ApiError('NOT_FOUND', 0, 'missing'));
+ act(() => {
+ splitGroupStore.addSession('session-missing', 'session-a', 'right');
+ });
+
+ renderSplitGroup('session-a');
+
+ await waitFor(() => expect(splitGroupStore.getSnapshot().root).toBeNull());
+ expect(screen.getByTestId('route-outlet')).toBeTruthy();
+ });
+
+ it('当前路由 owner 已失效时先切到存活 pane,并且不会把死 pane 回填', async () => {
+ useCCSessionsMock.mockReturnValue({
+ sessions: [
+ { id: 'session-b', title: 'Session B', status: 'active' },
+ { id: 'session-c', title: 'Session C', status: 'active' },
+ ],
+ isLoading: false,
+ error: null,
+ });
+ sessionGetMock.mockResolvedValue({ id: 'session-a', status: 'deleted' });
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+
+ renderSplitGroup('session-a');
+
+ await waitFor(() =>
+ expect(navigateMock).toHaveBeenCalledWith('/cc-agent/session-b', { replace: true }),
+ );
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-b', 'session-c'],
+ );
+ expect(screen.queryByTestId('session-view-session-a')).toBeNull();
+ expect(sessionGetMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('失效 owner 的恢复路由晚到时不会覆盖用户刚切换的 pane', async () => {
+ useCCSessionsMock.mockReturnValue({
+ sessions: [
+ { id: 'session-b', title: 'Session B', status: 'active' },
+ { id: 'session-c', title: 'Session C', status: 'active' },
+ ],
+ isLoading: false,
+ error: null,
+ });
+ sessionGetMock.mockResolvedValue({ id: 'session-a', status: 'deleted' });
+ let resolveStaleOwnerRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveStaleOwnerRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+
+ await waitFor(() =>
+ expect(resolveSessionRouteMock).toHaveBeenCalledWith(
+ 'session-b',
+ expect.objectContaining({ id: 'session-b' }),
+ ),
+ );
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-c">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ await act(async () => {
+ resolveStaleOwnerRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).not.toHaveBeenCalledWith('/cc-agent/session-b', { replace: true });
+ });
+
+ it('清理失效 owner 后仍会完成延迟返回的存活 pane 路由恢复', async () => {
+ useCCSessionsMock.mockReturnValue({
+ sessions: [
+ { id: 'session-b', title: 'Session B', status: 'active' },
+ { id: 'session-c', title: 'Session C', status: 'active' },
+ ],
+ isLoading: false,
+ error: null,
+ });
+ sessionGetMock.mockResolvedValue({ id: 'session-a', status: 'deleted' });
+ let resolveStaleOwnerRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveStaleOwnerRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ renderSplitGroup('session-a');
+
+ await waitFor(() =>
+ expect(
+ getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId),
+ ).toEqual(['session-b', 'session-c']),
+ );
+ await act(async () => {
+ resolveStaleOwnerRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).toHaveBeenCalledWith('/cc-agent/session-b', { replace: true });
+ });
+
+ it('两窗格因清理失效 owner 折叠后仍会完成延迟路由恢复', async () => {
+ useCCSessionsMock.mockReturnValue({
+ sessions: [{ id: 'session-b', title: 'Session B', status: 'active' }],
+ isLoading: false,
+ error: null,
+ });
+ sessionGetMock.mockResolvedValue({ id: 'session-a', status: 'deleted' });
+ let resolveStaleOwnerRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveStaleOwnerRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ renderSplitGroup('session-a');
+
+ await waitFor(() => expect(splitGroupStore.getSnapshot().root).toBeNull());
+ await act(async () => {
+ resolveStaleOwnerRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).toHaveBeenCalledWith('/cc-agent/session-b', { replace: true });
+ });
+
+ it('活动 pane 接管路由主权,切换活动任务不会重建 pane 视图', () => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ const view = renderSplitGroup('session-a');
+
+ const sessionAView = screen.getByTestId('session-view-session-a');
+ const sessionBView = screen.getByTestId('session-view-session-b');
+ expect(sessionAView.dataset.routeOwner).toBe('true');
+ expect(sessionBView.dataset.routeOwner).toBe('false');
+ expect(sessionAView.dataset.disableAutofocus).toBe('false');
+ expect(sessionBView.dataset.disableAutofocus).toBe('true');
+ expect(sessionAView.dataset.sidebarTargetSessionId).toBe('session-a');
+ expect(sessionBView.dataset.sidebarTargetSessionId).toBe('session-b');
+
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-b">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByTestId('session-view-session-a')).toBe(sessionAView);
+ expect(screen.getByTestId('session-view-session-b')).toBe(sessionBView);
+ expect(sessionAView.dataset.routeOwner).toBe('false');
+ expect(sessionBView.dataset.routeOwner).toBe('true');
+ expect(sessionAView.dataset.sidebarTargetSessionId).toBe('session-a');
+ expect(sessionBView.dataset.sidebarTargetSessionId).toBe('session-b');
+ });
+
+ it('在父级 layout 阶段运行前同步新路由任务到 pane 树', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const originalOwnerPane = getSplitPanes(splitGroupStore.getSnapshot().root).find(
+ (pane) => pane.sessionId === 'session-a',
+ );
+ const layoutSnapshots: Array<Array<{ key: string; sessionId: string }>> = [];
+
+ function LayoutProbe({ activeSessionId }: { activeSessionId: string }) {
+ useLayoutEffect(() => {
+ layoutSnapshots.push(
+ getSplitPanes(splitGroupStore.getSnapshot().root).map(({ key, sessionId }) => ({
+ key,
+ sessionId,
+ })),
+ );
+ }, [activeSessionId]);
+ return (
+ <SplitGroup activeSessionId={activeSessionId}>
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ );
+ }
+
+ const view = render(
+ <MemoryRouter>
+ <LayoutProbe activeSessionId="session-a" />
+ </MemoryRouter>,
+ );
+ layoutSnapshots.length = 0;
+
+ view.rerender(
+ <MemoryRouter>
+ <LayoutProbe activeSessionId="session-c" />
+ </MemoryRouter>,
+ );
+
+ expect(layoutSnapshots).toHaveLength(1);
+ expect(layoutSnapshots[0]?.map((pane) => pane.sessionId)).toEqual(['session-c', 'session-b']);
+ expect(layoutSnapshots[0]?.find((pane) => pane.sessionId === 'session-c')?.key).toBe(
+ originalOwnerPane?.key,
+ );
+ });
+
+ it('从非首个 owner 进入新建页再创建任务时保留原 owner pane', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-b');
+
+ // `/cc-agent/new` 没有 activeSessionId,SplitGroupActive 会暂时卸载,但外层
+ // layout 仍在;新任务创建后路由会直接变成 session-c。
+ act(() => {
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup>
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ });
+
+ act(() => {
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-c">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ });
+
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-a', 'session-c'],
+ );
+ expect(screen.getByTestId('session-view-session-c').dataset.routeOwner).toBe('true');
+ });
+
+ it('键盘焦点进入非活动 pane 时切换该 pane 的路由主权', async () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ renderSplitGroup('session-a');
+ const sessionAView = screen.getByTestId('session-view-session-a');
+ const sessionBView = screen.getByTestId('session-view-session-b');
+
+ await act(async () => {
+ fireEvent.focus(sessionBView, { relatedTarget: sessionAView });
+ await Promise.resolve();
+ });
+
+ expect(resolveSessionRouteMock).toHaveBeenCalledTimes(1);
+ expect(resolveSessionRouteMock).toHaveBeenCalledWith('session-b', null);
+ });
+
+ it('键盘焦点进入非活动 pane 的关闭按钮时不切换路由主权', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+ const sessionAView = screen.getByTestId('session-view-session-a');
+ const sessionBView = screen.getByTestId('session-view-session-b');
+ const closeButton = sessionBView
+ .closest('[data-split-pane-key]')
+ ?.querySelector<HTMLButtonElement>('[data-split-pane-no-focus]');
+ expect(closeButton).toBeTruthy();
+
+ act(() => {
+ fireEvent.focus(closeButton as HTMLButtonElement, { relatedTarget: sessionAView });
+ });
+
+ expect(resolveSessionRouteMock).not.toHaveBeenCalled();
+
+ act(() => {
+ fireEvent.click(closeButton as HTMLButtonElement);
+ });
+
+ expect(view.container.querySelectorAll('[data-split-pane-key]')).toHaveLength(0);
+ expect(screen.getByTestId('route-outlet')).toBeTruthy();
+ expect(resolveSessionRouteMock).not.toHaveBeenCalled();
+ });
+
+ it('键盘焦点从 pane 内豁免控件移到普通控件时切换路由主权', async () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ renderSplitGroup('session-a');
+ const sessionAView = screen.getByTestId('session-view-session-a');
+ const routeAction = screen.getByTestId('route-action-session-b');
+ const composerAction = screen.getByTestId('composer-action-session-b');
+
+ act(() => {
+ fireEvent.focus(routeAction, { relatedTarget: sessionAView });
+ });
+ expect(resolveSessionRouteMock).not.toHaveBeenCalled();
+
+ await act(async () => {
+ fireEvent.focus(composerAction, { relatedTarget: routeAction });
+ await Promise.resolve();
+ });
+
+ expect(resolveSessionRouteMock).toHaveBeenCalledTimes(1);
+ expect(resolveSessionRouteMock).toHaveBeenCalledWith('session-b', null);
+ });
+
+ it('pane 内显式子路由操作直接接管目标路由,不额外切换来源 pane', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ renderSplitGroup('session-a');
+ const sessionAView = screen.getByTestId('session-view-session-a');
+ const routeAction = screen.getByTestId('route-action-session-b');
+
+ act(() => {
+ fireEvent.focus(routeAction, { relatedTarget: sessionAView });
+ fireEvent.pointerDown(routeAction, { button: 0 });
+ fireEvent.click(routeAction);
+ });
+
+ expect(routeActionMock).toHaveBeenCalledTimes(1);
+ expect(resolveSessionRouteMock).not.toHaveBeenCalled();
+ expect(navigateMock).not.toHaveBeenCalled();
+ });
+
+ it('新的 pane 路由主权会取消仍在解析的旧焦点请求', async () => {
+ let resolveStaleRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveStaleRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+
+ act(() => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-b'), { button: 0 });
+ });
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-c">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+
+ await act(async () => {
+ resolveStaleRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ });
+
+ it('较早的路由提交不会取消更晚的 pane 聚焦请求', async () => {
+ let resolveLatestRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockResolvedValueOnce('/cc-agent/session-b').mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveLatestRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+
+ await act(async () => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-b'), { button: 0 });
+ await Promise.resolve();
+ });
+ expect(navigateMock).toHaveBeenCalledWith('/cc-agent/session-b');
+
+ act(() => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-c'), { button: 0 });
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-b">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ });
+ await act(async () => {
+ resolveLatestRoute?.('/cc-agent/session-c');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).toHaveBeenLastCalledWith('/cc-agent/session-c');
+ });
+
+ it('分屏卸载后会取消仍在解析的 pane 焦点请求', async () => {
+ let resolveStaleRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveStaleRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+
+ act(() => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-b'), { button: 0 });
+ });
+ view.unmount();
+
+ await act(async () => {
+ resolveStaleRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ });
+
+ it('关闭 pane 时会取消该 pane 仍在解析的焦点请求', async () => {
+ let resolveClosedPaneRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveClosedPaneRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+
+ act(() => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-b'), { button: 0 });
+ });
+ const sessionBPane = view.container.querySelector('[data-split-pane-session-id="session-b"]');
+ const closeButton = sessionBPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-b close button missing');
+
+ act(() => {
+ fireEvent.click(closeButton);
+ });
+
+ expect(screen.queryByTestId('session-view-session-b')).toBeNull();
+ expect(screen.getByTestId('session-view-session-a')).toBeTruthy();
+ expect(screen.getByTestId('session-view-session-c')).toBeTruthy();
+
+ await act(async () => {
+ resolveClosedPaneRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ expect(screen.queryByTestId('session-view-session-b')).toBeNull();
+ });
+
+ it('关闭 route owner 时等待目标 pane 接管路由后再删除原 pane', async () => {
+ let resolveTargetRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveTargetRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const originalPanes = getSplitPanes(splitGroupStore.getSnapshot().root);
+ const originalKeys = new Map(originalPanes.map((pane) => [pane.sessionId, pane.key]));
+ const view = renderSplitGroup('session-a');
+ const sessionAPane = view.container.querySelector('[data-split-pane-session-id="session-a"]');
+ const closeButton = sessionAPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-a close button missing');
+
+ act(() => {
+ fireEvent.click(closeButton);
+ });
+
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-a', 'session-b', 'session-c'],
+ );
+ expect(screen.getByTestId('session-view-session-a')).toBeTruthy();
+
+ await act(async () => {
+ resolveTargetRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).toHaveBeenCalledWith('/cc-agent/session-b');
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-a', 'session-b', 'session-c'],
+ );
+
+ act(() => {
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-b">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ });
+
+ const remainingPanes = getSplitPanes(splitGroupStore.getSnapshot().root);
+ expect(remainingPanes.map((pane) => pane.sessionId)).toEqual(['session-b', 'session-c']);
+ expect(remainingPanes.find((pane) => pane.sessionId === 'session-b')?.key).toBe(
+ originalKeys.get('session-b'),
+ );
+ expect(remainingPanes.find((pane) => pane.sessionId === 'session-c')?.key).toBe(
+ originalKeys.get('session-c'),
+ );
+ });
+
+ it('目标导航已发出后再关闭 owner,仍会在目标提交时完成关闭', async () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+
+ await act(async () => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-b'), { button: 0 });
+ await Promise.resolve();
+ });
+ expect(navigateMock).toHaveBeenCalledWith('/cc-agent/session-b');
+
+ const sessionAPane = view.container.querySelector('[data-split-pane-session-id="session-a"]');
+ const closeButton = sessionAPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-a close button missing');
+ act(() => {
+ fireEvent.click(closeButton);
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-b">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ });
+
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-b', 'session-c'],
+ );
+ });
+
+ it('关闭 route owner 的目标路由解析失败时保留原布局并允许重试', async () => {
+ resolveSessionRouteMock.mockRejectedValueOnce(new Error('route unavailable'));
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+ const sessionAPane = view.container.querySelector('[data-split-pane-session-id="session-a"]');
+ const closeButton = sessionAPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-a close button missing');
+
+ await act(async () => {
+ fireEvent.click(closeButton);
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-a', 'session-b', 'session-c'],
+ );
+
+ await act(async () => {
+ fireEvent.click(closeButton);
+ await Promise.resolve();
+ });
+
+ expect(resolveSessionRouteMock).toHaveBeenCalledTimes(2);
+ expect(navigateMock).toHaveBeenCalledWith('/cc-agent/session-b');
+ act(() => {
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-b">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ });
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-b', 'session-c'],
+ );
+ });
+
+ it('关闭 route owner 的焦点请求被后续请求取代时不会遗留陈旧关闭事务', async () => {
+ let resolveOwnerCloseRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock
+ .mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveOwnerCloseRoute = resolve;
+ }),
+ )
+ .mockRejectedValueOnce(new Error('new focus failed'));
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+ const sessionAPane = view.container.querySelector('[data-split-pane-session-id="session-a"]');
+ const closeButton = sessionAPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-a close button missing');
+
+ act(() => {
+ fireEvent.click(closeButton);
+ });
+ await act(async () => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-c'), { button: 0 });
+ await Promise.resolve();
+ resolveOwnerCloseRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ act(() => {
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-c">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ });
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-a', 'session-b', 'session-c'],
+ );
+ });
+
+ it('关闭到 Orca Worker pane 时等待 canonical Lead 接管后再删除 owner', async () => {
+ resolveSessionRouteMock.mockResolvedValueOnce('/cc-agent/lead-b?worker=worker-b');
+ act(() => {
+ splitGroupStore.addSession('worker-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'worker-b', 'bottom');
+ });
+ const workerPaneKey = getSplitPanes(splitGroupStore.getSnapshot().root).find(
+ (pane) => pane.sessionId === 'worker-b',
+ )?.key;
+ const view = renderSplitGroup('session-a');
+ const sessionAPane = view.container.querySelector('[data-split-pane-session-id="session-a"]');
+ const closeButton = sessionAPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-a close button missing');
+
+ await act(async () => {
+ fireEvent.click(closeButton);
+ await Promise.resolve();
+ });
+ act(() => {
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="lead-b">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ });
+
+ const remainingPanes = getSplitPanes(splitGroupStore.getSnapshot().root);
+ expect(remainingPanes.map((pane) => pane.sessionId)).toEqual(['lead-b', 'session-c']);
+ expect(remainingPanes.find((pane) => pane.sessionId === 'lead-b')?.key).toBe(workerPaneKey);
+ });
+
+ it('关闭 route owner 期间目标 pane 被移除会取消旧导航并保留 owner', async () => {
+ let resolveRemovedTargetRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveRemovedTargetRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+ const sessionAPane = view.container.querySelector('[data-split-pane-session-id="session-a"]');
+ const closeButton = sessionAPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-a close button missing');
+
+ act(() => {
+ fireEvent.click(closeButton);
+ splitGroupStore.removeSession('session-b');
+ });
+ await act(async () => {
+ resolveRemovedTargetRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-a', 'session-c'],
+ );
+ });
+
+ it('两个 pane 时先完成 owner 路由切换再退出分屏', async () => {
+ let resolveTargetRoute: ((route: string) => void) | undefined;
+ resolveSessionRouteMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveTargetRoute = resolve;
+ }),
+ );
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+ const sessionAPane = view.container.querySelector('[data-split-pane-session-id="session-a"]');
+ const closeButton = sessionAPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-a close button missing');
+
+ act(() => {
+ fireEvent.click(closeButton);
+ });
+
+ expect(splitGroupStore.isActive()).toBe(true);
+ expect(navigateMock).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolveTargetRoute?.('/cc-agent/session-b');
+ await Promise.resolve();
+ });
+
+ expect(splitGroupStore.isActive()).toBe(true);
+ expect(navigateMock).toHaveBeenCalledWith('/cc-agent/session-b');
+
+ act(() => {
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-b">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+ });
+
+ expect(splitGroupStore.isActive()).toBe(false);
+ expect(screen.getByTestId('route-outlet')).toBeTruthy();
+ });
+
+ it('pane 内普通 composer 按钮会先切换 pane 主权', async () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ renderSplitGroup('session-a');
+
+ await act(async () => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-b'), { button: 0 });
+ await Promise.resolve();
+ });
+
+ expect(resolveSessionRouteMock).toHaveBeenCalledWith('session-b', null);
+ });
+
+ it('非 owner pane 的右键上下文操作会先启动 pane 主权切换', async () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ renderSplitGroup('session-a');
+
+ await act(async () => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-b'), { button: 2 });
+ fireEvent.contextMenu(screen.getByTestId('composer-action-session-b'));
+ await Promise.resolve();
+ });
+
+ expect(resolveSessionRouteMock).toHaveBeenCalledWith('session-b', null);
+ expect(resolveSessionRouteMock.mock.invocationCallOrder[0]).toBeLessThan(
+ routeActionMock.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
+ );
+ });
+
+ it('中键与 no-focus 控件的右键不会切换 pane 主权', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+ const sessionBPane = view.container.querySelector('[data-split-pane-session-id="session-b"]');
+ const closeButton = sessionBPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-b close button missing');
+
+ act(() => {
+ fireEvent.pointerDown(screen.getByTestId('composer-action-session-b'), { button: 1 });
+ fireEvent.pointerDown(closeButton, { button: 2 });
+ });
+
+ expect(resolveSessionRouteMock).not.toHaveBeenCalled();
+ });
+
+ it('非 owner pane 发起子路由跳转时替换发起跳转的 pane', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+
+ act(() => {
+ fireEvent.click(screen.getByTestId('route-action-session-b'));
+ });
+
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-c">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByTestId('session-view-session-a')).toBeTruthy();
+ expect(screen.queryByTestId('session-view-session-b')).toBeNull();
+ expect(screen.getByTestId('session-view-session-c').dataset.routeOwner).toBe('true');
+ expect(resolveSessionRouteMock).not.toHaveBeenCalled();
+ });
+
+ it('Orca worker 深链规范化到 Lead 路由时仍替换来源 pane', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+
+ act(() => {
+ fireEvent.click(screen.getByTestId('worker-route-action-session-b'));
+ });
+
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="lead-c">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByTestId('session-view-session-a')).toBeTruthy();
+ expect(screen.queryByTestId('session-view-session-b')).toBeNull();
+ expect(screen.getByTestId('session-view-lead-c').dataset.routeOwner).toBe('true');
+ });
+
+ it('来源 pane 已关闭时忽略延迟完成的子路由替换意图', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+
+ act(() => {
+ fireEvent.click(screen.getByTestId('deferred-route-action-session-b'));
+ });
+ const reportNavigation = deferredRouteActionMock.mock.calls[0]?.[0] as
+ ((targetSessionId: string, routeOwnerSessionId?: string) => void) | undefined;
+ const sessionBPane = view.container.querySelector('[data-split-pane-session-id="session-b"]');
+ const closeButton = sessionBPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-b close button missing');
+
+ act(() => {
+ fireEvent.click(closeButton);
+ reportNavigation?.('session-d', 'session-d');
+ });
+ view.rerender(
+ <MemoryRouter>
+ <SplitGroup activeSessionId="session-d">
+ <div data-testid="route-outlet" />
+ </SplitGroup>
+ </MemoryRouter>,
+ );
+
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-a', 'session-c'],
+ );
+ });
+
+ it('递归渲染左一右二与左二右二混合布局', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-a');
+
+ const root = view.container.querySelector('[data-split-root-direction="row"]');
+ expect(root).toBeTruthy();
+ expect(view.container.querySelectorAll('[data-split-direction="column"]')).toHaveLength(1);
+ expect(view.container.querySelectorAll('[data-split-pane-key]')).toHaveLength(3);
+
+ act(() => {
+ splitGroupStore.addSession('session-d', 'session-a', 'bottom');
+ });
+
+ expect(view.container.querySelectorAll('[data-split-direction="column"]')).toHaveLength(2);
+ expect(view.container.querySelectorAll('[data-split-pane-key]')).toHaveLength(4);
+ });
+
+ it('关闭分支后提升 sibling 时保留其它 pane 的已挂载视图', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ });
+ const view = renderSplitGroup('session-b');
+ const sessionBView = screen.getByTestId('session-view-session-b');
+ const sessionCView = screen.getByTestId('session-view-session-c');
+ const sessionAPane = view.container.querySelector('[data-split-pane-session-id="session-a"]');
+ const closeButton = sessionAPane?.querySelector('button[aria-label="splitGroup.closeAria"]');
+ if (!(closeButton instanceof HTMLElement)) throw new Error('session-a close button missing');
+
+ act(() => {
+ fireEvent.click(closeButton);
+ });
+
+ expect(screen.getByTestId('session-view-session-b')).toBe(sessionBView);
+ expect(screen.getByTestId('session-view-session-c')).toBe(sessionCView);
+ });
+
+ it('分割线可聚焦,方向键与 Home/End 调整比例并同步 ARIA 值', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+ const separator = view.container.querySelector('[role="separator"]') as HTMLElement;
+
+ expect(separator).toBeTruthy();
+ expect(separator.getAttribute('tabindex')).toBe('0');
+ expect(separator.getAttribute('aria-valuemin')).toBe('10');
+ expect(separator.getAttribute('aria-valuemax')).toBe('90');
+ expect(separator.getAttribute('aria-valuenow')).toBe('50');
+
+ act(() => {
+ fireEvent.keyDown(separator, { key: 'ArrowRight' });
+ });
+ let root = splitGroupStore.getSnapshot().root;
+ if (root?.type !== 'split') throw new Error('root split missing');
+ expect(root.fraction).toBeCloseTo(0.55, 5);
+ expect(separator.getAttribute('aria-valuenow')).toBe('55');
+
+ act(() => {
+ // 行方向分割线忽略纵向按键,比例保持不变。
+ fireEvent.keyDown(separator, { key: 'ArrowUp' });
+ });
+ root = splitGroupStore.getSnapshot().root;
+ if (root?.type !== 'split') throw new Error('root split missing');
+ expect(root.fraction).toBeCloseTo(0.55, 5);
+
+ act(() => {
+ fireEvent.keyDown(separator, { key: 'Home' });
+ });
+ root = splitGroupStore.getSnapshot().root;
+ if (root?.type !== 'split') throw new Error('root split missing');
+ expect(root.fraction).toBeCloseTo(0.1, 5);
+
+ act(() => {
+ fireEvent.keyDown(separator, { key: 'End' });
+ });
+ root = splitGroupStore.getSnapshot().root;
+ if (root?.type !== 'split') throw new Error('root split missing');
+ expect(root.fraction).toBeCloseTo(0.9, 5);
+ });
+
+ it('窗口失焦时结束分割线拖动并清理全局 resize 状态', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+ const separator = view.container.querySelector('[role="separator"]') as HTMLElement;
+ const branch = separator.closest('[data-split-branch]') as HTMLElement;
+ vi.spyOn(branch, 'getBoundingClientRect').mockReturnValue({
+ left: 0,
+ right: 1006,
+ top: 0,
+ bottom: 500,
+ width: 1006,
+ height: 500,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ });
+ const setFractionSpy = vi.spyOn(splitGroupStore, 'setSplitFraction');
+
+ act(() => {
+ fireEvent.pointerDown(separator, { button: 0, clientX: 500 });
+ fireEvent.pointerMove(document, { clientX: 600 });
+ });
+ expect(document.body.classList.contains('resizing-pane')).toBe(true);
+
+ act(() => {
+ fireEvent.blur(window);
+ });
+
+ expect(document.body.classList.contains('resizing-pane')).toBe(false);
+ expect(setFractionSpy).toHaveBeenCalledTimes(1);
+ expect(setFractionSpy.mock.calls[0]?.[1]).toBeCloseTo(0.6, 5);
+
+ act(() => {
+ fireEvent.blur(window);
+ fireEvent.pointerMove(document, { clientX: 800 });
+ });
+ expect(setFractionSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('拖动分割线时不重渲染重型 session 视图', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+ const separator = view.container.querySelector('[role="separator"]') as HTMLElement;
+ const branch = separator.closest('[data-split-branch]') as HTMLElement;
+ vi.spyOn(branch, 'getBoundingClientRect').mockReturnValue({
+ left: 0,
+ right: 1006,
+ top: 0,
+ bottom: 500,
+ width: 1006,
+ height: 500,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ });
+ sessionViewRenderMock.mockClear();
+
+ act(() => {
+ fireEvent.pointerDown(separator, { button: 0, clientX: 500 });
+ fireEvent.pointerMove(document, { clientX: 550 });
+ fireEvent.pointerMove(document, { clientX: 600 });
+ });
+
+ expect(sessionViewRenderMock).not.toHaveBeenCalled();
+ act(() => fireEvent.pointerUp(document));
+ });
+
+ it('页面隐藏后连续收到其它终止事件时只提交一次 resize', () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+ const separator = view.container.querySelector('[role="separator"]') as HTMLElement;
+ const branch = separator.closest('[data-split-branch]') as HTMLElement;
+ vi.spyOn(branch, 'getBoundingClientRect').mockReturnValue({
+ left: 0,
+ right: 1006,
+ top: 0,
+ bottom: 500,
+ width: 1006,
+ height: 500,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ });
+ const setFractionSpy = vi.spyOn(splitGroupStore, 'setSplitFraction');
+ const visibilitySpy = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
+
+ act(() => {
+ fireEvent.pointerDown(separator, { button: 0, clientX: 500 });
+ fireEvent.pointerMove(document, { clientX: 650 });
+ fireEvent(document, new Event('visibilitychange'));
+ fireEvent.blur(window);
+ fireEvent.pointerCancel(document);
+ fireEvent.pointerMove(document, { clientX: 800 });
+ });
+
+ expect(document.body.classList.contains('resizing-pane')).toBe(false);
+ expect(setFractionSpy).toHaveBeenCalledTimes(1);
+ expect(setFractionSpy.mock.calls[0]?.[1]).toBeCloseTo(0.65, 5);
+ visibilitySpy.mockRestore();
+ });
+
+ it('pane 内子组件阻止冒泡时仍能捕获任务拖放', async () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ const view = renderSplitGroup('session-a');
+ const sessionBView = screen.getByTestId('session-view-session-b');
+ const dropTarget = sessionBView.closest('[data-split-drop-target="pane"]');
+ expect(dropTarget).toBeTruthy();
+ vi.spyOn(dropTarget as HTMLElement, 'getBoundingClientRect').mockReturnValue({
+ left: 100,
+ right: 500,
+ top: 50,
+ bottom: 350,
+ width: 400,
+ height: 300,
+ x: 100,
+ y: 50,
+ toJSON: () => ({}),
+ });
+ const dataTransfer = {
+ types: ['application/x-cindy-session-id'],
+ dropEffect: 'none',
+ getData: (format: string) => (format === 'application/x-cindy-session-id' ? 'session-c' : ''),
+ };
+
+ await act(async () => {
+ fireEvent.dragOver(sessionBView, { clientX: 300, clientY: 340, dataTransfer });
+ fireEvent.drop(sessionBView, { clientX: 300, clientY: 340, dataTransfer });
+ await Promise.resolve();
+ });
+
+ expect(view.container.querySelectorAll('[data-split-direction="column"]')).toHaveLength(1);
+ expect(view.container.querySelectorAll('[data-split-pane-key]')).toHaveLength(3);
+ });
+
+ it('达到窗格上限时拒绝拖入且不切换路由', async () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ for (let index = 3; index <= 8; index += 1) {
+ splitGroupStore.addSession(`session-${index}`, 'session-b', 'bottom');
+ }
+ });
+ const view = renderSplitGroup('session-a');
+ const sessionBView = screen.getByTestId('session-view-session-b');
+ const dropTarget = sessionBView.closest('[data-split-drop-target="pane"]');
+ expect(dropTarget).toBeTruthy();
+ vi.spyOn(dropTarget as HTMLElement, 'getBoundingClientRect').mockReturnValue({
+ left: 100,
+ right: 500,
+ top: 50,
+ bottom: 350,
+ width: 400,
+ height: 300,
+ x: 100,
+ y: 50,
+ toJSON: () => ({}),
+ });
+ const dataTransfer = {
+ types: ['application/x-cindy-session-id'],
+ dropEffect: 'none',
+ getData: (format: string) =>
+ format === 'application/x-cindy-session-id' ? 'session-over-limit' : '',
+ };
+
+ await act(async () => {
+ fireEvent.dragOver(sessionBView, { clientX: 490, clientY: 200, dataTransfer });
+ fireEvent.drop(sessionBView, { clientX: 490, clientY: 200, dataTransfer });
+ await Promise.resolve();
+ });
+
+ expect(view.container.querySelectorAll('[data-split-pane-key]')).toHaveLength(8);
+ expect(resolveSessionRouteMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupDnd.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupDnd.test.ts
new file mode 100644
index 0000000000..a20f02765b
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupDnd.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ SPLIT_GROUP_SESSION_MIME,
+ hasSplitGroupSessionType,
+ isSplitGroupDragSource,
+ resolveSplitDropSide,
+ writeSplitGroupSessionDragData,
+} from '../splitGroupDnd';
+
+const RECT = { left: 100, top: 50, width: 400, height: 300 };
+
+describe('splitGroupDnd', () => {
+ it('只接受 Cindy 任务拖拽 MIME', () => {
+ expect(hasSplitGroupSessionType([SPLIT_GROUP_SESSION_MIME])).toBe(true);
+ expect(hasSplitGroupSessionType(['Files', 'text/plain'])).toBe(false);
+ });
+
+ it('向侧栏拖拽写入专用 MIME 和纯文本回退', () => {
+ const values = new Map<string, string>();
+ const dataTransfer = {
+ effectAllowed: 'none',
+ setData: (format: string, data: string) => values.set(format, data),
+ };
+
+ expect(writeSplitGroupSessionDragData(dataTransfer, ' session-a ')).toBe(true);
+ expect(dataTransfer.effectAllowed).toBe('move');
+ expect(values.get(SPLIT_GROUP_SESSION_MIME)).toBe('session-a');
+ expect(values.get('text/plain')).toBe('session-a');
+ expect(writeSplitGroupSessionDragData(dataTransfer, ' ')).toBe(false);
+ });
+
+ it.each([
+ ['left', 110, 200],
+ ['right', 490, 200],
+ ['top', 300, 60],
+ ['bottom', 300, 340],
+ ] as const)('指针靠近 %s 边时返回对应落点', (side, clientX, clientY) => {
+ expect(resolveSplitDropSide(RECT, clientX, clientY)).toBe(side);
+ });
+
+ it('无尺寸目标不产生落点', () => {
+ expect(resolveSplitDropSide({ ...RECT, width: 0 }, 100, 100)).toBeNull();
+ });
+
+ it('时间排序列表里的普通任务行才是分屏拖拽源', () => {
+ expect(
+ isSplitGroupDragSource({ editing: false, orcaRole: null, inSortableContainer: false }),
+ ).toBe(true);
+ expect(
+ isSplitGroupDragSource({ editing: false, orcaRole: 'lead', inSortableContainer: false }),
+ ).toBe(true);
+ });
+
+ it('编辑态、Orca worker 与 Sortable 容器内的行不充当拖拽源', () => {
+ expect(
+ isSplitGroupDragSource({ editing: true, orcaRole: null, inSortableContainer: false }),
+ ).toBe(false);
+ expect(
+ isSplitGroupDragSource({ editing: false, orcaRole: 'worker', inSortableContainer: false }),
+ ).toBe(false);
+ expect(
+ isSplitGroupDragSource({ editing: false, orcaRole: null, inSortableContainer: true }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupStore.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupStore.test.ts
new file mode 100644
index 0000000000..49de5612fb
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupStore.test.ts
@@ -0,0 +1,296 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// 副窗口(「在新窗口打开」)与主窗共享同源 localStorage;store 依赖该判定决定
+// 是否触碰共享持久化。用可变开关模拟两种窗口环境。
+let secondaryWindow = false;
+vi.mock('@/lib/secondaryWindow', () => ({
+ isSecondaryWindow: () => secondaryWindow,
+}));
+
+const storageData = new Map<string, string>();
+
+const storage: Storage = {
+ get length() {
+ return storageData.size;
+ },
+ clear: vi.fn(() => storageData.clear()),
+ getItem: vi.fn((key: string) => storageData.get(key) ?? null),
+ key: vi.fn((index: number) => [...storageData.keys()][index] ?? null),
+ removeItem: vi.fn((key: string) => storageData.delete(key)),
+ setItem: vi.fn((key: string, value: string) => storageData.set(key, value)),
+};
+
+async function loadStore() {
+ return import('../splitGroupStore');
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ storageData.clear();
+ secondaryWindow = false;
+ vi.stubGlobal('localStorage', storage);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('splitGroupStore', () => {
+ it('默认未激活且不写持久化', async () => {
+ const { splitGroupStore, SPLIT_GROUP_STORAGE_KEY } = await loadStore();
+
+ expect(splitGroupStore.getSnapshot()).toEqual({ root: null });
+ expect(splitGroupStore.isActive()).toBe(false);
+ expect(storageData.has(SPLIT_GROUP_STORAGE_KEY)).toBe(false);
+ });
+
+ it('首次拖入按落点建立左右或上下分屏并持久化', async () => {
+ const { getSplitSessionIds, splitGroupStore, SPLIT_GROUP_STORAGE_KEY } = await loadStore();
+ const listener = vi.fn();
+ const unsubscribe = splitGroupStore.subscribe(listener);
+
+ splitGroupStore.addSession('session-b', 'session-a', 'left');
+
+ const snapshot = splitGroupStore.getSnapshot();
+ expect(snapshot.root).toMatchObject({
+ type: 'split',
+ direction: 'row',
+ fraction: 0.5,
+ first: { type: 'pane', sessionId: 'session-b' },
+ second: { type: 'pane', sessionId: 'session-a' },
+ });
+ expect(getSplitSessionIds(snapshot.root)).toEqual(['session-b', 'session-a']);
+ expect(splitGroupStore.isActive()).toBe(true);
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(storageData.get(SPLIT_GROUP_STORAGE_KEY) ?? '{}')).toMatchObject(snapshot);
+
+ unsubscribe();
+ });
+
+ it('只拆目标 pane,支持左一右二', async () => {
+ const { splitGroupStore } = await loadStore();
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+
+ expect(splitGroupStore.getSnapshot().root).toMatchObject({
+ type: 'split',
+ direction: 'row',
+ first: { type: 'pane', sessionId: 'session-a' },
+ second: {
+ type: 'split',
+ direction: 'column',
+ first: { type: 'pane', sessionId: 'session-b' },
+ second: { type: 'pane', sessionId: 'session-c' },
+ },
+ });
+ });
+
+ it('继续拆左侧后支持左二右二', async () => {
+ const { getSplitSessionIds, splitGroupStore } = await loadStore();
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ splitGroupStore.addSession('session-d', 'session-a', 'bottom');
+
+ const root = splitGroupStore.getSnapshot().root;
+ expect(root).toMatchObject({
+ type: 'split',
+ direction: 'row',
+ first: {
+ type: 'split',
+ direction: 'column',
+ first: { type: 'pane', sessionId: 'session-a' },
+ second: { type: 'pane', sessionId: 'session-d' },
+ },
+ second: {
+ type: 'split',
+ direction: 'column',
+ first: { type: 'pane', sessionId: 'session-b' },
+ second: { type: 'pane', sessionId: 'session-c' },
+ },
+ });
+ expect(getSplitSessionIds(root)).toEqual(['session-a', 'session-d', 'session-b', 'session-c']);
+ });
+
+ it('重复任务、非法 anchor 与上限不会修改状态', async () => {
+ const { getSplitPanes, MAX_SPLIT_PANES, splitGroupStore } = await loadStore();
+ expect(splitGroupStore.addSession('session-b', 'session-a', 'right')).toBe(true);
+ const initial = splitGroupStore.getSnapshot();
+
+ expect(splitGroupStore.addSession('session-b', 'session-a', 'left')).toBe(false);
+ expect(splitGroupStore.addSession('session-c', 'missing', 'right')).toBe(false);
+ expect(splitGroupStore.getAddBlockReason('session-b', 'session-a')).toBe('duplicate');
+ expect(splitGroupStore.getAddBlockReason('session-c', 'missing')).toBe('missing-anchor');
+ expect(splitGroupStore.getSnapshot()).toBe(initial);
+
+ for (let index = 3; index <= MAX_SPLIT_PANES; index += 1) {
+ expect(splitGroupStore.addSession(`session-${index}`, 'session-b', 'bottom')).toBe(true);
+ }
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root)).toHaveLength(MAX_SPLIT_PANES);
+ const atLimit = splitGroupStore.getSnapshot();
+ expect(splitGroupStore.getAddBlockReason('session-over-limit', 'session-b')).toBe(
+ 'limit-reached',
+ );
+ expect(splitGroupStore.addSession('session-over-limit', 'session-b', 'right')).toBe(false);
+ expect(splitGroupStore.getSnapshot()).toBe(atLimit);
+ });
+
+ it('移除 pane 时递归塌缩单子节点,剩单格时退出分屏', async () => {
+ const { splitGroupStore } = await loadStore();
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+
+ splitGroupStore.removeSession('session-c');
+ expect(splitGroupStore.getSnapshot().root).toMatchObject({
+ type: 'split',
+ direction: 'row',
+ first: { sessionId: 'session-a' },
+ second: { sessionId: 'session-b' },
+ });
+
+ splitGroupStore.removeSession('session-b');
+ expect(splitGroupStore.getSnapshot()).toEqual({ root: null });
+ });
+
+ it('替换 session 保留 pane key 和树位置', async () => {
+ const { getSplitPanes, splitGroupStore } = await loadStore();
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ const before = getSplitPanes(splitGroupStore.getSnapshot().root);
+
+ splitGroupStore.replaceSession('session-a', 'session-c');
+
+ const after = getSplitPanes(splitGroupStore.getSnapshot().root);
+ expect(after.map((pane) => pane.sessionId)).toEqual(['session-c', 'session-b']);
+ expect(after[0].key).toBe(before[0].key);
+ });
+
+ it('分支比例夹到下限,并仅切换根方向', async () => {
+ const { MIN_SPLIT_CHILD_FRACTION, splitGroupStore } = await loadStore();
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ splitGroupStore.addSession('session-c', 'session-b', 'bottom');
+ const root = splitGroupStore.getSnapshot().root;
+ expect(root?.type).toBe('split');
+ if (!root || root.type !== 'split') throw new Error('root split missing');
+ const nested = root.second;
+ expect(nested.type).toBe('split');
+ if (nested.type !== 'split') throw new Error('nested split missing');
+
+ splitGroupStore.setSplitFraction(nested.key, 1);
+ splitGroupStore.toggleRootDirection();
+
+ const next = splitGroupStore.getSnapshot().root;
+ expect(next).toMatchObject({
+ type: 'split',
+ direction: 'column',
+ second: {
+ type: 'split',
+ direction: 'column',
+ fraction: 1 - MIN_SPLIT_CHILD_FRACTION,
+ },
+ });
+ });
+
+ it('v1 平铺存档自动迁移为同方向递归树并删除旧 key', async () => {
+ storageData.set(
+ 'cc-agent.splitGroup.v1',
+ JSON.stringify({
+ direction: 'column',
+ panes: [
+ { key: 'one', sessionId: 'session-a', fraction: 0.25 },
+ { key: 'two', sessionId: 'session-b', fraction: 0.25 },
+ { key: 'three', sessionId: 'session-c', fraction: 0.5 },
+ ],
+ }),
+ );
+
+ const {
+ getSplitSessionIds,
+ LEGACY_SPLIT_GROUP_STORAGE_KEY,
+ SPLIT_GROUP_STORAGE_KEY,
+ splitGroupStore,
+ } = await loadStore();
+ const snapshot = splitGroupStore.getSnapshot();
+
+ expect(getSplitSessionIds(snapshot.root)).toEqual(['session-a', 'session-b', 'session-c']);
+ expect(snapshot.root).toMatchObject({
+ type: 'split',
+ direction: 'column',
+ fraction: 0.25,
+ second: { type: 'split', direction: 'column' },
+ });
+ expect(storageData.has(LEGACY_SPLIT_GROUP_STORAGE_KEY)).toBe(false);
+ expect(JSON.parse(storageData.get(SPLIT_GROUP_STORAGE_KEY) ?? '{}')).toEqual(snapshot);
+ });
+
+ it('副窗口不读取主窗持久化的分屏布局', async () => {
+ storageData.set(
+ 'cc-agent.splitGroup.v2',
+ JSON.stringify({
+ root: {
+ type: 'split',
+ key: 'split-main',
+ direction: 'row',
+ fraction: 0.5,
+ first: { type: 'pane', key: 'pane-a', sessionId: 'session-a' },
+ second: { type: 'pane', key: 'pane-b', sessionId: 'session-b' },
+ },
+ }),
+ );
+ secondaryWindow = true;
+
+ const { splitGroupStore } = await loadStore();
+
+ expect(splitGroupStore.getSnapshot()).toEqual({ root: null });
+ expect(splitGroupStore.isActive()).toBe(false);
+ });
+
+ it('副窗口分屏仅存内存,不覆盖主窗共享存储', async () => {
+ const mainWindowLayout = JSON.stringify({
+ root: {
+ type: 'split',
+ key: 'split-main',
+ direction: 'row',
+ fraction: 0.5,
+ first: { type: 'pane', key: 'pane-a', sessionId: 'session-a' },
+ second: { type: 'pane', key: 'pane-b', sessionId: 'session-b' },
+ },
+ });
+ storageData.set('cc-agent.splitGroup.v2', mainWindowLayout);
+ secondaryWindow = true;
+
+ const { getSplitSessionIds, SPLIT_GROUP_STORAGE_KEY, splitGroupStore } = await loadStore();
+ splitGroupStore.addSession('session-d', 'session-c', 'right');
+ expect(getSplitSessionIds(splitGroupStore.getSnapshot().root)).toEqual([
+ 'session-c',
+ 'session-d',
+ ]);
+
+ splitGroupStore.clear();
+ expect(splitGroupStore.getSnapshot()).toEqual({ root: null });
+ expect(storageData.get(SPLIT_GROUP_STORAGE_KEY)).toBe(mainWindowLayout);
+ });
+
+ it('损坏存档与 localStorage 异常均静默退化为空状态', async () => {
+ storageData.set('cc-agent.splitGroup.v2', '{broken');
+ let module = await loadStore();
+ expect(module.splitGroupStore.getSnapshot()).toEqual({ root: null });
+
+ vi.resetModules();
+ vi.stubGlobal('localStorage', {
+ getItem: () => {
+ throw new Error('storage unavailable');
+ },
+ removeItem: () => {
+ throw new Error('storage unavailable');
+ },
+ setItem: () => {
+ throw new Error('storage unavailable');
+ },
+ });
+ module = await loadStore();
+ expect(() =>
+ module.splitGroupStore.addSession('session-b', 'session-a', 'right'),
+ ).not.toThrow();
+ expect(module.getSplitPanes(module.splitGroupStore.getSnapshot().root)).toHaveLength(2);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/embeddedSessionNavigation.tsx b/apps/desktop/src/renderer/features/cc-agent/embeddedSessionNavigation.tsx
index 71394d6aed..064c63ecdc 100644
--- a/apps/desktop/src/renderer/features/cc-agent/embeddedSessionNavigation.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/embeddedSessionNavigation.tsx
@@ -1,35 +1,46 @@
import { createContext, useContext, type ReactNode } from 'react';
/** 会话视图的路由所有权;sidebar-embedded 只展示内容,不拥有窗口路由。 */
-export type SessionNavigationMode = 'route-owner' | 'sidebar-embedded';
+export type SessionNavigationMode = 'route-owner' | 'sidebar-embedded' | 'split-pane';
const SessionNavigationModeContext = createContext<SessionNavigationMode>('route-owner');
+export type SessionNavigationIntentReporter = (
+ targetSessionId: string,
+ routeOwnerSessionId?: string,
+) => void;
+const SessionNavigationIntentContext = createContext<SessionNavigationIntentReporter | null>(null);
const SidebarTargetSessionIdContext = createContext<string | null>(null);
const SidebarPanelHostSessionIdContext = createContext<string | null>(null);
export function SessionNavigationModeProvider({
mode,
+ onSessionNavigate,
sidebarTargetSessionId,
sidebarPanelHostSessionId,
children,
}: {
mode: SessionNavigationMode;
+ /** 分屏 pane 在真正改路由前上报目标任务,供 SplitGroup 选择被替换的来源 pane。 */
+ onSessionNavigate?: SessionNavigationIntentReporter;
/** 内嵌内容触发 RSB 动作时使用的可见 bucket;不传则沿用内容 session。 */
sidebarTargetSessionId?: string;
/**
- * 右栏面板此刻真正显示的那个会话(= 声明了右栏在场的聊天实例的 session)。
- * 只有它的 bucket 打开后用户看得见;内嵌实例不传,表示「本视图里打不开面板」。
+ * 当前子树的面板动作可以到达的会话 bucket。路由主实例的 bucket 已在场;可见
+ * split pane 会在点击前接管路由,因此自己的 bucket 也可达。其它内嵌实例不传,
+ * 表示「本视图里打不开该面板」。
*/
sidebarPanelHostSessionId?: string;
children: ReactNode;
}) {
return (
<SessionNavigationModeContext.Provider value={mode}>
- <SidebarTargetSessionIdContext.Provider value={sidebarTargetSessionId ?? null}>
- <SidebarPanelHostSessionIdContext.Provider value={sidebarPanelHostSessionId ?? null}>
- {children}
- </SidebarPanelHostSessionIdContext.Provider>
- </SidebarTargetSessionIdContext.Provider>
+ <SessionNavigationIntentContext.Provider value={onSessionNavigate ?? null}>
+ <SidebarTargetSessionIdContext.Provider value={sidebarTargetSessionId ?? null}>
+ <SidebarPanelHostSessionIdContext.Provider value={sidebarPanelHostSessionId ?? null}>
+ {children}
+ </SidebarPanelHostSessionIdContext.Provider>
+ </SidebarTargetSessionIdContext.Provider>
+ </SessionNavigationIntentContext.Provider>
</SessionNavigationModeContext.Provider>
);
}
@@ -38,6 +49,15 @@ export function useSessionNavigationMode(): SessionNavigationMode {
return useContext(SessionNavigationModeContext);
}
+/** 在组件调用 navigate 前记录目标任务;普通路由与 sidebar-embedded 默认无需处理。 */
+export function useSessionNavigationIntent(): SessionNavigationIntentReporter | null {
+ return useContext(SessionNavigationIntentContext);
+}
+
+export function isInteractiveSessionNavigationMode(mode: SessionNavigationMode): boolean {
+ return mode !== 'sidebar-embedded';
+}
+
/**
* 返回显式可见 RSB bucket;普通会话未注入时回退内容 session。
* contentSessionId 缺失仍表示调用点没有侧栏动作能力,Provider 只改目标、不负责启用动作。
@@ -49,13 +69,14 @@ export function useSidebarTargetSessionId(contentSessionId?: string): string | u
}
/**
- * 「该会话自己的右栏面板此刻打开后用户看得见吗」——面板类入口(后台任务面板等)
+ * 「该会话自己的右栏面板通过当前交互能否到达」——面板类入口(后台任务面板等)
* 的 affordance 判据。
*
* 面板按 session 分桶,而右栏一次只显示一个桶:显示哪个桶由「声明了右栏在场的
- * 那个聊天实例」决定(CCAgentSessionView 的 ownsRoute)。内嵌实例(协同 worker
- * 面板、workdir-browse 窄 rail、Orca split 双栏)都不声明在场,往它们自己的桶里
- * 写 tab 只会写进一个用户到不了的桶,点击必然无响应 —— 不给假 affordance
+ * 那个聊天实例」决定。路由主实例当前可达;可见 split pane 会先接管路由再显示
+ * 自己的 bucket。其它内嵌实例(协同 worker 面板、workdir-browse 窄 rail、Orca
+ * split 双栏)都不可达,往它们自己的桶里写 tab 只会写进用户到不了的桶,点击
+ * 必然无响应 —— 不给假 affordance
* (与 BackgroundTasksBody 里非 workflow 行的 isSidebarWindow 守卫同款口径)。
*/
export function useSidebarPanelReachable(contentSessionId?: string): boolean {
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/OpenInSplitMenu.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/OpenInSplitMenu.tsx
new file mode 100644
index 0000000000..686ccdcc5b
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/OpenInSplitMenu.tsx
@@ -0,0 +1,114 @@
+import { ChevronRight } from 'lucide-react';
+import { useId } from 'react';
+import { useLocation } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
+
+import {
+ DropdownMenuItem,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+} from '@/components/ui/dropdown-menu';
+import { resolveAgentIslandVisibleSessionIdFromPath } from '@/lib/agentIslandVisibleSessionRoute';
+import { toast } from '@/lib/toast';
+import {
+ MAX_SPLIT_PANES,
+ splitGroupStore,
+ useSplitGroup,
+ type DropSide,
+ type SplitGroupAddBlockReason,
+} from '../splitGroupStore';
+import { MENU_ITEM_CLASS, MENU_ROW_CLASS, MENU_SUB_CONTENT_CLASS } from './menuStyles';
+
+function addBlockedMessage(
+ reason: SplitGroupAddBlockReason | null,
+ t: ReturnType<typeof useTranslation>['t'],
+ isWorker: boolean,
+): string {
+ if (isWorker) return t('splitGroup.workerUnavailable');
+ if (reason === 'limit-reached') {
+ return t('splitGroup.limitReached', { count: MAX_SPLIT_PANES });
+ }
+ if (reason === 'duplicate') return t('splitGroup.alreadyOpen');
+ return t('splitGroup.addUnavailable');
+}
+
+export function OpenInSplitMenu({
+ sessionId,
+ orcaRole,
+ onOpenSession,
+}: {
+ sessionId: string;
+ orcaRole?: string | null;
+ onOpenSession: () => void;
+}) {
+ const { t } = useTranslation();
+ const location = useLocation();
+ const blockedReasonId = useId();
+ useSplitGroup();
+ const anchorSessionId = resolveAgentIslandVisibleSessionIdFromPath(location.pathname) ?? '';
+ const blockReason =
+ orcaRole === 'worker'
+ ? 'invalid'
+ : splitGroupStore.getAddBlockReason(sessionId, anchorSessionId);
+ const blockedMessage = blockReason
+ ? addBlockedMessage(blockReason, t, orcaRole === 'worker')
+ : undefined;
+
+ const open = (side: DropSide) => {
+ const currentBlockReason =
+ orcaRole === 'worker'
+ ? 'invalid'
+ : splitGroupStore.getAddBlockReason(sessionId, anchorSessionId);
+ if (currentBlockReason || !splitGroupStore.addSession(sessionId, anchorSessionId, side)) {
+ toast.warning(addBlockedMessage(currentBlockReason, t, orcaRole === 'worker'));
+ return;
+ }
+ onOpenSession();
+ };
+
+ if (blockedMessage) {
+ return (
+ <DropdownMenuItem
+ aria-disabled="true"
+ aria-label={t('splitGroup.openInSplit')}
+ aria-describedby={blockedReasonId}
+ title={blockedMessage}
+ onSelect={(event) => {
+ event.preventDefault();
+ toast.warning(blockedMessage);
+ }}
+ className={`${MENU_ITEM_CLASS} h-auto min-h-8 cursor-default items-start py-1.5 aria-disabled:opacity-60`}
+ >
+ <span className="min-w-0">
+ <span className="block">{t('splitGroup.openInSplit')}</span>
+ <span
+ id={blockedReasonId}
+ className="block whitespace-normal text-xs text-[var(--cmd-palette-item-meta)]"
+ >
+ {blockedMessage}
+ </span>
+ </span>
+ </DropdownMenuItem>
+ );
+ }
+
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger aria-label={t('splitGroup.openInSplit')} className={MENU_ROW_CLASS}>
+ <span className="flex-1">{t('splitGroup.openInSplit')}</span>
+ <ChevronRight size={14} className="ml-2 shrink-0 text-[var(--cmd-palette-item-meta)]" />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ sideOffset={4}
+ className={`${MENU_SUB_CONTENT_CLASS} min-w-36 overflow-hidden`}
+ >
+ {(['left', 'right', 'top', 'bottom'] as const).map((side) => (
+ <DropdownMenuItem key={side} onSelect={() => open(side)} className={MENU_ITEM_CLASS}>
+ {t(`splitGroup.openSide.${side}`)}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index 969b09233d..2cf6e4e8c1 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -79,6 +79,7 @@ import { loadScheduleSidebarIndexRuns } from '@/features/scheduler/lib/scheduleS
import { resolveSidebarRightStatus } from './sidebarRightStatus';
import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';
import { shouldPrefetchSessionOnPointerDown } from './sessionSwitchPrefetch';
+import { OpenInSplitMenu } from './OpenInSplitMenu';
const log = createLogger('SessionCard');
@@ -424,6 +425,13 @@ export function SessionCard({
{t('ccAgent.sidebar.sessionMenu.copySessionLink')}
</DropdownMenuItem>
);
+ const openInSplitMenu = (
+ <OpenInSplitMenu
+ sessionId={session.id}
+ orcaRole={session.orcaRole}
+ onOpenSession={() => onClick(session.id)}
+ />
+ );
// Orca lead 可导出(整个协同随包);Worker 不进 sidebar,双保险仍排除。
const canExportShare =
@@ -922,6 +930,7 @@ export function SessionCard({
{t('ccAgent.sidebar.sessionMenu.unarchive')}
</DropdownMenuItem>
{exportShareMenuItem}
+ {openInSplitMenu}
{copySessionIdSubmenu}
<DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
<DropdownMenuItem
@@ -941,6 +950,7 @@ export function SessionCard({
>
{t('ccAgent.sidebar.sessionMenu.rename')}
</DropdownMenuItem>
+ {openInSplitMenu}
{copySessionIdSubmenu}
<DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
<DropdownMenuItem
@@ -969,6 +979,7 @@ export function SessionCard({
</DropdownMenuItem>
{moveToProjectSubmenu}
<DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
+ {openInSplitMenu}
{copySessionIdSubmenu}
<DropdownMenuItem
disabled={remoteWritesBlocked}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
index d281403794..27486cc6cf 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -30,7 +30,7 @@
*/
import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
-import type { MouseEvent as ReactMouseEvent, ReactNode } from 'react';
+import type { DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, ReactNode } from 'react';
import { Archive, ChevronRight, EllipsisVertical, Play, Undo } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -73,7 +73,10 @@ import {
isEmptyDraftSession,
} from '../lib/sessionDisplayTitle';
import { useSessionBoundSchedules } from '@/features/scheduler/lib/scheduleSessionBinding';
-import { loadScheduleSidebarIndexRuns, type ScheduleSidebarIndexRun } from '@/features/scheduler/lib/scheduleSidebarIndexRuns';
+import {
+ loadScheduleSidebarIndexRuns,
+ type ScheduleSidebarIndexRun,
+} from '@/features/scheduler/lib/scheduleSidebarIndexRuns';
import { useSchedulesSnapshot } from '@/features/scheduler/lib/schedulesStore';
import { scheduleFocusPath } from '@/features/scheduler/lib/scheduleSessionBinding';
import { ScheduleBindingBadge } from './ScheduleBindingBadge';
@@ -91,7 +94,9 @@ import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionAc
import { resolveSidebarRightStatus } from './sidebarRightStatus';
import { AutomationTimerIcon } from './AutomationTimerIcon';
import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';
+import { isSplitGroupDragSource, writeSplitGroupSessionDragData } from '../splitGroupDnd';
import { shouldPrefetchSessionOnPointerDown } from './sessionSwitchPrefetch';
+import { OpenInSplitMenu } from './OpenInSplitMenu';
// Module-level dedup cache for loadScheduleSidebarIndexRuns.
// When many ungrouped automation rows mount simultaneously they all need the
@@ -350,16 +355,22 @@ export const SessionItem = memo(function SessionItem({
: remoteActivity.phase === 'running'
? ('running' as const)
: ('done' as const);
- const rightStatusKind = remoteRightStatus ?? resolveSidebarRightStatus({
- attentionKind,
- isUrgentFromContext,
- isRunning,
- hasAttentionNotification,
- });
+ const rightStatusKind =
+ remoteRightStatus ??
+ resolveSidebarRightStatus({
+ attentionKind,
+ isUrgentFromContext,
+ isRunning,
+ hasAttentionNotification,
+ });
const showRightStatus = rightStatusKind !== 'time';
- const remoteIconKind = session.deviceLinkDeviceId ? 'device-link' : session.remoteHostId ? 'ssh' : null;
+ const remoteIconKind = session.deviceLinkDeviceId
+ ? 'device-link'
+ : session.remoteHostId
+ ? 'ssh'
+ : null;
const remoteIconConnectionStatus = session.deviceLinkDeviceId
- ? session.deviceLinkConnectionStatus ?? 'connected'
+ ? (session.deviceLinkConnectionStatus ?? 'connected')
: null;
const remoteWritesBlocked = isRemoteSessionWriteBlocked(session);
const isAutomationGenerated = isAutomationGeneratedSession(session);
@@ -390,7 +401,9 @@ export const SessionItem = memo(function SessionItem({
// 组件卸载后 setState。null 明确表示「查过但没映射」,undefined 表示「还没查」——
// 两者都不显示按钮,避免闪现。
const shouldResolveSchedule = isAutomationGenerated && !insideAutomationGroup;
- const [resolvedScheduleId, setResolvedScheduleId] = useState<string | null | undefined>(undefined);
+ const [resolvedScheduleId, setResolvedScheduleId] = useState<string | null | undefined>(
+ undefined,
+ );
useEffect(() => {
if (!shouldResolveSchedule) return;
let cancelled = false;
@@ -416,8 +429,7 @@ export const SessionItem = memo(function SessionItem({
const schedulesSnapshot = useSchedulesSnapshot();
const scheduleStillExists =
resolvedScheduleId != null &&
- (schedulesSnapshot == null ||
- schedulesSnapshot.some((s) => s.id === resolvedScheduleId));
+ (schedulesSnapshot == null || schedulesSnapshot.some((s) => s.id === resolvedScheduleId));
const effectiveScheduleId = scheduleStillExists ? resolvedScheduleId : null;
const handleAutomationRunClick = useCallback(async () => {
if (!effectiveScheduleId) {
@@ -541,13 +553,46 @@ export const SessionItem = memo(function SessionItem({
[displayTitle, isEditing, remoteWritesBlocked, t],
);
+ // SortableJS(置顶/项目手动排序,forceFallback 指针手势)与原生 HTML5 拖拽会争抢
+ // 同一次手势:行带 `draggable` 时浏览器可能启动原生拖拽并中断 fallback 排序。这些
+ // 行保持原有排序拖拽,分屏拖拽源只留给非 Sortable 容器(时间排序的对话列表等)。
+ // 首帧先按 Sortable 容器处理,避免 ref effect 运行前短暂开启原生分屏拖拽。
+ const [inSortableContainer, setInSortableContainer] = useState(true);
+ useEffect(() => {
+ setInSortableContainer(Boolean(rowRef.current?.closest('[data-sortable-id]')));
+ }, []);
+ const splitDragEnabled = isSplitGroupDragSource({
+ editing: isEditing,
+ orcaRole: session.orcaRole,
+ inSortableContainer,
+ });
+
+ const handleDragStart = useCallback(
+ (event: ReactDragEvent<HTMLDivElement>) => {
+ const target = event.target instanceof Element ? event.target : null;
+ if (
+ !splitDragEnabled ||
+ (target !== event.currentTarget &&
+ target?.closest('button, input, textarea, select, a[href], [role="menuitem"]'))
+ ) {
+ event.preventDefault();
+ return;
+ }
+ if (!writeSplitGroupSessionDragData(event.dataTransfer, session.id)) {
+ event.preventDefault();
+ return;
+ }
+ event.currentTarget.dataset.sessionDragging = 'true';
+ },
+ [splitDragEnabled, session.id],
+ );
+
// isActive 由 false → true(或初次 mount 时即为 true)→ 把行滚进 viewport。
// 同 active 重渲染 / 其它字段更新不触发(useEffect deps 只有 isActive)。
useEffect(() => {
if (isActive) scrollIntoNearestView(rowRef.current);
}, [isActive]);
-
// archivePending 生命周期:进入 pending → 起 4s 自动撤回 timer + document mousedown
// 监听(点击不在 confirm 胶囊上就立刻撤回)。退出 pending → 全部清理。这两条退路确保
// 用户不会因为忘了取消而误归档,也不会让 pending 态滞留把行的 hover 行为锁死。
@@ -669,13 +714,17 @@ export const SessionItem = memo(function SessionItem({
// 渲染成会话 chip)。原「复制会话 ID」二级菜单(深度链接 / 仅 ID / Agent)已按
// 产品决策收敛为这一项;不自带分隔线,分组由各使用点决定,避免菜单被切得过碎。
const copySessionIdSubmenu = (
- <DropdownMenuItem
- onSelect={() => void handleCopyDeepLinkSelect()}
- className={MENU_ITEM_CLASS}
- >
+ <DropdownMenuItem onSelect={() => void handleCopyDeepLinkSelect()} className={MENU_ITEM_CLASS}>
{t('ccAgent.sidebar.sessionMenu.copySessionLink')}
</DropdownMenuItem>
);
+ const openInSplitMenu = (
+ <OpenInSplitMenu
+ sessionId={session.id}
+ orcaRole={session.orcaRole}
+ onOpenSession={() => onClick(session.id)}
+ />
+ );
const canMoveToProject =
Boolean(onMoveSession) &&
@@ -727,8 +776,14 @@ export const SessionItem = memo(function SessionItem({
ref={rowRef}
data-session-id={session.id}
data-sidebar-session-row="true"
+ data-split-group-drag-source={splitDragEnabled ? 'true' : undefined}
+ draggable={splitDragEnabled}
role="button"
tabIndex={0}
+ onDragStart={handleDragStart}
+ onDragEnd={(event) => {
+ delete event.currentTarget.dataset.sessionDragging;
+ }}
onPointerDown={(e) => {
if (shouldPrefetchSessionOnPointerDown(e, { isActive, isEditing })) {
makerChatStore.ensureInitialMessages(session.id);
@@ -772,7 +827,8 @@ export const SessionItem = memo(function SessionItem({
// 否则归档/取消归档后 DOM 列表重排,原 hover bg 在前一个屏幕位置上要
// 跑完 150ms 渐变才褪掉,视觉上像是"旧行仍然选中,延迟才切到新行"。
// 用 ProjectAction 同款瞬时反馈,跟 Cursor / Codex sidebar 的体感一致。
- 'text-sm font-medium text-left cursor-pointer',
+ 'text-left text-sm font-medium',
+ !isEditing && (splitDragEnabled ? 'cursor-grab active:cursor-grabbing' : 'cursor-pointer'),
// active 描边必须画在盒内且不参与布局。真实 border 会让固定宽高的
// border-box 内容区四边各缩 1px,导致选中行的左侧 icon / 标题整体右移。
isActive
@@ -854,7 +910,9 @@ export const SessionItem = memo(function SessionItem({
size={12}
strokeWidth={1.8}
connectionStatus={remoteIconConnectionStatus}
- className={cn(isActive ? 'text-sidebar-item-active-foreground' : 'text-sidebar-action-icon')}
+ className={cn(
+ isActive ? 'text-sidebar-item-active-foreground' : 'text-sidebar-action-icon',
+ )}
/>
)}
</span>
@@ -959,15 +1017,20 @@ export const SessionItem = memo(function SessionItem({
未归档 + 非 draft + 非远程只读。Edit 与左侧 Timer chip 同链路,不再重复
暴露;Run 走 main.maker.schedule.runNow,与 AutomationSessionGroupItem
组头 [Run ▶️][More ⋮] 保持高频直点、低频收纳的同构。 */}
- {isAutomationGenerated && !insideAutomationGroup && !isArchived && !isEmpty && !remoteWritesBlocked && effectiveScheduleId && (
- <SessionAction
- label={t('ccAgent.sidebar.automationGroup.menu.runNow')}
- onClick={() => void handleAutomationRunClick()}
- isActive={isActive}
- >
- <Play size={14} strokeWidth={2} />
- </SessionAction>
- )}
+ {isAutomationGenerated &&
+ !insideAutomationGroup &&
+ !isArchived &&
+ !isEmpty &&
+ !remoteWritesBlocked &&
+ effectiveScheduleId && (
+ <SessionAction
+ label={t('ccAgent.sidebar.automationGroup.menu.runNow')}
+ onClick={() => void handleAutomationRunClick()}
+ isActive={isActive}
+ >
+ <Play size={14} strokeWidth={2} />
+ </SessionAction>
+ )}
<SessionAction
label={t('ccAgent.sidebar.sessionMenu.moreActions')}
onClick={(e) => {
@@ -1071,6 +1134,7 @@ export const SessionItem = memo(function SessionItem({
{t('ccAgent.sidebar.sessionMenu.unarchive')}
</DropdownMenuItem>
{exportShareMenuItem}
+ {openInSplitMenu}
{copySessionIdSubmenu}
<DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
<DropdownMenuItem
@@ -1091,6 +1155,7 @@ export const SessionItem = memo(function SessionItem({
>
{t('ccAgent.sidebar.sessionMenu.rename')}
</DropdownMenuItem>
+ {openInSplitMenu}
{copySessionIdSubmenu}
<DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
<DropdownMenuItem
@@ -1122,6 +1187,7 @@ export const SessionItem = memo(function SessionItem({
</DropdownMenuItem>
{moveToProjectSubmenu}
<DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
+ {openInSplitMenu}
{copySessionIdSubmenu}
<DropdownMenuItem
disabled={remoteWritesBlocked}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/OpenInSplitMenu.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/OpenInSplitMenu.test.tsx
new file mode 100644
index 0000000000..68517c3132
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/OpenInSplitMenu.test.tsx
@@ -0,0 +1,161 @@
+// @vitest-environment jsdom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { getSplitPanes, splitGroupStore } from '../../splitGroupStore';
+import { OpenInSplitMenu } from '../OpenInSplitMenu';
+
+const { toastWarningMock } = vi.hoisted(() => ({
+ toastWarningMock: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/lib/toast', () => ({
+ toast: { warning: toastWarningMock },
+}));
+
+function renderMenu(
+ sessionId: string,
+ onOpenSession = vi.fn(),
+ options: { initialEntry?: string; orcaRole?: string } = {},
+) {
+ render(
+ <MemoryRouter initialEntries={[options.initialEntry ?? '/cc-agent/session-a']}>
+ <DropdownMenu defaultOpen modal={false}>
+ <DropdownMenuTrigger>More</DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <OpenInSplitMenu
+ sessionId={sessionId}
+ orcaRole={options.orcaRole}
+ onOpenSession={onOpenSession}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </MemoryRouter>,
+ );
+ return onOpenSession;
+}
+
+describe('OpenInSplitMenu', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ toastWarningMock.mockClear();
+ splitGroupStore.__resetForTest();
+ });
+
+ afterEach(() => {
+ cleanup();
+ splitGroupStore.__resetForTest();
+ });
+
+ it('opens all four split actions from the keyboard and applies the selected direction', async () => {
+ const onOpenSession = renderMenu('session-b');
+ const submenuTrigger = await screen.findByRole('menuitem', {
+ name: 'splitGroup.openInSplit',
+ });
+
+ await act(async () => {
+ submenuTrigger.focus();
+ fireEvent.keyDown(submenuTrigger, { key: 'ArrowRight' });
+ await Promise.resolve();
+ });
+
+ for (const side of ['left', 'right', 'top', 'bottom']) {
+ expect(
+ await screen.findByRole('menuitem', { name: `splitGroup.openSide.${side}` }),
+ ).toBeTruthy();
+ }
+ await act(async () => {
+ fireEvent.click(screen.getByRole('menuitem', { name: 'splitGroup.openSide.right' }));
+ await Promise.resolve();
+ });
+
+ expect(onOpenSession).toHaveBeenCalledTimes(1);
+ expect(getSplitPanes(splitGroupStore.getSnapshot().root).map((pane) => pane.sessionId)).toEqual(
+ ['session-a', 'session-b'],
+ );
+ expect(splitGroupStore.getSnapshot().root).toMatchObject({ type: 'split', direction: 'row' });
+ });
+
+ it('keeps an unavailable entry as a valid focusable menu item with an actionable reason', async () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ renderMenu('session-b');
+ const submenuTrigger = await screen.findByRole('menuitem', {
+ name: 'splitGroup.openInSplit',
+ description: 'splitGroup.alreadyOpen',
+ });
+
+ expect(submenuTrigger.getAttribute('aria-disabled')).toBe('true');
+ expect(submenuTrigger.hasAttribute('data-disabled')).toBe(false);
+ act(() => submenuTrigger.focus());
+ expect(document.activeElement).toBe(submenuTrigger);
+ expect(submenuTrigger.textContent).toContain('splitGroup.alreadyOpen');
+ });
+
+ it('explains that Worker sessions must be opened through their Lead', async () => {
+ renderMenu('worker-b', vi.fn(), { orcaRole: 'worker' });
+
+ expect(
+ await screen.findByRole('menuitem', {
+ name: 'splitGroup.openInSplit',
+ description: 'splitGroup.workerUnavailable',
+ }),
+ ).toBeTruthy();
+ });
+
+ it('reports the pane limit separately from a missing route anchor', async () => {
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ for (let index = 3; index <= 8; index += 1) {
+ splitGroupStore.addSession(`session-${index}`, 'session-b', 'bottom');
+ }
+ });
+ const firstView = renderMenu('session-over-limit');
+ expect(
+ await screen.findByRole('menuitem', {
+ name: 'splitGroup.openInSplit',
+ description: 'splitGroup.limitReached',
+ }),
+ ).toBeTruthy();
+
+ cleanup();
+ splitGroupStore.__resetForTest();
+ act(() => {
+ splitGroupStore.addSession('session-b', 'session-a', 'right');
+ });
+ renderMenu('session-c', firstView, { initialEntry: '/cc-agent/session-missing' });
+
+ expect(
+ await screen.findByRole('menuitem', {
+ name: 'splitGroup.openInSplit',
+ description: 'splitGroup.addUnavailable',
+ }),
+ ).toBeTruthy();
+ });
+
+ it('uses the generic unavailable reason for a normal session without a route anchor', async () => {
+ renderMenu('session-b', vi.fn(), { initialEntry: '/cc-agent' });
+
+ expect(
+ await screen.findByRole('menuitem', {
+ name: 'splitGroup.openInSplit',
+ description: 'splitGroup.addUnavailable',
+ }),
+ ).toBeTruthy();
+ expect(screen.queryByText('splitGroup.workerUnavailable')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
index 382fa40e29..dcdf008b5e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
@@ -7,12 +7,27 @@ const sidebarDir = resolve(__dirname, '..');
const sessionCardSource = readFileSync(resolve(sidebarDir, 'SessionCard.tsx'), 'utf8');
const sessionEntryListSource = readFileSync(resolve(sidebarDir, 'SessionEntryList.tsx'), 'utf8');
const sessionItemSource = readFileSync(resolve(sidebarDir, 'SessionItem.tsx'), 'utf8');
-const sessionRenameInputSource = readFileSync(resolve(sidebarDir, '..', 'SessionRenameInput.tsx'), 'utf8');
+const sessionRenameInputSource = readFileSync(
+ resolve(sidebarDir, '..', 'SessionRenameInput.tsx'),
+ 'utf8',
+);
const sessionStatusIconSource = readFileSync(resolve(sidebarDir, 'SessionStatusIcon.tsx'), 'utf8');
-const automationGroupSource = readFileSync(resolve(sidebarDir, 'AutomationSessionGroupItem.tsx'), 'utf8');
-const automationTimerIconSource = readFileSync(resolve(sidebarDir, 'AutomationTimerIcon.tsx'), 'utf8');
-const scheduleBindingBadgeSource = readFileSync(resolve(sidebarDir, 'ScheduleBindingBadge.tsx'), 'utf8');
-const globalsSource = readFileSync(resolve(__dirname, '..', '..', '..', '..', 'styles', 'globals.css'), 'utf8');
+const automationGroupSource = readFileSync(
+ resolve(sidebarDir, 'AutomationSessionGroupItem.tsx'),
+ 'utf8',
+);
+const automationTimerIconSource = readFileSync(
+ resolve(sidebarDir, 'AutomationTimerIcon.tsx'),
+ 'utf8',
+);
+const scheduleBindingBadgeSource = readFileSync(
+ resolve(sidebarDir, 'ScheduleBindingBadge.tsx'),
+ 'utf8',
+);
+const globalsSource = readFileSync(
+ resolve(__dirname, '..', '..', '..', '..', 'styles', 'globals.css'),
+ 'utf8',
+);
describe('SessionCard review regressions', () => {
it('only draws the list top divider on the first overall entry', () => {
@@ -23,7 +38,9 @@ describe('SessionCard review regressions', () => {
});
it('keeps awaiting text in list mode previews', () => {
- expect(sessionCardSource).toContain('const listPreview = awaitingText ?? runningDetail ?? summaryPreview');
+ expect(sessionCardSource).toContain(
+ 'const listPreview = awaitingText ?? runningDetail ?? summaryPreview',
+ );
expect(sessionCardSource).toContain('{listPreview}');
});
@@ -105,8 +122,12 @@ describe('SessionCard review regressions', () => {
});
it('keeps one Timer glyph for scheduled and automation sessions', () => {
- expect(sessionCardSource).toContain('const showScheduleBindingBadge = boundSchedules.length > 0');
- expect(sessionCardSource).toContain('const showAutomationTimer = !showScheduleBindingBadge && isAutomationGenerated');
+ expect(sessionCardSource).toContain(
+ 'const showScheduleBindingBadge = boundSchedules.length > 0',
+ );
+ expect(sessionCardSource).toContain(
+ 'const showAutomationTimer = !showScheduleBindingBadge && isAutomationGenerated',
+ );
// schedule 绑定与普通自动化都复用 AutomationTimerIcon;绑定态优先承载更多状态。
expect(sessionCardSource).toMatch(
/const renderAutomationMeta = \(iconSize: number\) =>[\s\S]*?showScheduleBindingBadge \? \([\s\S]*?<ScheduleBindingBadge[\s\S]*?schedules=\{boundSchedules\}[\s\S]*?size=\{iconSize\}[\s\S]*?activeForeground=\{isActive\}[\s\S]*?\) : showAutomationTimer \? \([\s\S]*?<AutomationTimerIcon size=\{iconSize\}/,
@@ -138,20 +159,29 @@ describe('SessionCard review regressions', () => {
});
it('keeps running card previews stable instead of streaming compact activity text', () => {
- expect(sessionCardSource).toContain('const listPreview = awaitingText ?? runningDetail ?? summaryPreview');
+ expect(sessionCardSource).toContain(
+ 'const listPreview = awaitingText ?? runningDetail ?? summaryPreview',
+ );
expect(sessionCardSource).toContain('const cardPreview = awaitingText ?? summaryPreview');
- expect(sessionCardSource).not.toContain('const cardPreview = awaitingText ?? runningDetail ?? summaryPreview');
+ expect(sessionCardSource).not.toContain(
+ 'const cardPreview = awaitingText ?? runningDetail ?? summaryPreview',
+ );
});
it('lets single-line card content keep its natural compact height', () => {
expect(sessionCardSource).toContain("'rounded-xl bg-[var(--surface-elevated)] border'");
- expect(sessionCardSource).not.toContain("'h-full rounded-xl bg-[var(--surface-elevated)] border'");
+ expect(sessionCardSource).not.toContain(
+ "'h-full rounded-xl bg-[var(--surface-elevated)] border'",
+ );
});
it('E1D 任务C: SessionCard active 反白链完整且运行态不降级文字颜色', () => {
const re = /isActive \? 'text-sidebar-item-active-foreground'/g;
const count = (sessionCardSource.match(re) || []).length;
- expect(count, 'isActive conditional active-foreground ≥7(title×2+time+RemoteProjectIcon×4)').toBeGreaterThanOrEqual(7);
+ expect(
+ count,
+ 'isActive conditional active-foreground ≥7(title×2+time+RemoteProjectIcon×4)',
+ ).toBeGreaterThanOrEqual(7);
// Running is already expressed by the status indicator, so its text keeps
// the same semantic colors as other non-active tasks.
@@ -183,20 +213,18 @@ describe('SessionCard review regressions', () => {
expect(sessionItemSource).toContain(
'const hasAutomationMeta = boundSchedules.length > 0 || isAutomationGenerated;',
);
- expect(sessionItemSource).toContain(
- "!isEditing && hasAutomationMeta ? 'gap-1.5' : 'gap-2.5'",
- );
+ expect(sessionItemSource).toContain("!isEditing && hasAutomationMeta ? 'gap-1.5' : 'gap-2.5'");
expect(automationGroupSource).toContain(
'className="flex min-w-0 items-center gap-1.5 text-left disabled:cursor-default"',
);
- expect(automationGroupSource).toContain(
- 'className="flex min-w-0 items-center gap-1.5"',
- );
+ expect(automationGroupSource).toContain('className="flex min-w-0 items-center gap-1.5"');
});
it('keeps active sidebar rename controls inside the active foreground color system', () => {
expect(sessionItemSource).toContain('activeForeground={isActive}');
- expect((sessionCardSource.match(/activeForeground=\{isActive\}/g) || []).length).toBeGreaterThanOrEqual(2);
+ expect(
+ (sessionCardSource.match(/activeForeground=\{isActive\}/g) || []).length,
+ ).toBeGreaterThanOrEqual(2);
expect(sessionRenameInputSource).toContain(
"activeForeground && 'text-sidebar-item-active-foreground'",
);
@@ -228,6 +256,19 @@ describe('SessionCard review regressions', () => {
);
});
+ it('aligns the session row cursor with the actual split drag source state', () => {
+ expect(sessionItemSource).toContain(
+ "splitDragEnabled ? 'cursor-grab active:cursor-grabbing' : 'cursor-pointer'",
+ );
+ expect(sessionItemSource).toContain('draggable={splitDragEnabled}');
+ expect(sessionItemSource).toContain('useState(true)');
+ });
+
+ it('wires split creation into both sidebar rendering modes', () => {
+ expect(sessionItemSource).toContain('<OpenInSplitMenu');
+ expect(sessionCardSource).toContain('<OpenInSplitMenu');
+ });
+
it('PR-123 greptile: card 路径的绑定徽章与 Timer 进反白体系', () => {
// P1:renderAutomationMeta 卡片/列表两路都要把选中态透传给 ScheduleBindingBadge,
// 否则红胶囊上 Timer 仍是 meta 灰;普通自动化分支也必须透传 activeForeground。
@@ -262,23 +303,15 @@ describe('SessionCard review regressions', () => {
expect(automationGroupSource).toContain(
"? 'text-sidebar-item-active-foreground hover:text-sidebar-item-active-foreground hover:bg-[color-mix(in_srgb,var(--sidebar-item-active-foreground)_14%,transparent)]'",
);
- expect(automationGroupSource).toContain(
- ": 'text-foreground hover:bg-sidebar-item-hover'",
- );
+ expect(automationGroupSource).toContain(": 'text-foreground hover:bg-sidebar-item-hover'");
});
it('aligns list automation headers with regular tasks and indents only expanded children', () => {
expect(automationGroupSource).toMatch(
/sessionVariant === 'list'\s*\? 'px-2\.5'\s*: indented\s*\? 'pl-\[22px\] pr-2'\s*: 'pl-3 pr-2'/,
);
- expect(automationGroupSource).toContain(
- '<div className="flex flex-col gap-0.5 pl-3">',
- );
- expect(automationGroupSource).toContain(
- "sessionVariant === 'list' ? 'w-3' : 'w-[15px]'",
- );
- expect(automationGroupSource).toContain(
- "sessionVariant === 'list' && 'order-2'",
- );
+ expect(automationGroupSource).toContain('<div className="flex flex-col gap-0.5 pl-3">');
+ expect(automationGroupSource).toContain("sessionVariant === 'list' ? 'w-3' : 'w-[15px]'");
+ expect(automationGroupSource).toContain("sessionVariant === 'list' && 'order-2'");
});
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts b/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts
new file mode 100644
index 0000000000..e98cbf148f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts
@@ -0,0 +1,64 @@
+import type { DropSide } from './splitGroupStore';
+
+export const SPLIT_GROUP_SESSION_MIME = 'application/x-cindy-session-id';
+
+export interface DropRect {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+interface SplitGroupDragDataTransfer {
+ effectAllowed: string;
+ setData(format: string, data: string): void;
+}
+
+export function writeSplitGroupSessionDragData(
+ dataTransfer: SplitGroupDragDataTransfer,
+ sessionIdInput: string,
+): boolean {
+ const sessionId = sessionIdInput.trim();
+ if (!sessionId) return false;
+ dataTransfer.effectAllowed = 'move';
+ dataTransfer.setData(SPLIT_GROUP_SESSION_MIME, sessionId);
+ dataTransfer.setData('text/plain', sessionId);
+ return true;
+}
+
+export function hasSplitGroupSessionType(types: ArrayLike<string>): boolean {
+ return Array.from(types).includes(SPLIT_GROUP_SESSION_MIME);
+}
+
+export interface SplitDragSourceContext {
+ editing: boolean;
+ orcaRole?: string | null;
+ /** 行是否被 SortableJS 容器(置顶/项目手动排序)包裹。 */
+ inSortableContainer: boolean;
+}
+
+/**
+ * 一行任务是否充当分屏拖拽源。SortableJS(forceFallback 指针手势)与原生 HTML5
+ * 拖拽会争抢同一次手势:行带 `draggable` 时浏览器可能启动原生拖拽并中断 fallback
+ * 排序,因此 Sortable 容器内的行保持原有手动排序,不再叠加分屏拖拽。Orca worker
+ * 不进侧栏列表,防御性排除,避免把 worker id 写进分屏树后与 Lead 路由错位。
+ */
+export function isSplitGroupDragSource(context: SplitDragSourceContext): boolean {
+ return !context.editing && context.orcaRole !== 'worker' && !context.inSortableContainer;
+}
+
+/** 按指针距四条边的最近距离决定左 / 右 / 上 / 下落点。 */
+export function resolveSplitDropSide(
+ rect: DropRect,
+ clientX: number,
+ clientY: number,
+): DropSide | null {
+ if (!(rect.width > 0 && rect.height > 0)) return null;
+ const relativeX = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));
+ const relativeY = Math.min(1, Math.max(0, (clientY - rect.top) / rect.height));
+ const horizontalSide: DropSide = relativeX < 0.5 ? 'left' : 'right';
+ const verticalSide: DropSide = relativeY < 0.5 ? 'top' : 'bottom';
+ const horizontalEdgeDistance = Math.min(relativeX, 1 - relativeX);
+ const verticalEdgeDistance = Math.min(relativeY, 1 - relativeY);
+ return horizontalEdgeDistance <= verticalEdgeDistance ? horizontalSide : verticalSide;
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/splitGroupStore.ts b/apps/desktop/src/renderer/features/cc-agent/splitGroupStore.ts
new file mode 100644
index 0000000000..5c11008430
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/splitGroupStore.ts
@@ -0,0 +1,440 @@
+/**
+ * splitGroupStore — chat-main 内部的同窗多任务递归分屏状态。
+ *
+ * 主界面布局树仍只包含一个 `chat-main`;本 store 维护该面板内部的二叉分屏树。
+ * 每次拖入只拆目标 pane,因此可组合出左一右二、左二右二等混合布局。
+ */
+
+import { useSyncExternalStore } from 'react';
+
+import { isSecondaryWindow } from '@/lib/secondaryWindow';
+
+export type SplitDirection = 'row' | 'column';
+export type DropSide = 'left' | 'right' | 'top' | 'bottom';
+export type SplitGroupAddBlockReason = 'invalid' | 'duplicate' | 'limit-reached' | 'missing-anchor';
+
+export interface SplitPaneNode {
+ type: 'pane';
+ key: string;
+ sessionId: string;
+}
+
+export interface SplitBranchNode {
+ type: 'split';
+ key: string;
+ direction: SplitDirection;
+ fraction: number;
+ first: SplitNode;
+ second: SplitNode;
+}
+
+export type SplitNode = SplitPaneNode | SplitBranchNode;
+
+export interface SplitGroupState {
+ root: SplitNode | null;
+}
+
+export const MIN_SPLIT_CHILD_FRACTION = 0.1;
+export const MAX_SPLIT_PANES = 8;
+export const SPLIT_GROUP_STORAGE_KEY = 'cc-agent.splitGroup.v2';
+export const LEGACY_SPLIT_GROUP_STORAGE_KEY = 'cc-agent.splitGroup.v1';
+
+const EMPTY: SplitGroupState = { root: null };
+
+let keySequence = 0;
+let state: SplitGroupState = EMPTY;
+let hydrated = false;
+const listeners = new Set<() => void>();
+
+function nextKey(prefix: 'pane' | 'split'): string {
+ keySequence += 1;
+ return `${prefix}-${Date.now().toString(36)}-${keySequence}`;
+}
+
+function nextUniqueKey(prefix: 'pane' | 'split', existingKeys: ReadonlySet<string>): string {
+ let key = nextKey(prefix);
+ while (existingKeys.has(key)) key = nextKey(prefix);
+ return key;
+}
+
+function normalizeSessionId(value: unknown): string {
+ return typeof value === 'string' ? value.trim() : '';
+}
+
+function directionForSide(side: DropSide): SplitDirection {
+ return side === 'top' || side === 'bottom' ? 'column' : 'row';
+}
+
+function isBeforeSide(side: DropSide): boolean {
+ return side === 'left' || side === 'top';
+}
+
+function normalizeFraction(value: unknown): number {
+ if (typeof value !== 'number' || !Number.isFinite(value)) return 0.5;
+ return Math.min(1 - MIN_SPLIT_CHILD_FRACTION, Math.max(MIN_SPLIT_CHILD_FRACTION, value));
+}
+
+export function getSplitPanes(root: SplitNode | null): SplitPaneNode[] {
+ if (!root) return [];
+ if (root.type === 'pane') return [root];
+ return [...getSplitPanes(root.first), ...getSplitPanes(root.second)];
+}
+
+export function getSplitSessionIds(root: SplitNode | null): string[] {
+ return getSplitPanes(root).map((pane) => pane.sessionId);
+}
+
+function collectNodeKeys(root: SplitNode, keys: Set<string>): void {
+ keys.add(root.key);
+ if (root.type === 'pane') return;
+ collectNodeKeys(root.first, keys);
+ collectNodeKeys(root.second, keys);
+}
+
+function replaceNode(
+ root: SplitNode,
+ predicate: (node: SplitNode) => boolean,
+ replacement: (node: SplitNode) => SplitNode,
+): SplitNode {
+ if (predicate(root)) return replacement(root);
+ if (root.type === 'pane') return root;
+ const first = replaceNode(root.first, predicate, replacement);
+ const second = replaceNode(root.second, predicate, replacement);
+ return first === root.first && second === root.second ? root : { ...root, first, second };
+}
+
+function removePane(root: SplitNode, sessionId: string): SplitNode | null {
+ if (root.type === 'pane') return root.sessionId === sessionId ? null : root;
+ const first = removePane(root.first, sessionId);
+ const second = removePane(root.second, sessionId);
+ if (!first) return second;
+ if (!second) return first;
+ return first === root.first && second === root.second ? root : { ...root, first, second };
+}
+
+interface CoerceContext {
+ seenKeys: Set<string>;
+ seenSessionIds: Set<string>;
+ paneCount: number;
+}
+
+function coerceKey(value: unknown, prefix: 'pane' | 'split', context: CoerceContext): string {
+ const persisted = typeof value === 'string' ? value.trim() : '';
+ const key =
+ persisted && !context.seenKeys.has(persisted)
+ ? persisted
+ : nextUniqueKey(prefix, context.seenKeys);
+ context.seenKeys.add(key);
+ return key;
+}
+
+function coerceNode(raw: unknown, context: CoerceContext): SplitNode | null {
+ if (typeof raw !== 'object' || raw === null) return null;
+ const record = raw as Record<string, unknown>;
+ if (record.type === 'pane') {
+ if (context.paneCount >= MAX_SPLIT_PANES) return null;
+ const sessionId = normalizeSessionId(record.sessionId);
+ if (!sessionId || context.seenSessionIds.has(sessionId)) return null;
+ context.seenSessionIds.add(sessionId);
+ context.paneCount += 1;
+ return {
+ type: 'pane',
+ key: coerceKey(record.key, 'pane', context),
+ sessionId,
+ };
+ }
+ if (record.type !== 'split') return null;
+ const first = coerceNode(record.first, context);
+ const second = coerceNode(record.second, context);
+ if (!first) return second;
+ if (!second) return first;
+ return {
+ type: 'split',
+ key: coerceKey(record.key, 'split', context),
+ direction: record.direction === 'column' ? 'column' : 'row',
+ fraction: normalizeFraction(record.fraction),
+ first,
+ second,
+ };
+}
+
+function coerce(raw: unknown): SplitGroupState {
+ if (typeof raw !== 'object' || raw === null) return EMPTY;
+ const record = raw as Record<string, unknown>;
+ const context: CoerceContext = {
+ seenKeys: new Set<string>(),
+ seenSessionIds: new Set<string>(),
+ paneCount: 0,
+ };
+ const root = coerceNode(record.root, context);
+ return root && getSplitPanes(root).length >= 2 ? { root } : EMPTY;
+}
+
+interface LegacyPane {
+ key: string;
+ sessionId: string;
+ fraction: number;
+}
+
+function legacyTree(
+ panes: readonly LegacyPane[],
+ direction: SplitDirection,
+ existingKeys: Set<string>,
+): SplitNode | null {
+ if (panes.length === 0) return null;
+ const [firstPane, ...rest] = panes;
+ const first: SplitPaneNode = {
+ type: 'pane',
+ key: firstPane.key,
+ sessionId: firstPane.sessionId,
+ };
+ existingKeys.add(first.key);
+ if (rest.length === 0) return first;
+ const remainingWeight = rest.reduce((sum, pane) => sum + pane.fraction, 0);
+ const second = legacyTree(rest, direction, existingKeys);
+ if (!second) return first;
+ return {
+ type: 'split',
+ key: nextUniqueKey('split', existingKeys),
+ direction,
+ fraction: normalizeFraction(firstPane.fraction / (firstPane.fraction + remainingWeight)),
+ first,
+ second,
+ };
+}
+
+function coerceLegacy(raw: unknown): SplitGroupState {
+ if (typeof raw !== 'object' || raw === null) return EMPTY;
+ const record = raw as Record<string, unknown>;
+ const rawPanes = Array.isArray(record.panes) ? record.panes : [];
+ const seenSessionIds = new Set<string>();
+ const seenKeys = new Set<string>();
+ const panes: LegacyPane[] = [];
+ for (const rawPane of rawPanes) {
+ if (panes.length >= MAX_SPLIT_PANES) break;
+ if (typeof rawPane !== 'object' || rawPane === null) continue;
+ const paneRecord = rawPane as Record<string, unknown>;
+ const sessionId = normalizeSessionId(paneRecord.sessionId);
+ if (!sessionId || seenSessionIds.has(sessionId)) continue;
+ const key = coerceKey(paneRecord.key, 'pane', {
+ seenKeys,
+ seenSessionIds,
+ paneCount: panes.length,
+ });
+ const fraction =
+ typeof paneRecord.fraction === 'number' &&
+ Number.isFinite(paneRecord.fraction) &&
+ paneRecord.fraction > 0
+ ? paneRecord.fraction
+ : 1;
+ seenSessionIds.add(sessionId);
+ panes.push({ key, sessionId, fraction });
+ }
+ if (panes.length < 2) return EMPTY;
+ const total = panes.reduce((sum, pane) => sum + pane.fraction, 0);
+ const normalized = panes.map((pane) => ({ ...pane, fraction: pane.fraction / total }));
+ const root = legacyTree(normalized, record.direction === 'column' ? 'column' : 'row', seenKeys);
+ return root ? { root } : EMPTY;
+}
+
+function removePersistedState(): void {
+ try {
+ if (typeof localStorage === 'undefined') return;
+ localStorage.removeItem(SPLIT_GROUP_STORAGE_KEY);
+ localStorage.removeItem(LEGACY_SPLIT_GROUP_STORAGE_KEY);
+ } catch {
+ // localStorage 不可用时退化为进程内状态。
+ }
+}
+
+function persist(next: SplitGroupState): void {
+ try {
+ // 「在新窗口打开」的副窗口与主窗共享同源 localStorage。持久化布局只归主窗,
+ // 副窗口的分屏仅存内存——否则副窗口启动即恢复主窗布局、又把自己的布局写回,
+ // 两个窗口会互相覆盖。
+ if (isSecondaryWindow()) return;
+ if (typeof localStorage === 'undefined') return;
+ if (!next.root || getSplitPanes(next.root).length < 2) {
+ removePersistedState();
+ return;
+ }
+ localStorage.setItem(SPLIT_GROUP_STORAGE_KEY, JSON.stringify(next));
+ localStorage.removeItem(LEGACY_SPLIT_GROUP_STORAGE_KEY);
+ } catch {
+ // 配额、私密模式或测试 stub 失败不能阻断 UI 操作。
+ }
+}
+
+function ensureHydrated(): void {
+ if (hydrated) return;
+ hydrated = true;
+ try {
+ // 副窗口不恢复主窗的持久化分屏(见 persist 的窗口归属说明)。
+ if (isSecondaryWindow()) return;
+ if (typeof localStorage === 'undefined') return;
+ const currentRaw = localStorage.getItem(SPLIT_GROUP_STORAGE_KEY);
+ const legacyRaw = currentRaw ? null : localStorage.getItem(LEGACY_SPLIT_GROUP_STORAGE_KEY);
+ if (!currentRaw && !legacyRaw) return;
+ state = currentRaw
+ ? coerce(JSON.parse(currentRaw) as unknown)
+ : coerceLegacy(JSON.parse(legacyRaw!) as unknown);
+ persist(state);
+ } catch {
+ state = EMPTY;
+ removePersistedState();
+ }
+}
+
+function emit(next: SplitGroupState): void {
+ const panes = getSplitPanes(next.root);
+ state = panes.length >= 2 ? next : EMPTY;
+ persist(state);
+ for (const listener of listeners) listener();
+}
+
+export const splitGroupStore = {
+ subscribe(listener: () => void): () => void {
+ ensureHydrated();
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+
+ getSnapshot(): SplitGroupState {
+ ensureHydrated();
+ return state;
+ },
+
+ isActive(): boolean {
+ ensureHydrated();
+ return getSplitPanes(state.root).length >= 2;
+ },
+
+ getAddBlockReason(
+ sessionIdInput: string,
+ anchorSessionIdInput: string,
+ ): SplitGroupAddBlockReason | null {
+ ensureHydrated();
+ const sessionId = normalizeSessionId(sessionIdInput);
+ const anchorSessionId = normalizeSessionId(anchorSessionIdInput);
+ if (!sessionId || !anchorSessionId) return 'invalid';
+ if (sessionId === anchorSessionId) return 'duplicate';
+ const panes = getSplitPanes(state.root);
+ if (panes.some((pane) => pane.sessionId === sessionId)) return 'duplicate';
+ if (panes.length >= MAX_SPLIT_PANES) return 'limit-reached';
+ if (state.root && !panes.some((pane) => pane.sessionId === anchorSessionId)) {
+ return 'missing-anchor';
+ }
+ return null;
+ },
+
+ addSession(sessionIdInput: string, anchorSessionIdInput: string, side: DropSide): boolean {
+ ensureHydrated();
+ const sessionId = normalizeSessionId(sessionIdInput);
+ const anchorSessionId = normalizeSessionId(anchorSessionIdInput);
+ if (this.getAddBlockReason(sessionId, anchorSessionId)) return false;
+
+ const existingKeys = new Set<string>();
+ if (state.root) collectNodeKeys(state.root, existingKeys);
+ const newPane: SplitPaneNode = {
+ type: 'pane',
+ key: nextUniqueKey('pane', existingKeys),
+ sessionId,
+ };
+ existingKeys.add(newPane.key);
+ const makeSplit = (anchorPane: SplitPaneNode): SplitBranchNode => ({
+ type: 'split',
+ key: nextUniqueKey('split', existingKeys),
+ direction: directionForSide(side),
+ fraction: 0.5,
+ first: isBeforeSide(side) ? newPane : anchorPane,
+ second: isBeforeSide(side) ? anchorPane : newPane,
+ });
+
+ if (!state.root) {
+ const anchorPane: SplitPaneNode = {
+ type: 'pane',
+ key: nextUniqueKey('pane', existingKeys),
+ sessionId: anchorSessionId,
+ };
+ emit({ root: makeSplit(anchorPane) });
+ return true;
+ }
+ emit({
+ root: replaceNode(
+ state.root,
+ (node) => node.type === 'pane' && node.sessionId === anchorSessionId,
+ (node) => makeSplit(node as SplitPaneNode),
+ ),
+ });
+ return true;
+ },
+
+ removeSession(sessionIdInput: string): void {
+ ensureHydrated();
+ const sessionId = normalizeSessionId(sessionIdInput);
+ if (!sessionId || !state.root) return;
+ const root = removePane(state.root, sessionId);
+ if (root === state.root) return;
+ emit({ root });
+ },
+
+ replaceSession(currentSessionIdInput: string, nextSessionIdInput: string): void {
+ ensureHydrated();
+ const currentSessionId = normalizeSessionId(currentSessionIdInput);
+ const nextSessionId = normalizeSessionId(nextSessionIdInput);
+ if (!currentSessionId || !nextSessionId || currentSessionId === nextSessionId || !state.root)
+ return;
+ const panes = getSplitPanes(state.root);
+ if (panes.some((pane) => pane.sessionId === nextSessionId)) return;
+ if (!panes.some((pane) => pane.sessionId === currentSessionId)) return;
+ emit({
+ root: replaceNode(
+ state.root,
+ (node) => node.type === 'pane' && node.sessionId === currentSessionId,
+ (node) => ({ ...node, sessionId: nextSessionId }),
+ ),
+ });
+ },
+
+ clear(): void {
+ ensureHydrated();
+ if (!state.root) return;
+ emit(EMPTY);
+ },
+
+ toggleRootDirection(): void {
+ ensureHydrated();
+ if (!state.root || state.root.type !== 'split') return;
+ emit({
+ root: {
+ ...state.root,
+ direction: state.root.direction === 'row' ? 'column' : 'row',
+ },
+ });
+ },
+
+ setSplitFraction(splitKey: string, fraction: number): void {
+ ensureHydrated();
+ if (!state.root || !splitKey) return;
+ const normalized = normalizeFraction(fraction);
+ const root = replaceNode(
+ state.root,
+ (node) => node.type === 'split' && node.key === splitKey,
+ (node) => ({ ...node, fraction: normalized }),
+ );
+ if (root === state.root) return;
+ emit({ root });
+ },
+
+ __resetForTest(): void {
+ state = EMPTY;
+ hydrated = false;
+ keySequence = 0;
+ removePersistedState();
+ for (const listener of listeners) listener();
+ },
+};
+
+export function useSplitGroup(): SplitGroupState {
+ return useSyncExternalStore(splitGroupStore.subscribe, splitGroupStore.getSnapshot, () => EMPTY);
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index bacc59257b..cb6297e4ca 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8622,6 +8622,25 @@
"closeAria": "Close"
}
},
+ "splitGroup": {
+ "closeAria": "Close Pane for “{{title}}”",
+ "closeAll": "Close Split",
+ "toggleDirection": "Toggle Horizontal / Vertical Split",
+ "dropHint": "Drop to Open the Session Here",
+ "loadingTask": "Loading Session…",
+ "resizeAria": "Resize Session Panes",
+ "openInSplit": "Open in Split",
+ "openSide": {
+ "left": "Open Session on Left",
+ "right": "Open Session on Right",
+ "top": "Open Session Above",
+ "bottom": "Open Session Below"
+ },
+ "alreadyOpen": "This session is already open in the split. Choose another session.",
+ "limitReached": "A split can contain up to {{count}} sessions. Close one pane and try again.",
+ "addUnavailable": "This session can’t be opened in the current split. Open a session in the main area and try again.",
+ "workerUnavailable": "A Worker can’t open in a separate pane. Open its Lead session instead."
+ },
"extraDirs": {
"menuAria": "Composer actions",
"tooltipEmpty": "More actions",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index fbd2aca2b8..00f335790c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8608,6 +8608,25 @@
"closeAria": "閉じる"
}
},
+ "splitGroup": {
+ "closeAria": "「{{title}}」のペインを閉じる",
+ "closeAll": "分割を閉じる",
+ "toggleDirection": "上下 / 左右の分割を切り替え",
+ "dropHint": "ここにセッションをドロップして開く",
+ "loadingTask": "セッションを読み込み中…",
+ "resizeAria": "セッションペインのサイズを変更",
+ "openInSplit": "分割で開く",
+ "openSide": {
+ "left": "セッションを左側で開く",
+ "right": "セッションを右側で開く",
+ "top": "セッションを上側で開く",
+ "bottom": "セッションを下側で開く"
+ },
+ "alreadyOpen": "このセッションはすでに分割内で開いています。別のセッションを選択してください。",
+ "limitReached": "1 つの分割で開けるセッションは最大 {{count}} 件です。ペインを 1 つ閉じてから、もう一度お試しください。",
+ "addUnavailable": "このセッションは現在の分割で開けません。メイン領域でセッションを開いてから、もう一度お試しください。",
+ "workerUnavailable": "Worker は個別のペインで開けません。所属する Lead セッションを開いてください。"
+ },
"extraDirs": {
"menuAria": "操作メニュー",
"tooltipEmpty": "その他の操作",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 893b8754c3..85368fe626 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8608,6 +8608,25 @@
"closeAria": "닫기"
}
},
+ "splitGroup": {
+ "closeAria": "‘{{title}}’ 분할 창 닫기",
+ "closeAll": "분할 닫기",
+ "toggleDirection": "상하 / 좌우 분할 전환",
+ "dropHint": "여기에 세션을 놓아 열기",
+ "loadingTask": "세션 불러오는 중…",
+ "resizeAria": "세션 분할 창 크기 조절",
+ "openInSplit": "분할로 열기",
+ "openSide": {
+ "left": "세션을 왼쪽에 열기",
+ "right": "세션을 오른쪽에 열기",
+ "top": "세션을 위쪽에 열기",
+ "bottom": "세션을 아래쪽에 열기"
+ },
+ "alreadyOpen": "이 세션은 이미 분할 창에 열려 있습니다. 다른 세션을 선택하세요.",
+ "limitReached": "한 분할 창에는 세션을 최대 {{count}}개까지 열 수 있습니다. 분할 창 하나를 닫고 다시 시도하세요.",
+ "addUnavailable": "현재 분할 창에서 이 세션을 열 수 없습니다. 기본 영역에서 세션을 연 후 다시 시도하세요.",
+ "workerUnavailable": "Worker는 별도의 분할 창에서 열 수 없습니다. 소속 Lead 세션을 대신 여세요."
+ },
"extraDirs": {
"menuAria": "작업 메뉴",
"tooltipEmpty": "더 많은 작업",
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 d8f7ef23b1..a3a14d4fb9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8608,6 +8608,25 @@
"closeAria": "关闭"
}
},
+ "splitGroup": {
+ "closeAria": "关闭任务“{{title}}”的分栏",
+ "closeAll": "关闭分栏",
+ "toggleDirection": "切换上下 / 左右分栏",
+ "dropHint": "松开以在此分栏打开任务",
+ "loadingTask": "正在加载任务…",
+ "resizeAria": "调整任务分栏大小",
+ "openInSplit": "在分栏中打开",
+ "openSide": {
+ "left": "在左侧打开任务",
+ "right": "在右侧打开任务",
+ "top": "在上方打开任务",
+ "bottom": "在下方打开任务"
+ },
+ "alreadyOpen": "该任务已在当前分栏中打开,请选择其他任务",
+ "limitReached": "一个分栏最多可打开 {{count}} 个任务,请先关闭一个任务分栏再重试",
+ "addUnavailable": "当前无法在分栏中打开该任务,请先在主区域打开一个任务再重试",
+ "workerUnavailable": "Worker 任务不能单独在分栏中打开,请改为打开所属 Lead 任务"
+ },
"extraDirs": {
"menuAria": "操作菜单",
"tooltipEmpty": "更多操作",
diff --git a/apps/desktop/src/renderer/lib/navigationCommands.ts b/apps/desktop/src/renderer/lib/navigationCommands.ts
index c98a8d803e..ac5cf16f30 100644
--- a/apps/desktop/src/renderer/lib/navigationCommands.ts
+++ b/apps/desktop/src/renderer/lib/navigationCommands.ts
@@ -3,6 +3,7 @@ import type { TFunction } from 'i18next';
import * as sessionService from '@/lib/sessionService';
import { toast } from '@/lib/toast';
import { createLogger } from '@/lib/logger';
+import { getSessionRouteOwnerId, resolveSessionRoute } from '@/lib/orcaSessionIdentity';
const log = createLogger('NavigationCommands');
const SLASH_COMMAND_REGEX = /^\/(\S+)(?:\s+(.*))?$/s;
@@ -23,8 +24,12 @@ export async function tryHandleNavigationCommand(
deps: {
navigate: (to: string) => void;
t: TFunction;
- /** embedded 内容视图消费命令但不解析/改变窗口路由。 */
+ /** sidebar-embedded 内容视图消费命令但不解析/改变窗口路由。 */
allowNavigation?: boolean;
+ /** split-pane 在改变窗口路由前报告来源 pane 的替换意图。 */
+ onSessionNavigate?: (targetSessionId: string, routeOwnerSessionId?: string) => void;
+ /** split-pane 来源 pane 卸载或切换后使仍在途的异步导航失效。 */
+ isNavigationCurrent?: () => boolean;
},
): Promise<boolean> {
const slashMatch = message.match(SLASH_COMMAND_REGEX);
@@ -36,6 +41,7 @@ export async function tryHandleNavigationCommand(
log.info('[jump-session] navigation ignored by embedded session view');
return true;
}
+ if (deps.isNavigationCurrent && !deps.isNavigationCurrent()) return true;
const sessionId = (slashMatch[2] ?? '').trim();
if (!sessionId) {
@@ -45,16 +51,23 @@ export async function tryHandleNavigationCommand(
try {
const session = await sessionService.get(sessionId);
+ if (deps.isNavigationCurrent && !deps.isNavigationCurrent()) return true;
if (!session || session.status === 'deleted') {
toast.error(deps.t('ccAgent.jumpSession.notFound'));
return true;
}
+ const route = await resolveSessionRoute(sessionId, session);
+ if (deps.isNavigationCurrent && !deps.isNavigationCurrent()) return true;
+ deps.onSessionNavigate?.(sessionId, getSessionRouteOwnerId(route) ?? sessionId);
+ deps.navigate(route);
} catch (err) {
- log.warn('[jump-session] session lookup failed', { sessionId, error: String(err) });
+ if (deps.isNavigationCurrent && !deps.isNavigationCurrent()) return true;
+ log.warn('[jump-session] navigation target resolution failed', {
+ sessionId,
+ error: String(err),
+ });
toast.error(deps.t('ccAgent.jumpSession.notFound'));
return true;
}
-
- deps.navigate(`/cc-agent/${sessionId}`);
return true;
}
diff --git a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts b/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts
index 2b68e72a0b..33ec593c99 100644
--- a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts
+++ b/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts
@@ -20,6 +20,17 @@ export function formatOrcaWorkerTitle(title: string | null | undefined): string
return t ? `Orca Worker: ${t}` : 'Orca Worker: Ready';
}
+/** Extract the session that owns the canonical `/cc-agent/:sessionId` route. */
+export function getSessionRouteOwnerId(route: string): string | null {
+ const match = /^\/cc-agent\/([^/?#]+)(?:[?#]|$)/.exec(route);
+ if (!match?.[1]) return null;
+ try {
+ return decodeURIComponent(match[1]);
+ } catch {
+ return match[1];
+ }
+}
+
/**
* Resolve the canonical chat route for a session before navigating from generic
* entry points such as notifications, deep links, and sidebar clicks. Orca lead
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 46b64f60c9..c377046426 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -150,6 +150,14 @@
-webkit-user-drag: none;
}
+ /* SessionItem 是同窗分屏的原生 HTML5 拖拽源。拖拽通常从标题、图标或时间
+ 子节点起手,所以必须与 composer atom 一样让整棵子树恢复 element drag;
+ 行内按钮仍由 onDragStart 的交互区守卫 preventDefault,不会误触发分屏。 */
+ [data-split-group-drag-source='true'],
+ [data-split-group-drag-source='true'] * {
+ -webkit-user-drag: element !important;
+ }
+
/* F3: Global disable focus outline — Chromium default :focus-visible draws
a yellow/orange ring on buttons, options and menu items after Esc/click
transitions focus. Suppress it on non-input elements while inputs keep