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: 将 Git 安全保存点改为三态策略 (#4797)

Dash3a7de7ce4036
diff --git a/apps/desktop/src/main/__tests__/git-safety-settings-store.test.ts b/apps/desktop/src/main/__tests__/git-safety-settings-store.test.ts
new file mode 100644
index 0000000000..60afb66e94
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/git-safety-settings-store.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ app: { getPath: () => '/tmp/cindy-git-safety-settings-test' },
+}));
+
+import { __testing } from '../maker-host/git-safety-settings-store';
+
+describe('git safety settings migration', () => {
+ it('defaults new installs to existing Git projects', () => {
+ expect(__testing.normalize({})).toEqual({ mode: 'existing-git' });
+ });
+
+ it('preserves the old disabled boolean', () => {
+ expect(__testing.normalize({ autoSnapshotEnabled: false })).toEqual({ mode: 'off' });
+ });
+
+ it('preserves the old enabled boolean including empty-project bootstrap', () => {
+ expect(__testing.normalize({ autoSnapshotEnabled: true })).toEqual({ mode: 'all-projects' });
+ });
+
+ it('accepts each new mode', () => {
+ expect(__testing.normalize({ mode: 'off' })).toEqual({ mode: 'off' });
+ expect(__testing.normalize({ mode: 'existing-git' })).toEqual({ mode: 'existing-git' });
+ expect(__testing.normalize({ mode: 'all-projects' })).toEqual({ mode: 'all-projects' });
+ });
+
+ it('keeps an explicit selection of the current default mode', () => {
+ expect(
+ __testing.mergeOverrides({
+ patch: { mode: 'existing-git' },
+ next: { mode: 'existing-git' },
+ overrides: { mode: 'off' },
+ }),
+ ).toEqual({ mode: 'existing-git' });
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts b/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts
index 2b04d5e310..3bca41f96a 100644
--- a/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts
+++ b/apps/desktop/src/main/__tests__/gitSnapshotCoordinator.test.ts
@@ -138,7 +138,7 @@ describe('GitSnapshotCoordinator', () => {
workspaceKind: 'project',
remoteHostId: null,
}),
- { autoSnapshotEnabled: true },
+ { autoSnapshotEnabled: true, autoInitProjectGit: true },
);
expect(deps.detectRepoRoot).toHaveBeenCalledOnce();
expect(deps.createShadowSavepoint).toHaveBeenCalledWith(
diff --git a/apps/desktop/src/main/__tests__/gitSnapshotHost.test.ts b/apps/desktop/src/main/__tests__/gitSnapshotHost.test.ts
index 85487e7739..10337f6015 100644
--- a/apps/desktop/src/main/__tests__/gitSnapshotHost.test.ts
+++ b/apps/desktop/src/main/__tests__/gitSnapshotHost.test.ts
@@ -169,6 +169,7 @@ describe('createGitSnapshotCoordinator', () => {
} satisfies ShadowSavepointResult);
const coordinator = createGitSnapshotCoordinator(maker, {
readAutoSnapshotEnabled: vi.fn(() => enabled),
+ readAutoInitProjectGit: () => true,
detectRepoRoot: vi.fn().mockResolvedValue(null),
initializeProjectGit,
createShadowSavepoint,
@@ -185,7 +186,7 @@ describe('createGitSnapshotCoordinator', () => {
workingDir: '/workspace/project',
remoteHostId: undefined,
}),
- { autoSnapshotEnabled: true },
+ { autoSnapshotEnabled: true, autoInitProjectGit: true },
);
expect(createShadowSavepoint).toHaveBeenCalledWith(
'/workspace/project',
@@ -201,6 +202,7 @@ describe('createGitSnapshotCoordinator', () => {
const createShadowSavepoint = vi.fn();
await createGitSnapshotCoordinator(maker, {
+ readAutoSnapshotEnabled: () => false,
createShadowSavepoint,
logger,
}).onTurnEnd('s1');
diff --git a/apps/desktop/src/main/__tests__/isolatedGitExec.test.ts b/apps/desktop/src/main/__tests__/isolatedGitExec.test.ts
new file mode 100644
index 0000000000..23541fc3c9
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/isolatedGitExec.test.ts
@@ -0,0 +1,96 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const gitExecMock = vi.hoisted(() => vi.fn());
+
+vi.mock('../worktree/gitExec', () => ({
+ gitExec: (...args: unknown[]) => gitExecMock(...args),
+}));
+
+import {
+ isolatedGitExec,
+ snapshotGitIsolationArgs,
+ SnapshotGitIsolationError,
+} from '../git-snapshot/isolatedGitExec';
+
+describe('isolatedGitExec', () => {
+ beforeEach(() => {
+ gitExecMock.mockReset();
+ gitExecMock.mockResolvedValue({ stdout: '', stderr: '' });
+ });
+
+ it('disables repository-local fsmonitor, hooks, and LFS filters including required', async () => {
+ await isolatedGitExec(['status', '--porcelain=v1', '-z'], '/repo');
+
+ expect(gitExecMock).toHaveBeenCalledTimes(2);
+ const listArgs = gitExecMock.mock.calls[0][0] as string[];
+ expect(listArgs.slice(-4)).toEqual(['config', '--null', '--name-only', '--list']);
+ const [args, cwd] = gitExecMock.mock.calls[1] as [string[], string];
+ expect(cwd).toBe('/repo');
+ expect(args).toContain('core.fsmonitor=');
+ expect(args).toContain('core.useBuiltinFSMonitor=false');
+ expect(args).toContain('filter.lfs.clean=');
+ expect(args).toContain('filter.lfs.smudge=');
+ expect(args).toContain('filter.lfs.process=');
+ expect(args).toContain('filter.lfs.required=false');
+ expect(args.some((arg) => arg.startsWith('core.hooksPath='))).toBe(true);
+ expect(args[args.length - 3]).toBe('status');
+ expect(args.slice(-2)).toEqual(['--porcelain=v1', '-z']);
+ });
+
+ it('overrides arbitrary discovered filter and textconv drivers', async () => {
+ gitExecMock.mockImplementation(async (args: readonly string[]) => {
+ if (args.includes('config')) {
+ return {
+ stdout: [
+ 'filter.evil.process',
+ 'filter.evil.required',
+ 'filter.evil=x.process',
+ 'diff.evil.textconv',
+ 'filter.lfs.required',
+ 'user.name',
+ ].join('\0'),
+ stderr: '',
+ };
+ }
+ return { stdout: '', stderr: '' };
+ });
+
+ await isolatedGitExec(['add', '-A'], '/repo');
+
+ const commandArgs = gitExecMock.mock.calls[1][0] as string[];
+ expect(commandArgs).toContain('filter.evil.process=');
+ expect(commandArgs).toContain('filter.evil.required=false');
+ expect(commandArgs).toContain('filter.evil=x.process=');
+ expect(commandArgs).toContain('diff.evil.textconv=');
+ expect(commandArgs).toContain('filter.lfs.required=false');
+ expect(commandArgs.slice(-2)).toEqual(['add', '-A']);
+ });
+
+ it('injects --no-textconv and --no-ext-diff for snapshot diffs', async () => {
+ await isolatedGitExec(['diff', '--cached'], '/repo');
+ const commandArgs = gitExecMock.mock.calls[1][0] as string[];
+ expect(commandArgs).toContain('diff.external=');
+ expect(commandArgs.slice(-4)).toEqual(['diff', '--no-textconv', '--no-ext-diff', '--cached']);
+ });
+
+ it('aborts when repository config cannot be listed', async () => {
+ gitExecMock.mockRejectedValueOnce(new Error('maxBuffer length exceeded'));
+ await expect(isolatedGitExec(['add', '-A'], '/repo')).rejects.toBeInstanceOf(
+ SnapshotGitIsolationError,
+ );
+ expect(gitExecMock).toHaveBeenCalledTimes(1);
+ expect((gitExecMock.mock.calls[0][0] as string[]).slice(-4)).toEqual([
+ 'config',
+ '--null',
+ '--name-only',
+ '--list',
+ ]);
+ });
+
+ it('keeps isolation args ahead of the git subcommand', () => {
+ const args = snapshotGitIsolationArgs('/tmp/empty-hooks');
+ expect(args.indexOf('core.fsmonitor=')).toBeLessThan(args.length);
+ expect(args[1]).toBe('core.hooksPath=/tmp/empty-hooks');
+ expect(args).toContain('filter.lfs.required=false');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts b/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts
index 4be05202de..12fe90af5e 100644
--- a/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts
+++ b/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts
@@ -13,7 +13,7 @@ vi.mock('../localDb/schema', () => ({ sessions: {} }));
vi.mock('../localDb/mapper', () => ({ sessionCreateToRow: (id: string, row: object) => ({ id, ...row }) }));
vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));
vi.mock('../git-snapshot/projectGitBootstrap', () => ({ ensureProjectGitInitialized: mocks.bootstrap }));
-vi.mock('../maker-host/git-safety-settings-store', () => ({ readGitSafetySettings: () => ({ autoSnapshotEnabled: true }) }));
+vi.mock('../maker-host/git-safety-settings-store', () => ({ readGitSafetySettings: () => ({ mode: 'all-projects', autoSnapshotEnabled: true, autoInitProjectGit: true }) }));
vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: mocks.recent }));
vi.mock('../localDb/pluginWorkspaceDedupe', () => ({ pickSessionForWorkdir: vi.fn() }));
vi.mock('../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));
diff --git a/apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.ts b/apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.ts
index f5f6514420..da4f13bca6 100644
--- a/apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/projectGitBootstrap.git-integration.test.ts
@@ -129,6 +129,20 @@ describe('projectGitBootstrap', () => {
expect(await isGitRepo(dir)).toBe(false);
});
+ it('does not initialize an empty project in existing-Git-only mode', async () => {
+ const dir = await makeTempDir();
+
+ const result = await ensureProjectGitInitialized({
+ workingDir: dir,
+ workspaceKind: 'local',
+ autoSnapshotEnabled: true,
+ autoInitProjectGit: false,
+ });
+
+ expect(result).toMatchObject({ status: 'skipped', reason: 'git-safety-disabled' });
+ expect(await isGitRepo(dir)).toBe(false);
+ });
+
it('initializes an empty local project and creates an empty XDT savepoint commit', async () => {
const dir = await makeTempDir();
diff --git a/apps/desktop/src/main/__tests__/rewind.test.ts b/apps/desktop/src/main/__tests__/rewind.test.ts
index dfed17fb8b..1a5430b9d1 100644
--- a/apps/desktop/src/main/__tests__/rewind.test.ts
+++ b/apps/desktop/src/main/__tests__/rewind.test.ts
@@ -1221,6 +1221,7 @@ describe('commitRewindAtMessage', () => {
await blocker;
await expect(preview).resolves.toEqual({
canRewind: true,
+ conversationOnly: true,
filesChanged: [],
insertions: 0,
deletions: 0,
@@ -1306,6 +1307,39 @@ describe('commitRewindAtMessage', () => {
expect(result.id).toBe('sess-1');
});
+ it('Codex commit: allowFileRestore=false skips file restore even if savepoints exist', async () => {
+ useFakeSession('codex');
+ detectCwdMock.mockResolvedValueOnce({ gitInstalled: true, isGitRepo: true, repoRoot: '/repo', isInsideWorktree: false });
+ listShadowSavepointsMock.mockResolvedValueOnce([
+ {
+ commit: 'sc1',
+ sessionId: 'sess-1',
+ kind: 'after-edit',
+ source: 'cindy',
+ parentCount: 1,
+ anchor: 'client-id',
+ baselineCommit: 'base1',
+ label: '本轮修改',
+ time: '2026-08-04T00:00:00+08:00',
+ },
+ ]);
+ commitRewindFilesMock.mockResolvedValueOnce({ sdkSessionId: 'conversation-thread-id' });
+ selectQueue.push(
+ [makeUserMessageRow({ agentMeta: null })],
+ [],
+ [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })],
+ [],
+ [makeSessionRow({ agentKind: 'codex' })],
+ );
+
+ await commitRewindAtMessage('sess-1', 'client-id', { allowFileRestore: false });
+
+ expect(executeCodexFileRestorePlanWithThreadRollbackMock).not.toHaveBeenCalled();
+ expect(executeCodexFileRewindPlanWithThreadRollbackMock).not.toHaveBeenCalled();
+ expect(listShadowSavepointsMock).not.toHaveBeenCalled();
+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });
+ });
+
it('Codex commit: legacy file-rewind 计划仍分发给 revert 执行器', async () => {
useFakeSession('codex');
detectCwdMock.mockResolvedValueOnce({ gitInstalled: true, isGitRepo: true, repoRoot: '/repo', isInsideWorktree: false });
diff --git a/apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.ts b/apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.ts
index d8f479da6d..7092bfb480 100644
--- a/apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/snapshotFileFilter.git-integration.test.ts
@@ -81,6 +81,22 @@ describe('buildSnapshotFilePlan', () => {
]);
});
+ it('does not execute repository-local fsmonitor when reading git status', async () => {
+ const marker = path.join(testRoot, 'fsmonitor-ran');
+ const script = path.join(testRoot, 'fsmonitor.js');
+ await fs.writeFile(
+ script,
+ `require('fs').writeFileSync(${JSON.stringify(marker)}, 'ran');\nprocess.exit(0);\n`,
+ );
+ await git(repoPath, ['config', 'core.fsmonitor', `node ${JSON.stringify(script)}`]);
+ await writeRepoFile(repoPath, 'src/app.ts', 'export const value = 1;\n');
+
+ const plan = await buildSnapshotFilePlan(repoPath);
+
+ expect(plan.includedFiles.map((file) => file.path)).toEqual(['src/app.ts']);
+ await expect(fs.access(marker)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
it('skips sensitive paths while allowing env templates', async () => {
await writeRepoFile(repoPath, '.env', 'TOKEN=secret\n');
await writeRepoFile(repoPath, 'config/secrets.json', '{}\n');
diff --git a/apps/desktop/src/main/__tests__/snapshotFilterOverflow.test.ts b/apps/desktop/src/main/__tests__/snapshotFilterOverflow.test.ts
index b806787696..c27888a44c 100644
--- a/apps/desktop/src/main/__tests__/snapshotFilterOverflow.test.ts
+++ b/apps/desktop/src/main/__tests__/snapshotFilterOverflow.test.ts
@@ -48,6 +48,9 @@ function installOverflowGitExec(): void {
err.message = 'spawn maxBuffer length exceeded';
throw err;
}
+ if (args.includes('config') && args.includes('--list')) {
+ return { stdout: '', stderr: '' };
+ }
if (args.includes('--git-path')) {
return { stdout: 'no-such-marker\n', stderr: '' };
}
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 3827874053..2ef7fb9141 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -880,7 +880,8 @@ import { createChatEmbeddingSettingsWatcher } from './maker-host/chat-embedding-
import {
readGitSafetySettingsState,
resetGitSafetySettings,
- writeGitSafetyAutoSnapshotEnabled,
+ writeGitSafetyMode,
+ type GitSafetyMode,
} from './maker-host/git-safety-settings-store.js';
import {
CHAT_EMBED_MODEL_ID,
@@ -5011,11 +5012,12 @@ const registerIpcHandlers = () => {
ipcMain.handle(MAKER_IPC_INVOKE.GIT_SAFETY_GET, async () => {
return gitSafetyWire();
});
- ipcMain.handle(MAKER_IPC_INVOKE.GIT_SAFETY_SET, async (_e, enabled: unknown) => {
- if (typeof enabled !== 'boolean') {
- throwIpcError('INVALID_PARAMS', 'git safety enabled required (boolean)');
+ ipcMain.handle(MAKER_IPC_INVOKE.GIT_SAFETY_SET, async (_e, mode: unknown) => {
+ if (typeof mode === 'boolean') mode = mode ? 'all-projects' : 'off';
+ if (mode !== 'off' && mode !== 'existing-git' && mode !== 'all-projects') {
+ throwIpcError('INVALID_PARAMS', 'git safety mode required');
}
- writeGitSafetyAutoSnapshotEnabled(enabled);
+ writeGitSafetyMode(mode as GitSafetyMode);
return gitSafetyWire();
});
ipcMain.handle(MAKER_IPC_INVOKE.GIT_SAFETY_RESET, async () => {
@@ -10202,8 +10204,11 @@ function chatEmbeddingWire() {
function gitSafetyWire() {
const state = readGitSafetySettingsState();
return {
+ mode: state.value.mode,
autoSnapshotEnabled: state.value.autoSnapshotEnabled,
+ autoInitProjectGit: state.value.autoInitProjectGit,
isCustomized: state.isCustomized,
+ defaultMode: state.defaults.mode,
defaultAutoSnapshotEnabled: state.defaults.autoSnapshotEnabled,
};
}
diff --git a/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts b/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts
index e6d0e664d2..6cfca73a89 100644
--- a/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts
+++ b/apps/desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts
@@ -32,13 +32,15 @@ export interface GitSnapshotSessionContext {
export interface GitSnapshotCoordinatorDeps {
/** Global auto-snapshot switch; turn-start decisions are reused at matching turn end. */
readAutoSnapshotEnabled: () => boolean;
+ /** Whether an empty local project may be initialized as Git during resolution. */
+ readAutoInitProjectGit?: () => boolean;
/** Resolves a working directory to a Git repo root, or null for non-Git dirs. */
detectRepoRoot: (workingDir: string) => Promise<string | null>;
/** Best-effort bootstrap for local empty project dirs that are not Git repos yet. */
initializeProjectGit?: (
sessionId: string,
context: GitSnapshotSessionContext,
- opts: { autoSnapshotEnabled: boolean },
+ opts: { autoSnapshotEnabled: boolean; autoInitProjectGit?: boolean },
) => Promise<{ repoRoot?: string | null } | null>;
/** Session lookup used for workingDir detection and label-agent routing. */
getSessionContext: (sessionId: string) => Promise<GitSnapshotSessionContext | null>;
@@ -77,6 +79,7 @@ interface TurnStartState {
interface TurnStartRecord extends Partial<TurnStartState> {
autoSnapshotEnabled: boolean;
+ autoInitProjectGit: boolean;
promise: Promise<void>;
/** Owning session, for same-repo concurrency checks across sessions. */
ownerSessionId?: string;
@@ -109,8 +112,10 @@ export class GitSnapshotCoordinator {
* shadow savepoint chain as the baseline for this turn's file rewind.
*/
async onTurnStart(sessionId: string): Promise<void> {
+ const autoSnapshotEnabled = this.deps.readAutoSnapshotEnabled();
const record: TurnStartRecord = {
- autoSnapshotEnabled: this.deps.readAutoSnapshotEnabled(),
+ autoSnapshotEnabled,
+ autoInitProjectGit: this.deps.readAutoInitProjectGit?.() ?? autoSnapshotEnabled,
promise: Promise.resolve(),
ownerSessionId: sessionId,
};
@@ -129,7 +134,11 @@ export class GitSnapshotCoordinator {
return;
}
- const resolved = await this.resolveSession(sessionId, record.autoSnapshotEnabled);
+ const resolved = await this.resolveSession(
+ sessionId,
+ record.autoSnapshotEnabled,
+ record.autoInitProjectGit,
+ );
if (!resolved) {
return;
}
@@ -165,12 +174,19 @@ export class GitSnapshotCoordinator {
const turnStart = this.shiftTurnStartRecord(sessionId);
try {
const autoSnapshotEnabled = turnStart?.autoSnapshotEnabled ?? this.deps.readAutoSnapshotEnabled();
+ const autoInitProjectGit = turnStart
+ ? turnStart.autoInitProjectGit
+ : this.deps.readAutoInitProjectGit?.() ?? autoSnapshotEnabled;
if (!autoSnapshotEnabled) return;
if (turnStart && !turnStart.repoRoot) {
await turnStart.promise;
}
- const resolved = await this.resolveSession(sessionId, autoSnapshotEnabled);
+ const resolved = await this.resolveSession(
+ sessionId,
+ autoSnapshotEnabled,
+ autoInitProjectGit,
+ );
if (!resolved) return;
await enqueueGitRepoWrite(resolved.repoRoot, async () => {
@@ -209,6 +225,7 @@ export class GitSnapshotCoordinator {
private async resolveSession(
sessionId: string,
autoSnapshotEnabled: boolean = this.deps.readAutoSnapshotEnabled(),
+ autoInitProjectGit: boolean = this.deps.readAutoInitProjectGit?.() ?? autoSnapshotEnabled,
): Promise<ResolvedSnapshotSession | null> {
const cached = this.sessionCache.get(sessionId);
if (cached) return cached;
@@ -217,8 +234,11 @@ export class GitSnapshotCoordinator {
if (!ctx?.workingDir) return null;
let repoRoot = await this.deps.detectRepoRoot(ctx.workingDir);
- if (!repoRoot && this.deps.initializeProjectGit) {
- const bootstrap = await this.deps.initializeProjectGit?.(sessionId, ctx, { autoSnapshotEnabled });
+ if (!repoRoot && autoInitProjectGit && this.deps.initializeProjectGit) {
+ const bootstrap = await this.deps.initializeProjectGit?.(sessionId, ctx, {
+ autoSnapshotEnabled,
+ autoInitProjectGit,
+ });
repoRoot = bootstrap?.repoRoot ?? null;
if (!repoRoot) {
repoRoot = await this.deps.detectRepoRoot(ctx.workingDir);
diff --git a/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts b/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts
index f668a12be1..0e2fc38def 100644
--- a/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts
+++ b/apps/desktop/src/main/git-snapshot/gitSnapshotService.ts
@@ -12,6 +12,7 @@ import path from 'node:path';
import { createLogger } from '../logger';
import { gitExec, GitExecError } from '../worktree/gitExec';
+import { isolatedGitExec, snapshotGitIsolationArgs } from './isolatedGitExec';
import { gitPathOutput } from '../worktree/gitPathOutput';
import {
buildSnapshotFilePlan,
@@ -196,8 +197,7 @@ export async function createSnapshotMarker(
await withDisabledHooks((hooksPath) =>
gitExec(
[
- '-c',
- `core.hooksPath=${toGitConfigPath(hooksPath)}`,
+ ...snapshotGitIsolationArgs(hooksPath),
...(input.author
? ['-c', `user.name=${input.author.name}`, '-c', `user.email=${input.author.email}`]
: []),
@@ -256,7 +256,7 @@ export async function createSnapshotDetailed(
const result = await withTemporaryIndex(repoPath, async (extraEnv) => {
if (stagePathspecs.length > 0) {
await withPathspecFile(stagePathspecs, (pathspecFile) =>
- gitExec(
+ isolatedGitExec(
['add', '-A', '--pathspec-from-file', pathspecFile, '--pathspec-file-nul'],
repoPath,
{ extraEnv },
@@ -295,8 +295,7 @@ export async function createSnapshotDetailed(
await withDisabledHooks((hooksPath) =>
gitExec(
[
- '-c',
- `core.hooksPath=${toGitConfigPath(hooksPath)}`,
+ ...snapshotGitIsolationArgs(hooksPath),
...(input.author
? ['-c', `user.name=${input.author.name}`, '-c', `user.email=${input.author.email}`]
: []),
@@ -504,7 +503,7 @@ export async function createShadowSavepoint(
return withTemporaryIndex(repoPath, async (extraEnv) => {
if (stagePathspecs.length > 0) {
await withPathspecFile(stagePathspecs, (pathspecFile) =>
- gitExec(
+ isolatedGitExec(
['add', '-A', '--pathspec-from-file', pathspecFile, '--pathspec-file-nul'],
repoPath,
{ extraEnv },
@@ -873,7 +872,7 @@ async function safeGitStdout(
extraEnv: Record<string, string>,
): Promise<string> {
try {
- const { stdout } = await gitExec(args, repoPath, { extraEnv });
+ const { stdout } = await isolatedGitExec(args, repoPath, { extraEnv });
return stdout;
} catch (err) {
log.debug('[createSnapshot] git read failed, degrade to empty', {
@@ -903,7 +902,7 @@ async function hasStagedChanges(
extraEnv: Record<string, string>,
): Promise<boolean> {
try {
- await gitExec(['diff', '--cached', '--quiet'], repoPath, { extraEnv });
+ await isolatedGitExec(['diff', '--cached', '--quiet'], repoPath, { extraEnv });
} catch (err) {
if (err instanceof GitExecError && err.exitCode === 1) return true;
throw err;
@@ -999,10 +998,6 @@ async function withDisabledHooks<T>(fn: (hooksPath: string) => Promise<T>): Prom
}
}
-function toGitConfigPath(filePath: string): string {
- return filePath.replace(/\\/g, '/');
-}
-
function isUnbornHeadError(err: GitExecError): boolean {
return /not a valid object name|unknown revision|ambiguous argument|bad revision/i.test(
err.stderr,
@@ -1021,7 +1016,7 @@ async function removeRenameOldPaths(
async function resetCommittedPaths(repoPath: string, pathspecs: readonly string[]): Promise<void> {
for (const chunk of chunkPathspecArgs(pathspecs)) {
- await gitExec(['reset', '-q', '--', ...chunk], repoPath);
+ await isolatedGitExec(['reset', '-q', '--', ...chunk], repoPath);
}
}
diff --git a/apps/desktop/src/main/git-snapshot/isolatedGitExec.ts b/apps/desktop/src/main/git-snapshot/isolatedGitExec.ts
new file mode 100644
index 0000000000..42b60a41b4
--- /dev/null
+++ b/apps/desktop/src/main/git-snapshot/isolatedGitExec.ts
@@ -0,0 +1,136 @@
+/**
+ * Snapshot Git invocations must not honor repository-local executable config.
+ *
+ * Turn-start snapshots now run by default on existing Git directories. A
+ * complete attacker-supplied `.git/config` can set hooks, fsmonitor, filter
+ * drivers, or diff textconv. Every snapshot `git` call overrides those keys.
+ * Config enumeration is fail-closed: if drivers cannot be listed, the
+ * snapshot is aborted instead of running unisolated Git.
+ */
+
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import {
+ gitExec,
+ type GitExecOpts,
+ type GitExecResult,
+} from '../worktree/gitExec';
+
+let emptyHooksDir: Promise<string> | null = null;
+
+function isExecutableDriverKey(key: string): boolean {
+ return (
+ /^diff\.external$/i.test(key) ||
+ /^filter\..+\.(?:clean|smudge|process|required)$/i.test(key) ||
+ /^diff\..+\.(?:textconv|command)$/i.test(key) ||
+ /^merge\..+\.driver$/i.test(key)
+ );
+}
+
+export class SnapshotGitIsolationError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message);
+ this.name = 'SnapshotGitIsolationError';
+ if (options?.cause !== undefined) {
+ (this as Error & { cause?: unknown }).cause = options.cause;
+ }
+ }
+}
+
+function toGitConfigPath(filePath: string): string {
+ return filePath.replace(/\\/g, '/');
+}
+
+async function getEmptyHooksDir(): Promise<string> {
+ if (!emptyHooksDir) {
+ emptyHooksDir = fs.mkdtemp(path.join(os.tmpdir(), 'cindy-snapshot-hooks-'));
+ }
+ return emptyHooksDir;
+}
+
+export function snapshotGitIsolationArgs(hooksPath: string): string[] {
+ return [
+ '-c',
+ `core.hooksPath=${toGitConfigPath(hooksPath)}`,
+ '-c',
+ 'core.fsmonitor=',
+ '-c',
+ 'core.useBuiltinFSMonitor=false',
+ '-c',
+ 'filter.lfs.clean=',
+ '-c',
+ 'filter.lfs.smudge=',
+ '-c',
+ 'filter.lfs.process=',
+ '-c',
+ 'filter.lfs.required=false',
+ '-c',
+ 'diff.external=',
+ ];
+}
+
+function overrideValue(key: string): string {
+ return /\.required$/i.test(key) ? 'false' : '';
+}
+
+function withDisabledExternalDiffHelpers(args: readonly string[]): string[] {
+ const idx = args.indexOf('diff');
+ if (idx === -1) return [...args];
+ const extra: string[] = [];
+ if (!args.includes('--no-textconv')) extra.push('--no-textconv');
+ if (!args.includes('--no-ext-diff')) extra.push('--no-ext-diff');
+ if (extra.length === 0) return [...args];
+ return [...args.slice(0, idx + 1), ...extra, ...args.slice(idx + 1)];
+}
+
+async function discoveredDriverIsolationArgs(
+ isolation: readonly string[],
+ cwd: string,
+ opts?: GitExecOpts,
+): Promise<string[]> {
+ let stdout: string;
+ try {
+ ({ stdout } = await gitExec(
+ [...isolation, 'config', '--null', '--name-only', '--list'],
+ cwd,
+ opts,
+ ));
+ } catch (cause) {
+ throw new SnapshotGitIsolationError(
+ 'snapshot git isolation could not read repository config; aborting automatic snapshot',
+ { cause },
+ );
+ }
+ const overrides = new Map<string, string>();
+ for (const key of stdout.split('\0')) {
+ if (!key || !isExecutableDriverKey(key)) continue;
+ overrides.set(key, overrideValue(key));
+ }
+ const args: string[] = [];
+ for (const [key, value] of overrides) {
+ args.push('-c', `${key}=${value}`);
+ }
+ return args;
+}
+
+export async function isolatedGitExec(
+ args: readonly string[],
+ cwd?: string,
+ opts?: GitExecOpts,
+): Promise<GitExecResult> {
+ const hooksPath = await getEmptyHooksDir();
+ const isolation = snapshotGitIsolationArgs(hooksPath);
+ const command = withDisabledExternalDiffHelpers(args);
+ if (command[0] === 'config') {
+ return gitExec([...isolation, ...command], cwd, opts);
+ }
+ if (!cwd) {
+ throw new SnapshotGitIsolationError(
+ 'snapshot git isolation requires a repository path',
+ );
+ }
+ const drivers = await discoveredDriverIsolationArgs(isolation, cwd, opts);
+ return gitExec([...isolation, ...drivers, ...command], cwd, opts);
+}
diff --git a/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts b/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts
index e36e629f08..fc92ecf8e0 100644
--- a/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts
+++ b/apps/desktop/src/main/git-snapshot/projectGitBootstrap.ts
@@ -27,6 +27,7 @@ export interface ProjectGitBootstrapRequest {
remoteHostId?: string | null;
sessionId?: string | null;
autoSnapshotEnabled?: boolean | null;
+ autoInitProjectGit?: boolean | null;
source?: string;
}
@@ -52,7 +53,9 @@ function getProjectGitBootstrapSkipReason(request: ProjectGitBootstrapRequest):
if (!workingDir) return 'not-local-project';
if (request.workspaceKind === 'dialogue') return 'not-local-project';
if (remoteHostId) return 'not-local-project';
- if (request.autoSnapshotEnabled !== true) return 'git-safety-disabled';
+ if ((request.autoInitProjectGit ?? request.autoSnapshotEnabled) !== true) {
+ return 'git-safety-disabled';
+ }
return null;
}
diff --git a/apps/desktop/src/main/git-snapshot/snapshotFileFilter.ts b/apps/desktop/src/main/git-snapshot/snapshotFileFilter.ts
index 1bbda92ea3..669f7024db 100644
--- a/apps/desktop/src/main/git-snapshot/snapshotFileFilter.ts
+++ b/apps/desktop/src/main/git-snapshot/snapshotFileFilter.ts
@@ -2,7 +2,8 @@ import { promises as fs } from 'node:fs';
import path from 'node:path';
import { detectSensitivePath } from '../security/sensitivePath';
-import { gitExec, GitExecError } from '../worktree/gitExec';
+import { GitExecError } from '../worktree/gitExec';
+import { isolatedGitExec } from './isolatedGitExec';
const DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024;
const DEFAULT_MAX_CONTENT_SCAN_BYTES = DEFAULT_MAX_FILE_BYTES;
@@ -157,7 +158,7 @@ async function readStatusEntries(
repoPath: string,
): Promise<{ entries: SnapshotStatusEntry[]; truncated: boolean }> {
try {
- const { stdout } = await gitExec(
+ const { stdout } = await isolatedGitExec(
['status', '--porcelain=v1', '-z', '--untracked-files=all'],
repoPath,
);
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 27a03b328e..973e6332cc 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -134,7 +134,7 @@ vi.mock('../../../git-snapshot/projectGitBootstrap.js', () => ({
ensureProjectGitInitialized: h.ensureGit,
}));
vi.mock('../../../maker-host/git-safety-settings-store.js', () => ({
- readGitSafetySettings: () => ({ autoSnapshotEnabled: true }),
+ readGitSafetySettings: () => ({ mode: 'all-projects', autoSnapshotEnabled: true, autoInitProjectGit: true }),
}));
vi.mock('../../../maker-host/custom-mcp-store.js', async (importOriginal) => ({
...await importOriginal<typeof import('../../../maker-host/custom-mcp-store.js')>(),
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index d13f04a3c7..ca3946be9f 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -1561,12 +1561,14 @@ export function registerBotIpc(): void {
),
title: profile.displayName,
};
+ const gitSafety = readGitSafetySettings();
await ensureProjectGitInitialized({
workingDir,
workspaceKind,
remoteHostId: null,
sessionId,
- autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,
+ autoSnapshotEnabled: gitSafety.autoSnapshotEnabled,
+ autoInitProjectGit: gitSafety.autoInitProjectGit,
source: 'local-db:bots:create-canonical-session',
});
diff --git a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts
index c92b73e1e8..50fcde400c 100644
--- a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts
@@ -114,14 +114,16 @@ export async function createPluginDraftSession(params: {
source: 'plugin' as const,
...(params.title ? { title: params.title } : {}),
};
- // 与 local-db:sessions:create 同流程:空目录且用户开了快照才会 git init,
- // 非空目录/未开快照原样跳过(projectGitBootstrap 自带守卫)。
+ // 与 local-db:sessions:create 同流程:只有“所有项目”模式才会给空目录 git init,
+ // 已有 Git 项目仍可在“已有 Git 项目”模式下记录保存点。
+ const gitSafety = readGitSafetySettings();
await ensureProjectGitInitialized({
workingDir: insertRow.workingDir,
workspaceKind: insertRow.workspaceKind,
remoteHostId: insertRow.remoteHostId,
sessionId: id,
- autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,
+ autoSnapshotEnabled: gitSafety.autoSnapshotEnabled,
+ autoInitProjectGit: gitSafety.autoInitProjectGit,
source: 'plugin-workspace-session',
});
if (params.shouldContinue && !params.shouldContinue()) return null;
@@ -204,12 +206,14 @@ export async function createGhostErrandSession(params: {
...(params.title ? { title: params.title } : {}),
};
// 与既有 create 同流程;dialogue 目录由 projectGitBootstrap 自带守卫跳过。
+ const gitSafety = readGitSafetySettings();
await ensureProjectGitInitialized({
workingDir: insertRow.workingDir,
workspaceKind: insertRow.workspaceKind,
remoteHostId: insertRow.remoteHostId,
sessionId: id,
- autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,
+ autoSnapshotEnabled: gitSafety.autoSnapshotEnabled,
+ autoInitProjectGit: gitSafety.autoInitProjectGit,
source: 'plugin-errand-session',
});
await db.insert(sessions).values(insertRow);
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 123790e029..70029ef394 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -1388,12 +1388,14 @@ export function registerSessionIpc(
}
// body 透传 agentKind / orcaRole 给 mapper;非法值已由上方校验拦截,默认值由 mapper 兜底。
const insertRow = sessionCreateToRow(id, { ...createBody, workspaceKind, workingDir }, now);
+ const gitSafety = readGitSafetySettings();
await ensureProjectGitInitialized({
workingDir: insertRow.workingDir,
workspaceKind: insertRow.workspaceKind,
remoteHostId: insertRow.remoteHostId,
sessionId: id,
- autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,
+ autoSnapshotEnabled: gitSafety.autoSnapshotEnabled,
+ autoInitProjectGit: gitSafety.autoInitProjectGit,
source: 'local-db:sessions:create',
});
const resource =
diff --git a/apps/desktop/src/main/maker-host/git-safety-settings-store.ts b/apps/desktop/src/main/maker-host/git-safety-settings-store.ts
index 6ecdf5706f..0f6391103d 100644
--- a/apps/desktop/src/main/maker-host/git-safety-settings-store.ts
+++ b/apps/desktop/src/main/maker-host/git-safety-settings-store.ts
@@ -2,11 +2,11 @@
* git-safety-settings-store —— Git safety workflow machine settings.
*
* File: <userData>/git-safety-settings.json
- * { "autoSnapshotEnabled": true }
+ * { "mode": "existing-git" }
*
- * Default off: automatic commits must be an explicit opt-in. The override file
- * stores only customized fields, so future default changes can flow to users
- * who never changed the setting.
+ * New installs snapshot existing Git projects without initializing empty
+ * folders. The override file stores only customized fields, so future default
+ * changes can flow to users who never changed the setting.
*/
import { app } from 'electron';
@@ -20,55 +20,114 @@ import {
const log = desktopMakerLogger.child('git-safety-settings-store');
+export type GitSafetyMode = 'off' | 'existing-git' | 'all-projects';
+
export interface GitSafetySettings {
+ mode: GitSafetyMode;
+ /** Derived compatibility field for existing snapshot consumers. */
autoSnapshotEnabled: boolean;
+ /** Whether an empty local non-Git project may be bootstrapped. */
+ autoInitProjectGit: boolean;
+}
+
+interface PersistedGitSafetySettings {
+ mode: GitSafetyMode;
}
-const DEFAULTS: GitSafetySettings = {
- autoSnapshotEnabled: false,
+const DEFAULTS: PersistedGitSafetySettings = {
+ mode: 'existing-git',
};
function settingsFilePath(): string {
return path.join(app.getPath('userData'), 'git-safety-settings.json');
}
-function normalize(raw: unknown): GitSafetySettings {
+function normalize(raw: unknown): PersistedGitSafetySettings {
if (!raw || typeof raw !== 'object') return { ...DEFAULTS };
const r = raw as Record<string, unknown>;
+ const legacyMode =
+ typeof r.autoSnapshotEnabled === 'boolean'
+ ? r.autoSnapshotEnabled
+ ? 'all-projects'
+ : 'off'
+ : undefined;
+ const mode: GitSafetyMode =
+ legacyMode !== undefined && (r.mode === undefined || r.mode === DEFAULTS.mode)
+ ? legacyMode
+ : r.mode === 'off' || r.mode === 'existing-git' || r.mode === 'all-projects'
+ ? r.mode
+ : DEFAULTS.mode;
+ return {
+ mode,
+ };
+}
+
+function derive(persisted: PersistedGitSafetySettings): GitSafetySettings {
return {
- autoSnapshotEnabled:
- typeof r.autoSnapshotEnabled === 'boolean'
- ? r.autoSnapshotEnabled
- : DEFAULTS.autoSnapshotEnabled,
+ mode: persisted.mode,
+ autoSnapshotEnabled: persisted.mode !== 'off',
+ autoInitProjectGit: persisted.mode === 'all-projects',
};
}
-const store = createOverrideSettingsFile<GitSafetySettings>({
+function mergeOverrides({
+ patch,
+ next,
+ overrides,
+}: {
+ patch: Partial<PersistedGitSafetySettings>;
+ next: PersistedGitSafetySettings;
+ overrides: Record<string, unknown>;
+}): Record<string, unknown> {
+ const updated = { ...overrides };
+ if (Object.prototype.hasOwnProperty.call(patch, 'mode')) {
+ // Keep an explicit selection even when it matches today's default. This
+ // preserves the user's choice if the default changes in a later release.
+ updated.mode = next.mode;
+ delete updated.autoSnapshotEnabled;
+ }
+ return updated;
+}
+
+const store = createOverrideSettingsFile<PersistedGitSafetySettings>({
filePath: settingsFilePath,
defaults: DEFAULTS,
normalize,
+ mergeOverrides,
log,
label: 'git safety',
});
export function readGitSafetySettings(): GitSafetySettings {
- return store.read();
+ return derive(store.read());
}
export function readGitSafetySettingsState(): OverrideSettingsState<GitSafetySettings> {
- return store.readState();
+ const state = store.readState();
+ return {
+ ...state,
+ value: derive(state.value),
+ defaults: derive(state.defaults),
+ };
+}
+
+export function writeGitSafetyMode(
+ mode: GitSafetyMode,
+): OverrideSettingsState<GitSafetySettings> {
+ store.writePatch({ mode });
+ log.info('git safety setting written', { mode });
+ return readGitSafetySettingsState();
}
+/** Compatibility for callers still sending the old boolean during migration. */
export function writeGitSafetyAutoSnapshotEnabled(
autoSnapshotEnabled: boolean,
): OverrideSettingsState<GitSafetySettings> {
- store.writePatch({ autoSnapshotEnabled });
- log.info('git safety setting written', { autoSnapshotEnabled });
- return store.readState();
+ return writeGitSafetyMode(autoSnapshotEnabled ? 'all-projects' : 'off');
}
export function resetGitSafetySettings(): GitSafetySettings {
- return store.reset();
+ return derive(store.reset());
}
-export const __testing = { normalize };
+export const __testing = { mergeOverrides, normalize };
diff --git a/apps/desktop/src/main/maker-host/git-snapshot-host.ts b/apps/desktop/src/main/maker-host/git-snapshot-host.ts
index 5e77cdd8e3..e20660e35f 100644
--- a/apps/desktop/src/main/maker-host/git-snapshot-host.ts
+++ b/apps/desktop/src/main/maker-host/git-snapshot-host.ts
@@ -38,6 +38,7 @@ interface LatestUserMessage {
/** Optional dependency overrides used by focused main-process unit tests. */
export interface GitSnapshotCoordinatorHostDeps {
readAutoSnapshotEnabled?: () => boolean;
+ readAutoInitProjectGit?: () => boolean;
detectRepoRoot?: (workingDir: string) => Promise<string | null>;
initializeProjectGit?: ConstructorParameters<
typeof GitSnapshotCoordinator
@@ -103,6 +104,8 @@ export function createGitSnapshotCoordinator(
return new GitSnapshotCoordinator({
readAutoSnapshotEnabled:
deps.readAutoSnapshotEnabled ?? (() => readGitSafetySettings().autoSnapshotEnabled),
+ readAutoInitProjectGit:
+ deps.readAutoInitProjectGit ?? (() => readGitSafetySettings().autoInitProjectGit),
detectRepoRoot: deps.detectRepoRoot ?? defaultDetectRepoRoot,
initializeProjectGit:
deps.initializeProjectGit ??
@@ -113,6 +116,7 @@ export function createGitSnapshotCoordinator(
remoteHostId: context.remoteHostId,
sessionId,
autoSnapshotEnabled: opts.autoSnapshotEnabled,
+ autoInitProjectGit: opts.autoInitProjectGit,
source: 'git-snapshot:on-turn',
})),
getSessionContext: async (sessionId) => {
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index 7bc540fac2..d55c9fde38 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -1906,12 +1906,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
childSessionId = prepared.sessionId;
input.session = { ...input.session, workingDir: prepared.workingDir, workspaceKind: 'project' };
}
+ const gitSafety = readGitSafetySettings();
await ensureProjectGitInitialized({
workingDir: input.session.workingDir,
workspaceKind: input.session.workspaceKind ?? 'dialogue',
remoteHostId: null,
sessionId: childSessionId,
- autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,
+ autoSnapshotEnabled: gitSafety.autoSnapshotEnabled,
+ autoInitProjectGit: gitSafety.autoInitProjectGit,
source: 'bot-delegation',
}).catch(async error => {
if (input.useWorktree) await deps.discardUnusedWorktree?.(childSessionId);
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 593153aad3..9e1c28592d 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -419,8 +419,9 @@ export const MAKER_INVOKE = {
CHAT_EMBEDDING_SET: 'maker:chat-embedding:set',
CHAT_EMBEDDING_RESET: 'maker:chat-embedding:reset',
/**
- * Git safety workflow: automatic XDT snapshot commits and the dependent
- * Codex file rewind entry. Default false; SET writes a user override.
+ * Git safety workflow: three-state automatic XDT savepoint policy. File
+ * rewind remains available as conversation-only rewind when no savepoint
+ * exists; SET writes a user override.
*/
GIT_SAFETY_GET: 'maker:git-safety:get',
GIT_SAFETY_SET: 'maker:git-safety:set',
diff --git a/apps/desktop/src/main/maker-ipc/rewind.ts b/apps/desktop/src/main/maker-ipc/rewind.ts
index c9b0b32d2c..710fb5b42d 100644
--- a/apps/desktop/src/main/maker-ipc/rewind.ts
+++ b/apps/desktop/src/main/maker-ipc/rewind.ts
@@ -41,7 +41,7 @@ const STOPPED_REWIND_TIMEOUT_MS = 15_000;
async function commitAfterStopping(
sessionId: string,
clientId: string,
- opts: { requireLatestUser: boolean },
+ opts: { requireLatestUser: boolean; allowFileRestore?: boolean },
) {
const deadline = Date.now() + STOPPED_REWIND_TIMEOUT_MS;
while (true) {
@@ -59,7 +59,7 @@ async function commitAfterStopping(
async function commitAfterPersistBarrier(
sessionId: string,
clientId: string,
- opts: { requireLatestUser: boolean },
+ opts: { requireLatestUser: boolean; allowFileRestore?: boolean },
) {
// Rewind must see every chat/Subagent observation that was already queued
// before its transaction chooses the visible tail. Otherwise a delayed
@@ -119,6 +119,15 @@ export function registerMakerRewindIpc(): void {
const stopIfRunning =
!!opts && typeof opts === 'object' &&
(opts as { stopIfRunning?: unknown }).stopIfRunning === true;
+ const allowFileRestore =
+ !!opts && typeof opts === 'object' &&
+ (opts as { allowFileRestore?: unknown }).allowFileRestore === false
+ ? false
+ : undefined;
+ const commitOpts = {
+ requireLatestUser,
+ ...(allowFileRestore === false ? { allowFileRestore: false as const } : {}),
+ };
let subagentFence: SubagentRewindFence | null = null;
// This flag controls observation-generation advancement, not whether
// the underlying message transaction has already committed.
@@ -134,8 +143,8 @@ export function registerMakerRewindIpc(): void {
// transaction. Edit-last-message keeps its existing direct orchestration.
const result = stopIfRunning
? await withSessionInputStoppedForRewind(sid, () =>
- commitAfterStopping(sid, cid, { requireLatestUser }))
- : await commitAfterPersistBarrier(sid, cid, { requireLatestUser });
+ commitAfterStopping(sid, cid, commitOpts))
+ : await commitAfterPersistBarrier(sid, cid, commitOpts);
visibleSubagentIdentitiesAfterCommit =
await listVisibleSubagentObservationIdentities(sid);
// The fence may advance generations only after the post-commit
diff --git a/apps/desktop/src/main/maker-orchestration/rewind.ts b/apps/desktop/src/main/maker-orchestration/rewind.ts
index fe1cf408e1..5dd7f31e36 100644
--- a/apps/desktop/src/main/maker-orchestration/rewind.ts
+++ b/apps/desktop/src/main/maker-orchestration/rewind.ts
@@ -27,6 +27,7 @@ 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 { readGitSafetySettings } from '../maker-host/git-safety-settings-store.js';
import type { Session } from '../../renderer/lib/ccAgent.types';
import type { RewindFilesResult } from '@cindy/maker-core';
@@ -398,6 +399,7 @@ export async function previewRewindAtMessage(
// 老 Claude 消息没有 user uuid:文件层面没有可预览 checkpoint,仅截断对话历史。
return {
canRewind: true,
+ conversationOnly: true,
filesChanged: [],
insertions: 0,
deletions: 0,
@@ -410,7 +412,18 @@ export async function previewRewindAtMessage(
async function previewCodexFileRewindPlan(plan: CodexRewindPlan): Promise<RewindFilesResult> {
if (plan.mode === 'file-restore') return previewCodexFileRestorePlan(plan);
- if (plan.mode !== 'file-rewind') return { canRewind: true, filesChanged: [], insertions: 0, deletions: 0 };
+ if (plan.mode !== 'file-rewind') {
+ const gitSafetyDisabled =
+ plan.fallbackReason === 'no-savepoints' && !readGitSafetySettings().autoSnapshotEnabled;
+ return {
+ canRewind: true,
+ conversationOnly: true,
+ ...(gitSafetyDisabled ? { gitSafetyDisabled: true } : {}),
+ filesChanged: [],
+ insertions: 0,
+ deletions: 0,
+ };
+ }
const files = new Set<string>(); let insertions = 0; let deletions = 0;
for (const commit of plan.revertCommitsNewestFirst) {
const { stdout } = await gitExec(['show', '--format=', '--numstat', commit], plan.repoRoot);
@@ -619,7 +632,7 @@ async function loadCodexRewindNativeBoundary(
export async function commitRewindAtMessage(
sessionId: string,
clientId: string,
- opts?: { requireLatestUser?: boolean },
+ opts?: { requireLatestUser?: boolean; allowFileRestore?: boolean },
): Promise<Session> {
const ctx = await loadRewindContext(sessionId, clientId, opts);
@@ -635,7 +648,6 @@ export async function commitRewindAtMessage(
let rewindResult: Awaited<ReturnType<typeof makerSession.commitRewindFiles>> | undefined;
let nativeForkAnchorSessionMap: Array<[string, string]> | undefined;
if (ctx.agentKind === 'codex' || ctx.agentKind === 'pi') {
- const filePlan = await buildCodexFilePlanForSession(sessionId, clientId, ctx.codexUserMessages ?? [], makerSession);
// Codex 分页线程拒绝 thread/rollback(#4421):把 target 之前的原生 turn 边界
// (持久化锚点或事件时间戳)一并交给 maker-core,遇拒绝时改走 thread/fork。
const { sdkSessionId: previousSdkSessionId, ...nativeBoundary } =
@@ -651,21 +663,28 @@ export async function commitRewindAtMessage(
error: compErr instanceof Error ? compErr.message : String(compErr),
});
};
- // shadow 保存点走文件恢复执行器,legacy 保存点走原 revert 执行器;
- // conversation-only 计划两个执行器都会直接透传 thread rollback。
- const result =
- filePlan.mode === 'file-restore'
- ? await executeCodexFileRestorePlanWithThreadRollback(filePlan, sessionId, {
- commitThreadRollback,
- onCompensationError: (compErr, execution) =>
- logCompensationError(compErr, execution.rollbackCommit),
- })
- : await executeCodexFileRewindPlanWithThreadRollback(filePlan, sessionId, {
- commitThreadRollback,
- onCompensationError: (compErr, execution) =>
- logCompensationError(compErr, execution.rollbackCommit),
- });
- rewindResult = result.threadRollback;
+ // Preview that told the user files would not change must not later restore
+ // them if a savepoint appears between preview and confirm.
+ if (opts?.allowFileRestore === false) {
+ rewindResult = await commitThreadRollback();
+ } else {
+ const filePlan = await buildCodexFilePlanForSession(sessionId, clientId, ctx.codexUserMessages ?? [], makerSession);
+ // shadow 保存点走文件恢复执行器,legacy 保存点走原 revert 执行器;
+ // conversation-only 计划两个执行器都会直接透传 thread rollback。
+ const result =
+ filePlan.mode === 'file-restore'
+ ? await executeCodexFileRestorePlanWithThreadRollback(filePlan, sessionId, {
+ commitThreadRollback,
+ onCompensationError: (compErr, execution) =>
+ logCompensationError(compErr, execution.rollbackCommit),
+ })
+ : await executeCodexFileRewindPlanWithThreadRollback(filePlan, sessionId, {
+ commitThreadRollback,
+ onCompensationError: (compErr, execution) =>
+ logCompensationError(compErr, execution.rollbackCommit),
+ });
+ rewindResult = result.threadRollback;
+ }
// thread/rollback 或分页 fork 换出新 thread id 时,保留消息里的 nativeForkAnchor
// 仍指向旧 thread,下一次回退/fork 会把它们判为异线程锚点丢弃(#4423 review
// P2)。与 fork.session 一样在同一事务里把 sdkSessionId 重映射到新 thread。
@@ -677,11 +696,13 @@ export async function commitRewindAtMessage(
) {
nativeForkAnchorSessionMap = [[previousSdkSessionId, rewindResult.sdkSessionId]];
}
- } else if (ctx.userUuid) {
+ } else if (ctx.userUuid && opts?.allowFileRestore !== false) {
rewindResult = await makerSession.commitRewindFiles(ctx.userUuid, ctx.assistantUuid!);
} else {
log.info(
- `[rewind commit] sid=${sessionId.slice(0, 8)} userUuid missing — skip SDK rewindFiles, only set pendingRewindTo via empty userUuid path`,
+ opts?.allowFileRestore === false
+ ? `[rewind commit] sid=${sessionId.slice(0, 8)} allowFileRestore=false — skip SDK rewindFiles`
+ : `[rewind commit] sid=${sessionId.slice(0, 8)} userUuid missing — skip SDK rewindFiles, only set pendingRewindTo via empty userUuid path`,
);
// 走一遍仅为了让 maker-core 设 pendingRewindTo. 它内部 rewindFiles('') 会 SDK 报错,
// 我们 catch 了 warn + 继续 (close + 设标记仍执行)。这与老链路 "userUuid 缺时跳过
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 918afbc2f2..05e6008cc1 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -3950,7 +3950,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('log-upload:settings-get'),
setLogUploadCrashAuto: (enabled: boolean): Promise<LogUploadSettingsPayload> =>
ipcRenderer.invoke('log-upload:set-crash-auto', enabled === true),
- /** 恢复默认:删掉开关 override,重新跟随当前版本默认值(默认关闭)。 */
+ /** 恢复默认:删掉 override,重新跟随当前版本默认的“已有 Git 项目”模式。 */
resetLogUploadCrashAuto: (): Promise<LogUploadSettingsPayload> =>
ipcRenderer.invoke('log-upload:reset-crash-auto'),
/** 手动上传一次。失败以 IPC 错误码返回(LOG_UPLOAD_* / PRIVACY_CONSENT_REQUIRED)。 */
@@ -6893,22 +6893,31 @@ contextBridge.exposeInMainWorld('electronAPI', {
}> => ipcRenderer.invoke('maker:chat-embedding:reset', owner),
// Git safety workflow —— 控制 turn end 自动 XDT snapshot commit。
- // 默认 false; Codex rewind 按钮跟随该开关显示。
+ // 三态默认只覆盖已有 Git 项目;Codex 对话编辑不依赖此开关。
gitSafetyGet: (): Promise<{
+ mode: 'off' | 'existing-git' | 'all-projects';
autoSnapshotEnabled: boolean;
+ autoInitProjectGit: boolean;
isCustomized: boolean;
+ defaultMode: 'off' | 'existing-git' | 'all-projects';
defaultAutoSnapshotEnabled: boolean;
}> => ipcRenderer.invoke('maker:git-safety:get'),
gitSafetySet: (
- enabled: boolean,
+ mode: 'off' | 'existing-git' | 'all-projects' | boolean,
): Promise<{
+ mode: 'off' | 'existing-git' | 'all-projects';
autoSnapshotEnabled: boolean;
+ autoInitProjectGit: boolean;
isCustomized: boolean;
+ defaultMode: 'off' | 'existing-git' | 'all-projects';
defaultAutoSnapshotEnabled: boolean;
- }> => ipcRenderer.invoke('maker:git-safety:set', enabled),
+ }> => ipcRenderer.invoke('maker:git-safety:set', mode),
gitSafetyReset: (): Promise<{
+ mode: 'off' | 'existing-git' | 'all-projects';
autoSnapshotEnabled: boolean;
+ autoInitProjectGit: boolean;
isCustomized: boolean;
+ defaultMode: 'off' | 'existing-git' | 'all-projects';
defaultAutoSnapshotEnabled: boolean;
}> => ipcRenderer.invoke('maker:git-safety:reset'),
@@ -7229,7 +7238,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
rewindCommit: (
sessionId: string,
clientId: string,
- opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean },
+ opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean; allowFileRestore?: boolean },
): Promise<unknown> => ipcRenderer.invoke('maker:rewind:commit', sessionId, clientId, opts),
fork: (sourceSessionId: string, messageClientId: string): Promise<unknown> =>
ipcRenderer.invoke('maker:fork', sourceSessionId, messageClientId),
diff --git a/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts b/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts
index d5cf8661a2..319472a495 100644
--- a/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts
@@ -152,6 +152,23 @@ describe('commitEditAndResend', () => {
});
});
+ it('conversation-only preview binds rewindCommit to skip file restore', async () => {
+ const { deps } = makeDeps();
+ await commitEditAndResend(
+ {
+ sessionId: SESSION_ID,
+ clientId: CLIENT_ID,
+ text: 'edited text',
+ fallbackWorkingDir: '/repo',
+ allowFileRestore: false,
+ },
+ deps,
+ );
+ expect(deps.rewindCommit).toHaveBeenCalledWith(SESSION_ID, CLIENT_ID, {
+ allowFileRestore: false,
+ });
+ });
+
it('原消息 quotesEncoded 时重发透传标志(opts 第 9 参);未带时不注入', async () => {
const { deps } = makeDeps();
await commitEditAndResend(
diff --git a/apps/desktop/src/renderer/__tests__/gitSafetySettingsWiring.test.ts b/apps/desktop/src/renderer/__tests__/gitSafetySettingsWiring.test.ts
index e10f8a35b8..59179291b7 100644
--- a/apps/desktop/src/renderer/__tests__/gitSafetySettingsWiring.test.ts
+++ b/apps/desktop/src/renderer/__tests__/gitSafetySettingsWiring.test.ts
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
bootstrapGitSafetySettingsFromMain,
getGitSafetyAutoSnapshotEnabled,
+ getGitSafetyMode,
setGitSafetyAutoSnapshotEnabled,
subscribeGitSafetyAutoSnapshotEnabled,
} from '@/lib/gitSafetySettingsStore';
@@ -16,6 +17,7 @@ import {
} from '@/hooks/useGitSafetySettings';
type GitSafetyWire = {
+ mode?: 'off' | 'existing-git' | 'all-projects';
autoSnapshotEnabled: boolean;
isCustomized: boolean;
defaultAutoSnapshotEnabled: boolean;
@@ -23,7 +25,7 @@ type GitSafetyWire = {
function installGitSafetyApi(overrides: {
gitSafetyGet?: () => Promise<GitSafetyWire>;
- gitSafetySet?: (enabled: boolean) => Promise<GitSafetyWire>;
+ gitSafetySet?: (mode: boolean | 'off' | 'existing-git' | 'all-projects') => Promise<GitSafetyWire>;
gitSafetyReset?: () => Promise<GitSafetyWire>;
deviceLinkInvoke?: (deviceId: string, channel: string, args: unknown[]) => Promise<unknown>;
}) {
@@ -81,8 +83,9 @@ describe('Git safety settings wiring', () => {
isCustomized: false,
defaultAutoSnapshotEnabled: false,
}),
- gitSafetySet: async (enabled) => ({
- autoSnapshotEnabled: enabled,
+ gitSafetySet: async (mode) => ({
+ mode: mode === true ? 'all-projects' : mode === false ? 'off' : mode,
+ autoSnapshotEnabled: mode !== false && mode !== 'off',
isCustomized: true,
defaultAutoSnapshotEnabled: false,
}),
@@ -95,7 +98,7 @@ describe('Git safety settings wiring', () => {
await result.current.setAutoSnapshotEnabled(true);
});
- expect(api.gitSafetySet).toHaveBeenCalledWith(true);
+ expect(api.gitSafetySet).toHaveBeenCalledWith('all-projects');
expect(result.current.autoSnapshotEnabled).toBe(true);
expect(result.current.isCustomized).toBe(true);
expect(getGitSafetyAutoSnapshotEnabled()).toBe(true);
@@ -186,4 +189,115 @@ describe('Git safety settings wiring', () => {
expect(api.deviceLinkInvoke).toHaveBeenCalledWith('remote-git-safety-off', 'maker:git-safety:get', []);
expect(result.current).toBe(false);
});
+
+ it('migrates a renderer-only legacy opt-out before applying the new default', async () => {
+ localStorage.setItem('gitSafety.autoSnapshotEnabled', 'false');
+ const api = installGitSafetyApi({
+ gitSafetyGet: async () => ({
+ mode: 'existing-git',
+ autoSnapshotEnabled: true,
+ isCustomized: false,
+ defaultAutoSnapshotEnabled: true,
+ }),
+ gitSafetySet: async () => ({
+ mode: 'off',
+ autoSnapshotEnabled: false,
+ isCustomized: true,
+ defaultAutoSnapshotEnabled: true,
+ }),
+ });
+
+ await bootstrapGitSafetySettingsFromMain();
+
+ expect(api.gitSafetySet).toHaveBeenCalledWith('off');
+ expect(api.gitSafetyGet).not.toHaveBeenCalled();
+ expect(getGitSafetyMode()).toBe('off');
+ expect(getGitSafetyAutoSnapshotEnabled()).toBe(false);
+ });
+
+ it('does not overwrite a legacy opt-out when migration write fails', async () => {
+ localStorage.setItem('gitSafety.autoSnapshotEnabled', 'false');
+ const api = installGitSafetyApi({
+ gitSafetyGet: async () => ({
+ mode: 'existing-git',
+ autoSnapshotEnabled: true,
+ isCustomized: false,
+ defaultAutoSnapshotEnabled: true,
+ }),
+ gitSafetySet: async () => {
+ throw new Error('disk full');
+ },
+ });
+
+ await bootstrapGitSafetySettingsFromMain();
+
+ expect(api.gitSafetySet).toHaveBeenCalledWith('off');
+ expect(api.gitSafetyGet).not.toHaveBeenCalled();
+ expect(localStorage.getItem('gitSafety.mode')).toBeNull();
+ expect(localStorage.getItem('gitSafety.autoSnapshotEnabled')).toBe('false');
+ expect(getGitSafetyMode()).toBe('off');
+ });
+
+ it('does not treat never-configured users as an opt-out', async () => {
+ const api = installGitSafetyApi({
+ gitSafetyGet: async () => ({
+ mode: 'existing-git',
+ autoSnapshotEnabled: true,
+ isCustomized: false,
+ defaultAutoSnapshotEnabled: true,
+ }),
+ });
+
+ await bootstrapGitSafetySettingsFromMain();
+
+ expect(api.gitSafetySet).not.toHaveBeenCalled();
+ expect(getGitSafetyMode()).toBe('existing-git');
+ expect(getGitSafetyAutoSnapshotEnabled()).toBe(true);
+ });
+
+ it('settings refresh does not overwrite a renderer legacy opt-out with the new default', async () => {
+ localStorage.setItem('gitSafety.autoSnapshotEnabled', 'false');
+ const api = installGitSafetyApi({
+ gitSafetyGet: async () => ({
+ mode: 'existing-git',
+ autoSnapshotEnabled: true,
+ isCustomized: false,
+ defaultAutoSnapshotEnabled: true,
+ }),
+ gitSafetySet: async () => ({
+ mode: 'off',
+ autoSnapshotEnabled: false,
+ isCustomized: true,
+ defaultAutoSnapshotEnabled: true,
+ }),
+ });
+
+ const { result } = renderHook(() => useGitSafetySettings());
+ await waitFor(() => expect(api.gitSafetySet).toHaveBeenCalledWith('off'));
+
+ expect(result.current.mode).toBe('off');
+ expect(result.current.autoSnapshotEnabled).toBe(false);
+ expect(getGitSafetyAutoSnapshotEnabled()).toBe(false);
+ });
+
+ it('refreshes customized state when another window re-selects the same mode', async () => {
+ const api = installGitSafetyApi({
+ gitSafetyGet: async () => ({
+ mode: 'existing-git',
+ autoSnapshotEnabled: true,
+ isCustomized: true,
+ defaultAutoSnapshotEnabled: true,
+ }),
+ });
+
+ const { result } = renderHook(() => useGitSafetySettings());
+ await waitFor(() => expect(api.gitSafetyGet).toHaveBeenCalledTimes(1));
+ expect(result.current.isCustomized).toBe(true);
+
+ act(() => {
+ window.dispatchEvent(new StorageEvent('storage', { key: 'gitSafety.sync', newValue: '2' }));
+ });
+
+ await waitFor(() => expect(api.gitSafetyGet).toHaveBeenCalledTimes(2));
+ });
});
diff --git a/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts b/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts
index 1eb557f2a7..00774ae803 100644
--- a/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts
+++ b/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts
@@ -430,4 +430,33 @@ describe('UserMessageEditBox — 取消与键盘', () => {
const { findByText } = renderBox();
expect(await findByText('chat.userMessage.editRollbackHint')).toBeTruthy();
});
+
+ it('preview 为 conversation-only 时明确提示文件不会恢复', async () => {
+ previewMock.mockResolvedValueOnce({
+ canRewind: true,
+ conversationOnly: true,
+ filesChanged: [],
+ insertions: 0,
+ deletions: 0,
+ });
+ const { findByText } = renderBox();
+ expect(await findByText('chat.userMessage.editConversationOnlyHint')).toBeTruthy();
+ });
+
+ it('conversation-only 发送把 allowFileRestore=false 传到 rewind commit', async () => {
+ previewMock.mockResolvedValueOnce({
+ canRewind: true,
+ conversationOnly: true,
+ filesChanged: [],
+ insertions: 0,
+ deletions: 0,
+ });
+ const { findByText, sendBtn } = renderBox();
+ await findByText('chat.userMessage.editConversationOnlyHint');
+ fireEvent.click(sendBtn);
+ await waitFor(() => expect(commitMock).toHaveBeenCalledTimes(1));
+ expect(commitMock.mock.calls[0][0]).toMatchObject({
+ allowFileRestore: false,
+ });
+ });
});
diff --git a/apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx b/apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx
index e2beeb0a83..fe1df4f3ac 100644
--- a/apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx
+++ b/apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx
@@ -7,10 +7,12 @@
* open=true + running → 直接确认 Stop + Rewind,不读取会立刻过期的 preview
* open=true + idle → 进 Loading → 调 rewindPreview(sessionId, clientId)
* ├─ filesChanged.length > 0 → Default(文件清单 + summary)
- * ├─ filesChanged.length == 0 → Empty("无文件被改动"占位)
+ * ├─ conversationOnly → Empty(说明文件恢复不可用)
+ * ├─ filesChanged.length == 0 → Empty(无文件改动)
* └─ canRewind=false 或抛错 → Error(红色 alert + "知道了")
*
* Confirm 点击(Running / Default / Empty)→ 调 rewindCommit(stopIfRunning=true)
+ * Empty 额外传 allowFileRestore:false,绑定预览时的 conversation-only 承诺
* → 成功后 onCommitted(session)
* → 失败 toast.error 但保持弹窗开
*
@@ -43,9 +45,8 @@ type DialogState =
insertions: number;
deletions: number;
}
- // empty: SDK 报告没有文件需要回滚(canRewind=true + filesChanged=[],
- // 或 canRewind=false 但因"该消息无 checkpoint" / "session 未开 checkpointing"
- // 导致——两种情况语义都是"仅截断对话历史",让用户继续 Confirm,由后端容错)
+ // empty: 对话可以回退,但文件层面要么没有改动,要么没有可用的恢复点;
+ // note 用于把这两种用户可见结果明确区分。
| { kind: 'empty'; note?: string }
// error: 真硬错(IPC 抛错,非 SDK 软拒绝)—— 阻塞 Confirm
| { kind: 'error'; errorText: string };
@@ -102,13 +103,22 @@ export function RewindPreviewDialog({
insertions: result.insertions ?? 0,
deletions: result.deletions ?? 0,
});
+ } else if (result.canRewind && result.conversationOnly) {
+ // The conversation can still rewind, but there is no file restore
+ // plan (for example a non-Git project or missing savepoints).
+ setState({
+ kind: 'empty',
+ note: result.gitSafetyDisabled
+ ? t('chat.rewind.gitSafetyDisabledNotice')
+ : t('chat.rewind.conversationOnlyNotice'),
+ });
} else if (result.canRewind) {
- // 文件层面没有改动可回滚,仅截断对话历史。
+ // 文件层面没有检测到改动,仍允许用户回退聊天记录。
setState({ kind: 'empty' });
} else {
// SDK 软拒绝(最常见:"No file checkpoint found for this message"
// = 该 user 消息之后没有任何工具改文件;或老 session 没开 checkpointing)。
- // 两种都不影响截断历史,让用户继续 Confirm。错误文案以 note 形式提示。
+ // 对话仍可回退,让用户继续 Confirm;具体原因以 note 形式提示。
setState({
kind: 'empty',
note: result.error || t('chat.rewind.noFilesToRollback'),
@@ -145,7 +155,10 @@ export function RewindPreviewDialog({
if (state.kind !== 'running' && state.kind !== 'default' && state.kind !== 'empty') return;
setCommitting(true);
try {
- const session = await rewindCommit(sessionId, clientId, { stopIfRunning: true });
+ const session = await rewindCommit(sessionId, clientId, {
+ stopIfRunning: true,
+ ...(state.kind === 'empty' ? { allowFileRestore: false } : {}),
+ });
onCommitted(session);
onOpenChange(false);
} catch (err) {
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 0dbd706d1b..9c5c0adaee 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -60,7 +60,6 @@ import {
useAgentCapabilities,
type AgentKind as MakerAgentKind,
} from '@/hooks/useAgentCapabilities';
-import { useGitSafetyAutoSnapshotEnabledForDevice } from '@/hooks/useGitSafetySettings';
import { useChatSessionFile } from './ChatSessionFileContext';
import { isRemoteFileOrigin, originDeviceId, toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';
import { rewriteToRemoteMediaOrigin } from '../../../shared/remoteMediaUrl';
@@ -173,8 +172,8 @@ interface UserMessageProps {
* the Fork button is not rendered. */
sessionId?: string;
/** Owning agent kind (renderer 短名 'cc' | 'codex') — gates Fork/Rewind icon
- * visibility via capabilities. Codex rewind additionally requires the Git
- * safety snapshot setting because file rewind depends on savepoint commits. */
+ * visibility via capabilities. File rewind may degrade to conversation-only
+ * rewind when no Git savepoint is available; the preview explains why. */
agentKind?: RendererAgentKind;
/** Owning session's remote SSH host id (null for local). Remote cc daemon
* sessions don't support the query-rebuild that Fork/Rewind need yet (MVP),
@@ -978,7 +977,6 @@ export function UserMessage({
// context 更新会穿透 memo 触发重渲,替代旧的 render 期一次性读取)。
const sessionFileCtx = useChatSessionFile();
const remoteDeviceId = originDeviceId(sessionFileCtx.origin);
- const gitSafetyAutoSnapshotEnabled = useGitSafetyAutoSnapshotEnabledForDevice(remoteDeviceId);
const remoteMediaOrigin = useMemo(
() => toRemoteMediaOrigin(sessionFileCtx.origin, sessionFileCtx.workingDir),
[sessionFileCtx],
@@ -987,10 +985,8 @@ export function UserMessage({
// 远端 cc daemon 会话暂不支持 Fork/Rewind 依赖的 query rebuild (MVP),
// remoteHostId 非空时直接关掉这两个能力, 避免点了落到后端错误。
const isRemote = Boolean(remoteHostId);
- const codexRewindEntryAllowed = agentKind !== 'codex' || gitSafetyAutoSnapshotEnabled;
const forkSupported = !isRemote && (!agentKind || (capabilities?.fork?.supported ?? true));
const rewindSupported =
- codexRewindEntryAllowed &&
!isRemote &&
(!agentKind || (capabilities?.rewind?.supported ?? true));
@@ -1272,7 +1268,7 @@ export function UserMessage({
// 第一条 user 消息没有可作为锚点的 prior assistant uuid → 后端必抛
// NO_PRIOR_ASSISTANT。直接藏掉按钮,避免无效点击。
- // 同时按 capabilities.rewind.supported gate;Codex 入口还要用户显式开启 Git safety。
+ // 同时按 capabilities.rewind.supported gate;文件恢复能力由实际 Git 保存点决定。
const canRewind =
Boolean(sessionId && messageClientId) &&
!isFirstUserMessage &&
diff --git a/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx b/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx
index c3eef81831..352ede59f7 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx
@@ -16,11 +16,9 @@
* isTurnRunning 与 renderer 状态的毫秒级尾差由
* commitEditAndResendWithRunningRetry 的有限重试消化。
*
- * 文件回滚提示:mount 时静默跑一次 rewindPreview(dryRun),上一轮有文件改动
- * 时在按钮左侧给一行小字("发送将撤销上一轮 N 个文件的改动"),不弹完整
- * Dialog —— 这是相对 Codex(完全不提示文件不会回滚)的体验差异化。preview
- * 失败(老消息无 checkpoint 等)只是不显示提示,不阻塞发送(commit 链路自带
- * forkSession 兜底,与 RewindPreviewDialog 的 Empty 态同语义)。
+ * 文件回滚提示:mount 时静默跑一次 rewindPreview(dryRun)。上一轮有文件改动
+ * 时在按钮左侧给一行小字;conversation-only 时明确告诉用户文件不会恢复,
+ * 避免静默叠加旧改动。preview 失败不阻塞发送。
*
* 键盘:Enter 发送(与主 composer 一致)、Shift+Enter 换行、Esc 取消。
* 附件:v1 不支持编辑态增删,原消息附件由编排层原样重建重发(chips 在
@@ -131,8 +129,10 @@ export function UserMessageEditBox({
// 运行中发送的挂起标记:等 sessionRunning 翻 false 后由 effect 接力提交。
const pendingSendRef = useRef(false);
const waitTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- // null = preview 未返回/失败(不显示提示);number = 上一轮改动的文件数。
- const [rollbackFileCount, setRollbackFileCount] = useState<number | null>(null);
+ // null = preview 未返回/失败(不显示提示)。
+ const [rollbackHint, setRollbackHint] = useState<
+ { kind: 'files'; count: number } | { kind: 'conversation-only' } | null
+ >(null);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
// 静默 preview 文件回滚影响。失败/软拒绝都归 null(不提示、不阻塞)。
@@ -147,7 +147,9 @@ export function UserMessageEditBox({
if (cancelled) return;
const fileCount = result.filesChanged?.length ?? 0;
if (result.canRewind && fileCount > 0) {
- setRollbackFileCount(fileCount);
+ setRollbackHint({ kind: 'files', count: fileCount });
+ } else if (result.canRewind && result.conversationOnly) {
+ setRollbackHint({ kind: 'conversation-only' });
}
})
.catch(() => {
@@ -236,6 +238,7 @@ export function UserMessageEditBox({
...(preservedAgentReferences ? { agentReferences: preservedAgentReferences } : {}),
...(preservedPastedTextRanges ? { pastedTextRanges: preservedPastedTextRanges } : {}),
...(preservedSlashCommandRanges !== undefined ? { slashCommandRanges: preservedSlashCommandRanges } : {}),
+ ...(rollbackHint?.kind === 'conversation-only' ? { allowFileRestore: false } : {}),
});
}
submittingRef.current = false;
@@ -260,7 +263,7 @@ export function UserMessageEditBox({
submittingRef.current = false;
setSubmitting(false);
}
- }, [sessionId, messageClientId, text, initialText, initialSubmitText, images, files, workingDir, quotesEncoded, agentReferences, pastedTextRanges, slashCommandRanges, onSent, onCommitOverride, t]);
+ }, [sessionId, messageClientId, text, initialText, initialSubmitText, images, files, workingDir, quotesEncoded, agentReferences, pastedTextRanges, slashCommandRanges, rollbackHint, onSent, onCommitOverride, t]);
const handleSend = useCallback(() => {
if (!canSend || submittingRef.current) return;
@@ -346,9 +349,14 @@ export function UserMessageEditBox({
)}
/>
<div className="mt-2 flex items-center justify-end gap-2">
- {rollbackFileCount !== null && rollbackFileCount > 0 && (
+ {rollbackHint?.kind === 'files' && (
<span className="min-w-0 flex-1 truncate text-left text-11 text-[var(--text-tertiary)]">
- {t('chat.userMessage.editRollbackHint', { count: rollbackFileCount })}
+ {t('chat.userMessage.editRollbackHint', { count: rollbackHint.count })}
+ </span>
+ )}
+ {rollbackHint?.kind === 'conversation-only' && (
+ <span className="min-w-0 flex-1 truncate text-left text-11 text-[var(--text-tertiary)]">
+ {t('chat.userMessage.editConversationOnlyHint')}
</span>
)}
<button
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/RewindPreviewDialog.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/RewindPreviewDialog.test.tsx
index 54b679f370..f01d5bc98f 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/RewindPreviewDialog.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/RewindPreviewDialog.test.tsx
@@ -152,4 +152,35 @@ describe('RewindPreviewDialog running-session flow', () => {
await waitFor(() => expect(screen.getByText('chat.rewind.dialog.summaryRunning')).toBeTruthy());
expect(screen.getByRole('button', { name: 'chat.rewind.dialog.confirmRunning' })).toBeTruthy();
});
+
+ it('binds conversation-only preview so commit cannot restore files', async () => {
+ mocks.rewindPreview.mockResolvedValueOnce({
+ canRewind: true,
+ conversationOnly: true,
+ filesChanged: [],
+ insertions: 0,
+ deletions: 0,
+ });
+
+ render(
+ <RewindPreviewDialog
+ open
+ sessionId="session-1"
+ clientId="message-1"
+ sessionRunning={false}
+ onCommitted={vi.fn()}
+ onOpenChange={vi.fn()}
+ />,
+ );
+
+ await waitFor(() => expect(screen.getByText('chat.rewind.conversationOnlyNotice')).toBeTruthy());
+ fireEvent.click(screen.getByRole('button', { name: 'chat.rewind.dialog.confirm' }));
+
+ await waitFor(() =>
+ expect(mocks.rewindCommit).toHaveBeenCalledWith('session-1', 'message-1', {
+ stopIfRunning: true,
+ allowFileRestore: false,
+ }),
+ );
+ });
});
diff --git a/apps/desktop/src/renderer/components/settings/GitSafetySection.tsx b/apps/desktop/src/renderer/components/settings/GitSafetySection.tsx
index 0e5e38dd9e..7e822d9a52 100644
--- a/apps/desktop/src/renderer/components/settings/GitSafetySection.tsx
+++ b/apps/desktop/src/renderer/components/settings/GitSafetySection.tsx
@@ -1,29 +1,41 @@
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Switch } from '@/components/ui/switch';
import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
import { useGitSafetySettings } from '@/hooks/useGitSafetySettings';
+import type { GitSafetyMode } from '@/lib/gitSafetySettingsStore';
+import { SegmentedControl } from '@/components/ui/segmented-control';
+import { DefaultOverrideControls } from './DefaultOverrideControls';
export function GitSafetySection() {
const { t } = useTranslation();
- const { autoSnapshotEnabled, setAutoSnapshotEnabled } = useGitSafetySettings();
+ const { mode, setMode, reset, isCustomized } = useGitSafetySettings();
const [saving, setSaving] = useState(false);
- const handleToggle = useCallback(
- (next: boolean) => {
+ const handleModeChange = useCallback(
+ (next: GitSafetyMode) => {
if (saving) return;
setSaving(true);
- void setAutoSnapshotEnabled(next)
+ void setMode(next)
.catch((err: unknown) => {
toast.error(err instanceof Error ? err.message : t('settings.gitSafety.saveFailed'));
})
.finally(() => setSaving(false));
},
- [saving, setAutoSnapshotEnabled, t],
+ [saving, setMode, t],
);
+ const handleReset = useCallback(() => {
+ if (saving) return;
+ setSaving(true);
+ void reset()
+ .catch((err: unknown) => {
+ toast.error(err instanceof Error ? err.message : t('settings.defaults.restoreFailed'));
+ })
+ .finally(() => setSaving(false));
+ }, [reset, saving, t]);
+
return (
<div className="flex flex-col gap-[14px]">
<h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">
@@ -42,16 +54,22 @@ export function GitSafetySection() {
<p className="text-13 font-medium text-[var(--settings-section-sublabel)]">
{t('settings.gitSafety.autoSnapshotTitle')}
</p>
- <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">
- {t('settings.gitSafety.description')}
- </p>
+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">{t('settings.gitSafety.description')}</p>
</div>
- <Switch
- checked={autoSnapshotEnabled}
- onCheckedChange={handleToggle}
- aria-label={t('settings.gitSafety.toggleAria')}
+ <SegmentedControl
+ value={mode}
+ onValueChange={handleModeChange}
+ disabled={saving}
+ aria-label={t('settings.gitSafety.modeAria')}
+ options={[
+ { value: 'off', label: t('settings.gitSafety.modes.off') },
+ { value: 'existing-git', label: t('settings.gitSafety.modes.existingGit') },
+ { value: 'all-projects', label: t('settings.gitSafety.modes.allProjects') },
+ ] satisfies ReadonlyArray<{ value: GitSafetyMode; label: string }>}
+ fullWidth
/>
+ <DefaultOverrideControls isCustomized={isCustomized} disabled={saving} onReset={handleReset} />
</div>
</div>
</div>
diff --git a/apps/desktop/src/renderer/hooks/useGitSafetySettings.ts b/apps/desktop/src/renderer/hooks/useGitSafetySettings.ts
index e53aaf876f..760aa6fbeb 100644
--- a/apps/desktop/src/renderer/hooks/useGitSafetySettings.ts
+++ b/apps/desktop/src/renderer/hooks/useGitSafetySettings.ts
@@ -1,17 +1,23 @@
import { useCallback, useEffect, useState } from 'react';
import {
+ getGitSafetyMode,
getGitSafetyAutoSnapshotEnabled,
- setGitSafetyAutoSnapshotEnabled,
+ persistLegacyGitSafetyOptOut,
+ setGitSafetyMode,
subscribeGitSafetyAutoSnapshotEnabled,
+ subscribeGitSafetyMode,
} from '@/lib/gitSafetySettingsStore';
+import type { GitSafetyMode } from '@/lib/gitSafetySettingsStore';
interface DeviceLinkShape {
invoke: (deviceId: string, channel: string, args: unknown[]) => Promise<unknown>;
}
type GitSafetyWire = {
+ mode?: GitSafetyMode;
autoSnapshotEnabled: boolean;
+ autoInitProjectGit: boolean;
isCustomized: boolean;
defaultAutoSnapshotEnabled: boolean;
};
@@ -27,20 +33,28 @@ function isGitSafetyWire(value: unknown): value is GitSafetyWire {
return Boolean(
value &&
typeof value === 'object' &&
- typeof (value as GitSafetyWire).autoSnapshotEnabled === 'boolean',
+ (typeof (value as GitSafetyWire).mode === 'string' ||
+ typeof (value as GitSafetyWire).autoSnapshotEnabled === 'boolean'),
);
}
-const remoteCache = new Map<string, boolean>();
-const remoteInflight = new Map<string, Promise<boolean>>();
+function modeFromWire(value: GitSafetyWire): GitSafetyMode {
+ if (value.mode === 'off' || value.mode === 'existing-git' || value.mode === 'all-projects') {
+ return value.mode;
+ }
+ return value.autoSnapshotEnabled ? 'all-projects' : 'off';
+}
+
+const remoteCache = new Map<string, GitSafetyMode>();
+const remoteInflight = new Map<string, Promise<GitSafetyMode>>();
const remoteDeviceGen = new Map<string, number>();
async function fetchRemoteGitSafetyAutoSnapshotEnabled(
deviceId: string,
opts: { force?: boolean } = {},
-): Promise<boolean> {
+): Promise<GitSafetyMode> {
const cached = remoteCache.get(deviceId);
- if (!opts.force && typeof cached === 'boolean') return cached;
+ if (!opts.force && cached) return cached;
const ip = remoteInflight.get(deviceId);
if (ip) return ip;
@@ -50,13 +64,13 @@ async function fetchRemoteGitSafetyAutoSnapshotEnabled(
const dl = getDeviceLink();
if (!dl) throw new Error('device-link IPC not available');
const p = dl.invoke(deviceId, 'maker:git-safety:get', [])
- .then((settings) => (isGitSafetyWire(settings) ? settings.autoSnapshotEnabled : false))
- .then((enabled) => {
+ .then((settings) => (isGitSafetyWire(settings) ? modeFromWire(settings) : 'off'))
+ .then((mode) => {
if (isCurrent()) {
- remoteCache.set(deviceId, enabled);
+ remoteCache.set(deviceId, mode);
remoteInflight.delete(deviceId);
}
- return enabled;
+ return mode;
})
.catch((e) => {
if (isCurrent()) remoteInflight.delete(deviceId);
@@ -67,33 +81,58 @@ async function fetchRemoteGitSafetyAutoSnapshotEnabled(
}
export function useGitSafetySettings(): {
+ mode: GitSafetyMode;
autoSnapshotEnabled: boolean;
isCustomized: boolean;
+ setMode: (next: GitSafetyMode) => Promise<void>;
setAutoSnapshotEnabled: (next: boolean) => Promise<void>;
reset: () => Promise<void>;
} {
+ const [mode, setModeState] = useState<GitSafetyMode>(getGitSafetyMode);
const [autoSnapshotEnabled, setEnabledState] = useState<boolean>(getGitSafetyAutoSnapshotEnabled);
const [isCustomized, setIsCustomized] = useState(false);
const refresh = useCallback(async (isCancelled: () => boolean = () => false) => {
+ try {
+ if (await persistLegacyGitSafetyOptOut()) {
+ if (isCancelled()) return;
+ setModeState('off');
+ setEnabledState(false);
+ setIsCustomized(true);
+ return;
+ }
+ } catch {
+ return;
+ }
const settings = await window.electronAPI.maker.gitSafetyGet();
if (isCancelled()) return;
- setGitSafetyAutoSnapshotEnabled(settings.autoSnapshotEnabled);
- setEnabledState(settings.autoSnapshotEnabled);
+ const nextMode = modeFromWire(settings);
+ setGitSafetyMode(nextMode);
+ setModeState(nextMode);
+ setEnabledState(nextMode !== 'off');
setIsCustomized(settings.isCustomized);
}, []);
- const setAutoSnapshotEnabled = useCallback(async (next: boolean) => {
+ const setMode = useCallback(async (next: GitSafetyMode) => {
const settings = await window.electronAPI.maker.gitSafetySet(next);
- setGitSafetyAutoSnapshotEnabled(settings.autoSnapshotEnabled);
- setEnabledState(settings.autoSnapshotEnabled);
+ const nextMode = modeFromWire(settings);
+ setGitSafetyMode(nextMode);
+ setModeState(nextMode);
+ setEnabledState(nextMode !== 'off');
setIsCustomized(settings.isCustomized);
}, []);
+ const setAutoSnapshotEnabled = useCallback(
+ (next: boolean) => setMode(next ? 'all-projects' : 'off'),
+ [setMode],
+ );
+
const reset = useCallback(async () => {
const settings = await window.electronAPI.maker.gitSafetyReset();
- setGitSafetyAutoSnapshotEnabled(settings.autoSnapshotEnabled);
- setEnabledState(settings.autoSnapshotEnabled);
+ const nextMode = modeFromWire(settings);
+ setGitSafetyMode(nextMode);
+ setModeState(nextMode);
+ setEnabledState(nextMode !== 'off');
setIsCustomized(settings.isCustomized);
}, []);
@@ -103,13 +142,23 @@ export function useGitSafetySettings(): {
const unsubscribe = subscribeGitSafetyAutoSnapshotEnabled((next) => {
if (!cancelled) setEnabledState(next);
});
+ const unsubscribeMode = subscribeGitSafetyMode((next, source) => {
+ if (!cancelled) {
+ setModeState(next);
+ setEnabledState(next !== 'off');
+ // The mode mirror cannot carry isCustomized. Refresh main's complete
+ // wire state so Settings windows also converge on override/reset changes.
+ if (source === 'storage') void refresh(() => cancelled).catch(() => undefined);
+ }
+ });
return () => {
cancelled = true;
unsubscribe();
+ unsubscribeMode();
};
}, [refresh]);
- return { autoSnapshotEnabled, isCustomized, setAutoSnapshotEnabled, reset };
+ return { mode, autoSnapshotEnabled, isCustomized, setMode, setAutoSnapshotEnabled, reset };
}
export function useGitSafetyAutoSnapshotEnabled(): boolean {
@@ -130,7 +179,7 @@ export function useGitSafetyAutoSnapshotEnabled(): boolean {
export function useGitSafetyAutoSnapshotEnabledForDevice(deviceId?: string): boolean {
const localEnabled = useGitSafetyAutoSnapshotEnabled();
const [remoteEnabled, setRemoteEnabled] = useState<boolean>(
- deviceId ? remoteCache.get(deviceId) ?? false : false,
+ deviceId ? (remoteCache.get(deviceId) ?? 'off') !== 'off' : false,
);
useEffect(() => {
@@ -140,15 +189,15 @@ export function useGitSafetyAutoSnapshotEnabledForDevice(deviceId?: string): boo
}
let cancelled = false;
const cached = remoteCache.get(deviceId);
- if (typeof cached === 'boolean') {
- setRemoteEnabled(cached);
+ if (cached) {
+ setRemoteEnabled(cached !== 'off');
} else {
setRemoteEnabled(false);
}
const refreshRemote = () => {
fetchRemoteGitSafetyAutoSnapshotEnabled(deviceId, { force: true })
.then((enabled) => {
- if (!cancelled) setRemoteEnabled(enabled);
+ if (!cancelled) setRemoteEnabled(enabled !== 'off');
})
.catch(() => {
if (!cancelled) setRemoteEnabled(false);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 7096d8f1c7..088682145e 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2461,9 +2461,15 @@
},
"gitSafety": {
"title": "Git Safety",
- "autoSnapshotTitle": "Git safety snapshots",
- "description": "Automatically record hidden savepoints in the project's Git repository after agent edits — no commits are added to your branch. Codex rewind is shown only when this is enabled.",
- "toggleAria": "Toggle Git safety snapshots",
+ "autoSnapshotTitle": "File recovery points",
+ "description": "Choose when Cindy records hidden file recovery points. This affects file recovery cost, not conversation rewind.",
+ "modeAria": "File recovery point mode",
+ "modes": {
+ "off": "Off",
+ "existingGit": "Existing Git projects only",
+ "allProjects": "Include new empty projects"
+ },
+ "toggleAria": "File recovery point mode",
"saveFailed": "Failed to save Git safety setting"
},
"feishuBot": {
@@ -9305,6 +9311,7 @@
"editCancel": "Cancel",
"editSend": "Send",
"editRollbackHint": "Sending will undo changes to {{count}} file(s) from the last turn",
+ "editConversationOnlyHint": "Sending will not restore project files; previous file changes will remain",
"forkErrors": {
"unsupportedHistory": "The historical agent session for this point is unavailable, so a new session can't be started from here",
"noPriorAssistant": "Start a new session from a message that follows an AI reply",
@@ -9324,7 +9331,9 @@
"viewThread": "View thread context ({{count}})"
},
"rewind": {
- "noFilesToRollback": "No files to roll back, only chat history will be truncated",
+ "noFilesToRollback": "No restorable project file changes were detected",
+ "conversationOnlyNotice": "Project files cannot be restored because no Git savepoint is available. Continuing will remove the chat after this message; files will not return to their earlier state",
+ "gitSafetyDisabledNotice": "Git safety savepoints are disabled, so project files cannot be restored. Enable them in Settings to restore files; continuing will remove the chat after this message",
"errors": {
"noPriorAssistantPreview": "Please rewind from a question that follows an AI reply (this one has no prior assistant reply)",
"sessionRunning": "The task did not stop in time — retry the rewind",
@@ -9339,11 +9348,11 @@
"errorDescription": "File checkpointing is not enabled for this Session — files modified by tools cannot be rolled back.",
"calculating": "Calculating rewind impact…",
"noChanges": "No file changes to roll back",
- "continueWillTruncate": "Continuing will still truncate subsequent messages",
+ "continueWillTruncate": "Continuing will remove the chat after this message",
"noPerFileDiff": "This SDK version does not support per-file diff preview",
"summaryDefault": "Subsequent messages after this will be discarded, and {{count}} files in the working directory will be rolled back to that moment.",
- "summaryRunning": "The current task will stop. Subsequent messages and the corresponding file changes will be rewound.",
- "summaryEmpty": "Subsequent messages will be discarded. No files were changed; only history is truncated.",
+ "summaryRunning": "The current task will stop. Later messages will be rewound. File restoration cannot be confirmed until the task has stopped.",
+ "summaryEmpty": "No project file changes were detected after this message. Continuing will remove the later chat.",
"summaryEmptyWithNote": "Subsequent messages will be discarded.",
"runningNotice": "The task is still running. Confirming will stop it before recalculating and applying the rewind.",
"runningQueueNotice": "Queued messages will be kept paused and will not be sent automatically.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index bc1b247ba0..deb9f0fa3b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2460,9 +2460,15 @@
},
"gitSafety": {
"title": "Git セーフティ",
- "autoSnapshotTitle": "Git セーフティ保存点",
- "description": "Agent の編集後にプロジェクトの Git リポジトリへ隠し保存点を自動記録します。ブランチに commit は追加されません。有効な場合のみ Codex rewind を表示します。",
- "toggleAria": "Git セーフティ保存点を切り替え",
+ "autoSnapshotTitle": "ファイル復元ポイント",
+ "description": "Cindy が隠しファイル復元ポイントを記録する範囲を選択します。ファイル復元のコストだけに影響し、会話の巻き戻しには影響しません。",
+ "modeAria": "ファイル復元ポイントのモード",
+ "modes": {
+ "off": "オフ",
+ "existingGit": "既存の Git プロジェクトのみ",
+ "allProjects": "新しい空のプロジェクトも含める"
+ },
+ "toggleAria": "ファイル復元ポイントのモード",
"saveFailed": "Git セーフティ設定の保存に失敗しました"
},
"feishuBot": {
@@ -9299,6 +9305,7 @@
"editCancel": "キャンセル",
"editSend": "送信",
"editRollbackHint": "送信すると前のターンで変更された {{count}} 個のファイルが元に戻ります",
+ "editConversationOnlyHint": "送信してもプロジェクトファイルは復元されず、前回のファイル変更は残ります",
"forkErrors": {
"unsupportedHistory": "この位置に対応する過去のエージェントセッションを利用できないため、ここから新しいセッションを始められません",
"noPriorAssistant": "AI の返信より後のメッセージから新しいセッションを始めてください",
@@ -9318,7 +9325,9 @@
"viewThread": "スレッドの文脈を見る ({{count}})"
},
"rewind": {
- "noFilesToRollback": "ロールバック対象のファイルはありません。会話履歴のみ切り詰めます",
+ "noFilesToRollback": "復元できるプロジェクトファイルの変更は検出されませんでした",
+ "conversationOnlyNotice": "利用できるファイル復元ポイントがありません。このメッセージ以降のチャットが削除され、プロジェクトファイルは復元されません",
+ "gitSafetyDisabledNotice": "Git のファイル復元ポイントが無効です。設定で有効にしてください。このメッセージ以降のチャットが削除され、プロジェクトファイルは復元されません",
"errors": {
"noPriorAssistantPreview": "AI の返信の後ろにある質問で rewind してください(この前に assistant の返信がありません)",
"sessionRunning": "タスクの停止待ちがタイムアウトしました。もう一度巻き戻してください",
@@ -9333,11 +9342,11 @@
"errorDescription": "この Session ではファイルの checkpointing が有効になっていないため、ツールで変更されたファイルを戻せません。",
"calculating": "rewind の影響を計算中…",
"noChanges": "ロールバックが必要なファイル変更はありません",
- "continueWillTruncate": "続行しても以降の会話は切り詰められます",
+ "continueWillTruncate": "続行すると、このメッセージ以降のチャットが削除されます",
"noPerFileDiff": "この SDK バージョンはファイル単位の diff プレビューに対応していません",
"summaryDefault": "このメッセージ以降の会話は破棄され、作業ディレクトリ内の {{count}} 件のファイルがその時点に戻ります。",
- "summaryRunning": "実行中のタスクを停止し、このメッセージ以降の会話と対応するファイル変更を巻き戻します。",
- "summaryEmpty": "このメッセージ以降の会話は破棄されます。ファイルは変更されず、履歴のみ切り詰めます。",
+ "summaryRunning": "実行中のタスクを停止し、このメッセージ以降の会話を巻き戻します。ファイルを復元できるかは停止後まで確定しません。",
+ "summaryEmpty": "このメッセージ以降のチャットが削除されます。プロジェクトファイルは変更されません。",
"summaryEmptyWithNote": "このメッセージ以降の会話は破棄されます。",
"runningNotice": "タスクはまだ実行中です。確認するとタスクを停止し、最新の状態から巻き戻します。",
"runningQueueNotice": "送信待ちのメッセージは一時停止したまま保持され、自動送信されません。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 2114adecc4..225b833df6 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2460,9 +2460,15 @@
},
"gitSafety": {
"title": "Git 안전",
- "autoSnapshotTitle": "Git 안전 저장점",
- "description": "Agent 편집 후 프로젝트 Git 저장소에 숨겨진 저장점을 자동으로 기록합니다. 브랜치에 commit이 추가되지 않습니다. 켜져 있을 때만 Codex rewind를 표시합니다.",
- "toggleAria": "Git 안전 저장점 전환",
+ "autoSnapshotTitle": "파일 복구 지점",
+ "description": "Cindy가 숨겨진 파일 복구 지점을 기록할 범위를 선택합니다. 파일 복구 비용에만 영향을 주며 대화 되돌리기에는 영향을 주지 않습니다.",
+ "modeAria": "파일 복구 지점 모드",
+ "modes": {
+ "off": "끔",
+ "existingGit": "기존 Git 프로젝트만",
+ "allProjects": "새 빈 프로젝트 포함"
+ },
+ "toggleAria": "파일 복구 지점 모드",
"saveFailed": "Git 안전 설정 저장에 실패했습니다"
},
"feishuBot": {
@@ -9299,6 +9305,7 @@
"editCancel": "취소",
"editSend": "전송",
"editRollbackHint": "전송하면 이전 턴에서 변경된 파일 {{count}}개가 되돌려집니다",
+ "editConversationOnlyHint": "전송해도 프로젝트 파일은 복원되지 않으며, 이전 파일 변경은 그대로 남습니다",
"forkErrors": {
"unsupportedHistory": "이 지점에 해당하는 이전 에이전트 세션을 사용할 수 없어 여기서 새 세션을 시작할 수 없습니다",
"noPriorAssistant": "AI 응답 뒤의 메시지에서 새 세션을 시작해 주세요",
@@ -9318,7 +9325,9 @@
"viewThread": "스레드 컨텍스트 보기 ({{count}})"
},
"rewind": {
- "noFilesToRollback": "롤백할 파일이 없습니다. 대화 기록만 잘립니다",
+ "noFilesToRollback": "복원할 수 있는 프로젝트 파일 변경이 감지되지 않았습니다",
+ "conversationOnlyNotice": "사용할 수 있는 파일 복원 지점이 없습니다. 계속하면 이 메시지 이후의 채팅이 삭제되고 프로젝트 파일은 복원되지 않습니다",
+ "gitSafetyDisabledNotice": "Git 파일 복원 지점이 비활성화되어 있습니다. 설정에서 켜세요. 계속하면 이 메시지 이후의 채팅이 삭제되고 프로젝트 파일은 복원되지 않습니다",
"errors": {
"noPriorAssistantPreview": "AI 응답 뒤의 질문에서 rewind 하세요(이전에 assistant 응답이 없습니다)",
"sessionRunning": "작업 중지 대기 시간이 초과되었습니다. 다시 되돌리세요",
@@ -9333,11 +9342,11 @@
"errorDescription": "이 Session에서는 파일 checkpointing이 활성화되어 있지 않아 도구가 수정한 파일을 되돌릴 수 없습니다.",
"calculating": "rewind 영향 계산 중…",
"noChanges": "롤백이 필요한 파일 변경이 없습니다",
- "continueWillTruncate": "계속해도 이후 대화는 잘립니다",
+ "continueWillTruncate": "계속하면 이 메시지 이후의 채팅이 삭제됩니다",
"noPerFileDiff": "이 SDK 버전은 파일별 diff 미리보기를 지원하지 않습니다",
"summaryDefault": "이 메시지 이후의 대화는 폐기되며, 작업 디렉터리의 {{count}}개 파일이 그 시점으로 되돌아갑니다.",
- "summaryRunning": "실행 중인 작업을 중지하고 이 메시지 이후의 대화와 관련 파일 변경을 되돌립니다.",
- "summaryEmpty": "이 메시지 이후의 대화는 폐기됩니다. 파일은 변경되지 않았으며, 기록만 잘립니다.",
+ "summaryRunning": "실행 중인 작업을 중지하고 이 메시지 이후의 대화를 되돌립니다. 파일을 복원할 수 있는지는 중지 후에야 확인할 수 있습니다.",
+ "summaryEmpty": "이 메시지 이후의 채팅이 삭제됩니다. 프로젝트 파일은 변경되지 않았습니다.",
"summaryEmptyWithNote": "이 메시지 이후의 대화는 폐기됩니다.",
"runningNotice": "작업이 아직 실행 중입니다. 확인하면 작업을 중지한 뒤 최신 상태를 기준으로 되돌립니다.",
"runningQueueNotice": "대기 중인 메시지는 일시 중지된 상태로 유지되며 자동 전송되지 않습니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 5c21e003b4..69ecfbeceb 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2460,9 +2460,15 @@
},
"gitSafety": {
"title": "Git 安全",
- "autoSnapshotTitle": "Git 安全保存点",
- "description": "Agent 修改后自动在项目 Git 仓库里记录隐藏保存点,不会在你的分支上产生 commit。只有开启后才显示 Codex rewind 入口。",
- "toggleAria": "切换 Git 安全保存点",
+ "autoSnapshotTitle": "文件恢复点",
+ "description": "选择 Cindy 记录隐藏文件恢复点的范围。这只影响文件恢复成本,不影响对话回退。",
+ "modeAria": "文件恢复点模式",
+ "modes": {
+ "off": "关闭",
+ "existingGit": "仅已有 Git 项目",
+ "allProjects": "包括新的空项目"
+ },
+ "toggleAria": "文件恢复点模式",
"saveFailed": "保存 Git 安全设置失败"
},
"feishuBot": {
@@ -9299,6 +9305,7 @@
"editCancel": "取消",
"editSend": "发送",
"editRollbackHint": "发送将撤销上一轮对 {{count}} 个文件的改动",
+ "editConversationOnlyHint": "发送不会恢复项目文件,上一轮的文件改动会保留",
"forkErrors": {
"unsupportedHistory": "目标位置对应的历史引擎会话已不可用,无法从这里开启新任务",
"noPriorAssistant": "请在 AI 回复之后的消息上开启新任务",
@@ -9318,7 +9325,9 @@
"viewThread": "查看 thread 上下文 ({{count}})"
},
"rewind": {
- "noFilesToRollback": "没有可回滚的文件,仅会截断对话历史",
+ "noFilesToRollback": "没有检测到可恢复的项目文件改动",
+ "conversationOnlyNotice": "当前无法恢复项目文件,因为没有可用的 Git 保存点;继续后会移除这条消息之后的对话记录,项目文件不会回到之前的状态",
+ "gitSafetyDisabledNotice": "Git 安全保存点未开启,因此当前无法恢复项目文件。请在设置中开启后再使用文件恢复;继续后会移除这条消息之后的对话记录,项目文件不会回到之前的状态",
"errors": {
"noPriorAssistantPreview": "请在 AI 回复之后的提问上 rewind(这条之前没有 assistant 回复)",
"sessionRunning": "等待任务停止超时,请重新回退",
@@ -9333,11 +9342,11 @@
"errorDescription": "这个任务的文件 checkpointing 未启用,无法回退被工具改动过的文件。",
"calculating": "正在计算回退影响…",
"noChanges": "没有需要回滚的文件改动",
- "continueWillTruncate": "继续回退仍会截断后续消息",
+ "continueWillTruncate": "继续后会移除这条消息之后的对话记录",
"noPerFileDiff": "该 SDK 版本不支持单文件 diff 预览",
"summaryDefault": "后续消息会被丢弃,工作目录里的 {{count}} 个文件会回退到那一刻。",
- "summaryRunning": "当前执行会被停止;后续消息和对应文件改动会被回退。",
- "summaryEmpty": "后续消息会被丢弃。没有文件被改动,仅截断历史。",
+ "summaryRunning": "当前任务会被停止;这条消息之后的对话会被回退。停止前无法确认项目文件是否会恢复。",
+ "summaryEmpty": "这条消息之后没有检测到项目文件改动,继续后会移除后续对话记录。",
"summaryEmptyWithNote": "后续消息会被丢弃。",
"runningNotice": "任务仍在运行。确认后会先停止任务,再按最新状态执行回退。",
"runningQueueNotice": "排队消息会保留并暂停,不会自动发送。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 7b99c57d28..0f45a2128a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2460,9 +2460,15 @@
},
"gitSafety": {
"title": "Git 安全",
- "autoSnapshotTitle": "Git 安全儲存點",
- "description": "Agent 修改後自動在專案 Git 倉庫裡記錄隱藏儲存點,不會在你的分支上產生 commit。只有開啟後才顯示 Codex rewind 入口。",
- "toggleAria": "切換 Git 安全儲存點",
+ "autoSnapshotTitle": "檔案恢復點",
+ "description": "選擇 Cindy 記錄隱藏檔案恢復點的範圍。這只影響檔案恢復成本,不影響對話回退。",
+ "modeAria": "檔案恢復點模式",
+ "modes": {
+ "off": "關閉",
+ "existingGit": "僅已有 Git 專案",
+ "allProjects": "包括新的空專案"
+ },
+ "toggleAria": "檔案恢復點模式",
"saveFailed": "儲存 Git 安全設定失敗"
},
"feishuBot": {
@@ -9298,6 +9304,7 @@
"editCancel": "取消",
"editSend": "傳送",
"editRollbackHint": "傳送將撤銷上一輪對 {{count}} 個檔案的改動",
+ "editConversationOnlyHint": "傳送不會恢復專案檔案,上一輪的檔案改動會保留",
"forkErrors": {
"unsupportedHistory": "目標位置對應的歷史引擎會話已不可用,無法從這裡開啟新任務",
"noPriorAssistant": "請在 AI 回覆之後的訊息上開啟新任務",
@@ -9317,7 +9324,9 @@
"viewThread": "檢視 thread 上下文 ({{count}})"
},
"rewind": {
- "noFilesToRollback": "沒有可回滾的檔案,僅會截斷對話歷史",
+ "noFilesToRollback": "沒有偵測到可恢復的專案檔案改動",
+ "conversationOnlyNotice": "目前無法恢復專案檔案,因為沒有可用的 Git 保存點;繼續後會移除這則訊息之後的對話記錄,專案檔案不會回到之前的狀態",
+ "gitSafetyDisabledNotice": "Git 安全保存點未開啟,因此目前無法恢復專案檔案。請在設定中開啟後再使用檔案恢復;繼續後會移除這則訊息之後的對話記錄,專案檔案不會回到之前的狀態",
"errors": {
"noPriorAssistantPreview": "請在 AI 回覆之後的提問上 rewind(這條之前沒有 assistant 回覆)",
"sessionRunning": "等待任務停止超時,請重新回退",
@@ -9332,11 +9341,11 @@
"errorDescription": "這個任務的檔案 checkpointing 未啟用,無法回退被工具改動過的檔案。",
"calculating": "正在計算回退影響…",
"noChanges": "沒有需要回滾的檔案改動",
- "continueWillTruncate": "繼續回退仍會截斷後續訊息",
+ "continueWillTruncate": "繼續後會移除這則訊息之後的對話記錄",
"noPerFileDiff": "該 SDK 版本不支援單檔案 diff 預覽",
"summaryDefault": "後續訊息會被丟棄,工作目錄裡的 {{count}} 個檔案會回退到那一刻。",
- "summaryRunning": "當前執行會被停止;後續訊息和對應檔案改動會被回退。",
- "summaryEmpty": "後續訊息會被丟棄。沒有檔案被改動,僅截斷歷史。",
+ "summaryRunning": "當前任務會被停止;這則訊息之後的對話會被回退。停止前無法確認專案檔案是否會恢復。",
+ "summaryEmpty": "這則訊息之後沒有偵測到專案檔案改動,繼續後會移除後續對話記錄。",
"summaryEmptyWithNote": "後續訊息會被丟棄。",
"runningNotice": "任務仍在執行。確認後會先停止任務,再按最新狀態執行回退。",
"runningQueueNotice": "排隊訊息會保留並暫停,不會自動傳送。",
diff --git a/apps/desktop/src/renderer/lib/editLastUserMessage.ts b/apps/desktop/src/renderer/lib/editLastUserMessage.ts
index 4591b10b0f..6f20589ed4 100644
--- a/apps/desktop/src/renderer/lib/editLastUserMessage.ts
+++ b/apps/desktop/src/renderer/lib/editLastUserMessage.ts
@@ -72,11 +72,17 @@ export interface CommitEditAndResendOptions {
pastedTextRanges?: PastedTextRange[];
/** 原消息 slash range;undefined 表示缺少显式 range,空数组表示明确无 slash。 */
slashCommandRanges?: SlashCommandRange[];
+ /** Bound from conversation-only preview so commit cannot restore files. */
+ allowFileRestore?: boolean;
}
/** 依赖注入口 — 单测用内存假件替换,生产走默认实现。 */
export interface CommitEditAndResendDeps {
- rewindCommit: (sessionId: string, clientId: string) => Promise<Session>;
+ rewindCommit: (
+ sessionId: string,
+ clientId: string,
+ opts?: { allowFileRestore?: boolean },
+ ) => Promise<Session>;
emitPatch: typeof emitSessionPatch;
dropMessagesFromClientId: (sessionId: string, clientId: string) => void;
sendMessage: typeof makerChatStore.sendMessage;
@@ -117,8 +123,11 @@ const defaultDeps: CommitEditAndResendDeps = {
// fetchLatestUserMessageClientId)到 IPC 落地之间存在 TOCTOU 窗口(自动化 /
// goal runner / 第二控制端可能追加新 user 消息),main 在 SDK 副作用前与软删
// 事务前各校验一次,超越则抛 REWIND_TARGET_NOT_LATEST。
- rewindCommit: (sessionId, clientId) =>
- rewindCommitService(sessionId, clientId, { requireLatestUser: true }),
+ rewindCommit: (sessionId, clientId, opts) =>
+ rewindCommitService(sessionId, clientId, {
+ requireLatestUser: true,
+ ...(opts?.allowFileRestore === false ? { allowFileRestore: false } : {}),
+ }),
emitPatch: emitSessionPatch,
dropMessagesFromClientId: (sessionId, clientId) =>
makerChatStore.dropMessagesFromClientId(sessionId, clientId),
@@ -224,7 +233,10 @@ export async function commitEditAndResend(
throw new ApiError('EDIT_NOT_LAST_MESSAGE', 0, 'target is no longer the latest user message');
}
- const session = await deps.rewindCommit(opts.sessionId, opts.clientId);
+ const session =
+ opts.allowFileRestore === false
+ ? await deps.rewindCommit(opts.sessionId, opts.clientId, { allowFileRestore: false })
+ : await deps.rewindCommit(opts.sessionId, opts.clientId);
deps.emitPatch(opts.sessionId, {
sdkSessionId: session.sdkSessionId,
diff --git a/apps/desktop/src/renderer/lib/gitSafetySettingsStore.ts b/apps/desktop/src/renderer/lib/gitSafetySettingsStore.ts
index 4554ef9734..558fa063b7 100644
--- a/apps/desktop/src/renderer/lib/gitSafetySettingsStore.ts
+++ b/apps/desktop/src/renderer/lib/gitSafetySettingsStore.ts
@@ -2,37 +2,62 @@
* gitSafetySettingsStore — renderer mirror for Git safety settings.
*
* Source of truth is main's <userData>/git-safety-settings.json. localStorage
- * is only a synchronous renderer mirror so message rows can decide whether to
- * show the Codex rewind entry without async work during render.
+ * is only a synchronous renderer mirror for settings UI and compatibility
+ * consumers; rewind visibility is determined by agent capabilities and its
+ * preview explains when file restoration is unavailable.
*/
-const STORAGE_KEY = 'gitSafety.autoSnapshotEnabled';
+export type GitSafetyMode = 'off' | 'existing-git' | 'all-projects';
+const STORAGE_KEY = 'gitSafety.mode';
+const LEGACY_STORAGE_KEY = 'gitSafety.autoSnapshotEnabled';
+const SYNC_KEY = 'gitSafety.sync';
type Subscriber = (value: boolean) => void;
+type ModeSubscriber = (value: GitSafetyMode, source: 'local' | 'storage') => void;
const subscribers = new Set<Subscriber>();
+const modeSubscribers = new Set<ModeSubscriber>();
-export function getGitSafetyAutoSnapshotEnabled(): boolean {
+function modeFromLegacy(value: string | null): GitSafetyMode {
+ return value === 'true' ? 'all-projects' : 'off';
+}
+
+export function getGitSafetyMode(): GitSafetyMode {
try {
- return localStorage.getItem(STORAGE_KEY) === 'true';
+ const value = localStorage.getItem(STORAGE_KEY);
+ if (value === 'off' || value === 'existing-git' || value === 'all-projects') return value;
+ const legacy = localStorage.getItem(LEGACY_STORAGE_KEY);
+ return legacy === null ? 'existing-git' : modeFromLegacy(legacy);
} catch {
- return false;
+ return 'off';
}
}
+export function getGitSafetyAutoSnapshotEnabled(): boolean {
+ return getGitSafetyMode() !== 'off';
+}
+
export function setGitSafetyAutoSnapshotEnabled(next: boolean): void {
+ setGitSafetyMode(next ? 'all-projects' : 'off');
+}
+
+export function setGitSafetyMode(next: GitSafetyMode): void {
try {
- localStorage.setItem(STORAGE_KEY, next ? 'true' : 'false');
+ localStorage.setItem(STORAGE_KEY, next);
+ // Same-mode writes still need a storage event so other Settings windows
+ // refresh isCustomized. Bump an unrelated key instead of adding a bus.
+ localStorage.setItem(SYNC_KEY, String(Date.now()));
} catch {
// localStorage unavailable — ignore; callers still get main IPC errors.
}
- subscribers.forEach((cb) => cb(next));
+ subscribers.forEach((cb) => cb(next !== 'off'));
+ modeSubscribers.forEach((cb) => cb(next, 'local'));
}
export function subscribeGitSafetyAutoSnapshotEnabled(cb: Subscriber): () => void {
subscribers.add(cb);
const storageHandler = (e: StorageEvent) => {
- if (e.key !== STORAGE_KEY) return;
+ if (e.key !== STORAGE_KEY && e.key !== LEGACY_STORAGE_KEY && e.key !== SYNC_KEY) return;
cb(getGitSafetyAutoSnapshotEnabled());
};
window.addEventListener('storage', storageHandler);
@@ -43,11 +68,60 @@ export function subscribeGitSafetyAutoSnapshotEnabled(cb: Subscriber): () => voi
};
}
+export function subscribeGitSafetyMode(cb: ModeSubscriber): () => void {
+ modeSubscribers.add(cb);
+ const storageHandler = (e: StorageEvent) => {
+ if (e.key !== STORAGE_KEY && e.key !== LEGACY_STORAGE_KEY && e.key !== SYNC_KEY) return;
+ cb(getGitSafetyMode(), 'storage');
+ };
+ window.addEventListener('storage', storageHandler);
+
+ return () => {
+ modeSubscribers.delete(cb);
+ window.removeEventListener('storage', storageHandler);
+ };
+}
+
+function hasExplicitLegacyOptOut(): boolean {
+ try {
+ return localStorage.getItem(STORAGE_KEY) === null
+ && localStorage.getItem(LEGACY_STORAGE_KEY) === 'false';
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Old `writePatch({ autoSnapshotEnabled: false })` deleted the main override,
+ * so explicit opt-out looks like "never configured" on disk. The renderer
+ * legacy key is the remaining durable marker; persist it to main *before*
+ * any GET can overwrite the mirror with the new default.
+ */
+export async function persistLegacyGitSafetyOptOut(): Promise<boolean> {
+ if (!hasExplicitLegacyOptOut()) return false;
+ await window.electronAPI.maker.gitSafetySet('off');
+ setGitSafetyMode('off');
+ return true;
+}
+
export async function bootstrapGitSafetySettingsFromMain(): Promise<void> {
try {
+ if (hasExplicitLegacyOptOut()) {
+ try {
+ await persistLegacyGitSafetyOptOut();
+ } catch {
+ // Keep the legacy opt-out marker; do not GET the new default.
+ }
+ return;
+ }
const settings = await window.electronAPI.maker.gitSafetyGet();
- if (getGitSafetyAutoSnapshotEnabled() === settings.autoSnapshotEnabled) return;
- setGitSafetyAutoSnapshotEnabled(settings.autoSnapshotEnabled);
+ const mode =
+ settings.mode === 'off' || settings.mode === 'existing-git' || settings.mode === 'all-projects'
+ ? settings.mode
+ : settings.autoSnapshotEnabled
+ ? 'all-projects'
+ : 'off';
+ setGitSafetyMode(mode);
} catch {
// preload unavailable / IPC failed — keep local fallback.
}
diff --git a/apps/desktop/src/renderer/lib/sessionService.ts b/apps/desktop/src/renderer/lib/sessionService.ts
index e65d4d310a..98d150f79c 100644
--- a/apps/desktop/src/renderer/lib/sessionService.ts
+++ b/apps/desktop/src/renderer/lib/sessionService.ts
@@ -344,7 +344,7 @@ export async function rewindPreview(
export async function rewindCommit(
sessionId: string,
clientId: string,
- opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean },
+ opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean; allowFileRestore?: boolean },
): Promise<Session> {
return wrap(
makerApiFor(sessionId).rewindCommit(sessionId, clientId, opts) as Promise<Session>,
diff --git a/apps/desktop/src/renderer/main-entry.tsx b/apps/desktop/src/renderer/main-entry.tsx
index de605fe86d..0a38f6bb06 100644
--- a/apps/desktop/src/renderer/main-entry.tsx
+++ b/apps/desktop/src/renderer/main-entry.tsx
@@ -72,8 +72,6 @@ void bootstrapSilentEncryptedRetryFromMain();
void bootstrapChatEmbeddingFromMain();
// LSP Beta 开关 (Phase 1) — admin-only, 默认 false; 同款镜像同步方式。
void bootstrapLspModeFromMain();
-// Git safety workflow 开关 — 默认 false; Codex rewind 入口同步依赖此镜像。
-void bootstrapGitSafetySettingsFromMain();
const view = new URLSearchParams(window.location.search).get('view');
const isVoiceInputOverlay = view === 'voice-input-overlay';
@@ -214,9 +212,11 @@ void (async () => {
import.meta.hot?.dispose(disposeRsbBrowserBridge);
}
- // 主视图挂载前完成 memory 真值同步与旧配置迁移,确保用户可交互的 toggle 不会和
- // 启动快照并发。浮窗不消费该设置,跳过同步以免多个 renderer 争写共享 localStorage。
+ // 主视图挂载前完成 memory 与 Git safety 真值同步及旧配置迁移,确保用户可交互的
+ // toggle、回退入口不会在镜像迁移完成前和启动快照并发。浮窗不消费这些设置,跳过
+ // 同步以免多个 renderer 争写共享 localStorage。
await bootstrapMemorySettingsFromMain();
+ await bootstrapGitSafetySettingsFromMain();
// TapDB 在线活跃上报 — 只在主视图启用,避免 voice-input 浮窗的弹出被算成 PV。
// 这里只挂"同意闸":SDK 是否初始化由 main 的 analytics-settings 决定,用户没
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 2f1778f45c..d6c2b8d60a 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -939,6 +939,8 @@ interface CCAgentSdkSessionIdPayload {
*/
interface RewindFilesResultPayload {
canRewind: boolean;
+ conversationOnly?: boolean;
+ gitSafetyDisabled?: boolean;
error?: string;
filesChanged?: string[];
insertions?: number;
@@ -2184,7 +2186,7 @@ interface ElectronAPI {
// 永不上报,凭证与邮箱在上传前被自动抹除(实现见 main/log-upload/)。
getLogUploadSettings: () => Promise<LogUploadSettingsPayload>;
setLogUploadCrashAuto: (enabled: boolean) => Promise<LogUploadSettingsPayload>;
- /** 恢复默认:删掉开关 override,重新跟随当前版本默认值(默认关闭)。 */
+ /** 恢复默认:删掉 override,重新跟随当前版本默认的“已有 Git 项目”模式。 */
resetLogUploadCrashAuto: () => Promise<LogUploadSettingsPayload>;
/**
* 手动上传一次;成功返回可报的上传编号。失败以 IPC 错误码区分:
@@ -6277,19 +6279,28 @@ interface ElectronAPI {
/** Git 安全保存点开关 — 控制 agent turn 后是否自动创建 XDT savepoint commit */
gitSafetyGet: () => Promise<{
+ mode: 'off' | 'existing-git' | 'all-projects';
autoSnapshotEnabled: boolean;
+ autoInitProjectGit: boolean;
isCustomized: boolean;
+ defaultMode: 'off' | 'existing-git' | 'all-projects';
defaultAutoSnapshotEnabled: boolean;
}>;
- /** 立即生效; Codex rewind 入口跟随此开关显示 */
- gitSafetySet: (enabled: boolean) => Promise<{
+ /** 立即生效; mode controls snapshot capture and empty-project bootstrap. */
+ gitSafetySet: (mode: 'off' | 'existing-git' | 'all-projects' | boolean) => Promise<{
+ mode: 'off' | 'existing-git' | 'all-projects';
autoSnapshotEnabled: boolean;
+ autoInitProjectGit: boolean;
isCustomized: boolean;
+ defaultMode: 'off' | 'existing-git' | 'all-projects';
defaultAutoSnapshotEnabled: boolean;
}>;
gitSafetyReset: () => Promise<{
+ mode: 'off' | 'existing-git' | 'all-projects';
autoSnapshotEnabled: boolean;
+ autoInitProjectGit: boolean;
isCustomized: boolean;
+ defaultMode: 'off' | 'existing-git' | 'all-projects';
defaultAutoSnapshotEnabled: boolean;
}>;
@@ -6478,7 +6489,7 @@ interface ElectronAPI {
rewindCommit: (
sessionId: string,
clientId: string,
- opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean },
+ opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean; allowFileRestore?: boolean },
) => Promise<import('@/lib/ccAgent.types').Session>;
forkStripEncrypted: (sourceSessionId: string) => Promise<import('@/lib/ccAgent.types').Session>;
/**
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index f988fb671d..8ec4c65525 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -620,6 +620,7 @@ import { createExpoRemoteMediaDiskCacheIO, downloadRemoteMediaShareTemp } from '
import {
buildRewindPreviewState,
isCommitReadyRewindState,
+ rewindCommitBindOpts,
type RewindPreviewState,
} from '@/session/rewindPreview';
import { projectMobileSessionActions } from '@/session/sessionActionProjection';
@@ -8891,7 +8892,11 @@ export default function SessionScreen() {
setMessageActionBusy({ clientId: state.clientId, kind: 'rewind' });
setError(null);
try {
- const updated = await maker.rewindCommit(sessionId, state.clientId);
+ const updated = await maker.rewindCommit(
+ sessionId,
+ state.clientId,
+ rewindCommitBindOpts(state),
+ );
// applySessionPatch 按显式 sessionId 写目标 session 的分片,与当前浏览无关,即使用户已切走
// 也必须执行,否则该 session 的回撤结果丢失——不受下面 guard 影响。
remoteSessionStore.applySessionPatch(deviceId, sessionId, updated);
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index 8d5080a120..af4a512dbf 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -883,6 +883,7 @@ describe("mobile maker transport", () => {
});
await maker.rewindPreview("s1", "m2");
await maker.rewindCommit("s1", "m2");
+ await maker.rewindCommit("s1", "m2", { allowFileRestore: false });
await maker.deleteMessage("s1", "m2");
expect(calls.map((call) => [call.channel, call.args])).toEqual([
@@ -901,6 +902,7 @@ describe("mobile maker transport", () => {
],
["maker:rewind:preview", ["s1", "m2"]],
["maker:rewind:commit", ["s1", "m2"]],
+ ["maker:rewind:commit", ["s1", "m2", { allowFileRestore: false }]],
["maker:message:delete", ["s1", "m2"]],
]);
});
diff --git a/apps/mobile/src/__tests__/rewindPreview.test.ts b/apps/mobile/src/__tests__/rewindPreview.test.ts
index 9125d3ee88..25f81df1b4 100644
--- a/apps/mobile/src/__tests__/rewindPreview.test.ts
+++ b/apps/mobile/src/__tests__/rewindPreview.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest';
-import { buildRewindPreviewState, isCommitReadyRewindState } from '@/session/rewindPreview';
+import {
+ buildRewindPreviewState,
+ isCommitReadyRewindState,
+ rewindCommitBindOpts,
+} from '@/session/rewindPreview';
describe('rewindPreview model', () => {
it('maps file rewind previews to the default confirm state', () => {
@@ -53,4 +57,24 @@ describe('rewindPreview model', () => {
expect(state.kind).toBe('error');
expect(isCommitReadyRewindState(state)).toBe(false);
});
+
+ it('binds conversation-only confirmation so commit cannot restore files', () => {
+ const empty = buildRewindPreviewState('m2', 'retry this', {
+ canRewind: true,
+ conversationOnly: true,
+ filesChanged: [],
+ });
+ const withFiles = buildRewindPreviewState('m2', 'retry this', {
+ canRewind: true,
+ filesChanged: ['apps/mobile/App.tsx'],
+ });
+
+ expect(empty.kind).toBe('empty');
+ expect(withFiles.kind).toBe('default');
+ if (empty.kind !== 'empty' || withFiles.kind !== 'default') {
+ throw new Error('unexpected rewind preview kinds');
+ }
+ expect(rewindCommitBindOpts(empty)).toEqual({ allowFileRestore: false });
+ expect(rewindCommitBindOpts(withFiles)).toBeUndefined();
+ });
});
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 952503b661..f8621d72ea 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -670,7 +670,11 @@ export interface MobileMakerTransport {
sessionId: string,
clientId: string,
): Promise<RewindPreviewPayload>;
- rewindCommit(sessionId: string, clientId: string): Promise<RemoteSession>;
+ rewindCommit(
+ sessionId: string,
+ clientId: string,
+ opts?: { allowFileRestore?: boolean },
+ ): Promise<RemoteSession>;
deleteMessage(
sessionId: string,
clientId: string,
@@ -1101,8 +1105,11 @@ export function createMobileMakerTransport({
call("maker:fork", [sourceSessionId, messageClientId]),
rewindPreview: (sessionId, clientId) =>
call("maker:rewind:preview", [sessionId, clientId]),
- rewindCommit: (sessionId, clientId) =>
- call("maker:rewind:commit", [sessionId, clientId]),
+ rewindCommit: (sessionId, clientId, opts) =>
+ call(
+ "maker:rewind:commit",
+ opts ? [sessionId, clientId, opts] : [sessionId, clientId],
+ ),
deleteMessage: (sessionId, clientId) =>
call("maker:message:delete", [sessionId, clientId]),
closeSession: (sessionId) => call("maker:close-session", [sessionId]),
diff --git a/apps/mobile/src/i18n/locales/en/interaction.json b/apps/mobile/src/i18n/locales/en/interaction.json
index d074bac8fb..cf9bb12fd7 100644
--- a/apps/mobile/src/i18n/locales/en/interaction.json
+++ b/apps/mobile/src/i18n/locales/en/interaction.json
@@ -127,7 +127,9 @@
},
"rewind": {
"readError": "Couldn't read the rewind preview. Sync again and retry.",
- "noFilesNote": "No files to roll back; only the chat after this message will be truncated.",
+ "noFilesNote": "No project file changes were detected after this message. Continuing will remove the later chat.",
+ "conversationOnlyNote": "Project files cannot be restored because no Git savepoint is available. Continuing will remove the chat after this message; files will not return to their earlier state.",
+ "gitSafetyDisabledNote": "Git safety savepoints are disabled, so project files cannot be restored. Enable them in Settings on your computer; continuing will remove the chat after this message.",
"moreFiles": "{{count}} more files",
"stats": "{{count}} files · +{{insertions}} / -{{deletions}} lines",
"gotIt": "Got it",
@@ -141,7 +143,8 @@
"titleError": "Can't rewind",
"detailLoading": "Reading the file rewind preview from your computer.",
"detailDefault": "This rolls back the files below and truncates the chat after this message.",
- "detailEmpty": "No files to roll back; confirming truncates only the chat after this message.",
+ "detailEmpty": "No project file changes were detected after this message.",
+ "detailConversationOnly": "Project files will not return to their earlier state.",
"detailError": "Your computer declined this rewind."
},
"collab": {
diff --git a/apps/mobile/src/i18n/locales/ja/interaction.json b/apps/mobile/src/i18n/locales/ja/interaction.json
index 600a9fc699..cc7f817ea3 100644
--- a/apps/mobile/src/i18n/locales/ja/interaction.json
+++ b/apps/mobile/src/i18n/locales/ja/interaction.json
@@ -127,7 +127,9 @@
},
"rewind": {
"readError": "巻き戻しプレビューを読み込めませんでした。再同期してからやり直してください。",
- "noFilesNote": "ロールバックするファイルはありません。このメッセージ以降の会話履歴のみを切り詰めます。",
+ "noFilesNote": "このメッセージ以降にプロジェクトファイルの変更はありません。続行すると後のチャットが削除されます。",
+ "conversationOnlyNote": "利用できる Git の保存ポイントがないため、プロジェクトファイルを復元できません。続行するとこのメッセージ以降のチャットが削除され、ファイルは以前の状態に戻りません。",
+ "gitSafetyDisabledNote": "Git の安全な保存ポイントが無効なため、プロジェクトファイルを復元できません。パソコンの設定で有効にしてください。続行するとこのメッセージ以降のチャットが削除されます。",
"moreFiles": "他に {{count}} 件のファイル",
"stats": "{{count}} 件のファイル · +{{insertions}} / -{{deletions}} 行",
"gotIt": "了解",
@@ -141,7 +143,8 @@
"titleError": "巻き戻せません",
"detailLoading": "パソコンからファイルの巻き戻しプレビューを読み込んでいます。",
"detailDefault": "以下のファイルをロールバックし、このメッセージ以降の会話履歴を切り詰めます。",
- "detailEmpty": "ロールバックするファイルはありません。確認するとこのメッセージ以降の会話履歴のみを切り詰めます。",
+ "detailEmpty": "このメッセージ以降にプロジェクトファイルの変更はありません。",
+ "detailConversationOnly": "プロジェクトファイルは以前の状態に戻りません。",
"detailError": "パソコンがこの巻き戻しを拒否しました。"
},
"collab": {
diff --git a/apps/mobile/src/i18n/locales/ko/interaction.json b/apps/mobile/src/i18n/locales/ko/interaction.json
index 9b627d3cda..dd65f48e9f 100644
--- a/apps/mobile/src/i18n/locales/ko/interaction.json
+++ b/apps/mobile/src/i18n/locales/ko/interaction.json
@@ -127,7 +127,9 @@
},
"rewind": {
"readError": "되감기 미리보기를 읽을 수 없습니다. 다시 동기화한 후 시도하세요.",
- "noFilesNote": "롤백할 파일이 없습니다. 이 메시지 이후의 대화 기록만 잘립니다.",
+ "noFilesNote": "이 메시지 이후 프로젝트 파일 변경이 감지되지 않았습니다. 계속하면 이후 채팅이 삭제됩니다.",
+ "conversationOnlyNote": "사용할 수 있는 Git 저장 지점이 없어 프로젝트 파일을 복원할 수 없습니다. 계속하면 이 메시지 이후의 채팅이 삭제되고 파일은 이전 상태로 돌아가지 않습니다.",
+ "gitSafetyDisabledNote": "Git 안전 저장 지점이 비활성화되어 프로젝트 파일을 복원할 수 없습니다. 컴퓨터 설정에서 켜세요. 계속하면 이 메시지 이후의 채팅이 삭제됩니다.",
"moreFiles": "파일 {{count}}개 더",
"stats": "파일 {{count}}개 · +{{insertions}} / -{{deletions}} 줄",
"gotIt": "확인",
@@ -141,7 +143,8 @@
"titleError": "되감을 수 없음",
"detailLoading": "컴퓨터에서 파일 되감기 미리보기를 읽는 중입니다.",
"detailDefault": "아래 파일을 롤백하고 이 메시지 이후의 대화 기록을 자릅니다.",
- "detailEmpty": "롤백할 파일이 없습니다. 확인하면 이 메시지 이후의 대화 기록만 잘립니다.",
+ "detailEmpty": "이 메시지 이후 프로젝트 파일 변경이 감지되지 않았습니다.",
+ "detailConversationOnly": "프로젝트 파일은 이전 상태로 돌아가지 않습니다.",
"detailError": "컴퓨터가 이 되감기를 거부했습니다."
},
"collab": {
diff --git a/apps/mobile/src/i18n/locales/zh-CN/interaction.json b/apps/mobile/src/i18n/locales/zh-CN/interaction.json
index 51ed50729e..7ae16b890d 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/interaction.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/interaction.json
@@ -127,7 +127,9 @@
},
"rewind": {
"readError": "无法读取回退预览结果,请重新同步后再试。",
- "noFilesNote": "没有可回滚的文件,将只截断这条消息之后的对话历史。",
+ "noFilesNote": "这条消息之后没有检测到项目文件改动,继续后会移除后续对话记录。",
+ "conversationOnlyNote": "当前无法恢复项目文件,因为没有可用的 Git 保存点;继续后会移除这条消息之后的对话记录,项目文件不会回到之前的状态。",
+ "gitSafetyDisabledNote": "Git 安全保存点未开启,因此当前无法恢复项目文件。请在电脑端设置中开启;继续后会移除这条消息之后的对话记录。",
"moreFiles": "另有 {{count}} 个文件",
"stats": "{{count}} 个文件 · +{{insertions}} / -{{deletions}} 行",
"gotIt": "知道了",
@@ -141,7 +143,8 @@
"titleError": "无法回退",
"detailLoading": "手机端正在向电脑端读取文件回退预览。",
"detailDefault": "会回滚下面这些文件,并截断这条消息之后的对话历史。",
- "detailEmpty": "没有文件需要回滚,确认后只会截断这条消息之后的对话历史。",
+ "detailEmpty": "这条消息之后没有检测到项目文件改动。",
+ "detailConversationOnly": "项目文件不会回到之前的状态。",
"detailError": "电脑端拒绝了这次回退操作。"
},
"collab": {
diff --git a/apps/mobile/src/i18n/locales/zh-TW/interaction.json b/apps/mobile/src/i18n/locales/zh-TW/interaction.json
index 3d700d5e81..aecec74eb6 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/interaction.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/interaction.json
@@ -127,7 +127,9 @@
},
"rewind": {
"readError": "無法讀取回退預覽結果,請重新同步後再試。",
- "noFilesNote": "沒有可回滾的檔案,將只截斷這條訊息之後的對話歷史。",
+ "noFilesNote": "這則訊息之後沒有偵測到專案檔案改動,繼續後會移除後續對話記錄。",
+ "conversationOnlyNote": "目前無法恢復專案檔案,因為沒有可用的 Git 保存點;繼續後會移除這則訊息之後的對話記錄,專案檔案不會回到之前的狀態。",
+ "gitSafetyDisabledNote": "Git 安全保存點未開啟,因此目前無法恢復專案檔案。請在電腦端設定中開啟;繼續後會移除這則訊息之後的對話記錄。",
"moreFiles": "另有 {{count}} 個檔案",
"stats": "{{count}} 個檔案 · +{{insertions}} / -{{deletions}} 行",
"gotIt": "知道了",
@@ -141,7 +143,8 @@
"titleError": "無法回退",
"detailLoading": "手機端正在向電腦端讀取檔案回退預覽。",
"detailDefault": "會回滾下面這些檔案,並截斷這條訊息之後的對話歷史。",
- "detailEmpty": "沒有檔案需要回滾,確認後只會截斷這條訊息之後的對話歷史。",
+ "detailEmpty": "這則訊息之後沒有偵測到專案檔案改動。",
+ "detailConversationOnly": "專案檔案不會回到之前的狀態。",
"detailError": "電腦端拒絕了這次回退操作。"
},
"collab": {
diff --git a/apps/mobile/src/session/RewindPreviewPanel.tsx b/apps/mobile/src/session/RewindPreviewPanel.tsx
index bd898c22d6..d69b300701 100644
--- a/apps/mobile/src/session/RewindPreviewPanel.tsx
+++ b/apps/mobile/src/session/RewindPreviewPanel.tsx
@@ -140,7 +140,9 @@ function titleForState(state: RewindPreviewState, t: TFunction): string {
function detailForState(state: RewindPreviewState, t: TFunction): string | null {
if (state.kind === 'loading') return t('interaction.rewind.detailLoading');
if (state.kind === 'default') return t('interaction.rewind.detailDefault');
- if (state.kind === 'empty') return t('interaction.rewind.detailEmpty');
+ if (state.kind === 'empty') {
+ return state.note ? t('interaction.rewind.detailConversationOnly') : t('interaction.rewind.detailEmpty');
+ }
return t('interaction.rewind.detailError');
}
diff --git a/apps/mobile/src/session/rewindPreview.ts b/apps/mobile/src/session/rewindPreview.ts
index 89021775a0..9f670233f8 100644
--- a/apps/mobile/src/session/rewindPreview.ts
+++ b/apps/mobile/src/session/rewindPreview.ts
@@ -4,6 +4,8 @@ import type { ComposerDocument } from '@/session/composerDocument';
export interface RewindPreviewPayload {
canRewind: boolean;
+ conversationOnly?: boolean;
+ gitSafetyDisabled?: boolean;
error?: string;
filesChanged?: string[];
insertions?: number;
@@ -91,7 +93,21 @@ export function buildRewindPreviewState(
}
if (payload.canRewind) {
- return { kind: 'empty', clientId, draftText, draftQuotes, ...orderedDraft, ...documentDraft };
+ return {
+ kind: 'empty',
+ clientId,
+ draftText,
+ draftQuotes,
+ ...orderedDraft,
+ ...documentDraft,
+ ...(payload.conversationOnly
+ ? {
+ note: payload.gitSafetyDisabled
+ ? i18n.t('interaction.rewind.gitSafetyDisabledNote')
+ : i18n.t('interaction.rewind.conversationOnlyNote'),
+ }
+ : {}),
+ };
}
return {
@@ -109,11 +125,19 @@ export function isCommitReadyRewindState(state: RewindPreviewState): state is Co
return state.kind === 'default' || state.kind === 'empty';
}
+export function rewindCommitBindOpts(
+ state: CommitReadyRewindState,
+): { allowFileRestore: false } | undefined {
+ return state.kind === 'empty' ? { allowFileRestore: false } : undefined;
+}
+
function normalizeRewindPreviewPayload(value: unknown): RewindPreviewPayload | null {
const record = readRecord(value);
if (!record || typeof record.canRewind !== 'boolean') return null;
return {
canRewind: record.canRewind,
+ conversationOnly: record.conversationOnly === true,
+ gitSafetyDisabled: record.gitSafetyDisabled === true,
error: typeof record.error === 'string' ? record.error : undefined,
filesChanged: readStringArray(record.filesChanged),
insertions: readFiniteNumber(record.insertions),
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 630044fc4a..42452fac7a 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -9,7 +9,7 @@
本区块由 `scripts/design-inventory.mjs` 生成,请勿手改。
重新生成:`pnpm design:inventory`;校验:`pnpm check:design-inventory`。
-计数快照日期:2026-09-20。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。
+计数快照日期:2026-09-21。生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。
登记 surface 数:50。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index ea3b8e38b1..9d00ddf6e5 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -451,6 +451,10 @@ export interface ImageEventData {
export interface RewindFilesResult {
canRewind: boolean;
+ /** True when conversation rewind can proceed but no file restore plan exists. */
+ conversationOnly?: boolean;
+ /** Git savepoints are disabled, so file restoration was not available. */
+ gitSafetyDisabled?: boolean;
error?: string;
filesChanged?: string[];
insertions?: number;