Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): show Cindy Make build progress and history actions

MagicLizi08304f618dbe
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index fe7ace53cd..b0f24be778 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -805,6 +805,7 @@ function extraResourcesForTarget(targetPlatform: string): string[] {
const base = [
'resources/icon.png',
'resources/cindy-source.json',
+ 'resources/cindy-version-protocol.json',
// Input bytes for upgrading retired preset avatars to ordinary managed images.
'resources/legacy-teammate-avatars',
'resources/teammate-portrait-gallery.png',
diff --git a/apps/desktop/resources/cindy-version-protocol.json b/apps/desktop/resources/cindy-version-protocol.json
new file mode 100644
index 0000000000..4aeabd69be
--- /dev/null
+++ b/apps/desktop/resources/cindy-version-protocol.json
@@ -0,0 +1 @@
+{"version":1}
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 295c0e77ce..2fc8d7bcf3 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1,5 +1,21 @@
import { registerFilePeerIpc } from './device-link/filePeer';
import { registerLoginItemIpc } from './login-item-ipc.js';
+import { createLatestSourceVersionReader } from './cindy-make/latestSourceVersion.js';
+import { refreshCindySourceStatus } from './cindy-make/sourceStatusRefresh.js';
+import {
+ configureUpstreamMerge,
+ actUpstreamMerge,
+ refreshUpstreamMergeProjection,
+} from './cindy-make/upstreamMergeRuntime.js';
+import {
+ configureMakeHistory,
+ getCindyMakeHistory,
+ actCindyMakeHistory,
+ generateHistoryPersonalVersion,
+ cancelHistoryPersonalVersion,
+ openHistoryPersonalBuild,
+ stopMakeHistoryBuild,
+} from './cindy-make/historyRuntime.js';
import { retainProviderPresentationAfterAuthChange } from './maker-host/provider-presentation-store.js';
import { codexAccountState } from './maker-host/codex-account-auth.js';
import { syncSubscriptionAccountUsage } from './usage/subscriptionAccountUsage.js';
@@ -13,7 +29,10 @@ import {
auditRegisteredWorktrees,
} from './worktree/recycleMaintenance';
import { requestWorktreeRecycle } from './worktree/managedRecycle';
-import { patchSessionMetaInDb, recycleSessionWorktreeForStatusChange } from './localDb/ipc/sessions';
+import {
+ patchSessionMetaInDb,
+ recycleSessionWorktreeForStatusChange,
+} from './localDb/ipc/sessions';
import { tryGetDbClient } from './localDb/client/current';
import {
app,
@@ -336,10 +355,37 @@ import {
createMakeToolchainEnvironment,
resolveMakeToolEnvironment,
} from './cindy-make/toolchainEnvironment.js';
-import { CINDY_MAKE_RUN_ID_PATTERN } from './cindy-make/sourcePaths.js';
+import {
+ CINDY_MAKE_RUN_ID_PATTERN,
+ isCindyMakeManagedWorktreePath,
+} from './cindy-make/sourcePaths.js';
import { prepareCindyMakeWorkspace } from './cindy-make/taskWorkspace.js';
import { restoreCindyMakeTaskState, startCindyMakeTask } from './cindy-make/taskRuntime.js';
-import { configureCindyMakeTaskManagement, manageCindyMakeTask } from './cindy-make/taskManagement.js';
+import {
+ configureCindyMakeTaskManagement,
+ manageCindyMakeTask,
+ refreshCindyMakeTaskIntegration,
+} from './cindy-make/taskManagement.js';
+import {
+ actCindyMakeTest,
+ cindyMakeTestController,
+ configureCindyMakeTestRuntime,
+} from './cindy-make/testRuntime.js';
+import {
+ actCindyVersion,
+ configureCindyVersions,
+ getCindyVersions,
+} from './cindy-make/versionService.js';
+import {
+ deliverCindyVersionOpenEvents,
+ isCindyVersionLaunchPending,
+ recordCindyVersionActive,
+ watchCindyVersionStartupResult,
+} from './cindy-make/versionStartup.js';
+import {
+ getCindyVersionLockScope,
+ isCindyPersonalRuntime,
+} from './cindy-make/versionRuntimeIdentity.js';
import { createStorageIpcHandlers } from './cindy-media/storageIpc';
import {
collectDatabaseSizeWarningStatus,
@@ -3632,7 +3678,8 @@ function applyPageZoomLevel(mainWindow: BrowserWindow, nextFactor: number): numb
// 写注册表 / .desktop entry; macOS 走 Info.plist, 此调用是兜底)
// - app.on('open-url') 是 macOS-only 事件, 冷启动时也会在 ready 之前 fire,
// 提前 attach 才能接住
-registerDeepLinkProtocol();
+watchCindyVersionStartupResult();
+if (!isCindyPersonalRuntime()) registerDeepLinkProtocol();
app.on('open-url', (event, url) => {
event.preventDefault();
handleIncomingDeepLink(url, 'open-url');
@@ -3684,16 +3731,22 @@ app.on('open-file', (event, filePath) => {
// reader lease 阻止之后的 primary 抢跑 migration。
// 隔离数据实例走 `--isolated[=<名字>]`(独立 userData → 独立锁域,见 docs/dev-rules/desktop-development.md)。
if (
+ getCindyVersionLockScope() !== null ||
shouldRequestSingleInstanceLock({
isPackaged: app.isPackaged,
schedulerPassive: process.env.XDT_SCHEDULER_PASSIVE === '1',
})
) {
const realUserDataDir = app.getPath('userData');
- const lockScopeDir = resolveSingleInstanceLockUserDataDir({
- isPackaged: app.isPackaged,
- userDataDir: realUserDataDir,
- });
+ const lockScopeDir =
+ getCindyVersionLockScope() === 'profile'
+ ? realUserDataDir
+ : getCindyVersionLockScope() === 'dev'
+ ? path.join(realUserDataDir, 'dev-single-instance-lock')
+ : resolveSingleInstanceLockUserDataDir({
+ isPackaged: app.isPackaged,
+ userDataDir: realUserDataDir,
+ });
let gotTheLock: boolean;
if (lockScopeDir === realUserDataDir) {
gotTheLock = app.requestSingleInstanceLock();
@@ -3717,6 +3770,7 @@ if (
);
app.quit();
} else {
+ recordCindyVersionActive();
app.on('second-instance', (_event, argv) => {
// Windows: 用户点 cindy://(或历史 xdt-maker://)链接 / 右键 "通过 Cindy 打开" 时,
// OS 会再起一个本 app 实例; 单例锁把它 redirect 成 second-instance 事件,
@@ -3757,6 +3811,16 @@ if (
}
}
+if (
+ app.hasSingleInstanceLock() ||
+ (getCindyVersionLockScope() === null &&
+ !shouldRequestSingleInstanceLock({
+ isPackaged: app.isPackaged,
+ schedulerPassive: process.env.XDT_SCHEDULER_PASSIVE === '1',
+ }))
+)
+ deliverCindyVersionOpenEvents();
+
// 冷启动 argv 扫描 — Windows 上首次点链接 / 右键 "通过 Cindy 打开" 启动 app
// 时, URL 或 --open-folder 在 process.argv 末尾。macOS deep link 走 open-url
// (已在上面 attach), 这里扫到也不会重复 dispatch; --open-folder 是 Windows-only
@@ -4034,7 +4098,7 @@ const createWindow = () => {
restoreFullscreen: shouldRestoreMacFullscreen,
});
refreshWindowsAppBadge();
- if (!app.isPackaged) markDesktopDevWindowReady();
+ if (!app.isPackaged || isCindyVersionLaunchPending()) markDesktopDevWindowReady();
void runComputerUseSmokeIfRequested();
// 资源用量窗口不应与主窗口首帧争 CPU。主窗口可见后再后台完成 BrowserWindow、
// renderer 和首份进程快照预热;回调绑定当代主窗口,重建/退出后不会创建孤儿窗。
@@ -5818,7 +5882,7 @@ const registerIpcHandlers = () => {
})
.finally(() => authCredentialRecovery.request());
await authManager.ensureStableOwnerPostCommitTasks('auth-initialize');
- if (!app.isPackaged) {
+ if (!app.isPackaged || isCindyVersionLaunchPending()) {
recordDesktopDevAuthStartupResult(state, pendingCompletion, () =>
authManager.getAuthState(),
);
@@ -7511,18 +7575,36 @@ const registerIpcHandlers = () => {
});
});
+ const readLatestSourceVersion = createLatestSourceVersionReader((url, init) =>
+ net.fetch(url, init),
+ );
+ configureUpstreamMerge((id) => getMakerIfReady()?.getSession(id)?.isTurnRunning() ?? false);
+ ipcMain.handle('app:cindy-make-merge', async (event, input: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return actUpstreamMerge(input);
+ });
ipcMain.handle('app:get-cindy-make-source-status', async (event) => {
assertTrustedAppRendererEvent(event);
const userData = app.getPath('userData');
- let env: Awaited<ReturnType<typeof createMakeToolchainEnvironment>> | undefined;
- try {
- env = await createMakeToolchainEnvironment(userData);
- } catch {
- // The persisted status remains usable when tool discovery is unavailable.
- }
- return cindyMakeManager.refreshSourceStatus(() =>
- readCurrentCindySourceStatus(makeSourceRoot(userData), env),
- );
+ const root = makeSourceRoot(userData);
+ const channel = !app.isPackaged
+ ? 'dev'
+ : /-beta(?:\.|$)/i.test(app.getVersion())
+ ? 'beta'
+ : 'release';
+ return refreshCindySourceStatus(cindyMakeManager, {
+ readSummary: () => readCurrentCindySourceStatus(root),
+ readLocal: async () => {
+ let env: Awaited<ReturnType<typeof createMakeToolchainEnvironment>> | undefined;
+ try {
+ env = await createMakeToolchainEnvironment(userData);
+ } catch {
+ // The persisted status remains usable when tool discovery is unavailable.
+ }
+ return readCurrentCindySourceStatus(root, env);
+ },
+ readLatest: (source) => readLatestSourceVersion(source, channel),
+ });
});
// 源码准备是全局单例:进度广播给所有窗口,任意窗口都能停止它。
subscribeCindySourceStatus(broadcastCindyMakeSourceStatus);
@@ -7530,44 +7612,138 @@ const registerIpcHandlers = () => {
configureCindyMakeTaskManagement({
isAlive: (id) => getMakerIfReady()?.isSessionAlive(id),
isRunning: (id) => getMakerIfReady()?.getSession(id)?.isTurnRunning() ?? false,
+ isWorkspaceBusy: (workingDir) => cindyMakeTestController.isUsingWorkspace(workingDir),
setStatus: patchSessionMetaInDb,
recycle: recycleSessionWorktreeForStatusChange,
});
+ configureCindyMakeTestRuntime(
+ (id) => getMakerIfReady()?.getSession(id)?.isTurnRunning() ?? false,
+ );
+ configureMakeHistory((id) => getMakerIfReady()?.getSession(id)?.isTurnRunning() ?? false);
+ ipcMain.handle('app:cindy-make-history', async (event, selected?: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (
+ selected !== undefined &&
+ (typeof selected !== 'string' || !/^[A-Za-z0-9-]{1,128}$/.test(selected))
+ )
+ throwIpcError('INVALID_PARAMS', 'Invalid history selection');
+ try {
+ return await getCindyMakeHistory(selected as string | undefined);
+ } catch (error) {
+ const details = error as { name?: unknown; code?: unknown; message?: unknown };
+ const message =
+ typeof details.message === 'string'
+ ? details.message
+ .replace(/[A-Za-z]:[\\/][^\r\n]{0,240}|\\\\[^\r\n]{0,240}/g, '<path>')
+ .slice(0, 240)
+ : String(error).slice(0, 240);
+ createLogger('cindy-make:history').warn('history read failed', {
+ errorName: typeof details.name === 'string' ? details.name : undefined,
+ errorCode: typeof details.code === 'string' ? details.code : undefined,
+ errorMessage: message,
+ });
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ }
+ });
+ ipcMain.handle(
+ 'app:cindy-make-history-action',
+ async (event, runId: unknown, action: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ try {
+ return await actCindyMakeHistory(runId, action);
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ }
+ },
+ );
+ ipcMain.handle('app:cindy-make-history-build', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ try {
+ return await generateHistoryPersonalVersion();
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ }
+ });
+ app.once('will-quit', stopMakeHistoryBuild);
+ ipcMain.handle('app:cindy-make-history-cancel-build', async (event, buildId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ try {
+ return await cancelHistoryPersonalVersion(buildId);
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ }
+ });
+ ipcMain.handle('app:cindy-make-history-open-build', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ try {
+ await openHistoryPersonalBuild();
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ }
+ });
+ configureCindyVersions(
+ () => cindyMakeTestController.hasActiveJobs() || cindyMakeManager.hasActiveWork(),
+ );
+ ipcMain.handle('app:cindy-versions-state', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ try {
+ return await getCindyVersions();
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ }
+ });
+ ipcMain.handle('app:cindy-versions-action', async (event, action: unknown, id: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return actCindyVersion(action, id);
+ });
+ app.once('will-quit', () => cindyMakeTestController.stopAll());
+ ipcMain.handle(
+ 'app:cindy-make-test',
+ async (event, sessionId: unknown, completionId: unknown, action: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return actCindyMakeTest(sessionId, completionId, action);
+ },
+ );
cindyMakeManager.setProjectBusyProbe(
(root) =>
getMakerIfReady()
?.listActiveSessions()
.some((session) => {
- const relative = path.relative(path.join(root, 'worktrees'), session.workDir);
return (
session.isTurnRunning() &&
- relative.length > 0 &&
- !relative.startsWith('..') &&
- !path.isAbsolute(relative)
+ root === makeSourceRoot(app.getPath('userData')) &&
+ isCindyMakeManagedWorktreePath(app.getPath('userData'), session.workDir)
);
}) ?? false,
);
ipcMain.handle('app:get-cindy-make-state', async (event) => {
assertTrustedAppRendererEvent(event);
+ refreshUpstreamMergeProjection();
try {
await restoreCindyMakeTaskState();
for (const [runId, report] of Object.entries(cindyMakeManager.getState().tasks ?? {})) {
- if (report.task) cindyMakeManager.projectTaskSession(runId, {
- executing: getMakerIfReady()?.getSession(report.task.sessionId)?.isTurnRunning() ?? false,
- });
+ if (report.task)
+ cindyMakeManager.projectTaskSession(runId, {
+ executing:
+ getMakerIfReady()?.getSession(report.task.sessionId)?.isTurnRunning() ?? false,
+ });
}
+ void refreshCindyMakeTaskIntegration();
} catch {
throwIpcError('INTERNAL', 'Could not restore Cindy Make preparation state');
}
return cindyMakeManager.getState();
});
- ipcMain.handle('app:manage-cindy-make-task', async (event, sessionId: unknown, action: unknown) => {
- assertTrustedAppRendererEvent(event);
- await manageCindyMakeTask(sessionId, action).catch((error) => {
- if (error instanceof Error && error.message.startsWith('[')) throw error;
- throwIpcError('INTERNAL', 'cleanupFailed');
- });
- });
+ ipcMain.handle(
+ 'app:manage-cindy-make-task',
+ async (event, sessionId: unknown, action: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ await manageCindyMakeTask(sessionId, action).catch((error) => {
+ if (error instanceof Error && error.message.startsWith('[')) throw error;
+ throwIpcError('INTERNAL', 'cleanupFailed');
+ });
+ },
+ );
ipcMain.handle('app:cancel-cindy-make-source', async (event): Promise<{ success: boolean }> => {
assertTrustedAppRendererEvent(event);
return { success: cancelCindySourcePreparation() };
diff --git a/apps/desktop/src/main/cindy-make/__tests__/completion.test.ts b/apps/desktop/src/main/cindy-make/__tests__/completion.test.ts
index 6de05f3d75..dfa96eb946 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/completion.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/completion.test.ts
@@ -2,8 +2,7 @@ import type { AgentEvent } from '@cindy/maker-core';
import { describe, expect, it, vi } from 'vitest';
import {
- CINDY_MAKE_COMMIT_AUTHOR,
- commitCindyMakeChanges,
+ collectCindyMakeChanges,
createCindyMakeCompletionTracker,
type CindyMakeCompletionSession,
} from '../completion';
@@ -84,12 +83,13 @@ describe('cindy_make completion tracker', () => {
expect(warn).toHaveBeenCalled();
});
- it('treats a terminal error as the end of the turn', async () => {
+ it('does not commit or publish completion when the turn ends with an error after reporting', async () => {
const { session, emit } = fakeSession();
const persist = vi.fn(async () => undefined);
+ const collectFacts = vi.fn(async () => ({}));
const tracker = createCindyMakeCompletionTracker({
getSession: () => session,
- collectFacts: async () => ({}),
+ collectFacts,
persist,
logger: { warn: vi.fn() },
});
@@ -99,58 +99,55 @@ describe('cindy_make completion tracker', () => {
expect(persist).not.toHaveBeenCalled();
emit({ type: 'error', data: { isTerminal: true } } as AgentEvent);
await flush();
- expect(persist).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('commitCindyMakeChanges', () => {
- it('commits the worktree with a fixed identity and reports the new commit', async () => {
- let head = 'aaaaaaa1111';
- const git = vi.fn(async (args: string[]) => {
- if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') return 'cindy-make/run-1\n';
- if (args[0] === 'status') return ' M a.ts\n?? b.ts\n\n';
- if (args[0] === 'add') return '';
- if (args.includes('commit')) {
- head = 'bbbbbbb2222';
- return '';
- }
- if (args[0] === 'rev-parse') return `${head}\n`;
- throw new Error(`unexpected ${args.join(' ')}`);
- });
- await expect(commitCindyMakeChanges(git, 'Cindy Make: 修复闪烁')).resolves.toEqual({
- branch: 'cindy-make/run-1',
- changedFiles: 2,
- commit: 'bbbbbbb2222',
- });
- const commitCall = git.mock.calls.map(([args]) => args).find((args) => args.includes('commit'));
- expect(commitCall).toEqual(
- expect.arrayContaining([
- `user.name=${CINDY_MAKE_COMMIT_AUTHOR}`,
- '--no-verify',
- '--message',
- 'Cindy Make: 修复闪烁',
- ]),
- );
- expect(git).toHaveBeenCalledWith(['add', '--all']);
+ expect(persist).not.toHaveBeenCalled();
+ expect(collectFacts).not.toHaveBeenCalled();
+ expect(tracker.isPending('make-3')).toBe(false);
});
- it('does not commit when nothing changed and keeps whichever answer Git can still give', async () => {
- const clean = vi.fn(async (args: string[]) => {
- if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') return 'HEAD';
- if (args[0] === 'status') return '';
- if (args[0] === 'rev-parse') return 'abcdef1234567';
- throw new Error('unexpected');
- });
- await expect(commitCindyMakeChanges(clean, 'msg')).resolves.toEqual({
- changedFiles: 0,
- commit: 'abcdef1234567',
+ it.each([
+ { status: 'cancelled' },
+ { status: 'interrupted' },
+ { status: 'failed' },
+ { is_error: true },
+ ])('does not commit a reported change after an unsuccessful done: %j', async (data) => {
+ const { session, emit, listenerCount } = fakeSession();
+ const collectFacts = vi.fn(async () => ({}));
+ const persist = vi.fn(async () => undefined);
+ const tracker = createCindyMakeCompletionTracker({
+ getSession: () => session,
+ collectFacts,
+ persist,
+ logger: { warn: vi.fn() },
});
- expect(clean.mock.calls.some(([args]) => args.includes('commit'))).toBe(false);
+ await tracker.report('make-stopped');
+ emit({ type: 'done', data } as AgentEvent);
+ await flush();
+ expect(collectFacts).not.toHaveBeenCalled();
+ expect(persist).not.toHaveBeenCalled();
+ expect(tracker.isPending('make-stopped')).toBe(false);
+ expect(listenerCount()).toBe(0);
- const broken = vi.fn(async (args: string[]) => {
- if (args[0] === 'status' || args[1] === '--abbrev-ref') throw new Error('not a repo');
- return 'not-a-hash';
- });
- await expect(commitCindyMakeChanges(broken, 'msg')).resolves.toEqual({});
+ // A later successful turn must explicitly report its own completion.
+ emit({ type: 'done', data: {} } as AgentEvent);
+ await flush();
+ expect(collectFacts).not.toHaveBeenCalled();
+ await tracker.report('make-stopped');
+ emit({ type: 'done', data: {} } as AgentEvent);
+ await flush();
+ expect(collectFacts).toHaveBeenCalledOnce();
+ expect(persist).toHaveBeenCalledOnce();
});
});
+
+describe('completion branch protection', () => {
+ it.each(['main', 'cindy-personal', 'HEAD', 'cindy-make/another'])(
+ 'refuses to snapshot an unexpected branch: %s',
+ async (branch) => {
+ const git = vi.fn(async () => branch);
+ await expect(
+ collectCindyMakeChanges(git, 'profile', 'profile/cindy-make/worktrees/run'),
+ ).rejects.toThrow('Unexpected Cindy Make worktree');
+ expect(git).toHaveBeenCalledTimes(1);
+ },
+ );
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/featureHistory.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/featureHistory.git-integration.test.ts
new file mode 100644
index 0000000000..303a8c9459
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/featureHistory.git-integration.test.ts
@@ -0,0 +1,291 @@
+import os from 'node:os';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { expect, it } from 'vitest';
+import { runSourceGit } from '../sourceGit';
+import { createCindyMakeWorktree } from '../taskWorkspace';
+import { collectCindyMakeChanges } from '../completion';
+import { manageCindyMakeWorkspace } from '../taskCleanup';
+import {
+ prepareFeatureMerge,
+ applyFeatureMerge,
+ mergeWorktree,
+ prepareUpstreamMerge,
+ applyUpstreamMerge,
+} from '../upstreamMerge';
+import { makeSourceCheckoutPath } from '../sourcePaths';
+import { planFeatureChange } from '../featurePlan';
+import { CindyMakeHistoryStore } from '../historyStore';
+import type { MakeFeatureAction } from '../../../shared/cindyMakeHistory';
+import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
+
+async function fixture() {
+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-feature-history-'));
+ const source = makeSourceCheckoutPath(userData);
+ const remote = path.join(userData, 'official');
+ const env = {
+ PATH: process.env.PATH,
+ SystemRoot: process.env.SystemRoot,
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_CONFIG_GLOBAL: path.join(userData, 'gitconfig'),
+ };
+ const git = (args: string[], cwd = source, indexFile?: string) =>
+ runSourceGit(
+ { ...env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args.map((arg) => (arg === 'https://github.com/makecindy/cindy.git' ? remote : arg)),
+ cwd,
+ AbortSignal.timeout(30000),
+ );
+ const commit = async (cwd: string, title: string) => {
+ await git(['add', '.'], cwd);
+ await git(
+ [
+ '-c',
+ 'user.name=Test',
+ '-c',
+ '-c',
+ 'commit.gpgSign=false',
+ 'commit',
+ '-s',
+ '-m',
+ title,
+ ],
+ cwd,
+ );
+ };
+ const clean = () => rm(userData, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
+ try {
+ await writeFile(env.GIT_CONFIG_GLOBAL, '');
+ await mkdir(remote);
+ await git(['init', '--initial-branch=main'], remote);
+ await writeFile(path.join(remote, 'a.txt'), 'base-a\n');
+ await writeFile(path.join(remote, 'b.txt'), 'base-b\n');
+ await commit(remote, 'base');
+ await mkdir(path.dirname(source), { recursive: true });
+ await git(['clone', remote, source], userData);
+ await git(['checkout', '-b', 'cindy-personal']);
+ const store = new CindyMakeHistoryStore(path.join(userData, 'history'));
+ const task = async (runId: string, file: string, content: string) => {
+ const worktree = await createCindyMakeWorktree(userData, runId, AbortSignal.timeout(30000), {
+ processEnvironment: env,
+ });
+ store.seed({
+ runId,
+ sessionId: runId + '-session',
+ title: runId,
+ request: runId,
+ createdAt: 1,
+ updatedAt: 1,
+ });
+ await writeFile(path.join(worktree.path, file), content);
+ const facts = await collectCindyMakeChanges(git, userData, worktree.path);
+ store.completion(runId, { ...facts, id: randomUUID(), reportedAt: Date.now() });
+ return worktree;
+ };
+ const record = (state: CindyMakeMergeState) => {
+ if (state.status !== 'merged') return;
+ store.receipt(state.feature!.runId, {
+ id: state.id,
+ action: state.feature!.action,
+ at: Date.now(),
+ baselineCommit: state.baselineCommit!,
+ commit: state.commit!,
+ beforeTree: state.baselineTree!,
+ tree: state.tree!,
+ taskTree: state.feature!.taskTree,
+ });
+ };
+ const action = async (runId: string, action: MakeFeatureAction) => {
+ const history = store.read(runId)!;
+ const state = await prepareFeatureMerge(
+ userData,
+ { id: randomUUID(), status: 'merging', ref: 'personal', upstreamCommit: '' },
+ planFeatureChange(history, action, history.completions.at(-1)),
+ git,
+ async () => {},
+ );
+ record(state);
+ return state;
+ };
+ return { userData, source, remote, env, git, store, task, commit, clean, action, record };
+ } catch (error) {
+ await clean();
+ throw error;
+ }
+}
+
+it('keeps history and undoable changes after ending a worktree, preserves another feature, and reapplies explicitly', async () => {
+ const h = await fixture();
+ try {
+ const a = await h.task('aaaa', 'a.txt', 'feature-a\n');
+ expect((await h.action('aaaa', 'integrate')).status).toBe('merged');
+ await h.task('bbbb', 'b.txt', 'feature-b\n');
+ await h.action('bbbb', 'integrate');
+ await manageCindyMakeWorkspace(h.userData, 'aaaa', 'end', h.env, AbortSignal.timeout(30000));
+ h.store.end('aaaa');
+ expect(h.store.list()).toHaveLength(2);
+ expect(h.store.read('aaaa')?.endedAt).toBeTypeOf('number');
+ await expect(readFile(path.join(a.path, 'a.txt'))).rejects.toThrow();
+ expect((await h.action('aaaa', 'revert')).status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'a.txt'), 'utf8')).toBe('base-a\n');
+ expect(await readFile(path.join(h.source, 'b.txt'), 'utf8')).toBe('feature-b\n');
+ expect((await h.action('aaaa', 'reapply')).status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'a.txt'), 'utf8')).toBe('feature-a\n');
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ } finally {
+ await h.clean();
+ }
+}, 90000);
+
+it('undoes all rounds of one make after an official rebase without removing the newer official files', async () => {
+ const h = await fixture();
+ try {
+ const a = await h.task('aaaa', 'a.txt', 'feature-a\n');
+ await h.action('aaaa', 'integrate');
+ await h.task('bbbb', 'b.txt', 'feature-b\n');
+ await h.action('bbbb', 'integrate');
+ await writeFile(path.join(a.path, 'a.txt'), 'feature-a-updated\n');
+ h.store.completion('aaaa', {
+ ...(await collectCindyMakeChanges(h.git, h.userData, a.path)),
+ id: randomUUID(),
+ reportedAt: Date.now(),
+ });
+ await h.action('aaaa', 'integrate');
+ await writeFile(path.join(h.remote, 'official.txt'), 'new official content\n');
+ await h.commit(h.remote, 'official update');
+ const upstreamCommit = await h.git(['rev-parse', 'HEAD'], h.remote);
+ expect(
+ (
+ await prepareUpstreamMerge(
+ h.userData,
+ { id: randomUUID(), status: 'fetching', ref: 'main', upstreamCommit },
+ h.git,
+ async () => {},
+ )
+ ).status,
+ ).toBe('merged');
+ expect((await h.action('aaaa', 'revert')).status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'a.txt'), 'utf8')).toBe('base-a\n');
+ expect(await readFile(path.join(h.source, 'b.txt'), 'utf8')).toBe('feature-b\n');
+ expect(await readFile(path.join(h.source, 'official.txt'), 'utf8')).toBe(
+ 'new official content\n',
+ );
+ expect((await h.action('aaaa', 'reapply')).status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'a.txt'), 'utf8')).toBe('feature-a-updated\n');
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ } finally {
+ await h.clean();
+ }
+}, 120000);
+
+it('isolates an undo conflict and adopts the resolved delta once without resetting later history', async () => {
+ const h = await fixture();
+ try {
+ await h.task('aaaa', 'a.txt', 'feature-a\n');
+ await h.action('aaaa', 'integrate');
+ await h.task('bbbb', 'a.txt', 'feature-b-depends-on-a\n');
+ await h.action('bbbb', 'integrate');
+ const before = await h.git(['rev-parse', 'HEAD']);
+ const pending = await h.action('aaaa', 'revert');
+ expect(pending.status).toBe('conflict');
+ expect(await h.git(['rev-parse', 'HEAD'])).toBe(before);
+ expect(await readFile(path.join(h.source, 'a.txt'), 'utf8')).toBe('feature-b-depends-on-a\n');
+ const worktree = mergeWorktree(h.userData, pending.id);
+ await writeFile(path.join(worktree, 'a.txt'), 'feature-b-without-a\n');
+ await h.git(['add', '.'], worktree);
+ const resolved = await applyFeatureMerge(h.userData, pending, h.git);
+ expect(resolved.status).toBe('merged');
+ h.record(resolved);
+ h.record(resolved);
+ expect(h.store.read('aaaa')?.receipts).toHaveLength(2);
+ expect(await h.git(['merge-base', '--is-ancestor', before, 'HEAD'])).toBe('');
+ expect(await readFile(path.join(h.source, 'a.txt'), 'utf8')).toBe('feature-b-without-a\n');
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ expect((await applyFeatureMerge(h.userData, resolved, h.git)).commit).toBe(resolved.commit);
+ } finally {
+ await h.clean();
+ }
+}, 90000);
+
+it('retries a merge whose commit hook failed without attempting a second merge over MERGE_HEAD', async () => {
+ const h = await fixture();
+ try {
+ await h.task('aaaa', 'a.txt', 'feature-a');
+ const hooks = path.join(h.userData, 'hooks');
+ await mkdir(hooks);
+ const hook = path.join(hooks, 'pre-commit');
+ await writeFile(hook, ['#!/bin/sh', 'exit 1', ''].join(String.fromCharCode(10)), {
+ mode: 0o755,
+ });
+ await h.git(['config', 'core.hooksPath', hooks]);
+ let saved: CindyMakeMergeState | undefined;
+ const record = h.store.read('aaaa')!;
+ await expect(
+ prepareFeatureMerge(
+ h.userData,
+ { id: randomUUID(), status: 'merging', ref: 'personal', upstreamCommit: '' },
+ planFeatureChange(record, 'integrate', record.completions.at(-1)),
+ h.git,
+ async (state) => {
+ saved = state;
+ },
+ ),
+ ).rejects.toThrow();
+ expect(await h.git(['rev-parse', 'HEAD'])).toBe(saved!.baselineCommit);
+ await writeFile(hook, ['#!/bin/sh', 'exit 0', ''].join(String.fromCharCode(10)));
+ const result = await applyFeatureMerge(h.userData, saved!, h.git);
+ expect(result.status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'a.txt'), 'utf8')).toBe('feature-a');
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ } finally {
+ await h.clean();
+ }
+}, 90000);
+
+it('holds an otherwise clean official rebase for review when a previous merge introduced additional code', async () => {
+ const h = await fixture();
+ try {
+ await h.task('aaaa', 'a.txt', 'feature-a');
+ await h.git([
+ '-c',
+ 'user.name=Test',
+ '-c',
+ 'merge',
+ '--no-commit',
+ '--no-ff',
+ 'cindy-make/aaaa',
+ ]);
+ await writeFile(path.join(h.source, 'merge-only.txt'), 'preserve this merge resolution');
+ await h.commit(h.source, 'manual integration with additional code');
+ const original = await h.git(['rev-parse', 'HEAD']);
+ await writeFile(path.join(h.remote, 'official.txt'), 'latest official content');
+ await h.commit(h.remote, 'official update');
+ const upstreamCommit = await h.git(['rev-parse', 'HEAD'], h.remote);
+ const state = await prepareUpstreamMerge(
+ h.userData,
+ { id: randomUUID(), status: 'fetching', ref: 'main', upstreamCommit },
+ h.git,
+ async () => {},
+ );
+ expect(state).toMatchObject({ status: 'conflict', rebaseReview: true });
+ expect(await h.git(['rev-parse', 'HEAD'])).toBe(original);
+ expect(await readFile(path.join(h.source, 'merge-only.txt'), 'utf8')).toBe(
+ 'preserve this merge resolution',
+ );
+ const worktree = mergeWorktree(h.userData, state.id);
+ await writeFile(path.join(worktree, 'merge-only.txt'), 'preserve this merge resolution');
+ const result = await applyUpstreamMerge(h.userData, state, h.git);
+ expect(result.status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'merge-only.txt'), 'utf8')).toBe(
+ 'preserve this merge resolution',
+ );
+ expect(await readFile(path.join(h.source, 'official.txt'), 'utf8')).toBe(
+ 'latest official content',
+ );
+ } finally {
+ await h.clean();
+ }
+}, 90000);
diff --git a/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts b/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts
new file mode 100644
index 0000000000..968f1b90d5
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from 'vitest';
+import { makeHistoryActions } from '../../../shared/cindyMakeHistory';
+
+const ready = {
+ lifecycle: 'ready' as const,
+ integration: 'unintegrated' as const,
+ sessionAvailable: true,
+ workspaceAvailable: true,
+ sourceAvailable: true,
+ completed: true,
+ hasReceipts: false,
+ busy: false,
+ conflict: false,
+};
+describe('history action admission', () => {
+ it.each(['preparing', 'running'] as const)(
+ 'offers only task navigation while %s',
+ (lifecycle) => {
+ expect(makeHistoryActions({ ...ready, lifecycle })).toEqual(['open']);
+ },
+ );
+ it('offers integration only for verified completed edits, without duplicate Open and Continue controls', () => {
+ expect(makeHistoryActions(ready)).toEqual(['continue', 'test', 'integrate', 'end']);
+ expect(makeHistoryActions({ ...ready, integration: 'unknown' })).toEqual(['open', 'end']);
+ expect(makeHistoryActions({ ...ready, integration: 'unchanged' })).toEqual(['continue', 'end']);
+ expect(makeHistoryActions({ ...ready, completed: false, lifecycle: 'editing' })).toEqual([
+ 'open',
+ 'end',
+ ]);
+ });
+ it('shows Undo after integration, Reapply after undo, and does not offer first-time integration twice', () => {
+ expect(makeHistoryActions({ ...ready, integration: 'integrated', hasReceipts: true })).toEqual([
+ 'continue',
+ 'test',
+ 'end',
+ 'revert',
+ ]);
+ expect(makeHistoryActions({ ...ready, integration: 'reverted', hasReceipts: true })).toEqual([
+ 'continue',
+ 'test',
+ 'end',
+ 'reapply',
+ ]);
+ expect(
+ makeHistoryActions({
+ ...ready,
+ integration: 'reverted',
+ hasReceipts: true,
+ newChanges: true,
+ }),
+ ).toEqual(['continue', 'test', 'integrate', 'end']);
+ expect(
+ makeHistoryActions({
+ ...ready,
+ lifecycle: 'ended',
+ workspaceAvailable: false,
+ integration: 'reverted',
+ hasReceipts: true,
+ }),
+ ).toEqual(['open', 'reapply']);
+ });
+ it('does not offer editing or cleanup again for ended history, but still permits retained undo', () => {
+ expect(
+ makeHistoryActions({
+ ...ready,
+ lifecycle: 'ended',
+ workspaceAvailable: false,
+ integration: 'integrated',
+ hasReceipts: true,
+ }),
+ ).toEqual(['open', 'revert']);
+ expect(makeHistoryActions({ ...ready, lifecycle: 'ended', workspaceAvailable: false })).toEqual(
+ ['open', 'integrate'],
+ );
+ });
+ it('replaces mutations with conflict recovery or the specific failed preparation/cleanup action', () => {
+ expect(makeHistoryActions({ ...ready, conflict: true })).toEqual(['open', 'resolve']);
+ expect(makeHistoryActions({ ...ready, lifecycle: 'failed' })).toEqual([
+ 'open',
+ 'retry-prepare',
+ 'end',
+ ]);
+ expect(makeHistoryActions({ ...ready, lifecycle: 'cleanup' })).toEqual([
+ 'open',
+ 'retry-cleanup',
+ ]);
+ expect(makeHistoryActions({ ...ready, lifecycle: 'ended', buildFailed: true })).toEqual([
+ 'open',
+ 'build',
+ 'integrate',
+ ]);
+ expect(
+ makeHistoryActions({
+ ...ready,
+ lifecycle: 'ended',
+ sessionAvailable: false,
+ buildFailed: true,
+ integration: 'integrated',
+ }),
+ ).toEqual(['build']);
+ });
+ it('blocks all writes while busy or when the source no longer supports their receipts', () => {
+ expect(makeHistoryActions({ ...ready, busy: true })).toEqual(['open']);
+ const actions = makeHistoryActions({
+ ...ready,
+ sourceAvailable: false,
+ integration: 'unknown',
+ hasReceipts: true,
+ });
+ expect(actions).not.toContain('integrate');
+ expect(actions).not.toContain('revert');
+ expect(actions).not.toContain('reapply');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/historyLegacy.test.ts b/apps/desktop/src/main/cindy-make/__tests__/historyLegacy.test.ts
new file mode 100644
index 0000000000..af8932c6c2
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/historyLegacy.test.ts
@@ -0,0 +1,45 @@
+import { expect, it, vi } from 'vitest';
+import { readLegacyFeatureReceipts } from '../historyLegacy';
+import type { CindyMakeHistoryRecord } from '../../../shared/cindyMakeHistory';
+
+it('reconstructs undo only from a proven legacy integration and rejects a file-only or unrelated build commit', async () => {
+ const record: CindyMakeHistoryRecord = {
+ schema: 1,
+ runId: 'aaaa',
+ sessionId: 'session',
+ title: 'Feature',
+ request: '',
+ createdAt: 1,
+ updatedAt: 2,
+ receipts: [],
+ versions: [],
+ completions: [
+ {
+ id: 'completion',
+ reportedAt: 2,
+ commit: 'a'.repeat(40),
+ tree: 'b'.repeat(40),
+ personal: { status: 'ready', commit: 'c'.repeat(40), tree: 'd'.repeat(40) },
+ },
+ ],
+ };
+ const git = vi.fn(async (args: string[]) => {
+ if (args[0] === 'rev-parse') return args[1].startsWith('c') ? 'd'.repeat(40) : 'e'.repeat(40);
+ if (args.includes('--format=%P')) return 'f'.repeat(40) + ' ' + 'a'.repeat(40);
+ return 'Cindy Make: integrate personal feature';
+ });
+ const receipts = await readLegacyFeatureReceipts(record, git, 'source');
+ expect(receipts).toEqual([
+ expect.objectContaining({
+ action: 'integrate',
+ baselineCommit: 'f'.repeat(40),
+ beforeTree: 'e'.repeat(40),
+ tree: 'd'.repeat(40),
+ taskTree: 'b'.repeat(40),
+ }),
+ ]);
+ expect((await readLegacyFeatureReceipts(record, git, 'source'))[0].id).toBe(receipts[0].id);
+ record.completions[0].personal!.tree = '9'.repeat(40);
+ expect(await readLegacyFeatureReceipts(record, git, 'source')).toEqual([]);
+ expect(await readLegacyFeatureReceipts({ ...record, receipts }, git, 'source')).toEqual([]);
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts b/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts
new file mode 100644
index 0000000000..1a990b21ff
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts
@@ -0,0 +1,367 @@
+import path from 'node:path';
+import os from 'node:os';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { CindyMakeHistoryRecord, MakeFeatureReceipt } from '../../../shared/cindyMakeHistory';
+const h = vi.hoisted(() => ({
+ current: true,
+ running: false,
+ busy: false,
+ exists: true,
+ rows: [] as any[],
+ cards: [] as any[],
+ records: new Map<string, CindyMakeHistoryRecord>(),
+ state: {} as any,
+ verify: vi.fn(async () => {}),
+ merge: vi.fn(),
+ end: vi.fn(),
+ saved: vi.fn(),
+ artifactPath: vi.fn(),
+ showItem: vi.fn(),
+ build: vi.fn(),
+}));
+const store = {
+ readBuild: vi.fn(),
+ saveBuild: vi.fn(),
+ directory: path.join(os.tmpdir(), 'history-runtime-unit-no-io'),
+ read: (id: string) => h.records.get(id),
+ list: () => [...h.records.values()].map((record) => structuredClone(record)),
+ seed: (record: any) => {
+ h.saved();
+ const old = h.records.get(record.runId);
+ h.records.set(record.runId, {
+ schema: 1,
+ completions: [],
+ receipts: [],
+ versions: [],
+ ...record,
+ ...old,
+ });
+ },
+ completion: (id: string, completion: any) => {
+ const record = h.records.get(id)!;
+ record.completions = [
+ ...record.completions.filter((entry) => entry.id !== completion.id),
+ completion,
+ ];
+ },
+ receipt: (id: string, receipt: MakeFeatureReceipt) => h.records.get(id)!.receipts.push(receipt),
+ version: vi.fn(),
+};
+vi.mock('electron', () => ({
+ app: { getPath: () => path.join(os.tmpdir(), 'history-runtime-profile') },
+ shell: { showItemInFolder: h.showItem },
+}));
+vi.mock('node:fs', () => ({ existsSync: () => h.exists }));
+vi.mock('../../utils/atomicWriteFile.js', () => ({
+ readAtomicFileSync: () => null,
+ atomicWriteFileSync: vi.fn(),
+}));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+vi.mock('../historyOwner.js', () => ({ captureMakeHistoryStore: () => store }));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({ ownerScopeKey: 'owner' }),
+ isDataOwnerBroadcastScopeCurrent: () => h.current,
+}));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => client }));
+vi.mock('../../localDb/sessionRouteLock.js', () => ({
+ withSessionRouteLock: async (_id: string, run: () => unknown) => run(),
+}));
+vi.mock('../upstreamMergeRuntime.js', () => ({
+ integrateMakeHistory: h.merge,
+ actUpstreamMerge: vi.fn(),
+}));
+vi.mock('../taskManagement.js', () => ({ manageCindyMakeTask: h.end }));
+vi.mock('../testRuntime.js', () => ({
+ actCindyMakeTest: vi.fn(),
+ cindyMakeTestController: { hasActiveJobs: () => false, isBuilding: () => false },
+}));
+vi.mock('../testRunner.js', () => ({ verifyMakeTestWorkspace: h.verify }));
+vi.mock('../personalBuild.js', () => ({
+ buildCindyPersonal: h.build,
+ personalBuildEnvironment: vi.fn(),
+ personalArtifactPath: h.artifactPath,
+}));
+vi.mock('../versionStartup.js', () => ({
+ rememberOriginalVersion: vi.fn(),
+ currentVersionProfile: vi.fn(),
+}));
+vi.mock('../toolchainEnvironment.js', () => ({
+ createMakeToolchainEnvironment: async () => ({
+ probe: async () => ({ path: process.execPath, status: 'ok' }),
+ }),
+ resolveMakeToolEnvironment: async () => ({}),
+}));
+vi.mock('../sourceGit.js', () => ({
+ runSourceGit: async (_env: unknown, args: string[]) =>
+ args[0] === 'branch' ? 'cindy-personal' : '',
+}));
+vi.mock('../manager.js', () => ({
+ cindyMakeManager: {
+ getState: () => h.state,
+ hasActiveWork: () => h.busy,
+ isTaskPreparing: () => false,
+ withProjectUse: async (_root: string, operation: () => unknown) => operation(),
+ },
+}));
+import { sessions } from '../../localDb/schema';
+import {
+ configureMakeHistory,
+ getCindyMakeHistory,
+ actCindyMakeHistory,
+ cancelHistoryPersonalVersion,
+ openHistoryPersonalBuild,
+ generateHistoryPersonalVersion,
+} from '../historyRuntime';
+const client = {
+ drizzle: {
+ select: () => {
+ let table: unknown;
+ const query = {
+ from: (value: unknown) => {
+ table = value;
+ return query;
+ },
+ where: () => query,
+ limit: async () => h.rows,
+ then: (resolve: (value: any[]) => unknown) =>
+ Promise.resolve(table === sessions ? h.rows : h.cards).then(resolve),
+ };
+ return query;
+ },
+ },
+};
+const receipt: MakeFeatureReceipt = {
+ id: 'operation',
+ action: 'integrate',
+ at: 4,
+ baselineCommit: 'a'.repeat(40),
+ commit: 'b'.repeat(40),
+ beforeTree: 'c'.repeat(40),
+ tree: 'd'.repeat(40),
+ taskTree: 'e'.repeat(40),
+};
+beforeEach(() => {
+ vi.clearAllMocks();
+ store.readBuild.mockReset();
+ store.saveBuild.mockReset();
+ h.artifactPath.mockResolvedValue(path.join(os.tmpdir(), 'history-installer.exe'));
+ h.current = true;
+ h.running = false;
+ h.busy = false;
+ h.exists = true;
+ h.records.clear();
+ h.state = {};
+ h.verify.mockResolvedValue(undefined);
+ configureMakeHistory(() => h.running);
+ h.rows = [
+ {
+ id: 'session',
+ source: 'cindy-make',
+ status: 'active',
+ remoteHostId: null,
+ title: 'Feature',
+ createdAt: 1,
+ updatedAt: 2,
+ workingDir: path.join(
+ os.tmpdir(),
+ 'history-runtime-profile',
+ 'cindy-make',
+ 'worktrees',
+ 'aaaa',
+ ),
+ },
+ ];
+ h.cards = [
+ {
+ id: 1,
+ sessionId: 'session',
+ role: 'assistant',
+ clientId: 'complete',
+ content: '',
+ createdAt: 3,
+ agentMeta: JSON.stringify({
+ cindyMakeCompletion: { reportedAt: 3, commit: 'f'.repeat(40), tree: 'e'.repeat(40) },
+ }),
+ },
+ ];
+});
+describe('history Main admission and owner boundary', () => {
+ it('settles a failed background build with its known cause and releases controls for retry', async () => {
+ let buildState: any;
+ store.readBuild.mockImplementation(() => buildState);
+ store.saveBuild.mockImplementation((value) => {
+ buildState = value;
+ });
+ let fail!: (error: Error) => void;
+ h.build.mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ fail = reject;
+ }),
+ );
+ expect(await generateHistoryPersonalVersion()).toMatchObject({ busy: true, canBuild: false });
+ await vi.waitFor(() => expect(fail).toBeTypeOf('function'));
+ fail(Object.assign(new Error('private test output'), { code: 'checksFailed' }));
+ await vi.waitFor(async () => {
+ expect(await getCindyMakeHistory()).toMatchObject({
+ busy: false,
+ canBuild: true,
+ build: { status: 'failed', error: 'checksFailed' },
+ });
+ });
+ expect(JSON.stringify(buildState)).not.toContain('private test output');
+ });
+ it('marks a running build as stopping and aborts only the matching build identity', async () => {
+ let buildState: any;
+ store.readBuild.mockImplementation(() => buildState);
+ store.saveBuild.mockImplementation((value) => {
+ buildState = value;
+ });
+ let signal!: AbortSignal;
+ h.build.mockImplementationOnce(
+ (...args: any[]) =>
+ new Promise((_resolve, reject) => {
+ signal = args[4];
+ signal.addEventListener(
+ 'abort',
+ () => reject(Object.assign(new Error('cancelled'), { code: 'cancelled' })),
+ { once: true },
+ );
+ }),
+ );
+ await expect(generateHistoryPersonalVersion()).resolves.toMatchObject({ busy: true });
+ await vi.waitFor(() => expect(buildState?.buildId).toBeTypeOf('string'));
+ const buildId = buildState.buildId;
+ await expect(cancelHistoryPersonalVersion('other-build')).resolves.toMatchObject({
+ busy: true,
+ });
+ expect(signal.aborted).toBe(false);
+ const state = await cancelHistoryPersonalVersion(buildId);
+ expect(signal.aborted).toBe(true);
+ expect(state.build).toMatchObject({ buildId, stopping: true });
+ await vi.waitFor(() =>
+ expect(buildState).toMatchObject({ status: 'failed', error: 'cancelled' }),
+ );
+ });
+ it('keeps an old generated record unverified when its integration delta cannot be reconstructed', async () => {
+ const meta = JSON.parse(h.cards[0].agentMeta);
+ meta.cindyMakeCompletion.personal = {
+ status: 'ready',
+ commit: 'a'.repeat(40),
+ tree: 'b'.repeat(40),
+ };
+ h.cards[0].agentMeta = JSON.stringify(meta);
+ expect((await getCindyMakeHistory('aaaa')).items[0]).toMatchObject({
+ integration: 'unknown',
+ actions: ['open', 'end'],
+ });
+ await expect(actCindyMakeHistory('aaaa', 'revert')).rejects.toThrow('unavailable');
+ expect(h.merge).not.toHaveBeenCalled();
+ });
+ it('opens only the saved verified installer and rejects an owner transition before file access', async () => {
+ await expect(openHistoryPersonalBuild()).rejects.toThrow('unavailable');
+ expect(h.artifactPath).not.toHaveBeenCalled();
+ const build = {
+ status: 'ready',
+ buildId: 'saved-build',
+ artifactDirectory: 'saved-build-output',
+ artifactName: 'Cindy.exe',
+ commit: 'a'.repeat(40),
+ sha256: 'b'.repeat(64),
+ };
+ store.readBuild.mockReturnValue(build);
+ await openHistoryPersonalBuild();
+ expect(h.artifactPath).toHaveBeenCalledWith(
+ path.join(os.tmpdir(), 'history-runtime-profile'),
+ 'saved-build',
+ build,
+ );
+ expect(h.showItem).toHaveBeenCalledWith(path.join(os.tmpdir(), 'history-installer.exe'));
+ h.current = false;
+ await expect(openHistoryPersonalBuild()).rejects.toThrow('unavailable');
+ expect(h.artifactPath).toHaveBeenCalledOnce();
+ expect(h.showItem).toHaveBeenCalledOnce();
+ });
+ it('shows writes only after selecting and verifying the record, and rejects stale completion files', async () => {
+ expect((await getCindyMakeHistory()).items[0].actions).toEqual(['open']);
+ expect((await getCindyMakeHistory('aaaa')).items[0].actions).toContain('integrate');
+ h.verify.mockRejectedValue(Object.assign(new Error('changed'), { code: 'changed' }));
+ await expect(actCindyMakeHistory('aaaa', 'integrate')).rejects.toThrow('unavailable');
+ expect(h.merge).not.toHaveBeenCalled();
+ });
+ it('retains ended history and undo but does not pretend a missing source can still be changed', async () => {
+ await getCindyMakeHistory();
+ const record = h.records.get('aaaa')!;
+ record.receipts.push(receipt);
+ record.endedAt = 5;
+ h.rows[0].status = 'archived';
+ expect((await getCindyMakeHistory('aaaa')).items[0]).toMatchObject({
+ lifecycle: 'ended',
+ integration: 'unknown',
+ actions: ['open', 'build'],
+ });
+ h.exists = false;
+ expect((await getCindyMakeHistory('aaaa')).items[0]).toMatchObject({
+ integration: 'unknown',
+ actions: ['open'],
+ });
+ });
+ it('explains an empty action area when the ended task is no longer available', async () => {
+ h.rows[0].status = 'deleted';
+ h.exists = false;
+ const item = (await getCindyMakeHistory('aaaa')).items[0];
+ expect(item.actions).toEqual([]);
+ expect(item.actionReason).toBe('sessionUnavailable');
+ });
+ it('keeps a failed personal build actionable after the task itself ended', async () => {
+ h.cards[0].agentMeta = JSON.stringify({
+ cindyMakeCompletion: {
+ reportedAt: 3,
+ commit: 'f'.repeat(40),
+ tree: 'e'.repeat(40),
+ personal: { status: 'failed', error: 'checksFailed' },
+ },
+ });
+ await getCindyMakeHistory();
+ const record = h.records.get('aaaa')!;
+ record.endedAt = 5;
+ h.rows[0].status = 'deleted';
+ const item = (await getCindyMakeHistory('aaaa')).items[0];
+ expect(item.actions).toContain('build');
+ expect(item.actions).not.toEqual([]);
+ });
+ it('does not offer mutation controls while the task is running or after a new user message', async () => {
+ h.running = true;
+ expect((await getCindyMakeHistory('aaaa')).items[0].actions).toEqual(['open']);
+ h.running = false;
+ h.cards.push({
+ id: 2,
+ sessionId: 'session',
+ role: 'user',
+ clientId: 'next',
+ content: '',
+ agentMeta: null,
+ createdAt: 4,
+ });
+ expect((await getCindyMakeHistory('aaaa')).items[0].actions).not.toContain('integrate');
+ await expect(actCindyMakeHistory('aaaa', 'integrate')).rejects.toThrow();
+ });
+ it('never writes captured task data into an owner that changed while the read was pending', async () => {
+ h.current = false;
+ await expect(getCindyMakeHistory()).rejects.toThrow('unavailable');
+ expect(h.saved).not.toHaveBeenCalled();
+ });
+ it('uses the selected record’s verified snapshot, not caller-supplied Git inputs', async () => {
+ await actCindyMakeHistory('aaaa', 'integrate');
+ expect(h.merge).toHaveBeenCalledWith(
+ expect.objectContaining({
+ runId: 'aaaa',
+ taskSessionId: 'session',
+ taskTree: 'e'.repeat(40),
+ mergeCommit: 'f'.repeat(40),
+ }),
+ expect.any(Object),
+ );
+ await expect(actCindyMakeHistory('../source', 'revert')).rejects.toThrow('Invalid');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/historyStore.test.ts b/apps/desktop/src/main/cindy-make/__tests__/historyStore.test.ts
new file mode 100644
index 0000000000..80dc75ec54
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/historyStore.test.ts
@@ -0,0 +1,118 @@
+import os from 'node:os';
+import path from 'node:path';
+import { mkdtempSync, rmSync, writeFileSync, renameSync } from 'node:fs';
+import { afterEach, expect, it } from 'vitest';
+import { CindyMakeHistoryStore } from '../historyStore';
+
+const dirs: string[] = [];
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+it('preserves real checking stages and known failures while filtering private or unknown values', () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'make-build-progress-'));
+ dirs.push(dir);
+ const store = new CindyMakeHistoryStore(dir);
+ for (const checkStep of ['dependencies', 'tests', 'types'] as const) {
+ store.saveBuild({ status: 'checking', checkStep });
+ expect(store.readBuild()).toEqual({ status: 'checking', checkStep });
+ }
+ for (const error of ['checksFailed', 'missingShell', 'baselineChanged', 'interrupted'] as const) {
+ store.saveBuild({ status: 'failed', error });
+ expect(store.readBuild()).toEqual({ status: 'failed', error });
+ }
+ for (const status of ['checking', 'failed']) {
+ writeFileSync(
+ path.join(dir, 'build-state.json'),
+ JSON.stringify({ status, checkStep: 'private process output', error: 'private error' }),
+ );
+ expect(store.readBuild()).toEqual(
+ status === 'checking' ? { status } : { status, error: 'buildFailed' },
+ );
+ }
+ store.saveBuild({ status: 'checking' });
+ expect(store.readBuild()).toEqual({ status: 'checking' });
+});
+it('keeps ended history, deduplicates operation receipts, and does not confuse build state with a task record', () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'make-history-store-'));
+ dirs.push(dir);
+ const store = new CindyMakeHistoryStore(dir);
+ const record = {
+ runId: 'aaaa',
+ sessionId: 'session',
+ title: 'Feature',
+ request: 'Change theme',
+ createdAt: 1,
+ updatedAt: 1,
+ };
+ store.seed(record);
+ const receipt = {
+ id: 'operation',
+ action: 'integrate' as const,
+ at: 3,
+ baselineCommit: 'a'.repeat(40),
+ commit: 'b'.repeat(40),
+ beforeTree: 'c'.repeat(40),
+ tree: 'd'.repeat(40),
+ taskTree: 'e'.repeat(40),
+ };
+ store.receipt('aaaa', receipt);
+ store.receipt('aaaa', receipt);
+ store.completion('aaaa', {
+ id: 'turn',
+ reportedAt: 2,
+ commit: 'f'.repeat(40),
+ tree: 'e'.repeat(40),
+ });
+ store.end('aaaa', 4);
+ store.seed({ ...record, endedAt: 99 });
+ writeFileSync(path.join(dir, 'build-state.json'), JSON.stringify({ status: 'ready' }));
+ store.saveBuild({ status: 'ready', commit: 'b'.repeat(40), generatedAt: 4 });
+ expect(store.readBuild()).toEqual({ status: 'ready', commit: 'b'.repeat(40), generatedAt: 4 });
+ writeFileSync(
+ path.join(dir, 'build-state.json'),
+ JSON.stringify({
+ status: 'ready',
+ commit: 'b'.repeat(40),
+ unrelatedPrivateField: 'must stay on disk',
+ }),
+ );
+ expect(store.readBuild()).toEqual({ status: 'ready', commit: 'b'.repeat(40) });
+ const restored = new CindyMakeHistoryStore(dir).list();
+ expect(restored).toHaveLength(1);
+ const file = path.join(dir, 'records', 'aaaa.json');
+ renameSync(file, file + '.bak');
+ expect(new CindyMakeHistoryStore(dir).list()).toEqual(restored);
+ expect(restored[0]).toMatchObject({
+ endedAt: 4,
+ updatedAt: 4,
+ receipts: [receipt],
+ completions: [{ id: 'turn' }],
+ });
+});
+it('keeps owners separate and refuses corrupt existing history instead of overwriting it', () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'make-history-owners-'));
+ dirs.push(dir);
+ const first = new CindyMakeHistoryStore(path.join(dir, 'first'));
+ const second = new CindyMakeHistoryStore(path.join(dir, 'second'));
+ first.seed({
+ runId: 'aaaa',
+ sessionId: 'session',
+ title: 'Private',
+ request: 'request',
+ createdAt: 1,
+ updatedAt: 1,
+ });
+ expect(second.list()).toEqual([]);
+ writeFileSync(path.join(dir, 'first', 'records', 'aaaa.json'), '{bad');
+ expect(() => first.list()).toThrow();
+ expect(() =>
+ first.seed({
+ runId: 'aaaa',
+ sessionId: 'session',
+ title: 'Overwrite',
+ request: '',
+ createdAt: 1,
+ updatedAt: 1,
+ }),
+ ).toThrow();
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/latestSourceVersion.test.ts b/apps/desktop/src/main/cindy-make/__tests__/latestSourceVersion.test.ts
new file mode 100644
index 0000000000..c2a9cb8bf7
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/latestSourceVersion.test.ts
@@ -0,0 +1,206 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { MakeSourceStatus } from '../../../shared/cindyMakeDoctor.js';
+import { createLatestSourceVersionReader } from '../latestSourceVersion.js';
+
+const local = 'a'.repeat(40);
+const remote = 'b'.repeat(40);
+const source: MakeSourceStatus = {
+ status: 'ready',
+ path: 'managed-source',
+ mainCommit: local,
+ mainRemoteCommit: 'c'.repeat(40),
+ mainAhead: 50,
+ mainBehind: 60,
+};
+const json = (value: unknown) => new Response(JSON.stringify(value));
+const release = (tag_name: string, prerelease = false, draft = false) => ({
+ tag_name,
+ prerelease,
+ draft,
+});
+const comparison = { base_commit: { sha: local }, ahead_by: 7, behind_by: 2 };
+
+afterEach(() => vi.useRealTimers());
+
+describe('latest Cindy source version', () => {
+ it('queries live main and reports the local main difference in the correct direction', async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(json({ sha: remote }))
+ .mockResolvedValueOnce(json(comparison));
+ const result = await createLatestSourceVersionReader(fetch)(source, 'dev');
+ expect(result.latestVersion).toEqual({
+ status: 'ready',
+ channel: 'dev',
+ ref: 'main',
+ commit: remote,
+ ahead: 2,
+ behind: 7,
+ });
+ expect(fetch.mock.calls.map(([url]) => url)).toEqual([
+ 'https://api.github.com/repos/makecindy/cindy/commits/main',
+ `https://api.github.com/repos/makecindy/cindy/compare/${local}...${remote}?per_page=1`,
+ ]);
+ expect(fetch.mock.calls[0][1]).toMatchObject({ credentials: 'omit', redirect: 'error' });
+ expect(result.mainRemoteCommit).toBe(source.mainRemoteCommit);
+ });
+
+ it('resolves the newest beta release tag, skipping stable, other prereleases and drafts', async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(
+ json([
+ release('v2.0.0'),
+ release('v2.1.0-rc', true),
+ release('v2.1.0-beta', true, true),
+ release('v2.0.0-beta.2', true),
+ release('v1.9.0-beta', true),
+ ]),
+ )
+ .mockResolvedValueOnce(json({ sha: remote }))
+ .mockResolvedValueOnce(json(comparison));
+ const result = await createLatestSourceVersionReader(fetch)(source, 'beta');
+ expect(result.latestVersion).toMatchObject({
+ status: 'ready',
+ ref: 'v2.0.0-beta.2',
+ commit: remote,
+ channel: 'beta',
+ });
+ expect(fetch.mock.calls[1][0]).toBe(
+ 'https://api.github.com/repos/makecindy/cindy/commits/v2.0.0-beta.2',
+ );
+ });
+
+ it('uses the latest stable release and resolves its tag, not target_commitish', async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(json({ ...release('v2.0.0'), target_commitish: 'main' }))
+ .mockResolvedValueOnce(json({ sha: local }));
+ const result = await createLatestSourceVersionReader(fetch)(source, 'release');
+ expect(result.latestVersion).toEqual({
+ status: 'ready',
+ channel: 'release',
+ ref: 'v2.0.0',
+ commit: local,
+ ahead: 0,
+ behind: 0,
+ });
+ expect(fetch.mock.calls.map(([url]) => url)).toEqual([
+ 'https://api.github.com/repos/makecindy/cindy/releases/latest',
+ 'https://api.github.com/repos/makecindy/cindy/commits/v2.0.0',
+ ]);
+ });
+
+ it('checks another beta page without switching channels', async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(json(Array.from({ length: 100 }, () => release('v2.0.0'))))
+ .mockResolvedValueOnce(json([release('v1.9.0-beta', true)]))
+ .mockResolvedValueOnce(json({ sha: local }));
+ const result = await createLatestSourceVersionReader(fetch)(source, 'beta');
+ expect(result.latestVersion).toMatchObject({ ref: 'v1.9.0-beta' });
+ expect(fetch.mock.calls[1][0]).toContain('page=2');
+ });
+
+ it.each(['beta', 'release'] as const)(
+ 'never substitutes another channel for %s',
+ async (channel) => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValue(
+ json(channel === 'beta' ? [release('v2.0.0')] : release('v2.0.0-beta', true)),
+ );
+ expect((await createLatestSourceVersionReader(fetch)(source, channel)).latestVersion).toEqual(
+ { status: 'unavailable', channel },
+ );
+ expect(fetch).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it.each([
+ new Response('', { status: 404 }),
+ json({ ...comparison, base_commit: { sha: remote } }),
+ json({ ...comparison, ahead_by: -1 }),
+ ])('keeps the latest hash when comparison is unavailable or invalid', async (response) => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(json({ sha: remote }))
+ .mockResolvedValueOnce(response);
+ expect((await createLatestSourceVersionReader(fetch)(source, 'dev')).latestVersion).toEqual({
+ status: 'ready',
+ channel: 'dev',
+ ref: 'main',
+ commit: remote,
+ });
+ });
+
+ it('does not substitute cached origin/main or the personal commit for missing local main', async () => {
+ const fetch = vi.fn().mockResolvedValue(json({ sha: remote }));
+ const result = await createLatestSourceVersionReader(fetch)(
+ { ...source, mainCommit: undefined, commit: local },
+ 'dev',
+ );
+ expect(result.latestVersion).toEqual({
+ status: 'ready',
+ channel: 'dev',
+ ref: 'main',
+ commit: remote,
+ });
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([new Response('', { status: 429 }), json({ sha: 'main' })])(
+ 'reports failed or invalid lookups without using stale refs',
+ async (response) => {
+ const fetch = vi.fn().mockResolvedValue(response);
+ expect((await createLatestSourceVersionReader(fetch)(source, 'dev')).latestVersion).toEqual({
+ status: 'unavailable',
+ channel: 'dev',
+ });
+ },
+ );
+
+ it('settles a stalled fetch after the time limit', async () => {
+ vi.useFakeTimers();
+ const fetch = vi.fn(() => new Promise<Response>(() => {}));
+ const result = createLatestSourceVersionReader(fetch)(source, 'dev');
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect((await result).latestVersion).toEqual({ status: 'unavailable', channel: 'dev' });
+ });
+
+ it('retries a failed lookup when Settings reopens', async () => {
+ const fetch = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce(json({ sha: local }));
+ const read = createLatestSourceVersionReader(fetch);
+ expect((await read(source, 'dev')).latestVersion?.status).toBe('unavailable');
+ expect((await read(source, 'dev')).latestVersion?.status).toBe('ready');
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('shares in-flight lookups, expires cached results, and recomputes for a changed main', async () => {
+ vi.useFakeTimers();
+ const fetch = vi.fn(async (url: string) =>
+ json(url.includes('/compare/') ? comparison : { sha: local }),
+ );
+ const read = createLatestSourceVersionReader(fetch);
+ await Promise.all([read(source, 'dev'), read(source, 'dev')]);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(60_001);
+ await read(source, 'dev');
+ expect(fetch).toHaveBeenCalledTimes(2);
+ await read({ ...source, mainCommit: remote }, 'dev');
+ expect(fetch).toHaveBeenCalledTimes(4);
+ });
+
+ it.each(['preparing', 'missing', 'failed'] as const)(
+ 'does not hold up %s source state with a remote query',
+ async (status) => {
+ const fetch = vi.fn();
+ const input = { ...source, status };
+ expect(await createLatestSourceVersionReader(fetch)(input, 'dev')).toBe(input);
+ expect(fetch).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/manager.test.ts b/apps/desktop/src/main/cindy-make/__tests__/manager.test.ts
index fc9e2e61a9..3df95a48bf 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/manager.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/manager.test.ts
@@ -14,6 +14,25 @@ const report = (
});
describe('CindyMakeManager', () => {
+ it('hides a merge task identity after its account boundary changes', () => {
+ const manager = new CindyMakeManager();
+ let current = true;
+ manager.setUpstreamMerge({ id: 'merge', ref: 'main', upstreamCommit: 'a'.repeat(40), status: 'conflict', sessionId: 'private-task', hasWorkspace: true }, () => current);
+ expect(manager.getState().upstreamMerge?.sessionId).toBe('private-task');
+ current = false;
+ expect(manager.getState().upstreamMerge).toMatchObject({ sessionId: undefined, ownedByAnotherAccount: true, hasWorkspace: true });
+ });
+ it('blocks source preparation and reset while an unresolved merge workspace is retained', async () => {
+ const manager = new CindyMakeManager();
+ manager.setUpstreamMerge({ id: 'merge', ref: 'main', upstreamCommit: 'a'.repeat(40), status: 'failed', hasWorkspace: true });
+ for (const clearOnly of [false, true]) {
+ const run = vi.fn();
+ await expect(manager.prepareSource({ root: '/managed', clearOnly, signal: new AbortController().signal,
+ cancelled: vi.fn(), onProgress: vi.fn(), toStatus: vi.fn(), run,
+ })).rejects.toMatchObject({ code: 'busy' });
+ expect(run).not.toHaveBeenCalled();
+ }
+ });
it('deduplicates one operation, replays progress, and keeps state after completion', async () => {
const manager = new CindyMakeManager();
const firstListener = vi.fn();
diff --git a/apps/desktop/src/main/cindy-make/__tests__/personalBuild.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/personalBuild.git-integration.test.ts
new file mode 100644
index 0000000000..587dcb2bc4
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/personalBuild.git-integration.test.ts
@@ -0,0 +1,415 @@
+import { createHash, randomBytes } from 'node:crypto';
+import { access, mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { expect, it, vi } from 'vitest';
+import {
+ buildCindyPersonal,
+ personalArtifactPath,
+ type runPersonalPackageCommand,
+} from '../personalBuild';
+import { makeSourceCheckoutPath, makeTaskBranch, makeTaskWorktreePath } from '../sourcePaths';
+import { manageCindyMakeWorkspace } from '../taskCleanup';
+import { collectCindyMakeChanges } from '../completion';
+import { createCindyMakeWorktree } from '../taskWorkspace';
+import { runSourceGit } from '../sourceGit';
+import type { runSourcePnpm } from '../sourcePnpm';
+
+async function fixture() {
+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-personal-git-'));
+ const source = makeSourceCheckoutPath(userData);
+ const workingDir = makeTaskWorktreePath(userData, 'run');
+ const signal = AbortSignal.timeout(90_000);
+ const env = {
+ PATH: process.env.PATH,
+ SystemRoot: process.env.SystemRoot,
+ GIT_CONFIG_GLOBAL: path.join(userData, 'empty.gitconfig'),
+ GIT_CONFIG_NOSYSTEM: '1',
+ };
+ const git = (args: string[], cwd = source, indexFile?: string) =>
+ runSourceGit(
+ { ...env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args,
+ cwd,
+ signal,
+ );
+ try {
+ await writeFile(env.GIT_CONFIG_GLOBAL, '');
+ await mkdir(path.join(source, 'scripts'), { recursive: true });
+ await git(['init', '--initial-branch=cindy-personal']);
+ await git(['config', 'user.name', 'Test']);
+ await git(['config', 'user.email', '[email protected]']);
+ await git(['config', 'commit.gpgSign', 'false']);
+ await writeFile(path.join(source, 'scripts/desktop-restart-runner.mjs'), '// fixture');
+ await writeFile(path.join(source, 'shared.txt'), 'base');
+ await writeFile(path.join(source, '.gitignore'), 'apps/desktop/release/\n');
+ await git(['add', '.']);
+ await git(['commit', '-s', '-m', 'base']);
+ await createCindyMakeWorktree(userData, 'run', signal, { processEnvironment: env });
+ await writeFile(path.join(workingDir, 'feature.txt'), 'task change');
+
+ await writeFile(path.join(source, 'personal.txt'), 'existing personal change');
+
+ const facts = await collectCindyMakeChanges(git, userData, workingDir);
+ const task = {
+ userData,
+ workingDir,
+ runId: 'run',
+ completionId: 'completion',
+ commit: facts.commit!,
+ tree: facts.tree,
+ };
+ const history = await git(['rev-list', '--all', '--count']);
+ const pnpm = vi.fn<typeof runSourcePnpm>(async (_env, _args, cwd) => {
+ expect(cwd).toBe(source);
+ expect(await git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd)).toBe('cindy-personal');
+ // The task commit is merged into personal before the first build command.
+ expect(await readFile(path.join(cwd, 'feature.txt'), 'utf8')).toBe('task change');
+ expect(await readFile(path.join(cwd, 'personal.txt'), 'utf8')).toBe(
+ 'existing personal change',
+ );
+ });
+ const pack = async (_node: string, args: string[], cwd: string) => {
+ expect(cwd).toBe(source);
+ expect(await git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd)).toBe('cindy-personal');
+ expect(args).not.toContain('--skip-smoke');
+ expect(args).not.toContain('--version');
+ const candidate = await git(['rev-parse', 'HEAD'], cwd);
+ expect(candidate).toBe(await git(['rev-parse', 'HEAD']));
+ const artifacts = path.join(
+ cwd,
+ 'apps/desktop/release/artifacts/global/unversioned',
+ process.platform + '-' + process.arch,
+ );
+ await mkdir(artifacts, { recursive: true });
+ await writeFile(path.join(artifacts, 'Cindy.exe'), 'installer');
+ await writeFile(
+ path.join(artifacts, 'build-info.json'),
+ JSON.stringify({
+ product: 'cindy-desktop',
+ versionless: true,
+ version: null,
+ commitSha: candidate,
+ region: 'global',
+ platform: process.platform,
+ arch: process.arch,
+ files: [
+ {
+ role: 'installer',
+ name: 'Cindy.exe',
+ sha256: createHash('sha256').update('installer').digest('hex'),
+ },
+ ],
+ }),
+ );
+ };
+ const packageCommand = vi.fn<typeof runPersonalPackageCommand>(pack);
+ const run = (buildSignal = signal) =>
+ buildCindyPersonal(
+ task,
+ process.execPath,
+ env,
+ 'global',
+ buildSignal,
+ async () => {},
+ () => {},
+ async (operation) => operation(),
+ { pnpm, packageCommand },
+ );
+ return {
+ userData,
+ source,
+ workingDir,
+ task,
+ git,
+ pnpm,
+ pack,
+ packageCommand,
+ run,
+ history,
+ env,
+ signal,
+ };
+ } catch (error) {
+ await rm(userData, { recursive: true, force: true });
+ throw error;
+ }
+}
+
+it('merges task commits before packaging in personal, preserving integration on failure and avoiding duplicate commits on retry', async () => {
+ const h = await fixture();
+ try {
+ const baseline = await h.git(['rev-parse', 'HEAD']);
+ h.pnpm.mockRejectedValueOnce(new Error('checks failed'));
+ await expect(h.run()).rejects.toMatchObject({ code: 'checksFailed' });
+ const integratedCommit = await h.git(['rev-parse', 'HEAD']);
+ expect(integratedCommit).not.toBe(baseline);
+ expect(await h.git(['merge-base', '--is-ancestor', h.task.commit, integratedCommit])).toBe('');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('task change');
+ expect(await readFile(path.join(h.workingDir, 'feature.txt'), 'utf8')).toBe('task change');
+ expect(await h.git(['rev-parse', 'refs/cindy-make/tasks/run/integrated'])).toBe(h.task.tree);
+ h.packageCommand.mockRejectedValueOnce(new Error('packaging failed'));
+ await expect(h.run()).rejects.toThrow('packaging failed');
+ expect(await h.git(['rev-parse', 'HEAD'])).toBe(integratedCommit);
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('task change');
+ h.packageCommand.mockImplementationOnce(async (...args) => {
+ await h.pack(args[0], args[1], args[2]);
+ await writeFile(path.join(h.source, 'concurrent.txt'), 'another completed personal change');
+ });
+ await expect(h.run()).rejects.toMatchObject({ code: 'baselineChanged' });
+ expect(await readFile(path.join(h.source, 'concurrent.txt'), 'utf8')).toBe(
+ 'another completed personal change',
+ );
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('task change');
+ const artifact = await h.run();
+ expect(await h.git(['rev-parse', 'HEAD'])).toBe(artifact.commit);
+ const adoptedHistory = await h.git(['rev-list', '--all', '--count']);
+ expect(Number(adoptedHistory)).toBeGreaterThan(Number(h.history));
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ expect(await h.git(['status', '--porcelain'], h.workingDir)).toBe('');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('task change');
+ expect(
+ await readFile(await personalArtifactPath(h.userData, 'completion', artifact), 'utf8'),
+ ).toBe('installer');
+ expect(await h.git(['rev-parse', 'HEAD'], h.workingDir)).toBe(h.task.commit);
+ expect(await readFile(path.join(h.workingDir, 'feature.txt'), 'utf8')).toBe('task change');
+ const worktrees = await h.git(['worktree', 'list', '--porcelain']);
+ expect(worktrees.match(/^worktree /gm)).toHaveLength(2);
+ expect(worktrees).not.toContain('cindy-make-merge-');
+ await expect(
+ manageCindyMakeWorkspace(h.userData, 'run', 'inspect', h.env, h.signal),
+ ).resolves.toBe(true);
+ await expect(
+ manageCindyMakeWorkspace(h.userData, 'run', 'archive', h.env, h.signal),
+ ).resolves.toBe(false);
+ await expect(access(h.workingDir)).resolves.toBeUndefined();
+ // A second generation is idempotent, and future tasks inherit committed personal features.
+ await h.run();
+ // A crash after applying files but before writing the receipt is also recoverable.
+ await h.git(['update-ref', '-d', 'refs/cindy-make/tasks/run/integrated']);
+ await h.run();
+ const next = await createCindyMakeWorktree(h.userData, 'next', h.signal, {
+ processEnvironment: h.env,
+ });
+ expect(await readFile(path.join(next.path, 'feature.txt'), 'utf8')).toBe('task change');
+ expect(await readFile(path.join(next.path, 'personal.txt'), 'utf8')).toBe(
+ 'existing personal change',
+ );
+ expect(await h.git(['rev-list', '--all', '--count'])).toBe(adoptedHistory);
+ // Continuing the same task integrates only its new file changes.
+ await writeFile(path.join(h.workingDir, 'feature.txt'), 'task change continued');
+ await expect(
+ manageCindyMakeWorkspace(h.userData, 'run', 'inspect', h.env, h.signal),
+ ).resolves.toBe(false);
+ Object.assign(h.task, await collectCindyMakeChanges(h.git, h.userData, h.workingDir));
+ h.pnpm.mockImplementation(async () => {});
+ await h.run();
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ 'task change continued',
+ );
+ await expect(
+ manageCindyMakeWorkspace(h.userData, 'run', 'finish', h.env, h.signal),
+ ).resolves.toBe(true);
+ await expect(access(h.workingDir)).rejects.toThrow();
+ expect(await readFile(path.join(h.source, 'concurrent.txt'), 'utf8')).toBe(
+ 'another completed personal change',
+ );
+ expect(await h.git(['merge-base', '--is-ancestor', h.task.commit, 'cindy-personal'])).toBe('');
+ h.task.workingDir = next.path;
+ h.task.runId = 'next';
+ await writeFile(path.join(next.path, 'second.txt'), 'next task feature');
+ Object.assign(h.task, await collectCindyMakeChanges(h.git, h.userData, next.path));
+ await h.run();
+ expect(await readFile(path.join(h.source, 'second.txt'), 'utf8')).toBe('next task feature');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ 'task change continued',
+ );
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ expect(await h.git(['merge-base', '--is-ancestor', h.task.commit, 'cindy-personal'])).toBe('');
+ } finally {
+ await rm(h.userData, { recursive: true, force: true });
+ }
+}, 90_000);
+
+it('converts a retained file-only completion into committed personal history and keeps retries idempotent', async () => {
+ const h = await fixture();
+ try {
+ // Recreate an old completion: the recorded HEAD precedes the retained file snapshot.
+ await h.git(['reset', '--mixed', 'HEAD^'], h.workingDir);
+ h.task.commit = await h.git(['rev-parse', 'HEAD'], h.workingDir);
+ expect(await h.git(['status', '--porcelain'], h.workingDir)).toContain('feature.txt');
+ const artifact = await h.run();
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ expect(await h.git(['show', 'HEAD:feature.txt'])).toBe('task change');
+ expect(await h.git(['show', 'HEAD:personal.txt'])).toBe('existing personal change');
+ expect(await h.git(['rev-parse', 'HEAD'])).toBe(artifact.commit);
+ const repeated = await h.run();
+ expect(repeated.commit).toBe(artifact.commit);
+ expect(repeated.tree).toBe(artifact.tree);
+ expect(await readFile(path.join(h.workingDir, 'feature.txt'), 'utf8')).toBe('task change');
+ } finally {
+ await rm(h.userData, { recursive: true, force: true });
+ }
+}, 90_000);
+
+it('rejects files edited after the completion snapshot before packaging or integration', async () => {
+ const h = await fixture();
+ try {
+ await writeFile(path.join(h.workingDir, 'feature.txt'), 'later edit');
+ await expect(h.run()).rejects.toMatchObject({ code: 'changed' });
+ expect(h.packageCommand).not.toHaveBeenCalled();
+ await expect(access(path.join(h.source, 'feature.txt'))).rejects.toThrow();
+ expect(await readFile(path.join(h.workingDir, 'feature.txt'), 'utf8')).toBe('later edit');
+ } finally {
+ await rm(h.userData, { recursive: true, force: true });
+ }
+}, 90_000);
+
+it('keeps integrated source and task files on cancellation, then retries without losing later edits', async () => {
+ const h = await fixture();
+ try {
+ const abort = new AbortController();
+ h.pnpm.mockImplementationOnce(async (_env, _args, cwd) => {
+ expect(cwd).toBe(h.source);
+ expect(await readFile(path.join(cwd, 'feature.txt'), 'utf8')).toBe('task change');
+ abort.abort();
+ });
+ await expect(h.run(AbortSignal.any([h.signal, abort.signal]))).rejects.toMatchObject({
+ code: 'interrupted',
+ });
+ expect(h.packageCommand).not.toHaveBeenCalled();
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('task change');
+ expect(await readFile(path.join(h.workingDir, 'feature.txt'), 'utf8')).toBe('task change');
+ expect(await h.git(['rev-parse', 'refs/cindy-make/tasks/run/integrated'])).toBe(h.task.tree);
+ await writeFile(path.join(h.workingDir, 'continued.txt'), 'continued after cancellation');
+ Object.assign(h.task, await collectCindyMakeChanges(h.git, h.userData, h.workingDir));
+ await h.run();
+ expect(await readFile(path.join(h.source, 'continued.txt'), 'utf8')).toBe(
+ 'continued after cancellation',
+ );
+ expect(await h.git(['diff', '--cached'])).toBe('');
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ expect(await h.git(['merge-base', '--is-ancestor', h.task.commit, 'cindy-personal'])).toBe('');
+ } finally {
+ await rm(h.userData, { recursive: true, force: true });
+ }
+}, 90_000);
+
+it('integrates large binary content, deletions, and renamed files without truncating patches', async () => {
+ const h = await fixture();
+ try {
+ const binary = randomBytes(90_000);
+ await writeFile(path.join(h.workingDir, 'asset.bin'), binary);
+ await rename(
+ path.join(h.workingDir, 'shared.txt'),
+ path.join(h.workingDir, 'renamed file.txt'),
+ );
+ const facts = await collectCindyMakeChanges(h.git, h.userData, h.workingDir);
+ expect(facts.changedFiles).toBe(4);
+ Object.assign(h.task, facts);
+ await h.run();
+ expect(await readFile(path.join(h.source, 'asset.bin'))).toEqual(binary);
+ expect(await readFile(path.join(h.source, 'renamed file.txt'), 'utf8')).toBe('base');
+ await expect(access(path.join(h.source, 'shared.txt'))).rejects.toThrow();
+ expect(await h.git(['merge-base', '--is-ancestor', facts.commit!, 'cindy-personal'])).toBe('');
+ expect(await h.git(['diff', '--cached'])).toBe('');
+ } finally {
+ await rm(h.userData, { recursive: true, force: true });
+ }
+}, 90_000);
+
+it('commits completed task files locally but refuses to commit on main', async () => {
+ const h = await fixture();
+ try {
+ await writeFile(path.join(h.workingDir, 'feature.txt'), 'staged-only revision');
+ await h.git(['add', 'feature.txt'], h.workingDir);
+ await writeFile(path.join(h.workingDir, 'feature.txt'), 'unstaged follow-up');
+ const facts = await collectCindyMakeChanges(h.git, h.userData, h.workingDir);
+ expect(facts.tree).toMatch(/^[0-9a-f]{40}$/);
+ expect(await h.git(['status', '--porcelain'], h.workingDir)).toBe('');
+ expect(await h.git(['show', 'HEAD:feature.txt'], h.workingDir)).toBe('unstaged follow-up');
+ const backupRefs = (
+ await h.git(['for-each-ref', '--format=%(refname)', 'refs/cindy-make/history-backups/'])
+ ).split('\n');
+ const stagedCopies = await Promise.all(
+ backupRefs
+ .filter((ref) => ref.endsWith('/index'))
+ .map((ref) => h.git(['show', ref + ':feature.txt']).catch(() => '')),
+ );
+ expect(stagedCopies).toContain('staged-only revision');
+ expect(await h.git(['log', '-1', '--format=%B'], h.workingDir)).toContain(
+ 'Signed-off-by: Cindy Make <[email protected]>',
+ );
+ expect(await collectCindyMakeChanges(h.git, h.userData, h.workingDir)).toEqual(facts);
+ await h.git(['checkout', '-b', 'main'], h.workingDir);
+ const main = await h.git(['rev-parse', 'main']);
+ const before = await h.git(['rev-list', '--all', '--count']);
+ await expect(collectCindyMakeChanges(h.git, h.userData, h.workingDir)).rejects.toThrow(
+ 'Unexpected',
+ );
+ expect(await h.git(['rev-parse', 'main'])).toBe(main);
+ expect(await h.git(['rev-list', '--all', '--count'])).toBe(before);
+ expect(await readFile(path.join(h.workingDir, 'feature.txt'), 'utf8')).toBe(
+ 'unstaged follow-up',
+ );
+ } finally {
+ await rm(h.userData, { recursive: true, force: true });
+ }
+}, 90_000);
+
+it('resumes interrupted task inheritance without overwriting subsequent edits', async () => {
+ const h = await fixture();
+ try {
+ let fail = true;
+ const git: typeof runSourceGit = async (env, args, cwd, signal) => {
+ if (fail && args[0] === 'apply') {
+ fail = false;
+ throw new Error('interrupted');
+ }
+ return runSourceGit(env, args, cwd, signal);
+ };
+ await expect(
+ createCindyMakeWorktree(h.userData, 'retry', h.signal, { processEnvironment: h.env, git }),
+ ).rejects.toThrow('interrupted');
+ const resumed = await createCindyMakeWorktree(h.userData, 'retry', h.signal, {
+ processEnvironment: h.env,
+ });
+ expect(await readFile(path.join(resumed.path, 'personal.txt'), 'utf8')).toBe(
+ 'existing personal change',
+ );
+ await writeFile(path.join(resumed.path, 'personal.txt'), 'continued editing');
+ await createCindyMakeWorktree(h.userData, 'retry', h.signal, { processEnvironment: h.env });
+ expect(await readFile(path.join(resumed.path, 'personal.txt'), 'utf8')).toBe(
+ 'continued editing',
+ );
+ expect(await h.git(['rev-list', '--all', '--count'])).toBe(h.history);
+ } finally {
+ await rm(h.userData, { recursive: true, force: true });
+ }
+}, 90_000);
+
+it('retains both sets of personal and task commits on feature merge conflict', async () => {
+ const h = await fixture();
+ try {
+ await writeFile(path.join(h.source, 'shared.txt'), 'personal edit');
+
+ await writeFile(path.join(h.workingDir, 'shared.txt'), 'task edit');
+
+ Object.assign(h.task, await collectCindyMakeChanges(h.git, h.userData, h.workingDir));
+ const baseline = await h.git(['rev-parse', 'HEAD']);
+ await expect(h.run()).rejects.toMatchObject({ code: 'conflict' });
+ expect(h.pnpm).not.toHaveBeenCalled();
+ expect(h.packageCommand).not.toHaveBeenCalled();
+ expect(await h.git(['merge-base', '--is-ancestor', baseline, 'HEAD'])).toBe('');
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ expect(await readFile(path.join(h.source, 'shared.txt'), 'utf8')).toBe('personal edit');
+ expect(await readFile(path.join(h.workingDir, 'shared.txt'), 'utf8')).toBe('task edit');
+ expect(await h.git(['status', '--porcelain'], h.workingDir)).toBe('');
+ expect(await h.git(['rev-parse', 'HEAD'], h.workingDir)).toBe(h.task.commit);
+ expect((await h.git(['worktree', 'list', '--porcelain'])).match(/^worktree /gm)).toHaveLength(
+ 2,
+ );
+ } finally {
+ await rm(h.userData, { recursive: true, force: true });
+ }
+}, 90_000);
diff --git a/apps/desktop/src/main/cindy-make/__tests__/personalBuild.test.ts b/apps/desktop/src/main/cindy-make/__tests__/personalBuild.test.ts
new file mode 100644
index 0000000000..80a84f2984
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/personalBuild.test.ts
@@ -0,0 +1,603 @@
+import { createHash } from 'node:crypto';
+import {
+ access,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ buildCindyPersonal,
+ personalArtifactPath,
+ personalBuildEnvironment,
+ personalBuildError,
+ runPersonalPackageCommand,
+ type PersonalArtifact,
+} from '../personalBuild';
+import { makeSourceCheckoutPath, makeSourceRoot, makeTaskWorktreePath } from '../sourcePaths';
+import type { runSourceGit } from '../sourceGit';
+import type { runSourcePnpm } from '../sourcePnpm';
+import type { PtySpawnFn } from '../../terminal/ptyFactory';
+import * as versionStore from '../versionStore';
+import { CindyMakeManager } from '../manager';
+vi.mock('../localHistory', () => ({
+ MAKE_GIT_IDENTITY: [],
+ commitPersonalFiles: async (
+ git: (args: string[], cwd: string) => Promise<string>,
+ cwd: string,
+ ) => ({
+ commit: await git(['rev-parse', 'HEAD'], cwd),
+ tree: await git(['snapshot-files'], cwd),
+ }),
+ commitLocalFiles: async (git: (args: string[], cwd: string) => Promise<string>, cwd: string) => ({
+ commit: 'f'.repeat(40),
+ tree: await git(['snapshot-files'], cwd),
+ }),
+}));
+
+vi.mock('../sourceContent', () => ({
+ snapshotContent: async (git: (args: string[], cwd: string) => Promise<string>, cwd: string) =>
+ git(['snapshot-files'], cwd),
+ contentRef: async () => undefined,
+ populateContent: async () => {},
+ applyContent: async (
+ git: (args: string[], cwd: string) => Promise<string>,
+ cwd: string,
+ _before: string,
+ _after: string,
+ threeWay: boolean,
+ ) => {
+ if (!threeWay) await git(['apply-files'], cwd);
+ },
+ taskContentRef: (run: string, kind: string) => 'refs/cindy-make/tasks/' + run + '/' + kind,
+}));
+
+const roots: string[] = [];
+async function temp() {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-personal-unit-'));
+ roots.push(root);
+ return root;
+}
+afterEach(async () => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
+});
+
+async function fixture() {
+ const userData = await temp();
+ const source = makeSourceCheckoutPath(userData);
+ const workingDir = makeTaskWorktreePath(userData, 'run');
+ await mkdir(source, { recursive: true });
+ await mkdir(workingDir, { recursive: true });
+ await writeFile(path.join(workingDir, 'keep.txt'), 'editing work');
+ const task = {
+ userData,
+ workingDir,
+ runId: 'run',
+ completionId: 'completion',
+ commit: 'b'.repeat(40),
+ profile: undefined as versionStore.VersionProfile | undefined,
+ };
+ let baseline = 'a'.repeat(40);
+ let sourceTree = baseline;
+ let buildDir = '';
+ let locked = false;
+ let locks = 0;
+ const events: string[] = [];
+ const abort = new AbortController();
+ const git = vi.fn<typeof runSourceGit>(async (_env, args, cwd) => {
+ expect(locked).toBe(true);
+ if (args[0] === 'worktree' && args[1] === 'add') {
+ buildDir = args[3];
+ events.push('merge');
+ }
+ if (args[0] === 'snapshot-files') return cwd === buildDir ? 'e'.repeat(40) : sourceTree;
+ if (args[0] === 'rev-parse') {
+ if (args[1] === '--abbrev-ref') return 'cindy-personal';
+ if (args[1] === '--git-path') return path.join(buildDir, 'MERGE_HEAD');
+ return cwd === buildDir ? task.commit : baseline;
+ }
+ if (args[0] === 'merge' && args[1] === '--ff-only') {
+ expect(cwd).toBe(source);
+ baseline = args[2];
+ sourceTree = 'e'.repeat(40);
+ events.push('adopt');
+ }
+ return '';
+ });
+ const pnpm = vi.fn<typeof runSourcePnpm>(async (_env, args, cwd) => {
+ expect(locked).toBe(true);
+ expect(cwd).toBe(source);
+ expect(sourceTree).toBe('e'.repeat(40));
+ events.push(args[0]);
+ });
+ const verify = vi.fn(async () => {});
+ const packageCommand = vi.fn<typeof runPersonalPackageCommand>(async (_node, _args, cwd) => {
+ expect(locked).toBe(true);
+ expect(cwd).toBe(source);
+ expect(sourceTree).toBe('e'.repeat(40));
+ events.push('package');
+ const artifacts = path.join(
+ cwd,
+ 'apps/desktop/release/artifacts/global/unversioned',
+ process.platform + '-' + process.arch,
+ );
+ await mkdir(artifacts, { recursive: true });
+ const name = 'Cindy-Setup.exe';
+ await writeFile(path.join(artifacts, name), 'installer bytes');
+ await writeFile(
+ path.join(artifacts, 'build-info.json'),
+ JSON.stringify({
+ product: 'cindy-desktop',
+ versionless: true,
+ version: null,
+ commitSha: baseline,
+ region: 'global',
+ platform: process.platform,
+ arch: process.arch,
+ files: [
+ {
+ role: 'installer',
+ name,
+ sha256: createHash('sha256').update('installer bytes').digest('hex'),
+ },
+ ],
+ }),
+ );
+ });
+ const publish = vi.fn(async (_state: { status: string }) => {});
+ const run = (
+ withProject: <T>(operation: () => Promise<T>) => Promise<T> = async (operation) => operation(),
+ personalOnly = false,
+ features?: () => Array<{ runId: string; operationId: string }>,
+ ) =>
+ buildCindyPersonal(
+ personalOnly ? { mode: 'personal', userData, completionId: 'history-build' } : task,
+ process.execPath,
+ {},
+ 'global',
+ abort.signal,
+ publish,
+ () => {},
+ async (operation) =>
+ withProject(async () => {
+ expect(locked).toBe(false);
+ locked = true;
+ locks++;
+ try {
+ return await operation();
+ } finally {
+ locked = false;
+ }
+ }),
+ { git, pnpm, verify, packageCommand, features },
+ );
+ return {
+ userData,
+ source,
+ task,
+ git,
+ pnpm,
+ verify,
+ packageCommand,
+ publish,
+ run,
+ events,
+ abort,
+ baseline: () => baseline,
+ sourceTree: () => sourceTree,
+ locked: () => locked,
+ locks: () => locks,
+ advance: () => {
+ baseline = 'c'.repeat(40);
+ },
+ buildDir: () => buildDir,
+ };
+}
+
+describe('personal source integration and packaging', () => {
+ it('reports each checking step before starting its command and stops at a failed test', async () => {
+ const h = await fixture();
+ const observed: unknown[] = [];
+ h.pnpm.mockImplementation(async (_env, args) => {
+ observed.push(h.publish.mock.calls.at(-1)?.[0]);
+ if (args[0] === 'test:unit:related') throw new Error('private test failure output');
+ });
+ await expect(h.run()).rejects.toMatchObject({ code: 'checksFailed' });
+ expect(observed).toEqual([
+ { status: 'checking', checkStep: 'dependencies' },
+ { status: 'checking', checkStep: 'tests' },
+ ]);
+ expect(h.packageCommand).not.toHaveBeenCalled();
+ observed.length = 0;
+ h.pnpm.mockImplementation(async () => {
+ observed.push(h.publish.mock.calls.at(-1)?.[0]);
+ });
+ await h.run(undefined, true);
+ expect(observed).toEqual([
+ { status: 'checking', checkStep: 'dependencies' },
+ { status: 'checking', checkStep: 'tests' },
+ { status: 'checking', checkStep: 'types' },
+ ]);
+ });
+ it('packages already integrated source after its editing directory is gone, without another merge or a synthetic task', async () => {
+ const h = await fixture();
+ const first = await h.run();
+ await rm(h.task.workingDir, { recursive: true, force: true });
+ h.verify.mockClear();
+ h.git.mockClear();
+ h.events.length = 0;
+ const features = vi.fn(() => {
+ expect(h.locked()).toBe(true);
+ return [{ runId: 'run', operationId: 'integrated' }];
+ });
+ const built = await h.run(undefined, true, features);
+ expect(built.commit).toBe(first.commit);
+ expect(built.includedFeatures).toEqual([{ runId: 'run', operationId: 'integrated' }]);
+ expect(h.verify).not.toHaveBeenCalled();
+ expect(h.events).toEqual(['install', 'test:unit:related', '--recursive', 'package']);
+ expect(
+ h.git.mock.calls.some(
+ ([, args]) => args[0] === 'merge' || (args[0] === 'worktree' && args[1] === 'add'),
+ ),
+ ).toBe(false);
+ expect(features).toHaveBeenCalledOnce();
+ });
+ it('adopts first, then checks and packages in personal under one lock, keeping both checkouts', async () => {
+ const h = await fixture();
+ const artifact = await h.run();
+ expect(h.events).toEqual([
+ 'merge',
+ 'adopt',
+ 'install',
+ 'test:unit:related',
+ '--recursive',
+ 'package',
+ ]);
+ expect(h.pnpm.mock.calls[2][1]).toEqual([
+ '--recursive',
+ '--workspace-concurrency=1',
+ '--if-present',
+ 'typecheck',
+ ]);
+ expect(h.verify).toHaveBeenCalledTimes(3);
+ expect(h.locks()).toBe(1);
+ expect(h.locked()).toBe(false);
+ const args = h.packageCommand.mock.calls[0][1];
+ expect(args).toEqual([
+ path.join(h.source, 'apps/desktop/scripts/package-desktop.mjs'),
+ '--platform',
+ process.platform,
+ '--arch',
+ process.arch,
+ '--region',
+ 'global',
+ '--no-sign',
+ ]);
+ expect(h.baseline()).toBe('f'.repeat(40));
+ expect(
+ await readFile(await personalArtifactPath(h.userData, 'completion', artifact), 'utf8'),
+ ).toBe('installer bytes');
+ expect(await readFile(path.join(h.task.workingDir, 'keep.txt'), 'utf8')).toBe('editing work');
+ await expect(access(h.buildDir())).rejects.toThrow();
+ await expect(
+ access(
+ path.join(
+ h.source,
+ 'apps/desktop/release/artifacts/global/unversioned',
+ process.platform + '-' + process.arch,
+ ),
+ ),
+ ).rejects.toThrow();
+ await expect(access(h.source)).resolves.toBeUndefined();
+ expect(
+ h.git.mock.calls.some(
+ ([, args]) =>
+ (args.includes(h.task.workingDir) || args.includes(h.source)) && args.includes('remove'),
+ ),
+ ).toBe(false);
+ });
+
+ it.each([
+ 'checks',
+ 'package',
+ 'checksum',
+ 'baseline',
+ 'task',
+ 'cancel',
+ 'publishCancel',
+ ] as const)(
+ 'preserves integrated files but publishes no artifact on %s failure',
+ async (failure) => {
+ const h = await fixture();
+ const original = h.packageCommand.getMockImplementation()!;
+ if (failure === 'checks') h.pnpm.mockRejectedValueOnce(new Error('test failed'));
+ if (failure === 'package')
+ h.packageCommand.mockRejectedValueOnce(personalBuildError('buildFailed'));
+ if (failure === 'task')
+ h.verify
+ .mockResolvedValueOnce()
+ .mockResolvedValueOnce()
+ .mockRejectedValueOnce(personalBuildError('changed'));
+ if (failure === 'publishCancel')
+ h.publish.mockImplementation(async (state) => {
+ if (state.status === 'publishing') h.abort.abort();
+ });
+ if (['checksum', 'baseline', 'cancel'].includes(failure))
+ h.packageCommand.mockImplementation(async (...args) => {
+ await original(...args);
+ if (failure === 'checksum') {
+ const installer = path.join(
+ args[2],
+ 'apps/desktop/release/artifacts/global/unversioned',
+ process.platform + '-' + process.arch,
+ 'Cindy-Setup.exe',
+ );
+ await writeFile(installer, 'modified after packaging');
+ }
+ if (failure === 'baseline') h.advance();
+ if (failure === 'cancel') h.abort.abort();
+ });
+ await expect(h.run()).rejects.toBeDefined();
+ expect(h.events).toContain('adopt');
+ expect(h.sourceTree()).toBe('e'.repeat(40));
+ expect(h.baseline()).toBe((failure === 'baseline' ? 'c' : 'f').repeat(40));
+ expect(await readFile(path.join(h.task.workingDir, 'keep.txt'), 'utf8')).toBe('editing work');
+ await expect(access(h.buildDir())).rejects.toThrow();
+ await expect(access(h.source)).resolves.toBeUndefined();
+ expect(h.locked()).toBe(false);
+ expect(
+ await readdir(path.join(makeSourceRoot(h.userData), 'packages')).catch(() => []),
+ ).toEqual([]);
+ },
+ );
+
+ it('finishes integration and its receipt on cancellation, then stops before checks and packaging', async () => {
+ const h = await fixture();
+ const original = h.git.getMockImplementation()!;
+ h.git.mockImplementation(async (...args) => {
+ if (args[1][0] === 'merge' && args[1][1] === '--ff-only') {
+ h.abort.abort();
+ expect(args[3].aborted).toBe(false);
+ }
+ return original(...args);
+ });
+ await expect(h.run()).rejects.toBeDefined();
+ expect(h.baseline()).toBe('f'.repeat(40));
+ expect(h.sourceTree()).toBe('e'.repeat(40));
+ expect(
+ h.git.mock.calls.some(
+ ([, args]) => args[0] === 'update-ref' && args[1].endsWith('/integrated'),
+ ),
+ ).toBe(true);
+ expect(h.pnpm).not.toHaveBeenCalled();
+ expect(h.packageCommand).not.toHaveBeenCalled();
+ await expect(access(h.source)).resolves.toBeUndefined();
+ await expect(access(h.task.workingDir)).resolves.toBeUndefined();
+ await expect(access(h.buildDir())).rejects.toThrow();
+ });
+
+ it('does not reuse an old manifest when a later package command produces nothing', async () => {
+ const h = await fixture();
+ const previous = await h.run();
+ h.packageCommand.mockResolvedValueOnce();
+ await expect(h.run()).rejects.toThrow();
+ expect(await readdir(path.join(makeSourceRoot(h.userData), 'packages'))).toEqual([
+ previous.artifactDirectory,
+ ]);
+ await expect(personalArtifactPath(h.userData, 'completion', previous)).resolves.toBeDefined();
+ });
+
+ it.each([false, true])(
+ 'retains the app from personal and cleans unpublished copies (cancel: %s)',
+ async (cancel) => {
+ const h = await fixture();
+ h.task.profile = { userData: h.userData, appName: 'Cindy', region: 'global', passive: false };
+ const id = '11111111-1111-4111-8111-111111111111';
+ const retainedDirectory = versionStore.versionDirectory(h.userData, id);
+ const packaged = path.join(
+ h.source,
+ 'apps',
+ 'desktop',
+ 'out',
+ 'Cindy-' + process.platform + '-' + process.arch,
+ );
+ vi.spyOn(versionStore, 'retainPersonalVersion').mockImplementation(async (input) => {
+ expect(h.locked()).toBe(true);
+ expect(input.sourceDirectory).toBe(
+ process.platform === 'darwin' ? path.join(packaged, 'Cindy.app') : packaged,
+ );
+ await mkdir(retainedDirectory, { recursive: true });
+ await writeFile(path.join(retainedDirectory, 'pending.txt'), 'retained app');
+ if (cancel) h.abort.abort();
+ return id;
+ });
+ const publishVersion = vi
+ .spyOn(versionStore, 'publishPersonalVersion')
+ .mockImplementation(() => {
+ expect(h.locked()).toBe(true);
+ });
+ if (cancel) {
+ await expect(h.run()).rejects.toBeDefined();
+ expect(publishVersion).not.toHaveBeenCalled();
+ await expect(access(retainedDirectory)).rejects.toThrow();
+ expect(await readdir(path.join(makeSourceRoot(h.userData), 'packages'))).toEqual([]);
+ } else {
+ await expect(h.run()).resolves.toMatchObject({ versionId: id });
+ expect(publishVersion).toHaveBeenCalledWith(h.userData, id);
+ await expect(access(retainedDirectory)).resolves.toBeUndefined();
+ }
+ expect(h.sourceTree()).toBe('e'.repeat(40));
+ await expect(access(h.source)).resolves.toBeUndefined();
+ await expect(access(h.task.workingDir)).resolves.toBeUndefined();
+ },
+ );
+
+ it('queues other source operations until packaging and artifact retention have finished', async () => {
+ const h = await fixture();
+ const manager = new CindyMakeManager();
+ const root = makeSourceRoot(h.userData);
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let packaging!: () => void;
+ const entered = new Promise<void>((resolve) => {
+ packaging = resolve;
+ });
+ const original = h.packageCommand.getMockImplementation()!;
+ h.packageCommand.mockImplementation(async (...args) => {
+ packaging();
+ await gate;
+ await original(...args);
+ });
+ const run = h.run((operation) => manager.withProject(root, operation));
+ await entered;
+ const update = vi.fn(async () => {
+ expect(h.publish).toHaveBeenLastCalledWith({ status: 'publishing' });
+ expect(h.locked()).toBe(false);
+ await expect(access(h.buildDir())).rejects.toThrow();
+ });
+ const pending = manager.withProject(root, update);
+ await Promise.resolve();
+ expect(update).not.toHaveBeenCalled();
+ release();
+ await run;
+ await pending;
+ expect(update).toHaveBeenCalledOnce();
+ });
+
+ it('does not apply files when the task or personal baseline changes during merge preparation', async () => {
+ for (const changed of ['task', 'personal']) {
+ const h = await fixture();
+ if (changed === 'task')
+ h.verify.mockResolvedValueOnce().mockRejectedValueOnce(personalBuildError('changed'));
+ else {
+ const original = h.git.getMockImplementation()!;
+ h.git.mockImplementation(async (...args) => {
+ const result = await original(...args);
+ if (args[1][0] === 'worktree' && args[1][1] === 'add') h.advance();
+ return result;
+ });
+ }
+ await expect(h.run()).rejects.toMatchObject({
+ code: changed === 'task' ? 'changed' : 'baselineChanged',
+ });
+ expect(h.events).not.toContain('adopt');
+ expect(h.pnpm).not.toHaveBeenCalled();
+ expect(h.packageCommand).not.toHaveBeenCalled();
+ await expect(access(h.source)).resolves.toBeUndefined();
+ await expect(access(h.task.workingDir)).resolves.toBeUndefined();
+ }
+ });
+});
+
+describe('recorded installer access', () => {
+ it('rejects other completions, traversal, changed content and redirected parent directories', async () => {
+ const h = await fixture();
+ const artifact = await h.run();
+ await expect(personalArtifactPath(h.userData, 'other', artifact)).rejects.toThrow();
+ await expect(
+ personalArtifactPath(h.userData, 'completion', {
+ ...artifact,
+ artifactName: '../outside.exe',
+ }),
+ ).rejects.toThrow();
+ await expect(
+ personalArtifactPath(h.userData, 'completion', {
+ ...artifact,
+ artifactDirectory: 'completion-/../elsewhere',
+ }),
+ ).rejects.toThrow();
+ const file = await personalArtifactPath(h.userData, 'completion', artifact);
+ await writeFile(file, 'changed');
+ await expect(personalArtifactPath(h.userData, 'completion', artifact)).rejects.toThrow();
+ const outside = path.join(h.userData, 'outside');
+ await mkdir(outside);
+ await writeFile(path.join(outside, artifact.artifactName), 'installer bytes');
+ const linked: PersonalArtifact = { ...artifact, artifactDirectory: 'completion-linked' };
+ await symlink(
+ outside,
+ path.join(makeSourceRoot(h.userData), 'packages', linked.artifactDirectory),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ await expect(personalArtifactPath(h.userData, 'completion', linked)).rejects.toThrow();
+ expect(await readFile(path.join(outside, artifact.artifactName), 'utf8')).toBe(
+ 'installer bytes',
+ );
+ });
+});
+
+describe('packaging process', () => {
+ function processFixture() {
+ let onExit!: (event: { exitCode: number }) => void;
+ const child = {
+ onData: vi.fn(),
+ onExit: vi.fn((callback) => {
+ onExit = callback;
+ }),
+ kill: vi.fn(() => onExit({ exitCode: 1 })),
+ };
+ const spawn = vi.fn(() => child) as unknown as PtySpawnFn;
+ const abort = new AbortController();
+ const run = () =>
+ runPersonalPackageCommand(
+ process.execPath,
+ ['package.js'],
+ os.tmpdir(),
+ {
+ PATH: path.dirname(process.execPath),
+ CINDY_SANDBOX: 'host',
+ ELECTRON_RUN_AS_NODE: '1',
+ NODE_OPTIONS: '--require private-hook',
+ OPENAI_API_KEY: 'secret',
+ },
+ abort.signal,
+ spawn,
+ );
+ return { child, spawn, abort, run, exit: (exitCode: number) => onExit({ exitCode }) };
+ }
+ it('uses a clean environment and only accepts a successful process exit', async () => {
+ const h = processFixture();
+ const run = h.run();
+ expect(vi.mocked(h.spawn).mock.calls[0][2].env).not.toHaveProperty('OPENAI_API_KEY');
+ expect(vi.mocked(h.spawn).mock.calls[0][2].env).not.toHaveProperty('NODE_OPTIONS');
+ expect(vi.mocked(h.spawn).mock.calls[0][2].env).not.toHaveProperty('CINDY_SANDBOX');
+ h.exit(0);
+ await expect(run).resolves.toBeUndefined();
+ });
+ it('cancels the owned process and bounds a hung package build', async () => {
+ vi.useFakeTimers();
+ const h = processFixture();
+ const result = expect(h.run()).rejects.toMatchObject({ code: 'interrupted' });
+ h.abort.abort();
+ await result;
+ expect(h.child.kill).toHaveBeenCalledOnce();
+ const hung = processFixture();
+ const timeout = expect(hung.run()).rejects.toMatchObject({ code: 'buildFailed' });
+ await vi.advanceTimersByTimeAsync(60 * 60_000);
+ await timeout;
+ expect(hung.child.kill).toHaveBeenCalledOnce();
+ });
+ it('finds Git Bash before Windows shell aliases and retains the selected build tools', async () => {
+ const root = await temp();
+ const bin = path.join(root, 'Git', 'bin');
+ await mkdir(bin, { recursive: true });
+ await writeFile(path.join(bin, 'bash.exe'), 'fixture');
+ const env = await personalBuildEnvironment(
+ { PATH: bin, PYTHON: '/selected/python', NODE_OPTIONS: 'private' },
+ path.join(root, 'Git/cmd/git.exe'),
+ );
+ expect(env.PYTHON).toBe('/selected/python');
+ expect(env).not.toHaveProperty('NODE_OPTIONS');
+ if (process.platform === 'win32')
+ expect(env.PATH?.split(path.delimiter)[0]).toBe(bin.replace(/\\/g, '/'));
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/projectAccess.test.ts b/apps/desktop/src/main/cindy-make/__tests__/projectAccess.test.ts
index 335270cb9c..d1ad9aff4a 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/projectAccess.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/projectAccess.test.ts
@@ -28,6 +28,13 @@ beforeEach(() => {
});
describe('Cindy Make project send access', () => {
+ it('also blocks a missing upstream-merge workspace without recreating it as an ordinary project', async () => {
+ const mergeDir = path.join(userData, 'cindy-make', 'merge-worktrees', '12345678-1234-1234-1234-123456789abc');
+ vi.mocked(lstat).mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }));
+ const send = vi.fn(async () => 'accepted');
+ await expect(withCindyMakeProjectUse(userData, mergeDir, send)).rejects.toThrow('PRECONDITION_FAILED');
+ expect(send).not.toHaveBeenCalled();
+ });
it('checks the worktree and original checkout before dispatch', async () => {
const send = vi.fn(async () => 'accepted');
await expect(withCindyMakeProjectUse(userData, workingDir, send)).resolves.toBe('accepted');
diff --git a/apps/desktop/src/main/cindy-make/__tests__/sourcePnpm.test.ts b/apps/desktop/src/main/cindy-make/__tests__/sourcePnpm.test.ts
index 9fe9ff9882..8b868de8fe 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/sourcePnpm.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/sourcePnpm.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { parseMakeDependencyProgress } from '../sourcePnpm.js';
+import { parseMakeDependencyProgress, runSourcePnpm } from '../sourcePnpm.js';
describe('dependency progress projection', () => {
it('keeps the actual counters when pnpm moves into installation scripts', () => {
@@ -28,3 +28,21 @@ describe('dependency progress projection', () => {
).toBeUndefined();
});
});
+
+it('accepts fixed colon-separated script names while rejecting shell operators before launch', async () => {
+ const signal = new AbortController().signal;
+ await expect(runSourcePnpm({ PATH: '' }, ['test:unit:related'], '.', signal)).rejects.toThrow(
+ 'pnpm not found',
+ );
+ for (const argument of [
+ 'test:unit&whoami',
+ 'test:unit|whoami',
+ 'test:unit;whoami',
+ '$(whoami)',
+ '%SECRET%',
+ ]) {
+ await expect(runSourcePnpm({ PATH: '' }, [argument], '.', signal)).rejects.toThrow(
+ 'unsafe pnpm argument',
+ );
+ }
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/sourcePreparation.test.ts b/apps/desktop/src/main/cindy-make/__tests__/sourcePreparation.test.ts
index 1dab38afcb..95cc0d6735 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/sourcePreparation.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/sourcePreparation.test.ts
@@ -220,6 +220,7 @@ describe('Source and dependency preparation', () => {
processEnvironment: () => ({}),
} as unknown as MakeToolchainEnvironment;
vi.mocked(runSourceGit).mockImplementation(async (_env, args) => {
+ if (args.includes('refs/cindy-make/personal-upstream^{commit}')) throw new Error('no file integration yet');
if (args[0] === 'ls-remote') return '0123456789abcdef refs/heads/main';
if (args[0] === 'remote') return CINDY_SOURCE_REPOSITORY;
if (args[0] === 'branch') return 'cindy-personal';
@@ -525,6 +526,7 @@ describe('Source and dependency preparation', () => {
);
const env = { processEnvironment: () => ({}) } as MakeToolchainEnvironment;
vi.mocked(runSourceGit).mockImplementation(async (_env, args) => {
+ if (args.includes('refs/cindy-make/personal-upstream^{commit}')) throw new Error('no file integration yet');
if (args[0] === 'merge-base') return 'b'.repeat(40);
if (args[0] === 'rev-parse' && args[1] === '--verify') return 'c'.repeat(40);
if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') return 'cindy-personal';
@@ -557,6 +559,7 @@ describe('Source and dependency preparation', () => {
);
const env = { processEnvironment: () => ({}) } as MakeToolchainEnvironment;
vi.mocked(runSourceGit).mockImplementation(async (_env, args) => {
+ if (args.includes('refs/cindy-make/personal-upstream^{commit}')) throw new Error('no file integration yet');
if (args[0] === 'rev-parse' && args[1] === 'HEAD') return 'a'.repeat(40);
if (args[0] === 'rev-parse' && args[1] === '--verify') return 'b'.repeat(40);
if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') return 'cindy-personal';
@@ -602,6 +605,7 @@ describe('Source and dependency preparation', () => {
processEnvironment: () => ({}),
} as unknown as MakeToolchainEnvironment;
vi.mocked(runSourceGit).mockImplementation(async (_env, args) => {
+ if (args.includes('refs/cindy-make/personal-upstream^{commit}')) throw new Error('no file integration yet');
switch (args[0]) {
case 'ls-remote':
return '0123456789abcdef\trefs/heads/main';
@@ -660,6 +664,7 @@ describe('Source and dependency preparation', () => {
processEnvironment: () => ({}),
} as unknown as MakeToolchainEnvironment;
vi.mocked(runSourceGit).mockImplementation(async (_env, args) => {
+ if (args.includes('refs/cindy-make/personal-upstream^{commit}')) throw new Error('no file integration yet');
if (
(missing === 'main' && args.includes('refs/heads/main^{commit}')) ||
(missing === 'origin/main' && args.includes('refs/remotes/origin/main^{commit}')) ||
@@ -777,6 +782,7 @@ describe('Source and dependency preparation', () => {
processEnvironment: () => ({}),
} as unknown as MakeToolchainEnvironment;
vi.mocked(runSourceGit).mockImplementation(async (_env, args) => {
+ if (args.includes('refs/cindy-make/personal-upstream^{commit}')) throw new Error('no file integration yet');
if (args[0] === 'ls-remote') return '0123456789abcdef\trefs/heads/main';
if (args[0] === 'remote') return CINDY_SOURCE_REPOSITORY;
if (args[0] === 'for-each-ref') return 'refs/heads/main';
@@ -802,6 +808,7 @@ describe('Source and dependency preparation', () => {
processEnvironment: () => ({}),
} as unknown as MakeToolchainEnvironment;
vi.mocked(runSourceGit).mockImplementation(async (_env, args) => {
+ if (args.includes('refs/cindy-make/personal-upstream^{commit}')) throw new Error('no file integration yet');
if (args[0] === 'ls-remote') return '0123456789abcdef\trefs/heads/main';
if (args[0] === 'clone') {
await expect(access(sourcePath)).rejects.toThrow();
@@ -829,6 +836,7 @@ describe('Source and dependency preparation', () => {
processEnvironment: () => ({}),
} as unknown as MakeToolchainEnvironment;
vi.mocked(runSourceGit).mockImplementation(async (_env, args) => {
+ if (args.includes('refs/cindy-make/personal-upstream^{commit}')) throw new Error('no file integration yet');
if (args[0] === 'ls-remote') return '0123456789abcdef\trefs/heads/main';
if (args[0] === 'remote') return CINDY_SOURCE_REPOSITORY;
if (args[0] === 'for-each-ref') return 'refs/heads/main';
@@ -918,6 +926,7 @@ describe('Source and dependency preparation', () => {
releaseFetch = resolve;
});
vi.mocked(runSourceGit).mockImplementation(async (_env, args) => {
+ if (args.includes('refs/cindy-make/personal-upstream^{commit}')) throw new Error('no file integration yet');
if (args[0] === 'ls-remote') return '0123456789abcdef\trefs/heads/main';
if (args[0] === 'remote') return CINDY_SOURCE_REPOSITORY;
if (args[0] === 'fetch') {
diff --git a/apps/desktop/src/main/cindy-make/__tests__/sourceRevisions.test.ts b/apps/desktop/src/main/cindy-make/__tests__/sourceRevisions.test.ts
index 58721e744a..7c98f01f9d 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/sourceRevisions.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/sourceRevisions.test.ts
@@ -43,7 +43,7 @@ describe('source revision snapshot', () => {
mainBehind: 4,
mainAhead: 0,
});
- expect(runSourceGit).toHaveBeenCalledTimes(5);
+ expect(runSourceGit).toHaveBeenCalledTimes(6);
expect(vi.mocked(runSourceGit).mock.calls.every(([, , cwd]) => cwd === 'managed-source')).toBe(
true,
);
@@ -68,7 +68,7 @@ describe('source revision snapshot', () => {
expect(result.mainBehind).toBeUndefined();
expect(result.mainAhead).toBeUndefined();
expect(result[ref === 'refs/heads/main' ? 'mainCommit' : 'mainRemoteCommit']).toBeUndefined();
- expect(runSourceGit).toHaveBeenCalledTimes(4);
+ expect(runSourceGit).toHaveBeenCalledTimes(5);
},
);
@@ -77,6 +77,12 @@ describe('source revision snapshot', () => {
await expect(read()).resolves.toMatchObject({ baseCommit: undefined, mainBehind: 4 });
});
+ it('reports the explicitly adopted upstream even when personal HEAD has not moved', async () => {
+ outputs['rev-parse --verify refs/cindy-make/personal-upstream^{commit}'] = remoteMain;
+ await expect(read()).resolves.toMatchObject({ baseCommit: remoteMain });
+ expect(vi.mocked(runSourceGit).mock.calls.some(([, args]) => args[0] === 'merge-base')).toBe(false);
+ });
+
it.each(['', '-1 2', '0 1.5', '0 9007199254740992', 'failed', new Error('count failed')])(
'omits unavailable or invalid comparison counts: %s',
async (output) => {
diff --git a/apps/desktop/src/main/cindy-make/__tests__/sourceStatusRefresh.test.ts b/apps/desktop/src/main/cindy-make/__tests__/sourceStatusRefresh.test.ts
new file mode 100644
index 0000000000..600f1eb8e2
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/sourceStatusRefresh.test.ts
@@ -0,0 +1,185 @@
+import path from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+import type { MakeSourceStatus } from '../../../shared/cindyMakeDoctor.js';
+import { CindyMakeManager } from '../manager.js';
+import { refreshCindySourceStatus } from '../sourceStatusRefresh.js';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+const summary: MakeSourceStatus = {
+ status: 'ready',
+ path: path.resolve('managed', 'source'),
+ channel: 'dev',
+ ref: 'main',
+};
+const local: MakeSourceStatus = {
+ ...summary,
+ branch: 'cindy-personal',
+ mainCommit: 'a'.repeat(40),
+};
+const latest: MakeSourceStatus = {
+ ...local,
+ latestVersion: {
+ status: 'ready',
+ channel: 'dev',
+ ref: 'main',
+ commit: 'b'.repeat(40),
+ behind: 2,
+ ahead: 0,
+ },
+};
+
+function harness() {
+ const manager = new CindyMakeManager();
+ const disk = deferred<MakeSourceStatus>();
+ const git = deferred<MakeSourceStatus>();
+ const network = deferred<MakeSourceStatus>();
+ const readers = {
+ readSummary: vi.fn(() => disk.promise),
+ readLocal: vi.fn(() => git.promise),
+ readLatest: vi.fn((_source: MakeSourceStatus) => network.promise),
+ };
+ return { manager, disk, git, network, readers };
+}
+
+describe('source status refresh', () => {
+ it.each(['ready', 'unavailable'] as const)(
+ 'publishes disk and Git details before the network returns %s',
+ async (status) => {
+ const h = harness();
+ const published: (MakeSourceStatus | undefined)[] = [];
+ h.manager.subscribe((state) => published.push(state.source));
+ const result = refreshCindySourceStatus(h.manager, h.readers);
+ h.disk.resolve(summary);
+ await vi.waitFor(() => expect(h.readers.readLocal).toHaveBeenCalledOnce());
+ expect(h.manager.getState().source).toEqual(summary);
+ expect(published).toContainEqual(summary);
+ expect(h.readers.readLatest).not.toHaveBeenCalled();
+ h.git.resolve(local);
+ await vi.waitFor(() => expect(h.readers.readLatest).toHaveBeenCalledWith(local));
+ expect(h.manager.getState().source).toEqual(local);
+ expect(published).toContainEqual(local);
+ const final =
+ status === 'ready'
+ ? latest
+ : {
+ ...local,
+ latestVersion: { status, channel: 'dev' as const },
+ };
+ h.network.resolve(final);
+ await expect(result).resolves.toEqual(final);
+ expect(h.manager.getState().source).toEqual(final);
+ },
+ );
+
+ it.each(['disk', 'git', 'network'] as const)(
+ 'cannot overwrite preparation or a subsequent clear after waiting for %s',
+ async (stage) => {
+ const h = harness();
+ const result = refreshCindySourceStatus(h.manager, h.readers);
+ if (stage !== 'disk') {
+ h.disk.resolve(summary);
+ await vi.waitFor(() => expect(h.readers.readLocal).toHaveBeenCalledOnce());
+ }
+ if (stage === 'network') {
+ h.git.resolve(local);
+ await vi.waitFor(() => expect(h.readers.readLatest).toHaveBeenCalledOnce());
+ }
+ h.manager.setSourceStatus({ ...summary, status: 'preparing', phase: 'cloning' });
+ const cleared: MakeSourceStatus = { status: 'missing', path: summary.path };
+ h.manager.setSourceStatus(cleared);
+ h.disk.resolve(summary);
+ h.git.resolve(local);
+ h.network.resolve(latest);
+ await expect(result).resolves.toEqual(cleared);
+ expect(h.manager.getState().source).toEqual(cleared);
+ if (stage === 'disk') expect(h.readers.readLocal).not.toHaveBeenCalled();
+ if (stage !== 'network') expect(h.readers.readLatest).not.toHaveBeenCalled();
+ },
+ );
+
+ it('keeps a newer refresh when an older network request finishes last', async () => {
+ const h = harness();
+ const old = refreshCindySourceStatus(h.manager, h.readers);
+ h.disk.resolve(summary);
+ h.git.resolve(local);
+ await vi.waitFor(() => expect(h.readers.readLatest).toHaveBeenCalledOnce());
+ const newer = { ...local, mainCommit: 'c'.repeat(40) };
+ await refreshCindySourceStatus(h.manager, {
+ readSummary: async () => summary,
+ readLocal: async () => newer,
+ readLatest: async (source) => source,
+ });
+ h.network.resolve(latest);
+ await expect(old).resolves.toEqual(newer);
+ expect(h.manager.getState().source).toEqual(newer);
+ });
+
+ it('invalidates an older lookup as soon as a newer refresh starts', async () => {
+ const h = harness();
+ const old = refreshCindySourceStatus(h.manager, h.readers);
+ h.disk.resolve(summary);
+ h.git.resolve(local);
+ await vi.waitFor(() => expect(h.readers.readLatest).toHaveBeenCalledOnce());
+ const newSummary = deferred<MakeSourceStatus>();
+ const newer = { ...local, mainCommit: 'c'.repeat(40) };
+ const current = refreshCindySourceStatus(h.manager, {
+ readSummary: () => newSummary.promise,
+ readLocal: async () => newer,
+ readLatest: async (source) => source,
+ });
+ h.network.resolve(latest);
+ await expect(old).resolves.toEqual(local);
+ expect(h.manager.getState().source).toEqual(local);
+ newSummary.resolve(summary);
+ await expect(current).resolves.toEqual(newer);
+ expect(h.manager.getState().source).toEqual(newer);
+ });
+
+ it.each(['missing', 'preparing', 'cancelled', 'failed'] as const)(
+ 'publishes %s immediately without discovering tools or checking the network',
+ async (status) => {
+ const h = harness();
+ const result = refreshCindySourceStatus(h.manager, h.readers);
+ h.disk.resolve({ ...summary, status });
+ await expect(result).resolves.toEqual({ ...summary, status });
+ expect(h.readers.readLocal).not.toHaveBeenCalled();
+ expect(h.readers.readLatest).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([true, false])(
+ 'retains previous details on reentry; same main commit: %s',
+ async (same) => {
+ const h = harness();
+ h.manager.setSourceStatus(latest);
+ const result = refreshCindySourceStatus(h.manager, h.readers);
+ h.disk.resolve(summary);
+ await vi.waitFor(() => expect(h.readers.readLocal).toHaveBeenCalledOnce());
+ expect(h.manager.getState().source).toEqual(latest);
+ const fresh = same ? local : { ...local, mainCommit: 'c'.repeat(40) };
+ h.git.resolve(fresh);
+ await vi.waitFor(() => expect(h.readers.readLatest).toHaveBeenCalledOnce());
+ expect(h.manager.getState().source?.latestVersion).toEqual(
+ same ? latest.latestVersion : undefined,
+ );
+ h.network.resolve(fresh);
+ await result;
+ },
+ );
+
+ it('retains the local summary if further inspection fails', async () => {
+ const h = harness();
+ h.readers.readLocal.mockRejectedValueOnce(new Error('Git unavailable'));
+ const result = refreshCindySourceStatus(h.manager, h.readers);
+ h.disk.resolve(summary);
+ await expect(result).rejects.toThrow('Git unavailable');
+ expect(h.manager.getState().source).toEqual(summary);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/taskCleanup.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/taskCleanup.git-integration.test.ts
index 7cef2e4d58..fe90a10199 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/taskCleanup.git-integration.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/taskCleanup.git-integration.test.ts
@@ -6,7 +6,7 @@ import { runSourceGit } from '../sourceGit.js';
import { manageCindyMakeWorkspace } from '../taskCleanup.js';
import { makeSourceCheckoutPath, makeTaskWorktreePath, makeTaskBranch } from '../sourcePaths.js';
-it('preserves archives, merges personal changes, and completely removes discarded work with real Git', async () => {
+it('preserves archives and finished unintegrated changes, and completely removes discarded work with real Git', async () => {
const profile = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-cleanup-'));
const source = makeSourceCheckoutPath(profile);
const env: NodeJS.ProcessEnv = {
@@ -47,7 +47,7 @@ it('preserves archives, merges personal changes, and completely removes discarde
await writeFile(path.join(target, 'feature.txt'), 'personal change');
await expect(
manageCindyMakeWorkspace(profile, 'first', 'finish', env, signal),
- ).rejects.toMatchObject({ code: 'dirty' });
+ ).resolves.toBe(false);
await git(['add', '.'], target);
await git(['commit', '-s', '-m', 'feature'], target);
await mkdir(path.join(target, 'node_modules'), { recursive: true });
@@ -56,9 +56,11 @@ it('preserves archives, merges personal changes, and completely removes discarde
manageCindyMakeWorkspace(profile, 'first', 'archive', env, signal, { baseCommit }),
).resolves.toBe(false);
await expect(manageCindyMakeWorkspace(profile, 'first', 'finish', env, signal)).resolves.toBe(
- true,
+ false,
);
- expect(await readFile(path.join(source, 'feature.txt'), 'utf8')).toBe('personal change');
+ expect(await readFile(path.join(target, 'feature.txt'), 'utf8')).toBe('personal change');
+ await expect(access(path.join(source, 'feature.txt'))).rejects.toThrow();
+ await manageCindyMakeWorkspace(profile, 'first', 'delete', env, signal);
await expect(access(target)).rejects.toThrow();
expect(await git(['branch', '--list', makeTaskBranch('first')])).toBe('');
const conflict = makeTaskWorktreePath(profile, 'conflict');
@@ -71,7 +73,7 @@ it('preserves archives, merges personal changes, and completely removes discarde
await git(['commit', '-s', '-m', 'personal change advanced']);
await expect(
manageCindyMakeWorkspace(profile, 'conflict', 'finish', env, signal),
- ).rejects.toMatchObject({ code: 'conflict' });
+ ).resolves.toBe(false);
expect(await readFile(path.join(conflict, 'feature.txt'), 'utf8')).toBe('task change');
expect(await readFile(path.join(source, 'feature.txt'), 'utf8')).toBe(
'personal change advanced',
@@ -92,7 +94,7 @@ it('preserves archives, merges personal changes, and completely removes discarde
await mkdir(longDependency, { recursive: true });
await writeFile(path.join(longDependency, 'index.js'), 'long path dependency');
await expect(
- manageCindyMakeWorkspace(profile, 'discarded', 'delete', env, signal),
+ manageCindyMakeWorkspace(profile, 'discarded', 'end', env, signal),
).resolves.toBe(true);
await expect(access(discarded)).rejects.toThrow();
// Match Windows' failed removal: no registration/.git, but dependencies and
@@ -120,7 +122,7 @@ it('preserves archives, merges personal changes, and completely removes discarde
manageCindyMakeWorkspace(profile, 'partial', 'delete', env, signal),
).rejects.toMatchObject({ code: 'unavailable' });
await expect(
- manageCindyMakeWorkspace(profile, 'partial', 'delete', env, signal, {
+ manageCindyMakeWorkspace(profile, 'partial', 'end', env, signal, {
preparedWorkspace: { path: partial, branch: partialBranch },
}),
).resolves.toBe(true);
diff --git a/apps/desktop/src/main/cindy-make/__tests__/taskCleanup.test.ts b/apps/desktop/src/main/cindy-make/__tests__/taskCleanup.test.ts
index 2663741c0f..77eb65da00 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/taskCleanup.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/taskCleanup.test.ts
@@ -3,6 +3,10 @@ import { rm } from 'node:fs/promises';
import os from 'node:os';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const h = vi.hoisted(() => ({ paths: new Set<string>(), links: new Set<string>() }));
+vi.mock('../sourceContent', () => ({
+ contentRef: async () => undefined,
+ taskContentRef: () => 'ref',
+}));
vi.mock('node:fs/promises', () => ({
lstat: vi.fn(async (p: string) => {
if (!h.paths.has(p)) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
@@ -67,7 +71,7 @@ function fixture() {
return '';
});
const manage = (
- action: 'finish' | 'delete' | 'archive',
+ action: 'end' | 'finish' | 'delete' | 'archive' | 'inspect',
checkCurrent?: () => void,
preparedWorkspace?: { path: string; branch: string },
) =>
@@ -92,15 +96,13 @@ beforeEach(() => {
]);
});
describe('managed task cleanup', () => {
- it('merges committed work before removing the worktree and branch', async () => {
+ it('keeps unintegrated committed work on finish without merging or deleting it', async () => {
const f = fixture();
- await expect(f.manage('finish')).resolves.toBe(true);
- const calls = f.git.mock.calls.map(([, args]) => args);
- expect(calls.findIndex((args) => args.includes('merge'))).toBeLessThan(
- calls.findIndex((args) => args.includes('remove')),
- );
- expect(calls.at(-1)).toEqual(['branch', '-d', branch]);
- expect(h.paths.has(target)).toBe(false);
+ await expect(f.manage('finish')).resolves.toBe(false);
+ expect(
+ f.git.mock.calls.some(([, args]) => args.includes('merge') || args.includes('remove')),
+ ).toBe(false);
+ expect(h.paths.has(target)).toBe(true);
});
it.each(['dirty', 'unmerged', 'unchanged'] as const)(
'retains %s work when merely archived',
@@ -113,20 +115,49 @@ describe('managed task cleanup', () => {
expect(f.state.branchExists).toBe(true);
},
);
- it('reclaims an archived task whose changes are already merged', async () => {
+ it('keeps an archived task even when its changes are already merged', async () => {
const f = fixture();
f.state.merged = true;
- await expect(f.manage('archive')).resolves.toBe(true);
+ await expect(f.manage('archive')).resolves.toBe(false);
+ expect(h.paths.has(target)).toBe(true);
+ expect(f.git).not.toHaveBeenCalled();
expect(f.git.mock.calls.some(([, args]) => args.includes('merge'))).toBe(false);
});
- it('refuses finish with uncommitted changes but explicit delete discards them', async () => {
+ it('retains finished uncommitted changes but explicit delete discards them', async () => {
const f = fixture();
f.state.dirty = true;
- await expect(f.manage('finish')).rejects.toMatchObject({ code: 'dirty' });
+ await expect(f.manage('finish')).resolves.toBe(false);
expect(h.paths.has(target)).toBe(true);
await expect(f.manage('delete')).resolves.toBe(true);
expect(f.git.mock.calls.at(-1)?.[1]).toEqual(['branch', '-D', branch]);
});
+ it.each([true, false])(
+ 'explicit end cleans integrated or unintegrated work (merged: %s)',
+ async (merged) => {
+ const f = fixture();
+ f.state.merged = merged;
+ f.state.dirty = !merged;
+ await expect(f.manage('end')).resolves.toBe(true);
+ expect(h.paths.has(target)).toBe(false);
+ expect(f.state.branchExists).toBe(false);
+ expect(
+ f.git.mock.calls.some(([, args]) => args.includes('merge') || args.includes('commit')),
+ ).toBe(false);
+ },
+ );
+ it.each([true, false])(
+ 'inspection reports integration without cleaning (merged: %s)',
+ async (merged) => {
+ const f = fixture();
+ f.state.merged = merged;
+ await expect(f.manage('inspect')).resolves.toBe(merged);
+ expect(h.paths.has(target)).toBe(true);
+ expect(f.state.branchExists).toBe(true);
+ expect(
+ f.git.mock.calls.some(([, args]) => args.includes('remove') || args.includes('update-ref')),
+ ).toBe(false);
+ },
+ );
it('retries after worktree removal succeeded but branch removal failed', async () => {
const f = fixture();
h.paths.delete(target);
@@ -203,14 +234,14 @@ describe('managed task cleanup', () => {
expect(rm).toHaveBeenCalled();
expect(f.state.branchExists).toBe(false);
});
- it('preserves work when merging fails', async () => {
+ it('never attempts a merge on finish', async () => {
const f = fixture();
const original = f.git.getMockImplementation()!;
f.git.mockImplementation(async (...args) => {
if (args[1].includes('merge')) throw new Error('conflict');
return original(...args);
});
- await expect(f.manage('finish')).rejects.toMatchObject({ code: 'conflict' });
+ await expect(f.manage('finish')).resolves.toBe(false);
expect(h.paths.has(target)).toBe(true);
expect(f.state.branchExists).toBe(true);
});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/taskManagement.test.ts b/apps/desktop/src/main/cindy-make/__tests__/taskManagement.test.ts
index efce48112f..d06a4108f9 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/taskManagement.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/taskManagement.test.ts
@@ -17,6 +17,7 @@ const h = vi.hoisted(() => ({
recycle: vi.fn(),
}));
vi.mock('electron', () => ({ app: { getPath: () => h.profile } }));
+vi.mock('../historyOwner.js', () => ({ captureMakeHistoryStore: () => ({ seed: vi.fn(), end: vi.fn() }) }));
vi.mock('../../localDb/client/current.js', () => ({
getDbClient: () => {
if (!h.dbReady) throw new Error('DbClient not ready');
@@ -41,6 +42,10 @@ vi.mock('../manager.js', async (original) => ({
withProject: async (_root: string, fn: () => unknown) => fn(),
isTaskPreparing: () => false,
forgetTask: h.forget,
+ getState: () => actionManager.getState(),
+ taskReport: (id: string) => actionManager.taskReport(id),
+ projectTaskSession: (...args: Parameters<CindyMakeManager['projectTaskSession']>) =>
+ actionManager.projectTaskSession(...args),
runTaskAction: (...args: Parameters<CindyMakeManager['runTaskAction']>) =>
actionManager.runTaskAction(...args),
},
@@ -55,6 +60,7 @@ import {
configureCindyMakeTaskManagement,
manageCindyMakeTask,
recycleCindyMakeTask,
+ refreshCindyMakeTaskIntegration,
} from '../taskManagement.js';
import { makeTaskWorktreePath } from '../sourcePaths.js';
@@ -120,6 +126,21 @@ beforeEach(() => {
});
});
describe('Cindy Make task management', () => {
+ it('keeps a workspace intact while an isolated test process is using it', async () => {
+ configureCindyMakeTaskManagement({
+ isAlive: () => false,
+ isRunning: () => false,
+ isWorkspaceBusy: () => true,
+ setStatus: h.patch,
+ recycle: h.recycle,
+ });
+ await expect(manageCindyMakeTask('session', 'finish')).rejects.toThrow();
+ await expect(manageCindyMakeTask('session', 'delete')).rejects.toThrow();
+ expect(h.patch).not.toHaveBeenCalled();
+ expect(h.recycle).not.toHaveBeenCalled();
+ expect(h.clean).not.toHaveBeenCalled();
+ });
+
it('uses canonical deletion and waits for runtime recycling before removing artifacts', async () => {
h.row!.status = 'active';
let settle!: () => void;
@@ -213,14 +234,14 @@ describe('Cindy Make task management', () => {
await expect(manageCindyMakeTask('session', 'finish')).rejects.toThrow('busy');
expect(h.patch).not.toHaveBeenCalled();
h.alive = true;
- await expect(recycleCindyMakeTask('session', db, () => true)).rejects.toMatchObject({
+ await expect(recycleCindyMakeTask('session', db, () => true, 'finish')).rejects.toMatchObject({
code: 'busy',
});
expect(h.clean).not.toHaveBeenCalled();
});
it('protects other active references and changed ownership', async () => {
h.borrowers = [{ id: 'another-session', status: 'active' }];
- await expect(recycleCindyMakeTask('session', db, () => true)).rejects.toMatchObject({
+ await expect(recycleCindyMakeTask('session', db, () => true, 'finish')).rejects.toMatchObject({
code: 'busy',
});
h.current = false;
@@ -240,4 +261,95 @@ describe('Cindy Make task management', () => {
await expect(manageCindyMakeTask('session', 'delete')).rejects.toThrow();
expect(h.clean).not.toHaveBeenCalled();
});
+
+ it('ends by archiving and discarding the confirmed workspace while keeping conversation records', async () => {
+ h.row!.status = 'active';
+ await manageCindyMakeTask('session', 'end');
+ expect(h.patch).toHaveBeenCalledWith('session', { status: 'archived', pinnedAt: null });
+ expect(h.recycle).toHaveBeenCalledWith('session', 'archived');
+ expect(h.clean.mock.calls[0][2]).toBe('end');
+ expect(h.persist.mock.calls[0][2].__cindyMakeCard.data.report.task.cleanupPending).toBe(true);
+ expect(h.persist.mock.calls.at(-1)![2].__cindyMakeCard.data.report.task).toMatchObject({
+ finished: true,
+ cleanupPending: false,
+ });
+ expect(h.forget).toHaveBeenCalledWith('run');
+ });
+
+ it('ordinary archive keeps even integrated work until an explicit end', async () => {
+ await recycleCindyMakeTask('session', db, () => true);
+ expect(h.clean).not.toHaveBeenCalled();
+ expect(h.persist).not.toHaveBeenCalled();
+ expect(h.forget).not.toHaveBeenCalled();
+ });
+
+ it('keeps failed end pending for a confirmed retry without deleting the session', async () => {
+ h.clean.mockRejectedValueOnce(Object.assign(new Error('locked'), { code: 'directoryBusy' }));
+ await expect(manageCindyMakeTask('session', 'end')).rejects.toThrow('directoryBusy');
+ expect(h.row!.status).toBe('archived');
+ expect(h.persist.mock.calls[0][2].__cindyMakeCard.data.report.task).toMatchObject({
+ cleanupPending: true,
+ });
+ expect(actionManager.getState().taskActions?.session).toEqual({
+ action: 'end',
+ status: 'failed',
+ error: 'directoryBusy',
+ });
+ expect(h.forget).not.toHaveBeenCalled();
+ await manageCindyMakeTask('session', 'end');
+ expect(h.forget).toHaveBeenCalledWith('run');
+ });
+
+ it('does not claim success for a legacy finish that retains files', async () => {
+ h.clean.mockResolvedValue(false);
+ await expect(manageCindyMakeTask('session', 'finish')).rejects.toThrow('dirty');
+ expect(h.forget).not.toHaveBeenCalled();
+ });
+
+ it('retries an already deleted task without resurrecting it', async () => {
+ h.row!.status = 'deleted';
+ await manageCindyMakeTask('session', 'end');
+ expect(h.patch).toHaveBeenCalledWith('session', { status: 'deleted', pinnedAt: null });
+ expect(h.clean.mock.calls[0][2]).toBe('delete');
+ });
+
+ it('refreshes integration without waiting in the caller or overlapping scans', async () => {
+ const report = JSON.parse(h.content).__cindyMakeCard.data.report;
+ actionManager.restoreTaskReport(report, () => h.current);
+ let complete!: (value: boolean) => void;
+ h.clean.mockImplementationOnce(
+ () =>
+ new Promise<boolean>((resolve) => {
+ complete = resolve;
+ }),
+ );
+ const first = refreshCindyMakeTaskIntegration();
+ const second = refreshCindyMakeTaskIntegration();
+ expect(first).toBe(second);
+ await vi.waitFor(() => expect(h.clean).toHaveBeenCalled());
+ expect(h.clean.mock.calls[0][2]).toBe('inspect');
+ complete(true);
+ await first;
+ expect(actionManager.taskReport('run')?.task?.integration).toBe('integrated');
+ h.clean.mockResolvedValueOnce(false);
+ await refreshCindyMakeTaskIntegration();
+ expect(actionManager.taskReport('run')?.task?.integration).toBe('unintegrated');
+ h.clean.mockRejectedValueOnce(new Error('unavailable'));
+ await refreshCindyMakeTaskIntegration();
+ expect(actionManager.taskReport('run')?.task?.integration).toBe('unknown');
+ expect(h.persist).not.toHaveBeenCalled();
+ });
+
+ it('does not publish a late integration scan after an account switch', async () => {
+ actionManager.restoreTaskReport(
+ JSON.parse(h.content).__cindyMakeCard.data.report,
+ () => h.current,
+ );
+ h.clean.mockImplementationOnce(async () => {
+ h.current = false;
+ return true;
+ });
+ await refreshCindyMakeTaskIntegration();
+ expect(actionManager.getState().tasks).toBeUndefined();
+ });
});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/taskRuntime.test.ts b/apps/desktop/src/main/cindy-make/__tests__/taskRuntime.test.ts
index 8e74f395d5..6a004ca5e8 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/taskRuntime.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/taskRuntime.test.ts
@@ -891,3 +891,4 @@ describe('Cindy Make task runtime', () => {
expect(harness.send).not.toHaveBeenCalled();
});
});
+vi.mock('../historyCapture.js', () => ({ captureMakeHistoryReport: vi.fn() }));
diff --git a/apps/desktop/src/main/cindy-make/__tests__/taskWorkspace.test.ts b/apps/desktop/src/main/cindy-make/__tests__/taskWorkspace.test.ts
index 273def4efc..07a7337397 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/taskWorkspace.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/taskWorkspace.test.ts
@@ -10,6 +10,13 @@ import {
prepareCindyMakeWorkspace,
} from '../taskWorkspace';
+vi.mock('../sourceContent', () => ({
+ contentRef: vi.fn(async () => undefined),
+ snapshotContent: vi.fn(async () => 'f'.repeat(40)),
+ applyContent: vi.fn(async () => {}),
+ taskContentRef: (run: string) => 'refs/cindy-make/tasks/' + run + '/base',
+}));
+
describe('prepareCindyMakeWorkspace', () => {
let userData: string;
beforeEach(async () => {
@@ -22,10 +29,11 @@ describe('prepareCindyMakeWorkspace', () => {
it('branches a new worktree off the personal baseline and installs dependencies', async () => {
const git = vi.fn(async (_env: NodeJS.ProcessEnv, args: string[]) => {
+ if (args[0] === 'branch' && args[1] === '--show-current') return 'cindy-personal';
if (args[0] === 'branch' && args[2] === 'cindy-personal') return ' cindy-personal\n';
if (args[0] === 'branch') return '';
if (args[0] === 'rev-parse') return 'abcdef1234567\n';
- if (args[0] === 'worktree') return '';
+ if (args[0] === 'worktree' || args[0] === 'update-ref') return '';
throw new Error(`unexpected ${args.join(' ')}`);
});
const pnpm = vi.fn(async () => undefined);
@@ -65,6 +73,7 @@ describe('prepareCindyMakeWorkspace', () => {
const git = vi.fn(async (_env: NodeJS.ProcessEnv, args: string[], cwd: string) => {
if (args[0] === 'branch')
return args[2] === 'cindy-personal' ? 'cindy-personal' : 'cindy-make/run-2';
+ if (args.includes('--git-common-dir')) return path.join(userData, 'cindy-make/source/.git');
if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref') {
expect(cwd).toBe(worktreePath);
return 'cindy-make/run-2';
@@ -127,9 +136,10 @@ describe('split Cindy Make workspace preparation', () => {
try {
await mkdir(path.join(userData, 'cindy-make', 'source', '.git'), { recursive: true });
const git = vi.fn(async (_env: NodeJS.ProcessEnv, args: string[]) => {
+ if (args[0] === 'branch' && args[1] === '--show-current') return 'cindy-personal';
if (args[0] === 'branch' && args[2] === 'cindy-personal') return 'cindy-personal\n';
if (args[0] === 'rev-parse') return 'base123\n';
- if (args[0] === 'worktree') return '';
+ if (args[0] === 'worktree' || args[0] === 'update-ref') return '';
return '';
});
const pnpm = vi.fn(async () => undefined);
@@ -140,12 +150,11 @@ describe('split Cindy Make workspace preparation', () => {
{ processEnvironment: {}, git, pnpm },
);
expect(pnpm).not.toHaveBeenCalled();
- await installCindyMakeWorktree(
- userData,
- workspace,
- new AbortController().signal,
- { processEnvironment: {}, git, pnpm },
- );
+ await installCindyMakeWorktree(userData, workspace, new AbortController().signal, {
+ processEnvironment: {},
+ git,
+ pnpm,
+ });
expect(pnpm).toHaveBeenCalledOnce();
} finally {
await rm(userData, { recursive: true, force: true });
diff --git a/apps/desktop/src/main/cindy-make/__tests__/testController.test.ts b/apps/desktop/src/main/cindy-make/__tests__/testController.test.ts
new file mode 100644
index 0000000000..1d29c0bcff
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/testController.test.ts
@@ -0,0 +1,251 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ createMakeTestController,
+ type MakeTestContext,
+ type MakeTestControllerDeps,
+} from '../testController';
+import { makeTestError } from '../testRunner';
+import type { PersonalArtifact } from '../personalBuild';
+import type { CindyMakeCompletionMeta } from '../../../shared/cindyMakeSession';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+}
+function harness(initial: Partial<CindyMakeCompletionMeta> = {}) {
+ let meta: CindyMakeCompletionMeta = { reportedAt: 1, commit: 'a'.repeat(40), ...initial };
+ let current = true;
+ let leased = false;
+ const ready = deferred<void>();
+ const closed = deferred<void>();
+ const artifact = deferred<PersonalArtifact>();
+ const build = vi.fn<NonNullable<MakeTestControllerDeps['build']>>(
+ async (_context, signal, publish) => {
+ signal.addEventListener('abort', () => artifact.reject(makeTestError('interrupted')), {
+ once: true,
+ });
+ await publish({ status: 'packaging' });
+ return artifact.promise;
+ },
+ );
+ const openBuild = vi.fn(async () => {});
+ const stop = vi.fn(() => {
+ ready.reject(makeTestError('interrupted'));
+ closed.resolve();
+ });
+ const context = (): MakeTestContext => ({
+ sessionId: 'session',
+ completionId: 'completion',
+ userData: '/profile',
+ workingDir: '/profile/task',
+ runId: 'run',
+ commit: meta.commit ?? '',
+ meta,
+ isCurrent: () => current,
+ });
+ const save = vi.fn(async (_context, patch) => {
+ meta = { ...meta, ...patch };
+ return meta;
+ });
+ const launch = vi.fn(async (_context, signal: AbortSignal) => {
+ signal.addEventListener('abort', stop, { once: true });
+ return { ready: ready.promise, closed: closed.promise, stop };
+ });
+ const controller = createMakeTestController({
+ load: async () => context(),
+ save,
+ launch,
+ build,
+ openBuild,
+ now: () => 123,
+ withUse: async (_context, run) => {
+ leased = true;
+ try {
+ await run();
+ } finally {
+ leased = false;
+ }
+ },
+ });
+ return {
+ controller,
+ launch,
+ build,
+ openBuild,
+ artifact,
+ save,
+ ready,
+ closed,
+ stop,
+ meta: () => meta,
+ leased: () => leased,
+ changeOwner: () => {
+ current = false;
+ },
+ };
+}
+afterEach(() => vi.useRealTimers());
+
+describe('Main-owned Cindy Make test lifecycle', () => {
+ it('coalesces repeated starts, broadcasts readiness and keeps a workspace lease until exit', async () => {
+ const h = harness();
+ await h.controller.act('session', 'completion', 'start');
+ await h.controller.act('session', 'completion', 'start');
+ expect(h.launch).toHaveBeenCalledOnce();
+ expect(h.meta().test?.status).toBe('starting');
+ expect(h.leased()).toBe(true);
+ h.ready.resolve();
+ await vi.waitFor(() => expect(h.meta().test?.status).toBe('ready'));
+ expect((await h.controller.act('session', 'completion', 'start')).test?.status).toBe('ready');
+ expect(h.launch).toHaveBeenCalledOnce();
+ h.closed.resolve();
+ await vi.waitFor(() => expect(h.leased()).toBe(false));
+ expect(h.meta().test?.status).toBe('stopped');
+ expect(h.controller.isUsingWorkspace('/profile/task')).toBe(false);
+ });
+ it('continues editing without losing the persisted choice to a late process exit', async () => {
+ const h = harness();
+ await h.controller.act('session', 'completion', 'start');
+ h.ready.resolve();
+ await vi.waitFor(() => expect(h.meta().test?.status).toBe('ready'));
+ await h.controller.act('session', 'completion', 'continue');
+ await vi.waitFor(() => expect(h.leased()).toBe(false));
+ expect(h.meta().continuedAt).toBe(123);
+ expect(h.meta().commit).toBe('a'.repeat(40));
+ await expect(h.controller.act('session', 'completion', 'start')).rejects.toMatchObject({
+ code: 'unavailable',
+ });
+ });
+ it('turns an unowned persisted launch into interrupted state without replaying it', async () => {
+ const h = harness({ test: { status: 'starting' } });
+ const result = await h.controller.act('session', 'completion', 'status');
+ expect(result.test).toEqual({ status: 'stopped', error: 'interrupted' });
+ expect(h.launch).not.toHaveBeenCalled();
+ });
+ it('preserves failure and releases the lease when validation fails before spawning', async () => {
+ const h = harness();
+ h.launch.mockRejectedValueOnce(makeTestError('changed'));
+ await h.controller.act('session', 'completion', 'start');
+ await vi.waitFor(() => expect(h.meta().test).toEqual({ status: 'failed', error: 'changed' }));
+ expect(h.leased()).toBe(false);
+ expect(h.controller.isUsingWorkspace('/profile/task')).toBe(false);
+ void h.ready.promise.catch(() => {});
+ });
+ it('stops owned processes on account change without publishing to the new owner', async () => {
+ vi.useFakeTimers();
+ const h = harness();
+ await h.controller.act('session', 'completion', 'start');
+ await Promise.resolve();
+ h.changeOwner();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(h.stop).toHaveBeenCalled();
+ expect(h.save).toHaveBeenCalledTimes(1);
+ expect(h.leased()).toBe(false);
+ });
+ it('requires a verified commit even if the renderer asks to start', async () => {
+ const h = harness({ commit: undefined });
+ await expect(h.controller.act('session', 'completion', 'start')).rejects.toMatchObject({
+ code: 'unavailable',
+ });
+ expect(h.launch).not.toHaveBeenCalled();
+ });
+});
+
+const installer: PersonalArtifact = {
+ artifactDirectory: 'completion-output',
+ artifactName: 'Cindy.exe',
+ sha256: 'f'.repeat(64),
+ commit: 'b'.repeat(40),
+};
+
+describe('personal build completion choices', () => {
+ it('coalesces build clicks, persists progress and opens only the recorded installer', async () => {
+ const h = harness();
+ await Promise.all([
+ h.controller.act('session', 'completion', 'build'),
+ h.controller.act('session', 'completion', 'build'),
+ ]);
+ await vi.waitFor(() => expect(h.meta().personal?.status).toBe('packaging'));
+ expect(h.build).toHaveBeenCalledOnce();
+ expect(h.launch).not.toHaveBeenCalled();
+ expect(h.leased()).toBe(true);
+ await expect(h.controller.act('session', 'completion', 'open-build')).rejects.toMatchObject({
+ code: 'unavailable',
+ });
+ h.artifact.resolve(installer);
+ await vi.waitFor(() => expect(h.leased()).toBe(false));
+ expect(h.meta()).toMatchObject({
+ personal: { status: 'ready', ...installer },
+ lastAction: 'build',
+ });
+ await h.controller.act('session', 'completion', 'open-build');
+ expect(h.openBuild).toHaveBeenCalledOnce();
+ });
+ it('closes a running test before building the personal installer', async () => {
+ const h = harness();
+ await h.controller.act('session', 'completion', 'start');
+ h.ready.resolve();
+ await vi.waitFor(() => expect(h.meta().test?.status).toBe('ready'));
+ await h.controller.act('session', 'completion', 'build');
+ expect(h.stop).toHaveBeenCalled();
+ expect(h.meta().test?.status).toBe('stopped');
+ expect(h.build).toHaveBeenCalledOnce();
+ h.artifact.resolve(installer);
+ await vi.waitFor(() => expect(h.leased()).toBe(false));
+ });
+ it('keeps the lease until cancelled build cleanup finishes and never loses Continue Editing', async () => {
+ const h = harness();
+ const cleanup = deferred<void>();
+ h.build.mockImplementation(async (_context, signal) => {
+ await new Promise<void>((resolve) =>
+ signal.addEventListener('abort', () => resolve(), { once: true }),
+ );
+ await cleanup.promise;
+ throw makeTestError('interrupted');
+ });
+ await h.controller.act('session', 'completion', 'build');
+ await h.controller.act('session', 'completion', 'continue');
+ expect(h.meta().continuedAt).toBe(123);
+ expect(h.leased()).toBe(true);
+ expect(h.controller.isUsingWorkspace('/profile/task')).toBe(true);
+ cleanup.resolve();
+ await vi.waitFor(() => expect(h.leased()).toBe(false));
+ expect(h.meta()).toMatchObject({
+ continuedAt: 123,
+ personal: { status: 'failed', error: 'interrupted' },
+ });
+ });
+ it('retains the adopted build receipt if the user continues during final adoption', async () => {
+ const h = harness();
+ h.build.mockImplementation(async () => h.artifact.promise);
+ await h.controller.act('session', 'completion', 'build');
+ await h.controller.act('session', 'completion', 'continue');
+ h.artifact.resolve(installer);
+ await vi.waitFor(() => expect(h.leased()).toBe(false));
+ expect(h.meta()).toMatchObject({
+ continuedAt: 123,
+ personal: { status: 'ready', ...installer },
+ });
+ });
+ it('marks persisted in-flight packaging as interrupted after restart without resuming it', async () => {
+ const h = harness({ lastAction: 'build', personal: { status: 'packaging' } });
+ expect(await h.controller.act('session', 'completion', 'status')).toMatchObject({
+ personal: { status: 'failed', error: 'interrupted' },
+ });
+ expect(h.build).not.toHaveBeenCalled();
+ });
+ it('keeps actionable conflict errors and releases the workspace on build failure', async () => {
+ const h = harness();
+ h.build.mockRejectedValueOnce(Object.assign(new Error('conflict'), { code: 'conflict' }));
+ await h.controller.act('session', 'completion', 'build');
+ await vi.waitFor(() =>
+ expect(h.meta().personal).toEqual({ status: 'failed', error: 'conflict' }),
+ );
+ expect(h.leased()).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/testRunner.test.ts b/apps/desktop/src/main/cindy-make/__tests__/testRunner.test.ts
new file mode 100644
index 0000000000..a830dd087c
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/testRunner.test.ts
@@ -0,0 +1,193 @@
+import path from 'node:path';
+import os from 'node:os';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { IPty } from 'node-pty';
+import type { PtySpawnFn } from '../../terminal/ptyFactory';
+const h = vi.hoisted(() => ({ links: new Set<string>(), files: new Set<string>(), git: vi.fn() }));
+vi.mock('node:fs/promises', () => ({
+ lstat: async (file: string) => ({
+ isSymbolicLink: () => h.links.has(file),
+ isDirectory: () => !h.files.has(file),
+ isFile: () => h.files.has(file),
+ }),
+ realpath: async (file: string) => file,
+}));
+vi.mock('../sourceGit.js', () => ({ runSourceGit: h.git }));
+import { launchMakeTest, makeTestEnvironment, verifyMakeTestWorkspace } from '../testRunner';
+import { makeSourceCheckoutPath, makeTaskWorktreePath } from '../sourcePaths';
+
+const profile = path.join(os.tmpdir(), 'cindy-preview-test');
+const task = {
+ userData: profile,
+ workingDir: makeTaskWorktreePath(profile, 'abcd-test'),
+ runId: 'abcd-test',
+ commit: 'a'.repeat(40),
+};
+function processHarness() {
+ let data: (value: string) => void = () => {};
+ let exit: () => void = () => {};
+ const kill = vi.fn(() => exit());
+ const spawn = vi.fn<PtySpawnFn>(
+ () =>
+ ({
+ onData: (fn: (value: string) => void) => {
+ data = fn;
+ return { dispose() {} };
+ },
+ onExit: (fn: (event: { exitCode: number }) => void) => {
+ exit = () => fn({ exitCode: 0 });
+ return { dispose() {} };
+ },
+ kill,
+ }) as unknown as IPty,
+ );
+ const controller = new AbortController();
+ const process = launchMakeTest(
+ task,
+ path.join(profile, 'node'),
+ { PATH: '/tools', XDT_USER_DATA_DIR: '/host' },
+ 'global',
+ controller.signal,
+ spawn,
+ );
+ void process.ready.catch(() => {});
+ const verdict = (extra: Partial<Record<string, string>> = {}) => {
+ const sandbox = spawn.mock.calls[0][1]
+ .find((arg) => arg.startsWith('--isolated='))!
+ .split('=')[1];
+ return [
+ 'DESKTOP_DEV_VERDICT=ready',
+ ...Object.entries({
+ mode: 'isolated',
+ sandbox,
+ root: task.workingDir,
+ commit: task.commit,
+ pid: '4242',
+ region: 'global',
+ ...extra,
+ }).map(([key, value]) => key + '=' + value),
+ '',
+ ].join('\r\n');
+ };
+ return {
+ process,
+ spawn,
+ kill,
+ controller,
+ emit: (value: string) => data(value),
+ exit: () => exit(),
+ verdict,
+ };
+}
+
+beforeEach(() => {
+ h.links.clear();
+ h.files.clear();
+ h.git.mockReset();
+ h.files.add(path.join(task.workingDir, '.git'));
+ h.files.add(path.join(task.workingDir, 'scripts', 'desktop-restart-runner.mjs'));
+ h.git.mockImplementation(async (_env, args) => {
+ if (args.includes('--git-common-dir'))
+ return path.join(makeSourceCheckoutPath(profile), '.git');
+ if (args.includes('--abbrev-ref')) return 'cindy-make/abcd-test';
+ if (args[0] === 'status') return '';
+ return task.commit;
+ });
+});
+afterEach(() => vi.useRealTimers());
+
+describe('isolated Make test runner', () => {
+ it('keeps OS/tool paths while dropping host profiles, auth and Node injection', () => {
+ expect(
+ makeTestEnvironment({
+ PATH: '/tools',
+ HOME: '/user',
+ XDT_USER_DATA_DIR: '/host',
+ CINDY_AUTH_REGION: 'cn',
+ ELECTRON_RUN_AS_NODE: '1',
+ NODE_OPTIONS: '--require bad',
+ ANTHROPIC_API_KEY: 'fake-secret',
+ OPENAI_API_KEY: 'fake-secret',
+ CODEX_HOME: '/host/codex',
+ }),
+ ).toEqual({ PATH: '/tools', HOME: '/user', TERM: 'xterm-256color', FORCE_COLOR: '0' });
+ });
+ it('uses the existing wrapper, explicit isolation and a real PTY without a shell command', async () => {
+ const h = processHarness();
+ expect(h.spawn.mock.calls[0][1]).toEqual([
+ path.join(task.workingDir, 'scripts', 'desktop-restart-runner.mjs'),
+ '--wait-ready',
+ '--region=global',
+ expect.stringMatching(/^--isolated=make-[0-9a-f]{20}$/),
+ '--passive',
+ ]);
+ expect(h.spawn.mock.calls[0][2].cwd).toBe(task.workingDir);
+ expect(h.spawn.mock.calls[0][2].env).not.toHaveProperty('XDT_USER_DATA_DIR');
+ const text = h.verdict();
+ h.emit(text.slice(0, 17));
+ h.emit(text.slice(17));
+ await expect(h.process.ready).resolves.toBeUndefined();
+ h.exit();
+ await h.process.closed;
+ });
+ it.each([{ root: profile }, { commit: 'b'.repeat(40) }, { mode: 'shared' }, { region: 'cn' }])(
+ 'rejects a ready verdict for the wrong launch %j',
+ async (extra) => {
+ const h = processHarness();
+ h.emit(h.verdict(extra));
+ await expect(h.process.ready).rejects.toMatchObject({ code: 'launchFailed' });
+ expect(h.kill).toHaveBeenCalledOnce();
+ },
+ );
+ it('fails on an early exit and aborts only its own process', async () => {
+ const h = processHarness();
+ h.exit();
+ await expect(h.process.ready).rejects.toMatchObject({ code: 'launchFailed' });
+ const next = processHarness();
+ next.controller.abort();
+ await expect(next.process.ready).rejects.toMatchObject({ code: 'interrupted' });
+ expect(next.kill).toHaveBeenCalledOnce();
+ });
+ it('bounds startup even if the wrapper never returns a verdict', async () => {
+ vi.useFakeTimers();
+ const h = processHarness();
+ await vi.advanceTimersByTimeAsync(25 * 60_000);
+ await expect(h.process.ready).rejects.toMatchObject({ code: 'timeout' });
+ expect(h.kill).toHaveBeenCalledOnce();
+ });
+});
+
+describe('test workspace validation', () => {
+ it('accepts the managed branch at the completed commit without changing files', async () => {
+ await expect(
+ verifyMakeTestWorkspace(task, {}, new AbortController().signal),
+ ).resolves.toBeUndefined();
+ expect(h.git.mock.calls.every(([, args]) => ['rev-parse', 'status'].includes(args[0]))).toBe(
+ true,
+ );
+ });
+ it('rejects a replaced managed root or source Git directory', async () => {
+ h.links.add(path.join(makeSourceCheckoutPath(profile), '.git'));
+ await expect(
+ verifyMakeTestWorkspace(task, {}, new AbortController().signal),
+ ).rejects.toMatchObject({ code: 'unavailable' });
+ expect(h.git).not.toHaveBeenCalled();
+ });
+ it('rejects an outside worktree before accessing Git', async () => {
+ await expect(
+ verifyMakeTestWorkspace({ ...task, workingDir: profile }, {}, new AbortController().signal),
+ ).rejects.toMatchObject({ code: 'unavailable' });
+ expect(h.git).not.toHaveBeenCalled();
+ });
+ it.each(['dirty', 'new-head'])('requires fresh completion after %s changes', async (change) => {
+ const original = h.git.getMockImplementation()!;
+ h.git.mockImplementation(async (env, args) => {
+ if (change === 'dirty' && args[0] === 'status') return ' M code.ts';
+ if (change === 'new-head' && args.length === 2 && args[1] === 'HEAD') return 'b'.repeat(40);
+ return original(env, args);
+ });
+ await expect(
+ verifyMakeTestWorkspace(task, {}, new AbortController().signal),
+ ).rejects.toMatchObject({ code: 'changed' });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/testRuntime.test.ts b/apps/desktop/src/main/cindy-make/__tests__/testRuntime.test.ts
new file mode 100644
index 0000000000..f8f9187a9e
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/testRuntime.test.ts
@@ -0,0 +1,306 @@
+import os from 'node:os';
+import path from 'node:path';
+import { SQLiteSyncDialect } from 'drizzle-orm/sqlite-core';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+const h = vi.hoisted(() => ({
+ profile: '',
+ row: {} as Record<string, unknown>,
+ card: {} as Record<string, unknown>,
+ laterUser: false,
+ current: true,
+ query: vi.fn(),
+ write: vi.fn(),
+ broadcast: vi.fn(),
+ launch: vi.fn(),
+ build: vi.fn(),
+ artifactPath: vi.fn(),
+ showItem: vi.fn(),
+ rememberOriginal: vi.fn(async () => {}),
+ historyIntegrate: vi.fn(async () => ({ items: [{ runId: 'run', integration: 'integrated' }] })),
+ history: vi.fn(async () => ({ items: [{ runId: 'run', integration: 'integrated' }] })),
+}));
+vi.mock('../historyOwner.js', () => ({
+ captureMakeHistoryStore: () => ({ completion: vi.fn(), version: vi.fn(), list: () => [] }),
+}));
+vi.mock('../historyRuntime.js', () => ({
+ getCindyMakeHistory: h.history,
+ actCindyMakeHistory: h.historyIntegrate,
+}));
+vi.mock('../versionStartup.js', () => ({
+ rememberOriginalVersion: h.rememberOriginal,
+ currentVersionProfile: () => ({
+ userData: h.profile,
+ appName: 'Cindy',
+ region: 'global',
+ passive: false,
+ }),
+}));
+vi.mock('electron', () => ({
+ app: { getPath: () => h.profile },
+ shell: { showItemInFolder: h.showItem },
+}));
+vi.mock('../personalBuild.js', () => ({
+ buildCindyPersonal: h.build,
+ personalArtifactPath: h.artifactPath,
+ personalBuildEnvironment: async (env: unknown) => env,
+}));
+vi.mock('../toolchainEnvironment.js', () => ({
+ createMakeToolchainEnvironment: async () => ({
+ probe: async () => ({ status: 'ok', path: process.execPath }),
+ }),
+ resolveMakeToolEnvironment: async () => ({}),
+}));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => client }));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({}),
+ isDataOwnerBroadcastScopeCurrent: () => h.current,
+}));
+vi.mock('../../localDb/sessionRouteLock.js', () => ({
+ withSessionRouteLock: async (_id: string, run: () => unknown) => run(),
+}));
+vi.mock('../../localDb/ipc/messages.js', () => ({ broadcastMessageAgentMetaUpdate: h.broadcast }));
+vi.mock('../testRunner.js', async (original) => ({
+ ...(await original<typeof import('../testRunner.js')>()),
+ launchMakeTest: h.launch,
+}));
+import { sessions } from '../../localDb/schema';
+import {
+ actCindyMakeTest,
+ cindyMakeTestController,
+ configureCindyMakeTestRuntime,
+} from '../testRuntime';
+import { makeTaskWorktreePath, makeSourceRoot } from '../sourcePaths';
+import { cindyMakeManager } from '../manager';
+const installer = {
+ commit: 'b'.repeat(40),
+ artifactDirectory: 'completion-output',
+ artifactName: 'Cindy.exe',
+ sha256: 'f'.repeat(64),
+};
+const dialect = new SQLiteSyncDialect();
+const client = {
+ drizzle: {
+ select: (columns?: Record<string, unknown>) => {
+ let table: unknown;
+ const query = {
+ from(value: unknown) {
+ table = value;
+ return query;
+ },
+ where() {
+ return query;
+ },
+ orderBy() {
+ return query;
+ },
+ async limit() {
+ h.query();
+ return table === sessions
+ ? [h.row]
+ : columns
+ ? h.laterUser
+ ? [{ id: 'later' }]
+ : []
+ : [h.card];
+ },
+ };
+ return query;
+ },
+ update: () => {
+ const query = {
+ set(values: { agentMeta: Parameters<typeof dialect.sqlToQuery>[0] }) {
+ h.write();
+ const params = dialect.sqlToQuery(values.agentMeta).params;
+ const next = JSON.parse(String(params[0]));
+ h.card.agentMeta = JSON.stringify({
+ ...JSON.parse(String(h.card.agentMeta)),
+ cindyMakeCompletion: next,
+ });
+ return query;
+ },
+ where() {
+ return query;
+ },
+ async returning() {
+ return [{ id: 'card' }];
+ },
+ };
+ return query;
+ },
+ },
+};
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.build.mockReset().mockResolvedValue(installer);
+ h.artifactPath.mockReset().mockResolvedValue(path.join(os.tmpdir(), 'installer.exe'));
+ h.current = true;
+ h.laterUser = false;
+ h.profile = path.join(os.tmpdir(), 'make-runtime-unit');
+ h.row = {
+ id: 'session',
+ source: 'cindy-make',
+ status: 'active',
+ workingDir: makeTaskWorktreePath(h.profile, 'run'),
+ remoteHostId: null,
+ };
+ h.card = {
+ id: 'card',
+ clientId: 'completion',
+ createdAt: '2026-09-17T08:00:00Z',
+ agentMeta: JSON.stringify({
+ otherMetadata: 'preserved',
+ cindyMakeCompletion: { reportedAt: 123, changedFiles: 2, commit: 'a'.repeat(40) },
+ }),
+ };
+ configureCindyMakeTestRuntime(() => false);
+});
+afterEach(() => cindyMakeTestController.stopAll());
+
+describe('Cindy Make test IPC ownership and persistence', () => {
+ it('only reads a valid completion on status requests', async () => {
+ expect(await actCindyMakeTest('session', 'completion', 'status')).toMatchObject({
+ reportedAt: 123,
+ });
+ expect(h.launch).not.toHaveBeenCalled();
+ expect(h.write).not.toHaveBeenCalled();
+ });
+ it.each([{}, ['start'], 'other'])(
+ 'rejects invalid action payload %j before touching data',
+ async (action) => {
+ await expect(actCindyMakeTest('session', 'completion', action)).rejects.toThrow();
+ expect(h.query).not.toHaveBeenCalled();
+ },
+ );
+ it.each([
+ { source: 'desktop' },
+ { remoteHostId: 'ssh-host' },
+ { status: 'deleted' },
+ { workingDir: os.tmpdir() },
+ ])('rejects an unavailable or nonlocal Make task %j', async (patch) => {
+ Object.assign(h.row, patch);
+ await expect(actCindyMakeTest('session', 'completion', 'start')).rejects.toThrow();
+ expect(h.launch).not.toHaveBeenCalled();
+ expect(h.write).not.toHaveBeenCalled();
+ });
+ it('rejects stale completions and newer user work instead of testing old code', async () => {
+ await expect(actCindyMakeTest('session', 'old-completion', 'start')).rejects.toThrow();
+ h.laterUser = true;
+ await expect(actCindyMakeTest('session', 'completion', 'start')).rejects.toThrow();
+ expect(h.launch).not.toHaveBeenCalled();
+ expect(h.write).not.toHaveBeenCalled();
+ });
+ it('persists continue while retaining verified facts and unrelated agent metadata', async () => {
+ const result = await actCindyMakeTest('session', 'completion', 'continue');
+ expect(result.continuedAt).toEqual(expect.any(Number));
+ expect(result.changedFiles).toBe(2);
+ expect(JSON.parse(String(h.card.agentMeta)).otherMetadata).toBe('preserved');
+ expect(h.broadcast).toHaveBeenCalledWith('session', 'completion', expect.any(Object));
+ expect(h.launch).not.toHaveBeenCalled();
+ });
+ it('persists personal build progress and opens only the verified recorded output', async () => {
+ h.build.mockImplementationOnce(async (_context, _node, _env, _region, _signal, publish) => {
+ await publish({ status: 'packaging' });
+ return installer;
+ });
+ await actCindyMakeTest('session', 'completion', 'build');
+ await vi.waitFor(() =>
+ expect(JSON.parse(String(h.card.agentMeta)).cindyMakeCompletion.personal).toEqual({
+ status: 'ready',
+ ...installer,
+ generatedAt: expect.any(Number),
+ }),
+ );
+ expect(h.rememberOriginal).toHaveBeenCalledWith(process.execPath);
+ expect(h.build.mock.calls[0][0].profile.userData).toBe(h.profile);
+ await actCindyMakeTest('session', 'completion', 'open-build');
+ expect(h.artifactPath).toHaveBeenCalledWith(h.profile, 'completion', {
+ status: 'ready',
+ ...installer,
+ generatedAt: expect.any(Number),
+ });
+ expect(h.showItem).toHaveBeenCalledWith(path.join(os.tmpdir(), 'installer.exe'));
+ expect(JSON.parse(String(h.card.agentMeta)).otherMetadata).toBe('preserved');
+ expect(h.launch).not.toHaveBeenCalled();
+ h.artifactPath.mockRejectedValueOnce(new Error('installer moved'));
+ await expect(actCindyMakeTest('session', 'completion', 'open-build')).rejects.toThrow();
+ expect(JSON.parse(String(h.card.agentMeta)).cindyMakeCompletion.personal).toEqual({
+ status: 'failed',
+ error: 'unavailable',
+ });
+ expect(h.showItem).toHaveBeenCalledOnce();
+ });
+ it('cancels a queued personal build promptly without running it after the queue is released', async () => {
+ let release!: () => void;
+ const queued = cindyMakeManager.withProject(
+ makeSourceRoot(h.profile) + ':personal-build',
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ }),
+ );
+ try {
+ await actCindyMakeTest('session', 'completion', 'build');
+ await actCindyMakeTest('session', 'completion', 'continue');
+ await vi.waitFor(() =>
+ expect(cindyMakeTestController.isUsingWorkspace(String(h.row.workingDir))).toBe(false),
+ );
+ expect(h.build).not.toHaveBeenCalled();
+ } finally {
+ release();
+ await queued;
+ // Wait behind the cancelled job to prove it cannot run later.
+ await cindyMakeManager.withProject(
+ makeSourceRoot(h.profile) + ':personal-build',
+ async () => {},
+ );
+ }
+ expect(h.build).not.toHaveBeenCalled();
+ });
+ it('retains active build ownership until cancelled cleanup is done', async () => {
+ let finishCleanup!: () => void;
+ let cancelled = false;
+ h.build.mockImplementationOnce(async (_context, _node, _env, _region, signal: AbortSignal) => {
+ await new Promise<void>((resolve) =>
+ signal.addEventListener(
+ 'abort',
+ () => {
+ cancelled = true;
+ resolve();
+ },
+ { once: true },
+ ),
+ );
+ await new Promise<void>((resolve) => {
+ finishCleanup = resolve;
+ });
+ throw new Error('cancelled');
+ });
+ await actCindyMakeTest('session', 'completion', 'build');
+ await vi.waitFor(() => expect(h.build).toHaveBeenCalledOnce());
+ await actCindyMakeTest('session', 'completion', 'continue');
+ expect(cancelled).toBe(true);
+ expect(cindyMakeTestController.isUsingWorkspace(String(h.row.workingDir))).toBe(true);
+ finishCleanup();
+ await vi.waitFor(() =>
+ expect(cindyMakeTestController.isUsingWorkspace(String(h.row.workingDir))).toBe(false),
+ );
+ expect(JSON.parse(String(h.card.agentMeta)).cindyMakeCompletion).toMatchObject({
+ continuedAt: expect.any(Number),
+ personal: { status: 'failed', error: 'interrupted' },
+ });
+ });
+ it('rejects personal builds for superseded completions and while the task is running', async () => {
+ h.laterUser = true;
+ await expect(actCindyMakeTest('session', 'completion', 'build')).rejects.toThrow();
+ h.laterUser = false;
+ configureCindyMakeTestRuntime(() => true);
+ await actCindyMakeTest('session', 'completion', 'build');
+ await vi.waitFor(() =>
+ expect(JSON.parse(String(h.card.agentMeta)).cindyMakeCompletion.personal).toEqual({
+ status: 'failed',
+ error: 'unavailable',
+ }),
+ );
+ expect(h.build).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts
new file mode 100644
index 0000000000..9932306f78
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts
@@ -0,0 +1,257 @@
+import os from 'node:os';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { expect, it } from 'vitest';
+import {
+ applyUpstreamMerge,
+ prepareUpstreamMerge,
+ mergeWorktree,
+ mergeBranch,
+} from '../upstreamMerge';
+import { PERSONAL_UPSTREAM_REF } from '../sourceContent';
+import { makeSourceCheckoutPath } from '../sourcePaths';
+import { runSourceGit } from '../sourceGit';
+import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
+
+async function fixture(conflict: boolean) {
+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-upstream-merge-'));
+ const source = makeSourceCheckoutPath(userData);
+ const remote = path.join(userData, 'official');
+ const env = {
+ PATH: process.env.PATH,
+ SystemRoot: process.env.SystemRoot,
+ GIT_CONFIG_GLOBAL: path.join(userData, 'gitconfig'),
+ GIT_CONFIG_NOSYSTEM: '1',
+ };
+ const run = (args: string[], cwd: string, indexFile?: string) =>
+ runSourceGit(
+ { ...env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args,
+ cwd,
+ AbortSignal.timeout(30_000),
+ );
+ const git = (args: string[], cwd: string, indexFile?: string) =>
+ run(
+ args.map((arg) => (arg === 'https://github.com/makecindy/cindy.git' ? remote : arg)),
+ cwd,
+ indexFile,
+ );
+ const commit = async (cwd: string, message: string) => {
+ await git(['add', '.'], cwd);
+ await git(
+ [
+ '-c',
+ 'user.name=Test',
+ '-c',
+ '-c',
+ 'commit.gpgSign=false',
+ 'commit',
+ '-s',
+ '-m',
+ message,
+ ],
+ cwd,
+ );
+ };
+ const clean = () => rm(userData, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
+ try {
+ await writeFile(env.GIT_CONFIG_GLOBAL, '');
+ await mkdir(remote);
+ await mkdir(path.dirname(source), { recursive: true });
+ await git(['init', '--initial-branch=main'], remote);
+ await writeFile(path.join(remote, 'feature.txt'), 'base\n');
+ await commit(remote, 'base');
+ await git(['clone', remote, source], userData);
+ await git(['checkout', '-b', 'cindy-personal'], source);
+ await writeFile(path.join(source, 'feature.txt'), 'local feature\n');
+
+ const baselineCommit = (await git(['rev-parse', 'HEAD'], source)).trim();
+ await writeFile(path.join(remote, conflict ? 'feature.txt' : 'upstream.txt'), 'upstream fix\n');
+ await commit(remote, 'official update');
+ const upstreamCommit = (await git(['rev-parse', 'HEAD'], remote)).trim();
+ const state: CindyMakeMergeState = {
+ id: randomUUID(),
+ status: 'fetching',
+ ref: 'main',
+ upstreamCommit,
+ };
+ return { userData, source, remote, git, commit, clean, state, baselineCommit };
+ } catch (error) {
+ await clean();
+ throw error;
+ }
+}
+
+it('rebases locally committed personal changes onto the latest official main and leaves both checkouts clean', async () => {
+ const h = await fixture(false);
+ try {
+ const result = await prepareUpstreamMerge(h.userData, h.state, h.git, async () => {});
+ expect(result.status).toBe('merged');
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(result.commit);
+ expect((await h.git(['rev-parse', 'main'], h.source)).trim()).toBe(h.state.upstreamCommit);
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('local feature\n');
+ expect(await readFile(path.join(h.source, 'upstream.txt'), 'utf8')).toBe('upstream fix\n');
+ expect(result.commit).not.toBe(h.baselineCommit);
+ expect(await h.git(['merge-base', 'main', 'cindy-personal'], h.source)).toBe(
+ h.state.upstreamCommit,
+ );
+ expect(await h.git(['diff', '--name-only', 'main..cindy-personal'], h.source)).toBe(
+ 'feature.txt',
+ );
+ expect(await h.git(['rev-list', 'main..cindy-personal', '--count'], h.source)).toBe('1');
+ expect(await h.git(['rev-list', 'main..cindy-personal', '--merges'], h.source)).toBe('');
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+ expect(await h.git(['log', '-1', '--format=%B'], h.source)).toContain(
+ 'Signed-off-by: Cindy Make <[email protected]>',
+ );
+ expect(
+ await h.git(['rev-parse', 'refs/cindy-make/backups/' + h.state.id + '/personal'], h.source),
+ ).toBe(result.baselineCommit);
+ } finally {
+ await h.clean();
+ }
+}, 30_000);
+
+it('moves a personal branch with no custom changes exactly to the official commit without an empty commit', async () => {
+ const h = await fixture(false);
+ try {
+ await writeFile(path.join(h.source, 'feature.txt'), 'base\n');
+ const result = await prepareUpstreamMerge(h.userData, h.state, h.git, async () => {});
+ expect(result.status).toBe('merged');
+ expect(result.commit).toBe(h.state.upstreamCommit);
+ expect(await h.git(['rev-parse', 'main'], h.source)).toBe(h.state.upstreamCommit);
+ expect(await h.git(['rev-parse', 'cindy-personal'], h.source)).toBe(h.state.upstreamCommit);
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+ expect(await readFile(path.join(h.source, 'upstream.txt'), 'utf8')).toBe('upstream fix\n');
+ } finally {
+ await h.clean();
+ }
+}, 30_000);
+
+it('isolates conflicts, preserves personal files, and applies a resolved merge idempotently', async () => {
+ const h = await fixture(true);
+ try {
+ const result = await prepareUpstreamMerge(h.userData, h.state, h.git, async () => {});
+ expect(result.status).toBe('conflict');
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(result.baselineCommit);
+ expect(await h.git(['rev-parse', 'main'], h.source)).toBe(h.state.upstreamCommit);
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('local feature\n');
+ const worktree = mergeWorktree(h.userData, h.state.id);
+ expect(await h.git(['diff', '--name-only', '--diff-filter=U'], worktree)).toContain(
+ 'feature.txt',
+ );
+ await expect(applyUpstreamMerge(h.userData, result, h.git)).rejects.toMatchObject({
+ code: 'dirty',
+ });
+ await writeFile(path.join(worktree, 'feature.txt'), 'local feature\nupstream fix\n');
+ await h.git(['add', '.'], worktree);
+ const applied = await applyUpstreamMerge(h.userData, result, h.git);
+ expect(applied.status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ 'local feature\nupstream fix\n',
+ );
+ expect(await applyUpstreamMerge(h.userData, result, h.git)).toEqual(applied);
+ expect(await h.git(['merge-base', 'main', 'cindy-personal'], h.source)).toBe(
+ h.state.upstreamCommit,
+ );
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+ } finally {
+ await h.clean();
+ }
+}, 30_000);
+
+it('preserves personal work added during resolution and refuses to overwrite concurrent uncommitted edits', async () => {
+ const h = await fixture(true);
+ try {
+ const result = await prepareUpstreamMerge(h.userData, h.state, h.git, async () => {});
+ const worktree = mergeWorktree(h.userData, h.state.id);
+ await writeFile(path.join(worktree, 'feature.txt'), 'local feature\nupstream fix\n');
+ await h.git(['add', '.'], worktree);
+ await writeFile(path.join(h.source, 'new-personal.txt'), 'new feature\n');
+
+ await expect(applyUpstreamMerge(h.userData, result, h.git)).rejects.toMatchObject({
+ code: 'baselineChanged',
+ });
+ expect(await readFile(path.join(h.source, 'new-personal.txt'), 'utf8')).toBe('new feature\n');
+ } finally {
+ await h.clean();
+ }
+}, 30_000);
+
+it('converts a retained legacy MERGE_HEAD into a local personal commit on the official base without losing original history', async () => {
+ const h = await fixture(true);
+ try {
+ // Represent an existing installation whose personal features already have history.
+ await h.commit(h.source, 'legacy personal feature');
+ const baselineCommit = await h.git(['rev-parse', 'HEAD'], h.source);
+ await h.git(['fetch', '--no-tags', h.remote, h.state.upstreamCommit], h.source);
+ const state = { ...h.state, baselineCommit, hasWorkspace: true, status: 'conflict' as const };
+ const worktree = mergeWorktree(h.userData, h.state.id);
+ await mkdir(path.dirname(worktree), { recursive: true });
+ await h.git(
+ ['worktree', 'add', '-b', mergeBranch(state.id), worktree, baselineCommit],
+ h.source,
+ );
+ const mergeHead = await h.git(
+ ['rev-parse', '--path-format=absolute', '--git-path', 'MERGE_HEAD'],
+ worktree,
+ );
+ await writeFile(mergeHead.trim(), h.state.upstreamCommit + '\n');
+ await writeFile(path.join(worktree, 'feature.txt'), 'local feature\nupstream fix\n');
+ await h.git(['add', '.'], worktree);
+ const count = await h.git(['rev-list', '--all', h.state.upstreamCommit, '--count'], h.source);
+ const result = await applyUpstreamMerge(h.userData, state, h.git);
+ expect(result.status).toBe('merged');
+ expect(await h.git(['rev-parse', 'HEAD'], h.source)).toBe(result.commit);
+ expect(Number(await h.git(['rev-list', '--all', '--count'], h.source))).toBe(Number(count) + 1);
+ expect(await h.git(['merge-base', h.state.upstreamCommit, 'HEAD'], h.source)).toBe(
+ h.state.upstreamCommit,
+ );
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ 'local feature\nupstream fix\n',
+ );
+ expect(await applyUpstreamMerge(h.userData, state, h.git)).toEqual(result);
+ } finally {
+ await h.clean();
+ }
+}, 30_000);
+
+it('migrates old applied-but-uncommitted official files and keeps only personal commits through subsequent updates', async () => {
+ const h = await fixture(false);
+ try {
+ await h.git(['fetch', '--no-tags', h.remote, h.state.upstreamCommit], h.source);
+ await h.git(['branch', '--force', 'main', h.state.upstreamCommit], h.source);
+ await writeFile(path.join(h.source, 'upstream.txt'), 'upstream fix\n');
+ await h.git(['update-ref', PERSONAL_UPSTREAM_REF, h.state.upstreamCommit], h.source);
+ expect(await h.git(['status', '--porcelain'], h.source)).toContain('upstream.txt');
+ const first = await prepareUpstreamMerge(h.userData, h.state, h.git, async () => {});
+ expect(first.status).toBe('merged');
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+ expect(await h.git(['diff', '--name-only', 'main..cindy-personal'], h.source)).toBe(
+ 'feature.txt',
+ );
+ expect(await h.git(['rev-list', 'main..cindy-personal', '--count'], h.source)).toBe('1');
+ await writeFile(path.join(h.remote, 'another.txt'), 'next official fix');
+ await h.commit(h.remote, 'another official update');
+ const upstreamCommit = await h.git(['rev-parse', 'HEAD'], h.remote);
+ const second = await prepareUpstreamMerge(
+ h.userData,
+ { ...h.state, id: randomUUID(), upstreamCommit },
+ h.git,
+ async () => {},
+ );
+ expect(await h.git(['merge-base', 'main', 'cindy-personal'], h.source)).toBe(upstreamCommit);
+ expect(await h.git(['diff', '--name-only', 'main..cindy-personal'], h.source)).toBe(
+ 'feature.txt',
+ );
+ expect(await h.git(['rev-list', 'main..cindy-personal', '--count'], h.source)).toBe('1');
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+ expect(await h.git(['rev-parse', 'HEAD'], h.source)).toBe(second.commit);
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.test.ts
new file mode 100644
index 0000000000..4804c10e39
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.test.ts
@@ -0,0 +1,116 @@
+import path from 'node:path';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { applyUpstreamMerge, prepareUpstreamMerge, type MergeGit } from '../upstreamMerge';
+import { makeSourceCheckoutPath } from '../sourcePaths';
+import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
+vi.mock('../sourceContent', () => ({
+ snapshotContent: async (git: MergeGit, cwd: string) => {
+ if ((await git(['ls-files', '--unmerged'], cwd)).trim())
+ throw Object.assign(new Error('conflicts'), { code: 'dirty' });
+ return 'e'.repeat(40);
+ },
+ populateContent: async () => {},
+ applyContent: async (git: MergeGit, cwd: string) => git(['apply-files'], cwd),
+ PERSONAL_UPSTREAM_REF: 'refs/cindy-make/personal-upstream',
+}));
+vi.mock('node:fs/promises', () => ({
+ mkdir: vi.fn(async () => {}),
+ realpath: vi.fn(async (p: string) => p),
+ lstat: vi.fn(async () => {
+ throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ }),
+}));
+vi.mock('../localHistory', async (load) => ({
+ ...(await load<typeof import('../localHistory')>()),
+ commitPersonalFiles: async (git: MergeGit, cwd: string) => ({
+ commit: await git(['rev-parse', 'HEAD'], cwd),
+ tree: 'e'.repeat(40),
+ }),
+}));
+const userData = path.resolve('fake-user-data');
+const state: CindyMakeMergeState = {
+ id: '12345678-1234-1234-1234-123456789abc',
+ status: 'merging',
+ ref: 'main',
+ upstreamCommit: 'a'.repeat(40),
+ baselineCommit: 'b'.repeat(40),
+ hasWorkspace: true,
+};
+let git: ReturnType<typeof vi.fn<MergeGit>>;
+const source = makeSourceCheckoutPath(userData);
+beforeEach(() => {
+ git = vi.fn(async (args, cwd) => {
+ const command = args.join(' ');
+ if (command === 'rev-parse --path-format=absolute --git-common-dir')
+ return path.join(source, '.git');
+ if (command === 'rev-parse --show-toplevel') return source;
+ if (command === 'branch --show-current')
+ return cwd === source ? 'cindy-personal' : `cindy-merge/${state.id}`;
+ if (command === 'rev-parse HEAD')
+ return cwd === source ? state.baselineCommit! : 'c'.repeat(40);
+ if (args[0] === 'rev-parse' && args[1]?.endsWith('^{tree}')) return 'e'.repeat(40);
+ if (command === 'rev-parse FETCH_HEAD^{commit}') return state.upstreamCommit;
+ if (command === 'rev-parse --verify refs/cindy-make/personal-upstream^{commit}')
+ return state.baselineCommit!;
+ return '';
+ });
+});
+describe('upstream merge protection', () => {
+ it('rejects invalid operation identities before mutating refs', async () => {
+ await expect(
+ prepareUpstreamMerge(userData, { ...state, id: '../bad' }, git, async () => {}),
+ ).rejects.toMatchObject({ code: 'unavailable' });
+ expect(git).not.toHaveBeenCalled();
+ });
+ it('refuses unresolved personal conflicts before fetch or backup', async () => {
+ const original = git.getMockImplementation()!;
+ git.mockImplementation(async (args, cwd) =>
+ args[0] === 'ls-files' ? 'unmerged file' : original(args, cwd),
+ );
+ await expect(prepareUpstreamMerge(userData, state, git, async () => {})).rejects.toMatchObject({
+ code: 'dirty',
+ });
+ expect(
+ git.mock.calls.some(([args]) => ['fetch', 'update-ref', 'worktree'].includes(args[0])),
+ ).toBe(false);
+ });
+ it('preserves a customized main instead of moving it backwards', async () => {
+ const original = git.getMockImplementation()!;
+ git.mockImplementation(async (args, cwd) => {
+ if (args.join(' ') === 'rev-parse --verify refs/heads/main^{commit}') return 'd'.repeat(40);
+ if (args[0] === 'merge-base') throw new Error('not ancestor');
+ return original(args, cwd);
+ });
+ await expect(prepareUpstreamMerge(userData, state, git, async () => {})).rejects.toMatchObject({
+ code: 'localMain',
+ });
+ expect(git.mock.calls.some(([args]) => args.includes('--force'))).toBe(false);
+ });
+ it('does not call a generic merge failure a conflict', async () => {
+ const original = git.getMockImplementation()!;
+ git.mockImplementation(async (args, cwd) => {
+ if (args.includes('rebase')) throw new Error('index.lock');
+ return original(args, cwd);
+ });
+ await expect(prepareUpstreamMerge(userData, state, git, async () => {})).rejects.toThrow(
+ 'index.lock',
+ );
+ });
+ it('will not apply a candidate that dropped either pinned history', async () => {
+ const original = git.getMockImplementation()!;
+ git.mockImplementation(async (args, cwd) => {
+ if (args[0] === 'merge-base' && args[2] === state.upstreamCommit)
+ throw new Error('missing upstream');
+ return original(args, cwd);
+ });
+ await expect(applyUpstreamMerge(userData, state, git)).rejects.toThrow('missing upstream');
+ expect(git.mock.calls.some(([args]) => args.includes('--ff-only'))).toBe(false);
+ });
+ it('rechecks the task/account guard immediately before applying', async () => {
+ const current = vi.fn().mockReturnValueOnce(true).mockReturnValue(false);
+ await expect(applyUpstreamMerge(userData, state, git, current)).rejects.toMatchObject({
+ code: 'busy',
+ });
+ expect(git.mock.calls.some(([args]) => args.includes('--ff-only'))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts
new file mode 100644
index 0000000000..4f22cea487
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts
@@ -0,0 +1,244 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ UpstreamMergeController,
+ parseSavedUpstreamMerge,
+ type SavedUpstreamMerge,
+ type UpstreamMergeDependencies,
+} from '../upstreamMergeController';
+import { mergeError } from '../upstreamMerge';
+import type { CindyMakeMergeState, MakeFeatureMergePlan } from '../../../shared/cindyMakeMerge';
+
+const candidate: CindyMakeMergeState = {
+ id: '12345678-1234-1234-1234-123456789abc',
+ status: 'conflict',
+ ref: 'main',
+ upstreamCommit: 'a'.repeat(40),
+ baselineCommit: 'b'.repeat(40),
+ hasWorkspace: true,
+};
+function harness(initial?: SavedUpstreamMerge) {
+ let saved = initial ? structuredClone(initial) : undefined;
+ let owner = 'alice';
+ let workspace = !!initial?.state.hasWorkspace;
+ const deps: UpstreamMergeDependencies = {
+ read: () => saved,
+ write: vi.fn((next) => {
+ saved = structuredClone(next);
+ }),
+ publish: vi.fn(),
+ owner: () => owner,
+ hasWorkspace: () => workspace,
+ exclusive: async (run) => run(),
+ latest: vi.fn(async () => ({ ref: 'main', commit: 'a'.repeat(40) })),
+ prepare: vi.fn(async (state, publish) => {
+ workspace = true;
+ await publish({
+ ...state,
+ hasWorkspace: true,
+ baselineCommit: 'b'.repeat(40),
+ status: 'merging',
+ });
+ return { ...state, hasWorkspace: true, status: 'merged', commit: 'c'.repeat(40) };
+ }),
+ apply: vi.fn(async (state) => ({ ...state, status: 'merged', commit: 'c'.repeat(40) })),
+ session: vi.fn(async (state, _options, bind) => {
+ const id = state.sessionId ?? 'merge-session';
+ bind(id);
+ return id;
+ }),
+ running: vi.fn(() => false),
+ refresh: vi.fn(async () => {}),
+ cleanup: vi.fn(async () => {}),
+ };
+ const controller = new UpstreamMergeController(deps);
+ return {
+ controller,
+ deps,
+ saved: () => saved,
+ setOwner: (next: string) => {
+ owner = next;
+ },
+ };
+}
+describe('upstream merge lifecycle', () => {
+ it('keeps Git adoption recoverable until its durable feature receipt has been saved', async () => {
+ const h = harness();
+ const plan: MakeFeatureMergePlan = {
+ runId: 'aaaa',
+ taskSessionId: 'original-task',
+ action: 'revert',
+ taskTree: 'e'.repeat(40),
+ nextStep: 0,
+ steps: [{ before: 'a'.repeat(40), after: 'b'.repeat(40) }],
+ };
+ h.deps.hasWorkspace = () => true;
+ h.deps.prepareFeature = vi.fn(async (state) => ({
+ ...state,
+ ...candidate,
+ status: 'merged',
+ feature: { ...plan, nextStep: 1 },
+ commit: 'c'.repeat(40),
+ tree: 'd'.repeat(40),
+ baselineTree: 'e'.repeat(40),
+ }));
+ h.deps.applied = vi.fn(async () => {
+ throw new Error('disk unavailable');
+ });
+ expect(await h.controller.feature(plan)).toMatchObject({
+ status: 'failed',
+ commit: 'c'.repeat(40),
+ hasWorkspace: true,
+ });
+ expect(h.deps.cleanup).not.toHaveBeenCalled();
+ const resumed = harness(h.saved());
+ resumed.deps.applied = vi.fn(async () => {});
+ expect(await resumed.controller.resolve()).toMatchObject({ status: 'merged' });
+ expect(resumed.deps.applied).toHaveBeenCalledOnce();
+ expect(resumed.deps.session).not.toHaveBeenCalled();
+ expect(resumed.deps.cleanup).toHaveBeenCalledOnce();
+ });
+ it('uses the existing dedicated-task lifecycle for feature conflicts and never starts a second operation beside one', async () => {
+ const h = harness();
+ const plan: MakeFeatureMergePlan = {
+ runId: 'aaaa',
+ taskSessionId: 'original-task',
+ action: 'revert',
+ taskTree: 'e'.repeat(40),
+ nextStep: 0,
+ steps: [{ before: 'a'.repeat(40), after: 'b'.repeat(40) }],
+ };
+ h.deps.prepareFeature = vi.fn(async (state) => ({
+ ...state,
+ ...candidate,
+ feature: { ...plan, awaitingResolution: true },
+ }));
+ expect(await h.controller.feature(plan)).toMatchObject({
+ status: 'resolving',
+ sessionId: 'merge-session',
+ });
+ await expect(h.controller.feature(plan)).rejects.toMatchObject({ code: 'busy' });
+ expect(h.deps.session).toHaveBeenCalledOnce();
+ expect(h.deps.prepareFeature).toHaveBeenCalledOnce();
+ });
+ it('rejects corrupt recovery data rather than treating it as an empty operation', () => {
+ for (const raw of [
+ '{',
+ '{}',
+ JSON.stringify({ state: { ...candidate, id: '../source' } }),
+ JSON.stringify({ state: { ...candidate, sessionId: 'unowned-task' } }),
+ ]) {
+ expect(() => parseSavedUpstreamMerge(raw, '/user-data')).toThrow();
+ }
+ expect(parseSavedUpstreamMerge(JSON.stringify({ state: candidate }), '/user-data')).toEqual({
+ state: candidate,
+ });
+ });
+ it('automatically applies a clean update and never creates an agent task', async () => {
+ const h = harness();
+ expect(await h.controller.update()).toMatchObject({ status: 'merged' });
+ expect(h.deps.session).not.toHaveBeenCalled();
+ expect(h.saved()?.state.commit).toBe('c'.repeat(40));
+ expect(h.deps.cleanup).toHaveBeenCalledOnce();
+ });
+ it('deduplicates simultaneous updates and opens one independent conflict task with the chosen model', async () => {
+ const h = harness();
+ h.deps.prepare = vi.fn(async (state) => ({ ...state, ...candidate }));
+ const options = { agentKind: 'codex' as const, model: 'test-model' };
+ const results = await Promise.all([h.controller.update(options), h.controller.update(options)]);
+ expect(h.deps.prepare).toHaveBeenCalledOnce();
+ expect(results.map((r) => r?.status)).toEqual(['resolving', 'resolving']);
+ expect(h.deps.session).toHaveBeenCalledOnce();
+ expect(vi.mocked(h.deps.session).mock.calls[0][1]).toEqual(options);
+ await h.controller.update();
+ expect(h.deps.prepare).toHaveBeenCalledOnce();
+ expect(h.deps.session).toHaveBeenCalledOnce();
+ expect(h.saved()).toMatchObject({
+ sessionOwner: 'alice',
+ state: { sessionId: 'merge-session', status: 'resolving' },
+ });
+ });
+ it('retains a conflict without starting a task for an account that changed during the update', async () => {
+ const h = harness();
+ h.deps.prepare = vi.fn(async (state) => {
+ h.setOwner('bob');
+ return { ...state, ...candidate };
+ });
+ expect(await h.controller.update()).toMatchObject({ status: 'conflict', hasWorkspace: true });
+ expect(h.deps.session).not.toHaveBeenCalled();
+ expect(h.saved()?.state.sessionId).toBeUndefined();
+ expect(h.deps.cleanup).not.toHaveBeenCalled();
+ });
+ it('keeps the bound task identity across a failed dispatch and restart', async () => {
+ const h = harness({ state: candidate });
+ h.deps.session = vi.fn(async (_state, _options, bind) => {
+ bind('same-task');
+ throw mergeError('startFailed');
+ });
+ await h.controller.resolve();
+ expect(h.saved()).toMatchObject({ state: { sessionId: 'same-task', status: 'failed' } });
+ const reopened = harness(h.saved());
+ await reopened.controller.resolve();
+ expect(reopened.saved()?.state.sessionId).toBe('same-task');
+ });
+ it('never resumes an interrupted Git write at startup', () => {
+ const h = harness({ state: { ...candidate, status: 'merging' } });
+ expect(h.controller.status()).toMatchObject({
+ status: 'failed',
+ error: 'interrupted',
+ hasWorkspace: true,
+ });
+ expect(h.deps.prepare).not.toHaveBeenCalled();
+ expect(h.deps.apply).not.toHaveBeenCalled();
+ });
+ it('does not expose or dispatch another account’s task', async () => {
+ const h = harness({
+ state: { ...candidate, sessionId: 'private-task' },
+ sessionOwner: 'alice',
+ });
+ h.setOwner('bob');
+ expect(h.controller.status()).toMatchObject({
+ sessionId: undefined,
+ ownedByAnotherAccount: true,
+ });
+ await expect(h.controller.resolve()).rejects.toMatchObject({ code: 'busy' });
+ await h.controller.finish('private-task');
+ expect(h.deps.session).not.toHaveBeenCalled();
+ expect(h.deps.apply).not.toHaveBeenCalled();
+ });
+ it('applies only the bound idle session and retains a failed candidate', async () => {
+ const h = harness({
+ state: { ...candidate, sessionId: 'task', status: 'resolving' },
+ sessionOwner: 'alice',
+ });
+ await h.controller.finish('ordinary-task');
+ expect(h.deps.apply).not.toHaveBeenCalled();
+ h.deps.running = () => true;
+ await h.controller.finish('task');
+ expect(h.deps.apply).not.toHaveBeenCalled();
+ h.deps.running = () => false;
+ h.deps.apply = vi.fn(async () => {
+ throw mergeError('baselineChanged');
+ });
+ await h.controller.finish('task');
+ expect(h.saved()?.state).toMatchObject({
+ status: 'failed',
+ error: 'baselineChanged',
+ hasWorkspace: true,
+ });
+ h.deps.apply = vi.fn(async (state) => ({ ...state, status: 'merged' }));
+ await h.controller.finish('task');
+ expect(h.saved()?.state.status).toBe('merged');
+ });
+ it('allows retry after a preflight failure with no workspace and does not undo merge success on refresh failure', async () => {
+ const h = harness();
+ h.deps.latest = vi
+ .fn()
+ .mockRejectedValueOnce(mergeError('unavailable'))
+ .mockResolvedValue({ ref: 'main', commit: 'a'.repeat(40) });
+ expect(await h.controller.update()).toMatchObject({ status: 'failed', hasWorkspace: false });
+ h.deps.refresh = async () => {
+ throw new Error('read failed');
+ };
+ expect(await h.controller.update()).toMatchObject({ status: 'merged' });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeSession.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeSession.test.ts
new file mode 100644
index 0000000000..a61f5b3fde
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeSession.test.ts
@@ -0,0 +1,133 @@
+import path from 'node:path';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { ensureUpstreamMergeSession, assertUpstreamMergeSession } from '../upstreamMergeSession';
+import { mergeWorktree } from '../upstreamMerge';
+import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
+import { normalizeWorkingDirForStorage } from '../../../shared/workingDir';
+
+const h = vi.hoisted(() => {
+ const reads: unknown[][] = [];
+ const insert = vi.fn(async (_row: unknown) => {});
+ const db = {
+ select: () => ({ from: () => ({ where: () => ({ limit: async () => reads.shift() ?? [] }) }) }),
+ insert: () => ({ values: insert }),
+ };
+ return {
+ reads,
+ insert,
+ client: { drizzle: db },
+ dispatch: vi.fn(async (..._args: unknown[]) => {}),
+ emit: vi.fn(),
+ current: true,
+ };
+});
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => h.client }));
+vi.mock('../taskRuntime.js', () => ({ dispatchCindyMakeMergeTask: h.dispatch }));
+vi.mock('../../localDb/ipc/sessionCreatedBroadcast.js', () => ({ emitSessionCreated: h.emit }));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({ ownerScopeKey: 'alice' }),
+ isDataOwnerBroadcastScopeCurrent: () => h.current,
+}));
+vi.mock('../../sessionIds.js', () => ({ createBusinessSessionId: () => 'new-merge-task' }));
+vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
+const userData = path.resolve('fake-data');
+const state: CindyMakeMergeState = {
+ id: '12345678-1234-1234-1234-123456789abc',
+ status: 'conflict',
+ ref: 'main',
+ upstreamCommit: 'a'.repeat(40),
+ baselineCommit: 'b'.repeat(40),
+ hasWorkspace: true,
+};
+const row = {
+ id: 'old-task',
+ source: 'cindy-make-merge',
+ status: 'active',
+ workingDir: mergeWorktree(userData, state.id),
+ remoteHostId: null,
+ clearedAt: null,
+ agentKind: 'codex',
+};
+beforeEach(() => {
+ h.reads.length = 0;
+ h.current = true;
+ vi.clearAllMocks();
+ h.insert.mockImplementation(async () => {});
+});
+describe('dedicated upstream merge session', () => {
+ it('creates the new source, binds before INSERT, preserves preferences, and sends a trusted first request', async () => {
+ const bind = vi.fn();
+ await ensureUpstreamMergeSession(
+ userData,
+ state,
+ { agentKind: 'codex', model: 'test-model' },
+ bind,
+ () => true,
+ );
+ expect(h.insert).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: 'cindy-make-merge',
+ workingDir: normalizeWorkingDirForStorage(row.workingDir),
+ model: 'test-model',
+ }),
+ );
+ expect(bind.mock.invocationCallOrder[0]).toBeLessThan(h.insert.mock.invocationCallOrder[0]);
+ expect(h.dispatch).toHaveBeenCalledOnce();
+ expect(h.dispatch.mock.calls[0][1]).toContain('确保不丢失本地已有功能');
+ expect(h.dispatch.mock.calls[0][1]).toContain(state.upstreamCommit);
+ });
+ it('reopens an existing task without dispatching the first message twice', async () => {
+ h.reads.push([row], [{ id: 'first-message' }]);
+ expect(
+ await ensureUpstreamMergeSession(
+ userData,
+ { ...state, sessionId: row.id },
+ undefined,
+ vi.fn(),
+ () => true,
+ ),
+ ).toBe(row.id);
+ expect(h.insert).not.toHaveBeenCalled();
+ expect(h.dispatch).not.toHaveBeenCalled();
+ });
+ it('keeps the workspace and creates a new task only after explicitly reopening removed work', async () => {
+ h.reads.push([{ ...row, status: 'deleted' }], []);
+ expect(
+ await ensureUpstreamMergeSession(
+ userData,
+ { ...state, sessionId: row.id },
+ undefined,
+ vi.fn(),
+ () => true,
+ ),
+ ).toBe('new-merge-task');
+ expect(h.insert).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workingDir: normalizeWorkingDirForStorage(row.workingDir),
+ source: 'cindy-make-merge',
+ }),
+ );
+ });
+ it('never sends into an account switched during creation', async () => {
+ h.insert.mockImplementation(async () => {
+ h.current = false;
+ });
+ await expect(
+ ensureUpstreamMergeSession(userData, state, undefined, vi.fn(), () => true),
+ ).rejects.toMatchObject({ code: 'busy' });
+ expect(h.dispatch).not.toHaveBeenCalled();
+ expect(h.emit).not.toHaveBeenCalled();
+ });
+ it('does not apply results from a deleted or repurposed task', async () => {
+ for (const changed of [
+ { ...row, status: 'deleted' },
+ { ...row, source: 'cindy-make' },
+ { ...row, workingDir: '/unrelated' },
+ ]) {
+ h.reads.push([changed]);
+ await expect(
+ assertUpstreamMergeSession(userData, { ...state, sessionId: row.id }),
+ ).rejects.toMatchObject({ code: 'unavailable' });
+ }
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/versionLaunchArguments.test.ts b/apps/desktop/src/main/cindy-make/__tests__/versionLaunchArguments.test.ts
new file mode 100644
index 0000000000..1a9db8a86e
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/versionLaunchArguments.test.ts
@@ -0,0 +1,38 @@
+import path from 'node:path';
+import os from 'node:os';
+import { describe, expect, it } from 'vitest';
+import { versionEntryArguments } from '../versionLaunchArguments';
+describe('version handoff entry arguments', () => {
+ it('keeps existing links and file entry points without forwarding debug or profile flags', () => {
+ const folder = path.join(os.tmpdir(), 'folder with spaces');
+ const file = path.join(os.tmpdir(), 'sample.cindy');
+ expect(
+ versionEntryArguments([
+ '--inspect=1234',
+ '--user-data-dir=/other',
+ '--require=private',
+ 'cindy://session/test',
+ 'xdt-maker://project/example',
+ '--open-folder',
+ folder,
+ file,
+ ]),
+ ).toEqual([
+ 'cindy://session/test',
+ 'xdt-maker://project/example',
+ '--open-folder',
+ folder,
+ file,
+ ]);
+ });
+ it('rejects unrecognized schemes and relative file paths', () => {
+ expect(
+ versionEntryArguments([
+ 'https://example.invalid',
+ '--open-folder=../private',
+ '../file.cindy',
+ '--cindy-version-helper=unknown',
+ ]),
+ ).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/versionService.test.ts b/apps/desktop/src/main/cindy-make/__tests__/versionService.test.ts
new file mode 100644
index 0000000000..15ccf2ab2d
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/versionService.test.ts
@@ -0,0 +1,145 @@
+import { mkdtemp, mkdir, writeFile, access, rm } from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+const h = vi.hoisted(() => ({
+ profile: '',
+ currentId: 'original',
+ selectedId: 'original',
+ current: true,
+ busy: false,
+ switching: false,
+ handoff: vi.fn(),
+ quit: vi.fn(),
+ original: {} as Record<string, unknown>,
+}));
+vi.mock('electron', () => ({ app: { getPath: () => h.profile, quit: h.quit } }));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({}),
+ isDataOwnerBroadcastScopeCurrent: () => h.current,
+}));
+vi.mock('../../relaunchBusyActivityIpc.js', () => ({
+ readRelaunchBlockingActivity: async () => ({ busy: h.busy }),
+}));
+vi.mock('../../logger', () => ({
+ createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+vi.mock('../versionStartup.js', () => ({
+ describeOriginalVersion: () => h.original,
+ getCurrentCindyVersionId: () => h.currentId,
+ isCindyVersionSwitching: () => h.switching,
+ startVersionHandoff: h.handoff,
+}));
+import { actCindyVersion, configureCindyVersions, getCindyVersions } from '../versionService';
+import { versionsRoot, versionDirectory, writeVersionJson } from '../versionStore';
+const id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+beforeEach(async () => {
+ vi.clearAllMocks();
+ h.profile = await mkdtemp(path.join(os.tmpdir(), 'cindy-version-service-'));
+ h.currentId = 'original';
+ h.selectedId = 'original';
+ h.current = true;
+ h.busy = false;
+ h.switching = false;
+ const executable = path.join(h.profile, 'original.exe');
+ await writeFile(executable, 'original');
+ h.original = {
+ protocol: 1,
+ version: '0.1.99',
+ commit: 'a'.repeat(40),
+ profile: { userData: h.profile, region: 'global', appName: 'Cindy', passive: false },
+ executable,
+ resources: h.profile,
+ appPath: h.profile,
+ development: { root: h.profile, node: executable, mode: 'remote', environment: {} },
+ };
+ configureCindyVersions(() => false);
+ h.handoff.mockReset().mockResolvedValue(undefined);
+});
+afterEach(async () => {
+ await new Promise((resolve) => setImmediate(resolve));
+ await rm(h.profile, { recursive: true, force: true });
+});
+describe('version management main boundary', () => {
+ it('projects Dev as the original without creating a registry on a read', async () => {
+ expect(await getCindyVersions()).toMatchObject({
+ currentId: 'original',
+ selectedId: 'original',
+ versions: [
+ {
+ id: 'original',
+ kind: 'original',
+ development: true,
+ version: '0.1.99',
+ commit: 'a'.repeat(40),
+ },
+ ],
+ });
+ await expect(access(versionsRoot(h.profile))).rejects.toThrow();
+ });
+ it('continues showing the saved original version while a personal version is running', async () => {
+ writeVersionJson(path.join(versionsRoot(h.profile), 'original.json'), h.original);
+ h.currentId = id;
+ expect((await getCindyVersions()).versions[0]).toMatchObject({
+ version: '0.1.99',
+ commit: 'a'.repeat(40),
+ });
+ });
+ it('reads the original package version for registries created before version labels', async () => {
+ delete h.original.version;
+ await writeFile(path.join(h.profile, 'package.json'), JSON.stringify({ version: '0.1.98' }));
+ writeVersionJson(path.join(versionsRoot(h.profile), 'original.json'), h.original);
+ h.currentId = id;
+ expect((await getCindyVersions()).versions[0].version).toBe('0.1.98');
+ });
+ it.each([
+ ['switch', '../outside'],
+ ['remove', {}],
+ ['run', id],
+ ])('rejects arbitrary version action %s %s', async (action, target) => {
+ await expect(actCindyVersion(action, target)).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(h.handoff).not.toHaveBeenCalled();
+ });
+ it('blocks switching during build or other running work and never quits on a failed handoff', async () => {
+ configureCindyVersions(() => true);
+ await expect(actCindyVersion('switch', id)).rejects.toThrow('busy');
+ configureCindyVersions(() => false);
+ h.busy = true;
+ await expect(actCindyVersion('switch', id)).rejects.toThrow('busy');
+ h.busy = false;
+ h.handoff.mockRejectedValueOnce(
+ Object.assign(new Error('incompatible'), { code: 'incompatible' }),
+ );
+ await expect(actCindyVersion('switch', id)).rejects.toThrow('incompatible');
+ expect(h.quit).not.toHaveBeenCalled();
+ });
+ it('uses normal quit only after the host-owned handoff accepts the current owner', async () => {
+ h.handoff.mockImplementationOnce(async (_id, current: () => Promise<boolean>) => {
+ expect(await current()).toBe(true);
+ });
+ await actCindyVersion('switch', id);
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(h.quit).toHaveBeenCalledOnce();
+ h.quit.mockClear();
+ h.handoff.mockImplementationOnce(async () => {
+ h.current = false;
+ });
+ await expect(actCindyVersion('switch', id)).rejects.toThrow('busy');
+ expect(h.quit).not.toHaveBeenCalled();
+ });
+ it('deletes only an inactive selected snapshot, retaining source and user data', async () => {
+ const directory = versionDirectory(h.profile, id);
+ await mkdir(directory, { recursive: true });
+ await writeFile(path.join(directory, 'application'), 'snapshot');
+ await writeFile(path.join(h.profile, 'keep.db'), 'keep data');
+ h.currentId = id;
+ await expect(actCindyVersion('remove', id)).rejects.toThrow('busy');
+ h.currentId = 'original';
+ writeVersionJson(path.join(versionsRoot(h.profile), 'selected.json'), { id });
+ await expect(actCindyVersion('remove', id)).rejects.toThrow('busy');
+ writeVersionJson(path.join(versionsRoot(h.profile), 'selected.json'), { id: 'original' });
+ await actCindyVersion('remove', id);
+ await expect(access(directory)).rejects.toThrow();
+ await expect(access(path.join(h.profile, 'keep.db'))).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts b/apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts
new file mode 100644
index 0000000000..7eb8bfd0d3
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts
@@ -0,0 +1,350 @@
+import { EventEmitter } from 'node:events';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import fs from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+const h = vi.hoisted(() => ({
+ profile: '',
+ appPath: '',
+ name: 'Cindy',
+ packaged: false,
+ spawn: vi.fn(),
+ pty: vi.fn(),
+ exit: vi.fn(),
+ quit: vi.fn(),
+ errorBox: vi.fn(),
+ live: new Set<number>(),
+}));
+vi.mock('electron', () => ({
+ app: {
+ get isPackaged() {
+ return h.packaged;
+ },
+ getPath: () => h.profile,
+ getAppPath: () => h.appPath,
+ getName: () => h.name,
+ getVersion: () => '0.1.99',
+ setName: (name: string) => {
+ h.name = name;
+ },
+ setPath: (_key: string, value: string) => {
+ h.profile = value;
+ },
+ whenReady: async () => {},
+ dock: { hide: vi.fn() },
+ once: vi.fn(),
+ on: vi.fn(),
+ removeListener: vi.fn(),
+ emit: vi.fn(),
+ exit: h.exit,
+ quit: h.quit,
+ },
+ dialog: { showErrorBox: h.errorBox },
+}));
+vi.mock('node:child_process', async (load) => ({
+ ...(await load<typeof import('node:child_process')>()),
+ spawn: h.spawn,
+}));
+vi.mock('../../terminal/ptyFactory.js', () => ({ defaultPtySpawn: h.pty }));
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
+}));
+vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
+vi.mock('../../../shared/brandRegion.js', () => ({ CURRENT_CINDY_REGION: 'global' }));
+
+const originalExec = process.execPath;
+const originalArgv = [...process.argv];
+let root = '';
+let startup: typeof import('../versionStartup');
+let store: typeof import('../versionStore');
+let original: import('../versionStore').OriginalVersion;
+beforeEach(async () => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ root = await mkdtemp(path.join(os.tmpdir(), 'cindy-version-startup-'));
+ h.profile = path.join(root, 'profile');
+ h.appPath = path.join(root, 'checkout', 'apps', 'desktop');
+ h.name = 'Cindy';
+ h.packaged = false;
+ await mkdir(h.profile);
+ await mkdir(path.join(h.appPath, 'drizzle'), { recursive: true });
+ await mkdir(path.join(root, 'checkout/config'), { recursive: true });
+ await writeFile(
+ path.join(root, 'checkout/config/endpoint.json'),
+ JSON.stringify({
+ schemaVersion: 1,
+ region: 'global',
+ authApiBaseUrl: 'https://auth.example.invalid',
+ }),
+ );
+ await writeFile(
+ path.join(h.appPath, 'drizzle', '0000_base.sql'),
+ 'CREATE TABLE sample(id TEXT);',
+ );
+ const executable = path.join(root, 'electron.exe');
+ await writeFile(executable, 'fixture');
+ Object.defineProperty(process, 'execPath', {
+ value: executable,
+ configurable: true,
+ writable: true,
+ });
+ process.argv = [executable, h.appPath];
+ h.live = new Set([process.pid]);
+ vi.spyOn(process, 'kill').mockImplementation((pid) => {
+ if (!h.live.has(Number(pid))) throw Object.assign(new Error('gone'), { code: 'ESRCH' });
+ return true;
+ });
+ for (const key of [
+ 'CINDY_VERSION_PROFILE',
+ 'CINDY_VERSION_LAUNCH',
+ 'CINDY_VERSION_FORWARD_ARGUMENTS',
+ 'XDT_USER_DATA_DIR',
+ 'XDT_DEVICE_ID_OVERRIDE',
+ 'XDT_SCHEDULER_PASSIVE',
+ 'XDT_ENDPOINT_MANIFEST_FILE',
+ 'XDT_ENDPOINTS_CDN',
+ 'XDT_DESKTOP_DEV_MODE',
+ ])
+ vi.stubEnv(key, undefined);
+ vi.stubEnv('PATH', path.dirname(originalExec));
+ store = await import('../versionStore');
+ startup = await import('../versionStartup');
+ original = {
+ protocol: 1,
+ profile: { userData: h.profile, appName: 'Cindy', region: 'global', passive: false },
+ executable,
+ appPath: h.appPath,
+ resources: h.appPath,
+ development: {
+ root: path.join(root, 'checkout'),
+ node: originalExec,
+ mode: 'remote',
+ environment: { PATH: path.dirname(originalExec), XDT_USER_DATA_DIR: h.profile },
+ },
+ };
+});
+afterEach(async () => {
+ process.argv = originalArgv;
+ Object.defineProperty(process, 'execPath', {
+ value: originalExec,
+ configurable: true,
+ writable: true,
+ });
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+ if (root) await rm(root, { recursive: true, force: true });
+});
+function saveOriginal() {
+ store.writeVersionJson(path.join(store.versionsRoot(h.profile), 'original.json'), original);
+}
+function launchRequest(patch: Partial<import('../versionStartup').VersionLaunchRequest> = {}) {
+ const value: import('../versionStartup').VersionLaunchRequest = {
+ protocol: 1,
+ id: randomUUID(),
+ profile: original.profile,
+ parentPid: 44001,
+ helperExecutable: process.execPath,
+ helperAppPath: h.appPath,
+ targetId: 'original',
+ fallbackId: 'original',
+ createdAt: Date.now(),
+ state: 'starting',
+ ...patch,
+ };
+ store.writeVersionJson(startup.versionRequestPath(h.profile, value.id), value);
+ return value;
+}
+describe('one original version type for Dev and installed Cindy', () => {
+ it('does nothing beyond normal startup when no personal version exists', async () => {
+ startup.prepareCindyVersionStartup();
+ expect(await startup.dispatchCindyVersionStartup()).toBe(false);
+ expect(startup.getCurrentCindyVersionId()).toBe('original');
+ expect(fs.existsSync(store.versionsRoot(h.profile))).toBe(false);
+ expect(h.spawn).not.toHaveBeenCalled();
+ });
+ it('captures Dev as the original and keeps full Forge/Vite return information without credentials', async () => {
+ vi.stubEnv('OPENAI_API_KEY', 'fake-never-persist');
+ vi.stubEnv('NODE_OPTIONS', '--require private-hook');
+ const value = await startup.rememberOriginalVersion(originalExec);
+ expect(value.version).toBe('0.1.99');
+ expect(store.readOriginalVersion(h.profile)?.version).toBe('0.1.99');
+ expect(value.development).toMatchObject({
+ root: path.join(root, 'checkout'),
+ node: originalExec,
+ mode: 'remote',
+ });
+ expect(value.development?.environment).not.toHaveProperty('OPENAI_API_KEY');
+ expect(value.development?.environment).not.toHaveProperty('NODE_OPTIONS');
+ expect(JSON.parse(value.profile.endpointSnapshot!.manifestText).authApiBaseUrl).toBe(
+ 'https://auth.example.invalid',
+ );
+ expect(store.selectedVersion(h.profile)).toBe('original');
+ expect(await startup.dispatchCindyVersionStartup()).toBe(false);
+ expect(h.spawn).not.toHaveBeenCalled();
+ });
+ it('rejects a declared endpoint realm that differs from the running original', async () => {
+ await writeFile(path.join(root, 'checkout/config/endpoint.json'), JSON.stringify({ schemaVersion: 1, region: 'cn', authApiBaseUrl: 'https://auth.example.invalid' }));
+ await expect(startup.rememberOriginalVersion(originalExec)).rejects.toMatchObject({ code: 'unavailable' });
+ expect(h.spawn).not.toHaveBeenCalled();
+ });
+ it('pins a validated launch to its original profile and consumes launch arguments before ordinary relaunch', async () => {
+ saveOriginal();
+ const request = launchRequest();
+ process.argv.push(
+ '--cindy-version-profile=' + h.profile,
+ '--cindy-version-launch=' + request.id,
+ );
+ startup.prepareCindyVersionStartup();
+ expect(h.profile).toBe(original.profile.userData);
+ expect(startup.getCurrentCindyVersionId()).toBe('original');
+ expect(process.argv.some((arg) => arg.startsWith('--cindy-version-'))).toBe(false);
+ expect(store.readVersionJson(startup.versionRequestPath(h.profile, request.id))).toMatchObject({
+ claimedPid: process.pid,
+ });
+ await startup.markCindyVersionReady();
+ expect(store.readVersionJson(startup.versionRequestPath(h.profile, request.id))).toMatchObject({
+ state: 'ready',
+ });
+ });
+ it('allows Forge hot reload to reuse its running Dev supervisor without replaying the switch', async () => {
+ saveOriginal();
+ h.live.add(45003);
+ const value = launchRequest({
+ state: 'ready',
+ claimedPid: 45004,
+ helperPid: 45003,
+ createdAt: 1,
+ });
+ vi.stubEnv('CINDY_VERSION_PROFILE', h.profile);
+ vi.stubEnv('CINDY_VERSION_LAUNCH', value.id);
+ startup.prepareCindyVersionStartup();
+ expect(process.env.CINDY_VERSION_LAUNCH).toBeUndefined();
+ expect(await startup.dispatchCindyVersionStartup()).toBe(false);
+ expect(h.spawn).not.toHaveBeenCalled();
+ });
+ it('preserves the profile keychain identity and rejects a conflicting launch identity', async () => {
+ saveOriginal();
+ await writeFile(path.join(h.profile, 'keychain-identity'), 'CindyDev\n');
+ const first = launchRequest();
+ process.argv.push('--cindy-version-profile=' + h.profile, '--cindy-version-launch=' + first.id);
+ expect(() => startup.prepareCindyVersionStartup()).toThrow();
+ const second = launchRequest({
+ profile: { ...original.profile, appName: 'CindyDev', deviceId: 'dev-test' },
+ });
+ process.argv = [
+ process.execPath,
+ h.appPath,
+ '--cindy-version-profile=' + h.profile,
+ '--cindy-version-launch=' + second.id,
+ ];
+ startup.prepareCindyVersionStartup();
+ expect(h.name).toBe('CindyDev');
+ expect(process.env.XDT_DEVICE_ID_OVERRIDE).toBe('dev-test');
+ });
+ it('uses the existing instance activation path instead of repeatedly launching the selected personal version', async () => {
+ saveOriginal();
+ h.live.add(45003);
+ store.writeVersionJson(path.join(store.versionsRoot(h.profile), 'active.json'), {
+ pid: 45003,
+ id: randomUUID(),
+ scope: 'profile',
+ });
+ await store.selectVersion(h.profile, randomUUID());
+ expect(await startup.dispatchCindyVersionStartup()).toBe(false);
+ expect(h.spawn).not.toHaveBeenCalled();
+ expect((await import('../versionRuntimeIdentity')).getCindyVersionLockScope()).toBe('profile');
+ });
+ it.each(['different-executable', 'different-app', 'expired', 'cancelled'])(
+ 'rejects %s handoffs before opening a profile',
+ (failure) => {
+ saveOriginal();
+ const value = launchRequest(
+ failure === 'expired'
+ ? { createdAt: 1 }
+ : failure === 'cancelled'
+ ? { state: 'cancelled' }
+ : {},
+ );
+ if (failure === 'different-executable') {
+ original.executable = path.join(root, 'other.exe');
+ saveOriginal();
+ }
+ if (failure === 'different-app') h.appPath = path.join(root, 'different-checkout');
+ process.argv.push(
+ '--cindy-version-profile=' + h.profile,
+ '--cindy-version-launch=' + value.id,
+ );
+ expect(() => startup.prepareCindyVersionStartup()).toThrow();
+ expect(h.spawn).not.toHaveBeenCalled();
+ },
+ );
+ it('refuses a conflicting switch when activity appears while the helper starts', async () => {
+ saveOriginal();
+ h.spawn.mockImplementation((_command, args: string[]) => {
+ const child = new EventEmitter() as EventEmitter & { pid: number; unref(): void };
+ child.pid = 45001;
+ child.unref = () => {};
+ h.live.add(child.pid);
+ queueMicrotask(() => {
+ const id = args
+ .find((arg) => arg.startsWith('--cindy-version-helper='))!
+ .split('=')
+ .at(-1)!;
+ const file = startup.versionRequestPath(h.profile, id);
+ store.writeVersionJson(file, {
+ ...store.readVersionJson<object>(file),
+ helperPid: child.pid,
+ });
+ child.emit('spawn');
+ });
+ return child;
+ });
+ const allowed = vi.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(false);
+ await expect(startup.startVersionHandoff('original', allowed)).rejects.toMatchObject({
+ code: 'busy',
+ });
+ expect(h.quit).not.toHaveBeenCalled();
+ expect(startup.isCindyVersionSwitching()).toBe(false);
+ expect(store.selectedVersion(h.profile)).toBe('original');
+ });
+ it('starts the original Dev through the complete existing runner and retains its PTY until exit', async () => {
+ saveOriginal();
+ const value = launchRequest({ state: 'pending' });
+ process.argv.push('--cindy-version-profile=' + h.profile, '--cindy-version-helper=' + value.id);
+ let onExit!: () => void;
+ const kill = vi.fn(() => onExit());
+ h.pty.mockImplementation((_node, _args, options) => {
+ expect(options.env.CINDY_VERSION_LAUNCH).toBe(value.id);
+ queueMicrotask(() => {
+ const file = startup.versionRequestPath(h.profile, value.id);
+ store.writeVersionJson(file, {
+ ...store.readVersionJson<object>(file),
+ state: 'ready',
+ claimedPid: 45002,
+ });
+ });
+ return {
+ onData: vi.fn(),
+ onExit: (callback: () => void) => {
+ onExit = callback;
+ },
+ kill,
+ };
+ });
+ startup.prepareCindyVersionStartup();
+ const result = startup.dispatchCindyVersionStartup();
+ await vi.waitFor(() => expect(h.pty).toHaveBeenCalledOnce());
+ expect(h.pty.mock.calls[0].slice(0, 2)).toEqual([
+ originalExec,
+ [path.join(root, 'checkout/scripts/desktop-dev-runner.mjs'), 'remote'],
+ ]);
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ expect(h.exit).not.toHaveBeenCalled();
+ onExit();
+ await expect(result).resolves.toBe(true);
+ expect(h.exit).toHaveBeenCalledWith(0);
+ expect(kill).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/versionStore.test.ts b/apps/desktop/src/main/cindy-make/__tests__/versionStore.test.ts
new file mode 100644
index 0000000000..81d26655d0
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/versionStore.test.ts
@@ -0,0 +1,205 @@
+import { mkdtemp, mkdir, writeFile, readFile, rm, symlink, readdir } from 'node:fs/promises';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ listPersonalVersions,
+ migrationIdentity,
+ publishPersonalVersion,
+ readOriginalVersion,
+ readPersonalVersion,
+ readVersionJson,
+ retainPersonalVersion,
+ runnableBundlePaths,
+ selectedVersion,
+ selectVersion,
+ verifyPersonalVersion,
+ versionDirectory,
+ versionsRoot,
+ writeVersionJson,
+ type OriginalVersion,
+ type VersionProfile,
+} from '../versionStore';
+vi.mock('../../logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+const roots: string[] = [];
+afterEach(async () => {
+ for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
+});
+async function fixture() {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-version-store-'));
+ roots.push(root);
+ const userData = path.join(root, 'profile');
+ await mkdir(userData);
+ const profile: VersionProfile = { userData, appName: 'Cindy', region: 'global', passive: false };
+ const source = path.join(root, process.platform === 'darwin' ? 'Cindy.app' : 'Cindy');
+ const { resources, executable } = runnableBundlePaths(source, 'Cindy');
+ await mkdir(path.join(resources, 'drizzle'), { recursive: true });
+ await mkdir(path.dirname(executable), { recursive: true });
+ await writeFile(executable, 'executable A');
+ await writeFile(path.join(resources, 'app.asar'), 'application A');
+ await writeFile(
+ path.join(resources, 'drizzle/0000_base.sql'),
+ 'CREATE TABLE example(id TEXT);\n',
+ );
+ await writeFile(
+ path.join(resources, 'cindy-version-protocol.json'),
+ JSON.stringify({ version: 1 }),
+ );
+ const commit = 'a'.repeat(40);
+ const builtAt = '2026-09-17T20:00:00.000+08:00';
+ await writeFile(
+ path.join(resources, 'cindy-source.json'),
+ JSON.stringify({ sourceCommit: commit, builtAt }),
+ );
+ const original: OriginalVersion = {
+ protocol: 1,
+ profile,
+ executable,
+ appPath: path.join(resources, 'app.asar'),
+ resources,
+ };
+ const retain = () =>
+ retainPersonalVersion({
+ profile,
+ sourceDirectory: source,
+ appName: 'Cindy',
+ title: 'Blue background',
+ commit,
+ });
+ return {
+ root,
+ userData,
+ profile,
+ source,
+ resources,
+ executable,
+ original,
+ retain,
+ commit,
+ builtAt,
+ };
+}
+describe('local Cindy version snapshots', () => {
+ it('defaults to the original without creating a version registry', async () => {
+ const h = await fixture();
+ expect(selectedVersion(h.userData)).toBe('original');
+ expect(readOriginalVersion(h.userData)).toBeNull();
+ expect(listPersonalVersions(h.userData, null)).toEqual([]);
+ expect(fs.existsSync(versionsRoot(h.userData))).toBe(false);
+ });
+ it('atomically stores readable JSON and remembers an explicit selection', async () => {
+ const h = await fixture();
+ const file = path.join(h.userData, 'record.json');
+ writeVersionJson(file, { message: 'hello' });
+ expect(readVersionJson(file)).toEqual({ message: 'hello' });
+ const id = 'a'.repeat(8) + '-aaaa-aaaa-aaaa-' + 'a'.repeat(12);
+ await selectVersion(h.userData, id);
+ expect(selectedVersion(h.userData)).toBe(id);
+ await selectVersion(h.userData, 'original');
+ expect(selectedVersion(h.userData)).toBe('original');
+ });
+ it('keeps A unchanged while building B and only lists successfully published versions', async () => {
+ const h = await fixture();
+ const first = (await h.retain())!;
+ expect(listPersonalVersions(h.userData, h.original)).toEqual([]);
+ publishPersonalVersion(h.userData, first);
+ const a = await verifyPersonalVersion(h.userData, first, h.original);
+ expect(a.builtAt).toBe(h.builtAt);
+ await writeFile(path.join(h.resources, 'app.asar'), 'application B');
+ const second = (await h.retain())!;
+ expect(second).not.toBe(first);
+ publishPersonalVersion(h.userData, second);
+ expect(
+ await readFile(
+ path.join(versionDirectory(h.userData, first), a.resources, 'app.asar'),
+ 'utf8',
+ ),
+ ).toBe('application A');
+ expect(listPersonalVersions(h.userData, h.original)).toHaveLength(2);
+ expect(selectedVersion(h.userData)).toBe('original');
+ // Clearing Make source cannot erase the runnable versions.
+ await mkdir(path.join(h.userData, 'cindy-make', 'source'), { recursive: true });
+ await rm(path.join(h.userData, 'cindy-make'), { recursive: true });
+ expect(await verifyPersonalVersion(h.userData, first, h.original)).toMatchObject({ id: first });
+ });
+ it('rejects modified applications and mismatched database migrations before launch', async () => {
+ const h = await fixture();
+ const id = (await h.retain())!;
+ publishPersonalVersion(h.userData, id);
+ const item = readPersonalVersion(h.userData, id);
+ const archive = path.join(versionDirectory(h.userData, id), item.resources, 'app.asar');
+ await writeFile(archive, 'modified');
+ await expect(verifyPersonalVersion(h.userData, id, h.original)).rejects.toMatchObject({
+ code: 'unavailable',
+ });
+ await writeFile(archive, 'application A');
+ await writeFile(
+ path.join(h.resources, 'drizzle/0001_new.sql'),
+ 'ALTER TABLE example ADD COLUMN name TEXT;',
+ );
+ await expect(verifyPersonalVersion(h.userData, id, h.original)).rejects.toMatchObject({
+ code: 'incompatible',
+ });
+ expect(listPersonalVersions(h.userData, h.original)[0].compatible).toBe(false);
+ });
+ it('runs retained personal applications even after the original Dev source directory is removed', async () => {
+ const h = await fixture();
+ h.original.migrationHash = migrationIdentity(path.join(h.resources, 'drizzle'));
+ const id = (await h.retain())!;
+ publishPersonalVersion(h.userData, id);
+ await rm(h.source, { recursive: true, force: true });
+ await expect(verifyPersonalVersion(h.userData, id, h.original)).resolves.toMatchObject({ id });
+ });
+ it('includes companion scripts in the compatibility identity and normalizes line endings', async () => {
+ const h = await fixture();
+ const drizzle = path.join(h.resources, 'drizzle');
+ const first = migrationIdentity(drizzle);
+ await writeFile(path.join(drizzle, '0000_base.sql'), 'CREATE TABLE example(id TEXT);\r\n');
+ expect(migrationIdentity(drizzle)).toBe(first);
+ await mkdir(path.join(drizzle, 'scripts'));
+ await writeFile(path.join(drizzle, 'scripts/0000_base.ts'), 'module.exports = () => {};');
+ expect(migrationIdentity(drizzle)).not.toBe(first);
+ });
+ it('preserves internal framework links but rejects links escaping the application', async () => {
+ const h = await fixture();
+ const inside = path.join(h.source, 'FrameworkVersions', 'A');
+ await mkdir(inside, { recursive: true });
+ await writeFile(path.join(inside, 'keep'), 'framework');
+ const link = path.join(h.source, 'FrameworkVersions', 'Current');
+ await symlink(
+ process.platform === 'win32' ? inside : 'A',
+ link,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ // Absolute junctions would keep pointing at the temporary source after copying, so test
+ // portable relative links on POSIX; Windows Electron outputs have no framework links.
+ if (process.platform !== 'win32') expect(await h.retain()).toEqual(expect.any(String));
+ await rm(link);
+ const outside = path.join(h.root, 'outside');
+ await mkdir(outside);
+ await writeFile(path.join(outside, 'keep'), 'private');
+ await symlink(outside, link, process.platform === 'win32' ? 'junction' : 'dir');
+ await expect(h.retain()).rejects.toMatchObject({ code: 'unavailable' });
+ expect(await readFile(path.join(outside, 'keep'), 'utf8')).toBe('private');
+ });
+ it('retains legacy installer support without pretending an old application can switch profiles', async () => {
+ const h = await fixture();
+ await rm(path.join(h.resources, 'cindy-version-protocol.json'));
+ expect(await h.retain()).toBeUndefined();
+ expect(fs.existsSync(versionsRoot(h.userData))).toBe(false);
+ });
+ it('uses complete bundle layouts on both macOS and Windows', () => {
+ const root = path.join(os.tmpdir(), 'Cindy.app');
+ expect(runnableBundlePaths(root, 'Cindy', 'darwin')).toEqual({
+ executable: path.join(root, 'Contents/MacOS/Cindy'),
+ resources: path.join(root, 'Contents/Resources'),
+ });
+ expect(runnableBundlePaths(root, 'Cindy', 'win32')).toEqual({
+ executable: path.join(root, 'Cindy.exe'),
+ resources: path.join(root, 'resources'),
+ });
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/completion.ts b/apps/desktop/src/main/cindy-make/completion.ts
index f91e9b3265..f891a08641 100644
--- a/apps/desktop/src/main/cindy-make/completion.ts
+++ b/apps/desktop/src/main/cindy-make/completion.ts
@@ -1,6 +1,12 @@
+import path from 'node:path';
+import { realpath } from 'node:fs/promises';
+import { contentRef, taskCommitRef, taskContentRef, type ContentGit } from './sourceContent.js';
+import { commitLocalFiles } from './localHistory.js';
+import { makeTaskBranch, makeSourceCheckoutPath, isCindyMakeWorktreePath } from './sourcePaths.js';
import type { AgentEvent } from '@cindy/maker-core';
import { isTerminalAgentErrorEvent } from '@cindy/maker-core';
import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-continuation';
+import { isSuccessfulAssistantReplyDoneData } from '../cindy-brain/assistantReplyHook.js';
import type { CindyMakeCompletionMeta } from '../../shared/cindyMakeSession.js';
/** The slice of a live maker Session the tracker needs; kept narrow for tests. */
@@ -11,7 +17,7 @@ export interface CindyMakeCompletionSession {
export interface CindyMakeCompletionTrackerDeps {
getSession: (sessionId: string) => CindyMakeCompletionSession | undefined;
- /** Commit the task worktree and return code-verified facts; failures degrade to an empty object. */
+ /** Commit completed task files locally and return verified facts; failures degrade to an empty object. */
collectFacts: (sessionId: string) => Promise<Omit<CindyMakeCompletionMeta, 'reportedAt'>>;
persist: (sessionId: string, meta: CindyMakeCompletionMeta) => Promise<void>;
logger: { warn: (msg: string, meta?: Record<string, unknown>) => void };
@@ -68,6 +74,11 @@ export function createCindyMakeCompletionTracker(
}
const off = session.onEvent((event) => {
if (!isProductTurnEnd(event) || !pending.has(sessionId)) return;
+ if (event.type !== 'done' || !isSuccessfulAssistantReplyDoneData(event.data)) {
+ pending.get(sessionId)?.();
+ pending.delete(sessionId);
+ return;
+ }
void finish(sessionId).catch((error) => {
deps.logger.warn('cindy_make completion persist failed', {
sessionId,
@@ -80,53 +91,44 @@ export function createCindyMakeCompletionTracker(
};
}
-export const CINDY_MAKE_COMMIT_AUTHOR = 'Cindy Make';
-export const CINDY_MAKE_COMMIT_EMAIL = 'cindy-make@localhost';
-
-const LINE_BREAK = /\r?\n/;
-
-/**
- * Commit everything the agent changed in the task worktree and return the facts
- * the completion card shows. The identity is fixed so the commit never depends
- * on the user's global Git configuration. Each Git answer is optional so one
- * failing command does not hide the others.
- */
-export async function commitCindyMakeChanges(
- git: (args: string[]) => Promise<string>,
- message: string,
+/** Finalize this managed task locally; personal/main branches are untouched. */
+export async function collectCindyMakeChanges(
+ git: ContentGit,
+ userData: string,
+ worktree: string,
): Promise<Omit<CindyMakeCompletionMeta, 'reportedAt'>> {
- const facts: Omit<CindyMakeCompletionMeta, 'reportedAt'> = {};
- try {
- const branch = (await git(['rev-parse', '--abbrev-ref', 'HEAD'])).trim();
- if (branch && branch !== 'HEAD') facts.branch = branch;
- } catch {
- // Reported without a branch.
- }
- try {
- const status = await git(['status', '--porcelain', '--untracked-files=all']);
- facts.changedFiles = status.split(LINE_BREAK).filter((line) => line.trim().length > 0).length;
- if (facts.changedFiles > 0) {
- await git(['add', '--all']);
- await git([
- '-c',
- `user.name=${CINDY_MAKE_COMMIT_AUTHOR}`,
- '-c',
- `user.email=${CINDY_MAKE_COMMIT_EMAIL}`,
- 'commit',
- '--quiet',
- '--no-verify',
- '--message',
- message,
- ]);
- }
- } catch {
- // Reported without a count; HEAD below still tells which commit the task is on.
- }
- try {
- const commit = (await git(['rev-parse', 'HEAD'])).trim();
- if (/^[0-9a-f]{7,64}$/i.test(commit)) facts.commit = commit;
- } catch {
- // Reported without a commit.
- }
- return facts;
+ const runId = path.basename(worktree);
+ const branch = (await git(['rev-parse', '--abbrev-ref', 'HEAD'], worktree)).trim();
+ const samePath = (a: string, b: string) =>
+ process.platform === 'win32'
+ ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
+ : path.resolve(a) === path.resolve(b);
+ if (
+ !isCindyMakeWorktreePath(userData, worktree) ||
+ branch !== makeTaskBranch(runId) ||
+ !samePath(await realpath(worktree), worktree) ||
+ !samePath(
+ (await git(['rev-parse', '--path-format=absolute', '--git-common-dir'], worktree)).trim(),
+ await realpath(path.join(makeSourceCheckoutPath(userData), '.git')),
+ )
+ )
+ throw new Error('Unexpected Cindy Make worktree');
+ const { commit, tree } = await commitLocalFiles(
+ git,
+ worktree,
+ 'Cindy Make: complete personal change',
+ );
+ await git(['update-ref', taskContentRef(runId, 'complete'), tree], worktree);
+ await git(['update-ref', taskCommitRef(runId), commit], worktree);
+ const base = await contentRef(git, worktree, taskContentRef(runId, 'base'));
+ const changes = base
+ ? await git(['diff', '--name-only', '-z', '--no-renames', base, tree, '--'], worktree)
+ : await git(['status', '--porcelain', '-z', '--untracked-files=all'], worktree);
+ return {
+ branch,
+ commit,
+ tree,
+ ...(base ? { baseTree: base } : {}),
+ changedFiles: changes.split('\u0000').filter(Boolean).length,
+ };
}
diff --git a/apps/desktop/src/main/cindy-make/featurePlan.ts b/apps/desktop/src/main/cindy-make/featurePlan.ts
new file mode 100644
index 0000000000..bcc549c644
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/featurePlan.ts
@@ -0,0 +1,46 @@
+import type {
+ CindyMakeHistoryRecord,
+ MakeFeatureAction,
+ MakeHistoryCompletion,
+} from '../../shared/cindyMakeHistory.js';
+import { activeFeatureReceipts } from '../../shared/cindyMakeHistory.js';
+import type { MakeFeatureMergePlan } from '../../shared/cindyMakeMerge.js';
+
+/** Content deltas remain usable after rebase rewrites commit IDs. Undo uses the actual adopted delta. */
+export function planFeatureChange(
+ record: CindyMakeHistoryRecord,
+ action: MakeFeatureAction,
+ completion?: MakeHistoryCompletion,
+): MakeFeatureMergePlan {
+ const latest = record.receipts.at(-1);
+ const active = activeFeatureReceipts(record.receipts);
+ const plan: MakeFeatureMergePlan = {
+ runId: record.runId,
+ taskSessionId: record.sessionId,
+ action,
+ taskTree: latest?.taskTree ?? '',
+ steps: [],
+ nextStep: 0,
+ };
+ if (action === 'revert') {
+ if (!active.length) throw new Error('No integrated feature to undo');
+ plan.steps = active
+ .slice()
+ .reverse()
+ .map((item) => ({ before: item.tree, after: item.beforeTree }));
+ return plan;
+ }
+ if (action === 'reapply' || latest?.action === 'revert') {
+ if (latest?.action !== 'revert') throw new Error('No reverted feature to reapply');
+ plan.steps.push({ before: latest.tree, after: latest.beforeTree });
+ if (action === 'reapply') return plan;
+ }
+ if (!completion?.tree || !completion.commit) throw new Error('No verified completion');
+ plan.taskTree = completion.tree;
+ plan.completionId = completion.id;
+ if (latest) {
+ if (latest.taskTree !== completion.tree)
+ plan.steps.push({ before: latest.taskTree, after: completion.tree });
+ } else plan.mergeCommit = completion.commit;
+ return plan;
+}
diff --git a/apps/desktop/src/main/cindy-make/historyCapture.ts b/apps/desktop/src/main/cindy-make/historyCapture.ts
new file mode 100644
index 0000000000..3aad73b7ce
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/historyCapture.ts
@@ -0,0 +1,39 @@
+import type { MakeDoctorReport } from '../../shared/cindyMakeDoctor.js';
+import type { CindyMakeCompletionMeta } from '../../shared/cindyMakeSession.js';
+import type { CindyMakeHistoryStore } from './historyStore.js';
+import { captureMakeHistoryStore } from './historyOwner.js';
+
+/** Save only typed product facts, never transcript content or a working-directory copy. */
+export function captureMakeHistoryReport(
+ report: MakeDoctorReport,
+ store = captureMakeHistoryStore(),
+ createdAt = Date.now(),
+): void {
+ if (!report.task) return;
+ store.seed({
+ runId: report.runId,
+ sessionId: report.task.sessionId,
+ title: report.task.title ?? '',
+ request: report.task.request ?? '',
+ createdAt,
+ updatedAt: createdAt,
+ ...(report.task.finished ? { endedAt: createdAt } : {}),
+ });
+}
+export function captureMakeHistoryCompletion(
+ store: CindyMakeHistoryStore,
+ runId: string,
+ id: string,
+ meta: CindyMakeCompletionMeta,
+): void {
+ store.completion(runId, { ...meta, id });
+ if (meta.personal?.status === 'ready' && meta.personal.commit) {
+ for (const feature of meta.personal.includedFeatures ?? [])
+ store.version(feature.runId, {
+ operationId: feature.operationId,
+ commit: meta.personal.commit,
+ versionId: meta.personal.versionId,
+ at: meta.personal.generatedAt,
+ });
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/historyLegacy.ts b/apps/desktop/src/main/cindy-make/historyLegacy.ts
new file mode 100644
index 0000000000..873a90d491
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/historyLegacy.ts
@@ -0,0 +1,54 @@
+import { createHash } from 'node:crypto';
+import type { CindyMakeHistoryRecord, MakeFeatureReceipt } from '../../shared/cindyMakeHistory.js';
+import type { ContentGit } from './sourceContent.js';
+
+const HASH = /^[a-f0-9]{40,64}$/i;
+/** Old build records are adopted only when Git proves the exact integration commit and both file trees. */
+export async function readLegacyFeatureReceipts(
+ record: CindyMakeHistoryRecord,
+ git: ContentGit,
+ source: string,
+): Promise<MakeFeatureReceipt[]> {
+ if (record.receipts.length) return [];
+ const receipts: MakeFeatureReceipt[] = [];
+ for (const completion of record.completions) {
+ const built = completion.personal;
+ if (
+ !built?.commit ||
+ !built.tree ||
+ !completion.commit ||
+ !completion.tree ||
+ ![built.commit, built.tree, completion.commit, completion.tree].every((value) =>
+ HASH.test(value),
+ )
+ )
+ continue;
+ if (receipts.some((receipt) => receipt.commit === built.commit)) continue;
+ try {
+ const tree = (await git(['rev-parse', built.commit + '^{tree}'], source)).trim();
+ if (tree !== built.tree) continue;
+ const parents = (await git(['show', '-s', '--format=%P', built.commit], source))
+ .trim()
+ .split(/\s+/);
+ const subject = (await git(['show', '-s', '--format=%s', built.commit], source)).trim();
+ if (!HASH.test(parents[0]) || !subject.startsWith('Cindy Make: integrate personal feature'))
+ continue;
+ if (parents.length > 1 && !parents.slice(1).includes(completion.commit)) continue;
+ const beforeTree = (await git(['rev-parse', parents[0] + '^{tree}'], source)).trim();
+ if (!HASH.test(beforeTree)) continue;
+ receipts.push({
+ id: 'legacy-' + createHash('sha256').update(completion.id).digest('hex').slice(0, 32),
+ action: 'integrate',
+ at: completion.reportedAt,
+ baselineCommit: parents[0],
+ commit: built.commit,
+ beforeTree,
+ tree,
+ taskTree: completion.tree,
+ });
+ } catch {
+ /* Missing pre-upgrade objects cannot be replaced with guessed undo data. */
+ }
+ }
+ return receipts;
+}
diff --git a/apps/desktop/src/main/cindy-make/historyOwner.ts b/apps/desktop/src/main/cindy-make/historyOwner.ts
new file mode 100644
index 0000000000..a5e9a2b260
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/historyOwner.ts
@@ -0,0 +1,7 @@
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { CindyMakeHistoryStore } from './historyStore.js';
+
+/** Capture before awaiting; never resolve an old operation against a newly signed-in owner. */
+export function captureMakeHistoryStore(): CindyMakeHistoryStore {
+ return new CindyMakeHistoryStore(ownerScopedUserDataPath('cindy-make-history'));
+}
diff --git a/apps/desktop/src/main/cindy-make/historyRuntime.ts b/apps/desktop/src/main/cindy-make/historyRuntime.ts
new file mode 100644
index 0000000000..0e6abfae0c
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/historyRuntime.ts
@@ -0,0 +1,718 @@
+import path from 'node:path';
+import { existsSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { and, eq, inArray, isNull, like, or, sql } from 'drizzle-orm';
+import { app, shell } from 'electron';
+import { getDbClient } from '../localDb/client/current.js';
+import { messages, sessions } from '../localDb/schema.js';
+import { withSessionRouteLock } from '../localDb/sessionRouteLock.js';
+import {
+ captureDataOwnerBroadcastScope,
+ isDataOwnerBroadcastScopeCurrent,
+} from '../device-link/broadcast-tap.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { createLogger } from '../logger.js';
+import { cindyMakeManager } from './manager.js';
+import { captureMakeHistoryStore } from './historyOwner.js';
+import { captureMakeHistoryCompletion, captureMakeHistoryReport } from './historyCapture.js';
+import { planFeatureChange } from './featurePlan.js';
+import { taskCommitRef } from './sourceContent.js';
+import { readLegacyFeatureReceipts } from './historyLegacy.js';
+import { integrateMakeHistory, actUpstreamMerge } from './upstreamMergeRuntime.js';
+import { manageCindyMakeTask } from './taskManagement.js';
+import { actCindyMakeTest, cindyMakeTestController } from './testRuntime.js';
+import {
+ makeSourceCheckoutPath,
+ makeSourceRoot,
+ makeTaskWorktreePath,
+ isCindyMakeWorktreePath,
+} from './sourcePaths.js';
+import {
+ createMakeToolchainEnvironment,
+ resolveMakeToolEnvironment,
+} from './toolchainEnvironment.js';
+import { runSourceGit } from './sourceGit.js';
+import { verifyMakeTestWorkspace } from './testRunner.js';
+import {
+ buildCindyPersonal,
+ personalArtifactPath,
+ personalBuildEnvironment,
+ type PersonalArtifact,
+} from './personalBuild.js';
+import { currentVersionProfile, rememberOriginalVersion } from './versionStartup.js';
+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+import {
+ makeHistoryActions,
+ activeFeatureReceipts,
+ type CindyMakeHistoryState,
+ type CindyMakeHistoryItem,
+ type MakeHistoryAction,
+ type MakeHistoryLifecycle,
+ type MakeHistoryIntegration,
+} from '../../shared/cindyMakeHistory.js';
+import type { CindyMakePersonalBuildState } from '../../shared/cindyMakeSession.js';
+import { parseCindyMakeBuildError } from '../../shared/cindyMakeSession.js';
+
+const ID = /^[A-Za-z0-9-]{1,128}$/;
+const HASH = /^[a-f0-9]{40,64}$/i;
+const log = createLogger('cindy-make');
+let running: (id: string) => boolean = () => true;
+let buildJob:
+ | {
+ id: string;
+ current: () => boolean;
+ abort: AbortController;
+ cancelled: boolean;
+ done: Promise<void>;
+ }
+ | undefined;
+export function configureMakeHistory(probe: typeof running): void {
+ running = probe;
+}
+export function stopMakeHistoryBuild(): void {
+ buildJob?.abort.abort();
+}
+/** A stale window cannot stop a newer build or one belonging to another owner. */
+export async function cancelHistoryPersonalVersion(
+ buildId: unknown,
+): Promise<CindyMakeHistoryState> {
+ if (typeof buildId !== 'string' || !ID.test(buildId))
+ throwIpcError('INVALID_PARAMS', 'Invalid build identity');
+ const h = context();
+ const job = buildJob;
+ const build = h.store.readBuild();
+ let stoppingState: CindyMakePersonalBuildState | undefined;
+ if (
+ job &&
+ job.id === buildId &&
+ job.current() &&
+ build?.buildId === buildId &&
+ !['ready', 'failed'].includes(build.status)
+ ) {
+ stoppingState = { ...build, stopping: true };
+ h.store.saveBuild(stoppingState);
+ job.cancelled = true;
+ job.abort.abort();
+ }
+ const next = await getCindyMakeHistory();
+ return stoppingState && next.build?.error === 'cancelled'
+ ? { ...next, build: stoppingState }
+ : next;
+}
+function context() {
+ const client = getDbClient();
+ const owner = captureDataOwnerBroadcastScope();
+ const store = captureMakeHistoryStore();
+ const userData = app.getPath('userData');
+ const current = () => {
+ try {
+ return (
+ isDataOwnerBroadcastScopeCurrent(owner) &&
+ getDbClient() === client &&
+ app.getPath('userData') === userData
+ );
+ } catch {
+ return false;
+ }
+ };
+ const check = () => {
+ if (!current()) throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ };
+ check();
+ return { client, owner, store, userData, current, check };
+}
+async function toolEnvironment(userData: string, signal: AbortSignal, build = false) {
+ const tools = await createMakeToolchainEnvironment(userData);
+ const env = await resolveMakeToolEnvironment(
+ tools,
+ build ? ['git', 'node', 'pnpm', 'python'] : ['git'],
+ signal,
+ );
+ return { tools, env };
+}
+
+/** Hydrate old installations once from their own task facts; ended tasks are deliberately included. */
+export async function getCindyMakeHistory(selectedRunId?: string): Promise<CindyMakeHistoryState> {
+ const h = context();
+ const rows = (
+ await h.client.drizzle.select().from(sessions).where(eq(sessions.source, 'cindy-make'))
+ ).filter(
+ (row) =>
+ !row.remoteHostId && row.workingDir && isCindyMakeWorktreePath(h.userData, row.workingDir),
+ );
+ h.check();
+ const cards: Array<
+ Pick<
+ typeof messages.$inferSelect,
+ 'id' | 'sessionId' | 'clientId' | 'role' | 'content' | 'agentMeta' | 'createdAt'
+ >
+ > = [];
+ for (let start = 0; start < rows.length; start += 100) {
+ cards.push(
+ ...(await h.client.drizzle
+ .select({
+ id: messages.id,
+ sessionId: messages.sessionId,
+ clientId: messages.clientId,
+ role: messages.role,
+ createdAt: messages.createdAt,
+ agentMeta: messages.agentMeta,
+ content: sql<string>`CASE WHEN ${messages.clientId} LIKE 'cindy-make-preparation-%' THEN ${messages.content} ELSE '' END`,
+ })
+ .from(messages)
+ .where(
+ and(
+ inArray(
+ messages.sessionId,
+ rows.slice(start, start + 100).map((row) => row.id),
+ ),
+ isNull(messages.rewindAt),
+ or(
+ eq(messages.role, 'user'),
+ like(messages.clientId, 'cindy-make-preparation-%'),
+ sql`json_type(CASE WHEN json_valid(${messages.agentMeta}) THEN ${messages.agentMeta} ELSE '{}' END, '$.cindyMakeCompletion') = 'object'`,
+ ),
+ ),
+ )),
+ );
+ h.check();
+ }
+ const source = makeSourceCheckoutPath(h.userData);
+ const sourceAvailable = existsSync(path.join(source, '.git'));
+ for (const row of rows) {
+ const runId = path.basename(row.workingDir!);
+ const prep = cards.find(
+ (card) => card.sessionId === row.id && card.clientId === 'cindy-make-preparation-' + runId,
+ );
+ let report;
+ let originalRequest: string | undefined;
+ try {
+ const data = JSON.parse(prep?.content ?? '{}').__cindyMakeCard?.data;
+ report = data?.report;
+ if (typeof data?.request === 'string') originalRequest = data.request;
+ } catch {
+ /* A damaged legacy card is not invented history. */
+ }
+ if (report?.runId === runId && report.task?.sessionId === row.id)
+ captureMakeHistoryReport(report, h.store, row.createdAt);
+ h.store.seed({
+ runId,
+ sessionId: row.id,
+ title: row.title ?? '',
+ request: report?.task?.request ?? originalRequest ?? h.store.read(runId)?.request ?? '',
+ createdAt: row.createdAt,
+ updatedAt: row.updatedAt ?? row.createdAt,
+ });
+ const knownCompletions = new Map(
+ h.store.read(runId)!.completions.map((entry) => [entry.id, entry]),
+ );
+ for (const card of cards.filter((entry) => entry.sessionId === row.id)) {
+ try {
+ const completion = JSON.parse(card.agentMeta ?? '{}').cindyMakeCompletion;
+ if (completion && Number.isFinite(completion.reportedAt)) {
+ const known = knownCompletions.get(card.clientId);
+ const next = { ...completion, id: card.clientId };
+ // A legacy tree was verified against this exact commit; an older card cannot erase it.
+ if (!next.tree && next.commit === known?.commit && known?.tree) next.tree = known.tree;
+ if (!next.baseTree && next.commit === known?.commit && known?.baseTree)
+ next.baseTree = known.baseTree;
+ if (JSON.stringify(next) !== JSON.stringify(known))
+ captureMakeHistoryCompletion(h.store, runId, card.clientId, next);
+ }
+ } catch {
+ /* Invalid legacy metadata cannot authorize an action. */
+ }
+ }
+ }
+ const state = cindyMakeManager.getState();
+ let buildSourceAvailable =
+ sourceAvailable &&
+ (state.source?.currentBranch === undefined || state.source.currentBranch === 'cindy-personal');
+ const pendingMerge =
+ state.upstreamMerge &&
+ state.upstreamMerge.status !== 'merged' &&
+ state.upstreamMerge.hasWorkspace
+ ? state.upstreamMerge
+ : undefined;
+ const busy =
+ !!buildJob || cindyMakeTestController.hasActiveJobs() || cindyMakeManager.hasActiveWork();
+ const items: CindyMakeHistoryItem[] = [];
+ for (const record of h.store.list()) {
+ const row = rows.find((entry) => entry.id === record.sessionId);
+ const report = state.tasks?.[record.runId];
+ const cleanup = state.taskActions?.[record.sessionId];
+ const workspace = makeTaskWorktreePath(h.userData, record.runId);
+ const workspaceAvailable = !record.endedAt && existsSync(path.join(workspace, '.git'));
+ const completion = record.completions.at(-1);
+ const completionMessage = cards.find(
+ (card) => card.sessionId === record.sessionId && card.clientId === completion?.id,
+ );
+ const laterMessage =
+ !completionMessage ||
+ cards.some(
+ (card) =>
+ card.sessionId === record.sessionId &&
+ card.role === 'user' &&
+ (card.createdAt > completionMessage.createdAt ||
+ (card.createdAt === completionMessage.createdAt && card.id > completionMessage.id)),
+ );
+ let completed =
+ !!row &&
+ (row.status === 'active' || record.endedAt !== undefined) &&
+ !!completion &&
+ !completion.continuedAt &&
+ !laterMessage &&
+ HASH.test(completion.commit ?? '') &&
+ HASH.test(completion.tree ?? '');
+ let lifecycle: MakeHistoryLifecycle = record.endedAt
+ ? 'ended'
+ : report?.task?.cleanupPending ||
+ cleanup?.status === 'failed' ||
+ (row?.status === 'deleted' && existsSync(workspace))
+ ? 'cleanup'
+ : row?.status === 'deleted' || !row
+ ? 'ended'
+ : report?.status === 'running'
+ ? 'preparing'
+ : running(record.sessionId)
+ ? 'running'
+ : report?.status === 'failed' || report?.status === 'cancelled'
+ ? 'failed'
+ : completed
+ ? 'ready'
+ : 'editing';
+ let changedSinceCompletion =
+ !!completion?.continuedAt || laterMessage || running(record.sessionId);
+ let verifiedSource = sourceAvailable;
+ let personalHead: string | undefined;
+ if (selectedRunId === record.runId && sourceAvailable && !busy && !pendingMerge) {
+ let checkedBranch = false;
+ try {
+ const signal = AbortSignal.timeout(15000);
+ const { env } = await toolEnvironment(h.userData, signal);
+ h.check();
+ buildSourceAvailable =
+ (await runSourceGit(env, ['branch', '--show-current'], source, signal)) ===
+ 'cindy-personal';
+ checkedBranch = true;
+ if (!buildSourceAvailable) throw new Error('Source branch changed');
+ const git = (args: string[], cwd: string) => runSourceGit(env, args, cwd, signal);
+ personalHead = (await git(['rev-parse', 'HEAD'], source)).trim();
+ if (completion && HASH.test(completion.commit ?? '') && !completion.tree) {
+ const tree = (await git(['rev-parse', completion.commit + '^{tree}'], source)).trim();
+ if (HASH.test(tree)) {
+ h.check();
+ Object.assign(
+ completion,
+ h.store.verifyCompletionFacts(record.runId, completion.id, completion.commit!, {
+ tree,
+ }),
+ );
+ completed =
+ !!row &&
+ (row.status === 'active' || record.endedAt !== undefined) &&
+ !completion.continuedAt &&
+ !laterMessage;
+ if (completed && lifecycle === 'editing') lifecycle = 'ready';
+ }
+ }
+ const legacy = await readLegacyFeatureReceipts(record, git, source);
+ h.check();
+ for (const receipt of legacy) {
+ h.store.receipt(record.runId, receipt);
+ record.receipts.push(receipt);
+ const built = record.completions.find(
+ (entry) => entry.personal?.commit === receipt.commit,
+ )?.personal;
+ if (built)
+ h.store.version(record.runId, {
+ operationId: receipt.id,
+ commit: receipt.commit,
+ versionId: built.versionId,
+ at: built.generatedAt,
+ });
+ }
+ if (legacy.length) record.versions = h.store.read(record.runId)!.versions;
+ if (completion && !completion.baseTree && workspaceAvailable) {
+ const base = await git(
+ ['rev-parse', '--verify', 'refs/cindy-make/tasks/' + record.runId + '/base^{tree}'],
+ source,
+ ).catch(() => '');
+ if (HASH.test(base.trim())) {
+ h.check();
+ Object.assign(
+ completion,
+ h.store.verifyCompletionFacts(record.runId, completion.id, completion.commit!, {
+ baseTree: base.trim(),
+ }),
+ );
+ }
+ }
+ for (const receipt of record.receipts)
+ for (const tree of [receipt.beforeTree, receipt.tree])
+ await runSourceGit(env, ['cat-file', '-e', tree + '^{tree}'], source, signal);
+ if (HASH.test(completion?.commit ?? '') && HASH.test(completion?.tree ?? '')) {
+ try {
+ if (workspaceAvailable) {
+ await verifyMakeTestWorkspace(
+ {
+ userData: h.userData,
+ workingDir: workspace,
+ runId: record.runId,
+ commit: completion!.commit!,
+ tree: completion!.tree,
+ },
+ env,
+ signal,
+ );
+ } else {
+ const savedCommit = (
+ await runSourceGit(
+ env,
+ ['rev-parse', '--verify', taskCommitRef(record.runId) + '^{commit}'],
+ source,
+ signal,
+ )
+ ).trim();
+ const savedTree = (
+ await runSourceGit(env, ['rev-parse', savedCommit + '^{tree}'], source, signal)
+ ).trim();
+ if (savedCommit !== completion!.commit || savedTree !== completion!.tree)
+ throw new Error('Completion commit is not retained');
+ }
+ changedSinceCompletion = false;
+ } catch (error) {
+ if ((error as { code?: string }).code === 'changed') {
+ completed = false;
+ lifecycle = 'editing';
+ changedSinceCompletion = true;
+ } else verifiedSource = false;
+ }
+ }
+ } catch {
+ verifiedSource = false;
+ if (!checkedBranch) buildSourceAvailable = false;
+ }
+ h.check();
+ }
+ const last = record.receipts.at(-1);
+ let integration: MakeHistoryIntegration =
+ last?.action === 'revert'
+ ? 'reverted'
+ : last
+ ? (changedSinceCompletion && lifecycle !== 'ended') || completion?.tree !== last.taskTree
+ ? 'changed'
+ : 'integrated'
+ : !changedSinceCompletion &&
+ completion?.baseTree &&
+ completion.baseTree === completion.tree
+ ? 'unchanged'
+ : 'unintegrated';
+ if (
+ (!verifiedSource && last) ||
+ (!last &&
+ record.completions.some(
+ (entry) =>
+ entry.personal?.status === 'ready' && !Array.isArray(entry.personal.includedFeatures),
+ ))
+ )
+ integration = 'unknown';
+ const operation = pendingMerge?.feature?.runId === record.runId ? pendingMerge : undefined;
+ const version = record.versions.at(-1);
+ const needsBuild =
+ !!last &&
+ (version?.operationId !== last.id || (!!personalHead && version?.commit !== personalHead));
+ const taskBuilding = cindyMakeTestController.isBuilding(record.sessionId);
+ const taskBuild = completion?.personal;
+ const projectedBuild =
+ taskBuild && !taskBuilding && !['ready', 'failed'].includes(taskBuild.status)
+ ? { status: 'failed' as const, error: 'interrupted' as const }
+ : taskBuild;
+ const historyActions = makeHistoryActions({
+ lifecycle,
+ integration,
+ sessionAvailable: !!row && row.status !== 'deleted',
+ workspaceAvailable,
+ sourceAvailable: verifiedSource,
+ completed,
+ buildFailed: completion?.personal?.status === 'failed',
+ needsBuild,
+ buildSourceAvailable,
+ canEdit: row?.status === 'active' && !!record.request.trim(),
+ hasReceipts:
+ last?.action === 'revert'
+ ? last.beforeTree !== last.tree
+ : activeFeatureReceipts(record.receipts).some(
+ (receipt) => receipt.beforeTree !== receipt.tree,
+ ),
+ newChanges: completion?.tree !== last?.taskTree,
+ busy:
+ busy ||
+ (!!pendingMerge && !operation) ||
+ record.runId !== selectedRunId ||
+ running(record.sessionId),
+ conflict: !!operation,
+ recoverableFailure: operation?.status === 'failed' && !operation.feature?.awaitingResolution,
+ });
+ items.push({
+ ...record,
+ lifecycle,
+ integration,
+ build: projectedBuild,
+ completionId: completed ? completion?.id : undefined,
+ resolutionSessionId: operation?.sessionId,
+ conflict: !!operation?.feature?.awaitingResolution,
+ operationError:
+ operation?.error ?? (cleanup?.status === 'failed' ? cleanup.error : undefined),
+ operation:
+ operation && !['failed', 'conflict', 'resolving'].includes(operation.status)
+ ? operation.feature!.action
+ : taskBuilding
+ ? 'build'
+ : cleanup?.status === 'running'
+ ? 'end'
+ : undefined,
+ needsBuild,
+ actions: historyActions,
+ actionReason:
+ historyActions.length === 0
+ ? busy || !!pendingMerge || running(record.sessionId)
+ ? 'busy'
+ : record.runId !== selectedRunId
+ ? 'checking'
+ : !row || row.status === 'deleted'
+ ? 'sessionUnavailable'
+ : completion?.continuedAt || (completion && laterMessage)
+ ? 'changedAfterCompletion'
+ : !completed
+ ? 'completionUnavailable'
+ : !verifiedSource
+ ? 'sourceUnavailable'
+ : 'ended'
+ : undefined,
+ });
+ }
+ let build = h.store.readBuild();
+ if (build && !buildJob && !['ready', 'failed'].includes(build.status)) {
+ build = { status: 'failed', error: 'interrupted' };
+ h.store.saveBuild(build);
+ }
+ h.check();
+ return {
+ items,
+ busy: busy || !!pendingMerge,
+ canBuild: buildSourceAvailable && !busy && !pendingMerge,
+ build,
+ };
+}
+
+export async function actCindyMakeHistory(
+ runId: unknown,
+ action: unknown,
+): Promise<CindyMakeHistoryState> {
+ if (typeof runId !== 'string' || !ID.test(runId) || typeof action !== 'string')
+ throwIpcError('INVALID_PARAMS', 'Invalid history action');
+ const h = context();
+ const state = await getCindyMakeHistory(runId);
+ h.check();
+ const item = state.items.find((entry) => entry.runId === runId);
+ if (!item || !item.actions.includes(action as MakeHistoryAction))
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ if (action === 'build') return generateHistoryPersonalVersion();
+ if (action === 'end' || action === 'retry-cleanup')
+ await manageCindyMakeTask(item.sessionId, 'end');
+ else if (action === 'test' || action === 'continue')
+ await actCindyMakeTest(
+ item.sessionId,
+ item.completionId,
+ action === 'test' ? 'start' : 'continue',
+ );
+ else if (action === 'resolve' || action === 'retry')
+ await actUpstreamMerge({ action: 'resolve' });
+ else if (action === 'integrate' || action === 'revert' || action === 'reapply') {
+ await withSessionRouteLock(item.sessionId, async () => {
+ h.check();
+ if (running(item.sessionId) || cindyMakeManager.isTaskPreparing(item.sessionId))
+ throwIpcError('PRECONDITION_FAILED', 'busy');
+ if (buildJob || cindyMakeTestController.hasActiveJobs() || cindyMakeManager.hasActiveWork())
+ throwIpcError('PRECONDITION_FAILED', 'busy');
+ const [row] = await h.client.drizzle
+ .select()
+ .from(sessions)
+ .where(eq(sessions.id, item.sessionId))
+ .limit(1);
+ h.check();
+ const record = h.store.read(runId)!;
+ if (record.receipts.at(-1)?.id !== item.receipts.at(-1)?.id)
+ throwIpcError('PRECONDITION_FAILED', 'busy');
+ const completion = record.completions.find((entry) => entry.id === item.completionId);
+ if (action === 'integrate') {
+ if (!completion) throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ const signal = AbortSignal.timeout(15000);
+ const { env } = await toolEnvironment(h.userData, signal);
+ const workspaceExists = !!row?.workingDir && existsSync(path.join(row.workingDir, '.git'));
+ if (workspaceExists) {
+ await verifyMakeTestWorkspace(
+ {
+ userData: h.userData,
+ workingDir: row!.workingDir!,
+ runId,
+ commit: completion.commit!,
+ tree: completion.tree,
+ },
+ env,
+ signal,
+ );
+ } else {
+ const savedCommit = (
+ await runSourceGit(
+ env,
+ ['rev-parse', '--verify', taskCommitRef(runId) + '^{commit}'],
+ makeSourceCheckoutPath(h.userData),
+ signal,
+ )
+ ).trim();
+ const savedTree = (
+ await runSourceGit(
+ env,
+ ['rev-parse', savedCommit + '^{tree}'],
+ makeSourceCheckoutPath(h.userData),
+ signal,
+ )
+ ).trim();
+ if (savedCommit !== completion.commit || savedTree !== completion.tree)
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ }
+ h.check();
+ }
+ const plan = planFeatureChange(record, action, completion);
+ if (action === 'integrate' && !plan.mergeCommit && plan.steps.length === 0) return;
+ await integrateMakeHistory(
+ plan,
+ row
+ ? {
+ agentKind: row.agentKind === 'codex' || row.agentKind === 'pi' ? row.agentKind : 'cc',
+ model: row.model ?? undefined,
+ providerId: row.providerId,
+ effort: row.effort ?? undefined,
+ permissionMode: row.permissionMode ?? undefined,
+ }
+ : undefined,
+ );
+ });
+ } else throwIpcError('INVALID_PARAMS', 'This action is handled by task navigation');
+ h.check();
+ return getCindyMakeHistory(runId);
+}
+
+/** A source build has no synthetic task. It packages the current personal branch under the existing project lock. */
+export async function generateHistoryPersonalVersion(): Promise<CindyMakeHistoryState> {
+ const h = context();
+ const state = await getCindyMakeHistory();
+ h.check();
+ if (!state.canBuild || buildJob) throwIpcError('PRECONDITION_FAILED', 'busy');
+ const abort = new AbortController();
+ const buildId = randomUUID();
+ const startedAt = Date.now();
+ const publish = async (build: CindyMakePersonalBuildState) => {
+ h.check();
+ // A late step notification must not erase a requested stop.
+ if (job.cancelled && !['ready', 'failed'].includes(build.status)) return;
+ h.store.saveBuild({ ...build, buildId, startedAt });
+ };
+ const job = { id: buildId, current: h.current, abort, cancelled: false, done: Promise.resolve() };
+ buildJob = job;
+ try {
+ await publish({ status: 'waiting' });
+ } catch (error) {
+ if (buildJob === job) buildJob = undefined;
+ throw error;
+ }
+ job.done = cindyMakeManager
+ .withProjectUse(makeSourceRoot(h.userData), async () => {
+ const watcher = setInterval(() => {
+ if (!h.current()) abort.abort();
+ }, 1000);
+ try {
+ const { tools, env } = await toolEnvironment(h.userData, abort.signal, true);
+ const node = await tools.probe('node', ['--version'], abort.signal);
+ const git = await tools.probe('git', ['--version'], abort.signal);
+ if (!node.path || node.status !== 'ok') throw new Error('environment');
+ await rememberOriginalVersion(node.path);
+ const artifact = await buildCindyPersonal(
+ {
+ mode: 'personal',
+ userData: h.userData,
+ completionId: buildId,
+ title: '',
+ profile: currentVersionProfile(),
+ },
+ node.path,
+ await personalBuildEnvironment(env, git.path),
+ CURRENT_CINDY_REGION,
+ abort.signal,
+ publish,
+ h.check,
+ (run) => cindyMakeManager.withProject(makeSourceRoot(h.userData), run),
+ {
+ features: () =>
+ h.store.list().flatMap((record) => {
+ const last = record.receipts.at(-1);
+ return last ? [{ runId: record.runId, operationId: last.id }] : [];
+ }),
+ },
+ );
+ h.check();
+ recordHistoryBuild(h.store, artifact);
+ await publish({ status: 'ready', ...artifact, generatedAt: Date.now() });
+ } catch (error) {
+ if (h.current())
+ await publish({
+ status: 'failed',
+ error:
+ (error as { code?: unknown })?.code === 'cleanupFailed'
+ ? 'cleanupFailed'
+ : abort.signal.aborted
+ ? job.cancelled
+ ? 'cancelled'
+ : 'interrupted'
+ : parseCindyMakeBuildError((error as { code?: unknown })?.code),
+ });
+ } finally {
+ clearInterval(watcher);
+ }
+ })
+ .catch(() => {
+ log.warn('Could not persist Cindy Make build result');
+ })
+ .finally(() => {
+ if (buildJob === job) buildJob = undefined;
+ });
+ return getCindyMakeHistory();
+}
+export function recordHistoryBuild(
+ store: ReturnType<typeof captureMakeHistoryStore>,
+ artifact: PersonalArtifact,
+): void {
+ for (const feature of artifact.includedFeatures ?? [])
+ store.version(feature.runId, {
+ operationId: feature.operationId,
+ commit: artifact.commit,
+ versionId: artifact.versionId,
+ at: Date.now(),
+ });
+}
+export async function openHistoryPersonalBuild(): Promise<void> {
+ const h = context();
+ const build = h.store.readBuild();
+ if (build?.status !== 'ready' || !build.buildId || !ID.test(build.buildId))
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ try {
+ const file = await personalArtifactPath(h.userData, build.buildId, build as PersonalArtifact);
+ h.check();
+ shell.showItemInFolder(file);
+ } catch {
+ if (h.current()) h.store.saveBuild({ ...build, status: 'failed', error: 'unavailable' });
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/historyStore.ts b/apps/desktop/src/main/cindy-make/historyStore.ts
new file mode 100644
index 0000000000..9d864f33ed
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/historyStore.ts
@@ -0,0 +1,249 @@
+import path from 'node:path';
+import fs from 'node:fs';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+import type {
+ CindyMakeHistoryRecord,
+ MakeFeatureReceipt,
+ MakeHistoryCompletion,
+ MakeHistoryVersion,
+} from '../../shared/cindyMakeHistory.js';
+import type { CindyMakePersonalBuildState } from '../../shared/cindyMakeSession.js';
+import { parseCindyMakeBuildError } from '../../shared/cindyMakeSession.js';
+
+const ID = /^[a-zA-Z0-9-]{1,128}$/;
+const HASH = /^[a-f0-9]{40,64}$/i;
+export function validFeatureReceipt(value: MakeFeatureReceipt): boolean {
+ return (
+ !!value &&
+ ID.test(value.id) &&
+ ['integrate', 'revert', 'reapply'].includes(value.action) &&
+ Number.isFinite(value.at) &&
+ [value.baselineCommit, value.commit, value.beforeTree, value.tree, value.taskTree].every(
+ (hash) => typeof hash === 'string' && HASH.test(hash),
+ )
+ );
+}
+/** A path captured for one owner. Synchronous read/modify/write prevents lost local updates. */
+export class CindyMakeHistoryStore {
+ constructor(readonly directory: string) {}
+ private file(runId: string): string {
+ if (!ID.test(runId)) throw new Error('Invalid Cindy Make history identity');
+ return path.join(this.directory, 'records', runId + '.json');
+ }
+ private assertDirectories(): void {
+ for (const directory of [this.directory, path.join(this.directory, 'records')]) {
+ try {
+ const info = fs.lstatSync(directory);
+ if (!info.isDirectory() || info.isSymbolicLink())
+ throw new Error('Invalid history directory');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ }
+ read(runId: string): CindyMakeHistoryRecord | undefined {
+ const file = this.file(runId);
+ this.assertDirectories();
+ for (const candidate of [file, file + '.bak']) {
+ try {
+ const info = fs.lstatSync(candidate);
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error('Invalid history file');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ const raw = readAtomicFileSync(file);
+ if (raw === null) return;
+ const value = JSON.parse(raw) as CindyMakeHistoryRecord;
+ if (
+ value.schema !== 1 ||
+ value.runId !== runId ||
+ !ID.test(value.sessionId) ||
+ typeof value.title !== 'string' ||
+ typeof value.request !== 'string' ||
+ !Number.isFinite(value.createdAt) ||
+ !Number.isFinite(value.updatedAt) ||
+ !Array.isArray(value.completions) ||
+ !Array.isArray(value.receipts) ||
+ !value.receipts.every(validFeatureReceipt) ||
+ !Array.isArray(value.versions)
+ )
+ throw new Error('Invalid Cindy Make history');
+ return value;
+ }
+ list(): CindyMakeHistoryRecord[] {
+ this.assertDirectories();
+ const records = path.join(this.directory, 'records');
+ let names: string[];
+ try {
+ names = fs.readdirSync(records);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+ const ids = new Set(
+ names
+ .filter((name) => /\.json(?:\.bak)?$/.test(name))
+ .map((name) => name.replace(/\.json(?:\.bak)?$/, ''))
+ .filter((id) => ID.test(id)),
+ );
+ return [...ids]
+ .map((id) => this.read(id))
+ .filter((record): record is CindyMakeHistoryRecord => record !== undefined)
+ .sort((a, b) => b.createdAt - a.createdAt);
+ }
+ save(record: CindyMakeHistoryRecord): void {
+ const file = this.file(record.runId);
+ this.assertDirectories();
+ atomicWriteFileSync(file, JSON.stringify(record));
+ }
+ readBuild(): CindyMakePersonalBuildState | undefined {
+ this.assertDirectories();
+ const file = path.join(this.directory, 'build-state.json');
+ for (const candidate of [file, file + '.bak']) {
+ try {
+ const info = fs.lstatSync(candidate);
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error('Invalid build state');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ const raw = readAtomicFileSync(file);
+ if (raw === null) return;
+ const value = JSON.parse(raw);
+ if (
+ !value ||
+ !['waiting', 'checking', 'merging', 'packaging', 'publishing', 'ready', 'failed'].includes(
+ value.status,
+ )
+ )
+ throw new Error('Invalid build state');
+ // The renderer needs status and version identity, never arbitrary fields read from disk.
+ return {
+ status: value.status,
+ ...(value.stopping === true ? { stopping: true } : {}),
+ ...(Number.isFinite(value.startedAt) && value.startedAt > 0
+ ? { startedAt: value.startedAt }
+ : {}),
+ ...(value.status === 'checking' &&
+ ['dependencies', 'tests', 'types'].includes(value.checkStep)
+ ? { checkStep: value.checkStep }
+ : {}),
+ ...(typeof value.buildId === 'string' && ID.test(value.buildId)
+ ? { buildId: value.buildId }
+ : {}),
+ ...(typeof value.artifactDirectory === 'string' &&
+ path.basename(value.artifactDirectory) === value.artifactDirectory
+ ? { artifactDirectory: value.artifactDirectory }
+ : {}),
+ ...(typeof value.artifactName === 'string' &&
+ path.basename(value.artifactName) === value.artifactName
+ ? { artifactName: value.artifactName }
+ : {}),
+ ...(typeof value.sha256 === 'string' && /^[a-f0-9]{64}$/i.test(value.sha256)
+ ? { sha256: value.sha256 }
+ : {}),
+ ...(typeof value.commit === 'string' && HASH.test(value.commit)
+ ? { commit: value.commit }
+ : {}),
+ ...(typeof value.versionId === 'string' && /^[a-f0-9-]{36}$/.test(value.versionId)
+ ? { versionId: value.versionId }
+ : {}),
+ ...(typeof value.generatedAt === 'number' && Number.isFinite(value.generatedAt)
+ ? { generatedAt: value.generatedAt }
+ : {}),
+ ...(value.status === 'failed' ? { error: parseCindyMakeBuildError(value.error) } : {}),
+ };
+ }
+ saveBuild(state: CindyMakePersonalBuildState): void {
+ this.assertDirectories();
+ atomicWriteFileSync(path.join(this.directory, 'build-state.json'), JSON.stringify(state));
+ }
+ seed(
+ record: Omit<CindyMakeHistoryRecord, 'schema' | 'completions' | 'receipts' | 'versions'>,
+ ): void {
+ const previous = this.read(record.runId);
+ if (previous && previous.sessionId !== record.sessionId)
+ throw new Error('History identity changed');
+ const next = previous
+ ? {
+ ...previous,
+ title: record.title,
+ request: record.request,
+ createdAt: Math.min(record.createdAt, previous.createdAt),
+ updatedAt: Math.max(record.updatedAt, previous.updatedAt),
+ endedAt: previous.endedAt ?? record.endedAt,
+ }
+ : { ...record, schema: 1 as const, completions: [], receipts: [], versions: [] };
+ if (JSON.stringify(previous) !== JSON.stringify(next)) this.save(next);
+ }
+ completion(runId: string, completion: MakeHistoryCompletion): void {
+ const record = this.read(runId);
+ if (!record) return;
+ const index = record.completions.findIndex((item) => item.id === completion.id);
+ const previous = record.completions[index];
+ if (previous && previous.commit === completion.commit)
+ completion = {
+ ...completion,
+ tree: completion.tree ?? previous.tree,
+ baseTree: completion.baseTree ?? previous.baseTree,
+ personal: completion.personal ?? previous.personal,
+ test: completion.test ?? previous.test,
+ lastAction: completion.lastAction ?? previous.lastAction,
+ };
+ if (index < 0) record.completions.push(completion);
+ else if (JSON.stringify(record.completions[index]) === JSON.stringify(completion)) return;
+ else record.completions[index] = completion;
+ record.completions.sort((a, b) => a.reportedAt - b.reportedAt);
+ record.updatedAt = Math.max(record.updatedAt, completion.reportedAt);
+ this.save(record);
+ }
+ receipt(runId: string, receipt: MakeFeatureReceipt): void {
+ const record = this.read(runId);
+ if (!record || !validFeatureReceipt(receipt)) throw new Error('Invalid integration receipt');
+ if (record.receipts.some((entry) => entry.id === receipt.id)) return;
+ record.receipts.push(receipt);
+ record.updatedAt = Math.max(record.updatedAt, receipt.at);
+ this.save(record);
+ }
+ verifyCompletionFacts(
+ runId: string,
+ id: string,
+ commit: string,
+ facts: { tree?: string; baseTree?: string },
+ ): MakeHistoryCompletion | undefined {
+ const record = this.read(runId);
+ const completion = record?.completions.find(
+ (entry) => entry.id === id && entry.commit === commit,
+ );
+ if (
+ !record ||
+ !completion ||
+ Object.values(facts).some((value) => value !== undefined && !HASH.test(value))
+ )
+ return;
+ for (const key of ['tree', 'baseTree'] as const)
+ if (!completion[key] && facts[key]) completion[key] = facts[key];
+ this.save(record);
+ return completion;
+ }
+ version(runId: string, version: MakeHistoryVersion): void {
+ const record = this.read(runId);
+ if (
+ !record ||
+ record.versions.some(
+ (entry) =>
+ entry.operationId === version.operationId &&
+ entry.commit === version.commit &&
+ entry.versionId === version.versionId,
+ )
+ )
+ return;
+ record.versions.push(version);
+ this.save(record);
+ }
+ end(runId: string, at = Date.now()): void {
+ const record = this.read(runId);
+ if (record && !record.endedAt) this.save({ ...record, endedAt: at, updatedAt: at });
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/latestSourceVersion.ts b/apps/desktop/src/main/cindy-make/latestSourceVersion.ts
new file mode 100644
index 0000000000..1353d36615
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/latestSourceVersion.ts
@@ -0,0 +1,111 @@
+import type { MakeSourceLatestVersion, MakeSourceStatus } from '../../shared/cindyMakeDoctor.js';
+import { untilAborted } from './doctor.js';
+
+const API = 'https://api.github.com/repos/makecindy/cindy';
+type Channel = MakeSourceLatestVersion['channel'];
+type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
+const isCommit = (value: unknown): value is string =>
+ typeof value === 'string' && /^[0-9a-f]{40}$/i.test(value);
+const record = (value: unknown): Record<string, unknown> =>
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+
+/** Read-only public version lookup, shared across Settings windows for one minute. */
+export function createLatestSourceVersionReader(fetch: Fetch) {
+ const cache = new Map<
+ Channel,
+ {
+ mainCommit?: string;
+ expires: number;
+ promise: Promise<MakeSourceLatestVersion>;
+ }
+ >();
+
+ async function query(channel: Channel, mainCommit?: string): Promise<MakeSourceLatestVersion> {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10_000);
+ const read = async (endpoint: string): Promise<unknown> => {
+ const response = await untilAborted(
+ fetch(`${API}/${endpoint}`, {
+ signal: controller.signal,
+ redirect: 'error',
+ credentials: 'omit',
+ headers: { accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' },
+ }),
+ controller.signal,
+ );
+ if (!response.ok) throw new Error('Version lookup failed');
+ return untilAborted(response.json(), controller.signal);
+ };
+ const releaseTag = (value: unknown): string | undefined => {
+ const release = record(value);
+ if (release.draft !== false || release.prerelease !== (channel === 'beta')) return;
+ const tag = release.tag_name;
+ const pattern =
+ channel === 'beta' ? /^v\d+\.\d+\.\d+-beta(?:\.[0-9A-Za-z.-]+)?$/ : /^v\d+\.\d+\.\d+$/;
+ return typeof tag === 'string' && pattern.test(tag) ? tag : undefined;
+ };
+ try {
+ let ref: string | undefined = channel === 'dev' ? 'main' : undefined;
+ if (channel === 'release') ref = releaseTag(await read('releases/latest'));
+ if (channel === 'beta') {
+ // GitHub's latest endpoint excludes prereleases. Never fall back to stable.
+ for (let page = 1; page <= 3 && !ref; page++) {
+ const releases = await read(`releases?per_page=100&page=${page}`);
+ if (!Array.isArray(releases)) break;
+ ref = releases.map(releaseTag).find((tag) => tag !== undefined);
+ if (releases.length < 100) break;
+ }
+ }
+ if (!ref) return { status: 'unavailable', channel };
+ // Resolve the tag to its commit, not target_commitish (which can be "main").
+ const commit = record(await read(`commits/${encodeURIComponent(ref)}`)).sha;
+ if (!isCommit(commit)) return { status: 'unavailable', channel };
+ const latest: MakeSourceLatestVersion = { status: 'ready', channel, ref, commit };
+ if (isCommit(mainCommit)) {
+ if (mainCommit === commit) return { ...latest, ahead: 0, behind: 0 };
+ try {
+ const comparison = record(await read(`compare/${mainCommit}...${commit}?per_page=1`));
+ const { ahead_by: behind, behind_by: ahead } = comparison;
+ if (
+ record(comparison.base_commit).sha === mainCommit &&
+ typeof ahead === 'number' &&
+ Number.isSafeInteger(ahead) &&
+ ahead >= 0 &&
+ typeof behind === 'number' &&
+ Number.isSafeInteger(behind) &&
+ behind >= 0
+ ) {
+ latest.ahead = ahead;
+ latest.behind = behind;
+ }
+ } catch {
+ // A local-only commit cannot be compared on GitHub; keep the verified latest hash.
+ }
+ }
+ return latest;
+ } catch {
+ return { status: 'unavailable', channel };
+ } finally {
+ clearTimeout(timeout);
+ }
+ }
+
+ return async (source: MakeSourceStatus, channel: Channel): Promise<MakeSourceStatus> => {
+ if (source.status !== 'ready') return source;
+ let cached = cache.get(channel);
+ if (!cached || cached.mainCommit !== source.mainCommit || cached.expires <= Date.now()) {
+ cached = {
+ mainCommit: source.mainCommit,
+ expires: Date.now() + 60_000,
+ promise: query(channel, source.mainCommit),
+ };
+ cache.set(channel, cached);
+ }
+ const latestVersion = await cached.promise;
+ if (latestVersion.status === 'unavailable' && cache.get(channel) === cached)
+ cache.delete(channel);
+ return { ...source, latestVersion };
+ };
+}
diff --git a/apps/desktop/src/main/cindy-make/localHistory.ts b/apps/desktop/src/main/cindy-make/localHistory.ts
new file mode 100644
index 0000000000..0870e99fad
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/localHistory.ts
@@ -0,0 +1,137 @@
+import path from 'node:path';
+import { lstat } from 'node:fs/promises';
+import { randomUUID } from 'node:crypto';
+import { snapshotContent, PERSONAL_UPSTREAM_REF, type ContentGit } from './sourceContent.js';
+
+export const MAKE_GIT_IDENTITY = [
+ '-c',
+ 'user.name=Cindy Make',
+ '-c',
+ '-c',
+ 'commit.gpgSign=false',
+ '-c',
+ 'core.editor=true',
+];
+export const historyError = (code: 'dirty' | 'baselineChanged' | 'gitFailed') =>
+ Object.assign(new Error(code), { code });
+const HASH = /^[0-9a-f]{40,64}$/i;
+export async function gitOperationExists(
+ git: ContentGit,
+ cwd: string,
+ name: string,
+): Promise<boolean> {
+ const file = (await git(['rev-parse', '--path-format=absolute', '--git-path', name], cwd)).trim();
+ try {
+ await lstat(path.resolve(cwd, file));
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
+ throw error;
+ }
+}
+export async function assertNoGitOperation(
+ git: ContentGit,
+ cwd: string,
+ allowMerge = false,
+): Promise<void> {
+ for (const name of [
+ 'rebase-merge',
+ 'rebase-apply',
+ 'CHERRY_PICK_HEAD',
+ ...(allowMerge ? [] : ['MERGE_HEAD']),
+ ])
+ if (await gitOperationExists(git, cwd, name)) throw historyError('dirty');
+ if ((await git(['ls-files', '--unmerged'], cwd)).trim()) throw historyError('dirty');
+}
+/** Keep original history, staged-only content and working files reachable before any conversion. */
+export async function backupLocalHistory(
+ git: ContentGit,
+ cwd: string,
+ id = randomUUID(),
+): Promise<{ head: string; tree: string }> {
+ const head = (await git(['rev-parse', 'HEAD'], cwd)).trim();
+ const tree = await snapshotContent(git, cwd);
+ const index = (await git(['write-tree'], cwd)).trim();
+ if (![head, tree, index].every((value) => HASH.test(value))) throw historyError('gitFailed');
+ const root = 'refs/cindy-make/history-backups/' + id;
+ await git(['update-ref', root + '/head', head], cwd);
+ await git(['update-ref', root + '/files', tree], cwd);
+ await git(['update-ref', root + '/index', index], cwd);
+ return { head, tree };
+}
+/** Called only at explicit completion/integration boundaries; never pushes or creates empty snapshots. */
+export async function commitLocalFiles(
+ git: ContentGit,
+ cwd: string,
+ message: string,
+ allowMerge = false,
+): Promise<{ commit: string; tree: string }> {
+ await assertNoGitOperation(git, cwd, allowMerge);
+ const tree = await snapshotContent(git, cwd);
+ const before = (await git(['rev-parse', 'HEAD^{tree}'], cwd)).trim();
+ const merging = allowMerge && (await gitOperationExists(git, cwd, 'MERGE_HEAD'));
+ if (tree !== before || merging) {
+ await backupLocalHistory(git, cwd);
+ await git(['diff', '--check', before, tree], cwd);
+ await git(['add', '--all', '--', '.'], cwd);
+ if (
+ (await git(['write-tree'], cwd)).trim() !== tree ||
+ (await snapshotContent(git, cwd)) !== tree
+ )
+ throw historyError('baselineChanged');
+ await git(
+ [
+ ...MAKE_GIT_IDENTITY,
+ 'commit',
+ '--signoff',
+ '--author=Cindy Make <[email protected]>',
+ '-m',
+ message,
+ ],
+ cwd,
+ );
+ }
+ const commit = (await git(['rev-parse', 'HEAD'], cwd)).trim();
+ if (
+ !HASH.test(commit) ||
+ (await git(['rev-parse', 'HEAD^{tree}'], cwd)).trim() !== tree ||
+ (await snapshotContent(git, cwd)) !== tree
+ )
+ throw historyError('baselineChanged');
+ return { commit, tree };
+}
+/** Migrate old file-only integrations: official files become the base, only personal differences are committed. */
+export async function commitPersonalFiles(
+ git: ContentGit,
+ source: string,
+): Promise<{ commit: string; tree: string }> {
+ await assertNoGitOperation(git, source);
+ const recorded = (
+ await git(['rev-parse', '--verify', PERSONAL_UPSTREAM_REF + '^{commit}'], source).catch(
+ (error) => {
+ if ((error as { exitCode?: number }).exitCode === 128) return '';
+ throw error;
+ },
+ )
+ ).trim();
+ const head = (await git(['rev-parse', 'HEAD'], source)).trim();
+ if (recorded && recorded !== head) {
+ let basedOnRecorded = true;
+ try {
+ await git(['merge-base', '--is-ancestor', recorded, head], source);
+ } catch (error) {
+ if ((error as { exitCode?: number }).exitCode !== 1) throw error;
+ basedOnRecorded = false;
+ }
+ if (!basedOnRecorded) {
+ const saved = await backupLocalHistory(git, source);
+ if (saved.head !== head) throw historyError('baselineChanged');
+ // --mixed deliberately keeps every working file. The old index/history also have durable backup refs.
+ await git(['reset', '--mixed', recorded], source);
+ if ((await snapshotContent(git, source)) !== saved.tree)
+ throw historyError('baselineChanged');
+ }
+ }
+ return commitLocalFiles(git, source, 'Cindy Make: preserve personal changes');
+}
diff --git a/apps/desktop/src/main/cindy-make/manager.ts b/apps/desktop/src/main/cindy-make/manager.ts
index 42b34bf498..e040d3adc1 100644
--- a/apps/desktop/src/main/cindy-make/manager.ts
+++ b/apps/desktop/src/main/cindy-make/manager.ts
@@ -110,13 +110,26 @@ export class CindyMakeManager {
>();
private sourceRevision = 0;
private isProjectBusy: (root: string) => boolean = () => false;
+ private mergeSessionCurrent: () => boolean = () => true;
setProjectBusyProbe(probe: (root: string) => boolean): void {
this.isProjectBusy = probe;
}
private projectInUse(root: string): boolean {
- return (this.projectUsers.get(root) ?? 0) > 0 || this.isProjectBusy(root);
+ return (this.projectUsers.get(root) ?? 0) > 0 || this.isProjectBusy(root) ||
+ (!!this.states.upstreamMerge && this.states.upstreamMerge.status !== 'merged' &&
+ (this.states.upstreamMerge.hasWorkspace === true || this.states.upstreamMerge.status !== 'failed'));
+ }
+ /** Active preparation/cleanup must finish before a local application version switch. */
+ hasActiveWork(): boolean {
+ return this.active.size > 0 || this.sourceJobs.size > 0 || this.tasks.size > 0 || this.taskActions.size > 0 || this.projectUsers.size > 0;
+ }
+
+ setUpstreamMerge(state: CindyMakeGlobalState['upstreamMerge'], isCurrent: () => boolean = () => true): void {
+ this.states.upstreamMerge = state;
+ this.mergeSessionCurrent = isCurrent;
+ this.notify();
}
async withProjectUse<T>(root: string, run: () => Promise<T>): Promise<T> {
@@ -167,12 +180,21 @@ export class CindyMakeManager {
this.notify();
}
- async refreshSourceStatus(read: () => Promise<MakeSourceStatus>): Promise<MakeSourceStatus> {
- const revision = this.sourceRevision;
- const status = await read();
- if (revision !== this.sourceRevision && this.states.source)
+ async refreshSourceStatus(
+ read: (publish: (status: MakeSourceStatus) => boolean) => Promise<MakeSourceStatus>,
+ ): Promise<MakeSourceStatus> {
+ let revision = ++this.sourceRevision;
+ // One revision guard spans every stage, including our own intermediate writes.
+ // A preparation/clear or another refresh invalidates all remaining stages.
+ const publish = (status: MakeSourceStatus): boolean => {
+ if (revision !== this.sourceRevision) return false;
+ revision += 1;
+ this.setSourceStatus(status);
+ return revision === this.sourceRevision;
+ };
+ const status = await read(publish);
+ if (!publish(status) && this.states.source)
return structuredClone(this.states.source);
- this.setSourceStatus(status);
return status;
}
@@ -209,6 +231,8 @@ export class CindyMakeManager {
);
}
if (input.signal.aborted) return input.cancelled();
+ if (this.states.upstreamMerge?.hasWorkspace && this.states.upstreamMerge.status !== 'merged')
+ throw Object.assign(new Error('upstream merge is pending'), { code: 'busy' });
if (
input.clearOnly &&
(this.projectInUse(input.root) ||
@@ -377,8 +401,7 @@ export class CindyMakeManager {
// The canonical terminal-session hook runs inside the outer Settings action.
// It must not await its own parent's promise or overwrite its progress.
if (nestedRecycle) return run();
- // A plain archive only checks already-merged work. A later explicit Finish
- // still needs to perform its merge after that background recycle settles.
+ // A later explicit action waits for the existing background recycle to settle.
if (existing.recycleOnly)
return existing.promise
.catch(() => undefined)
@@ -461,7 +484,11 @@ export class CindyMakeManager {
const previous = this.restoredTasks.get(report.runId);
if (previous?.isCurrent()) {
// Runtime execution is projected separately from the persisted preparation.
- restored.task = { ...restored.task!, executing: previous.report.task?.executing };
+ restored.task = {
+ ...restored.task!,
+ executing: previous.report.task?.executing,
+ integration: previous.report.task?.integration,
+ };
if (JSON.stringify(previous.report) === JSON.stringify(restored)) return undefined;
}
this.restoredTasks.set(report.runId, { report: restored, isCurrent });
@@ -560,6 +587,9 @@ export class CindyMakeManager {
};
return structuredClone({
...this.states,
+ ...(this.states.upstreamMerge && !this.mergeSessionCurrent() ? { upstreamMerge: {
+ ...this.states.upstreamMerge, sessionId: undefined, ownedByAnotherAccount: true,
+ } } : {}),
reports: Object.fromEntries(
[...this.reports].flatMap(([runId, entry]) =>
entry.isCurrent() ? [[runId, entry.report]] : [],
diff --git a/apps/desktop/src/main/cindy-make/personalBuild.ts b/apps/desktop/src/main/cindy-make/personalBuild.ts
new file mode 100644
index 0000000000..9035fc11c3
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/personalBuild.ts
@@ -0,0 +1,500 @@
+import path from 'node:path';
+import os from 'node:os';
+import { createHash } from 'node:crypto';
+import { createReadStream } from 'node:fs';
+import { copyFile, lstat, mkdir, mkdtemp, readFile, realpath, unlink } from 'node:fs/promises';
+import originalFs from 'original-fs';
+import { brandExecutableName } from '@cindy/maker-shared/brand-identity';
+import {
+ retainPersonalVersion,
+ publishPersonalVersion,
+ versionDirectory,
+ assertVersionDirectory,
+ type VersionProfile,
+} from './versionStore.js';
+import { defaultPtySpawn, type PtySpawnFn } from '../terminal/ptyFactory.js';
+import { snapshotContent, contentRef, applyContent, taskContentRef } from './sourceContent.js';
+import { runSourceGit } from './sourceGit.js';
+import { runSourcePnpm } from './sourcePnpm.js';
+import { makeSourceCheckoutPath, makeSourceRoot, CINDY_PERSONAL_BRANCH } from './sourcePaths.js';
+import {
+ makeTestEnvironment,
+ verifyMakeTestWorkspace,
+ type MakeTestWorkspace,
+} from './testRunner.js';
+import type { CindyMakePersonalBuildState } from '../../shared/cindyMakeSession.js';
+import { commitLocalFiles, commitPersonalFiles, MAKE_GIT_IDENTITY } from './localHistory.js';
+import { createPersonalBuildCleanup } from './personalBuildCleanup.js';
+
+type BuildError = NonNullable<CindyMakePersonalBuildState['error']>;
+export function personalBuildError(code: BuildError): Error & { code: BuildError } {
+ return Object.assign(new Error(code), { code });
+}
+export type PersonalArtifact = Required<
+ Pick<CindyMakePersonalBuildState, 'artifactDirectory' | 'artifactName' | 'sha256' | 'commit'>
+> & {
+ versionId?: string;
+ tree?: string;
+ includedFeatures?: Array<{ runId: string; operationId: string }>;
+};
+const samePath = (a: string, b: string) =>
+ process.platform === 'win32'
+ ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
+ : path.resolve(a) === path.resolve(b);
+const hashFile = async (file: string) => {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
+ return hash.digest('hex');
+};
+
+/** Resolve only recorded installer files inside this completion's private output directory. */
+export async function personalArtifactPath(
+ userData: string,
+ completionId: string,
+ artifact: PersonalArtifact,
+): Promise<string> {
+ if (
+ !artifact.artifactDirectory.startsWith(completionId + '-') ||
+ path.basename(artifact.artifactDirectory) !== artifact.artifactDirectory ||
+ path.basename(artifact.artifactName) !== artifact.artifactName ||
+ !/\.(exe|dmg|deb|zip)$/i.test(artifact.artifactName)
+ )
+ throw personalBuildError('unavailable');
+ const directory = path.join(makeSourceRoot(userData), 'packages', artifact.artifactDirectory);
+ const file = path.join(directory, artifact.artifactName);
+ const info = await lstat(file);
+ if (
+ !info.isFile() ||
+ info.isSymbolicLink() ||
+ !samePath(
+ await realpath(file),
+ path.join(await realpath(userData), path.relative(userData, file)),
+ ) ||
+ (await hashFile(file)) !== artifact.sha256
+ )
+ throw personalBuildError('unavailable');
+ return file;
+}
+
+export function runPersonalPackageCommand(
+ node: string,
+ args: string[],
+ cwd: string,
+ env: NodeJS.ProcessEnv,
+ signal: AbortSignal,
+ spawn: PtySpawnFn = defaultPtySpawn,
+): Promise<void> {
+ signal.throwIfAborted();
+ return new Promise((resolve, reject) => {
+ const child = spawn(node, args, {
+ cwd,
+ env: makeTestEnvironment(env),
+ cols: 4096,
+ rows: 30,
+ name: 'xterm-256color',
+ });
+ // Drain output so compiler progress cannot block the process; never publish raw build logs.
+ child.onData(() => {});
+ const abort = () => {
+ try {
+ child.kill();
+ } catch {
+ // The process may have exited before cancellation reached it.
+ }
+ };
+ let timedOut = false;
+ const timeout = setTimeout(() => {
+ timedOut = true;
+ abort();
+ }, 60 * 60_000);
+ timeout.unref?.();
+ signal.addEventListener('abort', abort, { once: true });
+ child.onExit(({ exitCode }) => {
+ clearTimeout(timeout);
+ signal.removeEventListener('abort', abort);
+ if (signal.aborted) reject(personalBuildError('interrupted'));
+ else if (timedOut || exitCode !== 0) reject(personalBuildError('buildFailed'));
+ else resolve();
+ });
+ if (signal.aborted) abort();
+ });
+}
+
+export async function personalBuildEnvironment(
+ env: NodeJS.ProcessEnv,
+ gitExecutable?: string,
+): Promise<NodeJS.ProcessEnv> {
+ const result = makeTestEnvironment(env);
+ if (process.platform !== 'win32') return result;
+ const roots = [
+ gitExecutable ? path.dirname(path.dirname(gitExecutable)) : undefined,
+ env.ProgramFiles ? path.join(env.ProgramFiles, 'Git') : undefined,
+ ];
+ const dirs = [
+ ...roots.flatMap((root) =>
+ root ? [path.join(root, 'bin'), path.join(root, 'usr', 'bin')] : [],
+ ),
+ ...result.PATH.split(path.delimiter),
+ ];
+ for (const directory of dirs) {
+ try {
+ if (
+ !(await lstat(path.join(directory, 'bash.exe'))).isFile() ||
+ /^(WindowsApps|System32|Sysnative)$/i.test(path.basename(directory))
+ )
+ continue;
+ return { ...result, PATH: directory.replace(/\\/g, '/') + path.delimiter + result.PATH };
+ } catch {
+ // A missing candidate does not prevent trying the next Git Bash location.
+ }
+ }
+ throw personalBuildError('missingShell');
+}
+
+interface BuildDeps {
+ git?: typeof runSourceGit;
+ pnpm?: typeof runSourcePnpm;
+ packageCommand?: typeof runPersonalPackageCommand;
+ verify?: typeof verifyMakeTestWorkspace;
+ features?: () => Array<{ runId: string; operationId: string }>;
+}
+
+/** Integrate task files first, then build only in the locked cindy-personal checkout. */
+export async function buildCindyPersonal(
+ task: (MakeTestWorkspace | { mode: 'personal'; userData: string }) & {
+ completionId: string;
+ title?: string;
+ profile?: VersionProfile;
+ },
+ node: string,
+ environment: NodeJS.ProcessEnv,
+ region: 'cn' | 'global' | 'dev',
+ signal: AbortSignal,
+ publish: (state: CindyMakePersonalBuildState) => Promise<void>,
+ checkCurrent: () => void,
+ withProject: <T>(operation: () => Promise<T>) => Promise<T>,
+ deps: BuildDeps = {},
+): Promise<PersonalArtifact> {
+ return withProject(async () => {
+ const editingTask = 'mode' in task ? undefined : task;
+ const verifyTask = async () => {
+ if (editingTask)
+ await (deps.verify ?? verifyMakeTestWorkspace)(editingTask, environment, signal);
+ };
+ const source = makeSourceCheckoutPath(task.userData);
+ const merge = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-merge-'));
+ const canonicalMerge = await realpath(merge);
+ let output: string | undefined;
+ let published = false;
+ let versionId: string | undefined;
+ let cleanup: Awaited<ReturnType<typeof createPersonalBuildCleanup>> | undefined;
+ const check = () => {
+ signal.throwIfAborted();
+ checkCurrent();
+ };
+ const git = async (args: string[], cwd = source, indexFile?: string) => {
+ check();
+ return (deps.git ?? runSourceGit)(
+ { ...environment, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args,
+ cwd,
+ signal,
+ );
+ };
+ const pnpm = (args: string[]) => {
+ check();
+ return (deps.pnpm ?? runSourcePnpm)(environment, args, source, signal);
+ };
+ let baseline = '';
+ let baselineTree = '';
+ let candidateTree = '';
+ let taskTree = '';
+ const assertSource = async (tree: string) => {
+ if (
+ (await git(['rev-parse', 'HEAD'])).trim() !== baseline ||
+ (await git(['rev-parse', '--abbrev-ref', 'HEAD'])).trim() !== CINDY_PERSONAL_BRANCH ||
+ (await snapshotContent(git, source)) !== tree
+ )
+ throw personalBuildError('baselineChanged');
+ };
+ try {
+ check();
+ await publish({ status: 'merging' });
+ await verifyTask();
+ const canonicalSource = await realpath(source);
+ if ((await git(['rev-parse', '--abbrev-ref', 'HEAD'])).trim() !== CINDY_PERSONAL_BRANCH)
+ throw personalBuildError('changed');
+ cleanup = await createPersonalBuildCleanup(task.userData, region, (args, cwd) =>
+ (deps.git ?? runSourceGit)(environment, args, cwd, AbortSignal.timeout(30_000)),
+ );
+ await cleanup.clean();
+ const personal = await commitPersonalFiles(git, source);
+ baseline = personal.commit;
+ baselineTree = personal.tree;
+ if (editingTask) {
+ const task = editingTask;
+ taskTree = task.tree ?? (await git(['rev-parse', task.commit + '^{tree}'])).trim();
+ const taskBase =
+ (await contentRef(git, source, taskContentRef(task.runId, 'integrated'))) ??
+ (await contentRef(git, source, taskContentRef(task.runId, 'base'))) ??
+ (
+ await git([
+ 'rev-parse',
+ (await git(['merge-base', baseline, task.commit])).trim() + '^{tree}',
+ ])
+ ).trim();
+ await git(['worktree', 'add', '--detach', merge, baseline]);
+ let candidateCommit: string;
+ try {
+ const committedTaskTree = (await git(['rev-parse', task.commit + '^{tree}'])).trim();
+ if (committedTaskTree === taskTree) {
+ await git(
+ [...MAKE_GIT_IDENTITY, 'merge', '--no-commit', '--no-ff', task.commit],
+ merge,
+ );
+ } else {
+ // Retained pre-upgrade completions have a file snapshot but no task commit yet.
+ await applyContent(git, merge, taskBase, taskTree, true);
+ }
+ const candidate = await commitLocalFiles(
+ git,
+ merge,
+ 'Cindy Make: integrate personal feature',
+ true,
+ );
+ candidateTree = candidate.tree;
+ candidateCommit = candidate.commit;
+ } catch (error) {
+ if ((await git(['ls-files', '--unmerged'], merge)).trim())
+ throw personalBuildError('conflict');
+ throw error;
+ }
+ await (deps.verify ?? verifyMakeTestWorkspace)(task, environment, signal);
+ await assertSource(baselineTree);
+ check();
+ // Adopt the local merge commit before checking/packaging in the real personal checkout.
+ // Cancellation never discards the already integrated commit or the editing worktree.
+ const adoptGit = (args: string[], cwd: string, indexFile?: string) =>
+ (deps.git ?? runSourceGit)(
+ { ...environment, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args,
+ cwd,
+ AbortSignal.timeout(120_000),
+ );
+ await adoptGit(['merge', '--ff-only', candidateCommit], source);
+ await adoptGit(['update-ref', taskContentRef(task.runId, 'integrated'), taskTree], source);
+ baseline = candidateCommit;
+ } else {
+ candidateTree = baselineTree;
+ }
+ const includedFeatures = deps.features?.();
+ check();
+ try {
+ await publish({ status: 'checking', checkStep: 'dependencies' });
+ await pnpm(['install', '--frozen-lockfile', '--prefer-offline', '--prod=false']);
+ await publish({ status: 'checking', checkStep: 'tests' });
+ await pnpm(['test:unit:related']);
+ await publish({ status: 'checking', checkStep: 'types' });
+ await pnpm(['--recursive', '--workspace-concurrency=1', '--if-present', 'typecheck']);
+ } catch {
+ throw personalBuildError(signal.aborted ? 'interrupted' : 'checksFailed');
+ }
+ check();
+ await assertSource(candidateTree);
+ const artifacts = path.join(
+ source,
+ 'apps',
+ 'desktop',
+ 'release',
+ 'artifacts',
+ region,
+ 'unversioned',
+ process.platform + '-' + process.arch,
+ );
+ // This checkout is reused. An old manifest must never make an empty build look successful.
+ try {
+ if (
+ !samePath(
+ await realpath(artifacts),
+ path.join(canonicalSource, path.relative(source, artifacts)),
+ )
+ )
+ throw personalBuildError('unavailable');
+ await unlink(path.join(artifacts, 'build-info.json'));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ await publish({ status: 'packaging' });
+ check();
+ await cleanup.captureManifest();
+ await (deps.packageCommand ?? runPersonalPackageCommand)(
+ node,
+ [
+ path.join(source, 'apps', 'desktop', 'scripts', 'package-desktop.mjs'),
+ '--platform',
+ process.platform,
+ '--arch',
+ process.arch,
+ '--region',
+ region,
+ '--no-sign',
+ ],
+ source,
+ environment,
+ signal,
+ );
+ check();
+ await assertSource(candidateTree);
+ const info = JSON.parse(await readFile(path.join(artifacts, 'build-info.json'), 'utf8'));
+ const installer = Array.isArray(info.files)
+ ? info.files.find((file: { role?: string }) => file.role === 'installer')
+ : undefined;
+ if (
+ info.product !== 'cindy-desktop' ||
+ info.versionless !== true ||
+ info.version !== null ||
+ info.commitSha !== baseline ||
+ info.region !== region ||
+ info.platform !== process.platform ||
+ info.arch !== process.arch ||
+ !installer ||
+ typeof installer.name !== 'string' ||
+ path.basename(installer.name) !== installer.name ||
+ !/\.(exe|dmg|deb|zip)$/i.test(installer.name) ||
+ !/^[0-9a-f]{64}$/i.test(installer.sha256 ?? '')
+ )
+ throw personalBuildError('buildFailed');
+ const installerPath = path.join(artifacts, installer.name);
+ if (
+ !samePath(
+ await realpath(installerPath),
+ path.join(canonicalSource, path.relative(source, installerPath)),
+ ) ||
+ (await hashFile(installerPath)) !== installer.sha256
+ )
+ throw personalBuildError('buildFailed');
+ const packages = path.join(makeSourceRoot(task.userData), 'packages');
+ await mkdir(packages, { recursive: true });
+ if (
+ (await lstat(packages)).isSymbolicLink() ||
+ !samePath(
+ await realpath(packages),
+ path.join(await realpath(task.userData), path.relative(task.userData, packages)),
+ )
+ )
+ throw personalBuildError('unavailable');
+ output = await mkdtemp(path.join(packages, task.completionId + '-'));
+ await copyFile(installerPath, path.join(output, installer.name));
+ const artifact: PersonalArtifact = {
+ artifactDirectory: path.basename(output),
+ artifactName: installer.name,
+ sha256: installer.sha256,
+ commit: baseline,
+ tree: candidateTree,
+ ...(includedFeatures ? { includedFeatures } : {}),
+ };
+ await personalArtifactPath(task.userData, task.completionId, artifact);
+ if (task.profile) {
+ const appName = brandExecutableName(region);
+ const packaged = path.join(
+ source,
+ 'apps',
+ 'desktop',
+ 'out',
+ appName + '-' + process.platform + '-' + process.arch,
+ );
+ versionId = await retainPersonalVersion({
+ profile: task.profile,
+ sourceDirectory:
+ process.platform === 'darwin' ? path.join(packaged, appName + '.app') : packaged,
+ appName,
+ title: task.title ?? '',
+ commit: baseline,
+ tree: candidateTree,
+ });
+ if (versionId) artifact.versionId = versionId;
+ }
+ await publish({ status: 'publishing' });
+ await verifyTask();
+ await cleanup.restoreManifest();
+ await cleanup.clean();
+ await assertSource(candidateTree);
+ check();
+ if (versionId) publishPersonalVersion(task.userData, versionId);
+ published = true;
+ return artifact;
+ } finally {
+ let cleanupFailed = false;
+ // Only the merge candidate is disposable. Never remove the source or editing worktree.
+ const disposable = async () => {
+ try {
+ return (
+ !(await lstat(merge)).isSymbolicLink() &&
+ samePath(await realpath(merge), canonicalMerge)
+ );
+ } catch {
+ return false;
+ }
+ };
+ if (await disposable()) {
+ try {
+ await (deps.git ?? runSourceGit)(
+ environment,
+ ['-c', 'core.longpaths=true', 'worktree', 'remove', '--force', merge],
+ source,
+ AbortSignal.timeout(120_000),
+ );
+ } catch {
+ // A partial Git cleanup can still leave a disposable directory below.
+ }
+ try {
+ if (await disposable())
+ await originalFs.promises.rm(merge, {
+ recursive: true,
+ force: true,
+ maxRetries: 3,
+ retryDelay: 200,
+ });
+ } catch {
+ cleanupFailed = true;
+ }
+ }
+ if (!published && output) {
+ try {
+ if (
+ !(await lstat(output)).isSymbolicLink() &&
+ samePath(
+ await realpath(output),
+ path.join(await realpath(task.userData), path.relative(task.userData, output)),
+ )
+ )
+ await originalFs.promises.rm(output, { recursive: true, force: true });
+ } catch {
+ cleanupFailed = true;
+ }
+ }
+ if (!published && versionId) {
+ const directory = versionDirectory(task.userData, versionId);
+ try {
+ assertVersionDirectory(task.userData, directory);
+ await originalFs.promises.rm(directory, { recursive: true, force: true });
+ } catch {
+ cleanupFailed = true;
+ }
+ }
+ if (cleanup) {
+ try {
+ await cleanup.restoreManifest();
+ } catch {
+ cleanupFailed = true;
+ }
+ try {
+ await cleanup.clean();
+ } catch {
+ cleanupFailed = true;
+ }
+ }
+ if (cleanupFailed && !published) throw personalBuildError('cleanupFailed');
+ }
+ });
+}
diff --git a/apps/desktop/src/main/cindy-make/personalBuildCleanup.ts b/apps/desktop/src/main/cindy-make/personalBuildCleanup.ts
new file mode 100644
index 0000000000..e51505e5e6
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/personalBuildCleanup.ts
@@ -0,0 +1,91 @@
+import path from 'node:path';
+import { lstat, readFile, realpath, writeFile } from 'node:fs/promises';
+import originalFs from 'original-fs';
+import { makeSourceCheckoutPath } from './sourcePaths.js';
+import type { ContentGit } from './sourceContent.js';
+
+const samePath = (a: string, b: string) =>
+ process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
+const cleanupError = () => Object.assign(new Error('cleanupFailed'), { code: 'cleanupFailed' });
+
+/** Only known generated paths in the managed checkout; never a blanket Git clean/reset. */
+export async function createPersonalBuildCleanup(
+ userData: string,
+ region: string,
+ git: ContentGit,
+) {
+ const source = makeSourceCheckoutPath(userData);
+ const canonicalSource = path.join(await realpath(userData), path.relative(userData, source));
+ const assertPath = async (file: string) => {
+ if (!samePath(await realpath(source), canonicalSource)) throw cleanupError();
+ const relative = path.relative(source, file);
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) throw cleanupError();
+ // Check every existing ancestor, including junctions on Windows.
+ let current = source;
+ for (const part of relative.split(path.sep)) {
+ current = path.join(current, part);
+ try {
+ if (
+ (await lstat(current)).isSymbolicLink() ||
+ !samePath(
+ await realpath(current),
+ path.join(canonicalSource, path.relative(source, current)),
+ )
+ )
+ throw cleanupError();
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw error;
+ }
+ }
+ };
+ const generated = [
+ 'apps/desktop/out',
+ 'apps/desktop/.vite',
+ 'apps/desktop/resources/cindy-source.json',
+ `apps/desktop/release/artifacts/${region}/unversioned/${process.platform}-${process.arch}`,
+ ];
+ const clean = async () => {
+ let failed = false;
+ for (const relative of generated) {
+ try {
+ const file = path.join(source, relative);
+ await assertPath(file);
+ // Personal source may have changed these paths into tracked content. Preserve it.
+ if ((await git(['ls-files', '--', relative], source)).trim()) throw cleanupError();
+ await assertPath(file);
+ await originalFs.promises.rm(file, {
+ recursive: true,
+ force: true,
+ maxRetries: 3,
+ retryDelay: 200,
+ });
+ } catch {
+ failed = true;
+ }
+ }
+ if (failed) throw cleanupError();
+ };
+ const manifest = path.join(source, 'apps/desktop/package.json');
+ let original: string | undefined;
+ const captureManifest = async () => {
+ await assertPath(manifest);
+ original = await readFile(manifest, 'utf8').catch((error) => {
+ if (error.code === 'ENOENT') return undefined;
+ throw error;
+ });
+ };
+ const restoreManifest = async () => {
+ if (original === undefined) return;
+ await assertPath(manifest);
+ const current = await readFile(manifest, 'utf8');
+ if (current === original) return;
+ const before = JSON.parse(original);
+ const after = JSON.parse(current);
+ // The packaging script rewrites only version/formatting. Never overwrite other edits.
+ after.version = before.version;
+ if (JSON.stringify(before) !== JSON.stringify(after)) throw cleanupError();
+ await writeFile(manifest, original, 'utf8');
+ };
+ return { clean, captureManifest, restoreManifest };
+}
diff --git a/apps/desktop/src/main/cindy-make/projectAccess.ts b/apps/desktop/src/main/cindy-make/projectAccess.ts
index d4192b0659..0f3bdc5766 100644
--- a/apps/desktop/src/main/cindy-make/projectAccess.ts
+++ b/apps/desktop/src/main/cindy-make/projectAccess.ts
@@ -3,13 +3,13 @@ import path from 'node:path';
import { t } from '../i18n.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { cindyMakeManager } from './manager.js';
-import { isCindyMakeWorktreePath, makeSourceCheckoutPath, makeSourceRoot } from './sourcePaths.js';
+import { isCindyMakeManagedWorktreePath, makeSourceCheckoutPath, makeSourceRoot } from './sourcePaths.js';
export async function assertCindyMakeWorkspace(
userData: string,
workingDir: string,
): Promise<void> {
- if (!isCindyMakeWorktreePath(userData, workingDir)) return;
+ if (!isCindyMakeManagedWorktreePath(userData, workingDir)) return;
try {
const [directory, worktreeGit, sourceGit] = await Promise.all([
lstat(workingDir),
@@ -32,7 +32,7 @@ export async function withCindyMakeProjectUse<T>(
workingDir: string | null | undefined,
run: () => Promise<T>,
): Promise<T> {
- if (!workingDir || !isCindyMakeWorktreePath(userData, workingDir)) return run();
+ if (!workingDir || !isCindyMakeManagedWorktreePath(userData, workingDir)) return run();
try {
return await cindyMakeManager.withProjectUse(makeSourceRoot(userData), async () => {
await assertCindyMakeWorkspace(userData, workingDir);
diff --git a/apps/desktop/src/main/cindy-make/runtimeVersion.ts b/apps/desktop/src/main/cindy-make/runtimeVersion.ts
index 6b58391eee..cabdcdfbdf 100644
--- a/apps/desktop/src/main/cindy-make/runtimeVersion.ts
+++ b/apps/desktop/src/main/cindy-make/runtimeVersion.ts
@@ -11,6 +11,14 @@ const loadedBuild: RuntimeSourceBuild = import.meta.env.CINDY_RUNTIME_SOURCE ??
const validCommit = (value: unknown): value is string =>
typeof value === 'string' && /^[a-f0-9]{40}$/.test(value);
+/** Identity of the loaded bundle, never a later working-tree HEAD. */
+export function getMakeRuntimeSourceIdentity(): { commit?: string; dirty?: boolean } {
+ return {
+ ...(validCommit(loadedBuild.commit) ? { commit: loadedBuild.commit } : {}),
+ ...(loadedBuild.dirty === true ? { dirty: true } : {}),
+ };
+}
+
export type RuntimeGit = (
root: string,
args: string[],
diff --git a/apps/desktop/src/main/cindy-make/sourceContent.ts b/apps/desktop/src/main/cindy-make/sourceContent.ts
new file mode 100644
index 0000000000..271ae15cc9
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/sourceContent.ts
@@ -0,0 +1,112 @@
+import { copyFile, mkdtemp, rm, stat } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+/** A private index is used only for content snapshots, never the user's staging area. */
+export type ContentGit = (args: string[], cwd: string, indexFile?: string) => Promise<string>;
+export const PERSONAL_UPSTREAM_REF = 'refs/cindy-make/personal-upstream';
+export function taskCommitRef(runId: string): string {
+ if (!/^[a-zA-Z0-9-]{1,128}$/.test(runId)) throw new Error('Invalid task identity');
+ return `refs/cindy-make/tasks/${runId}/complete-commit`;
+}
+const HASH = /^[0-9a-f]{40,64}$/i;
+export function taskContentRef(
+ runId: string,
+ kind: 'base' | 'complete' | 'integrated' | 'initialized',
+): string {
+ if (!/^[a-zA-Z0-9-]{1,128}$/.test(runId)) throw new Error('Invalid task identity');
+ return `refs/cindy-make/tasks/${runId}/${kind}`;
+}
+
+export async function contentRef(
+ git: ContentGit,
+ cwd: string,
+ ref: string,
+): Promise<string | undefined> {
+ try {
+ const value = (await git(['rev-parse', '--verify', `${ref}^{tree}`], cwd)).trim();
+ if (!HASH.test(value)) throw new Error('Invalid content snapshot');
+ return value;
+ } catch (error) {
+ if ((error as { exitCode?: number }).exitCode === 128) return undefined;
+ throw error;
+ }
+}
+
+/** Includes tracked and non-ignored new files, leaving branch history and the real index untouched. */
+export async function snapshotContent(git: ContentGit, cwd: string, ref?: string): Promise<string> {
+ if ((await git(['ls-files', '--unmerged'], cwd)).trim())
+ throw Object.assign(new Error('Unresolved file conflicts'), { code: 'dirty' });
+ const temporary = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-content-'));
+ try {
+ const index = path.join(temporary, 'index');
+ const original = (
+ await git(['rev-parse', '--path-format=absolute', '--git-path', 'index'], cwd)
+ ).trim();
+ await copyFile(original, index);
+ await git(['add', '--all', '--', '.'], cwd, index);
+ const tree = (await git(['write-tree'], cwd, index)).trim();
+ if (!HASH.test(tree)) throw new Error('Invalid content snapshot');
+ // Tree refs keep file contents alive through Git GC without creating any commits.
+ if (ref) await git(['update-ref', ref, tree], cwd);
+ return tree;
+ } finally {
+ await rm(temporary, { recursive: true, force: true });
+ }
+}
+
+/** Populate ONLY a newly-created, disposable worktree with an existing snapshot. */
+export async function populateContent(git: ContentGit, cwd: string, tree: string): Promise<void> {
+ if (!HASH.test(tree)) throw new Error('Invalid content snapshot');
+ await git(['read-tree', '--reset', '-u', tree], cwd);
+}
+
+/** Binary patches are files: never pass large diffs through the bounded Git stdout buffer. */
+export async function applyContent(
+ git: ContentGit,
+ cwd: string,
+ before: string,
+ after: string,
+ threeWay = false,
+): Promise<void> {
+ if (!HASH.test(before) || !HASH.test(after)) throw new Error('Invalid content snapshot');
+ if (before === after) return;
+ const temporary = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-patch-'));
+ try {
+ const patch = path.join(temporary, 'changes.patch');
+ await git(
+ [
+ 'diff',
+ '--binary',
+ '--full-index',
+ '--no-ext-diff',
+ '--no-textconv',
+ '--no-renames',
+ `--output=${patch}`,
+ before,
+ after,
+ '--',
+ ],
+ cwd,
+ );
+ if (!(await stat(patch)).size) return;
+ if (threeWay) {
+ // Recovery after files were adopted but their receipt was not persisted.
+ // Only skip when the entire delta is already present, not merely its branch history.
+ try {
+ await git(['apply', '--reverse', '--check', '--whitespace=nowarn', patch], cwd);
+ return;
+ } catch (error) {
+ if ((error as { exitCode?: number }).exitCode !== 1) throw error;
+ }
+ // Conflicts stay in this isolated candidate for explicit resolution.
+ await git(['apply', '--3way', '--index', '--whitespace=nowarn', patch], cwd);
+ } else {
+ // No --reject: Git validates the entire patch before touching any live files.
+ await git(['apply', '--check', '--whitespace=nowarn', patch], cwd);
+ await git(['apply', '--whitespace=nowarn', patch], cwd);
+ }
+ } finally {
+ await rm(temporary, { recursive: true, force: true });
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/sourcePaths.ts b/apps/desktop/src/main/cindy-make/sourcePaths.ts
index 6a8cc4df95..edb3522ef0 100644
--- a/apps/desktop/src/main/cindy-make/sourcePaths.ts
+++ b/apps/desktop/src/main/cindy-make/sourcePaths.ts
@@ -42,3 +42,10 @@ export function isCindyMakeWorktreePath(userData: string, workingDir: string): b
CINDY_MAKE_RUN_ID_PATTERN.test(relative)
);
}
+
+/** Shared filesystem protection only; this does not grant the personal-build harness. */
+export function isCindyMakeManagedWorktreePath(userData: string, workingDir: string): boolean {
+ if (isCindyMakeWorktreePath(userData, workingDir)) return true;
+ const relative = path.relative(path.join(makeSourceRoot(userData), 'merge-worktrees'), path.resolve(workingDir));
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(relative);
+}
diff --git a/apps/desktop/src/main/cindy-make/sourcePnpm.ts b/apps/desktop/src/main/cindy-make/sourcePnpm.ts
index 3f89a1648b..ede8d6e0ac 100644
--- a/apps/desktop/src/main/cindy-make/sourcePnpm.ts
+++ b/apps/desktop/src/main/cindy-make/sourcePnpm.ts
@@ -88,7 +88,7 @@ export async function runSourcePnpm(
signal.throwIfAborted();
// Keep progress visible in a non-TTY/CI process, including lifecycle scripts.
args = ['install', 'fetch'].includes(args[0]) ? [...args, '--reporter=append-only'] : args;
- if (args.some((arg) => !/^[\w.=-]+$/.test(arg))) {
+ if (args.some((arg) => !/^[\w.:=-]+$/.test(arg))) {
throw Object.assign(new Error('unsafe pnpm argument'), { code: 'installFailed' });
}
const file = await resolvePnpm(env);
diff --git a/apps/desktop/src/main/cindy-make/sourcePreparation.ts b/apps/desktop/src/main/cindy-make/sourcePreparation.ts
index 8d673137ca..1cfac53ad6 100644
--- a/apps/desktop/src/main/cindy-make/sourcePreparation.ts
+++ b/apps/desktop/src/main/cindy-make/sourcePreparation.ts
@@ -516,8 +516,8 @@ async function prepareCindySourceInternal(
progress,
}),
);
- // Nobody works in the managed checkout itself (tasks use their own worktrees),
- // so uncommitted changes here mean an older layout or outside tampering.
+ // Successful personal builds intentionally leave uncommitted content here.
+ // Never carry those files across a branch switch.
await emitProgress({
status: 'preparing',
path: sourcePath,
@@ -525,7 +525,11 @@ async function prepareCindySourceInternal(
phase: 'checkingLocal',
});
const dirty = await git(env, ['status', '--porcelain'], sourcePath, signal);
- if (dirty) throw Object.assign(new Error('dirty'), { code: 'dirty' });
+ if (
+ dirty &&
+ (await git(env, ['branch', '--show-current'], sourcePath, signal)).trim() !== CINDY_PERSONAL_BRANCH
+ )
+ throw Object.assign(new Error('dirty'), { code: 'dirty' });
}
if (!(await exists(gitDir))) {
if (await exists(sourcePath)) {
diff --git a/apps/desktop/src/main/cindy-make/sourceRevisions.ts b/apps/desktop/src/main/cindy-make/sourceRevisions.ts
index 3108301152..411e92facf 100644
--- a/apps/desktop/src/main/cindy-make/sourceRevisions.ts
+++ b/apps/desktop/src/main/cindy-make/sourceRevisions.ts
@@ -38,9 +38,14 @@ export async function readSourceRevisions(
const output = await query(args);
return output && /^[0-9a-f]{7,64}$/i.test(output) ? output : undefined;
};
- const baseCommit = upstreamCommit
- ? await readCommit(['merge-base', personalCommit, upstreamCommit])
- : undefined;
+ const recordedUpstream = await readCommit([
+ 'rev-parse',
+ '--verify',
+ 'refs/cindy-make/personal-upstream^{commit}',
+ ]);
+ const baseCommit =
+ recordedUpstream ??
+ (upstreamCommit ? await readCommit(['merge-base', personalCommit, upstreamCommit]) : undefined);
const mainCommit = await readCommit(['rev-parse', '--verify', 'refs/heads/main^{commit}']);
const mainRemoteCommit = await readCommit([
'rev-parse',
diff --git a/apps/desktop/src/main/cindy-make/sourceStatusRefresh.ts b/apps/desktop/src/main/cindy-make/sourceStatusRefresh.ts
new file mode 100644
index 0000000000..7717f26aba
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/sourceStatusRefresh.ts
@@ -0,0 +1,43 @@
+import type { MakeSourceStatus } from '../../shared/cindyMakeDoctor.js';
+import type { CindyMakeManager } from './manager.js';
+
+/** Publish the disk summary before tool discovery, Git inspection and network lookup. */
+export function refreshCindySourceStatus(
+ manager: CindyMakeManager,
+ readers: {
+ readSummary: () => Promise<MakeSourceStatus>;
+ readLocal: () => Promise<MakeSourceStatus>;
+ readLatest: (source: MakeSourceStatus) => Promise<MakeSourceStatus>;
+ },
+): Promise<MakeSourceStatus> {
+ const previous = manager.getState().source;
+ return manager.refreshSourceStatus(async (publish) => {
+ let summary = await readers.readSummary();
+ // Reopening Settings keeps the last known details while checking them again.
+ if (
+ previous?.status === 'ready' &&
+ summary.status === 'ready' &&
+ previous.path === summary.path &&
+ previous.ref === summary.ref &&
+ previous.channel === summary.channel &&
+ previous.version === summary.version
+ )
+ summary = { ...previous, ...summary };
+ if (!publish(summary) || summary.status !== 'ready') return summary;
+
+ let local = await readers.readLocal();
+ // A previous comparison is only meaningful for the same local main commit.
+ if (
+ local.status === 'ready' &&
+ local.path === summary.path &&
+ local.mainCommit &&
+ local.mainCommit === summary.mainCommit &&
+ local.channel === summary.channel &&
+ local.ref === summary.ref &&
+ local.version === summary.version
+ )
+ local = { ...local, latestVersion: summary.latestVersion };
+ if (!publish(local) || local.status !== 'ready') return local;
+ return readers.readLatest(local);
+ });
+}
diff --git a/apps/desktop/src/main/cindy-make/taskCleanup.ts b/apps/desktop/src/main/cindy-make/taskCleanup.ts
index b5f3f55f91..4b8d0c7837 100644
--- a/apps/desktop/src/main/cindy-make/taskCleanup.ts
+++ b/apps/desktop/src/main/cindy-make/taskCleanup.ts
@@ -1,5 +1,6 @@
import { lstat, realpath, rm } from 'node:fs/promises';
import path from 'node:path';
+import { contentRef, snapshotContent, taskContentRef } from './sourceContent.js';
import { runSourceGit } from './sourceGit.js';
import type { CindyMakeTaskError } from '../../shared/cindyMakeDoctor.js';
import {
@@ -11,7 +12,7 @@ import {
makeWorktreesRoot,
} from './sourcePaths.js';
-export type MakeTaskAction = 'finish' | 'delete';
+export type MakeTaskAction = 'end' | 'finish' | 'delete';
export type MakeTaskError = CindyMakeTaskError;
export function taskError(code: MakeTaskError): Error & { code: MakeTaskError } {
return Object.assign(new Error('Cindy Make task ' + code), { code });
@@ -31,7 +32,7 @@ async function exists(target: string): Promise<boolean> {
export async function manageCindyMakeWorkspace(
userData: string,
runId: string,
- action: MakeTaskAction | 'archive',
+ action: MakeTaskAction | 'archive' | 'inspect',
env: NodeJS.ProcessEnv,
signal: AbortSignal,
options: {
@@ -43,13 +44,21 @@ export async function manageCindyMakeWorkspace(
} = {},
): Promise<boolean> {
if (!CINDY_MAKE_RUN_ID_PATTERN.test(runId)) throw taskError('unavailable');
+ // Archiving alone never authorizes deleting a working directory.
+ if (action === 'archive') return false;
+ const discard = action === 'delete' || action === 'end';
const source = makeSourceCheckoutPath(userData);
const target = makeTaskWorktreePath(userData, runId);
const branch = makeTaskBranch(runId);
const check = options.checkCurrent ?? (() => {});
- const git = async (args: string[], cwd = source) => {
+ const git = async (args: string[], cwd = source, indexFile?: string) => {
check();
- return (options.git ?? runSourceGit)(env, args, cwd, signal);
+ return (options.git ?? runSourceGit)(
+ { ...env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args,
+ cwd,
+ signal,
+ );
};
const targetExists = await exists(target);
const samePath = (left: string, right: string) =>
@@ -75,12 +84,13 @@ export async function manageCindyMakeWorkspace(
};
await assertManagedPaths();
if (!(await exists(path.join(source, '.git')))) {
- if (!targetExists && action === 'delete') return true;
+ if (!targetExists && discard) return true;
throw taskError('unavailable');
}
const gitDirectory = await lstat(path.join(source, '.git'));
if (!gitDirectory.isDirectory() || gitDirectory.isSymbolicLink()) throw taskError('unavailable');
const branchExists = !!(await git(['branch', '--list', branch])).trim();
+ if (action === 'inspect' && (!targetExists || !branchExists)) throw taskError('unavailable');
if (!targetExists && !branchExists) return true;
const registrations = async () =>
(await git(['worktree', 'list', '--porcelain', '-z'])).split('\0\0').map((entry) => {
@@ -95,8 +105,7 @@ export async function manageCindyMakeWorkspace(
options.preparedWorkspace?.branch === branch &&
samePath(options.preparedWorkspace.path, target);
const canRemoveResidue = async () => {
- if (action !== 'delete' || !verifiedWorkspace || !branchExists || (await exists(gitMarker)))
- return false;
+ if (!discard || !verifiedWorkspace || !branchExists || (await exists(gitMarker))) return false;
return !(await registrations()).some(
(entry) =>
(entry.directory && samePath(entry.directory, target)) ||
@@ -124,57 +133,48 @@ export async function manageCindyMakeWorkspace(
verifiedWorkspace = true;
}
}
- if (action !== 'delete') {
+ let integrated: string | undefined;
+ const integratedFilesMatch = async () => {
+ if (!integrated || (await snapshotContent(git, target)) !== integrated) return false;
+ const index = (await git(['write-tree'], target)).trim();
+ const headTree = (await git(['rev-parse', 'HEAD^{tree}'], target)).trim();
+ // Preserve staged-only edits that are absent from the integrated file tree.
+ return index === headTree || index === integrated;
+ };
+ if (!discard) {
if (!branchExists) throw taskError('unavailable');
- if (
- targetExists &&
- (await git(['status', '--porcelain', '--untracked-files=all'], target)).trim()
- ) {
- if (action === 'archive') return false;
- throw taskError('dirty');
- }
- const head = (await git(['rev-parse', branch])).trim();
- if (action === 'archive' && (!options.baseCommit || head === options.baseCommit)) return false;
- let merged = false;
- try {
- await git(['merge-base', '--is-ancestor', branch, CINDY_PERSONAL_BRANCH]);
- merged = true;
- } catch (error) {
- if ((error as { exitCode?: number }).exitCode !== 1) throw error;
- }
- if (!merged && action === 'archive') return false;
- if (!merged) {
- if (await exists(path.join(source, '.git', 'MERGE_HEAD'))) throw taskError('dirty');
+ integrated = targetExists
+ ? await contentRef(git, source, taskContentRef(runId, 'integrated'))
+ : undefined;
+ if (integrated) {
+ if (!(await integratedFilesMatch())) return false;
+ } else {
if (
- (await git(['status', '--porcelain', '--untracked-files=all'])).trim() ||
- (await git(['rev-parse', '--abbrev-ref', 'HEAD'])).trim() !== CINDY_PERSONAL_BRANCH
+ targetExists &&
+ (await git(['status', '--porcelain', '--untracked-files=all'], target)).trim()
)
- throw taskError('dirty');
+ return false;
try {
- await git([
- '-c',
- 'user.name=Cindy Make',
- '-c',
- 'user.email=cindy-make@localhost',
- 'merge',
- '--no-edit',
- '--signoff',
- branch,
- ]);
- } catch {
- // The source was clean before our merge. Abort only a merge that Git
- // actually started; a pre-existing merge is never touched.
- if (await exists(path.join(source, '.git', 'MERGE_HEAD'))) await git(['merge', '--abort']);
- throw taskError('conflict');
+ await git(['merge-base', '--is-ancestor', branch, CINDY_PERSONAL_BRANCH]);
+ } catch (error) {
+ if ((error as { exitCode?: number }).exitCode === 1) return false;
+ throw error;
}
}
- // Recheck after merge: external edits must not be discarded by --force.
+ if (action === 'inspect') return true;
+ // Closing a task never integrates files or creates commits. Only reclaim proven content.
if (
targetExists &&
- (await git(['status', '--porcelain', '--untracked-files=all'], target)).trim()
+ (integrated
+ ? !(await integratedFilesMatch())
+ : (await git(['status', '--porcelain', '--untracked-files=all'], target)).trim())
)
throw taskError('dirty');
+ if (integrated)
+ await git(['update-ref', 'refs/cindy-make/tasks/' + runId + '/history', branch]);
}
+ if (action === 'end' && branchExists)
+ await git(['update-ref', 'refs/cindy-make/tasks/' + runId + '/history', branch]);
if (targetExists && registered) {
try {
// pnpm paths routinely exceed Win32's legacy MAX_PATH.
@@ -200,6 +200,6 @@ export async function manageCindyMakeWorkspace(
}
}
if (!targetExists) await git(['worktree', 'prune']);
- if (branchExists) await git(['branch', action === 'delete' ? '-D' : '-d', branch]);
+ if (branchExists) await git(['branch', discard || integrated ? '-D' : '-d', branch]);
return true;
}
diff --git a/apps/desktop/src/main/cindy-make/taskManagement.ts b/apps/desktop/src/main/cindy-make/taskManagement.ts
index a8987f0b80..3c0ee43f39 100644
--- a/apps/desktop/src/main/cindy-make/taskManagement.ts
+++ b/apps/desktop/src/main/cindy-make/taskManagement.ts
@@ -18,10 +18,13 @@ import {
} from './toolchainEnvironment.js';
import { manageCindyMakeWorkspace, taskError, type MakeTaskAction } from './taskCleanup.js';
import type { MakeDoctorReport } from '../../shared/cindyMakeDoctor.js';
+import { captureMakeHistoryReport } from './historyCapture.js';
+import { captureMakeHistoryStore } from './historyOwner.js';
interface TaskManagementRuntime {
isAlive(sessionId: string): boolean | undefined;
isRunning(sessionId: string): boolean;
+ isWorkspaceBusy?(workingDir: string): boolean;
setStatus(
sessionId: string,
patch: { status: 'archived' | 'deleted'; pinnedAt: null },
@@ -34,6 +37,81 @@ export function configureCindyMakeTaskManagement(deps: TaskManagementRuntime): v
runtime = deps;
}
+let integrationRefresh: { isCurrent: () => boolean; done: Promise<void> } | undefined;
+
+/** Refresh cell facts in the background; opening Settings never waits for Git file scans. */
+export function refreshCindyMakeTaskIntegration(): Promise<void> {
+ if (integrationRefresh?.isCurrent()) return integrationRefresh.done;
+ const client = getDbClient();
+ const owner = captureDataOwnerBroadcastScope();
+ const userData = app.getPath('userData');
+ const isCurrent = () => {
+ try {
+ return (
+ isDataOwnerBroadcastScopeCurrent(owner) &&
+ getDbClient() === client &&
+ app.getPath('userData') === userData
+ );
+ } catch {
+ return false;
+ }
+ };
+ const job = { isCurrent, done: Promise.resolve() };
+ integrationRefresh = job;
+ job.done = (async () => {
+ const reports = Object.values(cindyMakeManager.getState().tasks ?? {});
+ if (!reports.length) return;
+ const environment = await createMakeToolchainEnvironment(userData);
+ const env = await resolveMakeToolEnvironment(environment, ['git'], AbortSignal.timeout(15_000));
+ for (const report of reports) {
+ if (!isCurrent()) return;
+ if (!report.task || report.task.finished) continue;
+ await cindyMakeManager.withProject(makeSourceRoot(userData), async () => {
+ if (!isCurrent() || !cindyMakeManager.taskReport(report.runId)?.task) return;
+ const busy = () =>
+ !runtime ||
+ runtime.isRunning(report.task!.sessionId) ||
+ cindyMakeManager.isTaskPreparing(report.task!.sessionId) ||
+ !!cindyMakeManager.getState().taskActions?.[report.task!.sessionId];
+ let integration: NonNullable<MakeDoctorReport['task']>['integration'] = 'unknown';
+ if (!busy()) {
+ try {
+ integration = (await manageCindyMakeWorkspace(
+ userData,
+ report.runId,
+ 'inspect',
+ env,
+ AbortSignal.timeout(15_000),
+ {
+ checkCurrent: () => {
+ if (!isCurrent()) throw taskError('unavailable');
+ },
+ },
+ ))
+ ? 'integrated'
+ : 'unintegrated';
+ } catch {
+ /* Unknown must not be presented as already integrated. */
+ }
+ }
+ if (isCurrent())
+ cindyMakeManager.projectTaskSession(report.runId, {
+ integration: busy() ? 'unknown' : integration,
+ });
+ });
+ }
+ })()
+ .catch(() => {
+ if (!isCurrent()) return;
+ for (const runId of Object.keys(cindyMakeManager.getState().tasks ?? {}))
+ cindyMakeManager.projectTaskSession(runId, { integration: 'unknown' });
+ })
+ .finally(() => {
+ if (integrationRefresh === job) integrationRefresh = undefined;
+ });
+ return job.done;
+}
+
/** Called under the existing terminal-session route lock, after all writers stop. */
export async function recycleCindyMakeTask(
sessionId: string,
@@ -59,8 +137,12 @@ export async function recycleCindyMakeTask(
return;
}
if (action === 'finish' && row.status !== 'archived') throw taskError('unavailable');
+ if (!action && row.status === 'archived') return;
const workingDir = row.workingDir;
const runId = path.basename(workingDir);
+ const featureOperation = cindyMakeManager.getState().upstreamMerge;
+ if (featureOperation?.feature?.taskSessionId === sessionId && featureOperation.status !== 'merged' && featureOperation.hasWorkspace)
+ throw taskError('busy');
const [card] = await db
.select({ content: messages.content, clientId: messages.clientId })
.from(messages)
@@ -80,7 +162,10 @@ export async function recycleCindyMakeTask(
}
})();
const report = content?.__cindyMakeCard?.data?.report as MakeDoctorReport | undefined;
+ const history = captureMakeHistoryStore();
+ if (report) captureMakeHistoryReport(report, history, row.createdAt);
if (report?.task?.finished) {
+ history.end(runId);
cindyMakeManager.forgetTask(runId);
return;
}
@@ -90,7 +175,7 @@ export async function recycleCindyMakeTask(
if (!runtime) throw taskError('busy');
await cindyMakeManager.runTaskAction(
sessionId,
- row.status === 'deleted' ? 'delete' : 'finish',
+ action ?? (row.status === 'deleted' ? 'delete' : 'finish'),
isCurrent,
() =>
cindyMakeManager.withProject(makeSourceRoot(userData), async () => {
@@ -100,7 +185,8 @@ export async function recycleCindyMakeTask(
const env = await resolveMakeToolEnvironment(environment, ['git'], signal);
// Recheck after waiting for project operations and tool discovery. A failed
// close, or another session borrowing this directory, must preserve it.
- if (runtime!.isAlive(sessionId)) throw taskError('busy');
+ if (runtime!.isAlive(sessionId) || runtime!.isWorkspaceBusy?.(workingDir))
+ throw taskError('busy');
const borrowers = await db
.select({ id: sessions.id, status: sessions.status })
.from(sessions)
@@ -112,6 +198,12 @@ export async function recycleCindyMakeTask(
)
)
throw taskError('busy');
+ if (action === 'end' && card && report?.task && !report.task.cleanupPending) {
+ report.task.cleanupPending = true;
+ await updateMessageContent(sessionId, card.clientId, content);
+ checkCurrent();
+ cindyMakeManager.projectTaskSession(runId, { cleanupPending: true });
+ }
const cleaned = await manageCindyMakeWorkspace(
userData,
runId,
@@ -131,7 +223,10 @@ export async function recycleCindyMakeTask(
},
);
checkCurrent();
- if (!cleaned) return;
+ if (!cleaned) {
+ if (action) throw taskError('dirty');
+ return;
+ }
if (card && report?.task) {
await updateMessageContent(sessionId, card.clientId, {
...content,
@@ -139,12 +234,16 @@ export async function recycleCindyMakeTask(
...content.__cindyMakeCard,
data: {
...content.__cindyMakeCard.data,
- report: { ...report, task: { ...report.task, finished: true } },
+ report: {
+ ...report,
+ task: { ...report.task, finished: true, cleanupPending: false },
+ },
},
},
});
}
checkCurrent();
+ history.end(runId);
cindyMakeManager.forgetTask(runId);
}),
true,
@@ -156,7 +255,7 @@ export async function manageCindyMakeTask(sessionId: unknown, action: unknown):
if (
typeof sessionId !== 'string' ||
!/^[a-zA-Z0-9-]{1,128}$/.test(sessionId) ||
- (action !== 'finish' && action !== 'delete')
+ (action !== 'end' && action !== 'finish' && action !== 'delete')
)
throwIpcError('INVALID_PARAMS', 'Invalid Cindy Make action');
const client = getDbClient();
@@ -180,10 +279,14 @@ export async function manageCindyMakeTask(sessionId: unknown, action: unknown):
row.remoteHostId ||
!row.workingDir ||
!isCindyMakeWorktreePath(app.getPath('userData'), row.workingDir) ||
- (row.status === 'deleted' && action !== 'delete')
+ (row.status === 'deleted' && action === 'finish')
)
throwIpcError('NOT_FOUND', 'Cindy Make task unavailable');
if (!runtime) throwIpcError('PRECONDITION_FAILED', 'busy');
+ const featureOperation = cindyMakeManager.getState().upstreamMerge;
+ if (featureOperation?.feature?.taskSessionId === sessionId && featureOperation.status !== 'merged' && featureOperation.hasWorkspace)
+ throwIpcError('PRECONDITION_FAILED', 'busy');
+ if (runtime.isWorkspaceBusy?.(row.workingDir)) throwIpcError('PRECONDITION_FAILED', 'busy');
if (
action === 'finish' &&
(cindyMakeManager.isTaskPreparing(sessionId) || runtime.isRunning(sessionId))
@@ -192,7 +295,8 @@ export async function manageCindyMakeTask(sessionId: unknown, action: unknown):
if (!isCurrent()) throwIpcError('PRECONDITION_FAILED', 'unavailable');
try {
await cindyMakeManager.runTaskAction(sessionId, action, isCurrent, async () => {
- const status = action === 'delete' ? 'deleted' : 'archived';
+ // Ending keeps the conversation. Old deleted tasks may only finish their cleanup.
+ const status = action === 'delete' || row.status === 'deleted' ? 'deleted' : 'archived';
await runtime!.setStatus(sessionId, { status, pinnedAt: null });
await runtime!.recycle(sessionId, status);
if (!isCurrent()) throw taskError('unavailable');
diff --git a/apps/desktop/src/main/cindy-make/taskNote.ts b/apps/desktop/src/main/cindy-make/taskNote.ts
index f915b115fe..c113a49bad 100644
--- a/apps/desktop/src/main/cindy-make/taskNote.ts
+++ b/apps/desktop/src/main/cindy-make/taskNote.ts
@@ -13,7 +13,8 @@ export function buildCindyMakeTaskNote(): string {
'回复时不要把它当作用户的请求,也不要引用或复述它。' +
'当前任务在制作个人版 Cindy:工作目录就是 Cindy 源码仓库。' +
'请按仓库根目录 AGENTS.md 的规则,在这个目录内完成用户提出的修改需求;' +
- '只修改工作区文件,不要 commit、push,也不要改动版本号或打包配置。' +
+ '只在当前任务分支和 worktree 修改文件,不要切换分支,不要修改 main、cindy-personal 或其他工作目录。' +
+ '不要自行提交或推送,也不要改动版本号或打包配置;完成回报后由 Cindy 在本任务分支创建带签名的本地提交,生成个人版时再合入个人分支,永不自动推送。' +
'修改完成并通过仓库要求的提交前检查后,必须调用 cindy_make 的 report_complete 工具并附改动说明;' +
'这是向用户报告完成的唯一方式。'
);
diff --git a/apps/desktop/src/main/cindy-make/taskRuntime.ts b/apps/desktop/src/main/cindy-make/taskRuntime.ts
index e8318e864e..915d6f5448 100644
--- a/apps/desktop/src/main/cindy-make/taskRuntime.ts
+++ b/apps/desktop/src/main/cindy-make/taskRuntime.ts
@@ -36,6 +36,7 @@ import {
type MakeTaskWorkspace,
} from '../../shared/cindyMakeDoctor.js';
import type { DesktopMakerSendResult } from '../maker-host/send-outcome.js';
+import { captureMakeHistoryReport } from './historyCapture.js';
export const CINDY_MAKE_TASK_DISPATCH = Symbol('cindy-make-task-dispatch');
const log = createLogger('cindy-make');
@@ -48,6 +49,20 @@ type SendTask = (
let sendTask: SendTask | undefined;
let readClearBoundary: ((sessionId: string) => number | null) | undefined;
+/** Dispatch a Main-created task without opting it into the personal-build lifecycle. */
+export async function dispatchCindyMakeMergeTask(
+ sessionId: string, message: string, createOpts: Record<string, unknown>,
+ isCurrent: () => boolean, clientId: string,
+): Promise<void> {
+ if (!sendTask || !isCurrent()) throwIpcError('PRECONDITION_FAILED', 'Task runner is not ready');
+ const expectedClearBoundaryMs = readClearBoundary?.(sessionId) ?? null;
+ const sent = await sendTask(sessionId, message, createOpts, {
+ expectedClearBoundaryMs,
+ persistUserMessage: { clientId, content: message, expectedClearBoundaryMs, shouldBroadcast: isCurrent },
+ });
+ if (!sent.accepted) throwIpcError('PRECONDITION_FAILED', 'Could not start upstream merge task');
+}
+
export function configureCindyMakeTaskSender(
sender: SendTask,
getClearBoundary: (sessionId: string) => number | null,
@@ -73,6 +88,7 @@ export async function restoreCindyMakeTaskState(): Promise<void> {
content: messages.content,
clearedAt: sessions.clearedAt,
sessionStatus: sessions.status,
+ createdAt: sessions.createdAt,
})
.from(messages)
.innerJoin(sessions, eq(messages.sessionId, sessions.id))
@@ -106,6 +122,7 @@ export async function restoreCindyMakeTaskState(): Promise<void> {
)
continue;
const savedStatus = report.status;
+ captureMakeHistoryReport(report, undefined, row.createdAt);
if (report.task.finished) {
cindyMakeManager.forgetTask(report.runId);
continue;
@@ -279,6 +296,8 @@ export async function startCindyMakeTask(raw: unknown, sender: number): Promise<
shouldBroadcast: isPreparationCurrent,
},
);
+ checkPreparationCurrent();
+ captureMakeHistoryReport(next);
};
const phase = (
name: NonNullable<MakeDoctorReport['task']>['phase'],
diff --git a/apps/desktop/src/main/cindy-make/taskWorkspace.ts b/apps/desktop/src/main/cindy-make/taskWorkspace.ts
index f64459a77d..fe760d1a25 100644
--- a/apps/desktop/src/main/cindy-make/taskWorkspace.ts
+++ b/apps/desktop/src/main/cindy-make/taskWorkspace.ts
@@ -1,7 +1,8 @@
-import { access, lstat, mkdir } from 'node:fs/promises';
+import { access, lstat, mkdir, realpath } from 'node:fs/promises';
import path from 'node:path';
import type { CindyMakeTaskPreparation, MakeTaskWorkspace } from '../../shared/cindyMakeDoctor.js';
import { runSourceGit } from './sourceGit.js';
+import { contentRef, snapshotContent, applyContent, taskContentRef } from './sourceContent.js';
import { runSourcePnpm } from './sourcePnpm.js';
import {
CINDY_MAKE_RUN_ID_PATTERN,
@@ -49,6 +50,8 @@ export async function createCindyMakeWorktree(
}
const git = deps.git ?? runSourceGit;
const env = deps.processEnvironment;
+ const contentGit = (args: string[], cwd: string, indexFile?: string) =>
+ git({ ...env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) }, args, cwd, signal);
const sourcePath = makeSourceCheckoutPath(userData);
const worktreePath = makeTaskWorktreePath(userData, runId);
const branch = makeTaskBranch(runId);
@@ -85,8 +88,43 @@ export async function createCindyMakeWorktree(
if (current !== branch) {
throw Object.assign(new Error('worktree on unexpected branch'), { code: 'gitFailed' });
}
+ const common = (
+ await git(
+ env,
+ ['rev-parse', '--path-format=absolute', '--git-common-dir'],
+ worktreePath,
+ signal,
+ )
+ ).trim();
+ const canonical = (value: string) =>
+ process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
+ if (
+ canonical(await realpath(common)) !== canonical(await realpath(path.join(sourcePath, '.git')))
+ )
+ throw Object.assign(new Error('foreign worktree'), { code: 'gitFailed' });
+ const tree = await contentRef(contentGit, sourcePath, taskContentRef(runId, 'base'));
+ if (tree && !(await contentRef(contentGit, sourcePath, taskContentRef(runId, 'initialized')))) {
+ // Resume interrupted inheritance only when the task still has the original clean files.
+ const currentTree = await snapshotContent(contentGit, worktreePath);
+ const headTree = (await git(env, ['rev-parse', 'HEAD^{tree}'], worktreePath, signal)).trim();
+ if (currentTree !== tree) {
+ if (currentTree !== headTree)
+ throw Object.assign(new Error('unfinished inheritance with edits'), { code: 'dirty' });
+ await applyContent(contentGit, worktreePath, headTree, tree);
+ }
+ await contentGit(['update-ref', taskContentRef(runId, 'initialized'), tree], sourcePath);
+ }
} else {
onPhase('creating');
+ if (
+ (await git(env, ['branch', '--show-current'], sourcePath, signal)).trim() !==
+ CINDY_PERSONAL_BRANCH
+ )
+ throw Object.assign(new Error('unexpected source branch'), { code: 'gitFailed' });
+ // Persist the file baseline before creation; never replace it on a retry.
+ const baseRef = taskContentRef(runId, 'base');
+ let tree = await contentRef(contentGit, sourcePath, baseRef);
+ if (!tree && !hasBranch) tree = await snapshotContent(contentGit, sourcePath, baseRef);
await mkdir(makeWorktreesRoot(userData), { recursive: true });
if (hasBranch) {
// Branch survived a removed directory (e.g. a manual clean-up). Prune the
@@ -101,6 +139,11 @@ export async function createCindyMakeWorktree(
signal,
);
}
+ if (tree) {
+ const headTree = (await git(env, ['rev-parse', 'HEAD^{tree}'], worktreePath, signal)).trim();
+ await applyContent(contentGit, worktreePath, headTree, tree);
+ await contentGit(['update-ref', taskContentRef(runId, 'initialized'), tree], sourcePath);
+ }
}
return { path: worktreePath, branch, baseCommit: baseCommit.trim() };
}
diff --git a/apps/desktop/src/main/cindy-make/testController.ts b/apps/desktop/src/main/cindy-make/testController.ts
new file mode 100644
index 0000000000..91b5fdc888
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/testController.ts
@@ -0,0 +1,234 @@
+import type {
+ CindyMakeCompletionMeta,
+ CindyMakeTestAction,
+ CindyMakePersonalBuildState,
+} from '../../shared/cindyMakeSession.js';
+import type { PersonalArtifact } from './personalBuild.js';
+import { makeTestError, type MakeTestProcess, type MakeTestWorkspace } from './testRunner.js';
+
+export interface MakeTestContext extends MakeTestWorkspace {
+ title?: string;
+ sessionId: string;
+ completionId: string;
+ meta: CindyMakeCompletionMeta;
+ isCurrent(): boolean;
+}
+
+export interface MakeTestControllerDeps {
+ load(sessionId: string, completionId: string): Promise<MakeTestContext>;
+ save(
+ context: MakeTestContext,
+ patch: Partial<CindyMakeCompletionMeta>,
+ ): Promise<CindyMakeCompletionMeta>;
+ launch(context: MakeTestContext, signal: AbortSignal): Promise<MakeTestProcess>;
+ withUse(context: MakeTestContext, run: () => Promise<void>): Promise<void>;
+ build?(
+ context: MakeTestContext,
+ signal: AbortSignal,
+ publish: (state: CindyMakePersonalBuildState) => Promise<void>,
+ ): Promise<PersonalArtifact>;
+ openBuild?(context: MakeTestContext): Promise<void>;
+ now?: () => number;
+}
+
+interface TestJob {
+ kind: 'test' | 'build';
+ context: MakeTestContext;
+ controller: AbortController;
+ process?: MakeTestProcess;
+ accepted: Promise<CindyMakeCompletionMeta>;
+ finished: Promise<void>;
+}
+
+/** Owns test launches independently of any renderer, and never replays a launch after restart. */
+export function createMakeTestController(deps: MakeTestControllerDeps) {
+ const jobs = new Map<string, TestJob>();
+ const stop = (job: TestJob) => {
+ job.controller.abort();
+ job.process?.stop();
+ };
+ const execute = async (job: TestJob) => {
+ const { context, controller } = job;
+ const check = () => {
+ controller.signal.throwIfAborted();
+ if (!context.isCurrent()) throw makeTestError('unavailable');
+ };
+ const ownerWatch = setInterval(() => {
+ if (!context.isCurrent()) stop(job);
+ }, 1000);
+ ownerWatch.unref?.();
+ try {
+ await deps.withUse(context, async () => {
+ check();
+ if (job.kind === 'build') {
+ if (!deps.build) throw makeTestError('unavailable');
+ const artifact = await deps.build(context, controller.signal, async (state) => {
+ check();
+ context.meta = await deps.save(context, { personal: state });
+ });
+ // The builder returns only after publishing the verified artifact. Preserve that
+ // receipt even if Continue Editing arrived during its final publication.
+ if (!context.isCurrent()) throw makeTestError('unavailable');
+ context.meta = await deps.save(context, {
+ personal: { status: 'ready', ...artifact, generatedAt: (deps.now ?? Date.now)() },
+ });
+ return;
+ }
+ job.process = await deps.launch(context, controller.signal);
+ try {
+ await job.process.ready;
+ check();
+ context.meta = await deps.save(context, { test: { status: 'ready' } });
+ await job.process.closed;
+ if (context.isCurrent())
+ context.meta = await deps.save(context, { test: { status: 'stopped' } });
+ } finally {
+ job.process.stop();
+ await job.process.closed;
+ }
+ });
+ } catch (error) {
+ job.process?.stop();
+ if (context.isCurrent()) {
+ const code = (error as { code?: unknown })?.code;
+ if (job.kind === 'build') {
+ const known = [
+ 'unavailable',
+ 'changed',
+ 'environment',
+ 'missingShell',
+ 'checksFailed',
+ 'conflict',
+ 'baselineChanged',
+ 'interrupted',
+ ];
+ const failure = controller.signal.aborted
+ ? 'interrupted'
+ : typeof code === 'string' && known.includes(code)
+ ? (code as CindyMakePersonalBuildState['error'])
+ : 'buildFailed';
+ await deps
+ .save(context, { personal: { status: 'failed', error: failure } })
+ .catch(() => {});
+ return;
+ }
+ const errorCode =
+ code === 'unavailable' ||
+ code === 'changed' ||
+ code === 'environment' ||
+ code === 'timeout'
+ ? code
+ : 'launchFailed';
+ await deps
+ .save(context, {
+ test: controller.signal.aborted
+ ? { status: 'stopped' }
+ : { status: 'failed', error: errorCode },
+ })
+ .catch(() => {});
+ }
+ } finally {
+ clearInterval(ownerWatch);
+ if (jobs.get(context.sessionId) === job) jobs.delete(context.sessionId);
+ }
+ };
+ return {
+ hasActiveJobs: () => jobs.size > 0,
+ isBuilding: (sessionId: string) => jobs.get(sessionId)?.kind === 'build',
+ async stopTestForBuild(sessionId: string): Promise<void> {
+ const job = jobs.get(sessionId);
+ if (!job || job.kind !== 'test') return;
+ if (!job.context.isCurrent()) throw makeTestError('unavailable');
+ stop(job);
+ await job.accepted.catch(() => {});
+ await job.finished;
+ },
+ isUsingWorkspace(workingDir: string): boolean {
+ return [...jobs.values()].some((job) => job.context.workingDir === workingDir);
+ },
+ stopAll(): void {
+ for (const job of jobs.values()) stop(job);
+ },
+ async act(
+ sessionId: string,
+ completionId: string,
+ action: CindyMakeTestAction,
+ ): Promise<CindyMakeCompletionMeta> {
+ let context = await deps.load(sessionId, completionId);
+ if (!context.isCurrent()) throw makeTestError('unavailable');
+ let previous = jobs.get(sessionId);
+ const matching =
+ previous?.context.completionId === completionId && previous.context.isCurrent();
+ if (action === 'continue') {
+ if (previous && previous.context.isCurrent()) stop(previous);
+ return deps.save(context, { continuedAt: (deps.now ?? Date.now)() });
+ }
+ if (action === 'status') {
+ if (matching) return previous!.accepted.then(() => previous!.context.meta);
+ const patch: Partial<CindyMakeCompletionMeta> = {};
+ if (['starting', 'ready'].includes(context.meta.test?.status ?? ''))
+ patch.test = { status: 'stopped', error: 'interrupted' };
+ if (
+ ['waiting', 'checking', 'merging', 'packaging', 'publishing'].includes(
+ context.meta.personal?.status ?? '',
+ )
+ )
+ patch.personal = { status: 'failed', error: 'interrupted' };
+ if (Object.keys(patch).length) return deps.save(context, patch);
+ return context.meta;
+ }
+ if (action === 'open-build') {
+ if (!deps.openBuild || context.meta.personal?.status !== 'ready')
+ throw makeTestError('unavailable');
+ await deps.openBuild(context);
+ return context.meta;
+ }
+ if (context.meta.continuedAt || !/^[0-9a-f]{7,64}$/i.test(context.commit))
+ throw makeTestError('unavailable');
+ const kind = action === 'build' ? 'build' : 'test';
+ if (kind === 'build' && !deps.build) throw makeTestError('unavailable');
+ while (previous) {
+ if (
+ previous.context.completionId === completionId &&
+ previous.context.isCurrent() &&
+ previous.kind === kind &&
+ !previous.controller.signal.aborted
+ )
+ return previous.accepted.then(() => previous!.context.meta);
+ stop(previous);
+ await previous.accepted.catch(() => {});
+ await previous.finished;
+ context = await deps.load(sessionId, completionId);
+ if (!context.isCurrent() || context.meta.continuedAt) throw makeTestError('unavailable');
+ previous = jobs.get(sessionId);
+ }
+ const job: TestJob = {
+ kind,
+ context,
+ controller: new AbortController(),
+ accepted: Promise.resolve(context.meta),
+ finished: Promise.resolve(),
+ };
+ jobs.set(sessionId, job);
+ job.accepted = deps
+ .save(
+ context,
+ kind === 'test'
+ ? { lastAction: 'test', test: { status: 'starting' } }
+ : { lastAction: 'build', personal: { status: 'waiting' } },
+ )
+ .then(
+ (meta) => {
+ context.meta = meta;
+ job.finished = execute(job);
+ return meta;
+ },
+ (error) => {
+ if (jobs.get(sessionId) === job) jobs.delete(sessionId);
+ throw error;
+ },
+ );
+ return job.accepted;
+ },
+ };
+}
diff --git a/apps/desktop/src/main/cindy-make/testRunner.ts b/apps/desktop/src/main/cindy-make/testRunner.ts
new file mode 100644
index 0000000000..74addd9a2d
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/testRunner.ts
@@ -0,0 +1,305 @@
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+import { lstat, realpath } from 'node:fs/promises';
+import { defaultPtySpawn, type PtySpawnFn } from '../terminal/ptyFactory.js';
+import { snapshotContent } from './sourceContent.js';
+import { runSourceGit } from './sourceGit.js';
+import {
+ CINDY_MAKE_RUN_ID_PATTERN,
+ makeSourceCheckoutPath,
+ makeSourceRoot,
+ makeTaskBranch,
+ makeTaskWorktreePath,
+ makeWorktreesRoot,
+} from './sourcePaths.js';
+import type { CindyMakeTestState } from '../../shared/cindyMakeSession.js';
+
+export type MakeTestError = NonNullable<CindyMakeTestState['error']>;
+export function makeTestError(code: MakeTestError): Error & { code: MakeTestError } {
+ return Object.assign(new Error(code), { code });
+}
+
+const OS_ENV_KEYS = new Set([
+ 'path',
+ 'home',
+ 'userprofile',
+ 'appdata',
+ 'localappdata',
+ 'temp',
+ 'tmp',
+ 'tmpdir',
+ 'systemroot',
+ 'windir',
+ 'comspec',
+ 'pathext',
+ 'programfiles',
+ 'programfiles(x86)',
+ 'programdata',
+ 'allusersprofile',
+ 'username',
+ 'user',
+ 'logname',
+ 'shell',
+ 'lang',
+ 'lc_all',
+ 'lc_ctype',
+ 'pnpm_home',
+ 'corepack_home',
+ 'node_extra_ca_certs',
+ 'ssl_cert_file',
+ 'ssl_cert_dir',
+ 'http_proxy',
+ 'https_proxy',
+ 'all_proxy',
+ 'no_proxy',
+ 'python',
+ 'npm_config_python',
+ 'pythonutf8',
+ 'pythondontwritebytecode',
+ 'corepack_enable_network',
+ 'corepack_enable_auto_pin',
+ 'corepack_enable_download_prompt',
+ 'npm_config_manage_package_manager_versions',
+ 'npm_config_managepackagemanagerversions',
+ 'pnpm_manage_package_manager_versions',
+]);
+
+/** Do not inherit the host's profile, harness credentials, Node hooks or dev overrides. */
+export function makeTestEnvironment(environment: NodeJS.ProcessEnv): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [key, value] of Object.entries(environment)) {
+ if (key.toLowerCase() !== 'path' && value !== undefined && OS_ENV_KEYS.has(key.toLowerCase()))
+ env[key] = value;
+ }
+ env.PATH = (environment.PATH ?? environment.Path ?? '')
+ .split(path.delimiter)
+ .filter((directory) => path.isAbsolute(directory))
+ .join(path.delimiter);
+ env.TERM = 'xterm-256color';
+ env.FORCE_COLOR = '0';
+ return env;
+}
+
+export interface MakeTestWorkspace {
+ userData: string;
+ workingDir: string;
+ runId: string;
+ commit: string;
+ tree?: string;
+}
+
+export async function verifyMakeTestWorkspace(
+ task: MakeTestWorkspace,
+ env: NodeJS.ProcessEnv,
+ signal: AbortSignal,
+): Promise<void> {
+ const samePath = (a: string, b: string) =>
+ process.platform === 'win32'
+ ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
+ : path.resolve(a) === path.resolve(b);
+ if (
+ !CINDY_MAKE_RUN_ID_PATTERN.test(task.runId) ||
+ !samePath(task.workingDir, makeTaskWorktreePath(task.userData, task.runId))
+ )
+ throw makeTestError('unavailable');
+ const profile = await realpath(task.userData);
+ for (const directory of [
+ makeSourceRoot(task.userData),
+ makeSourceCheckoutPath(task.userData),
+ path.join(makeSourceCheckoutPath(task.userData), '.git'),
+ makeWorktreesRoot(task.userData),
+ task.workingDir,
+ ]) {
+ signal.throwIfAborted();
+ const info = await lstat(directory);
+ if (
+ !info.isDirectory() ||
+ info.isSymbolicLink() ||
+ !samePath(
+ await realpath(directory),
+ path.join(profile, path.relative(task.userData, directory)),
+ )
+ )
+ throw makeTestError('unavailable');
+ }
+ const git = (args: string[], cwd = task.workingDir, indexFile?: string) =>
+ runSourceGit(
+ { ...env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args,
+ cwd,
+ signal,
+ );
+ const common = (await git(['rev-parse', '--git-common-dir'])).trim();
+ if (
+ !samePath(
+ await realpath(path.resolve(task.workingDir, common)),
+ await realpath(path.join(makeSourceCheckoutPath(task.userData), '.git')),
+ )
+ )
+ throw makeTestError('unavailable');
+ if ((await git(['rev-parse', '--abbrev-ref', 'HEAD'])).trim() !== makeTaskBranch(task.runId))
+ throw makeTestError('unavailable');
+ if (
+ (await git(['rev-parse', 'HEAD'])).trim() !== task.commit ||
+ (task.tree
+ ? (await snapshotContent(git, task.workingDir)) !== task.tree
+ : (await git(['status', '--porcelain', '--untracked-files=all'])).trim())
+ )
+ throw makeTestError('changed');
+ for (const file of ['.git', path.join('scripts', 'desktop-restart-runner.mjs')]) {
+ const fullPath = path.join(task.workingDir, file);
+ const info = await lstat(fullPath);
+ if (
+ !info.isFile() ||
+ info.isSymbolicLink() ||
+ !samePath(
+ await realpath(fullPath),
+ path.join(profile, path.relative(task.userData, fullPath)),
+ )
+ )
+ throw makeTestError('unavailable');
+ }
+ signal.throwIfAborted();
+}
+
+export interface MakeTestProcess {
+ ready: Promise<void>;
+ closed: Promise<void>;
+ stop(): void;
+}
+
+/** The existing restart pipeline keeps its TTY runner without opening a terminal window. */
+export function launchMakeTest(
+ task: MakeTestWorkspace,
+ node: string,
+ environment: NodeJS.ProcessEnv,
+ region: 'cn' | 'global',
+ signal: AbortSignal,
+ spawn: PtySpawnFn = defaultPtySpawn,
+): MakeTestProcess {
+ signal.throwIfAborted();
+ const sandbox =
+ 'make-' +
+ createHash('sha256')
+ .update(task.userData + ':' + task.runId)
+ .digest('hex')
+ .slice(0, 20);
+ const child = spawn(
+ node,
+ [
+ path.join(task.workingDir, 'scripts', 'desktop-restart-runner.mjs'),
+ '--wait-ready',
+ '--region=' + region,
+ '--isolated=' + sandbox,
+ '--passive',
+ ],
+ {
+ cwd: task.workingDir,
+ env: makeTestEnvironment(environment),
+ // Keep the machine-readable identity lines intact even with long profile paths.
+ cols: 4096,
+ rows: 30,
+ name: 'xterm-256color',
+ },
+ );
+ let resolveReady!: () => void;
+ let rejectReady!: (error: Error) => void;
+ let resolveClosed!: () => void;
+ const ready = new Promise<void>((resolve, reject) => {
+ resolveReady = resolve;
+ rejectReady = reject;
+ });
+ const closed = new Promise<void>((resolve) => {
+ resolveClosed = resolve;
+ });
+ let settled = false;
+ let stopped = false;
+ let stopping = false;
+ let pending = '';
+ let verdict: Record<string, string> | undefined;
+ const timeout = setTimeout(() => fail('timeout'), 25 * 60_000);
+ const finish = () => {
+ if (stopped) return;
+ stopped = true;
+ clearTimeout(timeout);
+ signal.removeEventListener('abort', abort);
+ if (!settled) {
+ settled = true;
+ rejectReady(makeTestError('interrupted'));
+ }
+ resolveClosed();
+ };
+ const stop = () => {
+ if (stopped || stopping) return;
+ stopping = true;
+ clearTimeout(timeout);
+ if (!settled) {
+ settled = true;
+ rejectReady(makeTestError('interrupted'));
+ }
+ try {
+ child.kill();
+ } catch {
+ finish();
+ }
+ };
+ const fail = (code: MakeTestError) => {
+ if (!settled) {
+ settled = true;
+ rejectReady(makeTestError(code));
+ }
+ stop();
+ };
+ const abort = () => stop();
+ signal.addEventListener('abort', abort, { once: true });
+ child.onExit(() => {
+ if (!settled) {
+ settled = true;
+ rejectReady(makeTestError('launchFailed'));
+ }
+ finish();
+ });
+ child.onData((data) => {
+ // Only keep bounded protocol lines, never persist compiler output or environment contents.
+ pending = (pending + data).slice(-32_768);
+ const lines = pending.split(/\r?\n/);
+ pending = lines.pop() ?? '';
+ for (const raw of lines) {
+ const line = raw.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '').trim();
+ if (line === 'DESKTOP_DEV_VERDICT=failed') {
+ fail('launchFailed');
+ return;
+ }
+ if (line === 'DESKTOP_DEV_VERDICT=ready') {
+ verdict = {};
+ continue;
+ }
+ if (!verdict) continue;
+ const match = /^(mode|sandbox|root|commit|pid|region)=(.*)$/.exec(line);
+ if (match) verdict[match[1]] = match[2];
+ if (!verdict.pid || !verdict.region || settled) continue;
+ const root = path.resolve(verdict.root ?? '');
+ const expected = path.resolve(task.workingDir);
+ const sameRoot =
+ process.platform === 'win32'
+ ? root.toLowerCase() === expected.toLowerCase()
+ : root === expected;
+ if (
+ !sameRoot ||
+ verdict.commit !== task.commit ||
+ verdict.mode !== 'isolated' ||
+ verdict.sandbox !== sandbox ||
+ verdict.region !== region ||
+ !/^[1-9][0-9]*$/.test(verdict.pid)
+ ) {
+ fail('launchFailed');
+ return;
+ }
+ settled = true;
+ clearTimeout(timeout);
+ resolveReady();
+ }
+ });
+ if (signal.aborted) stop();
+ return { ready, closed, stop };
+}
diff --git a/apps/desktop/src/main/cindy-make/testRuntime.ts b/apps/desktop/src/main/cindy-make/testRuntime.ts
new file mode 100644
index 0000000000..dcc42201f2
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/testRuntime.ts
@@ -0,0 +1,341 @@
+import path from 'node:path';
+import { and, desc, eq, gt, isNull, sql } from 'drizzle-orm';
+import { app, shell } from 'electron';
+import { getDbClient } from '../localDb/client/current.js';
+import { messages, sessions } from '../localDb/schema.js';
+import { broadcastMessageAgentMetaUpdate } from '../localDb/ipc/messages.js';
+import { withSessionRouteLock } from '../localDb/sessionRouteLock.js';
+import {
+ captureDataOwnerBroadcastScope,
+ isDataOwnerBroadcastScopeCurrent,
+} from '../device-link/broadcast-tap.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+import type {
+ CindyMakeCompletionMeta,
+ CindyMakeTestAction,
+} from '../../shared/cindyMakeSession.js';
+import { createMakeTestController, type MakeTestContext } from './testController.js';
+import { launchMakeTest, makeTestError, verifyMakeTestWorkspace } from './testRunner.js';
+import {
+ createMakeToolchainEnvironment,
+ resolveMakeToolEnvironment,
+} from './toolchainEnvironment.js';
+import { cindyMakeManager } from './manager.js';
+import { isCindyMakeWorktreePath, makeSourceRoot } from './sourcePaths.js';
+import {
+ buildCindyPersonal,
+ personalArtifactPath,
+ personalBuildEnvironment,
+ type PersonalArtifact,
+} from './personalBuild.js';
+import { untilAborted } from './doctor.js';
+import { currentVersionProfile, rememberOriginalVersion } from './versionStartup.js';
+import { captureMakeHistoryStore } from './historyOwner.js';
+import { captureMakeHistoryCompletion } from './historyCapture.js';
+
+let isRunning: (sessionId: string) => boolean = () => true;
+export function configureCindyMakeTestRuntime(probe: typeof isRunning): void {
+ isRunning = probe;
+}
+
+interface StoredContext extends MakeTestContext {
+ client: ReturnType<typeof getDbClient>;
+ scope: ReturnType<typeof captureDataOwnerBroadcastScope>;
+}
+
+function readCompletion(agentMeta: string | null): CindyMakeCompletionMeta {
+ try {
+ const meta = JSON.parse(agentMeta ?? '{}').cindyMakeCompletion;
+ if (meta && typeof meta.reportedAt === 'number' && Number.isFinite(meta.reportedAt))
+ return meta;
+ } catch {}
+ throw makeTestError('unavailable');
+}
+
+async function load(sessionId: string, completionId: string): Promise<StoredContext> {
+ const client = getDbClient();
+ const scope = captureDataOwnerBroadcastScope();
+ const isCurrent = () => {
+ try {
+ return isDataOwnerBroadcastScopeCurrent(scope) && getDbClient() === client;
+ } catch {
+ return false;
+ }
+ };
+ const db = client.drizzle;
+ const [row] = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);
+ const userData = app.getPath('userData');
+ if (
+ !isCurrent() ||
+ !row ||
+ row.source !== 'cindy-make' ||
+ row.remoteHostId ||
+ row.status !== 'active' ||
+ !row.workingDir ||
+ !isCindyMakeWorktreePath(userData, row.workingDir)
+ )
+ throw makeTestError('unavailable');
+ const [card] = await db
+ .select()
+ .from(messages)
+ .where(
+ and(
+ eq(messages.sessionId, sessionId),
+ eq(messages.role, 'assistant'),
+ isNull(messages.rewindAt),
+ sql`json_type(CASE WHEN json_valid(${messages.agentMeta}) THEN ${messages.agentMeta} ELSE '{}' END, '$.cindyMakeCompletion') = 'object'`,
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(1);
+ if (
+ !isCurrent() ||
+ !card ||
+ card.clientId !== completionId ||
+ (row.clearedAt && card.createdAt <= row.clearedAt)
+ )
+ throw makeTestError('unavailable');
+ const [laterUser] = await db
+ .select({ id: messages.id })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.sessionId, sessionId),
+ eq(messages.role, 'user'),
+ isNull(messages.rewindAt),
+ gt(messages.createdAt, card.createdAt),
+ ),
+ )
+ .limit(1);
+ if (!isCurrent() || laterUser) throw makeTestError('unavailable');
+ const meta = readCompletion(card.agentMeta);
+ return {
+ sessionId,
+ completionId,
+ title: row.title ?? undefined,
+ meta,
+ client,
+ scope,
+ isCurrent,
+ userData,
+ workingDir: row.workingDir,
+ runId: path.basename(row.workingDir),
+ commit: meta.commit ?? '',
+ tree: meta.tree,
+ };
+}
+
+async function save(
+ context: MakeTestContext,
+ patch: Partial<CindyMakeCompletionMeta>,
+): Promise<CindyMakeCompletionMeta> {
+ return withSessionRouteLock(context.sessionId, async () => {
+ if (!context.isCurrent()) throw makeTestError('unavailable');
+ const fresh = await load(context.sessionId, context.completionId);
+ if (!context.isCurrent() || fresh.workingDir !== context.workingDir)
+ throw makeTestError('unavailable');
+ const next = { ...fresh.meta, ...patch };
+ // One owner-bound SQL write; preserve unrelated metadata that may arrive concurrently.
+ const result = await fresh.client.drizzle
+ .update(messages)
+ .set({
+ agentMeta: sql`json_set(${messages.agentMeta}, '$.cindyMakeCompletion', json(${JSON.stringify(next)}))`,
+ })
+ .where(
+ and(
+ eq(messages.sessionId, context.sessionId),
+ eq(messages.clientId, context.completionId),
+ isNull(messages.rewindAt),
+ ),
+ )
+ .returning({ id: messages.id });
+ if (!context.isCurrent() || !result.length) throw makeTestError('unavailable');
+ captureMakeHistoryCompletion(
+ captureMakeHistoryStore(),
+ context.runId,
+ context.completionId,
+ next,
+ );
+ await broadcastMessageAgentMetaUpdate(context.sessionId, context.completionId, fresh.scope);
+ return next;
+ });
+}
+
+export const cindyMakeTestController = createMakeTestController({
+ load,
+ save,
+ withUse: (context, run) => cindyMakeManager.withProjectUse(makeSourceRoot(context.userData), run),
+ build: (context, signal, publish) => {
+ let entered = false;
+ const waiting = new AbortController();
+ const abortWaiting = () => {
+ if (!entered) waiting.abort();
+ };
+ signal.addEventListener('abort', abortWaiting, { once: true });
+ if (signal.aborted) abortWaiting();
+ const work = cindyMakeManager.withProject(
+ makeSourceRoot(context.userData) + ':personal-build',
+ async () => {
+ entered = true;
+ signal.throwIfAborted();
+ const fresh = await load(context.sessionId, context.completionId);
+ if (
+ !context.isCurrent() ||
+ fresh.workingDir !== context.workingDir ||
+ fresh.meta.continuedAt ||
+ isRunning(context.sessionId) ||
+ cindyMakeManager.isTaskPreparing(context.sessionId)
+ )
+ throw makeTestError('unavailable');
+ const environment = await createMakeToolchainEnvironment(context.userData);
+ const env = await resolveMakeToolEnvironment(
+ environment,
+ ['git', 'node', 'pnpm', 'python'],
+ signal,
+ ).catch(() => {
+ throw makeTestError('environment');
+ });
+ const node = await environment.probe('node', ['--version'], signal);
+ const git = await environment.probe('git', ['--version'], signal);
+ if (node.status !== 'ok' || !node.path || !path.isAbsolute(node.path))
+ throw makeTestError('environment');
+ const buildEnv = await personalBuildEnvironment(env, git.path);
+ await rememberOriginalVersion(node.path);
+ const historyStore = captureMakeHistoryStore();
+ return buildCindyPersonal(
+ {
+ mode: 'personal',
+ userData: context.userData,
+ completionId: context.completionId,
+ title: context.title,
+ profile: currentVersionProfile(),
+ },
+ node.path,
+ buildEnv,
+ CURRENT_CINDY_REGION,
+ signal,
+ publish,
+ () => {
+ if (!context.isCurrent()) throw makeTestError('unavailable');
+ },
+ (run) => cindyMakeManager.withProject(makeSourceRoot(context.userData), run),
+ {
+ features: () =>
+ historyStore.list().flatMap((record) => {
+ const last = record.receipts.at(-1);
+ return last ? [{ runId: record.runId, operationId: last.id }] : [];
+ }),
+ },
+ );
+ },
+ signal,
+ );
+ return untilAborted(work, waiting.signal).finally(() =>
+ signal.removeEventListener('abort', abortWaiting),
+ );
+ },
+ openBuild: async (context) => {
+ try {
+ const artifact = await personalArtifactPath(
+ context.userData,
+ context.completionId,
+ context.meta.personal as PersonalArtifact,
+ );
+ if (!context.isCurrent()) throw makeTestError('unavailable');
+ shell.showItemInFolder(artifact);
+ } catch {
+ if (context.isCurrent())
+ await save(context, { personal: { status: 'failed', error: 'unavailable' } });
+ throw makeTestError('unavailable');
+ }
+ },
+ launch: (context, signal) =>
+ cindyMakeManager.withProject(
+ makeSourceRoot(context.userData),
+ async () => {
+ signal.throwIfAborted();
+ const fresh = await load(context.sessionId, context.completionId);
+ if (
+ !context.isCurrent() ||
+ fresh.workingDir !== context.workingDir ||
+ fresh.meta.continuedAt ||
+ isRunning(context.sessionId) ||
+ cindyMakeManager.isTaskPreparing(context.sessionId)
+ )
+ throw makeTestError('unavailable');
+ const environment = await createMakeToolchainEnvironment(context.userData);
+ const env = await resolveMakeToolEnvironment(
+ environment,
+ ['git', 'node', 'pnpm'],
+ signal,
+ ).catch(() => {
+ throw makeTestError('environment');
+ });
+ await verifyMakeTestWorkspace(context, env, signal);
+ const node = await environment.probe('node', ['--version'], signal);
+ if (node.status !== 'ok' || !node.path || !path.isAbsolute(node.path))
+ throw makeTestError('environment');
+ signal.throwIfAborted();
+ if (!context.isCurrent()) throw makeTestError('unavailable');
+ return launchMakeTest(
+ context,
+ node.path,
+ env,
+ CURRENT_CINDY_REGION === 'cn' ? 'cn' : 'global',
+ signal,
+ );
+ },
+ signal,
+ ),
+});
+
+export async function actCindyMakeTest(
+ sessionId: unknown,
+ completionId: unknown,
+ action: unknown,
+): Promise<CindyMakeCompletionMeta> {
+ if (
+ typeof sessionId !== 'string' ||
+ !/^[A-Za-z0-9-]{1,128}$/.test(sessionId) ||
+ typeof completionId !== 'string' ||
+ !/^[A-Za-z0-9-]{1,128}$/.test(completionId) ||
+ typeof action !== 'string' ||
+ !['start', 'continue', 'status', 'build', 'open-build'].includes(action)
+ )
+ throwIpcError('INVALID_PARAMS', 'Invalid Cindy Make test action');
+ try {
+ if (action === 'build' && !cindyMakeTestController.isBuilding(sessionId)) {
+ await cindyMakeTestController.stopTestForBuild(sessionId);
+ const context = await load(sessionId, completionId);
+ const { getCindyMakeHistory, actCindyMakeHistory } = await import('./historyRuntime.js');
+ const history = await getCindyMakeHistory(context.runId);
+ if (!context.isCurrent()) throw makeTestError('unavailable');
+ if (
+ !['integrated', 'unchanged'].includes(
+ history.items.find((item) => item.runId === context.runId)?.integration ?? '',
+ )
+ ) {
+ const updated = await actCindyMakeHistory(context.runId, 'integrate');
+ if (
+ updated.items.find((item) => item.runId === context.runId)?.integration !== 'integrated'
+ )
+ return save(context, {
+ lastAction: 'build',
+ personal: { status: 'failed', error: 'conflict' },
+ });
+ }
+ }
+ return await cindyMakeTestController.act(
+ sessionId,
+ completionId,
+ action as CindyMakeTestAction,
+ );
+ } catch (error) {
+ const code = (error as { code?: unknown })?.code;
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ code === 'environment' || code === 'changed' ? code : 'unavailable',
+ );
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/upstreamMerge.ts b/apps/desktop/src/main/cindy-make/upstreamMerge.ts
new file mode 100644
index 0000000000..fc48b3effd
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/upstreamMerge.ts
@@ -0,0 +1,482 @@
+import path from 'node:path';
+import { mkdir, readFile, realpath } from 'node:fs/promises';
+import type {
+ CindyMakeMergeError,
+ CindyMakeMergeState,
+ MakeFeatureMergePlan,
+} from '../../shared/cindyMakeMerge.js';
+import { CINDY_PERSONAL_BRANCH, makeSourceCheckoutPath, makeSourceRoot } from './sourcePaths.js';
+
+import {
+ snapshotContent,
+ applyContent,
+ PERSONAL_UPSTREAM_REF,
+ type ContentGit,
+} from './sourceContent.js';
+import {
+ assertNoGitOperation,
+ commitLocalFiles,
+ commitPersonalFiles,
+ gitOperationExists,
+ MAKE_GIT_IDENTITY,
+} from './localHistory.js';
+
+export type MergeGit = ContentGit;
+function ownedGit(git: MergeGit, isCurrent: () => boolean): MergeGit {
+ return (args, cwd, indexFile) => {
+ if (!isCurrent()) throw mergeError('busy');
+ return git(args, cwd, indexFile);
+ };
+}
+const COMMIT = /^[0-9a-f]{40}$/i;
+const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+export const mergeError = (code: CindyMakeMergeError) => Object.assign(new Error(code), { code });
+const samePath = (a: string, b: string) =>
+ process.platform === 'win32'
+ ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
+ : path.resolve(a) === path.resolve(b);
+
+export function mergeWorktree(userData: string, id: string): string {
+ if (!ID.test(id)) throw mergeError('unavailable');
+ return path.join(makeSourceRoot(userData), 'merge-worktrees', id);
+}
+export const mergeBranch = (id: string) => {
+ if (!ID.test(id)) throw mergeError('unavailable');
+ return `cindy-merge/${id}`;
+};
+
+async function assertSource(userData: string, git: MergeGit): Promise<string> {
+ const source = makeSourceCheckoutPath(userData);
+ if (
+ !samePath(await realpath(source), source) ||
+ !samePath((await git(['rev-parse', '--show-toplevel'], source)).trim(), source) ||
+ (await git(['branch', '--show-current'], source)).trim() !== CINDY_PERSONAL_BRANCH
+ ) {
+ throw mergeError('unavailable');
+ }
+ return source;
+}
+
+/** The candidate must belong to this managed repository and its dedicated merge branch. */
+export async function verifyMergeWorktree(
+ userData: string,
+ state: CindyMakeMergeState,
+ git: MergeGit,
+): Promise<string> {
+ const worktree = mergeWorktree(userData, state.id);
+ if (
+ !state.baselineCommit ||
+ !COMMIT.test(state.baselineCommit) ||
+ !COMMIT.test(state.upstreamCommit)
+ )
+ throw mergeError('unavailable');
+ const source = makeSourceCheckoutPath(userData);
+ let branch = (await git(['branch', '--show-current'], worktree)).trim();
+ if (!branch && state.strategy === 'rebase') {
+ for (const backend of ['rebase-merge', 'rebase-apply']) {
+ const nameFile = (
+ await git(
+ ['rev-parse', '--path-format=absolute', '--git-path', backend + '/head-name'],
+ worktree,
+ )
+ ).trim();
+ const name = await readFile(nameFile, 'utf8').catch((error) => {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return '';
+ throw error;
+ });
+ if (name.trim() === 'refs/heads/' + mergeBranch(state.id)) branch = mergeBranch(state.id);
+ }
+ }
+ if (
+ !samePath(await realpath(worktree), worktree) ||
+ !samePath(
+ (await git(['rev-parse', '--path-format=absolute', '--git-common-dir'], worktree)).trim(),
+ path.join(source, '.git'),
+ ) ||
+ branch !== mergeBranch(state.id)
+ ) {
+ throw mergeError('unavailable');
+ }
+ return worktree;
+}
+
+/** Rebase only in the retained candidate, then move the clean personal checkout to its result. */
+export async function applyUpstreamMerge(
+ userData: string,
+ state: CindyMakeMergeState,
+ git: MergeGit,
+ isCurrent: () => boolean = () => true,
+): Promise<CindyMakeMergeState> {
+ if (!isCurrent()) throw mergeError('busy');
+ const worktree = await verifyMergeWorktree(userData, state, git);
+ if (state.feature) return applyFeatureMerge(userData, state, git, isCurrent);
+ if (state.strategy === 'rebase') {
+ if ((await git(['ls-files', '--unmerged'], worktree)).trim()) throw mergeError('dirty');
+ if (
+ (await gitOperationExists(git, worktree, 'rebase-merge')) ||
+ (await gitOperationExists(git, worktree, 'rebase-apply'))
+ ) {
+ try {
+ await git([...MAKE_GIT_IDENTITY, 'rebase', '--continue'], worktree);
+ } catch (error) {
+ if ((await git(['ls-files', '--unmerged'], worktree)).trim())
+ return { ...state, status: 'conflict', error: undefined };
+ throw error;
+ }
+ }
+ const result = await commitLocalFiles(git, worktree, 'Cindy Make: resolve upstream rebase');
+ await git(['merge-base', '--is-ancestor', state.upstreamCommit, result.commit], worktree);
+ try {
+ await git(['diff', '--check', state.upstreamCommit, result.commit], worktree);
+ } catch {
+ throw mergeError('checksFailed');
+ }
+ const source = await assertSource(userData, git);
+ await assertNoGitOperation(git, source);
+ const head = (await git(['rev-parse', 'HEAD'], source)).trim();
+ const tree = await snapshotContent(git, source);
+ const alreadyApplied = head === result.commit && tree === result.tree;
+ if (
+ !alreadyApplied &&
+ (head !== state.baselineCommit ||
+ tree !== state.baselineTree ||
+ (await git(['status', '--porcelain', '--untracked-files=all'], source)).trim())
+ )
+ throw mergeError('baselineChanged');
+ if (!isCurrent()) throw mergeError('busy');
+ if (!alreadyApplied) await git(['reset', '--keep', result.commit], source);
+ if ((await snapshotContent(git, source)) !== result.tree) throw mergeError('baselineChanged');
+ await git(['update-ref', PERSONAL_UPSTREAM_REF, state.upstreamCommit], source);
+ return {
+ ...state,
+ status: 'merged',
+ commit: result.commit,
+ tree: result.tree,
+ error: undefined,
+ };
+ }
+ const commit = (await git(['rev-parse', 'HEAD'], worktree)).trim();
+ if (state.baselineTree && commit !== state.baselineCommit) throw mergeError('baselineChanged');
+ // Legacy candidates may already contain historical commits. Preserve them as file content.
+ if (!state.baselineTree) {
+ await git(['merge-base', '--is-ancestor', state.baselineCommit!, commit], worktree);
+ const pending = (
+ await git(['rev-parse', '--verify', 'MERGE_HEAD'], worktree).catch(() => '')
+ ).trim();
+ if (pending !== state.upstreamCommit)
+ await git(['merge-base', '--is-ancestor', state.upstreamCommit, commit], worktree);
+ }
+ const tree = await snapshotContent(git, worktree);
+ const before =
+ state.baselineTree ??
+ (await git(['rev-parse', state.baselineCommit + '^{tree}'], worktree)).trim();
+ try {
+ await git(['diff', '--check', before, tree], worktree);
+ } catch {
+ throw mergeError('checksFailed');
+ }
+ const source = await assertSource(userData, git);
+ const sourceHead = (await git(['rev-parse', 'HEAD'], source)).trim();
+ const sourceTree = await snapshotContent(git, source);
+ let legacyAlreadyApplied = !state.baselineTree && sourceHead === commit && sourceTree === tree;
+ if (
+ sourceTree === tree &&
+ (await git(['rev-parse', '--verify', PERSONAL_UPSTREAM_REF], source).catch(() => '')).trim() ===
+ state.upstreamCommit
+ ) {
+ try {
+ await git(['merge-base', '--is-ancestor', state.upstreamCommit, sourceHead], source);
+ legacyAlreadyApplied = true;
+ } catch (error) {
+ if ((error as { exitCode?: number }).exitCode !== 1) throw error;
+ }
+ }
+ if (
+ !legacyAlreadyApplied &&
+ (sourceHead !== state.baselineCommit || (sourceTree !== before && sourceTree !== tree))
+ )
+ throw mergeError('baselineChanged');
+ if (!isCurrent()) throw mergeError('busy');
+ if (sourceTree !== tree) await applyContent(git, source, before, tree);
+ await git(['update-ref', PERSONAL_UPSTREAM_REF, state.upstreamCommit], source);
+ const adopted = await commitPersonalFiles(git, source);
+ return {
+ ...state,
+ status: 'merged',
+ commit: adopted.commit,
+ tree: adopted.tree,
+ error: undefined,
+ };
+}
+
+/** Work through retained deltas. A conflict advances only after its resolved files are committed. */
+async function runFeatureSteps(
+ userData: string,
+ initial: CindyMakeMergeState,
+ git: MergeGit,
+ publish: (state: CindyMakeMergeState) => Promise<void>,
+): Promise<CindyMakeMergeState> {
+ let state = initial;
+ const worktree = await verifyMergeWorktree(userData, state, git);
+ let feature = { ...state.feature! };
+ if (feature.awaitingResolution) {
+ if ((await git(['ls-files', '--unmerged'], worktree)).trim())
+ return { ...state, status: 'conflict' };
+ await commitLocalFiles(git, worktree, 'Cindy Make: resolve feature conflict', true);
+ feature = { ...feature, awaitingResolution: false, nextStep: feature.nextStep + 1 };
+ state = { ...state, feature };
+ await publish(state);
+ }
+ const count = feature.mergeCommit ? 1 : feature.steps.length;
+ for (let index = feature.nextStep; index < count; index += 1) {
+ try {
+ if (feature.mergeCommit) {
+ if (await gitOperationExists(git, worktree, 'MERGE_HEAD')) {
+ if ((await git(['rev-parse', 'MERGE_HEAD'], worktree)).trim() !== feature.mergeCommit)
+ throw mergeError('baselineChanged');
+ // A previous commit hook can fail after merge applied its files. Finalize that merge.
+ } else
+ await git(
+ [...MAKE_GIT_IDENTITY, 'merge', '--no-commit', '--no-ff', feature.mergeCommit],
+ worktree,
+ );
+ } else
+ await applyContent(
+ git,
+ worktree,
+ feature.steps[index].before,
+ feature.steps[index].after,
+ true,
+ );
+ await commitLocalFiles(
+ git,
+ worktree,
+ 'Cindy Make: ' + feature.action + ' ' + feature.runId,
+ true,
+ );
+ } catch (error) {
+ if (!(await git(['ls-files', '--unmerged'], worktree)).trim()) throw error;
+ state = {
+ ...state,
+ status: 'conflict',
+ feature: { ...feature, nextStep: index, awaitingResolution: true },
+ };
+ await publish(state);
+ return state;
+ }
+ feature = { ...feature, nextStep: index + 1 };
+ state = { ...state, feature };
+ await publish(state);
+ }
+ return state;
+}
+
+export async function prepareFeatureMerge(
+ userData: string,
+ initial: CindyMakeMergeState,
+ plan: MakeFeatureMergePlan,
+ git: MergeGit,
+ publish: (state: CindyMakeMergeState) => Promise<void>,
+ isCurrent: () => boolean = () => true,
+): Promise<CindyMakeMergeState> {
+ git = ownedGit(git, isCurrent);
+ const source = await assertSource(userData, git);
+ const baseline = await commitPersonalFiles(git, source);
+ const worktree = mergeWorktree(userData, initial.id);
+ await mkdir(path.dirname(worktree), { recursive: true });
+ if (!samePath(await realpath(path.dirname(worktree)), path.dirname(worktree)))
+ throw mergeError('unavailable');
+ let feature = { ...plan };
+ if (
+ feature.mergeCommit &&
+ (await git(['rev-parse', feature.mergeCommit + '^{tree}'], source)).trim() !== feature.taskTree
+ ) {
+ // Upgrade a file-only completion using its preserved creation baseline.
+ const before = (
+ await git(['rev-parse', 'refs/cindy-make/tasks/' + feature.runId + '/base^{tree}'], source)
+ ).trim();
+ feature = { ...feature, mergeCommit: undefined, steps: [{ before, after: feature.taskTree }] };
+ }
+ const state: CindyMakeMergeState = {
+ ...initial,
+ upstreamCommit: baseline.commit,
+ baselineCommit: baseline.commit,
+ baselineTree: baseline.tree,
+ ref: 'personal',
+ status: 'merging',
+ hasWorkspace: true,
+ feature,
+ };
+ await publish(state);
+ await git(
+ ['update-ref', 'refs/cindy-make/features/' + state.id + '/before', baseline.commit],
+ source,
+ );
+ await git(
+ ['update-ref', 'refs/cindy-make/features/' + state.id + '/task', feature.taskTree],
+ source,
+ );
+ await git(['worktree', 'add', '-b', mergeBranch(state.id), worktree, baseline.commit], source);
+ const prepared = await runFeatureSteps(userData, state, git, publish);
+ return prepared.status === 'conflict'
+ ? prepared
+ : applyFeatureMerge(userData, prepared, git, isCurrent);
+}
+
+/** Adopts only a complete candidate; source history is never rewound to undo one feature. */
+export async function applyFeatureMerge(
+ userData: string,
+ initial: CindyMakeMergeState,
+ git: MergeGit,
+ isCurrent: () => boolean = () => true,
+ publish: (state: CindyMakeMergeState) => Promise<void> = async () => {},
+): Promise<CindyMakeMergeState> {
+ git = ownedGit(git, isCurrent);
+ const state = await runFeatureSteps(userData, initial, git, publish);
+ if (state.status === 'conflict' && state.feature?.awaitingResolution) return state;
+ const worktree = await verifyMergeWorktree(userData, state, git);
+ const candidate = await commitLocalFiles(git, worktree, 'Cindy Make: resolve personal feature');
+ const source = await assertSource(userData, git);
+ await assertNoGitOperation(git, source);
+ const head = (await git(['rev-parse', 'HEAD'], source)).trim();
+ const tree = await snapshotContent(git, source);
+ const applied = head === candidate.commit && tree === candidate.tree;
+ if (
+ !applied &&
+ (head !== state.baselineCommit ||
+ tree !== state.baselineTree ||
+ (await git(['status', '--porcelain'], source)).trim())
+ )
+ throw mergeError('baselineChanged');
+ await git(['merge-base', '--is-ancestor', state.baselineCommit!, candidate.commit], source);
+ await git(['diff', '--check', state.baselineTree!, candidate.tree], source);
+ if (!isCurrent()) throw mergeError('busy');
+ await git(
+ ['update-ref', 'refs/cindy-make/features/' + state.id + '/after', candidate.commit],
+ source,
+ );
+ if (!applied) await git(['merge', '--ff-only', candidate.commit], source);
+ if ((await snapshotContent(git, source)) !== candidate.tree) throw mergeError('baselineChanged');
+ if (state.feature!.action !== 'revert')
+ await git(
+ [
+ 'update-ref',
+ 'refs/cindy-make/tasks/' + state.feature!.runId + '/integrated',
+ state.feature!.taskTree,
+ ],
+ source,
+ );
+ else
+ await git(
+ ['update-ref', '-d', 'refs/cindy-make/tasks/' + state.feature!.runId + '/integrated'],
+ source,
+ );
+ return {
+ ...state,
+ status: 'merged',
+ commit: candidate.commit,
+ tree: candidate.tree,
+ error: undefined,
+ };
+}
+
+/** Fetch a pinned official commit and try the merge away from the user's personal checkout. */
+export async function prepareUpstreamMerge(
+ userData: string,
+ initial: CindyMakeMergeState,
+ git: MergeGit,
+ publish: (state: CindyMakeMergeState) => Promise<void>,
+): Promise<CindyMakeMergeState> {
+ const worktree = mergeWorktree(userData, initial.id);
+ if (!COMMIT.test(initial.upstreamCommit)) throw mergeError('unavailable');
+ const source = await assertSource(userData, git);
+ await assertNoGitOperation(git, source);
+ await git(
+ ['fetch', '--no-tags', 'https://github.com/makecindy/cindy.git', initial.upstreamCommit],
+ source,
+ );
+ if ((await git(['rev-parse', 'FETCH_HEAD^{commit}'], source)).trim() !== initial.upstreamCommit)
+ throw mergeError('gitFailed');
+ const main = await git(['rev-parse', '--verify', 'refs/heads/main^{commit}'], source).catch(
+ () => '',
+ );
+ if (main.trim()) {
+ // A customized local main is never reset behind the user's back.
+ try {
+ await git(['merge-base', '--is-ancestor', main.trim(), initial.upstreamCommit], source);
+ } catch {
+ throw mergeError('localMain');
+ }
+ await git(['update-ref', `refs/cindy-make/backups/${initial.id}/main`, main.trim()], source);
+ }
+ await git(['branch', '--force', 'main', initial.upstreamCommit], source);
+ const personal = await commitPersonalFiles(git, source);
+ const baselineCommit = personal.commit;
+ const baselineTree = personal.tree;
+ const previousUpstream =
+ (
+ await git(['rev-parse', '--verify', PERSONAL_UPSTREAM_REF + '^{commit}'], source).catch(
+ (error) => {
+ if ((error as { exitCode?: number }).exitCode === 128) return '';
+ throw error;
+ },
+ )
+ ).trim() || (await git(['merge-base', baselineCommit, initial.upstreamCommit], source)).trim();
+ if (!COMMIT.test(previousUpstream)) throw mergeError('unavailable');
+ await git(['merge-base', '--is-ancestor', previousUpstream, baselineCommit], source);
+ const merges = (
+ await git(['rev-list', '--merges', previousUpstream + '..' + baselineCommit], source)
+ )
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean);
+ if (merges.some((commit) => !COMMIT.test(commit))) throw mergeError('gitFailed');
+ const rebaseReview =
+ merges.length > 0 &&
+ !!(await git(['show', '--remerge-diff', '--format=', '--name-only', ...merges], source)).trim();
+ await git(
+ ['update-ref', 'refs/cindy-make/backups/' + initial.id + '/personal', baselineCommit],
+ source,
+ );
+ await mkdir(path.dirname(worktree), { recursive: true });
+ if (!samePath(await realpath(path.dirname(worktree)), path.dirname(worktree)))
+ throw mergeError('unavailable');
+ const state: CindyMakeMergeState = {
+ ...initial,
+ baselineCommit,
+ baselineTree,
+ strategy: 'rebase',
+ rebaseBase: previousUpstream,
+ ...(rebaseReview ? { rebaseReview: true } : {}),
+ status: 'merging',
+ hasWorkspace: true,
+ };
+ // Save intent before creating the worktree so a crash cannot lose its identity.
+ await publish(state);
+ await git(['worktree', 'add', '-b', mergeBranch(state.id), worktree, baselineCommit], source);
+ await git(['update-ref', 'refs/cindy-make/backups/' + state.id + '/files', baselineTree], source);
+ try {
+ await git(
+ [
+ ...MAKE_GIT_IDENTITY,
+ '-c',
+ 'rebase.updateRefs=false',
+ 'rebase',
+ '--no-autostash',
+ '--no-update-refs',
+ '--signoff',
+ '--onto',
+ state.upstreamCommit,
+ previousUpstream,
+ ],
+ worktree,
+ );
+ } catch (error) {
+ const conflicts = await git(['diff', '--name-only', '--diff-filter=U'], worktree);
+ if (!conflicts.trim()) throw error;
+ return { ...state, status: 'conflict' };
+ }
+ // Rebase does not replay edits introduced only in a merge commit. Never silently adopt their loss.
+ if (state.rebaseReview) return { ...state, status: 'conflict' };
+ return applyUpstreamMerge(userData, state, git);
+}
diff --git a/apps/desktop/src/main/cindy-make/upstreamMergeController.ts b/apps/desktop/src/main/cindy-make/upstreamMergeController.ts
new file mode 100644
index 0000000000..ab3ed68be5
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/upstreamMergeController.ts
@@ -0,0 +1,331 @@
+import { randomUUID } from 'node:crypto';
+import type { CindyMakeTaskOptions } from '../../shared/cindyMakeDoctor.js';
+import type { CindyMakeMergeState, MakeFeatureMergePlan } from '../../shared/cindyMakeMerge.js';
+import { mergeError, mergeWorktree } from './upstreamMerge.js';
+
+export interface SavedUpstreamMerge {
+ state: CindyMakeMergeState;
+ sessionOwner?: string;
+}
+export function parseSavedUpstreamMerge(raw: string, userData: string): SavedUpstreamMerge {
+ const saved = JSON.parse(raw) as SavedUpstreamMerge;
+ const state = saved?.state;
+ if (
+ !state ||
+ typeof state.id !== 'string' ||
+ !['fetching', 'merging', 'conflict', 'resolving', 'checking', 'merged', 'failed'].includes(
+ state.status,
+ ) ||
+ typeof state.ref !== 'string' ||
+ typeof state.upstreamCommit !== 'string' ||
+ (state.upstreamCommit !== '' && !/^[0-9a-f]{40}$/i.test(state.upstreamCommit)) ||
+ (state.baselineTree !== undefined && !/^[0-9a-f]{40,64}$/i.test(state.baselineTree)) ||
+ (state.strategy !== undefined && state.strategy !== 'rebase') ||
+ (state.rebaseBase !== undefined && !/^[0-9a-f]{40}$/i.test(state.rebaseBase)) ||
+ (state.rebaseReview !== undefined && typeof state.rebaseReview !== 'boolean') ||
+ (state.feature !== undefined && (!validFeaturePlan(state.feature) || !saved.sessionOwner)) ||
+ (state.tree !== undefined && !/^[0-9a-f]{40,64}$/i.test(state.tree)) ||
+ (state.baselineCommit !== undefined && !/^[0-9a-f]{40}$/i.test(state.baselineCommit)) ||
+ (state.sessionId !== undefined &&
+ (typeof state.sessionId !== 'string' ||
+ !/^[a-zA-Z0-9-]{1,128}$/.test(state.sessionId) ||
+ !saved.sessionOwner)) ||
+ (saved.sessionOwner !== undefined && typeof saved.sessionOwner !== 'string')
+ )
+ throw mergeError('unavailable');
+ mergeWorktree(userData, state.id);
+ return saved;
+}
+function validFeaturePlan(feature: MakeFeatureMergePlan): boolean {
+ const id = /^[a-zA-Z0-9-]{1,128}$/;
+ const hash = /^[a-f0-9]{40,64}$/i;
+ return (
+ !!feature &&
+ id.test(feature.runId) &&
+ id.test(feature.taskSessionId) &&
+ ['integrate', 'revert', 'reapply'].includes(feature.action) &&
+ hash.test(feature.taskTree) &&
+ (feature.mergeCommit === undefined || hash.test(feature.mergeCommit)) &&
+ (feature.awaitingResolution === undefined || typeof feature.awaitingResolution === 'boolean') &&
+ Array.isArray(feature.steps) &&
+ feature.steps.length <= 10000 &&
+ (feature.mergeCommit === undefined || feature.steps.length === 0) &&
+ feature.steps.every((step) => !!step && hash.test(step.before) && hash.test(step.after)) &&
+ Number.isInteger(feature.nextStep) &&
+ feature.nextStep >= 0 &&
+ feature.nextStep <= (feature.mergeCommit ? 1 : feature.steps.length)
+ );
+}
+export interface UpstreamMergeDependencies {
+ read: () => SavedUpstreamMerge | undefined;
+ write: (saved: SavedUpstreamMerge) => void;
+ publish: (state: CindyMakeMergeState | undefined) => void;
+ owner: () => string;
+ hasWorkspace: (state: CindyMakeMergeState) => boolean;
+ exclusive: <T>(run: () => Promise<T>) => Promise<T>;
+ latest: () => Promise<{ ref: string; commit: string }>;
+ prepare: (
+ state: CindyMakeMergeState,
+ publish: (state: CindyMakeMergeState) => Promise<void>,
+ ) => Promise<CindyMakeMergeState>;
+ apply: (
+ state: CindyMakeMergeState,
+ isCurrent: () => boolean,
+ publish?: (state: CindyMakeMergeState) => Promise<void>,
+ ) => Promise<CindyMakeMergeState>;
+ prepareFeature?: (
+ state: CindyMakeMergeState,
+ plan: MakeFeatureMergePlan,
+ publish: (state: CindyMakeMergeState) => Promise<void>,
+ isCurrent: () => boolean,
+ ) => Promise<CindyMakeMergeState>;
+ applied?: (state: CindyMakeMergeState, isCurrent: () => boolean) => Promise<void>;
+ session: (
+ state: CindyMakeMergeState,
+ options: CindyMakeTaskOptions | undefined,
+ bind: (id: string) => void,
+ isCurrent: () => boolean,
+ ) => Promise<string>;
+ running: (sessionId: string) => boolean;
+ refresh: () => Promise<void>;
+ cleanup: (state: CindyMakeMergeState) => Promise<void>;
+}
+const errors = new Set([
+ 'busy',
+ 'dirty',
+ 'localMain',
+ 'unavailable',
+ 'gitFailed',
+ 'baselineChanged',
+ 'checksFailed',
+ 'interrupted',
+ 'startFailed',
+]);
+
+/** Device-local Git operation, with an account-bound resolution task. Never resumes writes on boot. */
+export class UpstreamMergeController {
+ private saved?: SavedUpstreamMerge;
+ private active?: Promise<unknown>;
+ constructor(private readonly deps: UpstreamMergeDependencies) {
+ this.saved = deps.read();
+ if (this.saved && this.saved.state.status !== 'merged') {
+ const state = this.saved.state;
+ this.save({
+ ...state,
+ hasWorkspace: deps.hasWorkspace(state),
+ ...(['fetching', 'merging', 'checking'].includes(state.status)
+ ? { status: 'failed' as const, error: 'interrupted' as const }
+ : {}),
+ });
+ }
+ this.status();
+ }
+ status(): CindyMakeMergeState | undefined {
+ const state = this.saved?.state;
+ const other = !!this.saved?.sessionOwner && this.saved.sessionOwner !== this.deps.owner();
+ const projected = state
+ ? { ...state, ...(other ? { sessionId: undefined, ownedByAnotherAccount: true } : {}) }
+ : undefined;
+ this.deps.publish(projected);
+ return projected;
+ }
+ isApplying(sessionId: string): boolean {
+ return this.saved?.state.sessionId === sessionId && this.saved?.state.status === 'checking';
+ }
+ private save(state: CindyMakeMergeState): void {
+ const saved = { ...this.saved, state };
+ // Persist before publishing or performing the next mutation.
+ this.deps.write(saved);
+ this.saved = saved;
+ this.status();
+ }
+ private fail(error: unknown): void {
+ const state = this.saved?.state;
+ if (!state) return;
+ const code = (error as { code?: string })?.code;
+ this.save({
+ ...state,
+ status: 'failed',
+ hasWorkspace: this.deps.hasWorkspace(state),
+ error: errors.has(code ?? '') ? (code as CindyMakeMergeState['error']) : 'gitFailed',
+ });
+ }
+ private async acceptResult(result: CindyMakeMergeState, isCurrent: () => boolean): Promise<void> {
+ if (result.feature && result.status === 'merged') {
+ // A crash after Git adoption must resume receipt persistence, not masquerade as fully complete.
+ this.save({ ...result, status: 'checking' });
+ if (!isCurrent()) throw mergeError('busy');
+ await this.deps.applied?.(result, isCurrent);
+ }
+ this.save(result);
+ }
+ private async run(work: () => Promise<void>): Promise<CindyMakeMergeState | undefined> {
+ if (this.active) {
+ await this.active.catch(() => undefined);
+ return this.status();
+ }
+ let started = false;
+ const pending = Promise.resolve().then(() =>
+ this.deps.exclusive(async () => {
+ started = true;
+ await work();
+ }),
+ );
+ this.active = pending;
+ try {
+ await pending;
+ } catch (error) {
+ if (!started) throw error;
+ this.fail(error);
+ } finally {
+ this.active = undefined;
+ }
+ return this.status();
+ }
+ async update(options?: CindyMakeTaskOptions): Promise<CindyMakeMergeState | undefined> {
+ const owner = this.deps.owner();
+ return this.run(async () => {
+ if (this.saved?.state.hasWorkspace && this.saved.state.status !== 'merged') return;
+ this.saved = undefined;
+ this.save({ id: randomUUID(), status: 'fetching', ref: '', upstreamCommit: '' });
+ const latest = await this.deps.latest();
+ this.save({ ...this.saved!.state, ref: latest.ref, upstreamCommit: latest.commit });
+ const result = await this.deps.prepare(this.saved!.state, async (next) => this.save(next));
+ this.save(result);
+ if (result.status === 'conflict' && owner && this.deps.owner() === owner) {
+ await this.createResolutionTask(options, owner);
+ }
+ if (result.status === 'merged') await this.deps.cleanup(result);
+ await this.deps.refresh().catch(() => undefined);
+ });
+ }
+ async resolve(options?: CindyMakeTaskOptions): Promise<CindyMakeMergeState | undefined> {
+ const owner = this.deps.owner();
+ if (this.saved?.sessionOwner && this.saved.sessionOwner !== owner) throw mergeError('busy');
+ return this.run(async () => {
+ if (this.saved?.state.feature && !this.saved.state.feature.awaitingResolution) {
+ const isCurrent = () => this.deps.owner() === owner;
+ let result: CindyMakeMergeState;
+ if (this.saved.state.error === 'baselineChanged' && this.deps.prepareFeature) {
+ // Keep the old candidate and its task for inspection; retry against the changed personal source.
+ const plan = { ...this.saved.state.feature, nextStep: 0, awaitingResolution: false };
+ this.save({
+ id: randomUUID(),
+ status: 'merging',
+ ref: 'personal',
+ upstreamCommit: '',
+ feature: plan,
+ });
+ result = await this.deps.prepareFeature(
+ this.saved.state,
+ plan,
+ async (next) => this.save(next),
+ isCurrent,
+ );
+ } else
+ result = await this.deps.apply(this.saved.state, isCurrent, async (next) =>
+ this.save(next),
+ );
+ await this.acceptResult(result, isCurrent);
+ if (result.status === 'merged') {
+ await this.deps.cleanup(result);
+ return;
+ }
+ }
+ await this.createResolutionTask(options, owner);
+ });
+ }
+ async feature(
+ plan: MakeFeatureMergePlan,
+ options?: CindyMakeTaskOptions,
+ ): Promise<CindyMakeMergeState | undefined> {
+ if (!validFeaturePlan(plan) || !this.deps.prepareFeature) throw mergeError('unavailable');
+ const owner = this.deps.owner();
+ if (
+ !owner ||
+ this.active ||
+ (this.saved?.state.hasWorkspace && this.saved.state.status !== 'merged')
+ )
+ throw mergeError('busy');
+ return this.run(async () => {
+ const isCurrent = () => owner === this.deps.owner();
+ if (!isCurrent()) throw mergeError('busy');
+ this.saved = {
+ sessionOwner: owner,
+ state: {
+ id: randomUUID(),
+ status: 'merging',
+ ref: 'personal',
+ upstreamCommit: '',
+ feature: plan,
+ },
+ };
+ this.save(this.saved.state);
+ const result = await this.deps.prepareFeature!(
+ this.saved.state,
+ plan,
+ async (next) => this.save(next),
+ isCurrent,
+ );
+ await this.acceptResult(result, isCurrent);
+ if (result.status === 'merged') {
+ await this.deps.cleanup(result);
+ } else if (result.status === 'conflict' && isCurrent())
+ await this.createResolutionTask(options, owner);
+ await this.deps.refresh().catch(() => undefined);
+ });
+ }
+ private async createResolutionTask(
+ options: CindyMakeTaskOptions | undefined,
+ owner: string,
+ ): Promise<void> {
+ const state = this.saved?.state;
+ if (!state?.hasWorkspace || state.status === 'merged') throw mergeError('unavailable');
+ const isCurrent = () => this.deps.owner() === owner;
+ if (!isCurrent()) throw mergeError('busy');
+ const id = await this.deps.session(
+ state,
+ options,
+ (sessionId) => {
+ if (!isCurrent()) throw mergeError('busy');
+ this.saved = { ...this.saved!, sessionOwner: owner };
+ this.save({ ...this.saved.state, sessionId, status: 'resolving', error: undefined });
+ },
+ isCurrent,
+ );
+ this.save({ ...this.saved!.state, sessionId: id, status: 'resolving', error: undefined });
+ }
+ async finish(sessionId: string): Promise<void> {
+ if (this.active && this.saved?.state.sessionId === sessionId)
+ await this.active.catch(() => undefined);
+ const state = this.saved?.state;
+ if (
+ this.active ||
+ !state ||
+ state.sessionId !== sessionId ||
+ state.status === 'merged' ||
+ this.saved?.sessionOwner !== this.deps.owner()
+ )
+ return;
+ // Providers may retire their running flag after synchronous done listeners return.
+ await Promise.resolve();
+ const owner = this.deps.owner();
+ const isCurrent = () =>
+ this.saved?.sessionOwner === owner &&
+ this.deps.owner() === owner &&
+ !this.deps.running(sessionId);
+ if (!isCurrent()) return;
+ await this.run(async () => {
+ if (!isCurrent()) return;
+ this.save({ ...state, status: 'checking', error: undefined });
+ const result = await this.deps.apply(state, isCurrent, async (next) => this.save(next));
+ await this.acceptResult(result, isCurrent);
+ if (result.feature && result.status === 'conflict' && isCurrent()) {
+ // Another delta of the same undo conflicted after resolving the preceding one.
+ this.save({ ...result, sessionId: undefined });
+ await this.createResolutionTask(undefined, owner);
+ }
+ await this.deps.refresh().catch(() => undefined);
+ });
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts b/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts
new file mode 100644
index 0000000000..8e8da75094
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts
@@ -0,0 +1,237 @@
+import path from 'node:path';
+import { existsSync } from 'node:fs';
+import { app, net } from 'electron';
+import type { CindyMakeMergeState, MakeFeatureMergePlan } from '../../shared/cindyMakeMerge.js';
+import type { CindyMakeTaskOptions } from '../../shared/cindyMakeDoctor.js';
+import { captureMakeHistoryStore } from './historyOwner.js';
+import { readAtomicFileSync, atomicWriteFileSync } from '../utils/atomicWriteFile.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { captureDataOwnerBroadcastScope } from '../device-link/broadcast-tap.js';
+import { createLogger } from '../logger.js';
+import { makeSourceRoot, makeSourceCheckoutPath } from './sourcePaths.js';
+import {
+ createMakeToolchainEnvironment,
+ resolveMakeToolEnvironment,
+} from './toolchainEnvironment.js';
+import { readCurrentCindySourceStatus } from './sourcePreparation.js';
+import { createLatestSourceVersionReader } from './latestSourceVersion.js';
+import { runSourceGit } from './sourceGit.js';
+import { snapshotContent } from './sourceContent.js';
+import { cindyMakeManager } from './manager.js';
+import { validateCindyMakeTaskStart } from './taskRuntime.js';
+import { ensureUpstreamMergeSession, assertUpstreamMergeSession } from './upstreamMergeSession.js';
+import { withSessionRouteLock } from '../localDb/sessionRouteLock.js';
+import { UpstreamMergeController, parseSavedUpstreamMerge } from './upstreamMergeController.js';
+import {
+ prepareUpstreamMerge,
+ applyUpstreamMerge,
+ verifyMergeWorktree,
+ mergeWorktree,
+ mergeError,
+ prepareFeatureMerge,
+ applyFeatureMerge,
+ type MergeGit,
+} from './upstreamMerge.js';
+
+const log = createLogger('cindy-make');
+let controller: UpstreamMergeController | undefined;
+let unavailable = false;
+const ownerKey = () => captureDataOwnerBroadcastScope().ownerScopeKey ?? '';
+
+/** Called explicitly at bootstrap, before source reset can be invoked. */
+export function configureUpstreamMerge(isRunning: (id: string) => boolean): void {
+ const userData = app.getPath('userData');
+ const root = makeSourceRoot(userData);
+ const stateFile = path.join(root, 'upstream-merge.json');
+ let savedOwner: string | undefined;
+ const git = async (): Promise<MergeGit> => {
+ const signal = AbortSignal.timeout(3 * 60_000);
+ const env = await createMakeToolchainEnvironment(userData);
+ const processEnv = await resolveMakeToolEnvironment(env, ['git'], signal);
+ return (args, cwd, indexFile) =>
+ runSourceGit(
+ { ...processEnv, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args,
+ cwd,
+ signal,
+ );
+ };
+ const refresh = async () => {
+ const env = await createMakeToolchainEnvironment(userData);
+ await cindyMakeManager.refreshSourceStatus(() => readCurrentCindySourceStatus(root, env));
+ };
+ try {
+ controller = new UpstreamMergeController({
+ read: () => {
+ const raw = readAtomicFileSync(stateFile);
+ if (raw === null) return;
+ const saved = parseSavedUpstreamMerge(raw, userData);
+ savedOwner = saved.sessionOwner;
+ return saved;
+ },
+ write: (saved) => {
+ atomicWriteFileSync(stateFile, JSON.stringify(saved));
+ savedOwner = saved.sessionOwner;
+ },
+ publish: (state) =>
+ cindyMakeManager.setUpstreamMerge(state, () => !savedOwner || savedOwner === ownerKey()),
+ owner: ownerKey,
+ hasWorkspace: (state) => existsSync(mergeWorktree(userData, state.id)),
+ exclusive: (run) =>
+ cindyMakeManager.withProjectUse(root, () =>
+ cindyMakeManager.withProject(root, async () => {
+ if (cindyMakeManager.isPreparingSource(root)) throw mergeError('busy');
+ return run();
+ }),
+ ),
+ latest: async () => {
+ const env = await createMakeToolchainEnvironment(userData);
+ const source = await readCurrentCindySourceStatus(root, env);
+ const channel = !app.isPackaged
+ ? 'dev'
+ : /-beta(?:\.|$)/i.test(app.getVersion())
+ ? 'beta'
+ : 'release';
+ // An explicit update gets a fresh pin rather than the Settings display cache.
+ const { latestVersion } = await createLatestSourceVersionReader((url, init) =>
+ net.fetch(url, init),
+ )(source, channel);
+ if (latestVersion?.status !== 'ready') throw mergeError('unavailable');
+ return latestVersion;
+ },
+ prepare: async (state, publish) =>
+ prepareUpstreamMerge(userData, state, await git(), publish),
+ prepareFeature: async (state, plan, publish, isCurrent) => {
+ if (!isCurrent() || isRunning(plan.taskSessionId)) throw mergeError('busy');
+ return prepareFeatureMerge(userData, state, plan, await git(), publish, isCurrent);
+ },
+ applied: async (state, isCurrent) => {
+ if (
+ !state.feature ||
+ !state.commit ||
+ !state.tree ||
+ !state.baselineCommit ||
+ !state.baselineTree
+ )
+ return;
+ if (!isCurrent()) throw mergeError('busy');
+ captureMakeHistoryStore().receipt(state.feature.runId, {
+ id: state.id,
+ action: state.feature.action,
+ at: Date.now(),
+ baselineCommit: state.baselineCommit,
+ commit: state.commit,
+ beforeTree: state.baselineTree,
+ tree: state.tree,
+ taskTree: state.feature.taskTree,
+ });
+ },
+ apply: async (state, isCurrent, publish) => {
+ if (state.feature && (!state.sessionId || state.commit))
+ return applyFeatureMerge(userData, state, await git(), isCurrent, publish);
+ if (!state.sessionId) throw mergeError('unavailable');
+ return withSessionRouteLock(state.sessionId, async () => {
+ if (!isCurrent()) throw mergeError('busy');
+ await assertUpstreamMergeSession(userData, state);
+ return state.feature
+ ? applyFeatureMerge(userData, state, await git(), isCurrent, publish)
+ : applyUpstreamMerge(userData, state, await git(), isCurrent);
+ });
+ },
+ session: async (state, options, bind, isCurrent) => {
+ if (!ownerKey()) throw mergeError('unavailable');
+ await verifyMergeWorktree(userData, state, await git());
+ try {
+ return await ensureUpstreamMergeSession(userData, state, options, bind, isCurrent);
+ } catch (error) {
+ if ((error as { code?: string })?.code === 'busy') throw error;
+ throw mergeError('startFailed');
+ }
+ },
+ running: isRunning,
+ refresh,
+ cleanup: async (state) => {
+ if (state.sessionId) return;
+ // Only reclaim the exact file tree already adopted by the personal checkout.
+ try {
+ const run = await git();
+ await verifyMergeWorktree(userData, state, run);
+ if (
+ !state.tree ||
+ (await snapshotContent(run, mergeWorktree(userData, state.id))) !== state.tree
+ )
+ return;
+ await run(
+ ['worktree', 'remove', '--force', mergeWorktree(userData, state.id)],
+ makeSourceCheckoutPath(userData),
+ );
+ } catch {
+ log.warn('Upstream merge completed; worktree cleanup deferred', {
+ operationId: state.id,
+ });
+ }
+ },
+ });
+ } catch {
+ unavailable = true;
+ // Unreadable recovery data is never interpreted as permission to delete a candidate.
+ cindyMakeManager.setUpstreamMerge({
+ id: '',
+ ref: '',
+ upstreamCommit: '',
+ status: 'failed',
+ error: 'unavailable',
+ hasWorkspace: true,
+ });
+ log.warn('Could not restore upstream merge state');
+ }
+}
+
+export async function actUpstreamMerge(raw: unknown): Promise<CindyMakeMergeState | undefined> {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
+ throwIpcError('INVALID_PARAMS', 'Invalid upstream merge request');
+ const { action, createOptions } = raw as Record<string, unknown>;
+ if (!['update', 'resolve', 'status'].includes(String(action)))
+ throwIpcError('INVALID_PARAMS', 'Invalid upstream merge action');
+ const options = validateCindyMakeTaskStart({
+ runId: 'merge',
+ request: 'merge',
+ title: 'merge',
+ createOptions,
+ }).createOptions;
+ if (!controller || unavailable)
+ throwIpcError('PRECONDITION_FAILED', 'Upstream merge is unavailable');
+ try {
+ return action === 'update'
+ ? await controller.update(options)
+ : action === 'resolve'
+ ? await controller.resolve(options)
+ : controller.status();
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'Upstream merge is unavailable');
+ }
+}
+
+/** Only Main passes verified task facts here; renderer requests go through history admission. */
+export async function integrateMakeHistory(
+ plan: MakeFeatureMergePlan,
+ options?: CindyMakeTaskOptions,
+): Promise<CindyMakeMergeState | undefined> {
+ if (!controller || unavailable) throw mergeError('unavailable');
+ return controller.feature(plan, options);
+}
+
+export function assertUpstreamMergeTaskWritable(sessionId: string): void {
+ if (controller?.isApplying(sessionId))
+ throwIpcError('PRECONDITION_FAILED', 'Upstream merge is being applied');
+}
+export function refreshUpstreamMergeProjection(): void {
+ controller?.status();
+}
+export async function finishUpstreamMergeTurn(sessionId: string): Promise<void> {
+ try {
+ await controller?.finish(sessionId);
+ } catch {
+ log.warn('Could not finalize upstream merge task');
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/upstreamMergeSession.ts b/apps/desktop/src/main/cindy-make/upstreamMergeSession.ts
new file mode 100644
index 0000000000..125219fd5c
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/upstreamMergeSession.ts
@@ -0,0 +1,178 @@
+import { and, eq } from 'drizzle-orm';
+import { getDbClient } from '../localDb/client/current.js';
+import { sessions, messages } from '../localDb/schema.js';
+import { sessionCreateToRow } from '../localDb/mapper.js';
+import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast.js';
+import {
+ captureDataOwnerBroadcastScope,
+ isDataOwnerBroadcastScopeCurrent,
+} from '../device-link/broadcast-tap.js';
+import { createBusinessSessionId } from '../sessionIds.js';
+import { normalizeDbAgentKind, dbToMakerAgentKind } from '../../shared/agentKindConversion.js';
+import type { CindyMakeTaskOptions } from '../../shared/cindyMakeDoctor.js';
+import {
+ CINDY_MAKE_MERGE_SESSION_SOURCE,
+ type CindyMakeMergeState,
+} from '../../shared/cindyMakeMerge.js';
+import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
+import { dispatchCindyMakeMergeTask } from './taskRuntime.js';
+import { mergeError, mergeWorktree } from './upstreamMerge.js';
+import { t } from '../i18n.js';
+
+export function upstreamMergePrompt(state: CindyMakeMergeState): string {
+ if (state.feature)
+ return `请在当前独立工作目录解决 Cindy Make 的${state.feature.action === 'revert' ? '撤销合入' : '合入个人版'}冲突。
+Cindy 已应用当前这一步的改动,冲突仅在当前目录。先检查 git status 和冲突文件;不要重新执行 merge、revert、rebase 或 reset,不要 push,也不要修改 main、cindy-personal 或其他工作目录。
+本步之前的个人版本:${state.baselineCommit}。对应制作标记:${state.feature.runId}。
+${state.feature.action === 'revert' ? '目标是撤销本次制作的个人功能,同时保留官方更新和其他制作的修改。不要把整个项目恢复到旧版本;遇到后续功能依赖它且无法判断取舍时询问用户。' : '保留本次制作的功能,也保留个人版已有的其他功能和官方更新。逐项理解冲突,不整批选择 ours/theirs。'}
+解决后可以 git add 标记完成,不要自行提交;运行受影响的测试与类型检查,并说明结果。Cindy 会在正常结束后核验原个人目录未变化,创建本地提交;若本次撤销还有后续改动需要处理,将由 Cindy 继续应用。此任务不生成个人版。`;
+ if (state.strategy === 'rebase')
+ return (
+ (state.rebaseReview
+ ? '注意:原个人历史包含在合并提交中额外完成的修改,普通 rebase 不会自动保留它们。本目录的 rebase 可能已经完成,即使没有文本冲突,也必须对照下方原个人分支提交逐项核对功能,补回遗漏的合并处理结果并验证;不要重新开始 rebase。\n'
+ : '') +
+ `请在当前独立工作目录中解决 Cindy 个人版更新到最新官方版本时的 rebase 冲突,确保不丢失本地已有功能。
+个人分支更新前提交:${state.baselineCommit}
+本次官方目标:${state.ref} (${state.upstreamCommit})
+Cindy 已在当前隔离目录启动 rebase。先检查 git status、当前冲突与待重放提交;不要重新执行 git merge 或重新开始 rebase,不要使用 rebase --skip、reset --hard 或整批选择 ours/theirs 丢弃个人功能。
+只在当前工作目录处理冲突,可以 git add 标记解决。每次解决后继续现有 rebase:git -c user.name="Cindy Make" -c [email protected] -c core.editor=true -c commit.gpgSign=false rebase --continue。后续再次遇到冲突则逐项处理,直到 rebase 完整结束。保留提交的 Signed-off-by,禁止 push,不修改 main、cindy-personal 或其他工作目录。
+按仓库规则运行受影响测试和类型检查;如需修改非冲突代码,留在本目录由 Cindy 在完成时本地提交。最后说明保留的个人功能、处理结果、验证和未验证项。遇到无法判断的产品取舍向用户说明并确认。
+Cindy 会在本轮正常结束后核实没有未完成的 rebase/冲突、最新官方提交已包含、原个人分支未被并发修改,再将 cindy-personal 更新到这份已提交结果。此任务不生成个人版,也不推送远端。`
+ );
+ return `请在当前独立工作目录中安全合并 Cindy 上游更新,解决冲突,确保不丢失本地已有功能。
+个人分支原提交:${state.baselineCommit}
+本次上游目标:${state.ref} (${state.upstreamCommit})
+先检查 Git 状态和双方变更,逐项理解冲突,同时保留个人功能和上游修复,不要整批选择 ours/theirs,不要用 reset --hard 或删除文件来掩盖冲突。涉及无法判断的产品取舍时,向用户说明并确认。
+上游文件差异已应用到当前独立工作目录,冲突保留在文件及索引中。先检查现场,不要重新执行 git merge。只在当前工作目录及当前分支中修改,不要切换、重置或直接修改 main、cindy-personal 或其他工作目录。
+不要自行创建额外提交或推送。解决冲突后可以用 git add 标记已解决。按仓库规则运行与改动匹配的测试和类型检查,最后说明冲突如何解决、保留了哪些本地功能、验证结果与未验证项。
+这是旧版保留的文件合并现场。Cindy 会在本轮正常结束后核实冲突已解决、个人版未被并发修改,将结果迁移到对应官方基线并本地提交个人差异,保留原有历史备份。若检查未通过,现场会保留供继续处理。此任务不生成个人版、不推送远端。`;
+}
+
+export async function ensureUpstreamMergeSession(
+ userData: string,
+ state: CindyMakeMergeState,
+ options: CindyMakeTaskOptions | undefined,
+ bind: (id: string) => void,
+ ownerCurrent: () => boolean,
+): Promise<string> {
+ const dbClient = getDbClient();
+ const db = dbClient.drizzle;
+ const owner = captureDataOwnerBroadcastScope();
+ const isCurrent = () =>
+ ownerCurrent() && isDataOwnerBroadcastScopeCurrent(owner) && getDbClient() === dbClient;
+ const check = () => {
+ if (!isCurrent()) throw mergeError('busy');
+ };
+ if (!options && state.feature) {
+ const [origin] = await db
+ .select()
+ .from(sessions)
+ .where(eq(sessions.id, state.feature.taskSessionId))
+ .limit(1);
+ check();
+ if (origin?.source === 'cindy-make' && !origin.remoteHostId)
+ options = {
+ agentKind: normalizeDbAgentKind(origin.agentKind),
+ model: origin.model ?? undefined,
+ providerId: origin.providerId,
+ effort: origin.effort ?? undefined,
+ permissionMode: origin.permissionMode ?? undefined,
+ fastMode: origin.fastMode ?? undefined,
+ };
+ }
+ let id = state.sessionId ?? createBusinessSessionId();
+ const workingDir = mergeWorktree(userData, state.id);
+ const [found] = await db.select().from(sessions).where(eq(sessions.id, id)).limit(1);
+ let existing: typeof found | undefined = found;
+ check();
+ if (
+ existing &&
+ (existing.source !== CINDY_MAKE_MERGE_SESSION_SOURCE ||
+ existing.remoteHostId ||
+ normalizeWorkingDirForStorage(existing.workingDir) !==
+ normalizeWorkingDirForStorage(workingDir))
+ )
+ throw mergeError('unavailable');
+ // An explicit Resolve click can continue retained work after the old task was removed.
+ if (existing && existing.status !== 'active') {
+ id = createBusinessSessionId();
+ existing = undefined;
+ }
+ // Bind the ID before INSERT, so retries after a crash never create a second task.
+ bind(id);
+ const row =
+ existing ??
+ sessionCreateToRow(
+ id,
+ {
+ ...options,
+ agentKind: normalizeDbAgentKind(options?.agentKind),
+ title: t(
+ state.feature
+ ? state.feature.action === 'revert'
+ ? 'cindyMake.history.revertTaskTitle'
+ : 'cindyMake.history.mergeTaskTitle'
+ : 'cindyMake.merge.taskTitle',
+ ),
+ workingDir,
+ workspaceKind: 'project',
+ source: CINDY_MAKE_MERGE_SESSION_SOURCE,
+ },
+ Date.now(),
+ );
+ if (!existing) {
+ await db.insert(sessions).values(row);
+ check();
+ emitSessionCreated(id);
+ }
+ const clientId = `cindy-make-merge-first-${state.id}`;
+ const [first] = await db
+ .select({ id: messages.id })
+ .from(messages)
+ .where(and(eq(messages.sessionId, id), eq(messages.clientId, clientId)))
+ .limit(1);
+ check();
+ // A persisted first message belongs to the ordinary retry/continue UI, not another dispatch.
+ if (!first && row.status === 'active' && row.clearedAt === null) {
+ await dispatchCindyMakeMergeTask(
+ id,
+ upstreamMergePrompt(state),
+ {
+ id,
+ agentKind: dbToMakerAgentKind(row.agentKind),
+ workingDir,
+ model: row.model,
+ effort: row.effort,
+ providerId: row.providerId,
+ fastMode: row.fastMode,
+ permissionMode: row.permissionMode,
+ planMode: row.planModeEnabled,
+ },
+ isCurrent,
+ clientId,
+ );
+ }
+ check();
+ return id;
+}
+
+export async function assertUpstreamMergeSession(
+ userData: string,
+ state: CindyMakeMergeState,
+): Promise<void> {
+ if (!state.sessionId) throw mergeError('unavailable');
+ const [row] = await getDbClient()
+ .drizzle.select()
+ .from(sessions)
+ .where(eq(sessions.id, state.sessionId))
+ .limit(1);
+ if (
+ !row ||
+ row.status !== 'active' ||
+ row.source !== CINDY_MAKE_MERGE_SESSION_SOURCE ||
+ row.remoteHostId ||
+ normalizeWorkingDirForStorage(row.workingDir) !==
+ normalizeWorkingDirForStorage(mergeWorktree(userData, state.id))
+ )
+ throw mergeError('unavailable');
+}
diff --git a/apps/desktop/src/main/cindy-make/versionLaunchArguments.ts b/apps/desktop/src/main/cindy-make/versionLaunchArguments.ts
new file mode 100644
index 0000000000..5073173e1e
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/versionLaunchArguments.ts
@@ -0,0 +1,24 @@
+import path from 'node:path';
+import { matchDeepLinkPrefix } from '../../shared/deepLinkSchemes.js';
+
+/** Only existing product entry arguments may cross a version handoff; no Node/debug/profile flags. */
+export function versionEntryArguments(argv: readonly string[]): string[] {
+ const result: string[] = [];
+ for (let i = 0; i < argv.length && result.length < 16; i++) {
+ const value = argv[i];
+ if (value.length > 16_384) continue;
+ if (matchDeepLinkPrefix(value)) result.push(value);
+ else if (
+ ['--open-folder', '--open-share-file'].includes(value) &&
+ path.isAbsolute(argv[i + 1] ?? '')
+ )
+ result.push(value, argv[++i]);
+ else if (
+ /^--open-(?:folder|share-file)=/.test(value) &&
+ path.isAbsolute(value.slice(value.indexOf('=') + 1))
+ )
+ result.push(value);
+ else if (path.isAbsolute(value) && /\.(cindy|cshare)$/i.test(value)) result.push(value);
+ }
+ return result;
+}
diff --git a/apps/desktop/src/main/cindy-make/versionRuntimeIdentity.ts b/apps/desktop/src/main/cindy-make/versionRuntimeIdentity.ts
new file mode 100644
index 0000000000..5d3cfe5806
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/versionRuntimeIdentity.ts
@@ -0,0 +1,38 @@
+/** Set only by the verified early startup handoff, before database/updater bootstrap. */
+let personal = false;
+let lockScope: 'profile' | 'dev' | null = null;
+/** Public service configuration only; no account tokens or provider credentials. */
+export interface CindyVersionEndpointSnapshot {
+ manifestText: string;
+ local: boolean;
+}
+let endpointOverride: CindyVersionEndpointSnapshot | undefined;
+let originEndpoints: { snapshot?: CindyVersionEndpointSnapshot } | undefined;
+export function setCindyVersionEndpointOverride(
+ value: CindyVersionEndpointSnapshot | undefined,
+): void {
+ endpointOverride = value;
+}
+export function getCindyVersionEndpointOverride(): CindyVersionEndpointSnapshot | undefined {
+ return personal ? endpointOverride : undefined;
+}
+export function captureCindyVersionOriginEndpoints(
+ snapshot: CindyVersionEndpointSnapshot | undefined,
+): void {
+ originEndpoints = { snapshot };
+}
+export function getCindyVersionOriginEndpoints() {
+ return originEndpoints;
+}
+export function setCindyVersionLockScope(value: 'profile' | 'dev' | null): void {
+ lockScope = value;
+}
+export function getCindyVersionLockScope(): 'profile' | 'dev' | null {
+ return lockScope;
+}
+export function setCindyPersonalRuntime(value: boolean): void {
+ personal = value;
+}
+export function isCindyPersonalRuntime(): boolean {
+ return personal;
+}
diff --git a/apps/desktop/src/main/cindy-make/versionService.ts b/apps/desktop/src/main/cindy-make/versionService.ts
new file mode 100644
index 0000000000..c0bdb210ad
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/versionService.ts
@@ -0,0 +1,130 @@
+import { app } from 'electron';
+import fs from 'node:fs';
+import path from 'node:path';
+import originalFs from 'original-fs';
+import type { CindyVersionsState } from '../../shared/cindyVersions.js';
+import { isIpcError } from '../../shared/ipc-errors.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import {
+ captureDataOwnerBroadcastScope,
+ isDataOwnerBroadcastScopeCurrent,
+} from '../device-link/broadcast-tap.js';
+import { readRelaunchBlockingActivity } from '../relaunchBusyActivityIpc.js';
+import {
+ describeOriginalVersion,
+ getCurrentCindyVersionId,
+ isCindyVersionSwitching,
+ startVersionHandoff,
+} from './versionStartup.js';
+import {
+ assertVersionDirectory,
+ listPersonalVersions,
+ readOriginalVersion,
+ readVersionJson,
+ selectedVersion,
+ versionDirectory,
+ versionsRoot,
+ VERSION_ID,
+ withVersionStore,
+} from './versionStore.js';
+
+let makeBusy: () => boolean = () => true;
+export function configureCindyVersions(probe: () => boolean): void {
+ makeBusy = probe;
+}
+export async function getCindyVersions(): Promise<CindyVersionsState> {
+ const profile = app.getPath('userData');
+ const currentId = getCurrentCindyVersionId();
+ const original =
+ currentId === 'original' ? describeOriginalVersion() : readOriginalVersion(profile);
+ let version = original?.version;
+ // Old version registries predate this field. Read the original package, not the running personal app.
+ if (!version && original) {
+ try {
+ version = readVersionJson<{ version?: string }>(
+ path.join(original.appPath, 'package.json'),
+ )?.version;
+ } catch {}
+ }
+ return {
+ currentId,
+ selectedId: selectedVersion(profile),
+ switching: isCindyVersionSwitching(),
+ versions: [
+ {
+ id: 'original',
+ kind: 'original',
+ development: Boolean(original?.development),
+ version: typeof version === 'string' ? version : undefined,
+ commit: typeof original?.commit === 'string' ? original.commit : undefined,
+ dirty: original?.dirty === true,
+ available: !!original && fs.existsSync(original.executable),
+ compatible: true,
+ },
+ ...listPersonalVersions(profile, original),
+ ],
+ };
+}
+export async function actCindyVersion(action: unknown, id: unknown): Promise<CindyVersionsState> {
+ if (
+ (action !== 'switch' && action !== 'remove') ||
+ typeof id !== 'string' ||
+ (id !== 'original' && !VERSION_ID.test(id))
+ )
+ throwIpcError('INVALID_PARAMS', 'Invalid version action');
+ const scope = captureDataOwnerBroadcastScope();
+ const profile = app.getPath('userData');
+ const current = () =>
+ isDataOwnerBroadcastScopeCurrent(scope) && app.getPath('userData') === profile;
+ try {
+ if (makeBusy() || isCindyVersionSwitching()) throwIpcError('PRECONDITION_FAILED', 'busy');
+ if (action === 'switch') {
+ if (getCurrentCindyVersionId() === id) return getCindyVersions();
+ if ((await readRelaunchBlockingActivity()).busy || !current())
+ throwIpcError('PRECONDITION_FAILED', 'busy');
+ await startVersionHandoff(
+ id,
+ async () => current() && !makeBusy() && !(await readRelaunchBlockingActivity()).busy,
+ );
+ if (!current()) throwIpcError('PRECONDITION_FAILED', 'busy');
+ // Normal quit awaits the existing Maker, plugin, credential and DB disposers.
+ setImmediate(() => app.quit());
+ } else {
+ await withVersionStore(profile, async () => {
+ if (
+ !current() ||
+ id === 'original' ||
+ id === getCurrentCindyVersionId() ||
+ id === selectedVersion(profile)
+ )
+ throwIpcError('PRECONDITION_FAILED', 'busy');
+ const active = readVersionJson<{ id: string; pid: number }>(
+ path.join(versionsRoot(profile), 'active.json'),
+ );
+ if (active?.id === id) {
+ try {
+ process.kill(active.pid, 0);
+ throwIpcError('PRECONDITION_FAILED', 'busy');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
+ }
+ }
+ const directory = versionDirectory(profile, id);
+ assertVersionDirectory(profile, directory);
+ await originalFs.promises.rm(directory, {
+ recursive: true,
+ force: true,
+ maxRetries: 3,
+ retryDelay: 200,
+ });
+ });
+ }
+ return getCindyVersions();
+ } catch (error) {
+ const code = (error as { code?: string }).code;
+ if (code === 'busy' || code === 'incompatible' || code === 'launchFailed')
+ throwIpcError('PRECONDITION_FAILED', code);
+ if (isIpcError(error)) throw error;
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/versionStartup.ts b/apps/desktop/src/main/cindy-make/versionStartup.ts
new file mode 100644
index 0000000000..b669e6e462
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/versionStartup.ts
@@ -0,0 +1,701 @@
+import { app, dialog } from 'electron';
+import path from 'node:path';
+import fs from 'node:fs';
+import { spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { resolveClientEndpointsStrict } from '@cindy/maker-shared/client-endpoints';
+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+import { createLogger } from '../logger.js';
+import { t } from '../i18n.js';
+import { observeDesktopStartupResult } from '../devStartupStatus.js';
+import { defaultPtySpawn } from '../terminal/ptyFactory.js';
+import { makeTestEnvironment } from './testRunner.js';
+import { getMakeRuntimeSourceIdentity } from './runtimeVersion.js';
+import { versionEntryArguments } from './versionLaunchArguments.js';
+import {
+ getCindyVersionLockScope,
+ getCindyVersionOriginEndpoints,
+ setCindyPersonalRuntime,
+ setCindyVersionLockScope,
+ setCindyVersionEndpointOverride,
+} from './versionRuntimeIdentity.js';
+import {
+ assertVersionDirectory,
+ migrationIdentity,
+ readOriginalVersion,
+ readPersonalVersion,
+ readVersionJson,
+ sameVersionPath,
+ selectedVersion,
+ selectVersion,
+ verifyPersonalVersion,
+ versionDirectory,
+ versionError,
+ versionsRoot,
+ VERSION_ID,
+ ORIGINAL_DEV_ENV_KEYS,
+ withVersionStore,
+ writeVersionJson,
+ type OriginalVersion,
+ type VersionProfile,
+} from './versionStore.js';
+
+const log = createLogger('cindy-versions');
+const FLAGS = {
+ profile: '--cindy-version-profile=',
+ request: '--cindy-version-launch=',
+ helper: '--cindy-version-helper=',
+};
+export interface VersionLaunchRequest {
+ protocol: 1;
+ id: string;
+ profile: VersionProfile;
+ parentPid: number;
+ helperExecutable: string;
+ helperAppPath: string;
+ targetId: string;
+ fallbackId: string;
+ createdAt: number;
+ state: 'pending' | 'starting' | 'ready' | 'cancelled' | 'failed';
+ claimedPid?: number;
+ helperPid?: number;
+}
+let currentId = 'original';
+let request: VersionLaunchRequest | undefined;
+let helper = false;
+let switching = false;
+let inheritedProfile: VersionProfile | undefined;
+let forwardedArguments: string[] = [];
+let bufferedUrls: string[] = [];
+let bufferedFiles: string[] = [];
+const bufferUrl = (event: { preventDefault(): void }, url: string) => {
+ event.preventDefault();
+ if (bufferedUrls.length < 16) bufferedUrls.push(url);
+};
+const bufferFile = (event: { preventDefault(): void }, file: string) => {
+ event.preventDefault();
+ if (bufferedFiles.length < 16) bufferedFiles.push(file);
+};
+
+/** Stop buffering only after the existing handlers have been installed. Nothing is persisted. */
+export function deliverCindyVersionOpenEvents(): void {
+ app.removeListener('open-url', bufferUrl);
+ app.removeListener('open-file', bufferFile);
+ for (const url of bufferedUrls.splice(0)) app.emit('open-url', { preventDefault() {} }, url);
+ for (const file of bufferedFiles.splice(0)) app.emit('open-file', { preventDefault() {} }, file);
+ forwardedArguments = [];
+}
+function handoffArguments(): string[] {
+ const files = bufferedFiles.flatMap((file) => {
+ try {
+ return fs.statSync(file).isDirectory() ? ['--open-folder', file] : [file];
+ } catch {
+ return [];
+ }
+ });
+ return versionEntryArguments([...forwardedArguments, ...bufferedUrls, ...files]);
+}
+const pidAlive = (pid: number) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';
+ }
+};
+const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+export const getCurrentCindyVersionId = () => currentId;
+export const isCindyVersionSwitching = () => switching;
+export const isCindyVersionLaunchPending = () => !!request && !helper;
+export function watchCindyVersionStartupResult(): void {
+ if (!request || helper) return;
+ observeDesktopStartupResult((ready) => {
+ if (ready) void markCindyVersionReady().catch(() => {});
+ else {
+ const file = versionRequestPath(request!.profile.userData, request!.id);
+ const value = readVersionJson<VersionLaunchRequest>(file);
+ if (value?.state === 'starting' && value.claimedPid === process.pid)
+ writeVersionJson(file, { ...value, state: 'failed' });
+ }
+ });
+}
+export const versionRequestPath = (profile: string, id: string) => {
+ if (!VERSION_ID.test(id)) throw versionError('unavailable');
+ return path.join(versionsRoot(profile), 'launches', id + '.json');
+};
+function parseVersionEndpoints(text: string, region: VersionProfile['region']) {
+ const parsed = resolveClientEndpointsStrict(text, { allowHttp: true });
+ const expected = region === 'global' ? 'global' : 'cn';
+ if (
+ !parsed.ok ||
+ (parsed.region !== undefined && parsed.region !== null && parsed.region !== expected)
+ )
+ throw versionError('unavailable');
+ return parsed;
+}
+export function currentVersionProfile(): VersionProfile {
+ let endpointSnapshot = inheritedProfile?.endpointSnapshot;
+ if (currentId === 'original') {
+ const resolved = getCindyVersionOriginEndpoints();
+ if (resolved) endpointSnapshot = resolved.snapshot;
+ else if (!app.isPackaged && process.env.XDT_ENDPOINTS_CDN !== '1') {
+ const root = path.resolve(app.getAppPath(), '..', '..');
+ const file = process.env.XDT_ENDPOINT_MANIFEST_FILE?.trim();
+ const location = file ? path.resolve(root, file) : path.join(root, 'config', 'endpoint.json');
+ if (fs.statSync(location).size > 256 * 1024) throw versionError('unavailable');
+ const parsed = parseVersionEndpoints(fs.readFileSync(location, 'utf8'), CURRENT_CINDY_REGION);
+ endpointSnapshot = {
+ manifestText: JSON.stringify({
+ schemaVersion: 1,
+ region: parsed.region ?? (CURRENT_CINDY_REGION === 'global' ? 'global' : 'cn'),
+ ...parsed.endpoints,
+ }),
+ local: process.env.XDT_DESKTOP_DEV_MODE === 'local',
+ };
+ } else endpointSnapshot = undefined;
+ }
+ return {
+ userData: app.getPath('userData'),
+ appName: app.getName(),
+ region: CURRENT_CINDY_REGION,
+ deviceId: process.env.XDT_DEVICE_ID_OVERRIDE,
+ passive: process.env.XDT_SCHEDULER_PASSIVE === '1',
+ ...(endpointSnapshot ? { endpointSnapshot } : {}),
+ };
+}
+function assertProfile(profile: VersionProfile): void {
+ if (
+ !profile ||
+ !path.isAbsolute(profile.userData) ||
+ !['Cindy', 'CindyDev'].includes(profile.appName) ||
+ !['cn', 'global', 'dev'].includes(profile.region) ||
+ (profile.deviceId !== undefined && !/^[A-Za-z0-9_-]{1,128}$/.test(profile.deviceId))
+ )
+ throw versionError('unavailable');
+ const marker = path.join(profile.userData, 'keychain-identity');
+ let name = 'Cindy';
+ try {
+ if (fs.lstatSync(marker).isSymbolicLink()) throw versionError('unavailable');
+ const value = fs.readFileSync(marker, 'utf8');
+ if (!['Cindy\n', 'Cindy\r\n', 'CindyDev\n', 'CindyDev\r\n'].includes(value))
+ throw versionError('unavailable');
+ name = value.trim();
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ if (name !== profile.appName) throw versionError('unavailable');
+ if (
+ profile.endpointSnapshot &&
+ (typeof profile.endpointSnapshot.manifestText !== 'string' ||
+ profile.endpointSnapshot.manifestText.length > 256 * 1024 ||
+ typeof profile.endpointSnapshot.local !== 'boolean')
+ )
+ throw versionError('unavailable');
+ if (profile.endpointSnapshot)
+ parseVersionEndpoints(profile.endpointSnapshot.manifestText, profile.region);
+}
+function argvValue(prefix: string): string | undefined {
+ return process.argv.find((arg) => arg.startsWith(prefix))?.slice(prefix.length);
+}
+function targetExecutable(item: VersionLaunchRequest): string {
+ if (item.targetId === 'original') {
+ const original = readOriginalVersion(item.profile.userData);
+ if (!original) throw versionError('unavailable');
+ return original.executable;
+ }
+ const target = readPersonalVersion(item.profile.userData, item.targetId);
+ return path.join(versionDirectory(item.profile.userData, target.id), target.executable);
+}
+/** Narrow, owner-created handoff, not a general packaged profile/env override. Runs before credentials load. */
+export function prepareCindyVersionStartup(): void {
+ const profilePath = argvValue(FLAGS.profile) ?? process.env.CINDY_VERSION_PROFILE;
+ const id =
+ argvValue(FLAGS.helper) ?? argvValue(FLAGS.request) ?? process.env.CINDY_VERSION_LAUNCH;
+ helper = !!argvValue(FLAGS.helper);
+ if (id || profilePath) {
+ if (!id || !profilePath || !path.isAbsolute(profilePath)) throw versionError('unavailable');
+ assertVersionDirectory(profilePath, path.join(versionsRoot(profilePath), 'launches'));
+ const item = readVersionJson<VersionLaunchRequest>(versionRequestPath(profilePath, id));
+ const devRestart =
+ !helper &&
+ !app.isPackaged &&
+ item?.state === 'ready' &&
+ item.targetId === 'original' &&
+ !!item.helperPid &&
+ pidAlive(item.helperPid);
+ if (
+ !item ||
+ item.protocol !== 1 ||
+ item.id !== id ||
+ !sameVersionPath(item.profile.userData, profilePath) ||
+ (!devRestart && Date.now() - item.createdAt > 30 * 60_000) ||
+ (!devRestart && !['pending', 'starting'].includes(item.state)) ||
+ !Number.isSafeInteger(item.parentPid) ||
+ item.parentPid <= 0
+ )
+ throw versionError('unavailable');
+ assertProfile(item.profile);
+ const expected = helper ? item.helperExecutable : targetExecutable(item);
+ if (!sameVersionPath(fs.realpathSync(expected), fs.realpathSync(process.execPath)))
+ throw versionError('unavailable');
+ if (!app.isPackaged) {
+ const expectedApp = helper ? item.helperAppPath : readOriginalVersion(profilePath)?.appPath;
+ if (!expectedApp || !sameVersionPath(app.getAppPath(), expectedApp))
+ throw versionError('unavailable');
+ }
+ request = devRestart ? undefined : item;
+ if (devRestart) applyProfile(item.profile);
+ if (helper) {
+ item.helperPid = process.pid;
+ writeVersionJson(versionRequestPath(profilePath, id), item);
+ }
+ if (!helper && !devRestart) {
+ if (item.state !== 'starting' || item.claimedPid) throw versionError('unavailable');
+ currentId = item.targetId;
+ item.claimedPid = process.pid;
+ writeVersionJson(versionRequestPath(profilePath, id), item);
+ }
+ } else if (app.isPackaged) {
+ // Finder/direct execution of a saved .app must retain its original profile too.
+ let directory = path.dirname(process.execPath);
+ for (let depth = 0; depth < 7; depth++, directory = path.dirname(directory)) {
+ const id = path.basename(directory);
+ if (
+ !VERSION_ID.test(id) ||
+ path.basename(path.dirname(directory)) !== 'versions' ||
+ path.basename(path.dirname(path.dirname(directory))) !== 'cindy-versions'
+ )
+ continue;
+ const profile = path.dirname(path.dirname(path.dirname(directory)));
+ const item = readPersonalVersion(profile, id);
+ if (!sameVersionPath(path.join(directory, item.executable), process.execPath))
+ throw versionError('unavailable');
+ const profileIdentity = readOriginalVersion(profile)?.profile ?? item.profile;
+ assertProfile(profileIdentity);
+ currentId = item.id;
+ applyProfile(profileIdentity);
+ setCindyPersonalRuntime(true);
+ break;
+ }
+ }
+ if (request) applyProfile(request.profile);
+ forwardedArguments = versionEntryArguments(process.argv);
+ if (id && process.env.CINDY_VERSION_FORWARD_ARGUMENTS) {
+ try {
+ const forwarded = JSON.parse(process.env.CINDY_VERSION_FORWARD_ARGUMENTS);
+ if (Array.isArray(forwarded) && forwarded.every((value) => typeof value === 'string'))
+ forwardedArguments.push(...versionEntryArguments(forwarded));
+ } catch {}
+ }
+ if (!helper && process.platform !== 'darwin')
+ process.argv.push(...forwardedArguments.filter((arg) => !process.argv.includes(arg)));
+ if (!helper && process.platform === 'darwin') {
+ for (let i = 0; i < forwardedArguments.length; i++) {
+ const arg = forwardedArguments[i];
+ if (arg.startsWith('--open-')) {
+ const file = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : forwardedArguments[++i];
+ if (file && !bufferedFiles.includes(file)) bufferedFiles.push(file);
+ } else if (path.isAbsolute(arg)) {
+ if (!bufferedFiles.includes(arg)) bufferedFiles.push(arg);
+ } else if (!bufferedUrls.includes(arg)) bufferedUrls.push(arg);
+ }
+ }
+ app.on('open-url', bufferUrl);
+ app.on('open-file', bufferFile);
+ // Handoff arguments authorize this launch only. Ordinary relaunches must not replay them.
+ process.argv = process.argv.filter(
+ (arg) => !Object.values(FLAGS).some((prefix) => arg.startsWith(prefix)),
+ );
+ delete process.env.CINDY_VERSION_PROFILE;
+ delete process.env.CINDY_VERSION_LAUNCH;
+ delete process.env.CINDY_VERSION_FORWARD_ARGUMENTS;
+ setCindyPersonalRuntime(currentId !== 'original' && !helper);
+}
+function applyProfile(profile: VersionProfile): void {
+ if (profile.region !== CURRENT_CINDY_REGION) throw versionError('incompatible');
+ inheritedProfile = profile;
+ setCindyVersionEndpointOverride(profile.endpointSnapshot);
+ app.setPath('userData', profile.userData);
+ app.setName(profile.appName);
+ if (profile.deviceId) process.env.XDT_DEVICE_ID_OVERRIDE = profile.deviceId;
+ else delete process.env.XDT_DEVICE_ID_OVERRIDE;
+ if (profile.passive) process.env.XDT_SCHEDULER_PASSIVE = '1';
+ else delete process.env.XDT_SCHEDULER_PASSIVE;
+}
+
+export function describeOriginalVersion(node?: string): OriginalVersion {
+ const profile = currentVersionProfile();
+ if (currentId !== 'original') {
+ const existing = readOriginalVersion(profile.userData);
+ if (!existing) throw versionError('unavailable');
+ return existing;
+ }
+ const root = path.resolve(app.getAppPath(), '..', '..');
+ const previous = readOriginalVersion(profile.userData);
+ const original: OriginalVersion = {
+ protocol: 1,
+ version: app.getVersion(),
+ ...getMakeRuntimeSourceIdentity(),
+ profile,
+ executable: process.execPath,
+ appPath: app.getAppPath(),
+ resources: app.isPackaged ? process.resourcesPath : app.getAppPath(),
+ migrationHash: migrationIdentity(
+ path.join(app.isPackaged ? process.resourcesPath : app.getAppPath(), 'drizzle'),
+ ),
+ ...(!app.isPackaged
+ ? {
+ development: {
+ root,
+ node: node ?? previous?.development?.node ?? '',
+ mode:
+ process.env.XDT_DESKTOP_DEV_MODE === 'local'
+ ? ('local' as const)
+ : ('remote' as const),
+ environment: Object.fromEntries(
+ ORIGINAL_DEV_ENV_KEYS.flatMap((key) =>
+ process.env[key] !== undefined ? [[key, process.env[key]!]] : [],
+ ),
+ ),
+ },
+ }
+ : {}),
+ };
+ return original;
+}
+export async function rememberOriginalVersion(node?: string): Promise<OriginalVersion> {
+ const original = describeOriginalVersion(node);
+ if (currentId === 'original')
+ await withVersionStore(original.profile.userData, async () =>
+ writeVersionJson(
+ path.join(versionsRoot(original.profile.userData), 'original.json'),
+ original,
+ ),
+ );
+ recordCindyVersionActive();
+ return original;
+}
+/** Called only by the running owner or after Electron grants its existing single-instance lock. */
+export function recordCindyVersionActive(): void {
+ const profile = app.getPath('userData');
+ if (helper || !fs.existsSync(versionsRoot(profile))) return;
+ assertVersionDirectory(profile, versionsRoot(profile));
+ const scope =
+ getCindyVersionLockScope() ??
+ (app.isPackaged ? 'profile' : process.env.XDT_SCHEDULER_PASSIVE === '1' ? 'none' : 'dev');
+ writeVersionJson(path.join(versionsRoot(profile), 'active.json'), {
+ pid: process.pid,
+ id: currentId,
+ scope,
+ });
+}
+
+/** Helper is a separate headless Electron process, so it survives normal app shutdown without RunAsNode. */
+export async function startVersionHandoff(
+ targetId: string,
+ canSwitch: () => Promise<boolean> = async () => true,
+): Promise<void> {
+ if (switching) throw versionError('busy');
+ const profile = currentVersionProfile();
+ const original = readOriginalVersion(profile.userData);
+ if (!original) throw versionError('unavailable');
+ if (targetId !== 'original') await verifyPersonalVersion(profile.userData, targetId, original);
+ else if (
+ !fs.existsSync(original.executable) ||
+ (original.development && !fs.existsSync(original.development.node))
+ )
+ throw versionError('unavailable');
+ if (
+ targetId === 'original' &&
+ currentId !== 'original' &&
+ readPersonalVersion(profile.userData, currentId).migrationHash !==
+ migrationIdentity(path.join(original.resources, 'drizzle'))
+ )
+ throw versionError('incompatible');
+ if (!(await canSwitch())) throw versionError('busy');
+ const item: VersionLaunchRequest = {
+ protocol: 1,
+ id: randomUUID(),
+ profile,
+ parentPid: process.pid,
+ helperExecutable: process.execPath,
+ helperAppPath: app.getAppPath(),
+ targetId,
+ fallbackId: currentId,
+ createdAt: Date.now(),
+ state: 'pending',
+ };
+ await withVersionStore(profile.userData, async () => {
+ const pending = path.join(versionsRoot(profile.userData), 'pending.json');
+ const previous = readVersionJson<{ id: string; pid: number }>(pending);
+ if (previous && pidAlive(previous.pid)) throw versionError('busy');
+ writeVersionJson(versionRequestPath(profile.userData, item.id), item);
+ writeVersionJson(pending, { id: item.id, pid: process.pid });
+ });
+ switching = true;
+ const args = [
+ ...(!app.isPackaged ? [app.getAppPath()] : []),
+ FLAGS.profile + profile.userData,
+ FLAGS.helper + item.id,
+ ];
+ try {
+ const helperPid = await new Promise<number>((resolve, reject) => {
+ const child = spawn(process.execPath, args, {
+ detached: true,
+ stdio: 'ignore',
+ windowsHide: true,
+ env: {
+ ...makeTestEnvironment(process.env),
+ CINDY_VERSION_FORWARD_ARGUMENTS: JSON.stringify(handoffArguments()),
+ },
+ });
+ child.once('error', reject);
+ child.once('spawn', () => {
+ child.unref();
+ resolve(child.pid!);
+ });
+ });
+ const deadline = Date.now() + 10_000;
+ while (
+ readVersionJson<VersionLaunchRequest>(versionRequestPath(profile.userData, item.id))
+ ?.helperPid !== helperPid
+ ) {
+ if (!pidAlive(helperPid) || Date.now() >= deadline) throw versionError('launchFailed');
+ await delay(100);
+ }
+ if (!(await canSwitch())) throw versionError('busy');
+ await withVersionStore(profile.userData, async () =>
+ writeVersionJson(path.join(versionsRoot(profile.userData), 'pending.json'), {
+ id: item.id,
+ pid: helperPid,
+ }),
+ );
+ } catch (error) {
+ switching = false;
+ item.state = 'cancelled';
+ writeVersionJson(versionRequestPath(profile.userData, item.id), item);
+ throw error;
+ }
+}
+
+async function launchTarget(
+ item: VersionLaunchRequest,
+): Promise<{ stop(): Promise<void>; closed: Promise<void> }> {
+ const original = readOriginalVersion(item.profile.userData);
+ if (!original) throw versionError('unavailable');
+ const directory = versionRequestPath(item.profile.userData, item.id);
+ item.state = 'starting';
+ delete item.claimedPid;
+ writeVersionJson(directory, item);
+ const environment = {
+ ...makeTestEnvironment(process.env),
+ CINDY_VERSION_PROFILE: item.profile.userData,
+ CINDY_VERSION_LAUNCH: item.id,
+ CINDY_VERSION_FORWARD_ARGUMENTS: JSON.stringify(handoffArguments()),
+ };
+ if (item.targetId === 'original' && original.development) {
+ const dev = original.development;
+ if (!path.isAbsolute(dev.node)) throw versionError('unavailable');
+ const child = defaultPtySpawn(
+ dev.node,
+ [path.join(dev.root, 'scripts', 'desktop-dev-runner.mjs'), dev.mode],
+ {
+ cwd: dev.root,
+ env: { ...environment, ...dev.environment },
+ name: 'xterm-256color',
+ cols: 160,
+ rows: 30,
+ },
+ );
+ child.onData(() => {});
+ const closed = new Promise<void>((resolve) => child.onExit(() => resolve()));
+ return {
+ closed,
+ stop: async () => {
+ child.kill();
+ await closed;
+ },
+ };
+ }
+ const executable =
+ item.targetId === 'original'
+ ? original.executable
+ : await verifyPersonalVersion(item.profile.userData, item.targetId, original).then(
+ (version) =>
+ path.join(versionDirectory(item.profile.userData, version.id), version.executable),
+ );
+ // Executing the precise binary inside .app preserves bundle identity and gives us an owned PID.
+ const child = spawn(
+ executable,
+ [FLAGS.profile + item.profile.userData, FLAGS.request + item.id],
+ {
+ cwd: path.dirname(executable),
+ detached: true,
+ stdio: 'ignore',
+ windowsHide: true,
+ env: environment,
+ },
+ );
+ await new Promise<void>((resolve, reject) => {
+ child.once('spawn', resolve);
+ child.once('error', reject);
+ });
+ const closed = new Promise<void>((resolve) => child.once('exit', () => resolve()));
+ return {
+ closed,
+ stop: async () => {
+ if (child.exitCode === null) child.kill();
+ await closed;
+ },
+ };
+}
+
+async function runVersionHelper(item: VersionLaunchRequest): Promise<void> {
+ await app.whenReady();
+ app.dock?.hide();
+ const file = versionRequestPath(item.profile.userData, item.id);
+ const deadline = Date.now() + 60_000;
+ while (pidAlive(item.parentPid) && Date.now() < deadline) {
+ if (readVersionJson<VersionLaunchRequest>(file)?.state === 'cancelled') return;
+ await delay(200);
+ }
+ if (pidAlive(item.parentPid)) {
+ item.state = 'cancelled';
+ writeVersionJson(file, item);
+ return;
+ }
+ for (let attempt = 0; attempt < 2; attempt++) {
+ let child: Awaited<ReturnType<typeof launchTarget>> | undefined;
+ try {
+ child = await launchTarget(item);
+ let closed = false;
+ void child.closed.then(() => {
+ closed = true;
+ });
+ const readyDeadline =
+ Date.now() +
+ (item.targetId === 'original' && readOriginalVersion(item.profile.userData)?.development
+ ? 25 * 60_000
+ : 120_000);
+ while (Date.now() < readyDeadline) {
+ const latest = readVersionJson<VersionLaunchRequest>(file);
+ if (latest?.state === 'ready' && latest.targetId === item.targetId) {
+ forwardedArguments = [];
+ bufferedUrls = [];
+ bufferedFiles = [];
+ if (
+ item.targetId === 'original' &&
+ readOriginalVersion(item.profile.userData)?.development
+ )
+ await child.closed;
+ return;
+ }
+ if (closed || latest?.state === 'failed') break;
+ await delay(200);
+ }
+ throw versionError('launchFailed');
+ } catch (error) {
+ item.state = 'cancelled';
+ writeVersionJson(file, item);
+ if (child) await child.stop();
+ log.warn('Version launch failed; retaining existing application data', { attempt });
+ if (attempt === 0 && item.targetId !== item.fallbackId) {
+ item.targetId = item.fallbackId;
+ continue;
+ }
+ item.state = 'failed';
+ writeVersionJson(file, item);
+ // Preserve the explicit original-version recovery entry even if a personal build is broken.
+ await selectVersion(item.profile.userData, 'original');
+ dialog.showErrorBox('Cindy', t('cindyMake.versions.errors.recovery'));
+ }
+ }
+}
+
+/** Called after dev profile resolution, before the database, single-instance lock and main windows. */
+export async function dispatchCindyVersionStartup(): Promise<boolean> {
+ if (helper && request) {
+ try {
+ await runVersionHelper(request);
+ } finally {
+ app.exit(0);
+ }
+ return true;
+ }
+ const profile = app.getPath('userData');
+ if (fs.existsSync(versionsRoot(profile))) {
+ if (!request) {
+ const pending = readVersionJson<{ id: string; pid: number }>(
+ path.join(versionsRoot(profile), 'pending.json'),
+ );
+ if (pending && pidAlive(pending.pid)) {
+ const pendingRequest = readVersionJson<VersionLaunchRequest>(
+ versionRequestPath(profile, pending.id),
+ );
+ if (pendingRequest && ['pending', 'starting'].includes(pendingRequest.state)) {
+ app.exit(0);
+ return true;
+ }
+ }
+ }
+ const active = readVersionJson<{ pid: number; scope?: string }>(
+ path.join(versionsRoot(profile), 'active.json'),
+ );
+ if (active && active.pid !== process.pid && pidAlive(active.pid)) {
+ if (active.scope === 'none') throw versionError('busy');
+ // Let Electron's existing second-instance path focus the running version.
+ setCindyVersionLockScope(active.scope === 'dev' ? 'dev' : 'profile');
+ return false;
+ }
+ setCindyVersionLockScope('profile');
+ }
+ if (currentId !== 'original') {
+ const original = readOriginalVersion(profile);
+ if (!original) throw versionError('unavailable');
+ await verifyPersonalVersion(profile, currentId, original);
+ if (!request) {
+ const selected = process.argv.includes('--cindy-version-original')
+ ? 'original'
+ : selectedVersion(profile);
+ if (selected !== currentId) {
+ await startVersionHandoff(selected);
+ app.exit(0);
+ return true;
+ }
+ }
+ }
+ if (
+ currentId === 'original' &&
+ !request &&
+ fs.existsSync(path.join(versionsRoot(profile), 'original.json'))
+ ) {
+ try {
+ await rememberOriginalVersion();
+ if (process.argv.includes('--cindy-version-original'))
+ await selectVersion(profile, 'original');
+ const selected = selectedVersion(profile);
+ if (selected !== 'original') {
+ await startVersionHandoff(selected);
+ app.exit(0);
+ return true;
+ }
+ } catch {
+ await selectVersion(profile, 'original').catch(() => {});
+ log.warn('Personal version selection unavailable; opening the original');
+ }
+ }
+ return false;
+}
+
+export async function markCindyVersionReady(): Promise<void> {
+ if (!request || helper) return;
+ const file = versionRequestPath(request.profile.userData, request.id);
+ const latest = readVersionJson<VersionLaunchRequest>(file);
+ if (!latest || latest.state !== 'starting' || latest.claimedPid !== process.pid) return;
+ await selectVersion(request.profile.userData, currentId);
+ writeVersionJson(file, { ...latest, state: 'ready' });
+ await withVersionStore(request.profile.userData, async () => {
+ const pending = path.join(versionsRoot(request!.profile.userData), 'pending.json');
+ if (readVersionJson<{ id: string }>(pending)?.id === request!.id) fs.unlinkSync(pending);
+ });
+}
diff --git a/apps/desktop/src/main/cindy-make/versionStore.ts b/apps/desktop/src/main/cindy-make/versionStore.ts
new file mode 100644
index 0000000000..d6622d7c6c
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/versionStore.ts
@@ -0,0 +1,372 @@
+import path from 'node:path';
+import fs from 'node:fs';
+import { createHash, randomUUID } from 'node:crypto';
+import originalFs from 'original-fs';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
+import { createMigrationRuntimeManifest } from '../localDb/migrationRunner.js';
+import { CINDY_VERSION_PROTOCOL, type CindyVersionInfo } from '../../shared/cindyVersions.js';
+import type { CindyVersionEndpointSnapshot } from './versionRuntimeIdentity.js';
+
+export const VERSION_ID = /^[a-f0-9-]{36}$/;
+export const ORIGINAL_DEV_ENV_KEYS = [
+ 'PATH',
+ 'XDT_USER_DATA_DIR',
+ 'XDT_ISOLATED',
+ 'XDT_ISOLATED_NAME',
+ 'XDT_USER_DATA_DIR_EPOCH',
+ 'XDT_DEVICE_ID_OVERRIDE',
+ 'XDT_SCHEDULER_PASSIVE',
+ 'XDT_ENDPOINTS_CDN',
+ 'XDT_ENDPOINT_MANIFEST_FILE',
+ 'XDT_DEV_SAFE_STORAGE_BASIC',
+ 'CINDY_AUTH_REGION',
+];
+export interface VersionProfile {
+ userData: string;
+ appName: string;
+ region: 'cn' | 'global' | 'dev';
+ deviceId?: string;
+ passive: boolean;
+ endpointSnapshot?: CindyVersionEndpointSnapshot;
+}
+export interface OriginalVersion {
+ protocol: 1;
+ version?: string;
+ commit?: string;
+ dirty?: boolean;
+ profile: VersionProfile;
+ executable: string;
+ appPath: string;
+ resources: string;
+ migrationHash?: string;
+ development?: {
+ root: string;
+ node: string;
+ mode: 'local' | 'remote';
+ environment: Record<string, string>;
+ };
+}
+export interface PersonalVersion {
+ protocol: 1;
+ id: string;
+ profile: VersionProfile;
+ title: string;
+ commit: string;
+ tree?: string;
+ builtAt: string;
+ platform: string;
+ arch: string;
+ executable: string;
+ resources: string;
+ executableHash: string;
+ applicationHash: string;
+ migrationHash: string;
+}
+export function versionError(
+ code: 'busy' | 'unavailable' | 'incompatible' | 'launchFailed',
+): Error & { code: string } {
+ return Object.assign(new Error(code), { code });
+}
+export const versionsRoot = (profile: string) => path.join(profile, 'cindy-versions');
+export function versionDirectory(profile: string, id: string): string {
+ if (!VERSION_ID.test(id)) throw versionError('unavailable');
+ return path.join(versionsRoot(profile), 'versions', id);
+}
+export function sameVersionPath(a: string, b: string): boolean {
+ return process.platform === 'win32'
+ ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
+ : path.resolve(a) === path.resolve(b);
+}
+export function assertVersionDirectory(profile: string, directory: string): void {
+ const relative = path.relative(profile, directory);
+ if (path.isAbsolute(relative) || relative === '..' || relative.startsWith('..' + path.sep))
+ throw versionError('unavailable');
+ const expected = path.join(fs.realpathSync(profile), relative);
+ if (
+ fs.lstatSync(directory).isSymbolicLink() ||
+ !sameVersionPath(fs.realpathSync(directory), expected)
+ )
+ throw versionError('unavailable');
+}
+export function readVersionJson<T>(file: string): T | null {
+ try {
+ const stat = fs.lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 256 * 1024)
+ throw versionError('unavailable');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ const raw = readAtomicFileSync(file);
+ if (raw && raw.length > 256 * 1024) throw versionError('unavailable');
+ return raw === null ? null : (JSON.parse(raw) as T);
+}
+export function writeVersionJson(file: string, value: unknown): void {
+ atomicWriteFileSync(file, JSON.stringify(value) + '\n');
+}
+export function readOriginalVersion(profile: string): OriginalVersion | null {
+ const value = readVersionJson<OriginalVersion>(path.join(versionsRoot(profile), 'original.json'));
+ if (
+ value &&
+ (value.protocol !== 1 ||
+ !sameVersionPath(value.profile?.userData ?? '', profile) ||
+ !path.isAbsolute(value.executable) ||
+ !path.isAbsolute(value.resources))
+ )
+ throw versionError('unavailable');
+ if (
+ value?.development &&
+ (!path.isAbsolute(value.development.root) ||
+ typeof value.development.node !== 'string' ||
+ !['local', 'remote'].includes(value.development.mode) ||
+ !value.development.environment ||
+ Object.entries(value.development.environment).some(
+ ([key, entry]) => !ORIGINAL_DEV_ENV_KEYS.includes(key) || typeof entry !== 'string',
+ ))
+ )
+ throw versionError('unavailable');
+ return value;
+}
+export function readPersonalVersion(profile: string, id: string): PersonalVersion {
+ const directory = versionDirectory(profile, id);
+ assertVersionDirectory(profile, directory);
+ const item = readVersionJson<PersonalVersion>(path.join(directory, 'version.json'));
+ if (
+ !item ||
+ item.protocol !== 1 ||
+ item.id !== id ||
+ !sameVersionPath(item.profile?.userData ?? '', profile) ||
+ item.platform !== process.platform ||
+ item.arch !== process.arch
+ )
+ throw versionError('unavailable');
+ if (
+ typeof item.title !== 'string' ||
+ item.title.length > 4096 ||
+ typeof item.builtAt !== 'string' ||
+ !Number.isFinite(Date.parse(item.builtAt)) ||
+ typeof item.commit !== 'string' ||
+ !/^[0-9a-f]{7,64}$/i.test(item.commit) ||
+ (item.tree !== undefined && !/^[0-9a-f]{40,64}$/i.test(item.tree)) ||
+ [item.migrationHash, item.executableHash, item.applicationHash].some(
+ (hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash),
+ )
+ )
+ throw versionError('unavailable');
+ for (const rel of [item.executable, item.resources]) {
+ if (typeof rel !== 'string' || path.isAbsolute(rel) || rel.split(/[\/\\]/).includes('..'))
+ throw versionError('unavailable');
+ const full = path.join(directory, rel);
+ if (!sameVersionPath(fs.realpathSync(full), path.join(fs.realpathSync(directory), rel)))
+ throw versionError('unavailable');
+ }
+ return item;
+}
+export function migrationIdentity(directory: string): string {
+ return createHash('sha256')
+ .update(JSON.stringify(createMigrationRuntimeManifest(directory).migrations))
+ .digest('hex');
+}
+export async function fileDigest(file: string): Promise<string> {
+ const hash = createHash('sha256');
+ for await (const data of originalFs.createReadStream(file)) hash.update(data);
+ return hash.digest('hex');
+}
+export function runnableBundlePaths(
+ directory: string,
+ appName: string,
+ platform: NodeJS.Platform = process.platform,
+) {
+ return {
+ executable:
+ platform === 'darwin'
+ ? path.join(directory, 'Contents', 'MacOS', appName)
+ : path.join(directory, appName + (platform === 'win32' ? '.exe' : '')),
+ resources:
+ platform === 'darwin'
+ ? path.join(directory, 'Contents', 'Resources')
+ : path.join(directory, 'resources'),
+ };
+}
+async function assertRuntimeLinksInside(directory: string): Promise<void> {
+ if ((await originalFs.promises.lstat(directory)).isSymbolicLink())
+ throw versionError('unavailable');
+ const root = await originalFs.promises.realpath(directory);
+ const walk = async (folder: string): Promise<void> => {
+ for (const entry of await originalFs.promises.readdir(folder, { withFileTypes: true })) {
+ const full = path.join(folder, entry.name);
+ if (entry.isSymbolicLink()) {
+ if (path.isAbsolute(await originalFs.promises.readlink(full)))
+ throw versionError('unavailable');
+ const target = path.relative(root, await originalFs.promises.realpath(full));
+ if (path.isAbsolute(target) || target === '..' || target.startsWith('..' + path.sep))
+ throw versionError('unavailable');
+ } else if (entry.isDirectory()) await walk(full);
+ }
+ };
+ await walk(directory);
+}
+export function publishPersonalVersion(profile: string, id: string): void {
+ const directory = versionDirectory(profile, id);
+ assertVersionDirectory(profile, directory);
+ const staged = readVersionJson<PersonalVersion>(path.join(directory, 'staged.json'));
+ if (!staged || staged.id !== id) throw versionError('unavailable');
+ writeVersionJson(path.join(directory, 'version.json'), staged);
+ try {
+ fs.unlinkSync(path.join(directory, 'staged.json'));
+ } catch {}
+}
+export async function verifyPersonalVersion(
+ profile: string,
+ id: string,
+ original: OriginalVersion,
+): Promise<PersonalVersion> {
+ const item = readPersonalVersion(profile, id);
+ const root = versionDirectory(profile, id);
+ if (
+ item.profile.region !== original.profile.region ||
+ item.migrationHash !==
+ (original.migrationHash ?? migrationIdentity(path.join(original.resources, 'drizzle')))
+ )
+ throw versionError('incompatible');
+ const resources = path.join(root, item.resources);
+ if (
+ readVersionJson<{ version: number }>(path.join(resources, 'cindy-version-protocol.json'))
+ ?.version !== CINDY_VERSION_PROTOCOL ||
+ (await fileDigest(path.join(root, item.executable))) !== item.executableHash ||
+ (await fileDigest(path.join(resources, 'app.asar'))) !== item.applicationHash ||
+ migrationIdentity(path.join(resources, 'drizzle')) !== item.migrationHash
+ )
+ throw versionError('unavailable');
+ return item;
+}
+export async function withVersionStore<T>(profile: string, run: () => Promise<T>): Promise<T> {
+ const root = versionsRoot(profile);
+ await fs.promises.mkdir(root, { recursive: true });
+ assertVersionDirectory(profile, root);
+ return withCrossProcessLock(
+ path.join(root, 'registry.lock'),
+ { label: 'cindy-versions' },
+ async (lock) => {
+ if (!lock.held) throw versionError('busy');
+ return run();
+ },
+ );
+}
+export function selectedVersion(profile: string): string {
+ const value = readVersionJson<{ id: string }>(path.join(versionsRoot(profile), 'selected.json'));
+ if (!value) return 'original';
+ if (value.id !== 'original' && !VERSION_ID.test(value.id)) throw versionError('unavailable');
+ return value.id;
+}
+export async function selectVersion(profile: string, id: string): Promise<void> {
+ if (id !== 'original' && !VERSION_ID.test(id)) throw versionError('unavailable');
+ await withVersionStore(profile, async () =>
+ writeVersionJson(path.join(versionsRoot(profile), 'selected.json'), { id }),
+ );
+}
+export function listPersonalVersions(
+ profile: string,
+ original: OriginalVersion | null,
+): CindyVersionInfo[] {
+ const root = path.join(versionsRoot(profile), 'versions');
+ if (!fs.existsSync(root)) return [];
+ assertVersionDirectory(profile, root);
+ let fingerprint: string | undefined;
+ try {
+ if (original)
+ fingerprint =
+ original.migrationHash ?? migrationIdentity(path.join(original.resources, 'drizzle'));
+ } catch {}
+ return fs
+ .readdirSync(root)
+ .filter((id) => VERSION_ID.test(id))
+ .flatMap<CindyVersionInfo>((id) => {
+ if (!fs.existsSync(path.join(root, id, 'version.json'))) return [];
+ try {
+ const item = readPersonalVersion(profile, id);
+ return [
+ {
+ id,
+ kind: 'personal' as const,
+ title: item.title,
+ commit: item.commit,
+ builtAt: item.builtAt,
+ available: true,
+ compatible:
+ item.migrationHash === fingerprint &&
+ item.profile.region === original?.profile.region,
+ },
+ ];
+ } catch {
+ return [{ id, kind: 'personal' as const, available: false, compatible: false }];
+ }
+ })
+ .sort((a, b) => (b.builtAt ?? '').localeCompare(a.builtAt ?? ''));
+}
+
+/** Copy the complete signed bundle unchanged; macOS framework symlinks stay inside it. */
+export async function retainPersonalVersion(input: {
+ profile: VersionProfile;
+ sourceDirectory: string;
+ appName: string;
+ title: string;
+ commit: string;
+ tree?: string;
+}): Promise<string | undefined> {
+ const sourceResources = runnableBundlePaths(input.sourceDirectory, input.appName).resources;
+ // Old source revisions still export installers, but cannot offer an unsupported profile handoff.
+ if (
+ readVersionJson<{ version: number }>(path.join(sourceResources, 'cindy-version-protocol.json'))
+ ?.version !== 1
+ )
+ return undefined;
+ const sourceInfo = readVersionJson<{ sourceCommit: string; builtAt: string }>(
+ path.join(sourceResources, 'cindy-source.json'),
+ );
+ if (sourceInfo?.sourceCommit !== input.commit || !sourceInfo.builtAt)
+ throw versionError('unavailable');
+ await assertRuntimeLinksInside(input.sourceDirectory);
+ const id = randomUUID();
+ const directory = versionDirectory(input.profile.userData, id);
+ const runtime = path.join(
+ directory,
+ 'runtime',
+ process.platform === 'darwin' ? input.appName + '.app' : input.appName,
+ );
+ await fs.promises.mkdir(path.dirname(directory), { recursive: true });
+ assertVersionDirectory(input.profile.userData, path.dirname(directory));
+ try {
+ await originalFs.promises.cp(input.sourceDirectory, runtime, {
+ recursive: true,
+ dereference: false,
+ verbatimSymlinks: true,
+ preserveTimestamps: true,
+ });
+ const { executable, resources } = runnableBundlePaths(runtime, input.appName);
+ const item: PersonalVersion = {
+ protocol: 1,
+ id,
+ profile: input.profile,
+ title: input.title,
+ commit: input.commit,
+ ...(input.tree ? { tree: input.tree } : {}),
+ builtAt: sourceInfo.builtAt,
+ platform: process.platform,
+ arch: process.arch,
+ executable: path.relative(directory, executable),
+ resources: path.relative(directory, resources),
+ executableHash: await fileDigest(executable),
+ applicationHash: await fileDigest(path.join(resources, 'app.asar')),
+ migrationHash: migrationIdentity(path.join(resources, 'drizzle')),
+ };
+ writeVersionJson(path.join(directory, 'staged.json'), item);
+ return id;
+ } catch (error) {
+ if (fs.existsSync(directory)) {
+ assertVersionDirectory(input.profile.userData, directory);
+ await originalFs.promises.rm(directory, { recursive: true, force: true });
+ }
+ throw error;
+ }
+}
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index e3d2884293..c16e5f9cc5 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -16,6 +16,7 @@ import { beginDesktopDevInstance, type DesktopDevMode } from './devStartupStatus
import { ensureSystemBinPathForMachineId } from './deviceId.js';
import { configureLinuxPasswordStore } from './linuxPasswordStore.js';
import { recognizeLinuxUserInstallation, linuxUserDesktopName } from './linuxInstallation.js';
+import { prepareCindyVersionStartup, dispatchCindyVersionStartup } from './cindy-make/versionStartup.js';
if (process.platform === 'linux' && app.isPackaged) {
const installation = recognizeLinuxUserInstallation(app.getPath('exe'), os.homedir(), process.getuid?.() ?? -1);
@@ -43,6 +44,8 @@ const regionUserDataDirName = resolveRegionUserDataDirName({
if (regionUserDataDirName) {
app.setPath('userData', path.join(app.getPath('appData'), regionUserDataDirName));
}
+// A verified version handoff retains the launching original's profile and keychain identity.
+prepareCindyVersionStartup();
// Node happy-eyeballs(autoSelectFamily)默认每个地址只给 250ms 完成 TCP 握手,
// VPN/高 RTT 链路上直连海外端点(platform.claude.com 换 token、订阅模式模型流量等)
@@ -284,6 +287,7 @@ if (!process.env.XDT_BROWSER_RUNTIME_DIR) {
refreshBrowserRuntimeConfigDir();
async function dispatch(): Promise<void> {
+ if (await dispatchCindyVersionStartup()) return;
const cleanupDevInstance = await beginDesktopDevInstance(desktopDevInstanceOptions);
// Windows updater forceQuit() ends in process.exit(0), which bypasses Electron will-quit.
process.once('exit', cleanupDevInstance);
diff --git a/apps/desktop/src/main/localDb/index.ts b/apps/desktop/src/main/localDb/index.ts
index 4010ec3b3e..34d976becf 100644
--- a/apps/desktop/src/main/localDb/index.ts
+++ b/apps/desktop/src/main/localDb/index.ts
@@ -26,6 +26,7 @@
import type Database from 'better-sqlite3';
import { drizzle, type BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
import { app, dialog, BrowserWindow } from 'electron';
+import { isCindyPersonalRuntime } from '../cindy-make/versionRuntimeIdentity.js';
import fs from 'node:fs';
import { createBetterSqliteDatabase } from './betterSqliteFactory';
@@ -155,7 +156,7 @@ export async function ensureReady(userId: string): Promise<EnsureReadyResult> {
}
const filePath = dbPath(userId);
- const passiveSharedUserData = !app.isPackaged && process.env.XDT_PASSIVE_SHARED_USER_DATA === '1';
+ const passiveSharedUserData = (isCindyPersonalRuntime() && fs.existsSync(filePath)) || (!app.isPackaged && process.env.XDT_PASSIVE_SHARED_USER_DATA === '1');
// A packaged release may be launched while a shared passive dev instance is still
// open. The passive reader lease must continue to block schema writes, but an
// already-compatible database does not need any startup DDL; let the release use
diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.ts
index 1b4c0232b1..2ba6f0a21c 100644
--- a/apps/desktop/src/main/localDb/mapper.ts
+++ b/apps/desktop/src/main/localDb/mapper.ts
@@ -371,7 +371,7 @@ export function sessionCreateToRow(
*/
providerId?: string | null;
/** Main-owned purposes only; the renderer create IPC validates which values it accepts. */
- source?: 'bot' | 'cindy-make';
+ source?: 'bot' | 'cindy-make' | 'cindy-make-merge';
}
| undefined,
now: number,
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 0761a6e869..8c10115bca 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -37,6 +37,7 @@ const SESSION_SOURCES = [
'plugin',
'bot',
'cindy-make',
+ 'cindy-make-merge',
] as const satisfies readonly SessionSource[];
export const sessions = sqliteTable(
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 529f6526a7..5e77cdd8e3 100644
--- a/apps/desktop/src/main/maker-host/git-snapshot-host.ts
+++ b/apps/desktop/src/main/maker-host/git-snapshot-host.ts
@@ -7,6 +7,12 @@
*/
import type { AgentKind, Maker } from '@cindy/maker-core';
+import { app } from 'electron';
+import path from 'node:path';
+import {
+ isCindyMakeManagedWorktreePath,
+ makeSourceCheckoutPath,
+} from '../cindy-make/sourcePaths.js';
import { and, desc, eq, isNull } from 'drizzle-orm';
import { GitSnapshotCoordinator } from '../git-snapshot/gitSnapshotCoordinator.js';
@@ -33,10 +39,16 @@ interface LatestUserMessage {
export interface GitSnapshotCoordinatorHostDeps {
readAutoSnapshotEnabled?: () => boolean;
detectRepoRoot?: (workingDir: string) => Promise<string | null>;
- initializeProjectGit?: ConstructorParameters<typeof GitSnapshotCoordinator>[0]['initializeProjectGit'];
+ initializeProjectGit?: ConstructorParameters<
+ typeof GitSnapshotCoordinator
+ >[0]['initializeProjectGit'];
getLatestUserMessage?: (sessionId: string) => Promise<LatestUserMessage | null>;
- createShadowSavepoint?: ConstructorParameters<typeof GitSnapshotCoordinator>[0]['createShadowSavepoint'];
- createShadowMarker?: ConstructorParameters<typeof GitSnapshotCoordinator>[0]['createShadowMarker'];
+ createShadowSavepoint?: ConstructorParameters<
+ typeof GitSnapshotCoordinator
+ >[0]['createShadowSavepoint'];
+ createShadowMarker?: ConstructorParameters<
+ typeof GitSnapshotCoordinator
+ >[0]['createShadowMarker'];
logger?: ConstructorParameters<typeof GitSnapshotCoordinator>[0]['logger'];
}
@@ -55,11 +67,9 @@ async function defaultGetLatestUserMessage(sessionId: string): Promise<LatestUse
const [row] = await db
.select({ clientId: messages.clientId, content: messages.content })
.from(messages)
- .where(and(
- eq(messages.sessionId, sessionId),
- eq(messages.role, 'user'),
- isNull(messages.rewindAt),
- ))
+ .where(
+ and(eq(messages.sessionId, sessionId), eq(messages.role, 'user'), isNull(messages.rewindAt)),
+ )
.orderBy(desc(messages.createdAt))
.limit(1);
@@ -108,6 +118,17 @@ export function createGitSnapshotCoordinator(
getSessionContext: async (sessionId) => {
const meta = await maker.getSessionMeta(sessionId);
if (!meta?.workDir || meta.remoteHostId) return null;
+ // Cindy Make stores file trees itself. Generic savepoints create commit objects.
+ const userData = app.getPath('userData');
+ const samePath = (a: string, b: string) =>
+ process.platform === 'win32'
+ ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
+ : path.resolve(a) === path.resolve(b);
+ if (
+ isCindyMakeManagedWorktreePath(userData, meta.workDir) ||
+ samePath(meta.workDir, makeSourceCheckoutPath(userData))
+ )
+ return null;
return {
workingDir: meta.workDir,
agentKind: meta.agentKind as AgentKind,
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 0a174d9fd2..db2fb9df0c 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -54,8 +54,11 @@ import { listCustomMcpRuntimeGenerations } from './custom-mcp-store.js';
import { createMessage } from '../localDb/ipc/messages.js';
import { createCindyMakeMcpProvider } from '../cindy-make/mcpProvider.js';
+import { captureMakeHistoryStore } from '../cindy-make/historyOwner.js';
+import { captureMakeHistoryCompletion } from '../cindy-make/historyCapture.js';
+import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from '../device-link/broadcast-tap.js';
import {
- commitCindyMakeChanges,
+ collectCindyMakeChanges,
createCindyMakeCompletionTracker,
} from '../cindy-make/completion.js';
import { isCindyMakeWorktreePath } from '../cindy-make/taskWorkspace.js';
@@ -1067,28 +1070,38 @@ export function getMaker(): Maker {
collectFacts: async (sessionId) => {
const userData = app.getPath('userData');
const meta = await _maker?.getSessionMeta(sessionId);
- // Only a worktree Cindy created for this task may be committed on the
- // task's behalf; anything else is not a Cindy Make workspace.
+ // Finalize only the managed task branch; official/personal integration is a separate action.
if (!meta?.workDir || !isCindyMakeWorktreePath(userData, meta.workDir)) {
throw new Error('session working directory is not a Cindy Make worktree');
}
const env = await createMakeToolchainEnvironment(userData);
- const title = meta.title?.trim();
return cindyMakeManager.withProject(makeSourceRoot(userData), () =>
- commitCindyMakeChanges(
- (args) =>
- runSourceGit(env.processEnvironment(), args, meta.workDir, AbortSignal.timeout(60_000)),
- `Cindy Make: ${title || sessionId}`,
+ collectCindyMakeChanges(
+ (args, cwd, indexFile) =>
+ runSourceGit(
+ { ...env.processEnvironment(), ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args, cwd, AbortSignal.timeout(60_000),
+ ),
+ userData,
+ meta.workDir,
),
);
},
- persist: (sessionId, meta) =>
- createMessage(sessionId, {
- clientId: randomUUID(),
+ persist: async (sessionId, meta) => {
+ const scope = captureDataOwnerBroadcastScope();
+ const history = captureMakeHistoryStore();
+ const session = await _maker?.getSessionMeta(sessionId);
+ if (!isDataOwnerBroadcastScopeCurrent(scope)) return;
+ const clientId = randomUUID();
+ await createMessage(sessionId, {
+ clientId,
role: 'assistant',
content: '',
agentMeta: { cindyMakeCompletion: meta },
- }).then(() => undefined),
+ });
+ if (isDataOwnerBroadcastScopeCurrent(scope) && session?.workDir)
+ captureMakeHistoryCompletion(history, path.basename(session.workDir), clientId, meta);
+ },
logger: desktopMakerLogger,
});
const cindyMakeProvider = createCindyMakeMcpProvider({
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/cindyMakeSessionStart.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/cindyMakeSessionStart.test.ts
index 7b6b0b613e..dd3570be17 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/cindyMakeSessionStart.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/cindyMakeSessionStart.test.ts
@@ -4,6 +4,11 @@ import { CINDY_MAKE_VENDOR_OPTION_KEY } from '../../../shared/cindyMakeSession';
import { applyPersistedCindyMakeMarker } from '../cindyMakeSessionStart';
describe('applyPersistedCindyMakeMarker', () => {
+ it('does not give an upstream merge task the personal-build harness', async () => {
+ const options: { id: string; vendorOptions?: Record<string, unknown> } = { id: 'merge' };
+ expect(await applyPersistedCindyMakeMarker(options, async () => 'cindy-make-merge')).toBe(false);
+ expect(options.vendorOptions?.[CINDY_MAKE_VENDOR_OPTION_KEY]).not.toBe(true);
+ });
it('hydrates the marker only from a persisted cindy-make source', async () => {
const readSource = vi.fn(async (id: string) => (id === 'make-1' ? 'cindy-make' : 'desktop'));
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
index 5746064c70..be904c3b49 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@ -240,6 +240,7 @@ function harness() {
});
const activity = new SessionTurnActivityTracker();
const deps = {
+ onSuccessfulProductTurn: vi.fn(async () => {}),
log,
botCompactRuntimeRefreshCoordinator: { noteBoundary: vi.fn() },
attemptBotCompactRuntimeRefresh: vi.fn(),
@@ -389,6 +390,16 @@ function ordered(...names: string[]) {
}
describe('production Session event pipeline', () => {
+ it.each(['completed', 'failed', 'cancelled', 'interrupted'])(
+ 'runs the upstream-merge follow-up only for a successful product boundary: %s', async (status) => {
+ const h = harness();
+ h.emit(event('status', { isRunning: true }));
+ h.emit(event('done', { status }));
+ await microtasks();
+ expect(h.deps.onSuccessfulProductTurn).toHaveBeenCalledTimes(status === 'completed' ? 1 : 0);
+ await h.dispose();
+ },
+ );
it.each([
['zh-CN', 'Pi 扩展未能完成刷新。请重启 Cindy 后再使用 Pi。'],
['zh-TW', 'Pi 擴充功能未能完成重新整理。請重新啟動 Cindy 後再使用 Pi。'],
@@ -451,6 +462,7 @@ describe('production Session event pipeline', () => {
effects.fn('consumeLastAssistantPersistId').mockReturnValueOnce('segment-row');
vi.setSystemTime(3000);
h.emit(event('done', {}, { source, turnContinuationId: 0 }));
+ expect(h.deps.onSuccessfulProductTurn).not.toHaveBeenCalled();
expect(h.activity.isSessionInTurn('task')).toBe(true);
expect(h.deps.notifyGoalIdleAfterTurnSettled).not.toHaveBeenCalled();
expect(effects.fn('turn-drain')).not.toHaveBeenCalled();
@@ -1383,7 +1395,6 @@ describe('Bot adapters in the shared event pipeline', () => {
await microtasks();
expect(h.deps.botDelegationServiceHolder.settleSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
childSessionId: 'task', outcome: 'error', resultText: result,
- execution: { instanceId: h.session.instanceId, generation: 4 },
error: 'Pi reached the model output limit.',
}));
h.deps.autoResumeBookkeeping.consumeFailedTurnCompletionTail.mockReturnValue(true);
@@ -1409,21 +1420,6 @@ describe('Bot adapters in the shared event pipeline', () => {
}));
});
- it('preserves retry ownership in the terminal queue snapshot', async () => {
- const h = harness();
- h.deps.agentInputCoordinatorHolder.getQueueControlSnapshot.mockReturnValue({ pendingQueue: [
- { clientId: 'retry-clone', supersedesUserClientId: 'bot-delegation-interject:task:original' },
- { clientId: 'auto-clone', retrySourceClientId: 'bot-delegation-interject:task:auto' },
- { clientId: 'direct-input' },
- ] });
- h.emit(event('done', { result: 'prior result' }));
- await microtasks();
- expect(h.deps.botDelegationServiceHolder.settleSession).toHaveBeenCalledWith(expect.objectContaining({
- pendingInputClientIds: ['retry-clone', 'bot-delegation-interject:task:original', 'auto-clone', 'bot-delegation-interject:task:auto', 'direct-input'],
- }));
- await h.dispose();
- });
-
it('carries a pending follow-up into task settlement and remembers compact boundaries without rebuilding early', async () => {
const h = harness();
h.emit(event('compact_boundary'));
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 02468f305e..7df0bc698f 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -595,8 +595,9 @@ import { applyPersistedCindyMakeMarker } from './cindyMakeSessionStart.js';
import { CINDY_MAKE_SESSION_SOURCE } from '../../shared/cindyMakeSession.js';
import { cindyMakeManager } from '../cindy-make/manager.js';
import { assertCindyMakeWorkspace, withCindyMakeProjectUse } from '../cindy-make/projectAccess.js';
-import { isCindyMakeWorktreePath } from '../cindy-make/sourcePaths.js';
+import { isCindyMakeWorktreePath, isCindyMakeManagedWorktreePath } from '../cindy-make/sourcePaths.js';
import { assertCindyMakeTaskReady, configureCindyMakeTaskSender, CINDY_MAKE_TASK_DISPATCH } from '../cindy-make/taskRuntime.js';
+import { finishUpstreamMergeTurn, assertUpstreamMergeTaskWritable } from '../cindy-make/upstreamMergeRuntime.js';
import { isIpcError, type IpcErrorCode } from '../../shared/ipc-errors.js';
import { piPackageCommandDiagnostic } from '../maker-host/pi-package-diagnostic.js';
import {
@@ -4459,6 +4460,7 @@ function cleanupClosedSessionRuntime(session: WiredSession): void {
// operation. Capturing these services when wiring a Session would freeze the
// pre-initialization or previous runtime value for later events.
const sessionEventDependencies: SessionEventDependencies = {
+ onSuccessfulProductTurn: finishUpstreamMergeTurn,
get botCompactRuntimeRefreshCoordinator() { return botCompactRuntimeRefreshCoordinator; },
get attemptBotCompactRuntimeRefresh() { return attemptBotCompactRuntimeRefresh; },
get botDelegationServiceHolder() { return botDelegationServiceHolder; },
@@ -8492,6 +8494,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
anchorClientId: string,
opts: SessionSendOptions,
): Promise<SessionSendResult> {
+ assertUpstreamMergeTaskWritable(session.id);
if (!session.remoteHostId && isCindyMakeWorktreePath(app.getPath('userData'), session.workDir)) {
if (cindyMakeManager.isTaskPreparing(session.id))
throwIpcError('PRECONDITION_FAILED', 'Cindy Make is still preparing this task');
@@ -18125,7 +18128,7 @@ async function checkWorkDirExists(
// 或者 agent 真跑起来时由远端 codex 自己报 ENOENT)。这里直接放行。
if (remoteHostId) return true;
if (!workingDir?.trim()) return true;
- const cindyMakeWorkspace = isCindyMakeWorktreePath(app.getPath('userData'), workingDir);
+ const cindyMakeWorkspace = isCindyMakeManagedWorktreePath(app.getPath('userData'), workingDir);
if (cindyMakeWorkspace) workingDirectoryRecovery.discard(sessionId);
workingDir = workingDirectoryRecovery.resolve(sessionId, workingDir);
const source: AgentKind = agentKind === 'codex' || agentKind === 'pi' ? agentKind : 'claude-code';
diff --git a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
index 0afec7c5d4..75d803a6b4 100644
--- a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
@@ -46,6 +46,7 @@ import type { PreparedSessionEvent } from './sessionEventPreparation.js';
import type { SessionDeliveryResult } from './sessionEventDelivery.js';
import { isSessionErrorSuppressed } from './sessionErrorSuppression.js';
export interface FinishSessionTerminalEventDeps {
+ readonly onSuccessfulProductTurn?: (sessionId: string) => Promise<void>;
readonly botDelegationServiceHolder: Pick<BotDelegationService, 'settleSession'> | null;
readonly pendingFailedTurnAssistantPersistId: Map<string, string>;
readonly autoResumeBookkeeping: Pick<
@@ -436,6 +437,15 @@ export function finishSessionTerminalEvent(
session.id,
event.sessionTurnGeneration,
);
+ if (event.type === 'done' && !isContinuationBoundary && !isPairedFailedTurnDone &&
+ !isFailedTurnCompletionTail && !deferredOrcaWorkerTerminal &&
+ !isTerminalTurnErrorEvent(event) && isSuccessfulAssistantReplyDoneData(event.data) &&
+ !deps.autoResumeBookkeeping.hasSuppressedError(session.id) &&
+ !deps.agentInputCoordinatorHolder?.isAutoResumePending(session.id) &&
+ !deps.agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id)) {
+ void deps.onSuccessfulProductTurn?.(session.id).catch(() =>
+ deps.log.warn('Could not finish product turn follow-up'));
+ }
if (
!shouldSkipOrcaWorkerTerminal({
isContinuationBoundary,
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index afda73b708..903c0ed8bf 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -3856,10 +3856,45 @@ contextBridge.exposeInMainWorld('electronAPI', {
getCindyMakeSourceStatus: (): Promise<import('../shared/cindyMakeDoctor').MakeSourceStatus> =>
ipcRenderer.invoke('app:get-cindy-make-source-status'),
+ cindyMakeMerge: (
+ input: import('../shared/cindyMakeMerge').CindyMakeMergeRequest,
+ ): Promise<import('../shared/cindyMakeMerge').CindyMakeMergeState | undefined> =>
+ ipcRenderer.invoke('app:cindy-make-merge', input),
+ getCindyMakeHistory: (
+ selected?: string,
+ ): Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState> =>
+ ipcRenderer.invoke('app:cindy-make-history', selected),
+ actCindyMakeHistory: (
+ runId: string,
+ action: import('../shared/cindyMakeHistory').MakeHistoryAction,
+ ): Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState> =>
+ ipcRenderer.invoke('app:cindy-make-history-action', runId, action),
+ generateCindyMakePersonal: (): Promise<
+ import('../shared/cindyMakeHistory').CindyMakeHistoryState
+ > => ipcRenderer.invoke('app:cindy-make-history-build'),
+ cancelCindyMakePersonal: (
+ buildId: string,
+ ): Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState> =>
+ ipcRenderer.invoke('app:cindy-make-history-cancel-build', buildId),
+ openCindyMakeHistoryBuild: (): Promise<void> =>
+ ipcRenderer.invoke('app:cindy-make-history-open-build'),
+ cindyMakeTest: (
+ sessionId: string,
+ completionId: string,
+ action: import('../shared/cindyMakeSession').CindyMakeTestAction,
+ ): Promise<import('../shared/cindyMakeSession').CindyMakeCompletionMeta> =>
+ ipcRenderer.invoke('app:cindy-make-test', sessionId, completionId, action),
+ getCindyVersions: (): Promise<import('../shared/cindyVersions').CindyVersionsState> =>
+ ipcRenderer.invoke('app:cindy-versions-state'),
+ actCindyVersion: (
+ action: import('../shared/cindyVersions').CindyVersionAction,
+ id: string,
+ ): Promise<import('../shared/cindyVersions').CindyVersionsState> =>
+ ipcRenderer.invoke('app:cindy-versions-action', action, id),
getCindyMakeState: (): Promise<import('../shared/cindyMakeDoctor').CindyMakeGlobalState> =>
ipcRenderer.invoke('app:get-cindy-make-state'),
- manageCindyMakeTask: (sessionId: string, action: 'finish' | 'delete'): Promise<void> =>
+ manageCindyMakeTask: (sessionId: string, action: 'end' | 'finish' | 'delete'): Promise<void> =>
ipcRenderer.invoke('app:manage-cindy-make-task', sessionId, action),
onCindyMakeState: (
@@ -3895,8 +3930,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
runId: string,
): Promise<import('../shared/cindyMakeDoctor').MakeTaskWorkspace> =>
ipcRenderer.invoke('app:prepare-cindy-make-workspace', runId),
- startCindyMakeTask: (input: import('../shared/cindyMakeDoctor').CindyMakeTaskStart): Promise<string> =>
- ipcRenderer.invoke('app:start-cindy-make-task', input),
+ startCindyMakeTask: (
+ input: import('../shared/cindyMakeDoctor').CindyMakeTaskStart,
+ ): Promise<string> => ipcRenderer.invoke('app:start-cindy-make-task', input),
cancelCindyMakeTask: (runId: string): Promise<{ success: boolean }> =>
ipcRenderer.invoke('app:cancel-cindy-make-task', runId),
diff --git a/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts b/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts
index e917ed0343..d858897ccf 100644
--- a/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/cindyMakeInlineEntry.test.ts
@@ -31,6 +31,6 @@ describe('Cindy Make composer presentation', () => {
/pendingPlanReview ||[\s\S]*pendingPermission ||[\s\S]*pendingAskUser/,
);
expect(interactionGuard).toContain('pendingGhostGrantConfirm ? null');
- expect(sessionView).toContain('if (cindyMakeComposerPhase) return false;');
+ expect(sessionView).toContain('if (cindyMakeComposerPhase || cindyMakePendingTest) return false;');
});
});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/CindyMakeCompleteCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/CindyMakeCompleteCard.test.tsx
index c83c7d083f..fb929e0db6 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/CindyMakeCompleteCard.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/CindyMakeCompleteCard.test.tsx
@@ -27,7 +27,7 @@ const render = (ui: ReactElement) => renderUI(ui, { wrapper: MemoryRouter });
afterEach(() => cleanup());
describe('cindy-make-complete system card', () => {
- it('renders a full card with the code step and code-verified facts', () => {
+ it('renders one completion summary with code-verified facts', () => {
render(
<SystemCard
cardType="cindy-make-complete"
@@ -41,7 +41,9 @@ describe('cindy-make-complete system card', () => {
);
expect(screen.getByRole('region', { name: 'cindyMake.complete.title' })).toBeTruthy();
expect(screen.getByText('cindyMake.complete.description')).toBeTruthy();
- expect(screen.getByText('cindyMake.complete.stepCode')).toBeTruthy();
+ expect(
+ screen.getByRole('region', { name: 'cindyMake.complete.title' }).querySelectorAll('svg'),
+ ).toHaveLength(1);
const meta = screen.getByText(/cindyMake\.complete\.changedFiles/).textContent ?? '';
expect(meta).toContain('"count":3');
expect(meta).toContain('"commit":"abcdef123456"');
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeCompleteCard.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeCompleteCard.tsx
new file mode 100644
index 0000000000..414119e951
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeCompleteCard.tsx
@@ -0,0 +1,86 @@
+import type { ReactNode } from 'react';
+import { Check, CircleAlert } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { cn } from '@/lib/utils';
+import { Spinner } from '@/components/ui/spinner';
+
+/** The same verified completion facts, in history or in the input-area test handoff. */
+export function CindyMakeCompleteCard({
+ data,
+ composer = false,
+ heading,
+ description,
+ busy,
+ failed,
+ children,
+}: {
+ data?: Record<string, unknown>;
+ composer?: boolean;
+ heading?: string;
+ description?: string;
+ busy?: boolean;
+ failed?: boolean;
+ children?: ReactNode;
+}) {
+ const { t, i18n } = useTranslation();
+ const changedFiles = typeof data?.changedFiles === 'number' ? data.changedFiles : undefined;
+ const commit =
+ typeof data?.commit === 'string' && data.commit ? data.commit.slice(0, 12) : undefined;
+ const reportedAt =
+ typeof data?.reportedAt === 'number' && Number.isFinite(data.reportedAt)
+ ? data.reportedAt
+ : undefined;
+ const time =
+ reportedAt !== undefined
+ ? new Intl.DateTimeFormat(i18n?.resolvedLanguage ?? i18n?.language, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ }).format(reportedAt)
+ : undefined;
+ const branch = typeof data?.branch === 'string' && data.branch ? data.branch : undefined;
+ const meta = [
+ changedFiles !== undefined
+ ? t('cindyMake.complete.changedFiles', { count: changedFiles })
+ : null,
+ branch ? t('cindyMake.complete.branch', { branch }) : null,
+ commit ? t('cindyMake.complete.commit', { commit }) : null,
+ time ?? null,
+ ].filter((part): part is string => typeof part === 'string' && part.length > 0);
+ const border = composer ? 'border-[var(--chat-input-border)]' : 'border-[var(--border-default)]';
+ return (
+ <section
+ className={cn(
+ 'w-full rounded-xl border text-14 text-[var(--text-primary)]',
+ border,
+ composer ? 'bg-[var(--chat-input-bg)]' : 'bg-[var(--surface-elevated)]',
+ )}
+ aria-label={t(composer ? 'cindyMake.test.title' : 'cindyMake.complete.title')}
+ >
+ <div className="flex items-start gap-3 px-4 py-4">
+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-[var(--surface-chip)]">
+ {busy ? (
+ <Spinner size={18} />
+ ) : failed ? (
+ <CircleAlert size={18} className="text-[var(--status-danger)]" aria-hidden />
+ ) : (
+ <Check size={18} className="text-[var(--status-success)]" aria-hidden />
+ )}
+ </div>
+ <div className="min-w-0 flex-1">
+ <div role={composer ? 'status' : undefined}>
+ <p className="text-16 font-medium">{heading ?? t('cindyMake.complete.title')}</p>
+ <p className="mt-0.5 text-13 text-[var(--text-secondary)]">
+ {description ?? t('cindyMake.complete.description')}
+ </p>
+ </div>
+ {meta.length > 0 && (
+ <p className="mt-2 break-words text-12 text-[var(--text-secondary)]">
+ {meta.join(' · ')}
+ </p>
+ )}
+ </div>
+ </div>
+ {children && <div className={cn('space-y-3 border-t px-4 py-3', border)}>{children}</div>}
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeComposerMask.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeComposerMask.tsx
index 3a54ee4deb..9570ae795f 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeComposerMask.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeComposerMask.tsx
@@ -1,32 +1,46 @@
import { LockKeyhole } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import type { CindyMakeComposerPhase } from '@/lib/cindyMakeComposer';
+import type { MakeDoctorReport } from '../../../shared/cindyMakeDoctor';
+import { CindyMakeTaskCard } from './CindyMakeTaskCard';
-/** Same footprint as TakeoverMask; interaction prompts are rendered ahead of this mask. */
+/** Preparation lives in the composer; interaction prompts keep their existing priority. */
export function CindyMakeComposerMask({
phase,
- onStop,
+ report,
+ request,
+ readOnly = false,
}: {
phase: CindyMakeComposerPhase;
- onStop?: () => void;
+ report?: MakeDoctorReport;
+ request?: string;
+ readOnly?: boolean;
}) {
const { t } = useTranslation();
+ if (report?.task) {
+ return (
+ <CindyMakeTaskCard
+ key={report.runId}
+ report={report}
+ request={request}
+ readOnly={readOnly}
+ variant="composer"
+ />
+ );
+ }
const stopped = phase === 'failed' || phase === 'cancelled';
const heading =
- phase === 'executing'
- ? 'cindyMake.code.inputLocked.executing'
- : phase === 'failed'
- ? 'cindyMake.code.preparationFailed'
- : phase === 'cancelled'
- ? 'cindyMake.prepare.cancelled'
- : 'cindyMake.code.phases.' + phase;
+ phase === 'failed'
+ ? 'cindyMake.code.preparationFailed'
+ : phase === 'cancelled'
+ ? 'cindyMake.prepare.cancelled'
+ : 'cindyMake.code.phases.' + phase;
return (
<div
role="status"
aria-live="polite"
- className="flex min-h-[90px] w-full items-center justify-between gap-3 rounded-xl border border-[hsl(var(--sidebar-border))] bg-[hsl(var(--content-area))] px-4 py-3"
+ className="flex min-h-[90px] w-full items-center justify-between gap-3 rounded-xl border border-[var(--chat-input-border)] bg-[var(--chat-input-bg)] px-4 py-3"
>
<div className="flex min-w-0 items-center gap-3">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[hsl(var(--sidebar-item-hover))] text-[var(--workingdir-icon)]">
@@ -41,11 +55,6 @@ export function CindyMakeComposerMask({
</p>
</div>
</div>
- {phase === 'executing' && onStop && (
- <Button variant="primary" onClick={onStop}>
- {t('cindyMake.prepare.stop')}
- </Button>
- )}
</div>
);
}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx
new file mode 100644
index 0000000000..0a1f5cf5d0
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx
@@ -0,0 +1,556 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+import { Input } from '@/components/ui/input';
+import { Select } from '@/components/ui/select';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { useCindyMakeState } from '@/lib/cindyMakeState';
+import { formatCindyMakeTitle } from '@/lib/cindyMakeTitle';
+import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
+import type { CindyMakeHistoryState, MakeHistoryAction } from '../../../shared/cindyMakeHistory';
+import './cindyMakeTasks.css';
+
+type Filter = 'all' | 'pending' | 'integrated' | 'ended';
+/** Historical facts and allowed actions come from Main; an old button cannot authorize a write. */
+export function CindyMakeHistoryPanel({
+ active = true,
+ onState,
+}: {
+ active?: boolean;
+ onState?: (state: CindyMakeHistoryState) => void;
+}) {
+ const { t, i18n } = useTranslation();
+ const navigate = useNavigate();
+ const { confirm } = useConfirmDialog();
+ const make = useCindyMakeState();
+ const [snapshot, setSnapshot] = useState<{
+ owner: ReturnType<typeof getDataOwnerGeneration>;
+ value: CindyMakeHistoryState;
+ }>();
+ const state =
+ snapshot && isDataOwnerGenerationCurrent(snapshot.owner) ? snapshot.value : undefined;
+ const [selectedId, select] = useState('');
+ const [query, search] = useState('');
+ const [filter, setFilter] = useState<Filter>('all');
+ const [pending, setPending] = useState<string>();
+ const [failed, setFailed] = useState(false);
+ const request = useRef(0);
+ const acting = useRef(false);
+ const actionGeneration = useRef(0);
+ const owner = getDataOwnerGeneration();
+ const refresh = useCallback(async () => {
+ if (!window.electronAPI.getCindyMakeHistory) {
+ setFailed(true);
+ return;
+ }
+ const generation = ++request.current;
+ try {
+ const next = await window.electronAPI.getCindyMakeHistory(selectedId || undefined);
+ if (isDataOwnerGenerationCurrent(owner) && generation === request.current) {
+ setSnapshot({ owner, value: next });
+ setFailed(false);
+ }
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner) && generation === request.current) setFailed(true);
+ }
+ }, [owner, selectedId]);
+ useEffect(() => {
+ setSnapshot(undefined);
+ setPending(undefined);
+ acting.current = false;
+ actionGeneration.current += 1;
+ return () => {
+ request.current += 1;
+ actionGeneration.current += 1;
+ };
+ }, [owner]);
+ useEffect(() => {
+ if (!active) return;
+ const timer = window.setInterval(() => {
+ if (document.visibilityState !== 'hidden' && !acting.current) void refresh();
+ }, 5000);
+ const focus = () => {
+ if (!acting.current) void refresh();
+ };
+ window.addEventListener('focus', focus);
+ return () => {
+ window.clearInterval(timer);
+ window.removeEventListener('focus', focus);
+ request.current += 1;
+ };
+ }, [active, refresh]);
+ useEffect(() => {
+ if (active && !acting.current) void refresh();
+ }, [make, active, refresh]);
+ useEffect(() => {
+ if (state) onState?.(state);
+ }, [state, onState]);
+ const items = state?.items ?? [];
+ const visible = items.filter(
+ (item) =>
+ (!query.trim() ||
+ (item.title + ' ' + item.request)
+ .toLocaleLowerCase()
+ .includes(query.trim().toLocaleLowerCase())) &&
+ (filter === 'all' || filter === 'ended'
+ ? filter === 'all' || item.lifecycle === 'ended'
+ : filter === 'integrated'
+ ? item.integration === 'integrated'
+ : ['unintegrated', 'changed', 'reverted'].includes(item.integration) &&
+ item.lifecycle !== 'ended'),
+ );
+ const selected = visible.find((item) => item.runId === selectedId) ?? visible[0];
+ useEffect(() => {
+ if (selected && selected.runId !== selectedId) select(selected.runId);
+ }, [selected?.runId, selectedId]);
+ const date = (value: number) =>
+ new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', timeStyle: 'short' }).format(
+ value,
+ );
+ const update = (next: CindyMakeHistoryState) => {
+ request.current += 1;
+ if (isDataOwnerGenerationCurrent(owner)) {
+ setSnapshot({ owner, value: next });
+ setFailed(false);
+ }
+ };
+ const act = async (action: MakeHistoryAction) => {
+ if (
+ !selected ||
+ acting.current ||
+ !selected.actions.includes(action) ||
+ !isDataOwnerGenerationCurrent(owner)
+ )
+ return;
+ acting.current = true;
+ const actionId = ++actionGeneration.current;
+ setPending(action);
+ try {
+ if (action === 'open') {
+ navigate('/cc-agent/' + selected.sessionId);
+ return;
+ }
+ if (action === 'end' || action === 'retry-cleanup' || action === 'revert') {
+ const accepted = await confirm({
+ title: t('cindyMake.history.actions.' + action),
+ description:
+ t('cindyMake.history.' + (action === 'revert' ? 'revertConfirm' : 'endConfirm')) +
+ (action !== 'revert' && selected.integration === 'unknown'
+ ? '\n\n' + t('settings.cindyMake.tasks.endUnknown')
+ : ''),
+ confirmText: t('cindyMake.history.actions.' + action),
+ cancelText: t('settings.cindyMake.create.cancel'),
+ confirmVariant: 'destructive',
+ });
+ if (!accepted || !isDataOwnerGenerationCurrent(owner)) return;
+ }
+ if (action === 'build') {
+ update(await window.electronAPI.generateCindyMakePersonal());
+ } else if (action === 'retry-prepare') {
+ await window.electronAPI.startCindyMakeTask({
+ runId: selected.runId,
+ request: selected.request,
+ title: selected.title.slice(0, 200),
+ });
+ await refresh();
+ } else {
+ const next = await window.electronAPI.actCindyMakeHistory(selected.runId, action);
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ update(next);
+ if (action === 'continue') navigate('/cc-agent/' + selected.sessionId);
+ if (action === 'resolve') {
+ const session = next.items.find(
+ (item) => item.runId === selected.runId,
+ )?.resolutionSessionId;
+ if (session) navigate('/cc-agent/' + session);
+ }
+ }
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) {
+ toast.error(t('cindyMake.history.actionFailed'));
+ await refresh();
+ }
+ } finally {
+ if (actionId === actionGeneration.current) {
+ acting.current = false;
+ if (isDataOwnerGenerationCurrent(owner)) setPending(undefined);
+ }
+ }
+ };
+ const build = async () => {
+ if (!state?.canBuild || acting.current) return;
+ acting.current = true;
+ const actionId = ++actionGeneration.current;
+ setPending('build');
+ try {
+ update(await window.electronAPI.generateCindyMakePersonal());
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) toast.error(t('cindyMake.history.actionFailed'));
+ } finally {
+ if (actionId === actionGeneration.current) {
+ acting.current = false;
+ if (isDataOwnerGenerationCurrent(owner)) setPending(undefined);
+ }
+ }
+ };
+ const building = !!state?.build && !['ready', 'failed'].includes(state.build.status);
+ const stopping = building && state?.build?.stopping === true;
+ const buildStep = (value: NonNullable<CindyMakeHistoryState['build']>) => {
+ if (value.status === 'waiting') return 1;
+ if (value.status === 'merging') return 2;
+ if (value.status === 'checking') return 3;
+ if (value.status === 'packaging') return 4;
+ if (value.status === 'publishing') return 5;
+ return 1;
+ };
+ const stopBuild = async () => {
+ const buildId = state?.build?.buildId;
+ if (!building || !buildId || stopping || !isDataOwnerGenerationCurrent(owner)) return;
+ try {
+ update(await window.electronAPI.cancelCindyMakePersonal(buildId));
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) {
+ toast.error(t('cindyMake.history.actionFailed'));
+ await refresh();
+ }
+ }
+ };
+ const openInstaller = async () => {
+ if (acting.current || !isDataOwnerGenerationCurrent(owner)) return;
+ acting.current = true;
+ const actionId = ++actionGeneration.current;
+ setPending('open-build');
+ try {
+ await window.electronAPI.openCindyMakeHistoryBuild();
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) {
+ toast.error(t('cindyMake.history.actionFailed'));
+ await refresh();
+ }
+ } finally {
+ if (actionId === actionGeneration.current) {
+ acting.current = false;
+ if (isDataOwnerGenerationCurrent(owner)) setPending(undefined);
+ }
+ }
+ };
+ return (
+ <section
+ aria-label={t('cindyMake.history.title')}
+ className="cindy-make-tasks rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] text-13 text-[var(--text-primary)]"
+ >
+ <div className="space-y-3 border-b border-[var(--border-default)] p-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <h3 className="font-medium">
+ {t('cindyMake.history.title')} · {items.length}
+ </h3>
+ {!building && (
+ <Button
+ variant="secondary"
+ className="gap-2"
+ disabled={!state?.canBuild || !!pending || failed}
+ onClick={() => void build()}
+ >
+ {pending === 'build' && <Spinner size={14} />}
+ {t(pending === 'build' ? 'cindyMake.history.building' : 'cindyMake.history.build')}
+ </Button>
+ )}
+ </div>
+ {!building && (
+ <>
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.history.buildDescription')}
+ </p>
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.history.counts', {
+ total: items.length,
+ pending: items.filter(
+ (item) =>
+ ['unintegrated', 'changed', 'reverted'].includes(item.integration) &&
+ item.lifecycle !== 'ended',
+ ).length,
+ integrated: items.filter((item) => item.integration === 'integrated').length,
+ })}
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <Select
+ label={t('cindyMake.history.filterLabel')}
+ value={filter}
+ options={(['all', 'pending', 'integrated', 'ended'] as const).map((value) => ({
+ value,
+ label: t('cindyMake.history.filters.' + value),
+ }))}
+ onValueChange={(value) => setFilter(value as Filter)}
+ className="h-8 w-[168px]"
+ />
+ <Input
+ size="sm"
+ value={query}
+ onChange={search}
+ aria-label={t('settings.cindyMake.tasks.search')}
+ placeholder={t('settings.cindyMake.tasks.search')}
+ className="cindy-make-tasks-search"
+ />
+ </div>
+ </>
+ )}
+ {building && state?.build && (
+ <div
+ role="status"
+ aria-live="polite"
+ className="space-y-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-card)] p-4"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex min-w-0 items-start gap-2">
+ <Spinner size={16} className="mt-0.5 shrink-0" />
+ <div className="min-w-0">
+ <p className="font-medium">
+ {t(
+ stopping
+ ? 'cindyMake.history.stopping'
+ : 'cindyMake.history.buildStatus.' + state.build.status,
+ )}
+ </p>
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t(
+ state.build.status === 'checking' && state.build.checkStep
+ ? 'cindyMake.personal.checkStep.' + state.build.checkStep
+ : 'cindyMake.history.buildStatus.' + state.build.status,
+ )}
+ </p>
+ </div>
+ </div>
+ <Button
+ variant="secondary"
+ disabled={stopping || !state.build.buildId}
+ onClick={() => void stopBuild()}
+ >
+ {stopping && <Spinner size={14} />}
+ {t(stopping ? 'cindyMake.history.stopping' : 'cindyMake.history.stop')}
+ </Button>
+ </div>
+ <ol className="grid gap-1 text-12 text-[var(--text-secondary)] sm:grid-cols-2">
+ {(['waiting', 'merging', 'checking', 'packaging', 'publishing'] as const).map(
+ (step, index) => {
+ const current = buildStep(state.build!);
+ const active = current === index + 1;
+ const done = current > index + 1;
+ return (
+ <li
+ key={step}
+ className={cn(
+ 'flex items-center gap-2',
+ active && 'font-medium text-[var(--text-primary)]',
+ done && 'text-[var(--status-success)]',
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className="inline-block h-1.5 w-1.5 rounded-full bg-current"
+ />
+ {t('cindyMake.history.progress.' + step)}
+ </li>
+ );
+ },
+ )}
+ </ol>
+ </div>
+ )}
+ {state?.build && !building && (
+ <p role="status" className="text-12 text-[var(--text-secondary)]">
+ {t(
+ state.build.status === 'checking' && state.build.checkStep
+ ? 'cindyMake.personal.checkStep.' + state.build.checkStep
+ : 'cindyMake.history.buildStatus.' +
+ (state.build.status === 'ready' && !state.build.versionId
+ ? 'installerReady'
+ : state.build.status),
+ )}
+ </p>
+ )}
+ {state?.build?.status === 'failed' && state.build.error && (
+ <p role="alert" className="text-12 text-[var(--status-danger)]">
+ {t('cindyMake.personal.errors.' + state.build.error)}
+ </p>
+ )}
+ {state?.build?.status === 'ready' &&
+ !state.build.versionId &&
+ state.build.buildId &&
+ state.build.artifactName && (
+ <Button
+ variant="secondary"
+ disabled={!!pending || state.busy || failed}
+ loading={pending === 'open-build'}
+ onClick={() => void openInstaller()}
+ >
+ {t('cindyMake.history.openInstaller')}
+ </Button>
+ )}
+ {failed && (
+ <div role="alert" className="flex items-center gap-2 text-[var(--error-fg)]">
+ {t('cindyMake.history.loadFailed')}
+ <Button size="md" variant="secondary" onClick={() => void refresh()}>
+ {t('cindyMake.prepare.retry')}
+ </Button>
+ </div>
+ )}
+ </div>
+ {!state && !failed && (
+ <p role="status" className="p-4 text-[var(--text-secondary)]">
+ {t('cindyMake.history.loading')}
+ </p>
+ )}
+ <div className="cindy-make-tasks-layout grid min-w-0">
+ <ul
+ aria-label={t('cindyMake.history.title')}
+ className="cindy-make-tasks-list max-h-80 space-y-1 overflow-y-auto overscroll-contain border-b border-[var(--border-default)] p-2"
+ >
+ {visible.map((item) => (
+ <li key={item.runId}>
+ <button
+ type="button"
+ aria-pressed={selected?.runId === item.runId}
+ onClick={() => select(item.runId)}
+ className={cn(
+ 'flex w-full min-w-0 flex-col gap-1 rounded-lg border px-3 py-3 text-left',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]',
+ selected?.runId === item.runId
+ ? 'border-[var(--settings-menu-border-selected)] bg-[var(--settings-menu-bg-selected)] text-[var(--settings-menu-text-selected)]'
+ : 'border-transparent hover:bg-[var(--settings-menu-bg-hover)]',
+ )}
+ >
+ <span className="line-clamp-2 break-words font-medium">
+ {formatCindyMakeTitle(item.title, item.runId)}
+ </span>
+ <span className="text-12 text-[var(--text-secondary)]">
+ {t(
+ item.operation === 'build'
+ ? 'cindyMake.history.building'
+ : 'cindyMake.history.lifecycle.' + item.lifecycle,
+ )}{' '}
+ · {t('cindyMake.history.integration.' + item.integration)}
+ </span>
+ <span className="text-12 text-[var(--text-tertiary)]">{date(item.createdAt)}</span>
+ </button>
+ </li>
+ ))}
+ {state && !visible.length && (
+ <li className="p-3 text-[var(--text-secondary)]">
+ {t('settings.cindyMake.tasks.noResults')}
+ </li>
+ )}
+ </ul>
+ {selected && (
+ <div className="flex max-h-[480px] min-w-0 flex-col">
+ <div className="min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain p-4">
+ <h4 className="break-words font-medium">
+ {formatCindyMakeTitle(selected.title, selected.runId)}
+ </h4>
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.history.lifecycle.' + selected.lifecycle)} ·{' '}
+ {t('cindyMake.history.integration.' + selected.integration)}
+ </p>
+ <p className="whitespace-pre-wrap break-words">{selected.request}</p>
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.history.updated', { time: date(selected.updatedAt) })}
+ </p>
+ {selected.needsBuild && (
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.history.needsBuild')}
+ </p>
+ )}
+ {selected.build && selected.build.status !== 'ready' && (
+ <p role="status" className="text-12 text-[var(--text-secondary)]">
+ {t(
+ selected.build.status === 'checking' && selected.build.checkStep
+ ? 'cindyMake.personal.checkStep.' + selected.build.checkStep
+ : 'cindyMake.history.buildStatus.' + selected.build.status,
+ )}
+ </p>
+ )}
+ {selected.build?.status === 'failed' && selected.build.error && (
+ <p role="alert" className="text-12 text-[var(--status-danger)]">
+ {t('cindyMake.personal.errors.' + selected.build.error)}
+ </p>
+ )}
+ {!!selected.versions.length && (
+ <p className="text-12 text-[var(--text-secondary)]">
+ {selected.versions.at(-1)!.at === undefined
+ ? t('cindyMake.history.builtKnown')
+ : t('cindyMake.history.built', { time: date(selected.versions.at(-1)!.at!) })}
+ </p>
+ )}
+ {(selected.conflict || selected.operationError) && (
+ <p role="status" className="text-12 text-[var(--status-warning)]">
+ {t(
+ selected.conflict
+ ? 'cindyMake.history.conflict'
+ : 'cindyMake.history.actionFailed',
+ )}
+ </p>
+ )}
+ {!selected.actions.length && selected.actionReason && (
+ <p role="status" className="text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.history.noActions.' + selected.actionReason)}
+ </p>
+ )}
+ {!!selected.completions.length && (
+ <details>
+ <summary className="min-h-8 cursor-pointer py-2 text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.history.rounds', { count: selected.completions.length })}
+ </summary>
+ <ol className="mt-2 space-y-2">
+ {selected.completions.map((completion, index) => (
+ <li key={completion.id} className="text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.history.round', {
+ number: index + 1,
+ time: date(completion.reportedAt),
+ })}
+ {completion.changedFiles !== undefined &&
+ ' · ' + t('cindyMake.history.files', { count: completion.changedFiles })}
+ </li>
+ ))}
+ </ol>
+ </details>
+ )}
+ </div>
+ <div className="flex shrink-0 flex-wrap gap-2 border-t border-[var(--border-default)] p-4">
+ {selected.operation && (
+ <span role="status" className="self-center text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.history.working')}
+ </span>
+ )}
+ {selected.actions.map((action) => (
+ <Button
+ key={action}
+ variant="secondary"
+ disabled={!!pending || failed}
+ loading={pending === action}
+ onClick={() => void act(action)}
+ >
+ {t(
+ action === 'build' && selected.build?.status === 'failed'
+ ? 'cindyMake.history.actions.retryBuild'
+ : action === 'end' &&
+ selected.integration === 'integrated' &&
+ !selected.needsBuild &&
+ selected.versions.length
+ ? 'cindyMake.history.endAndClean'
+ : 'cindyMake.history.actions.' + action,
+ )}
+ </Button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeMergeNotice.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeMergeNotice.tsx
new file mode 100644
index 0000000000..742df036e2
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeMergeNotice.tsx
@@ -0,0 +1,86 @@
+import { useRef, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { Tip } from '@/components/ui/tooltip';
+import { Spinner } from '@/components/ui/spinner';
+import { toast } from '@/lib/toast';
+import { isSelectableVendor } from '@/lib/agentVendors';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
+
+function ResolveMergeButton({ state }: { state: CindyMakeMergeState }) {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const submitting = useRef(false);
+ const [busy, setBusy] = useState(false);
+ const resolve = async () => {
+ if (submitting.current) return;
+ const owner = getDataOwnerGeneration();
+ submitting.current = true;
+ setBusy(true);
+ try {
+ const draftState = await import('@/state/newMakerDraft');
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ const draft = draftState.getDraft();
+ const vendor = isSelectableVendor(draft.vendor) ? draft.vendor : 'cc';
+ const prefs = draft.lastByVendor[vendor];
+ const result = await window.electronAPI.cindyMakeMerge({
+ action: 'resolve',
+ createOptions: {
+ agentKind: vendor,
+ model: prefs.model,
+ effort: prefs.effort,
+ providerId: prefs.providerId,
+ permissionMode: prefs.permissionMode,
+ fastMode: draftState.getFastModeForModel(prefs.model),
+ planModeEnabled: false,
+ },
+ });
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ if (result?.sessionId) navigate(`/cc-agent/${result.sessionId}`);
+ else toast.error(t('cindyMake.merge.errors.startFailed'));
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) toast.error(t('cindyMake.merge.errors.startFailed'));
+ } finally {
+ submitting.current = false;
+ setBusy(false);
+ }
+ };
+ return (
+ <Tip text={t('cindyMake.merge.resolveHint')}>
+ <Button variant="secondary" disabled={busy} onClick={() => void resolve()}>
+ {busy && <Spinner size={14} />}
+ {t(state.sessionId ? 'cindyMake.merge.openTask' : 'cindyMake.merge.resolve')}
+ </Button>
+ </Tip>
+ );
+}
+
+export function CindyMakeMergeNotice({ state }: { state: CindyMakeMergeState }) {
+ const { t } = useTranslation();
+ const active = ['fetching', 'merging', 'checking'].includes(state.status);
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--border-default)] px-4 py-3 text-12">
+ <div className="min-w-0 flex-1 space-y-1 text-[var(--text-secondary)]" role="status">
+ <p className="flex items-center gap-2">
+ {active && <Spinner size={14} />}
+ {t(`cindyMake.merge.status.${state.status}`)}
+ </p>
+ {state.error && (
+ <p className="text-[var(--status-danger)]">
+ {t(`cindyMake.merge.errors.${state.error}`)}
+ </p>
+ )}
+ {state.ownedByAnotherAccount && <p>{t('cindyMake.merge.otherAccount')}</p>}
+ </div>
+ {!active &&
+ state.hasWorkspace &&
+ state.status !== 'merged' &&
+ !state.ownedByAnotherAccount && <ResolveMergeButton state={state} />}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakePreflightDialog.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakePreflightDialog.tsx
index 10625786a0..add80f9555 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakePreflightDialog.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakePreflightDialog.tsx
@@ -94,6 +94,7 @@ export function CindyMakePreflightDialog({
runId: report.runId,
request,
title: t('cindyMake.code.taskTitle', {
+ worktree: report.runId.slice(0, 4),
request: chars.slice(0, 60).join('') + (chars.length > 60 ? '…' : ''),
}),
createOptions,
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeSourceDetails.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeSourceDetails.tsx
index 0d2ff62643..3467139f6d 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeSourceDetails.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeSourceDetails.tsx
@@ -1,9 +1,38 @@
import { useTranslation } from 'react-i18next';
-import type { MakeSourcePreparation } from '../../../shared/cindyMakeDoctor';
+import { ArrowRight } from 'lucide-react';
+import type { ReactNode } from 'react';
+import type {
+ MakeSourceLatestVersion,
+ MakeSourcePreparation,
+} from '../../../shared/cindyMakeDoctor';
-export function CindyMakeSourceDetails({ source }: { source: MakeSourcePreparation }) {
+export function CindyMakeSourceDetails({
+ source,
+ latestVersion,
+ updateAction,
+}: {
+ source: MakeSourcePreparation;
+ latestVersion?: MakeSourceLatestVersion;
+ updateAction?: ReactNode;
+}) {
const { t } = useTranslation();
const unknown = t('cindyMake.source.details.unknown');
+ let difference: string | undefined;
+ if (
+ latestVersion?.status === 'ready' &&
+ latestVersion.ahead !== undefined &&
+ latestVersion.behind !== undefined
+ ) {
+ const { ahead, behind } = latestVersion;
+ difference =
+ ahead === 0 && behind === 0
+ ? t('cindyMake.source.details.latest.same')
+ : ahead === 0
+ ? t('cindyMake.source.details.latest.behind', { count: behind })
+ : behind === 0
+ ? t('cindyMake.source.details.latest.ahead', { count: ahead })
+ : t('cindyMake.source.details.latest.difference', { ahead, behind });
+ }
return (
<div className="min-w-0 space-y-2 text-12 text-[var(--text-secondary)]">
<dl className="grid gap-3">
@@ -21,11 +50,51 @@ export function CindyMakeSourceDetails({ source }: { source: MakeSourcePreparati
</div>
</dd>
</div>
- <div className="min-w-0">
- <dt className="font-medium">{t('cindyMake.source.details.mainCommit')}</dt>
- <dd className="break-all font-mono" title={source.mainCommit}>
- {source.mainCommit?.slice(0, 12) ?? unknown}
+ <div className="flex min-w-0 items-center gap-2">
+ <dt className="shrink-0 font-medium">{t('cindyMake.source.details.mainCommit')}</dt>
+ <dd className="flex min-w-0 flex-1 items-center gap-2 overflow-x-auto whitespace-nowrap">
+ <span
+ className="shrink-0 font-mono text-[var(--text-secondary)]"
+ title={source.mainCommit}
+ >
+ {source.mainCommit?.slice(0, 12) ?? unknown}
+ </span>
+ {latestVersion && (
+ <>
+ <ArrowRight
+ size={14}
+ className="shrink-0 text-[var(--text-tertiary)]"
+ aria-hidden="true"
+ />
+ <span
+ className={
+ latestVersion.status === 'ready'
+ ? 'shrink-0 text-[var(--status-success)]'
+ : 'shrink-0 text-[var(--text-tertiary)]'
+ }
+ >
+ <span>{t(`cindyMake.source.details.latest.${latestVersion.channel}`)}</span>{' '}
+ {latestVersion.status === 'ready' ? (
+ <>
+ {latestVersion.ref !== 'main' && <span>{latestVersion.ref} </span>}
+ <span className="font-mono" title={latestVersion.commit}>
+ {latestVersion.commit.slice(0, 12)}
+ </span>
+ {difference && (
+ <>
+ {' '}
+ <span>{difference}</span>
+ </>
+ )}
+ </>
+ ) : (
+ t('cindyMake.source.details.latest.unavailable')
+ )}
+ </span>
+ </>
+ )}
</dd>
+ {updateAction && <dd className="ml-auto shrink-0">{updateAction}</dd>}
</div>
<div className="min-w-0">
<dt className="font-medium">{t('cindyMake.source.details.currentBranch')}</dt>
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeTaskCard.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeTaskCard.tsx
index 83475c7984..3c56091de2 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeTaskCard.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeTaskCard.tsx
@@ -5,6 +5,8 @@ import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { CindyMakeDependencyProgress } from './CindyMakeDependencyProgress';
import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
+import { formatCindyMakeTitle } from '@/lib/cindyMakeTitle';
import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
import type { MakeDoctorReport } from '../../../shared/cindyMakeDoctor';
@@ -15,16 +17,26 @@ export function CindyMakeTaskCard({
request,
onOpenTask,
readOnly = false,
+ variant = 'default',
}: {
report: MakeDoctorReport;
request?: string;
onOpenTask?: () => void;
readOnly?: boolean;
+ variant?: 'default' | 'composer';
}) {
const { t } = useTranslation();
const [pending, setPending] = useState(false);
const task = report.task;
if (!task) return null;
+ const displayTitle = formatCindyMakeTitle(
+ task.title ?? t('cindyMake.code.taskName'),
+ report.runId,
+ );
+ const inComposer = variant === 'composer';
+ const borderClass = inComposer
+ ? 'border-[var(--chat-input-border)]'
+ : 'border-[var(--border-default)]';
const canOperate = () =>
!readOnly &&
!getStickySessionDeviceId(task.sessionId) &&
@@ -47,7 +59,7 @@ export function CindyMakeTaskCard({
originSessionId: task.originSessionId,
runId: report.runId,
request,
- title: task.title ?? t('cindyMake.code.taskName'),
+ title: displayTitle,
});
}
} catch {
@@ -58,16 +70,26 @@ export function CindyMakeTaskCard({
};
return (
<section
- className="w-full rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] text-13 text-[var(--text-primary)]"
+ className={cn(
+ 'w-full rounded-xl border text-13 text-[var(--text-primary)]',
+ borderClass,
+ inComposer
+ ? 'flex max-h-[min(420px,50vh)] flex-col overflow-hidden bg-[var(--chat-input-bg)]'
+ : 'bg-[var(--surface-elevated)]',
+ )}
aria-label={t('cindyMake.code.taskName')}
>
- <div className="flex items-center gap-2 px-4 py-3">
- <span className="min-w-0 flex-1 break-words font-medium">
- {task.title ?? t('cindyMake.code.taskName')}
- </span>
+ <div className="flex shrink-0 items-center gap-2 px-4 py-3">
+ <span className="min-w-0 flex-1 break-words font-medium">{displayTitle}</span>
{running && <Spinner size={14} />}
</div>
- <div className="space-y-3 border-t border-[var(--border-default)] px-4 py-3">
+ <div
+ className={cn(
+ 'space-y-3 border-t px-4 py-3',
+ borderClass,
+ inComposer && 'min-h-0 overflow-y-auto overscroll-contain',
+ )}
+ >
<ol className="space-y-2">
{phases.map((phase, index) => (
<li key={phase} className="flex items-center gap-2">
@@ -143,21 +165,21 @@ export function CindyMakeTaskCard({
)}
</div>
{interactive && onOpenTask && (
- <div className="flex justify-end px-4 pb-3">
+ <div className="flex shrink-0 justify-end px-4 pb-3">
<Button variant="secondary" onClick={() => canOperate() && onOpenTask()}>
{t('cindyMake.code.open')}
</Button>
</div>
)}
{interactive && !completed && task.phase !== 'starting' && (running || request) && (
- <div className="flex justify-end border-t border-[var(--border-default)] px-4 py-3">
+ <div className={cn('flex shrink-0 justify-end border-t px-4 py-3', borderClass)}>
<Button variant="secondary" disabled={pending} onClick={() => void operate()}>
{t(running ? 'cindyMake.prepare.stop' : 'cindyMake.prepare.retry')}
</Button>
</div>
)}
{interactive && !running && task.phase === 'starting' && request && (
- <div className="flex justify-end border-t border-[var(--border-default)] px-4 py-3">
+ <div className={cn('flex shrink-0 justify-end border-t px-4 py-3', borderClass)}>
<Button variant="secondary" disabled={pending} onClick={() => void operate()}>
{t('cindyMake.prepare.retry')}
</Button>
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeTasksPanel.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeTasksPanel.tsx
index b683fac503..3757466e61 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeTasksPanel.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeTasksPanel.tsx
@@ -5,6 +5,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { cindyMakeState } from '@/lib/cindyMakeState';
+import { formatCindyMakeTitle } from '@/lib/cindyMakeTitle';
import { toast } from '@/lib/toast';
import { extractIpcError } from '@/utils/ipcError';
import {
@@ -21,12 +22,13 @@ import './cindyMakeTasks.css';
function statusOf(report: MakeDoctorReport, action?: CindyMakeTaskActionState): string {
if (action?.status === 'running') return 'cleaning';
- if (report.task?.sessionStatus === 'deleted') return 'cleanup';
- if (report.task?.sessionStatus === 'archived') return 'archived';
+ if (action?.status === 'failed') return 'cleanupFailed';
+ if (report.task?.sessionStatus === 'deleted' || report.task?.cleanupPending) return 'cleanup';
+ if (report.task?.sessionStatus === 'archived') return report.task.integration ?? 'unknown';
if (report.status === 'running') return 'preparing';
if (report.status === 'failed') return 'failed';
if (report.status === 'cancelled') return 'cancelled';
- return report.task?.executing ? 'running' : 'ready';
+ return report.task?.executing ? 'running' : (report.task?.integration ?? 'unknown');
}
/** A bounded master/detail view: only the selected task mounts its preparation details. */
@@ -45,15 +47,17 @@ export function CindyMakeTasksPanel({
const [pending, setPending] = useState(false);
const [operation, setOperation] = useState<{
runId: string;
- action: 'open' | 'finish' | 'delete';
+ action: 'open' | 'end';
}>();
const busy = useRef(false);
const owner = getDataOwnerGeneration();
const current = () => isDataOwnerGenerationCurrent(owner);
const tasks = reports.filter((report) => report.task && !report.task.finished);
+ const titleOf = (report: MakeDoctorReport) =>
+ formatCindyMakeTitle(report.task?.title ?? t('cindyMake.code.taskName'), report.runId);
const search = query.trim().toLocaleLowerCase();
const visible = tasks.filter((report) =>
- [report.task?.title, report.task?.request].some((value) =>
+ [titleOf(report), report.task?.request].some((value) =>
value?.toLocaleLowerCase().includes(search),
),
);
@@ -111,26 +115,40 @@ export function CindyMakeTasksPanel({
}
};
- const manage = async (action: 'finish' | 'delete') => {
+ const manage = async () => {
if (!selected?.task || busy.current || cleaning || !current()) return;
busy.current = true;
setPending(true);
try {
- if (selected.task.sessionStatus !== 'deleted') {
- const accepted = await confirm({
- title: t('settings.cindyMake.tasks.' + action),
- description: t('settings.cindyMake.tasks.' + action + 'Confirm', {
- title: selected.task.title,
- }),
- confirmText: t('settings.cindyMake.tasks.' + action),
- cancelText: t('settings.cindyMake.create.cancel'),
- confirmVariant: action === 'delete' ? 'destructive' : 'default',
- });
- if (!accepted || !current()) return;
- }
- setOperation({ runId: selected.runId, action });
- await window.electronAPI.manageCindyMakeTask(selected.task.sessionId, action);
- if (current()) await cindyMakeState.refresh();
+ // Every deletion, including a retry, has the same explicit confirmation.
+ // The base copy warns about unintegrated work even if the last cell snapshot is stale.
+ const accepted = await confirm({
+ title: t('settings.cindyMake.tasks.end'),
+ description: [
+ t(
+ selected.task.sessionStatus === 'deleted'
+ ? 'settings.cindyMake.tasks.cleanupDeletedConfirm'
+ : 'settings.cindyMake.tasks.endConfirm',
+ { title: titleOf(selected) },
+ ),
+ selected.task.integration !== 'integrated'
+ ? t(
+ selected.task.integration === 'unintegrated'
+ ? 'settings.cindyMake.tasks.endUnintegrated'
+ : 'settings.cindyMake.tasks.endUnknown',
+ )
+ : '',
+ ]
+ .filter(Boolean)
+ .join('\n\n'),
+ confirmText: t('settings.cindyMake.tasks.end'),
+ cancelText: t('settings.cindyMake.create.cancel'),
+ confirmVariant: 'destructive',
+ });
+ if (!accepted || !current()) return;
+ setOperation({ runId: selected.runId, action: 'end' });
+ await cindyMakeState.manageTask(selected.task.sessionId, 'end');
+ if (current()) void cindyMakeState.refresh().catch(() => {});
} catch (error) {
if (!current()) return;
const message = extractIpcError(error)?.message;
@@ -184,9 +202,7 @@ export function CindyMakeTasksPanel({
onClick={() => setSelectedId(report.runId)}
className="flex w-full min-w-0 flex-col gap-1 rounded-lg px-3 py-3 text-left hover:bg-[var(--surface-hover)] aria-pressed:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]"
>
- <span className="line-clamp-2 break-words font-medium">
- {report.task?.title ?? t('cindyMake.code.taskName')}
- </span>
+ <span className="line-clamp-2 break-words font-medium">{titleOf(report)}</span>
<span className="text-12 text-[var(--text-secondary)]">
{t(
'settings.cindyMake.tasks.status.' +
@@ -208,9 +224,7 @@ export function CindyMakeTasksPanel({
{selected?.task && (
<div className="flex min-w-0 max-h-[420px] flex-col">
<div className="shrink-0 p-4 pb-0">
- <h4 className="break-words font-medium">
- {selected.task.title ?? t('cindyMake.code.taskName')}
- </h4>
+ <h4 className="break-words font-medium">{titleOf(selected)}</h4>
<p className="mt-1 text-12 text-[var(--text-secondary)]">
{t('settings.cindyMake.tasks.status.' + statusOf(selected, taskAction))}
</p>
@@ -226,7 +240,7 @@ export function CindyMakeTasksPanel({
)}
{selected.status === 'completed' && selected.task.sessionStatus !== 'deleted' && (
<p className="text-12 text-[var(--text-secondary)]">
- {t('settings.cindyMake.tasks.finishHint')}
+ {t('settings.cindyMake.tasks.endHint')}
</p>
)}
</div>
@@ -251,32 +265,20 @@ export function CindyMakeTasksPanel({
)}
</Button>
)}
- {selected.status === 'completed' && selected.task.sessionStatus !== 'deleted' && (
- <Button
- variant="secondary"
- disabled={disabled || selected.task.executing}
- loading={
- (cleaning && taskAction.action === 'finish') ||
- (operation?.runId === selected.runId && operation.action === 'finish')
- }
- onClick={() => void manage('finish')}
- >
- {t('settings.cindyMake.tasks.finish')}
- </Button>
- )}
<Button
variant="secondary"
disabled={disabled}
loading={
- (cleaning && taskAction.action === 'delete') ||
- (operation?.runId === selected.runId && operation.action === 'delete')
+ cleaning || (operation?.runId === selected.runId && operation.action === 'end')
}
- onClick={() => void manage('delete')}
+ onClick={() => void manage()}
>
{t(
- selected.task.sessionStatus === 'deleted'
+ selected.task.sessionStatus === 'deleted' ||
+ selected.task.cleanupPending ||
+ failureCode
? 'settings.cindyMake.tasks.retryCleanup'
- : 'settings.cindyMake.tasks.delete',
+ : 'settings.cindyMake.tasks.end',
)}
</Button>
</div>
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeTestCard.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeTestCard.tsx
new file mode 100644
index 0000000000..f8193ed288
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeTestCard.tsx
@@ -0,0 +1,181 @@
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { makerChatStore } from '@/lib/makerChatStore';
+import { useCindyVersions } from '@/lib/useCindyVersions';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
+import { extractIpcError } from '@/utils/ipcError';
+import type {
+ CindyMakeCompletionMeta,
+ CindyMakeTestAction,
+ CindyMakeTestState,
+} from '../../../shared/cindyMakeSession';
+import { CindyMakeCompleteCard } from './CindyMakeCompleteCard';
+
+export function CindyMakeTestCard({
+ sessionId,
+ completionId,
+ meta,
+}: {
+ sessionId: string;
+ completionId: string;
+ meta: CindyMakeCompletionMeta;
+}) {
+ const { t } = useTranslation();
+ const versions = useCindyVersions(!!meta.personal?.versionId, meta.personal?.versionId);
+ const [pending, setPending] = useState<Exclude<CindyMakeTestAction, 'status'>>();
+ const [error, setError] = useState<{
+ mode: 'test' | 'build';
+ code: CindyMakeTestState['error'];
+ }>();
+ const busy = useRef(false);
+ const active = useRef(true);
+ const version = useRef(0);
+ const latest = useRef(meta);
+ latest.current = meta;
+ const owner = getDataOwnerGeneration();
+ const current = () =>
+ active.current && isDataOwnerGenerationCurrent(owner) && !getStickySessionDeviceId(sessionId);
+ useEffect(() => {
+ active.current = true;
+ const initial = latest.current;
+ const requestVersion = ++version.current;
+ void window.electronAPI
+ .cindyMakeTest(sessionId, completionId, 'status')
+ .then((next) => {
+ if (current() && latest.current === initial && version.current === requestVersion)
+ makerChatStore.updateSystemCardData(sessionId, completionId, { ...next });
+ })
+ .catch(() => {});
+ return () => {
+ active.current = false;
+ };
+ }, [sessionId, completionId, owner.dataOwnerId, owner.generation]);
+ const act = async (action: Exclude<CindyMakeTestAction, 'status'>) => {
+ if (busy.current || !current()) return;
+ busy.current = true;
+ version.current += 1;
+ setPending(action);
+ setError(undefined);
+ const initial = latest.current;
+ try {
+ const next = await window.electronAPI.cindyMakeTest(sessionId, completionId, action);
+ if (current() && (action === 'continue' || latest.current === initial))
+ makerChatStore.updateSystemCardData(sessionId, completionId, { ...next });
+ } catch (error) {
+ if (current()) {
+ const code = extractIpcError(error)?.message;
+ setError({
+ mode: action === 'build' || action === 'open-build' ? 'build' : 'test',
+ code: code === 'changed' || code === 'environment' ? code : 'unavailable',
+ });
+ }
+ } finally {
+ busy.current = false;
+ if (active.current) setPending(undefined);
+ }
+ };
+ const buildMode =
+ pending === 'build' ||
+ pending === 'open-build' ||
+ (pending !== 'start' &&
+ (error?.mode ?? meta.lastAction ?? (meta.personal ? 'build' : 'test')) === 'build');
+ const testStatus = pending === 'start' ? 'starting' : (meta.test?.status ?? 'waiting');
+ const buildStatus = pending === 'build' ? 'waiting' : meta.personal?.status;
+ const building = ['waiting', 'checking', 'merging', 'packaging', 'publishing'].includes(
+ buildStatus ?? '',
+ );
+ const starting = testStatus === 'starting';
+ const switching = !!versions.pending || versions.state?.switching === true;
+ const usingPersonal =
+ !!meta.personal?.versionId && versions.state?.currentId === meta.personal.versionId;
+ const working = buildMode ? building : starting;
+ const errorCode =
+ starting || building
+ ? undefined
+ : (error?.code ??
+ (buildMode ? meta.personal?.error : meta.test?.error) ??
+ (!meta.commit ? 'unavailable' : undefined));
+ return (
+ <CindyMakeCompleteCard
+ composer
+ data={{ ...meta }}
+ busy={working}
+ failed={Boolean(errorCode)}
+ heading={t(
+ buildMode && buildStatus
+ ? buildStatus === 'checking' && meta.personal?.checkStep
+ ? 'cindyMake.personal.checkStep.' + meta.personal.checkStep
+ : 'cindyMake.personal.status.' + buildStatus
+ : 'cindyMake.test.status.' + testStatus,
+ )}
+ description={t(
+ buildMode && buildStatus === 'ready'
+ ? meta.personal?.versionId
+ ? 'cindyMake.versions.readyHint'
+ : 'cindyMake.personal.readyHint'
+ : buildMode && building
+ ? 'cindyMake.personal.description'
+ : testStatus === 'ready'
+ ? 'cindyMake.test.readyHint'
+ : 'cindyMake.test.description',
+ { name: meta.personal?.artifactName ?? '' },
+ )}
+ >
+ {versions.error && (
+ <p role="alert" className="text-12 text-[var(--status-danger)]">
+ {t('cindyMake.versions.errors.' + versions.error)}
+ </p>
+ )}
+ {errorCode && (
+ <p role="alert" className="text-12 text-[var(--status-danger)]">
+ {t((buildMode ? 'cindyMake.personal.errors.' : 'cindyMake.test.errors.') + errorCode)}
+ </p>
+ )}
+ <div className="flex flex-wrap justify-end gap-2">
+ <Button
+ variant="secondary"
+ disabled={!!pending || building || switching}
+ loading={pending === 'continue'}
+ onClick={() => void act('continue')}
+ >
+ {t('cindyMake.test.continue')}
+ </Button>
+ <Button
+ variant="secondary"
+ disabled={
+ !!pending || building || starting || switching || testStatus === 'ready' || !meta.commit
+ }
+ loading={starting}
+ onClick={() => void act('start')}
+ >
+ {t(testStatus === 'ready' ? 'cindyMake.test.started' : 'cindyMake.test.start')}
+ </Button>
+ <Button
+ variant="secondary"
+ disabled={!!pending || building || starting || switching || usingPersonal || !meta.commit}
+ loading={building || switching || pending === 'open-build'}
+ onClick={() => {
+ if (meta.personal?.status === 'ready' && meta.personal.versionId)
+ void versions.act('switch', meta.personal.versionId);
+ else void act(meta.personal?.status === 'ready' ? 'open-build' : 'build');
+ }}
+ >
+ {t(
+ meta.personal?.status === 'ready'
+ ? usingPersonal
+ ? 'cindyMake.versions.using'
+ : meta.personal.versionId
+ ? 'cindyMake.versions.switchPersonal'
+ : 'cindyMake.personal.open'
+ : 'cindyMake.personal.generate',
+ )}
+ </Button>
+ </div>
+ </CindyMakeCompleteCard>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeVersionsPanel.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeVersionsPanel.tsx
new file mode 100644
index 0000000000..e48dd9f5f6
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeVersionsPanel.tsx
@@ -0,0 +1,117 @@
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { useCindyVersions } from '@/lib/useCindyVersions';
+
+export function CindyMakeVersionsPanel({
+ active = true,
+ busy = false,
+ refreshKey,
+}: {
+ active?: boolean;
+ busy?: boolean;
+ refreshKey?: string;
+}) {
+ const { t, i18n } = useTranslation();
+ const versions = useCindyVersions(active, refreshKey);
+ const { confirm } = useConfirmDialog();
+ const disabled = busy || !!versions.pending || versions.state?.switching;
+ if (typeof window.electronAPI.getCindyVersions !== 'function') return null;
+ return (
+ <section className="rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] p-5">
+ <h3 className="text-14 font-medium text-[var(--text-primary)]">
+ {t('cindyMake.versions.title')}
+ </h3>
+ <p className="mt-1 text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.versions.description')}
+ </p>
+ {versions.error && (
+ <p role="alert" className="mt-2 text-12 text-[var(--status-danger)]">
+ {t('cindyMake.versions.errors.' + versions.error)}
+ </p>
+ )}
+ <div className="mt-3 divide-y divide-[var(--border-default)]">
+ {versions.state?.versions.map((version) => {
+ const current = versions.state?.currentId === version.id;
+ const title =
+ version.kind === 'original'
+ ? t('cindyMake.versions.original')
+ : version.title || t('cindyMake.versions.personal');
+ const date =
+ version.builtAt && Number.isFinite(Date.parse(version.builtAt))
+ ? new Date(version.builtAt).toLocaleString(i18n.language)
+ : '';
+ return (
+ <div
+ key={version.id}
+ className="flex flex-wrap items-center justify-between gap-3 py-3"
+ >
+ <div className="min-w-0 flex-1">
+ <p className="break-words text-13 font-medium text-[var(--text-primary)]">
+ {title}
+ {current && (
+ <span className="ml-2 text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.versions.current')}
+ </span>
+ )}
+ </p>
+ <p className="mt-1 text-12 text-[var(--text-secondary)]">
+ {[
+ version.development ? t('cindyMake.versions.development') : null,
+ version.version,
+ date,
+ version.commit?.slice(0, 12),
+ version.dirty ? t('cindyMake.versions.localChanges') : null,
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </p>
+ {(!version.available || !version.compatible) && (
+ <p className="mt-1 text-12 text-[var(--text-secondary)]">
+ {t(
+ !version.available
+ ? 'cindyMake.versions.unavailable'
+ : 'cindyMake.versions.incompatible',
+ )}
+ </p>
+ )}
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ variant="secondary"
+ disabled={disabled || current || !version.available || !version.compatible}
+ loading={versions.pending === version.id}
+ onClick={() => void versions.act('switch', version.id)}
+ >
+ {t(current ? 'cindyMake.versions.using' : 'cindyMake.versions.switch')}
+ </Button>
+ {version.kind === 'personal' && (
+ <Button
+ variant="secondary"
+ disabled={disabled || current || versions.state?.selectedId === version.id}
+ onClick={async () => {
+ if (
+ await confirm({
+ title: t('cindyMake.versions.removeTitle'),
+ description: t('cindyMake.versions.removeDescription'),
+ confirmText: t('cindyMake.versions.remove'),
+ confirmVariant: 'destructive',
+ })
+ )
+ await versions.act('remove', version.id);
+ }}
+ >
+ {t('cindyMake.versions.remove')}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ {versions.state?.versions.length === 1 && (
+ <p className="text-12 text-[var(--text-secondary)]">{t('cindyMake.versions.empty')}</p>
+ )}
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeComposerMask.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeComposerMask.test.tsx
index 4f17543f6e..96cc7d72c2 100644
--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeComposerMask.test.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeComposerMask.test.tsx
@@ -1,30 +1,124 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { CindyMakeComposerMask } from '../CindyMakeComposerMask';
+import { getCindyMakeComposerPhase } from '@/lib/cindyMakeComposer';
+import type { MakeDoctorReport } from '../../../../shared/cindyMakeDoctor';
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
-afterEach(cleanup);
+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));
+vi.mock('@/features/device-link/stickySessionOrigin', () => ({
+ getStickySessionDeviceId: () => undefined,
+}));
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+const report: MakeDoctorReport = {
+ runId: 'make-run',
+ status: 'running',
+ platform: 'win32',
+ arch: 'x64',
+ checks: [],
+ task: { sessionId: 'make-session', title: 'Personal Cindy', phase: 'dependencies' },
+};
describe('Cindy Make input replacement', () => {
- it('replaces the editor with preparation status and an explanation', () => {
- const view = render(<CindyMakeComposerMask phase="dependencies" />);
- expect(screen.getByRole('status').textContent).toContain('cindyMake.code.phases.dependencies');
+ it('keeps input unavailable while the preparation snapshot is loading', () => {
+ const view = render(<CindyMakeComposerMask phase="waiting" />);
+ expect(screen.getByRole('status').textContent).toContain('cindyMake.code.phases.waiting');
expect(screen.getByText('cindyMake.code.inputLocked.hint')).toBeTruthy();
expect(screen.queryByRole('textbox')).toBeNull();
expect(view.container.querySelector('[contenteditable="true"]')).toBeNull();
expect(screen.queryByRole('button')).toBeNull();
});
- it('preserves the stop action during first execution', () => {
- const stop = vi.fn();
- render(<CindyMakeComposerMask phase="executing" onStop={stop} />);
+ it('shows the full preparation card in place of the editor and stops the preparation', async () => {
+ const cancel = vi.fn(async () => ({ success: true }));
+ vi.stubGlobal('electronAPI', { cancelCindyMakeTask: cancel });
+ const view = render(<CindyMakeComposerMask phase="dependencies" report={report} />);
+ expect(screen.getAllByRole('listitem')).toHaveLength(5);
+ expect(screen.getByText('[make] Personal Cindy')).toBeTruthy();
+ expect(screen.getByText('cindyMake.code.dependencyActivity.starting')).toBeTruthy();
+ expect(screen.queryByText('cindyMake.code.inputLocked.hint')).toBeNull();
+ expect(screen.queryByRole('textbox')).toBeNull();
+ expect(view.container.querySelector('[contenteditable="true"]')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'cindyMake.prepare.stop' }));
- expect(stop).toHaveBeenCalledOnce();
+ await waitFor(() => expect(cancel).toHaveBeenCalledWith(report.runId));
});
- it.each(['failed', 'cancelled'] as const)('explains where to retry %s preparation', (phase) => {
- render(<CindyMakeComposerMask phase={phase} />);
- expect(screen.getByText('cindyMake.code.inputLocked.retry')).toBeTruthy();
+ it('restores ordinary input while the first editing turn is still running', () => {
+ const content = (value: MakeDoctorReport) => {
+ const phase = getCindyMakeComposerPhase({
+ session: {
+ id: 'make-session',
+ source: 'cindy-make',
+ clearedAt: null,
+ lastTurnEndedAt: null,
+ interruptedTurnStartedAt: null,
+ },
+ report: value,
+ messages: [],
+ historyLoaded: true,
+ busy: true,
+ error: null,
+ });
+ return phase ? (
+ <CindyMakeComposerMask phase={phase} report={value} />
+ ) : (
+ <textarea aria-label="Chat input" />
+ );
+ };
+ const view = render(content(report));
expect(screen.queryByRole('textbox')).toBeNull();
+ view.rerender(
+ content({ ...report, status: 'completed', task: { ...report.task!, phase: 'completed' } }),
+ );
+ expect(screen.queryByRole('list')).toBeNull();
+ const input = screen.getByRole('textbox', { name: 'Chat input' });
+ fireEvent.change(input, { target: { value: 'another change' } });
+ expect((input as HTMLTextAreaElement).value).toBe('another change');
});
+
+ it.each(['failed', 'cancelled'] as const)(
+ 'retries %s preparation directly from the composer with the original request',
+ async (phase) => {
+ const start = vi.fn(async () => 'make-session');
+ vi.stubGlobal('electronAPI', { startCindyMakeTask: start });
+ render(
+ <CindyMakeComposerMask
+ phase={phase}
+ report={{ ...report, status: phase }}
+ request="original request"
+ />,
+ );
+ expect(screen.queryByRole('textbox')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.prepare.retry' }));
+ await waitFor(() =>
+ expect(start).toHaveBeenCalledWith({
+ originSessionId: undefined,
+ runId: report.runId,
+ request: 'original request',
+ title: '[make] Personal Cindy',
+ }),
+ );
+ },
+ );
+
+ it.each(['running', 'failed', 'cancelled'] as const)(
+ 'keeps remote or read-only %s preparation visible without local actions',
+ (status) => {
+ render(
+ <CindyMakeComposerMask
+ phase={status === 'running' ? 'dependencies' : status}
+ report={{ ...report, status }}
+ request="original request"
+ readOnly
+ />,
+ );
+ expect(screen.getAllByRole('listitem')).toHaveLength(5);
+ expect(screen.queryByRole('button')).toBeNull();
+ },
+ );
});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeHistoryPanel.i18n.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeHistoryPanel.i18n.test.tsx
new file mode 100644
index 0000000000..247e939677
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeHistoryPanel.i18n.test.tsx
@@ -0,0 +1,260 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createInstance } from 'i18next';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import en from '@/i18n/locales/en/common.json';
+import zhCN from '@/i18n/locales/zh-CN/common.json';
+import zhTW from '@/i18n/locales/zh-TW/common.json';
+import ja from '@/i18n/locales/ja/common.json';
+import ko from '@/i18n/locales/ko/common.json';
+import type { CindyMakeHistoryState } from '../../../../shared/cindyMakeHistory';
+import { CindyMakeHistoryPanel } from '../CindyMakeHistoryPanel';
+import { CindyMakeVersionsPanel } from '../CindyMakeVersionsPanel';
+import { CindyMakeMergeNotice } from '../CindyMakeMergeNotice';
+
+const h = vi.hoisted(() => ({ make: {} }));
+vi.mock('@/lib/cindyMakeState', () => ({ useCindyMakeState: () => h.make }));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: async () => false }),
+}));
+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));
+
+const cases = [
+ {
+ locale: 'en',
+ resource: en,
+ title: 'Make history',
+ build: 'Generate personal version',
+ integrate: 'Integrate into personal version',
+ counts: '1 total · 1 pending integration · 0 integrated',
+ script: /[a-z]/i,
+ },
+ {
+ locale: 'zh-CN',
+ resource: zhCN,
+ title: '制作历史',
+ build: '生成个人版',
+ integrate: '合入个人版',
+ counts: '共 1 次 · 待合入 1 次 · 已合入 0 次',
+ script: /\p{Script=Han}/u,
+ },
+ {
+ locale: 'zh-TW',
+ resource: zhTW,
+ title: '製作歷史',
+ build: '產生個人版',
+ integrate: '合入個人版',
+ counts: '共 1 次 · 待合入 1 次 · 已合入 0 次',
+ script: /\p{Script=Han}/u,
+ },
+ {
+ locale: 'ja',
+ resource: ja,
+ title: '制作履歴',
+ build: '個人版を生成',
+ integrate: '個人版に取り込む',
+ counts: '合計 1 件 · 未取り込み 1 件 · 取り込み済み 0 件',
+ script: /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u,
+ },
+ {
+ locale: 'ko',
+ resource: ko,
+ title: '제작 기록',
+ build: '개인 버전 생성',
+ integrate: '개인 버전에 반영',
+ counts: '전체 1회 · 반영 대기 1회 · 반영 완료 0회',
+ script: /\p{Script=Hangul}/u,
+ },
+];
+
+function strings(value: Record<string, unknown>, prefix = ''): Array<[string, string]> {
+ return Object.entries(value).flatMap(([key, child]) =>
+ typeof child === 'string'
+ ? [[prefix + key, child] as [string, string]]
+ : strings(child as Record<string, unknown>, prefix + key + '.'),
+ );
+}
+
+beforeEach(() => {
+ setDataOwnerGeneration('history-real-locales');
+ const state: CindyMakeHistoryState = {
+ busy: false,
+ canBuild: true,
+ items: [
+ {
+ schema: 1,
+ runId: 'aaaa',
+ sessionId: 'task-a',
+ title: 'Example make',
+ request: 'Example request',
+ createdAt: 1,
+ updatedAt: 2,
+ completions: [],
+ receipts: [],
+ versions: [],
+ lifecycle: 'ready',
+ integration: 'unintegrated',
+ actions: ['continue', 'test', 'integrate', 'end'],
+ },
+ ],
+ };
+ vi.stubGlobal('electronAPI', { getCindyMakeHistory: async () => state });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('Cindy Make history with real translations', () => {
+ it.each(cases)(
+ 'shows the live test stage and useful failure text in $locale',
+ async ({ locale, resource }) => {
+ const state = await window.electronAPI.getCindyMakeHistory();
+ state.busy = true;
+ state.canBuild = false;
+ state.build = { status: 'checking', checkStep: 'tests', buildId: 'build-1' };
+ const i18n = createInstance();
+ await i18n.use(initReactI18next).init({
+ lng: locale,
+ fallbackLng: false,
+ defaultNS: 'common',
+ resources: { [locale]: { common: resource } },
+ });
+ const view = render(
+ <MemoryRouter>
+ <I18nextProvider i18n={i18n}>
+ <CindyMakeHistoryPanel />
+ </I18nextProvider>
+ </MemoryRouter>,
+ );
+ expect(await screen.findByText(resource.cindyMake.personal.checkStep.tests)).toBeTruthy();
+ expect(screen.getByRole('button', { name: resource.cindyMake.history.stop })).toBeTruthy();
+ state.build = { status: 'failed', error: 'checksFailed' };
+ state.busy = false;
+ state.canBuild = true;
+ fireEvent(window, new Event('focus'));
+ expect(await screen.findByText(resource.cindyMake.personal.errors.checksFailed)).toBeTruthy();
+ expect(view.container.textContent).not.toMatch(/cindyMake\.|\{\{|\?{2,}|\uFFFD/);
+ },
+ );
+ it.each(cases)(
+ 'renders $locale copy instead of translation keys or encoding placeholders',
+ async ({ locale, resource, title, build, integrate, counts, script }) => {
+ const i18n = createInstance();
+ await i18n.use(initReactI18next).init({
+ lng: locale,
+ fallbackLng: false,
+ defaultNS: 'common',
+ resources: { [locale]: { common: resource } },
+ interpolation: { escapeValue: false },
+ });
+ render(
+ <MemoryRouter>
+ <I18nextProvider i18n={i18n}>
+ <CindyMakeHistoryPanel />
+ </I18nextProvider>
+ </MemoryRouter>,
+ );
+ expect(await screen.findByRole('heading', { name: title + ' · 1' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: build })).toBeTruthy();
+ expect(screen.getByRole('button', { name: integrate })).toBeTruthy();
+ expect(screen.getByText(counts)).toBeTruthy();
+ for (const [key, value] of strings({
+ history: resource.cindyMake.history,
+ checkStep: resource.cindyMake.personal.checkStep,
+ merge: resource.cindyMake.merge,
+ tabs: resource.settings.cindyMake.tabs,
+ localChanges: resource.cindyMake.versions.localChanges,
+ })) {
+ expect(value, locale + ':' + key).not.toMatch(/\?{2,}|\uFFFD/);
+ expect(value.replace(/\{\{[^}]+\}\}/g, ''), locale + ':' + key).toMatch(script);
+ }
+ },
+ );
+
+ it.each(cases)(
+ 'renders ended builds, local changes and conflicts in $locale',
+ async ({ locale, resource }) => {
+ const state = await window.electronAPI.getCindyMakeHistory();
+ state.items[0].lifecycle = 'ended';
+ state.items[0].build = { status: 'failed' };
+ state.items[0].actions = ['build'];
+ state.items[0].completions = [{ id: 'round-a', reportedAt: 1, changedFiles: 2 }];
+ vi.stubGlobal('electronAPI', {
+ getCindyMakeHistory: async () => state,
+ getCindyVersions: async () => ({
+ currentId: 'original',
+ selectedId: 'original',
+ switching: false,
+ versions: [
+ {
+ id: 'original',
+ kind: 'original',
+ development: true,
+ dirty: true,
+ available: true,
+ compatible: true,
+ },
+ ],
+ }),
+ });
+ const missing: string[] = [];
+ const i18n = createInstance();
+ await i18n.use(initReactI18next).init({
+ lng: locale,
+ fallbackLng: false,
+ defaultNS: 'common',
+ resources: { [locale]: { common: resource } },
+ interpolation: { escapeValue: false },
+ saveMissing: true,
+ missingKeyHandler: (_languages, _namespace, key) => {
+ missing.push(key);
+ },
+ });
+ const view = render(
+ <MemoryRouter>
+ <I18nextProvider i18n={i18n}>
+ <CindyMakeVersionsPanel />
+ <CindyMakeHistoryPanel />
+ <CindyMakeMergeNotice
+ state={{
+ id: 'merge',
+ status: 'conflict',
+ error: 'checksFailed',
+ ref: 'main',
+ upstreamCommit: 'a'.repeat(40),
+ hasWorkspace: true,
+ }}
+ />
+ </I18nextProvider>
+ </MemoryRouter>,
+ );
+ expect(
+ await screen.findByRole('button', { name: resource.cindyMake.history.actions.retryBuild }),
+ ).toBeTruthy();
+ expect(
+ await screen.findByText(
+ resource.cindyMake.versions.development +
+ ' · ' +
+ resource.cindyMake.versions.localChanges,
+ ),
+ ).toBeTruthy();
+ expect(screen.getByText(resource.cindyMake.history.buildStatus.failed)).toBeTruthy();
+ expect(
+ screen.getByText(i18n.t('cindyMake.history.files', { count: 2 }), { exact: false }),
+ ).toBeTruthy();
+ expect(screen.getByRole('button', { name: resource.cindyMake.merge.resolve })).toBeTruthy();
+ expect(i18n.t('settings.cindyMake.tabs.versions')).toBe(
+ resource.settings.cindyMake.tabs.versions,
+ );
+ expect(i18n.t('settings.cindyMake.tabs.environment')).toBe(
+ resource.settings.cindyMake.tabs.environment,
+ );
+ expect(view.container.textContent).not.toMatch(/cindyMake\.|\{\{|\?{2,}|\uFFFD/);
+ expect(missing).toEqual([]);
+ },
+ );
+});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeHistoryPanel.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeHistoryPanel.test.tsx
new file mode 100644
index 0000000000..b617aa98cc
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeHistoryPanel.test.tsx
@@ -0,0 +1,256 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import type {
+ CindyMakeHistoryItem,
+ CindyMakeHistoryState,
+} from '../../../../shared/cindyMakeHistory';
+import { CindyMakeHistoryPanel } from '../CindyMakeHistoryPanel';
+
+const h = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ confirm: vi.fn(async () => true),
+ error: vi.fn(),
+ make: {},
+}));
+vi.mock('react-router-dom', () => ({ useNavigate: () => h.navigate }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}));
+vi.mock('@/lib/cindyMakeState', () => ({ useCindyMakeState: () => h.make }));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: h.confirm }),
+}));
+vi.mock('@/lib/toast', () => ({ toast: { error: h.error } }));
+function item(patch: Partial<CindyMakeHistoryItem> = {}): CindyMakeHistoryItem {
+ return {
+ schema: 1,
+ runId: 'aaaa',
+ sessionId: 'task-a',
+ title: 'Blue background',
+ request: 'Make the background blue',
+ createdAt: 1,
+ updatedAt: 2,
+ completions: [],
+ receipts: [],
+ versions: [],
+ lifecycle: 'ready',
+ integration: 'unintegrated',
+ actions: ['continue', 'test', 'integrate', 'end'],
+ ...patch,
+ };
+}
+function harness(items = [item()]) {
+ let state: CindyMakeHistoryState = { items, busy: false, canBuild: true };
+ const read = vi.fn(async () => state);
+ const execute = vi.fn(async () => state);
+ const build = vi.fn(async () => state);
+ const cancel = vi.fn(async () => state);
+ vi.stubGlobal('electronAPI', {
+ getCindyMakeHistory: read,
+ actCindyMakeHistory: execute,
+ generateCindyMakePersonal: build,
+ cancelCindyMakePersonal: cancel,
+ });
+ return {
+ read,
+ execute,
+ build,
+ cancel,
+ set: (next: CindyMakeHistoryState) => {
+ state = next;
+ },
+ };
+}
+beforeEach(() => {
+ setDataOwnerGeneration('history-ui-owner');
+ vi.clearAllMocks();
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+describe('Make history controls', () => {
+ it('refreshes a long-running global build through checking steps to failure and allows retry', async () => {
+ const f = harness([]);
+ render(<CindyMakeHistoryPanel />);
+ const build = await screen.findByRole('button', { name: 'cindyMake.history.build' });
+ await waitFor(() => expect(build.hasAttribute('disabled')).toBe(false));
+ f.set({
+ items: [],
+ busy: true,
+ canBuild: false,
+ build: { status: 'checking', checkStep: 'dependencies', buildId: 'build-1' },
+ });
+ fireEvent.click(build);
+ await screen.findByText('cindyMake.personal.checkStep.dependencies');
+ const stop = screen.getByRole('button', { name: 'cindyMake.history.stop' });
+ expect(stop.hasAttribute('disabled')).toBe(false);
+ fireEvent.click(stop);
+ await waitFor(() => expect(f.cancel).toHaveBeenCalledOnce());
+ for (const checkStep of ['tests', 'types'] as const) {
+ f.set({ items: [], busy: true, canBuild: false, build: { status: 'checking', checkStep } });
+ fireEvent(window, new Event('focus'));
+ await screen.findByText('cindyMake.personal.checkStep.' + checkStep);
+ }
+ f.set({
+ items: [],
+ busy: false,
+ canBuild: true,
+ build: { status: 'failed', error: 'checksFailed' },
+ });
+ fireEvent(window, new Event('focus'));
+ expect((await screen.findByRole('alert')).textContent).toBe(
+ 'cindyMake.personal.errors.checksFailed',
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.history.build' }));
+ await waitFor(() => expect(f.build).toHaveBeenCalledTimes(2));
+ });
+ it('shows the actual task build stage while removing mutation controls', async () => {
+ const building = item({
+ operation: 'build',
+ build: { status: 'packaging' },
+ actions: ['open'],
+ });
+ const f = harness([building]);
+ f.set({ items: [building], busy: true, canBuild: false });
+ render(<CindyMakeHistoryPanel />);
+ expect(await screen.findByText('cindyMake.history.buildStatus.packaging')).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: 'cindyMake.history.build' }).hasAttribute('disabled'),
+ ).toBe(true);
+ expect(
+ screen.queryByRole('button', { name: 'cindyMake.history.actions.integrate' }),
+ ).toBeNull();
+ expect(screen.queryByRole('button', { name: 'cindyMake.history.actions.end' })).toBeNull();
+ });
+ it('exposes retry generation from a failed ended record', async () => {
+ const failed = item({
+ lifecycle: 'ended',
+ integration: 'integrated',
+ build: { status: 'failed', error: 'checksFailed' },
+ actions: ['build'],
+ });
+ const f = harness([failed]);
+ render(<CindyMakeHistoryPanel />);
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'cindyMake.history.actions.retryBuild' }),
+ );
+ await waitFor(() => expect(f.build).toHaveBeenCalledOnce());
+ });
+ it('offers the verified installer fallback when the source cannot produce a managed switchable version', async () => {
+ const f = harness([]);
+ const open = vi.fn(async () => {});
+ vi.stubGlobal('electronAPI', { ...window.electronAPI, openCindyMakeHistoryBuild: open });
+ f.set({
+ items: [],
+ busy: false,
+ canBuild: true,
+ build: { status: 'ready', buildId: 'build', artifactName: 'Cindy.exe' },
+ });
+ render(<CindyMakeHistoryPanel />);
+ fireEvent.click(await screen.findByRole('button', { name: 'cindyMake.history.openInstaller' }));
+ await waitFor(() => expect(open).toHaveBeenCalledOnce());
+ expect(screen.getByText('cindyMake.history.buildStatus.installerReady')).toBeTruthy();
+ expect(screen.queryByText('cindyMake.history.buildStatus.ready')).toBeNull();
+ });
+ it('shows only operations admitted for the selected record and changes them after integration', async () => {
+ const f = harness();
+ render(<CindyMakeHistoryPanel />);
+ expect(screen.getByRole('combobox', { name: 'cindyMake.history.filterLabel' })).toBeTruthy();
+ expect((await screen.findByRole('button', { name: /Blue background/ })).className).toContain(
+ 'settings-menu-bg-selected',
+ );
+ const integrate = await screen.findByRole('button', {
+ name: 'cindyMake.history.actions.integrate',
+ });
+ f.set({
+ items: [
+ item({
+ integration: 'integrated',
+ actions: ['continue', 'test', 'end', 'revert'],
+ needsBuild: true,
+ }),
+ ],
+ busy: false,
+ canBuild: true,
+ });
+ fireEvent.click(integrate);
+ expect(f.execute).toHaveBeenCalledWith('aaaa', 'integrate');
+ expect(
+ await screen.findByRole('button', { name: 'cindyMake.history.actions.revert' }),
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: 'cindyMake.history.actions.integrate' }),
+ ).toBeNull();
+ expect(screen.queryByRole('button', { name: 'cindyMake.history.actions.reapply' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'cindyMake.history.actions.open' })).toBeNull();
+ expect(screen.getByText('cindyMake.history.needsBuild')).toBeTruthy();
+ });
+ it('retains finished history and exposes retained undo without edit, test, or repeated cleanup actions', async () => {
+ harness([
+ item({
+ lifecycle: 'ended',
+ integration: 'integrated',
+ endedAt: 3,
+ actions: ['open', 'revert'],
+ }),
+ ]);
+ render(<CindyMakeHistoryPanel />);
+ expect(
+ await screen.findByRole('button', { name: 'cindyMake.history.actions.revert' }),
+ ).toBeTruthy();
+ expect(screen.getByRole('heading', { name: 'cindyMake.history.title · 1' })).toBeTruthy();
+ for (const action of ['end', 'test', 'continue', 'integrate'])
+ expect(
+ screen.queryByRole('button', { name: 'cindyMake.history.actions.' + action }),
+ ).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.history.actions.revert' }));
+ await waitFor(() =>
+ expect(h.confirm).toHaveBeenCalledWith(
+ expect.objectContaining({ description: 'cindyMake.history.revertConfirm' }),
+ ),
+ );
+ });
+ it('opens the dedicated resolution task and does not offer unrelated integration actions during a conflict', async () => {
+ const f = harness([
+ item({ conflict: true, resolutionSessionId: 'conflict-task', actions: ['open', 'resolve'] }),
+ ]);
+ render(<CindyMakeHistoryPanel />);
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'cindyMake.history.actions.resolve' }),
+ );
+ await waitFor(() => expect(h.navigate).toHaveBeenCalledWith('/cc-agent/conflict-task'));
+ expect(f.execute).toHaveBeenCalledWith('aaaa', 'resolve');
+ expect(screen.queryByRole('button', { name: 'cindyMake.history.actions.end' })).toBeNull();
+ });
+ it('keeps a cancelled cleanup confirmation from mutating or hiding the record', async () => {
+ const f = harness();
+ h.confirm.mockResolvedValueOnce(false);
+ render(<CindyMakeHistoryPanel />);
+ fireEvent.click(await screen.findByRole('button', { name: 'cindyMake.history.actions.end' }));
+ await waitFor(() => expect(h.confirm).toHaveBeenCalledOnce());
+ expect(f.execute).not.toHaveBeenCalled();
+ expect(screen.getByRole('heading', { name: 'cindyMake.history.title · 1' })).toBeTruthy();
+ });
+ it('does not replace a switched owner’s history with an older in-flight result', async () => {
+ const f = harness();
+ let old!: (state: CindyMakeHistoryState) => void;
+ f.read.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ old = resolve;
+ }),
+ );
+ const view = render(<CindyMakeHistoryPanel />);
+ setDataOwnerGeneration('new-history-owner');
+ f.set({ items: [item({ title: 'New owner record' })], busy: false, canBuild: true });
+ view.rerender(<CindyMakeHistoryPanel />);
+ await screen.findByRole('button', { name: /New owner record/ });
+ await act(async () =>
+ old({ items: [item({ title: 'Private previous owner' })], busy: false, canBuild: true }),
+ );
+ expect(screen.queryByText(/Private previous owner/)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePreflightDialog.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePreflightDialog.test.tsx
index 5422bbd1e5..5fdc4499f9 100644
--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePreflightDialog.test.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePreflightDialog.test.tsx
@@ -17,7 +17,12 @@ const h = vi.hoisted(() => ({
remote: false,
publish: undefined as undefined | ((report: MakeDoctorReport) => void),
}));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: { worktree: string; request: string }) =>
+ key === 'cindyMake.code.taskTitle' && values ? `[${values.worktree}] ${values.request}` : key,
+ }),
+}));
vi.mock('react-router-dom', () => ({ useNavigate: () => h.navigate }));
vi.mock('@/lib/cindyMakeDoctor', () => ({ startMakeDoctor: h.start, cancelMakeDoctor: h.cancel }));
vi.mock('@/lib/makerChatStore', () => ({ makerChatStore: { setSessionRuntime: h.runtime } }));
@@ -82,6 +87,21 @@ afterEach(() => {
});
describe('Make preflight confirmation boundary', () => {
+ it('names the created task after the first four characters of its worktree run', async () => {
+ open();
+ await finishChecks();
+ act(() => h.publish!({ ...ready, runId: 'f428ca8b-242b-43c6-b2e5-e54bdd915f62' }));
+ fireEvent.click(continueButton());
+ await waitFor(() =>
+ expect(h.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ runId: 'f428ca8b-242b-43c6-b2e5-e54bdd915f62',
+ title: '[f428] Keep my request',
+ }),
+ ),
+ );
+ });
+
it('starts checks once under StrictMode without cancelling them on the rehearsal mount', async () => {
render(
<StrictMode>
@@ -108,7 +128,7 @@ describe('Make preflight confirmation boundary', () => {
originSessionId: sessionId,
runId: 'run',
request: ' Keep my request ',
- title: 'cindyMake.code.taskTitle',
+ title: '[run] Keep my request',
createOptions: { agentKind: 'codex', model: 'selected' },
});
expect(h.runtime).toHaveBeenCalledWith('code-task', { autoTitleDisabled: true });
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeSourceDetails.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeSourceDetails.test.tsx
index b7fe0ca736..ce3c33b785 100644
--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeSourceDetails.test.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeSourceDetails.test.tsx
@@ -4,7 +4,10 @@ import { afterEach, describe, expect, it } from 'vitest';
import { createInstance } from 'i18next';
import { I18nextProvider } from 'react-i18next';
import { CindyMakeSourceDetails } from '../CindyMakeSourceDetails';
-import type { MakeSourcePreparation } from '../../../../shared/cindyMakeDoctor';
+import type {
+ MakeSourceLatestVersion,
+ MakeSourcePreparation,
+} from '../../../../shared/cindyMakeDoctor';
import en from '@/i18n/locales/en/common.json';
import zhCN from '@/i18n/locales/zh-CN/common.json';
import zhTW from '@/i18n/locales/zh-TW/common.json';
@@ -29,12 +32,13 @@ const locales = { en, 'zh-CN': zhCN, 'zh-TW': zhTW, ja, ko };
async function show(
overrides: Partial<MakeSourcePreparation> = {},
locale: keyof typeof locales = 'zh-CN',
+ latestVersion?: MakeSourceLatestVersion,
) {
const i18n = createInstance();
await i18n.init({ lng: locale, resources: { [locale]: { translation: locales[locale] } } });
return render(
<I18nextProvider i18n={i18n}>
- <CindyMakeSourceDetails source={{ ...source, ...overrides }} />
+ <CindyMakeSourceDetails source={{ ...source, ...overrides }} latestVersion={latestVersion} />
</I18nextProvider>,
);
}
@@ -42,6 +46,92 @@ async function show(
afterEach(cleanup);
describe('Cindy Make source summary', () => {
+ it.each(Object.keys(locales) as (keyof typeof locales)[])(
+ 'shows live latest main and verified comparison counts in %s',
+ async (locale) => {
+ const { container } = await show({}, locale, {
+ status: 'ready',
+ channel: 'dev',
+ ref: 'main',
+ commit: 'e'.repeat(40),
+ ahead: 0,
+ behind: 9,
+ });
+ expect(screen.getByText('e'.repeat(12)).title).toBe('e'.repeat(40));
+ expect(screen.getByText(locales[locale].cindyMake.source.details.latest.dev)).toBeTruthy();
+ expect(
+ screen.getByText(
+ locales[locale].cindyMake.source.details.latest.behind_other.replace('{{count}}', '9'),
+ ),
+ ).toBeTruthy();
+ expect(container.textContent).not.toMatch(/cindyMake\.source|\{\{/);
+ },
+ );
+
+ it.each(['beta', 'release'] as const)(
+ 'labels the latest %s tag separately from local main',
+ async (channel) => {
+ const ref = channel === 'beta' ? 'v2.0.0-beta' : 'v2.0.0';
+ await show({}, 'zh-CN', { status: 'ready', channel, ref, commit: 'e'.repeat(40) });
+ expect(screen.getByText(zhCN.cindyMake.source.details.latest[channel])).toBeTruthy();
+ expect(screen.getByText(ref)).toBeTruthy();
+ expect(screen.getByText(source.mainCommit!.slice(0, 12))).toBeTruthy();
+ expect(screen.queryByText(/main 落后/)).toBeNull();
+ },
+ );
+
+ it('shows matching versions without displaying stale cached counts', async () => {
+ await show({}, 'zh-CN', {
+ status: 'ready',
+ channel: 'dev',
+ ref: 'main',
+ commit: source.mainCommit!,
+ ahead: 0,
+ behind: 0,
+ });
+ expect(screen.getByText('(已同步)')).toBeTruthy();
+ expect(screen.queryByText(/main 落后/)).toBeNull();
+ });
+
+ it('shows a lookup failure rather than treating cached origin/main as latest', async () => {
+ const { container } = await show({}, 'zh-CN', { status: 'unavailable', channel: 'dev' });
+ expect(container.textContent).toContain('未能查询');
+ expect(container.textContent).not.toContain(source.mainRemoteCommit!.slice(0, 12));
+ expect(screen.getByText(source.mainCommit!.slice(0, 12))).toBeTruthy();
+ });
+
+ it.each([
+ { ahead: 0, behind: 24, expected: '(落后 24 个提交)' },
+ { ahead: 3, behind: 0, expected: '(领先 3 个提交)' },
+ { ahead: 2, behind: 7, expected: '(落后 7,领先 2 个提交)' },
+ ])(
+ 'keeps the difference compact without hiding a nonzero side: $expected',
+ async ({ ahead, behind, expected }) => {
+ await show({}, 'zh-CN', {
+ status: 'ready',
+ channel: 'dev',
+ ref: 'main',
+ commit: 'e'.repeat(40),
+ ahead,
+ behind,
+ });
+ expect(screen.getByText(expected)).toBeTruthy();
+ expect(screen.queryByText(/(?:落后|领先) 0/)).toBeNull();
+ },
+ );
+
+ it('uses the singular form for one commit', async () => {
+ await show({}, 'en', {
+ status: 'ready',
+ channel: 'dev',
+ ref: 'main',
+ commit: 'e'.repeat(40),
+ ahead: 0,
+ behind: 1,
+ });
+ expect(screen.getByText('(1 commit behind)')).toBeTruthy();
+ });
+
it.each(Object.keys(locales) as (keyof typeof locales)[])(
'shows exactly three Git entries with short hashes in %s',
async (locale) => {
@@ -55,7 +145,6 @@ describe('Cindy Make source summary', () => {
expect(screen.getByText(terms.baseRef.replace('{{ref}}', 'main'))).toBeTruthy();
for (const commit of [source.baseCommit!, source.mainCommit!]) {
const hash = screen.getByText(commit.slice(0, 12));
- expect(hash.className).toContain('break-all');
expect(hash.className).toContain('font-mono');
expect(hash.title).toBe(commit);
}
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTaskCard.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTaskCard.test.tsx
index 650e075510..23b0efb97c 100644
--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTaskCard.test.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTaskCard.test.tsx
@@ -122,7 +122,7 @@ describe('Cindy Make preparation card', () => {
originSessionId: 'origin',
runId: 'make-run',
request: 'original request',
- title: report.task!.title,
+ title: '[make] Cindy Make: scrolling',
}),
);
});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTasksPanel.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTasksPanel.test.tsx
index ba45a67964..ff70e6be4d 100644
--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTasksPanel.test.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTasksPanel.test.tsx
@@ -18,7 +18,9 @@ vi.mock('@/components/ui/confirm-dialog-provider', () => ({
}));
vi.mock('@/lib/sessionService', () => ({ get: h.get, restoreIfArchived: h.restore }));
vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { prependCreated: h.prepend } }));
-vi.mock('@/lib/cindyMakeState', () => ({ cindyMakeState: { refresh: h.refresh } }));
+vi.mock('@/lib/cindyMakeState', () => ({
+ cindyMakeState: { refresh: h.refresh, manageTask: h.manage },
+}));
vi.mock('@/lib/toast', () => ({ toast: { error: h.error } }));
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import type { MakeDoctorReport } from '../../../../shared/cindyMakeDoctor';
@@ -117,19 +119,19 @@ describe('Cindy Make settings task list', () => {
setDataOwnerGeneration('another-owner');
return true;
});
- fireEvent.click(screen.getByRole('button', { name: 'settings.cindyMake.tasks.delete' }));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.cindyMake.tasks.end' }));
await waitFor(() => expect(h.confirm).toHaveBeenCalled());
expect(h.manage).not.toHaveBeenCalled();
});
- it('requires confirmation before deleting and refreshes only after the operation settles', async () => {
+ it('requires confirmation before ending and refreshes only after the operation settles', async () => {
h.confirm.mockResolvedValueOnce(false);
render(<CindyMakeTasksPanel reports={[report(1)]} />);
- const remove = screen.getByRole('button', { name: 'settings.cindyMake.tasks.delete' });
+ const remove = screen.getByRole('button', { name: 'settings.cindyMake.tasks.end' });
fireEvent.click(remove);
await waitFor(() => expect(remove.hasAttribute('disabled')).toBe(false));
expect(h.manage).not.toHaveBeenCalled();
fireEvent.click(remove);
- await waitFor(() => expect(h.manage).toHaveBeenCalledWith('session-1', 'delete'));
+ await waitFor(() => expect(h.manage).toHaveBeenCalledWith('session-1', 'end'));
expect(h.confirm).toHaveBeenLastCalledWith(
expect.objectContaining({ confirmVariant: 'destructive' }),
);
@@ -139,8 +141,12 @@ describe('Cindy Make settings task list', () => {
render(<CindyMakeTasksPanel reports={[report(1, { sessionStatus: 'deleted' })]} />);
expect(screen.queryByRole('button', { name: 'cindyMake.code.open' })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'settings.cindyMake.tasks.retryCleanup' }));
- await waitFor(() => expect(h.manage).toHaveBeenCalledWith('session-1', 'delete'));
- expect(h.confirm).not.toHaveBeenCalled();
+ await waitFor(() => expect(h.manage).toHaveBeenCalledWith('session-1', 'end'));
+ expect(h.confirm).toHaveBeenCalledWith(
+ expect.objectContaining({
+ description: expect.stringContaining('settings.cindyMake.tasks.cleanupDeletedConfirm'),
+ }),
+ );
});
it('shows cleanup progress and keeps an actionable failure beside the retry button', async () => {
let reject!: (error: Error) => void;
@@ -204,4 +210,50 @@ describe('Cindy Make settings task list', () => {
.hasAttribute('disabled'),
).toBe(false);
});
+
+ it.each(['integrated', 'unintegrated', 'unknown'] as const)(
+ 'shows %s in the cell and always confirms before ending',
+ async (integration) => {
+ h.confirm.mockResolvedValueOnce(false);
+ render(<CindyMakeTasksPanel reports={[report(1, { integration })]} />);
+ const row = screen.getByRole('button', { name: /Build 1/ });
+ expect(row.textContent).toContain('settings.cindyMake.tasks.status.' + integration);
+ expect(screen.queryByRole('button', { name: 'settings.cindyMake.tasks.finish' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'settings.cindyMake.tasks.delete' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'settings.cindyMake.tasks.end' }));
+ await waitFor(() => expect(h.confirm).toHaveBeenCalled());
+ expect(h.manage).not.toHaveBeenCalled();
+ const dialog = h.confirm.mock.calls[0][0];
+ expect(dialog.description).toContain('settings.cindyMake.tasks.endConfirm');
+ expect(dialog.confirmVariant).toBe('destructive');
+ if (integration === 'unintegrated') expect(dialog.description).toContain('endUnintegrated');
+ if (integration === 'unknown') expect(dialog.description).toContain('endUnknown');
+ },
+ );
+
+ it('shows a failed end in its cell, preserves its record and confirms retry after reopening', async () => {
+ const props = {
+ reports: [report(1, { sessionStatus: 'archived', cleanupPending: true })],
+ taskActions: {
+ 'session-1': {
+ action: 'end' as const,
+ status: 'failed' as const,
+ error: 'directoryBusy' as const,
+ },
+ },
+ };
+ const view = render(<CindyMakeTasksPanel {...props} />);
+ expect(screen.getByRole('button', { name: /Build 1/ }).textContent).toContain(
+ 'settings.cindyMake.tasks.status.cleanupFailed',
+ );
+ view.unmount();
+ render(<CindyMakeTasksPanel reports={props.reports} />);
+ expect(screen.getByRole('button', { name: /Build 1/ }).textContent).toContain(
+ 'settings.cindyMake.tasks.status.cleanup',
+ );
+ h.confirm.mockResolvedValueOnce(false);
+ fireEvent.click(screen.getByRole('button', { name: 'settings.cindyMake.tasks.retryCleanup' }));
+ await waitFor(() => expect(h.confirm).toHaveBeenCalled());
+ expect(h.manage).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTasksPanelState.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTasksPanelState.test.tsx
new file mode 100644
index 0000000000..b8dab5494f
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTasksPanelState.test.tsx
@@ -0,0 +1,104 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import { useCindyMakeState } from '@/lib/cindyMakeState';
+import type { CindyMakeGlobalState, MakeDoctorReport } from '../../../../shared/cindyMakeDoctor';
+import { CindyMakeTasksPanel } from '../CindyMakeTasksPanel';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: async () => true }),
+}));
+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));
+
+function report(index: number): MakeDoctorReport {
+ return {
+ runId: 'run-' + index,
+ platform: 'win32',
+ arch: 'x64',
+ status: 'completed',
+ checks: [],
+ task: {
+ sessionId: 'session-' + index,
+ title: 'Build ' + index,
+ request: 'Request ' + index,
+ phase: 'completed',
+ sessionStatus: 'active',
+ },
+ };
+}
+
+/** Use the same shared snapshot and conditional panel as Settings. */
+function TaskList() {
+ const state = useCindyMakeState();
+ const reports = Object.values(state.tasks ?? {});
+ return reports.length ? (
+ <CindyMakeTasksPanel reports={reports} taskActions={state.taskActions} />
+ ) : null;
+}
+
+beforeEach(() => setDataOwnerGeneration('make-task-list-state-test'));
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('Cindy Make task list completion', () => {
+ it.each(['end'] as const)(
+ 'removes a successful %s without waiting for another snapshot or reopening Settings',
+ async (action) => {
+ let push!: (state: CindyMakeGlobalState) => void;
+ let complete!: () => void;
+ const initial: CindyMakeGlobalState = { tasks: { 'run-1': report(1), 'run-2': report(2) } };
+ const getState = vi
+ .fn(() => new Promise<CindyMakeGlobalState>(() => {}))
+ .mockResolvedValueOnce(initial);
+ const manage = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ complete = resolve;
+ }),
+ );
+ vi.stubGlobal('electronAPI', {
+ getCindyMakeState: getState,
+ onCindyMakeState: (listener: typeof push) => {
+ push = listener;
+ return () => {};
+ },
+ manageCindyMakeTask: manage,
+ });
+ render(<TaskList />);
+ fireEvent.click(await screen.findByRole('button', { name: /Build 2/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.cindyMake.tasks.' + action }));
+ await waitFor(() => expect(manage).toHaveBeenCalledWith('session-2', action));
+ act(() =>
+ push({
+ ...initial,
+ taskActions: { 'session-2': { action, status: 'running' } },
+ }),
+ );
+ expect(screen.getAllByText('settings.cindyMake.tasks.status.cleaning')).toHaveLength(2);
+
+ // Main has completed, but its final push is absent and the next read is still pending.
+ await act(async () => complete());
+ await waitFor(() => expect(screen.queryByRole('button', { name: /Build 2/ })).toBeNull());
+ expect(
+ screen.getByRole('heading', { name: 'settings.cindyMake.tasks.title · 1' }),
+ ).toBeTruthy();
+ expect(screen.getByText('Request 1')).toBeTruthy();
+ expect(screen.queryByText('settings.cindyMake.tasks.status.cleaning')).toBeNull();
+ expect(
+ screen
+ .getByRole('button', { name: 'settings.cindyMake.tasks.end' })
+ .hasAttribute('disabled'),
+ ).toBe(false);
+
+ fireEvent.click(screen.getByRole('button', { name: 'settings.cindyMake.tasks.end' }));
+ await waitFor(() => expect(manage).toHaveBeenLastCalledWith('session-1', 'end'));
+ await act(async () => complete());
+ expect(screen.queryByRole('region', { name: 'settings.cindyMake.tasks.title' })).toBeNull();
+ },
+ );
+});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTestCard.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTestCard.test.tsx
new file mode 100644
index 0000000000..30b6daf3c4
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTestCard.test.tsx
@@ -0,0 +1,216 @@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { CindyMakeTestCard } from '../CindyMakeTestCard';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import type { CindyMakeCompletionMeta } from '../../../../shared/cindyMakeSession';
+const h = vi.hoisted(() => ({ api: vi.fn(), patch: vi.fn() }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}));
+vi.mock('@/lib/makerChatStore', () => ({ makerChatStore: { updateSystemCardData: h.patch } }));
+vi.mock('@/features/device-link/stickySessionOrigin', () => ({
+ getStickySessionDeviceId: () => undefined,
+}));
+const meta: CindyMakeCompletionMeta = { reportedAt: 123, commit: 'a'.repeat(40), changedFiles: 2 };
+const view = () =>
+ render(<CindyMakeTestCard sessionId="session" completionId="completion" meta={meta} />);
+beforeEach(() => {
+ vi.clearAllMocks();
+ setDataOwnerGeneration('test-owner');
+ h.api.mockResolvedValue(meta);
+ vi.stubGlobal('electronAPI', { cindyMakeTest: h.api });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('completion card in the input area', () => {
+ it('only reads status on mount and starts the isolated build after the user clicks', async () => {
+ view();
+ await waitFor(() => expect(h.api).toHaveBeenCalledWith('session', 'completion', 'status'));
+ expect(h.api).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole('textbox')).toBeNull();
+ h.api.mockResolvedValueOnce({ ...meta, test: { status: 'starting' } });
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.test.start' }));
+ await waitFor(() => expect(h.api).toHaveBeenCalledWith('session', 'completion', 'start'));
+ });
+ it('does not let a delayed status read undo the acknowledged launch', async () => {
+ let status!: (value: CindyMakeCompletionMeta) => void;
+ h.api.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ status = resolve;
+ }),
+ );
+ h.api.mockResolvedValueOnce({ ...meta, test: { status: 'starting' } });
+ view();
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.test.start' }));
+ await waitFor(() => expect(h.patch).toHaveBeenCalledOnce());
+ await act(async () => status(meta));
+ expect(h.patch).toHaveBeenCalledOnce();
+ expect(h.patch.mock.calls[0][2].test.status).toBe('starting');
+ });
+ it('keeps the card when continuing is rejected and persists continuation only after acknowledgment', async () => {
+ view();
+ await waitFor(() => expect(h.api).toHaveBeenCalledOnce());
+ h.api.mockRejectedValueOnce(new Error('rejected'));
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.test.continue' }));
+ await screen.findByRole('alert');
+ expect(h.patch.mock.calls.some(([, , value]) => value.continuedAt)).toBe(false);
+ h.api.mockResolvedValueOnce({ ...meta, continuedAt: 456 });
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.test.continue' }));
+ await waitFor(() =>
+ expect(h.patch).toHaveBeenCalledWith('session', 'completion', { ...meta, continuedAt: 456 }),
+ );
+ });
+ it('prevents duplicate launches while the first request is pending', async () => {
+ view();
+ await waitFor(() => expect(h.api).toHaveBeenCalledOnce());
+ let resolve!: (value: CindyMakeCompletionMeta) => void;
+ h.api.mockImplementationOnce(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const start = screen.getByRole('button', { name: 'cindyMake.test.start' });
+ fireEvent.click(start);
+ fireEvent.click(start);
+ expect(h.api.mock.calls.filter(([, , action]) => action === 'start')).toHaveLength(1);
+ await act(async () => resolve({ ...meta, test: { status: 'starting' } }));
+ });
+ it('does not offer a launch without a verified commit', () => {
+ render(
+ <CindyMakeTestCard
+ sessionId="session"
+ completionId="completion"
+ meta={{ reportedAt: 123 }}
+ />,
+ );
+ expect(
+ (screen.getByRole('button', { name: 'cindyMake.test.start' }) as HTMLButtonElement).disabled,
+ ).toBe(true);
+ expect(screen.getByRole('alert').textContent).toContain('cindyMake.test.errors.unavailable');
+ expect(
+ (screen.getByRole('button', { name: 'cindyMake.personal.generate' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
+ });
+ it('offers all three choices and generates a personal installer only on click', async () => {
+ view();
+ await waitFor(() => expect(h.api).toHaveBeenCalledOnce());
+ expect(screen.getByRole('button', { name: 'cindyMake.test.continue' })).toBeDefined();
+ expect(screen.getByRole('button', { name: 'cindyMake.test.start' })).toBeDefined();
+ h.api.mockResolvedValueOnce({ ...meta, lastAction: 'build', personal: { status: 'waiting' } });
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.personal.generate' }));
+ await waitFor(() => expect(h.api).toHaveBeenCalledWith('session', 'completion', 'build'));
+ expect(h.patch).toHaveBeenCalledWith(
+ 'session',
+ 'completion',
+ expect.objectContaining({ personal: { status: 'waiting' } }),
+ );
+ });
+ it('shows personal build progress and disables every action until it finishes', () => {
+ render(
+ <CindyMakeTestCard
+ sessionId="session"
+ completionId="completion"
+ meta={{ ...meta, lastAction: 'build', personal: { status: 'packaging' } }}
+ />,
+ );
+ expect(screen.getByText('cindyMake.personal.status.packaging')).toBeDefined();
+ expect(
+ (screen.getByRole('button', { name: 'cindyMake.test.continue' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
+ expect(
+ (screen.getByRole('button', { name: 'cindyMake.test.start' }) as HTMLButtonElement).disabled,
+ ).toBe(true);
+ expect(
+ (screen.getByRole('button', { name: 'cindyMake.personal.generate' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.test.continue' }));
+ expect(h.api.mock.calls.some(([, , action]) => action !== 'status')).toBe(false);
+ });
+ it('offers the installer when ready and gives failed builds a retry', async () => {
+ const { rerender } = render(
+ <CindyMakeTestCard
+ sessionId="session"
+ completionId="completion"
+ meta={{
+ ...meta,
+ lastAction: 'build',
+ personal: { status: 'ready', artifactName: 'Cindy.exe' },
+ }}
+ />,
+ );
+ await waitFor(() => expect(h.api).toHaveBeenCalledOnce());
+ expect(
+ screen.getAllByRole('button').every((button) => !(button as HTMLButtonElement).disabled),
+ ).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.personal.open' }));
+ await waitFor(() => expect(h.api).toHaveBeenCalledWith('session', 'completion', 'open-build'));
+ rerender(
+ <CindyMakeTestCard
+ sessionId="session"
+ completionId="completion"
+ meta={{
+ ...meta,
+ lastAction: 'build',
+ personal: { status: 'failed', error: 'checksFailed' },
+ }}
+ />,
+ );
+ expect(screen.getByRole('alert').textContent).toBe('cindyMake.personal.errors.checksFailed');
+ expect(
+ screen.getAllByRole('button').every((button) => !(button as HTMLButtonElement).disabled),
+ ).toBe(true);
+ expect(
+ (screen.getByRole('button', { name: 'cindyMake.personal.generate' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(false);
+ });
+ it('replaces the generation action with the shared version switch for a runnable snapshot', async () => {
+ const switchVersion = vi
+ .fn()
+ .mockResolvedValue({
+ currentId: 'original',
+ selectedId: 'original',
+ versions: [],
+ switching: true,
+ });
+ vi.stubGlobal('electronAPI', {
+ cindyMakeTest: h.api,
+ getCindyVersions: vi
+ .fn()
+ .mockResolvedValue({
+ currentId: 'original',
+ selectedId: 'original',
+ versions: [],
+ switching: false,
+ }),
+ actCindyVersion: switchVersion,
+ });
+ render(
+ <CindyMakeTestCard
+ sessionId="session"
+ completionId="completion"
+ meta={{
+ ...meta,
+ lastAction: 'build',
+ personal: { status: 'ready', versionId: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' },
+ }}
+ />,
+ );
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'cindyMake.versions.switchPersonal' }),
+ );
+ await waitFor(() =>
+ expect(switchVersion).toHaveBeenCalledWith('switch', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ );
+ expect(h.api.mock.calls.some(([, , action]) => action === 'open-build')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeVersionsPanel.i18n.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeVersionsPanel.i18n.test.tsx
new file mode 100644
index 0000000000..4198879aa5
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeVersionsPanel.i18n.test.tsx
@@ -0,0 +1,103 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createInstance } from 'i18next';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import en from '@/i18n/locales/en/common.json';
+import zhCN from '@/i18n/locales/zh-CN/common.json';
+import zhTW from '@/i18n/locales/zh-TW/common.json';
+import ja from '@/i18n/locales/ja/common.json';
+import ko from '@/i18n/locales/ko/common.json';
+import type { CindyVersionsState } from '../../../../shared/cindyVersions';
+import { CindyMakeVersionsPanel } from '../CindyMakeVersionsPanel';
+
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: async () => false }),
+}));
+
+const cases = [
+ {
+ locale: 'en',
+ resource: en,
+ title: 'My Versions',
+ switchLabel: 'Switch and Restart',
+ remove: 'Delete Version',
+ },
+ {
+ locale: 'zh-CN',
+ resource: zhCN,
+ title: '我的版本',
+ switchLabel: '切换并重启',
+ remove: '删除版本',
+ },
+ {
+ locale: 'zh-TW',
+ resource: zhTW,
+ title: '我的版本',
+ switchLabel: '切換並重新啟動',
+ remove: '刪除版本',
+ },
+ {
+ locale: 'ja',
+ resource: ja,
+ title: 'マイバージョン',
+ switchLabel: '切り替えて再起動',
+ remove: 'バージョンを削除',
+ },
+ {
+ locale: 'ko',
+ resource: ko,
+ title: '내 버전',
+ switchLabel: '전환 후 다시 시작',
+ remove: '버전 삭제',
+ },
+];
+
+beforeEach(() => {
+ setDataOwnerGeneration('versions-real-locales');
+ const state: CindyVersionsState = {
+ currentId: 'original',
+ selectedId: 'original',
+ switching: false,
+ versions: [
+ { id: 'original', kind: 'original', available: true, compatible: true },
+ { id: 'personal', kind: 'personal', available: true, compatible: true },
+ ],
+ };
+ vi.stubGlobal('electronAPI', {
+ getCindyVersions: async () => state,
+ actCindyVersion: async () => state,
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('Cindy Make versions with real translations', () => {
+ it.each(cases)(
+ 'renders $locale labels without missing translations or damaged characters',
+ async ({ locale, resource, title, switchLabel, remove }) => {
+ const i18n = createInstance();
+ await i18n.use(initReactI18next).init({
+ lng: locale,
+ fallbackLng: false,
+ defaultNS: 'common',
+ resources: { [locale]: { common: resource } },
+ interpolation: { escapeValue: false },
+ });
+ const { container } = render(
+ <I18nextProvider i18n={i18n}>
+ <CindyMakeVersionsPanel />
+ </I18nextProvider>,
+ );
+ expect(await screen.findByRole('button', { name: switchLabel })).toBeTruthy();
+ expect(screen.getByRole('heading', { name: title })).toBeTruthy();
+ expect(screen.getByRole('button', { name: remove })).toBeTruthy();
+ expect(screen.getByText(resource.cindyMake.versions.personal)).toBeTruthy();
+ expect(container.textContent).not.toMatch(/cindyMake\.|\{\{|\?{2,}|\uFFFD/);
+ },
+ );
+});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeVersionsPanel.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeVersionsPanel.test.tsx
new file mode 100644
index 0000000000..6f6afe3716
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeVersionsPanel.test.tsx
@@ -0,0 +1,81 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { CindyMakeVersionsPanel } from '../CindyMakeVersionsPanel';
+const h = vi.hoisted(() => ({ get: vi.fn(), act: vi.fn(), confirm: vi.fn() }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: h.confirm }),
+}));
+const versions = {
+ currentId: 'original',
+ selectedId: 'original',
+ switching: false,
+ versions: [
+ {
+ id: 'original',
+ kind: 'original',
+ development: true,
+ version: '0.1.99',
+ commit: 'a'.repeat(40),
+ available: true,
+ compatible: true,
+ },
+ {
+ id: 'personal',
+ kind: 'personal',
+ title: 'Blue background',
+ available: true,
+ compatible: true,
+ },
+ ],
+};
+beforeEach(() => {
+ vi.clearAllMocks();
+ h.get.mockResolvedValue(versions);
+ h.act.mockResolvedValue(versions);
+ h.confirm.mockResolvedValue(false);
+ vi.stubGlobal('electronAPI', { getCindyVersions: h.get, actCindyVersion: h.act });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+describe('Cindy Make local versions', () => {
+ it('shows Dev inside the original row and switches through the shared native operation', async () => {
+ render(<CindyMakeVersionsPanel />);
+ await screen.findByText('Blue background');
+ expect(screen.getByText('cindyMake.versions.original')).toBeDefined();
+ expect(
+ screen.getByText('cindyMake.versions.development · 0.1.99 · aaaaaaaaaaaa'),
+ ).toBeDefined();
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.versions.switch' }));
+ await waitFor(() => expect(h.act).toHaveBeenCalledWith('switch', 'personal'));
+ });
+ it('requires explicit deletion confirmation and never offers deleting the running version', async () => {
+ render(<CindyMakeVersionsPanel />);
+ const remove = await screen.findByRole('button', { name: 'cindyMake.versions.remove' });
+ fireEvent.click(remove);
+ await waitFor(() => expect(h.confirm).toHaveBeenCalledOnce());
+ expect(h.act).not.toHaveBeenCalled();
+ h.confirm.mockResolvedValueOnce(true);
+ fireEvent.click(remove);
+ await waitFor(() => expect(h.act).toHaveBeenCalledWith('remove', 'personal'));
+ });
+ it('does not let an incompatible version switch', async () => {
+ h.get.mockResolvedValue({
+ ...versions,
+ versions: versions.versions.map((version) =>
+ version.id === 'personal' ? { ...version, compatible: false } : version,
+ ),
+ });
+ render(<CindyMakeVersionsPanel />);
+ await screen.findByText('cindyMake.versions.incompatible');
+ expect(
+ (screen.getByRole('button', { name: 'cindyMake.versions.switch' }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx b/apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx
index 853567cf1b..d08f29a027 100644
--- a/apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx
@@ -1,28 +1,55 @@
-import { useEffect, useState } from 'react';
-import { ChevronDown, ChevronRight, GitBranch, Plus, Wrench } from 'lucide-react';
+import { useEffect, useId, useRef, useState } from 'react';
+import {
+ ChevronDown,
+ ChevronRight,
+ FolderOpen,
+ GitBranch,
+ Download,
+ Plus,
+ Trash2,
+ Wrench,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { Spinner } from '@/components/ui/spinner';
+import { Tip } from '@/components/ui/tooltip';
import { MakeDoctorReportCard } from '@/components/chat/CindyMakeDoctorCard';
import { CindyMakeSourceDetails } from '@/components/cindy-make/CindyMakeSourceDetails';
import { CindyMakeCreateDialog } from '@/components/cindy-make/CindyMakeCreateDialog';
import { CindyMakeDependencyProgress } from '@/components/cindy-make/CindyMakeDependencyProgress';
-import { CindyMakeTasksPanel } from '@/components/cindy-make/CindyMakeTasksPanel';
+import { CindyMakeHistoryPanel } from '@/components/cindy-make/CindyMakeHistoryPanel';
+import { CindyMakeVersionsPanel } from '@/components/cindy-make/CindyMakeVersionsPanel';
+import { CindyMakeMergeNotice } from '@/components/cindy-make/CindyMakeMergeNotice';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
+import type { CindyMakeHistoryState } from '../../../shared/cindyMakeHistory';
import { useCindyMakeState } from '@/lib/cindyMakeState';
import { cancelMakeDoctor, startMakeDoctor } from '@/lib/cindyMakeDoctor';
import { useCindyMakeSettings } from '@/lib/cindyMakeSettings';
+import { isSelectableVendor } from '@/lib/agentVendors';
+import { getDraft, getFastModeForModel } from '@/state/newMakerDraft';
import { toast } from '@/lib/toast';
import type { MakeDoctorReport, MakeSourceStatus } from '../../../shared/cindyMakeDoctor';
+const CINDY_MAKE_SETTINGS_TABS = ['versions', 'environment'] as const;
+type CindyMakeSettingsTab = (typeof CINDY_MAKE_SETTINGS_TABS)[number];
+
export function CindyMakeSection() {
const { t } = useTranslation();
+ const [activeTab, setActiveTab] = useState<CindyMakeSettingsTab>('versions');
+ const tabId = useId();
+ const tabButtons = useRef<Array<HTMLButtonElement | null>>([]);
const { forceManagedTools, setForceManagedTools } = useCindyMakeSettings();
const [createOpen, setCreateOpen] = useState(false);
const [report, setReport] = useState<MakeDoctorReport>();
const makeState = useCindyMakeState();
+ const [historyState, setHistoryState] = useState<CindyMakeHistoryState>();
const [dismissedPreparationId, setDismissedPreparationId] = useState<string>();
const [trackedPreparationId, setTrackedPreparationId] = useState<string>();
const [checkVersion, setCheckVersion] = useState(0);
@@ -35,9 +62,60 @@ export function CindyMakeSection() {
const sourceStatus = makeState.source;
const [sourceRunPending, setSourceRunPending] = useState(false);
const { confirm } = useConfirmDialog();
+ const mergeSubmitting = useRef(false);
+ const [mergePending, setMergePending] = useState(false);
+ const operation = makeState.upstreamMerge;
+ const merge = operation?.feature ? undefined : operation;
+ const mergeActive = !!operation && ['fetching', 'merging', 'checking'].includes(operation.status);
+ const mergeBlocked =
+ mergePending || mergeActive || (!!operation?.hasWorkspace && operation.status !== 'merged');
+ const updateSource = async () => {
+ if (mergeSubmitting.current || mergeBlocked) return;
+ const owner = getDataOwnerGeneration();
+ mergeSubmitting.current = true;
+ try {
+ const confirmed = await confirm({
+ title: t('cindyMake.merge.confirmTitle'),
+ description: t('cindyMake.merge.confirmDescription'),
+ confirmText: t('cindyMake.merge.confirm'),
+ cancelText: t('settings.cindyMake.source.resetConfirm.cancel'),
+ });
+ if (!confirmed || !isDataOwnerGenerationCurrent(owner)) return;
+ setMergePending(true);
+ const draft = getDraft();
+ const vendor = isSelectableVendor(draft.vendor) ? draft.vendor : 'cc';
+ const prefs = draft.lastByVendor[vendor];
+ await window.electronAPI.cindyMakeMerge({
+ action: 'update',
+ createOptions: {
+ agentKind: vendor,
+ model: prefs.model,
+ effort: prefs.effort,
+ providerId: prefs.providerId,
+ permissionMode: prefs.permissionMode,
+ fastMode: getFastModeForModel(prefs.model),
+ planModeEnabled: false,
+ },
+ });
+ if (isDataOwnerGenerationCurrent(owner)) await window.electronAPI.getCindyMakeSourceStatus();
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) toast.error(t('cindyMake.merge.errors.unavailable'));
+ } finally {
+ mergeSubmitting.current = false;
+ setMergePending(false);
+ }
+ };
useEffect(() => {
void window.electronAPI.getCindyMakeSourceStatus?.().catch(() => undefined);
}, []);
+ const previousSourceStatus = useRef(sourceStatus?.status);
+ useEffect(() => {
+ const previous = previousSourceStatus.current;
+ previousSourceStatus.current = sourceStatus?.status;
+ if (previous === 'preparing' && sourceStatus?.status === 'ready') {
+ void window.electronAPI.getCindyMakeSourceStatus?.().catch(() => undefined);
+ }
+ }, [sourceStatus?.status]);
useEffect(() => {
if (sourceStatus?.status !== 'preparing') setSourceRunPending(false);
}, [sourceStatus]);
@@ -108,120 +186,202 @@ export function CindyMakeSection() {
<p className="mt-2 text-13 leading-[1.45] text-[var(--settings-section-desc)]">
{t('settings.cindyMake.description')}
</p>
- <Button className="mt-3" onClick={() => setCreateOpen(true)}>
- <Plus size={14} aria-hidden="true" />
- {t('settings.cindyMake.create.title')}
- </Button>
</div>
{createOpen && <CindyMakeCreateDialog onOpenChange={setCreateOpen} />}
+ <div
+ role="tablist"
+ aria-label={t('settings.cindyMake.title')}
+ className="flex flex-wrap gap-1"
+ >
+ {CINDY_MAKE_SETTINGS_TABS.map((tab, index) => (
+ <Button
+ key={tab}
+ ref={(button) => {
+ tabButtons.current[index] = button;
+ }}
+ id={tabId + '-' + tab + '-tab'}
+ role="tab"
+ aria-selected={activeTab === tab}
+ aria-controls={tabId + '-' + tab + '-panel'}
+ tabIndex={activeTab === tab ? 0 : -1}
+ className={
+ activeTab === tab
+ ? undefined
+ : 'border-transparent bg-transparent text-[var(--text-secondary)] enabled:hover:border-[var(--surface-hover)] enabled:hover:bg-[var(--surface-hover)] enabled:hover:text-[var(--text-primary)]'
+ }
+ onClick={() => setActiveTab(tab)}
+ onKeyDown={(event) => {
+ const rtl = getComputedStyle(event.currentTarget).direction === 'rtl';
+ let next: number;
+ switch (event.key) {
+ case 'ArrowRight':
+ next = index + (rtl ? -1 : 1);
+ break;
+ case 'ArrowLeft':
+ next = index + (rtl ? 1 : -1);
+ break;
+ case 'Home':
+ next = 0;
+ break;
+ case 'End':
+ next = CINDY_MAKE_SETTINGS_TABS.length - 1;
+ break;
+ default:
+ return;
+ }
+ event.preventDefault();
+ next = (next + CINDY_MAKE_SETTINGS_TABS.length) % CINDY_MAKE_SETTINGS_TABS.length;
+ tabButtons.current[next]?.focus();
+ setActiveTab(CINDY_MAKE_SETTINGS_TABS[next]);
+ }}
+ >
+ {t('settings.cindyMake.tabs.' + tab)}
+ </Button>
+ ))}
+ </div>
- {import.meta.env.DEV && (
- <div className="flex flex-col gap-3 rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] p-5">
- <div className="flex items-start justify-between gap-4">
- <div className="min-w-0">
- <p className="text-13 font-medium text-[var(--settings-section-sublabel)]">
- {t('settings.cindyMake.forceManaged.title')}
- </p>
- <p className="mt-1 text-12 leading-[1.45] text-[var(--settings-section-desc)]">
- {t('settings.cindyMake.forceManaged.description')}
- </p>
+ {/* Keep both panels mounted so tab navigation preserves checks and local UI state. */}
+ <div
+ role="tabpanel"
+ id={tabId + '-environment-panel'}
+ aria-labelledby={tabId + '-environment-tab'}
+ hidden={activeTab !== 'environment'}
+ >
+ <div className="flex flex-col gap-[18px]">
+ {import.meta.env.DEV && (
+ <div className="flex flex-col gap-3 rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] p-5">
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <p className="text-13 font-medium text-[var(--settings-section-sublabel)]">
+ {t('settings.cindyMake.forceManaged.title')}
+ </p>
+ <p className="mt-1 text-12 leading-[1.45] text-[var(--settings-section-desc)]">
+ {t('settings.cindyMake.forceManaged.description')}
+ </p>
+ </div>
+ <Switch
+ checked={forceManagedTools}
+ onCheckedChange={(checked) => {
+ // Toggling the developer switch is a diagnostic recheck. Never
+ // let it restart an in-progress preparation run implicitly.
+ setRunMode('check');
+ setTrackedPreparationId(undefined);
+ setForceManagedTools(checked);
+ }}
+ aria-label={t('settings.cindyMake.forceManaged.ariaLabel')}
+ />
+ </div>
+ {forceManagedTools ? (
+ <div className="space-y-2">
+ <p className="text-12 leading-[1.45] text-[var(--settings-section-desc)]">
+ {t('settings.cindyMake.forceManaged.enabledHint')}
+ </p>
+ </div>
+ ) : null}
</div>
- <Switch
- checked={forceManagedTools}
- onCheckedChange={(checked) => {
- // Toggling the developer switch is a diagnostic recheck. Never
- // let it restart an in-progress preparation run implicitly.
- setRunMode('check');
+ )}
+
+ {displayReport ? (
+ <MakeDoctorReportCard
+ report={displayReport}
+ showSource={false}
+ showSteps={false}
+ alwaysAllowRecheck
+ onPrepare={() => {
+ setDismissedPreparationId(undefined);
+ setRunMode('prepare');
+ setRunVersion((version) => version + 1);
+ }}
+ onOpenToolsDir={() => {
+ void window.electronAPI
+ .openCindyMakeToolsDir()
+ .then((result) => {
+ if (!result.success) toast.error(t('cindyMakeDoctor.failed'));
+ })
+ .catch(() => toast.error(t('cindyMakeDoctor.failed')));
+ }}
+ onStop={() => {
+ void cancelMakeDoctor(displayReport.runId, displayReport.mode).catch(() =>
+ toast.error(t('cindyMakeDoctor.failed')),
+ );
+ }}
+ onRecheck={() => {
+ setDismissedPreparationId(preparation?.report.runId);
setTrackedPreparationId(undefined);
- setForceManagedTools(checked);
+ setRunMode('check');
+ setCheckVersion((version) => version + 1);
}}
- aria-label={t('settings.cindyMake.forceManaged.ariaLabel')}
/>
- </div>
- {forceManagedTools ? (
- <div className="space-y-2">
- <p className="text-12 leading-[1.45] text-[var(--settings-section-desc)]">
- {t('settings.cindyMake.forceManaged.enabledHint')}
- </p>
+ ) : (
+ <div className="flex items-center gap-2 text-13 text-[var(--settings-section-desc)]">
+ <Spinner size={15} />
+ {t('settings.cindyMake.checking')}
</div>
- ) : null}
+ )}
+ <CindyMakeSourceStatusCard
+ status={sourceStatus}
+ preparing={sourceBusy}
+ merge={merge}
+ mergeBlocked={mergeBlocked}
+ onPrepare={() => {
+ if (!sourceStatus || sourceBusy) return;
+ if (sourceStatus.status === 'ready') {
+ void updateSource();
+ return;
+ }
+ setSourceRunPending(true);
+ setSourceRun({ makeAction: 'prepare-source', forceManagedTools });
+ }}
+ onStop={() => {
+ void Promise.resolve(window.electronAPI.cancelCindyMakeSource?.())
+ .then((result) => {
+ if (result && !result.success) setSourceRunPending(false);
+ })
+ .catch(() => toast.error(t('cindyMakeDoctor.failed')));
+ }}
+ onClear={async () => {
+ if (!sourceStatus || sourceBusy || mergeBlocked) return;
+ const confirmed = await confirm({
+ title: t('settings.cindyMake.source.resetConfirm.title'),
+ description: t('settings.cindyMake.source.resetConfirm.description'),
+ confirmText: t('settings.cindyMake.source.resetConfirm.confirm'),
+ cancelText: t('settings.cindyMake.source.resetConfirm.cancel'),
+ confirmVariant: 'destructive',
+ });
+ if (!confirmed) return;
+ setSourceRunPending(true);
+ setSourceRun({ makeAction: 'clear-source', forceManagedTools });
+ }}
+ />
</div>
- )}
-
- {displayReport ? (
- <MakeDoctorReportCard
- report={displayReport}
- showSource={false}
- showSteps={false}
- alwaysAllowRecheck
- onPrepare={() => {
- setDismissedPreparationId(undefined);
- setRunMode('prepare');
- setRunVersion((version) => version + 1);
- }}
- onOpenToolsDir={() => {
- void window.electronAPI
- .openCindyMakeToolsDir()
- .then((result) => {
- if (!result.success) toast.error(t('cindyMakeDoctor.failed'));
- })
- .catch(() => toast.error(t('cindyMakeDoctor.failed')));
- }}
- onStop={() => {
- void cancelMakeDoctor(displayReport.runId, displayReport.mode).catch(() =>
- toast.error(t('cindyMakeDoctor.failed')),
- );
- }}
- onRecheck={() => {
- setDismissedPreparationId(preparation?.report.runId);
- setTrackedPreparationId(undefined);
- setRunMode('check');
- setCheckVersion((version) => version + 1);
- }}
- />
- ) : (
- <div className="flex items-center gap-2 text-13 text-[var(--settings-section-desc)]">
- <Spinner size={15} />
- {t('settings.cindyMake.checking')}
+ </div>
+ <div
+ role="tabpanel"
+ id={tabId + '-versions-panel'}
+ aria-labelledby={tabId + '-versions-tab'}
+ hidden={activeTab !== 'versions'}
+ >
+ <div className="flex flex-col gap-[18px]">
+ <Button className="self-start" onClick={() => setCreateOpen(true)}>
+ <Plus size={14} aria-hidden="true" />
+ {t('settings.cindyMake.create.title')}
+ </Button>
+ <CindyMakeVersionsPanel
+ active={activeTab === 'versions'}
+ busy={historyState?.busy}
+ refreshKey={
+ historyState?.build?.status === 'ready'
+ ? String(
+ historyState.build.generatedAt ??
+ historyState.build.versionId ??
+ historyState.build.commit,
+ )
+ : undefined
+ }
+ />
+ <CindyMakeHistoryPanel active={activeTab === 'versions'} onState={setHistoryState} />
</div>
- )}
- {sourceStatus && (
- <CindyMakeSourceStatusCard
- status={sourceStatus}
- preparing={sourceBusy}
- onPrepare={() => {
- if (sourceBusy) return;
- setSourceRunPending(true);
- setSourceRun({ makeAction: 'prepare-source', forceManagedTools });
- }}
- onStop={() => {
- void Promise.resolve(window.electronAPI.cancelCindyMakeSource?.())
- .then((result) => {
- if (result && !result.success) setSourceRunPending(false);
- })
- .catch(() => toast.error(t('cindyMakeDoctor.failed')));
- }}
- onClear={async () => {
- if (sourceBusy) return;
- const confirmed = await confirm({
- title: t('settings.cindyMake.source.resetConfirm.title'),
- description: t('settings.cindyMake.source.resetConfirm.description'),
- confirmText: t('settings.cindyMake.source.resetConfirm.confirm'),
- cancelText: t('settings.cindyMake.source.resetConfirm.cancel'),
- confirmVariant: 'destructive',
- });
- if (!confirmed) return;
- setSourceRunPending(true);
- setSourceRun({ makeAction: 'clear-source', forceManagedTools });
- }}
- />
- )}
- {Object.keys(makeState.tasks ?? {}).length > 0 && (
- <CindyMakeTasksPanel
- reports={Object.values(makeState.tasks ?? {})}
- taskActions={makeState.taskActions}
- />
- )}
+ </div>
</div>
);
}
@@ -232,19 +392,23 @@ function CindyMakeSourceStatusCard({
onPrepare,
onStop,
onClear,
+ merge,
+ mergeBlocked = false,
}: {
- status: MakeSourceStatus;
+ status?: MakeSourceStatus;
preparing?: boolean;
onPrepare?: () => void;
onStop?: () => void;
onClear?: () => void | Promise<void>;
+ merge?: CindyMakeMergeState;
+ mergeBlocked?: boolean;
}) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(true);
- const displayStatus = preparing ? 'preparing' : status.status;
+ const displayStatus = preparing ? 'preparing' : status?.status;
// A click is pending before Main publishes the new run. Never reuse the last
// run's phase, counters or error in that window.
- const activeStatus = preparing && status.status === 'preparing' ? status : undefined;
+ const activeStatus = preparing && status?.status === 'preparing' ? status : undefined;
const statusClass =
displayStatus === 'ready'
? 'text-[var(--status-success)]'
@@ -282,73 +446,118 @@ function CindyMakeSourceStatusCard({
<p className="text-13 text-[var(--text-secondary)]">
{t('settings.cindyMake.source.description')}
</p>
- {(status.branch || status.commit || status.status === 'ready') && (
- <CindyMakeSourceDetails source={status} />
- )}
- <dl className="grid gap-1 text-12 text-[var(--text-tertiary)]">
- <div>
- <dt className="inline font-medium">{t('settings.cindyMake.source.path')}: </dt>
- <dd className="inline break-all font-mono">{status.path}</dd>
- </div>
- </dl>
- {activeStatus?.progress?.message && (
- <p className="break-all font-mono text-11 text-[var(--text-tertiary)]">
- {activeStatus.progress.message}
- </p>
+ {status && (
+ <>
+ {(status.branch || status.commit || status.status === 'ready') && (
+ <CindyMakeSourceDetails
+ source={status}
+ latestVersion={status.latestVersion}
+ updateAction={
+ status.status === 'ready' && onPrepare ? (
+ <Tip text={t('cindyMake.merge.updateHint')}>
+ <button
+ type="button"
+ aria-label={t('cindyMake.merge.getLatest')}
+ disabled={preparing || mergeBlocked}
+ onClick={onPrepare}
+ className="inline-flex h-6 w-6 items-center justify-center rounded-full text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] active:bg-[var(--surface-chip)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ <Download size={14} aria-hidden />
+ </button>
+ </Tip>
+ ) : undefined
+ }
+ />
+ )}
+ <dl className="grid gap-1 text-12 text-[var(--text-tertiary)]">
+ <div className="flex min-w-0 items-center gap-1">
+ <dt className="shrink-0 font-medium">{t('settings.cindyMake.source.path')}:</dt>
+ <dd className="flex min-w-0 flex-1 items-center gap-3">
+ <span className="min-w-0 flex-1 break-all font-mono">{status.path}</span>
+ <span className="inline-flex shrink-0 items-center gap-1">
+ <Tip text={t('settings.cindyMake.source.openDir')}>
+ <button
+ type="button"
+ onClick={openSourceDir}
+ aria-label={t('settings.cindyMake.source.openDir')}
+ className="inline-flex h-6 w-6 items-center justify-center rounded-full text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] active:bg-[var(--surface-chip)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <FolderOpen size={14} aria-hidden />
+ </button>
+ </Tip>
+ {/* Failed or cancelled preparation can leave a checkout to clear. */}
+ {onClear && !preparing && status.status !== 'missing' && (
+ <Tip text={t('settings.cindyMake.source.reset')}>
+ <button
+ type="button"
+ onClick={() => void onClear()}
+ disabled={mergeBlocked}
+ aria-label={t('settings.cindyMake.source.reset')}
+ className="inline-flex h-6 w-6 items-center justify-center rounded-full text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] active:bg-[var(--surface-chip)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ <Trash2 size={14} aria-hidden />
+ </button>
+ </Tip>
+ )}
+ </span>
+ </dd>
+ </div>
+ </dl>
+ {activeStatus?.progress?.message && (
+ <p className="break-all font-mono text-11 text-[var(--text-tertiary)]">
+ {activeStatus.progress.message}
+ </p>
+ )}
+ </>
)}
</div>
)}
- <div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--border-default)] px-4 py-3">
- <div className={`min-w-0 flex-1 space-y-1 text-13 ${statusClass}`} role="status">
- <div>
- {t(`settings.cindyMake.source.status.${displayStatus}`)}
- {activeStatus?.phase ? ` · ${t(`cindyMake.source.phase.${activeStatus.phase}`)}` : ''}
- {activeStatus?.progress && (
- <>
- {' · '}
- <span>{t(`cindyMake.source.gitProgress.${activeStatus.progress.stage}`)}</span>{' '}
- <span>({activeStatus.progress.percent}%)</span>
- </>
+ {merge && <CindyMakeMergeNotice state={merge} />}
+ {status && (
+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--border-default)] px-4 py-3">
+ <div className={`min-w-0 flex-1 space-y-1 text-13 ${statusClass}`} role="status">
+ <div>
+ {t(`settings.cindyMake.source.status.${displayStatus}`)}
+ {activeStatus?.phase ? ` · ${t(`cindyMake.source.phase.${activeStatus.phase}`)}` : ''}
+ {activeStatus?.progress && (
+ <>
+ {' · '}
+ <span>
+ {t(`cindyMake.source.gitProgress.${activeStatus.progress.stage}`)}
+ </span>{' '}
+ <span>({activeStatus.progress.percent}%)</span>
+ </>
+ )}
+ </div>
+ {!preparing && status.error && <p>{t(`cindyMake.source.errors.${status.error}`)}</p>}
+ {(activeStatus?.phase === 'installing' || activeStatus?.phase === 'caching') && (
+ <CindyMakeDependencyProgress
+ progress={activeStatus.dependencies}
+ running={activeStatus.phase === 'installing'}
+ cacheOnly={activeStatus.phase === 'caching'}
+ />
+ )}
+ </div>
+ <div className="flex shrink-0 flex-wrap justify-end gap-2">
+ {preparing && onStop && (
+ <Button variant="secondary" onClick={onStop}>
+ {t('settings.cindyMake.source.stop')}
+ </Button>
+ )}
+ {onPrepare && !preparing && status.status !== 'ready' && (
+ <Tip text={t('settings.cindyMake.source.description')}>
+ <Button variant="secondary" onClick={onPrepare} disabled={mergeBlocked}>
+ {t(
+ status.status === 'failed' || status.status === 'cancelled'
+ ? 'settings.cindyMake.source.retry'
+ : 'settings.cindyMake.source.prepare',
+ )}
+ </Button>
+ </Tip>
)}
</div>
- {!preparing && status.error && <p>{t(`cindyMake.source.errors.${status.error}`)}</p>}
- {(activeStatus?.phase === 'installing' || activeStatus?.phase === 'caching') && (
- <CindyMakeDependencyProgress
- progress={activeStatus.dependencies}
- running={activeStatus.phase === 'installing'}
- cacheOnly={activeStatus.phase === 'caching'}
- />
- )}
- </div>
- <div className="flex shrink-0 flex-wrap justify-end gap-2">
- <Button variant="secondary" onClick={openSourceDir}>
- {t('settings.cindyMake.source.openDir')}
- </Button>
- {preparing && onStop && (
- <Button variant="secondary" onClick={onStop}>
- {t('settings.cindyMake.source.stop')}
- </Button>
- )}
- {onPrepare && !preparing && (
- <Button variant="secondary" onClick={onPrepare}>
- {t(
- status.status === 'ready'
- ? 'settings.cindyMake.source.update'
- : status.status === 'failed' || status.status === 'cancelled'
- ? 'settings.cindyMake.source.retry'
- : 'settings.cindyMake.source.prepare',
- )}
- </Button>
- )}
- {/* A failed or cancelled preparation still leaves a checkout behind; clearing
- it is the documented way out of a dirty tree, so the button must stay. */}
- {onClear && !preparing && status.status !== 'missing' && (
- <Button variant="secondary" disabled={preparing} onClick={() => void onClear()}>
- {t('settings.cindyMake.source.reset')}
- </Button>
- )}
</div>
- </div>
+ )}
</section>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CindyMakeSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CindyMakeSection.test.tsx
index 9bc0ded5f7..0cb97802fc 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/CindyMakeSection.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/CindyMakeSection.test.tsx
@@ -2,7 +2,9 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';
+import { isValidElement } from 'react';
import { CindyMakeSection } from '../CindyMakeSection';
+import type { CindyMakeMergeState, CindyMakeMergeRequest } from '../../../../shared/cindyMakeMerge';
import { startMakeDoctor } from '@/lib/cindyMakeDoctor';
import { setCindyMakeForceManagedTools } from '@/lib/cindyMakeSettings';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
@@ -14,6 +16,7 @@ import type {
vi.mock('react-i18next', () => ({
useTranslation: () => ({
+ i18n: { language: 'en' },
t: (key: string, values?: { resolved: number; reused: number; downloaded: number }) =>
key === 'cindyMake.source.cacheProgress' && values
? `${key} ${values.resolved} / ${values.reused} / ${values.downloaded}`
@@ -21,9 +24,17 @@ vi.mock('react-i18next', () => ({
}),
}));
vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));
+vi.mock('@/state/newMakerDraft', () => ({
+ getDraft: () => ({
+ vendor: 'codex',
+ lastByVendor: { codex: { model: 'test-model', permissionMode: 'ask' } },
+ }),
+ getFastModeForModel: () => false,
+}));
+const confirmMerge = vi.hoisted(() => vi.fn(async () => true));
vi.mock('@/components/ui/confirm-dialog-provider', () => ({
useConfirmDialog: () => ({
- confirm: vi.fn(async () => true),
+ confirm: confirmMerge,
}),
}));
@@ -38,6 +49,10 @@ function harness() {
let globalState: CindyMakeGlobalState = {};
const runs = new Map<string, (result: Result) => void>();
const api = {
+ cindyMakeMerge: vi.fn(
+ async (_request: CindyMakeMergeRequest): Promise<CindyMakeMergeState | undefined> =>
+ undefined,
+ ),
getCindyMakeState: vi.fn(async (): Promise<CindyMakeGlobalState> => ({
...globalState,
source: globalState.source ?? (await api.getCindyMakeSourceStatus()),
@@ -72,6 +87,28 @@ function harness() {
}),
};
vi.stubGlobal('electronAPI', {
+ getCindyMakeHistory: async () => ({
+ busy: false,
+ canBuild: false,
+ items: Object.values(globalState.tasks ?? {})
+ .filter((report) => report.task)
+ .map((report) => ({
+ schema: 1,
+ runId: report.runId,
+ sessionId: report.task!.sessionId,
+ title: report.task!.title ?? '',
+ request: report.task!.request ?? '',
+ createdAt: 1,
+ updatedAt: 1,
+ completions: [],
+ receipts: [],
+ versions: [],
+ lifecycle: 'editing',
+ integration: 'unintegrated',
+ actions: ['open'],
+ })),
+ }),
+ cindyMakeMerge: api.cindyMakeMerge,
maker: api,
getCindyMakeState: api.getCindyMakeState,
onCindyMakeState: api.onCindyMakeState,
@@ -92,6 +129,7 @@ function harness() {
/** Main's global source broadcast, whichever window or workflow drives the job. */
const pushSource = async (status: MakeSourceStatus) => {
await act(async () => {
+ api.getCindyMakeSourceStatus.mockResolvedValue(status);
for (const listener of sourceListeners) listener(status);
globalState = { ...globalState, source: status };
for (const listener of stateListeners) listener(globalState);
@@ -122,6 +160,15 @@ function harness() {
return { api, starts, complete, listeners, pushSource, pushState, stateListeners };
}
+/** Environment-specific cases explicitly enter the second tab after opening Settings. */
+function renderEnvironment(ui: Parameters<typeof render>[0]) {
+ const view = render(
+ isValidElement(ui) && ui.type === MemoryRouter ? ui : <MemoryRouter>{ui}</MemoryRouter>,
+ );
+ fireEvent.click(screen.getByRole('tab', { name: 'settings.cindyMake.tabs.environment' }));
+ return view;
+}
+
beforeEach(() => {
setDataOwnerGeneration('settings-make-test-owner');
vi.stubEnv('DEV', true);
@@ -135,6 +182,282 @@ afterEach(() => {
});
describe('Settings > Cindy Make', () => {
+ it('opens version control first and preserves the keyboard tab order and scoped creation action', async () => {
+ const h = harness();
+ const getVersions = vi.fn(async () => ({
+ currentId: 'original',
+ selectedId: 'original',
+ switching: false,
+ versions: [
+ { id: 'original', kind: 'original', available: true, compatible: true, version: '0.1.99' },
+ ],
+ }));
+ vi.stubGlobal('electronAPI', { ...window.electronAPI, getCindyVersions: getVersions });
+ render(
+ <MemoryRouter>
+ <CindyMakeSection />
+ </MemoryRouter>,
+ );
+ await h.complete(h.starts()[0][1].doctorRunId!, '22.23.2');
+ const environment = screen.getByRole('tab', { name: 'settings.cindyMake.tabs.environment' });
+ const versions = screen.getByRole('tab', { name: 'settings.cindyMake.tabs.versions' });
+ expect(screen.getAllByRole('tab')).toEqual([versions, environment]);
+ expect(versions.getAttribute('aria-selected')).toBe('true');
+ expect(versions.getAttribute('aria-controls')).toBe(
+ screen.getByRole('tabpanel', { name: 'settings.cindyMake.tabs.versions' }).id,
+ );
+ expect(screen.getAllByRole('tabpanel')).toHaveLength(1);
+ expect(screen.queryByRole('region', { name: 'settings.cindyMake.source.title' })).toBeNull();
+ expect(screen.queryByRole('switch')).toBeNull();
+ expect(await screen.findByText('0.1.99')).toBeTruthy();
+ expect(
+ within(screen.getByRole('tabpanel', { name: 'settings.cindyMake.tabs.versions' })).getByRole(
+ 'button',
+ { name: 'settings.cindyMake.create.title' },
+ ),
+ ).toBeTruthy();
+
+ expect(getVersions).toHaveBeenCalledTimes(1);
+ versions.focus();
+ fireEvent.keyDown(versions, { key: 'ArrowRight' });
+ expect(document.activeElement).toBe(environment);
+ const environmentPanel = screen.getByRole('tabpanel', {
+ name: 'settings.cindyMake.tabs.environment',
+ });
+ expect(environment.getAttribute('aria-selected')).toBe('true');
+ expect(environment.getAttribute('aria-controls')).toBe(environmentPanel.id);
+ expect(screen.getByRole('region', { name: 'settings.cindyMake.source.title' })).toBeTruthy();
+ expect(screen.queryByRole('heading', { name: 'cindyMake.versions.title' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'settings.cindyMake.create.title' })).toBeNull();
+ fireEvent.keyDown(environment, { key: 'ArrowRight' });
+ expect(document.activeElement).toBe(versions);
+ await waitFor(() => expect(getVersions).toHaveBeenCalledTimes(2));
+ fireEvent.keyDown(versions, { key: 'End' });
+ expect(document.activeElement).toBe(environment);
+ expect(screen.getByRole('tabpanel', { name: 'settings.cindyMake.tabs.environment' })).toBe(
+ environmentPanel,
+ );
+ fireEvent.keyDown(environment, { key: 'Home' });
+ expect(document.activeElement).toBe(versions);
+ await waitFor(() => expect(getVersions).toHaveBeenCalledTimes(3));
+ expect(h.starts()).toHaveLength(1);
+ });
+ it('keeps background preparation, expansion and task search intact while switching tabs', async () => {
+ const h = harness();
+ renderEnvironment(
+ <MemoryRouter>
+ <CindyMakeSection />
+ </MemoryRouter>,
+ );
+ const checkRun = h.starts()[0][1].doctorRunId!;
+ await h.complete(checkRun, '22.23.2');
+ const task: MakeDoctorReport = {
+ runId: 'personal-run',
+ platform: 'win32',
+ arch: 'x64',
+ status: 'completed',
+ checks: [],
+ task: {
+ sessionId: 'personal-task',
+ title: 'Blue background',
+ request: 'Make it blue',
+ phase: 'completed',
+ },
+ };
+ await h.pushState({
+ source: {
+ status: 'preparing',
+ path: '/managed/source',
+ ref: 'main',
+ phase: 'cloning',
+ progress: { stage: 'receiving', percent: 25 },
+ },
+ tasks: { 'personal-run': task },
+ });
+ const sourceCard = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
+ const expand = within(sourceCard).getByRole('button', {
+ name: 'settings.cindyMake.source.title',
+ });
+ fireEvent.click(expand);
+ expect(expand.getAttribute('aria-expanded')).toBe('false');
+ fireEvent.click(screen.getByRole('tab', { name: 'settings.cindyMake.tabs.versions' }));
+ expect(screen.queryByRole('region', { name: 'settings.cindyMake.source.title' })).toBeNull();
+ const tasks = screen.getByRole('region', { name: 'cindyMake.history.title' });
+ fireEvent.change(within(tasks).getByRole('textbox'), { target: { value: 'Blue' } });
+ await h.pushSource({
+ status: 'preparing',
+ path: '/managed/source',
+ ref: 'main',
+ phase: 'cloning',
+ progress: { stage: 'receiving', percent: 75 },
+ });
+ fireEvent.click(screen.getByRole('tab', { name: 'settings.cindyMake.tabs.environment' }));
+ expect(screen.getByRole('region', { name: 'settings.cindyMake.source.title' })).toBe(
+ sourceCard,
+ );
+ expect(expand.getAttribute('aria-expanded')).toBe('false');
+ expect(within(sourceCard).getByRole('status').textContent).toContain('(75%)');
+ expect(screen.queryByRole('region', { name: 'cindyMake.history.title' })).toBeNull();
+ fireEvent.click(screen.getByRole('tab', { name: 'settings.cindyMake.tabs.versions' }));
+ expect((within(tasks).getByRole('textbox') as HTMLInputElement).value).toBe('Blue');
+ expect(h.starts()).toHaveLength(1);
+ expect(
+ h.api.executeDesktopCommand.mock.calls.some(
+ ([, context]) => context.doctorAction === 'cancel',
+ ),
+ ).toBe(false);
+ expect(h.api.cancelCindyMakeSource).not.toHaveBeenCalled();
+ });
+ it('keeps only the update icon, confirms it and does nothing on cancel', async () => {
+ const h = harness();
+ const source: MakeSourceStatus = {
+ status: 'ready',
+ path: '/managed/source',
+ ref: 'main',
+ commit: 'a'.repeat(40),
+ };
+ h.api.getCindyMakeSourceStatus.mockResolvedValue(source);
+ renderEnvironment(<CindyMakeSection />);
+ const button = await screen.findByRole('button', { name: 'cindyMake.merge.getLatest' });
+ expect(screen.getAllByRole('button', { name: 'cindyMake.merge.getLatest' })).toHaveLength(1);
+ expect(screen.queryByRole('button', { name: 'settings.cindyMake.source.update' })).toBeNull();
+ confirmMerge.mockResolvedValueOnce(false);
+ fireEvent.click(button);
+ await waitFor(() =>
+ expect(confirmMerge).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: 'cindyMake.merge.confirmTitle',
+ description: 'cindyMake.merge.confirmDescription',
+ }),
+ ),
+ );
+ expect(h.api.cindyMakeMerge).not.toHaveBeenCalled();
+ fireEvent.click(button);
+ await waitFor(() =>
+ expect(h.api.cindyMakeMerge).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'update',
+ createOptions: expect.objectContaining({ agentKind: 'codex', model: 'test-model' }),
+ }),
+ ),
+ );
+ expect(h.starts().filter(([, ctx]) => ctx.makeAction === 'prepare-source')).toHaveLength(0);
+ });
+ it('shows the source card immediately and keeps local details visible while the latest lookup waits', async () => {
+ const h = harness();
+ let finish!: (source: MakeSourceStatus) => void;
+ const pending = new Promise<MakeSourceStatus>((resolve) => {
+ finish = resolve;
+ });
+ h.api.getCindyMakeSourceStatus.mockReturnValue(pending);
+ renderEnvironment(<CindyMakeSection />);
+ const card = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
+ expect(within(card).getByText('settings.cindyMake.source.description')).toBeTruthy();
+ expect(within(card).queryByRole('status')).toBeNull();
+ expect(
+ within(card).queryByRole('button', { name: 'settings.cindyMake.source.prepare' }),
+ ).toBeNull();
+ expect(within(card).queryByRole('button', { name: 'cindyMake.merge.getLatest' })).toBeNull();
+
+ const source: MakeSourceStatus = {
+ status: 'ready',
+ path: '/managed/source',
+ ref: 'main',
+ mainCommit: 'a'.repeat(40),
+ };
+ await h.pushState({ source });
+ expect(within(card).getByText(source.path)).toBeTruthy();
+ expect(within(card).getByText('a'.repeat(12))).toBeTruthy();
+ expect(within(card).getByRole('button', { name: 'cindyMake.merge.getLatest' })).toBeTruthy();
+ await act(async () =>
+ finish({
+ ...source,
+ latestVersion: { status: 'unavailable', channel: 'dev' },
+ }),
+ );
+ expect(screen.getByRole('region', { name: 'settings.cindyMake.source.title' })).toBe(card);
+ expect(within(card).getByText('a'.repeat(12))).toBeTruthy();
+ expect(within(card).getByText('cindyMake.source.details.latest.unavailable')).toBeTruthy();
+ });
+ it('offers conflict resolution only after a conflict and creates a task only on click', async () => {
+ const h = harness();
+ const source: MakeSourceStatus = { status: 'ready', path: '/managed/source', ref: 'main' };
+ const merge: CindyMakeMergeState = {
+ id: 'merge',
+ status: 'conflict',
+ ref: 'main',
+ upstreamCommit: 'a'.repeat(40),
+ hasWorkspace: true,
+ };
+ renderEnvironment(
+ <MemoryRouter>
+ <CindyMakeSection />
+ </MemoryRouter>,
+ );
+ await h.pushState({ source, upstreamMerge: merge });
+ expect(screen.getByText('cindyMake.merge.status.conflict')).toBeTruthy();
+ expect(h.api.cindyMakeMerge).not.toHaveBeenCalled();
+ expect(
+ screen.getByRole('button', { name: 'cindyMake.merge.getLatest' }).hasAttribute('disabled'),
+ ).toBe(true);
+ h.api.cindyMakeMerge.mockResolvedValue({
+ ...merge,
+ status: 'resolving',
+ sessionId: 'merge-task',
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.merge.resolve' }));
+ await waitFor(() =>
+ expect(h.api.cindyMakeMerge).toHaveBeenCalledWith(
+ expect.objectContaining({ action: 'resolve' }),
+ ),
+ );
+ });
+ it.each(['resolving', 'failed'] as const)(
+ 'keeps a %s upstream task outside the unfinished production list',
+ async (status) => {
+ const h = harness();
+ const merge: CindyMakeMergeState = {
+ id: 'abcd-merge',
+ status,
+ ref: 'main',
+ upstreamCommit: 'a'.repeat(40),
+ hasWorkspace: true,
+ sessionId: 'merge-task',
+ };
+ h.api.getCindyMakeState.mockResolvedValue({ upstreamMerge: merge });
+ renderEnvironment(
+ <MemoryRouter>
+ <CindyMakeSection />
+ </MemoryRouter>,
+ );
+ expect(await screen.findByRole('button', { name: 'cindyMake.merge.openTask' })).toBeTruthy();
+ fireEvent.click(screen.getByRole('tab', { name: 'settings.cindyMake.tabs.versions' }));
+ expect(screen.getByRole('heading', { name: 'cindyMake.history.title · 0' })).toBeTruthy();
+ const report: MakeDoctorReport = {
+ runId: 'make-run',
+ platform: 'win32',
+ arch: 'x64',
+ status: 'completed',
+ checks: [],
+ task: {
+ sessionId: 'make-task',
+ title: 'Personal feature',
+ request: 'A change',
+ phase: 'completed',
+ },
+ };
+ await h.pushState({ upstreamMerge: merge, tasks: { 'make-run': report } });
+ const panel = screen.getByRole('region', { name: 'cindyMake.history.title' });
+ expect(
+ await within(panel).findByRole('heading', { name: 'cindyMake.history.title · 1' }),
+ ).toBeTruthy();
+ expect(within(panel).getByRole('button', { name: /Personal feature/ })).toBeTruthy();
+ expect(within(panel).queryByText('cindyMake.merge.taskTitle')).toBeNull();
+ expect(within(panel).queryByRole('button', { name: 'cindyMake.merge.openTask' })).toBeNull();
+ expect(h.api.cindyMakeMerge).not.toHaveBeenCalled();
+ },
+ );
+
it.each(['missing', 'passed'] as const)(
'shows the new %s check instead of a completed preparation from before entry',
async (status) => {
@@ -148,7 +471,7 @@ describe('Settings > Cindy Make', () => {
checks: [{ id: 'node', status: status === 'missing' ? 'passed' : 'missing' }],
};
await environment.pushState({ environmentPrepare: { active: false, report: preparation } });
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
const runId = environment.starts()[0][1].doctorRunId!;
await environment.complete(runId, '', [{ id: 'node', status }]);
await environment.pushState({
@@ -174,7 +497,7 @@ describe('Settings > Cindy Make', () => {
it('restores a background installation after reentry, keeps completion, and stops the real run', async () => {
const environment = harness();
- const first = render(<CindyMakeSection />);
+ const first = renderEnvironment(<CindyMakeSection />);
await environment.complete(environment.starts()[0][1].doctorRunId!, '', [
{ id: 'node', status: 'missing' },
]);
@@ -193,7 +516,7 @@ describe('Settings > Cindy Make', () => {
await environment.pushState({ environmentPrepare: { active: true, report: preparation } });
first.unmount();
expect(environment.stateListeners.size).toBe(0);
- const second = render(<CindyMakeSection />);
+ const second = renderEnvironment(<CindyMakeSection />);
await screen.findByText('cindyMake.prepare.stop');
const reentryCheckId = environment.starts()[2][1].doctorRunId!;
await environment.complete(reentryCheckId, '', [{ id: 'node', status: 'missing' }]);
@@ -243,7 +566,7 @@ describe('Settings > Cindy Make', () => {
resolveSnapshot = resolve;
}),
);
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
const preparation: MakeDoctorReport = {
runId: 'new-preparation',
mode: 'prepare',
@@ -277,7 +600,7 @@ describe('Settings > Cindy Make', () => {
resolveSnapshot = resolve;
}),
);
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
const preparation: MakeDoctorReport = {
runId: 'finishing-preparation',
mode: 'prepare',
@@ -316,7 +639,7 @@ describe('Settings > Cindy Make', () => {
resolveSnapshot = resolve;
}),
);
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
const preparation: MakeDoctorReport = {
runId: 'completed-preparation',
mode: 'prepare',
@@ -349,11 +672,12 @@ describe('Settings > Cindy Make', () => {
it('offers an explicit creation form without starting preparation on open or cancel', async () => {
const environment = harness();
- render(
+ renderEnvironment(
<MemoryRouter>
<CindyMakeSection />
</MemoryRouter>,
);
+ fireEvent.click(screen.getByRole('tab', { name: 'settings.cindyMake.tabs.versions' }));
const entry = screen.getByRole('button', { name: 'settings.cindyMake.create.title' });
entry.focus();
fireEvent.click(entry);
@@ -368,7 +692,7 @@ describe('Settings > Cindy Make', () => {
it('checks on each entry without creating a task or starting preparation, and allows recheck after all passed', async () => {
const h = harness();
- const first = render(<CindyMakeSection />);
+ const first = renderEnvironment(<CindyMakeSection />);
expect(h.starts()).toHaveLength(1);
expect(h.starts()[0][0]).toBe('cindy-make-doctor');
await h.complete(h.starts()[0][1].doctorRunId!, '22.23.2');
@@ -385,14 +709,14 @@ describe('Settings > Cindy Make', () => {
fireEvent.click(screen.getByText('cindyMakeDoctor.recheck'));
expect(h.starts()).toHaveLength(2);
first.unmount();
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
expect(h.starts()).toHaveLength(3);
expect(h.starts().every(([name]) => name === 'cindy-make-doctor')).toBe(true);
});
it('opens Cindy’s managed tools folder from the section header', async () => {
const h = harness();
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
await h.complete(h.starts()[0][1].doctorRunId!, '22.23.2');
fireEvent.click(screen.getByText('settings.cindyMake.openToolsDir'));
expect(h.api.openCindyMakeToolsDir).toHaveBeenCalledTimes(1);
@@ -414,10 +738,19 @@ describe('Settings > Cindy Make', () => {
mainRemoteCommit: 'd'.repeat(40),
mainBehind: 3,
mainAhead: 0,
+ latestVersion: {
+ status: 'ready',
+ channel: 'dev',
+ ref: 'main',
+ commit: 'f'.repeat(40),
+ ahead: 0,
+ behind: 6,
+ },
};
h.api.getCindyMakeSourceStatus = vi.fn(async () => source);
h.api.openCindyMakeSourceDir = vi.fn(async () => ({ success: true }));
vi.stubGlobal('electronAPI', {
+ cindyMakeMerge: h.api.cindyMakeMerge,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -427,10 +760,11 @@ describe('Settings > Cindy Make', () => {
onCindyMakeSourceStatus: h.api.onCindyMakeSourceStatus,
cancelCindyMakeSource: h.api.cancelCindyMakeSource,
});
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
await waitFor(() => expect(screen.getByText('c'.repeat(12))).toBeTruthy());
const sourceCard = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
expect(within(sourceCard).getByText('cindy-personal')).toBeTruthy();
+ expect(within(sourceCard).getByText('f'.repeat(12))).toBeTruthy();
for (const hash of [source.baseCommit, source.mainCommit]) {
expect(within(sourceCard).getByText(hash!.slice(0, 12))).toBeTruthy();
}
@@ -446,23 +780,40 @@ describe('Settings > Cindy Make', () => {
expect(within(sourceCard).getByText('e'.repeat(12))).toBeTruthy();
const statusLine = within(sourceCard).getByRole('status');
const footer = statusLine.parentElement!;
- const openButton = within(sourceCard).getByText('settings.cindyMake.source.openDir');
- const updateButton = within(sourceCard).getByText('settings.cindyMake.source.update');
- const resetButton = within(sourceCard).getByText('settings.cindyMake.source.reset');
+ const openButton = within(sourceCard).getByRole('button', {
+ name: 'settings.cindyMake.source.openDir',
+ });
+ const updateButton = within(sourceCard).getByRole('button', {
+ name: 'cindyMake.merge.getLatest',
+ });
+ const resetButton = within(sourceCard).getByRole('button', {
+ name: 'settings.cindyMake.source.reset',
+ });
+ const pathDetails = within(sourceCard).getByText(source.path).closest('dd')!;
expect(statusLine.textContent).toBe('settings.cindyMake.source.status.ready');
- expect(footer.contains(openButton)).toBe(true);
- expect(footer.contains(updateButton)).toBe(true);
- expect(footer.contains(resetButton)).toBe(true);
+ expect(pathDetails.contains(openButton)).toBe(true);
+ expect(pathDetails.contains(resetButton)).toBe(true);
+ expect(footer.contains(openButton)).toBe(false);
+ expect(footer.contains(updateButton)).toBe(false);
+ expect(footer.contains(resetButton)).toBe(false);
+
+ fireEvent.click(openButton);
+ expect(h.api.openCindyMakeSourceDir).toHaveBeenCalledTimes(1);
fireEvent.click(
within(sourceCard).getByRole('button', { name: 'settings.cindyMake.source.title' }),
);
expect(within(sourceCard).queryByText('e'.repeat(12))).toBeNull();
expect(within(sourceCard).getByRole('status')).toBeTruthy();
- expect(within(sourceCard).getByText('settings.cindyMake.source.openDir')).toBeTruthy();
-
- fireEvent.click(openButton);
- expect(h.api.openCindyMakeSourceDir).toHaveBeenCalledTimes(1);
+ expect(
+ within(sourceCard).queryByRole('button', { name: 'settings.cindyMake.source.openDir' }),
+ ).toBeNull();
+ expect(
+ within(sourceCard).queryByRole('button', { name: 'settings.cindyMake.source.reset' }),
+ ).toBeNull();
+ expect(
+ within(sourceCard).queryByRole('button', { name: 'cindyMake.merge.getLatest' }),
+ ).toBeNull();
});
it.each(['waiting', 'checkingRemote', 'checkingLocal', 'cloning', 'installing'] as const)(
@@ -475,7 +826,7 @@ describe('Settings > Cindy Make', () => {
ref: 'main',
phase,
});
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
const sourceCard = await screen.findByRole('region', {
name: 'settings.cindyMake.source.title',
});
@@ -483,14 +834,18 @@ describe('Settings > Cindy Make', () => {
within(sourceCard).getByText(new RegExp('cindyMake.source.phase.' + phase)),
).toBeTruthy();
expect(within(sourceCard).queryByText('settings.cindyMake.source.prepare')).toBeNull();
- expect(within(sourceCard).queryByText('settings.cindyMake.source.reset')).toBeNull();
+ expect(
+ within(sourceCard).queryByRole('button', { name: 'settings.cindyMake.source.reset' }),
+ ).toBeNull();
fireEvent.click(within(sourceCard).getByText('settings.cindyMake.source.stop'));
expect(h.api.cancelCindyMakeSource).toHaveBeenCalledTimes(1);
// Settings itself never started a doctor run for this job.
expect(h.starts().filter(([name]) => name === 'cindy-make')).toHaveLength(0);
await h.pushSource({ status: 'cancelled', path: 'C:\\managed\\source', error: 'cancelled' });
expect(within(sourceCard).getByText('settings.cindyMake.source.retry')).toBeTruthy();
- expect(within(sourceCard).getByText('settings.cindyMake.source.reset')).toBeTruthy();
+ expect(
+ within(sourceCard).getByRole('button', { name: 'settings.cindyMake.source.reset' }),
+ ).toBeTruthy();
},
);
@@ -509,7 +864,7 @@ describe('Settings > Cindy Make', () => {
dependencies: { resolved: 21, reused: 12, downloaded: 9, added: 0 },
};
h.api.getCindyMakeSourceStatus.mockResolvedValue(source);
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
const sourceCard = await screen.findByRole('region', {
name: 'settings.cindyMake.source.title',
});
@@ -531,11 +886,21 @@ describe('Settings > Cindy Make', () => {
'cindyMake.source.phase.checkingRemote',
);
expect(within(sourceCard).queryByText('cindyMake.source.errors.' + error)).toBeNull();
+ const sourceReads = h.api.getCindyMakeSourceStatus.mock.calls.length;
await h.pushSource({ status: 'ready', path: source.path });
+ expect(h.api.getCindyMakeSourceStatus).toHaveBeenCalledTimes(sourceReads + 1);
expect(within(sourceCard).getByRole('status').textContent).toBe(
'settings.cindyMake.source.status.ready',
);
- expect(within(sourceCard).getByText('settings.cindyMake.source.update')).toBeTruthy();
+ expect(
+ within(sourceCard).queryByRole('button', { name: 'cindyMake.merge.getLatest' }),
+ ).toBeNull();
+ fireEvent.click(
+ within(sourceCard).getByRole('button', { name: 'settings.cindyMake.source.title' }),
+ );
+ expect(
+ within(sourceCard).getByRole('button', { name: 'cindyMake.merge.getLatest' }),
+ ).toBeTruthy();
},
);
@@ -551,6 +916,7 @@ describe('Settings > Cindy Make', () => {
};
h.api.getCindyMakeSourceStatus = vi.fn(async () => source);
vi.stubGlobal('electronAPI', {
+ cindyMakeMerge: h.api.cindyMakeMerge,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -560,10 +926,12 @@ describe('Settings > Cindy Make', () => {
onCindyMakeSourceStatus: h.api.onCindyMakeSourceStatus,
cancelCindyMakeSource: h.api.cancelCindyMakeSource,
});
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
await waitFor(() => expect(screen.getByText('cindyMake.source.errors.dirty')).toBeTruthy());
const sourceCard = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
- expect(within(sourceCard).getByText('settings.cindyMake.source.reset')).toBeTruthy();
+ expect(
+ within(sourceCard).getByRole('button', { name: 'settings.cindyMake.source.reset' }),
+ ).toBeTruthy();
});
it('prepares missing source and updates an existing source through the shared Make action', async () => {
@@ -574,6 +942,7 @@ describe('Settings > Cindy Make', () => {
};
h.api.getCindyMakeSourceStatus = vi.fn(async () => source);
vi.stubGlobal('electronAPI', {
+ cindyMakeMerge: h.api.cindyMakeMerge,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -583,7 +952,7 @@ describe('Settings > Cindy Make', () => {
onCindyMakeSourceStatus: h.api.onCindyMakeSourceStatus,
cancelCindyMakeSource: h.api.cancelCindyMakeSource,
});
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
await waitFor(() => expect(screen.getByText('settings.cindyMake.source.prepare')).toBeTruthy());
fireEvent.click(screen.getByText('settings.cindyMake.source.prepare'));
expect(screen.getByText('settings.cindyMake.source.stop')).toBeTruthy();
@@ -595,6 +964,7 @@ describe('Settings > Cindy Make', () => {
const ready: MakeSourceStatus = { ...source, status: 'ready', commit: '0123456789abcdef' };
h.api.getCindyMakeSourceStatus = vi.fn(async () => ready);
vi.stubGlobal('electronAPI', {
+ cindyMakeMerge: h.api.cindyMakeMerge,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -604,12 +974,17 @@ describe('Settings > Cindy Make', () => {
onCindyMakeSourceStatus: h.api.onCindyMakeSourceStatus,
cancelCindyMakeSource: h.api.cancelCindyMakeSource,
});
- render(<CindyMakeSection />);
- await waitFor(() => expect(screen.getByText('settings.cindyMake.source.update')).toBeTruthy());
- fireEvent.click(screen.getByText('settings.cindyMake.source.update'));
- expect(h.starts()).toHaveLength(4);
- expect(h.starts()[3][0]).toBe('cindy-make');
- expect(h.starts()[3][1].makeAction).toBe('prepare-source');
+ renderEnvironment(<CindyMakeSection />);
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'cindyMake.merge.getLatest' })).toBeTruthy(),
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.merge.getLatest' }));
+ await waitFor(() =>
+ expect(h.api.cindyMakeMerge).toHaveBeenCalledWith(
+ expect.objectContaining({ action: 'update' }),
+ ),
+ );
+ expect(h.starts()).toHaveLength(3);
});
it('confirms and starts clearing the source without re-pulling it', async () => {
@@ -623,6 +998,7 @@ describe('Settings > Cindy Make', () => {
};
h.api.getCindyMakeSourceStatus = vi.fn(async () => source);
vi.stubGlobal('electronAPI', {
+ cindyMakeMerge: h.api.cindyMakeMerge,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -632,9 +1008,8 @@ describe('Settings > Cindy Make', () => {
onCindyMakeSourceStatus: h.api.onCindyMakeSourceStatus,
cancelCindyMakeSource: h.api.cancelCindyMakeSource,
});
- render(<CindyMakeSection />);
- await waitFor(() => expect(screen.getByText('settings.cindyMake.source.reset')).toBeTruthy());
- fireEvent.click(screen.getByText('settings.cindyMake.source.reset'));
+ renderEnvironment(<CindyMakeSection />);
+ fireEvent.click(await screen.findByRole('button', { name: 'settings.cindyMake.source.reset' }));
await waitFor(() => expect(h.starts()).toHaveLength(2));
expect(h.starts()[1][0]).toBe('cindy-make');
expect(h.starts()[1][1].makeAction).toBe('clear-source');
@@ -644,7 +1019,7 @@ describe('Settings > Cindy Make', () => {
const h = harness();
const source: MakeSourceStatus = { status: 'ready', path: 'C:\\managed\\source', ref: 'main' };
h.api.getCindyMakeSourceStatus.mockResolvedValue(source);
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
await h.complete(h.starts()[0][1].doctorRunId!, '22.23.2', [
{ id: 'node', status: 'passed', version: '22.23.2' },
{ id: 'native', status: 'missing' },
@@ -652,7 +1027,7 @@ describe('Settings > Cindy Make', () => {
const environmentCard = screen.getByRole('region', { name: 'cindyMakeDoctor.title' });
const previousEnvironment = environmentCard.textContent;
const sourceCard = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
- fireEvent.click(within(sourceCard).getByText('settings.cindyMake.source.update'));
+ fireEvent.click(within(sourceCard).getByRole('button', { name: 'cindyMake.merge.getLatest' }));
fireEvent.click(
within(sourceCard).getByRole('button', { name: 'settings.cindyMake.source.title' }),
);
@@ -689,7 +1064,7 @@ describe('Settings > Cindy Make', () => {
expect(environmentCard.textContent).toBe(previousEnvironment);
fireEvent.click(within(sourceCard).getByText('settings.cindyMake.source.retry'));
expect(within(sourceCard).queryByText('cindyMake.source.errors.gitUnavailable')).toBeNull();
- expect(h.starts()).toHaveLength(3);
+ expect(h.starts()).toHaveLength(2);
expect(
h
.starts()
@@ -706,7 +1081,7 @@ describe('Settings > Cindy Make', () => {
status: 'missing',
path: 'C:\\managed\\source',
});
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
await waitFor(() => expect(screen.getByText('settings.cindyMake.source.prepare')).toBeTruthy());
fireEvent.click(screen.getByText('settings.cindyMake.source.prepare'));
expect(h.starts()).toHaveLength(2);
@@ -729,7 +1104,7 @@ describe('Settings > Cindy Make', () => {
it('does not restore a previously tracked completion after switching check modes back', async () => {
const environment = harness();
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
await environment.complete(environment.starts()[0][1].doctorRunId!, '');
const preparation: MakeDoctorReport = {
runId: 'tracked-preparation',
@@ -759,7 +1134,7 @@ describe('Settings > Cindy Make', () => {
it('changing the switch leaves the old check running, ignores late results, and carries the option into the chat command', async () => {
const h = harness();
- const view = render(<CindyMakeSection />);
+ const view = renderEnvironment(<CindyMakeSection />);
const oldRun = h.starts()[0][1].doctorRunId!;
fireEvent.click(screen.getByRole('switch'));
expect(
@@ -797,7 +1172,7 @@ describe('Settings > Cindy Make', () => {
it('leaving the page only removes its progress subscription and does not cancel the check', () => {
const h = harness();
- const view = render(<CindyMakeSection />);
+ const view = renderEnvironment(<CindyMakeSection />);
const runId = h.starts()[0][1].doctorRunId;
expect(h.listeners.size).toBe(1);
view.unmount();
@@ -812,7 +1187,7 @@ describe('Settings > Cindy Make', () => {
vi.stubEnv('DEV', false);
setCindyMakeForceManagedTools(true);
const h = harness();
- render(<CindyMakeSection />);
+ renderEnvironment(<CindyMakeSection />);
expect(screen.queryByRole('switch')).toBeNull();
expect(h.starts()).toHaveLength(1);
expect(h.starts()[0][1]).not.toHaveProperty('forceManagedTools');
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index aa8262df8d..85f1aa46fe 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -28,7 +28,7 @@ import {
import type { CSSProperties, ReactNode } from 'react';
import { useLocation, useNavigate, useOutletContext, useParams } from 'react-router-dom';
import { dbToMakerAgentKind, normalizeDbAgentKind } from '../../../shared/agentKindConversion';
-import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';
+import { useTranslation } from 'react-i18next';
import {
isCodexResumeNotReadyProjectionError,
type AgentInputReference,
@@ -62,7 +62,8 @@ import { setRemoteReceiptDisplayReady } from '@/lib/sessionAttentionStore';
import { shortSessionId } from '@/lib/sessionId';
import { ChatInput } from '@/components/new-chat/ChatInput';
import { CindyMakeComposerMask } from '@/components/cindy-make/CindyMakeComposerMask';
-import { getCindyMakeComposerPhase } from '@/lib/cindyMakeComposer';
+import { getCindyMakeComposerPhase, getCindyMakePendingTest, getCindyMakePreparation } from '@/lib/cindyMakeComposer';
+import { CindyMakeTestCard } from '@/components/cindy-make/CindyMakeTestCard';
import { useCindyMakeState } from '@/lib/cindyMakeState';
import { GoalIndicator } from '@/components/new-chat/GoalIndicator';
import { PinnedPlanPanel } from '@/components/new-chat/PinnedPlanPanel';
@@ -1768,9 +1769,9 @@ export function CCAgentSessionView({
chatDisplaySnapshot,
} = useCCAgentChat(sessionId, handleTitleUpdate, { chatRealtime });
const makeState = useCindyMakeState();
- const cindyMakeComposerPhase = useMemo(
+ const cindyMakePreparation = useMemo(
() =>
- getCindyMakeComposerPhase({
+ getCindyMakePreparation({
session,
report: remoteDeviceId
? undefined
@@ -1778,11 +1779,25 @@ export function CCAgentSessionView({
(report) => report.task?.sessionId === sessionId,
),
messages,
+ }),
+ [session, sessionId, remoteDeviceId, makeState, messages],
+ );
+ const cindyMakeComposerPhase = useMemo(
+ () =>
+ getCindyMakeComposerPhase({
+ session,
+ report: cindyMakePreparation?.report,
+ messages,
historyLoaded,
busy: isAgentBusy,
error,
}),
- [session, sessionId, remoteDeviceId, makeState, messages, historyLoaded, isAgentBusy, error],
+ [session, cindyMakePreparation, messages, historyLoaded, isAgentBusy, error],
+ );
+ const cindyMakePendingTest = useMemo(
+ () => !remoteDeviceId && !readOnly && typeof window.electronAPI.cindyMakeTest === 'function'
+ ? getCindyMakePendingTest({ session, messages, busy: isAgentBusy }) : null,
+ [session, messages, isAgentBusy, remoteDeviceId, readOnly],
);
useEffect(() => {
if (!sessionId || !isOrcaLeadSessionView || !historyLoaded) return;
@@ -3397,7 +3412,7 @@ export function CCAgentSessionView({
},
) => {
if (readOnly) return false;
- if (cindyMakeComposerPhase) return false;
+ if (cindyMakeComposerPhase || cindyMakePendingTest) return false;
const deliveryMode = opts?.deliveryMode ?? 'queue';
const originalMessage = message;
const navigationRequestVersion =
@@ -3681,6 +3696,7 @@ export function CCAgentSessionView({
remoteDeviceId,
sessionHandoffPreparing,
cindyMakeComposerPhase,
+ cindyMakePendingTest,
],
);
@@ -3850,10 +3866,10 @@ export function CCAgentSessionView({
]);
const handleBeforeVoiceInputStart = useCallback(async () => {
- if (cindyMakeComposerPhase) return false;
+ if (cindyMakeComposerPhase || cindyMakePendingTest) return false;
const { proceed } = await vendorAuthGate.checkAndConfirm('codex', { purpose: 'voice-input' });
return proceed;
- }, [vendorAuthGate, cindyMakeComposerPhase]);
+ }, [vendorAuthGate, cindyMakeComposerPhase, cindyMakePendingTest]);
// M32: Retry — ErrorBanner 的 retryText 现在只是兼容展示值。真正的
// recovery target 由 main coordinator 持有,避免把已发出的文本重新走普通
@@ -4454,7 +4470,7 @@ export function CCAgentSessionView({
const shareSelectionBlocked =
Boolean(sessionBinding.attached) ||
worktreePreparing ||
- Boolean(cindyMakeComposerPhase) ||
+ Boolean(cindyMakeComposerPhase || cindyMakePendingTest) ||
Boolean(
pendingPlanReview ||
pendingPermission ||
@@ -4494,6 +4510,8 @@ export function CCAgentSessionView({
simplifiedBotConversation={Boolean(botChatIdentity)}
botUnreadBoundaryAt={botChatIdentity ? botUnreadBoundaryAt : null}
messages={messages}
+ cindyMakeSessionId={session?.source === 'cindy-make' ? sessionId : undefined}
+ cindyMakeCompletionInComposer={session?.source === 'cindy-make' && !remoteDeviceId && !readOnly && typeof window.electronAPI.cindyMakeTest === 'function'}
historyLoaded={historyLoaded}
historyCleared={Boolean(session?.clearedAt)}
taskUpdates={taskUpdates}
@@ -4602,7 +4620,7 @@ export function CCAgentSessionView({
if (hasSplitGroupSessionType(e.dataTransfer.types)) return;
e.preventDefault();
e.stopPropagation();
- if (cindyMakeComposerPhase) return;
+ if (cindyMakeComposerPhase || cindyMakePendingTest) return;
dragCounterRef.current += 1;
if (dragCounterRef.current === 1) setIsDragOver(true);
}}
@@ -4610,7 +4628,7 @@ export function CCAgentSessionView({
if (hasSplitGroupSessionType(e.dataTransfer.types)) return;
e.preventDefault();
e.stopPropagation();
- e.dataTransfer.dropEffect = cindyMakeComposerPhase ? 'none' : 'copy';
+ e.dataTransfer.dropEffect = cindyMakeComposerPhase || cindyMakePendingTest ? 'none' : 'copy';
}}
onDragLeave={(e) => {
if (hasSplitGroupSessionType(e.dataTransfer.types)) return;
@@ -4625,7 +4643,7 @@ export function CCAgentSessionView({
e.stopPropagation();
dragCounterRef.current = 0;
setIsDragOver(false);
- if (cindyMakeComposerPhase) return;
+ if (cindyMakeComposerPhase || cindyMakePendingTest) return;
// .cindy / .cshare 已被窗口级 capture 接管(装入 / 导入链路),
// 只清理拖拽 UI 状态,不当附件消费。
if (isGlobalDropIntercepted(e.nativeEvent)) return;
@@ -5161,12 +5179,11 @@ export function CCAgentSessionView({
既处理不了确认又无法继续发送或排队消息。
优先级 (高 → 低):
1. attached (远程接管中) → TakeoverMask (90px)
- 2. Cindy Make 准备 / 首次执行 → CindyMakeComposerMask (90px, 视觉同款)
+ 2. Cindy Make 准备 → 完整准备卡;开始修改后恢复普通输入
3. worktreePreparing → WorktreeCreatingOverlay (90px, 视觉同款)
4. 默认 → ChatInput
- 这些 mask 共用 TakeoverMask 同款外形 (90px h / 12px round / sidebar
- border), 切到 ChatInput 时高度变大, 与 takeover 收回回到 ChatInput
- 的体验一致。 */}
+ Cindy Make 沿用输入框的背景与边框,准备详情限高滚动;
+ 接管与 worktree 创建继续使用 90px 状态框。 */}
{pendingPlanReview ||
pendingPermission ||
pendingAskUser ||
@@ -5183,7 +5200,16 @@ export function CCAgentSessionView({
) : cindyMakeComposerPhase ? (
<CindyMakeComposerMask
phase={cindyMakeComposerPhase}
- onStop={!readOnly && isAgentBusy ? handleStopSession : undefined}
+ report={cindyMakePreparation?.report}
+ request={cindyMakePreparation?.request}
+ readOnly={readOnly || Boolean(remoteDeviceId)}
+ />
+ ) : cindyMakePendingTest && sessionId ? (
+ <CindyMakeTestCard
+ key={cindyMakePendingTest.completionId}
+ sessionId={sessionId}
+ completionId={cindyMakePendingTest.completionId}
+ meta={cindyMakePendingTest.meta}
/>
) : worktreePreparing && smoothedBranchName ? (
<WorktreeCreatingOverlay branchName={smoothedBranchName} />
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 3424b56bbb..16cfd22995 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -35,6 +35,7 @@ import {
CircleAlert,
CirclePlus,
Folder,
+ Hammer,
Loader2,
Plug,
SquarePen,
@@ -43,7 +44,6 @@ import {
X,
} from 'lucide-react';
import { useNavigate, useMatch, useLocation } from 'react-router-dom';
-import { useSidebarNavigate } from './sidebar/sidebarNavigation';
import { useTranslation } from 'react-i18next';
import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';
@@ -173,8 +173,13 @@ import {
import { PinnedSection, type PinnedSidebarEntry } from './sidebar/sections/PinnedSection';
import { ProjectNode as ProjectNodeView } from './sidebar/sections/ProjectNode';
import { compareDialogueSessions, type DialogueSortBy } from './sidebar/sections/DialogueSection';
-import { holdSidebarViewedPriority, ProjectsSection } from './sidebar/sections/ProjectsSection';
import { sidebarPriorityContext } from './lib/sidebarPriorityContext';
+import {
+ holdSidebarViewedPriority,
+ ProjectsSection,
+ SessionGroupNode,
+} from './sidebar/sections/ProjectsSection';
+import { partitionCindyMakeSessions, sortSessionsForMainList } from './lib/mainListModel';
import { toStoredSessionTitle } from './lib/sessionDisplayTitle';
import {
getVisibleSidebarSessionIds,
@@ -506,7 +511,7 @@ export function CCAgentSidebarUpper() {
}
return next;
}, [scheduleSessionIndex, remoteScheduleIndex]);
- const navigate = useSidebarNavigate();
+ const navigate = useNavigate();
// Workdir-browse mode (skillhub Market sidebar pattern). When the user
// clicked the file-text button on a Project, we swap sidebar contents to
@@ -1572,18 +1577,27 @@ function ExpandedView({
[pinnedProjectKeys, localPlatform],
);
- // Only the directory-picker restore path needs this catalogue. Read the
- // latest inputs after its await instead of grouping twice on every patch.
- const collectRestorableProjectKeysRef = useRef<() => ReadonlySet<string>>(() => new Set());
- collectRestorableProjectKeysRef.current = () =>
- collectRestorableProjectKeys({
- sessions: scopedSidebarSessions,
- persistentLocalProjects: visiblePersistentLocalProjects,
- lastActivityCutoff: cutoffForLastActivity(filter.lastActivity),
+ const restorableProjectKeys = useMemo(
+ () =>
+ collectRestorableProjectKeys({
+ sessions: scopedSidebarSessions,
+ persistentLocalProjects: visiblePersistentLocalProjects,
+ lastActivityCutoff: cutoffForLastActivity(filter.lastActivity),
+ pinnedProjectKeys,
+ vendorPredicate,
+ localPlatform,
+ }),
+ [
+ filter.lastActivity,
+ localPlatform,
pinnedProjectKeys,
+ scopedSidebarSessions,
vendorPredicate,
- localPlatform,
- });
+ visiblePersistentLocalProjects,
+ ],
+ );
+ const restorableProjectKeysRef = useRef(restorableProjectKeys);
+ restorableProjectKeysRef.current = restorableProjectKeys;
const hiddenProjectComparisonKeys = useMemo(
() => buildProjectKeyComparisonSet(hiddenProjectKeys, localPlatform),
[hiddenProjectKeys, localPlatform],
@@ -1835,10 +1849,9 @@ function ExpandedView({
!(selectedMachineId !== MACHINE_ALL && selectedMachineId.length === 1);
const [selectedSessionIds, setSelectedSessionIds] = useState<Set<string>>(() => new Set());
- // The range-selection anchor is interaction bookkeeping, never rendered.
- const selectionAnchorSessionIdRef = useRef<string | null>(null);
+ const [selectionAnchorSessionId, setSelectionAnchorSessionId] = useState<string | null>(null);
// 这几个值 handleSessionClick 只在「点击那一刻」读一次。留在它的 deps 里会让
- // 每次切换都重建 handler,
+ // 每次点击(:setSelectionAnchorSessionId 必触发)和每次切换都重建 handler,
// 行的 onClick 跟着换引用 → 整表 memo 失效重画一遍(SessionItem.tsx 不变量 #3)。
// 经 ref 读还顺带避开闭包陈旧:拿到的是最新值而非渲染时快照。
// attention / running / 未读集合更是:点进去会先清通知,若留在 deps 里,刚点的
@@ -1858,6 +1871,8 @@ function ExpandedView({
viewedSessionIdRef.current = viewedSessionId;
const selectedSessionIdsRef = useRef(selectedSessionIds);
selectedSessionIdsRef.current = selectedSessionIds;
+ const selectionAnchorSessionIdRef = useRef(selectionAnchorSessionId);
+ selectionAnchorSessionIdRef.current = selectionAnchorSessionId;
const [bulkActionPending, setBulkActionPending] = useState<BulkSessionAction | null>(null);
const sidebarScrollRef = useRef<HTMLDivElement>(null);
/**
@@ -2056,12 +2071,7 @@ function ExpandedView({
const next = new Set([...prev].filter((id) => renderedSessionIds.has(id)));
return sameStringSet(prev, next) ? prev : next;
});
- if (
- selectionAnchorSessionIdRef.current &&
- !renderedSessionIds.has(selectionAnchorSessionIdRef.current)
- ) {
- selectionAnchorSessionIdRef.current = null;
- }
+ setSelectionAnchorSessionId((prev) => (prev && renderedSessionIds.has(prev) ? prev : null));
}, []);
// 只在真有多选集合时才盯 DOM。单击也会写下 selectionAnchorSessionId 当
@@ -2080,7 +2090,7 @@ function ExpandedView({
const handleClearSelection = useCallback(() => {
setSelectedSessionIds((prev) => (prev.size === 0 ? prev : new Set()));
- selectionAnchorSessionIdRef.current = null;
+ setSelectionAnchorSessionId((prev) => (prev === null ? prev : null));
}, []);
useEffect(() => {
@@ -2175,7 +2185,7 @@ function ExpandedView({
}
return next;
});
- selectionAnchorSessionIdRef.current ??= id;
+ setSelectionAnchorSessionId((prev) => prev ?? id);
return;
}
@@ -2188,14 +2198,14 @@ function ExpandedView({
}
return next;
});
- selectionAnchorSessionIdRef.current = id;
+ setSelectionAnchorSessionId(id);
return;
}
if (selectedSessionIdsRef.current.size > 0) {
setSelectedSessionIds(new Set());
}
- selectionAnchorSessionIdRef.current = id;
+ setSelectionAnchorSessionId(id);
// 清点会先于路由更新抹掉 attention。必须先按当前档位钉住,否则
// ProjectsSection 首次 hold 只能读到 rest,刚打开的完成未读仍会立刻沉底。
const waiting = new Set(urgentSetRef.current);
@@ -2221,9 +2231,7 @@ function ExpandedView({
clearSystemSessionAttention(id);
if (id === activeSessionIdRef.current) return; // No duplicate navigate.
if (import.meta.env.DEV) perfLog.debug(`sidebar:click sid=${id}`); // 纯诊断,生产剔除
- // Known ordinary tasks can navigate in the current click batch.
- if (target && !isOrcaWorkerSession(target)) navigate(`/cc-agent/${id}`);
- else navigate(await resolveSessionRoute(id, target));
+ navigate(await resolveSessionRoute(id, target));
},
[navigate, clearNotification, markAutomationSessionRunsRead],
);
@@ -2426,7 +2434,7 @@ function ExpandedView({
localPlatform,
),
setProjectHidden,
- getCurrentProjectKeys: () => collectRestorableProjectKeysRef.current(),
+ getCurrentProjectKeys: () => restorableProjectKeysRef.current,
ensureProjectIncluded: filter.ensureProjectIncluded,
localPlatform,
});
@@ -2552,7 +2560,6 @@ function ExpandedView({
};
// 优先用 active session(若属于这个 project)。
- const activeSessionId = activeSessionIdRef.current;
if (activeSessionId) {
const active = sessions.find((s) => s.id === activeSessionId);
if (active && inProject(active)) {
@@ -2568,7 +2575,7 @@ function ExpandedView({
}
toast.warning(t('ccAgent.sidebar.browseEmpty'));
},
- [sessions, navigate, t],
+ [activeSessionId, sessions, navigate, t],
);
/* ---- Rename handler ---- */
@@ -2610,7 +2617,7 @@ function ExpandedView({
throw err;
}
},
- [projectAliases.updateAlias, t],
+ [projectAliases, t],
);
const handleRemoveProjectFromSidebar = useCallback(
@@ -2698,7 +2705,7 @@ function ExpandedView({
toast.error(t('ccAgent.sidebar.pinFailed'));
}
},
- [filter.removePin, filter.promotePin, t],
+ [filter, t],
);
// Event-only state: metadata updates recreate the collapsed Set even when
@@ -3011,12 +3018,7 @@ function ExpandedView({
for (const id of succeededIds) next.delete(id);
return next;
});
- if (
- selectionAnchorSessionIdRef.current &&
- succeededIds.has(selectionAnchorSessionIdRef.current)
- ) {
- selectionAnchorSessionIdRef.current = null;
- }
+ setSelectionAnchorSessionId((prev) => (prev && succeededIds.has(prev) ? null : prev));
if (failed.length === 0) {
toast.success(t('ccAgent.sidebar.bulkSelection.deleted', { count: succeededIds.size }));
@@ -3152,12 +3154,7 @@ function ExpandedView({
for (const id of succeededIds) next.delete(id);
return next;
});
- if (
- selectionAnchorSessionIdRef.current &&
- succeededIds.has(selectionAnchorSessionIdRef.current)
- ) {
- selectionAnchorSessionIdRef.current = null;
- }
+ setSelectionAnchorSessionId((prev) => (prev && succeededIds.has(prev) ? null : prev));
if (failed.length === 0) {
toast.success(t('ccAgent.sidebar.bulkSelection.archived', { count: succeededIds.size }));
@@ -3332,8 +3329,7 @@ function ExpandedView({
// 当前注视中的 session 被归档了 → 走 /cc-agent 让 CCAgentIndexRedirect
// 做 Orca-aware 的「选下一条 / 空则跳 new」决策(见 runSessionAction 同位置注释)。
- const currentlyViewedSessionId = viewedSessionIdRef.current;
- if (currentlyViewedSessionId && succeededIds.has(currentlyViewedSessionId)) {
+ if (viewedSessionId && succeededIds.has(viewedSessionId)) {
navigate('/cc-agent');
}
@@ -3353,6 +3349,7 @@ function ExpandedView({
runningSessionIds,
confirmDialog,
refreshSessions,
+ viewedSessionId,
navigate,
patchLocal,
filter.status,
@@ -3762,6 +3759,7 @@ function ExpandedView({
与「显示全部」),见 railPanelStore 头注。 */}
<RailPanels
projects={visibleRailProjectsWithVendor}
+ sortBy={filter.sortBy}
pinnedProjectKeys={pinnedProjectKeys}
unclassified={railUnclassified}
dialogues={railDialogues}
@@ -4023,6 +4021,7 @@ function RailPanelShell({
}
interface RailPanelsProps {
+ sortBy: Parameters<typeof sortSessionsForMainList>[1];
projects: ProjectNode[];
pinnedProjectKeys: ReadonlySet<string>;
/** 未分类(草稿等)会话——展开态 UnclassifiedSection 同源,面板内平铺在项目列表之上。 */
@@ -4067,10 +4066,11 @@ interface RailPanelsProps {
* - 项目列表:getProjectCollapseLimit()(默认 20)纯硬性上限 + 同款页脚。
*/
function RailPanels({
- projects,
+ projects: inputProjects,
pinnedProjectKeys,
- unclassified,
- dialogues,
+ unclassified: inputUnclassified,
+ dialogues: inputDialogues,
+ sortBy,
activeSessionId,
viewedSessionId,
runningSessionIds,
@@ -4092,6 +4092,16 @@ function RailPanels({
onRemoveProjectFromSidebar,
}: RailPanelsProps) {
const { t } = useTranslation();
+ const { projects, dialogues, unclassified, cindyMake } = useMemo(
+ () =>
+ partitionCindyMakeSessions({
+ projects: inputProjects,
+ dialogues: inputDialogues,
+ unclassified: inputUnclassified,
+ }),
+ [inputProjects, inputDialogues, inputUnclassified],
+ );
+ const [cindyMakeCollapsed, setCindyMakeCollapsed] = useState(false);
const panelState = useSyncExternalStore(railPanelStore.subscribe, railPanelStore.getSnapshot);
// 项目行右键菜单(「在此项目内新建」)——controlled DropdownMenu + 不可见
// trigger 跟坐标(Automations 菜单同款模式)。
@@ -4117,6 +4127,7 @@ function RailPanels({
if (panelState.openSection !== 'projects') {
setShowAllProjects(false);
setProjectMenu(null);
+ setCindyMakeCollapsed(false);
}
}, [panelState.openSection]);
@@ -4142,10 +4153,10 @@ function RailPanels({
// RailNav 的段灯据此聚合(review P2「灯绕过筛选/截断」两条的根治)。
useEffect(() => {
railPanelStore.setLampScope({
- projectSessions: [...projects.flatMap((p) => p.sessions), ...unclassified],
+ projectSessions: [...projects.flatMap((p) => p.sessions), ...unclassified, ...cindyMake],
dialogueSessions: dialogues,
});
- }, [projects, unclassified, dialogues]);
+ }, [projects, unclassified, dialogues, cindyMake]);
// 键盘打开(popover 焦点契约,DESIGN.md §14.2):焦点移入一级面板的首个
// 可聚焦元素(对话面板=头部新建钮/项目面板=首行),Tab 不再穿越 portal 间隔
@@ -4282,6 +4293,22 @@ function RailPanels({
// 远程活动镜像整表版本号:项目行聚合灯 / 折叠豁免要跟上被控端 relay 推送。
const remoteActivityRevision = useRemoteSessionActivityRevision();
+ const cindyMakeSessions = useMemo(() => {
+ const running = new Set(runningSessionIds);
+ const attention = new Set(notifications);
+ const waiting = new Set(urgentSet);
+ for (const session of cindyMake) {
+ const remote = remoteLampOf(session.id, session.deviceLinkDeviceId);
+ if (remote?.running) running.add(session.id);
+ if (remote?.tone) attention.add(session.id);
+ if (remote?.tone === 'error' || remote?.tone === 'awaiting') waiting.add(session.id);
+ }
+ return sortSessionsForMainList(cindyMake, sortBy, {
+ runningSessionIds: running,
+ attentionSessionIds: attention,
+ waitingSessionIds: waiting,
+ });
+ }, [cindyMake, sortBy, runningSessionIds, notifications, urgentSet, remoteActivityRevision]);
// 可见性口径的「当前会话」:files 路由下 activeSessionId 为 undefined,被浏览
// 文件的会话若排在折叠上限外且无灯语会被折进「显示全部」(codex review)。
@@ -4333,11 +4360,12 @@ function RailPanels({
};
collect(dialogues);
collect(unclassified);
+ collect(cindyMake);
for (const p of projects) collect(p.sessions);
if (remoteIds.length === 0) return notifications;
return new Set([...notifications, ...remoteIds]);
// eslint-disable-next-line react-hooks/exhaustive-deps -- remoteActivityRevision 代表 remoteLampOf 读到的整表内容
- }, [notifications, dialogues, unclassified, projects, remoteActivityRevision]);
+ }, [notifications, dialogues, unclassified, projects, cindyMake, remoteActivityRevision]);
// 项目列表折叠:纯硬性上限(ProjectsSection 同口径,默认 20)+「显示全部 N 项」。
const projectsView = useMemo(
@@ -4469,8 +4497,25 @@ function RailPanels({
)}
{panelState.openSection === 'projects' && (
<>
- {panelHead(t('ccAgent.sidebar.railNav.projects'), projects.length)}
+ {panelHead(
+ t('ccAgent.sidebar.railNav.projects'),
+ projects.length + (cindyMake.length ? 1 : 0),
+ )}
<div className="max-h-[420px] overflow-y-auto [scrollbar-width:thin]">
+ {cindyMake.length > 0 && (
+ <SessionGroupNode
+ sessions={cindyMakeSessions}
+ {...entryListShared}
+ groupTitle={t('settings.cindyMake.title')}
+ groupIcon={<Hammer size={15} strokeWidth={1.8} className="shrink-0" aria-hidden />}
+ collapsed={cindyMakeCollapsed}
+ onToggle={() => setCindyMakeCollapsed((value) => !value)}
+ isCreateDisabled={false}
+ parentSectionCollapsed={false}
+ disableSessionCollapse={false}
+ sessionVariant="text"
+ />
+ )}
{/* 未分类(草稿等)会话:展开态渲染在项目树之前(UnclassifiedSection,
无标题纯列表),面板同形同序——折叠态不能让它们不可达(review P2)。 */}
{unclassified.length > 0 && (
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionDisplayTitle.test.ts b/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionDisplayTitle.test.ts
index 0e8824d9bf..694dd7992e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionDisplayTitle.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionDisplayTitle.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect } from 'vitest';
+import { posix, win32 } from 'node:path';
import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
@@ -12,6 +13,7 @@ import {
} from '../sessionDisplayTitle';
const UNNAMED = '未命名任务';
+const MAKE_RUN = 'f428ca8b-242b-43c6-b2e5-e54bdd915f62';
function session(over: Partial<Session> = {}): Session {
return {
@@ -27,6 +29,49 @@ function session(over: Partial<Session> = {}): Session {
}
describe('getSessionDisplayTitle', () => {
+ it.each([
+ win32.join('C:/managed', 'worktrees', MAKE_RUN),
+ posix.join('/managed', 'worktrees', MAKE_RUN),
+ ])('uses the worktree name rather than the session id for %s', (workingDir) => {
+ const s = session({
+ id: 'other-session',
+ source: 'cindy-make',
+ workingDir,
+ title: '[Cindy-Make] 修改背景色',
+ });
+ expect(getSessionDisplayTitle(s, UNNAMED)).toBe('[f428] 修改背景色');
+ expect(s.title).toBe('[Cindy-Make] 修改背景色');
+ });
+
+ it.each(['[Cindy Make] 修改背景色', '[f428] 修改背景色', '修改背景色'])(
+ 'keeps one short tag when displaying %s',
+ (title) => {
+ const s = session({
+ source: 'cindy-make',
+ title,
+ workingDir: '/managed/worktrees/' + MAKE_RUN,
+ });
+ expect(getSessionDisplayTitle(s, UNNAMED)).toBe('[f428] 修改背景色');
+ },
+ );
+
+ it('does not guess a worktree tag when only the session id is known', () => {
+ const s = session({
+ id: 'abcd-session',
+ source: 'cindy-make',
+ title: '[Cindy-Make] 修改背景色',
+ });
+ expect(getSessionDisplayTitle(s, UNNAMED)).toBe('修改背景色');
+ });
+
+ it('leaves similar prefixes in ordinary task titles untouched', () => {
+ const s = session({
+ title: '[Cindy-Make] notes',
+ workingDir: '/managed/worktrees/' + MAKE_RUN,
+ });
+ expect(getSessionDisplayTitle(s, UNNAMED)).toBe('[Cindy-Make] notes');
+ });
+
it('哨兵标题换成本地化兜底文案', () => {
expect(getSessionDisplayTitle(session(), UNNAMED)).toBe(UNNAMED);
});
@@ -60,16 +105,34 @@ describe('getSessionDisplayTitle', () => {
describe('isEmptyDraftSession', () => {
it('哨兵 + 零消息 = 空草稿', () => {
expect(isEmptyDraftSession(session())).toBe(true);
- expect(isEmptyDraftSession(session({ _count: { messages: 0 } } as Partial<Session>))).toBe(true);
+ expect(isEmptyDraftSession(session({ _count: { messages: 0 } } as Partial<Session>))).toBe(
+ true,
+ );
});
it('有消息或已起名都不算空草稿', () => {
- expect(isEmptyDraftSession(session({ _count: { messages: 1 } } as Partial<Session>))).toBe(false);
+ expect(isEmptyDraftSession(session({ _count: { messages: 1 } } as Partial<Session>))).toBe(
+ false,
+ );
expect(isEmptyDraftSession(session({ title: '已起名' }))).toBe(false);
});
});
describe('toStoredSessionTitle — 显示投影必须还原成存储值', () => {
+ it.each(['新名字', '[f428] 新名字', '[Cindy-Make] 新名字'])(
+ 'preserves one worktree tag after renaming to %s',
+ (editedTitle) => {
+ const s = session({
+ source: 'cindy-make',
+ title: '[Cindy-Make] old',
+ workingDir: '/managed/worktrees/' + MAKE_RUN,
+ });
+ const stored = toStoredSessionTitle(s, editedTitle);
+ expect(stored).toBe('[f428] 新名字');
+ expect(getSessionDisplayTitle({ ...s, title: stored }, UNNAMED)).toBe(stored);
+ },
+ );
+
it('legacy automation 会话补回 [Schedule] 前缀', () => {
// 预填给用户的是剥掉前缀的 'nightly'。若原样落库,isAutomationGeneratedSession
// (legacy 数据只靠前缀识别)再也认不出它,会话从 automation 分组消失。
@@ -100,6 +163,16 @@ describe('toStoredSessionTitle — 显示投影必须还原成存储值', () =>
});
describe('canHighlightSessionDisplayTitle', () => {
+ it('avoids stale search offsets for legacy Make titles and retains them for new titles', () => {
+ const s = session({
+ source: 'cindy-make',
+ title: '[Cindy-Make] old',
+ workingDir: '/managed/worktrees/' + MAKE_RUN,
+ });
+ expect(canHighlightSessionDisplayTitle(s)).toBe(false);
+ expect(canHighlightSessionDisplayTitle({ ...s, title: '[f428] old' })).toBe(true);
+ });
+
it('显示串等于原始 title 时才允许高亮', () => {
expect(canHighlightSessionDisplayTitle(session({ title: '帮我排查登录失败' }))).toBe(true);
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
index e2830ee853..46ff729a9c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
@@ -24,12 +24,10 @@
*/
import type { Session } from '@/lib/ccAgent.types';
+import { isCindyMakeFamilySource } from '../../../../shared/cindyMakeMerge';
import { LIVE_TASK_PRIORITY, liveTaskPriorityRank } from '../../../../shared/liveTaskPriority';
-import type {
- FilterProjectOrder,
- FilterSortBy,
-} from '../hooks/helpers/sidebarFilterCore';
+import type { FilterProjectOrder, FilterSortBy } from '../hooks/helpers/sidebarFilterCore';
import { normalizeManualProjectOrder } from '../hooks/helpers/sidebarFilterCore';
import {
groupAutomationSidebarEntries,
@@ -42,6 +40,7 @@ import type { BotGroupNode, ProjectNode } from './projectGrouping';
export type MainListEntry =
| { kind: 'project'; project: ProjectNode }
| { kind: 'dialogue-group'; sessions: Session[] }
+ | { kind: 'cindy-make-group'; sessions: Session[] }
/** 一个伙伴名下的全部任务。与项目行并列 —— 项目是实体目录,伙伴名是用户起的。 */
| { kind: 'bot-group'; bot: BotGroupNode }
| SidebarSessionEntry;
@@ -101,10 +100,7 @@ export function naturalPriorityRankForId(
});
}
-export function sessionNaturalPriorityRank(
- session: Session,
- ctx: MainListPriorityContext,
-): number {
+export function sessionNaturalPriorityRank(session: Session, ctx: MainListPriorityContext): number {
return naturalPriorityRankForId(session.id, ctx);
}
@@ -183,7 +179,7 @@ export function sessionPriorityRecencyMs(session: Session, ctx: MainListPriority
export function getMainListEntrySessions(entry: MainListEntry): readonly Session[] {
if (entry.kind === 'project') return entry.project.sessions;
- if (entry.kind === 'dialogue-group') return entry.sessions;
+ if (entry.kind === 'dialogue-group' || entry.kind === 'cindy-make-group') return entry.sessions;
if (entry.kind === 'bot-group') return entry.bot.sessions;
if (entry.kind === 'automation-group') return entry.group.sessions;
return [entry.session];
@@ -233,15 +229,21 @@ export function sortSessionsForMainList(
sortBy: FilterSortBy,
ctx: MainListPriorityContext = EMPTY_PRIORITY_CONTEXT,
): Session[] {
- // Compute numeric keys once per call, never retain them across session updates.
- return sessions.map((session) => ({
- session,
- rank: sortBy === 'priority' ? sessionPriorityRank(session, ctx) : 0,
- time: sortBy === 'priority' ? sessionPriorityRecencyMs(session, ctx)
- : sortBy === 'created' ? sessionCreatedMs(session) : sessionActivityMs(session),
- })).sort((a, b) => a.rank - b.rank || b.time - a.time ||
- (sortBy === 'created' ? a.session.id.localeCompare(b.session.id) : 0))
- .map(({ session }) => session);
+ if (sortBy === 'priority') {
+ return sessions
+ .slice()
+ .sort(
+ (a, b) =>
+ sessionPriorityRank(a, ctx) - sessionPriorityRank(b, ctx) ||
+ sessionPriorityRecencyMs(b, ctx) - sessionPriorityRecencyMs(a, ctx),
+ );
+ }
+ if (sortBy === 'created') {
+ return sessions
+ .slice()
+ .sort((a, b) => sessionCreatedMs(b) - sessionCreatedMs(a) || a.id.localeCompare(b.id));
+ }
+ return sessions.slice().sort((a, b) => sessionActivityMs(b) - sessionActivityMs(a));
}
export interface BuildMainListEntriesInput {
@@ -267,6 +269,45 @@ export interface BuildMainListEntriesInput {
const EMPTY_SESSION_ID_SET: ReadonlySet<string> = new Set<string>();
+export const CINDY_MAKE_GROUP_KEY = 'cindy-make';
+
+/** Group by the task's source, never by a title or a guessed worktree path. */
+export function partitionCindyMakeSessions({
+ projects,
+ dialogues,
+ unclassified,
+}: {
+ projects: readonly ProjectNode[];
+ dialogues: readonly Session[];
+ unclassified: readonly Session[];
+}): {
+ projects: ProjectNode[];
+ dialogues: Session[];
+ unclassified: Session[];
+ cindyMake: Session[];
+} {
+ const cindyMake = new Map<string, Session>();
+ const regular = (sessions: readonly Session[]) =>
+ sessions.filter((session) => {
+ if (!isCindyMakeFamilySource(session.source)) return true;
+ cindyMake.set(session.id, session);
+ return false;
+ });
+ const regularProjects = projects.flatMap((project) => {
+ const sessions = regular(project.sessions);
+ if (sessions.length === project.sessions.length) return [project];
+ return sessions.length ? [{ ...project, sessions }] : [];
+ });
+ const regularDialogues = regular(dialogues);
+ const regularUnclassified = regular(unclassified);
+ return {
+ projects: regularProjects,
+ dialogues: regularDialogues,
+ unclassified: regularUnclassified,
+ cindyMake: [...cindyMake.values()],
+ };
+}
+
function buildFlatSessionEntries(
sessions: readonly Session[],
sortBy: FilterSortBy,
@@ -295,6 +336,16 @@ export function buildMainListEntries({
}: BuildMainListEntriesInput): MainListEntry[] {
const ctx = priorityContext;
const entries: MainListEntry[] = [];
+ const partitioned = partitionCindyMakeSessions({ projects, dialogues, unclassified });
+ projects = partitioned.projects;
+ dialogues = partitioned.dialogues;
+ unclassified = partitioned.unclassified;
+ if (partitioned.cindyMake.length) {
+ entries.push({
+ kind: 'cindy-make-group',
+ sessions: sortSessionsForMainList(partitioned.cindyMake, sortBy, ctx),
+ });
+ }
if (groupBy === 'flat') {
const flatEntries = buildFlatSessionEntries(
@@ -366,6 +417,24 @@ export function buildMainListEntries({
return sortMainListEntries(entries, sortBy, projectOrder, manualProjectOrder, ctx);
}
+function compareEntriesBySortBy(
+ a: MainListEntry,
+ b: MainListEntry,
+ sortBy: FilterSortBy,
+ ctx: MainListPriorityContext,
+): number {
+ if (sortBy === 'priority') {
+ return (
+ entryPriorityRank(a, ctx) - entryPriorityRank(b, ctx) ||
+ entryPriorityRecencyMs(b, ctx) - entryPriorityRecencyMs(a, ctx)
+ );
+ }
+ const timeDifference = entryTimeMs(b, sortBy) - entryTimeMs(a, sortBy);
+ if (timeDifference !== 0 || sortBy !== 'created') return timeDifference;
+ return (getMainListEntrySessions(a)[0]?.id ?? '').localeCompare(
+ getMainListEntrySessions(b)[0]?.id ?? '',
+ );
+}
function sortMainListEntries(
entries: readonly MainListEntry[],
@@ -374,17 +443,6 @@ function sortMainListEntries(
manualProjectOrder: readonly string[],
ctx: MainListPriorityContext,
): MainListEntry[] {
- const keys = new Map(entries.map((entry) => [entry, {
- rank: sortBy === 'priority' ? entryPriorityRank(entry, ctx) : 0,
- time: sortBy === 'priority' ? entryPriorityRecencyMs(entry, ctx) : entryTimeMs(entry, sortBy),
- id: sortBy === 'created' ? getMainListEntrySessions(entry)[0]?.id ?? '' : '',
- }]));
- const compare = (a: MainListEntry, b: MainListEntry) => {
- const left = keys.get(a)!;
- const right = keys.get(b)!;
- return left.rank - right.rank || right.time - left.time ||
- (sortBy === 'created' ? left.id.localeCompare(right.id) : 0);
- };
if (projectOrder === 'custom') {
// 自定义项目序:项目行按 manualProjectOrder;不在序的新项目由 normalize
// 追加到已排序列之后。非项目条目排在项目之后,仍按当前任务排序。
@@ -407,11 +465,11 @@ function sortMainListEntries(
Number.MAX_SAFE_INTEGER)
);
}
- return compare(a, b);
+ return compareEntriesBySortBy(a, b, sortBy, ctx);
});
}
- return entries.slice().sort((a, b) => compare(a, b));
+ return entries.slice().sort((a, b) => compareEntriesBySortBy(a, b, sortBy, ctx));
}
/* ============================== 设备分组(E 期) ============================== */
@@ -460,7 +518,7 @@ export function splitEntriesByDevice(
// 先把跨设备对话组拆开(组内成员可能来自不同设备)。
const flattened: MainListEntry[] = [];
for (const entry of entries) {
- if (entry.kind !== 'dialogue-group') {
+ if (entry.kind !== 'dialogue-group' && entry.kind !== 'cindy-make-group') {
flattened.push(entry);
continue;
}
@@ -472,7 +530,7 @@ export function splitEntriesByDevice(
else byDevice.set(key, [s]);
}
for (const sessions of byDevice.values()) {
- flattened.push({ kind: 'dialogue-group', sessions });
+ flattened.push({ kind: entry.kind, sessions });
}
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionDisplayTitle.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionDisplayTitle.ts
index 790934d0af..0e357c2928 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionDisplayTitle.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionDisplayTitle.ts
@@ -13,6 +13,8 @@
import { isDefaultDraftSessionTitle } from '@cindy/maker-shared/session-title';
import type { Session } from '@/lib/ccAgent.types';
+import { cindyMakeWorktreeName, formatCindyMakeTitle } from '@/lib/cindyMakeTitle';
+import { isCindyMakeFamilySource } from '../../../../shared/cindyMakeMerge';
import {
getAutomationSessionDisplayTitle,
@@ -51,6 +53,9 @@ export function isEmptyDraftSession(session: Session): boolean {
*/
export function getSessionDisplayTitle(session: Session, unnamedLabel: string): string {
if (isDefaultDraftSessionTitle(session.title)) return unnamedLabel;
+ if (isCindyMakeFamilySource(session.source)) {
+ return formatCindyMakeTitle(session.title, cindyMakeWorktreeName(session.workingDir));
+ }
return getAutomationSessionDisplayTitle(session);
}
@@ -67,10 +72,14 @@ export function getSessionDisplayTitle(session: Session, unnamedLabel: string):
* automation 分组和相关 UI 里消失(PR #1031 review P1)。
* - 哨兵会话若被存成兜底文案,自动起名的哨兵匹配失效、永久跳过该会话。后者由调用方
* 的「没改就不落库」判据挡住(编辑结果等于预填值时直接 return),这里只负责前缀。
+ * - Cindy Make 使用工作目录的四位标记;保存重命名时保留一次该标记。
*
* 新数据带 `source='scheduler'`,不依赖前缀,所以只需给仍带前缀的行补回去。
*/
export function toStoredSessionTitle(session: Session, editedTitle: string): string {
+ if (isCindyMakeFamilySource(session.source)) {
+ return formatCindyMakeTitle(editedTitle, cindyMakeWorktreeName(session.workingDir));
+ }
if (!isScheduledSession(session)) return editedTitle;
// 用户手动把前缀打回来了(或压根没删)→ 不重复叠加。
if (editedTitle.startsWith(SCHEDULE_TITLE_PREFIX)) return editedTitle;
@@ -82,11 +91,16 @@ export function toStoredSessionTitle(session: Session, editedTitle: string): str
*
* `matchIndices` 是搜索在**原始** `session.title` 上算出的下标
* (见 `lib/sessionSearch.ts` 的 `fuzzyFilterAndRank`),显示串一旦与原串不同,下标
- * 就会错位、把高亮画到别的字上。两种情况必须关掉高亮:
+ * 就会错位、把高亮画到别的字上。以下情况必须关掉高亮:
*
* - `[Schedule] xxx` 前缀被剥掉(既有 case);
* - 哨兵标题被换成本地化的「未命名任务」(本次新增,同一个坑)。
+ * - Cindy Make 的旧前缀被替换为工作目录短标记。
*/
export function canHighlightSessionDisplayTitle(session: Session): boolean {
- return !isScheduledSession(session) && !isDefaultDraftSessionTitle(session.title);
+ return (
+ !isScheduledSession(session) &&
+ !isDefaultDraftSessionTitle(session.title) &&
+ getSessionDisplayTitle(session, '') === session.title
+ );
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionSourceLabel.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionSourceLabel.ts
index 948e5dc9a8..0e596c565f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionSourceLabel.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionSourceLabel.ts
@@ -1,27 +1,41 @@
+import { isCindyMakeFamilySource } from '../../../../shared/cindyMakeMerge';
import type { Session } from '@/lib/ccAgent.types';
-import { normalizeWorkingDir, projectIdentityKeyForSession, type ProjectNode } from './projectGrouping';
+import {
+ normalizeWorkingDir,
+ projectIdentityKeyForSession,
+ type ProjectNode,
+} from './projectGrouping';
/**
- * 构建 session → "项目来源"标签映射,供平铺时标题旁展示。
+ * 构建 session → "项目来源"标签映射,供文字模式 SessionItem hover 时右侧浮层展示。
*
- * 口径(主列表与置顶视图共用,保持一致):
- * - dialogue → 不注入(独立对话本身不需要再标「对话」);
+ * 口径(时间排序视图与置顶视图共用,保持一致):
+ * - dialogue → 传入的 `dialogueLabel`(已 i18n 解析,保持本函数 i18n-agnostic / 纯函数);
* - project → 命中 ProjectNode 就用其 displayName(消歧后可能带父目录段);
* - orca-lead / 罕见来源找不到 ProjectNode 时 → 回退 workingDir basename;
- * - 都拿不到 → 不注入(map 里无该 session key),标题旁不画来源。
+ * - 都拿不到 → 不注入(map 里无该 session key),SessionTooltip 直接透传行。
*
* 纯函数、无 React 依赖:调用方各自用 useMemo 包裹并传入自己的 session 数组
- * (主列表传散排会话,置顶视图传 visibleSessions),memo 依赖各自维护。
+ * (时间视图传全量 sessions,置顶视图传 slicedSessions),memo 依赖各自维护。
*/
export function buildSessionSourceLabelMap(
sessions: readonly Session[],
allKnownProjects: readonly ProjectNode[],
+ dialogueLabel: string,
+ cindyMakeLabel?: string,
): Map<string, string> {
const nameByKey = new Map(allKnownProjects.map((p) => [p.projectKey, p.displayName]));
const map = new Map<string, string>();
for (const s of sessions) {
- if (s.workspaceKind === 'dialogue') continue;
+ if (isCindyMakeFamilySource(s.source) && cindyMakeLabel) {
+ map.set(s.id, cindyMakeLabel);
+ continue;
+ }
+ if (s.workspaceKind === 'dialogue') {
+ map.set(s.id, dialogueLabel);
+ continue;
+ }
const key = projectIdentityKeyForSession(s);
const name = key ? nameByKey.get(key) : undefined;
if (name) {
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx
index 3cfaf7f53b..4ee9afc4a6 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx
@@ -210,8 +210,14 @@ export function PinnedSection({
// 平铺时标题旁的"项目来源"标签(口径见 buildSessionSourceLabelMap)。
// 置顶视图传 visibleSessions;文字 / 列表都画,card 变体不画这个标签。
const sourceLabelMap = useMemo(
- () => buildSessionSourceLabelMap(visibleSessions, allKnownProjects),
- [visibleSessions, allKnownProjects],
+ () =>
+ buildSessionSourceLabelMap(
+ visibleSessions,
+ allKnownProjects,
+ t('ccAgent.sidebar.dialogues'),
+ t('settings.cindyMake.title'),
+ ),
+ [visibleSessions, allKnownProjects, t],
);
const getEntryId = useCallback((entry: PinnedSidebarEntry) => entry.id, []);
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
index 51200982e4..62b420d6aa 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
@@ -1,3 +1,4 @@
+import { isCindyMakeFamilySource } from '../../../../../shared/cindyMakeMerge';
/**
* ProjectsSection — Sidebar 中部的 Projects 段
* ---------------------------------------------------------------------------
@@ -29,11 +30,12 @@ import {
ChevronRight,
ChevronsDownUp,
ChevronsUpDown,
+ Hammer,
MessagesSquare,
MonitorSmartphone,
SquarePen,
} from 'lucide-react';
-import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';
+import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { Tip } from '@/components/ui/tooltip';
@@ -50,7 +52,6 @@ import {
useRemoteHostProjectOrders,
} from '../../hooks/useRemoteHostProjectOrders';
import { SortableList } from '@/components/sidebar/SortableList';
-import { useMainListEntries } from '../../hooks/useMainListEntries';
import { useReducedMotion } from '@/hooks/useReducedMotion';
import { useSidebarMainViewMode } from '@/hooks/useSidebarCardMode';
import { ProjectNode } from './ProjectNode';
@@ -69,6 +70,8 @@ import {
DIALOGUE_GROUP_ALL_KEY,
} from '../../hooks/helpers/sidebarFilterCore';
import {
+ buildMainListEntries,
+ CINDY_MAKE_GROUP_KEY,
getMainListEntrySessions,
holdViewedPriorityRank,
splitEntriesByDevice,
@@ -247,20 +250,17 @@ export interface ProjectsSectionProps {
isCreateDialogueDisabled?: boolean;
}
-const EMPTY_BOTS: BotGroupNode[] = [];
-
export function ProjectsSection({
unclassified,
projects,
dialogues,
- bots = EMPTY_BOTS,
+ bots = [],
onOpenBot,
allKnownProjects,
dialogueCount = 0,
allProjectKeysForOrder,
filter,
collapsed,
- isAllCollapsed,
activeSessionId,
viewedSessionId,
runningSessionIds,
@@ -307,36 +307,22 @@ export function ProjectsSection({
const mainSessionVariant: 'text' | 'list' = mainViewMode === 'list' ? 'list' : 'text';
// SortableList 只在自定义项目顺序且按项目分组时挂载。
// 折叠溢出且未点「显示全部」时禁用,避免只重排可见前缀。
- const projectOrderScope = useMemo(
- () => projectOrderWriteScopeForSelection(selectedMachineForOrder),
- [selectedMachineForOrder],
- );
+ const projectOrderScope = projectOrderWriteScopeForSelection(selectedMachineForOrder);
const hostSnapshotForDisplay =
projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null
? localHostProjectOrder.snapshot
: projectOrderScope.kind === 'host' && projectOrderScope.deviceId
? remoteHostProjectOrders.orders.get(projectOrderScope.deviceId)
: undefined;
- const displayedProjectOrder = useMemo(
- () =>
- resolveDisplayedProjectOrder(
- projectOrderScope,
- hostSnapshotForDisplay,
- { projectOrder: filter.projectOrder, manualProjectOrder: filter.manualProjectOrder },
- projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null
- ? localHostProjectOrder.snapshot.manualProjectOrder
- : projectOrderScope.kind === 'host' && projectOrderScope.deviceId
- ? (controllerManualOrderForDevice(projectOrderScope.deviceId, hostSnapshotForDisplay) ??
- [])
- : [],
- ),
- [
- projectOrderScope,
- hostSnapshotForDisplay,
- filter.projectOrder,
- filter.manualProjectOrder,
- localHostProjectOrder.snapshot.manualProjectOrder,
- ],
+ const displayedProjectOrder = resolveDisplayedProjectOrder(
+ projectOrderScope,
+ hostSnapshotForDisplay,
+ filter,
+ projectOrderScope.kind === 'host' && projectOrderScope.deviceId === null
+ ? localHostProjectOrder.snapshot.manualProjectOrder
+ : projectOrderScope.kind === 'host' && projectOrderScope.deviceId
+ ? (controllerManualOrderForDevice(projectOrderScope.deviceId, hostSnapshotForDisplay) ?? [])
+ : [],
);
const customProjectOrder =
filter.groupBy === 'project' && displayedProjectOrder.projectOrder === 'custom';
@@ -505,8 +491,6 @@ export function ProjectsSection({
[naturalPriorityContext, hold],
);
- const sortingPriorityContext = filter.sortBy === 'priority' ? priorityContext : undefined;
-
// starting 只让位给真实 in-flight:本地 isRunning(见 useStartingSessionIds),
// 远程 running / needs-interaction。终态 attention 不再吸收 —— 旧终态会误伤
// 新发送,新终态又要代次才能和旧的区分,两边补丁会来回打。没经过 running
@@ -548,20 +532,42 @@ export function ProjectsSection({
// 混排模型(D 期):项目行 / 散排对话 / 对话组统一为顶层条目并按同一口径排序。
// 这有意推翻旧「Dialogue 固定段在 Projects 之后」的裁决(mainListModel.ts 文件头)。
// 设备分组开启时,未分类草稿并进混排再按设备切段;单段路径仍走顶部独立段。
- const mixedEntries = useMainListEntries({
- projects,
- dialogues,
- bots,
- unclassified: deviceGroupingActive && !unclassifiedHidden ? unclassified : undefined,
- groupBy: filter.groupBy,
- groupDialogue: filter.groupDialogue,
- sortBy: filter.sortBy,
- projectOrder: displayedProjectOrder.projectOrder,
- manualProjectOrder: displayedProjectOrder.manualProjectOrder,
- priorityContext,
- notifications,
- scheduleSessionIndex,
- });
+ const mixedEntries = useMemo(
+ () =>
+ buildMainListEntries({
+ projects,
+ dialogues,
+ bots,
+ unclassified: unclassifiedHidden
+ ? []
+ : deviceGroupingActive
+ ? unclassified
+ : unclassified.filter((session) => isCindyMakeFamilySource(session.source)),
+ groupBy: filter.groupBy,
+ groupDialogue: filter.groupDialogue,
+ sortBy: filter.sortBy,
+ projectOrder: displayedProjectOrder.projectOrder,
+ manualProjectOrder: displayedProjectOrder.manualProjectOrder,
+ priorityContext,
+ notifications,
+ scheduleSessionIndex,
+ }),
+ [
+ projects,
+ dialogues,
+ bots,
+ unclassified,
+ unclassifiedHidden,
+ deviceGroupingActive,
+ filter.groupBy,
+ filter.groupDialogue,
+ filter.sortBy,
+ displayedProjectOrder,
+ priorityContext,
+ notifications,
+ scheduleSessionIndex,
+ ],
+ );
// 顶层条目折叠:最多显示 N 条,超出收起 + 「显示全部 N 项」。与会话同一套
// 规则(getSessionListCollapseView):始终保留"有需关注会话"的条目、以及包含当前会话的
@@ -638,7 +644,7 @@ export function ProjectsSection({
sortBy: filter.sortBy,
projectOrder: filter.projectOrder,
manualProjectOrder: filter.manualProjectOrder,
- priorityContext: sortingPriorityContext,
+ priorityContext,
});
}, [
deviceGroupingActive,
@@ -648,7 +654,7 @@ export function ProjectsSection({
filter.sortBy,
filter.projectOrder,
filter.manualProjectOrder,
- sortingPriorityContext,
+ priorityContext,
]);
// 设备段折叠(E 期):本机段 key 'local'。
const [collapsedDevices, setCollapsedDevices] = useState<ReadonlySet<string>>(new Set());
@@ -688,21 +694,27 @@ export function ProjectsSection({
// 组层 = 项目行 + 自动任务组 + 「对话」组行。项目侧复用 ProjectNode 折叠状态,
// 自动任务组复用 owner-scoped 持久化状态,对话组沿用本地显示偏好。
const hasGroupLayer = mixedEntries.some((entry) => entry.kind !== 'session');
- // 当前可见的对话组 key:设备分组下 = 各含对话组条目的设备段;否则单一组。
+ // 对话与 Cindy Make 分组按各自命名空间、设备段记忆折叠。
// 「收起/展开所有分组」只作用于这些可见 key,不动其它模式下的记忆。
- const visibleDialogueGroupKeys = useMemo<string[]>(() => {
+ const visibleSessionGroupKeys = useMemo<string[]>(() => {
+ const keysFor = (entries: readonly MainListEntry[], scope: string) =>
+ entries.flatMap((entry) =>
+ entry.kind === 'dialogue-group'
+ ? [scope]
+ : entry.kind === 'cindy-make-group'
+ ? [`${CINDY_MAKE_GROUP_KEY}:${scope}`]
+ : [],
+ );
if (!deviceGroupingActive) {
- return visibleMixedEntries.some((entry) => entry.kind === 'dialogue-group')
- ? [DIALOGUE_GROUP_ALL_KEY]
- : [];
+ return keysFor(visibleMixedEntries, DIALOGUE_GROUP_ALL_KEY);
}
- return deviceSections
- .filter((section) => section.entries.some((entry) => entry.kind === 'dialogue-group'))
- .map((section) => deviceSectionKey(section.deviceId));
+ return deviceSections.flatMap((section) =>
+ keysFor(section.entries, deviceSectionKey(section.deviceId)),
+ );
}, [deviceGroupingActive, visibleMixedEntries, deviceSections]);
- const allDialogueGroupsCollapsed =
- visibleDialogueGroupKeys.length === 0 ||
- visibleDialogueGroupKeys.every((key) => collapsedDialogueGroups.has(key));
+ const allSessionGroupsCollapsed =
+ visibleSessionGroupKeys.length === 0 ||
+ visibleSessionGroupKeys.every((key) => collapsedDialogueGroups.has(key));
const visibleAutomationGroupKeys = useMemo(
() =>
mixedEntries
@@ -734,14 +746,14 @@ export function ProjectsSection({
filter.groupBy,
legacyAutomationGroupKeys,
);
- // 组层是否收齐必须看**当前范围**有没有项目行。allKnownProjects 是全机器宇宙,
- // 单机范围下本机只有对话组、远端仍有项目时 length>0;isAllCollapsed 却来自
- // 当前范围的 activeWorkingDirs,此时为空并恒为 false,foldState 会卡在
- // collapse-groups。有可见项目行才并上 isAllCollapsed。
- const hasVisibleProjectGroups = mixedEntries.some((entry) => entry.kind === 'project');
+ // 只检查实际项目行。已经收进 Cindy Make 的工作目录不再各占一行,
+ // 不能用它们旧的目录折叠状态阻止分组整体进入“全部展开”状态。
+ const allVisibleProjectGroupsCollapsed = mixedEntries.every(
+ (entry) => entry.kind !== 'project' || collapsed.has(entry.project.projectKey),
+ );
const allGroupsCollapsed =
- (!hasVisibleProjectGroups || isAllCollapsed) &&
- allDialogueGroupsCollapsed &&
+ allVisibleProjectGroupsCollapsed &&
+ allSessionGroupsCollapsed &&
allAutomationGroupsCollapsed;
const hasDeviceLayer = deviceGroupingActive && deviceSections.length > 0;
const allDevicesCollapsed =
@@ -756,7 +768,7 @@ export function ProjectsSection({
const handleFoldAll = useCallback(() => {
if (foldState === 'collapse-groups') {
onCollapseAll();
- setDialogueCollapsed(visibleDialogueGroupKeys, true);
+ setDialogueCollapsed(visibleSessionGroupKeys, true);
setAllAutomationGroupsCollapsed(true);
return;
}
@@ -769,12 +781,12 @@ export function ProjectsSection({
// expand-all:全部层级展开(设备段 + 项目行 + 自动任务组 + 对话组)。
setCollapsedDevices(new Set());
onExpandAll();
- setDialogueCollapsed(visibleDialogueGroupKeys, false);
+ setDialogueCollapsed(visibleSessionGroupKeys, false);
setAllAutomationGroupsCollapsed(false);
}, [
foldState,
deviceSections,
- visibleDialogueGroupKeys,
+ visibleSessionGroupKeys,
onCollapseAll,
onExpandAll,
setDialogueCollapsed,
@@ -795,8 +807,14 @@ export function ProjectsSection({
return [...projects.flatMap((project) => project.sessions), ...dialogues];
}, [filter.groupBy, projects, dialogues]);
const dialogueSourceLabelMap = useMemo(
- () => buildSessionSourceLabelMap(flattenedSessionsForSourceLabels, allKnownProjects),
- [flattenedSessionsForSourceLabels, allKnownProjects],
+ () =>
+ buildSessionSourceLabelMap(
+ flattenedSessionsForSourceLabels,
+ allKnownProjects,
+ t('ccAgent.sidebar.dialogues'),
+ t('settings.cindyMake.title'),
+ ),
+ [flattenedSessionsForSourceLabels, allKnownProjects, t],
);
// F-PJ-10:即使 projects 因 filter 收窄到空,也要保留段头供用户切回 Filter。
@@ -939,8 +957,10 @@ export function ProjectsSection({
/>
);
}
- if (entry.kind === 'dialogue-group') {
- const isCollapsed = collapsedDialogueGroups.has(dialogueGroupKey);
+ if (entry.kind === 'dialogue-group' || entry.kind === 'cindy-make-group') {
+ const isMake = entry.kind === 'cindy-make-group';
+ const groupKey = isMake ? `${CINDY_MAKE_GROUP_KEY}:${dialogueGroupKey}` : dialogueGroupKey;
+ const isCollapsed = collapsedDialogueGroups.has(groupKey);
// 目标设备离线时不能在它上面新建(被控端才是真正的创建方)——与远程项目行的
// 新建同款保护(isDeviceLinkWriteBlocked / actionsUnavailable 文案)。
const targetDeviceOffline = Boolean(
@@ -952,11 +972,15 @@ export function ProjectsSection({
targetDeviceOffline;
return (
<SessionGroupNode
- key={`dialogue-group:${dialogueGroupKey}`}
+ key={`${entry.kind}:${dialogueGroupKey}`}
sessions={entry.sessions}
+ groupTitle={isMake ? t('settings.cindyMake.title') : undefined}
+ groupIcon={
+ isMake ? <Hammer size={15} strokeWidth={1.8} className="shrink-0" aria-hidden /> : undefined
+ }
collapsed={isCollapsed}
- onToggle={() => setDialogueCollapsed([dialogueGroupKey], !isCollapsed)}
- onCreateDialogue={() => onCreateDialogue(dialogueDeviceTarget)}
+ onToggle={() => setDialogueCollapsed([groupKey], !isCollapsed)}
+ onCreateDialogue={isMake ? undefined : () => onCreateDialogue(dialogueDeviceTarget)}
isCreateDisabled={createDisabled}
createDisabledReason={
targetDeviceOffline ? t('ccAgent.remoteSession.actionsUnavailable') : undefined
@@ -1006,7 +1030,7 @@ export function ProjectsSection({
<div className="relative flex flex-col gap-1 pt-1 pr-0 pl-3">
{!deviceGroupingActive ? (
<UnclassifiedSection
- sessions={unclassified}
+ sessions={unclassified.filter((session) => !isCindyMakeFamilySource(session.source))}
hidden={unclassifiedHidden}
activeSessionId={activeSessionId}
runningSessionIds={runningSessionIds}
@@ -1189,7 +1213,7 @@ export function ProjectsSection({
/**
* SessionGroupNode — 一个带标题的会话组行。
*
- * 两个用法共用它:「对话」组(D 期,「对话归为一组」开启时)与**伙伴组**。两者是
+ * 「对话」、伙伴与 Cindy Make 复用同一种会话分组。它们是
* 同一种东西,只差图标和标题 —— 所以参数化,不复制。默认值就是对话组的原始形态,
* 既有调用点行为逐字不变。
* 视觉与交互与 ProjectNode 表头**同款**(2026-08-12 用户裁决:对话组的分组 UI、
@@ -1199,7 +1223,7 @@ export function ProjectsSection({
* 「收起所有分组」的批量收起/展开。
* 标题「对话」是归属分类名(task-and-conversation-naming §2.3)。
*/
-function SessionGroupNode({
+export function SessionGroupNode({
sessions,
collapsed,
onToggle,
@@ -1243,7 +1267,7 @@ function SessionGroupNode({
* 组头右侧的新建入口(与项目行 SquarePen 等位):新建不绑项目的对话任务。
* 目标设备由父层按所在设备段决定(闭包传入),本组件不关心。
*/
- onCreateDialogue: () => void;
+ onCreateDialogue?: () => void;
isCreateDisabled: boolean;
/** 禁用原因(目标设备离线),有值时替换按钮 tooltip / aria——与远程项目行同款。 */
createDisabledReason?: string;
@@ -1309,34 +1333,36 @@ function SessionGroupNode({
</div>
{/* 悬浮工具组:与 ProjectNode Header 同款——常态隐藏,hover 整行淡入。
对话组没有项目那套 More 菜单,只保留新建(SquarePen,与项目行等位)。 */}
- <div
- className={cn(
- 'flex shrink-0 items-center gap-0.5',
- 'opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100',
- )}
- >
- <Tip text={createDisabledReason ?? createLabel ?? t('ccAgent.sidebar.newDialogue')}>
- <button
- type="button"
- aria-label={createDisabledReason ?? createLabel ?? t('ccAgent.sidebar.newDialogue')}
- disabled={isCreateDisabled}
- onClick={(e) => {
- e.stopPropagation();
- if (!isCreateDisabled) onCreateDialogue();
- }}
- onPointerDown={(e) => e.stopPropagation()}
- onKeyDown={(e) => e.stopPropagation()}
- className={cn(
- 'flex size-5 shrink-0 items-center justify-center rounded-md',
- 'text-sidebar-action-icon hover:text-foreground',
- 'hover:bg-sidebar-item-hover focus:outline-none',
- 'disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent',
- )}
- >
- <SquarePen size={14} strokeWidth={2} />
- </button>
- </Tip>
- </div>
+ {onCreateDialogue && (
+ <div
+ className={cn(
+ 'flex shrink-0 items-center gap-0.5',
+ 'opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100',
+ )}
+ >
+ <Tip text={createDisabledReason ?? createLabel ?? t('ccAgent.sidebar.newDialogue')}>
+ <button
+ type="button"
+ aria-label={createDisabledReason ?? createLabel ?? t('ccAgent.sidebar.newDialogue')}
+ disabled={isCreateDisabled}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (!isCreateDisabled) onCreateDialogue();
+ }}
+ onPointerDown={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ className={cn(
+ 'flex size-5 shrink-0 items-center justify-center rounded-md',
+ 'text-sidebar-action-icon hover:text-foreground',
+ 'hover:bg-sidebar-item-hover focus:outline-none',
+ 'disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent',
+ )}
+ >
+ <SquarePen size={14} strokeWidth={2} />
+ </button>
+ </Tip>
+ </div>
+ )}
</div>
{/* 组内会话:与 ProjectNode 的会话区同款容器(gap / pt / pb 呼吸、list 缩进)
与同一份折叠上限(getProjectSessionCollapseLimit)。 */}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index cc01e6b23b..1d77b92737 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5748,7 +5748,11 @@
"failed": "Preparation failed",
"cancelled": "Preparation stopped",
"cleaning": "Cleaning up",
- "cleanup": "Cleanup pending"
+ "cleanup": "Cleanup pending",
+ "cleanupFailed": "Cleanup failed",
+ "integrated": "Integrated",
+ "unintegrated": "Not integrated",
+ "unknown": "Integration status unverified"
},
"errors": {
"busy": "The session or folder is still in use. Stop it and try again.",
@@ -5757,7 +5761,17 @@
"cleanupFailed": "Cleanup did not finish. The record is kept so you can retry.",
"directoryBusy": "Files in the development folder are in use or cannot be removed. Close terminals, editors, or previews using this folder, then retry cleanup.",
"unavailable": "The session or development folder changed. Refresh and try again."
- }
+ },
+ "end": "End build",
+ "endHint": "End the build to clean up its working directory. Make history and retained changes will be kept.",
+ "endConfirm": "End “{{title}}” and clean up its working directory? Make history and retained changes will be kept.",
+ "cleanupDeletedConfirm": "Clean up the remaining working directory for “{{title}}”? Retained make history will be kept.",
+ "endUnintegrated": "Some changes have not been integrated into your personal version. Ending the build will not integrate them automatically.",
+ "endUnknown": "The integration status could not be verified. Check your changes before cleaning up."
+ },
+ "tabs": {
+ "versions": "Version Control",
+ "environment": "Environment"
}
}
},
@@ -12174,38 +12188,6 @@
}
},
"billing": {
- "comparison": {
- "free": "FREE",
- "freeUsage": "Free to use",
- "priceFromSuffix": "and up",
- "topup": "Top up as needed",
- "topupExpiry": "Top-up credits never expire",
- "agent": "Full Agent features",
- "apiKey": "Bring your own API key",
- "existingSubscription": "Connect existing subscriptions",
- "localModels": "Use local models",
- "basicModels": "Access basic models",
- "subscription": "Subscription plan",
- "rollover": "Keep up to {{amount}} in unused credits for {{period}}",
- "nextPeriod": {
- "MONTH": "next month",
- "YEAR": "next year",
- "OTHER": "the next period"
- },
- "includesFree": "Everything in FREE",
- "advancedModels": "Unlock advanced models",
- "managedService": "Managed service, no setup",
- "topupUnlock": "Pay as you go to unlock advanced models",
- "select": "Choose {{name}}",
- "upgrade": "Upgrade to {{name}}",
- "downgrade": "Downgrade to {{name}}",
- "changeUnavailable": "Unavailable",
- "creditMultiple": "{{multiple}}× the period credits of {{name}}",
- "credits": {
- "MONTH": "{{amount}} credits each month",
- "YEAR": "{{amount}} credits each year"
- }
- },
"sidebar": "Balance & Plans",
"settings": {
"title": "Usage and billing",
@@ -12259,7 +12241,7 @@
"observedAt": "Balance updated {{date}}",
"poolDetail": "Used {{used}} · Total {{total}}",
"remaining": "Remaining",
- "progressLabel": "{{label}} remaining percentage",
+ "progressLabel": "{{label}} usage",
"noPlanCredits": "No plan balance because there is no active subscription.",
"historyUnavailable": "Usage history is incomplete. Only the remaining balance is available.",
"detailsUnavailable": "Usage details are temporarily unavailable. Current balances are shown instead.",
@@ -12328,7 +12310,6 @@
},
"dialogs": {
"subscription": {
- "confirmTitle": "Confirm subscription",
"title": "Choose a subscription plan"
},
"topup": {
@@ -12421,9 +12402,13 @@
"failedBody": "Payment failed. Try again later or contact support."
},
"planChange": {
- "emptyTitle": "No plans available to switch to",
"targetTitle": "Change subscription plan",
"back": "Back",
+ "upgradeBadge": "Upgrade",
+ "sameLevelBadge": "Same tier",
+ "downgradeBadge": "Downgrade",
+ "emptyTitle": "No plans available to switch to",
+ "emptyDescription": "There are no other plans available to switch to.",
"quotingTitle": "Preparing plan change",
"quotingBody": "Confirming the price and effective time…",
"quoteTitle": "Confirm plan change",
@@ -12786,7 +12771,19 @@
"mainCommit": "main Version",
"currentBranch": "Current Project Branch",
"detached": "No branch (fixed commit)",
- "unknown": "Update source to check"
+ "unknown": "Update source to check",
+ "latest": {
+ "dev": "Latest main",
+ "beta": "Latest Beta",
+ "release": "Latest Release",
+ "unavailable": "Could not check — reopen Settings to retry",
+ "same": "(up to date)",
+ "behind_one": "({{count}} commit behind)",
+ "behind_other": "({{count}} commits behind)",
+ "ahead_one": "({{count}} commit ahead)",
+ "ahead_other": "({{count}} commits ahead)",
+ "difference": "({{behind}} behind, {{ahead}} ahead)"
+ }
}
},
"code": {
@@ -12814,8 +12811,8 @@
"projectClearing": "The personal-build project is being cleared. Wait before sending another message.",
"inputLocked": {
"executing": "Cindy Make is running your first request",
- "hint": "Input resumes after this run. You can still answer questions and review plans.",
- "retry": "Input is unavailable. Retry from the preparation card above."
+ "hint": "Input becomes available when preparation finishes.",
+ "retry": "Preparation is incomplete. Retry to continue."
},
"dependencyActivity": {
"starting": "Starting dependency installation…",
@@ -12824,7 +12821,7 @@
},
"dependencyProgress": "Resolved {{resolved}} · reused {{reused}} · downloaded {{downloaded}} · added {{added}}",
"taskName": "Cindy Make personal build",
- "taskTitle": "[Cindy-Make] {{request}}",
+ "taskTitle": "[{{worktree}}] {{request}}",
"workspace": "Workspace {{branch}}"
},
"complete": {
@@ -12835,6 +12832,213 @@
"changedFiles_other": "{{count}} files changed",
"commit": "Based on {{commit}}",
"branch": "Committed to {{branch}}"
+ },
+ "versions": {
+ "title": "My Versions",
+ "description": "Choose the Cindy version to use on this computer. Switching restarts the app and keeps your accounts, settings and tasks.",
+ "original": "Original",
+ "personal": "Personal Version",
+ "development": "Development Environment",
+ "current": "Current",
+ "using": "In Use",
+ "switch": "Switch and Restart",
+ "switchPersonal": "Switch to This Personal Version",
+ "remove": "Delete Version",
+ "removeTitle": "Delete this personal version?",
+ "removeDescription": "Only the generated application files are deleted. Source code, accounts, settings and tasks are kept.",
+ "empty": "No switchable personal versions have been built yet.",
+ "unavailable": "The application files for this version are unavailable.",
+ "incompatible": "This version is incompatible with the current data. Rebuild it from the current original version.",
+ "readyHint": "Your personal version is ready. Switching restarts Cindy and keeps your accounts, settings and tasks.",
+ "errors": {
+ "busy": "Tasks, tests or builds are still running. Finish them before switching or deleting a version.",
+ "incompatible": "The data structures differ. Rebuild your personal version from the current original version before switching.",
+ "unavailable": "This version could not be read. Rebuild it and try again.",
+ "launchFailed": "The target version could not start. The current version has been kept.",
+ "recovery": "The selected version could not start. The original version is now the default. Reopen Cindy from its original entry point. Your data has been kept."
+ },
+ "localChanges": "Local changes"
+ },
+ "personal": {
+ "generate": "Build Personal Version",
+ "open": "Show Installer",
+ "description": "Merge these changes with your personal version, then save the new version after checks and packaging pass.",
+ "readyHint": "Installer {{name}} is ready. Open its folder to install it.",
+ "checkStep": {
+ "dependencies": "Installing build dependencies…",
+ "tests": "Running automated tests; this may take several minutes…",
+ "types": "Checking code types…"
+ },
+ "status": {
+ "waiting": "Waiting to Build Personal Version…",
+ "merging": "Merging Changes…",
+ "checking": "Checking Personal Version…",
+ "packaging": "Packaging Personal Version…",
+ "publishing": "Saving Personal Version…",
+ "ready": "Personal Version Built",
+ "failed": "Personal Version Could Not Be Built"
+ },
+ "errors": {
+ "unavailable": "The build record or installer is unavailable. Build the personal version again.",
+ "changed": "The task directory or code has changed. Finish editing before building again.",
+ "environment": "Build tools are not ready. Check the Cindy Make environment and retry.",
+ "missingShell": "Automated checks require Git Bash. Install Git for Windows and retry.",
+ "checksFailed": "The merged code did not pass checks. Continue editing before building again.",
+ "conflict": "These changes conflict with the current personal version. Continue editing to resolve the conflict.",
+ "baselineChanged": "The personal version changed during the build. Build again to include the latest changes.",
+ "buildFailed": "Packaging did not finish. Retry or continue editing before building again.",
+ "cancelled": "Generation cancelled. You can generate again.",
+ "cleanupFailed": "Generation stopped, but temporary files could not all be cleaned. Restart Cindy and try again.",
+ "interrupted": "The build stopped. You can build the personal version again."
+ }
+ },
+ "test": {
+ "title": "Changes Complete — Choose Next Step",
+ "description": "Continue editing, try an isolated test build, or build your personal installer.",
+ "readyHint": "Try the changes in the test window. Continue Editing closes it and restores input.",
+ "start": "Launch Isolated Test Build",
+ "started": "Test Build Launched",
+ "continue": "Continue Editing",
+ "status": {
+ "waiting": "Changes Complete — Choose Next Step",
+ "starting": "Launching Isolated Test Build…",
+ "ready": "Test Build Ready to Try",
+ "failed": "Test Build Could Not Start",
+ "stopped": "Ready to Launch Again"
+ },
+ "errors": {
+ "unavailable": "The saved changes or working directory are no longer available. Continue editing and report completion again.",
+ "changed": "The code has changed since completion. Finish editing before testing again.",
+ "environment": "The test environment is not ready. Check Cindy Make in Settings and retry.",
+ "launchFailed": "The test build could not start. Retry or return to editing.",
+ "timeout": "The test build took too long to start. Retry the launch.",
+ "interrupted": "The previous test was interrupted. Launch the isolated build again."
+ }
+ },
+ "history": {
+ "title": "Make history",
+ "build": "Generate personal version",
+ "buildDescription": "Generate a new version from the current personal source. Changes not yet integrated are excluded.",
+ "building": "Generating personal version…",
+ "stop": "Stop making",
+ "stopping": "Stopping…",
+ "progress": {
+ "waiting": "Waiting to start",
+ "merging": "Merging changes",
+ "checking": "Running checks",
+ "packaging": "Packaging personal version",
+ "publishing": "Saving personal version"
+ },
+ "noActions": {
+ "ended": "This making task has ended; no actions are available.",
+ "sessionUnavailable": "This task record is no longer available.",
+ "completionUnavailable": "The completion could not be verified, so no safe action is available.",
+ "sourceUnavailable": "The personal source could not be verified, so no safe action is available.",
+ "changedAfterCompletion": "The recorded completion no longer matches the source, so no safe action is available.",
+ "busy": "Another making operation or check is running. Try again when it finishes.",
+ "checking": "This making record is still being checked. Try again shortly."
+ },
+ "counts": "{{total}} total · {{pending}} pending integration · {{integrated}} integrated",
+ "filterLabel": "Filter make history",
+ "filters": {
+ "all": "All builds",
+ "pending": "Pending integration",
+ "integrated": "Integrated",
+ "ended": "Ended"
+ },
+ "loadFailed": "Could not load make history. Please retry.",
+ "loading": "Loading make history…",
+ "actionFailed": "The operation did not finish. Refresh and retry.",
+ "openInstaller": "Show installer",
+ "updated": "Updated {{time}}",
+ "needsBuild": "The source has changed. Generate a personal version to use these changes.",
+ "built": "Included in the personal version generated {{time}}",
+ "builtKnown": "Included in a generated personal version",
+ "conflict": "The changes conflict. Open the resolution task to continue.",
+ "rounds": "{{count}} editing rounds",
+ "round": "Round {{number}} · {{time}}",
+ "files": "{{count}} files changed",
+ "working": "Working…",
+ "endAndClean": "End and clean up",
+ "endConfirm": "End this build and remove its working directory? Make history and retained changes will remain available.",
+ "revertConfirm": "Undo the changes from this build in the personal source? Other builds and generated applications will be kept.",
+ "lifecycle": {
+ "preparing": "Preparing",
+ "running": "Making changes",
+ "editing": "Editing",
+ "ready": "Ready for next step",
+ "failed": "Preparation failed",
+ "ended": "Ended",
+ "cleanup": "Cleaning up"
+ },
+ "integration": {
+ "unintegrated": "Not integrated",
+ "integrated": "Integrated",
+ "changed": "New changes to integrate",
+ "reverted": "Integration undone",
+ "unknown": "Integration status unverified",
+ "unchanged": "No changes to integrate"
+ },
+ "actions": {
+ "open": "Open task",
+ "continue": "Continue editing",
+ "test": "Launch isolated test build",
+ "integrate": "Integrate into personal version",
+ "revert": "Undo integration",
+ "reapply": "Reapply integration",
+ "resolve": "Resolve conflicts",
+ "retry": "Retry",
+ "build": "Generate personal version",
+ "retryBuild": "Retry generation",
+ "end": "End build",
+ "retry-prepare": "Retry preparation",
+ "retry-cleanup": "Retry cleanup"
+ },
+ "buildStatus": {
+ "waiting": "Waiting to generate personal version…",
+ "checking": "Checking personal version…",
+ "merging": "Integrating changes…",
+ "packaging": "Packaging personal version…",
+ "publishing": "Saving personal version…",
+ "ready": "Personal version generated",
+ "failed": "Personal version generation failed",
+ "installerReady": "Installer ready"
+ },
+ "rounds_one": "{{count}} editing round",
+ "rounds_other": "{{count}} editing rounds",
+ "files_one": "{{count}} file changed",
+ "files_other": "{{count}} files changed"
+ },
+ "merge": {
+ "getLatest": "Get latest source",
+ "updateHint": "Update official source and reapply your personal changes.",
+ "confirmTitle": "Update to the latest source?",
+ "confirmDescription": "Your personal changes will be kept. If conflicts occur, a separate task will help resolve them.",
+ "confirm": "Update source",
+ "openTask": "Open resolution task",
+ "resolve": "Resolve conflicts",
+ "resolveHint": "Open a separate task to resolve conflicts and check the result.",
+ "otherAccount": "Another account started this operation. Switch back to that account to continue.",
+ "status": {
+ "fetching": "Fetching latest source…",
+ "merging": "Integrating source changes…",
+ "conflict": "Conflicts need attention",
+ "resolving": "Resolving conflicts",
+ "checking": "Checking changes…",
+ "merged": "Source changes integrated",
+ "failed": "Source integration failed"
+ },
+ "errors": {
+ "busy": "Another operation is running. Wait and retry.",
+ "dirty": "The source has uncommitted changes. Save them before retrying.",
+ "localMain": "The main branch has local commits. Check them before updating.",
+ "unavailable": "The source or operation record is unavailable. Refresh and retry.",
+ "gitFailed": "Git could not finish the operation. Please retry.",
+ "baselineChanged": "The personal source has changed. Retry using its latest state.",
+ "checksFailed": "The changes did not pass checks. Open the resolution task to continue.",
+ "interrupted": "The operation was interrupted. Your changes are kept; please retry.",
+ "startFailed": "Could not open the resolution task. Please retry."
+ }
}
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 62e4a0f2a0..6358bf85b1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5746,7 +5746,11 @@
"failed": "準備に失敗",
"cancelled": "準備を停止",
"cleaning": "クリーンアップ中",
- "cleanup": "クリーンアップ待ち"
+ "cleanup": "クリーンアップ待ち",
+ "cleanupFailed": "クリーンアップに失敗",
+ "integrated": "取り込み済み",
+ "unintegrated": "未取り込み",
+ "unknown": "取り込み状態が未確認"
},
"errors": {
"busy": "タスクまたはフォルダーは使用中です。停止して再試行してください。",
@@ -5755,7 +5759,17 @@
"cleanupFailed": "クリーンアップは未完了です。記録を保持しているため再試行できます。",
"directoryBusy": "開発フォルダー内のファイルが使用中か、削除できません。このフォルダーを使用しているターミナル、エディター、プレビューを閉じてから、クリーンアップを再試行してください。",
"unavailable": "タスクまたは開発フォルダーが変更されました。更新して再試行してください。"
- }
+ },
+ "end": "制作を終了",
+ "endHint": "制作を終了すると作業ディレクトリを削除し、制作履歴と保存済みの変更を保持します。",
+ "endConfirm": "「{{title}}」を終了して作業ディレクトリを削除しますか?制作履歴と保存済みの変更は保持されます。",
+ "cleanupDeletedConfirm": "「{{title}}」の残っている作業ディレクトリを削除しますか?保存済みの制作履歴は保持されます。",
+ "endUnintegrated": "個人版に取り込まれていない変更があります。制作を終了しても自動では取り込まれません。",
+ "endUnknown": "取り込み状態を確認できません。変更を確認してからクリーンアップしてください。"
+ },
+ "tabs": {
+ "versions": "バージョン管理",
+ "environment": "環境準備"
}
}
},
@@ -12157,38 +12171,6 @@
}
},
"billing": {
- "comparison": {
- "free": "FREE",
- "freeUsage": "無料で利用",
- "priceFromSuffix": "〜",
- "topup": "必要な分だけチャージ",
- "topupExpiry": "チャージしたクレジットは無期限",
- "agent": "Agent の全機能",
- "apiKey": "自分の API key を使用",
- "existingSubscription": "既存のサブスクリプションを接続",
- "localModels": "ローカルモデルに対応",
- "basicModels": "基本モデルを利用",
- "subscription": "サブスクリプション",
- "rollover": "未使用クレジットは{{period}}も利用可能(最大 {{amount}})",
- "nextPeriod": {
- "MONTH": "翌月",
- "YEAR": "翌年",
- "OTHER": "次の期間"
- },
- "includesFree": "FREE の全機能を含む",
- "advancedModels": "上位モデルを利用可能に",
- "managedService": "公式サービス、設定不要",
- "topupUnlock": "必要な分だけ支払い、上位モデルを利用",
- "select": "{{name}} を選択",
- "upgrade": "{{name}} にアップグレード",
- "downgrade": "{{name}} にダウングレード",
- "changeUnavailable": "変更不可",
- "creditMultiple": "{{name}} の {{multiple}} 倍の期間クレジット",
- "credits": {
- "MONTH": "毎月 {{amount}} のクレジット",
- "YEAR": "毎年 {{amount}} のクレジット"
- }
- },
"sidebar": "残高とプラン",
"settings": {
"title": "使用量と請求",
@@ -12242,7 +12224,7 @@
"observedAt": "残高更新: {{date}}",
"poolDetail": "使用済み {{used}} · 合計 {{total}}",
"remaining": "残り",
- "progressLabel": "{{label}}の残りの割合",
+ "progressLabel": "{{label}}の使用量",
"noPlanCredits": "有効なサブスクリプションがないため、プラン残高はありません。",
"historyUnavailable": "使用履歴が完全ではないため、残りの残高のみ表示しています。",
"detailsUnavailable": "使用量の詳細を取得できないため、現在の残高のみ表示しています。",
@@ -12311,7 +12293,6 @@
},
"dialogs": {
"subscription": {
- "confirmTitle": "サブスクリプションの確認",
"title": "サブスクリプションプランを選択"
},
"topup": {
@@ -12404,9 +12385,13 @@
"failedBody": "支払いに失敗しました。しばらくしてからもう一度お試しください。"
},
"planChange": {
- "emptyTitle": "切り替え可能なプランがありません",
"targetTitle": "サブスクリプションプランの変更",
"back": "戻る",
+ "upgradeBadge": "アップグレード",
+ "sameLevelBadge": "同じレベル",
+ "downgradeBadge": "ダウングレード",
+ "emptyTitle": "切り替え可能なプランがありません",
+ "emptyDescription": "現在、切り替え可能な他のプランはありません。",
"quotingTitle": "プラン変更を準備中",
"quotingBody": "金額と適用時期を確認しています…",
"quoteTitle": "プラン変更の確認",
@@ -12769,7 +12754,19 @@
"mainCommit": "main のバージョン",
"currentBranch": "プロジェクトの現在のブランチ",
"detached": "ブランチなし(固定コミット)",
- "unknown": "ソースを更新して確認"
+ "unknown": "ソースを更新して確認",
+ "latest": {
+ "dev": "最新の main",
+ "beta": "最新の beta",
+ "release": "最新の正式版",
+ "unavailable": "確認できませんでした。設定を開き直して再試行してください",
+ "same": "(同期済み)",
+ "behind_one": "({{count}} コミット遅れ)",
+ "behind_other": "({{count}} コミット遅れ)",
+ "ahead_one": "({{count}} コミット先行)",
+ "ahead_other": "({{count}} コミット先行)",
+ "difference": "({{behind}} コミット遅れ、{{ahead}} コミット先行)"
+ }
}
},
"code": {
@@ -12797,8 +12794,8 @@
"projectClearing": "個人版のプロジェクトを削除中です。完了してからメッセージを送信してください。",
"inputLocked": {
"executing": "Cindy Make が初回のリクエストを実行中",
- "hint": "初回の実行が終わると入力できます。質問への回答やプランの確認は引き続き行えます。",
- "retry": "入力は一時的に無効です。上の準備カードから再試行してください。"
+ "hint": "準備が完了すると入力でき、編集を始められます。",
+ "retry": "準備が完了していません。再試行すると続行できます。"
},
"dependencyActivity": {
"starting": "依存関係のインストールを開始中…",
@@ -12807,7 +12804,7 @@
},
"dependencyProgress": "解決 {{resolved}} · 再利用 {{reused}} · ダウンロード {{downloaded}} · 追加 {{added}}",
"taskName": "Cindy Make 個人版",
- "taskTitle": "[Cindy-Make] {{request}}",
+ "taskTitle": "[{{worktree}}] {{request}}",
"workspace": "作業ディレクトリ {{branch}}"
},
"complete": {
@@ -12818,6 +12815,211 @@
"changedFiles_other": "{{count}} 個のファイルを変更",
"commit": "{{commit}} を基準",
"branch": "{{branch}} にコミット済み"
+ },
+ "versions": {
+ "title": "マイバージョン",
+ "description": "このコンピューターで使う Cindy のバージョンを選びます。切り替えると再起動し、アカウント、設定、タスクを引き継ぎます。",
+ "original": "オリジナル版",
+ "personal": "個人版",
+ "development": "開発環境",
+ "current": "現在使用中",
+ "using": "使用中",
+ "switch": "切り替えて再起動",
+ "switchPersonal": "この個人版に切り替える",
+ "remove": "バージョンを削除",
+ "removeTitle": "この個人版を削除しますか?",
+ "removeDescription": "生成されたアプリのファイルだけを削除します。ソースコード、アカウント、設定、タスクは保持されます。",
+ "empty": "切り替え可能な個人版はまだありません。",
+ "unavailable": "このバージョンのアプリファイルを利用できません。",
+ "incompatible": "現在のデータと互換性がありません。現在のオリジナル版から再度ビルドしてください。",
+ "readyHint": "個人版の準備ができました。切り替えると Cindy が再起動し、アカウント、設定、タスクを引き継ぎます。",
+ "errors": {
+ "busy": "タスク、テスト、ビルドが実行中です。終了してから切り替えまたは削除してください。",
+ "incompatible": "データ構造が異なります。現在のオリジナル版から個人版を再度ビルドしてください。",
+ "unavailable": "このバージョンを読み込めません。再度ビルドしてお試しください。",
+ "launchFailed": "対象のバージョンを起動できませんでした。現在のバージョンは保持されています。",
+ "recovery": "選択したバージョンを起動できませんでした。オリジナル版を既定に戻しました。元の起動元から Cindy を開き直してください。データは保持されています。"
+ },
+ "localChanges": "ローカル変更あり"
+ },
+ "personal": {
+ "generate": "個人版をビルド",
+ "open": "インストーラーの場所を開く",
+ "description": "今回の変更を個人版にマージし、チェックとパッケージ化が完了してから新しい個人版として保存します。",
+ "readyHint": "インストーラー {{name}} を作成しました。保存先フォルダーを開けます。",
+ "checkStep": {
+ "dependencies": "ビルドに必要な依存関係をインストール中…",
+ "tests": "自動テストを実行中です。数分かかる場合があります…",
+ "types": "コードの型をチェック中…"
+ },
+ "status": {
+ "waiting": "個人版のビルド待ち…",
+ "merging": "変更をマージ中…",
+ "checking": "個人版を確認中…",
+ "packaging": "個人版をパッケージ化中…",
+ "publishing": "個人版を保存中…",
+ "ready": "個人版を作成しました",
+ "failed": "個人版を作成できませんでした"
+ },
+ "errors": {
+ "unavailable": "ビルド記録またはインストーラーを読み込めません。再度ビルドしてください。",
+ "changed": "作業ディレクトリまたはコードが変更されています。編集を完了してから再度ビルドしてください。",
+ "environment": "ビルドツールの準備ができていません。Cindy Make の環境を確認し、再試行してください。",
+ "missingShell": "自動チェックには Git Bash が必要です。Git for Windows をインストールして再試行してください。",
+ "checksFailed": "マージ後のコードがチェックに通りませんでした。編集を続けてから再度ビルドしてください。",
+ "conflict": "現在の個人版と変更が競合しています。編集を続けて競合を解決してください。",
+ "baselineChanged": "ビルド中に個人版が更新されました。最新の変更を含めるため、再度ビルドしてください。",
+ "buildFailed": "パッケージ化が完了しませんでした。再試行するか、編集を続けてください。",
+ "cancelled": "制作をキャンセルしました。もう一度生成できます。",
+ "cleanupFailed": "制作を停止しましたが、一部の一時ファイルを削除できませんでした。Cindyを再起動して再試行してください。",
+ "interrupted": "ビルドを停止しました。個人版を再度ビルドできます。"
+ }
+ },
+ "test": {
+ "title": "変更完了・次の操作を選択",
+ "description": "編集を続けるか、隔離テスト版を起動するか、個人版のインストーラーを作成できます。",
+ "readyHint": "テスト用ウィンドウで変更を確認してください。「編集を続ける」を選ぶとテスト版を閉じ、入力に戻ります。",
+ "start": "隔離テスト版を起動",
+ "started": "テスト版を起動済み",
+ "continue": "編集を続ける",
+ "status": {
+ "waiting": "変更完了・次の操作を選択",
+ "starting": "隔離テスト版を起動中…",
+ "ready": "テスト版の準備ができました",
+ "failed": "テスト版を起動できませんでした",
+ "stopped": "テスト版を再起動できます"
+ },
+ "errors": {
+ "unavailable": "変更の記録または作業ディレクトリが変更されました。編集を続け、もう一度完了を報告してください。",
+ "changed": "完了後にコードが変更されています。編集を完了してからテストしてください。",
+ "environment": "テスト環境の準備ができていません。設定の Cindy Make で環境を確認し、再試行してください。",
+ "launchFailed": "テスト版を起動できませんでした。再試行するか、編集に戻ってください。",
+ "timeout": "テスト版の起動がタイムアウトしました。再試行してください。",
+ "interrupted": "前回のテストは中断されました。隔離テスト版を再起動してください。"
+ }
+ },
+ "history": {
+ "title": "制作履歴",
+ "build": "個人版を生成",
+ "buildDescription": "現在の個人版ソースから新しいバージョンを生成します。未取り込みの過去の変更は含まれません。",
+ "building": "個人版を生成中…",
+ "stop": "制作を停止",
+ "stopping": "停止中…",
+ "progress": {
+ "waiting": "開始を待機中",
+ "merging": "変更を統合中",
+ "checking": "チェックを実行中",
+ "packaging": "個人版をパッケージ中",
+ "publishing": "個人版を保存中"
+ },
+ "noActions": {
+ "ended": "この制作は終了しているため、実行できる操作はありません。",
+ "sessionUnavailable": "この制作タスクの記録は利用できません。",
+ "completionUnavailable": "完了状態を確認できないため、安全な操作はありません。",
+ "sourceUnavailable": "個人用ソースを確認できないため、安全な操作はありません。",
+ "changedAfterCompletion": "完了時と現在のソースが一致しないため、安全な操作はありません。",
+ "busy": "別の制作またはチェックが実行中です。完了後に再試行してください。",
+ "checking": "この制作記録を確認中です。しばらくしてから再試行してください。"
+ },
+ "counts": "合計 {{total}} 件 · 未取り込み {{pending}} 件 · 取り込み済み {{integrated}} 件",
+ "filterLabel": "制作履歴を絞り込む",
+ "filters": {
+ "all": "すべての制作",
+ "pending": "未取り込み",
+ "integrated": "取り込み済み",
+ "ended": "終了済み"
+ },
+ "loadFailed": "制作履歴を読み込めませんでした。再試行してください。",
+ "loading": "制作履歴を読み込み中…",
+ "actionFailed": "操作を完了できませんでした。更新して再試行してください。",
+ "openInstaller": "インストーラーを表示",
+ "updated": "更新日時:{{time}}",
+ "needsBuild": "ソースが変更されています。個人版を生成すると変更を使えます。",
+ "built": "{{time}} に生成した個人版に含まれています",
+ "builtKnown": "生成済みの個人版に含まれています",
+ "conflict": "変更が競合しています。解決用タスクを開いて続行してください。",
+ "rounds": "編集 {{count}} 回",
+ "round": "{{number}} 回目 · {{time}}",
+ "files": "{{count}} ファイルを変更",
+ "working": "処理中…",
+ "endAndClean": "終了してクリーンアップ",
+ "endConfirm": "この制作を終了し、作業ディレクトリを削除しますか?制作履歴と保存済みの変更は保持されます。",
+ "revertConfirm": "この制作から個人ソースに取り込んだ変更を取り消しますか?他の制作と生成済みアプリは保持されます。",
+ "lifecycle": {
+ "preparing": "準備中",
+ "running": "変更中",
+ "editing": "編集中",
+ "ready": "次の操作を選択",
+ "failed": "準備に失敗",
+ "ended": "終了済み",
+ "cleanup": "クリーンアップ中"
+ },
+ "integration": {
+ "unintegrated": "未取り込み",
+ "integrated": "取り込み済み",
+ "changed": "新しい変更が未取り込み",
+ "reverted": "取り込みを取り消し済み",
+ "unknown": "取り込み状態が未確認",
+ "unchanged": "取り込む変更なし"
+ },
+ "actions": {
+ "open": "タスクを開く",
+ "continue": "編集を続ける",
+ "test": "隔離テスト版を起動",
+ "integrate": "個人版に取り込む",
+ "revert": "取り込みを取り消す",
+ "reapply": "再度取り込む",
+ "resolve": "競合を解決",
+ "retry": "再試行",
+ "build": "個人版を生成",
+ "retryBuild": "生成を再試行",
+ "end": "制作を終了",
+ "retry-prepare": "準備を再試行",
+ "retry-cleanup": "クリーンアップを再試行"
+ },
+ "buildStatus": {
+ "waiting": "個人版の生成を待機中…",
+ "checking": "個人版を確認中…",
+ "merging": "変更を取り込み中…",
+ "packaging": "個人版をパッケージ化中…",
+ "publishing": "個人版を保存中…",
+ "ready": "個人版を生成しました",
+ "failed": "個人版の生成に失敗しました",
+ "installerReady": "インストーラーの準備完了"
+ },
+ "rounds_other": "編集 {{count}} 回",
+ "files_other": "{{count}} ファイルを変更"
+ },
+ "merge": {
+ "getLatest": "最新ソースを取得",
+ "updateHint": "公式ソースを更新し、個人の変更を保持します。",
+ "confirmTitle": "最新ソースに更新しますか?",
+ "confirmDescription": "個人の変更は保持されます。競合が発生した場合は、専用タスクで解決を支援します。",
+ "confirm": "ソースを更新",
+ "openTask": "解決用タスクを開く",
+ "resolve": "競合を解決",
+ "resolveHint": "専用タスクで競合を解決し、結果を確認します。",
+ "otherAccount": "この操作は別のアカウントで開始されました。そのアカウントに切り替えて続行してください。",
+ "status": {
+ "fetching": "最新ソースを取得中…",
+ "merging": "ソースの変更を取り込み中…",
+ "conflict": "競合の解決が必要です",
+ "resolving": "競合を解決中",
+ "checking": "変更を確認中…",
+ "merged": "ソースの変更を取り込みました",
+ "failed": "ソースの取り込みに失敗しました"
+ },
+ "errors": {
+ "busy": "別の操作が実行中です。しばらくしてから再試行してください。",
+ "dirty": "ソースに未コミットの変更があります。保存してから再試行してください。",
+ "localMain": "main ブランチにローカルコミットがあります。確認してから更新してください。",
+ "unavailable": "ソースまたは操作記録を利用できません。更新して再試行してください。",
+ "gitFailed": "Git の操作を完了できませんでした。再試行してください。",
+ "baselineChanged": "個人ソースが変更されました。最新の状態で再試行してください。",
+ "checksFailed": "変更がチェックを通過しませんでした。解決用タスクを開いて続行してください。",
+ "interrupted": "操作が中断されました。変更は保持されています。再試行してください。",
+ "startFailed": "解決用タスクを開けませんでした。再試行してください。"
+ }
}
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 64ca6830c9..9e8e4a8920 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5746,7 +5746,11 @@
"failed": "준비 실패",
"cancelled": "준비 중지됨",
"cleaning": "정리 중",
- "cleanup": "정리 대기"
+ "cleanup": "정리 대기",
+ "cleanupFailed": "정리 실패",
+ "integrated": "반영 완료",
+ "unintegrated": "미반영",
+ "unknown": "반영 상태 미확인"
},
"errors": {
"busy": "작업 또는 폴더가 사용 중입니다. 중지한 후 다시 시도하세요.",
@@ -5755,7 +5759,17 @@
"cleanupFailed": "정리하지 못했습니다. 다시 시도할 수 있도록 기록이 유지됩니다.",
"directoryBusy": "개발 폴더의 파일이 사용 중이거나 삭제할 수 없습니다. 이 폴더를 사용하는 터미널, 편집기 또는 미리보기를 닫은 후 정리를 다시 시도하세요.",
"unavailable": "작업 또는 개발 폴더가 변경되었습니다. 새로 고침한 후 다시 시도하세요."
- }
+ },
+ "end": "제작 종료",
+ "endHint": "제작을 종료하면 작업 폴더를 정리하고 제작 기록과 저장된 변경 사항을 유지합니다.",
+ "endConfirm": "“{{title}}”을 종료하고 작업 폴더를 정리할까요? 제작 기록과 저장된 변경 사항은 유지됩니다.",
+ "cleanupDeletedConfirm": "“{{title}}”의 남은 작업 폴더를 정리할까요? 저장된 제작 기록은 유지됩니다.",
+ "endUnintegrated": "개인 버전에 반영되지 않은 변경 사항이 있습니다. 제작을 종료해도 자동으로 반영되지 않습니다.",
+ "endUnknown": "반영 상태를 확인할 수 없습니다. 변경 사항을 확인한 후 정리해 주세요."
+ },
+ "tabs": {
+ "versions": "버전 관리",
+ "environment": "환경 준비"
}
}
},
@@ -12157,38 +12171,6 @@
}
},
"billing": {
- "comparison": {
- "free": "FREE",
- "freeUsage": "무료 사용",
- "priceFromSuffix": "부터",
- "topup": "필요할 때 충전",
- "topupExpiry": "충전 크레딧은 만료되지 않음",
- "agent": "모든 Agent 기능",
- "apiKey": "내 API key 사용",
- "existingSubscription": "기존 구독 연결",
- "localModels": "로컬 모델 지원",
- "basicModels": "기본 모델 사용",
- "subscription": "구독 요금제",
- "rollover": "남은 크레딧은 {{period}}에 최대 {{amount}}까지 사용 가능",
- "nextPeriod": {
- "MONTH": "다음 달",
- "YEAR": "다음 해",
- "OTHER": "다음 기간"
- },
- "includesFree": "FREE의 모든 기능 포함",
- "advancedModels": "고급 모델 잠금 해제",
- "managedService": "공식 서비스, 설정 불필요",
- "topupUnlock": "필요한 만큼 결제하고 고급 모델 사용",
- "select": "{{name}} 선택",
- "upgrade": "{{name}}(으)로 업그레이드",
- "downgrade": "{{name}}(으)로 다운그레이드",
- "changeUnavailable": "변경 불가",
- "creditMultiple": "{{name}} 대비 {{multiple}}배의 기간 크레딧",
- "credits": {
- "MONTH": "매월 {{amount}} 크레딧",
- "YEAR": "매년 {{amount}} 크레딧"
- }
- },
"sidebar": "잔액 및 요금제",
"settings": {
"title": "사용량 및 결제",
@@ -12242,7 +12224,7 @@
"observedAt": "잔액 업데이트: {{date}}",
"poolDetail": "사용 {{used}} · 전체 {{total}}",
"remaining": "잔여",
- "progressLabel": "{{label}} 잔여 비율",
+ "progressLabel": "{{label}} 사용량",
"noPlanCredits": "활성 구독이 없어 요금제 잔액이 없습니다.",
"historyUnavailable": "사용 기록이 완전하지 않아 잔여 잔액만 표시합니다.",
"detailsUnavailable": "사용량 상세를 불러올 수 없어 현재 잔액만 표시합니다.",
@@ -12311,7 +12293,6 @@
},
"dialogs": {
"subscription": {
- "confirmTitle": "구독 확인",
"title": "구독 요금제 선택"
},
"topup": {
@@ -12404,9 +12385,13 @@
"failedBody": "결제에 실패했습니다. 나중에 다시 시도하세요."
},
"planChange": {
- "emptyTitle": "전환 가능한 플랜이 없습니다",
"targetTitle": "구독 플랜 변경",
"back": "이전",
+ "upgradeBadge": "업그레이드",
+ "sameLevelBadge": "동일 등급",
+ "downgradeBadge": "다운그레이드",
+ "emptyTitle": "전환 가능한 플랜이 없습니다",
+ "emptyDescription": "현재 전환할 수 있는 다른 요금제가 없습니다.",
"quotingTitle": "플랜 변경 준비 중",
"quotingBody": "금액과 적용 시점을 확인하는 중…",
"quoteTitle": "플랜 변경 확인",
@@ -12769,7 +12754,19 @@
"mainCommit": "main 버전",
"currentBranch": "프로젝트의 현재 브랜치",
"detached": "브랜치 없음 (고정 커밋)",
- "unknown": "소스를 업데이트해 확인하세요"
+ "unknown": "소스를 업데이트해 확인하세요",
+ "latest": {
+ "dev": "최신 main",
+ "beta": "최신 beta",
+ "release": "최신 정식 버전",
+ "unavailable": "확인하지 못했습니다. 설정을 다시 열어 재시도하세요",
+ "same": "(동기화됨)",
+ "behind_one": "({{count}}개 커밋 뒤)",
+ "behind_other": "({{count}}개 커밋 뒤)",
+ "ahead_one": "({{count}}개 커밋 앞)",
+ "ahead_other": "({{count}}개 커밋 앞)",
+ "difference": "({{behind}}개 커밋 뒤, {{ahead}}개 커밋 앞)"
+ }
}
},
"code": {
@@ -12797,8 +12794,8 @@
"projectClearing": "개인 버전 프로젝트를 정리하고 있습니다. 완료된 후 메시지를 보내세요.",
"inputLocked": {
"executing": "Cindy Make가 첫 요청을 실행 중입니다",
- "hint": "첫 실행이 끝나면 입력할 수 있습니다. 질문 응답과 계획 검토는 계속할 수 있습니다.",
- "retry": "지금은 입력할 수 없습니다. 위의 준비 카드에서 다시 시도하세요."
+ "hint": "준비가 완료되면 입력창을 사용할 수 있습니다.",
+ "retry": "준비가 완료되지 않았습니다. 다시 시도하여 계속하세요."
},
"dependencyActivity": {
"starting": "의존성 설치 시작 중…",
@@ -12807,7 +12804,7 @@
},
"dependencyProgress": "해결 {{resolved}} · 재사용 {{reused}} · 다운로드 {{downloaded}} · 추가 {{added}}",
"taskName": "Cindy Make 개인 버전",
- "taskTitle": "[Cindy-Make] {{request}}",
+ "taskTitle": "[{{worktree}}] {{request}}",
"workspace": "작업 디렉터리 {{branch}}"
},
"complete": {
@@ -12818,6 +12815,211 @@
"changedFiles_other": "{{count}}개 파일 변경됨",
"commit": "{{commit}} 기준",
"branch": "{{branch}}에 커밋됨"
+ },
+ "versions": {
+ "title": "내 버전",
+ "description": "이 컴퓨터에서 사용할 Cindy 버전을 선택하세요. 전환하면 앱이 다시 시작되며 계정, 설정, 작업은 유지됩니다.",
+ "original": "기본 버전",
+ "personal": "개인 버전",
+ "development": "개발 환경",
+ "current": "현재 사용",
+ "using": "사용 중",
+ "switch": "전환 후 다시 시작",
+ "switchPersonal": "이 개인 버전으로 전환",
+ "remove": "버전 삭제",
+ "removeTitle": "이 개인 버전을 삭제할까요?",
+ "removeDescription": "생성된 앱 파일만 삭제합니다. 소스 코드, 계정, 설정, 작업은 유지됩니다.",
+ "empty": "아직 전환할 수 있는 개인 버전이 없습니다.",
+ "unavailable": "이 버전의 앱 파일을 사용할 수 없습니다.",
+ "incompatible": "현재 데이터와 호환되지 않습니다. 현재 기본 버전에서 다시 빌드하세요.",
+ "readyHint": "개인 버전이 준비되었습니다. 전환하면 Cindy가 다시 시작되며 계정, 설정, 작업은 유지됩니다.",
+ "errors": {
+ "busy": "작업, 테스트 또는 빌드가 진행 중입니다. 완료한 후 버전을 전환하거나 삭제하세요.",
+ "incompatible": "데이터 구조가 다릅니다. 현재 기본 버전에서 개인 버전을 다시 빌드하세요.",
+ "unavailable": "이 버전을 읽을 수 없습니다. 다시 빌드한 후 시도하세요.",
+ "launchFailed": "대상 버전을 시작하지 못했습니다. 현재 버전은 유지됩니다.",
+ "recovery": "선택한 버전을 시작하지 못했습니다. 기본 버전을 다시 기본값으로 설정했습니다. 원래 실행 경로에서 Cindy를 다시 여세요. 기존 데이터는 유지됩니다."
+ },
+ "localChanges": "로컬 변경 사항 있음"
+ },
+ "personal": {
+ "generate": "개인 버전 빌드",
+ "open": "설치 파일 위치 열기",
+ "description": "이번 수정 사항을 개인 버전에 병합하고, 검사와 패키징을 통과한 후 새 개인 버전으로 저장합니다.",
+ "readyHint": "설치 파일 {{name}}이 준비되었습니다. 저장된 폴더를 열 수 있습니다.",
+ "checkStep": {
+ "dependencies": "빌드 의존성 설치 중…",
+ "tests": "자동 테스트 실행 중입니다. 몇 분 정도 걸릴 수 있습니다…",
+ "types": "코드 타입 검사 중…"
+ },
+ "status": {
+ "waiting": "개인 버전 빌드 대기 중…",
+ "merging": "수정 사항 병합 중…",
+ "checking": "개인 버전 검사 중…",
+ "packaging": "개인 버전 패키징 중…",
+ "publishing": "개인 버전 저장 중…",
+ "ready": "개인 버전 생성 완료",
+ "failed": "개인 버전을 생성하지 못했습니다"
+ },
+ "errors": {
+ "unavailable": "빌드 기록이나 설치 파일을 읽을 수 없습니다. 개인 버전을 다시 빌드하세요.",
+ "changed": "작업 디렉터리나 코드가 변경되었습니다. 수정을 완료한 후 다시 빌드하세요.",
+ "environment": "빌드 도구가 준비되지 않았습니다. Cindy Make 환경을 확인한 후 다시 시도하세요.",
+ "missingShell": "자동 검사에는 Git Bash가 필요합니다. Git for Windows를 설치한 후 다시 시도하세요.",
+ "checksFailed": "병합한 코드가 검사를 통과하지 못했습니다. 수정을 계속한 후 다시 빌드하세요.",
+ "conflict": "현재 개인 버전과 수정 사항이 충돌합니다. 편집을 계속하여 충돌을 해결하세요.",
+ "baselineChanged": "빌드 중에 개인 버전이 변경되었습니다. 최신 수정 사항을 포함하려면 다시 빌드하세요.",
+ "buildFailed": "패키징이 완료되지 않았습니다. 다시 시도하거나 수정을 계속하세요.",
+ "cancelled": "제작이 취소되었습니다. 다시 생성할 수 있습니다.",
+ "cleanupFailed": "제작을 중지했지만 일부 임시 파일을 정리하지 못했습니다. Cindy를 다시 시작한 뒤 다시 시도하세요.",
+ "interrupted": "빌드가 중지되었습니다. 개인 버전을 다시 빌드할 수 있습니다."
+ }
+ },
+ "test": {
+ "title": "수정 완료 · 다음 단계 선택",
+ "description": "수정을 계속하거나, 격리 테스트 버전을 실행하거나, 개인 버전 설치 파일을 생성할 수 있습니다.",
+ "readyHint": "테스트 창에서 수정 사항을 확인하세요. 계속 수정을 선택하면 테스트 버전이 종료되고 입력창으로 돌아갑니다.",
+ "start": "격리 테스트 버전 실행",
+ "started": "테스트 버전 실행됨",
+ "continue": "계속 수정",
+ "status": {
+ "waiting": "수정 완료 · 다음 단계 선택",
+ "starting": "격리 테스트 버전 실행 중…",
+ "ready": "테스트 버전 준비 완료",
+ "failed": "테스트 버전을 실행하지 못했습니다",
+ "stopped": "테스트 버전을 다시 실행할 수 있습니다"
+ },
+ "errors": {
+ "unavailable": "수정 기록이나 작업 디렉터리가 변경되었습니다. 수정을 계속한 후 완료를 다시 보고하세요.",
+ "changed": "완료 후 코드가 변경되었습니다. 수정을 마친 후 다시 테스트하세요.",
+ "environment": "테스트 환경이 준비되지 않았습니다. 설정의 Cindy Make에서 환경을 확인한 후 다시 시도하세요.",
+ "launchFailed": "테스트 버전을 실행하지 못했습니다. 다시 시도하거나 편집으로 돌아가세요.",
+ "timeout": "테스트 버전 실행 시간이 초과되었습니다. 다시 시도하세요.",
+ "interrupted": "이전 테스트가 중단되었습니다. 격리 테스트 버전을 다시 실행하세요."
+ }
+ },
+ "history": {
+ "title": "제작 기록",
+ "build": "개인 버전 생성",
+ "buildDescription": "현재 개인 소스로 새 버전을 생성합니다. 아직 반영하지 않은 이전 변경 사항은 포함되지 않습니다.",
+ "building": "개인 버전 생성 중…",
+ "stop": "제작 중지",
+ "stopping": "중지 중…",
+ "progress": {
+ "waiting": "시작 대기 중",
+ "merging": "변경 사항 병합 중",
+ "checking": "검사 실행 중",
+ "packaging": "개인 버전 패키징 중",
+ "publishing": "개인 버전 저장 중"
+ },
+ "noActions": {
+ "ended": "이 제작은 종료되어 실행할 수 있는 작업이 없습니다.",
+ "sessionUnavailable": "이 제작 작업 기록을 사용할 수 없습니다.",
+ "completionUnavailable": "완료 상태를 확인할 수 없어 안전한 작업이 없습니다.",
+ "sourceUnavailable": "개인 소스 코드를 확인할 수 없어 안전한 작업이 없습니다.",
+ "changedAfterCompletion": "완료 당시와 현재 소스가 일치하지 않아 안전한 작업이 없습니다.",
+ "busy": "다른 제작 또는 검사가 진행 중입니다. 완료 후 다시 시도하세요.",
+ "checking": "이 제작 기록을 확인하는 중입니다. 잠시 후 다시 시도하세요."
+ },
+ "counts": "전체 {{total}}회 · 반영 대기 {{pending}}회 · 반영 완료 {{integrated}}회",
+ "filterLabel": "제작 기록 필터",
+ "filters": {
+ "all": "전체 제작",
+ "pending": "반영 대기",
+ "integrated": "반영 완료",
+ "ended": "종료됨"
+ },
+ "loadFailed": "제작 기록을 불러오지 못했습니다. 다시 시도해 주세요.",
+ "loading": "제작 기록 불러오는 중…",
+ "actionFailed": "작업을 완료하지 못했습니다. 새로 고친 후 다시 시도해 주세요.",
+ "openInstaller": "설치 파일 보기",
+ "updated": "업데이트: {{time}}",
+ "needsBuild": "소스가 변경되었습니다. 개인 버전을 생성하면 변경 사항을 사용할 수 있습니다.",
+ "built": "{{time}}에 생성한 개인 버전에 포함됨",
+ "builtKnown": "생성된 개인 버전에 포함됨",
+ "conflict": "변경 사항이 충돌합니다. 해결 작업을 열어 계속해 주세요.",
+ "rounds": "수정 {{count}}회",
+ "round": "{{number}}차 · {{time}}",
+ "files": "파일 {{count}}개 변경",
+ "working": "처리 중…",
+ "endAndClean": "종료 및 정리",
+ "endConfirm": "이 제작을 종료하고 작업 폴더를 정리할까요? 제작 기록과 저장된 변경 사항은 유지됩니다.",
+ "revertConfirm": "이 제작에서 개인 소스에 반영한 변경 사항을 취소할까요? 다른 제작과 생성된 앱은 유지됩니다.",
+ "lifecycle": {
+ "preparing": "준비 중",
+ "running": "수정 중",
+ "editing": "편집 중",
+ "ready": "다음 단계 대기",
+ "failed": "준비 실패",
+ "ended": "종료됨",
+ "cleanup": "정리 중"
+ },
+ "integration": {
+ "unintegrated": "미반영",
+ "integrated": "반영 완료",
+ "changed": "새 변경 사항 반영 대기",
+ "reverted": "반영 취소됨",
+ "unknown": "반영 상태 미확인",
+ "unchanged": "반영할 변경 사항 없음"
+ },
+ "actions": {
+ "open": "작업 열기",
+ "continue": "수정 계속",
+ "test": "격리 테스트 버전 실행",
+ "integrate": "개인 버전에 반영",
+ "revert": "반영 취소",
+ "reapply": "다시 반영",
+ "resolve": "충돌 해결",
+ "retry": "다시 시도",
+ "build": "개인 버전 생성",
+ "retryBuild": "생성 다시 시도",
+ "end": "제작 종료",
+ "retry-prepare": "준비 다시 시도",
+ "retry-cleanup": "정리 다시 시도"
+ },
+ "buildStatus": {
+ "waiting": "개인 버전 생성 대기 중…",
+ "checking": "개인 버전 확인 중…",
+ "merging": "변경 사항 반영 중…",
+ "packaging": "개인 버전 패키징 중…",
+ "publishing": "개인 버전 저장 중…",
+ "ready": "개인 버전 생성 완료",
+ "failed": "개인 버전 생성 실패",
+ "installerReady": "설치 파일 준비 완료"
+ },
+ "rounds_other": "수정 {{count}}회",
+ "files_other": "파일 {{count}}개 변경"
+ },
+ "merge": {
+ "getLatest": "최신 소스 가져오기",
+ "updateHint": "공식 소스를 업데이트하고 개인 변경 사항을 유지합니다.",
+ "confirmTitle": "최신 소스로 업데이트할까요?",
+ "confirmDescription": "개인 변경 사항은 유지됩니다. 충돌이 발생하면 별도 작업에서 해결을 도와드립니다.",
+ "confirm": "소스 업데이트",
+ "openTask": "해결 작업 열기",
+ "resolve": "충돌 해결",
+ "resolveHint": "별도 작업에서 충돌을 해결하고 결과를 확인합니다.",
+ "otherAccount": "다른 계정에서 시작한 작업입니다. 해당 계정으로 전환해 계속해 주세요.",
+ "status": {
+ "fetching": "최신 소스 가져오는 중…",
+ "merging": "소스 변경 사항 반영 중…",
+ "conflict": "충돌 해결 필요",
+ "resolving": "충돌 해결 중",
+ "checking": "변경 사항 확인 중…",
+ "merged": "소스 변경 사항 반영 완료",
+ "failed": "소스 반영 실패"
+ },
+ "errors": {
+ "busy": "다른 작업이 진행 중입니다. 잠시 후 다시 시도해 주세요.",
+ "dirty": "소스에 커밋되지 않은 변경 사항이 있습니다. 저장한 후 다시 시도해 주세요.",
+ "localMain": "main 브랜치에 로컬 커밋이 있습니다. 확인한 후 업데이트해 주세요.",
+ "unavailable": "소스 또는 작업 기록을 사용할 수 없습니다. 새로 고친 후 다시 시도해 주세요.",
+ "gitFailed": "Git 작업을 완료하지 못했습니다. 다시 시도해 주세요.",
+ "baselineChanged": "개인 소스가 변경되었습니다. 최신 상태에서 다시 시도해 주세요.",
+ "checksFailed": "변경 사항이 검사를 통과하지 못했습니다. 해결 작업을 열어 계속해 주세요.",
+ "interrupted": "작업이 중단되었습니다. 변경 사항은 유지됩니다. 다시 시도해 주세요.",
+ "startFailed": "해결 작업을 열지 못했습니다. 다시 시도해 주세요."
+ }
}
}
}
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 4608738f30..2841eda0c3 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5746,7 +5746,11 @@
"failed": "准备失败",
"cancelled": "准备已停止",
"cleaning": "正在清理",
- "cleanup": "待清理"
+ "cleanup": "待清理",
+ "cleanupFailed": "清理失败",
+ "integrated": "已合入",
+ "unintegrated": "未合入",
+ "unknown": "合入状态待确认"
},
"errors": {
"busy": "任务仍在运行或目录正在使用,请停止后重试。",
@@ -5755,7 +5759,17 @@
"cleanupFailed": "清理未完成,记录已保留,请重试清理。",
"directoryBusy": "开发目录中的文件被占用或无法删除,请关闭使用该目录的终端、编辑器或预览后重试清理。",
"unavailable": "任务或开发目录已变化,请刷新后重试。"
- }
+ },
+ "end": "结束制作",
+ "endHint": "结束制作后会清理工作目录,保留制作历史与已保存的改动。",
+ "endConfirm": "结束“{{title}}”并清理工作目录?制作历史与已保存的改动会保留。",
+ "cleanupDeletedConfirm": "清理“{{title}}”剩余的工作目录?已保存的制作历史会保留。",
+ "endUnintegrated": "还有改动未合入个人版,结束制作不会自动合入。",
+ "endUnknown": "暂时无法确认合入状态,请先检查改动再清理。"
+ },
+ "tabs": {
+ "versions": "版本控制",
+ "environment": "环境准备"
}
}
},
@@ -12157,38 +12171,6 @@
}
},
"billing": {
- "comparison": {
- "free": "FREE",
- "freeUsage": "免费使用",
- "priceFromSuffix": "起",
- "topup": "按需充值",
- "topupExpiry": "充值点数不过期",
- "agent": "完整 Agent 功能",
- "apiKey": "自带 API key",
- "existingSubscription": "接入已有订阅",
- "localModels": "支持本地模型",
- "basicModels": "可用基础模型",
- "subscription": "订阅套餐",
- "rollover": "剩余点数可留到{{period}},最多 {{amount}}",
- "nextPeriod": {
- "MONTH": "下月",
- "YEAR": "下一年",
- "OTHER": "下期"
- },
- "includesFree": "包含 FREE 全部能力",
- "advancedModels": "解锁高级模型",
- "managedService": "官方服务,免配置",
- "topupUnlock": "按需付费,解锁高级模型",
- "select": "选择 {{name}}",
- "upgrade": "升级至 {{name}}",
- "downgrade": "降级至 {{name}}",
- "changeUnavailable": "暂不可切换",
- "creditMultiple": "{{name}} 的 {{multiple}} 倍周期点数",
- "credits": {
- "MONTH": "每月 {{amount}} 点数",
- "YEAR": "每年 {{amount}} 点数"
- }
- },
"sidebar": "余额与订阅",
"settings": {
"title": "用量和计费",
@@ -12242,7 +12224,7 @@
"observedAt": "余额更新于 {{date}}",
"poolDetail": "已用 {{used}} · 总额 {{total}}",
"remaining": "剩余",
- "progressLabel": "{{label}}剩余比例",
+ "progressLabel": "{{label}}使用进度",
"noPlanCredits": "当前无生效订阅,因此没有订阅余额。",
"historyUnavailable": "历史记录不完整,暂时仅显示剩余余额。",
"detailsUnavailable": "用量明细暂时不可用,当前仅显示各类余额。",
@@ -12311,7 +12293,6 @@
},
"dialogs": {
"subscription": {
- "confirmTitle": "确认订阅",
"title": "选择订阅套餐"
},
"topup": {
@@ -12404,9 +12385,13 @@
"failedBody": "支付失败,请稍后重试或联系支持。"
},
"planChange": {
- "emptyTitle": "暂无可切换的套餐",
"targetTitle": "更改订阅套餐",
"back": "上一步",
+ "upgradeBadge": "升级",
+ "sameLevelBadge": "同等级",
+ "downgradeBadge": "降级",
+ "emptyTitle": "暂无可切换的套餐",
+ "emptyDescription": "当前没有其他可切换的套餐。",
"quotingTitle": "正在准备套餐变更",
"quotingBody": "正在确认价格与生效时间…",
"quoteTitle": "确认套餐变更",
@@ -12769,7 +12754,19 @@
"mainCommit": "main 版本",
"currentBranch": "当前项目分支",
"detached": "未在分支上(固定提交)",
- "unknown": "更新源码后查看"
+ "unknown": "更新源码后查看",
+ "latest": {
+ "dev": "最新 main",
+ "beta": "最新 beta",
+ "release": "最新正式版",
+ "unavailable": "未能查询,请重新打开设置重试",
+ "same": "(已同步)",
+ "behind_one": "(落后 {{count}} 个提交)",
+ "behind_other": "(落后 {{count}} 个提交)",
+ "ahead_one": "(领先 {{count}} 个提交)",
+ "ahead_other": "(领先 {{count}} 个提交)",
+ "difference": "(落后 {{behind}},领先 {{ahead}} 个提交)"
+ }
}
},
"code": {
@@ -12797,8 +12794,8 @@
"projectClearing": "正在清理个人版项目,请等待清理完成后再发送消息",
"inputLocked": {
"executing": "Cindy Make 正在首次执行",
- "hint": "首次执行结束后恢复输入,提问和计划确认不受影响。",
- "retry": "输入暂不可用,请在上方准备卡片中重试。"
+ "hint": "准备完成后恢复输入,即可开始修改。",
+ "retry": "准备尚未完成,重试后可继续。"
},
"dependencyActivity": {
"starting": "正在启动依赖安装…",
@@ -12807,7 +12804,7 @@
},
"dependencyProgress": "已解析 {{resolved}} · 已复用 {{reused}} · 已下载 {{downloaded}} · 已添加 {{added}}",
"taskName": "Cindy Make 个人版",
- "taskTitle": "[Cindy-Make] {{request}}",
+ "taskTitle": "[{{worktree}}] {{request}}",
"workspace": "开发目录 {{branch}}"
},
"complete": {
@@ -12818,6 +12815,211 @@
"changedFiles_other": "{{count}} 个文件有改动",
"commit": "基于 {{commit}}",
"branch": "已提交到 {{branch}}"
+ },
+ "versions": {
+ "title": "我的版本",
+ "description": "选择本机要使用的 Cindy 版本。切换后会重启,并保留账号、设置与任务。",
+ "original": "原版",
+ "personal": "个人版",
+ "development": "开发环境",
+ "current": "当前使用",
+ "using": "正在使用",
+ "switch": "切换并重启",
+ "switchPersonal": "切换到此个人版",
+ "remove": "删除版本",
+ "removeTitle": "删除这份个人版?",
+ "removeDescription": "仅删除生成的应用文件,保留源码、账号、设置和任务。",
+ "empty": "还没有生成可切换的个人版。",
+ "unavailable": "此版本的应用文件已不可用。",
+ "incompatible": "此版本与当前数据不兼容,请基于当前原版重新生成。",
+ "readyHint": "个人版已准备好。切换后会重启 Cindy,并保留当前账号、设置和任务。",
+ "errors": {
+ "busy": "还有任务、测试或构建正在进行,请结束后再切换或删除版本。",
+ "incompatible": "数据结构不同,暂时不能切换到这份版本。请基于当前原版重新生成个人版。",
+ "unavailable": "无法读取这份版本,请重新生成后重试。",
+ "launchFailed": "未能启动目标版本,当前版本已保留。",
+ "recovery": "未能启动所选版本。已将原版恢复为默认,请从原入口重新打开 Cindy。现有数据已保留。"
+ },
+ "localChanges": "含本地改动"
+ },
+ "personal": {
+ "generate": "生成个人版",
+ "open": "查看安装包",
+ "description": "将本次修改与个人版合并,检查和打包通过后保存为新个人版。",
+ "readyHint": "安装包 {{name}} 已生成,可打开所在目录。",
+ "checkStep": {
+ "dependencies": "正在安装构建依赖…",
+ "tests": "正在运行自动测试,可能需要数分钟…",
+ "types": "正在检查代码类型…"
+ },
+ "status": {
+ "waiting": "等待生成个人版…",
+ "merging": "正在合并修改…",
+ "checking": "正在检查个人版…",
+ "packaging": "正在打包个人版…",
+ "publishing": "正在保存个人版…",
+ "ready": "个人版已生成",
+ "failed": "个人版未能生成"
+ },
+ "errors": {
+ "unavailable": "无法读取生成记录或安装包,请重新生成。",
+ "changed": "制作目录或代码已有变化,请完成修改后重新生成。",
+ "environment": "构建工具尚未就绪,请检查 Cindy Make 环境后重试。",
+ "missingShell": "自动检查需要 Git Bash,请安装 Git for Windows 后重试。",
+ "checksFailed": "合并后的代码未通过检查,请继续修改后重新生成。",
+ "conflict": "与当前个人版的修改有冲突,请继续修改并解决冲突。",
+ "baselineChanged": "生成期间个人版已有更新,请重新生成以包含最新修改。",
+ "buildFailed": "打包未完成,请重试,或继续修改后再生成。",
+ "cancelled": "制作已取消,可以重新生成个人版。",
+ "cleanupFailed": "制作已停止,但部分临时内容未能清理。请重启 Cindy 后再试。",
+ "interrupted": "生成已停止,可以重新生成个人版。"
+ }
+ },
+ "test": {
+ "title": "修改已完成,选择下一步",
+ "description": "可以继续修改、启动隔离版测试,或直接生成个人版安装包。",
+ "readyHint": "请在测试窗口体验修改。点击“继续修改”会关闭测试版并恢复输入。",
+ "start": "启动隔离版测试",
+ "started": "测试版已启动",
+ "continue": "继续修改",
+ "status": {
+ "waiting": "修改已完成,选择下一步",
+ "starting": "正在启动隔离版测试…",
+ "ready": "隔离版已启动,等待测试",
+ "failed": "隔离版未能启动",
+ "stopped": "可以再次启动测试"
+ },
+ "errors": {
+ "unavailable": "这份修改记录或工作目录已变化,请继续修改后重新完成。",
+ "changed": "代码已有新的修改,请完成修改后再启动测试。",
+ "environment": "测试环境尚未就绪,请在设置中检查 Cindy Make 环境后重试。",
+ "launchFailed": "未能启动隔离版,请重试;仍失败可返回继续修改。",
+ "timeout": "隔离版启动超时,请重试。",
+ "interrupted": "上次测试已中断,请重新启动隔离版。"
+ }
+ },
+ "history": {
+ "title": "制作历史",
+ "build": "生成个人版",
+ "buildDescription": "将当前个人源码生成新版本,未合入的历史改动不会包含在内。",
+ "building": "正在生成个人版…",
+ "stop": "停止制作",
+ "stopping": "正在停止…",
+ "progress": {
+ "waiting": "等待开始",
+ "merging": "正在合入修改",
+ "checking": "正在运行检查",
+ "packaging": "正在打包个人版",
+ "publishing": "正在保存个人版"
+ },
+ "noActions": {
+ "ended": "这次制作已结束,当前没有可执行的操作。",
+ "sessionUnavailable": "这条制作记录对应的任务已不可用。",
+ "completionUnavailable": "完成记录无法核验,暂时没有安全的操作可执行。",
+ "sourceUnavailable": "个人源码无法核验,暂时没有安全的操作可执行。",
+ "changedAfterCompletion": "记录中的完成结果与当前源码不一致,暂时没有安全的操作可执行。",
+ "busy": "另一个制作或检查正在进行,请稍后再试。",
+ "checking": "正在核对这条制作记录,请稍后再试。"
+ },
+ "counts": "共 {{total}} 次 · 待合入 {{pending}} 次 · 已合入 {{integrated}} 次",
+ "filterLabel": "筛选制作历史",
+ "filters": {
+ "all": "全部制作",
+ "pending": "待合入",
+ "integrated": "已合入",
+ "ended": "已结束"
+ },
+ "loadFailed": "无法读取制作历史,请重试。",
+ "loading": "正在读取制作历史…",
+ "actionFailed": "操作未完成,请刷新后重试。",
+ "openInstaller": "查看安装包",
+ "updated": "更新于 {{time}}",
+ "needsBuild": "源码已有改动,生成个人版后即可使用。",
+ "built": "已包含在 {{time}} 生成的个人版中",
+ "builtKnown": "已包含在生成的个人版中",
+ "conflict": "改动存在冲突,请打开处理任务继续。",
+ "rounds": "{{count}} 轮修改",
+ "round": "第 {{number}} 轮 · {{time}}",
+ "files": "改动 {{count}} 个文件",
+ "working": "正在处理…",
+ "endAndClean": "结束并清理",
+ "endConfirm": "结束这次制作并清理工作目录?制作历史与已保存的改动会保留。",
+ "revertConfirm": "撤销这次制作合入个人源码的改动?其他制作和已生成的应用会保留。",
+ "lifecycle": {
+ "preparing": "准备中",
+ "running": "正在修改",
+ "editing": "修改中",
+ "ready": "等待下一步",
+ "failed": "准备失败",
+ "ended": "已结束",
+ "cleanup": "清理中"
+ },
+ "integration": {
+ "unintegrated": "未合入",
+ "integrated": "已合入",
+ "changed": "有新改动待合入",
+ "reverted": "已撤销合入",
+ "unknown": "合入状态待确认",
+ "unchanged": "没有需要合入的改动"
+ },
+ "actions": {
+ "open": "打开任务",
+ "continue": "继续修改",
+ "test": "启动隔离测试版",
+ "integrate": "合入个人版",
+ "revert": "撤销合入",
+ "reapply": "重新合入",
+ "resolve": "处理冲突",
+ "retry": "重试",
+ "build": "生成个人版",
+ "retryBuild": "重新生成",
+ "end": "结束制作",
+ "retry-prepare": "重试准备",
+ "retry-cleanup": "重试清理"
+ },
+ "buildStatus": {
+ "waiting": "等待生成个人版…",
+ "checking": "正在检查个人版…",
+ "merging": "正在合入改动…",
+ "packaging": "正在打包个人版…",
+ "publishing": "正在保存个人版…",
+ "ready": "个人版已生成",
+ "failed": "个人版生成失败",
+ "installerReady": "安装包已就绪"
+ },
+ "rounds_other": "{{count}} 轮修改",
+ "files_other": "改动 {{count}} 个文件"
+ },
+ "merge": {
+ "getLatest": "获取最新源码",
+ "updateHint": "更新官方源码,并保留个人改动。",
+ "confirmTitle": "更新到最新源码?",
+ "confirmDescription": "会保留你的个人改动。如有冲突,将通过独立任务协助处理。",
+ "confirm": "更新源码",
+ "openTask": "打开处理任务",
+ "resolve": "处理冲突",
+ "resolveHint": "在独立任务中处理冲突并检查结果。",
+ "otherAccount": "这项操作由其他账号发起,请切回该账号继续。",
+ "status": {
+ "fetching": "正在获取最新源码…",
+ "merging": "正在合入源码改动…",
+ "conflict": "有冲突需要处理",
+ "resolving": "正在处理冲突",
+ "checking": "正在检查改动…",
+ "merged": "源码改动已合入",
+ "failed": "源码合入失败"
+ },
+ "errors": {
+ "busy": "其他操作正在进行,请稍后重试。",
+ "dirty": "源码有未提交的改动,请先保存再重试。",
+ "localMain": "main 分支存在本地提交,请检查后再更新。",
+ "unavailable": "源码或操作记录不可用,请刷新后重试。",
+ "gitFailed": "Git 未能完成操作,请重试。",
+ "baselineChanged": "个人源码已发生变化,请基于最新状态重试。",
+ "checksFailed": "改动未通过检查,请打开处理任务继续。",
+ "interrupted": "操作已中断,改动已保留,请重试。",
+ "startFailed": "无法打开处理任务,请重试。"
+ }
}
}
}
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 c153f9138b..a5e2082895 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5746,7 +5746,11 @@
"failed": "準備失敗",
"cancelled": "準備已停止",
"cleaning": "正在清理",
- "cleanup": "待清理"
+ "cleanup": "待清理",
+ "cleanupFailed": "清理失敗",
+ "integrated": "已合入",
+ "unintegrated": "未合入",
+ "unknown": "合入狀態待確認"
},
"errors": {
"busy": "任務仍在執行或目錄正在使用,請停止後重試。",
@@ -5755,7 +5759,17 @@
"cleanupFailed": "清理未完成,記錄已保留,請重試清理。",
"directoryBusy": "開發目錄中的檔案被占用或無法刪除,請關閉使用該目錄的終端機、編輯器或預覽後重試清理。",
"unavailable": "任務或開發目錄已變更,請重新整理後重試。"
- }
+ },
+ "end": "結束製作",
+ "endHint": "結束製作後會清理工作目錄,保留製作歷史與已儲存的改動。",
+ "endConfirm": "結束「{{title}}」並清理工作目錄?製作歷史與已儲存的改動會保留。",
+ "cleanupDeletedConfirm": "清理「{{title}}」剩餘的工作目錄?已儲存的製作歷史會保留。",
+ "endUnintegrated": "還有改動未合入個人版,結束製作不會自動合入。",
+ "endUnknown": "暫時無法確認合入狀態,請先檢查改動再清理。"
+ },
+ "tabs": {
+ "versions": "版本控制",
+ "environment": "環境準備"
}
}
},
@@ -12157,38 +12171,6 @@
}
},
"billing": {
- "comparison": {
- "free": "FREE",
- "freeUsage": "免費使用",
- "priceFromSuffix": "起",
- "topup": "按需儲值",
- "topupExpiry": "儲值點數不過期",
- "agent": "完整 Agent 功能",
- "apiKey": "自備 API key",
- "existingSubscription": "接入現有訂閱",
- "localModels": "支援本機模型",
- "basicModels": "可用基礎模型",
- "subscription": "訂閱方案",
- "rollover": "剩餘點數可留到{{period}},最多 {{amount}}",
- "nextPeriod": {
- "MONTH": "下個月",
- "YEAR": "下一年",
- "OTHER": "下期"
- },
- "includesFree": "包含 FREE 全部功能",
- "advancedModels": "解鎖進階模型",
- "managedService": "官方服務,免設定",
- "topupUnlock": "按需付費,解鎖進階模型",
- "select": "選擇 {{name}}",
- "upgrade": "升級至 {{name}}",
- "downgrade": "降級至 {{name}}",
- "changeUnavailable": "暫不可切換",
- "creditMultiple": "{{name}} 的 {{multiple}} 倍週期點數",
- "credits": {
- "MONTH": "每月 {{amount}} 點數",
- "YEAR": "每年 {{amount}} 點數"
- }
- },
"sidebar": "餘額與訂閱",
"settings": {
"title": "用量和計費",
@@ -12242,7 +12224,7 @@
"observedAt": "餘額更新於 {{date}}",
"poolDetail": "已用 {{used}} · 總額 {{total}}",
"remaining": "剩餘",
- "progressLabel": "{{label}}剩餘比例",
+ "progressLabel": "{{label}}使用進度",
"noPlanCredits": "當前無生效訂閱,因此沒有訂閱餘額。",
"historyUnavailable": "歷史記錄不完整,暫時僅顯示剩餘餘額。",
"detailsUnavailable": "用量明細暫時不可用,當前僅顯示各類餘額。",
@@ -12311,7 +12293,6 @@
},
"dialogs": {
"subscription": {
- "confirmTitle": "確認訂閱",
"title": "選擇訂閱套餐"
},
"topup": {
@@ -12404,9 +12385,13 @@
"failedBody": "支付失敗,請稍後重試或聯絡支援。"
},
"planChange": {
- "emptyTitle": "暫無可切換的套餐",
"targetTitle": "更改訂閱套餐",
"back": "上一步",
+ "upgradeBadge": "升級",
+ "sameLevelBadge": "同等級",
+ "downgradeBadge": "降級",
+ "emptyTitle": "暫無可切換的套餐",
+ "emptyDescription": "當前沒有其他可切換的套餐。",
"quotingTitle": "正在準備套餐變更",
"quotingBody": "正在確認價格與生效時間…",
"quoteTitle": "確認套餐變更",
@@ -12769,7 +12754,19 @@
"mainCommit": "main 版本",
"currentBranch": "目前專案分支",
"detached": "不在分支上(固定提交)",
- "unknown": "更新原始碼後查看"
+ "unknown": "更新原始碼後查看",
+ "latest": {
+ "dev": "最新 main",
+ "beta": "最新 beta",
+ "release": "最新正式版",
+ "unavailable": "無法查詢,請重新開啟設定重試",
+ "same": "(已同步)",
+ "behind_one": "(落後 {{count}} 個提交)",
+ "behind_other": "(落後 {{count}} 個提交)",
+ "ahead_one": "(領先 {{count}} 個提交)",
+ "ahead_other": "(領先 {{count}} 個提交)",
+ "difference": "(落後 {{behind}},領先 {{ahead}} 個提交)"
+ }
}
},
"code": {
@@ -12797,8 +12794,8 @@
"projectClearing": "正在清理個人版專案,請等待清理完成後再傳送訊息",
"inputLocked": {
"executing": "Cindy Make 正在首次執行",
- "hint": "首次執行結束後恢復輸入,提問和計畫確認不受影響。",
- "retry": "輸入暫不可用,請在上方準備卡片中重試。"
+ "hint": "準備完成後恢復輸入,即可開始修改。",
+ "retry": "準備尚未完成,重試後可繼續。"
},
"dependencyActivity": {
"starting": "正在啟動依賴安裝…",
@@ -12807,7 +12804,7 @@
},
"dependencyProgress": "已解析 {{resolved}} · 已重用 {{reused}} · 已下載 {{downloaded}} · 已新增 {{added}}",
"taskName": "Cindy Make 個人版",
- "taskTitle": "[Cindy-Make] {{request}}",
+ "taskTitle": "[{{worktree}}] {{request}}",
"workspace": "開發目錄 {{branch}}"
},
"complete": {
@@ -12818,6 +12815,211 @@
"changedFiles_other": "{{count}} 個檔案有改動",
"commit": "基於 {{commit}}",
"branch": "已提交到 {{branch}}"
+ },
+ "versions": {
+ "title": "我的版本",
+ "description": "選擇這台電腦要使用的 Cindy 版本。切換後會重新啟動,並保留帳號、設定與任務。",
+ "original": "原版",
+ "personal": "個人版",
+ "development": "開發環境",
+ "current": "目前使用",
+ "using": "使用中",
+ "switch": "切換並重新啟動",
+ "switchPersonal": "切換至此個人版",
+ "remove": "刪除版本",
+ "removeTitle": "刪除此個人版?",
+ "removeDescription": "僅刪除產生的應用程式檔案,保留原始碼、帳號、設定和任務。",
+ "empty": "尚未產生可切換的個人版。",
+ "unavailable": "此版本的應用程式檔案已無法使用。",
+ "incompatible": "此版本與目前資料不相容,請以目前原版重新產生。",
+ "readyHint": "個人版已就緒。切換後會重新啟動 Cindy,並保留目前帳號、設定和任務。",
+ "errors": {
+ "busy": "仍有任務、測試或建置正在進行,請結束後再切換或刪除版本。",
+ "incompatible": "資料結構不同,暫時無法切換至此版本。請以目前原版重新產生個人版。",
+ "unavailable": "無法讀取此版本,請重新產生後再試。",
+ "launchFailed": "無法啟動目標版本,目前版本已保留。",
+ "recovery": "無法啟動所選版本。已將原版恢復為預設,請從原入口重新開啟 Cindy。現有資料已保留。"
+ },
+ "localChanges": "含本機改動"
+ },
+ "personal": {
+ "generate": "產生個人版",
+ "open": "查看安裝套件",
+ "description": "將本次修改與個人版合併,檢查和打包通過後儲存為新個人版。",
+ "readyHint": "安裝套件 {{name}} 已產生,可開啟所在目錄。",
+ "checkStep": {
+ "dependencies": "正在安裝建置相依套件…",
+ "tests": "正在執行自動測試,可能需要數分鐘…",
+ "types": "正在檢查程式碼型別…"
+ },
+ "status": {
+ "waiting": "等待產生個人版…",
+ "merging": "正在合併修改…",
+ "checking": "正在檢查個人版…",
+ "packaging": "正在打包個人版…",
+ "publishing": "正在儲存個人版…",
+ "ready": "個人版已產生",
+ "failed": "未能產生個人版"
+ },
+ "errors": {
+ "unavailable": "無法讀取產生記錄或安裝套件,請重新產生。",
+ "changed": "製作目錄或程式碼已有變更,請完成修改後重新產生。",
+ "environment": "建置工具尚未就緒,請檢查 Cindy Make 環境後重試。",
+ "missingShell": "自動檢查需要 Git Bash,請安裝 Git for Windows 後重試。",
+ "checksFailed": "合併後的程式碼未通過檢查,請繼續修改後重新產生。",
+ "conflict": "與目前個人版的修改有衝突,請繼續修改並解決衝突。",
+ "baselineChanged": "產生期間個人版已有更新,請重新產生以包含最新修改。",
+ "buildFailed": "打包未完成,請重試,或繼續修改後再產生。",
+ "cancelled": "製作已取消,可以重新產生個人版。",
+ "cleanupFailed": "製作已停止,但部分暫存內容未能清理。請重新啟動 Cindy 後再試。",
+ "interrupted": "產生程序已停止,可以重新產生個人版。"
+ }
+ },
+ "test": {
+ "title": "修改已完成,選擇下一步",
+ "description": "可以繼續修改、啟動隔離版測試,或直接產生個人版安裝套件。",
+ "readyHint": "請在測試視窗體驗修改。點擊「繼續修改」會關閉測試版並恢復輸入。",
+ "start": "啟動隔離版測試",
+ "started": "測試版已啟動",
+ "continue": "繼續修改",
+ "status": {
+ "waiting": "修改已完成,選擇下一步",
+ "starting": "正在啟動隔離版測試…",
+ "ready": "隔離版已啟動,等待測試",
+ "failed": "隔離版未能啟動",
+ "stopped": "可以再次啟動測試"
+ },
+ "errors": {
+ "unavailable": "這份修改記錄或工作目錄已變更,請繼續修改後重新完成。",
+ "changed": "程式碼已有新的修改,請完成修改後再啟動測試。",
+ "environment": "測試環境尚未就緒,請在設定中檢查 Cindy Make 環境後重試。",
+ "launchFailed": "未能啟動隔離版,請重試;仍失敗可返回繼續修改。",
+ "timeout": "隔離版啟動逾時,請重試。",
+ "interrupted": "上次測試已中斷,請重新啟動隔離版。"
+ }
+ },
+ "history": {
+ "title": "製作歷史",
+ "build": "產生個人版",
+ "buildDescription": "將目前的個人原始碼產生為新版本,尚未合入的歷史改動不會包含在內。",
+ "building": "正在產生個人版…",
+ "stop": "停止製作",
+ "stopping": "正在停止…",
+ "progress": {
+ "waiting": "等待開始",
+ "merging": "正在合併修改",
+ "checking": "正在執行檢查",
+ "packaging": "正在打包個人版",
+ "publishing": "正在儲存個人版"
+ },
+ "noActions": {
+ "ended": "這次製作已結束,目前沒有可執行的操作。",
+ "sessionUnavailable": "這筆製作記錄對應的任務已無法使用。",
+ "completionUnavailable": "完成記錄無法驗證,目前沒有安全的操作可執行。",
+ "sourceUnavailable": "個人原始碼無法驗證,目前沒有安全的操作可執行。",
+ "changedAfterCompletion": "記錄中的完成結果與目前原始碼不一致,目前沒有安全的操作可執行。",
+ "busy": "其他製作或檢查正在進行,請稍後再試。",
+ "checking": "正在核對這筆製作記錄,請稍後再試。"
+ },
+ "counts": "共 {{total}} 次 · 待合入 {{pending}} 次 · 已合入 {{integrated}} 次",
+ "filterLabel": "篩選製作歷史",
+ "filters": {
+ "all": "全部製作",
+ "pending": "待合入",
+ "integrated": "已合入",
+ "ended": "已結束"
+ },
+ "loadFailed": "無法讀取製作歷史,請重試。",
+ "loading": "正在讀取製作歷史…",
+ "actionFailed": "操作未完成,請重新整理後重試。",
+ "openInstaller": "查看安裝程式",
+ "updated": "更新於 {{time}}",
+ "needsBuild": "原始碼已有改動,產生個人版後即可使用。",
+ "built": "已包含在 {{time}} 產生的個人版中",
+ "builtKnown": "已包含在產生的個人版中",
+ "conflict": "改動存在衝突,請開啟處理任務繼續。",
+ "rounds": "{{count}} 輪修改",
+ "round": "第 {{number}} 輪 · {{time}}",
+ "files": "改動 {{count}} 個檔案",
+ "working": "正在處理…",
+ "endAndClean": "結束並清理",
+ "endConfirm": "結束這次製作並清理工作目錄?製作歷史與已儲存的改動會保留。",
+ "revertConfirm": "撤銷這次製作合入個人原始碼的改動?其他製作和已產生的應用程式會保留。",
+ "lifecycle": {
+ "preparing": "準備中",
+ "running": "正在修改",
+ "editing": "修改中",
+ "ready": "等待下一步",
+ "failed": "準備失敗",
+ "ended": "已結束",
+ "cleanup": "清理中"
+ },
+ "integration": {
+ "unintegrated": "未合入",
+ "integrated": "已合入",
+ "changed": "有新改動待合入",
+ "reverted": "已撤銷合入",
+ "unknown": "合入狀態待確認",
+ "unchanged": "沒有需要合入的改動"
+ },
+ "actions": {
+ "open": "開啟任務",
+ "continue": "繼續修改",
+ "test": "啟動隔離測試版",
+ "integrate": "合入個人版",
+ "revert": "撤銷合入",
+ "reapply": "重新合入",
+ "resolve": "處理衝突",
+ "retry": "重試",
+ "build": "產生個人版",
+ "retryBuild": "重新產生",
+ "end": "結束製作",
+ "retry-prepare": "重試準備",
+ "retry-cleanup": "重試清理"
+ },
+ "buildStatus": {
+ "waiting": "等待產生個人版…",
+ "checking": "正在檢查個人版…",
+ "merging": "正在合入改動…",
+ "packaging": "正在封裝個人版…",
+ "publishing": "正在儲存個人版…",
+ "ready": "個人版已產生",
+ "failed": "個人版產生失敗",
+ "installerReady": "安裝程式已就緒"
+ },
+ "rounds_other": "{{count}} 輪修改",
+ "files_other": "改動 {{count}} 個檔案"
+ },
+ "merge": {
+ "getLatest": "取得最新原始碼",
+ "updateHint": "更新官方原始碼,並保留個人改動。",
+ "confirmTitle": "更新到最新原始碼?",
+ "confirmDescription": "會保留你的個人改動。如有衝突,將透過獨立任務協助處理。",
+ "confirm": "更新原始碼",
+ "openTask": "開啟處理任務",
+ "resolve": "處理衝突",
+ "resolveHint": "在獨立任務中處理衝突並檢查結果。",
+ "otherAccount": "這項操作由其他帳號發起,請切回該帳號繼續。",
+ "status": {
+ "fetching": "正在取得最新原始碼…",
+ "merging": "正在合入原始碼改動…",
+ "conflict": "有衝突需要處理",
+ "resolving": "正在處理衝突",
+ "checking": "正在檢查改動…",
+ "merged": "原始碼改動已合入",
+ "failed": "原始碼合入失敗"
+ },
+ "errors": {
+ "busy": "其他操作正在進行,請稍後重試。",
+ "dirty": "原始碼有未提交的改動,請先儲存再重試。",
+ "localMain": "main 分支存在本機提交,請檢查後再更新。",
+ "unavailable": "原始碼或操作記錄無法使用,請重新整理後重試。",
+ "gitFailed": "Git 未能完成操作,請重試。",
+ "baselineChanged": "個人原始碼已發生變化,請依最新狀態重試。",
+ "checksFailed": "改動未通過檢查,請開啟處理任務繼續。",
+ "interrupted": "操作已中斷,改動已保留,請重試。",
+ "startFailed": "無法開啟處理任務,請重試。"
+ }
}
}
}
diff --git a/apps/desktop/src/renderer/lib/__tests__/cindyMakeComposer.test.ts b/apps/desktop/src/renderer/lib/__tests__/cindyMakeComposer.test.ts
index e760bdf9eb..b762b02d3c 100644
--- a/apps/desktop/src/renderer/lib/__tests__/cindyMakeComposer.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/cindyMakeComposer.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest';
-import { getCindyMakeComposerPhase } from '../cindyMakeComposer';
+import {
+ getCindyMakeComposerPhase,
+ getCindyMakePendingTest,
+ getCindyMakePreparation,
+} from '../cindyMakeComposer';
import type { MakeDoctorReport } from '../../../shared/cindyMakeDoctor';
import type { ChatMessage } from '../makerChatStore';
@@ -38,13 +42,99 @@ const card = (report: MakeDoctorReport): ChatMessage => ({
systemCardData: { report },
});
+describe('Cindy Make waiting-for-test card', () => {
+ const done = (id: string, continuedAt?: number): ChatMessage => ({
+ clientId: id,
+ role: 'assistant',
+ content: '',
+ systemCardType: 'cindy-make-complete',
+ systemCardData: { reportedAt: 123, commit: 'a'.repeat(40), continuedAt },
+ });
+ const select = (messages: ChatMessage[], busy = false) =>
+ getCindyMakePendingTest({
+ session: { ...session, status: 'active' },
+ messages,
+ busy,
+ });
+ it('uses a stored completion after reopening, but only when execution has ended', () => {
+ expect(select([done('done')])?.completionId).toBe('done');
+ expect(select([done('done')], true)).toBeNull();
+ });
+ it('does not restore older cards after continuing or a new user request', () => {
+ expect(select([done('old'), done('new', 456)])).toBeNull();
+ expect(
+ select([done('old'), { clientId: 'u', role: 'user', content: 'edit again' }]),
+ ).toBeNull();
+ expect(
+ select([
+ done('old', 456),
+ { clientId: 'u', role: 'user', content: 'edit again' },
+ done('new'),
+ ])?.completionId,
+ ).toBe('new');
+ });
+ it('leaves ordinary, cleared and archived tasks alone', () => {
+ for (const extra of [
+ { source: 'desktop' as const },
+ { clearedAt: '2026-09-17T10:00:00Z' },
+ { status: 'archived' as const },
+ ]) {
+ expect(
+ getCindyMakePendingTest({
+ session: { ...session, status: 'active', ...extra },
+ messages: [done('done')],
+ busy: false,
+ }),
+ ).toBeNull();
+ }
+ });
+});
+
describe('Cindy Make composer lifecycle', () => {
- it('locks from preparation through accepted dispatch until the first product turn ends', () => {
+ it('restores the full preparation card and retry request from persisted history', () => {
+ const saved = card(preparing);
+ saved.systemCardData = { ...saved.systemCardData, request: 'original request' };
+ expect(getCindyMakePreparation({ session, messages: [saved] })).toEqual({
+ report: preparing,
+ request: 'original request',
+ });
+ });
+
+ it('prefers the live report while preserving the original request for the same run', () => {
+ const saved = card(preparing);
+ saved.systemCardData = { ...saved.systemCardData, request: 'original request' };
+ const live = { ...preparing, status: 'cancelled' as const };
+ expect(getCindyMakePreparation({ session, report: live, messages: [saved] })).toEqual({
+ report: live,
+ request: 'original request',
+ });
+ });
+
+ it('never borrows a retry request from another run or another task', () => {
+ const saved = card(preparing);
+ saved.systemCardData = { ...saved.systemCardData, request: 'other request' };
+ const nextRun = { ...preparing, runId: 'next-run' };
+ expect(getCindyMakePreparation({ session, report: nextRun, messages: [saved] })).toEqual({
+ report: nextRun,
+ request: undefined,
+ });
+ expect(
+ getCindyMakePreparation({
+ session: { ...session, id: 'another-session' },
+ report: preparing,
+ messages: [saved],
+ }),
+ ).toBeUndefined();
+ const withRequest = { ...nextRun, task: { ...nextRun.task!, request: 'live request' } };
+ expect(
+ getCindyMakePreparation({ session, report: withRequest, messages: [saved] })?.request,
+ ).toBe('live request');
+ });
+
+ it('locks only preparation and releases input as soon as first dispatch is accepted', () => {
expect(getCindyMakeComposerPhase(input)).toBe('dependencies');
- expect(getCindyMakeComposerPhase({ ...input, report: dispatched })).toBe('executing');
- expect(getCindyMakeComposerPhase({ ...input, report: dispatched, busy: true })).toBe(
- 'executing',
- );
+ expect(getCindyMakeComposerPhase({ ...input, report: dispatched })).toBeNull();
+ expect(getCindyMakeComposerPhase({ ...input, report: dispatched, busy: true })).toBe(null);
expect(
getCindyMakeComposerPhase({
...input,
@@ -54,18 +144,18 @@ describe('Cindy Make composer lifecycle', () => {
).toBeNull();
});
- it('does not unlock just because a question or plan temporarily pauses streaming', () => {
+ it('leaves question and plan handling to the ordinary composer after preparation', () => {
const messages: ChatMessage[] = [
card(dispatched),
{ clientId: 'ask', role: 'assistant', content: 'Choose', askUserStatus: 'pending' },
{ clientId: 'plan', role: 'assistant', content: 'Plan', planReviewStatus: 'pending' },
];
expect(getCindyMakeComposerPhase({ ...input, report: dispatched, messages, busy: false })).toBe(
- 'executing',
+ null,
);
});
- it('restores the lock from the saved card after remount and supports remote history', () => {
+ it('keeps input available after reloading a dispatched preparation', () => {
expect(
getCindyMakeComposerPhase({
...input,
@@ -73,7 +163,7 @@ describe('Cindy Make composer lifecycle', () => {
messages: [card(dispatched)],
busy: true,
}),
- ).toBe('executing');
+ ).toBeNull();
});
it('does not relock later manual turns, including after remount', () => {
@@ -118,7 +208,7 @@ describe('Cindy Make composer lifecycle', () => {
).toBeNull();
});
- it('uses a persisted top-level terminal before session metadata arrives, not a subagent terminal', () => {
+ it('does not need a terminal message to unlock the first editing turn', () => {
const terminal: ChatMessage = {
clientId: 'answer',
role: 'assistant',
@@ -134,7 +224,7 @@ describe('Cindy Make composer lifecycle', () => {
report: dispatched,
messages: [{ ...terminal, parentToolUseId: 'subagent' }],
}),
- ).toBe('executing');
+ ).toBeNull();
});
it('leaves ordinary, cleared, legacy and other-session tasks alone', () => {
diff --git a/apps/desktop/src/renderer/lib/__tests__/cindyMakeDoctorStream.test.ts b/apps/desktop/src/renderer/lib/__tests__/cindyMakeDoctorStream.test.ts
index bbb0dce6b9..3b8e7323ff 100644
--- a/apps/desktop/src/renderer/lib/__tests__/cindyMakeDoctorStream.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/cindyMakeDoctorStream.test.ts
@@ -641,7 +641,7 @@ describe('personal code task handoff', () => {
originSessionId: id,
runId,
request,
- title: expect.stringContaining('修复滚动 保留 <b>原文</b>'),
+ title: '[code] 修复滚动 保留 <b>原文</b>',
});
expect(makerChatStore.getSnapshot(target!).autoTitleDisabled).toBe(true);
expect(messages(id)[0].systemCardData?.codeSessionId).toBe(target);
diff --git a/apps/desktop/src/renderer/lib/__tests__/cindyMakeState.test.ts b/apps/desktop/src/renderer/lib/__tests__/cindyMakeState.test.ts
index 0aa623f8e5..f25f8bbb56 100644
--- a/apps/desktop/src/renderer/lib/__tests__/cindyMakeState.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/cindyMakeState.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cindyMakeState } from '../cindyMakeState';
import { getDataOwnerGeneration, setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
-import type { CindyMakeGlobalState } from '../../../shared/cindyMakeDoctor';
+import type { CindyMakeGlobalState, MakeDoctorReport } from '../../../shared/cindyMakeDoctor';
const subscriptions: Array<() => void> = [];
let push: (state: CindyMakeGlobalState) => void;
@@ -9,6 +9,7 @@ let resolve: (state: CindyMakeGlobalState) => void;
let api: {
getCindyMakeState: ReturnType<typeof vi.fn>;
onCindyMakeState: ReturnType<typeof vi.fn>;
+ manageCindyMakeTask: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
setDataOwnerGeneration('make-state-owner');
@@ -23,6 +24,7 @@ beforeEach(() => {
push = listener;
return vi.fn();
}),
+ manageCindyMakeTask: vi.fn(async () => undefined),
};
vi.stubGlobal('window', { electronAPI: api });
});
@@ -36,6 +38,17 @@ function subscribe() {
return listener;
}
+function taskReport(sessionId: string): MakeDoctorReport {
+ return {
+ runId: sessionId + '-run',
+ platform: 'win32',
+ arch: 'x64',
+ checks: [],
+ status: 'completed',
+ task: { sessionId, phase: 'completed', sessionStatus: 'active' },
+ };
+}
+
describe('read-only Main Cindy Make state', () => {
it('shares one subscription between Settings, task cards and the sidebar', () => {
const first = subscribe();
@@ -89,4 +102,91 @@ describe('read-only Main Cindy Make state', () => {
await Promise.resolve();
expect(cindyMakeState.getSnapshot().source?.path).toBe('/current');
});
+
+ it.each(['delete', 'finish'] as const)(
+ 'applies a successful %s to all subscribers only after Main acknowledges it',
+ async (action) => {
+ const listener = subscribe();
+ const otherTask = taskReport('other');
+ const source: CindyMakeGlobalState['source'] = { status: 'ready', path: '/source' };
+ const otherAction = { action: 'delete' as const, status: 'running' as const };
+ const state: CindyMakeGlobalState = {
+ tasks: { target: taskReport('target'), other: otherTask },
+ taskActions: { target: { action, status: 'running' }, other: otherAction },
+ source,
+ };
+ push(state);
+ let complete!: () => void;
+ api.manageCindyMakeTask.mockImplementationOnce(
+ () =>
+ new Promise<void>((done) => {
+ complete = done;
+ }),
+ );
+ const operation = cindyMakeState.manageTask('target', action);
+ expect(api.manageCindyMakeTask).toHaveBeenCalledWith('target', action);
+ expect(cindyMakeState.getSnapshot()).toBe(state);
+ listener.mockClear();
+ complete();
+ await operation;
+ expect(cindyMakeState.getSnapshot()).toEqual({
+ tasks: { other: otherTask },
+ taskActions: { other: otherAction },
+ source,
+ });
+ expect(listener).toHaveBeenCalledOnce();
+ },
+ );
+
+ it.each(['refresh', 'reconnect'] as const)(
+ 'does not restore a completed task from a late %s read',
+ async (read) => {
+ subscribe();
+ const stale: CindyMakeGlobalState = {
+ tasks: { target: taskReport('target') },
+ taskActions: { target: { action: 'delete', status: 'running' } },
+ };
+ push(stale);
+ let refresh: Promise<void> | undefined;
+ if (read === 'reconnect') {
+ subscriptions.pop()!();
+ subscribe();
+ } else {
+ refresh = cindyMakeState.refresh();
+ }
+ await cindyMakeState.manageTask('target', 'delete');
+ resolve(stale);
+ await refresh;
+ expect(cindyMakeState.getSnapshot().tasks).toBeUndefined();
+ expect(cindyMakeState.getSnapshot().taskActions).toEqual({});
+ },
+ );
+
+ it('keeps a failed cleanup in the list for retry', async () => {
+ subscribe();
+ const state: CindyMakeGlobalState = { tasks: { target: taskReport('target') } };
+ push(state);
+ api.manageCindyMakeTask.mockRejectedValueOnce(new Error('directoryBusy'));
+ await expect(cindyMakeState.manageTask('target', 'delete')).rejects.toThrow('directoryBusy');
+ expect(cindyMakeState.getSnapshot()).toBe(state);
+ });
+
+ it('ignores an old account cleanup acknowledgement after reconnecting', async () => {
+ subscribe();
+ let complete!: () => void;
+ api.manageCindyMakeTask.mockImplementationOnce(
+ () =>
+ new Promise<void>((done) => {
+ complete = done;
+ }),
+ );
+ const operation = cindyMakeState.manageTask('target', 'delete');
+ setDataOwnerGeneration('another-owner');
+ subscribe();
+ const next: CindyMakeGlobalState = { tasks: { target: taskReport('target') } };
+ push(next);
+ complete();
+ await operation;
+ expect(cindyMakeState.getSnapshot()).toBe(next);
+ });
});
diff --git a/apps/desktop/src/renderer/lib/cindyMakeComposer.ts b/apps/desktop/src/renderer/lib/cindyMakeComposer.ts
index f2f8723c99..4e5e1115f5 100644
--- a/apps/desktop/src/renderer/lib/cindyMakeComposer.ts
+++ b/apps/desktop/src/renderer/lib/cindyMakeComposer.ts
@@ -2,23 +2,95 @@ import type { Session } from './ccAgent.types';
import type { ChatMessage } from './makerChatStore';
import type { MakeDoctorReport, CindyMakeTaskPreparation } from '../../shared/cindyMakeDoctor';
import { CINDY_MAKE_SESSION_SOURCE } from '../../shared/cindyMakeSession';
+import type { CindyMakeCompletionMeta } from '../../shared/cindyMakeSession';
export type CindyMakeComposerPhase =
- Exclude<CindyMakeTaskPreparation['phase'], 'completed'> | 'executing' | 'failed' | 'cancelled';
+ Exclude<CindyMakeTaskPreparation['phase'], 'completed'> | 'failed' | 'cancelled';
+
+export function isCindyMakeCompletionMessage(message: ChatMessage): boolean {
+ return message.role === 'assistant' && message.systemCardType === 'cindy-make-complete';
+}
+
+/** Only the newest completed edit can ask for testing; continued/new work supersedes it. */
+export function getCindyMakePendingTest({
+ session,
+ messages,
+ busy,
+}: {
+ session: Pick<Session, 'id' | 'source' | 'status' | 'clearedAt'> | null;
+ messages: readonly ChatMessage[];
+ busy: boolean;
+}): { completionId: string; meta: CindyMakeCompletionMeta } | null {
+ if (
+ session?.source !== CINDY_MAKE_SESSION_SOURCE ||
+ session.status !== 'active' ||
+ session.clearedAt ||
+ busy
+ )
+ return null;
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
+ const message = messages[i];
+ if (message.parentToolUseId) continue;
+ if (message.role === 'user') return null;
+ if (!isCindyMakeCompletionMessage(message)) continue;
+ const meta = message.systemCardData as unknown as CindyMakeCompletionMeta | undefined;
+ if (
+ !meta ||
+ typeof meta.reportedAt !== 'number' ||
+ !Number.isFinite(meta.reportedAt) ||
+ meta.continuedAt
+ )
+ return null;
+ return { completionId: message.clientId, meta };
+ }
+ return null;
+}
type MakeSession = Pick<
Session,
'id' | 'source' | 'clearedAt' | 'lastTurnEndedAt' | 'interruptedTurnStartedAt'
>;
-/** Preparation completion means dispatch accepted, not the end of the first execution. */
+export function isCindyMakePreparationMessage(
+ message: ChatMessage,
+ sessionId: string | undefined,
+): boolean {
+ return (
+ !!sessionId &&
+ message.role === 'assistant' &&
+ (message.systemCardType === 'cindy-make' || message.systemCardType === 'cindy-make-doctor') &&
+ (message.systemCardData?.report as MakeDoctorReport | undefined)?.task?.sessionId === sessionId
+ );
+}
+
+/** The composer and its lifecycle use the same live report, with durable history as fallback. */
+export function getCindyMakePreparation({
+ session,
+ report,
+ messages,
+}: {
+ session: MakeSession | null;
+ report?: MakeDoctorReport;
+ messages: readonly ChatMessage[];
+}): { report: MakeDoctorReport; request?: string } | undefined {
+ if (session?.source !== CINDY_MAKE_SESSION_SOURCE || session.clearedAt) return undefined;
+ const saved = messages.find((message) => isCindyMakePreparationMessage(message, session.id));
+ const savedReport = saved?.systemCardData?.report as MakeDoctorReport | undefined;
+ const preparation = report?.task?.sessionId === session.id ? report : savedReport;
+ if (!preparation) return undefined;
+ const savedRequest =
+ savedReport?.runId === preparation.runId && typeof saved?.systemCardData?.request === 'string'
+ ? saved.systemCardData.request
+ : undefined;
+ return { report: preparation, request: preparation.task?.request ?? savedRequest };
+}
+
+/** Only preparation replaces input. Editing uses the ordinary composer from the first turn. */
export function getCindyMakeComposerPhase({
session,
report,
messages,
historyLoaded,
- busy,
- error,
}: {
session: MakeSession | null;
report?: MakeDoctorReport;
@@ -28,32 +100,14 @@ export function getCindyMakeComposerPhase({
error: string | null;
}): CindyMakeComposerPhase | null {
if (session?.source !== CINDY_MAKE_SESSION_SOURCE || session.clearedAt) return null;
- // Main persists this only at a product-turn terminal, not while waiting for
- // questions, plan review, permission, or an automatic continuation. It also
- // survives remounts and keeps later manual turns from locking the composer.
+ // A completed editing turn also rules out stale preparation history after reload.
if (session.lastTurnEndedAt != null) return null;
- const saved = messages.find(
- (message) =>
- message.systemCardType === 'cindy-make' &&
- (message.systemCardData?.report as MakeDoctorReport | undefined)?.task?.sessionId ===
- session.id,
- )?.systemCardData?.report as MakeDoctorReport | undefined;
- const preparation = report?.task?.sessionId === session.id ? report : saved;
+ const preparation = getCindyMakePreparation({ session, report, messages })?.report;
if (!preparation) return historyLoaded ? null : 'waiting';
if (preparation.status === 'failed' || preparation.status === 'cancelled')
return preparation.status;
if (preparation.status === 'running')
- return preparation.task?.phase === 'completed'
- ? 'executing'
- : (preparation.task?.phase ?? 'waiting');
-
- // Old history can arrive before the session patch. An interrupted/failed
- // execution must leave the existing recovery controls and manual input usable.
- if (
- (!busy && (error || session.interruptedTurnStartedAt != null)) ||
- messages.some((message) => !message.parentToolUseId && message.turnCompleted === true)
- )
- return null;
- return 'executing';
+ return preparation.task?.phase === 'completed' ? null : (preparation.task?.phase ?? 'waiting');
+ return null;
}
diff --git a/apps/desktop/src/renderer/lib/cindyMakeDoctorStream.ts b/apps/desktop/src/renderer/lib/cindyMakeDoctorStream.ts
index fe92359bbe..dbd86cf3ab 100644
--- a/apps/desktop/src/renderer/lib/cindyMakeDoctorStream.ts
+++ b/apps/desktop/src/renderer/lib/cindyMakeDoctorStream.ts
@@ -42,6 +42,7 @@ export function startMakeCodeSession(sessionId: string, runId: string): Promise<
try {
const requestChars = Array.from(request.replace(/\s+/gu, ' ').trim());
const title = i18n.t('cindyMake.code.taskTitle', {
+ worktree: runId.slice(0, 4),
request:
requestChars.length > 60
? requestChars.slice(0, 60).join('') + '…'
diff --git a/apps/desktop/src/renderer/lib/cindyMakeState.ts b/apps/desktop/src/renderer/lib/cindyMakeState.ts
index 3d2e7d0d9f..e9a5f0c0fa 100644
--- a/apps/desktop/src/renderer/lib/cindyMakeState.ts
+++ b/apps/desktop/src/renderer/lib/cindyMakeState.ts
@@ -25,6 +25,7 @@ function connect(): void {
if (unsubscribe || typeof window === 'undefined' || !window.electronAPI) return;
const generation = owner;
const connectionId = ++connection;
+ const previous = state;
let pushed = false;
const apply = (next: CindyMakeGlobalState) => {
if (
@@ -44,12 +45,28 @@ function connect(): void {
}) ?? (() => {});
void Promise.resolve(window.electronAPI.getCindyMakeState?.())
.then((next) => {
- if (next && !pushed) apply(next);
+ if (next && !pushed && state === previous) apply(next);
})
.catch(() => undefined);
}
export const cindyMakeState = {
+ async manageTask(sessionId: string, action: 'end' | 'finish' | 'delete'): Promise<void> {
+ const generation = getDataOwnerGeneration();
+ await window.electronAPI.manageCindyMakeTask(sessionId, action);
+ if (!isDataOwnerGenerationCurrent(generation)) return;
+ // Main only acknowledges success after cleanup and its completion marker.
+ // Apply that fact immediately; a delayed snapshot must not keep the task spinning.
+ const tasks = Object.fromEntries(
+ Object.entries(state.tasks ?? {}).filter(
+ ([, report]) => report.task?.sessionId !== sessionId,
+ ),
+ );
+ const taskActions = { ...state.taskActions };
+ delete taskActions[sessionId];
+ state = { ...state, tasks: Object.keys(tasks).length ? tasks : undefined, taskActions };
+ for (const listener of listeners) listener();
+ },
async refresh(): Promise<void> {
const generation = getDataOwnerGeneration();
const previous = state;
diff --git a/apps/desktop/src/renderer/lib/cindyMakeTitle.ts b/apps/desktop/src/renderer/lib/cindyMakeTitle.ts
new file mode 100644
index 0000000000..fbfb89da1d
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/cindyMakeTitle.ts
@@ -0,0 +1,13 @@
+/** The managed task directory is named after its run, on both Windows and POSIX. */
+export function cindyMakeWorktreeName(workingDir: string | null | undefined): string | undefined {
+ return workingDir?.match(/(?:^|[\\/])(?:merge-)?worktrees[\\/]([A-Za-z0-9-]{1,64})[\\/]?$/i)?.[1];
+}
+
+/** Replace the legacy feature tag and keep the worktree tag stable across renames/reloads. */
+export function formatCindyMakeTitle(title: string, worktreeName?: string | null): string {
+ const text = title.replace(/^\[Cindy(?:-| )Make\]\s*/i, '');
+ if (!worktreeName) return text;
+ const tag = `[${worktreeName.slice(0, 4)}]`;
+ const body = text.startsWith(tag) ? text.slice(tag.length).trimStart() : text;
+ return body ? `${tag} ${body}` : tag;
+}
diff --git a/apps/desktop/src/renderer/lib/useCindyVersions.ts b/apps/desktop/src/renderer/lib/useCindyVersions.ts
new file mode 100644
index 0000000000..10154a7451
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/useCindyVersions.ts
@@ -0,0 +1,61 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { extractIpcError } from '@/utils/ipcError';
+import type { CindyVersionAction, CindyVersionsState } from '../../shared/cindyVersions';
+
+export function useCindyVersions(enabled = true, refreshKey?: string) {
+ const [state, setState] = useState<CindyVersionsState>();
+ const [pending, setPending] = useState<string>();
+ const [error, setError] = useState<string>();
+ const busy = useRef(false);
+ const active = useRef(true);
+ const generation = useRef(0);
+ const owner = getDataOwnerGeneration();
+ const current = () => active.current && isDataOwnerGenerationCurrent(owner);
+ const refresh = useCallback(async () => {
+ if (!enabled || typeof window.electronAPI.getCindyVersions !== 'function') return;
+ const version = ++generation.current;
+ try {
+ const next = await window.electronAPI.getCindyVersions();
+ if (current() && version === generation.current) setState(next);
+ } catch {
+ if (current()) setError('unavailable');
+ }
+ }, [enabled, owner.dataOwnerId, owner.generation]);
+ useEffect(() => {
+ active.current = true;
+ void refresh();
+ const focus = () => {
+ if (!busy.current) void refresh();
+ };
+ window.addEventListener('focus', focus);
+ return () => {
+ active.current = false;
+ window.removeEventListener('focus', focus);
+ };
+ }, [refresh, refreshKey]);
+ const act = async (action: CindyVersionAction, id: string) => {
+ if (busy.current || !current()) return;
+ busy.current = true;
+ generation.current += 1;
+ setPending(id);
+ setError(undefined);
+ try {
+ const next = await window.electronAPI.actCindyVersion(action, id);
+ if (current()) setState(next);
+ } catch (failure) {
+ const code = extractIpcError(failure)?.message;
+ if (current())
+ setError(
+ code && ['busy', 'incompatible', 'launchFailed'].includes(code) ? code : 'unavailable',
+ );
+ } finally {
+ busy.current = false;
+ if (current()) setPending(undefined);
+ }
+ };
+ return { state, pending, error, act, refresh };
+}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 8d8880e074..20efdf8245 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2116,7 +2116,10 @@ interface ElectronAPI {
/** 内置 API-key 供应商专用 IPC(查/写/删,永不回读明文;对应 MAIN_ONLY 键)。mutation 失败抛统一 IPC 错误。 */
builtinApiKeyHas: (providerId: string) => Promise<boolean>;
builtinApiKeyStore: (providerId: string, value: string) => Promise<void>;
- builtinApiKeyRemove: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => Promise<void>;
+ builtinApiKeyRemove: (
+ providerId: string,
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ ) => Promise<void>;
/** CC 网络调试日志开关 (admin experimental). main 端 mutate process.env.XDT_CC_DEBUG_NET。 */
ccSetDebugNet: (enabled: boolean) => Promise<{ ok: true }>;
/** 网关凭据自动下发(model-access,类型见 shared/modelAccess.ts)。 */
@@ -2417,10 +2420,13 @@ interface ElectronAPI {
modelChosenByVendor: Partial<Record<'cc' | 'codex' | 'pi', boolean>>;
fastModeByModel: Record<string, boolean>;
effortByModel: Record<string, string>;
- providerModelMemory?: Record<string, {
- effortByModel: Record<string, string>;
- fastByModel: Record<string, boolean>;
- }>;
+ providerModelMemory?: Record<
+ string,
+ {
+ effortByModel: Record<string, string>;
+ fastByModel: Record<string, boolean>;
+ }
+ >;
/** 「新建会话默认启用 worktree」勾选记忆(vendor 无关根字段,远程草稿播种用)。 */
worktreeEnabled: boolean;
}) => void;
@@ -2818,7 +2824,9 @@ interface ElectronAPI {
clear: () => Promise<{ configured: boolean; enabled: boolean }>;
};
/** 主窗口投影全部任务的关注总数;独立于通知事件及逐任务已读回执。 */
- notificationSetAppAttentionCount: (snapshot: import('../shared/sessionAttention').AppAttentionSnapshot) => Promise<void>;
+ notificationSetAppAttentionCount: (
+ snapshot: import('../shared/sessionAttention').AppAttentionSnapshot,
+ ) => Promise<void>;
/** 将对应 session 标记为需要关注,同步灵动岛状态。 */
notificationMarkSessionAttention: (sessionId: string) => Promise<void>;
/** 用户查看或处置对应 session 后,同步逐任务已读回执。 */
@@ -3007,8 +3015,35 @@ interface ElectronAPI {
/** Open Cindy's managed Make tools directory (`<userData>/cindy-make/tools`). */
openCindyMakeToolsDir: () => Promise<{ success: boolean }>;
getCindyMakeSourceStatus: () => Promise<import('../shared/cindyMakeDoctor').MakeSourceStatus>;
+ cindyMakeMerge: (
+ input: import('../shared/cindyMakeMerge').CindyMakeMergeRequest,
+ ) => Promise<import('../shared/cindyMakeMerge').CindyMakeMergeState | undefined>;
+ getCindyMakeHistory: (
+ selected?: string,
+ ) => Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState>;
+ actCindyMakeHistory: (
+ runId: string,
+ action: import('../shared/cindyMakeHistory').MakeHistoryAction,
+ ) => Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState>;
+ generateCindyMakePersonal: () => Promise<
+ import('../shared/cindyMakeHistory').CindyMakeHistoryState
+ >;
+ cancelCindyMakePersonal: (
+ buildId: string,
+ ) => Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState>;
+ openCindyMakeHistoryBuild: () => Promise<void>;
getCindyMakeState: () => Promise<import('../shared/cindyMakeDoctor').CindyMakeGlobalState>;
- manageCindyMakeTask: (sessionId: string, action: 'finish' | 'delete') => Promise<void>;
+ manageCindyMakeTask: (sessionId: string, action: 'end' | 'finish' | 'delete') => Promise<void>;
+ cindyMakeTest: (
+ sessionId: string,
+ completionId: string,
+ action: import('../shared/cindyMakeSession').CindyMakeTestAction,
+ ) => Promise<import('../shared/cindyMakeSession').CindyMakeCompletionMeta>;
+ getCindyVersions: () => Promise<import('../shared/cindyVersions').CindyVersionsState>;
+ actCindyVersion: (
+ action: import('../shared/cindyVersions').CindyVersionAction,
+ id: string,
+ ) => Promise<import('../shared/cindyVersions').CindyVersionsState>;
openCindyMakeSourceDir: () => Promise<{ success: boolean }>;
onCindyMakeState: (
listener: (state: import('../shared/cindyMakeDoctor').CindyMakeGlobalState) => void,
@@ -3023,7 +3058,9 @@ interface ElectronAPI {
prepareCindyMakeWorkspace: (
runId: string,
) => Promise<import('../shared/cindyMakeDoctor').MakeTaskWorkspace>;
- startCindyMakeTask: (input: import('../shared/cindyMakeDoctor').CindyMakeTaskStart) => Promise<string>;
+ startCindyMakeTask: (
+ input: import('../shared/cindyMakeDoctor').CindyMakeTaskStart,
+ ) => Promise<string>;
cancelCindyMakeTask: (runId: string) => Promise<{ success: boolean }>;
/**
@@ -3217,7 +3254,11 @@ interface ElectronAPI {
// ── SkillHub (xdt-maker-技能中心 v0.2) ──
skillhub: {
- setEnabled: (params: { absolutePath: string; skillId?: string; enabled: boolean }) => Promise<{ cindyEnabled: boolean }>;
+ setEnabled: (params: {
+ absolutePath: string;
+ skillId?: string;
+ enabled: boolean;
+ }) => Promise<{ cindyEnabled: boolean }>;
onLocalStateChanged: (callback: () => void) => () => void;
scan: (params: { projects?: SkillhubProjectInput[] }) => Promise<{
success: boolean;
@@ -3559,7 +3600,10 @@ interface ElectronAPI {
uninstall: (
absolutePath: string,
skillId?: string,
- ) => Promise<{ success: true; cleanupToken?: string } | { success: false; errorCode: string; message: string }>;
+ ) => Promise<
+ | { success: true; cleanupToken?: string }
+ | { success: false; errorCode: string; message: string }
+ >;
retryUninstallCleanup: (token: string) => Promise<{ complete: boolean }>;
/** 在 main 内选择并检查本地包,成功时签发绑定当前 renderer 的短期导入授权。 */
@@ -3821,7 +3865,7 @@ interface ElectronAPI {
fetchReleaseNotesIndex: () => Promise<string[] | null>;
// ── Device Link (设备互联/跨设备远程控制) ─────────────────────────────
- openRemoteDesktop: (target: {deviceId: string; name: string}) => Promise<void>;
+ openRemoteDesktop: (target: { deviceId: string; name: string }) => Promise<void>;
remoteDesktopViewer: import('../shared/remoteDesktopViewer').RemoteDesktopViewerApi;
remoteDesktop: import('../shared/remoteDesktop').RemoteDesktopApi;
deviceLink: {
@@ -4496,10 +4540,7 @@ interface ElectronAPI {
isCustomized?: boolean;
defaultThresholdGiB: number;
}>;
- setSettings: (settings: {
- thresholdGiB?: number;
- disabled?: boolean;
- }) => Promise<{
+ setSettings: (settings: { thresholdGiB?: number; disabled?: boolean }) => Promise<{
thresholdGiB: number;
disabled: boolean;
isCustomized?: boolean;
@@ -4650,9 +4691,15 @@ interface ElectronAPI {
modelChain: import('../shared/botModelChain').BotModelRoute[];
isCustomized: boolean;
}>;
- list: (body?: { lastReadAtByBotId?: Record<string, number>; welcomeContext?: import('../shared/botWelcomeContext').BotWelcomeContext; locale?: import('../shared/locale').SupportedLocale }) => Promise<unknown[]>;
+ list: (body?: {
+ lastReadAtByBotId?: Record<string, number>;
+ welcomeContext?: import('../shared/botWelcomeContext').BotWelcomeContext;
+ locale?: import('../shared/locale').SupportedLocale;
+ }) => Promise<unknown[]>;
get: (botId: string) => Promise<unknown>;
- generateDraft: (body: import('../shared/botCreation').BotCreationRequest) => Promise<import('../shared/botCreation').BotCreationDraft>;
+ generateDraft: (
+ body: import('../shared/botCreation').BotCreationRequest,
+ ) => Promise<import('../shared/botCreation').BotCreationDraft>;
generateAvatar: (token: string) => Promise<{ avatarImageBase64: string }>;
chooseAvatar: (body: { botId: string; avatarImageBase64?: string }) => Promise<{
canceled: boolean;
@@ -5146,7 +5193,13 @@ interface ElectronAPI {
) => Promise<import('../shared/workflow-progress').WorkflowProgress | null>;
// 模型供应商目录(只读)—— 内置目录元数据 + 各供应商实时连接状态。
- setProviderPresentation: (input: { providerId?: string; action: 'rename' | 'remove' | 'restore'; name?: string; dataOwnerId: string | null; ownerGeneration: number }) => Promise<void>;
+ setProviderPresentation: (input: {
+ providerId?: string;
+ action: 'rename' | 'remove' | 'restore';
+ name?: string;
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ }) => Promise<void>;
listProviders: () => Promise<{
dataOwnerId: string | null;
ownerGeneration: number;
@@ -5173,8 +5226,16 @@ interface ElectronAPI {
keys: Partial<Record<'claude-code' | 'codex' | 'pi', string>>,
options?: CustomProviderUpdateOptions,
) => Promise<CustomProviderUpdateResult>;
- disconnectCustomProvider: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions) => Promise<CustomProviderUpdateResult>;
- deleteCustomProvider: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions) => Promise<CustomProviderUpdateResult>;
+ disconnectCustomProvider: (
+ providerId: string,
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ options?: CustomProviderUpdateOptions,
+ ) => Promise<CustomProviderUpdateResult>;
+ deleteCustomProvider: (
+ providerId: string,
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ options?: CustomProviderUpdateOptions,
+ ) => Promise<CustomProviderUpdateResult>;
localModelStatus: () => Promise<import('../shared/localModelRuntime').LocalRuntimeStatus>;
localModelStart: () => Promise<import('../shared/localModelRuntime').LocalRuntimeStatus>;
localModelList: () => Promise<{
@@ -5287,7 +5348,9 @@ interface ElectronAPI {
onProvidersChanged: (cb: () => void) => () => void;
// 自定义 MCP 服务器配置 CRUD(可选 bearer token 另走通用 safeStorage IPC,不经这里)。
- listCustomMcpServers: (context?: import('../shared/customMcp').CustomMcpListContext) => Promise<import('../shared/customMcp').CustomMcpListResult>;
+ listCustomMcpServers: (
+ context?: import('../shared/customMcp').CustomMcpListContext,
+ ) => Promise<import('../shared/customMcp').CustomMcpListResult>;
createCustomMcpServer: (
config: import('../shared/customMcp').CustomMcpConfig,
) => Promise<{ ok: true }>;
@@ -5304,7 +5367,11 @@ interface ElectronAPI {
providerId: string,
options?: { ownerId?: string },
) => Promise<{ ok: boolean; reason?: string }>;
- providerOAuthLogout: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions) => Promise<CustomProviderUpdateResult>;
+ providerOAuthLogout: (
+ providerId: string,
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ options?: CustomProviderUpdateOptions,
+ ) => Promise<CustomProviderUpdateResult>;
providerOAuthCancel: (
providerId: string,
options?: { releaseOwner?: boolean; ownerId?: string },
@@ -5320,18 +5387,22 @@ interface ElectronAPI {
) => Promise<import('../shared/providerImport').ProviderImportConfirmResult>;
cancelProviderImport: (importId: string) => Promise<{ ok: true }>;
onProviderOAuthProgress: (
- cb: (progress: {
- providerId: string;
- phase: 'device-code';
- verificationUrl: string;
- userCode: string;
- expiresAt: number;
- } | {
- providerId: string;
- ownerId: string;
- phase: 'browser-url';
- url: string | null;
- }) => void,
+ cb: (
+ progress:
+ | {
+ providerId: string;
+ phase: 'device-code';
+ verificationUrl: string;
+ userCode: string;
+ expiresAt: number;
+ }
+ | {
+ providerId: string;
+ ownerId: string;
+ phase: 'browser-url';
+ url: string | null;
+ },
+ ) => void,
) => () => void;
/** 自定义供应商上游错误订阅(返回 off);code 走 providerError.* i18n。 */
onProviderUpstreamError: (
@@ -6261,15 +6332,23 @@ interface ElectronAPI {
/** Claude.ai 订阅 OAuth 登录状态(系统 ~/.claude 凭证库是否有 OAuth 登录) */
claudeOAuthStatus: () => Promise<{ authorized: boolean }>;
/** 连接本机 Claude 订阅;loginKey 用于限定取消范围。 */
- claudeOAuthLogin: (loginKey?: string) => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;
+ claudeOAuthLogin: (
+ loginKey?: string,
+ ) => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;
/** 断开 Cindy 使用许可,保留本机 Claude 凭证。 */
- claudeOAuthLogout: (ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => Promise<{ authorized: boolean }>;
+ claudeOAuthLogout: (ownerScope?: {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ }) => Promise<{ authorized: boolean }>;
/** 取消对应登录尝试。 */
claudeOAuthCancel: (loginKey?: string) => Promise<{ authorized: boolean }>;
/** 拉起浏览器 OAuth 登录 xAI(SuperGrok 订阅);成功写 safeStorage。reason 在失败时给出 */
xaiOAuthLogin: () => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;
/** 登出 xAI(清本机 safeStorage 的 xai 凭证) */
- xaiOAuthLogout: (ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => Promise<{ authorized: boolean }>;
+ xaiOAuthLogout: (ownerScope?: {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ }) => Promise<{ authorized: boolean }>;
/** 取消进行中的 xAI 浏览器 OAuth 登录流 */
xaiOAuthCancel: () => Promise<{ authorized: boolean }>;
@@ -6302,7 +6381,9 @@ interface ElectronAPI {
sessionId?: string,
) => Promise<{ title: string | null }>;
/** Optional status copy from public execution facts only. */
- polishWorkingStatus: (request: import('../shared/workingStatus').WorkingStatusRequest) => Promise<{ text: string | null }>;
+ polishWorkingStatus: (
+ request: import('../shared/workingStatus').WorkingStatusRequest,
+ ) => Promise<{ text: string | null }>;
/** 重命名输入框 Magic 按钮:按会话最新对话内容重新生成标题(失败返 title: null)。 */
regenerateSessionTitle: (sessionId: string) => Promise<{ title: string | null }>;
/**
@@ -6399,7 +6480,10 @@ interface ElectronAPI {
agentKind: 'claude-code' | 'codex' | 'pi',
options?: { releaseOwner?: boolean; ownerId?: string },
) => Promise<void>;
- logout: (agentKind: 'claude-code' | 'codex' | 'pi', ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }) => Promise<void>;
+ logout: (
+ agentKind: 'claude-code' | 'codex' | 'pi',
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ ) => Promise<void>;
onStateChanged: (
cb: (s: { agentKind: 'claude-code' | 'codex' | 'pi' } & CodexAuthState) => void,
) => () => void;
@@ -6445,11 +6529,14 @@ interface ElectronAPI {
cachedTokens?: number;
cacheCreationTokens?: number;
}>;
- getAccount: (agentKind: 'claude-code' | 'codex' | 'pi', providerId?: string) => Promise<unknown | null>;
+ getAccount: (
+ agentKind: 'claude-code' | 'codex' | 'pi',
+ providerId?: string,
+ ) => Promise<unknown | null>;
/** Codex app-server authoritative windows and banked reset-credit metadata. */
- getCodexRateLimits: (providerId?: string) => Promise<
- import('@cindy/maker-shared/device-link-contract').MobileCodexRateLimitsResult
- >;
+ getCodexRateLimits: (
+ providerId?: string,
+ ) => Promise<import('@cindy/maker-shared/device-link-contract').MobileCodexRateLimitsResult>;
/** Cindy AI /models 下发的 XD 原生报价。 */
getModelPricing: () => Promise<import('../shared/regionalMoney').ModelPricingCatalog | null>;
onModelPricingChanged: (
@@ -6528,9 +6615,16 @@ interface ElectronAPI {
providerId?: string,
) => () => void;
/** Existing native Anthropic subscription snapshot (null means cleared). */
- getClaudeSubscription: (providerId?: string) => Promise<import('../shared/claudeSubscriptionUsage').ClaudeSubscriptionUsageSnapshot | null>;
+ getClaudeSubscription: (
+ providerId?: string,
+ ) => Promise<
+ import('../shared/claudeSubscriptionUsage').ClaudeSubscriptionUsageSnapshot | null
+ >;
onClaudeSubscriptionChanged: (
- cb: (snapshot: import('../shared/claudeSubscriptionUsage').ClaudeSubscriptionUsageSnapshot | null) => void,
+ cb: (
+ snapshot:
+ import('../shared/claudeSubscriptionUsage').ClaudeSubscriptionUsageSnapshot | null,
+ ) => void,
providerId?: string,
) => () => void;
getXaiSubscription: (providerId?: string) => Promise<unknown | null>;
@@ -6672,7 +6766,11 @@ interface ElectronAPI {
};
plugins: {
- list: (workingDir?: string, includeHidden?: boolean, botContext?: Omit<BotToolsetContext, 'workingDir'>) => Promise<PluginListItem[]>;
+ list: (
+ workingDir?: string,
+ includeHidden?: boolean,
+ botContext?: Omit<BotToolsetContext, 'workingDir'>,
+ ) => Promise<PluginListItem[]>;
getState: (
id: string,
workingDir?: string,
diff --git a/apps/desktop/src/shared/cindyMakeDoctor.ts b/apps/desktop/src/shared/cindyMakeDoctor.ts
index f5115e06ba..415725c98c 100644
--- a/apps/desktop/src/shared/cindyMakeDoctor.ts
+++ b/apps/desktop/src/shared/cindyMakeDoctor.ts
@@ -69,6 +69,10 @@ export interface CindyMakeTaskPreparation {
/** Settings projection; preparation completion is not production completion. */
sessionStatus?: 'active' | 'archived' | 'deleted';
executing?: boolean;
+ /** Live file comparison for Settings, never inferred from preparation or build success. */
+ integration?: 'integrated' | 'unintegrated' | 'unknown';
+ /** An explicitly confirmed end left cleanup unfinished; restart never replays deletion. */
+ cleanupPending?: boolean;
/** Persisted only after the task directory and branch have both been reclaimed. */
finished?: boolean;
}
@@ -117,12 +121,14 @@ export const CINDY_MAKE_TASK_ERROR_CODES = [
] as const;
export type CindyMakeTaskError = (typeof CINDY_MAKE_TASK_ERROR_CODES)[number];
export interface CindyMakeTaskActionState {
- action: 'finish' | 'delete';
+ /** Legacy finish/delete callers retain their existing semantics. */
+ action: 'end' | 'finish' | 'delete';
status: 'running' | 'failed';
error?: CindyMakeTaskError;
}
export interface CindyMakeGlobalState {
+ upstreamMerge?: import('./cindyMakeMerge').CindyMakeMergeState;
ownerStamp?: import('./dataOwnerPush').DataOwnerPushStamp;
environmentCheck?: CindyMakeOperationSnapshot;
environmentPrepare?: CindyMakeOperationSnapshot;
@@ -195,6 +201,14 @@ export interface MakeSourceGitProgress {
message?: string;
}
+/** Live upstream lookup; never inferred from a cached origin/main ref or persisted on disk. */
+export type MakeSourceLatestVersion = {
+ channel: 'dev' | 'beta' | 'release';
+} & (
+ | { status: 'unavailable' }
+ | { status: 'ready'; ref: string; commit: string; ahead?: number; behind?: number }
+);
+
/** Persisted summary of the managed Cindy source checkout. */
export interface MakeSourceStatus {
status: 'missing' | 'preparing' | 'ready' | 'failed' | 'cancelled';
@@ -210,6 +224,7 @@ export interface MakeSourceStatus {
mainRemoteCommit?: string;
mainBehind?: number;
mainAhead?: number;
+ latestVersion?: MakeSourceLatestVersion;
error?: MakeSourcePreparation['error'];
phase?: MakeSourcePreparation['phase'];
progress?: MakeSourceGitProgress;
diff --git a/apps/desktop/src/shared/cindyMakeHistory.ts b/apps/desktop/src/shared/cindyMakeHistory.ts
new file mode 100644
index 0000000000..1c1b25beaf
--- /dev/null
+++ b/apps/desktop/src/shared/cindyMakeHistory.ts
@@ -0,0 +1,147 @@
+import type { CindyMakeCompletionMeta, CindyMakePersonalBuildState } from './cindyMakeSession';
+
+export type MakeFeatureAction = 'integrate' | 'revert' | 'reapply';
+export interface MakeFeatureReceipt {
+ id: string;
+ action: MakeFeatureAction;
+ at: number;
+ baselineCommit: string;
+ commit: string;
+ beforeTree: string;
+ tree: string;
+ taskTree: string;
+}
+export interface MakeHistoryCompletion extends CindyMakeCompletionMeta {
+ id: string;
+}
+export interface MakeHistoryVersion {
+ operationId: string;
+ commit: string;
+ at?: number;
+ versionId?: string;
+}
+/** Durable, owner-private facts; directory cleanup does not delete this record. */
+export interface CindyMakeHistoryRecord {
+ schema: 1;
+ runId: string;
+ sessionId: string;
+ title: string;
+ request: string;
+ createdAt: number;
+ updatedAt: number;
+ endedAt?: number;
+ completions: MakeHistoryCompletion[];
+ receipts: MakeFeatureReceipt[];
+ versions: MakeHistoryVersion[];
+}
+export type MakeHistoryAction =
+ | MakeFeatureAction
+ | 'open'
+ | 'continue'
+ | 'test'
+ | 'resolve'
+ | 'retry'
+ | 'build'
+ | 'end'
+ | 'retry-prepare'
+ | 'retry-cleanup';
+export type MakeHistoryLifecycle =
+ 'preparing' | 'running' | 'editing' | 'ready' | 'failed' | 'ended' | 'cleanup';
+export type MakeHistoryIntegration =
+ 'unintegrated' | 'integrated' | 'changed' | 'reverted' | 'unknown' | 'unchanged';
+export type MakeHistoryActionReason =
+ | 'busy'
+ | 'checking'
+ | 'ended'
+ | 'sessionUnavailable'
+ | 'completionUnavailable'
+ | 'sourceUnavailable'
+ | 'changedAfterCompletion';
+export interface CindyMakeHistoryItem extends CindyMakeHistoryRecord {
+ lifecycle: MakeHistoryLifecycle;
+ integration: MakeHistoryIntegration;
+ actions: MakeHistoryAction[];
+ completionId?: string;
+ resolutionSessionId?: string;
+ operation?: MakeFeatureAction | 'end' | 'build';
+ conflict?: boolean;
+ operationError?: string;
+ needsBuild?: boolean;
+ build?: CindyMakePersonalBuildState;
+ /** Why the action area is empty; derived from Main facts, never guessed by Renderer. */
+ actionReason?: MakeHistoryActionReason;
+}
+export interface CindyMakeHistoryState {
+ items: CindyMakeHistoryItem[];
+ busy: boolean;
+ canBuild: boolean;
+ build?: CindyMakePersonalBuildState;
+}
+/** The last undo removes all preceding active changes; reapply starts a new effective delta. */
+export function activeFeatureReceipts(receipts: MakeFeatureReceipt[]): MakeFeatureReceipt[] {
+ const lastUndo = receipts.findLastIndex((receipt) => receipt.action === 'revert');
+ return receipts.slice(lastUndo + 1).filter((receipt) => receipt.action !== 'revert');
+}
+/** One policy for both the visible controls and Main's action admission. */
+export function makeHistoryActions(facts: {
+ lifecycle: MakeHistoryLifecycle;
+ integration: MakeHistoryIntegration;
+ sessionAvailable: boolean;
+ workspaceAvailable: boolean;
+ sourceAvailable: boolean;
+ completed: boolean;
+ hasReceipts: boolean;
+ busy: boolean;
+ conflict: boolean;
+ newChanges?: boolean;
+ recoverableFailure?: boolean;
+ buildFailed?: boolean;
+ needsBuild?: boolean;
+ buildSourceAvailable?: boolean;
+ canEdit?: boolean;
+}): MakeHistoryAction[] {
+ const actions: MakeHistoryAction[] = facts.sessionAvailable ? ['open'] : [];
+ if (facts.busy) return actions;
+ if (facts.recoverableFailure) return [...actions, 'retry'];
+ if (
+ (facts.buildFailed || facts.needsBuild) &&
+ (facts.buildSourceAvailable ?? facts.sourceAvailable)
+ )
+ actions.push('build');
+ if (facts.conflict) return [...actions, 'resolve'];
+ if (facts.lifecycle === 'cleanup') return [...actions, 'retry-cleanup'];
+ if (facts.lifecycle === 'preparing' || facts.lifecycle === 'running') return actions;
+ if (facts.integration === 'unknown')
+ return facts.lifecycle !== 'ended' &&
+ facts.sessionAvailable &&
+ (facts.sourceAvailable || !facts.workspaceAvailable)
+ ? [...actions, 'end']
+ : actions;
+ if (facts.lifecycle === 'failed' && facts.sessionAvailable && facts.canEdit !== false)
+ return [...actions, 'retry-prepare', 'end'];
+ if (facts.lifecycle !== 'ended' && facts.sessionAvailable) {
+ if (facts.workspaceAvailable && facts.completed) {
+ actions.splice(actions.indexOf('open'), actions.includes('open') ? 1 : 0);
+ actions.push('continue');
+ if (facts.sourceAvailable && facts.integration !== 'unchanged') actions.push('test');
+ }
+ }
+ if (
+ facts.completed &&
+ (facts.workspaceAvailable || facts.lifecycle === 'ended') &&
+ facts.sourceAvailable &&
+ facts.integration !== 'integrated' &&
+ facts.integration !== 'unchanged' &&
+ (facts.integration !== 'reverted' || facts.newChanges) &&
+ !actions.includes('integrate')
+ )
+ actions.push('integrate');
+ if (facts.lifecycle !== 'ended' && facts.sessionAvailable) actions.push('end');
+ if (facts.sourceAvailable && facts.hasReceipts) {
+ if (facts.integration === 'reverted') {
+ if (!actions.includes('integrate')) actions.push('reapply');
+ } else if (facts.integration === 'integrated' || facts.integration === 'changed')
+ actions.push('revert');
+ }
+ return actions;
+}
diff --git a/apps/desktop/src/shared/cindyMakeMerge.ts b/apps/desktop/src/shared/cindyMakeMerge.ts
new file mode 100644
index 0000000000..247d3d85fc
--- /dev/null
+++ b/apps/desktop/src/shared/cindyMakeMerge.ts
@@ -0,0 +1,57 @@
+import type { CindyMakeTaskOptions } from './cindyMakeDoctor';
+import type { MakeFeatureAction } from './cindyMakeHistory';
+
+export interface MakeFeatureMergePlan {
+ runId: string;
+ taskSessionId: string;
+ action: MakeFeatureAction;
+ taskTree: string;
+ completionId?: string;
+ mergeCommit?: string;
+ steps: Array<{ before: string; after: string }>;
+ nextStep: number;
+ awaitingResolution?: boolean;
+}
+
+/** Upstream integration is a separate task purpose, never a personal-feature build task. */
+export const CINDY_MAKE_MERGE_SESSION_SOURCE = 'cindy-make-merge' as const;
+export function isCindyMakeFamilySource(source: unknown): boolean {
+ return source === 'cindy-make' || source === CINDY_MAKE_MERGE_SESSION_SOURCE;
+}
+export type CindyMakeMergeError =
+ | 'busy'
+ | 'dirty'
+ | 'localMain'
+ | 'unavailable'
+ | 'gitFailed'
+ | 'baselineChanged'
+ | 'checksFailed'
+ | 'interrupted'
+ | 'startFailed';
+export interface CindyMakeMergeState {
+ id: string;
+ status: 'fetching' | 'merging' | 'conflict' | 'resolving' | 'checking' | 'merged' | 'failed';
+ ref: string;
+ upstreamCommit: string;
+ baselineCommit?: string;
+ baselineTree?: string;
+ /** Missing on retained file-only operations from older clients. */
+ strategy?: 'rebase';
+ rebaseBase?: string;
+ /** Merge-only resolutions need an explicit content review before a flattened rebase is adopted. */
+ rebaseReview?: boolean;
+ /** Native feature integration/undo shares the same retained conflict lifecycle. */
+ feature?: MakeFeatureMergePlan;
+ tree?: string;
+ commit?: string;
+ sessionId?: string;
+ /** A retained candidate must not be removed by source preparation/reset. */
+ hasWorkspace?: boolean;
+ ownedByAnotherAccount?: boolean;
+ error?: CindyMakeMergeError;
+}
+export type CindyMakeMergeAction = 'update' | 'resolve' | 'status';
+export interface CindyMakeMergeRequest {
+ action: CindyMakeMergeAction;
+ createOptions?: CindyMakeTaskOptions;
+}
diff --git a/apps/desktop/src/shared/cindyMakeSession.ts b/apps/desktop/src/shared/cindyMakeSession.ts
index 8f060014e0..fcd747aa93 100644
--- a/apps/desktop/src/shared/cindyMakeSession.ts
+++ b/apps/desktop/src/shared/cindyMakeSession.ts
@@ -30,10 +30,81 @@ export function isCindyMakeVendorOptions(
*/
export interface CindyMakeCompletionMeta {
reportedAt: number;
- /** Files committed by this completion on the task branch; absent when Git could not answer. */
+ /** Explicitly returned to editing; this completion must not replace input again. */
+ continuedAt?: number;
+ test?: CindyMakeTestState;
+ personal?: CindyMakePersonalBuildState;
+ lastAction?: 'test' | 'build';
+ /** Changed files in the task workspace; absent when Git could not answer. */
changedFiles?: number;
- /** Task-branch commit created by this completion (or HEAD when nothing changed). */
+ /** Local task commit after completion; older records may contain a file-only base HEAD. */
commit?: string;
- /** Task branch the changes were committed to. */
+ /** File-content tree, distinct from commit history. */
+ tree?: string;
+ /** Creation baseline, used to distinguish a completed no-op from a feature waiting for integration. */
+ baseTree?: string;
+ /** Task branch owning this completed change. */
branch?: string;
}
+
+export interface CindyMakeTestState {
+ status: 'starting' | 'ready' | 'failed' | 'stopped';
+ error?: 'unavailable' | 'changed' | 'environment' | 'launchFailed' | 'timeout' | 'interrupted';
+}
+
+export interface CindyMakePersonalBuildState {
+ status: 'waiting' | 'checking' | 'merging' | 'packaging' | 'publishing' | 'ready' | 'failed';
+ /** Optional detail within checking; old records/clients retain the broad status. */
+ checkStep?: 'dependencies' | 'tests' | 'types';
+ /** Cancellation is pending until owned processes and disposable outputs are cleaned. */
+ stopping?: boolean;
+ startedAt?: number;
+ /** Verified packaged snapshot, adopted by the personal baseline on success. */
+ commit?: string;
+ /** File-content tree, distinct from commit history. */
+ tree?: string;
+ artifactDirectory?: string;
+ artifactName?: string;
+ sha256?: string;
+ /** Complete runnable snapshot, absent on legacy installer-only builds. */
+ versionId?: string;
+ /** Exact feature operations captured under the source lock for this build. */
+ includedFeatures?: Array<{ runId: string; operationId: string }>;
+ generatedAt?: number;
+ buildId?: string;
+ error?:
+ | 'unavailable'
+ | 'changed'
+ | 'environment'
+ | 'missingShell'
+ | 'checksFailed'
+ | 'conflict'
+ | 'baselineChanged'
+ | 'buildFailed'
+ | 'cancelled'
+ | 'cleanupFailed'
+ | 'interrupted';
+}
+
+/** Only known failure codes may cross from build processes or saved records into UI. */
+export function parseCindyMakeBuildError(
+ value: unknown,
+): NonNullable<CindyMakePersonalBuildState['error']> {
+ switch (value) {
+ case 'unavailable':
+ case 'changed':
+ case 'environment':
+ case 'missingShell':
+ case 'checksFailed':
+ case 'conflict':
+ case 'baselineChanged':
+ case 'interrupted':
+ case 'cancelled':
+ case 'cleanupFailed':
+ return value;
+ default:
+ return 'buildFailed';
+ }
+}
+
+export type CindyMakeTestAction = 'start' | 'continue' | 'status' | 'build' | 'open-build';
diff --git a/apps/desktop/src/shared/cindyVersions.ts b/apps/desktop/src/shared/cindyVersions.ts
new file mode 100644
index 0000000000..867e0e51b6
--- /dev/null
+++ b/apps/desktop/src/shared/cindyVersions.ts
@@ -0,0 +1,24 @@
+/** Public projection: executable paths and launch capabilities never cross into Renderer. */
+export interface CindyVersionInfo {
+ id: string;
+ kind: 'original' | 'personal';
+ development?: boolean;
+ version?: string;
+ dirty?: boolean;
+ title?: string;
+ builtAt?: string;
+ commit?: string;
+ available: boolean;
+ compatible: boolean;
+}
+
+export interface CindyVersionsState {
+ currentId: string;
+ selectedId: string;
+ switching: boolean;
+ versions: CindyVersionInfo[];
+}
+
+export type CindyVersionAction = 'switch' | 'remove';
+export const CINDY_ORIGINAL_VERSION = 'original';
+export const CINDY_VERSION_PROTOCOL = 1;
diff --git a/apps/desktop/src/shared/sessionSource.ts b/apps/desktop/src/shared/sessionSource.ts
index a754a279f5..61aea379fa 100644
--- a/apps/desktop/src/shared/sessionSource.ts
+++ b/apps/desktop/src/shared/sessionSource.ts
@@ -15,6 +15,7 @@ export const SESSION_SOURCES = [
'plugin',
'bot',
'cindy-make',
+ 'cindy-make-merge',
] as const;
export type SessionSource = (typeof SESSION_SOURCES)[number];
@@ -76,6 +77,7 @@ export const DESKTOP_VISIBLE_SESSION_SOURCES: SessionSource[] = [
'shared',
'plugin',
'cindy-make',
+ 'cindy-make-merge',
];
export function normalizeSessionSource(source: unknown): SessionSource {
@@ -93,7 +95,8 @@ export function normalizeSessionSource(source: unknown): SessionSource {
source === 'shared' ||
source === 'plugin' ||
source === 'bot' ||
- source === 'cindy-make'
+ source === 'cindy-make' ||
+ source === 'cindy-make-merge'
? source
: 'desktop';
}
diff --git a/docs/cindy-make-upstream.md b/docs/cindy-make-upstream.md
index 1cccc0e27b..c2662adad2 100644
--- a/docs/cindy-make-upstream.md
+++ b/docs/cindy-make-upstream.md
@@ -40,10 +40,36 @@ Main 负责网络和 Git,UI 只消费报告;运行版本摘要在结果详
## 个人版任务准备
+### 文件与分支边界(2026-09-18 用户更新裁决)
+
+用户选择本地提交、合并与 rebase,替代此前只应用文件且永不提交的模型。`main` 只包含
+官方提交,Cindy Make 永不推送远端。模型在任务 worktree 修改、验证并回报完成后,宿主在
+该任务分支创建带 DCO 签名的本地提交;未成功结束的轮次不提交或生成完成卡。没有新改动
+不制造空提交。通用自动保存点仍跳过托管目录,避免在明确完成边界之外提交。
+
+生成个人版时先把功能分支的提交合入 `cindy-personal`,再从这个实际源码目录安装依赖、
+检查、构建。临时目录用于检测冲突并形成候选合并提交,不在那里构建。成功合入后的
+个人源码工作区保持干净;构建失败/取消保留已合入提交与任务,不回退源码。
+旧完成记录只有文件树时仍能转换为本地提交。源码存在旧版未提交内容时先保存原 HEAD、
+暂存树与文件树;若此前已应用官方文件但分支仍停在旧提交,以已记录的官方基线保存个人
+差异,不把大量上游文件误当成个人功能提交。所有旧历史与文件备份通过本地引用保留。
+
+获取官方更新时先固定当前渠道目标、更新本地 main,再在独立分支/worktree 中把个人提交
+rebase 到新官方基线(禁止 update-refs 自动改动其他任务分支)。无冲突自动采纳;有冲突
+自动创建独立任务,沿用当前模型设置。冲突解决并完整结束 rebase、校验个人源码未并发
+变化后,才更新 cindy-personal。结果是“最新 main + 个人提交”,不是要求两者 hash 相等;
+官方更新不再堆积在未提交列表中。旧版遗留冲突现场仍可完成并迁移,新旧路径均不推送。
+实现见 [localHistory](../apps/desktop/src/main/cindy-make/localHistory.ts) 与
+[真实 Git 回归](../apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts)。
+
- 环境、个人版源码、任务分支和工作目录统一由 Main 的 `CindyMakeManager` 管理。
源码准备/清理、任务工作目录创建/依赖安装、完成后的 Git 写操作共用项目队列,
不再由 Settings、消息卡片或创建弹窗各自维护后台作业。发送入场与源码清理互斥,
已进入发送事务或运行中的任务禁止清理源码;清理已开始时拒绝新的发送。
+- Settings → Cindy Make 分为“版本控制”和“环境检查”两个页签,版本控制排在首位并默认打开。
+ 工具检查、Dev 测试开关和个人版源码准备归环境检查;我的版本和制作历史归版本控制。
+ 创建个人版本入口放在版本控制页签内、我的版本上方。切换只改变可见面板,保留检查/准备作业、展开状态与
+ 制作搜索内容;进入版本控制时重新读取版本列表。页签支持方向键、Home/End 及独立面板标识。
- 输入 /cindy-make 需求后,在当前页面弹窗检查环境、准备个人版源码并查询上游;
这段前置流程不创建任务、不创建 worktree;源码准备与 Settings 共用同一流程,
准备 Git 内容后按锁文件预热依赖缓存,不生成个人分支的依赖目录或执行安装脚本。
@@ -60,6 +86,17 @@ Main 负责网络和 Git,UI 只消费报告;运行版本摘要在结果详
缓存缺失或版本变化时按需补下载,任务 worktree 再复用缓存独立安装并执行安装脚本。
Settings 源码卡的底部状态常驻:区分等待其他工程操作、Git 检查、上游版本查询和本地源码检查,
收起详情后仍显示当前阶段与已有进度。失败或停止时保留结果和原因,按钮为「重试准备」;
+ 卡片进入页面即显示,先发布本机保存的源码摘要,再补 Git 版本与联网查询结果;
+ 不让工具发现或网络查询阻塞整张卡。重新进入保留已有信息,查询失败仍显示本地版本。
+ 各阶段共用同一刷新代次,迟到的查询不能覆盖之后的准备、清理或较新的查询结果。
+ Settings 的「main 版本」用一行展示「当前 hash → 最新 hash(差距)」:当前版本为次要文字色,
+ 箭头为图标,最新版本与括号内差距使用成功色;省略领先/落后的零值。
+ 开发版查询 GitHub 最新 main,
+ beta 查询最新已发布 beta 的 tag,正式版查询最新非 beta 发布的 tag;渠道之间不回退。
+ 能核实时显示本地 main 相对该版本的领先/落后提交数,查询失败不把缓存的 origin/main
+ 当作最新版本。查询只读、最长等待 10 秒,成功结果在进程内复用一分钟;
+ 实现与回归见 [latestSourceVersion](../apps/desktop/src/main/cindy-make/latestSourceVersion.ts)
+ 和[渠道查询测试](../apps/desktop/src/main/cindy-make/__tests__/latestSourceVersion.test.ts)。
点击重试立即切换到本轮状态,不沿用上一轮错误或进度。
准备不冒充 Agent 正在执行。
首阶段检查及源码准备也按 runId 从 Main 读取完整报告;Renderer 重载不退回过时的保存卡片。
@@ -67,13 +104,76 @@ Main 负责网络和 Git,UI 只消费报告;运行版本摘要在结果详
- 准备成功后由 Main 自动发送原始需求,通过既有发送事务继承模型、供应商、推理档位、
权限、计划模式与 Fast 设置。确认后的任务准备不因切换任务或重载 Renderer 中止,
也不会丢失首次发送;确认前关闭弹窗则停止该轮前置检查。
-- 从确认后的准备阶段到首次自动执行结束,普通输入区用飞书接管同款状态框替代,
- 不接受输入、语音或附件拖入;Ask Question、Plan 和权限确认仍优先展示并正常操作。
- 首轮结束后恢复输入,之后的手动执行不再锁定。准备失败/取消时提示从准备卡重试;
- 执行中保留停止入口,执行失败或中断继续使用既有恢复入口。判定复用持久准备报告与
- 主进程的执行结束记录,切换页面或重载不会提前解锁。
+- 确认后,完整准备卡替代普通输入区,显示步骤、下载/安装进度及停止/重试操作;
+ 直接复用输入框的背景和边框,详情限高滚动,操作留在固定底栏。环境、源码和依赖
+ 准备完成后立即恢复普通输入框,包括第一次自动执行;修改期间沿用普通任务的输入、
+ 语音、附件及停止操作。该任务自己的准备卡不再重复显示在消息流中,持久报告仍用于
+ 重载恢复,Settings 与来源任务中的卡片继续保留。Ask Question、Plan 和权限确认
+ 保持原有优先级。准备失败/取消时从准备卡重试;执行失败或中断使用既有恢复入口。
+ 已结束的执行记录优先于过时的准备报告,切换页面或重载不会重新锁住输入框。
见 [CindyMakeComposerMask](../apps/desktop/src/renderer/components/cindy-make/CindyMakeComposerMask.tsx)
和[生命周期回归](../apps/desktop/src/renderer/lib/__tests__/cindyMakeComposer.test.ts)。
+- 每轮修改完成回报落库后,本机制作任务在输入区显示“修改已完成,选择下一步”,沿用输入框
+ 背景和边框,状态、说明与已核实的文件信息合为一个内容区,不重复显示“修改源码”步骤;
+ 底栏提供“继续修改”“启动隔离版测试”和“生成个人版”。同一完成记录
+ 不再重复出现在本机消息流。继续修改需 Main 确认并持久化,重载不恢复已收起的旧卡;
+ 新的用户消息或下一次完成回报会取代旧结果。提问、计划和权限交互保持原有优先级。
+- 测试必须由用户点击启动。Main 只接受当前账号的本机制作任务及最新完成记录,检查
+ 工作目录仍属于托管 worktree、没有链接替换、分支与原有 HEAD 匹配,且文件内容与完成
+ 时的 tree 一致,然后经既有开发版启动器启动独立命名的隔离实例。旧完成记录沿用干净
+ HEAD 的核验。PTY 保留启动器的终端语义,
+ 不另开命令行窗口;环境只保留系统及工具配置,不继承宿主 profile、凭证和 Node 注入。
+ 只有与目标目录、commit、隔离名及区域匹配的 ready 回执才显示已启动,不能把它当作
+ 用户验收通过。状态写入该完成记录并沿用消息推送;切换页面不取消启动。
+- “生成个人版”同样由用户点击触发:固定本次完成的提交和文件树,在临时工作目录与
+ 当前 cindy-personal 合并,无冲突则将本地合并提交采纳到个人版并保存合入记录。
+ 旧版仅含文件树的完成记录兼容转换为本地提交。随后依赖安装、相关单测、类型检查与打包都在
+ `source` 目录的 `cindy-personal` 分支执行,使用既有版本无关打包入口,保留 packaged smoke。
+ 校验安装包的区域、架构、commit 与 SHA-256,保存到本机专属产物目录后,重新核对任务
+ 与个人版文件没有变化。冲突不影响个人版原文件;合入后检查/打包失败或取消,
+ 两个工作目录的源码都保留,重试从已合入记录继续,失败产物不进入版本列表。
+ 同一源码从合入直到成品保存与清理全程持有项目锁,其他源码操作排队;临时合并目录
+ 在结束后清理,个人版源码与依赖保留供下次生成复用。除安装包外,将完整可运行
+ 应用保存成独立快照(Windows 完整目录、macOS 完整 .app),保留签名、执行权限与
+ 包内相对链接;外部链接拒绝进入快照。成品位于独立的 `userData/cindy-versions`,清理
+ 源码不删除成品。检查、打包与保存完成后才登记到版本列表,生成不自动启用、安装或发布。
+ 新源码声明启动协议后,完成卡按钮变成“切换到此个人版”;旧源码/旧完成记录继续保留
+ “查看安装包”,不声称不具备协议的旧程序能够接管当前数据。
+- 个人版排队、合并、检查、打包及保存期间,完成卡三个操作全部禁用,成功或失败后恢复;
+ “继续修改”不作为生成期间的取消入口。继续修改会停止本次测试进程,退出宿主会取消
+ 构建;文件合入已经开始时完成合入记录并保留源码,成品登记完成时保留成功产物及
+ 回执。运行与清理完成前保持工作目录占用,避免误删。应用重启不自动重放启动或构建,
+ 旧在途状态按已中断呈现,可显式重试。入口仅本机 Desktop 提供;远端 Desktop 保留完成记录与输入框,手机可读取
+ 已有消息投影,不新增远程 invoke 白名单,也不改变 SSH 或 device-link 恢复策略。
+ 设置页制作历史在生成期间收敛为一个状态卡,显示合并、检查(依赖/测试/类型)、打包和保存步骤,
+ 提供“停止制作”。停止只中止本次构建进程,并清理临时合并目录、未完成安装包、打包输出和构建元数据;
+ 不回退个人源码、已合入提交、历史记录或已生成版本。历史记录没有安全动作时,Main 返回不可用原因,
+ 页面必须显示原因,不能留下空白按钮区。
+ 实现与回归见 [testRuntime](../apps/desktop/src/main/cindy-make/testRuntime.ts)、
+ [testRunner](../apps/desktop/src/main/cindy-make/testRunner.ts)、
+ [personalBuild](../apps/desktop/src/main/cindy-make/personalBuild.ts) 及其
+ [真实 Git 回归](../apps/desktop/src/main/cindy-make/__tests__/personalBuild.git-integration.test.ts) 和
+ [CindyMakeTestCard](../apps/desktop/src/renderer/components/cindy-make/CindyMakeTestCard.tsx)。
+- 本机版本只有“原版”和“个人版”两类。Dev 与正式安装版都属于原版,只在启动方法上
+ 分别恢复 Forge/Vite 与安装应用;Dev 同样记住选择。从哪个原版进入,就沿用它的账号、
+ 设置、任务、设备身份和钥匙串身份,不能从 Dev 误跳到另一份正式数据目录。Dev 本地/
+ 自定义端点按已校验的公共配置保存给个人版,不能把本地登录凭证送往线上;恢复 Dev
+ 时仍使用原开发入口和端点配置。个人版自身启动不依赖原源码目录。
+- 设置中的“我的版本”和完成卡共用本机切换操作;Renderer 只传版本 ID,不接受路径或
+ 启动命令。原版不存在个人版选择时正常启动;生成过但未切换也不改变默认。启动入口
+ 在数据库打开前分流,显式 `--cindy-version-original` 可恢复原版。已运行的实例复用
+ Electron 单实例激活;使用版本管理后 Dev/安装版共享该 profile 的实例锁。
+- 切换先核验完整应用与数据兼容性、检查在途工作,再由独立的无窗口 Electron 交接进程
+ 等待旧进程正常退出并启动目标。返回 Dev 复用既有开发 runner 和 PTY;不以裸 Electron
+ 重启替代 Forge/Vite。只有既有窗口+认证/数据库就绪合同成功后才记住新选择,失败
+ 停止本次启动并尝试上一版本。登录回调、文件入口只在进程间临时转交,不写版本记录。
+- 个人版对已有数据库只进行严格兼容核对,不迁移其 schema;不兼容的版本拒绝切换,
+ 不通过回退数据库丢弃后续任务。个人版停用 Cindy 本体的应用更新检测、下载和安装,
+ 保持原入口的系统协议注册;原版仍走其既有更新规则。正在使用/选中的成品不允许清理。
+ 实现与回归见 [versionStartup](../apps/desktop/src/main/cindy-make/versionStartup.ts)、
+ [versionStore](../apps/desktop/src/main/cindy-make/versionStore.ts)、
+ [versionService](../apps/desktop/src/main/cindy-make/versionService.ts) 和
+ [版本切换回归](../apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts)。
- 失败或取消时不发送需求;显式重试复用原任务和分支。取消单个任务不会取消共享的
环境/源码准备;全局准备的停止入口仍在 Settings。重复点击、打开已有任务不会再次派发。
- 应用进程重启不静默重放请求。未完成的持久准备卡按已中断显示,用户可显式重试;不能仅凭
@@ -82,29 +182,99 @@ Main 负责网络和 Git,UI 只消费报告;运行版本摘要在结果详
任务被归档、工作目录改变或切换账号后,不再自动发送。
- 个人项目或任务工作目录丢失时,阻止发送并提示恢复原工作目录或新建制作任务;不会进入
通用 mkdir 恢复、在空目录执行,也不会偷偷重建源码来冒充已恢复原来的文件和分支。
-- Settings 的「未完成的制作」使用可搜索的列表/详情双栏;窄容器改为上下排列,列表和
- 详情内容分别限高滚动,操作区始终可见。只展开当前选中任务的准备进度,已完成的准备步骤
- 不再占据页面。准备完成或一轮执行结束不等于整个制作已完成,仍可打开任务继续修改。
-- 「打开任务」跳转到原任务;归档但未完成的任务先通过既有恢复入口重新激活,再跳转。
- 「完成制作」要求执行已结束且没有未提交改动,将制作分支合入个人版后清理 worktree
- (包括安装的依赖)和制作分支,保留已归档任务中的交流记录,随后从未完成列表移除。
- 普通归档只回收已确认合入个人版的提交,未合入、未提交或尚无新提交的工作仍保留。
-- 「删除制作」确认后沿用既有删除流程,先停止准备与运行时再丢弃该任务的工作目录和分支。
- 清理失败不标记完成,保留「待清理/重试清理」,重启后仍可重试;已删除的任务不提供恢复入口。
+- 侧栏将制作任务收进带锤子图标的「Cindy Make」分组,展开直接显示任务标题;不再把
+ 每个制作工作目录作为单独项目行。分组只改变展示,不移动目录或改变任务归属数据;
+ 置顶仍沿用置顶区,设备分组开启时按设备各自收纳。展开侧栏与折叠侧栏面板共用该口径。
+ 制作任务标题使用工作目录名称的前四位标记,例如 `[f428] 修改背景色`,不再重复
+ `[Cindy-Make]` 前缀。新任务直接生成短标记;旧任务在显示层兼容,重命名不重复叠加。
+- Settings 的「制作历史」使用可搜索、可筛选的列表/详情双栏;窄容器改为上下排列,列表和
+ 详情分别限高滚动,操作区始终可见。按普通制作任务计数,每轮完成回报在详情中展开;
+ 官方更新与合入/撤销冲突任务不计入制作次数。历史覆盖正在制作与已结束的记录。
+ 准备完成、一轮修改完成、源码合入和生成应用分别呈现,不互相冒充。
+- 历史按当前数据 owner 持久化在源码目录之外,清理单个工作目录不会删除历史。
+ 老任务从准备卡、完成事实与实际 Git 合入提交核验回填;缺少证据时不伪造撤销依据。
+ 选中记录时核验源码、完成快照与保留的 Git 对象;Main 在操作入场再检查一次。
+ 当前正在制作只提供查看,完成后提供继续修改、隔离测试与合入;已合入不重复显示合入,
+ 有新一轮修改后再提供合入,已撤销才提供重新合入。冲突和普通失败分别提供解决、重试。
+ 已结束不再显示编辑、测试和重复清理,但有效的合入记录仍可撤销。所有按钮复用统一边框。
+- 合入、撤销与重新合入共用已有项目互斥及独立冲突任务生命周期。首次正常合入保留功能
+ 分支的真实 merge;后续增量与撤销保存实际采纳前后的文件树。撤销逆序应用该制作尚有效的
+ 全部合入差异,并创建新的提交;重新合入反向应用那次撤销的实际差异。依赖冲突留在隔离
+ 目录,原个人源码保留。官方 rebase 改写 hash 后仍通过保留的文件差异处理,不能依据旧
+ commit 的祖先关系误判已经撤销或无法撤销。Git 采纳和历史写入之间中断可显式重试,
+ 历史回执按操作 ID 去重;重启不静默重放写操作。
+- 「合入个人版」不自动打包;页面统一的「生成个人版」从当前个人源码构建,无需仍存在
+ 的制作工作目录,也不创建虚假的任务。生成时在源码锁内记录实际包含的合入/撤销操作,
+ 成功后刷新版本列表。记录区分已合入待生成与已经生成,生成时间只显示真实保存的时间;
+ 旧版缺失生成时间时仅显示已生成。生成失败保留源码,原有应用成品不变。
+ 生成入口说明只包含当前个人源码,未合入的历史改动不自动加入;检查期间分别显示安装依赖、
+ 自动测试和类型检查,加载时保留可见按钮文字,失败保留已知原因。旧记录缺少检查子阶段时
+ 回退到检查中,不改变已有状态含义。
+ 未声明托管版本启动协议的旧源码仍提供「查看安装包」,不声称可在版本列表中切换。
+ 完成卡的直接生成同样先走这条合入流程,遇到冲突先处理冲突再生成。
+ 实现与回归见 [historyRuntime](../apps/desktop/src/main/cindy-make/historyRuntime.ts)、
+ [动作准入](../apps/desktop/src/shared/cindyMakeHistory.ts) 与
+ [合入/撤销真实 Git 测试](../apps/desktop/src/main/cindy-make/__tests__/featureHistory.git-integration.test.ts)。
+- 原「完成制作/删除制作」统一为「结束制作」,不触发合并、提交或生成。无论是否已合入,
+ 都必须二次弹窗确认,说明会删除工作目录、项目依赖和制作分支,保留归档交流记录;
+ 未合入时额外提示改动会丢失,合入状态未知时明确提示无法确认。用户确认丢弃即可结束,
+ 不强制生成个人版。普通归档只停止制作并保留目录,不能代替删除确认;全局清理源码入口独立。
+ 确认后沿用既有归档与运行时停止流程,再清理该任务的目录和分支,保留已有历史引用。
+ 合入或生成成功本身不触发清理;生成后可选择「结束制作并清理」。等待冲突处理时不能
+ 清理关联的制作目录。保留的合入提交和文件树使结束后仍能撤销;如果用户另行清空整个
+ 托管源码仓库,历史继续可看,但缺失 Git 对象的动作不再提供。
+ 清理失败不标记完成,cell 保留失败状态,操作区提供原因和「重试清理」;重试也必须弹窗确认。
+ 兼容旧版已删除任务的清理重试,不恢复已删除的交流记录,也不提供恢复入口。
只操作从合法 runId 派生且由该个人项目 Git 注册的目录,拒绝符号链接/junction 替换、
- 仍在使用的目录和账号切换后的旧操作。合并冲突保留两侧修改,清理成功后才持久化完成标记。
- Windows 清理启用 Git 长路径支持;Git 移除登记后仍残留目录时,仅显式删除允许续清理,
+ 仍在使用的目录和账号切换后的旧操作。清理成功后才持久化完成标记。
+ Windows 清理启用 Git 长路径支持;Git 移除登记后仍残留目录时,仅确认丢弃的操作允许续清理,
必须同时匹配持久准备记录中的任务、路径与分支,确认原分支仍在、目录没有 `.git`,
且该路径和分支都未登记在其它 worktree。删除前重新核验托管根与链接边界;目录删除成功
才删除分支。文件占用时在操作区保留原因和重试入口,执行期间按钮显示加载状态。
- 完成/删除操作及失败原因由 Main manager 按任务和当前账号持有,通过同一全局快照推送;
+ 清理操作及失败原因由 Main manager 按任务和当前账号持有,通过同一全局快照推送;
退出设置不取消清理,重进设置或另开窗口继续显示「正在清理」,同一任务的重复请求共用
- 在途操作。失败后保留原因直到重试;应用退出中断的清理在重启后显示「待清理」,由用户
- 重试,不自动重放删除。临时的打开/确认弹窗状态才留在 Renderer。
+ 在途操作。失败后保留原因直到重试;删除前在原准备卡持久化待清理标记,应用退出中断的
+ 清理在重启后显示「待清理」,由用户再次确认后重试,不自动重放删除。临时的打开/确认弹窗
+ 状态才留在 Renderer。旧版 finish 调用仍只清理已合入的内容,不能升级为无条件丢弃。
实现见 [taskManagement](../apps/desktop/src/main/cindy-make/taskManagement.ts),
[真实 Git 回归](../apps/desktop/src/main/cindy-make/__tests__/taskCleanup.git-integration.test.ts)
- 覆盖合并、冲突保留、忽略目录与分支回收。
+ 覆盖普通归档保留、显式丢弃未采纳改动、忽略目录与分支回收。
- 此流程仍是本地 Desktop Cindy Make:拒绝 SSH 任务作为来源,不新增 device-link invoke
白名单。手机可通过已有任务/消息同步读取保存的阶段文本,但没有新增原生准备控制卡,
实时多端准备操作需单独适配。远端 Desktop 的准备卡只读,不能误调用查看端的停止/重试。
本次不改 device-link 重试、超时或连接恢复策略。
+
+## 获取官方更新与解决冲突
+
+- Settings 的单行版本比较右侧仅保留「获取最新」图标,带悬停说明与点击确认框,
+ 底部不重复放更新按钮;首次准备、失败重试与停止按钮保留。
+ 确认后重新查询当前运行渠道的最新提交,不复用展示用的缓存。
+- Main 拉取固定官方提交,保存个人历史/文件与 main 的备份,再更新 main。
+ 旧个人目录的未提交修改先转成本地提交;有未结束的 Git 操作或 main 含非目标提交时停止。
+- rebase 在托管的独立目录中进行;只重放官方基线之后的个人提交,main 不接收个人提交。
+ 无冲突自动采纳;冲突时原个人源码保持可用,自动创建一个独立任务。重复点击不重复创建。
+ 个人历史中的 merge 提交若含额外修改/冲突处理结果,普通 rebase 可能漏掉这些内容;
+ Main 通过 remerge 差异识别后,即使 rebase 没有文本冲突也先创建核对任务,保留原个人目录,
+ 待核对原功能并补回遗漏后再采纳。
+- 冲突任务使用独立 source `cindy-make-merge`,归入 Cindy Make 侧栏分组,标题使用
+ 工作目录的四位标记。它不继承普通制作任务的每轮说明、完成回报工具、隔离测试或
+ 生成个人版卡片。首条用户需求由 Main 固定组装,要求理解双方修改、保留本地功能、
+ 安全解决冲突,并按仓库规则验证。允许暂存并继续现有 rebase,不重新开始、不跳过个人
+ 提交、不修改其他目录,也不推送;结束后宿主提交必要的附加修复。
+- 正常执行结束后,Main 核验目录归属、分支身份、原有 HEAD、文件冲突状态及
+ `git diff --check`,再应用结果。自动检查不代表功能测试已通过;功能验证由解决冲突的
+ 任务执行并如实说明。个人版期间发生变化则停止应用并保留现场;中断、失败或
+ continuation 边界不应用结果。旧文件合并现场可保留 MERGE_HEAD,解决后由宿主将个人
+ 差异迁移为本地提交,既有历史保留备份。
+- 操作和任务绑定持久化到 userData;重启不静默重放 Git 写操作,重复点击复用任务。
+ 创建任务前先持久化任务 ID;账号切换后不发送旧请求、不暴露另一账号的任务入口。
+ 已删除或归档的任务由下一次显式解决冲突操作创建新任务,继续使用保留的工作目录。
+ 未完成的合并禁止清理源码;缺失的合并目录不会被普通恢复流程重建为空目录。
+- 没有任务的自动合并成功后,仅在文件树与已采纳结果一致时移除临时 worktree。冲突任务
+ 的目录继续保留,便于查看与继续交流。仅支持本机 Desktop,不增加远控调用权限。
+
+实现见 [Git 合并](../apps/desktop/src/main/cindy-make/upstreamMerge.ts)、
+[生命周期](../apps/desktop/src/main/cindy-make/upstreamMergeController.ts)、
+[独立任务](../apps/desktop/src/main/cindy-make/upstreamMergeSession.ts);
+[真实 Git 回归](../apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts)
+覆盖无冲突自动应用、冲突隔离与期间新增未提交个人改动的保护。