Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 新建任务继承当前任务的电脑 (#4572)

Dashc780a7b4aeae
diff --git a/apps/desktop/src/renderer/__tests__/genericNewMakerRouteState.test.ts b/apps/desktop/src/renderer/__tests__/genericNewMakerRouteState.test.ts
new file mode 100644
index 0000000000..217beea5d8
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/genericNewMakerRouteState.test.ts
@@ -0,0 +1,193 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const origins = new Map<string, string>();
+const localSessionIds = new Set<string>();
+const sshHosts = new Map<string, string>();
+type BotSession = { id: string; role: 'canonical' | 'history' };
+const botSessions = new Map<string, BotSession[]>();
+vi.mock('@/features/bots/botStore', () => ({
+ getBotProfiles: () => [...botSessions].map(([id, sessions]) => ({ id, sessions })),
+ canonicalBotSessionId: (bot: { sessions: BotSession[] }) => {
+ const canonical = bot.sessions.filter((row) => row.role === 'canonical');
+ return canonical.length === 1 ? canonical[0].id : undefined;
+ },
+}));
+vi.mock('@/lib/sessionsStore', () => ({
+ sessionsStore: {
+ findById: (id: string) =>
+ localSessionIds.has(id) ? { id, remoteHostId: sshHosts.get(id) ?? null } : null,
+ },
+}));
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ getSessionDeviceId: (id: string) => origins.get(id),
+ remoteProjectsStore: {
+ getDeviceList: () => [
+ { deviceId: 'computer-a', deviceName: 'Computer A', connected: false },
+ { deviceId: 'computer-b', deviceName: 'Computer B', connected: true },
+ ],
+ },
+}));
+
+import { __resetStickySessionOriginForTest } from '@/features/device-link/stickySessionOrigin';
+import { makeGenericNewMakerRouteState } from '@/features/cc-agent/lib/genericNewMakerRouteState';
+import {
+ consumeNewMakerDialogueTargetRequest,
+ readNewMakerDialogueTargetRequest,
+} from '@/features/cc-agent/lib/newMakerRouteState';
+
+beforeEach(() => {
+ origins.clear();
+ localSessionIds.clear();
+ sshHosts.clear();
+ botSessions.clear();
+ __resetStickySessionOriginForTest();
+});
+
+describe('new task inherits the current task computer', () => {
+ it.each([
+ '/cc-agent/task-a',
+ '/cc-agent/orca/task-a',
+ '/cc-agent/files/task-a',
+ '/bots/remote/computer-a/bot-a',
+ ])('inherits the task computer from %s, including an offline computer', (path) => {
+ origins.set('task-a', 'computer-a');
+ const state = makeGenericNewMakerRouteState(path);
+ expect(state.workspacePrompt).toBe('generic');
+ expect(readNewMakerDialogueTargetRequest(state)).toMatchObject({
+ deviceId: 'computer-a',
+ deviceName: 'Computer A',
+ preserveWorkspaceIfSameDevice: true,
+ });
+ });
+
+ it('follows the newly viewed task instead of the previous draft computer', () => {
+ origins.set('task-a', 'computer-a');
+ origins.set('task-b', 'computer-b');
+ makeGenericNewMakerRouteState('/cc-agent/task-a');
+ expect(
+ readNewMakerDialogueTargetRequest(makeGenericNewMakerRouteState('/cc-agent/task-b')),
+ ).toMatchObject({ deviceId: 'computer-b', deviceName: 'Computer B' });
+ });
+
+ it('returns to this computer from a local task', () => {
+ localSessionIds.add('local-task');
+ expect(
+ readNewMakerDialogueTargetRequest(makeGenericNewMakerRouteState('/cc-agent/local-task')),
+ ).toMatchObject({ deviceId: null, deviceName: null, preserveWorkspaceIfSameDevice: true });
+ });
+
+ it('inherits explicit remote bot ownership before the session list loads', () => {
+ expect(
+ readNewMakerDialogueTargetRequest(
+ makeGenericNewMakerRouteState('/bots/remote/computer-a/bot-a'),
+ ),
+ ).toMatchObject({ deviceId: 'computer-a' });
+ });
+
+ it('follows remote bot, local canonical bot, then local history navigation', () => {
+ botSessions.set('bot-local', [
+ { id: 'local-task', role: 'canonical' },
+ { id: 'old-task', role: 'history' },
+ ]);
+ expect(
+ readNewMakerDialogueTargetRequest(
+ makeGenericNewMakerRouteState('/bots/remote/computer-a/bot-a'),
+ ),
+ ).toMatchObject({ deviceId: 'computer-a' });
+ expect(
+ readNewMakerDialogueTargetRequest(makeGenericNewMakerRouteState('/bots/bot-local')),
+ ).toMatchObject({ deviceId: null });
+ // Production excludes source=bot from sessionsStore, even after loading.
+ expect(localSessionIds.size).toBe(0);
+ for (const path of ['/bots/bot-local/session/local-task', '/bots/bot-local/history/old-task']) {
+ expect(readNewMakerDialogueTargetRequest(makeGenericNewMakerRouteState(path))).toMatchObject({
+ deviceId: null,
+ });
+ }
+ });
+
+ it.each(['/cc-agent/task-a', '/cc-agent/orca/task-a', '/cc-agent/files/task-a'])(
+ 'uses execution provenance rather than cache presence on %s',
+ (path) => {
+ expect(makeGenericNewMakerRouteState(path)).toEqual({ workspacePrompt: 'generic' });
+ // Loaded SSH rows still belong to another host; keep the existing draft.
+ localSessionIds.add('task-a');
+ sshHosts.set('task-a', 'ssh-a');
+ expect(makeGenericNewMakerRouteState(path)).toEqual({ workspacePrompt: 'generic' });
+ sshHosts.delete('task-a');
+ expect(readNewMakerDialogueTargetRequest(makeGenericNewMakerRouteState(path))).toMatchObject({
+ deviceId: null,
+ });
+ // Bot-owned rows come from a separate projection, not the ordinary cache.
+ localSessionIds.clear();
+ botSessions.set('bot-a', [{ id: 'task-a', role: 'canonical' }]);
+ expect(readNewMakerDialogueTargetRequest(makeGenericNewMakerRouteState(path))).toMatchObject({
+ deviceId: null,
+ });
+ // Explicit SSH evidence must also win over a lingering Bot projection.
+ localSessionIds.add('task-a');
+ sshHosts.set('task-a', 'ssh-b');
+ expect(makeGenericNewMakerRouteState(path)).toEqual({ workspacePrompt: 'generic' });
+ },
+ );
+
+ it.each(['session', 'history'])('requires matching Bot ownership on a %s route', (kind) => {
+ const path = `/bots/bot-a/${kind}/task-a`;
+ localSessionIds.add('task-a');
+ origins.set('task-a', 'computer-a');
+ botSessions.set('bot-b', [{ id: 'task-a', role: 'canonical' }]);
+ botSessions.set('bot-a', []);
+ expect(makeGenericNewMakerRouteState(path)).toEqual({ workspacePrompt: 'generic' });
+ localSessionIds.clear();
+ origins.clear();
+ botSessions.set('bot-a', [
+ { id: 'task-a', role: kind === 'session' ? 'canonical' : 'history' },
+ ]);
+ expect(readNewMakerDialogueTargetRequest(makeGenericNewMakerRouteState(path))).toMatchObject({
+ deviceId: null,
+ });
+ botSessions.delete('bot-a');
+ expect(makeGenericNewMakerRouteState(path)).toEqual({ workspacePrompt: 'generic' });
+ });
+
+ it('keeps remote ownership during a reconnect instead of falling back locally', () => {
+ origins.set('task-a', 'computer-a');
+ makeGenericNewMakerRouteState('/cc-agent/task-a');
+ origins.clear();
+ expect(
+ readNewMakerDialogueTargetRequest(makeGenericNewMakerRouteState('/cc-agent/task-a')),
+ ).toMatchObject({ deviceId: 'computer-a' });
+ });
+
+ it('preserves the draft until a cold-start task origin is known', () => {
+ expect(makeGenericNewMakerRouteState('/cc-agent/task-a')).toEqual({
+ workspacePrompt: 'generic',
+ });
+ origins.set('task-a', 'computer-a');
+ expect(
+ readNewMakerDialogueTargetRequest(makeGenericNewMakerRouteState('/cc-agent/task-a')),
+ ).toMatchObject({ deviceId: 'computer-a' });
+ });
+
+ it.each([
+ '/cc-agent/new',
+ '/cc-agent/scheduled',
+ '/cc-agent/orca/new',
+ '/settings',
+ '/plugins',
+ '/bots',
+ '/bots/roster',
+ '/bots/remote',
+ '/bots/unknown',
+ '/bots/bot-a/direct/thread-a',
+ ])('preserves the draft when no task is active at %s', (path) => {
+ expect(makeGenericNewMakerRouteState(path)).toEqual({ workspacePrompt: 'generic' });
+ });
+
+ it('consumes the inherited target once so history does not override later user choices', () => {
+ origins.set('task-a', 'computer-a');
+ const state = makeGenericNewMakerRouteState('/cc-agent/task-a');
+ expect(consumeNewMakerDialogueTargetRequest(state)).toEqual({ workspacePrompt: 'generic' });
+ expect(readNewMakerDialogueTargetRequest(state)).not.toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/newMakerGenericCreatePreservesDraft.test.ts b/apps/desktop/src/renderer/__tests__/newMakerGenericCreatePreservesDraft.test.ts
index faf7674864..7e0b858f0c 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerGenericCreatePreservesDraft.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerGenericCreatePreservesDraft.test.ts
@@ -6,9 +6,8 @@
* 背景:草稿页(/cc-agent/new)的「对话或选择项目」选择由 newMakerDraft store
* 持久化。此前展开态 SidebarTopNav.handleNew 与折叠态 CCAgentSidebarUpper.handleNewCCS
* 都会先重置 newMakerDraft
- * 再 navigate,导致用户选好项目后切到别的会话、再点「新建」回来时选择被重置为默认、
- * 需要重新选。修复后这两个通用入口只 navigate、不清空;清空语义只保留在「新建对话」
- * 等显式入口(handleCreateDialogue)。
+ * 再 navigate,导致用户选好项目后切到别的会话、再点「新建」回来时选择被重置为默认。
+ * 通用入口通过导航请求继承当前任务电脑;同机保留项目,跨机由草稿页集中迁移。
*
* 静态扫描风格(renderer 测试环境无 jsdom),与 sidebarUpperSingleButton.test.ts 一致。
*/
@@ -41,6 +40,21 @@ function extractHandlerBlock(source: string, name: string): string {
}
describe('通用「新建」保留 newMakerDraft 选择', () => {
+ it('草稿保留与目标迁移共用包含 SSH 身份的同机判据', () => {
+ expect(draftRouteSource).toContain(
+ '!isSameNewMakerDevice(dialogueTargetRequest.deviceId, getDraft())',
+ );
+ expect(draftRouteSource).toContain(
+ 'const deviceChanged = !isSameNewMakerDevice(req.deviceId, {',
+ );
+ });
+ it('旋钮的新建站使用与侧栏相同的当前任务设备请求', () => {
+ const start = sidebarUpperSource.indexOf("if (target.kind === 'new-task')");
+ const block = sidebarUpperSource.slice(start, sidebarUpperSource.indexOf('return;', start));
+ expect(start).toBeGreaterThan(-1);
+ expect(block).toContain('state: makeGenericNewMakerRouteState(location.pathname)');
+ });
+
it('展开态 SidebarTopNav.handleNew 只 navigate、不清空 workingDir', () => {
const block = extractHandlerBlock(topNavSource, 'handleNew');
expect(block).toMatch(/navigate\(['`]\/cc-agent\/new['`]/);
@@ -52,7 +66,7 @@ describe('通用「新建」保留 newMakerDraft 选择', () => {
it('折叠态 CCAgentSidebarUpper.handleNewCCS 只 navigate、不清空 workingDir', () => {
const block = extractHandlerBlock(sidebarUpperSource, 'handleNewCCS');
expect(block).toMatch(
- /navigate\(['`]\/cc-agent\/new['`],\s*\{\s*state:\s*makeNewMakerRouteState\('generic'\)\s*\}\)/,
+ /navigate\(['`]\/cc-agent\/new['`],\s*\{\s*state:\s*makeGenericNewMakerRouteState\(location.pathname\)\s*\}\)/,
);
expect(block).not.toContain('workingDir: null');
});
@@ -76,7 +90,7 @@ describe('通用「新建」保留 newMakerDraft 选择', () => {
// 通用入口依旧不 patch store(前两条断言不受影响)。
it('NewMakerDraftRoute mount 时清空 extraDirs(引用目录不跨草稿保留)', () => {
expect(draftRouteSource).toContain(
- "if (getDraft().extraDirs.length > 0 || getDraft().writableDirs.length > 0) {",
+ 'if (getDraft().extraDirs.length > 0 || getDraft().writableDirs.length > 0) {',
);
});
});
diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
index 1643a58206..ed5bf67e27 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
@@ -214,7 +214,7 @@ describe('Shared create project picker', () => {
it('invalidates an in-flight folder restore before applying a same-route dialogue target', () => {
const effectStart = newMakerDraftRouteSource.indexOf(
- '// “对话”分组可能在 /cc-agent/new 已经打开时再次导航到同一路由',
+ 'handledDialogueTargetRequestRef.current = dialogueTargetRequest.requestId;',
);
const effectEnd = newMakerDraftRouteSource.indexOf(
'// 弹窗确认添加后的落点',
@@ -1310,7 +1310,8 @@ describe('Shared create project picker', () => {
);
const body = action.slice(0, action.indexOf(' patchDraft({'));
// 变化判据本身。
- expect(body).toContain('const deviceChanged = req.deviceId !== prevDeviceId;');
+ expect(body).toContain('const deviceChanged = !isSameNewMakerDevice(req.deviceId, {');
+ expect(body).toContain('remoteHostId: effectiveRemoteHostId,');
expect(body).toContain('const workingDirChanged = req.workingDir !== draft.workingDir;');
// mention chip 存**项目相对**路径 → 设备或项目任一变化都要剥(第 29 轮 P1)。
expect(body).toContain(
@@ -1327,6 +1328,7 @@ describe('Shared create project picker', () => {
// 判据读 draft.workingDir,必须在依赖数组里,否则闭包比的是上一次渲染的值。
const deps = action.slice(action.indexOf(' [', action.indexOf('patchDraft({')));
expect(deps.slice(0, deps.indexOf(' );'))).toContain('draft.workingDir,');
+ expect(deps.slice(0, deps.indexOf(' );'))).toContain('effectiveRemoteHostId,');
});
// #807 review 第十九轮:被控端能力 / 供应商 / Git safety 快照是「拉一次、无 TTL、只在设备下线
diff --git a/apps/desktop/src/renderer/__tests__/newMakerRouteState.test.ts b/apps/desktop/src/renderer/__tests__/newMakerRouteState.test.ts
index db3b650943..3b144e8a80 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerRouteState.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerRouteState.test.ts
@@ -5,10 +5,57 @@ import {
consumeNewMakerFolderPickerRequest,
makeDialogueNewMakerRouteState,
makeFolderPickerNewMakerRouteState,
+ isSameNewMakerDevice,
readNewMakerDialogueTargetRequest,
readNewMakerFolderPickerRequest,
} from '@/features/cc-agent/lib/newMakerRouteState';
+describe('new maker execution device identity', () => {
+ it.each([
+ {
+ label: 'local',
+ deviceLinkDeviceId: null,
+ remoteHostId: null,
+ expected: [true, false, false],
+ },
+ {
+ label: 'remote A',
+ deviceLinkDeviceId: 'a',
+ remoteHostId: null,
+ expected: [false, true, false],
+ },
+ {
+ label: 'remote B',
+ deviceLinkDeviceId: 'b',
+ remoteHostId: null,
+ expected: [false, false, true],
+ },
+ {
+ label: 'SSH',
+ deviceLinkDeviceId: null,
+ remoteHostId: 'ssh-a',
+ expected: [false, false, false],
+ },
+ ])('preserves only the matching execution target for $label drafts', ({ expected, ...draft }) => {
+ expect([null, 'a', 'b'].map((deviceId) => isSameNewMakerDevice(deviceId, draft))).toEqual(
+ expected,
+ );
+ });
+
+ it('distinguishes SSH and local even when a folder path is reused', () => {
+ const draft = {
+ deviceLinkDeviceId: null,
+ remoteHostId: 'ssh-a' as string | null,
+ workingDir: '/project',
+ };
+ expect(isSameNewMakerDevice(null, draft)).toBe(false);
+ draft.remoteHostId = null;
+ expect(isSameNewMakerDevice(null, draft)).toBe(true);
+ draft.remoteHostId = 'ssh-b';
+ expect(isSameNewMakerDevice(null, draft)).toBe(false);
+ });
+});
+
describe('new maker dialogue route target request', () => {
it('encodes remote and local dialogue targets', () => {
vi.spyOn(Date, 'now').mockReturnValue(1234);
diff --git a/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts b/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts
index 2c9f552fee..b14a52563e 100644
--- a/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts
@@ -32,7 +32,7 @@ describe('sidebar 顶部 + New 单按钮(delayed-create)', () => {
it("通用新建进入 /cc-agent/new,并带 generic workspace 提示", () => {
// sidebar 重构后 expanded 态的“+ New”上移到 shell 的 SidebarTopNav;
// CCAgentSidebarUpper 内只剩 CollapsedView(rail 态)自带的 handleNewCCS 一处。
- const matches = sidebarSource.match(/navigate\(['`]\/cc-agent\/new['`],\s*\{\s*state:\s*makeNewMakerRouteState\('generic'\)\s*\}\)/g);
+ const matches = sidebarSource.match(/navigate\(['`]\/cc-agent\/new['`],\s*\{\s*state:\s*makeGenericNewMakerRouteState\(location.pathname\)\s*\}\)/g);
expect(matches).not.toBeNull();
expect(matches!.length).toBeGreaterThanOrEqual(1);
expect(sidebarSource).toContain("function makeNewMakerRouteState(workspacePrompt: 'generic' | 'dialogue')");
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 04a90dab99..6667bb3501 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -97,6 +97,7 @@ import {
} from '@/features/right-sidebar/lib/sidebarCommands';
import { requestSessionSwitch } from '@/features/cc-agent/lib/sessionSwitchCommands';
import { makeFolderPickerNewMakerRouteState } from '@/features/cc-agent/lib/newMakerRouteState';
+import { makeGenericNewMakerRouteState } from '@/features/cc-agent/lib/genericNewMakerRouteState';
import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { getBotProfiles } from '@/features/bots/botStore';
import { botRouteForOwnedSession } from '@/features/bots/botSessionOwners';
@@ -1035,7 +1036,9 @@ export function MainLayout() {
return;
}
applicationMenuLog.info('new-maker shortcut invoked, navigating to /cc-agent/new');
- navigate('/cc-agent/new');
+ navigate('/cc-agent/new', {
+ state: makeGenericNewMakerRouteState(currentPathRef.current.split('?')[0]),
+ });
})
.catch((err: unknown) => {
applicationMenuLog.warn('new-maker shortcut routing failed', err);
@@ -1076,11 +1079,11 @@ export function MainLayout() {
navigate('/issues');
break;
case 'new-maker':
- // 等价于 CCAgentSidebarUpper.handleNewCCS (sidebar 顶部 "+ New Maker" 按钮):
- // 单步 navigate 到 /cc-agent/new, draft 状态由 NewMakerDraftRoute 自己读取。
- // 不重置 workingDir —— sidebar 按钮也不重置, 保留用户上次的目录上下文。
+ // 与侧栏同口径:继承当前任务电脑,同机保留草稿项目。
applicationMenuLog.info('new-maker invoked, navigating to /cc-agent/new');
- navigate('/cc-agent/new');
+ navigate('/cc-agent/new', {
+ state: makeGenericNewMakerRouteState(currentPathRef.current.split('?')[0]),
+ });
break;
case 'new-maker-shortcut':
handleNewMakerShortcut();
@@ -1187,7 +1190,9 @@ export function MainLayout() {
if (action.type !== 'command') return false;
switch (action.commandId) {
case 'newTask':
- navigate('/cc-agent/new');
+ navigate('/cc-agent/new', {
+ state: makeGenericNewMakerRouteState(currentPathRef.current.split('?')[0]),
+ });
return true;
case 'settings':
navigate('/settings?tab=shortcuts');
diff --git a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
index e7de416661..bd55c5f839 100644
--- a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx
@@ -34,6 +34,7 @@ import { SidebarInlineSearch } from '@/features/cc-agent/sidebar/SidebarInlineSe
import { SidebarIconButton } from './SidebarIconButton';
import { useConversationSearchContext } from '@/features/cc-agent/sidebar/conversationSearchContext';
import { GhostMainViewNavEntries } from './GhostMainViewNavEntries';
+import { makeGenericNewMakerRouteState } from '@/features/cc-agent/lib/genericNewMakerRouteState';
/** 列表行通用样式 —— 各行同款 pill 行。 */
const ROW_CLASS =
@@ -71,13 +72,9 @@ export function SidebarTopNav({
// 呼吸留给单条卡片;见 AttentionDot 头部的形态规范)。
const hasGhostUnread = useAnyGhostUnread();
- // 通用「新建」入口:只 navigate 到草稿页,不清空 newMakerDraft。
- // 之前这里会把 workingDir / remoteHostId / extraDirs 清成默认,导致用户在草稿页
- // 选好「对话或选择项目」后,切到别的会话再点「新建」回来时选择被重置为默认、需要
- // 重新选。草稿页的选择由 newMakerDraft store 持久化(见 state/newMakerDraft.ts),
- // 通用新建应保留上次选择;「新建对话」等显式入口才负责清空(见 CCAgentSidebarUpper)。
+ // 通用新建继承当前任务的电脑,由草稿页集中迁移;同机保留已选项目。
const handleNew = () => {
- navigate('/cc-agent/new', { state: { workspacePrompt: 'generic' } });
+ navigate('/cc-agent/new', { state: makeGenericNewMakerRouteState(location.pathname) });
};
// 搜索结果 overlay 只在 cc-agent 视图(CCAgentSidebarUpper)绘制;本行却在所有非 rail 视图都渲染。
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index c319f2f792..61fe01cfa4 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -42,7 +42,7 @@ import {
Trash2,
X,
} from 'lucide-react';
-import { useNavigate, useMatch } from 'react-router-dom';
+import { useNavigate, useMatch, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
@@ -284,6 +284,7 @@ import {
} from '@/features/scheduler/hooks/useDeleteScheduleWithSessions';
import { resolveDialogueDeviceTarget, type DialogueDeviceTarget } from './lib/dialogueCreateTarget';
import { makeDialogueNewMakerRouteState } from './lib/newMakerRouteState';
+import { makeGenericNewMakerRouteState } from './lib/genericNewMakerRouteState';
const log = createLogger('CCAgentSidebarUpper');
// perf-baseline(与 MessageStream 的 perf/session-switch 探针同通道):
@@ -826,6 +827,7 @@ function ExpandedView({
persistentLocalProjects,
}: ExpandedProps) {
const { t, i18n } = useTranslation();
+ const location = useLocation();
const localPlatform = window.electronAPI.platform;
const { sessions, refreshSessions, patchLocal, effectiveIncludeArchived } = sessionsHook;
const {
@@ -2257,13 +2259,13 @@ function ExpandedView({
const target = pickAdjacentSessionId(visibleIds, activeId, direction);
if (!target) return;
if (target.kind === 'new-task') {
- navigate('/cc-agent/new');
+ navigate('/cc-agent/new', { state: makeGenericNewMakerRouteState(location.pathname) });
return;
}
// 同样复用行点击唯一入口,继承清通知 / 同对话去重 / Orca 角色路由。
void handleSessionClick(target.sessionId);
});
- }, [handleSessionClick, navigate, sessionSwitchEnabled]);
+ }, [handleSessionClick, location.pathname, navigate, sessionSwitchEnabled]);
useAppShortcut('switch-session-1', () => handleSwitchSessionSlot(0), {
enabled: sessionSwitchEnabled,
@@ -3807,6 +3809,7 @@ function CollapsedView({
manualPinnedOrder,
onReorderPinned,
}: CollapsedProps) {
+ const location = useLocation();
const isCollapsed = useSidebarCollapsedState();
const projectFilterRequest = useConversationSearchRequest();
const selectedMachineId = useEffectiveSelectedMachineId();
@@ -3827,13 +3830,10 @@ function CollapsedView({
// 让"失败的定时任务"落到默认绿色 done tone(否则和 SessionItem 不一致,
// 折叠视图会把失败误传成"完成了")。
const urgentSet = useSessionAttentionUrgencySet();
- // delayed-create:与 ExpandedView 同——单按钮 navigate transient draft 单例。
- // 与展开态 SidebarTopNav 的通用「新建」同口径:只 navigate,不清空 newMakerDraft,
- // 保留用户上次在草稿页选好的「对话或选择项目」(切走再回来不重置);清空语义只属于
- // 「新建对话」等显式入口(handleCreateDialogue)。
+ // 与展开态同口径:继承当前任务的电脑,同机保留草稿项目。
const handleNewCCS = useCallback(() => {
- navigate('/cc-agent/new', { state: makeNewMakerRouteState('generic') });
- }, [navigate]);
+ navigate('/cc-agent/new', { state: makeGenericNewMakerRouteState(location.pathname) });
+ }, [location.pathname, navigate]);
const handleNavScheduled = useCallback(() => {
navigate('/cc-agent/scheduled');
}, [navigate]);
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index bf99284c94..18c8c30b7f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -156,6 +156,7 @@ import { crossAgentConvertService } from '@/lib/crossAgentConvertService';
import {
consumeNewMakerDialogueTargetRequest,
consumeNewMakerFolderPickerRequest,
+ isSameNewMakerDevice,
readNewMakerDialogueTargetRequest,
readNewMakerFolderPickerRequest,
} from './lib/newMakerRouteState';
@@ -2139,8 +2140,10 @@ export function NewMakerDraftRoute() {
*/
const applyDraftTarget = useCallback(
(req: DraftTargetRequest) => {
- const prevDeviceId = effectiveDeviceLinkDeviceId ?? null;
- const deviceChanged = req.deviceId !== prevDeviceId;
+ const deviceChanged = !isSameNewMakerDevice(req.deviceId, {
+ deviceLinkDeviceId: effectiveDeviceLinkDeviceId,
+ remoteHostId: effectiveRemoteHostId,
+ });
const workingDirChanged = req.workingDir !== draft.workingDir;
// chip 绑 workingDir;附件绑设备。两者条件不同,见各自函数的注释。
@@ -2264,6 +2267,7 @@ export function NewMakerDraftRoute() {
},
[
effectiveDeviceLinkDeviceId,
+ effectiveRemoteHostId,
draft.workingDir,
capabilityAgentKind,
stripProjectRelativeMentions,
@@ -2271,7 +2275,7 @@ export function NewMakerDraftRoute() {
],
);
- // “对话”分组可能在 /cc-agent/new 已经打开时再次导航到同一路由,组件不会 remount。
+ // 通用新建继承当前任务电脑;“对话”分组还可能在 /cc-agent/new 已经打开时再次导航。
// 目标因此随 location.state 交给本页消费,而不是让侧栏直接 patch device 字段;无论首次进入
// 还是重复导航,local ↔ remote / remote A ↔ B / 项目 → 对话都统一经过 applyDraftTarget,
// mention、路径型附件、远程运行配置和 worktree 三态才不会绕过集中迁移。
@@ -2286,12 +2290,17 @@ export function NewMakerDraftRoute() {
// 同路由的对话目标是比在途目录恢复更新的用户选择。先推进同一 sequence owner,
// 让旧 restore completion 只能释放锁,不能把目录重新写回草稿。
modePickerSelectionSeqRef.current += 1;
- patchCollab({ enabled: false });
- applyDraftTarget({
- deviceId: dialogueTargetRequest.deviceId,
- deviceName: dialogueTargetRequest.deviceName,
- workingDir: null,
- });
+ if (
+ !dialogueTargetRequest.preserveWorkspaceIfSameDevice ||
+ !isSameNewMakerDevice(dialogueTargetRequest.deviceId, getDraft())
+ ) {
+ patchCollab({ enabled: false });
+ applyDraftTarget({
+ deviceId: dialogueTargetRequest.deviceId,
+ deviceName: dialogueTargetRequest.deviceName,
+ workingDir: null,
+ });
+ }
navigate(`${location.pathname}${location.search}${location.hash}`, {
replace: true,
state: consumeNewMakerDialogueTargetRequest(location.state),
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/genericNewMakerRouteState.ts b/apps/desktop/src/renderer/features/cc-agent/lib/genericNewMakerRouteState.ts
new file mode 100644
index 0000000000..708ebe8ce5
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/genericNewMakerRouteState.ts
@@ -0,0 +1,66 @@
+import { matchPath } from 'react-router-dom';
+import { resolveAgentIslandVisibleSessionIdFromPath } from '@/lib/agentIslandVisibleSessionRoute';
+import { sessionsStore } from '@/lib/sessionsStore';
+import { canonicalBotSessionId, getBotProfiles } from '@/features/bots/botStore';
+import { findBotProfileForSession } from '@/features/bots/botSessionOwners';
+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { makeDialogueNewMakerRouteState, type NewMakerRouteState } from './newMakerRouteState';
+
+/** undefined preserves the draft; null is affirmative evidence of local execution. */
+function resolveCurrentTaskDevice(pathname: string): string | null | undefined {
+ const remoteBot = matchPath('/bots/remote/:deviceId/:botId', pathname);
+ if (remoteBot) return remoteBot.params.deviceId;
+
+ const botTask =
+ matchPath('/bots/:botId/session/:sessionId', pathname) ??
+ matchPath('/bots/:botId/history/:sessionId', pathname);
+ const botId = (botTask ?? matchPath('/bots/:botId', pathname))?.params.botId;
+ if (botId) {
+ if (botId === 'roster' || botId === 'remote') return undefined;
+ const bot = getBotProfiles().find((profile) => profile.id === botId);
+ if (!bot) return undefined;
+ const sessionId = botTask?.params.sessionId ?? canonicalBotSessionId(bot);
+ if (!sessionId || !findBotProfileForSession([bot], sessionId)) return undefined;
+ return sessionsStore.findById(sessionId)?.remoteHostId ? undefined : null;
+ }
+
+ const sessionId =
+ resolveAgentIslandVisibleSessionIdFromPath(pathname) ??
+ matchPath('/cc-agent/orca/:sessionId', pathname)?.params.sessionId ??
+ matchPath('/cc-agent/files/:sessionId', pathname)?.params.sessionId;
+ if (!sessionId || sessionId === 'new') return undefined;
+
+ const deviceId = getStickySessionDeviceId(sessionId);
+ if (deviceId) return deviceId;
+ // The ordinary cache includes SSH rows but excludes Bot rows. Neither a
+ // cache hit nor a miss alone proves the task runs on this computer.
+ const session = sessionsStore.findById(sessionId);
+ if (session?.remoteHostId) return undefined;
+ if (session || findBotProfileForSession(getBotProfiles(), sessionId)) return null;
+ return undefined;
+}
+
+/** Capture the current task's computer at the new-task action, before leaving its route. */
+export function makeGenericNewMakerRouteState(pathname: string): NewMakerRouteState {
+ const deviceId = resolveCurrentTaskDevice(pathname);
+ if (deviceId === undefined) return { workspacePrompt: 'generic' };
+ const state = makeDialogueNewMakerRouteState(
+ deviceId
+ ? {
+ deviceId,
+ deviceName:
+ remoteProjectsStore.getDeviceList().find((device) => device.deviceId === deviceId)
+ ?.deviceName ?? deviceId,
+ }
+ : null,
+ );
+ return {
+ ...state,
+ workspacePrompt: 'generic',
+ dialogueTargetRequest: {
+ ...state.dialogueTargetRequest,
+ preserveWorkspaceIfSameDevice: true,
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/newMakerRouteState.ts b/apps/desktop/src/renderer/features/cc-agent/lib/newMakerRouteState.ts
index b405a37820..b0a1ddf303 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/newMakerRouteState.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/newMakerRouteState.ts
@@ -4,6 +4,8 @@ export interface NewMakerDialogueTargetRequest {
requestId: string;
deviceId: string | null;
deviceName: string | null;
+ /** 通用新建只继承电脑;同机时保留草稿项目及用户选择。 */
+ preserveWorkspaceIfSameDevice?: boolean;
}
export interface NewMakerFolderPickerRequest {
@@ -19,13 +21,21 @@ export interface NewMakerRouteState {
let dialogueTargetRequestSequence = 0;
let folderPickerRequestSequence = 0;
+/** These requests select local/device-link execution, never an SSH workspace. */
+export function isSameNewMakerDevice(
+ deviceId: string | null,
+ draft: { deviceLinkDeviceId?: string | null; remoteHostId?: string | null },
+): boolean {
+ return !draft.remoteHostId && deviceId === (draft.deviceLinkDeviceId ?? null);
+}
+
/**
* “对话”分组每次点击都生成新 requestId。同路由重复 navigate 不会 remount 创建页,
* 但 location.state 会更新,创建页可据此再次执行完整 target transition。
*/
export function makeDialogueNewMakerRouteState(
target: DialogueDeviceTarget | null,
-): NewMakerRouteState {
+): NewMakerRouteState & { dialogueTargetRequest: NewMakerDialogueTargetRequest } {
dialogueTargetRequestSequence += 1;
return {
workspacePrompt: 'dialogue',
@@ -47,7 +57,9 @@ export function makeFolderPickerNewMakerRouteState(): NewMakerRouteState {
};
}
-export function readNewMakerFolderPickerRequest(state: unknown): NewMakerFolderPickerRequest | null {
+export function readNewMakerFolderPickerRequest(
+ state: unknown,
+): NewMakerFolderPickerRequest | null {
if (!state || typeof state !== 'object') return null;
const request = (state as Record<string, unknown>).folderPickerRequest;
if (!request || typeof request !== 'object') return null;
@@ -76,7 +88,14 @@ export function readNewMakerDialogueTargetRequest(
if (deviceId !== null && (typeof deviceId !== 'string' || deviceId.length === 0)) return null;
if (deviceName !== null && typeof deviceName !== 'string') return null;
if (deviceId === null && deviceName !== null) return null;
- return { requestId: record.requestId, deviceId, deviceName };
+ return {
+ requestId: record.requestId,
+ deviceId,
+ deviceName,
+ ...(record.preserveWorkspaceIfSameDevice === true
+ ? { preserveWorkspaceIfSameDevice: true }
+ : {}),
+ };
}
/**