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): 支持将任务拖出窗口打开 (#2367)

Dash226e51acee3e
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index c2453890c1..18f5433083 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -888,6 +888,7 @@ function ensureMacIOSSimulatorWdaArchive(platform: ForgePlatform): void {
const MACOS_VOICE_HELPER_DEPLOYMENT_TARGET = 'macos10.15';
const MACOS_AGENT_ISLAND_HELPER_DEPLOYMENT_TARGET = 'macos14.0';
const MACOS_COMPUTER_PERMISSION_GUIDE_HELPER_DEPLOYMENT_TARGET = 'macos13.0';
+const MACOS_SESSION_DRAG_RELEASE_HELPER_DEPLOYMENT_TARGET = 'macos10.15';
function swiftTargetTriple(cpuArch: 'arm64' | 'x86_64', deploymentTarget: string): string {
return `${cpuArch}-apple-${deploymentTarget}`;
@@ -1106,6 +1107,35 @@ function buildMacComputerPermissionGuideHelper(platform: ForgePlatform, arch: Fo
console.log(`[forge:prePackage] macOS computer permission guide helper (${swiftArchLabel(arch, MACOS_COMPUTER_PERMISSION_GUIDE_HELPER_DEPLOYMENT_TARGET)}) -> ${dest} (${sizeMb} MB)`);
}
+function buildMacSessionDragReleaseHelper(platform: ForgePlatform, arch: ForgeArch): void {
+ if (process.platform !== 'darwin' || !isMacForgePlatform(platform)) return;
+ const src = path.join(
+ __dirname,
+ 'native',
+ 'session-drag-release',
+ 'macos-session-drag-release-helper.swift',
+ );
+ const destDir = path.join(__dirname, 'resources', 'tools', 'session-drag-release');
+ const dest = path.join(destDir, 'xdt-macos-session-drag-release-helper');
+ if (!fs.existsSync(src)) {
+ throw new Error(`[forge] macOS session drag release helper source missing at ${src}`);
+ }
+ fs.mkdirSync(destDir, { recursive: true });
+ buildSwiftHelperForForgeArch(
+ src,
+ dest,
+ arch,
+ MACOS_SESSION_DRAG_RELEASE_HELPER_DEPLOYMENT_TARGET,
+ ['-O'],
+ 'session drag release helper',
+ );
+ fs.chmodSync(dest, 0o755);
+ const sizeMb = (fs.statSync(dest).size / (1024 * 1024)).toFixed(2);
+ console.log(
+ `[forge:prePackage] macOS session drag release helper (${swiftArchLabel(arch, MACOS_SESSION_DRAG_RELEASE_HELPER_DEPLOYMENT_TARGET)}) -> ${dest} (${sizeMb} MB)`,
+ );
+}
+
// MakerNSIS is Windows-only (native dependency), conditionally require to
// avoid import errors on macOS / Linux.
const makers: ForgeConfig['makers'] = [
@@ -1386,6 +1416,7 @@ const config: ForgeConfig = {
buildMacVoiceInputModifierShortcutListener(platform, arch);
buildMacAgentIslandHelper(platform, arch);
buildMacComputerPermissionGuideHelper(platform, arch);
+ buildMacSessionDragReleaseHelper(platform, arch);
},
// packaged dir 产出后、makers 跑之前签内部 .exe。这样 NSIS 包出来的
// Setup.exe 内嵌的、和 publish 阶段从同一 packagedDir 打的热更 ZIP 内嵌的,
diff --git a/apps/desktop/native/session-drag-release/macos-session-drag-release-helper.swift b/apps/desktop/native/session-drag-release/macos-session-drag-release-helper.swift
new file mode 100644
index 0000000000..ea56b89e49
--- /dev/null
+++ b/apps/desktop/native/session-drag-release/macos-session-drag-release-helper.swift
@@ -0,0 +1,112 @@
+import AppKit
+import Foundation
+
+private struct Command: Decodable {
+ let type: String
+ let token: Int64?
+}
+
+private func emit(_ payload: [String: Any]) {
+ guard JSONSerialization.isValidJSONObject(payload),
+ let data = try? JSONSerialization.data(withJSONObject: payload),
+ var line = String(data: data, encoding: .utf8) else { return }
+ line.append("\n")
+ FileHandle.standardOutput.write(Data(line.utf8))
+}
+
+/// A tiny, listen-only AppKit process used only while Cindy owns a task drag.
+/// It never records positions or input contents; it reports one matching
+/// left-button release and immediately removes both event monitors.
+private final class DragReleaseListener {
+ private var globalMonitor: Any?
+ private var localMonitor: Any?
+ private var armedToken: Int64?
+
+ func arm(token: Int64) {
+ disarm()
+ armedToken = token
+ let mask: NSEvent.EventTypeMask = [.leftMouseUp]
+ globalMonitor = NSEvent.addGlobalMonitorForEvents(matching: mask) { [weak self] _ in
+ self?.released()
+ }
+ localMonitor = NSEvent.addLocalMonitorForEvents(matching: mask) { [weak self] event in
+ self?.released()
+ return event
+ }
+ if globalMonitor == nil && localMonitor == nil {
+ armedToken = nil
+ emit(["type": "unavailable", "token": token])
+ }
+ }
+
+ func disarm() {
+ if let monitor = globalMonitor {
+ NSEvent.removeMonitor(monitor)
+ globalMonitor = nil
+ }
+ if let monitor = localMonitor {
+ NSEvent.removeMonitor(monitor)
+ localMonitor = nil
+ }
+ armedToken = nil
+ }
+
+ private func released() {
+ guard let token = armedToken else { return }
+ disarm()
+ emit(["type": "mouse-up", "token": token])
+ }
+}
+
+private final class ApplicationDelegate: NSObject, NSApplicationDelegate {
+ private let listener = DragReleaseListener()
+ private var inputBuffer = Data()
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ NSApp.setActivationPolicy(.accessory)
+ beginReadingCommands()
+ emit(["type": "ready"])
+ }
+
+ func applicationWillTerminate(_ notification: Notification) {
+ FileHandle.standardInput.readabilityHandler = nil
+ listener.disarm()
+ }
+
+ private func beginReadingCommands() {
+ FileHandle.standardInput.readabilityHandler = { [weak self] handle in
+ let data = handle.availableData
+ if data.isEmpty {
+ DispatchQueue.main.async { NSApp.terminate(nil) }
+ return
+ }
+ DispatchQueue.main.async { self?.consume(data) }
+ }
+ }
+
+ private func consume(_ data: Data) {
+ inputBuffer.append(data)
+ while let newline = inputBuffer.firstIndex(of: 0x0A) {
+ let line = inputBuffer.prefix(upTo: newline)
+ inputBuffer.removeSubrange(...newline)
+ guard !line.isEmpty,
+ let command = try? JSONDecoder().decode(Command.self, from: line) else { continue }
+ switch command.type {
+ case "arm":
+ guard let token = command.token else { continue }
+ listener.arm(token: token)
+ case "disarm":
+ listener.disarm()
+ default:
+ break
+ }
+ }
+ }
+}
+
+private let application = NSApplication.shared
+private let delegate = ApplicationDelegate()
+application.delegate = delegate
+application.setActivationPolicy(.accessory)
+application.finishLaunching()
+application.run()
diff --git a/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts b/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts
index aee7809df2..f934bd6cee 100644
--- a/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts
@@ -21,12 +21,20 @@ describe('model pricing prewarm ordering', () => {
it('prewarms after localDb user takeover succeeds', () => {
const localDbReady = source.indexOf('const dbClientTakeover = await ensureLifecycleDbClient(userId);');
const failedGuard = source.indexOf("dbClientTakeover.mode === 'failed'");
+ const unchangedGuard = source.indexOf("dbClientTakeover.mode === 'unchanged'");
+ const attachmentSweep = source.indexOf('sweepStagedChatAttachmentsOnStartup({');
+ const lifecycleStartupBlock = source.slice(localDbReady, attachmentSweep);
const earlyUsageIpc = source.indexOf('registerMakerUsageIpc(ipcMaker);');
const prewarm = source.indexOf('void prewarmModelPricing();');
const refreshCatalog = source.indexOf('await refreshCustomProvidersIntoCatalog(');
expect(localDbReady).toBeGreaterThanOrEqual(0);
expect(failedGuard).toBeGreaterThan(localDbReady);
+ expect(unchangedGuard).toBeGreaterThan(failedGuard);
+ expect(attachmentSweep).toBeGreaterThan(unchangedGuard);
+ expect(lifecycleStartupBlock).not.toContain(
+ 'BrowserWindow.getAllWindows().some(isSecondaryAppWindow)',
+ );
expect(earlyUsageIpc).toBeGreaterThanOrEqual(0);
expect(prewarm).toBeGreaterThan(failedGuard);
expect(prewarm).toBeGreaterThan(earlyUsageIpc);
diff --git a/apps/desktop/src/main/__tests__/sessionDragNativeOpenCoordinator.test.ts b/apps/desktop/src/main/__tests__/sessionDragNativeOpenCoordinator.test.ts
new file mode 100644
index 0000000000..c70a3399b1
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/sessionDragNativeOpenCoordinator.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { SessionDragNativeOpenCoordinator } from '../sessionDragNativeOpenCoordinator';
+
+describe('SessionDragNativeOpenCoordinator', () => {
+ it('opens on native release and lets the later fallback consume the result once', () => {
+ const owner = {};
+ const beforeOpen = vi.fn();
+ const openIfOutside = vi.fn(() => true);
+ const coordinator = new SessionDragNativeOpenCoordinator();
+ coordinator.begin(1, owner, 'session-a', 'device-a');
+
+ expect(coordinator.handleNativeRelease(1, beforeOpen, openIfOutside)).toBe(true);
+ expect(beforeOpen).toHaveBeenCalledOnce();
+ expect(openIfOutside).toHaveBeenCalledWith({
+ owner,
+ sessionId: 'session-a',
+ deviceId: 'device-a',
+ });
+ expect(coordinator.consumeNativeResult(owner, 'session-a', 'device-a')).toBe(true);
+ expect(coordinator.consumeNativeResult(owner, 'session-a', 'device-a')).toBeNull();
+ });
+
+ it('preserves an inside-window result so dragend does not reclassify it', () => {
+ const owner = {};
+ const coordinator = new SessionDragNativeOpenCoordinator();
+ coordinator.begin(2, owner, 'session-a');
+
+ expect(coordinator.handleNativeRelease(2, vi.fn(), () => false)).toBe(false);
+ expect(coordinator.consumeNativeResult(owner, 'session-a')).toBe(false);
+ });
+
+ it('ignores stopped, stale, and mismatched native results', () => {
+ let now = 100;
+ const firstOwner = {};
+ const secondOwner = {};
+ const coordinator = new SessionDragNativeOpenCoordinator({
+ now: () => now,
+ resultTtlMs: 50,
+ });
+
+ coordinator.begin(3, firstOwner, 'session-a');
+ coordinator.stop(3);
+ expect(coordinator.handleNativeRelease(3, vi.fn(), () => true)).toBeNull();
+
+ coordinator.begin(4, firstOwner, 'session-a', 'device-a');
+ coordinator.handleNativeRelease(4, vi.fn(), () => true);
+ expect(coordinator.consumeNativeResult(firstOwner, 'session-b', 'device-a')).toBeNull();
+
+ coordinator.begin(5, secondOwner, 'session-a');
+ coordinator.handleNativeRelease(5, vi.fn(), () => true);
+ now = 151;
+ expect(coordinator.consumeNativeResult(secondOwner, 'session-a')).toBeNull();
+ });
+
+ it('invalidates an unconsumed result when the same window starts another drag', () => {
+ const owner = {};
+ const coordinator = new SessionDragNativeOpenCoordinator();
+ coordinator.begin(6, owner, 'session-a');
+ coordinator.handleNativeRelease(6, vi.fn(), () => true);
+
+ coordinator.begin(7, owner, 'session-a');
+
+ expect(coordinator.consumeNativeResult(owner, 'session-a')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/sessionDragPreviewController.test.ts b/apps/desktop/src/main/__tests__/sessionDragPreviewController.test.ts
new file mode 100644
index 0000000000..30f66186d3
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/sessionDragPreviewController.test.ts
@@ -0,0 +1,208 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ SessionDragPreviewController,
+ type SessionDragPreviewWindowLike,
+} from '../sessionDragPreviewController';
+import type { SessionDragPreviewPalette } from '../../shared/sessionDragPreview';
+
+const PALETTE: SessionDragPreviewPalette = {
+ surface: 'rgb(31, 32, 34)',
+ border: 'rgb(64, 66, 70)',
+ text: 'rgb(244, 244, 242)',
+};
+
+function createPreviewWindow(): SessionDragPreviewWindowLike & {
+ setPosition: ReturnType<typeof vi.fn>;
+ setOpacity: ReturnType<typeof vi.fn>;
+ showInactive: ReturnType<typeof vi.fn>;
+ hide: ReturnType<typeof vi.fn>;
+ close: ReturnType<typeof vi.fn>;
+} {
+ return {
+ ready: Promise.resolve(),
+ isDestroyed: vi.fn(() => false),
+ setPosition: vi.fn(),
+ setOpacity: vi.fn(),
+ showInactive: vi.fn(),
+ hide: vi.fn(),
+ close: vi.fn(),
+ };
+}
+
+describe('SessionDragPreviewController', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('keeps the preview hidden while the pointer is inside Cindy windows', () => {
+ const owner = {};
+ const preview = createPreviewWindow();
+ const create = vi.fn(() => preview);
+ const controller = new SessionDragPreviewController({
+ screen: {
+ getCursorScreenPoint: () => ({ x: 200, y: 200 }),
+ getDisplayNearestPoint: () => ({ workArea: { x: 0, y: 0, width: 1200, height: 800 } }),
+ },
+ getAppWindowBounds: () => [{ x: 0, y: 0, width: 800, height: 600 }],
+ createPreviewWindow: create,
+ });
+
+ controller.begin(owner, '任务 A', PALETTE);
+ vi.advanceTimersByTime(48);
+
+ expect(create).toHaveBeenCalledWith('任务 A', PALETTE);
+ expect(preview.showInactive).not.toHaveBeenCalled();
+ expect(controller.isActive()).toBe(true);
+ controller.end(owner);
+ });
+
+ it('shows and follows a preview only after the pointer leaves all Cindy windows', async () => {
+ const owner = {};
+ let point = { x: 200, y: 200 };
+ const preview = createPreviewWindow();
+ const create = vi.fn(() => preview);
+ const controller = new SessionDragPreviewController({
+ screen: {
+ getCursorScreenPoint: () => point,
+ getDisplayNearestPoint: () => ({ workArea: { x: 0, y: 0, width: 1200, height: 800 } }),
+ },
+ getAppWindowBounds: () => [{ x: 0, y: 0, width: 800, height: 600 }],
+ createPreviewWindow: create,
+ });
+
+ controller.begin(owner, '任务 A', PALETTE);
+ point = { x: 900, y: 700 };
+ vi.advanceTimersByTime(16);
+ await Promise.resolve();
+
+ expect(create).toHaveBeenCalledWith('任务 A', PALETTE);
+ expect(preview.setPosition).toHaveBeenCalledWith(880, 708, false);
+ expect(preview.showInactive).toHaveBeenCalled();
+
+ point = { x: 300, y: 300 };
+ vi.advanceTimersByTime(16);
+ expect(preview.hide).toHaveBeenCalled();
+
+ point = { x: 900, y: 700 };
+ vi.advanceTimersByTime(16);
+ expect(create).toHaveBeenCalledOnce();
+ expect(preview.showInactive).toHaveBeenCalledTimes(2);
+
+ controller.end(owner);
+ expect(preview.hide).toHaveBeenCalled();
+ expect(preview.setOpacity).not.toHaveBeenCalled();
+ expect(preview.close).not.toHaveBeenCalled();
+ vi.runOnlyPendingTimers();
+ expect(preview.setOpacity).toHaveBeenCalledWith(0);
+ expect(preview.close).toHaveBeenCalledOnce();
+ expect(controller.isActive()).toBe(false);
+ });
+
+ it('can show again when the preview finishes loading after re-entering Cindy', async () => {
+ const owner = {};
+ let point = { x: 200, y: 200 };
+ let resolveReady!: () => void;
+ const preview = {
+ ...createPreviewWindow(),
+ ready: new Promise<void>((resolve) => {
+ resolveReady = resolve;
+ }),
+ };
+ const create = vi.fn(() => preview);
+ const controller = new SessionDragPreviewController({
+ screen: {
+ getCursorScreenPoint: () => point,
+ getDisplayNearestPoint: () => ({ workArea: { x: 0, y: 0, width: 1200, height: 800 } }),
+ },
+ getAppWindowBounds: () => [{ x: 0, y: 0, width: 800, height: 600 }],
+ createPreviewWindow: create,
+ });
+
+ controller.begin(owner, '任务 A', PALETTE);
+ point = { x: 900, y: 700 };
+ vi.advanceTimersByTime(16);
+ point = { x: 300, y: 300 };
+ vi.advanceTimersByTime(16);
+ resolveReady();
+ await Promise.resolve();
+
+ expect(preview.showInactive).not.toHaveBeenCalled();
+
+ point = { x: 900, y: 700 };
+ vi.advanceTimersByTime(16);
+ expect(preview.showInactive).toHaveBeenCalledOnce();
+
+ controller.end(owner);
+ });
+
+ it('does not let another window stop the active drag', () => {
+ const owner = {};
+ const other = {};
+ const preview = createPreviewWindow();
+ const controller = new SessionDragPreviewController({
+ screen: {
+ getCursorScreenPoint: () => ({ x: 900, y: 700 }),
+ getDisplayNearestPoint: () => ({ workArea: { x: 0, y: 0, width: 1200, height: 800 } }),
+ },
+ getAppWindowBounds: () => [],
+ createPreviewWindow: () => preview,
+ });
+
+ controller.begin(owner, '任务 A', PALETTE);
+ controller.end(other);
+
+ expect(controller.isActive()).toBe(true);
+ controller.end(owner);
+ });
+
+ it('ignores a native release from an older drag token', () => {
+ const owner = {};
+ const firstPreview = createPreviewWindow();
+ const secondPreview = createPreviewWindow();
+ const controller = new SessionDragPreviewController({
+ screen: {
+ getCursorScreenPoint: () => ({ x: 900, y: 700 }),
+ getDisplayNearestPoint: () => ({ workArea: { x: 0, y: 0, width: 1200, height: 800 } }),
+ },
+ getAppWindowBounds: () => [],
+ createPreviewWindow: vi.fn().mockReturnValueOnce(firstPreview).mockReturnValue(secondPreview),
+ });
+
+ const firstToken = controller.begin(owner, '任务 A', PALETTE);
+ const secondToken = controller.begin(owner, '任务 B', PALETTE);
+ expect(firstToken).not.toBe(secondToken);
+
+ expect(controller.endByToken(firstToken!)).toBe(false);
+ expect(controller.isActive()).toBe(true);
+ expect(secondPreview.hide).not.toHaveBeenCalled();
+
+ expect(controller.endByToken(secondToken!)).toBe(true);
+ expect(controller.isActive()).toBe(false);
+ expect(secondPreview.hide).toHaveBeenCalledOnce();
+ });
+
+ it('notifies native cleanup when the safety timeout ends a drag', () => {
+ const onStopped = vi.fn();
+ const controller = new SessionDragPreviewController({
+ screen: {
+ getCursorScreenPoint: () => ({ x: 900, y: 700 }),
+ getDisplayNearestPoint: () => ({ workArea: { x: 0, y: 0, width: 1200, height: 800 } }),
+ },
+ getAppWindowBounds: () => [],
+ createPreviewWindow,
+ maxDurationMs: 32,
+ onStopped,
+ });
+
+ const token = controller.begin({}, '任务 A', PALETTE);
+ vi.advanceTimersByTime(48);
+
+ expect(controller.isActive()).toBe(false);
+ expect(onStopped).toHaveBeenCalledWith(token);
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/sessionDragPreviewHtml.test.ts b/apps/desktop/src/main/__tests__/sessionDragPreviewHtml.test.ts
new file mode 100644
index 0000000000..0f26e0d305
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/sessionDragPreviewHtml.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildSessionDragPreviewHtml,
+ parseSessionDragPreviewPalette,
+ truncateSessionDragPreviewLabel,
+} from '../sessionDragPreviewHtml';
+
+describe('sessionDragPreviewHtml', () => {
+ it('uses a validated application-theme palette and escapes the task label', () => {
+ const palette = parseSessionDragPreviewPalette({
+ surface: 'rgb(31, 32, 34)',
+ border: 'rgba(255, 255, 255, 0.22)',
+ text: '#f4f4f2',
+ });
+
+ expect(palette).toEqual({
+ surface: 'rgb(31, 32, 34)',
+ border: 'rgba(255, 255, 255, 0.22)',
+ text: '#f4f4f2',
+ });
+ const html = buildSessionDragPreviewHtml('A <remote> task', palette!);
+ expect(html).toContain('background:rgb(31, 32, 34)');
+ expect(html).toContain('border:1px solid rgba(255, 255, 255, 0.22)');
+ expect(html).toContain('color:#f4f4f2');
+ expect(html).toContain('A &lt;remote&gt; task');
+ expect(html).not.toContain('A <remote> task');
+ });
+
+ it.each([
+ ['non-object', 'red'],
+ ['missing field', { surface: '#fff', border: '#000' }],
+ ['style injection', { surface: '#fff;position:fixed', border: '#000', text: '#111' }],
+ [
+ 'numeric entity injection',
+ {
+ surface: 'rgb(0 0 0 / 1 &#41 &#59 background-image:url(https://example.invalid/pixel)',
+ border: '#000',
+ text: '#111',
+ },
+ ],
+ ['markup injection', { surface: '#fff', border: '#000', text: 'red"><script' }],
+ ['unsupported CSS', { surface: 'var(--surface)', border: '#000', text: '#111' }],
+ ['oversized value', { surface: `#${'f'.repeat(129)}`, border: '#000', text: '#111' }],
+ ])('rejects %s palette input', (_label, input) => {
+ expect(parseSessionDragPreviewPalette(input)).toBeNull();
+ });
+
+ it('truncates labels without splitting an emoji surrogate pair', () => {
+ const label = `${'a'.repeat(159)}😀tail`;
+
+ expect(truncateSessionDragPreviewLabel(label)).toBe(`${'a'.repeat(159)}😀`);
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/sessionDragReleaseNativeHost.test.ts b/apps/desktop/src/main/__tests__/sessionDragReleaseNativeHost.test.ts
new file mode 100644
index 0000000000..d614488461
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/sessionDragReleaseNativeHost.test.ts
@@ -0,0 +1,155 @@
+import { EventEmitter } from 'node:events';
+import fs from 'node:fs';
+import path from 'node:path';
+import { PassThrough } from 'node:stream';
+import type { ChildProcessByStdio } from 'node:child_process';
+import type { Readable, Writable } from 'node:stream';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ spawn: vi.fn(),
+ execFile: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ app: {
+ isPackaged: true,
+ getAppPath: vi.fn(),
+ getPath: vi.fn(),
+ },
+}));
+
+vi.mock('node:child_process', () => ({
+ spawn: h.spawn,
+ execFile: h.execFile,
+}));
+
+vi.mock('../logger.js', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+type FakeNativeProcess = Omit<
+ ChildProcessByStdio<Writable, Readable, Readable>,
+ 'stdin' | 'stdout' | 'stderr'
+> & {
+ stdin: PassThrough;
+ stdout: PassThrough;
+ stderr: PassThrough;
+ emit(event: 'exit', code: number | null, signal: NodeJS.Signals | null): boolean;
+ emit(event: 'error', error: Error): boolean;
+};
+
+const originalPlatform = process.platform;
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
+ Object.defineProperty(process, 'resourcesPath', {
+ value: '/Applications/Cindy.app/Contents/Resources',
+ configurable: true,
+ });
+ h.spawn.mockReset();
+ h.execFile.mockReset();
+});
+
+afterEach(() => {
+ Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+describe('SessionDragReleaseNativeHost', () => {
+ it('arms one token and forwards only its matching native mouse-up', async () => {
+ const child = createFakeChild();
+ const writes: string[] = [];
+ child.stdin.on('data', (chunk) => writes.push(chunk.toString()));
+ h.spawn.mockReturnValue(child);
+ const onMouseUp = vi.fn();
+ const { SessionDragReleaseNativeHost } = await import('../sessionDragReleaseNativeHost.js');
+ const host = new SessionDragReleaseNativeHost({ onMouseUp });
+
+ const prewarm = host.prewarm();
+ child.stdout.write('{"type":"ready"}\n');
+ await expect(prewarm).resolves.toBe(true);
+ await expect(host.arm(41)).resolves.toBe(true);
+ expect(writes).toContain('{"type":"arm","token":41}\n');
+
+ child.stdout.write('{"type":"mouse-up","token":40}\n');
+ expect(onMouseUp).not.toHaveBeenCalled();
+ child.stdout.write('{"type":"mouse-up","token":41}\n');
+ expect(onMouseUp).toHaveBeenCalledOnce();
+ expect(onMouseUp).toHaveBeenCalledWith(41);
+
+ host.dispose();
+ expect(child.kill).toHaveBeenCalledOnce();
+ });
+
+ it('does not arm after the drag ends while helper startup is pending', async () => {
+ const child = createFakeChild();
+ const writes: string[] = [];
+ child.stdin.on('data', (chunk) => writes.push(chunk.toString()));
+ h.spawn.mockReturnValue(child);
+ const { SessionDragReleaseNativeHost } = await import('../sessionDragReleaseNativeHost.js');
+ const host = new SessionDragReleaseNativeHost({ onMouseUp: vi.fn() });
+
+ const arm = host.arm(7);
+ host.disarm();
+ child.stdout.write('{"type":"ready"}\n');
+
+ await expect(arm).resolves.toBe(false);
+ expect(writes).not.toContain('{"type":"arm","token":7}\n');
+ host.dispose();
+ });
+
+ it('uses a listen-only, one-shot AppKit event monitor without reading cursor data', () => {
+ const source = fs
+ .readFileSync(
+ new URL(
+ '../../../native/session-drag-release/macos-session-drag-release-helper.swift',
+ import.meta.url,
+ ),
+ 'utf8',
+ )
+ .replace(/\r\n?/g, '\n');
+
+ expect(source).toContain('NSEvent.addGlobalMonitorForEvents(matching: mask)');
+ expect(source).toContain('NSEvent.addLocalMonitorForEvents(matching: mask)');
+ expect(source).toContain('let mask: NSEvent.EventTypeMask = [.leftMouseUp]');
+ expect(source).toContain('disarm()\n emit(["type": "mouse-up", "token": token])');
+ expect(source).not.toContain('mouseLocation');
+ expect(source).not.toContain('locationInWindow');
+ });
+
+ it('is included in the macOS package helper build', () => {
+ const forgeSource = fs.readFileSync(
+ path.resolve(__dirname, '..', '..', '..', 'forge.config.ts'),
+ 'utf8',
+ );
+ expect(forgeSource).toContain('function buildMacSessionDragReleaseHelper(');
+ expect(forgeSource).toContain('buildMacSessionDragReleaseHelper(platform, arch);');
+ expect(forgeSource).toContain("'xdt-macos-session-drag-release-helper'");
+ });
+});
+
+function createFakeChild(): FakeNativeProcess {
+ const child = new EventEmitter() as FakeNativeProcess;
+ child.stdin = new PassThrough();
+ child.stdout = new PassThrough();
+ child.stderr = new PassThrough();
+ let killed = false;
+ Object.defineProperty(child, 'killed', {
+ configurable: true,
+ get: () => killed,
+ });
+ child.kill = vi.fn(() => {
+ killed = true;
+ return true;
+ });
+ return child;
+}
diff --git a/apps/desktop/src/main/__tests__/windowBounds.test.ts b/apps/desktop/src/main/__tests__/windowBounds.test.ts
new file mode 100644
index 0000000000..48729aaaaa
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/windowBounds.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ isPointInWindowBounds,
+ isPointInsideAnyWindow,
+ resolveSessionDragPreviewBounds,
+ resolveWindowBoundsNearPoint,
+} from '../windowBounds';
+
+const bounds = { x: 10, y: 20, width: 100, height: 80 };
+
+describe('window bounds', () => {
+ it('uses a half-open rectangle', () => {
+ expect(isPointInWindowBounds({ x: 10, y: 20 }, bounds)).toBe(true);
+ expect(isPointInWindowBounds({ x: 109, y: 99 }, bounds)).toBe(true);
+ expect(isPointInWindowBounds({ x: 110, y: 99 }, bounds)).toBe(false);
+ expect(isPointInWindowBounds({ x: 109, y: 100 }, bounds)).toBe(false);
+ });
+
+ it('recognizes any app window as an in-app drop target', () => {
+ expect(
+ isPointInsideAnyWindow({ x: 250, y: 150 }, [
+ bounds,
+ { x: 200, y: 100, width: 80, height: 80 },
+ ]),
+ ).toBe(true);
+ expect(isPointInsideAnyWindow({ x: 500, y: 500 }, [bounds])).toBe(false);
+ });
+
+ it('places a detached task window with its title bar near the release point', () => {
+ expect(
+ resolveWindowBoundsNearPoint(
+ { x: 1800, y: 200 },
+ { width: 1200, height: 800 },
+ { x: 1440, y: 0, width: 1920, height: 1080 },
+ ),
+ ).toEqual({ x: 1720, y: 176, width: 1200, height: 800 });
+ });
+
+ it('clamps detached windows to the target display work area', () => {
+ expect(
+ resolveWindowBoundsNearPoint(
+ { x: 3300, y: 1000 },
+ { width: 1200, height: 800 },
+ { x: 1440, y: 0, width: 1920, height: 1080 },
+ ),
+ ).toEqual({ x: 2160, y: 280, width: 1200, height: 800 });
+ });
+
+ it('shrinks oversized detached windows to remain fully visible', () => {
+ expect(
+ resolveWindowBoundsNearPoint(
+ { x: -1200, y: 200 },
+ { width: 1600, height: 1000 },
+ { x: -1440, y: 0, width: 1440, height: 900 },
+ ),
+ ).toEqual({ x: -1440, y: 0, width: 1440, height: 900 });
+ });
+
+ it('places the transient drag preview below the cursor and clamps it to the display', () => {
+ expect(
+ resolveSessionDragPreviewBounds(
+ { x: 1800, y: 200 },
+ { x: 1440, y: 0, width: 1920, height: 1080 },
+ ),
+ ).toEqual({ x: 1808, y: 208, width: 320, height: 68 });
+ expect(
+ resolveSessionDragPreviewBounds(
+ { x: 3350, y: 1060 },
+ { x: 1440, y: 0, width: 1920, height: 1080 },
+ ),
+ ).toEqual({ x: 3040, y: 1012, width: 320, height: 68 });
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b1671ab2ee..5dfbb1724f 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -349,6 +349,7 @@ import {
} from './windowFocusClassifier.js';
import {
assertTrustedAppRendererEvent,
+ isTrustedAppRendererEvent,
isTrustedAppRendererWindow,
} from './security/trustedAppRenderer.js';
import { isMainShellWindowUrl } from './cindy-brain/scheduleSlot.js';
@@ -499,7 +500,7 @@ import {
withSendToSessionLock,
} from './maker-ipc/register.js';
import { cleanupActiveReviewArtifactSnapshots } from './reviewer/reviewArtifactSnapshot.js';
-import { MAKER_INVOKE as MAKER_IPC_INVOKE, MAKER_PUSH } from './maker-ipc/channels.js';
+import { MAKER_INVOKE as MAKER_IPC_INVOKE, MAKER_PUSH, MAKER_SEND } from './maker-ipc/channels.js';
import {
preserveLegacyMakerMemoryDisabled,
readMemorySettings,
@@ -606,7 +607,22 @@ import { registerFileBrowserDeviceOp } from './file-browser/device-op.js';
import { registerSearchIpc } from './file-browser/search/index.js';
import { registerVoiceInputIpc } from './voice-input/index.js';
import { installWindowHiddenBroadcast } from './windowHiddenBroadcast.js';
-import { isSecondaryAppWindow, openSessionInNewWindow } from './secondary-windows.js';
+import {
+ isSecondaryAppWindow,
+ openSessionInNewWindow,
+ openSessionInNewWindowIfDroppedOutside,
+} from './secondary-windows.js';
+import {
+ beginSessionDragPreview,
+ consumeNativeSessionDragOpenResult,
+ disposeSessionDragPreview,
+ endSessionDragPreview,
+ prewarmSessionDragReleaseHelper,
+} from './session-drag-preview.js';
+import {
+ parseSessionDragPreviewPalette,
+ truncateSessionDragPreviewLabel,
+} from './sessionDragPreviewHtml.js';
import {
isGlobalVoiceInputOverlayVisible,
registerGlobalVoiceInputIpc,
@@ -1031,6 +1047,7 @@ const safeStorageReadLog = createLogger('safe-storage:read');
const rendererConsoleLog = createLogger('renderer-console');
const updatePresentationLog = createLogger('update-presentation');
const voicePowerBroadcastLog = createLogger('voice-input-power');
+const sessionDragPreviewLog = createLogger('session-drag-preview');
let rendererBootGuard: RendererBootGuard | null = null;
const lifecycleDbClientManager = createLifecycleDbClientManager({
@@ -2933,6 +2950,19 @@ function syncDefaultPluginsForActiveOwner(): void {
});
}
+function parseOptionalDeviceLinkDeviceId(value: unknown): string | null | undefined {
+ if (value === undefined) return undefined;
+ if (value === null) return null;
+ const trimmed = typeof value === 'string' ? value.trim() : '';
+ if (trimmed.length === 0 || trimmed.length > 256 || value !== trimmed) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ 'deviceLinkDeviceId must be a non-empty, trimmed string of at most 256 characters or null',
+ );
+ }
+ return trimmed;
+}
+
const registerIpcHandlers = () => {
// Find the primary app window, skipping transient utility BrowserWindows like
// the voice-input overlay (minimizable:false, maximizable:false). Electron's
@@ -2993,11 +3023,94 @@ const registerIpcHandlers = () => {
});
// 「在新窗口打开」会话多开 —— 新建一个完整窗口定位到该 session, 初始 bounds 取主窗。
- ipcMain.handle(MAKER_IPC_INVOKE.OPEN_SESSION_IN_NEW_WINDOW, (_e, sessionId: unknown) => {
- if (typeof sessionId !== 'string' || sessionId.length === 0) {
- throwIpcError('INVALID_PARAMS', 'sessionId required');
+ ipcMain.handle(
+ MAKER_IPC_INVOKE.OPEN_SESSION_IN_NEW_WINDOW,
+ (event, sessionId: unknown, deviceIdRaw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'sessionId required');
+ }
+ const deviceId = parseOptionalDeviceLinkDeviceId(deviceIdRaw);
+ const sourceWindow = BrowserWindow.fromWebContents(event.sender);
+ openSessionInNewWindow(sessionId, sourceWindow ?? mainWindowRef, deviceId);
+ },
+ );
+
+ ipcMain.handle(
+ MAKER_IPC_INVOKE.OPEN_SESSION_IN_NEW_WINDOW_IF_DROPPED_OUTSIDE,
+ (event, sessionId: unknown, deviceIdRaw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'sessionId required');
+ }
+ const deviceId = parseOptionalDeviceLinkDeviceId(deviceIdRaw);
+ const sourceWindow = BrowserWindow.fromWebContents(event.sender);
+ // The renderer normally ends the preview immediately before invoking
+ // this check. Stop again here so a delayed dragend/IPC cannot leave the
+ // transient card visible after the drop has already been classified.
+ // Keep the owner check so a delayed IPC from one window cannot stop a
+ // newer drag that already started in another window.
+ if (sourceWindow) endSessionDragPreview(sourceWindow);
+ const nativeResult = sourceWindow
+ ? consumeNativeSessionDragOpenResult(sourceWindow, sessionId, deviceId)
+ : null;
+ if (nativeResult !== null) return nativeResult;
+ return openSessionInNewWindowIfDroppedOutside(
+ sessionId,
+ mainWindowRef,
+ sourceWindow,
+ deviceId,
+ );
+ },
+ );
+
+ ipcMain.handle(
+ MAKER_IPC_INVOKE.SESSION_DRAG_PREVIEW_START,
+ (event, labelRaw: unknown, sessionId: unknown, deviceIdRaw: unknown, paletteRaw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof labelRaw !== 'string' || typeof sessionId !== 'string' || sessionId.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'label and sessionId required');
+ }
+ const deviceId = parseOptionalDeviceLinkDeviceId(deviceIdRaw);
+ const palette = parseSessionDragPreviewPalette(paletteRaw);
+ if (!palette) {
+ throwIpcError('INVALID_PARAMS', 'invalid session drag preview palette');
+ }
+ const sourceWindow = BrowserWindow.fromWebContents(event.sender);
+ if (!sourceWindow || sourceWindow.isDestroyed()) return;
+ beginSessionDragPreview(
+ sourceWindow,
+ truncateSessionDragPreviewLabel(labelRaw),
+ sessionId,
+ deviceId,
+ palette,
+ );
+ },
+ );
+
+ ipcMain.on(MAKER_SEND.SESSION_DRAG_PREVIEW_END, (event, dragEndAtMsRaw: unknown) => {
+ // Fire-and-forget callers cannot receive an IPC error. Drop stale or
+ // untrusted senders instead of throwing through Electron's EventEmitter.
+ if (!isTrustedAppRendererEvent(event)) return;
+ const sourceWindow = BrowserWindow.fromWebContents(event.sender);
+ if (!sourceWindow || sourceWindow.isDestroyed()) return;
+ const receivedAtMs = Date.now();
+ endSessionDragPreview(sourceWindow);
+ if (!app.isPackaged) {
+ const dragEndAtMs =
+ typeof dragEndAtMsRaw === 'number' &&
+ Number.isFinite(dragEndAtMsRaw) &&
+ Math.abs(receivedAtMs - dragEndAtMsRaw) <= 60_000
+ ? dragEndAtMsRaw
+ : null;
+ sessionDragPreviewLog.info(
+ JSON.stringify({
+ event: 'sessionDragPreview.end.dispatched',
+ rendererToMainMs: dragEndAtMs === null ? null : Math.max(0, receivedAtMs - dragEndAtMs),
+ hideApiDispatchMs: Date.now() - receivedAtMs,
+ }),
+ );
}
- openSessionInNewWindow(sessionId, mainWindowRef);
});
// E4D 毛玻璃(R1 audit,用户裁决透壁纸 2026-07-17):仅 CINDY family 启用毛玻璃透壁纸;
@@ -6166,19 +6279,17 @@ async function runSmokeTest(
const metaCount = (
db.prepare('SELECT COUNT(*) AS c FROM migration_meta').get() as { c: number }
).c;
- const pluginStorageResult = pluginStorage
- ? await runPluginStorageSmoke(userId)
- : undefined;
+ const pluginStorageResult = pluginStorage ? await runPluginStorageSmoke(userId) : undefined;
const payload = {
- ok: true,
- schema_version: schemaVersion,
- tables: {
- sessions: sessionsCount,
- messages: messagesCount,
- migration_meta: metaCount,
- },
- ...(pluginStorageResult ? { plugin_storage: pluginStorageResult } : {}),
- };
+ ok: true,
+ schema_version: schemaVersion,
+ tables: {
+ sessions: sessionsCount,
+ messages: messagesCount,
+ migration_meta: metaCount,
+ },
+ ...(pluginStorageResult ? { plugin_storage: pluginStorageResult } : {}),
+ };
const serialized = `${JSON.stringify(payload)}\n`;
if (resultFile) fs.writeFileSync(resultFile, serialized, { mode: 0o600 });
process.stdout.write(serialized);
@@ -6520,6 +6631,19 @@ app.on('ready', async () => {
});
return;
}
+ if (dbClientTakeover.mode === 'unchanged') {
+ // 副窗口会再次走 localDb.ensureReady;同 owner 的 lifecycle client 已由首个
+ // onReady 完整启动,因此这里只保留 DB 连接交接,不重复执行账号级启动维护。
+ // worker takeover 会让 ensureReady 为本次副窗口重新打开 main DB,交接完成后立即
+ // 释放该短暂连接,避免它长期占用文件句柄和 optimize 定时器。
+ if (dbClientTakeover.shouldReleaseMainDb && process.env.XDT_DB_INPROC !== 'true') {
+ localDbCloseDb({ preserveSchemaMigrationLease: true });
+ dbClientLog.info('[DbClient] duplicate owner ensure released reopened main db', {
+ userId,
+ });
+ }
+ return;
+ }
// Phase 1.1: file worker 接管 DB 连接后,释放 main 端的 _db + optimize 定时器。
// 如果 worker takeover 失败并进入 inproc fallback,main _db 必须继续保留,
// 否则 fallback 会拿到已关闭的连接。
@@ -6812,6 +6936,10 @@ app.on('ready', async () => {
initLogUploadService();
startupWindowCreationAllowed = true;
createWindow();
+ // The macOS release watcher stays disarmed until a task drag begins. Start
+ // its tiny helper after the first window exists so drag latency never pays
+ // a dev swiftc compile or process-spawn cost.
+ prewarmSessionDragReleaseHelper();
// 预热仅服务 dev macOS,延迟执行避免和启动关键路径争用 CPU;失败由入口内部吞掉。
setTimeout(() => {
prewarmMacComputerPermissionGuideHelper();
@@ -6931,6 +7059,7 @@ onQuit(
);
onQuit('auth-manager', () => authManager.dispose(), 'sync');
onQuit('app-badge-clear', () => clearAllSessionAttention(), 'sync');
+onQuit('session-drag-preview', () => disposeSessionDragPreview(), 'sync');
// 自带 adb 的常驻 server 守护进程随退出收掉(fire-and-forget detached spawn,
// 不阻塞)。不收会一直锁安装目录里的 adb.exe,弄挂增量更新(os error 32)。
onQuit('android-adb-kill-server', () => disposeAndroidAdb(), 'sync');
diff --git a/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts b/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts
index f7f58adaf1..bc8dd96bba 100644
--- a/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts
@@ -15,11 +15,21 @@ describe('shared-passive schema lease worker takeover wiring', () => {
path.resolve(__dirname, '..', '..', 'bootstrap-electron.ts'),
'utf8',
);
- const takeoverStart = bootstrap.indexOf('if (dbClientTakeover.shouldReleaseMainDb');
+ const unchangedGuard = bootstrap.indexOf("dbClientTakeover.mode === 'unchanged'");
+ const attachmentSweep = bootstrap.indexOf('sweepStagedChatAttachmentsOnStartup({');
+ const takeoverStart = bootstrap.indexOf(
+ 'if (dbClientTakeover.shouldReleaseMainDb',
+ attachmentSweep,
+ );
const takeoverEnd = bootstrap.indexOf('custom-mcp-account-switch', takeoverStart);
- expect(bootstrap.slice(takeoverStart, takeoverEnd)).toContain(
+ const takeoverBlock = bootstrap.slice(takeoverStart, takeoverEnd);
+ expect(unchangedGuard).toBeGreaterThanOrEqual(0);
+ expect(attachmentSweep).toBeGreaterThan(unchangedGuard);
+ expect(takeoverStart).toBeGreaterThan(attachmentSweep);
+ expect(takeoverBlock).toContain(
'localDbCloseDb({ preserveSchemaMigrationLease: true })',
);
+ expect(bootstrap.slice(unchangedGuard, attachmentSweep)).toContain('return;');
});
it('preserves the real lease across takeover close and releases it on logout/quit close', () => {
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 236dd6d4b9..3d85ab969d 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -650,6 +650,11 @@ export const MAKER_INVOKE = {
* 自动同步。窗口生命周期见 main/secondary-windows.ts。
*/
OPEN_SESSION_IN_NEW_WINDOW: 'maker:open-session-in-new-window',
+ /** Native task drag released outside every Cindy app window. */
+ OPEN_SESSION_IN_NEW_WINDOW_IF_DROPPED_OUTSIDE:
+ 'maker:open-session-in-new-window-if-dropped-outside',
+ /** Start the transient task drag preview shown outside Cindy windows. */
+ SESSION_DRAG_PREVIEW_START: 'maker:session-drag-preview:start',
/**
* 右侧栏独立子窗口(RSB window)——「侧边栏在新窗口中显示」全局偏好 + 窗口生命周期。
* 状态机 / 窗口管理见 main/right-sidebar-window/controller.ts。
@@ -702,6 +707,11 @@ export const MAKER_INVOKE = {
* (typically localStorage 镜像) 推给 main, main 只更新内存缓存供后续工具调用读。
*/
export const MAKER_SEND = {
+ /**
+ * Stop the transient task drag preview. Release feedback is latency-sensitive
+ * and has no response payload, so it must not pay an invoke/ack round trip.
+ */
+ SESSION_DRAG_PREVIEW_END: 'maker:session-drag-preview:end',
/**
* macOS permission coach: begin a native drag of the real Computer Use app
* bundle into System Settings. Main validates that the sender is the
diff --git a/apps/desktop/src/main/secondary-windows.ts b/apps/desktop/src/main/secondary-windows.ts
index 3716f8aed8..749f7a7a4b 100644
--- a/apps/desktop/src/main/secondary-windows.ts
+++ b/apps/desktop/src/main/secondary-windows.ts
@@ -15,13 +15,18 @@
* `?secondaryWindow=1`,renderer 据此默认折叠侧栏 + 关闭走"只关本窗"语义。
*/
-import { BrowserWindow, app, nativeTheme, shell } from 'electron';
+import { BrowserWindow, app, nativeTheme, screen, shell } from 'electron';
import path from 'node:path';
import { BRAND_NAME } from '@cindy/maker-shared/branding';
import { createLogger } from './logger.js';
import { installNewMakerWindowShortcut } from './app-shortcuts/new-maker-window-shortcut.js';
-import { markAppContentWindow } from './windowFocusClassifier.js';
+import { isAppContentWindow, markAppContentWindow } from './windowFocusClassifier.js';
+import {
+ isPointInsideAnyWindow,
+ resolveWindowBoundsNearPoint,
+ type ScreenPoint,
+} from './windowBounds.js';
import { readWindowBehaviorSettings } from './window-behavior-settings-store.js';
import { resolveVibrancyConfig, type WindowsBackdropMaterial } from './vibrancyConfig.js';
import { installSelectionContextMenu } from './selection-context-menu.js';
@@ -80,7 +85,13 @@ export function installExternalLinkGuards(win: BrowserWindow): void {
* 新开一个完整应用窗口并定位到指定 session。
* @param mainWindow 主窗口,用来取当前 bounds 作为新窗初始大小(右下错开);可为 null。
*/
-export function openSessionInNewWindow(sessionId: string, mainWindow: BrowserWindow | null): void {
+export function openSessionInNewWindow(
+ sessionId: string,
+ mainWindow: BrowserWindow | null,
+ deviceId?: string | null,
+ anchorPoint?: ScreenPoint,
+): void {
+ const createdAt = performance.now();
// frame 配置复刻主窗(bootstrap-electron.ts createWindow): Mac 隐藏标题栏留红绿灯,
// Windows 无边框 + 自绘标题栏。
const platformOptions =
@@ -90,9 +101,18 @@ export function openSessionInNewWindow(sessionId: string, mainWindow: BrowserWin
const bgColor = nativeTheme.shouldUseDarkColors ? '#1f1f1e' : '#f8f8f6';
const base = mainWindow && !mainWindow.isDestroyed() ? mainWindow.getBounds() : null;
- const bounds = base
- ? { x: base.x + OFFSET_PX, y: base.y + OFFSET_PX, width: base.width, height: base.height }
+ const requestedSize = base
+ ? { width: base.width, height: base.height }
: { width: 1280, height: 800 };
+ const bounds = anchorPoint
+ ? resolveWindowBoundsNearPoint(
+ anchorPoint,
+ requestedSize,
+ screen.getDisplayNearestPoint(anchorPoint).workArea,
+ )
+ : base
+ ? { x: base.x + OFFSET_PX, y: base.y + OFFSET_PX, ...requestedSize }
+ : requestedSize;
// 副窗同样读一次 window-behavior 设置,和主窗保持 acceptFirstMouse 一致——否则
// macOS 上用户关掉开关重启后, 主窗一次点击透传但副窗仍被 Electron 默认 false
@@ -115,6 +135,9 @@ export function openSessionInNewWindow(sessionId: string, mainWindow: BrowserWin
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
spellcheck: false,
+ // A task drag that misses a renderer drop target must never navigate the
+ // application window to the dragged plain-text fallback.
+ navigateOnDragDrop: false,
},
});
markAppContentWindow(win);
@@ -133,13 +156,28 @@ export function openSessionInNewWindow(sessionId: string, mainWindow: BrowserWin
installExternalLinkGuards(win);
- win.once('ready-to-show', () => {
- if (!win.isDestroyed()) win.show();
- });
+ let shown = false;
+ const showWindow = (trigger: 'did-finish-load' | 'ready-to-show'): void => {
+ if (shown || win.isDestroyed()) return;
+ shown = true;
+ win.show();
+ log.info('secondary window visible', {
+ sessionId,
+ trigger,
+ elapsedMs: Math.round(performance.now() - createdAt),
+ });
+ };
+ // The boot gate intentionally resolves the session route after the document
+ // loads. Showing at did-finish-load lets the user see that the new window
+ // was created while that async route/database work continues; ready-to-show
+ // remains a fallback for platforms that do not emit the load event first.
+ win.webContents.once('did-finish-load', () => showWindow('did-finish-load'));
+ win.once('ready-to-show', () => showWindow('ready-to-show'));
// 副窗启动参数:
// ?secondaryWindow=1 —— renderer 据此默认折叠侧栏 + 关闭只关本窗
// ?bootSession=<id> —— 要定位到的 sessionId
+ // ?bootDevice=<id> —— device-link 远程任务的归属设备(可选)
// hash 固定落到中性的 /cc-agent/boot 网关路由(SecondaryWindowBootGate):由它
// 在 renderer 侧调 resolveSessionRoute 解析出 canonical route(普通 / Orca lead /
// worker)再 navigate。main 端**不**写死 /cc-agent/<id> —— 否则 Orca lead/worker
@@ -149,11 +187,16 @@ export function openSessionInNewWindow(sessionId: string, mainWindow: BrowserWin
const url = new URL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
url.searchParams.set('secondaryWindow', '1');
url.searchParams.set('bootSession', sessionId);
+ if (deviceId) url.searchParams.set('bootDevice', deviceId);
url.hash = hash;
void win.loadURL(url.toString());
} else {
void win.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`), {
- query: { secondaryWindow: '1', bootSession: sessionId },
+ query: {
+ secondaryWindow: '1',
+ bootSession: sessionId,
+ ...(deviceId ? { bootDevice: deviceId } : {}),
+ },
hash,
});
}
@@ -161,6 +204,27 @@ export function openSessionInNewWindow(sessionId: string, mainWindow: BrowserWin
log.info('opened session in new window', { sessionId });
}
+/**
+ * Open a task only when the native drag ended outside every Cindy app window.
+ * The cursor is queried in main so renderer coordinates cannot drift across
+ * displays or browser zoom, and existing Cindy windows remain valid targets.
+ */
+export function openSessionInNewWindowIfDroppedOutside(
+ sessionId: string,
+ mainWindow: BrowserWindow | null,
+ sourceWindow: BrowserWindow | null,
+ deviceId?: string | null,
+): boolean {
+ const point = screen.getCursorScreenPoint();
+ const appWindowBounds = BrowserWindow.getAllWindows()
+ .filter((win) => isAppContentWindow(win) && win.isVisible() && !win.isMinimized())
+ .map((win) => win.getBounds());
+ if (isPointInsideAnyWindow(point, appWindowBounds)) return false;
+
+ openSessionInNewWindow(sessionId, sourceWindow ?? mainWindow, deviceId, point);
+ return true;
+}
+
// E4D 毛玻璃(lead 裁决副窗同处理):遍历副窗 set,用同 resolveVibrancyConfig 映射
/**
* 是不是本模块开出来的会话副窗口。
diff --git a/apps/desktop/src/main/session-drag-preview.ts b/apps/desktop/src/main/session-drag-preview.ts
new file mode 100644
index 0000000000..3ea1f31895
--- /dev/null
+++ b/apps/desktop/src/main/session-drag-preview.ts
@@ -0,0 +1,136 @@
+import { BrowserWindow, screen } from 'electron';
+
+import type { SessionDragPreviewPalette } from '../shared/sessionDragPreview.js';
+import { isAppContentWindow } from './windowFocusClassifier.js';
+import { openSessionInNewWindowIfDroppedOutside } from './secondary-windows.js';
+import { buildSessionDragPreviewHtml } from './sessionDragPreviewHtml.js';
+import { createLogger } from './logger.js';
+import { SessionDragNativeOpenCoordinator } from './sessionDragNativeOpenCoordinator.js';
+import { SessionDragReleaseNativeHost } from './sessionDragReleaseNativeHost.js';
+import { SessionDragPreviewController } from './sessionDragPreviewController.js';
+
+const PREVIEW_WIDTH = 320;
+const PREVIEW_HEIGHT = 68;
+const log = createLogger('session-drag-preview/window');
+
+function createSessionDragPreviewWindow(label: string, palette: SessionDragPreviewPalette) {
+ const preview = new BrowserWindow({
+ width: PREVIEW_WIDTH,
+ height: PREVIEW_HEIGHT,
+ show: false,
+ frame: false,
+ transparent: true,
+ resizable: false,
+ movable: false,
+ minimizable: false,
+ maximizable: false,
+ closable: false,
+ focusable: false,
+ hasShadow: false,
+ skipTaskbar: process.platform !== 'darwin',
+ backgroundColor: '#00000000',
+ webPreferences: {
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ },
+ });
+ preview.setIgnoreMouseEvents(true, { forward: true });
+ preview.setAlwaysOnTop(true, 'floating', 1);
+
+ let resolveReady: () => void = () => undefined;
+ const ready = new Promise<void>((resolve) => {
+ resolveReady = resolve;
+ });
+ preview.webContents.once('did-finish-load', resolveReady);
+ preview.once('closed', resolveReady);
+ void preview
+ .loadURL(
+ `data:text/html;charset=utf-8,${encodeURIComponent(
+ buildSessionDragPreviewHtml(label, palette),
+ )}`,
+ )
+ .catch((error: unknown) => {
+ log.warn('session drag preview failed to load', {
+ errorName: error instanceof Error ? error.name : typeof error,
+ });
+ resolveReady();
+ });
+
+ return {
+ ready,
+ isDestroyed: () => preview.isDestroyed(),
+ setPosition: (x: number, y: number, animate?: boolean) => preview.setPosition(x, y, animate),
+ setOpacity: (opacity: number) => preview.setOpacity(opacity),
+ showInactive: () => preview.showInactive(),
+ hide: () => preview.hide(),
+ close: () => preview.close(),
+ };
+}
+
+let nativeReleaseHost: SessionDragReleaseNativeHost | null = null;
+const nativeOpenCoordinator = new SessionDragNativeOpenCoordinator<BrowserWindow>();
+const controller = new SessionDragPreviewController({
+ screen,
+ getAppWindowBounds: () =>
+ BrowserWindow.getAllWindows()
+ .filter((win) => isAppContentWindow(win) && win.isVisible() && !win.isMinimized())
+ .map((win) => win.getBounds()),
+ createPreviewWindow: createSessionDragPreviewWindow,
+ onStopped: (token) => {
+ nativeOpenCoordinator.stop(token);
+ nativeReleaseHost?.disarm();
+ },
+});
+nativeReleaseHost = new SessionDragReleaseNativeHost({
+ onMouseUp: (token) => {
+ nativeOpenCoordinator.handleNativeRelease(
+ token,
+ () => controller.endByToken(token),
+ ({ owner, sessionId, deviceId }) =>
+ openSessionInNewWindowIfDroppedOutside(sessionId, owner, owner, deviceId),
+ );
+ },
+});
+
+export function beginSessionDragPreview(
+ sourceWindow: BrowserWindow,
+ label: string,
+ sessionId: string,
+ deviceId: string | null | undefined,
+ palette: SessionDragPreviewPalette,
+): void {
+ const token = controller.begin(sourceWindow, label, palette);
+ if (token !== null) {
+ nativeOpenCoordinator.begin(token, sourceWindow, sessionId, deviceId);
+ void nativeReleaseHost?.arm(token);
+ }
+}
+
+export function endSessionDragPreview(sourceWindow: BrowserWindow): void {
+ controller.end(sourceWindow);
+}
+
+export function consumeNativeSessionDragOpenResult(
+ sourceWindow: BrowserWindow,
+ sessionId: string,
+ deviceId?: string | null,
+): boolean | null {
+ return nativeOpenCoordinator.consumeNativeResult(sourceWindow, sessionId, deviceId);
+}
+
+export function prewarmSessionDragReleaseHelper(): void {
+ void nativeReleaseHost?.prewarm();
+}
+
+export function disposeSessionDragPreview(): void {
+ controller.end();
+ nativeReleaseHost?.dispose();
+}
diff --git a/apps/desktop/src/main/sessionDragNativeOpenCoordinator.ts b/apps/desktop/src/main/sessionDragNativeOpenCoordinator.ts
new file mode 100644
index 0000000000..0dd4979e3f
--- /dev/null
+++ b/apps/desktop/src/main/sessionDragNativeOpenCoordinator.ts
@@ -0,0 +1,85 @@
+export interface SessionDragNativeOpenIntent<Owner extends object> {
+ owner: Owner;
+ sessionId: string;
+ deviceId: string | null;
+}
+
+interface NativeOpenResult {
+ sessionId: string;
+ deviceId: string | null;
+ opened: boolean;
+ expiresAt: number;
+}
+
+export interface SessionDragNativeOpenCoordinatorOptions {
+ now?: () => number;
+ resultTtlMs?: number;
+}
+
+const DEFAULT_RESULT_TTL_MS = 5_000;
+
+/**
+ * Coordinates the macOS mouse-up fast path with Chromium's later dragend.
+ *
+ * The native path owns the first outside-window classification. Its result is
+ * consumed once by the renderer fallback so the same gesture cannot open two
+ * windows. Starting another drag invalidates any result left by the previous
+ * gesture from that source window.
+ */
+export class SessionDragNativeOpenCoordinator<Owner extends object> {
+ private readonly intents = new Map<number, SessionDragNativeOpenIntent<Owner>>();
+ private readonly results = new WeakMap<Owner, NativeOpenResult>();
+ private readonly now: () => number;
+ private readonly resultTtlMs: number;
+
+ constructor(options: SessionDragNativeOpenCoordinatorOptions = {}) {
+ this.now = options.now ?? Date.now;
+ this.resultTtlMs = options.resultTtlMs ?? DEFAULT_RESULT_TTL_MS;
+ }
+
+ begin(token: number, owner: Owner, sessionId: string, deviceId?: string | null): void {
+ this.results.delete(owner);
+ this.intents.set(token, {
+ owner,
+ sessionId,
+ deviceId: deviceId ?? null,
+ });
+ }
+
+ stop(token: number): void {
+ this.intents.delete(token);
+ }
+
+ handleNativeRelease(
+ token: number,
+ beforeOpen: () => void,
+ openIfOutside: (intent: SessionDragNativeOpenIntent<Owner>) => boolean,
+ ): boolean | null {
+ const intent = this.intents.get(token);
+ if (!intent) return null;
+ this.intents.delete(token);
+ beforeOpen();
+ const opened = openIfOutside(intent);
+ this.results.set(intent.owner, {
+ sessionId: intent.sessionId,
+ deviceId: intent.deviceId,
+ opened,
+ expiresAt: this.now() + this.resultTtlMs,
+ });
+ return opened;
+ }
+
+ consumeNativeResult(owner: Owner, sessionId: string, deviceId?: string | null): boolean | null {
+ const result = this.results.get(owner);
+ if (!result) return null;
+ this.results.delete(owner);
+ if (
+ result.expiresAt < this.now() ||
+ result.sessionId !== sessionId ||
+ result.deviceId !== (deviceId ?? null)
+ ) {
+ return null;
+ }
+ return result.opened;
+ }
+}
diff --git a/apps/desktop/src/main/sessionDragPreviewController.ts b/apps/desktop/src/main/sessionDragPreviewController.ts
new file mode 100644
index 0000000000..d54960e191
--- /dev/null
+++ b/apps/desktop/src/main/sessionDragPreviewController.ts
@@ -0,0 +1,175 @@
+import {
+ isPointInsideAnyWindow,
+ resolveSessionDragPreviewBounds,
+ type ScreenPoint,
+ type WindowBounds,
+} from './windowBounds.js';
+import type { SessionDragPreviewPalette } from '../shared/sessionDragPreview.js';
+
+export interface SessionDragPreviewScreenLike {
+ getCursorScreenPoint(): ScreenPoint;
+ getDisplayNearestPoint(point: ScreenPoint): { workArea: WindowBounds };
+}
+
+export interface SessionDragPreviewWindowLike {
+ readonly ready: Promise<void>;
+ isDestroyed(): boolean;
+ setPosition(x: number, y: number, animate?: boolean): void;
+ setOpacity(opacity: number): void;
+ showInactive(): void;
+ hide(): void;
+ close(): void;
+}
+
+export interface SessionDragPreviewControllerDeps {
+ screen: SessionDragPreviewScreenLike;
+ getAppWindowBounds: () => readonly WindowBounds[];
+ createPreviewWindow: (
+ label: string,
+ palette: SessionDragPreviewPalette,
+ ) => SessionDragPreviewWindowLike;
+ onStopped?: (token: number) => void;
+ intervalMs?: number;
+ maxDurationMs?: number;
+}
+
+interface ActiveSessionDrag {
+ owner: object;
+ token: number;
+ label: string;
+ startedAt: number;
+ preview: SessionDragPreviewWindowLike | null;
+ previewReady: boolean;
+ previewVisible: boolean;
+ isOutside: boolean;
+ timer: ReturnType<typeof setInterval> | null;
+}
+
+const DEFAULT_INTERVAL_MS = 16;
+const DEFAULT_MAX_DURATION_MS = 30_000;
+
+/**
+ * Drives the short-lived native preview shown only outside Cindy windows.
+ *
+ * The HTML5 drag image is transparent, so this controller owns the visible
+ * preview and can hide it while the cursor is over any Cindy app window. Main
+ * reads screen coordinates to keep the preview correct across displays and
+ * renderer zoom levels.
+ */
+export class SessionDragPreviewController {
+ private active: ActiveSessionDrag | null = null;
+ private nextToken = 1;
+
+ constructor(private readonly deps: SessionDragPreviewControllerDeps) {}
+
+ begin(owner: object, labelInput: string, palette: SessionDragPreviewPalette): number | null {
+ if (this.active?.owner && this.active.owner !== owner) return null;
+ this.stop();
+
+ const active: ActiveSessionDrag = {
+ owner,
+ token: this.nextToken++,
+ label: labelInput,
+ startedAt: Date.now(),
+ preview: null,
+ previewReady: false,
+ previewVisible: false,
+ isOutside: false,
+ timer: null,
+ };
+ this.active = active;
+ this.preparePreview(active, palette);
+ this.tick(active);
+ active.timer = setInterval(
+ () => this.tick(active),
+ this.deps.intervalMs ?? DEFAULT_INTERVAL_MS,
+ );
+ return active.token;
+ }
+
+ end(owner?: object): boolean {
+ if (owner !== undefined && this.active?.owner !== owner) return false;
+ return this.stop();
+ }
+
+ isActive(): boolean {
+ return this.active !== null;
+ }
+
+ endByToken(token: number): boolean {
+ if (this.active?.token !== token) return false;
+ return this.stop(this.active.owner);
+ }
+
+ private preparePreview(active: ActiveSessionDrag, palette: SessionDragPreviewPalette): void {
+ const preview = this.deps.createPreviewWindow(active.label, palette);
+ active.preview = preview;
+ void preview.ready.then(() => {
+ if (this.active !== active || preview.isDestroyed()) return;
+ active.previewReady = true;
+ if (active.isOutside && !active.previewVisible) {
+ preview.showInactive();
+ active.previewVisible = true;
+ }
+ });
+ }
+
+ private tick(active: ActiveSessionDrag): void {
+ if (this.active !== active) return;
+ if (Date.now() - active.startedAt > (this.deps.maxDurationMs ?? DEFAULT_MAX_DURATION_MS)) {
+ this.stop(active.owner);
+ return;
+ }
+
+ const point = this.deps.screen.getCursorScreenPoint();
+ active.isOutside = !isPointInsideAnyWindow(point, this.deps.getAppWindowBounds());
+
+ if (!active.isOutside) {
+ if (active.preview && active.previewVisible && !active.preview.isDestroyed()) {
+ active.preview.hide();
+ active.previewVisible = false;
+ }
+ return;
+ }
+
+ const preview = active.preview;
+ if (!preview || preview.isDestroyed()) {
+ this.stop(active.owner);
+ return;
+ }
+
+ const workArea = this.deps.screen.getDisplayNearestPoint(point).workArea;
+ const bounds = resolveSessionDragPreviewBounds(point, workArea);
+ preview.setPosition(bounds.x, bounds.y, false);
+ if (active.previewReady && !active.previewVisible) {
+ preview.showInactive();
+ active.previewVisible = true;
+ }
+ }
+
+ private stop(owner?: object): boolean {
+ if (owner !== undefined && this.active?.owner !== owner) return false;
+ const active = this.active;
+ this.active = null;
+ if (!active) return false;
+ this.deps.onStopped?.(active.token);
+ if (active.timer) clearInterval(active.timer);
+ const preview = active.preview;
+ if (preview && !preview.isDestroyed()) {
+ // Hide synchronously on release. BrowserWindow.close() can spend a
+ // noticeable amount of time in native window teardown, so do not make
+ // the visible drag-end path wait for it.
+ preview.hide();
+ setTimeout(() => {
+ // A test double or future window implementation may reuse the same
+ // BrowserWindow for a new drag; never tear down that new preview.
+ if (this.active?.preview === preview || preview.isDestroyed()) return;
+ // Opacity zero is a second guard for a delayed native close after the
+ // synchronous hide call has already returned.
+ preview.setOpacity(0);
+ preview.close();
+ }, 0);
+ }
+ return true;
+ }
+}
diff --git a/apps/desktop/src/main/sessionDragPreviewHtml.ts b/apps/desktop/src/main/sessionDragPreviewHtml.ts
new file mode 100644
index 0000000000..cc63acecb5
--- /dev/null
+++ b/apps/desktop/src/main/sessionDragPreviewHtml.ts
@@ -0,0 +1,59 @@
+import type { SessionDragPreviewPalette } from '../shared/sessionDragPreview.js';
+import { parseCssColor } from '../shared/theme-import/color.js';
+
+const MAX_COLOR_LENGTH = 128;
+const UNSAFE_STYLE_CHARACTERS = /[\u0000-\u001f\u007f&"'<>;*\\]/;
+const SUPPORTED_COLOR_LITERAL = /^(?:#?[0-9a-f]{3,8}|(?:rgba?|hsla?)\([0-9a-z+.,%/\s-]+\))$/i;
+
+export function truncateSessionDragPreviewLabel(value: string, maxCodePoints = 160): string {
+ return Array.from(value).slice(0, maxCodePoints).join('');
+}
+
+function parsePaletteColor(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim();
+ if (
+ trimmed.length === 0 ||
+ trimmed.length > MAX_COLOR_LENGTH ||
+ UNSAFE_STYLE_CHARACTERS.test(trimmed) ||
+ !SUPPORTED_COLOR_LITERAL.test(trimmed) ||
+ parseCssColor(trimmed) === null
+ ) {
+ return null;
+ }
+ return trimmed;
+}
+
+export function parseSessionDragPreviewPalette(input: unknown): SessionDragPreviewPalette | null {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
+ const record = input as Record<string, unknown>;
+ const surface = parsePaletteColor(record.surface);
+ const border = parsePaletteColor(record.border);
+ const text = parsePaletteColor(record.text);
+ return surface && border && text ? { surface, border, text } : null;
+}
+
+function escapeHtml(value: string): string {
+ return value.replace(
+ /[&<>'"]/g,
+ (character) =>
+ ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ "'": '&#39;',
+ '"': '&quot;',
+ })[character] ?? character,
+ );
+}
+
+export function buildSessionDragPreviewHtml(
+ labelInput: string,
+ paletteInput: SessionDragPreviewPalette,
+): string {
+ const label = escapeHtml(labelInput.trim());
+ const palette = parseSessionDragPreviewPalette(paletteInput);
+ if (!palette) throw new TypeError('Invalid session drag preview palette');
+ const openWindowIcon = `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true" style="display:block"><path d="M15 3h6v6M21 3l-9 9M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
+ return `<!doctype html><html><body style="margin:0;width:100vw;height:100vh;background:transparent;overflow:hidden;-webkit-font-smoothing:antialiased"><div style="box-sizing:border-box;display:flex;align-items:center;gap:9px;position:absolute;inset:8px;overflow:hidden;border:1px solid ${palette.border};border-radius:13px;background:${palette.surface};padding:0 12px 0 9px;color:${palette.text};font-family:Inter,system-ui,-apple-system,'Segoe UI',sans-serif;font-size:13px;font-weight:500;line-height:1.3"><span style="box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;width:28px;height:28px;color:${palette.text}">${openWindowIcon}</span><span style="min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${label}</span></div></body></html>`;
+}
diff --git a/apps/desktop/src/main/sessionDragReleaseNativeHost.ts b/apps/desktop/src/main/sessionDragReleaseNativeHost.ts
new file mode 100644
index 0000000000..2acfabec3d
--- /dev/null
+++ b/apps/desktop/src/main/sessionDragReleaseNativeHost.ts
@@ -0,0 +1,239 @@
+import { execFile, spawn, type ChildProcessByStdio } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import { app } from 'electron';
+import type { Readable, Writable } from 'node:stream';
+
+import { createLogger } from './logger.js';
+
+const log = createLogger('session-drag-release/native');
+const HELPER_RESOURCE = path.join(
+ 'tools',
+ 'session-drag-release',
+ 'xdt-macos-session-drag-release-helper',
+);
+const HELPER_SOURCE_RELATIVE = path.join(
+ 'native',
+ 'session-drag-release',
+ 'macos-session-drag-release-helper.swift',
+);
+const HELPER_START_TIMEOUT_MS = 1_500;
+const HELPER_BUILD_TIMEOUT_MS = 15_000;
+const DEV_BINARY_NAME = 'xdt-macos-session-drag-release-helper';
+const DEV_BINARY_DIR = 'session-drag-release';
+
+type NativeProcess = ChildProcessByStdio<Writable, Readable, Readable>;
+
+export interface SessionDragReleaseNativeHostOptions {
+ onMouseUp: (token: number) => void;
+}
+
+interface NativePayload {
+ type?: unknown;
+ token?: unknown;
+}
+
+export class SessionDragReleaseNativeHost {
+ private child: NativeProcess | null = null;
+ private stdoutBuffer = '';
+ private ready = false;
+ private starting: Promise<boolean> | null = null;
+ private desiredToken: number | null = null;
+ private disposed = false;
+
+ constructor(private readonly options: SessionDragReleaseNativeHostOptions) {}
+
+ async arm(token: number): Promise<boolean> {
+ if (process.platform !== 'darwin' || this.disposed) return false;
+ this.desiredToken = token;
+ if (!(await this.ensureStarted()) || !this.child || !this.ready) return false;
+ if (this.desiredToken !== token) return false;
+ return this.writeCommand({ type: 'arm', token });
+ }
+
+ disarm(): void {
+ if (process.platform !== 'darwin') return;
+ this.desiredToken = null;
+ if (this.ready && this.child) this.writeCommand({ type: 'disarm' });
+ }
+
+ async prewarm(): Promise<boolean> {
+ if (process.platform !== 'darwin' || this.disposed) return false;
+ return this.ensureStarted();
+ }
+
+ dispose(): void {
+ this.disposed = true;
+ this.desiredToken = null;
+ const child = this.child;
+ this.child = null;
+ this.ready = false;
+ if (child && !child.killed) child.kill();
+ }
+
+ private ensureStarted(): Promise<boolean> {
+ if (this.ready && this.child && !this.child.killed) return Promise.resolve(true);
+ if (this.starting) return this.starting;
+ this.starting = this.start().finally(() => {
+ this.starting = null;
+ });
+ return this.starting;
+ }
+
+ private async start(): Promise<boolean> {
+ let binary: string;
+ try {
+ binary = await resolveHelperBinary();
+ } catch (error) {
+ log.warn('session drag release helper could not be prepared', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return false;
+ }
+ if (this.disposed) return false;
+
+ return new Promise<boolean>((resolve) => {
+ let settled = false;
+ const child = spawn(binary, [], { stdio: ['pipe', 'pipe', 'pipe'] });
+ this.child = child;
+ this.ready = false;
+ this.stdoutBuffer = '';
+ const timer = setTimeout(() => {
+ settle(false);
+ if (this.child === child) this.child = null;
+ if (!child.killed) child.kill();
+ }, HELPER_START_TIMEOUT_MS);
+ const settle = (ok: boolean): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(ok);
+ };
+
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk: string) => {
+ this.stdoutBuffer += chunk;
+ let newline = this.stdoutBuffer.indexOf('\n');
+ while (newline >= 0) {
+ const line = this.stdoutBuffer.slice(0, newline).trim();
+ this.stdoutBuffer = this.stdoutBuffer.slice(newline + 1);
+ if (line) this.handlePayload(line, child, settle);
+ newline = this.stdoutBuffer.indexOf('\n');
+ }
+ });
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk: string) => {
+ const text = chunk.trim();
+ if (text) log.debug('session drag release helper stderr', { text });
+ });
+ child.stdin.on('error', (error) => {
+ log.debug('session drag release helper stdin closed', { error: error.message });
+ });
+ child.on('error', (error) => {
+ log.warn('session drag release helper process error', { error: error.message });
+ if (this.child === child) {
+ this.child = null;
+ this.ready = false;
+ }
+ settle(false);
+ });
+ child.on('exit', (code, signal) => {
+ if (this.child === child) {
+ this.child = null;
+ this.ready = false;
+ }
+ settle(false);
+ log.debug('session drag release helper exited', { code, signal });
+ });
+ });
+ }
+
+ private handlePayload(line: string, child: NativeProcess, settle: (ok: boolean) => void): void {
+ let payload: NativePayload;
+ try {
+ payload = JSON.parse(line) as NativePayload;
+ } catch {
+ return;
+ }
+ if (payload.type === 'ready' && this.child === child) {
+ this.ready = true;
+ settle(true);
+ return;
+ }
+ if (payload.type === 'mouse-up' && typeof payload.token === 'number') {
+ if (this.desiredToken !== payload.token) return;
+ this.desiredToken = null;
+ this.options.onMouseUp(payload.token);
+ return;
+ }
+ if (payload.type === 'unavailable') {
+ log.warn('session drag release helper could not install an event monitor');
+ }
+ }
+
+ private writeCommand(command: { type: string; token?: number }): boolean {
+ const line = `${JSON.stringify(command)}\n`;
+ if (!this.child || !this.ready) return false;
+ try {
+ this.child.stdin.write(line);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+}
+
+let helperBinaryPromise: Promise<string> | null = null;
+
+async function resolveHelperBinary(): Promise<string> {
+ if (app.isPackaged) return path.join(process.resourcesPath, HELPER_RESOURCE);
+ if (!helperBinaryPromise) {
+ helperBinaryPromise = buildDevHelperBinary().finally(() => {
+ helperBinaryPromise = null;
+ });
+ }
+ return helperBinaryPromise;
+}
+
+async function buildDevHelperBinary(): Promise<string> {
+ const source = resolveDevHelperSource();
+ const binary = path.join(app.getPath('userData'), DEV_BINARY_DIR, DEV_BINARY_NAME);
+ if (!fs.existsSync(source)) {
+ throw new Error(`Session drag release helper source missing at ${source}`);
+ }
+ const hashPath = `${binary}.sha256`;
+ const sourceHash = createHash('sha256').update(fs.readFileSync(source)).digest('hex');
+ if (
+ fs.existsSync(binary) &&
+ fs.existsSync(hashPath) &&
+ fs.readFileSync(hashPath, 'utf8').trim() === sourceHash
+ ) {
+ return binary;
+ }
+ fs.mkdirSync(path.dirname(binary), { recursive: true });
+ await execFilePromise('swiftc', [source, '-O', '-o', binary], HELPER_BUILD_TIMEOUT_MS);
+ fs.chmodSync(binary, 0o755);
+ fs.writeFileSync(hashPath, `${sourceHash}\n`, 'utf8');
+ log.info('built dev macOS session drag release helper', { path: binary });
+ return binary;
+}
+
+function resolveDevHelperSource(): string {
+ const fromAppPath = path.join(app.getAppPath(), HELPER_SOURCE_RELATIVE);
+ if (fs.existsSync(fromAppPath)) return fromAppPath;
+ return path.join(__dirname, '..', '..', HELPER_SOURCE_RELATIVE);
+}
+
+function execFilePromise(command: string, args: string[], timeoutMs: number): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const child = execFile(command, args, { timeout: timeoutMs }, (error, _stdout, stderr) => {
+ if (error) {
+ reject(new Error(stderr?.trim() ? `${error.message}: ${stderr.trim()}` : error.message));
+ return;
+ }
+ resolve();
+ });
+ child.on('error', reject);
+ });
+}
diff --git a/apps/desktop/src/main/windowBounds.ts b/apps/desktop/src/main/windowBounds.ts
new file mode 100644
index 0000000000..283ce65a5f
--- /dev/null
+++ b/apps/desktop/src/main/windowBounds.ts
@@ -0,0 +1,74 @@
+export interface WindowBounds {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export interface ScreenPoint {
+ x: number;
+ y: number;
+}
+
+const DROP_WINDOW_POINTER_OFFSET = { x: 80, y: 24 };
+const SESSION_DRAG_PREVIEW_POINTER_OFFSET = { x: 8, y: 8 };
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(max, Math.max(min, value));
+}
+
+/** Window bounds use a half-open rectangle, matching Electron's screen space. */
+export function isPointInWindowBounds(point: ScreenPoint, bounds: WindowBounds): boolean {
+ return (
+ point.x >= bounds.x &&
+ point.x < bounds.x + bounds.width &&
+ point.y >= bounds.y &&
+ point.y < bounds.y + bounds.height
+ );
+}
+
+export function isPointInsideAnyWindow(
+ point: ScreenPoint,
+ windows: readonly WindowBounds[],
+): boolean {
+ return windows.some((bounds) => isPointInWindowBounds(point, bounds));
+}
+
+/**
+ * Place a newly detached task window with its title-bar area near the release
+ * point, while keeping the complete window visible on the nearest display.
+ */
+export function resolveWindowBoundsNearPoint(
+ point: ScreenPoint,
+ requestedSize: Pick<WindowBounds, 'width' | 'height'>,
+ workArea: WindowBounds,
+): WindowBounds {
+ const width = Math.min(Math.max(1, Math.round(requestedSize.width)), workArea.width);
+ const height = Math.min(Math.max(1, Math.round(requestedSize.height)), workArea.height);
+ const maxX = workArea.x + workArea.width - width;
+ const maxY = workArea.y + workArea.height - height;
+ return {
+ x: clamp(Math.round(point.x - DROP_WINDOW_POINTER_OFFSET.x), workArea.x, maxX),
+ y: clamp(Math.round(point.y - DROP_WINDOW_POINTER_OFFSET.y), workArea.y, maxY),
+ width,
+ height,
+ };
+}
+
+/** Place the transient drag preview just below/right of the cursor. */
+export function resolveSessionDragPreviewBounds(
+ point: ScreenPoint,
+ workArea: WindowBounds,
+ requestedSize: Pick<WindowBounds, 'width' | 'height'> = { width: 320, height: 68 },
+): WindowBounds {
+ const width = Math.min(Math.max(1, Math.round(requestedSize.width)), workArea.width);
+ const height = Math.min(Math.max(1, Math.round(requestedSize.height)), workArea.height);
+ const maxX = workArea.x + workArea.width - width;
+ const maxY = workArea.y + workArea.height - height;
+ return {
+ x: clamp(point.x + SESSION_DRAG_PREVIEW_POINTER_OFFSET.x, workArea.x, maxX),
+ y: clamp(point.y + SESSION_DRAG_PREVIEW_POINTER_OFFSET.y, workArea.y, maxY),
+ width,
+ height,
+ };
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 4dd8d03d26..9953b7713d 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,6 +1,7 @@
import { contextBridge, ipcRenderer, webUtils } from 'electron';
import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
import type { AppearanceSettings } from '../shared/appearanceSettings';
+import type { SessionDragPreviewPalette } from '../shared/sessionDragPreview';
import {
AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL,
AGENT_ISLAND_PREVIEW_SOUND_CHANNEL,
@@ -5096,8 +5097,26 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:model-price-override:reset', target),
// 「在新窗口打开」会话多开 —— 新建一个完整窗口定位到该 session。
- openSessionInNewWindow: (sessionId: string): Promise<void> =>
- ipcRenderer.invoke('maker:open-session-in-new-window', sessionId),
+ openSessionInNewWindow: (sessionId: string, deviceId?: string | null): Promise<void> =>
+ ipcRenderer.invoke('maker:open-session-in-new-window', sessionId, deviceId),
+ openSessionInNewWindowIfDroppedOutside: (
+ sessionId: string,
+ deviceId?: string | null,
+ ): Promise<boolean> =>
+ ipcRenderer.invoke(
+ 'maker:open-session-in-new-window-if-dropped-outside',
+ sessionId,
+ deviceId,
+ ),
+ beginSessionDragPreview: (
+ label: string,
+ sessionId: string,
+ deviceId: string | null | undefined,
+ palette: SessionDragPreviewPalette,
+ ): Promise<void> =>
+ ipcRenderer.invoke('maker:session-drag-preview:start', label, sessionId, deviceId, palette),
+ endSessionDragPreview: (dragEndAtMs?: number): void =>
+ ipcRenderer.send('maker:session-drag-preview:end', dragEndAtMs),
// ── Palette `/` 命令三源 (palette refactor) ─────────────────────────
// Renderer 通过这四个调用合并三路数据 + 触发 desktop 命令 execute。
@@ -6393,7 +6412,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
onH264Frame: (callback: (payload: IOSSimulatorH264FramePush) => void) =>
fanOutIOSSimulatorH264Frame((payload) => callback(payload as IOSSimulatorH264FramePush)),
onRouteStatus: (callback: (payload: IOSSimulatorRouteStatusPush) => void) =>
- fanOutIOSSimulatorRouteStatus((payload) => callback(payload as IOSSimulatorRouteStatusPush)),
+ fanOutIOSSimulatorRouteStatus((payload) =>
+ callback(payload as IOSSimulatorRouteStatusPush),
+ ),
onFocusRequest: (callback: (request: IOSSimulatorFocusRequest) => void) =>
fanOutIOSSimulatorFocusRequest((request) => callback(request as IOSSimulatorFocusRequest)),
},
diff --git a/apps/desktop/src/renderer/components/sidebar/Sidebar.tsx b/apps/desktop/src/renderer/components/sidebar/Sidebar.tsx
index 02da13e3e8..3ed92d2e0e 100644
--- a/apps/desktop/src/renderer/components/sidebar/Sidebar.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/Sidebar.tsx
@@ -24,6 +24,7 @@ import type { SidebarPeekDrawerProps, SidebarPeekState } from '@/hooks/useSideba
import { useMacFullscreen } from '@/hooks/useMacFullscreen';
import { useFeatureSidebarUpper } from '@/features/feature-context';
import { ConversationSearchProvider } from '@/features/cc-agent/sidebar/conversationSearchContext';
+import { isSecondaryWindow } from '@/lib/secondaryWindow';
import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';
import { SidebarTopNav } from './SidebarTopNav';
import { UpdateBanner } from './UpdateBanner';
@@ -93,6 +94,10 @@ export function Sidebar({
// peek 抽屉态(fixed overlay,不占流内布局)。矩形与正常展开态逐像素一致,
// 因此 pin 时(pinning → idle)fixed↔static 的交换帧不产生视觉跳变。
const isPeek = peekState != null;
+ // 副窗口默认完全隐藏侧栏。此时不挂载任务列表及其搜索 Provider,避免开窗
+ // 首帧为了不可见内容发起两份大列表查询;展开、rail 与 peek 都仍需完整内容。
+ // 主窗口保持原有常驻挂载语义,避免改变切换与缓存体验。
+ const shouldMountFeatureContent = !isSecondaryWindow() || !isCollapsed || isPeek;
// 离开 peek 的交换帧必须禁用宽度过渡:peekClosing → idle(收起)时,aside 带着
// 上一帧的 width=展开宽 回流为流内 width=0,若 transition-[width] 还挂着,这次
@@ -204,21 +209,23 @@ export function Sidebar({
{/* ConversationSearchProvider:在顶部导航行(SidebarTopNav 的「搜索」行)与功能槽
(CCAgentSidebarUpper 的结果 overlay)这两个兄弟子树的共同祖先处,只实例化一次
会话搜索状态,经 context 共享。外壳本身仍不感知搜索细节,只负责放置 Provider。 */}
- <ConversationSearchProvider>
- {/* 顶部常驻动作/导航列表(新建 / 自动任务 / Skill / 搜索)。
- 取代原 HorizontalTabbar:同级等权列表行,无单独项目 Tab。
- rail(收窄)态放不下,隐藏——rail 自身承担入口;展开后回归。
- 完全隐藏态 w-0 自然裁掉。 */}
- {!isRail && <SidebarTopNav />}
-
- {/* Upper: feature-injected content slot.
- The current Feature Layout injects either an expanded or collapsed
- sidebar tree through the FeatureSidebarSlotContext. Shell renders
- whatever it's given. If no feature is active (e.g. /settings with
- the intentionally empty SettingsSidebarUpper), this simply leaves
- the upper area blank. */}
- <div className="flex flex-1 flex-col overflow-hidden">{upperContent}</div>
- </ConversationSearchProvider>
+ {shouldMountFeatureContent && (
+ <ConversationSearchProvider>
+ {/* 顶部常驻动作/导航列表(新建 / 自动任务 / Skill / 搜索)。
+ 取代原 HorizontalTabbar:同级等权列表行,无单独项目 Tab。
+ rail(收窄)态放不下,隐藏——rail 自身承担入口;展开后回归。
+ 完全隐藏态 w-0 自然裁掉。 */}
+ {!isRail && <SidebarTopNav />}
+
+ {/* Upper: feature-injected content slot.
+ The current Feature Layout injects either an expanded or collapsed
+ sidebar tree through the FeatureSidebarSlotContext. Shell renders
+ whatever it's given. If no feature is active (e.g. /settings with
+ the intentionally empty SettingsSidebarUpper), this simply leaves
+ the upper area blank. */}
+ <div className="flex flex-1 flex-col overflow-hidden">{upperContent}</div>
+ </ConversationSearchProvider>
+ )}
{/* Update banner: shown only when a verified update is ready
peek 抽屉视同展开(否则横幅在抽屉里消失,与「预览完整列表」语义相悖)。 */}
diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/Sidebar.lazy-feature-content.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/Sidebar.lazy-feature-content.test.tsx
new file mode 100644
index 0000000000..27f8acc8f7
--- /dev/null
+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/Sidebar.lazy-feature-content.test.tsx
@@ -0,0 +1,123 @@
+// @vitest-environment jsdom
+
+import { useMemo, type ReactNode } from 'react';
+import { render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { FeatureSidebarSlotProvider, useRegisterSidebarUpper } from '@/features/feature-context';
+import type { SidebarPeekState } from '@/hooks/useSidebarPeek';
+import { Sidebar } from '../Sidebar';
+
+const mocks = vi.hoisted(() => ({
+ isSecondaryWindow: true,
+}));
+
+vi.mock('@/lib/secondaryWindow', () => ({
+ isSecondaryWindow: () => mocks.isSecondaryWindow,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/hooks/useMacFullscreen', () => ({
+ useMacFullscreen: () => ({ isMac: true, isFullscreen: false }),
+}));
+
+vi.mock('@/features/cc-agent/sidebar/conversationSearchContext', () => ({
+ ConversationSearchProvider: ({ children }: { children: ReactNode }) => (
+ <div data-testid="conversation-search-provider">{children}</div>
+ ),
+}));
+
+vi.mock('../SidebarTopNav', () => ({
+ SidebarTopNav: () => <div data-testid="sidebar-top-nav" />,
+}));
+
+vi.mock('../UpdateBanner', () => ({
+ UpdateBanner: () => null,
+}));
+
+vi.mock('../UserInfoSection', () => ({
+ UserInfoSection: () => null,
+}));
+
+function UpperProbe() {
+ return <div data-testid="sidebar-upper" />;
+}
+
+function RegisterUpper() {
+ const upper = useMemo(() => <UpperProbe />, []);
+ useRegisterSidebarUpper(upper);
+ return null;
+}
+
+interface HarnessProps {
+ isCollapsed: boolean;
+ isRail?: boolean;
+ peekState?: SidebarPeekState | null;
+}
+
+function Harness({ isCollapsed, isRail = false, peekState = null }: HarnessProps) {
+ return (
+ <FeatureSidebarSlotProvider isCollapsed={peekState != null ? false : isCollapsed || isRail}>
+ <RegisterUpper />
+ <Sidebar isCollapsed={isCollapsed} isRail={isRail} peekState={peekState} />
+ </FeatureSidebarSlotProvider>
+ );
+}
+
+describe('Sidebar secondary-window lazy feature content', () => {
+ beforeEach(() => {
+ mocks.isSecondaryWindow = true;
+ });
+
+ it('does not mount hidden task-list content until a secondary sidebar expands', () => {
+ const view = render(<Harness isCollapsed />);
+
+ expect(screen.queryByTestId('conversation-search-provider')).toBeNull();
+ expect(screen.queryByTestId('sidebar-upper')).toBeNull();
+
+ view.rerender(<Harness isCollapsed={false} />);
+
+ expect(screen.getByTestId('conversation-search-provider')).toBeTruthy();
+ expect(screen.getByTestId('sidebar-upper')).toBeTruthy();
+ });
+
+ it('unmounts the task-list content when the secondary sidebar is hidden again', () => {
+ const view = render(<Harness isCollapsed={false} />);
+ expect(screen.getByTestId('sidebar-upper')).toBeTruthy();
+
+ view.rerender(<Harness isCollapsed />);
+ expect(screen.queryByTestId('sidebar-upper')).toBeNull();
+
+ view.rerender(<Harness isCollapsed={false} />);
+ expect(screen.getByTestId('sidebar-upper')).toBeTruthy();
+ });
+
+ it('keeps feature content mounted in a secondary rail sidebar', () => {
+ render(<Harness isCollapsed={false} isRail />);
+
+ expect(screen.getByTestId('conversation-search-provider')).toBeTruthy();
+ expect(screen.getByTestId('sidebar-upper')).toBeTruthy();
+ });
+
+ it.each<SidebarPeekState>(['peeking', 'peekClosing', 'pinning'])(
+ 'keeps feature content mounted while the secondary sidebar is %s',
+ (peekState) => {
+ render(<Harness isCollapsed peekState={peekState} />);
+
+ expect(screen.getByTestId('conversation-search-provider')).toBeTruthy();
+ expect(screen.getByTestId('sidebar-upper')).toBeTruthy();
+ },
+ );
+
+ it("preserves the primary window's collapsed mounting behavior", () => {
+ mocks.isSecondaryWindow = false;
+
+ render(<Harness isCollapsed />);
+
+ expect(screen.getByTestId('conversation-search-provider')).toBeTruthy();
+ expect(screen.getByTestId('sidebar-upper')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/SecondaryWindowBootGate.tsx b/apps/desktop/src/renderer/features/cc-agent/SecondaryWindowBootGate.tsx
index d98f4f30d5..30838a329c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SecondaryWindowBootGate.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SecondaryWindowBootGate.tsx
@@ -22,8 +22,10 @@
import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
-import { getBootSessionId } from '@/lib/secondaryWindow';
+import { getBootDeviceId, getBootSessionId } from '@/lib/secondaryWindow';
+import { getSessionFor } from '@/lib/makerTransport';
import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { createLogger } from '@/lib/logger';
const log = createLogger('SecondaryWindowBootGate');
@@ -45,7 +47,20 @@ export function SecondaryWindowBootGate() {
}
let cancelled = false;
- void resolveSessionRoute(bootSessionId)
+ const bootDeviceId = getBootDeviceId();
+ void (async () => {
+ if (!bootDeviceId) return resolveSessionRoute(bootSessionId);
+
+ // The remote session is not in the local DB. Pin its origin before any
+ // metadata read so getSessionFor tunnels to the owning device even when
+ // the secondary window's remote mirror has not hydrated yet.
+ remoteProjectsStore.pinSessionOrigin(bootDeviceId, bootSessionId);
+ const mirroredSession = remoteProjectsStore
+ .getMergedRemoteSessions()
+ .find((session) => session.id === bootSessionId);
+ const remoteSession = mirroredSession ?? (await getSessionFor(bootSessionId));
+ return resolveSessionRoute(bootSessionId, remoteSession);
+ })()
.then((target) => {
if (cancelled) return;
navigate(target, { replace: true });
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
index 2bf2a73585..4e8b5e5c78 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
@@ -300,8 +300,8 @@ export function SessionContentHeader({
showRemoteWriteBlockedToast();
return;
}
- void window.electronAPI.maker.openSessionInNewWindow(session.id);
- }, [remoteWritesBlocked, session.id, showRemoteWriteBlockedToast]);
+ void window.electronAPI.maker.openSessionInNewWindow(session.id, session.deviceLinkDeviceId);
+ }, [remoteWritesBlocked, session.deviceLinkDeviceId, session.id, showRemoteWriteBlockedToast]);
/* ---- 移动到项目 / 对话 ----
* 与 CCAgentSidebarUpper.handleMoveSession 同款守卫(远程不支持 / 执行中 /
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/SecondaryWindowBootGate.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/SecondaryWindowBootGate.test.tsx
new file mode 100644
index 0000000000..e2d218a602
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/SecondaryWindowBootGate.test.tsx
@@ -0,0 +1,86 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ getBootDeviceId: vi.fn<() => string | null>(),
+ getBootSessionId: vi.fn<() => string | null>(),
+ getMergedRemoteSessions: vi.fn<() => Array<Record<string, unknown>>>(),
+ getSessionFor: vi.fn(),
+ navigate: vi.fn(),
+ pinSessionOrigin: vi.fn(),
+ resolveSessionRoute: vi.fn(),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => mocks.navigate,
+}));
+
+vi.mock('@/lib/secondaryWindow', () => ({
+ getBootDeviceId: mocks.getBootDeviceId,
+ getBootSessionId: mocks.getBootSessionId,
+}));
+
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ remoteProjectsStore: {
+ getMergedRemoteSessions: mocks.getMergedRemoteSessions,
+ pinSessionOrigin: mocks.pinSessionOrigin,
+ },
+}));
+
+vi.mock('@/lib/makerTransport', () => ({
+ getSessionFor: mocks.getSessionFor,
+}));
+
+vi.mock('@/lib/orcaSessionIdentity', () => ({
+ resolveSessionRoute: mocks.resolveSessionRoute,
+}));
+
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({ warn: vi.fn() }),
+}));
+
+import { SecondaryWindowBootGate } from '../SecondaryWindowBootGate';
+
+describe('SecondaryWindowBootGate', () => {
+ beforeEach(() => {
+ mocks.getBootDeviceId.mockReset();
+ mocks.getBootSessionId.mockReset();
+ mocks.getMergedRemoteSessions.mockReset();
+ mocks.getSessionFor.mockReset();
+ mocks.navigate.mockReset();
+ mocks.pinSessionOrigin.mockReset();
+ mocks.resolveSessionRoute.mockReset();
+ mocks.getBootSessionId.mockReturnValue('worker-remote');
+ mocks.getBootDeviceId.mockReturnValue('device-remote');
+ mocks.getMergedRemoteSessions.mockReturnValue([]);
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('reads remote Worker metadata after pinning when the mirror has not hydrated', async () => {
+ const workerSession = { id: 'worker-remote', orcaRole: 'worker' };
+ mocks.getSessionFor.mockResolvedValue(workerSession);
+ mocks.resolveSessionRoute.mockResolvedValue('/cc-agent/lead-remote?worker=worker-remote');
+
+ render(<SecondaryWindowBootGate />);
+
+ await waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/lead-remote?worker=worker-remote', {
+ replace: true,
+ }),
+ );
+ expect(mocks.pinSessionOrigin).toHaveBeenCalledWith('device-remote', 'worker-remote');
+ expect(mocks.getSessionFor).toHaveBeenCalledWith('worker-remote');
+ expect(mocks.resolveSessionRoute).toHaveBeenCalledWith('worker-remote', workerSession);
+ expect(mocks.pinSessionOrigin.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.getSessionFor.mock.invocationCallOrder[0],
+ );
+ expect(mocks.getSessionFor.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.resolveSessionRoute.mock.invocationCallOrder[0],
+ );
+ });
+});
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
index 7b405f9273..82615c1e01 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,6 +1,6 @@
// @vitest-environment jsdom
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
SPLIT_GROUP_SESSION_MIME,
@@ -11,12 +11,31 @@ import {
needsDedicatedSplitGroupDragHandle,
resolveSplitDropSide,
shouldStartSplitGroupDrag,
+ finishSessionDrag,
+ startSessionDrag,
writeSplitGroupSessionDragData,
} from '../splitGroupDnd';
const RECT = { left: 100, top: 50, width: 400, height: 300 };
+const PREVIEW_PALETTE = {
+ surface: 'rgb(248, 248, 248)',
+ border: 'rgb(220, 223, 227)',
+ text: 'rgb(60, 63, 67)',
+};
+
+function mockPreviewPalette(): void {
+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({
+ backgroundColor: PREVIEW_PALETTE.surface,
+ borderTopColor: PREVIEW_PALETTE.border,
+ color: PREVIEW_PALETTE.text,
+ } as unknown as CSSStyleDeclaration);
+}
describe('splitGroupDnd', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it('输入框内的任务拖放由 composer 消费,不属于分屏落点', () => {
const composer = document.createElement('div');
composer.setAttribute('data-split-group-composer-drop-target', '');
@@ -32,18 +51,26 @@ describe('splitGroupDnd', () => {
expect(hasSplitGroupSessionType(['Files', 'text/plain'])).toBe(false);
});
- it('向侧栏拖拽写入专用 MIME 和纯文本回退', () => {
+ it('只写入 Cindy 专用 MIME,避免系统把任务拖拽落成桌面文件', () => {
const values = new Map<string, string>();
const dataTransfer = {
effectAllowed: 'none',
+ clearData: (format?: string) => {
+ if (format === undefined) values.clear();
+ else values.delete(format);
+ },
setData: (format: string, data: string) => values.set(format, data),
};
+ values.set('text/plain', 'stale-text');
+ values.set('text/uri-list', 'https://example.com/dragged');
+
expect(writeSplitGroupSessionDragData(dataTransfer, ' session-a ')).toBe(true);
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(values.has('text/plain')).toBe(false);
+ expect(values.has('text/uri-list')).toBe(false);
expect(
writeSplitGroupSessionDragData(dataTransfer, 'session-remote', { deviceId: 'device-b' }),
).toBe(true);
@@ -53,6 +80,171 @@ describe('splitGroupDnd', () => {
expect(writeSplitGroupSessionDragData(dataTransfer, ' ')).toBe(false);
});
+ it('共享原生拖拽 helper 保留任务 payload 并在结束时请求窗口外判定', () => {
+ mockPreviewPalette();
+ const row = document.createElement('div');
+ const title = document.createElement('span');
+ row.append(title);
+ const values = new Map<string, string>();
+ const dataTransfer = {
+ effectAllowed: 'none',
+ setData: (format: string, data: string) => values.set(format, data),
+ setDragImage: vi.fn(),
+ };
+ const beginPreview = vi.fn().mockResolvedValue(undefined);
+ const endPreview = vi.fn();
+ const openOutside = vi.fn().mockResolvedValue(false);
+ const electronApiDescriptor = Object.getOwnPropertyDescriptor(window, 'electronAPI');
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ maker: {
+ beginSessionDragPreview: beginPreview,
+ endSessionDragPreview: endPreview,
+ openSessionInNewWindowIfDroppedOutside: openOutside,
+ },
+ },
+ });
+ const dragStartEvent = {
+ target: title,
+ currentTarget: row,
+ dataTransfer,
+ preventDefault: vi.fn(),
+ };
+ expect(
+ startSessionDrag(dragStartEvent, {
+ sessionId: 'session-a',
+ deviceId: 'device-b',
+ label: '任务 A',
+ enabled: true,
+ needsDedicatedHandle: false,
+ }),
+ ).toBe(true);
+ expect(values.get(SPLIT_GROUP_SESSION_MIME)).toBe('session-a');
+ expect(row.dataset.sessionDragging).toBe('true');
+ expect(dataTransfer.setDragImage).toHaveBeenCalledOnce();
+ const preview = dataTransfer.setDragImage.mock.calls[0]?.[0];
+ expect(preview).toBeInstanceOf(HTMLCanvasElement);
+ expect((preview as HTMLCanvasElement).width).toBe(1);
+ expect((preview as HTMLCanvasElement).height).toBe(1);
+ expect((preview as HTMLCanvasElement).dataset.sessionDragPreviewTransparent).toBe('true');
+ expect(document.querySelector('[data-session-drag-preview-transparent]')).toBe(preview);
+ expect(beginPreview).toHaveBeenCalledWith('任务 A', 'session-a', 'device-b', PREVIEW_PALETTE);
+ expect(document.querySelector('[data-session-drag-preview-palette-probe]')).toBeNull();
+
+ window.dispatchEvent(new Event('pointerup'));
+ window.dispatchEvent(new Event('dragend'));
+ expect(row.dataset.sessionDragging).toBeUndefined();
+ expect(endPreview).toHaveBeenCalledOnce();
+ expect(endPreview).toHaveBeenCalledWith(expect.any(Number));
+ expect(openOutside).toHaveBeenCalledWith('session-a', 'device-b');
+ expect(document.querySelector('[data-session-drag-preview-transparent]')).toBeNull();
+ if (electronApiDescriptor) {
+ Object.defineProperty(window, 'electronAPI', electronApiDescriptor);
+ } else {
+ Reflect.deleteProperty(window, 'electronAPI');
+ }
+ });
+
+ it('macOS waits for the native mouse-up path before ending the drag', () => {
+ const row = document.createElement('div');
+ const dataTransfer = {
+ effectAllowed: 'none',
+ setData: vi.fn(),
+ setDragImage: vi.fn(),
+ };
+ const beginPreview = vi.fn().mockResolvedValue(undefined);
+ const endPreview = vi.fn();
+ const openOutside = vi.fn().mockResolvedValue(false);
+ const electronApiDescriptor = Object.getOwnPropertyDescriptor(window, 'electronAPI');
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ platform: 'darwin',
+ maker: {
+ beginSessionDragPreview: beginPreview,
+ endSessionDragPreview: endPreview,
+ openSessionInNewWindowIfDroppedOutside: openOutside,
+ },
+ },
+ });
+
+ startSessionDrag(
+ {
+ target: row,
+ currentTarget: row,
+ dataTransfer,
+ preventDefault: vi.fn(),
+ },
+ {
+ sessionId: 'session-a',
+ enabled: true,
+ needsDedicatedHandle: false,
+ },
+ );
+ window.dispatchEvent(new Event('pointerup'));
+ expect(endPreview).not.toHaveBeenCalled();
+ expect(openOutside).not.toHaveBeenCalled();
+
+ window.dispatchEvent(new Event('dragend'));
+ expect(endPreview).toHaveBeenCalledOnce();
+ expect(openOutside).toHaveBeenCalledWith('session-a', undefined);
+ if (electronApiDescriptor) {
+ Object.defineProperty(window, 'electronAPI', electronApiDescriptor);
+ } else {
+ Reflect.deleteProperty(window, 'electronAPI');
+ }
+ });
+
+ it('按 Escape 取消原生拖拽时不会请求窗口外开窗', () => {
+ mockPreviewPalette();
+ const row = document.createElement('div');
+ const dataTransfer = {
+ effectAllowed: 'none',
+ setData: vi.fn(),
+ };
+ const openOutside = vi.fn().mockResolvedValue(false);
+ const beginPreview = vi.fn().mockResolvedValue(undefined);
+ const endPreview = vi.fn();
+ const electronApiDescriptor = Object.getOwnPropertyDescriptor(window, 'electronAPI');
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ maker: {
+ beginSessionDragPreview: beginPreview,
+ endSessionDragPreview: endPreview,
+ openSessionInNewWindowIfDroppedOutside: openOutside,
+ },
+ },
+ });
+
+ startSessionDrag(
+ {
+ target: row,
+ currentTarget: row,
+ dataTransfer,
+ preventDefault: vi.fn(),
+ },
+ {
+ sessionId: 'session-a',
+ enabled: true,
+ needsDedicatedHandle: false,
+ },
+ );
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ finishSessionDrag({ currentTarget: row }, 'session-a');
+
+ expect(beginPreview).toHaveBeenCalledWith('session-a', 'session-a', undefined, PREVIEW_PALETTE);
+ expect(endPreview).toHaveBeenCalledOnce();
+ expect(endPreview).toHaveBeenCalledWith(expect.any(Number));
+ expect(openOutside).not.toHaveBeenCalled();
+ if (electronApiDescriptor) {
+ Object.defineProperty(window, 'electronAPI', electronApiDescriptor);
+ } else {
+ Reflect.deleteProperty(window, 'electronAPI');
+ }
+ });
+
it.each([
['left', 110, 200],
['right', 490, 200],
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 04104d3252..5099efd9f8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -81,12 +81,10 @@ import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';
import { shouldPrefetchSessionOnPointerDown } from './sessionSwitchPrefetch';
import { OpenInSplitMenu } from './OpenInSplitMenu';
import {
- SPLIT_GROUP_DRAG_HANDLE_SELECTOR,
- SPLIT_GROUP_DRAG_INTERACTIVE_SELECTOR,
+ finishSessionDrag,
isSplitGroupDragSource,
needsDedicatedSplitGroupDragHandle,
- shouldStartSplitGroupDrag,
- writeSplitGroupSessionDragData,
+ startSessionDrag,
} from '../splitGroupDnd';
const log = createLogger('SessionCard');
@@ -289,33 +287,17 @@ export function SessionCard({
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({
+ startSessionDrag(event, {
+ sessionId: session.id,
+ deviceId: session.deviceLinkDeviceId,
+ label: displayTitle,
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';
+ dragStartTarget: dragStartTargetRef.current,
+ });
+ dragStartTargetRef.current = null;
},
- [needsSplitDragHandle, session.deviceLinkDeviceId, session.id, splitDragEnabled],
+ [displayTitle, needsSplitDragHandle, session.deviceLinkDeviceId, session.id, splitDragEnabled],
);
// raw 由 SessionRenameInput 传入:输入框当前文本(Magic 生成的标题也先填入输入框,用户 Enter 确认后才走到这里)。
@@ -450,8 +432,8 @@ export function SessionCard({
toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
return;
}
- void window.electronAPI.maker.openSessionInNewWindow(session.id);
- }, [remoteWritesBlocked, session.id, t]);
+ void window.electronAPI.maker.openSessionInNewWindow(session.id, session.deviceLinkDeviceId);
+ }, [remoteWritesBlocked, session.deviceLinkDeviceId, session.id, t]);
// 「导出会话…」——打成 .cshare 分享给同事。空草稿、remote / orca / device-link 会话不显示此入口
// (转录在远端或协同关系不可移植,main 侧同样有双保险拒绝)。
@@ -615,7 +597,7 @@ export function SessionCard({
onDragStart={handleDragStart}
onDragEnd={(event) => {
dragStartTargetRef.current = null;
- delete event.currentTarget.dataset.sessionDragging;
+ finishSessionDrag(event, session.id, session.deviceLinkDeviceId);
}}
onPointerDown={(e) => {
if (shouldPrefetchSessionOnPointerDown(e, { isActive, isEditing })) {
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 c9770d5785..44f3123ee0 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -95,12 +95,10 @@ import { resolveSidebarRightStatus } from './sidebarRightStatus';
import { AutomationTimerIcon } from './AutomationTimerIcon';
import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';
import {
- SPLIT_GROUP_DRAG_HANDLE_SELECTOR,
- SPLIT_GROUP_DRAG_INTERACTIVE_SELECTOR,
+ finishSessionDrag,
isSplitGroupDragSource,
needsDedicatedSplitGroupDragHandle,
- shouldStartSplitGroupDrag,
- writeSplitGroupSessionDragData,
+ startSessionDrag,
} from '../splitGroupDnd';
import { shouldPrefetchSessionOnPointerDown } from './sessionSwitchPrefetch';
import { OpenInSplitMenu } from './OpenInSplitMenu';
@@ -589,35 +587,17 @@ export const SessionItem = memo(function SessionItem({
const handleDragStart = useCallback(
(event: ReactDragEvent<HTMLDivElement>) => {
- const target =
- dragStartTargetRef.current ?? (event.target instanceof Element ? event.target : null);
+ startSessionDrag(event, {
+ sessionId: session.id,
+ deviceId: session.deviceLinkDeviceId,
+ label: displayTitle,
+ enabled: splitDragEnabled,
+ needsDedicatedHandle: needsSplitDragHandle,
+ dragStartTarget: dragStartTargetRef.current,
+ });
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],
+ [displayTitle, needsSplitDragHandle, session.deviceLinkDeviceId, session.id, splitDragEnabled],
);
// isActive 由 false → true(或初次 mount 时即为 true)→ 把行滚进 viewport。
@@ -726,8 +706,8 @@ export const SessionItem = memo(function SessionItem({
toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
return;
}
- void window.electronAPI.maker.openSessionInNewWindow(session.id);
- }, [remoteWritesBlocked, session.id, t]);
+ void window.electronAPI.maker.openSessionInNewWindow(session.id, session.deviceLinkDeviceId);
+ }, [remoteWritesBlocked, session.deviceLinkDeviceId, session.id, t]);
// 复制 cindy://session/<id> 深度链接到剪贴板。三个变体(标准/Pinned/Archived/Draft)
// 共用此 handler — sessionId 始终存在(draft 也是 DB-backed 的 Session row)。
@@ -825,7 +805,7 @@ export const SessionItem = memo(function SessionItem({
onDragStart={handleDragStart}
onDragEnd={(event) => {
dragStartTargetRef.current = null;
- delete event.currentTarget.dataset.sessionDragging;
+ finishSessionDrag(event, session.id, session.deviceLinkDeviceId);
}}
onPointerDown={(e) => {
if (shouldPrefetchSessionOnPointerDown(e, { isActive, isEditing })) {
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.ts
index 6b08925ba4..49d522b896 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
@@ -277,6 +277,23 @@ describe('SessionCard visual cases', () => {
expect(values.get(SPLIT_GROUP_SESSION_MIME)).toBe(visualCase.session.id);
expect(dataTransfer.effectAllowed).toBe('copyMove');
+ const openOutside = vi.fn().mockResolvedValue(false);
+ const electronApiDescriptor = Object.getOwnPropertyDescriptor(window, 'electronAPI');
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { maker: { openSessionInNewWindowIfDroppedOutside: openOutside } },
+ });
+ fireEvent.dragEnd(card!, { dataTransfer });
+ expect(openOutside).toHaveBeenCalledWith(
+ visualCase.session.id,
+ visualCase.session.deviceLinkDeviceId,
+ );
+ if (electronApiDescriptor) {
+ Object.defineProperty(window, 'electronAPI', electronApiDescriptor);
+ } else {
+ Reflect.deleteProperty(window, 'electronAPI');
+ }
+
values.clear();
dataTransfer.effectAllowed = 'none';
fireEvent.pointerDown(actionButton!, { button: 0, pointerType: 'mouse' });
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 1297101816..225f1cf436 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
@@ -284,7 +284,7 @@ describe('SessionCard review regressions', () => {
);
expect(sessionCardSource).toContain('data-split-group-drag-handle');
expect(sessionCardSource).toContain('data-no-drag={splitDragHandleActive');
- expect(sessionCardSource).toContain('writeSplitGroupSessionDragData');
+ expect(sessionCardSource).toContain('startSessionDrag');
});
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.ts
index 8a8afc6595..28b10b48e1 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
@@ -208,6 +208,12 @@ describe('SessionItem — 置顶分屏拖拽', () => {
effectAllowed: 'none',
setData: (format: string, data: string) => values.set(format, data),
};
+ const openOutside = vi.fn().mockResolvedValue(false);
+ const electronApiDescriptor = Object.getOwnPropertyDescriptor(window, 'electronAPI');
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { maker: { openSessionInNewWindowIfDroppedOutside: openOutside } },
+ });
const { container } = render(
createElement(SessionAttentionUrgencyProvider, {
urgentSessionIds: new Set<string>(),
@@ -247,6 +253,9 @@ describe('SessionItem — 置顶分屏拖拽', () => {
expect(values.get(SPLIT_GROUP_SESSION_MIME)).toBe(pinnedSession.id);
expect(dataTransfer.effectAllowed).toBe('copyMove');
+ fireEvent.dragEnd(row!, { dataTransfer });
+ expect(openOutside).toHaveBeenCalledWith(pinnedSession.id, null);
+
values.clear();
dataTransfer.effectAllowed = 'none';
fireEvent.pointerDown(actionButton!, { button: 0, pointerType: 'mouse' });
@@ -257,6 +266,12 @@ describe('SessionItem — 置顶分屏拖拽', () => {
expect(preventDefault).toHaveBeenCalledOnce();
expect(values.has(SPLIT_GROUP_SESSION_MIME)).toBe(false);
expect(dataTransfer.effectAllowed).toBe('none');
+
+ if (electronApiDescriptor) {
+ Object.defineProperty(window, 'electronAPI', electronApiDescriptor);
+ } else {
+ Reflect.deleteProperty(window, 'electronAPI');
+ }
});
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts b/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts
index 05acb6a6c9..c37730f2e7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/splitGroupDnd.ts
@@ -1,4 +1,5 @@
import type { DropSide } from './splitGroupStore';
+import type { SessionDragPreviewPalette } from '../../../shared/sessionDragPreview';
import { buildSessionDeepLink } from '@/lib/deepLink';
import {
isSessionLinkDropTarget,
@@ -24,7 +25,119 @@ export interface DropRect {
interface SplitGroupDragDataTransfer {
effectAllowed: string;
+ clearData?(format?: string): void;
setData(format: string, data: string): void;
+ setDragImage?(image: Element, x: number, y: number): void;
+}
+
+interface SessionDragEventLike {
+ target: EventTarget | null;
+ currentTarget: EventTarget | null;
+ dataTransfer: SplitGroupDragDataTransfer;
+ preventDefault(): void;
+}
+
+interface SessionDragEndEventLike {
+ currentTarget: EventTarget | null;
+}
+
+let activeSessionDragCancelled = false;
+let activeSessionDragCleanup: (() => void) | null = null;
+
+function resolveSessionDragPreviewPalette(): SessionDragPreviewPalette | undefined {
+ if (typeof document === 'undefined' || typeof window === 'undefined') return undefined;
+ const parent = document.body ?? document.documentElement;
+ if (!parent) return undefined;
+
+ const probe = document.createElement('div');
+ probe.dataset.sessionDragPreviewPaletteProbe = 'true';
+ probe.style.cssText =
+ 'position:fixed;left:0;top:0;width:0;height:0;visibility:hidden;pointer-events:none;';
+ probe.style.backgroundColor = 'var(--surface-elevated)';
+ probe.style.borderTop = '1px solid var(--border-default)';
+ probe.style.color = 'var(--text-primary)';
+ parent.appendChild(probe);
+ try {
+ const style = window.getComputedStyle(probe);
+ return {
+ surface: style.backgroundColor,
+ border: style.borderTopColor,
+ text: style.color,
+ };
+ } finally {
+ probe.remove();
+ }
+}
+
+function stopTrackingSessionDrag(): boolean {
+ const cancelled = activeSessionDragCancelled;
+ activeSessionDragCancelled = false;
+ activeSessionDragCleanup?.();
+ activeSessionDragCleanup = null;
+ return cancelled;
+}
+
+function startTrackingSessionDrag(
+ label: string,
+ sessionId: string,
+ deviceId: string | null | undefined,
+ dragImageCleanup: () => void,
+ onNativeDragEnd: () => void,
+): void {
+ stopTrackingSessionDrag();
+ activeSessionDragCancelled = false;
+ if (typeof window === 'undefined') {
+ return;
+ }
+ const beginPreview = window.electronAPI?.maker?.beginSessionDragPreview;
+ if (beginPreview) {
+ const palette = resolveSessionDragPreviewPalette();
+ if (palette) {
+ void beginPreview(label, sessionId, deviceId, palette).catch(() => undefined);
+ }
+ }
+ let previewEndSent = false;
+ const signalPreviewEnd = () => {
+ if (previewEndSent) return;
+ previewEndSent = true;
+ const endPreview = window.electronAPI?.maker?.endSessionDragPreview;
+ try {
+ endPreview?.(Date.now());
+ } catch {
+ // Renderer teardown can make preload unavailable mid-drag. Local drag
+ // cleanup must still complete; main has its own duration safety cap.
+ }
+ };
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== 'Escape') return;
+ activeSessionDragCancelled = true;
+ // Escape may cancel Chromium's drag without immediately producing
+ // dragend. Disarm the macOS mouse-up fast path now so releasing the button
+ // after cancellation cannot open a window.
+ signalPreviewEnd();
+ };
+ const onDragEnd = () => onNativeDragEnd();
+ const onPointerUp = () => onNativeDragEnd();
+ window.addEventListener('keydown', onKeyDown, true);
+ window.addEventListener('dragend', onDragEnd, true);
+ // macOS has a main-process AppKit mouse-up fast path. Renderer pointer/mouse
+ // events can arrive first and disarm that listener before it sees the drop;
+ // leave them as the fallback only on platforms without the native path.
+ const hasNativeMouseUpPath = window.electronAPI?.platform === 'darwin';
+ if (!hasNativeMouseUpPath) {
+ window.addEventListener('pointerup', onPointerUp, true);
+ window.addEventListener('mouseup', onPointerUp, true);
+ }
+ activeSessionDragCleanup = () => {
+ signalPreviewEnd();
+ window.removeEventListener('keydown', onKeyDown, true);
+ window.removeEventListener('dragend', onDragEnd, true);
+ if (!hasNativeMouseUpPath) {
+ window.removeEventListener('pointerup', onPointerUp, true);
+ window.removeEventListener('mouseup', onPointerUp, true);
+ }
+ dragImageCleanup();
+ };
}
interface SplitGroupDragOptions {
@@ -43,12 +156,119 @@ export function writeSplitGroupSessionDragData(
// 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';
+ // Never expose a native text/URL flavor. Finder turns those into clipping
+ // files and macOS may add its globe/link drag badge; every Cindy target
+ // consumes one of the two private MIME types below.
+ dataTransfer.clearData?.();
dataTransfer.setData(SPLIT_GROUP_SESSION_MIME, sessionId);
dataTransfer.setData(SESSION_LINK_DROP_MIME, link);
- dataTransfer.setData('text/plain', sessionId);
return true;
}
+function installSessionDragPreview(dataTransfer: SplitGroupDragDataTransfer): () => void {
+ if (typeof document === 'undefined' || !dataTransfer.setDragImage) return () => undefined;
+
+ // Native drag images are captured by the OS for the whole gesture. Keep the
+ // captured image transparent so it never appears in Cindy or animates back
+ // to the source after an external drop; main owns the visible outside-window
+ // preview and can stop it synchronously on dragend/Escape.
+ const transparentPreview = document.createElement('canvas');
+ transparentPreview.width = 1;
+ transparentPreview.height = 1;
+ transparentPreview.dataset.sessionDragPreviewTransparent = 'true';
+ transparentPreview.style.cssText =
+ 'position:fixed;left:0;top:0;width:1px;height:1px;pointer-events:none;';
+ document.body?.appendChild(transparentPreview);
+ try {
+ dataTransfer.setDragImage(transparentPreview, 0, 0);
+ } catch {
+ // Some test doubles / older WebKit builds may reject a canvas drag image;
+ // the drag payload itself remains valid and main preview is independent.
+ }
+ return () => transparentPreview.remove();
+}
+
+/**
+ * Shared native drag-start policy for every task presentation (list/card/pinned).
+ * Sorting implementations may differ, but the task payload and the allowed
+ * drag-start surface must stay identical across those presentations.
+ */
+export function startSessionDrag(
+ event: SessionDragEventLike,
+ options: {
+ sessionId: string;
+ deviceId?: string | null;
+ enabled: boolean;
+ needsDedicatedHandle: boolean;
+ label?: string;
+ dragStartTarget?: Element | null;
+ },
+): boolean {
+ const currentTarget =
+ typeof Element !== 'undefined' && event.currentTarget instanceof Element
+ ? event.currentTarget
+ : null;
+ const target =
+ options.dragStartTarget ??
+ (typeof Element !== 'undefined' && event.target instanceof Element ? event.target : null);
+ const startedOnDedicatedHandle = Boolean(target?.closest(SPLIT_GROUP_DRAG_HANDLE_SELECTOR));
+ const startedOnInteractiveElement = Boolean(
+ target &&
+ currentTarget &&
+ target !== currentTarget &&
+ target.closest(SPLIT_GROUP_DRAG_INTERACTIVE_SELECTOR),
+ );
+
+ if (
+ !shouldStartSplitGroupDrag({
+ enabled: options.enabled,
+ needsDedicatedHandle: options.needsDedicatedHandle,
+ startedOnDedicatedHandle,
+ startedOnInteractiveElement,
+ }) ||
+ !writeSplitGroupSessionDragData(event.dataTransfer, options.sessionId, {
+ deviceId: options.deviceId,
+ })
+ ) {
+ event.preventDefault();
+ return false;
+ }
+
+ currentTarget?.setAttribute('data-session-dragging', 'true');
+ const dragImageCleanup = installSessionDragPreview(event.dataTransfer);
+ startTrackingSessionDrag(
+ options.label || options.sessionId,
+ options.sessionId,
+ options.deviceId,
+ dragImageCleanup,
+ () => {
+ finishSessionDrag({ currentTarget }, options.sessionId, options.deviceId);
+ },
+ );
+ return true;
+}
+
+/** Finish the shared native drag path and request the main-process outside drop check. */
+export function finishSessionDrag(
+ event: SessionDragEndEventLike,
+ sessionId: string,
+ deviceId?: string | null,
+): void {
+ const currentTarget =
+ typeof Element !== 'undefined' && event.currentTarget instanceof Element
+ ? event.currentTarget
+ : null;
+ const wasSessionDrag = currentTarget?.getAttribute('data-session-dragging') === 'true';
+ currentTarget?.removeAttribute('data-session-dragging');
+ const cancelled = stopTrackingSessionDrag();
+ if (!wasSessionDrag) return;
+ if (cancelled) return;
+
+ const openOutside = window.electronAPI?.maker?.openSessionInNewWindowIfDroppedOutside;
+ if (!openOutside) return;
+ void openOutside(sessionId, deviceId).catch(() => undefined);
+}
+
export function hasSplitGroupSessionType(types: ArrayLike<string>): boolean {
return Array.from(types).includes(SPLIT_GROUP_SESSION_MIME);
}
diff --git a/apps/desktop/src/renderer/lib/secondaryWindow.ts b/apps/desktop/src/renderer/lib/secondaryWindow.ts
index 6720a6742a..cbed91e652 100644
--- a/apps/desktop/src/renderer/lib/secondaryWindow.ts
+++ b/apps/desktop/src/renderer/lib/secondaryWindow.ts
@@ -18,7 +18,8 @@ export function isSecondaryWindow(): boolean {
/**
* 副窗口启动时要定位到的 sessionId(由 main/secondary-windows.ts 写进启动参数
- * `?bootSession=<id>`)。SecondaryWindowBootGate 读它,经 resolveSessionRoute 解析
+ * `?bootSession=<id>`,可选 `?bootDevice=<id>`)。SecondaryWindowBootGate 读它,经
+ * resolveSessionRoute 解析
* 出 canonical route(普通 / Orca lead / worker)后再 navigate,避免 main 端写死
* 单 session 路由导致 Orca 会话退化成单栏。
*
@@ -32,3 +33,13 @@ export function getBootSessionId(): string | null {
return null;
}
}
+
+/** Device-link origin carried by a task drag into a secondary window. */
+export function getBootDeviceId(): string | null {
+ try {
+ const id = new URLSearchParams(window.location.search).get('bootDevice');
+ return id && id.length > 0 ? id : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index a04c5a126b..79946dc4ad 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4719,7 +4719,18 @@ interface ElectronAPI {
) => Promise<import('../shared/modelPriceOverride').ModelPriceOverrideView>;
// 「在新窗口打开」会话多开
- openSessionInNewWindow: (sessionId: string) => Promise<void>;
+ openSessionInNewWindow: (sessionId: string, deviceId?: string | null) => Promise<void>;
+ openSessionInNewWindowIfDroppedOutside: (
+ sessionId: string,
+ deviceId?: string | null,
+ ) => Promise<boolean>;
+ beginSessionDragPreview: (
+ label: string,
+ sessionId: string,
+ deviceId: string | null | undefined,
+ palette: import('../shared/sessionDragPreview').SessionDragPreviewPalette,
+ ) => Promise<void>;
+ endSessionDragPreview: (dragEndAtMs?: number) => void;
// ── Palette `/` 命令三源 (palette refactor) ───────────────────────
listDesktopCommands: () => Promise<{
diff --git a/apps/desktop/src/shared/sessionDragPreview.ts b/apps/desktop/src/shared/sessionDragPreview.ts
new file mode 100644
index 0000000000..57c0108bc5
--- /dev/null
+++ b/apps/desktop/src/shared/sessionDragPreview.ts
@@ -0,0 +1,5 @@
+export interface SessionDragPreviewPalette {
+ surface: string;
+ border: string;
+ text: string;
+}