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): 首条消息与前面没有回复的消息也能编辑和回退

Dash4fe425030fcd
diff --git a/apps/desktop/src/main/__tests__/rewind.test.ts b/apps/desktop/src/main/__tests__/rewind.test.ts
index b76d0e7d7f..503fe87978 100644
--- a/apps/desktop/src/main/__tests__/rewind.test.ts
+++ b/apps/desktop/src/main/__tests__/rewind.test.ts
@@ -6,7 +6,7 @@
* + 软删 messages + 重置 sessions
* - SESSION_RUNNING 守卫 (session.isTurnRunning() = true)
* - NO_LIVE_QUERY 守卫 (maker.getSession() = undefined)
- * - NO_PRIOR_ASSISTANT
+ * - 目标之前没有可续接的回复 → 只回滚文件、关闭会话、事务清原生会话并留交接
* - 老消息 user uuid 缺失 → 仍调 commitRewindFiles 但 userUuid='', maker 内部跳过
* SDK 文件回滚, forkSession=true 在下次 send 时兜底
* - commitRewindFiles 抛错 → DB tx 不跑 (commitRewindFiles 内部已经 try/catch
@@ -92,11 +92,20 @@ function useFakeSession(agentKind: 'claude-code' | 'codex' | 'pi') {
getSessionMock.mockImplementation(() => fakeSession);
}
+const closeSessionMock = vi.fn(async () => undefined);
vi.mock('../maker-host/index.js', () => ({
getMaker: () => ({
getSession: getSessionMock,
getSessionMeta: getSessionMetaMock,
+ closeSession: closeSessionMock,
}),
+ withRehydrateCloseSuppressed: (_sessionId: string, fn: () => Promise<unknown>) => fn(),
+}));
+
+const listMessagesForAgentHandoffMock = vi.fn();
+vi.mock('../localDb/ipc/messages.js', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../localDb/ipc/messages.js')>()),
+ listMessagesForAgentHandoff: listMessagesForAgentHandoffMock,
}));
vi.mock('../git-context/prRefsStore.js', () => ({
@@ -235,6 +244,9 @@ beforeEach(async () => {
isTurnRunningMock.mockReturnValue(false);
getSessionMock.mockReset();
getSessionMetaMock.mockReset();
+ closeSessionMock.mockClear();
+ listMessagesForAgentHandoffMock.mockReset();
+ listMessagesForAgentHandoffMock.mockResolvedValue([]);
// restore default fake Session
useFakeSession('claude-code');
getSessionMetaMock.mockImplementation(async () =>
@@ -885,19 +897,53 @@ describe('commitRewindAtMessage', () => {
expect(txCalls).toHaveLength(0);
});
- it('throws NO_PRIOR_ASSISTANT when target user msg has no preceding assistant with uuid', async () => {
+ it('no preceding reply: restores files, restarts the native session and carries the stopped message as handoff', async () => {
+ // 首条消息发出就停掉、再发第二条:第二条之前没有 Claude 回复可作续接点。
selectQueue.push([makeUserMessageRow({
agentMeta: JSON.stringify({ uuid: 'sdk-msg-uuid-target', sdkSessionId: 'sdk-uuid-old' }),
})]); // target without transcript parent
selectQueue.push([]); // agent_switch 边界守卫:无边界
- selectQueue.push([]); // prior assistants — empty
+ selectQueue.push([]); // prior assistants — empty
+ selectQueue.push([makeSessionRow({ sdkSessionId: null })]); // post-update select
+ listMessagesForAgentHandoffMock.mockResolvedValue([
+ { clientId: 'stopped-id', role: 'user', content: { text: '先前被停掉的问题' }, createdAt: 2000, agentMeta: null, toolUseId: null },
+ { clientId: 'client-id', role: 'user', content: { text: 'hello' }, createdAt: 3000, agentMeta: null, toolUseId: null },
+ ]);
- await expect(
- commitRewindAtMessage('sess-1', 'client-id'),
- ).rejects.toMatchObject({ code: 'NO_PRIOR_ASSISTANT' });
+ await commitRewindAtMessage('sess-1', 'client-id');
+
+ expect(commitRewindFilesMock).toHaveBeenCalledTimes(1);
+ expect(commitRewindFilesMock).toHaveBeenCalledWith('sdk-msg-uuid-target', '', { rewindsToNativeThreadStart: true });
+ expect(closeSessionMock).toHaveBeenCalledWith('sess-1');
+ const txCall = txCalls.find((c) => c.name === 'rewind.commit');
+ if (!txCall) throw new Error('缺少 rewind.commit tx 调用');
+ const reset = (txCall.args as { nativeContextReset?: { markerContent: string } }).nativeContextReset;
+ if (!reset) throw new Error('缺少 nativeContextReset');
+ const marker = JSON.parse(reset.markerContent) as { handoff: string; consumed: boolean };
+ expect(marker.consumed).toBe(false);
+ expect(marker.handoff).toContain('先前被停掉的问题');
+ expect(marker.handoff).not.toContain('hello');
+ expect(setLastAssistantTranscriptUuidMock).toHaveBeenCalledWith('sess-1', undefined);
+ });
+
+ it('first message: restarts the native session with an empty handoff', async () => {
+ selectQueue.push([makeUserMessageRow({
+ agentMeta: JSON.stringify({ uuid: 'sdk-msg-uuid-target', sdkSessionId: 'sdk-uuid-old' }),
+ })]);
+ selectQueue.push([]); // agent_switch 边界守卫:无边界
+ selectQueue.push([]); // prior assistants — empty
+ selectQueue.push([makeSessionRow({ sdkSessionId: null })]);
+ listMessagesForAgentHandoffMock.mockResolvedValue([
+ { clientId: 'client-id', role: 'user', content: { text: 'hello' }, createdAt: 3000, agentMeta: null, toolUseId: null },
+ ]);
+
+ await commitRewindAtMessage('sess-1', 'client-id', { allowFileRestore: false });
expect(commitRewindFilesMock).not.toHaveBeenCalled();
- expect(txCalls).toHaveLength(0);
+ expect(closeSessionMock).toHaveBeenCalledWith('sess-1');
+ const txCall = txCalls.find((c) => c.name === 'rewind.commit');
+ const reset = (txCall?.args as { nativeContextReset?: { markerContent: string } }).nativeContextReset;
+ expect(JSON.parse(reset!.markerContent)).toMatchObject({ handoff: '', consumed: false });
});
it('OLD message (user uuid missing) still commits, calls commitRewindFiles with empty userUuid', async () => {
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index c1baf28b05..9235f177ec 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -1750,6 +1750,18 @@ function rewindCommit(readyDb, args) {
payload.expectedClearedAt === undefined || payload.expectedClearedAt === null
? null
: expectNumber(payload.expectedClearedAt, 'expectedClearedAt');
+ // Mirror worker/opHandlers/tx.ts: a Claude rewind without a prior reply
+ // clears the native session id and leaves a hidden context_rebuild marker.
+ const resetPayload = payload.nativeContextReset === undefined
+ ? null
+ : asRecord(payload.nativeContextReset, 'nativeContextReset');
+ const nativeContextReset = resetPayload
+ ? {
+ markerId: expectString(resetPayload.markerId, 'nativeContextReset.markerId'),
+ markerClientId: expectString(resetPayload.markerClientId, 'nativeContextReset.markerClientId'),
+ markerContent: expectString(resetPayload.markerContent, 'nativeContextReset.markerContent'),
+ }
+ : null;
const rows = readyDb.prepare(
'SELECT id, client_id, role, created_at, agent_meta, tool_use_id FROM messages WHERE session_id = ? AND rewind_at IS NULL',
).all(sessionId);
@@ -1826,7 +1838,17 @@ function rewindCommit(readyDb, args) {
// so fail closed rather than expose work from a withdrawn branch.
rewindParentlessSubagentTail.run(now, sessionId, targetCreatedAt);
}
- if (sdkSessionId) {
+ if (nativeContextReset) {
+ readyDb.prepare('UPDATE sessions SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0, codex_plan_json = NULL, sdk_session_id = NULL, list_preview = NULL, list_preview_role = NULL WHERE id = ?').run(now, now, sessionId);
+ readyDb.prepare("INSERT INTO messages (id, client_id, session_id, role, content, created_at, rewind_at) VALUES (?, ?, ?, 'context_rebuild', ?, ?, ?)").run(
+ nativeContextReset.markerId,
+ nativeContextReset.markerClientId,
+ sessionId,
+ nativeContextReset.markerContent,
+ now,
+ now,
+ );
+ } else if (sdkSessionId) {
readyDb.prepare('UPDATE sessions SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0, codex_plan_json = NULL, sdk_session_id = ?, list_preview = NULL, list_preview_role = NULL WHERE id = ?').run(now, now, sdkSessionId, sessionId);
} else {
readyDb.prepare('UPDATE sessions SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0, codex_plan_json = NULL, list_preview = NULL, list_preview_role = NULL WHERE id = ?').run(now, now, sessionId);
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index f2f29e83b3..f9d1d794a9 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -1270,6 +1270,43 @@ describe('db worker tx handlers', () => {
},
);
+ // Claude 首条消息 / 前面轮次都被停掉时没有续接点:软删、清原生会话 id 与交接标记
+ // 必须同一事务落地,否则下次发送会续接仍含被撤回消息的旧原生会话。
+ it.each([false, true])(
+ 'rewind.commit clears the native session and stores the handoff marker when restarting (inline=%s)',
+ async (useInlineWorker) => {
+ await withClient(async (client) => {
+ await seedSession(client, 's1');
+ await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', ['sdk-old', 's1']);
+ await client.exec(
+ 'INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?)',
+ ['m1', 'c1', 's1', 'user', 'stopped', 100, 'm2', 'c2', 's1', 'user', 'target', 200],
+ );
+ const markerContent = JSON.stringify({ handoff: 'kept history', consumed: false, reason: 'message-rewind' });
+
+ await client.tx('rewind.commit', {
+ sessionId: 's1',
+ targetCreatedAt: 200,
+ targetMessageId: 'm2',
+ targetClientId: 'c2',
+ nativeContextReset: { markerId: 'mk', markerClientId: 'context-rebuild:mk', markerContent },
+ now: 999,
+ });
+
+ await expect(
+ client.query('SELECT id, role, content, created_at, rewind_at FROM messages ORDER BY created_at, id'),
+ ).resolves.toEqual([
+ { id: 'm1', role: 'user', content: 'stopped', created_at: 100, rewind_at: null },
+ { id: 'm2', role: 'user', content: 'target', created_at: 200, rewind_at: 999 },
+ { id: 'mk', role: 'context_rebuild', content: markerContent, created_at: 999, rewind_at: 999 },
+ ]);
+ await expect(
+ client.queryOne('SELECT sdk_session_id FROM sessions WHERE id = ?', ['s1']),
+ ).resolves.toEqual({ sdk_session_id: null });
+ }, { useInlineWorker });
+ },
+ );
+
it.each([false, true])(
'rewind.commit remaps surviving native fork anchors to the replacement thread (inline=%s)',
async (useInlineWorker) => {
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index 6e5d35fbd1..85ac529ed7 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -147,6 +147,15 @@ export interface RewindCommitArgs {
* 省略或 null 表示当时会话未被清空。
*/
expectedClearedAt?: number | null;
+ /**
+ * Claude 目标之前没有可续接的回复:与软删同一事务清掉 sdk_session_id,并追加隐藏
+ * context_rebuild 标记(内容含交接文本),下次发送开全新原生会话并注入保留下来的历史。
+ */
+ nativeContextReset?: {
+ markerId: string;
+ markerClientId: string;
+ markerContent: string;
+ };
now: number;
}
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index c04b2e1167..3a7dc49916 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -2678,6 +2678,16 @@ function rewindCommit(db: Database.Database, args: unknown): void {
payload.expectedClearedAt === undefined || payload.expectedClearedAt === null
? null
: expectNumber(payload.expectedClearedAt, 'expectedClearedAt');
+ const nativeContextReset = payload.nativeContextReset === undefined
+ ? null
+ : (() => {
+ const reset = asRecord(payload.nativeContextReset, 'nativeContextReset');
+ return {
+ markerId: expectString(reset.markerId, 'nativeContextReset.markerId'),
+ markerClientId: expectString(reset.markerClientId, 'nativeContextReset.markerClientId'),
+ markerContent: expectString(reset.markerContent, 'nativeContextReset.markerContent'),
+ };
+ })();
const rows = db
.prepare(
`SELECT id, client_id, role, created_at, agent_meta, tool_use_id
@@ -2777,7 +2787,25 @@ function rewindCommit(db: Database.Database, args: unknown): void {
// work from the branch the user explicitly withdrew.
rewindParentlessSubagentTail.run(now, sessionId, targetCreatedAt);
}
- if (sdkSessionId) {
+ if (nativeContextReset) {
+ db.prepare(
+ `UPDATE sessions
+ SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0,
+ codex_plan_json = NULL, sdk_session_id = NULL,
+ list_preview = NULL, list_preview_role = NULL
+ WHERE id = ?`,
+ ).run(now, now, sessionId);
+ db.prepare(
+ "INSERT INTO messages (id, client_id, session_id, role, content, created_at, rewind_at) VALUES (?, ?, ?, 'context_rebuild', ?, ?, ?)",
+ ).run(
+ nativeContextReset.markerId,
+ nativeContextReset.markerClientId,
+ sessionId,
+ nativeContextReset.markerContent,
+ now,
+ now,
+ );
+ } else if (sdkSessionId) {
db.prepare(
`UPDATE sessions
SET user_send_at = ?, updated_at = ?, context_tokens = 0, context_window = 0,
diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
index 069098d713..e1fd4ee74f 100644
--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts
+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
@@ -70,7 +70,8 @@ export interface BuildHandoffOptions {
includeToolResults?: boolean;
/**
* 交接触发原因。message-deletion 表示同一引擎因本地消息被删除而重建原生
- * 上下文;context-overflow 表示同一引擎因窗口超限而换干净原生会话;
+ * 上下文;message-rewind 表示回退/编辑的目标之前没有可续接的 Claude 回复,
+ * 只能换全新原生会话并带上保留下来的历史;context-overflow 表示同一引擎因窗口超限而换干净原生会话;
* model-window-switch 表示切到更小模型前主动换窗;pi-prompt-timeout 表示原生会话
* 对 prompt 无响应后用户重试换窗;idle-gap 表示伙伴对话空闲足够久之后的下一条消息
* 主动换干净原生会话,免得老话题带偏新话题。
@@ -78,6 +79,7 @@ export interface BuildHandoffOptions {
reason?:
| 'agent-switch'
| 'message-deletion'
+ | 'message-rewind'
| 'context-overflow'
| 'model-window-switch'
| 'pi-prompt-timeout'
@@ -621,6 +623,7 @@ const FORK_TERMINATOR = "== End of fork note; the user's new message follows =="
function isRebuildReason(reason: BuildHandoffOptions['reason']): boolean {
return (
reason === 'message-deletion' ||
+ reason === 'message-rewind' ||
reason === 'context-overflow' ||
reason === 'model-window-switch' ||
reason === 'pi-prompt-timeout' ||
@@ -765,6 +768,10 @@ function assembleHandoffText(
: opts.reason === 'native-session-recovery'
? `The previous native session history could not be safely transferred, so Cindy started a fresh native session in the same task. ` +
`The original conversation remains available through the history retrieval tools. Use the handoff below to continue; do not repeat completed actions. `
+ : opts.reason === 'message-rewind'
+ ? `The user rewound or edited a message in this conversation, so Cindy started a fresh native session in the same task. ` +
+ `Below is the conversation before that point; user messages without a reply there were stopped by the user before any answer. ` +
+ `Treat only these records as the prior conversation. `
: opts.reason === 'pi-prompt-timeout'
? `The previous native agent session stopped responding to prompts, so Cindy started a fresh native session in the same task. ` +
`Below is the valid conversation history before the unresponsive turn; treat only these records as the prior conversation, ` +
diff --git a/apps/desktop/src/main/maker-orchestration/rewind.ts b/apps/desktop/src/main/maker-orchestration/rewind.ts
index 19c8599fc4..9a70833e53 100644
--- a/apps/desktop/src/main/maker-orchestration/rewind.ts
+++ b/apps/desktop/src/main/maker-orchestration/rewind.ts
@@ -3,7 +3,8 @@
*
* Stage 2 C2 重构后:SDK 调用全部走 maker-core 的 Session.previewRewindFiles /
* commitRewindFiles。本文件只剩业务编排:
- * - Claude: 反向找 prior assistant uuid (跳 subagent / 跳 rewinded)
+ * - Claude: 反向找 prior assistant uuid (跳 subagent / 跳 rewinded);找不到时
+ * 只回滚文件并换全新原生会话,目标之前保留的历史作为交接带过去
* - Codex: 计算 target 之后要裁掉的完整 user turn 数与原生 turn 边界,交给
* maker-core(thread/rollback;不可用时按边界 fork,第一轮换空线程)
* - SQLite 事务 (messages.rewind_at + sessions reset tokens + bump userSendAt)
@@ -23,11 +24,15 @@
*/
import { and, asc, desc, eq, gt, gte, isNull, lt, or, sql } from 'drizzle-orm';
+import { createId } from '@paralleldrive/cuid2';
import { getDbClient } from '../localDb/client/current';
import { sessions, messages } from '../localDb/schema';
import { sessionToCamel } from '../localDb/mapper';
-import { getMaker } from '../maker-host/index.js';
+import { listMessagesForAgentHandoff } from '../localDb/ipc/messages.js';
+import type { RewindCommitArgs } from '../localDb/client/tx/types';
+import { getMaker, withRehydrateCloseSuppressed } from '../maker-host/index.js';
+import { buildHandoffText } from '../maker-ipc/agentHandoff.js';
import { readGitSafetySettings } from '../maker-host/git-safety-settings-store.js';
import { ownerScopedUserDataPath } from '../appSessionState';
import { SnapshotAttemptStore } from '../git-snapshot/snapshotAttemptStore';
@@ -160,7 +165,10 @@ interface RewindContext {
targetClientId: string;
/** 当前 agent kind;Claude checkpoint 与 conversation-tree rollback 机制不同。 */
agentKind: 'claude-code' | 'codex' | 'pi';
- /** prior assistant uuid(Claude 必填)——SDK resumeSessionAt 用。 */
+ /**
+ * prior assistant uuid——Claude SDK resumeSessionAt 用。Claude 缺省表示目标之前没有
+ * 可续接的回复(首条消息、之前的轮次都被停掉等),改为换全新原生会话。
+ */
assistantUuid?: string;
/** target user 消息的 SDK uuid——仅 preview 的 rewindFiles dryRun 用,老消息可能 NULL。 */
userUuid?: string;
@@ -370,13 +378,12 @@ async function loadRewindContext(
break;
}
}
- if (!assistantUuid) {
- throw rewindError('NO_PRIOR_ASSISTANT', '请在 AI 回复之后的提问上 rewind');
- }
+ // 没有可续接的回复时不再拒绝:提交时换全新原生会话,目标之前保留下来的历史
+ // 作为交接带过去(见 commitRewindAtMessage)。
const userUuid = targetMeta.uuid;
log.debug(
- `[rewind] sessionId=${sessionId.slice(0, 8)} clientId=${clientId} target.createdAt=${target.createdAt} userUuid=${userUuid ?? 'NONE'} assistantUuid=${assistantUuid} preserveMessageUuid=${preserveMessageUuid ?? assistantUuid}`,
+ `[rewind] sessionId=${sessionId.slice(0, 8)} clientId=${clientId} target.createdAt=${target.createdAt} userUuid=${userUuid ?? 'NONE'} assistantUuid=${assistantUuid ?? 'NONE (native session restart)'} preserveMessageUuid=${preserveMessageUuid ?? assistantUuid}`,
);
// Claude Code 在另一台电脑运行:文件按本机保存点链回退,需要 target 之后的 user 消息时间线。
@@ -752,6 +759,40 @@ async function loadCodexRewindNativeBoundary(
: { sdkSessionId, expectedClearedAt: clearedAt };
}
+/**
+ * Claude 目标之前没有可续接的回复时,目标之前仍保留的可见历史(例如发出后被停掉、
+ * 没有回复的消息)只存在于即将放弃的原生会话里。把它们做成交接写进隐藏标记,
+ * 下次任意入口发送时注入全新原生会话;没有 user 历史时交接为空,不注入。
+ */
+async function buildNativeContextReset(
+ sessionId: string,
+ targetClientId: string,
+): Promise<NonNullable<RewindCommitArgs['nativeContextReset']>> {
+ // 不设条数上限:这条路径的目标靠近会话开头,最近 N 条窗口可能整段落在目标之后。
+ const history = await listMessagesForAgentHandoff(sessionId, null);
+ const targetIndex = history.findIndex((message) => message.clientId === targetClientId);
+ const kept = targetIndex >= 0 ? history.slice(0, targetIndex) : [];
+ const handoff = kept.some((message) => message.role === 'user')
+ ? buildHandoffText(kept, {
+ fromLabel: 'Claude Code',
+ toLabel: 'Claude Code',
+ sessionId,
+ reason: 'message-rewind',
+ })
+ : '';
+ return {
+ markerId: createId(),
+ markerClientId: `context-rebuild:${createId()}`,
+ markerContent: JSON.stringify({ handoff, consumed: false, reason: 'message-rewind' }),
+ };
+}
+
+/** 与消息删除同口径:关闭期间抑制 onClose 副作用(worktree 收尾等),任务本身仍在继续。 */
+async function closeSessionForNativeRestart(sessionId: string): Promise<undefined> {
+ await withRehydrateCloseSuppressed(sessionId, () => getMaker().closeSession(sessionId));
+ return undefined;
+}
+
export async function commitRewindAtMessage(
sessionId: string,
clientId: string,
@@ -770,6 +811,7 @@ export async function commitRewindAtMessage(
// pendingRewindTo, 下次 send 仍走三件套 (forkSession=true CLI 端兜底回滚)。
let rewindResult: Awaited<ReturnType<typeof makerSession.commitRewindFiles>> | undefined;
let nativeForkAnchorSessionMap: Array<[string, string]> | undefined;
+ let nativeContextReset: RewindCommitArgs['nativeContextReset'];
let expectedClearedAt: number | null = null;
if (ctx.agentKind === 'codex' || ctx.agentKind === 'pi') {
// thread/rollback 不可用(分页线程 #4421、0.156.0 起已移除 #4994):把 target 之前的
@@ -832,9 +874,14 @@ export async function commitRewindAtMessage(
} else if (ctx.savepointRewind) {
// Claude Code 在另一台电脑运行:先用本机保存点链回退文件,再让那台的 Claude Code 只截断
// 对话(空 userUuid = 不碰它那边并不存在的文件检查点);截断失败时撤回文件回退。
+ // 没有可续接的回复时改为关闭会话,下次发送开全新原生会话。
expectedClearedAt = await rereadSessionClearedAt(sessionId);
await assertClearGenerationUnchanged(sessionId, expectedClearedAt, ctx.targetCreatedAt);
- const commitConversationRewind = () => makerSession.commitRewindFiles('', ctx.assistantUuid!);
+ if (!ctx.assistantUuid) nativeContextReset = await buildNativeContextReset(sessionId, ctx.targetClientId);
+ const priorAssistantUuid = ctx.assistantUuid;
+ const commitConversationRewind = priorAssistantUuid
+ ? () => makerSession.commitRewindFiles('', priorAssistantUuid)
+ : () => closeSessionForNativeRestart(sessionId);
if (opts?.allowFileRestore === false) {
rewindResult = await commitConversationRewind();
} else {
@@ -858,6 +905,16 @@ export async function commitRewindAtMessage(
});
rewindResult = result.threadRollback;
}
+ } else if (!ctx.assistantUuid) {
+ // 目标之前没有可续接的回复:原生会话里没有可回到的时点。文件照常按原生检查点
+ // 回滚,然后关闭会话;事务清掉 sdk_session_id 并留下交接,下次发送开全新原生会话。
+ expectedClearedAt = await rereadSessionClearedAt(sessionId);
+ await assertClearGenerationUnchanged(sessionId, expectedClearedAt, ctx.targetCreatedAt);
+ nativeContextReset = await buildNativeContextReset(sessionId, ctx.targetClientId);
+ if (ctx.userUuid && opts?.allowFileRestore !== false) {
+ await makerSession.commitRewindFiles(ctx.userUuid, '', { rewindsToNativeThreadStart: true });
+ }
+ await closeSessionForNativeRestart(sessionId);
} else {
expectedClearedAt = await rereadSessionClearedAt(sessionId);
await assertClearGenerationUnchanged(sessionId, expectedClearedAt, ctx.targetCreatedAt);
@@ -897,8 +954,10 @@ export async function commitRewindAtMessage(
expectedClearedAt,
...(opts?.requireLatestUser ? { requireLatestUser: true } : {}),
...(nativeForkAnchorSessionMap ? { nativeForkAnchorSessionMap } : {}),
+ ...(nativeContextReset ? { nativeContextReset } : {}),
});
- if (ctx.assistantUuid) {
+ if (ctx.assistantUuid || nativeContextReset) {
+ // 换全新原生会话时清掉旧会话的父节点,下一条 user 不能挂到已放弃的会话上。
setLastAssistantTranscriptUuid(sessionId, ctx.assistantUuid);
}
} catch (err) {
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index a2f6589ad2..ddb344f690 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -6244,8 +6244,7 @@ export function MessageStream({
root.scrollTo({ top: Math.max(0, targetTop), behavior: 'smooth' });
}, [railJumpRequest, allRenderItems, visibleRenderItems, beginChipJump]);
- // 第一条 user 消息没有"上一条 assistant"作为 resumeSessionAt 锚点,
- // rewind 必然抛 NO_PRIOR_ASSISTANT。直接在 UI 层把按钮藏掉,避免无效点击。
+ // 第一条 user 消息 fork 出来等价于复制整条任务,UI 层藏掉 fork 入口。
// 注意:这里要用全量 messages 而不是 visibleRenderItems —— "首条 user" 的语义
// 是整段对话的首条,不是当前窗口的首条;且 messages 本身也只是已加载的尾部
// 切片,还有老页未加载(hasMoreMessages)时不能把切片首条误判为对话首条
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 1b59ff889b..e38e235acc 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -1186,13 +1186,12 @@ export function UserMessage({
[sessionId, draftBody, quoteDraftDocument, images, files],
);
- // 第一条 user 消息没有可作为锚点的 prior assistant uuid → 后端必抛
- // NO_PRIOR_ASSISTANT。直接藏掉按钮,避免无效点击。
- // 同时按 capabilities.rewind.supported gate;文件恢复能力由实际 Git 保存点决定。
+ // 第一条消息同样可回退:Codex / Pi 回到原生线程开头,Claude 目标之前没有可续接的
+ // 回复时换全新原生会话(见 main 侧 commitRewindAtMessage)。
+ // 按 capabilities.rewind.supported gate;文件恢复能力由实际 Git 保存点决定。
const canRewind =
!sharedGuest &&
Boolean(sessionId && messageClientId) &&
- !isFirstUserMessage &&
rewindSupported &&
!orcaCommunication &&
!hasEmbeddedImPrompt(hookSource);
@@ -1200,8 +1199,8 @@ export function UserMessage({
// ── edit-last-message ──────────────────────────────────────────────────
// 编辑 = rewind 到本条 + 用编辑后的文本立即重发(见 UserMessageEditBox)。
// 只在最后一条 user 消息开放;能力门控与 Rewind 完全一致(编辑走同一条
- // commit 链路,rewind 不可用则编辑必然也不可用),首条消息同样因缺
- // prior assistant 锚点而隐藏。进入编辑态零副作用,取消原样恢复。
+ // commit 链路,rewind 不可用则编辑必然也不可用),首条消息同样可编辑。
+ // 进入编辑态零副作用,取消原样恢复。
const [editing, setEditing] = useState(false);
// 被意识钩子拦下的消息(订阅槽①):从未落库、无 turn 可 rewind,编辑走
// 普通重发(onCommitOverride),故可编辑条件与 rewind 无关——只要有
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 8d054500b4..ed41f33df1 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -320,6 +320,11 @@ Desktop 回包还须核对浏览器当前路由,覆盖地址已切换但 React
`/clear` 之后的新消息。实现见 Desktop `maker-orchestration/rewind.ts` 与 maker-core
`agents/codex/index.ts` 的 `commitRewindFiles`,回归见 `rewind.test.ts`、`fork.test.ts`、
`rewindNativeBoundarySqlite.test.ts`、`tx.test.ts` 与 `index.test.ts`。
+Claude 回退/编辑重发的目标之前没有可续接的 assistant(首条消息,或之前的轮次都在回复前被
+停掉)时不报错:宿主传 `rewindsToNativeThreadStart` 只借原生检查点回滚文件(另一台电脑上的
+Claude 用本机保存点),再关闭会话;`rewind.commit` 在同一事务里软删目标、清掉
+`sdk_session_id` 并写入隐藏 `context_rebuild`(reason `message-rewind`),把目标之前仍保留的
+可见历史作为交接,下次任意入口发送时注入全新原生会话,没有 user 历史时交接为空。
查询与 fork 使用同一隔离控制面 host,关闭其写入进程后才发布子线程身份。
HTTP 回退遇到缺失 `Content-Type` 的成功响应时,只允许从明文 SSE 前缀(可带注释心跳)
确认事件流并补齐响应头;显式非 SSE 类型、HTML/JSON、空响应与只有心跳的正文不能放行。
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts
index 765cdcccd5..287a01c3df 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/rewind-runtime-settings.test.ts
@@ -647,6 +647,19 @@ describe('ClaudeCodeAgent runtime settings during rewind window', () => {
await handle.close();
});
+ // 宿主在没有可续接回复时只借原生检查点回滚文件,随后自己关闭会话;这里不能 close
+ // Query 或设续接点,否则同一 handle 上的下一次发送会去 resume 一个不存在的时点。
+ it('rolls back files only when the host restarts the native session', async () => {
+ const { handle, firstQuery } = await startRewindableSession();
+
+ await handle.commitRewindFiles?.('user-uuid-1', '', { rewindsToNativeThreadStart: true });
+
+ expect(firstQuery.rewindFiles).toHaveBeenCalledWith('user-uuid-1', { dryRun: false });
+ expect(firstQuery.close).not.toHaveBeenCalled();
+
+ await handle.close();
+ });
+
it('uses the session provider route when the same model id has different windows', async () => {
const configDir = await makeTempDir();
process.env.CLAUDE_CONFIG_DIR = configDir;
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 9408d527f9..8257b1dfe8 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -101,6 +101,7 @@ import type {
AskUserQuestionItem,
UsageSnapshot,
RewindFilesResult,
+ RewindCommitOptions,
ForkSdkSessionOptions,
ForkSdkSessionResult,
} from '../../types/events.js';
@@ -7886,7 +7887,11 @@ export class ClaudeCodeAgent extends BaseAgent {
}
},
- async commitRewindFiles(userUuid: string, priorAssistantUuid: string): Promise<undefined> {
+ async commitRewindFiles(
+ userUuid: string,
+ priorAssistantUuid: string,
+ rewindOpts?: RewindCommitOptions,
+ ): Promise<undefined> {
// 同 previewRewindFiles:重建窗口内不得对死掉/半替换的 q 做 rewindFiles/close,
// 否则 pendingRewindTo 会指向一个已不存在的会话时点。等替换 query 就绪再走。
while (idleResumeRebuildGate) {
@@ -7907,6 +7912,12 @@ export class ClaudeCodeAgent extends BaseAgent {
error: err instanceof Error ? err.message : String(err),
});
}
+ if (rewindOpts?.rewindsToNativeThreadStart) {
+ // 目标之前没有可续接的 assistant:不设续接点,由宿主关闭会话并清掉原生
+ // 会话 id,下次发送开全新原生会话。
+ log.info('commitRewindFiles ◀ files only; host restarts the native session');
+ return undefined;
+ }
// ② **先**设 rewind transition 再 close —— q.close() 会让正在跑的 forward loop
// for-await 抛 "Claude Code process aborted by user", 这是预期行为不是错误。
// pendingRewindTo 是共享标记,会在新 q 接管后清掉;因此还要把当前 q 放进
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index bae9522dd0..44dcf8447f 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -517,6 +517,9 @@ export interface RewindCommitOptions {
* (首条消息,或 /clear、上下文重建、切换引擎新开线程后的第一轮)。此时没有可作
* fork 边界的 turn,rollback 不可用时 Codex 改为按当前配置新开一条空线程替换。
* 只在没有 lastTurnId / forkAtTimestampMs 时生效。
+ *
+ * Claude:目标之前没有可续接的 assistant 时由宿主传入,只回滚文件、不设续接点;
+ * 宿主随后关闭会话并清掉原生会话 id,下次发送开全新原生会话。
*/
rewindsToNativeThreadStart?: boolean;
}