Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 完善任务拖拽到输入框的引用行为 (#2146)
Dash512e35360d7c
diff --git a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.tsindex 260a2b2abe..8c4d8ffac7 100644--- a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts@@ -53,7 +53,7 @@ describe('sidebar remote project icon', () => {it('keeps remote session icons next to titles instead of in the right-side time slots', () => {expect(sessionItemSource).toMatch(- /<span className="min-w-0 flex flex-1 items-center gap-1\.5">[\s\S]*?<SidebarTitleMarquee[\s\S]*?\{remoteIconKind && \([\s\S]*?<RemoteProjectIcon/,+ /<span[\s\S]*?className=\{cn\(\s*'min-w-0 flex flex-1 items-center gap-1\.5'[\s\S]*?<SidebarTitleMarquee[\s\S]*?\{remoteIconKind && \([\s\S]*?<RemoteProjectIcon/,);expect(sessionItemSource).toMatch(/<div className="group\/slot relative ml-auto flex h-6 shrink-0 items-center justify-end min-w-14">[\s\S]*?<WorktreeBadge[\s\S]*?<time/,diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex f4f6f88c08..946eb861ef 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -300,6 +300,7 @@ import { appendMentionChip } from './mentionChipInsertion';// device-link 远程会话:设置变更不落本地 DB(会 404),改写远程内存层 + 运行时隧道。import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';import { makerApiFor, makerApiForDevice } from '@/lib/makerTransport';+import { SESSION_LINK_DROP_MIME } from '@/lib/sessionLinkDrop';const log = createLogger('ChatInput');// perf-baseline(与 MessageStream / sidebar 的 perf/session-switch 探针同通道):@@ -1986,6 +1987,13 @@ export function ChatInput({return false;},handleDrop(_view, event) {+ // Session-link drops are inserted by the outer composer drop handler.+ // Consume the event here first so ProseMirror does not also insert the+ // drag source's `text/plain` fallback (the raw session id).+ if (event.dataTransfer?.getData(SESSION_LINK_DROP_MIME).trim()) {+ event.preventDefault();+ return true;+ }const payload = decodeComposerMentionPayload(event.dataTransfer?.getData(COMPOSER_MENTION_MIME) ?? '',);@@ -2355,6 +2363,20 @@ export function ChatInput({[editor],);+ const insertSessionLinkDrop = useCallback(+ (e: ReactDragEvent<HTMLElement>): boolean => {+ if (!editor || editor.isDestroyed) return false;+ const href = e.dataTransfer.getData(SESSION_LINK_DROP_MIME).trim();+ if (!href) return false;+ const at = lastComposerSelectionFromRef.current ?? editor.state.selection.from;+ appendMentionChip(editor, pastedSessionChipAttrs({ href, label: null }), { at });+ lastComposerSelectionFromRef.current = editor.state.selection.from;+ resolveSessionChipTitles(editor);+ return true;+ },+ [editor],+ );+// Hold a live ref to the editor for handlers that mount before Tiptap// exposes it through React (e.g. the blur handler above).const editorRef = useRef<Editor | null>(null);@@ -6248,6 +6270,7 @@ export function ChatInput({: 'focus-within:border-[var(--chat-input-border-focus)]',],)}+ data-split-group-composer-drop-target// 卡片里的空白(文字行下方的空隙、工具栏两组按钮之间的空档、四周// padding)没有元素承接点击:浏览器默认会把焦点从 contenteditable 撤到// <body>,正在输入的光标凭空消失;而点空白又该能进入输入态。所以先@@ -6337,6 +6360,9 @@ export function ChatInput({if (mentionInserted) {return;}+ if (insertSessionLinkDrop(e)) {+ return;+ }// 意识面板拖来的产物(cindy-ghost:// 媒体地址):走引渡链路——// main 验归属后,图片落图片附件、视频落路径引用的 file 附件(托盘可见)。// 键用 storageKey(= draftKey ?? sessionId):新建会话草稿态没有diff --git a/apps/desktop/src/renderer/components/sidebar/SortableList.tsx b/apps/desktop/src/renderer/components/sidebar/SortableList.tsxindex 735816a231..2f531da5e7 100644--- a/apps/desktop/src/renderer/components/sidebar/SortableList.tsx+++ b/apps/desktop/src/renderer/components/sidebar/SortableList.tsx@@ -84,6 +84,9 @@ export interface SortableListProps<T> {* 默认 `'button, input, textarea, select, a, [data-no-drag]'`,覆盖* 绝大多数会"误把可交互元素当成拖动起点"的场景。 */filter?: string;+ /** 是否强制使用 SortableJS 的 pointer fallback。关闭后使用原生 DnD,+ * 允许同一个会话行把拖拽交给右侧分屏 drop target。 */+ forceFallback?: boolean;/** 容器额外 class(如 flex-col / gap 等布局)。 */className?: string;/** 每个 Sortable wrapper 的额外 class,用于非侧栏场景覆盖 drag/ghost 视觉。 */@@ -111,6 +114,7 @@ export function SortableList<T>({handle,onDragActiveChange,filter,+ forceFallback = true,className,rowClassName,role,@@ -133,6 +137,10 @@ export function SortableList<T>({// 标记下一次 onEnd 是"窗口失焦兜底"触发的——onEnd 里把 DOM 复位后直接 return,// 不调 onReorder, 避免用户切走窗口的瞬间被记下一次未授意的顺序变化。const abortNextEndRef = useRef(false);+ // Native DnD must only persist a reorder when the final drop lands in this+ // sortable container. Drops on the composer, split panes, or outside Cindy+ // can still leave Sortable's DOM temporarily moved while the gesture passes.+ const nativeDropDispositionRef = useRef<'internal' | 'external' | null>(null);// mount 时创建 Sortable;unmount 时销毁。后续 props 变化通过 option() 更新。useEffect(() => {@@ -155,12 +163,24 @@ export function SortableList<T>({dragClass: 'xdt-sortable-drag',// 见文件顶部"设计要点 5":强制 JS fallback,绕开 HTML5 DnD 在 React 19 +// 嵌套 click/contextmenu 环境下的不稳定行为。- forceFallback: true,+ forceFallback,fallbackOnBody: true,fallbackTolerance: 4,+ setData: (dataTransfer, dragEl) => {+ // Keep the browser-required plain-text slot empty: DOM text can contain+ // task titles/previews and would leak if the drag leaves the app.+ dataTransfer.setData('Text', '');+ const rect = dragEl.getBoundingClientRect();+ dataTransfer.setDragImage(+ dragEl,+ Math.min(24, Math.max(0, rect.width / 2)),+ Math.min(24, Math.max(0, rect.height / 2)),+ );+ },// 真正开拖(移动超过 fallbackTolerance)才触发,不是 pointerdown 即触发——// 所以"按下未拖"和"普通 hover"都不会上 grabbing 光标,只有真正拖动中才会。onStart: () => {+ nativeDropDispositionRef.current = null;document.body.classList.add(SORTING_BODY_CLASS);onDragActiveChangeRef.current?.(true);},@@ -172,6 +192,8 @@ export function SortableList<T>({const aborted = abortNextEndRef.current;abortNextEndRef.current = false;+ const dropDisposition = nativeDropDispositionRef.current;+ nativeDropDispositionRef.current = null;const oldIndex = evt.oldIndex;const newIndex = evt.newIndex;@@ -183,13 +205,12 @@ export function SortableList<T>({// 让位时的位置上。const parent = evt.from;if (parent && evt.item && oldIndex != null) {+ evt.item.parentNode?.removeChild(evt.item);const refNode = parent.children[oldIndex] ?? null;- if (evt.item !== refNode) {- parent.insertBefore(evt.item, refNode);- }+ parent.insertBefore(evt.item, refNode);}- if (aborted) return;+ if (aborted || (!forceFallback && dropDisposition !== 'internal')) return;if (oldIndex == null || newIndex == null || oldIndex === newIndex) return;const currentItems = itemsRef.current;@@ -205,6 +226,17 @@ export function SortableList<T>({});sortableRef.current = instance;+ // Native Sortable receives the document `drop` event after capture. Record+ // whether the final target is internal or external before onEnd restores+ // the transient DOM move.+ const markDropDisposition = (event: Event) => {+ if (Sortable.active !== instance) return;+ const target = event.target;+ nativeDropDispositionRef.current =+ target instanceof Node && el.contains(target) ? 'internal' : 'external';+ };+ document.addEventListener('drop', markDropDisposition, true);+// 窗口失焦兜底:用户 Alt-Tab / 点窗口外 / 调出系统 UI 时,document 上的// pointerup/mouseup/touchend 都不会触发,SortableJS 的 fallback 拖拽会卡住。// 这里发现自家实例正在拖时,dispatch 一个合成 pointercancel(它在 fallback@@ -229,6 +261,7 @@ export function SortableList<T>({return () => {window.removeEventListener('blur', abortIfActive);document.removeEventListener('visibilitychange', onVisibilityChange);+ document.removeEventListener('drop', markDropDisposition, true);// 拖动中组件被卸载时兜底清掉标记,避免 grabbing 光标残留到全局。document.body.classList.remove(SORTING_BODY_CLASS);onDragActiveChangeRef.current?.(false);@@ -269,7 +302,13 @@ export function SortableList<T>({);return (- <div ref={containerRef} role={role} aria-label={ariaLabel} className={className}>+ <div+ ref={containerRef}+ data-sortable-native-dnd={forceFallback ? undefined : 'true'}+ role={role}+ aria-label={ariaLabel}+ className={className}+ >{children}</div>);diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/SortableList.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/SortableList.test.tsxnew file mode 100644index 0000000000..e1e4e13434--- /dev/null+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/SortableList.test.tsx@@ -0,0 +1,152 @@+// @vitest-environment jsdom++import { afterEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render } from '@testing-library/react';++const sortableMock = vi.hoisted(() => {+ class MockSortable {+ static active: MockSortable | null = null;+ static instances: MockSortable[] = [];++ readonly el: HTMLElement;+ readonly options: Record<string, unknown>;++ constructor(el: HTMLElement, options: Record<string, unknown>) {+ this.el = el;+ this.options = options;+ }++ static create(el: HTMLElement, options: Record<string, unknown>) {+ const instance = new MockSortable(el, options);+ MockSortable.instances.push(instance);+ return instance;+ }++ option(name: string, value: unknown) {+ this.options[name] = value;+ }++ destroy() {}+ }++ return { MockSortable };+});++vi.mock('sortablejs', () => ({ default: sortableMock.MockSortable }));++import { SortableList } from '../SortableList';++type SortableEvent = {+ item: HTMLElement;+ from: HTMLElement;+ oldIndex: number;+ newIndex: number;+};++function callback<T extends (...args: never[]) => unknown>(options: Record<string, unknown>, name: string) {+ return options[name] as T;+}++function rowIds(container: HTMLElement): string[] {+ return Array.from(container.children).map((row) => row.getAttribute('data-sortable-id') ?? '');+}++afterEach(() => {+ cleanup();+ sortableMock.MockSortable.instances.length = 0;+ sortableMock.MockSortable.active = null;+});++describe('SortableList native drop disposition', () => {+ it('restores the DOM and skips reorder when the final drop is external', () => {+ const onReorder = vi.fn();+ const { container } = render(+ <SortableList+ items={['a', 'b']}+ getId={(id) => id}+ onReorder={onReorder}+ renderItem={(id) => <span>{id}</span>}+ forceFallback={false}+ />,+ );+ const list = container.firstElementChild as HTMLElement;+ const instance = sortableMock.MockSortable.instances[0];+ const onStart = callback<() => void>(instance.options, 'onStart');+ const onEnd = callback<(event: SortableEvent) => void>(instance.options, 'onEnd');+ const moved = list.children[0] as HTMLElement;++ sortableMock.MockSortable.active = instance;+ onStart();+ list.append(moved);++ const external = document.createElement('div');+ document.body.append(external);+ external.dispatchEvent(new Event('drop', { bubbles: true }));++ onEnd({ item: moved, from: list, oldIndex: 0, newIndex: 1 });++ expect(rowIds(list)).toEqual(['a', 'b']);+ expect(onReorder).not.toHaveBeenCalled();+ external.remove();+ });++ it('restores an upward transient move when the final drop is external', () => {+ const onReorder = vi.fn();+ const { container } = render(+ <SortableList+ items={['a', 'b', 'c']}+ getId={(id) => id}+ onReorder={onReorder}+ renderItem={(id) => <span>{id}</span>}+ forceFallback={false}+ />,+ );+ const list = container.firstElementChild as HTMLElement;+ const instance = sortableMock.MockSortable.instances[0];+ const onStart = callback<() => void>(instance.options, 'onStart');+ const onEnd = callback<(event: SortableEvent) => void>(instance.options, 'onEnd');+ const moved = list.children[2] as HTMLElement;++ sortableMock.MockSortable.active = instance;+ onStart();+ list.insertBefore(moved, list.children[0] ?? null);++ const external = document.createElement('div');+ document.body.append(external);+ external.dispatchEvent(new Event('drop', { bubbles: true }));++ onEnd({ item: moved, from: list, oldIndex: 2, newIndex: 0 });++ expect(rowIds(list)).toEqual(['a', 'b', 'c']);+ expect(onReorder).not.toHaveBeenCalled();+ external.remove();+ });++ it('persists reorder when the final drop is inside the sortable container', () => {+ const onReorder = vi.fn();+ const { container } = render(+ <SortableList+ items={['a', 'b']}+ getId={(id) => id}+ onReorder={onReorder}+ renderItem={(id) => <span>{id}</span>}+ forceFallback={false}+ />,+ );+ const list = container.firstElementChild as HTMLElement;+ const instance = sortableMock.MockSortable.instances[0];+ const onStart = callback<() => void>(instance.options, 'onStart');+ const onEnd = callback<(event: SortableEvent) => void>(instance.options, 'onEnd');+ const moved = list.children[0] as HTMLElement;++ sortableMock.MockSortable.active = instance;+ onStart();+ list.append(moved);+ (list.children[0] as HTMLElement).dispatchEvent(new Event('drop', { bubbles: true }));++ onEnd({ item: moved, from: list, oldIndex: 0, newIndex: 1 });++ expect(rowIds(list)).toEqual(['a', 'b']);+ expect(onReorder).toHaveBeenCalledWith(['b', 'a']);+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsx b/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsxindex a4a2152aac..8f353d755e 100644--- a/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsx@@ -40,6 +40,7 @@ import { mergeSessionSources } from './lib/mergeSessionSources';import {SPLIT_GROUP_SESSION_MIME,hasSplitGroupSessionType,+ isSplitGroupComposerDropTarget,resolveSplitDropSide,} from './splitGroupDnd';import {@@ -962,6 +963,10 @@ function SplitDropTarget({const handleDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {if (!hasSplitGroupSessionType(event.dataTransfer.types)) return;+ if (isSplitGroupComposerDropTarget(event.target)) {+ setDropSide(null);+ return;+ }event.preventDefault();event.stopPropagation();event.dataTransfer.dropEffect = 'move';@@ -981,6 +986,10 @@ function SplitDropTarget({const handleDrop = useCallback((event: DragEvent<HTMLDivElement>) => {if (!hasSplitGroupSessionType(event.dataTransfer.types)) return;+ if (isSplitGroupComposerDropTarget(event.target)) {+ setDropSide(null);+ return;+ }event.preventDefault();event.stopPropagation();const sessionId = event.dataTransfer.getData(SPLIT_GROUP_SESSION_MIME).trim();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.tsxindex 78faca81f1..75ccfd5407 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/SplitGroup.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/SplitGroup.test.tsx@@ -119,6 +119,12 @@ vi.mock('../CCAgentSessionView', () => ({>Composer action</button>+ <div+ data-testid={`composer-drop-target-${sessionIdProp}`}+ data-split-group-composer-drop-target=""+ >+ <span data-testid={`composer-drop-child-${sessionIdProp}`}>Composer drop</span>+ </div></div>);},@@ -1353,6 +1359,29 @@ describe('SplitGroup', () => {expect(view.container.querySelectorAll('[data-split-pane-key]')).toHaveLength(3);});+ it('任务拖到输入框时不被 pane capture 抢走', async () => {+ act(() => {+ splitGroupStore.addSession('session-b', 'session-a', 'right');+ });+ const view = renderSplitGroup('session-a');+ const composerDropChild = screen.getByTestId('composer-drop-child-session-b');+ const dataTransfer = {+ types: ['application/x-cindy-session-id', 'application/x-cindy-session-link'],+ dropEffect: 'none',+ getData: (format: string) =>+ format === 'application/x-cindy-session-id' ? 'session-c' : 'cindy://session/session-c',+ };++ await act(async () => {+ fireEvent.dragOver(composerDropChild, { clientX: 300, clientY: 340, dataTransfer });+ fireEvent.drop(composerDropChild, { clientX: 300, clientY: 340, dataTransfer });+ await Promise.resolve();+ });++ expect(view.container.querySelectorAll('[data-split-pane-key]')).toHaveLength(2);+ expect(sessionViewRenderMock).not.toHaveBeenCalledWith('session-c');+ });+it('达到窗格上限时拒绝拖入且不切换路由', async () => {act(() => {splitGroupStore.addSession('session-b', 'session-a', 'right');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.tsindex 55bb752dbf..7b405f9273 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupDnd.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/splitGroupDnd.test.ts@@ -1,16 +1,32 @@+// @vitest-environment jsdom+import { describe, expect, it } from 'vitest';import {SPLIT_GROUP_SESSION_MIME,+ SPLIT_GROUP_SESSION_LINK_MIME,hasSplitGroupSessionType,+ isSplitGroupComposerDropTarget,isSplitGroupDragSource,+ needsDedicatedSplitGroupDragHandle,resolveSplitDropSide,+ shouldStartSplitGroupDrag,writeSplitGroupSessionDragData,} from '../splitGroupDnd';const RECT = { left: 100, top: 50, width: 400, height: 300 };describe('splitGroupDnd', () => {+ it('输入框内的任务拖放由 composer 消费,不属于分屏落点', () => {+ const composer = document.createElement('div');+ composer.setAttribute('data-split-group-composer-drop-target', '');+ const child = document.createElement('span');+ composer.append(child);++ expect(isSplitGroupComposerDropTarget(child)).toBe(true);+ expect(isSplitGroupComposerDropTarget(document.createElement('div'))).toBe(false);+ });+it('只接受 Cindy 任务拖拽 MIME', () => {expect(hasSplitGroupSessionType([SPLIT_GROUP_SESSION_MIME])).toBe(true);expect(hasSplitGroupSessionType(['Files', 'text/plain'])).toBe(false);@@ -24,9 +40,16 @@ describe('splitGroupDnd', () => {};expect(writeSplitGroupSessionDragData(dataTransfer, ' session-a ')).toBe(true);- expect(dataTransfer.effectAllowed).toBe('move');+ expect(dataTransfer.effectAllowed).toBe('copyMove');expect(values.get(SPLIT_GROUP_SESSION_MIME)).toBe('session-a');+ expect(values.get(SPLIT_GROUP_SESSION_LINK_MIME)).toBe('cindy://session/session-a');expect(values.get('text/plain')).toBe('session-a');+ expect(+ writeSplitGroupSessionDragData(dataTransfer, 'session-remote', { deviceId: 'device-b' }),+ ).toBe(true);+ expect(values.get(SPLIT_GROUP_SESSION_LINK_MIME)).toBe(+ 'cindy://session/session-remote?device=device-b',+ );expect(writeSplitGroupSessionDragData(dataTransfer, ' ')).toBe(false);});@@ -63,6 +86,67 @@ describe('splitGroupDnd', () => {).toBe(true);});+ it('置顶排序行提供独立起手区后仍可作为分屏拖拽源', () => {+ const context = {+ editing: false,+ orcaRole: null,+ inSortableContainer: true,+ sortableDragBlocked: false,+ hasDedicatedHandle: true,+ };++ expect(needsDedicatedSplitGroupDragHandle(context)).toBe(true);+ expect(isSplitGroupDragSource(context)).toBe(true);+ expect(+ shouldStartSplitGroupDrag({+ enabled: true,+ needsDedicatedHandle: true,+ startedOnDedicatedHandle: true,+ startedOnInteractiveElement: false,+ }),+ ).toBe(true);+ });++ it('原生 Sortable 行不再需要分开的分屏起手区', () => {+ const context = {+ editing: false,+ orcaRole: null,+ inSortableContainer: true,+ sortableDragBlocked: false,+ nativeSortable: true,+ };++ expect(needsDedicatedSplitGroupDragHandle(context)).toBe(false);+ expect(isSplitGroupDragSource(context)).toBe(true);+ expect(+ shouldStartSplitGroupDrag({+ enabled: true,+ needsDedicatedHandle: false,+ startedOnDedicatedHandle: false,+ startedOnInteractiveElement: false,+ }),+ ).toBe(true);+ });++ it('置顶排序行的非起手区和交互元素不会启动分屏拖拽', () => {+ expect(+ shouldStartSplitGroupDrag({+ enabled: true,+ needsDedicatedHandle: true,+ startedOnDedicatedHandle: false,+ startedOnInteractiveElement: false,+ }),+ ).toBe(false);+ expect(+ shouldStartSplitGroupDrag({+ enabled: true,+ needsDedicatedHandle: true,+ startedOnDedicatedHandle: true,+ startedOnInteractiveElement: true,+ }),+ ).toBe(false);+ });+it('编辑态、Orca worker 与 Sortable 容器内的行不充当拖拽源', () => {expect(isSplitGroupDragSource({ editing: true, orcaRole: null, inSortableContainer: false }),diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/CardMasonry.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/CardMasonry.tsxindex 5097199015..5f0225537f 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/CardMasonry.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/CardMasonry.tsx@@ -43,6 +43,8 @@ export interface CardMasonryProps<T> {reducedMotion: boolean;/** SortableJS 跨列拖拽的 group 名;默认 'pinned-cards'。 */groupId?: string;+ /** 与 SortableList 同口径;置顶卡片用原生 DnD 兼容分屏 drop。 */+ forceFallback?: boolean;}export function CardMasonry<T>({@@ -52,6 +54,7 @@ export function CardMasonry<T>({onReorder,reducedMotion,groupId,+ forceFallback = true,}: CardMasonryProps<T>) {const containerRef = useRef<HTMLDivElement>(null);const [columns, setColumns] = useState(1);@@ -81,6 +84,7 @@ export function CardMasonry<T>({getId={getId}onReorder={onReorder}reducedMotion={reducedMotion}+ forceFallback={forceFallback}className="flex flex-col gap-[7px]"renderItem={renderItem}/>@@ -93,6 +97,7 @@ export function CardMasonry<T>({onReorder={onReorder}reducedMotion={reducedMotion}groupId={groupId}+ forceFallback={forceFallback}/>)}</div>diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/DraggableCardColumns.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/DraggableCardColumns.tsxindex 637a38150f..e136adf524 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/DraggableCardColumns.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/DraggableCardColumns.tsx@@ -24,6 +24,8 @@ export interface DraggableCardColumnsProps<T> {onReorder: (newOrderIds: string[]) => void;reducedMotion: boolean;groupId?: string;+ /** 与 SortableList 同口径;置顶卡片用原生 DnD 兼容分屏 drop。 */+ forceFallback?: boolean;}const CARD_DRAG_FILTER = 'button, input, textarea, select, a, [data-no-drag]';@@ -122,6 +124,7 @@ export function DraggableCardColumns<T>({onReorder,reducedMotion,groupId,+ forceFallback = true,}: DraggableCardColumnsProps<T>) {const columnRefs = useRef<(HTMLDivElement | null)[]>([]);const itemsRef = useRef(items);@@ -130,6 +133,10 @@ export function DraggableCardColumns<T>({const columnsRef = useRef(columns);const originalBucketsRef = useRef<string[][] | null>(null);const abortNextEndRef = useRef(false);+ // Native DnD may move a card between columns while the pointer passes over+ // the sidebar. Only persist a reorder when the final drop lands in one of+ // this component's columns; external drops must restore the transient DOM.+ const nativeDropDispositionRef = useRef<'internal' | 'external' | null>(null);itemsRef.current = items;getIdRef.current = getId;@@ -149,6 +156,7 @@ export function DraggableCardColumns<T>({if (cols.length === 0) return;const onStart = () => {+ nativeDropDispositionRef.current = null;document.body.classList.add(SORTING_BODY_CLASS);originalBucketsRef.current = readColumnIds(columnRefs.current, columnsRef.current);};@@ -158,6 +166,8 @@ export function DraggableCardColumns<T>({const aborted = abortNextEndRef.current;abortNextEndRef.current = false;+ const dropDisposition = nativeDropDispositionRef.current;+ nativeDropDispositionRef.current = null;const movedId = evt.item.getAttribute('data-card-id');const toColumn = readColumnIndex(evt.to);@@ -171,7 +181,7 @@ export function DraggableCardColumns<T>({restoreColumnDomOrder(columnRefs.current, originalBuckets);}- if (aborted) return;+ if (aborted || (!forceFallback && dropDisposition !== 'internal')) return;if (current.length === newOrder.length && current.every((id, i) => id === newOrder[i])) {return;@@ -188,14 +198,39 @@ export function DraggableCardColumns<T>({ghostClass: 'xdt-sortable-ghost',chosenClass: '',dragClass: 'xdt-sortable-drag',- forceFallback: true,fallbackOnBody: true,fallbackTolerance: 4,+ forceFallback,+ setData: (dataTransfer, dragEl) => {+ // Keep the browser-required plain-text slot empty: DOM text can contain+ // task titles/previews and would leak if the drag leaves the app.+ dataTransfer.setData('Text', '');+ const rect = dragEl.getBoundingClientRect();+ dataTransfer.setDragImage(+ dragEl,+ Math.min(24, Math.max(0, rect.width / 2)),+ Math.min(24, Math.max(0, rect.height / 2)),+ );+ },onStart,onEnd,}),);+ // Native Sortable receives the document `drop` event after capture. Record+ // whether the final target is inside any of this component's columns so+ // onEnd can restore external drops without persisting an intermediate move.+ const markDropDisposition = (event: Event) => {+ const active = Sortable.active;+ if (!active || !instances.includes(active)) return;+ const target = event.target;+ nativeDropDispositionRef.current =+ target instanceof Node && cols.some((col) => col.contains(target))+ ? 'internal'+ : 'external';+ };+ document.addEventListener('drop', markDropDisposition, true);+const abortIfActive = () => {const active = Sortable.active;if (!active || !instances.includes(active)) return;@@ -215,11 +250,13 @@ export function DraggableCardColumns<T>({return () => {window.removeEventListener('blur', abortIfActive);document.removeEventListener('visibilitychange', onVisibilityChange);+ document.removeEventListener('drop', markDropDisposition, true);document.body.classList.remove(SORTING_BODY_CLASS);originalBucketsRef.current = null;+ nativeDropDispositionRef.current = null;instances.forEach((inst) => inst.destroy());};- }, [columns, reducedMotion, groupId]);+ }, [columns, forceFallback, reducedMotion, groupId]);return (<div className="flex w-full items-stretch gap-[7px]">@@ -227,6 +264,7 @@ export function DraggableCardColumns<T>({<divkey={c}data-col={c}+ data-sortable-native-dnd={forceFallback ? undefined : 'true'}ref={(el) => {columnRefs.current[c] = el;}}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsxindex 2cf6e4e8c1..19e106af9d 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx@@ -22,7 +22,7 @@*/import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';-import type { MouseEvent as ReactMouseEvent, ReactNode, RefObject } from 'react';+import type { DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, ReactNode, RefObject } from 'react';import { Archive, ChevronRight, EllipsisVertical, Undo } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';@@ -80,6 +80,14 @@ import { resolveSidebarRightStatus } from './sidebarRightStatus';import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';import { shouldPrefetchSessionOnPointerDown } from './sessionSwitchPrefetch';import { OpenInSplitMenu } from './OpenInSplitMenu';+import {+ SPLIT_GROUP_DRAG_HANDLE_SELECTOR,+ SPLIT_GROUP_DRAG_INTERACTIVE_SELECTOR,+ isSplitGroupDragSource,+ needsDedicatedSplitGroupDragHandle,+ shouldStartSplitGroupDrag,+ writeSplitGroupSessionDragData,+} from '../splitGroupDnd';const log = createLogger('SessionCard');@@ -216,6 +224,7 @@ export function SessionCard({const [shareExportOpen, setShareExportOpen] = useState(false);const confirmPillRef = useRef<HTMLButtonElement>(null);const cardRef = useRef<HTMLDivElement>(null);+ const dragStartTargetRef = useRef<Element | null>(null);// 归档/删除前那次 dirty-worktree 预检要在 main 侧跑 git status,是"点了归档、// 卡片还没消失"里剩下的最大一块等待。亮出 Confirm 胶囊 / 打开菜单到用户点下去@@ -253,6 +262,62 @@ export function SessionCard({const [editValue, setEditValue] = useState(displayTitle);const committedRef = useRef(false);+ // 置顶卡片/宽列表使用原生 Sortable DnD:同一整卡的 dragstart 同时写入分屏 MIME,+ // 由落点决定是侧栏内排序还是拖入右侧。普通 forceFallback 列表仍保留专用标题起手区;+ // ProjectNode 内的卡片已有 data-no-drag 祖先,因此子任务仍可整卡分屏拖拽。+ const [dragContainerState, setDragContainerState] = useState({+ inSortableContainer: true,+ sortableDragBlocked: false,+ nativeSortable: false,+ });+ useEffect(() => {+ const card = cardRef.current;+ setDragContainerState({+ inSortableContainer: Boolean(card?.closest('[data-sortable-id]')),+ sortableDragBlocked: Boolean(card?.closest('[data-no-drag]')),+ nativeSortable: Boolean(card?.closest('[data-sortable-native-dnd]')),+ });+ }, []);+ const needsSplitDragHandle = needsDedicatedSplitGroupDragHandle(dragContainerState);+ const splitDragEnabled = isSplitGroupDragSource({+ editing: isEditing,+ orcaRole: session.orcaRole,+ ...dragContainerState,+ hasDedicatedHandle: true,+ });+ const splitDragHandleActive = splitDragEnabled && needsSplitDragHandle;++ const handleDragStart = useCallback(+ (event: ReactDragEvent<HTMLDivElement>) => {+ const target =+ dragStartTargetRef.current ?? (event.target instanceof Element ? event.target : null);+ dragStartTargetRef.current = null;+ const startedOnDedicatedHandle = Boolean(target?.closest(SPLIT_GROUP_DRAG_HANDLE_SELECTOR));+ const startedOnInteractiveElement = Boolean(+ target !== event.currentTarget && target?.closest(SPLIT_GROUP_DRAG_INTERACTIVE_SELECTOR),+ );+ if (!shouldStartSplitGroupDrag({+ enabled: splitDragEnabled,+ needsDedicatedHandle: needsSplitDragHandle,+ startedOnDedicatedHandle,+ startedOnInteractiveElement,+ })) {+ event.preventDefault();+ return;+ }+ if (+ !writeSplitGroupSessionDragData(event.dataTransfer, session.id, {+ deviceId: session.deviceLinkDeviceId,+ })+ ) {+ event.preventDefault();+ return;+ }+ event.currentTarget.dataset.sessionDragging = 'true';+ },+ [needsSplitDragHandle, session.deviceLinkDeviceId, session.id, splitDragEnabled],+ );+// raw 由 SessionRenameInput 传入:输入框当前文本(Magic 生成的标题也先填入输入框,用户 Enter 确认后才走到这里)。const commitTitle = useCallback((raw: string) => {@@ -534,8 +599,24 @@ export function SessionCard({// 多选范围选取靠 getVisibleSidebarSessionIds 扫 [data-sidebar-session-row][data-session-id];// 卡片也打这个标记,shift 范围选才能把卡片纳入"可见行"。data-sidebar-session-row="true"+ data-split-group-drag-source={splitDragEnabled ? 'true' : undefined}+ draggable={splitDragEnabled && (dragContainerState.nativeSortable || !needsSplitDragHandle)}role="button"tabIndex={0}+ onPointerDownCapture={(event) => {+ dragStartTargetRef.current = event.target instanceof Element ? event.target : null;+ }}+ onPointerUpCapture={() => {+ dragStartTargetRef.current = null;+ }}+ onPointerCancelCapture={() => {+ dragStartTargetRef.current = null;+ }}+ onDragStart={handleDragStart}+ onDragEnd={(event) => {+ dragStartTargetRef.current = null;+ delete event.currentTarget.dataset.sessionDragging;+ }}onPointerDown={(e) => {if (shouldPrefetchSessionOnPointerDown(e, { isActive, isEditing })) {makerChatStore.ensureInitialMessages(session.id);@@ -557,7 +638,10 @@ export function SessionCard({setMenuPos({ x: e.clientX, y: e.clientY });}}className={cn(- 'group/card relative w-full overflow-hidden text-left cursor-pointer',+ 'group/card relative w-full overflow-hidden text-left',+ splitDragEnabled && !needsSplitDragHandle+ ? 'cursor-grab active:cursor-grabbing'+ : 'cursor-pointer',variant === 'list'? cn(// 扁平行(类 Telegram / 对话列表):无描边、无卡片底色,仅 hover/active 行底色。@@ -606,7 +690,15 @@ export function SessionCard({{/* 标题槽固定沿用常态时间槽的 20px 高度。改名框本身是 24px,编辑时绝对定位居中覆盖文字槽位,不参与布局计算,避免整条置顶任务被撑高。状态 / Agent / 自动化图标始终留在文字槽左侧,编辑态也不改变标题起点。 */}- <div className="relative flex h-5 min-w-0 flex-1 items-center gap-0">+ <div+ data-split-group-drag-handle={splitDragHandleActive ? 'true' : undefined}+ data-no-drag={splitDragHandleActive ? 'true' : undefined}+ draggable={splitDragHandleActive}+ className={cn(+ 'relative flex h-5 min-w-0 flex-1 items-center gap-0',+ splitDragHandleActive && 'cursor-grab active:cursor-grabbing',+ )}+ ><span className="flex shrink-0 items-center">{titlePrefixNode}</span>{isEditing ? (<SessionRenameInput@@ -687,9 +779,13 @@ export function SessionCard({非运行、内容长短都不变,始终渲染占位)。等待交互 TapTap 蓝高亮(--card-status-awaiting),其余状态统一走次级色。 */}<p+ data-split-group-drag-handle={splitDragHandleActive ? 'true' : undefined}+ data-no-drag={splitDragHandleActive ? 'true' : undefined}+ draggable={splitDragHandleActive}className={cn('mt-1 overflow-hidden text-11 leading-[1.45]','[display:-webkit-box] [-webkit-line-clamp:1] [-webkit-box-orient:vertical]',+ splitDragHandleActive && 'cursor-grab active:cursor-grabbing',rightStatusKind !== 'time' && 'pr-5',awaitingText? isActive@@ -773,7 +869,15 @@ export function SessionCard({{/* 卡片标题始终保留原来的流式盒子;编辑时只把原标题隐藏,并以绝对定位的24px 输入框覆盖。这样一行 / 两行标题都维持原高度,也不会凭空多出状态图标。 */}- <div className="relative">+ <div+ data-split-group-drag-handle={splitDragHandleActive ? 'true' : undefined}+ data-no-drag={splitDragHandleActive ? 'true' : undefined}+ draggable={splitDragHandleActive}+ className={cn(+ 'relative',+ splitDragHandleActive && 'cursor-grab active:cursor-grabbing',+ )}+ ><divclassName={cn('min-w-0 text-[12.5px] font-semibold leading-[1.22] tracking-[-0.005em]',@@ -817,10 +921,14 @@ export function SessionCard({此处只放正文文字。 */}{cardPreview && (<p+ data-split-group-drag-handle={splitDragHandleActive ? 'true' : undefined}+ data-no-drag={splitDragHandleActive ? 'true' : undefined}+ draggable={splitDragHandleActive}className={cn('mt-[4px] text-11 leading-[1.4]','[display:-webkit-box] [-webkit-box-orient:vertical] overflow-hidden','text-[var(--text-secondary)]',+ splitDragHandleActive && 'cursor-grab active:cursor-grabbing',)}style={{ WebkitLineClamp: cardPreviewLineClamp }}>diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsxindex 567ad3e159..c9770d5785 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx@@ -94,7 +94,14 @@ import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionAcimport { resolveSidebarRightStatus } from './sidebarRightStatus';import { AutomationTimerIcon } from './AutomationTimerIcon';import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';-import { isSplitGroupDragSource, writeSplitGroupSessionDragData } from '../splitGroupDnd';+import {+ SPLIT_GROUP_DRAG_HANDLE_SELECTOR,+ SPLIT_GROUP_DRAG_INTERACTIVE_SELECTOR,+ isSplitGroupDragSource,+ needsDedicatedSplitGroupDragHandle,+ shouldStartSplitGroupDrag,+ writeSplitGroupSessionDragData,+} from '../splitGroupDnd';import { shouldPrefetchSessionOnPointerDown } from './sessionSwitchPrefetch';import { OpenInSplitMenu } from './OpenInSplitMenu';@@ -497,6 +504,7 @@ export const SessionItem = memo(function SessionItem({// 也不会触发。这种"用户明确想再看一眼"的语义由调用方通过// imperative 路径(querySelector + scrollIntoNearestView)补一刀const rowRef = useRef<HTMLDivElement>(null);+ const dragStartTargetRef = useRef<Element | null>(null);// ── Double-click rename ──const [isEditing, setIsEditing] = useState(false);@@ -553,45 +561,63 @@ export const SessionItem = memo(function SessionItem({[displayTitle, isEditing, remoteWritesBlocked, t],);- // SortableJS(置顶/项目手动排序,forceFallback 指针手势)与原生 HTML5 拖拽会争抢- // 同一次手势:普通 Sortable 行保持原有排序拖拽;但 ProjectNode 的子任务区已经由- // data-no-drag 祖先拦截了项目级 Sortable 起手,因此这类行可以安全地作为分屏拖拽源。- // 首帧先按 Sortable 容器处理,避免 ref effect 运行前短暂开启原生分屏拖拽。+ // 置顶段使用原生 Sortable DnD:Sortable 负责侧栏内排序,原生 dragstart 同时写入+ // 分屏 MIME,因此同一整行可以根据落点完成排序或拖入右侧。普通 forceFallback+ // 列表仍保留原来的专用标题起手区,项目子任务则继续由 data-no-drag 隔离。+ // 首帧先按 Sortable 容器处理,避免 ref effect 运行前短暂开启原生拖拽。const [dragContainerState, setDragContainerState] = useState({inSortableContainer: true,sortableDragBlocked: false,+ nativeSortable: false,});useEffect(() => {const row = rowRef.current;setDragContainerState({inSortableContainer: Boolean(row?.closest('[data-sortable-id]')),sortableDragBlocked: Boolean(row?.closest('[data-no-drag]')),+ nativeSortable: Boolean(row?.closest('[data-sortable-native-dnd]')),});}, []);+ const needsSplitDragHandle = needsDedicatedSplitGroupDragHandle(dragContainerState);const splitDragEnabled = isSplitGroupDragSource({editing: isEditing,orcaRole: session.orcaRole,...dragContainerState,+ hasDedicatedHandle: true,});+ const splitDragHandleActive = splitDragEnabled && needsSplitDragHandle;const handleDragStart = useCallback((event: ReactDragEvent<HTMLDivElement>) => {- const target = event.target instanceof Element ? event.target : null;+ const target =+ dragStartTargetRef.current ?? (event.target instanceof Element ? event.target : null);+ dragStartTargetRef.current = null;+ const startedOnDedicatedHandle = Boolean(target?.closest(SPLIT_GROUP_DRAG_HANDLE_SELECTOR));+ const startedOnInteractiveElement = Boolean(+ target !== event.currentTarget && target?.closest(SPLIT_GROUP_DRAG_INTERACTIVE_SELECTOR),+ );if (- !splitDragEnabled ||- (target !== event.currentTarget &&- target?.closest('button, input, textarea, select, a[href], [role="menuitem"]'))+ !shouldStartSplitGroupDrag({+ enabled: splitDragEnabled,+ needsDedicatedHandle: needsSplitDragHandle,+ startedOnDedicatedHandle,+ startedOnInteractiveElement,+ })) {event.preventDefault();return;}- if (!writeSplitGroupSessionDragData(event.dataTransfer, session.id)) {+ if (+ !writeSplitGroupSessionDragData(event.dataTransfer, session.id, {+ deviceId: session.deviceLinkDeviceId,+ })+ ) {event.preventDefault();return;}event.currentTarget.dataset.sessionDragging = 'true';},- [splitDragEnabled, session.id],+ [needsSplitDragHandle, session.deviceLinkDeviceId, session.id, splitDragEnabled],);// isActive 由 false → true(或初次 mount 时即为 true)→ 把行滚进 viewport。@@ -784,11 +810,21 @@ export const SessionItem = memo(function SessionItem({data-session-id={session.id}data-sidebar-session-row="true"data-split-group-drag-source={splitDragEnabled ? 'true' : undefined}- draggable={splitDragEnabled}+ draggable={splitDragEnabled && (dragContainerState.nativeSortable || !needsSplitDragHandle)}role="button"tabIndex={0}+ onPointerDownCapture={(event) => {+ dragStartTargetRef.current = event.target instanceof Element ? event.target : null;+ }}+ onPointerUpCapture={() => {+ dragStartTargetRef.current = null;+ }}+ onPointerCancelCapture={() => {+ dragStartTargetRef.current = null;+ }}onDragStart={handleDragStart}onDragEnd={(event) => {+ dragStartTargetRef.current = null;delete event.currentTarget.dataset.sessionDragging;}}onPointerDown={(e) => {@@ -885,7 +921,15 @@ export const SessionItem = memo(function SessionItem({// 也会直接返回原 string,所以两路渲染最终都走 truncate 容器。// 远程项目 icon 跟项目标题同口径:直接贴在标题右侧。标题过长时标题截断,// icon shrink-0 保持可见;右侧槽位只保留 worktree + 时间 + hover action。- <span className="min-w-0 flex flex-1 items-center gap-1.5">+ <span+ data-split-group-drag-handle={splitDragHandleActive ? 'true' : undefined}+ data-no-drag={splitDragHandleActive ? 'true' : undefined}+ draggable={splitDragHandleActive}+ className={cn(+ 'min-w-0 flex flex-1 items-center gap-1.5',+ splitDragHandleActive && 'cursor-grab active:cursor-grabbing',+ )}+ >{/* 绑定徽章优先于普通自动化 Timer:persistentSession 会话两者皆真,主图标统一为 Timer,绑定态额外承载频率/暂停信息。 */}{boundSchedules.length > 0 ? (diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/DraggableCardColumns.nativeDnd.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/DraggableCardColumns.nativeDnd.test.tsxnew file mode 100644index 0000000000..d7bf76f036--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/DraggableCardColumns.nativeDnd.test.tsx@@ -0,0 +1,142 @@+// @vitest-environment jsdom++import { afterEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render } from '@testing-library/react';++const sortableMock = vi.hoisted(() => {+ class MockSortable {+ static active: MockSortable | null = null;+ static instances: MockSortable[] = [];++ readonly el: HTMLElement;+ readonly options: Record<string, unknown>;++ constructor(el: HTMLElement, options: Record<string, unknown>) {+ this.el = el;+ this.options = options;+ }++ static create(el: HTMLElement, options: Record<string, unknown>) {+ const instance = new MockSortable(el, options);+ MockSortable.instances.push(instance);+ return instance;+ }++ destroy() {}+ }++ return { MockSortable };+});++vi.mock('sortablejs', () => ({ default: sortableMock.MockSortable }));++import { DraggableCardColumns } from '../DraggableCardColumns';++type SortableEvent = {+ item: HTMLElement;+ from: HTMLElement;+ to: HTMLElement;+ oldIndex: number;+ newIndex: number;+ newDraggableIndex: number;+};++function callback<T extends (...args: never[]) => unknown>(options: Record<string, unknown>, name: string) {+ return options[name] as T;+}++function columnIds(column: HTMLElement): string[] {+ return Array.from(column.children).map((card) => card.getAttribute('data-card-id') ?? '');+}++afterEach(() => {+ cleanup();+ sortableMock.MockSortable.instances.length = 0;+ sortableMock.MockSortable.active = null;+});++describe('DraggableCardColumns native drop disposition', () => {+ it('restores all columns and skips reorder when dropped outside', () => {+ const onReorder = vi.fn();+ const { container } = render(+ <DraggableCardColumns+ items={['a', 'b', 'c', 'd']}+ columns={2}+ getId={(id) => id}+ onReorder={onReorder}+ renderItem={(id) => <span>{id}</span>}+ reducedMotion+ forceFallback={false}+ />,+ );+ const columns = Array.from(container.firstElementChild?.children ?? []) as HTMLElement[];+ const [firstColumn, secondColumn] = columns;+ const instance = sortableMock.MockSortable.instances[0];+ const onStart = callback<() => void>(instance.options, 'onStart');+ const onEnd = callback<(event: SortableEvent) => void>(instance.options, 'onEnd');+ const moved = firstColumn.children[0] as HTMLElement;++ sortableMock.MockSortable.active = instance;+ onStart();+ secondColumn.append(moved);++ const external = document.createElement('div');+ document.body.append(external);+ external.dispatchEvent(new Event('drop', { bubbles: true }));++ onEnd({+ item: moved,+ from: firstColumn,+ to: secondColumn,+ oldIndex: 0,+ newIndex: secondColumn.children.length - 1,+ newDraggableIndex: secondColumn.children.length - 1,+ });++ expect(columnIds(firstColumn)).toEqual(['a', 'c']);+ expect(columnIds(secondColumn)).toEqual(['b', 'd']);+ expect(onReorder).not.toHaveBeenCalled();+ external.remove();+ });++ it('persists a cross-column reorder when dropped inside a column', () => {+ const onReorder = vi.fn();+ const { container } = render(+ <DraggableCardColumns+ items={['a', 'b', 'c', 'd']}+ columns={2}+ getId={(id) => id}+ onReorder={onReorder}+ renderItem={(id) => <span>{id}</span>}+ reducedMotion+ forceFallback={false}+ />,+ );+ const columns = Array.from(container.firstElementChild?.children ?? []) as HTMLElement[];+ const [firstColumn, secondColumn] = columns;+ const instance = sortableMock.MockSortable.instances[0];+ const onStart = callback<() => void>(instance.options, 'onStart');+ const onEnd = callback<(event: SortableEvent) => void>(instance.options, 'onEnd');+ const moved = firstColumn.children[0] as HTMLElement;++ sortableMock.MockSortable.active = instance;+ onStart();+ secondColumn.append(moved);+ (secondColumn.children[secondColumn.children.length - 1] as HTMLElement).dispatchEvent(+ new Event('drop', { bubbles: true }),+ );++ onEnd({+ item: moved,+ from: firstColumn,+ to: secondColumn,+ oldIndex: 0,+ newIndex: secondColumn.children.length - 1,+ newDraggableIndex: secondColumn.children.length - 1,+ });++ expect(columnIds(firstColumn)).toEqual(['a', 'c']);+ expect(columnIds(secondColumn)).toEqual(['b', 'd']);+ expect(onReorder).toHaveBeenCalledWith(['b', 'c', 'd', 'a']);+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.tsindex 7164f3990f..6b08925ba4 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts@@ -1,11 +1,12 @@// @vitest-environment jsdomimport { createElement, type ReactNode } from 'react';-import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';+import { cleanup, createEvent, fireEvent, render, screen, within } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SessionCard } from '../SessionCard';import { sessionCardVisualCases } from '../__fixtures__/sessionCardVisualCases';+import { SPLIT_GROUP_SESSION_MIME } from '../../splitGroupDnd';const mocks = vi.hoisted(() => ({navigate: vi.fn(),@@ -226,6 +227,69 @@ describe('SessionCard visual cases', () => {expect(mocks.ensureInitialMessages).toHaveBeenCalledWith('short-idle-cc');});+ it.each(['card', 'list'] as const)(+ 'uses native %s dragging for normal content while excluding action buttons',+ (variant) => {+ const visualCase = sessionCardVisualCases.find((item) => item.id === 'short-idle-cc');+ if (!visualCase) throw new Error('Missing idle visual case');+ const values = new Map<string, string>();+ const dataTransfer = {+ effectAllowed: 'none',+ setData: (format: string, data: string) => values.set(format, data),+ };++ const { container } = render(+ createElement(+ 'div',+ {+ 'data-sortable-id': visualCase.session.id,+ 'data-sortable-native-dnd': 'true',+ },+ createElement(SessionCard, {+ session: visualCase.session,+ variant,+ isActive: false,+ isRunning: false,+ isAttached: false,+ hasAttentionNotification: false,+ isSelected: false,+ onClick: vi.fn(),+ onAction: vi.fn(),+ onRename: vi.fn(),+ onTogglePin: vi.fn(),+ projectOptions: [],+ }),+ ),+ );++ const card = container.querySelector<HTMLElement>('[data-sidebar-session-row="true"]');+ const title = within(card!).getByText(visualCase.session.title);+ const actionButton = card?.querySelector<HTMLButtonElement>(+ 'button[aria-label="ccAgent.sidebar.sessionMenu.moreActions"]',+ );+ expect(card?.draggable).toBe(true);+ expect(card?.querySelector('[data-split-group-drag-handle="true"]')).toBeNull();+ expect(actionButton).not.toBeNull();++ fireEvent.pointerDown(title, { button: 0, pointerType: 'mouse' });+ fireEvent.dragStart(card!, { dataTransfer });++ expect(values.get(SPLIT_GROUP_SESSION_MIME)).toBe(visualCase.session.id);+ expect(dataTransfer.effectAllowed).toBe('copyMove');++ values.clear();+ dataTransfer.effectAllowed = 'none';+ fireEvent.pointerDown(actionButton!, { button: 0, pointerType: 'mouse' });+ const blockedDragStart = createEvent.dragStart(card!, { dataTransfer });+ const preventDefault = vi.spyOn(blockedDragStart, 'preventDefault');+ fireEvent(card!, blockedDragStart);++ expect(preventDefault).toHaveBeenCalledOnce();+ expect(values.has(SPLIT_GROUP_SESSION_MIME)).toBe(false);+ expect(dataTransfer.effectAllowed).toBe('none');+ },+ );+it.each(sessionCardVisualCases.map((item) => [item.label, item.id] as const))('renders visual case: %s',(_label, id) => {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.tsindex 5ebc79fd98..1297101816 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@@ -257,14 +257,34 @@ describe('SessionCard review regressions', () => {});it('aligns the session row cursor with the actual split drag source state', () => {+ expect(sessionItemSource).toContain("!isEditing && 'cursor-pointer'");expect(sessionItemSource).toContain(- "!isEditing && 'cursor-pointer'",+ 'draggable={splitDragEnabled && (dragContainerState.nativeSortable || !needsSplitDragHandle)}',);- expect(sessionItemSource).toContain('draggable={splitDragEnabled}');expect(sessionItemSource).toContain('inSortableContainer: true');+ expect(sessionItemSource).toContain('nativeSortable: false');expect(sessionItemSource).toContain("sortableDragBlocked: Boolean(row?.closest('[data-no-drag]'))",);+ expect(sessionItemSource).toContain(+ "nativeSortable: Boolean(row?.closest('[data-sortable-native-dnd]'))",+ );+ expect(sessionItemSource).toContain('data-split-group-drag-handle');+ expect(sessionItemSource).toContain('data-no-drag={splitDragHandleActive');+ });++ it('wires pinned card and list titles into split drag without disabling item sorting', () => {+ expect(sessionCardSource).toContain('data-split-group-drag-source');+ expect(sessionCardSource).toContain(+ 'draggable={splitDragEnabled && (dragContainerState.nativeSortable || !needsSplitDragHandle)}',+ );+ expect(sessionCardSource).toContain('nativeSortable: false');+ expect(sessionCardSource).toContain(+ "nativeSortable: Boolean(card?.closest('[data-sortable-native-dnd]'))",+ );+ expect(sessionCardSource).toContain('data-split-group-drag-handle');+ expect(sessionCardSource).toContain('data-no-drag={splitDragHandleActive');+ expect(sessionCardSource).toContain('writeSplitGroupSessionDragData');});it('wires split creation into both sidebar rendering modes', () => {diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.tsindex 876ff63669..8a8afc6595 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionRowRenderIsolation.test.ts@@ -18,7 +18,7 @@*/import { createElement, Fragment } from 'react';-import { act, cleanup, render } from '@testing-library/react';+import { act, cleanup, createEvent, fireEvent, render } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { readFileSync } from 'node:fs';import { resolve } from 'node:path';@@ -29,6 +29,7 @@ import {clearSessionAttention,} from '@/lib/sessionAttentionStore';import { SessionAttentionUrgencyProvider } from '../../contexts/SessionAttentionUrgencyContext';+import { SPLIT_GROUP_SESSION_MIME } from '../../splitGroupDnd';// ── mocks:剥离与"渲染隔离"无关的重依赖,只留计数探针 ──────────────────────────@@ -87,6 +88,10 @@ vi.mock('@/lib/toast', () => ({toast: { success: vi.fn(), warning: vi.fn(), error: vi.fn() },}));+vi.mock('@/lib/makerChatStore', () => ({+ makerChatStore: { ensureInitialMessages: vi.fn() },+}));+// mock 之后再 import,确保 SessionItem 拿到的是探针版依赖。import { SessionItem } from '../SessionItem';@@ -192,6 +197,69 @@ describe('SessionItem — 归档视觉', () => {});});+describe('SessionItem — 置顶分屏拖拽', () => {+ it('原生整行拖拽保留普通内容起手,并排除内部操作按钮', () => {+ const pinnedSession = {+ ...makeSession('pinned-session'),+ pinnedAt: '2026-08-08T00:00:00.000Z',+ };+ const values = new Map<string, string>();+ const dataTransfer = {+ effectAllowed: 'none',+ setData: (format: string, data: string) => values.set(format, data),+ };+ const { container } = render(+ createElement(SessionAttentionUrgencyProvider, {+ urgentSessionIds: new Set<string>(),+ children: createElement(+ 'div',+ {+ 'data-sortable-id': pinnedSession.id,+ 'data-sortable-native-dnd': 'true',+ },+ createElement(SessionItem, {+ session: pinnedSession,+ isActive: false,+ isRunning: false,+ hasAttentionNotification: false,+ onClick: noop,+ onAction: noop,+ onRename: noop,+ onTogglePin: noop,+ }),+ ),+ }),+ );++ const row = container.querySelector<HTMLElement>('[data-session-id="pinned-session"]');+ const title = row?.querySelector<HTMLElement>('.sidebar-title-marquee__ellipsis');+ const actionButton = row?.querySelector<HTMLButtonElement>(+ 'button[aria-label="ccAgent.sidebar.sessionMenu.moreActions"]',+ );+ expect(row?.draggable).toBe(true);+ expect(row?.querySelector('[data-split-group-drag-handle="true"]')).toBeNull();+ expect(title).not.toBeNull();+ expect(actionButton).not.toBeNull();++ fireEvent.pointerDown(title!, { button: 0, pointerType: 'mouse' });+ fireEvent.dragStart(row!, { dataTransfer });++ expect(values.get(SPLIT_GROUP_SESSION_MIME)).toBe(pinnedSession.id);+ expect(dataTransfer.effectAllowed).toBe('copyMove');++ values.clear();+ dataTransfer.effectAllowed = 'none';+ fireEvent.pointerDown(actionButton!, { button: 0, pointerType: 'mouse' });+ const blockedDragStart = createEvent.dragStart(row!, { dataTransfer });+ const preventDefault = vi.spyOn(blockedDragStart, 'preventDefault');+ fireEvent(row!, blockedDragStart);++ expect(preventDefault).toHaveBeenCalledOnce();+ expect(values.has(SPLIT_GROUP_SESSION_MIME)).toBe(false);+ expect(dataTransfer.effectAllowed).toBe('none');+ });+});+// ── 不变量 2:attention 变化只惊动自己那一行 ──────────────────────────────────describe('SessionItem — attention 渲染隔离', () => {diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsxindex 22604ef419..68b834df74 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx@@ -356,6 +356,7 @@ export function PinnedSection({getId={getEntryId}onReorder={onReorder}reducedMotion={reducedMotion}+ forceFallback={false}renderItem={renderCard}/>) : mode === 'list' ? (@@ -368,6 +369,7 @@ export function PinnedSection({getId={getEntryId}onReorder={onReorder}reducedMotion={reducedMotion}+ forceFallback={false}className="flex flex-col gap-0.5"renderItem={renderCard}/>@@ -377,6 +379,7 @@ export function PinnedSection({getId={getEntryId}onReorder={onReorder}reducedMotion={reducedMotion}+ forceFallback={false}className="flex flex-col gap-0.5"renderItem={(entry) =>entry.kind === 'project' ? (diff --git a/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts b/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.tsindex 31d89a4e1d..05acb6a6c9 100644--- a/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts+++ b/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts@@ -1,6 +1,19 @@import type { DropSide } from './splitGroupStore';+import { buildSessionDeepLink } from '@/lib/deepLink';+import {+ isSessionLinkDropTarget,+ SESSION_LINK_DROP_MIME,+ SESSION_LINK_DROP_TARGET_SELECTOR,+} from '@/lib/sessionLinkDrop';export const SPLIT_GROUP_SESSION_MIME = 'application/x-cindy-session-id';+/** Backward-compatible feature-local name for the shared composer payload. */+export { SESSION_LINK_DROP_MIME as SPLIT_GROUP_SESSION_LINK_MIME };+/** 输入框优先消费任务拖放,分屏 pane 不应在 capture 阶段抢走。 */+export const SPLIT_GROUP_COMPOSER_DROP_TARGET_SELECTOR = SESSION_LINK_DROP_TARGET_SELECTOR;+export const SPLIT_GROUP_DRAG_HANDLE_SELECTOR = '[data-split-group-drag-handle]';+export const SPLIT_GROUP_DRAG_INTERACTIVE_SELECTOR =+ 'button, input, textarea, select, a[href], [role="menuitem"]';export interface DropRect {left: number;@@ -14,14 +27,24 @@ interface SplitGroupDragDataTransfer {setData(format: string, data: string): void;}+interface SplitGroupDragOptions {+ /** 远程任务的归属设备,冻结进深链避免引用解析漂移。 */+ deviceId?: string | null;+}+export function writeSplitGroupSessionDragData(dataTransfer: SplitGroupDragDataTransfer,sessionIdInput: string,+ options?: SplitGroupDragOptions,): boolean {const sessionId = sessionIdInput.trim();if (!sessionId) return false;- dataTransfer.effectAllowed = 'move';+ const link = buildSessionDeepLink(sessionId, { deviceId: options?.deviceId });+ // The same gesture can reorder a row (move) or insert its link into the+ // composer (copy), so the source must advertise both legal drop effects.+ dataTransfer.effectAllowed = 'copyMove';dataTransfer.setData(SPLIT_GROUP_SESSION_MIME, sessionId);+ dataTransfer.setData(SESSION_LINK_DROP_MIME, link);dataTransfer.setData('text/plain', sessionId);return true;}@@ -30,6 +53,10 @@ export function hasSplitGroupSessionType(types: ArrayLike<string>): boolean {return Array.from(types).includes(SPLIT_GROUP_SESSION_MIME);}+export function isSplitGroupComposerDropTarget(target: EventTarget | null): boolean {+ return isSessionLinkDropTarget(target);+}+export interface SplitDragSourceContext {editing: boolean;orcaRole?: string | null;@@ -37,23 +64,54 @@ export interface SplitDragSourceContext {inSortableContainer: boolean;/** SortableJS 是否已被祖先的 data-no-drag 边界拦截。 */sortableDragBlocked?: boolean;+ /** SortableJS 是否使用原生 DnD;原生模式可与右侧分屏 drop 共用一条手势。 */+ nativeSortable?: boolean;+ /** Sortable 行是否提供了独立、会被 data-no-drag 隔离的原生分屏拖拽起手区。 */+ hasDedicatedHandle?: boolean;+}++/** Sortable 行必须从独立起手区开始分屏拖拽,避免与整项排序争抢同一手势。 */+export function needsDedicatedSplitGroupDragHandle(+ context: Pick<+ SplitDragSourceContext,+ 'inSortableContainer' | 'sortableDragBlocked' | 'nativeSortable'+ >,+): boolean {+ return (+ context.inSortableContainer &&+ context.sortableDragBlocked !== true &&+ context.nativeSortable !== true+ );}/*** 一行任务是否充当分屏拖拽源。SortableJS(forceFallback 指针手势)与原生 HTML5* 拖拽会争抢同一次手势:行带 `draggable` 时浏览器可能启动原生拖拽并中断 fallback- * 排序,因此未被 `data-no-drag` 边界隔离的 Sortable 行保持原有手动排序,不叠加分屏- * 拖拽。Orca worker 不进侧栏列表,防御性排除,避免把 worker id 写进分屏树后与 Lead- * 路由错位。+ * 排序。Sortable 行只有在已被 `data-no-drag` 隔离,或提供独立的分屏拖拽起手区时才+ * 放行;原生 Sortable 模式则允许整行同时进入排序或右侧分屏。Orca worker 不进侧栏列表,+ * 防御性排除,避免把 worker id 写进分屏树后与 Lead 路由错位。*/export function isSplitGroupDragSource(context: SplitDragSourceContext): boolean {return (!context.editing &&context.orcaRole !== 'worker' &&- (!context.inSortableContainer || context.sortableDragBlocked === true)+ (!needsDedicatedSplitGroupDragHandle(context) || context.hasDedicatedHandle === true));}+export interface SplitDragStartContext {+ enabled: boolean;+ needsDedicatedHandle: boolean;+ startedOnDedicatedHandle: boolean;+ startedOnInteractiveElement: boolean;+}++/** 原生拖拽只能从允许的区域开始;按钮、输入框和菜单项永远保留自身交互。 */+export function shouldStartSplitGroupDrag(context: SplitDragStartContext): boolean {+ if (!context.enabled || context.startedOnInteractiveElement) return false;+ return !context.needsDedicatedHandle || context.startedOnDedicatedHandle;+}+/** 按指针距四条边的最近距离决定左 / 右 / 上 / 下落点。 */export function resolveSplitDropSide(rect: DropRect,diff --git a/apps/desktop/src/renderer/lib/sessionLinkDrop.ts b/apps/desktop/src/renderer/lib/sessionLinkDrop.tsnew file mode 100644index 0000000000..3905c24321--- /dev/null+++ b/apps/desktop/src/renderer/lib/sessionLinkDrop.ts@@ -0,0 +1,13 @@+/**+ * Task deep-link drag payload shared by sidebar drag sources and composers.+ * The split-pane MIME remains feature-local; this payload is intentionally+ * generic so ChatInput does not depend on the cc-agent feature module.+ */+export const SESSION_LINK_DROP_MIME = 'application/x-cindy-session-link';+export const SESSION_LINK_DROP_TARGET_SELECTOR =+ '[data-split-group-composer-drop-target]';++export function isSessionLinkDropTarget(target: EventTarget | null): boolean {+ const element = typeof Element !== 'undefined' && target instanceof Element ? target : null;+ return Boolean(element?.closest(SESSION_LINK_DROP_TARGET_SELECTOR));+}