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): 本机新建发送后切走不再丢掉首条消息 (#3550)

Dashb5e0e9261a93
diff --git a/apps/desktop/src/renderer/__tests__/newMakerLocalFirstMessageSend.test.ts b/apps/desktop/src/renderer/__tests__/newMakerLocalFirstMessageSend.test.ts
new file mode 100644
index 0000000000..ffc8262a80
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/newMakerLocalFirstMessageSend.test.ts
@@ -0,0 +1,115 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const source = readFileSync(
+ resolve(__dirname, '..', 'features', 'cc-agent', 'NewMakerDraftRoute.tsx'),
+ 'utf8',
+);
+
+const pendingSource = readFileSync(
+ resolve(__dirname, '..', 'state', 'pendingFirstMessage.ts'),
+ 'utf8',
+);
+
+const sessionViewSource = readFileSync(
+ resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSessionView.tsx'),
+ 'utf8',
+);
+
+describe('NewMakerDraftRoute local first-message send', () => {
+ const localFence = source.indexOf(
+ '本机首条消息在草稿路由发出,不把发送绑在 SessionView hydrate 上。',
+ );
+
+ it('sends the local first message from the draft route before navigating', () => {
+ const sendMessage = source.indexOf(
+ 'const sendPromise = makerChatStore.sendMessage(',
+ localFence,
+ );
+ const navigate = source.indexOf('navigateToSession();', sendMessage);
+
+ expect(localFence).toBeGreaterThan(-1);
+ expect(sendMessage).toBeGreaterThan(localFence);
+ expect(navigate).toBeGreaterThan(sendMessage);
+ });
+
+ it('seeds remoteHostId into chat store before the draft-route first send', () => {
+ const seed = source.indexOf(
+ 'makerChatStore.setSessionRuntime(newSession.id, {',
+ source.indexOf("workspaceKind: workingDir ? 'project' : 'dialogue'"),
+ );
+ const seedBlock = source.slice(seed, source.indexOf('});', seed) + 3);
+
+ expect(seed).toBeGreaterThan(-1);
+ expect(seed).toBeLessThan(localFence);
+ expect(seedBlock).toContain('remoteHostId: workingDir ? (effectiveRemoteHostId ?? null) : null');
+ });
+
+ it('does not register a memory-only pending payload for ordinary local text', () => {
+ const localSend = source.indexOf('const sendPromise = makerChatStore.sendMessage(', localFence);
+ const pendingAfterSend = source.indexOf('setPending(newSession.id', localSend);
+ expect(source).toContain('setPending(remoteSessionId, {');
+ expect(pendingSource).toContain(
+ '本机新建的普通文本不走这里:草稿路由 createSession 后直接 sendMessage',
+ );
+ expect(pendingAfterSend).toBe(-1);
+ });
+
+ it('restores a rejected or thrown first send onto the created task without clobbering newer input', () => {
+ const localSend = source.indexOf('const sendWorkingDir = workingDir ?? newSession.workingDir;');
+ const restore = source.indexOf('const restoreFirstMessageDraft = () => {', localSend);
+ const fifoRestore = source.indexOf('restoreRemoteOptimisticDraft(newSession.id, {', restore);
+ const saveDraft = source.indexOf('saveComposerDraft(newSession.id, {', restore);
+ const catchRestore = source.indexOf(
+ 'restoreFirstMessageDraft();',
+ source.indexOf("log.error('[draft send]', err);", localFence),
+ );
+ const falseRestore = source.indexOf(
+ 'restoreFirstMessageDraft();',
+ source.indexOf('} else {', source.indexOf('(accepted) => {', localFence)),
+ );
+
+ expect(restore).toBeGreaterThan(localSend);
+ expect(fifoRestore).toBeGreaterThan(restore);
+ expect(fifoRestore).toBeLessThan(catchRestore);
+ expect(saveDraft).toBe(-1);
+ expect(source.slice(localSend, fifoRestore)).toContain(
+ 'rewriteBrowserCommentsFromRehomedFiles(',
+ );
+ expect(source.slice(fifoRestore, catchRestore)).toContain(
+ 'excludeCommentScreenshots(rehydratedFiles, preNavBrowserComments)',
+ );
+ expect(source.slice(fifoRestore, catchRestore)).toContain(
+ 'browserComments: preNavBrowserComments',
+ );
+ expect(source.slice(fifoRestore, catchRestore)).not.toContain('browserComments: []');
+ expect(catchRestore).toBeGreaterThan(fifoRestore);
+ expect(falseRestore).toBeGreaterThan(fifoRestore);
+ expect(falseRestore).not.toBe(catchRestore);
+ });
+
+ it('hands slash-looking first messages to SessionView instead of copying desktop dispatch', () => {
+ const slashMatch = source.indexOf('const slashMatch = message.match(', localFence);
+ const leading = source.indexOf('leadingSlashInvocation(message)', slashMatch);
+ const pendingHandoff = source.indexOf('setPending(newSession.id, {', slashMatch);
+ const sendPromise = source.indexOf(
+ 'const sendPromise = makerChatStore.sendMessage(',
+ localFence,
+ );
+ const reviewStart = source.indexOf('window.electronAPI.maker.startReview({', localFence);
+
+ expect(slashMatch).toBeGreaterThan(localFence);
+ expect(leading).toBeGreaterThan(slashMatch);
+ expect(leading).toBeLessThan(pendingHandoff);
+ expect(pendingHandoff).toBeGreaterThan(slashMatch);
+ expect(pendingHandoff).toBeLessThan(sendPromise);
+ expect(reviewStart).toBe(-1);
+ expect(source.slice(slashMatch, pendingHandoff)).toContain("capabilityAgentKind === 'pi'");
+ expect(sessionViewSource).toContain('const pending = consumePending(sessionId);');
+ expect(sessionViewSource).toContain('maybeDispatchDesktopSlashCommand');
+ expect(sessionViewSource).toContain('leadingSlashInvocation(message)');
+ expect(sessionViewSource).toContain('本机普通文本已在草稿路由发出');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
index ef9f67278d..770501973c 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
@@ -89,6 +89,15 @@ describe('NewMakerDraftRoute worktree send flow', () => {
expect(restoreHelper).toBeGreaterThan(-1);
expect(saveDraft).toBeGreaterThan(failedCard);
expect(restoreText).toBeGreaterThan(restoreHelper);
+ expect(source.slice(restoreHelper, restoreHelper + 500)).toContain(
+ 'browserComments: rehomedComments',
+ );
+ expect(source.slice(restoreHelper, failedCard)).toContain(
+ 'rewriteBrowserCommentsFromRehomedFiles(',
+ );
+ expect(source.slice(restoreHelper, failedCard)).toContain(
+ 'excludeCommentScreenshots(rehomedFiles, rehomedComments)',
+ );
});
it('does not make the new worktree path the next New Maker default project', () => {
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index f87128a281..cbfda6d2b2 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -3730,9 +3730,10 @@ export function CCAgentSessionView({
[sessionId, t],
);
- // delayed-create:从 NewMakerDraftRoute 经 navigate 进来的首条消息,在 session
- // 完全 hydrate(historyLoaded + workingDir 就位)后自动 sendMessage。
- // 一次性消费 + ref guard,防 StrictMode 双 mount / 重渲染时重复发送。
+ // delayed-create:device-link / 远程草稿,以及本机斜杠命令首条(含 Pi 空白前缀),把内容登记在
+ // pending 里,等 session 完全 hydrate 后再由 maybeDispatchDesktopSlashCommand /
+ // sendMessage 消费。本机普通文本已在草稿路由发出。一次性消费 + ref guard,防
+ // StrictMode 双 mount / 重渲染时重复发送。
const pendingConsumedRef = useRef(false);
useEffect(() => {
if (!sessionId || !historyLoaded || !session) return;
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index ba0b9b2acf..70b4f1ac9b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -17,10 +17,14 @@
* 6. 用户按 Send:
* a. vendorAuthGate.checkAndConfirm(vendor)
* - 未就绪 → 弹通用 confirmDialog → 跳 settings → 中止
- * b. 普通路径: createSession → setPending → navigate → SessionView 自动发送
+ * b. 本机普通路径: createSession → sendMessage → navigate。首条消息在草稿
+ * 路由发出,不把发送绑在 SessionView hydrate 上;切走只换画面。
+ * SessionView 会当成斜杠命令的首条(列首 /cmd,以及 Pi 空白前缀)仍 setPending。
* c. Worktree 路径: 先 createSession + 插入状态卡 + navigate,再后台
* createWorktree;成功后更新 workingDir 并发送首条消息,失败则把原消息
* 存回该 session 的 composer draft 供用户重试
+ * d. device-link 远程路径仍走 setPending → SessionView 消费(对端开协同
+ * 可能要等隧道,不能挡在 navigate 前面)
*
* 文本/附件持久化:
* - vendor / workingDir / lastByVendor → localStorage 跨重启保留
@@ -124,6 +128,7 @@ import {
getDraft as getComposerDraft,
plainTextToTiptapDoc,
quickStartTextToTiptapDoc,
+ restoreRemoteOptimisticDraft,
saveDraft as saveComposerDraft,
} from '@/lib/composerDraftStore';
import type { JSONContent } from '@tiptap/core';
@@ -144,6 +149,7 @@ import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageClean
import type { GoalLimitValues } from '@/components/new-chat/GoalAdvancedLimits';
import { makerChatStore } from '@/lib/makerChatStore';
import {
+ leadingSlashInvocation,
rebaseInlineRangesAfterSlashCommandRewrite,
rewritePiSkillMessageForSend,
} from '@/lib/slashCommands';
@@ -568,6 +574,41 @@ async function rehomeDraftAttachments(
return rehomed;
}
+async function rehomeDraftBrowserComments<T extends { screenshot: AttachedFile }>(
+ comments: T[] | undefined,
+ sessionId: string,
+): Promise<T[] | undefined> {
+ if (!comments || comments.length === 0) return comments;
+ return Promise.all(
+ comments.map(async (comment) => {
+ const rehomed = await rehomeDraftAttachments([comment.screenshot], sessionId);
+ return rehomed?.[0] ? { ...comment, screenshot: rehomed[0] } : comment;
+ }),
+ );
+}
+
+function rewriteBrowserCommentsFromRehomedFiles<T extends { screenshot: AttachedFile }>(
+ comments: T[] | undefined,
+ rehomedFiles: AttachedFile[] | undefined,
+): T[] {
+ if (!comments?.length) return comments ?? [];
+ const byId = new Map((rehomedFiles ?? []).map((file) => [file.id, file]));
+ return comments.map((comment) => {
+ const screenshot = byId.get(comment.screenshot.id);
+ return screenshot ? { ...comment, screenshot } : comment;
+ });
+}
+
+function excludeCommentScreenshots(
+ files: AttachedFile[] | undefined,
+ comments: readonly { screenshot: AttachedFile }[],
+): AttachedFile[] {
+ if (!files?.length) return files ?? [];
+ if (comments.length === 0) return files;
+ const commentIds = new Set(comments.map((comment) => comment.screenshot.id));
+ return files.filter((file) => !commentIds.has(file.id));
+}
+
function getCurrentRoutePath(): string {
const raw =
window.location.hash.startsWith('#') && window.location.hash.length > 1
@@ -2469,6 +2510,7 @@ export function NewMakerDraftRoute() {
agentKind: dbToMakerAgentKind(draftVendor),
fastMode: sshFastMode,
planModeEnabled: effectivePlanMode,
+ remoteHostId: target.hostId,
});
// 把草稿页已输入的文本/附件移交到新会话,避免 navigate 后丢失。
// rehomeDraftAttachments 把 base64 和 xdt-image://__new_maker_draft__/ 迁移到
@@ -2483,15 +2525,10 @@ export function NewMakerDraftRoute() {
existingDraft.attachments.filter((attachment) => attachment.category !== 'image'),
);
const rehomedAttachments = await rehomeDraftAttachments(imageOnly, newSession.id);
- let rehomedComments = existingDraft.browserComments;
- if (rehomedComments && rehomedComments.length > 0) {
- rehomedComments = await Promise.all(
- rehomedComments.map(async (c) => {
- const rehomed = await rehomeDraftAttachments([c.screenshot], newSession.id);
- return rehomed?.[0] ? { ...c, screenshot: rehomed[0] } : c;
- }),
- );
- }
+ const rehomedComments = await rehomeDraftBrowserComments(
+ existingDraft.browserComments,
+ newSession.id,
+ );
// SSH 环境下本地 @file/@dir mention 无效,从 Tiptap 文档中剥离。
const strippedText = existingDraft.text
? stripLocalMentionChips(existingDraft.text)
@@ -3896,6 +3933,7 @@ export function NewMakerDraftRoute() {
agentKind: persistedAgentKind === 'cc' ? 'claude-code' : persistedAgentKind,
fastMode: effectiveFastMode,
planModeEnabled: effectivePlanMode,
+ remoteHostId: effectiveRemoteHostId ?? null,
});
worktreeCreationStore.set(newSession.id, {
status: 'creating',
@@ -3908,7 +3946,9 @@ export function NewMakerDraftRoute() {
// 不会暴露 cleared 后的视觉状态。clearFiles 仍然在 React 提交 unmount cleanup
// 之前同步执行,所以 useAttachments 的 cleanup 不会把刚送出去的附件回写到 store。
// 保存原始 doc JSON(含 quickStartPill 等 mark),供 worktree 失败恢复时原样还原。
- const preNavDraftDoc = getComposerDraft(NEW_MAKER_DRAFT_KEY)?.text ?? null;
+ const preNavDraft = getComposerDraft(NEW_MAKER_DRAFT_KEY);
+ const preNavDraftDoc = preNavDraft?.text ?? null;
+ const preNavBrowserComments = preNavDraft?.browserComments ?? [];
navigate(`/cc-agent/${newSession.id}`, { replace: true });
// clearDraftAndNotify (not bare clear): onSend returned false above
// so ChatInput never cleared its editor — without notifying it, the
@@ -3924,10 +3964,12 @@ export function NewMakerDraftRoute() {
// 真实会话消息(删会话清不到)。初始值取原 files:rehome 自身抛错时
// 走 catch 恢复原附件,行为与迁移前一致(fail-soft)。
let rehomedFiles = files;
+ let rehomedComments = preNavBrowserComments;
const restoreFirstMessageDraft = () => {
saveComposerDraft(newSession.id, {
text: preNavDraftDoc ?? plainTextToTiptapDoc(message),
- attachments: rehomedFiles ?? [],
+ attachments: excludeCommentScreenshots(rehomedFiles, rehomedComments),
+ browserComments: rehomedComments,
});
// 第一条消息退回草稿 = 它没被交出去,也就永远不会有权威标题回流。
// 不撤回的话标题预览会一直盖着 DB 里的哨兵(每次全量刷新后重新盖上),
@@ -3939,6 +3981,10 @@ export function NewMakerDraftRoute() {
};
try {
rehomedFiles = await rehomeDraftAttachments(files, newSession.id);
+ rehomedComments = rewriteBrowserCommentsFromRehomedFiles(
+ preNavBrowserComments,
+ rehomedFiles,
+ );
const resp = await window.electronAPI.worktreeCreate({
sessionId: newSession.id,
baseRepo,
@@ -4128,14 +4174,15 @@ export function NewMakerDraftRoute() {
carryDraftFavoriteAnchorToSession(newSession.id, persistedAgentKind, model, providerId);
// 计划模式是一次性选择:随本次发送被消耗,草稿勾选同步熄灭。
if (effectivePlanMode) patchActivePrefs({ planMode: false });
- // 首条消息经 setPending → SessionView 自动发送,createOpts 读 chat store 的
- // planModeEnabled —— ensureInitialMessages 的行水合是异步的,必须先确定性
- // seed store,否则勾了计划模式的首条消息可能以 planMode:false 发出
- // (worktree 路径同款 seed;bot review P2)。
+ // 本机/SSH 首条在下面直接 sendMessage,createOpts 读 chat store 的
+ // planModeEnabled / remoteHostId —— ensureInitialMessages 的行水合是异步的,
+ // 必须先确定性 seed store,否则勾了计划模式的首条可能以 planMode:false 发出,
+ // SSH 首条会把远端路径当本机 workdir(worktree 路径同款 seed)。
makerChatStore.setSessionRuntime(newSession.id, {
agentKind: capabilityAgentKind,
fastMode: effectiveFastMode,
planModeEnabled: effectivePlanMode,
+ remoteHostId: workingDir ? (effectiveRemoteHostId ?? null) : null,
});
// "创建即发送"路径:乐观回写 userSendAt 跳过 projectGrouping 的草稿兜底
@@ -4184,38 +4231,150 @@ export function NewMakerDraftRoute() {
}
// 草稿态 base64 图片回填到新 session 的 image cache,换成 xdt-image://
- // URL。必须在 setPending 之前,否则 SessionView 拿到的还是 base64。
+ // URL。必须在发出首条之前,否则消息里还是草稿命名空间。
const rehydratedFiles = await rehomeDraftAttachments(files, newSession.id);
- setPending(newSession.id, {
- text: message,
- files: rehydratedFiles,
- mentions,
- ...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
- ...(opts?.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),
- ...(opts?.pastedTextRanges?.length ? { pastedTextRanges: opts.pastedTextRanges } : {}),
- ...(opts?.slashCommandRanges !== undefined
- ? { slashCommandRanges: opts.slashCommandRanges }
- : {}),
- ...(deferredUiAssignment ? { deferredUiAssignment } : {}),
- });
- opts?.onAccepted?.();
- // 草稿已经成功移交给新会话(setPending),清掉 NEW_MAKER_DRAFT_KEY
- // 下的 store 条目,防止下次回到 /cc-agent/new 还看到本次刚发送的内容。
- // 用 clearDraftAndNotify:上面 onSend return false,ChatInput 没清自己的
- // 编辑器,这里必须通知它同步清空,否则 navigate 卸载时 ChatInput 的兜底
- // effect 会把残留文本又写回 NEW_MAKER_DRAFT_KEY,撤销这次 clear。
- clearComposerDraftAndNotify(NEW_MAKER_DRAFT_KEY);
- // 同步清空 attachmentsRef,否则 navigate 触发 unmount 时
- // useAttachments 的 cleanup effect 会把旧附件重新写回 store。
- attachmentState.clearFiles();
- resetDraftWorkspaceAfterSend();
- // 让 SessionView 接管:它 mount 时 consumePending 自动发送首条。
- navigate(orcaNavTarget ?? `/cc-agent/${newSession.id}`, {
- replace: true,
- state: orcaWorkersRevealState
- ? { orcaWorkersReveal: orcaWorkersRevealState }
- : undefined,
- });
+ const sendWorkingDir = workingDir ?? newSession.workingDir;
+ const preNavDraft = getComposerDraft(NEW_MAKER_DRAFT_KEY);
+ const preNavDraftDoc = preNavDraft?.text ?? null;
+ const preNavBrowserComments = rewriteBrowserCommentsFromRehomedFiles(
+ preNavDraft?.browserComments,
+ rehydratedFiles,
+ );
+ const restoreFirstMessageDraft = () => {
+ // FIFO 插回失败的首条,不覆盖用户在等待期间已经写进新任务输入框的内容。
+ restoreRemoteOptimisticDraft(newSession.id, {
+ clientId: `local-first:${newSession.id}`,
+ text: preNavDraftDoc ?? plainTextToTiptapDoc(message),
+ attachments: excludeCommentScreenshots(rehydratedFiles, preNavBrowserComments),
+ browserComments: preNavBrowserComments,
+ });
+ emitAutoTitlePreviewCleared(newSession.id);
+ clearSessionStarting(newSession.id);
+ };
+ const navigateToSession = () => {
+ navigate(orcaNavTarget ?? `/cc-agent/${newSession.id}`, {
+ replace: true,
+ state: orcaWorkersRevealState
+ ? { orcaWorkersReveal: orcaWorkersRevealState }
+ : undefined,
+ });
+ };
+ const handOffDraftToSession = () => {
+ // 用 clearDraftAndNotify:上面 onSend return false,ChatInput 没清自己的
+ // 编辑器,这里必须通知它同步清空,否则 navigate 卸载时 ChatInput 的兜底
+ // effect 会把残留文本写回 NEW_MAKER_DRAFT_KEY,撤销这次 clear。
+ clearComposerDraftAndNotify(NEW_MAKER_DRAFT_KEY);
+ attachmentState.clearFiles();
+ resetDraftWorkspaceAfterSend();
+ };
+
+ // 本机首条消息在草稿路由发出,不把发送绑在 SessionView hydrate 上。
+ // sendMessage 同步推入 store 后再 navigate,切走只换画面、不撤发送。
+ if (!sendWorkingDir) {
+ log.error('[draft send] created session missing workingDir');
+ restoreFirstMessageDraft();
+ handOffDraftToSession();
+ navigateToSession();
+ return;
+ }
+
+ try {
+ // 斜杠命令必须走 SessionView 的完整分派(SSH skipAgentSkills、远端 /review
+ // 拒绝、Pi runtime 重试)。识别窗口与 maybeDispatchDesktopSlashCommand 相同:
+ // 列首 /cmd,以及 Pi 的空白前缀 /cmd;草稿路由只交接,不复制分派逻辑。
+ const slashMatch = message.match(/^\/(\S+)(?:\s+(.*))?$/s);
+ const leading =
+ !slashMatch && capabilityAgentKind === 'pi'
+ ? leadingSlashInvocation(message)
+ : undefined;
+ if (slashMatch || leading) {
+ setPending(newSession.id, {
+ text: message,
+ files: rehydratedFiles,
+ mentions,
+ ...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(opts?.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),
+ ...(opts?.pastedTextRanges?.length
+ ? { pastedTextRanges: opts.pastedTextRanges }
+ : {}),
+ ...(opts?.slashCommandRanges !== undefined
+ ? { slashCommandRanges: opts.slashCommandRanges }
+ : {}),
+ ...(deferredUiAssignment ? { deferredUiAssignment } : {}),
+ });
+ handOffDraftToSession();
+ navigateToSession();
+ return;
+ }
+
+ const dispatchedMessage = await rewritePiSkillMessageForSend({
+ agentKind: capabilityAgentKind,
+ message,
+ workingDir: sendWorkingDir,
+ sessionId: newSession.id,
+ });
+ const rebaseRanges = <T extends { start: number; end: number }>(
+ ranges: readonly T[] | undefined,
+ ): T[] | undefined => {
+ if (!ranges) return undefined;
+ return rebaseInlineRangesAfterSlashCommandRewrite(
+ ranges,
+ message,
+ dispatchedMessage,
+ );
+ };
+ const sendPromise = makerChatStore.sendMessage(
+ newSession.id,
+ dispatchedMessage,
+ model,
+ effort,
+ permissionMode,
+ sendWorkingDir,
+ rehydratedFiles,
+ mentions,
+ {
+ ...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(opts?.agentReferences?.length
+ ? { agentReferences: rebaseRanges(opts.agentReferences) }
+ : {}),
+ ...(opts?.pastedTextRanges?.length
+ ? { pastedTextRanges: rebaseRanges(opts.pastedTextRanges) }
+ : {}),
+ ...(opts?.slashCommandRanges !== undefined
+ ? { slashCommandRanges: rebaseRanges(opts.slashCommandRanges) }
+ : {}),
+ },
+ );
+ handOffDraftToSession();
+ navigateToSession();
+ void sendPromise.then(
+ (accepted) => {
+ if (accepted) {
+ opts?.onAccepted?.();
+ void dispatchDeferredUiAssignment(newSession.id, deferredUiAssignment).catch(
+ (err) => {
+ log.error('[draft send] deferred Worker assignment failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ },
+ );
+ } else {
+ restoreFirstMessageDraft();
+ if (deferredUiAssignment) {
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ }
+ }
+ },
+ (err) => {
+ log.error('[draft send]', err);
+ restoreFirstMessageDraft();
+ },
+ );
+ } catch (err) {
+ log.error('[draft send]', err);
+ restoreFirstMessageDraft();
+ handOffDraftToSession();
+ navigateToSession();
+ }
} catch (err) {
// 交接失败 → 撤回乐观标题预览(理由见上面 optimisticTitleSessionId 的注释)。
// 归属切换也会提前 return,必须先撤;否则已建、未发出首条的空会话会一直顶着原文。
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 12f16c1b1a..bd1b5559e0 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -14894,6 +14894,8 @@ function setSessionRuntime(
agentKind?: 'claude-code' | 'codex' | 'pi';
fastMode?: boolean;
planModeEnabled?: boolean;
+ /** Seed before SessionView hydrates the DB row; sendMessage reads this for SSH routing. */
+ remoteHostId?: string | null;
},
): void {
if (!sessionId) return;
@@ -14901,10 +14903,14 @@ function setSessionRuntime(
const nextAgentKind = opts.agentKind ?? s.agentKind;
const nextFastMode = opts.fastMode ?? s.fastMode;
const nextPlanMode = opts.planModeEnabled ?? s.planModeEnabled;
+ const nextRemoteHostId = Object.hasOwn(opts, 'remoteHostId')
+ ? (opts.remoteHostId ?? null)
+ : s.remoteHostId;
if (
s.agentKind === nextAgentKind &&
s.fastMode === nextFastMode &&
- s.planModeEnabled === nextPlanMode
+ s.planModeEnabled === nextPlanMode &&
+ s.remoteHostId === nextRemoteHostId
)
return s;
return {
@@ -14912,6 +14918,7 @@ function setSessionRuntime(
agentKind: nextAgentKind,
fastMode: nextFastMode,
planModeEnabled: nextPlanMode,
+ remoteHostId: nextRemoteHostId,
...(s.planModeEnabled !== nextPlanMode ? { planModeRev: s.planModeRev + 1 } : {}),
};
});
diff --git a/apps/desktop/src/renderer/state/pendingFirstMessage.ts b/apps/desktop/src/renderer/state/pendingFirstMessage.ts
index 1a5cfde84b..8a9aef9884 100644
--- a/apps/desktop/src/renderer/state/pendingFirstMessage.ts
+++ b/apps/desktop/src/renderer/state/pendingFirstMessage.ts
@@ -1,13 +1,21 @@
/**
- * pendingFirstMessage —— 跨路由把"NewMaker 草稿首条消息"递交给真实 SessionView。
+ * pendingFirstMessage —— 跨路由把「还不能在草稿页发出的首条」递交给真实 SessionView。
*
- * 流程:
- * NewMakerDraftRoute.handleSend
- * → createSession() 拿到 newId
- * → setPending(newId, { text, files })
- * → navigate('/cc-agent/' + newId)
+ * 本机新建的普通文本不走这里:草稿路由 createSession 后直接 sendMessage,再 navigate。
+ * 切走只换画面,发送在 makerChatStore 里继续,不依赖 SessionView hydrate。
+ * SessionView 会当成斜杠命令的本机首条(列首 /cmd,以及 Pi 空白前缀)仍走 setPending:
+ * desktop / Pi 分派必须等 SessionView 挂上(SSH 跳过控制端 skill、远端 /review 拒绝、
+ * Pi runtime 重试),不能在草稿路由复制一套。
+ *
+ * 仍走这套交接的还有 device-link 远程草稿(含开协同):对端建会话之后,首条必须等
+ * SessionView 挂上隧道订阅 / 开协同,不能挡在 navigate 前面。
+ *
+ * NewMakerDraftRoute.handleSend(远程)
+ * → 对端 create-session 拿到 remoteSessionId
+ * → setPending(remoteSessionId, { text, files, remoteCollab? })
+ * → navigate('/cc-agent/' + remoteSessionId)
* CCAgentSessionView mount
- * → consumePending(newId) → sendMessage(text, files)
+ * → consumePending(id) → (可选开协同) → sendMessage(text, files)
*
* 仅内存(模块级 Map):app 重启意味着发送链路被打断,丢弃不持久化。
* 一次性消费(consume 即删):防止重复发送。
@@ -119,8 +127,9 @@ export function consumePendingGoal(sessionId: string): PendingGoalPayload | null
// ─── 远程协同交接的可恢复副本 ──────────────────────────────────────────────────
//
// 为什么只有 remoteCollab 这条路径要落盘(greptile P1):
-// 其余创建路径的 setPending → navigate → mount → consume → sendMessage 是一串毫秒级
-// 步骤,内存 Map 与渲染进程同生共死不构成实际风险。而 **device-link 远程交接**这条不同 ——
+// 本机普通文本已在草稿路由直接 sendMessage。仍走 setPending 的是 device-link
+// 远程草稿,以及本机必须交给 SessionView 分派的斜杠命令首条(含 Pi 空白前缀)。
+// **device-link 远程交接**和本机不同 ——
// consume 之后还要 await 隧道往返:开协同要等被控端起 Worker(正常一两秒,慢设备会一路走到
// 30s 隧道超时再加 6×3s 回查),起目标之前还要先 await 一次 `deviceLink.subscribe`
// (同样是 invoke,同样可能走到 30s)。这段时间用户输入只存在于渲染进程内存里,