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(cindy-make): batch history changes into one personal build and unify build status

Lizi94de217158a2
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 3d3ca553c3..4c8c4b5764 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -7632,10 +7632,10 @@ const registerIpcHandlers = () => {
}
},
);
- ipcMain.handle('app:cindy-make-history-build', async (event) => {
+ ipcMain.handle('app:cindy-make-history-build', async (event, selection: unknown) => {
assertTrustedAppRendererEvent(event);
try {
- return await generateHistoryPersonalVersion();
+ return await generateHistoryPersonalVersion(selection);
} catch {
throwIpcError('PRECONDITION_FAILED', 'unavailable');
}
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
index 97a2bc0e59..cca2eae78b 100644
--- 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
@@ -215,6 +215,33 @@ it('undoes all rounds of one make after an official rebase without removing the
}
}, 120000);
+it('adopts a later conflicting selection against the preserved unbuilt prefix', async () => {
+ const h = await fixture();
+ try {
+ await h.task('aaaa', 'a.txt', 'first-selection\n');
+ await h.task('bbbb', 'a.txt', 'second-selection\n');
+ const first = await h.action('aaaa', 'integrate');
+ expect(first.status).toBe('merged');
+ const pending = await h.action('bbbb', 'integrate');
+ expect(pending).toMatchObject({ status: 'conflict', baselineCommit: first.commit });
+ expect(h.store.read('aaaa')?.versions).toEqual([]);
+ expect(await h.git(['rev-parse', 'HEAD'])).toBe(first.commit);
+ const worktree = mergeWorktree(h.userData, pending.id);
+ await writeFile(path.join(worktree, 'a.txt'), 'both-selections\n');
+ await h.git(['add', '.'], worktree);
+ const resolved = await applyFeatureMerge(h.userData, pending, h.git);
+ expect(resolved.status).toBe('merged');
+ h.record(resolved);
+ expect(h.store.read('aaaa')?.receipts).toHaveLength(1);
+ expect(h.store.read('bbbb')?.receipts).toHaveLength(1);
+ expect(await h.git(['merge-base', '--is-ancestor', first.commit!, 'HEAD'])).toBe('');
+ expect(await readFile(path.join(h.source, 'a.txt'), 'utf8')).toBe('both-selections\n');
+ expect(await h.git(['status', '--porcelain'])).toBe('');
+ } finally {
+ await h.clean();
+ }
+}, 90000);
+
it('isolates an undo conflict and adopts the resolved delta once without resetting later history', async () => {
const h = await fixture();
try {
diff --git a/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts b/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts
index e20b6977c3..e517af9a1a 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts
@@ -13,7 +13,7 @@ const ready = {
conflict: false,
};
describe('history action admission', () => {
- it('locks editing during launch but lets a ready test stop through Continue', () => {
+ it('locks editing during launch and permits controller-owned restart/build once ready', () => {
expect(makeHistoryActions({ ...ready, busy: true, test: { status: 'starting' } })).toEqual([
'open',
]);
@@ -23,6 +23,8 @@ describe('history action admission', () => {
expect(makeHistoryActions({ ...ready, busy: true, test: { status: 'ready' } })).toEqual([
'open',
'continue',
+ 'test',
+ 'build',
]);
expect(
makeHistoryActions({ ...ready, busy: true, test: { status: 'ready' }, completed: false }),
diff --git a/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts b/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts
index 660d77f72a..7f184c6d40 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts
@@ -11,7 +11,7 @@ const h = vi.hoisted(() => ({
cards: [] as any[],
records: new Map<string, CindyMakeHistoryRecord>(),
state: {} as any,
- verify: vi.fn(async () => {}),
+ verify: vi.fn(async (_workspace: { runId: string }) => {}),
merge: vi.fn(),
end: vi.fn(),
saved: vi.fn(),
@@ -24,6 +24,7 @@ const h = vi.hoisted(() => ({
testStatus: vi.fn(),
testUsing: false,
testAction: vi.fn(),
+ stopTest: vi.fn(),
retryMerge: vi.fn(),
}));
const store = {
@@ -92,6 +93,7 @@ vi.mock('../testRuntime.js', () => ({
!!h.testBuild && (h.testBuild.sessionId ?? 'session') === sessionId,
activeBuild: () => h.testBuild,
cancelBuild: h.cancelTestBuild,
+ stopTestForBuild: h.stopTest,
},
}));
vi.mock('../testRunner.js', () => ({ verifyMakeTestWorkspace: h.verify }));
@@ -165,6 +167,9 @@ beforeEach(() => {
h.testBuild = undefined;
h.testUsing = false;
h.testStatus.mockReset();
+ h.merge.mockReset();
+ h.build.mockReset();
+ h.stopTest.mockReset();
h.cancelTestBuild.mockReset();
vi.spyOn(cindyMakeManager, 'getState').mockImplementation(() => h.state);
h.exists = true;
@@ -275,7 +280,8 @@ describe('history Main admission and owner boundary', () => {
expect(item.test).toEqual(test);
expect(item.completions.at(-1)?.test).toEqual(test);
if (status === 'starting') expect(item.actions).toEqual(['open']);
- else if (status === 'ready') expect(item.actions).toEqual(['open', 'continue']);
+ else if (status === 'ready')
+ expect(item.actions).toEqual(['open', 'continue', 'test', 'build']);
else expect(item.actions).toContain('test');
expect(item.canHide).toBe(!h.testUsing);
},
@@ -611,3 +617,195 @@ describe('history Main admission and owner boundary', () => {
await expect(actCindyMakeHistory('../source', 'revert')).rejects.toThrow('Invalid');
});
});
+
+/** Two independent completed tasks; the newer row is intentionally listed first. */
+async function batchFixture() {
+ const original = h.rows[0];
+ h.rows = [
+ { ...original, createdAt: 20 },
+ {
+ ...original,
+ id: 'older-session',
+ createdAt: 10,
+ workingDir: path.join(path.dirname(original.workingDir), 'bbbb'),
+ },
+ ];
+ h.cards.push(...h.cards.map((card) => ({ ...card, sessionId: 'older-session' })));
+ const state = await getCindyMakeHistory();
+ const pins = state.items.map((item) => ({
+ runId: item.runId,
+ completionId: item.completionId!,
+ commit: item.completions.at(-1)!.commit!,
+ tree: item.completions.at(-1)!.tree!,
+ }));
+ let buildState: any;
+ store.saveBuild.mockImplementation((value) => {
+ buildState = value;
+ });
+ store.readBuild.mockImplementation(() => buildState);
+ h.merge.mockImplementation(async (plan) => {
+ h.records
+ .get(plan.runId)!
+ .receipts.push({ ...receipt, id: 'merge-' + plan.runId, taskTree: plan.taskTree });
+ });
+ h.build.mockResolvedValue({
+ commit: 'b'.repeat(40),
+ tree: 'd'.repeat(40),
+ includedFeatures: [
+ { runId: 'aaaa', operationId: 'merge-aaaa' },
+ { runId: 'bbbb', operationId: 'merge-bbbb' },
+ ],
+ });
+ return {
+ pins,
+ state: () => buildState,
+ settled: async () => {
+ await vi.waitFor(() => expect(realHasActiveWork()).toBe(false));
+ },
+ };
+}
+
+describe('one personal version from selected history', () => {
+ it('merges oldest first and packages once with both feature receipts', async () => {
+ const f = await batchFixture();
+ await generateHistoryPersonalVersion(f.pins);
+ await f.settled();
+ expect(h.merge.mock.calls.map(([plan]) => plan.runId)).toEqual(['bbbb', 'aaaa']);
+ expect(h.build).toHaveBeenCalledOnce();
+ expect(h.testAction).not.toHaveBeenCalled();
+ expect(f.state()).toMatchObject({
+ status: 'ready',
+ includedFeatures: [
+ { runId: 'aaaa', operationId: 'merge-aaaa' },
+ { runId: 'bbbb', operationId: 'merge-bbbb' },
+ ],
+ });
+ expect(store.version).toHaveBeenCalledTimes(2);
+ });
+ it('validates every selected workspace before merging any of them', async () => {
+ const f = await batchFixture();
+ h.verify.mockImplementation(async ({ runId }) => {
+ if (runId === 'aaaa') throw Object.assign(new Error('changed'), { code: 'changed' });
+ });
+ await generateHistoryPersonalVersion(f.pins);
+ await f.settled();
+ expect(h.merge).not.toHaveBeenCalled();
+ expect(h.build).not.toHaveBeenCalled();
+ expect(f.state()).toMatchObject({ status: 'failed' });
+ expect(['changed', 'cleanupFailed']).toContain(f.state().error);
+ });
+ it('rejects stale, duplicate and foreign selections before stopping tests or changing source', async () => {
+ const f = await batchFixture();
+ await expect(generateHistoryPersonalVersion([])).rejects.toThrow('Invalid');
+ await expect(generateHistoryPersonalVersion([f.pins[0], f.pins[0]])).rejects.toThrow(
+ 'Duplicate',
+ );
+ await expect(
+ generateHistoryPersonalVersion([{ ...f.pins[0], runId: '../other' }]),
+ ).rejects.toThrow('Invalid');
+ await expect(
+ generateHistoryPersonalVersion([{ ...f.pins[0], runId: 'foreign' }]),
+ ).rejects.toThrow('unavailable');
+ await expect(
+ generateHistoryPersonalVersion([{ ...f.pins[0], tree: 'a'.repeat(40) }]),
+ ).rejects.toThrow('unavailable');
+ expect(h.stopTest).not.toHaveBeenCalled();
+ expect(h.merge).not.toHaveBeenCalled();
+ expect(h.build).not.toHaveBeenCalled();
+ });
+ it('keeps a conflicting prefix recoverable and never packages a partial selection', async () => {
+ const f = await batchFixture();
+ h.merge.mockImplementationOnce(async () => {
+ h.state.upstreamMerge = {
+ id: 'conflict',
+ status: 'conflict',
+ hasWorkspace: true,
+ feature: { runId: 'bbbb', action: 'integrate', awaitingResolution: true },
+ };
+ });
+ await generateHistoryPersonalVersion(f.pins);
+ await f.settled();
+ expect(h.merge).toHaveBeenCalledOnce();
+ expect(h.build).not.toHaveBeenCalled();
+ expect(f.state()).toMatchObject({ status: 'failed', error: 'conflict' });
+ });
+ it('rechecks later completions and refuses a new round that arrived while merging', async () => {
+ const f = await batchFixture();
+ h.merge.mockImplementationOnce(async (plan) => {
+ h.records.get(plan.runId)!.receipts.push({ ...receipt, taskTree: plan.taskTree });
+ h.cards.push({ ...h.cards[1], id: 10, createdAt: 100, clientId: 'new-edit' });
+ });
+ await generateHistoryPersonalVersion(f.pins);
+ await f.settled();
+ expect(h.merge).toHaveBeenCalledOnce();
+ expect(h.build).not.toHaveBeenCalled();
+ expect(f.state()).toMatchObject({ status: 'failed' });
+ expect(['changed', 'cleanupFailed']).toContain(f.state().error);
+ });
+ it.each(['conflict', 'resolving', 'failed'])(
+ 'preserves the merged prefix while the next candidate is %s',
+ async (status) => {
+ const f = await batchFixture();
+ const project = vi.spyOn(cindyMakeManager, 'withProject');
+ h.merge.mockImplementation(async (plan) => {
+ if (plan.runId === 'bbbb') {
+ h.records.get(plan.runId)!.receipts.push({ ...receipt, taskTree: plan.taskTree });
+ } else {
+ h.state.upstreamMerge = {
+ id: 'conflict',
+ status,
+ hasWorkspace: true,
+ baselineCommit: receipt.commit,
+ feature: { runId: 'aaaa', action: 'integrate', awaitingResolution: true },
+ };
+ }
+ });
+ await generateHistoryPersonalVersion(f.pins);
+ await f.settled();
+ expect(h.merge.mock.calls.map(([plan]) => plan.runId)).toEqual(['bbbb', 'aaaa']);
+ expect(h.build).not.toHaveBeenCalled();
+ expect(project).not.toHaveBeenCalled();
+ expect(h.records.get('bbbb')!.receipts).toEqual([receipt]);
+ expect(f.state()).toMatchObject({ status: 'failed', error: 'conflict' });
+ expect(h.state.upstreamMerge.baselineCommit).toBe(receipt.commit);
+ },
+ );
+ it('exposes merge progress, blocks another build and cancels before the next merge', async () => {
+ const f = await batchFixture();
+ let finish!: () => void;
+ h.merge.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await generateHistoryPersonalVersion(f.pins);
+ await vi.waitFor(() => expect(h.merge).toHaveBeenCalledOnce());
+ expect((await getCindyMakeHistory()).batch).toMatchObject({
+ current: 1,
+ total: 2,
+ runId: 'bbbb',
+ });
+ await expect(generateHistoryPersonalVersion()).rejects.toThrow('busy');
+ await cancelHistoryPersonalVersion(f.state().buildId);
+ finish();
+ await f.settled();
+ expect(h.merge).toHaveBeenCalledOnce();
+ expect(h.build).not.toHaveBeenCalled();
+ expect(f.state()).toMatchObject({ status: 'failed', error: 'cancelled' });
+ });
+ it('stops the ready test before restarting the same completed round', async () => {
+ const meta = JSON.parse(h.cards[0].agentMeta).cindyMakeCompletion;
+ h.cards[0].agentMeta = JSON.stringify({
+ cindyMakeCompletion: { ...meta, test: { status: 'ready' } },
+ });
+ h.testStatus.mockResolvedValue({ ...meta, test: { status: 'ready' } });
+ h.testUsing = true;
+ await actCindyMakeHistory('aaaa', 'test');
+ expect(h.stopTest).toHaveBeenCalledWith('session');
+ expect(h.testAction).toHaveBeenCalledWith('session', 'complete', 'start');
+ expect(h.stopTest.mock.invocationCallOrder[0]).toBeLessThan(
+ h.testAction.mock.invocationCallOrder[0],
+ );
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/historyRuntime.ts b/apps/desktop/src/main/cindy-make/historyRuntime.ts
index a6aef72ec4..b19c8fb377 100644
--- a/apps/desktop/src/main/cindy-make/historyRuntime.ts
+++ b/apps/desktop/src/main/cindy-make/historyRuntime.ts
@@ -53,6 +53,7 @@ import {
type MakeHistoryAction,
type MakeHistoryLifecycle,
type MakeHistoryIntegration,
+ type MakeHistoryBuildSelection,
} from '../../shared/cindyMakeHistory.js';
import type { CindyMakePersonalBuildState } from '../../shared/cindyMakeSession.js';
import {
@@ -64,15 +65,16 @@ 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;
+/** Owns a source build, including its ordered history merges, independently of Settings. */
+interface HistoryBuildJob {
+ id: string;
+ current: () => boolean;
+ abort: AbortController;
+ cancelled: boolean;
+ done: Promise<void>;
+ batch?: CindyMakeHistoryState['batch'];
+}
+let buildJob: HistoryBuildJob | undefined;
type MakeHistoryCard = Pick<
typeof messages.$inferSelect,
'id' | 'sessionId' | 'clientId' | 'role' | 'content' | 'agentMeta' | 'createdAt'
@@ -186,6 +188,14 @@ async function toolEnvironment(userData: string, signal: AbortSignal, build = fa
/** Hydrate old installations once from their own task facts; ended tasks are deliberately included. */
export async function getCindyMakeHistory(selectedRunId?: string): Promise<CindyMakeHistoryState> {
+ return readCindyMakeHistory(selectedRunId);
+}
+
+/** Only the current build may verify candidates while holding its own build reservation. */
+async function readCindyMakeHistory(
+ selectedRunId?: string,
+ ownBuild?: HistoryBuildJob,
+): Promise<CindyMakeHistoryState> {
const h = context();
const rows = (
await h.client.drizzle.select().from(sessions).where(eq(sessions.source, 'cindy-make'))
@@ -302,8 +312,10 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<Cindy
(state.upstreamMerge.hasWorkspace || state.upstreamMerge.cancellationRequested)
? state.upstreamMerge
: undefined;
+ const ownsBuild = !!ownBuild && buildJob === ownBuild && ownBuild.current();
const globalBusy =
- !!buildJob || cindyMakeTestController.hasActiveJobs() || cindyMakeManager.hasActiveWork();
+ cindyMakeTestController.hasActiveJobs() ||
+ (!ownsBuild && (!!buildJob || cindyMakeManager.hasActiveWork()));
const items: CindyMakeHistoryItem[] = [];
for (const record of h.store.list()) {
if (record.hiddenAt !== undefined) continue;
@@ -599,6 +611,15 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<Cindy
? 'sourceUnavailable'
: 'ended'
: undefined,
+ canSelectForBuild:
+ completed &&
+ lifecycle === 'ready' &&
+ workspaceAvailable &&
+ verifiedSource &&
+ !operation &&
+ !taskBuilding &&
+ test?.status !== 'starting' &&
+ ['unintegrated', 'changed', 'reverted'].includes(integration),
canHide: !targetBusy && !['starting', 'ready'].includes(test?.status ?? ''),
});
}
@@ -609,6 +630,7 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<Cindy
busy: globalBusy || !!pendingMerge,
canBuild: buildSourceAvailable && !globalBusy && !pendingMerge,
build,
+ batch: buildJob?.current() ? buildJob.batch : undefined,
};
}
@@ -683,13 +705,17 @@ export async function actCindyMakeHistory(
h.store.hide(runId);
} else if (action === 'end' || action === 'retry-cleanup')
await manageCindyMakeTask(item.sessionId, 'end');
- else if (action === 'test' || action === 'continue')
+ else if (action === 'test' || action === 'continue') {
+ if (action === 'test' && item.test?.status === 'ready') {
+ await cindyMakeTestController.stopTestForBuild(item.sessionId);
+ h.check();
+ }
await actCindyMakeTest(
item.sessionId,
item.completionId,
action === 'test' ? 'start' : 'continue',
);
- else if (action === 'resolve' || action === 'retry') {
+ } else if (action === 'resolve' || action === 'retry') {
await actUpstreamMerge({ action: 'resolve' });
if (action === 'retry') {
h.check();
@@ -699,85 +725,175 @@ export async function actCindyMakeHistory(
return next;
}
} 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,
- );
- });
+ await integrateHistoryItem(h, item, action);
} else throwIpcError('INVALID_PARAMS', 'This action is handled by task navigation');
h.check();
return getCindyMakeHistory(runId);
}
+/** Shared by single-item actions and batches; retains route and source locks. */
+async function integrateHistoryItem(
+ h: ReturnType<typeof context>,
+ item: CindyMakeHistoryItem,
+ action: 'integrate' | 'revert' | 'reapply',
+ ownBuild?: HistoryBuildJob,
+): Promise<void> {
+ const runId = item.runId;
+ await withSessionRouteLock(item.sessionId, async () => {
+ h.check();
+ if (ownBuild) {
+ ownBuild.abort.signal.throwIfAborted();
+ if (buildJob !== ownBuild) throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ const fresh = (await readCindyMakeHistory(item.runId, ownBuild)).items.find(
+ (entry) => entry.runId === item.runId,
+ );
+ if (
+ !fresh ||
+ !fresh.actions.includes(action) ||
+ fresh.completionId !== item.completionId ||
+ fresh.completions.at(-1)?.commit !== item.completions.at(-1)?.commit ||
+ fresh.completions.at(-1)?.tree !== item.completions.at(-1)?.tree
+ )
+ throw personalBuildError('changed');
+ }
+ if (running(item.sessionId) || cindyMakeManager.isTaskPreparing(item.sessionId))
+ throwIpcError('PRECONDITION_FAILED', 'busy');
+ if (
+ cindyMakeTestController.hasActiveJobs() ||
+ (!ownBuild && (buildJob || 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,
+ );
+ });
+}
+
/** A source build has no synthetic task. It packages the current personal branch under the existing project lock. */
-export async function generateHistoryPersonalVersion(): Promise<CindyMakeHistoryState> {
+export async function generateHistoryPersonalVersion(
+ rawSelection?: unknown,
+): Promise<CindyMakeHistoryState> {
+ let selection: MakeHistoryBuildSelection[] | undefined;
+ if (rawSelection !== undefined) {
+ if (!Array.isArray(rawSelection) || !rawSelection.length || rawSelection.length > 500)
+ throwIpcError('INVALID_PARAMS', 'Invalid build selection');
+ selection = rawSelection.map((entry: unknown) => {
+ if (!entry || typeof entry !== 'object')
+ throwIpcError('INVALID_PARAMS', 'Invalid build selection');
+ const value = entry as Record<string, unknown>;
+ if (
+ typeof value.runId !== 'string' ||
+ !ID.test(value.runId) ||
+ typeof value.completionId !== 'string' ||
+ !ID.test(value.completionId) ||
+ typeof value.commit !== 'string' ||
+ !HASH.test(value.commit) ||
+ typeof value.tree !== 'string' ||
+ !HASH.test(value.tree)
+ )
+ throwIpcError('INVALID_PARAMS', 'Invalid build selection');
+ return {
+ runId: value.runId,
+ completionId: value.completionId,
+ commit: value.commit,
+ tree: value.tree,
+ };
+ });
+ if (new Set(selection.map((entry) => entry.runId)).size !== selection.length)
+ throwIpcError('INVALID_PARAMS', 'Duplicate build selection');
+ }
const h = context();
- const state = await getCindyMakeHistory();
+ let state = await getCindyMakeHistory();
+ h.check();
+ const matches = (item: CindyMakeHistoryItem | undefined, pin: MakeHistoryBuildSelection) =>
+ item?.canSelectForBuild &&
+ item.completionId === pin.completionId &&
+ item.completions.at(-1)?.commit === pin.commit &&
+ item.completions.at(-1)?.tree === pin.tree;
+ if (selection) {
+ // Validate every identity before stopping any selected test. Never substitute a newer round.
+ if (
+ selection.some(
+ (pin) =>
+ !matches(
+ state.items.find((item) => item.runId === pin.runId),
+ pin,
+ ),
+ )
+ )
+ throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ selection.sort((a, b) => {
+ const left = state.items.find((item) => item.runId === a.runId)!;
+ const right = state.items.find((item) => item.runId === b.runId)!;
+ return left.createdAt - right.createdAt || left.runId.localeCompare(right.runId);
+ });
+ for (const pin of selection) {
+ const item = state.items.find((entry) => entry.runId === pin.runId)!;
+ await cindyMakeTestController.stopTestForBuild(item.sessionId);
+ h.check();
+ }
+ state = await getCindyMakeHistory();
+ }
h.check();
if (
!state.canBuild ||
@@ -798,7 +914,13 @@ export async function generateHistoryPersonalVersion(): Promise<CindyMakeHistory
appendCindyMakeBuildLog(h.store.readBuild(), { ...build, buildId, startedAt }),
);
};
- const job = { id: buildId, current: h.current, abort, cancelled: false, done: Promise.resolve() };
+ const job: HistoryBuildJob = {
+ id: buildId,
+ current: h.current,
+ abort,
+ cancelled: false,
+ done: Promise.resolve(),
+ };
buildJob = job;
try {
await publish({ status: 'waiting' });
@@ -813,7 +935,54 @@ export async function generateHistoryPersonalVersion(): Promise<CindyMakeHistory
if (!h.current()) abort.abort();
}, 1000);
let enteredBuilder = false;
+ let canRollback = !selection;
try {
+ if (selection) {
+ if (h.store.readBuildRollback().length) await recoverHistoryBuildRollback();
+ const candidates: CindyMakeHistoryItem[] = [];
+ for (const pin of selection) {
+ abort.signal.throwIfAborted();
+ const fresh = await readCindyMakeHistory(pin.runId, job);
+ h.check();
+ const item = fresh.items.find((entry) => entry.runId === pin.runId);
+ if (
+ !matches(item, pin) ||
+ !(item!.actions.includes('integrate') || item!.actions.includes('reapply'))
+ )
+ throw personalBuildError('changed');
+ candidates.push(item!);
+ }
+ // All candidates are checked before the first merge; each is rechecked under its route lock.
+ for (const [index, item] of candidates.entries()) {
+ abort.signal.throwIfAborted();
+ job.batch = {
+ current: index + 1,
+ total: candidates.length,
+ runId: item.runId,
+ title: item.title,
+ };
+ await publish({ status: 'merging' });
+ await integrateHistoryItem(
+ h,
+ item,
+ item.actions.includes('reapply') ? 'reapply' : 'integrate',
+ job,
+ );
+ canRollback = true;
+ h.check();
+ abort.signal.throwIfAborted();
+ const next = await readCindyMakeHistory(item.runId, job);
+ if (
+ next.items.find((entry) => entry.runId === item.runId)?.integration !==
+ 'integrated' ||
+ next.items.some(
+ (entry) => entry.runId === item.runId && (entry.conflict || entry.operationError),
+ )
+ )
+ throw personalBuildError('conflict');
+ }
+ job.batch = undefined;
+ }
await publish({ status: 'waiting', preparationStep: 'environment' });
const { tools, env } = await toolEnvironment(h.userData, abort.signal, true);
const node = await tools.probe('node', ['--version'], abort.signal);
@@ -839,10 +1008,8 @@ export async function generateHistoryPersonalVersion(): Promise<CindyMakeHistory
h.check,
(run) => cindyMakeManager.withProject(makeSourceRoot(h.userData), run),
{
- ...historyBuildRollback(
- h.store,
- makeSourceCheckoutPath(h.userData),
- (commit) => hasPublishedPersonalVersionCommit(h.userData, commit),
+ ...historyBuildRollback(h.store, makeSourceCheckoutPath(h.userData), (commit) =>
+ hasPublishedPersonalVersionCommit(h.userData, commit),
),
features: () =>
h.store.list().flatMap((record) => {
@@ -855,11 +1022,19 @@ export async function generateHistoryPersonalVersion(): Promise<CindyMakeHistory
recordHistoryBuild(h.store, artifact);
await publish({ status: 'ready', ...artifact, generatedAt: Date.now() });
} catch (error) {
- if (!enteredBuilder && h.current()) {
- try {
- await recoverHistoryBuildRollback(true);
- } catch (cleanupError) {
- error = cleanupError;
+ // A cancelled/failed batch follows the same unbuilt-prefix recovery as a single build.
+ // Admission failures before the first merge must not undo unrelated earlier work.
+ if (!enteredBuilder && canRollback && h.current()) {
+ const merge = cindyMakeManager.getState().upstreamMerge;
+ // A live conflict candidate is based on the already merged prefix. Keep that baseline
+ // until its resolution is adopted; rolling it back would invalidate the recovery task.
+ const awaitingMerge = selection && merge?.hasWorkspace && merge.status !== 'merged';
+ if (!awaitingMerge) {
+ try {
+ await recoverHistoryBuildRollback(true);
+ } catch (cleanupError) {
+ error = cleanupError;
+ }
}
}
if (h.current())
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 7cddae746a..918afbc2f2 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -3875,9 +3875,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
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'),
+ generateCindyMakePersonal: (
+ selection?: import('../shared/cindyMakeHistory').MakeHistoryBuildSelection[],
+ ): Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState> =>
+ ipcRenderer.invoke('app:cindy-make-history-build', selection),
cancelCindyMakePersonal: (
buildId: string,
): Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState> =>
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildFailure.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildFailure.tsx
new file mode 100644
index 0000000000..65cdee2282
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildFailure.tsx
@@ -0,0 +1,33 @@
+import { useTranslation } from 'react-i18next';
+import type { CindyMakePersonalBuildState } from '../../../shared/cindyMakeSession';
+
+/** Failure stays outside the collapsed log on every build surface, including legacy receipts. */
+export function CindyMakeBuildFailure({
+ build,
+ error,
+}: {
+ build?: CindyMakePersonalBuildState;
+ error?: string;
+}) {
+ const { t } = useTranslation();
+ if (build?.status !== 'failed' && !error) return null;
+ const code = error ?? build?.error ?? 'unavailable';
+ const lastStep =
+ build?.status === 'failed' && code !== 'cancelled'
+ ? build.logs?.findLast((entry) => entry.step !== 'failed' && entry.step !== 'cancelled')?.step
+ : undefined;
+ const step = lastStep === 'ready' ? undefined : lastStep;
+ const reason = 'cindyMake.personal.errors.' + code;
+ return (
+ <div role="alert" className="space-y-1 text-12 text-[var(--status-danger)]">
+ {step && (
+ <p>
+ {t('cindyMake.personal.failedStep', {
+ step: t('cindyMake.personal.buildLog.steps.' + step),
+ })}
+ </p>
+ )}
+ <p>{t(reason)}</p>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildLog.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildLog.tsx
index b24e3b9c1c..93025121a3 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildLog.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildLog.tsx
@@ -1,29 +1,19 @@
-import { useEffect, useState } from 'react';
+import { ChevronRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { CindyMakePersonalBuildState } from '../../../shared/cindyMakeSession';
/** A compact, localizable timeline of build stages; it deliberately omits raw process output. */
-export function CindyMakeBuildLog({
- build,
- openWhileActive = false,
-}: {
- build?: CindyMakePersonalBuildState;
- openWhileActive?: boolean;
-}) {
+export function CindyMakeBuildLog({ build }: { build?: CindyMakePersonalBuildState }) {
const { t, i18n } = useTranslation();
const entries = build?.logs ?? [];
- const [open, setOpen] = useState(openWhileActive);
- useEffect(() => {
- if (openWhileActive) setOpen(true);
- }, [openWhileActive]);
if (!entries.length) return null;
return (
<details
- open={open}
- onToggle={(event) => setOpen(event.currentTarget.open)}
- className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-card)] px-3 py-2"
+ key={build?.buildId ?? build?.startedAt}
+ className="group rounded-xl border border-[var(--border-default)] bg-[var(--surface-card)] px-3 py-2"
>
- <summary className="flex min-h-8 cursor-pointer select-none items-center text-12 font-medium text-[var(--text-secondary)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]">
+ <summary className="flex min-h-8 cursor-pointer select-none items-center gap-1.5 text-12 font-medium text-[var(--text-secondary)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]">
+ <ChevronRight size={14} aria-hidden className="shrink-0 group-open:rotate-90" />
{t('cindyMake.personal.buildLog.title')} · {entries.length}
</summary>
<ol className="mt-2 max-h-40 space-y-1 overflow-y-auto border-t border-[var(--border-default)] pt-2 text-12">
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildProgress.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildProgress.tsx
new file mode 100644
index 0000000000..e21acf2658
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeBuildProgress.tsx
@@ -0,0 +1,35 @@
+import { useTranslation } from 'react-i18next';
+import { cn } from '@/lib/utils';
+import type { CindyMakePersonalBuildState } from '../../../shared/cindyMakeSession';
+
+const BUILD_STEPS = ['waiting', 'merging', 'checking', 'packaging', 'publishing'] as const;
+
+/** Shared build-stage presentation for the session card and Make history. */
+export function CindyMakeBuildProgress({ build }: { build?: CindyMakePersonalBuildState }) {
+ const { t } = useTranslation();
+ if (!build || build.status === 'ready' || build.status === 'failed') return null;
+
+ const current = BUILD_STEPS.indexOf(build.status);
+ return (
+ <ol className="grid gap-1 text-12 text-[var(--text-secondary)] sm:grid-cols-2">
+ {BUILD_STEPS.map((step, index) => {
+ const active = current === index;
+ const done = current > index;
+ return (
+ <li
+ key={step}
+ aria-current={active ? 'step' : undefined}
+ 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>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx
index eda1ea226d..5d5ffbb6d6 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx
@@ -16,10 +16,17 @@ import { formatCindyMakeTitle } from '@/lib/cindyMakeTitle';
import { toast } from '@/lib/toast';
import { extractIpcError } from '@/utils/ipcError';
import { cn } from '@/lib/utils';
-import type { CindyMakeHistoryState, MakeHistoryAction } from '../../../shared/cindyMakeHistory';
+import type {
+ CindyMakeHistoryState,
+ MakeHistoryAction,
+ MakeHistoryBuildSelection,
+} from '../../../shared/cindyMakeHistory';
import './cindyMakeTasks.css';
import { CindyMakeTestStep } from './CindyMakeTestStep';
import { CindyMakeBuildLog } from './CindyMakeBuildLog';
+import { CindyMakeBuildProgress } from './CindyMakeBuildProgress';
+import { CindyMakeBuildFailure } from './CindyMakeBuildFailure';
+import { cindyMakeBuildStatusKey } from './cindyMakeBuildStatus';
type Filter = 'all' | 'pending' | 'integrated' | 'ended';
/** Historical facts and allowed actions come from Main; an old button cannot authorize a write. */
@@ -43,6 +50,8 @@ export function CindyMakeHistoryPanel({
const [selectedId, select] = useState('');
const [query, search] = useState('');
const [filter, setFilter] = useState<Filter>('all');
+ const [selecting, setSelecting] = useState(false);
+ const [checkedIds, setCheckedIds] = useState<string[]>([]);
const [pending, setPending] = useState<string>();
const [failed, setFailed] = useState(false);
const request = useRef(0);
@@ -68,6 +77,8 @@ export function CindyMakeHistoryPanel({
useEffect(() => {
setSnapshot(undefined);
setPending(undefined);
+ setSelecting(false);
+ setCheckedIds([]);
acting.current = false;
actionGeneration.current += 1;
return () => {
@@ -124,6 +135,12 @@ export function CindyMakeHistoryPanel({
item.lifecycle !== 'ended'),
);
const selected = visible.find((item) => item.runId === selectedId) ?? visible[0];
+ const selectable = visible.filter((item) => item.canSelectForBuild);
+ const checked = items
+ .filter((item) => item.canSelectForBuild && checkedIds.includes(item.runId))
+ .sort((a, b) => a.createdAt - b.createdAt || a.runId.localeCompare(b.runId));
+ const allChecked =
+ selectable.length > 0 && selectable.every((item) => checkedIds.includes(item.runId));
const currentBuild = (item: CindyMakeHistoryState['items'][number]) =>
item.operation === 'build' ||
(!item.operation && ['ready', 'ended'].includes(item.lifecycle) && !item.test)
@@ -134,14 +151,7 @@ export function CindyMakeHistoryPanel({
if (item.operationError) return 'cindyMake.history.actionFailed';
if (item.operation && item.operation !== 'build') return 'cindyMake.history.working';
const build = currentBuild(item);
- if (build)
- return build.stopping
- ? 'cindyMake.history.stopping'
- : build.status === 'waiting' && build.preparationStep
- ? 'cindyMake.personal.preparationStep.' + build.preparationStep
- : build.status === 'checking' && build.checkStep
- ? 'cindyMake.personal.checkStep.' + build.checkStep
- : 'cindyMake.history.buildStatus.' + build.status;
+ if (build) return cindyMakeBuildStatusKey(build);
return item.test
? 'cindyMake.test.status.' + item.test.status
: 'cindyMake.history.lifecycle.' + item.lifecycle;
@@ -150,11 +160,13 @@ export function CindyMakeHistoryPanel({
const selectedError =
selected?.conflict || selected?.operationError
? undefined
- : selectedBuild?.status === 'failed' && selectedBuild.error
- ? 'cindyMake.personal.errors.' + selectedBuild.error
- : selected?.test?.error
- ? 'cindyMake.test.errors.' + selected.test.error
- : undefined;
+ : !selectedBuild && selected?.test?.error
+ ? 'cindyMake.test.errors.' + selected.test.error
+ : undefined;
+ const selectedIsGlobalFailure =
+ state?.build?.status === 'failed' &&
+ !!state.build.buildId &&
+ selectedBuild?.buildId === state.build.buildId;
const selectedActions: MakeHistoryAction[] = selected
? (
[
@@ -326,19 +338,62 @@ export function CindyMakeHistoryPanel({
}
};
const building = !!state?.build && !['ready', 'failed'].includes(state.build.status);
+ const buildSelected = async () => {
+ if (acting.current || !checked.length || !isDataOwnerGenerationCurrent(owner)) return;
+ const pins: MakeHistoryBuildSelection[] = checked.map((item) => ({
+ runId: item.runId,
+ completionId: item.completionId!,
+ commit: item.completions.at(-1)!.commit!,
+ tree: item.completions.at(-1)!.tree!,
+ }));
+ acting.current = true;
+ request.current += 1;
+ const actionId = ++actionGeneration.current;
+ setPending('batch-build');
+ try {
+ const accepted = await confirm({
+ title: t('cindyMake.history.batch.confirmTitle', { count: checked.length }),
+ description: t('cindyMake.history.batch.confirmDescription'),
+ content: (
+ <ol className="list-decimal space-y-2 pl-5 text-[var(--confirm-desc)]">
+ {checked.map((item) => (
+ <li key={item.runId} className="break-words">
+ {formatCindyMakeTitle(item.title, item.runId)}
+ <span className="block text-12 text-[var(--text-secondary)]">
+ {date(item.createdAt)}
+ </span>
+ </li>
+ ))}
+ </ol>
+ ),
+ describeContent: true,
+ confirmText: t('cindyMake.history.batch.start'),
+ cancelText: t('settings.cindyMake.create.cancel'),
+ });
+ if (!accepted || !isDataOwnerGenerationCurrent(owner)) return;
+ const next = await window.electronAPI.generateCindyMakePersonal(pins);
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ update(next);
+ setSelecting(false);
+ setCheckedIds([]);
+ } 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 showGlobalResult =
state?.build &&
!building &&
- !items.some((item) => state.build?.buildId && item.build?.buildId === state.build.buildId);
+ (state.build.status === 'failed' ||
+ !items.some((item) => state.build?.buildId && item.build?.buildId === state.build.buildId));
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;
@@ -402,7 +457,12 @@ export function CindyMakeHistoryPanel({
value,
label: t('cindyMake.history.filters.' + value),
}))}
- onValueChange={(value) => setFilter(value as Filter)}
+ onValueChange={(value) => {
+ setFilter(value as Filter);
+ setSelecting(false);
+ setCheckedIds([]);
+ }}
+ disabled={!!pending}
className="h-8 w-[168px]"
/>
<Input
@@ -413,7 +473,68 @@ export function CindyMakeHistoryPanel({
placeholder={t('settings.cindyMake.tasks.search')}
className="cindy-make-tasks-search"
/>
+ {filter === 'pending' && !selecting && (
+ <Button
+ variant="primary"
+ className="ml-auto"
+ disabled={!!pending || failed || !selectable.length}
+ onClick={() => {
+ setSelecting(true);
+ setCheckedIds([]);
+ }}
+ >
+ {t('cindyMake.history.batch.make')}
+ </Button>
+ )}
+ {selecting && (
+ <div className="ml-auto flex flex-wrap items-center gap-2">
+ <Button
+ variant="secondary"
+ disabled={!!pending}
+ onClick={() => {
+ setSelecting(false);
+ setCheckedIds([]);
+ }}
+ >
+ {t('settings.cindyMake.create.cancel')}
+ </Button>
+ <Button
+ variant="primary"
+ disabled={!!pending || failed || !checked.length}
+ loading={pending === 'batch-build'}
+ onClick={() => void buildSelected()}
+ >
+ {t('cindyMake.history.batch.selected', { count: checked.length })}
+ </Button>
+ </div>
+ )}
</div>
+ {selecting && (
+ <div className="flex flex-wrap items-center gap-3 text-12 text-[var(--text-secondary)]">
+ <label className="flex min-h-8 cursor-pointer items-center gap-2">
+ <input
+ type="checkbox"
+ checked={allChecked}
+ disabled={!!pending || !selectable.length}
+ ref={(node) => {
+ if (node)
+ node.indeterminate =
+ !allChecked && selectable.some((item) => checkedIds.includes(item.runId));
+ }}
+ className="size-4 accent-[var(--confirm-btn-primary-bg)]"
+ onChange={() =>
+ setCheckedIds((previous) =>
+ allChecked
+ ? previous.filter((id) => !selectable.some((item) => item.runId === id))
+ : [...new Set([...previous, ...selectable.map((item) => item.runId)])],
+ )
+ }
+ />
+ {t('cindyMake.history.batch.selectAll')}
+ </label>
+ <span>{t('cindyMake.history.batch.hint')}</span>
+ </div>
+ )}
</>
)}
{building && state?.build && (
@@ -426,18 +547,14 @@ export function CindyMakeHistoryPanel({
<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'
- : state.build.status === 'waiting' && state.build.preparationStep
- ? 'cindyMake.personal.preparationStep.' + state.build.preparationStep
- : 'cindyMake.history.buildStatus.' + state.build.status,
- )}
- </p>
- {state.build.status === 'checking' && state.build.checkStep && (
+ <p className="font-medium">{t(cindyMakeBuildStatusKey(state.build, stopping))}</p>
+ {state.batch && (
<p className="text-12 text-[var(--text-secondary)]">
- {t('cindyMake.personal.checkStep.' + state.build.checkStep)}
+ {t('cindyMake.history.batch.progress', {
+ current: state.batch.current,
+ total: state.batch.total,
+ title: formatCindyMakeTitle(state.batch.title, state.batch.runId),
+ })}
</p>
)}
</div>
@@ -451,51 +568,22 @@ export function CindyMakeHistoryPanel({
{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>
- <CindyMakeBuildLog build={state.build} openWhileActive />
+ <CindyMakeBuildProgress build={state.build} />
+ <CindyMakeBuildLog build={state.build} />
</div>
)}
- {showGlobalResult && state?.build && (
- <p
- role={state.build.status === 'failed' ? 'alert' : 'status'}
- className={cn(
- 'text-12',
- state.build.status === 'failed'
- ? 'text-[var(--status-danger)]'
- : 'text-[var(--text-secondary)]',
- )}
- >
+ {showGlobalResult && state?.build?.status === 'failed' && (
+ <div className="space-y-3">
+ <CindyMakeBuildFailure build={state.build} />
+ <CindyMakeBuildLog build={state.build} />
+ </div>
+ )}
+ {showGlobalResult && state?.build?.status === 'ready' && (
+ <p role="status" className="text-12 text-[var(--text-secondary)]">
{t(
- state.build.status === 'failed' && state.build.error
- ? 'cindyMake.personal.errors.' + state.build.error
- : 'cindyMake.history.buildStatus.' +
- (state.build.status === 'ready' && !state.build.versionId
- ? 'installerReady'
- : state.build.status),
+ !state.build.versionId
+ ? 'cindyMake.history.buildStatus.installerReady'
+ : cindyMakeBuildStatusKey(state.build),
)}
</p>
)}
@@ -532,7 +620,27 @@ export function CindyMakeHistoryPanel({
className="cindy-make-history-list min-h-0 space-y-1 overflow-y-auto overscroll-contain border-b border-[var(--border-default)] p-2"
>
{visible.map((item) => (
- <li key={item.runId}>
+ <li key={item.runId} className="flex items-center gap-1">
+ {selecting && (
+ <label className="flex min-h-8 min-w-8 shrink-0 cursor-pointer items-center justify-center">
+ <input
+ type="checkbox"
+ checked={checked.some((entry) => entry.runId === item.runId)}
+ disabled={!!pending || !item.canSelectForBuild}
+ aria-label={t('cindyMake.history.batch.selectItem', {
+ title: formatCindyMakeTitle(item.title, item.runId),
+ })}
+ className="size-4 accent-[var(--confirm-btn-primary-bg)]"
+ onChange={(event) =>
+ setCheckedIds((previous) =>
+ event.target.checked
+ ? [...new Set([...previous, item.runId])]
+ : previous.filter((id) => id !== item.runId),
+ )
+ }
+ />
+ </label>
+ )}
<button
type="button"
aria-pressed={selected?.runId === item.runId}
@@ -589,7 +697,12 @@ export function CindyMakeHistoryPanel({
)}
</p>
<CindyMakeTestStep test={selected.test} />
- <CindyMakeBuildLog build={selectedBuild} />
+ {!selectedIsGlobalFailure && (
+ <>
+ <CindyMakeBuildFailure build={selectedBuild} />
+ <CindyMakeBuildLog build={selectedBuild} />
+ </>
+ )}
{!selected.completions.length &&
formatCindyMakeTitle(selected.request.trim(), selected.runId) !==
formatCindyMakeTitle(selected.title.trim(), selected.runId) && (
@@ -638,7 +751,9 @@ export function CindyMakeHistoryPanel({
: action === 'retry'
? 'cindyMake.history.actions.build'
: action === 'test'
- ? 'cindyMake.test.start'
+ ? selected.test?.status === 'ready'
+ ? 'cindyMake.history.batch.restartTest'
+ : 'cindyMake.test.start'
: 'cindyMake.history.actions.' + action,
)}
</Button>
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeTestCard.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeTestCard.tsx
index 695346b717..dbfc13f978 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeTestCard.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeTestCard.tsx
@@ -17,6 +17,9 @@ import type {
} from '../../../shared/cindyMakeSession';
import { CindyMakeCompleteCard } from './CindyMakeCompleteCard';
import { CindyMakeBuildLog } from './CindyMakeBuildLog';
+import { CindyMakeBuildProgress } from './CindyMakeBuildProgress';
+import { CindyMakeBuildFailure } from './CindyMakeBuildFailure';
+import { cindyMakeBuildStatusKey } from './cindyMakeBuildStatus';
import { CindyMakeTestStep } from './CindyMakeTestStep';
type CompletedTestProps = {
@@ -244,7 +247,9 @@ function CindyMakeCompletedTest({ sessionId, completionId, meta, onContinue }: C
}
};
const testStatus = pending === 'start' ? 'starting' : (meta.test?.status ?? 'waiting');
- const buildStatus = pending === 'build' ? 'waiting' : personal?.status;
+ const displayBuild: CindyMakePersonalBuildState | undefined =
+ pending === 'build' ? { status: 'waiting' } : personal;
+ const buildStatus = displayBuild?.status;
const building = ['waiting', 'checking', 'merging', 'packaging', 'publishing'].includes(
buildStatus ?? '',
);
@@ -255,7 +260,7 @@ function CindyMakeCompletedTest({ sessionId, completionId, meta, onContinue }: C
pending === 'build' ||
pending === 'open-build' ||
(error?.mode ?? meta.lastAction ?? (meta.personal ? 'build' : 'test')) === 'build');
- const stopping = building && (stoppingBuild || personal?.stopping === true);
+ const stopping = building && (stoppingBuild || displayBuild?.stopping === true);
const stopBuild = async () => {
if (!personal?.buildId || stopping || !current()) return;
setStoppingBuild(true);
@@ -283,16 +288,10 @@ function CindyMakeCompletedTest({ sessionId, completionId, meta, onContinue }: C
composer
data={{ ...meta }}
busy={working}
- failed={Boolean(errorCode)}
+ failed={Boolean(errorCode) || (buildMode && buildStatus === 'failed')}
heading={t(
- buildMode && buildStatus
- ? stopping
- ? 'cindyMake.history.stopping'
- : buildStatus === 'waiting' && personal?.preparationStep
- ? 'cindyMake.personal.preparationStep.' + personal.preparationStep
- : buildStatus === 'checking' && personal?.checkStep
- ? 'cindyMake.personal.checkStep.' + personal.checkStep
- : 'cindyMake.personal.status.' + buildStatus
+ buildMode && displayBuild
+ ? cindyMakeBuildStatusKey(displayBuild, stopping)
: 'cindyMake.test.status.' + testStatus,
)}
description={t(
@@ -311,7 +310,11 @@ function CindyMakeCompletedTest({ sessionId, completionId, meta, onContinue }: C
)}
detail={
buildMode ? (
- <CindyMakeBuildLog build={personal} openWhileActive={building || Boolean(errorCode)} />
+ <div className="mt-3 space-y-3">
+ <CindyMakeBuildProgress build={displayBuild} />
+ <CindyMakeBuildFailure build={displayBuild} error={errorCode} />
+ <CindyMakeBuildLog build={displayBuild} />
+ </div>
) : (
<CindyMakeTestStep
test={pending === 'start' ? { status: 'starting', step: 'waiting' } : meta.test}
@@ -324,9 +327,9 @@ function CindyMakeCompletedTest({ sessionId, completionId, meta, onContinue }: C
{t('cindyMake.versions.errors.' + versions.error)}
</p>
)}
- {errorCode && (
+ {errorCode && !buildMode && (
<p role="alert" className="text-12 text-[var(--status-danger)]">
- {t((buildMode ? 'cindyMake.personal.errors.' : 'cindyMake.test.errors.') + errorCode)}
+ {t('cindyMake.test.errors.' + errorCode)}
</p>
)}
<div className="flex flex-wrap justify-end gap-2">
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeBuildParity.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeBuildParity.test.tsx
new file mode 100644
index 0000000000..6a3806b67f
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeBuildParity.test.tsx
@@ -0,0 +1,141 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+import type { CindyMakePersonalBuildState } from '../../../../shared/cindyMakeSession';
+import { CindyMakeHistoryPanel } from '../CindyMakeHistoryPanel';
+import { CindyMakeTestCard } from '../CindyMakeTestCard';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { step?: string }) =>
+ options?.step ? key + ': ' + options.step : key,
+ i18n: { language: 'en' },
+ }),
+}));
+vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: vi.fn() }),
+}));
+vi.mock('@/lib/cindyMakeState', () => {
+ const state = {};
+ return { useCindyMakeState: () => state };
+});
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: { updateSystemCardData: vi.fn() },
+}));
+vi.mock('@/features/device-link/stickySessionOrigin', () => ({
+ getStickySessionDeviceId: () => undefined,
+}));
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+it('keeps the session and history headings and stage indicators in sync as the shared build advances', async () => {
+ setDataOwnerGeneration('build-parity-owner');
+ const meta = { reportedAt: 1, commit: 'a'.repeat(40) };
+ let build: CindyMakePersonalBuildState = { status: 'waiting', buildId: 'shared-build' };
+ vi.stubGlobal('electronAPI', {
+ cindyMakeTest: vi.fn(async () => meta),
+ getCindyMakeHistory: vi.fn(async () => ({
+ items: [],
+ busy: true,
+ canBuild: false,
+ build,
+ })),
+ });
+ render(
+ <>
+ <CindyMakeHistoryPanel />
+ <CindyMakeTestCard sessionId="session" completionId="completion" meta={meta} />
+ </>,
+ );
+ const history = screen.getByRole('region', { name: 'cindyMake.history.title' });
+ const session = screen.getByRole('region', { name: 'cindyMake.test.title' });
+ await within(session).findByText('cindyMake.personal.status.waiting');
+
+ const stages: Array<{ state: CindyMakePersonalBuildState; heading: string; completed: number }> =
+ [
+ {
+ state: { status: 'waiting', preparationStep: 'original' },
+ heading: 'preparationStep.original',
+ completed: 0,
+ },
+ { state: { status: 'merging' }, heading: 'status.merging', completed: 1 },
+ {
+ state: { status: 'checking', checkStep: 'dependencies' },
+ heading: 'checkStep.dependencies',
+ completed: 2,
+ },
+ {
+ state: { status: 'checking', checkStep: 'tests' },
+ heading: 'checkStep.tests',
+ completed: 2,
+ },
+ {
+ state: { status: 'checking', checkStep: 'types' },
+ heading: 'checkStep.types',
+ completed: 2,
+ },
+ { state: { status: 'packaging' }, heading: 'status.packaging', completed: 3 },
+ { state: { status: 'publishing' }, heading: 'status.publishing', completed: 4 },
+ ];
+ for (const { state, heading, completed } of stages) {
+ build = { ...state, buildId: 'shared-build' };
+ fireEvent(window, new Event('focus'));
+ await waitFor(() => {
+ for (const surface of [history, session]) {
+ expect(within(surface).getByText('cindyMake.personal.' + heading)).toBeTruthy();
+ const current = surface.querySelectorAll('[aria-current="step"]');
+ expect(current).toHaveLength(1);
+ expect(current[0].textContent).toBe('cindyMake.history.progress.' + state.status);
+ expect(surface.querySelectorAll('li[class*="--status-success"]')).toHaveLength(completed);
+ }
+ });
+ }
+ build = { ...build, stopping: true };
+ fireEvent(window, new Event('focus'));
+ await waitFor(() => {
+ for (const surface of [history, session]) {
+ expect(within(surface).getAllByText('cindyMake.history.stopping')).toHaveLength(2);
+ expect(surface.querySelector('[aria-current="step"]')?.textContent).toBe(
+ 'cindyMake.history.progress.publishing',
+ );
+ }
+ });
+
+ for (const error of ['checksFailed', 'cancelled', undefined] as const) {
+ build = {
+ status: 'failed',
+ buildId: 'shared-build',
+ error,
+ logs: [
+ { step: 'checking-tests', at: 123 },
+ { step: error === 'cancelled' ? 'cancelled' : 'failed', at: 124 },
+ ],
+ };
+ fireEvent(window, new Event('focus'));
+ await waitFor(() => {
+ for (const surface of [history, session]) {
+ const alert = within(surface).getByRole('alert');
+ expect(alert.textContent).toContain(
+ 'cindyMake.personal.errors.' + (error ?? 'unavailable'),
+ );
+ expect(alert.closest('details')).toBeNull();
+ if (error === 'cancelled') {
+ expect(alert.textContent).not.toContain('cindyMake.personal.failedStep');
+ } else {
+ expect(alert.textContent).toContain(
+ 'cindyMake.personal.failedStep: cindyMake.personal.buildLog.steps.checking-tests',
+ );
+ }
+ const details = within(surface)
+ .getByText('cindyMake.personal.buildLog.title · 2')
+ .closest('details');
+ expect(details?.open).toBe(false);
+ }
+ });
+ }
+});
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
index d22c977d7b..ffd5ebe0cf 100644
--- 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
@@ -248,7 +248,7 @@ describe('Cindy Make history with real translations', () => {
resource.cindyMake.versions.localChanges,
),
).toBeTruthy();
- expect(screen.getAllByText(resource.cindyMake.history.buildStatus.failed)).toHaveLength(2);
+ expect(screen.getAllByText(resource.cindyMake.personal.status.failed)).toHaveLength(2);
expect(
screen.getByText(i18n.t('cindyMake.history.files', { count: 2 }), { exact: false }),
).toBeTruthy();
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
index f5fc7e8e07..570cef9ffd 100644
--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeHistoryPanel.test.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeHistoryPanel.test.tsx
@@ -3,6 +3,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libra
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import type { ConfirmOptions } from '@/components/ui/confirm-dialog-provider';
+import type { SelectProps } from '@/components/ui/select';
import type {
CindyMakeHistoryItem,
CindyMakeHistoryState,
@@ -29,6 +30,22 @@ vi.mock('@/components/ui/confirm-dialog-provider', () => ({
useConfirmDialog: () => ({ confirm: h.confirm }),
}));
vi.mock('@/lib/toast', () => ({ toast: { error: h.error } }));
+vi.mock('@/components/ui/select', () => ({
+ Select: ({ label, value, options, onValueChange, disabled }: SelectProps) => (
+ <select
+ aria-label={label}
+ value={value}
+ disabled={disabled}
+ onChange={(event) => onValueChange(event.target.value)}
+ >
+ {options.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </select>
+ ),
+}));
function item(patch: Partial<CindyMakeHistoryItem> = {}): CindyMakeHistoryItem {
return {
schema: 1,
@@ -54,7 +71,7 @@ function harness(items = [item()]) {
const execute = vi.fn(async () => state);
const build = vi.fn(async () => state);
const cancel = vi.fn(async () => state);
- let onMessage: (() => void) | undefined;
+ let onMessage: ((event?: { sessionId?: string; message?: unknown }) => void) | undefined;
const unsubscribe = vi.fn();
vi.stubGlobal('electronAPI', {
getCindyMakeHistory: read,
@@ -76,7 +93,7 @@ function harness(items = [item()]) {
build,
cancel,
changed: () =>
- (onMessage as any)?.({
+ onMessage?.({
sessionId: items[0]?.sessionId,
message: { agentMeta: { cindyMakeCompletion: {} } },
}),
@@ -228,7 +245,7 @@ describe('Make history controls', () => {
const f = harness([building]);
f.set({ items: [building], busy: true, canBuild: false });
render(<CindyMakeHistoryPanel />);
- expect(await screen.findAllByText('cindyMake.history.buildStatus.packaging')).toHaveLength(2);
+ expect(await screen.findAllByText('cindyMake.personal.status.packaging')).toHaveLength(2);
expect(screen.queryByRole('button', { name: 'cindyMake.history.build' })).toBeNull();
expect(
screen.queryByRole('button', { name: 'cindyMake.history.actions.integrate' }),
@@ -540,3 +557,128 @@ describe('Make history controls', () => {
expect(screen.queryByText(/Private previous owner/)).toBeNull();
});
});
+
+function selectableItem(runId: string, createdAt: number) {
+ return item({
+ runId,
+ createdAt,
+ title: runId,
+ sessionId: 'task-' + runId,
+ canSelectForBuild: true,
+ completionId: 'done-' + runId,
+ completions: [
+ { id: 'done-' + runId, reportedAt: createdAt, commit: 'a'.repeat(40), tree: 'b'.repeat(40) },
+ ],
+ });
+}
+async function beginSelection() {
+ fireEvent.change(await screen.findByRole('combobox', { name: 'cindyMake.history.filterLabel' }), {
+ target: { value: 'pending' },
+ });
+ fireEvent.click(await screen.findByRole('button', { name: 'cindyMake.history.batch.make' }));
+}
+
+describe('pending history selection', () => {
+ it('selects multiple pending records and confirms the chronological list before one build', async () => {
+ const newer = selectableItem('newer', 20);
+ const older = selectableItem('older', 10);
+ const f = harness([
+ newer,
+ older,
+ item({ runId: 'busy', actions: ['open'] }),
+ item({ runId: 'merged', integration: 'integrated' }),
+ ]);
+ render(<CindyMakeHistoryPanel />);
+ await beginSelection();
+ expect(
+ screen
+ .getByRole('button', { name: 'cindyMake.history.batch.selected' })
+ .hasAttribute('disabled'),
+ ).toBe(true);
+ fireEvent.click(screen.getByRole('checkbox', { name: 'cindyMake.history.batch.selectAll' }));
+ const checks = screen.getAllByRole('checkbox', {
+ name: 'cindyMake.history.batch.selectItem',
+ }) as HTMLInputElement[];
+ expect(checks.map((checkbox) => checkbox.checked)).toEqual([true, true, false]);
+ expect(checks[2].disabled).toBe(true);
+ // Multi-select can also remove and re-add one entry without losing the others.
+ fireEvent.click(checks[0]);
+ expect(checks[1].checked).toBe(true);
+ fireEvent.click(checks[0]);
+ let approve!: (accepted: boolean) => void;
+ h.confirm.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ approve = resolve;
+ }),
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.history.batch.selected' }));
+ await waitFor(() => expect(h.confirm).toHaveBeenCalledOnce());
+ expect(f.build).not.toHaveBeenCalled();
+ const confirmation = h.confirm.mock.calls[0][0];
+ expect(confirmation).toMatchObject({
+ description: 'cindyMake.history.batch.confirmDescription',
+ });
+ const preview = render(<>{confirmation.content}</>);
+ expect(preview.container.textContent!.indexOf('older')).toBeLessThan(
+ preview.container.textContent!.indexOf('newer'),
+ );
+ preview.unmount();
+ await act(async () => approve(true));
+ expect(f.build).toHaveBeenCalledOnce();
+ expect(f.build).toHaveBeenCalledWith(
+ [older, newer].map((record) => ({
+ runId: record.runId,
+ completionId: record.completionId,
+ commit: record.completions[0].commit,
+ tree: record.completions[0].tree,
+ })),
+ );
+ expect(f.execute).not.toHaveBeenCalled();
+ });
+ it('keeps selections after cancelling the second dialog and does not build', async () => {
+ const f = harness([selectableItem('one', 1)]);
+ h.confirm.mockResolvedValueOnce(false);
+ render(<CindyMakeHistoryPanel />);
+ await beginSelection();
+ fireEvent.click(screen.getByRole('checkbox', { name: 'cindyMake.history.batch.selectAll' }));
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.history.batch.selected' }));
+ await waitFor(() => expect(h.confirm).toHaveBeenCalledOnce());
+ expect(f.build).not.toHaveBeenCalled();
+ expect(
+ (
+ screen.getByRole('checkbox', {
+ name: 'cindyMake.history.batch.selectItem',
+ }) as HTMLInputElement
+ ).checked,
+ ).toBe(true);
+ });
+ it("does not submit another owner's selections after confirmation", async () => {
+ const f = harness([selectableItem('one', 1)]);
+ let approve!: (accepted: boolean) => void;
+ h.confirm.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ approve = resolve;
+ }),
+ );
+ render(<CindyMakeHistoryPanel />);
+ await beginSelection();
+ fireEvent.click(screen.getByRole('checkbox', { name: 'cindyMake.history.batch.selectAll' }));
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.history.batch.selected' }));
+ await waitFor(() => expect(h.confirm).toHaveBeenCalledOnce());
+ setDataOwnerGeneration('other-history-owner');
+ await act(async () => approve(true));
+ expect(f.build).not.toHaveBeenCalled();
+ });
+ it('offers restart for the selected running isolated version', async () => {
+ const f = harness([
+ item({ test: { status: 'ready' }, actions: ['test', 'continue', 'build'] }),
+ ]);
+ render(<CindyMakeHistoryPanel />);
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'cindyMake.history.batch.restartTest' }),
+ );
+ await waitFor(() => expect(f.execute).toHaveBeenCalledWith('aaaa', 'test'));
+ });
+});
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
index c6050fda7f..1aa1416e60 100644
--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTestCard.test.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeTestCard.test.tsx
@@ -116,6 +116,44 @@ describe('completion card in the input area', () => {
screen.getByText('cindyMake.test.failedStep: cindyMake.test.steps.assets'),
).toBeDefined();
});
+ it('starts retry progress at waiting without carrying over the failed build log', async () => {
+ render(
+ <CindyMakeTestCard
+ sessionId="session"
+ completionId="completion"
+ meta={{
+ ...meta,
+ lastAction: 'build',
+ personal: {
+ status: 'failed',
+ error: 'checksFailed',
+ logs: [
+ { step: 'environment', at: 1 },
+ { step: 'original', at: 2 },
+ { step: 'merging', at: 3 },
+ { step: 'checking-dependencies', at: 4 },
+ ],
+ },
+ }}
+ />,
+ );
+
+ await waitFor(() => expect(h.api).toHaveBeenCalledOnce());
+ h.api.mockImplementationOnce(() => new Promise(() => {}));
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.personal.generate' }));
+ expect(h.api).toHaveBeenLastCalledWith('session', 'completion', 'build');
+ expect(screen.getByText('cindyMake.personal.status.waiting')).toBeTruthy();
+ expect(
+ screen.getByText('cindyMake.history.progress.waiting').getAttribute('aria-current'),
+ ).toBe('step');
+ expect(screen.getByText('cindyMake.history.progress.merging').className).not.toContain(
+ '--status-success',
+ );
+ expect(
+ screen.queryByText('cindyMake.personal.buildLog.steps.checking-dependencies'),
+ ).toBeNull();
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
it('shows live startup steps, blocks editing, and offers retry with the failed step', async () => {
const { rerender } = render(
<CindyMakeTestCard
@@ -377,6 +415,12 @@ describe('completion card in the input area', () => {
expect(screen.getByText('cindyMake.personal.status.packaging')).toBeDefined();
expect(screen.getByText('cindyMake.personal.buildLog.title · 1')).toBeDefined();
expect(screen.getByText('cindyMake.personal.buildLog.steps.packaging')).toBeDefined();
+ expect(
+ screen
+ .getByText('cindyMake.personal.buildLog.title · 1')
+ .closest('details')
+ ?.hasAttribute('open'),
+ ).toBe(false);
expect(
(screen.getByRole('button', { name: 'cindyMake.test.continue' }) as HTMLButtonElement)
.disabled,
@@ -409,6 +453,12 @@ describe('completion card in the input area', () => {
);
expect(screen.getByText('cindyMake.personal.preparationStep.environment')).toBeDefined();
expect(screen.getByText('cindyMake.personal.buildLog.steps.environment')).toBeDefined();
+ expect(
+ screen
+ .getByText('cindyMake.personal.buildLog.title · 1')
+ .closest('details')
+ ?.hasAttribute('open'),
+ ).toBe(false);
});
it('offers the installer when ready and gives failed builds a retry', async () => {
const { rerender } = render(
@@ -435,11 +485,30 @@ describe('completion card in the input area', () => {
meta={{
...meta,
lastAction: 'build',
- personal: { status: 'failed', error: 'checksFailed' },
+ personal: {
+ status: 'failed',
+ error: 'checksFailed',
+ logs: [
+ { step: 'merging', at: 123 },
+ { step: 'checking-tests', at: 124 },
+ { step: 'failed', at: 125 },
+ ],
+ },
}}
/>,
);
- expect(screen.getByRole('alert').textContent).toBe('cindyMake.personal.errors.checksFailed');
+ expect(screen.getByRole('alert').textContent).toContain(
+ 'cindyMake.personal.failedStep: cindyMake.personal.buildLog.steps.checking-tests',
+ );
+ expect(screen.getByRole('alert').textContent).toContain(
+ 'cindyMake.personal.errors.checksFailed',
+ );
+ expect(
+ screen
+ .getByText('cindyMake.personal.buildLog.title · 3')
+ .closest('details')
+ ?.hasAttribute('open'),
+ ).toBe(false);
expect(
screen.getAllByRole('button').every((button) => !(button as HTMLButtonElement).disabled),
).toBe(true);
diff --git a/apps/desktop/src/renderer/components/cindy-make/cindyMakeBuildStatus.ts b/apps/desktop/src/renderer/components/cindy-make/cindyMakeBuildStatus.ts
new file mode 100644
index 0000000000..3c51515ba7
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/cindyMakeBuildStatus.ts
@@ -0,0 +1,14 @@
+import type { CindyMakePersonalBuildState } from '../../../shared/cindyMakeSession';
+
+/** Both build surfaces name the same live stage, including preparation and check details. */
+export function cindyMakeBuildStatusKey(
+ build: CindyMakePersonalBuildState,
+ stopping = build.stopping,
+): string {
+ if (stopping) return 'cindyMake.history.stopping';
+ if (build.status === 'waiting' && build.preparationStep)
+ return 'cindyMake.personal.preparationStep.' + build.preparationStep;
+ if (build.status === 'checking' && build.checkStep)
+ return 'cindyMake.personal.checkStep.' + build.checkStep;
+ return 'cindyMake.personal.status.' + build.status;
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index a9fc163d9d..7096d8f1c7 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -13044,6 +13044,7 @@
"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.",
+ "failedStep": "Failed during: {{step}}",
"preparationStep": {
"environment": "Preparing the build environment…",
"original": "Checking the current version…"
@@ -13137,6 +13138,18 @@
},
"history": {
"title": "Make history",
+ "batch": {
+ "make": "Make Personal Version",
+ "selected": "Build {{count}} Selected Changes",
+ "selectAll": "Select all in this list",
+ "selectItem": "Select {{title}}",
+ "hint": "Merge oldest to newest, then generate one new version.",
+ "confirmTitle": "Make a personal version with {{count}} changes?",
+ "confirmDescription": "The selected changes will be merged in the order below, then one new version will be generated after all merges succeed. Running isolated tests for these changes will stop first. A conflict stops the build and keeps already merged changes; resolve it, then start a new build. When no conflict is pending, cancellation or failure rolls back merges that have not produced a saved version, keeping each task's original changes.",
+ "start": "Confirm Build",
+ "progress": "Merging {{current}} / {{total}}: {{title}}",
+ "restartTest": "Restart Isolated Version"
+ },
"build": "Generate personal version",
"buildDescription": "Generate a new version from the current personal source. Changes not yet integrated are excluded.",
"building": "Generating personal version…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 693856699a..bc1b247ba0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -13027,6 +13027,7 @@
"open": "インストーラーの場所を開く",
"description": "今回の変更を個人版にマージし、チェックとパッケージ化が完了してから新しい個人版として保存します。",
"readyHint": "インストーラー {{name}} を作成しました。保存先フォルダーを開けます。",
+ "failedStep": "失敗したステップ:{{step}}",
"preparationStep": {
"environment": "ビルド環境を準備中…",
"original": "現在のバージョンを確認中…"
@@ -13120,6 +13121,18 @@
},
"history": {
"title": "制作履歴",
+ "batch": {
+ "make": "個人版を作成",
+ "selected": "選択した {{count}} 件で作成",
+ "selectAll": "この一覧をすべて選択",
+ "selectItem": "{{title}} を選択",
+ "hint": "古い順にマージし、最後に新しいバージョンを1つ作成します。",
+ "confirmTitle": "{{count}} 件の変更を含む個人版を作成しますか?",
+ "confirmDescription": "選択した変更を以下の順序でマージし、すべて成功したら新しいバージョンを1つ作成します。選択した変更の隔離版が起動中の場合は先に停止します。競合が発生した場合は停止し、マージ済みの変更を保持します。競合を解消してから、再度作成を開始してください。未解決の競合がない場合、キャンセルや失敗時は保存済みバージョンに含まれていないマージを取り消し、各セッションの元の変更を保持します。",
+ "start": "作成を確定",
+ "progress": "マージ中 {{current}} / {{total}}: {{title}}",
+ "restartTest": "隔離版を再起動"
+ },
"build": "個人版を生成",
"buildDescription": "現在の個人版ソースから新しいバージョンを生成します。未取り込みの過去の変更は含まれません。",
"building": "個人版を生成中…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f07465d8ca..2114adecc4 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -13027,6 +13027,7 @@
"open": "설치 파일 위치 열기",
"description": "이번 수정 사항을 개인 버전에 병합하고, 검사와 패키징을 통과한 후 새 개인 버전으로 저장합니다.",
"readyHint": "설치 파일 {{name}}이 준비되었습니다. 저장된 폴더를 열 수 있습니다.",
+ "failedStep": "실패한 단계: {{step}}",
"preparationStep": {
"environment": "빌드 환경 준비 중…",
"original": "현재 버전 확인 중…"
@@ -13120,6 +13121,18 @@
},
"history": {
"title": "제작 기록",
+ "batch": {
+ "make": "개인 버전 만들기",
+ "selected": "선택한 변경 {{count}}개로 만들기",
+ "selectAll": "이 목록 모두 선택",
+ "selectItem": "{{title}} 선택",
+ "hint": "오래된 변경부터 병합한 뒤 새 버전 하나를 생성합니다.",
+ "confirmTitle": "변경 {{count}}개를 포함한 개인 버전을 만들까요?",
+ "confirmDescription": "선택한 변경을 아래 순서대로 병합하고 모두 성공하면 새 버전 하나를 생성합니다. 선택한 변경의 격리 버전이 실행 중이면 먼저 중지합니다. 충돌이 발생하면 중단하고 이미 병합된 변경은 유지합니다. 충돌을 해결한 뒤 다시 만들 수 있습니다. 해결되지 않은 충돌이 없을 때 취소하거나 실패하면 저장된 버전에 포함되지 않은 병합을 되돌리고 각 세션의 원래 변경은 유지합니다.",
+ "start": "만들기 확인",
+ "progress": "병합 중 {{current}} / {{total}}: {{title}}",
+ "restartTest": "격리 버전 다시 시작"
+ },
"build": "개인 버전 생성",
"buildDescription": "현재 개인 소스로 새 버전을 생성합니다. 아직 반영하지 않은 이전 변경 사항은 포함되지 않습니다.",
"building": "개인 버전 생성 중…",
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 f024a9861e..5c21e003b4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -13027,6 +13027,7 @@
"open": "查看安装包",
"description": "将本次修改与个人版合并,检查和打包通过后保存为新个人版。",
"readyHint": "安装包 {{name}} 已生成,可打开所在目录。",
+ "failedStep": "失败步骤:{{step}}",
"preparationStep": {
"environment": "正在准备生成环境…",
"original": "正在检查当前版本…"
@@ -13120,6 +13121,18 @@
},
"history": {
"title": "制作历史",
+ "batch": {
+ "make": "制作个人版",
+ "selected": "制作所选 {{count}} 项",
+ "selectAll": "全选当前列表",
+ "selectItem": "选择 {{title}}",
+ "hint": "按从老到新的顺序合入,统一生成一个新版本。",
+ "confirmTitle": "制作包含 {{count}} 项改动的个人版?",
+ "confirmDescription": "所选改动将按以下顺序逐条合入,全部成功后只生成一个新版本。已启动的所选隔离版会先停止。遇到冲突时停止制作并保留已合入改动,处理后可重新发起制作。没有待处理冲突时,取消或生成失败会撤回尚未生成成功版本的合入,保留各任务的原始改动。",
+ "start": "确认制作",
+ "progress": "正在合入 {{current}} / {{total}}:{{title}}",
+ "restartTest": "重新启动隔离版"
+ },
"build": "生成个人版",
"buildDescription": "将当前个人源码生成新版本,未合入的历史改动不会包含在内。",
"building": "正在生成个人版…",
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 e1f00bbc28..7b99c57d28 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -13027,6 +13027,7 @@
"open": "查看安裝套件",
"description": "將本次修改與個人版合併,檢查和打包通過後儲存為新個人版。",
"readyHint": "安裝套件 {{name}} 已產生,可開啟所在目錄。",
+ "failedStep": "失敗步驟:{{step}}",
"preparationStep": {
"environment": "正在準備產生環境…",
"original": "正在檢查目前版本…"
@@ -13120,6 +13121,18 @@
},
"history": {
"title": "製作歷史",
+ "batch": {
+ "make": "製作個人版",
+ "selected": "製作所選 {{count}} 項",
+ "selectAll": "全選目前清單",
+ "selectItem": "選取 {{title}}",
+ "hint": "由舊到新依序合入,統一產生一個新版本。",
+ "confirmTitle": "製作包含 {{count}} 項變更的個人版?",
+ "confirmDescription": "所選變更將依下列順序逐項合入,全部成功後只產生一個新版本。已啟動的所選隔離版會先停止。遇到衝突時停止製作並保留已合入變更,處理後可重新開始製作。沒有待處理衝突時,取消或產生失敗會撤回尚未產生成功版本的合入,保留各任務的原始變更。",
+ "start": "確認製作",
+ "progress": "正在合入 {{current}} / {{total}}:{{title}}",
+ "restartTest": "重新啟動隔離版"
+ },
"build": "產生個人版",
"buildDescription": "將目前的個人原始碼產生為新版本,尚未合入的歷史改動不會包含在內。",
"building": "正在產生個人版…",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 3ed003b649..2f1778f45c 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3025,9 +3025,9 @@ interface ElectronAPI {
runId: string,
action: import('../shared/cindyMakeHistory').MakeHistoryAction,
) => Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState>;
- generateCindyMakePersonal: () => Promise<
- import('../shared/cindyMakeHistory').CindyMakeHistoryState
- >;
+ generateCindyMakePersonal: (
+ selection?: import('../shared/cindyMakeHistory').MakeHistoryBuildSelection[],
+ ) => Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState>;
cancelCindyMakePersonal: (
buildId: string,
) => Promise<import('../shared/cindyMakeHistory').CindyMakeHistoryState>;
@@ -3463,7 +3463,9 @@ interface ElectronAPI {
error?: string;
errorCode?: string;
}>;
- comparePublished: (params: import('../shared/skillhubPublishComparison').SkillhubPublishComparisonParams) => Promise<import('../shared/skillhubPublishComparison').SkillhubPublishComparison>;
+ comparePublished: (
+ params: import('../shared/skillhubPublishComparison').SkillhubPublishComparisonParams,
+ ) => Promise<import('../shared/skillhubPublishComparison').SkillhubPublishComparison>;
getFolderHash: (absolutePath: string) => Promise<{
success: boolean;
diff --git a/apps/desktop/src/shared/cindyMakeHistory.ts b/apps/desktop/src/shared/cindyMakeHistory.ts
index f85a7778df..eb890939c8 100644
--- a/apps/desktop/src/shared/cindyMakeHistory.ts
+++ b/apps/desktop/src/shared/cindyMakeHistory.ts
@@ -83,12 +83,22 @@ export interface CindyMakeHistoryItem extends CindyMakeHistoryRecord {
actionReason?: MakeHistoryActionReason;
/** Main-owned permission to hide this entry after its workspace is reclaimed. */
canHide?: boolean;
+ /** A selection hint; Main verifies the pinned completion again before merging. */
+ canSelectForBuild?: boolean;
+}
+/** The exact editing round approved in the batch confirmation. */
+export interface MakeHistoryBuildSelection {
+ runId: string;
+ completionId: string;
+ commit: string;
+ tree: string;
}
export interface CindyMakeHistoryState {
items: CindyMakeHistoryItem[];
busy: boolean;
canBuild: boolean;
build?: CindyMakePersonalBuildState;
+ batch?: { current: number; total: number; runId: string; title: string };
}
/** The last undo removes all preceding active changes; reapply starts a new effective delta. */
export function activeFeatureReceipts(receipts: MakeFeatureReceipt[]): MakeFeatureReceipt[] {
@@ -119,15 +129,14 @@ export function makeHistoryActions(facts: {
}): MakeHistoryAction[] {
const actions: MakeHistoryAction[] = facts.sessionAvailable ? ['open'] : [];
if (facts.test?.status === 'starting') return actions;
- // Continue is the one action that stops a ready test through its controller.
- // Do not depend on a global busy snapshot taken before the latest receipt.
+ // A ready test can be restarted or handed over to a build through its controller.
if (facts.test?.status === 'ready')
return facts.completed &&
facts.sessionAvailable &&
facts.workspaceAvailable &&
facts.lifecycle === 'ready' &&
!facts.conflict
- ? [...actions, 'continue']
+ ? [...actions, 'continue', ...(facts.sourceAvailable ? (['test', 'build'] as const) : [])]
: actions;
if (facts.busy) {
if (!facts.allowCleanupWhileBusy) return actions;
diff --git a/docs/cindy-make-upstream.md b/docs/cindy-make-upstream.md
index 21d58de6bc..0c8e7d56f9 100644
--- a/docs/cindy-make-upstream.md
+++ b/docs/cindy-make-upstream.md
@@ -277,6 +277,14 @@ rebase 到新官方基线(禁止 update-refs 自动改动其他任务分支)
commit 的祖先关系误判已经撤销或无法撤销。Git 采纳和历史写入之间中断可显式重试,
历史回执按操作 ID 去重;重启不静默重放写操作。
- 制作历史的「生成个人版」自动合入所选任务已经完成的修改,再从当前个人源码构建;
+ 筛选「待合入」时,工具栏右侧另提供「制作个人版」进入多选;支持全选当前搜索列表,
+ 二次确认按创建时间从老到新列出所选记录。Main 固定已确认的完成记录、commit 与文件树,
+ 先停止所选记录正在运行的隔离测试,再核验全部选择,逐条合入并且只在全部成功后生成一次。
+ 合入期间显示当前条目与总数;离开设置不取消流程。冲突或取消停止后续合入与打包,
+ 待处理的冲突工作区仍依赖已合入的前缀,因此此时保留个人源码基线,待冲突处理后再显式制作;
+ 没有待处理冲突工作区时,失败清理沿用下述撤回规则。不在重启后重放批量操作。
+ 每条可测试的待合入记录沿用同一隔离测试控制器;已启动时提供「重新启动隔离版」,
+ 等待旧进程真实退出后才重新启动,停止失败保留原状态。
当前完成轮复用任务完成卡的同一生成流程。已结束的任务可使用保留的完成快照,无需仍存在
的制作工作目录,也不创建虚假的任务。生成时在源码锁内记录实际包含的操作,成功后刷新版本列表。
按钮始终叫「生成个人版」,失败后保持同一入口,不另设「重新生成」。失败或取消自动撤回