Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(cindy-make): 统一历史状态与任务清理操作
Lizieb8465d960f8
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 89fb4dba99..19f06cbac4 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -7674,8 +7674,15 @@ const registerIpcHandlers = () => {assertTrustedAppRendererEvent(event);try {return await actCindyMakeHistory(runId, action);- } catch {- throwIpcError('PRECONDITION_FAILED', 'unavailable');+ } catch (error) {+ const message = (error as { message?: unknown }).message;+ const reason =+ typeof message === 'string'+ ? /^\[PRECONDITION_FAILED\]\s*(busy|dirty|conflict|cleanupFailed|directoryBusy|unavailable)$/.exec(+ message,+ )?.[1]+ : undefined;+ throwIpcError('PRECONDITION_FAILED', reason ?? 'unavailable');}},);diff --git a/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts b/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.tsindex 968f1b90d5..cb7e4136d2 100644--- a/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts+++ b/apps/desktop/src/main/cindy-make/__tests__/historyActions.test.ts@@ -13,16 +13,35 @@ const ready = {conflict: false,};describe('history action admission', () => {+ it('locks editing during launch but lets a ready test stop through Continue', () => {+ expect(makeHistoryActions({ ...ready, busy: true, test: { status: 'starting' } })).toEqual([+ 'open',+ ]);+ expect(makeHistoryActions({ ...ready, busy: false, test: { status: 'starting' } })).toEqual([+ 'open',+ ]);+ expect(makeHistoryActions({ ...ready, busy: true, test: { status: 'ready' } })).toEqual([+ 'open',+ 'continue',+ ]);+ expect(+ makeHistoryActions({ ...ready, busy: true, test: { status: 'ready' }, completed: false }),+ ).toEqual(['open']);+ });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']);+ it('keeps Open available and adds Continue for verified completed edits', () => {+ expect(makeHistoryActions(ready)).toEqual(['open', 'continue', 'test', 'integrate', 'end']);expect(makeHistoryActions({ ...ready, integration: 'unknown' })).toEqual(['open', 'end']);- expect(makeHistoryActions({ ...ready, integration: 'unchanged' })).toEqual(['continue', 'end']);+ expect(makeHistoryActions({ ...ready, integration: 'unchanged' })).toEqual([+ 'open',+ 'continue',+ 'end',+ ]);expect(makeHistoryActions({ ...ready, completed: false, lifecycle: 'editing' })).toEqual(['open','end',@@ -30,12 +49,14 @@ describe('history action admission', () => {});it('shows Undo after integration, Reapply after undo, and does not offer first-time integration twice', () => {expect(makeHistoryActions({ ...ready, integration: 'integrated', hasReceipts: true })).toEqual([+ 'open','continue','test','end','revert',]);expect(makeHistoryActions({ ...ready, integration: 'reverted', hasReceipts: true })).toEqual([+ 'open','continue','test','end',@@ -48,7 +69,7 @@ describe('history action admission', () => {hasReceipts: true,newChanges: true,}),- ).toEqual(['continue', 'test', 'integrate', 'end']);+ ).toEqual(['open', 'continue', 'test', 'integrate', 'end']);expect(makeHistoryActions({...ready,@@ -99,6 +120,28 @@ describe('history action admission', () => {}),).toEqual(['build']);});+ it('keeps unrelated cleanup available while global work is busy', () => {+ expect(makeHistoryActions({ ...ready, busy: true, allowCleanupWhileBusy: true })).toEqual([+ 'open',+ 'end',+ ]);+ expect(+ makeHistoryActions({+ ...ready,+ busy: true,+ allowCleanupWhileBusy: true,+ lifecycle: 'cleanup',+ }),+ ).toEqual(['open', 'retry-cleanup']);+ expect(+ makeHistoryActions({+ ...ready,+ busy: true,+ allowCleanupWhileBusy: true,+ lifecycle: 'running',+ }),+ ).toEqual(['open']);+ });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({diff --git a/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts b/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.tsindex adc749b993..122ff18a44 100644--- a/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts+++ b/apps/desktop/src/main/cindy-make/__tests__/historyRuntime.test.ts@@ -18,10 +18,10 @@ const h = vi.hoisted(() => ({artifactPath: vi.fn(),showItem: vi.fn(),build: vi.fn(),- testBuild: undefined as- | { buildId: string; status: string; stopping?: boolean }- | undefined,+ testBuild: undefined as { buildId: string; status: string; stopping?: boolean } | undefined,cancelTestBuild: vi.fn(),+ testStatus: vi.fn(),+ testUsing: false,}));const store = {readBuild: vi.fn(),@@ -78,7 +78,9 @@ vi.mock('../taskManagement.js', () => ({ manageCindyMakeTask: h.end }));vi.mock('../testRuntime.js', () => ({actCindyMakeTest: vi.fn(),cindyMakeTestController: {- hasActiveJobs: () => !!h.testBuild,+ hasActiveJobs: () => !!h.testBuild || h.testUsing,+ isUsingWorkspace: () => h.testUsing,+ act: h.testStatus,isBuilding: () => !!h.testBuild,activeBuild: () => h.testBuild,cancelBuild: h.cancelTestBuild,@@ -152,6 +154,8 @@ beforeEach(() => {h.running = false;h.busy = false;h.testBuild = undefined;+ h.testUsing = false;+ h.testStatus.mockReset();h.cancelTestBuild.mockReset();vi.spyOn(cindyMakeManager, 'getState').mockImplementation(() => h.state);h.exists = true;@@ -195,6 +199,55 @@ beforeEach(() => {];});describe('history Main admission and owner boundary', () => {+ it.each(['starting', 'ready', 'failed', 'stopped'] as const)(+ 'projects the completion card test receipt: %s',+ async (status) => {+ const meta = JSON.parse(h.cards[0].agentMeta).cindyMakeCompletion;+ const test = {+ status,+ step: 'launching',+ ...(status === 'failed' ? { error: 'launchFailed' } : {}),+ };+ h.cards[0].agentMeta = JSON.stringify({+ cindyMakeCompletion: { ...meta, lastAction: 'test', test },+ });+ h.testUsing = ['starting', 'ready'].includes(status);+ h.testStatus.mockResolvedValue({ ...meta, lastAction: 'test', test });+ const item = (await getCindyMakeHistory('aaaa')).items[0];+ 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 expect(item.actions).toContain('test');+ expect(item.canHide).toBe(!h.testUsing);+ },+ );+ it('uses the card controller to reconcile an interrupted test after restart', async () => {+ const meta = JSON.parse(h.cards[0].agentMeta).cindyMakeCompletion;+ h.cards[0].agentMeta = JSON.stringify({+ cindyMakeCompletion: { ...meta, test: { status: 'starting' } },+ });+ const recovered = { ...meta, test: { status: 'stopped', error: 'interrupted' } };+ h.testStatus.mockResolvedValue(recovered);+ const item = (await getCindyMakeHistory('aaaa')).items[0];+ expect(h.testStatus).toHaveBeenCalledWith('session', 'complete', 'status');+ expect(item.test).toEqual(recovered.test);+ expect(item.completions.at(-1)?.test).toEqual(recovered.test);+ expect(item.actions).toContain('test');+ });+ it('does not present a previous round test failure during continued editing', async () => {+ const meta = JSON.parse(h.cards[0].agentMeta).cindyMakeCompletion;+ h.cards[0].agentMeta = JSON.stringify({+ cindyMakeCompletion: {+ ...meta,+ continuedAt: 4,+ test: { status: 'failed', error: 'launchFailed' },+ },+ });+ const item = (await getCindyMakeHistory('aaaa')).items[0];+ expect(item.test).toBeUndefined();+ expect(item.actions).not.toContain('test');+ });it('releases history integration and builds after real manager preparation and failed cleanup settle', async () => {const runId = 'prepared-history';const report = {@@ -414,6 +467,15 @@ describe('history Main admission and owner boundary', () => {expect((await getCindyMakeHistory('aaaa')).items[0].actions).not.toContain('integrate');await expect(actCindyMakeHistory('aaaa', 'integrate')).rejects.toThrow();});+ it('returns busy immediately for a stale cleanup action on the running task', async () => {+ h.running = true;+ await expect(actCindyMakeHistory('aaaa', 'hide')).rejects.toThrow('busy');+ expect(h.end).not.toHaveBeenCalled();+ });+ it('keeps cleanup available for an idle history record while another task owns global work', async () => {+ h.busy = true;+ expect((await getCindyMakeHistory('aaaa')).items[0].actions).toContain('end');+ });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');diff --git a/apps/desktop/src/main/cindy-make/__tests__/historyStore.test.ts b/apps/desktop/src/main/cindy-make/__tests__/historyStore.test.tsindex 80dc75ec54..aa4468eee4 100644--- a/apps/desktop/src/main/cindy-make/__tests__/historyStore.test.ts+++ b/apps/desktop/src/main/cindy-make/__tests__/historyStore.test.ts@@ -64,6 +64,7 @@ it('keeps ended history, deduplicates operation receipts, and does not confuse btree: 'e'.repeat(40),});store.end('aaaa', 4);+ store.hide('aaaa', 5);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 });@@ -84,7 +85,8 @@ it('keeps ended history, deduplicates operation receipts, and does not confuse bexpect(new CindyMakeHistoryStore(dir).list()).toEqual(restored);expect(restored[0]).toMatchObject({endedAt: 4,- updatedAt: 4,+ hiddenAt: 5,+ updatedAt: 5,receipts: [receipt],completions: [{ id: 'turn' }],});diff --git a/apps/desktop/src/main/cindy-make/historyRuntime.ts b/apps/desktop/src/main/cindy-make/historyRuntime.tsindex e0f187d41f..d75d92e927 100644--- a/apps/desktop/src/main/cindy-make/historyRuntime.ts+++ b/apps/desktop/src/main/cindy-make/historyRuntime.ts@@ -238,10 +238,11 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<Cindystate.upstreamMerge.hasWorkspace? state.upstreamMerge: undefined;- const busy =+ const globalBusy =!!buildJob || cindyMakeTestController.hasActiveJobs() || cindyMakeManager.hasActiveWork();const items: CindyMakeHistoryItem[] = [];for (const record of h.store.list()) {+ if (record.hiddenAt !== undefined) continue;const row = rows.find((entry) => entry.id === record.sessionId);const report = state.tasks?.[record.runId];const cleanup = state.taskActions?.[record.sessionId];@@ -287,9 +288,39 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<Cindy: 'editing';let changedSinceCompletion =!!completion?.continuedAt || laterMessage || running(record.sessionId);+ if (+ completed &&+ row?.status === 'active' &&+ completion &&+ (['starting', 'ready'].includes(completion.test?.status ?? '') ||+ ['waiting', 'checking', 'merging', 'packaging', 'publishing'].includes(+ completion.personal?.status ?? '',+ ))+ ) {+ // Reuse the task card's live job lookup and restart recovery. Settings must+ // never independently guess whether a persisted test is still running.+ try {+ const current = await cindyMakeTestController.act(+ record.sessionId,+ completion.id,+ 'status',+ );+ Object.assign(completion, current);+ if (current.continuedAt) completed = false;+ } catch {+ // A newer user message/clear can invalidate the completion during this read.+ // Drop its controls; do not fail the entire history or revive an old test.+ completed = false;+ }+ h.check();+ if (!completed) {+ lifecycle = 'editing';+ changedSinceCompletion = true;+ }+ }let verifiedSource = sourceAvailable;let personalHead: string | undefined;- if (selectedRunId === record.runId && sourceAvailable && !busy && !pendingMerge) {+ if (selectedRunId === record.runId && sourceAvailable && !globalBusy && !pendingMerge) {let checkedBranch = false;try {const signal = AbortSignal.timeout(15000);@@ -422,11 +453,21 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<Cindy)integration = 'unknown';const operation = pendingMerge?.feature?.runId === record.runId ? pendingMerge : undefined;+ const targetBusy =+ running(record.sessionId) ||+ cindyMakeManager.isTaskPreparing(record.sessionId) ||+ cleanup?.status === 'running' ||+ cindyMakeTestController.isUsingWorkspace?.(workspace) === true;+ const blockedByGlobalWork = globalBusy || (!!pendingMerge && !operation);const version = record.versions.at(-1);const needsBuild =!!last &&(version?.operationId !== last.id || (!!personalHead && version?.commit !== personalHead));const taskBuilding = cindyMakeTestController.isBuilding(record.sessionId);+ const test =+ completed && lifecycle === 'ready' && completion?.lastAction !== 'build'+ ? completion?.test+ : undefined;const taskBuild = completion?.personal;const projectedBuild =taskBuild && !taskBuilding && !['ready', 'failed'].includes(taskBuild.status)@@ -439,6 +480,7 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<CindyworkspaceAvailable,sourceAvailable: verifiedSource,completed,+ test,buildFailed: completion?.personal?.status === 'failed',needsBuild,buildSourceAvailable,@@ -450,11 +492,8 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<Cindy(receipt) => receipt.beforeTree !== receipt.tree,),newChanges: completion?.tree !== last?.taskTree,- busy:- busy ||- (!!pendingMerge && !operation) ||- record.runId !== selectedRunId ||- running(record.sessionId),+ busy: blockedByGlobalWork || record.runId !== selectedRunId || running(record.sessionId),+ allowCleanupWhileBusy: blockedByGlobalWork && !targetBusy && !operation,conflict: !!operation,recoverableFailure: operation?.status === 'failed' && !operation.feature?.awaitingResolution,});@@ -463,6 +502,7 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<Cindylifecycle,integration,build: projectedBuild,+ test,completionId: completed ? completion?.id : undefined,resolutionSessionId: operation?.sessionId,conflict: !!operation?.feature?.awaitingResolution,@@ -479,8 +519,9 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<CindyneedsBuild,actions: historyActions,actionReason:- historyActions.length === 0- ? busy || !!pendingMerge || running(record.sessionId)+ historyActions.length === 0 ||+ (targetBusy && historyActions.length === 1 && historyActions[0] === 'open')+ ? blockedByGlobalWork || running(record.sessionId)? 'busy': record.runId !== selectedRunId? 'checking'@@ -494,14 +535,15 @@ export async function getCindyMakeHistory(selectedRunId?: string): Promise<Cindy? 'sourceUnavailable': 'ended': undefined,+ canHide: !targetBusy && !['starting', 'ready'].includes(test?.status ?? ''),});}const build = readCindyMakeBuildState();h.check();return {items,- busy: busy || !!pendingMerge,- canBuild: buildSourceAvailable && !busy && !pendingMerge,+ busy: globalBusy || !!pendingMerge,+ canBuild: buildSourceAvailable && !globalBusy && !pendingMerge,build,};}@@ -511,8 +553,12 @@ export function readCindyMakeBuildState(): CindyMakePersonalBuildState | undefinconst h = context();let build = h.store.readBuild();const activeBuild = cindyMakeTestController.activeBuild();- if (build && !buildJob && !(activeBuild?.buildId && activeBuild.buildId === build.buildId)- && !['ready', 'failed'].includes(build.status)) {+ if (+ build &&+ !buildJob &&+ !(activeBuild?.buildId && activeBuild.buildId === build.buildId) &&+ !['ready', 'failed'].includes(build.status)+ ) {build = { ...build, status: 'failed', stopping: undefined, error: 'interrupted' };h.store.saveBuild(build);}@@ -530,10 +576,22 @@ export async function actCindyMakeHistory(const state = await getCindyMakeHistory(runId);h.check();const item = state.items.find((entry) => entry.runId === runId);- if (!item || !item.actions.includes(action as MakeHistoryAction))+ const canHide = action === 'hide' && item?.canHide === true;+ // Keep a stale cleanup button harmless when this record itself is still+ // running, preparing, being tested, or already cleaning. The snapshot+ // carries the stable reason so Renderer can show the actionable busy tip+ // immediately instead of reporting a generic unavailable action.+ if (item?.actionReason === 'busy' && ['end', 'retry-cleanup', 'hide'].includes(action))+ throwIpcError('PRECONDITION_FAILED', 'busy');+ if (!item || (!item.actions.includes(action as MakeHistoryAction) && !canHide))throwIpcError('PRECONDITION_FAILED', 'unavailable');if (action === 'build') return generateHistoryPersonalVersion();- if (action === 'end' || action === 'retry-cleanup')+ if (action === 'hide') {+ // An ended record has already gone through the canonical task cleanup path.+ // Active/cleanup records must finish that path before they become dismissible.+ if (item.lifecycle !== 'ended') await manageCindyMakeTask(item.sessionId, 'end');+ h.store.hide(runId);+ } else if (action === 'end' || action === 'retry-cleanup')await manageCindyMakeTask(item.sessionId, 'end');else if (action === 'test' || action === 'continue')await actCindyMakeTest(diff --git a/apps/desktop/src/main/cindy-make/historyStore.ts b/apps/desktop/src/main/cindy-make/historyStore.tsindex 9d864f33ed..b5240b0379 100644--- a/apps/desktop/src/main/cindy-make/historyStore.ts+++ b/apps/desktop/src/main/cindy-make/historyStore.ts@@ -63,6 +63,7 @@ export class CindyMakeHistoryStore {typeof value.request !== 'string' ||!Number.isFinite(value.createdAt) ||!Number.isFinite(value.updatedAt) ||+ (value.hiddenAt !== undefined && !Number.isFinite(value.hiddenAt)) ||!Array.isArray(value.completions) ||!Array.isArray(value.receipts) ||!value.receipts.every(validFeatureReceipt) ||@@ -246,4 +247,8 @@ export class CindyMakeHistoryStore {const record = this.read(runId);if (record && !record.endedAt) this.save({ ...record, endedAt: at, updatedAt: at });}+ hide(runId: string, at = Date.now()): void {+ const record = this.read(runId);+ if (record && !record.hiddenAt) this.save({ ...record, hiddenAt: at, updatedAt: at });+ }}diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsxindex 0a1f5cf5d0..e832773202 100644--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx@@ -9,13 +9,16 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import {getDataOwnerGeneration,isDataOwnerGenerationCurrent,+ isDataOwnerPushCurrent,} from '@/contexts/dataOwnerGeneration';import { useCindyMakeState } from '@/lib/cindyMakeState';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 './cindyMakeTasks.css';+import { CindyMakeTestStep } from './CindyMakeTestStep';type Filter = 'all' | 'pending' | 'integrated' | 'ended';/** Historical facts and allowed actions come from Main; an old button cannot authorize a write. */@@ -88,7 +91,20 @@ export function CindyMakeHistoryPanel({}, [active, refresh]);useEffect(() => {if (active && !acting.current) void refresh();- }, [make, active, refresh]);+ }, [make, active, refresh, pending]);+ useEffect(() => {+ if (!active) return;+ // Completion state uses the same owner-stamped message broadcast as the task card.+ return window.electronAPI.localDb?.messages?.onCreated?.(({ message }, stamp) => {+ if (+ isDataOwnerGenerationCurrent(owner) &&+ isDataOwnerPushCurrent(stamp) &&+ message.agentMeta?.cindyMakeCompletion &&+ !acting.current+ )+ void refresh();+ });+ }, [active, owner, refresh]);useEffect(() => {if (state) onState?.(state);}, [state, onState]);@@ -107,8 +123,30 @@ export function CindyMakeHistoryPanel({item.lifecycle !== 'ended'),);const selected = visible.find((item) => item.runId === selectedId) ?? visible[0];+ const statusKey = (item: CindyMakeHistoryState['items'][number]) => {+ if (+ item.build &&+ (item.operation === 'build' ||+ (item.lifecycle === 'ready' && item.completions.at(-1)?.lastAction === 'build'))+ )+ return item.build.stopping+ ? 'cindyMake.history.stopping'+ : item.build.status === 'checking' && item.build.checkStep+ ? 'cindyMake.personal.checkStep.' + item.build.checkStep+ : 'cindyMake.personal.status.' + item.build.status;+ return item.test+ ? 'cindyMake.test.status.' + item.test.status+ : 'cindyMake.history.lifecycle.' + item.lifecycle;+ };+ const versionStatus = (item: CindyMakeHistoryState['items'][number]) =>+ item.needsBuild+ ? t('cindyMake.history.versionPending')+ : item.versions.length+ ? t('cindyMake.history.versionReady')+ : undefined;useEffect(() => {- if (selected && selected.runId !== selectedId) select(selected.runId);+ const nextId = selected?.runId ?? '';+ if (nextId !== selectedId) select(nextId);}, [selected?.runId, selectedId]);const date = (value: number) =>new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', timeStyle: 'short' }).format(@@ -125,28 +163,73 @@ export function CindyMakeHistoryPanel({if (!selected ||acting.current ||- !selected.actions.includes(action) ||+ (!selected.actions.includes(action) && !(action === 'hide' && selected.canHide)) ||!isDataOwnerGenerationCurrent(owner))return;acting.current = true;+ // A read started before this action must not restore an obsolete history row.+ request.current += 1;const actionId = ++actionGeneration.current;setPending(action);try {if (action === 'open') {- navigate('/cc-agent/' + selected.sessionId);+ const [service, { sessionsStore }] = await Promise.all([+ import('@/lib/sessionService'),+ import('@/lib/sessionsStore'),+ ]);+ if (!isDataOwnerGenerationCurrent(owner)) return;+ let session = await service.get(selected.sessionId);+ if (!isDataOwnerGenerationCurrent(owner) || session.status === 'deleted')+ throw new Error('unavailable');+ if (session.status === 'archived') {+ const restored = await service.restoreIfArchived(session.id, session);+ if (!isDataOwnerGenerationCurrent(owner) || !restored) throw new Error('unavailable');+ session = restored;+ }+ if (!isDataOwnerGenerationCurrent(owner)) return;+ sessionsStore.prependCreated(session);+ navigate('/cc-agent/' + session.id);return;}- if (action === 'end' || action === 'retry-cleanup' || action === 'revert') {+ if (+ action === 'end' ||+ action === 'retry-cleanup' ||+ action === 'revert' ||+ action === 'hide'+ ) {const accepted = await confirm({- title: t('cindyMake.history.actions.' + action),+ title: t(+ action === 'hide'+ ? 'cindyMake.history.cleanTitle'+ : 'cindyMake.history.actions.' + action,+ ),description:- t('cindyMake.history.' + (action === 'revert' ? 'revertConfirm' : 'endConfirm')) +- (action !== 'revert' && selected.integration === 'unknown'+ t(+ action === 'hide'+ ? 'cindyMake.history.cleanConfirm'+ : 'cindyMake.history.' + (action === 'revert' ? 'revertConfirm' : 'endConfirm'),+ ) ++ (action !== 'revert' && action !== 'hide' && selected.integration === 'unknown'? '\n\n' + t('settings.cindyMake.tasks.endUnknown'): ''),- confirmText: t('cindyMake.history.actions.' + action),+ confirmText: t(+ action === 'hide'+ ? 'cindyMake.history.cleanTask'+ : 'cindyMake.history.actions.' + action,+ ),cancelText: t('settings.cindyMake.create.cancel'),+ ...(action === 'hide'+ ? {+ content: (+ <ul className="list-disc space-y-2 pl-5 text-[var(--confirm-desc)]">+ <li>{t('cindyMake.history.cleanWorkspace')}</li>+ <li>{t('cindyMake.history.cleanKeep')}</li>+ </ul>+ ),+ describeContent: true,+ }+ : {}),confirmVariant: 'destructive',});if (!accepted || !isDataOwnerGenerationCurrent(owner)) return;@@ -172,9 +255,29 @@ export function CindyMakeHistoryPanel({if (session) navigate('/cc-agent/' + session);}}- } catch {+ } catch (error) {if (isDataOwnerGenerationCurrent(owner)) {- toast.error(t('cindyMake.history.actionFailed'));+ const rawReason = extractIpcError(error)?.message;+ // Electron may preserve the IpcError code on the Error object, in which+ // case the shared decoder intentionally leaves the `[CODE]` prefix in+ // the message. Main's history handler only exposes the stable reason+ // after that prefix, so normalize both IPC shapes before translating.+ const reason = rawReason?.replace(/^\[PRECONDITION_FAILED\]\s*/, '');+ const knownReason = [+ 'busy',+ 'dirty',+ 'conflict',+ 'cleanupFailed',+ 'directoryBusy',+ 'unavailable',+ ].includes(reason ?? '')+ ? reason+ : undefined;+ toast.error(+ knownReason+ ? t('settings.cindyMake.tasks.errors.' + knownReason)+ : t('cindyMake.history.actionFailed'),+ );await refresh();}} finally {@@ -184,22 +287,6 @@ export function CindyMakeHistoryPanel({}}};- 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']>) => {@@ -246,28 +333,14 @@ export function CindyMakeHistoryPanel({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="space-y-2 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,@@ -407,10 +480,10 @@ export function CindyMakeHistoryPanel({{t('cindyMake.history.loading')}</p>)}- <div className="cindy-make-tasks-layout grid min-w-0">+ <div className="cindy-make-history-layout grid min-w-0"><ularia-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"+ 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}>@@ -419,25 +492,23 @@ export function CindyMakeHistoryPanel({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',+ 'cindy-make-history-row flex w-full min-w-0 flex-col justify-center gap-0.5 rounded-lg border px-3 py-2 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">+ <span className="w-full truncate 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 className="w-full truncate text-12 text-[var(--text-secondary)]">+ {t(statusKey(item))} · {t('cindyMake.history.integration.' + item.integration)}+ {versionStatus(item) && <> · {versionStatus(item)}</>}+ </span>+ <span className="w-full truncate text-12 text-[var(--text-tertiary)]">+ {date(item.createdAt)}</span>- <span className="text-12 text-[var(--text-tertiary)]">{date(item.createdAt)}</span></button></li>))}@@ -448,16 +519,23 @@ export function CindyMakeHistoryPanel({)}</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">+ <div className="flex min-h-0 min-w-0 flex-col overflow-y-auto overscroll-contain">+ <div className="cindy-make-history-detail min-h-0 shrink-0 space-y-3 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(statusKey(selected))} ·{' '}{t('cindyMake.history.integration.' + selected.integration)}+ {versionStatus(selected) && <> · {versionStatus(selected)}</>}</p><p className="whitespace-pre-wrap break-words">{selected.request}</p>+ <CindyMakeTestStep test={selected.test} />+ {selected.test?.error && (+ <p role="alert" className="text-12 text-[var(--status-danger)]">+ {t('cindyMake.test.errors.' + selected.test.error)}+ </p>+ )}<p className="text-12 text-[var(--text-secondary)]">{t('cindyMake.history.updated', { time: date(selected.updatedAt) })}</p>@@ -496,7 +574,7 @@ export function CindyMakeHistoryPanel({)}</p>)}- {!selected.actions.length && selected.actionReason && (+ {selected.actionReason && (<p role="status" className="text-12 text-[var(--text-secondary)]">{t('cindyMake.history.noActions.' + selected.actionReason)}</p>@@ -527,7 +605,10 @@ export function CindyMakeHistoryPanel({{t('cindyMake.history.working')}</span>)}- {selected.actions.map((action) => (+ {[+ ...selected.actions.filter((action) => action !== 'end'),+ ...(selected.canHide ? (['hide'] as const) : []),+ ].map((action) => (<Buttonkey={action}variant="secondary"@@ -536,14 +617,14 @@ export function CindyMakeHistoryPanel({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,+ action === 'hide'+ ? 'cindyMake.history.cleanTask'+ : action === 'test' &&+ ['failed', 'stopped'].includes(selected.test?.status ?? '')+ ? 'cindyMake.test.retry'+ : action === 'build' && selected.build?.status === 'failed'+ ? 'cindyMake.history.actions.retryBuild'+ : 'cindyMake.history.actions.' + action,)}</Button>))}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.tsxindex 247e939677..211e4af6e7 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@@ -159,7 +159,7 @@ describe('Cindy Make history with real translations', () => {</MemoryRouter>,);expect(await screen.findByRole('heading', { name: title + ' · 1' })).toBeTruthy();- expect(screen.getByRole('button', { name: build })).toBeTruthy();+ expect(screen.queryByRole('button', { name: build })).toBeNull();expect(screen.getByRole('button', { name: integrate })).toBeTruthy();expect(screen.getByText(counts)).toBeTruthy();for (const [key, value] of strings({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.tsxindex b617aa98cc..6dbde3182f 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@@ -2,6 +2,7 @@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 { ConfirmOptions } from '@/components/ui/confirm-dialog-provider';import type {CindyMakeHistoryItem,CindyMakeHistoryState,@@ -10,11 +11,16 @@ import { CindyMakeHistoryPanel } from '../CindyMakeHistoryPanel';const h = vi.hoisted(() => ({navigate: vi.fn(),- confirm: vi.fn(async () => true),+ confirm: vi.fn<(options: ConfirmOptions) => Promise<boolean>>(async () => true),+ get: vi.fn(),+ restore: vi.fn(),+ prepend: vi.fn(),error: vi.fn(),make: {},}));vi.mock('react-router-dom', () => ({ useNavigate: () => h.navigate }));+vi.mock('@/lib/sessionService', () => ({ get: h.get, restoreIfArchived: h.restore }));+vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { prependCreated: h.prepend } }));vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),}));@@ -37,7 +43,8 @@ function item(patch: Partial<CindyMakeHistoryItem> = {}): CindyMakeHistoryItem {versions: [],lifecycle: 'ready',integration: 'unintegrated',- actions: ['continue', 'test', 'integrate', 'end'],+ actions: ['open', 'continue', 'test', 'integrate', 'end'],+ canHide: true,...patch,};}@@ -47,17 +54,33 @@ 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;+ const unsubscribe = vi.fn();vi.stubGlobal('electronAPI', {getCindyMakeHistory: read,actCindyMakeHistory: execute,generateCindyMakePersonal: build,cancelCindyMakePersonal: cancel,+ localDb: {+ messages: {+ onCreated: (callback: () => void) => {+ onMessage = callback;+ return unsubscribe;+ },+ },+ },});return {read,execute,build,cancel,+ changed: () =>+ (onMessage as any)?.({+ sessionId: items[0]?.sessionId,+ message: { agentMeta: { cindyMakeCompletion: {} } },+ }),+ unsubscribe,set: (next: CindyMakeHistoryState) => {state = next;},@@ -66,19 +89,68 @@ function harness(items = [item()]) {beforeEach(() => {setDataOwnerGeneration('history-ui-owner');vi.clearAllMocks();+ h.get.mockResolvedValue({+ id: 'task-a',+ status: 'active',+ workingDir: '/make/task-a',+ workspaceKind: 'project',+ remoteHostId: null,+ });+ h.restore.mockResolvedValue({+ id: 'task-a',+ status: 'active',+ workingDir: '/make/task-a',+ workspaceKind: 'project',+ remoteHostId: null,+ });});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([]);+ it('shares test failure, retry, live progress and exit state with the completion broadcast', async () => {+ const failed = item({ test: { status: 'failed', step: 'launching', error: 'launchFailed' } });+ const f = harness([failed]);+ const view = render(<CindyMakeHistoryPanel />);+ const retry = await screen.findByRole('button', { name: 'cindyMake.test.retry' });+ expect(screen.getByRole('alert').textContent).toBe('cindyMake.test.errors.launchFailed');+ expect(screen.getByText('cindyMake.test.failedStep')).toBeTruthy();+ expect(screen.queryByText('cindyMake.history.lifecycle.ready')).toBeNull();+ const starting = item({+ test: { status: 'starting', step: 'dependencies' },+ actions: ['open'],+ canHide: false,+ });+ f.set({ items: [starting], busy: true, canBuild: false });+ fireEvent.click(retry);+ await screen.findByText('cindyMake.test.currentStep');+ expect(f.execute).toHaveBeenCalledWith('aaaa', 'test');+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.queryByRole('button', { name: 'cindyMake.history.actions.continue' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'cindyMake.history.cleanTask' })).toBeNull();+ f.set({+ items: [item({ test: { status: 'ready' }, actions: ['open', 'continue'], canHide: false })],+ busy: true,+ canBuild: false,+ });+ act(() => f.changed());+ await screen.findByRole('button', { name: 'cindyMake.history.actions.continue' });+ expect(screen.queryByText('cindyMake.test.currentStep')).toBeNull();+ f.set({ items: [item({ test: { status: 'stopped' } })], busy: false, canBuild: true });+ act(() => f.changed());+ await screen.findByRole('button', { name: 'cindyMake.test.retry' });+ view.unmount();+ expect(f.unsubscribe).toHaveBeenCalled();+ });+ it('refreshes a task-triggered build through checking steps to failure and allows retry', async () => {+ const task = item({ integration: 'integrated', actions: ['open', 'build'], needsBuild: true });+ const f = harness([task]);render(<CindyMakeHistoryPanel />);- const build = await screen.findByRole('button', { name: 'cindyMake.history.build' });+ const build = await screen.findByRole('button', { name: 'cindyMake.history.actions.build' });await waitFor(() => expect(build.hasAttribute('disabled')).toBe(false));f.set({- items: [],+ items: [{ ...task, actions: ['open'] }],busy: true,canBuild: false,build: { status: 'checking', checkStep: 'dependencies', buildId: 'build-1' },@@ -95,7 +167,7 @@ describe('Make history controls', () => {await screen.findByText('cindyMake.personal.checkStep.' + checkStep);}f.set({- items: [],+ items: [task],busy: false,canBuild: true,build: { status: 'failed', error: 'checksFailed' },@@ -104,7 +176,7 @@ describe('Make history controls', () => {expect((await screen.findByRole('alert')).textContent).toBe('cindyMake.personal.errors.checksFailed',);- fireEvent.click(screen.getByRole('button', { name: 'cindyMake.history.build' }));+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.history.actions.build' }));await waitFor(() => expect(f.build).toHaveBeenCalledTimes(2));});it('shows the actual task build stage while removing mutation controls', async () => {@@ -117,9 +189,7 @@ describe('Make history controls', () => {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.build' })).toBeNull();expect(screen.queryByRole('button', { name: 'cindyMake.history.actions.integrate' }),).toBeNull();@@ -169,7 +239,8 @@ describe('Make history controls', () => {items: [item({integration: 'integrated',- actions: ['continue', 'test', 'end', 'revert'],+ actions: ['open', 'continue', 'test', 'build', 'end', 'revert'],+ canHide: true,needsBuild: true,}),],@@ -185,9 +256,50 @@ describe('Make history controls', () => {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.getByRole('button', { name: 'cindyMake.history.actions.open' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'cindyMake.history.actions.test' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'cindyMake.history.actions.build' })).toBeTruthy();+ expect(screen.getAllByText(/cindyMake.history.versionPending/)).toHaveLength(2);expect(screen.getByText('cindyMake.history.needsBuild')).toBeTruthy();});+ it('opens an active task and keeps it available in the sidebar', async () => {+ const f = harness([item({ actions: ['open'] })]);+ render(<CindyMakeHistoryPanel />);+ fireEvent.click(await screen.findByRole('button', { name: 'cindyMake.history.actions.open' }));+ await waitFor(() => expect(h.navigate).toHaveBeenCalledWith('/cc-agent/task-a'));+ expect(h.get).toHaveBeenCalledWith('task-a');+ expect(h.restore).not.toHaveBeenCalled();+ expect(h.prepend).toHaveBeenCalledWith(expect.objectContaining({ id: 'task-a' }));+ expect(f.execute).not.toHaveBeenCalled();+ });+ it('restores an archived task before navigating to it', async () => {+ const archived = {+ id: 'task-a',+ status: 'archived',+ workingDir: '/make/task-a',+ workspaceKind: 'project',+ remoteHostId: null,+ };+ h.get.mockResolvedValue(archived);+ let resolve!: (value: typeof archived & { status: 'active' }) => void;+ h.restore.mockImplementation(+ () =>+ new Promise((done) => {+ resolve = done;+ }),+ );+ const f = harness([item({ actions: ['open'] })]);+ render(<CindyMakeHistoryPanel />);+ fireEvent.click(await screen.findByRole('button', { name: 'cindyMake.history.actions.open' }));+ await waitFor(() => expect(h.restore).toHaveBeenCalledWith('task-a', archived));+ expect(h.navigate).not.toHaveBeenCalled();+ await act(async () => resolve({ ...archived, status: 'active' }));+ expect(h.prepend).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'task-a', status: 'active' }),+ );+ expect(h.navigate).toHaveBeenCalledWith('/cc-agent/task-a');+ expect(f.execute).not.toHaveBeenCalled();+ });it('retains finished history and exposes retained undo without edit, test, or repeated cleanup actions', async () => {harness([item({@@ -206,6 +318,8 @@ describe('Make history controls', () => {expect(screen.queryByRole('button', { name: 'cindyMake.history.actions.' + action }),).toBeNull();+ expect(screen.getByRole('button', { name: 'cindyMake.history.actions.open' })).toBeTruthy();+ expect(screen.getByRole('button', { name: 'cindyMake.history.cleanTask' })).toBeTruthy();fireEvent.click(screen.getByRole('button', { name: 'cindyMake.history.actions.revert' }));await waitFor(() =>expect(h.confirm).toHaveBeenCalledWith(@@ -229,10 +343,127 @@ describe('Make history controls', () => {const f = harness();h.confirm.mockResolvedValueOnce(false);render(<CindyMakeHistoryPanel />);- fireEvent.click(await screen.findByRole('button', { name: 'cindyMake.history.actions.end' }));+ const clean = await screen.findByRole('button', { name: 'cindyMake.history.cleanTask' });+ await act(async () => fireEvent.click(clean));await waitFor(() => expect(h.confirm).toHaveBeenCalledOnce());expect(f.execute).not.toHaveBeenCalled();expect(screen.getByRole('heading', { name: 'cindyMake.history.title · 1' })).toBeTruthy();+ const confirmation = h.confirm.mock.calls[0][0];+ expect(confirmation).toMatchObject({+ title: 'cindyMake.history.cleanTitle',+ description: 'cindyMake.history.cleanConfirm',+ confirmVariant: 'destructive',+ describeContent: true,+ });+ render(<>{confirmation.content}</>);+ expect(screen.getByText('cindyMake.history.cleanWorkspace')).toBeTruthy();+ expect(screen.getByText('cindyMake.history.cleanKeep')).toBeTruthy();+ });+ it.each([0, 1])(+ 'refreshes after cleanup with %i remaining records and ignores an older read',+ async (remaining) => {+ const next = item({ runId: 'bbbb', sessionId: 'task-b', title: 'Next task' });+ const f = harness(remaining ? [item(), next] : [item()]);+ render(<CindyMakeHistoryPanel />);+ await screen.findByRole('button', { name: /Blue background/ });+ await waitFor(() => expect(f.read).toHaveBeenLastCalledWith('aaaa'));+ let staleRead!: (value: CindyMakeHistoryState) => void;+ f.read.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ staleRead = resolve;+ }),+ );+ fireEvent(window, new Event('focus'));+ let cleaned!: (value: CindyMakeHistoryState) => void;+ f.execute.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ cleaned = resolve;+ }),+ );+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.history.cleanTask' }));+ await waitFor(() => expect(f.execute).toHaveBeenCalledWith('aaaa', 'hide'));+ f.read.mockClear();+ const fresh: CindyMakeHistoryState = {+ items: remaining ? [next] : [],+ busy: false,+ canBuild: true,+ };+ f.set(fresh);+ await act(async () =>+ cleaned({ ...fresh, items: fresh.items.map((row) => ({ ...row, actions: ['open'] })) }),+ );+ await waitFor(() => expect(f.read).toHaveBeenLastCalledWith(remaining ? 'bbbb' : undefined));+ expect(screen.queryByRole('button', { name: /Blue background/ })).toBeNull();+ expect(+ screen.getByRole('heading', { name: 'cindyMake.history.title · ' + remaining }),+ ).toBeTruthy();+ if (remaining) {+ expect(screen.getByRole('button', { name: /Next task/ }).getAttribute('aria-pressed')).toBe(+ 'true',+ );+ expect(+ await screen.findByRole('button', { name: 'cindyMake.history.actions.test' }),+ ).toBeTruthy();+ } else {+ expect(screen.getByText('settings.cindyMake.tasks.noResults')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'cindyMake.history.cleanTask' })).toBeNull();+ }+ await act(async () => staleRead({ items: [item()], busy: false, canBuild: true }));+ expect(screen.queryByRole('button', { name: /Blue background/ })).toBeNull();+ },+ );+ it('keeps a failed cleanup visible and refreshes its retry state', async () => {+ const f = harness();+ f.execute.mockImplementationOnce(async () => {+ f.set({+ items: [item({ lifecycle: 'cleanup', actions: ['open', 'retry-cleanup'] })],+ busy: false,+ canBuild: true,+ });+ throw Object.assign(new Error('[PRECONDITION_FAILED] cleanupFailed'), {+ code: 'PRECONDITION_FAILED',+ });+ });+ render(<CindyMakeHistoryPanel />);+ fireEvent.click(await screen.findByRole('button', { name: 'cindyMake.history.cleanTask' }));+ expect(+ await screen.findByRole('button', { name: 'cindyMake.history.actions.retry-cleanup' }),+ ).toBeTruthy();+ expect(h.error).toHaveBeenCalledWith('settings.cindyMake.tasks.errors.cleanupFailed');+ expect(screen.getByRole('button', { name: /Blue background/ })).toBeTruthy();+ });+ it('shows the busy cleanup reason returned by Main', async () => {+ const f = harness([item({ actions: ['open', 'end'], canHide: true })]);+ f.execute.mockRejectedValueOnce(+ Object.assign(new Error('[PRECONDITION_FAILED] busy'), { code: 'PRECONDITION_FAILED' }),+ );+ render(<CindyMakeHistoryPanel />);+ fireEvent.click(await screen.findByRole('button', { name: 'cindyMake.history.cleanTask' }));+ await waitFor(() =>+ expect(h.error).toHaveBeenCalledWith('settings.cindyMake.tasks.errors.busy'),+ );+ expect(screen.getByRole('button', { name: /Blue background/ })).toBeTruthy();+ expect(+ screen.getByRole('button', { name: 'cindyMake.history.cleanTask' }).hasAttribute('disabled'),+ ).toBe(false);+ });+ it('keeps history cleanup visible for a busy record and reports busy immediately', async () => {+ const f = harness([item({ actions: ['open'], actionReason: 'busy', canHide: true })]);+ f.execute.mockRejectedValueOnce(+ Object.assign(new Error('[PRECONDITION_FAILED] busy'), { code: 'PRECONDITION_FAILED' }),+ );+ render(<CindyMakeHistoryPanel />);+ fireEvent.click(await screen.findByRole('button', { name: 'cindyMake.history.cleanTask' }));+ await waitFor(() =>+ expect(h.error).toHaveBeenCalledWith('settings.cindyMake.tasks.errors.busy'),+ );+ });+ it('renders a busy tip when the current task has no mutation action', async () => {+ harness([item({ lifecycle: 'running', actions: ['open'], actionReason: 'busy' })]);+ render(<CindyMakeHistoryPanel />);+ expect(await screen.findByText('cindyMake.history.noActions.busy')).toBeTruthy();});it('does not replace a switched owner’s history with an older in-flight result', async () => {const f = harness();diff --git a/apps/desktop/src/renderer/components/cindy-make/cindyMakeTasks.css b/apps/desktop/src/renderer/components/cindy-make/cindyMakeTasks.cssindex a97e01d18e..3ddfa81cae 100644--- a/apps/desktop/src/renderer/components/cindy-make/cindyMakeTasks.css+++ b/apps/desktop/src/renderer/components/cindy-make/cindyMakeTasks.css@@ -2,6 +2,20 @@container-type: inline-size;}+.cindy-make-history-layout {+ /* Five 80px entries, four 4px gaps, and 16px list padding. */+ height: 432px;+ grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);+}++.cindy-make-history-layout:not(:has(> div)) {+ grid-template-rows: minmax(0, 1fr);+}++.cindy-make-history-row {+ height: 80px;+}+@container (min-width: 560px) {.cindy-make-tasks-search {width: 224px;@@ -16,4 +30,20 @@border-bottom-width: 0;border-right-width: 1px;}++ .cindy-make-history-layout {+ grid-template-columns: minmax(180px, 2fr) minmax(0, 3fr);+ grid-template-rows: minmax(0, 1fr);+ }++ .cindy-make-history-list {+ border-bottom-width: 0;+ border-right-width: 1px;+ }++ .cindy-make-history-detail {+ flex: 1 1 0%;+ overflow-y: auto;+ overscroll-behavior: contain;+ }}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex c5a4daea18..e69fce6097 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -13047,6 +13047,8 @@"openInstaller": "Show installer","updated": "Updated {{time}}","needsBuild": "The source has changed. Generate a personal version to use these changes.",+ "versionReady": "Personal version generated",+ "versionPending": "Personal version pending","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.",@@ -13055,6 +13057,12 @@"files": "{{count}} files changed","working": "Working…","endAndClean": "End and clean up",+ "clean": "Hide history",+ "cleanTask": "Clean task",+ "cleanTitle": "Clean up this task?",+ "cleanConfirm": "This entry will be hidden from Make history and the session will be archived. Conversation history will be kept.",+ "cleanWorkspace": "Any remaining task branch and worktree will be removed. Uncommitted changes will be lost.",+ "cleanKeep": "Changes already integrated into your personal version and generated app versions will be kept.","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": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 8096e0fed6..13570f7ab9 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -13030,6 +13030,8 @@"openInstaller": "インストーラーを表示","updated": "更新日時:{{time}}","needsBuild": "ソースが変更されています。個人版を生成すると変更を使えます。",+ "versionReady": "個人版を生成済み",+ "versionPending": "個人版の生成待ち","built": "{{time}} に生成した個人版に含まれています","builtKnown": "生成済みの個人版に含まれています","conflict": "変更が競合しています。解決用タスクを開いて続行してください。",@@ -13038,6 +13040,12 @@"files": "{{count}} ファイルを変更","working": "処理中…","endAndClean": "終了してクリーンアップ",+ "clean": "履歴を非表示",+ "cleanTask": "タスクを整理",+ "cleanTitle": "このセッションをクリーンアップしますか?",+ "cleanConfirm": "この記録を制作履歴から非表示にし、セッションをアーカイブします。会話履歴は保持されます。",+ "cleanWorkspace": "残っている制作ブランチと作業ディレクトリを削除します。未コミットの変更は失われます。",+ "cleanKeep": "個人版に取り込まれた変更と生成済みのアプリバージョンは保持されます。","endConfirm": "この制作を終了し、作業ディレクトリを削除しますか?制作履歴と保存済みの変更は保持されます。","revertConfirm": "この制作から個人ソースに取り込んだ変更を取り消しますか?他の制作と生成済みアプリは保持されます。","lifecycle": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 905d12015d..386eb22864 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -13030,6 +13030,8 @@"openInstaller": "설치 파일 보기","updated": "업데이트: {{time}}","needsBuild": "소스가 변경되었습니다. 개인 버전을 생성하면 변경 사항을 사용할 수 있습니다.",+ "versionReady": "개인 버전 생성됨",+ "versionPending": "개인 버전 생성 대기","built": "{{time}}에 생성한 개인 버전에 포함됨","builtKnown": "생성된 개인 버전에 포함됨","conflict": "변경 사항이 충돌합니다. 해결 작업을 열어 계속해 주세요.",@@ -13038,6 +13040,12 @@"files": "파일 {{count}}개 변경","working": "처리 중…","endAndClean": "종료 및 정리",+ "clean": "기록 숨기기",+ "cleanTask": "작업 정리",+ "cleanTitle": "이 세션을 정리할까요?",+ "cleanConfirm": "이 기록은 제작 기록 목록에서 숨겨지고 세션은 보관됩니다. 대화 기록은 유지됩니다.",+ "cleanWorkspace": "남아 있는 제작 브랜치와 작업 폴더를 삭제합니다. 커밋하지 않은 변경 사항은 사라집니다.",+ "cleanKeep": "개인 버전에 반영된 변경 사항과 생성된 앱 버전은 유지됩니다.","endConfirm": "이 제작을 종료하고 작업 폴더를 정리할까요? 제작 기록과 저장된 변경 사항은 유지됩니다.","revertConfirm": "이 제작에서 개인 소스에 반영한 변경 사항을 취소할까요? 다른 제작과 생성된 앱은 유지됩니다.","lifecycle": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 5f5d8e7554..9c364b46d0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -13030,6 +13030,8 @@"openInstaller": "查看安装包","updated": "更新于 {{time}}","needsBuild": "源码已有改动,生成个人版后即可使用。",+ "versionReady": "已生成个人版",+ "versionPending": "待生成个人版","built": "已包含在 {{time}} 生成的个人版中","builtKnown": "已包含在生成的个人版中","conflict": "改动存在冲突,请打开处理任务继续。",@@ -13038,6 +13040,12 @@"files": "改动 {{count}} 个文件","working": "正在处理…","endAndClean": "结束并清理",+ "clean": "清理历史",+ "cleanTask": "清理任务",+ "cleanTitle": "清理这条任务?",+ "cleanConfirm": "这条记录将从制作历史中隐藏,任务会归档,对话记录保留。",+ "cleanWorkspace": "删除仍存在的制作分支和工作目录,其中未提交的改动将丢失。",+ "cleanKeep": "保留已合入个人版的改动和已生成的应用版本。","endConfirm": "结束这次制作并清理工作目录?制作历史与已保存的改动会保留。","revertConfirm": "撤销这次制作合入个人源码的改动?其他制作和已生成的应用会保留。","lifecycle": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex ae3f1322bc..38bc1e5fbc 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -13030,6 +13030,8 @@"openInstaller": "查看安裝程式","updated": "更新於 {{time}}","needsBuild": "原始碼已有改動,產生個人版後即可使用。",+ "versionReady": "已產生個人版",+ "versionPending": "待產生個人版","built": "已包含在 {{time}} 產生的個人版中","builtKnown": "已包含在產生的個人版中","conflict": "改動存在衝突,請開啟處理任務繼續。",@@ -13038,6 +13040,12 @@"files": "改動 {{count}} 個檔案","working": "正在處理…","endAndClean": "結束並清理",+ "clean": "隱藏歷史",+ "cleanTask": "清理任務",+ "cleanTitle": "要清理這筆任務嗎?",+ "cleanConfirm": "這筆記錄將從製作歷史中隱藏,任務會封存,對話記錄保留。",+ "cleanWorkspace": "刪除仍存在的製作分支和工作目錄,其中尚未提交的改動將會遺失。",+ "cleanKeep": "保留已合入個人版的改動和已產生的應用程式版本。","endConfirm": "結束這次製作並清理工作目錄?製作歷史與已儲存的改動會保留。","revertConfirm": "撤銷這次製作合入個人原始碼的改動?其他製作和已產生的應用程式會保留。","lifecycle": {diff --git a/apps/desktop/src/shared/cindyMakeHistory.ts b/apps/desktop/src/shared/cindyMakeHistory.tsindex 1c1b25beaf..0eba8f2c37 100644--- a/apps/desktop/src/shared/cindyMakeHistory.ts+++ b/apps/desktop/src/shared/cindyMakeHistory.ts@@ -1,4 +1,8 @@-import type { CindyMakeCompletionMeta, CindyMakePersonalBuildState } from './cindyMakeSession';+import type {+ CindyMakeCompletionMeta,+ CindyMakePersonalBuildState,+ CindyMakeTestState,+} from './cindyMakeSession';export type MakeFeatureAction = 'integrate' | 'revert' | 'reapply';export interface MakeFeatureReceipt {@@ -30,6 +34,8 @@ export interface CindyMakeHistoryRecord {createdAt: number;updatedAt: number;endedAt?: number;+ /** User dismissed this record from Settings; durable facts remain for builds and undo. */+ hiddenAt?: number;completions: MakeHistoryCompletion[];receipts: MakeFeatureReceipt[];versions: MakeHistoryVersion[];@@ -44,7 +50,8 @@ export type MakeHistoryAction =| 'build'| 'end'| 'retry-prepare'- | 'retry-cleanup';+ | 'retry-cleanup'+ | 'hide';export type MakeHistoryLifecycle ='preparing' | 'running' | 'editing' | 'ready' | 'failed' | 'ended' | 'cleanup';export type MakeHistoryIntegration =@@ -68,8 +75,12 @@ export interface CindyMakeHistoryItem extends CindyMakeHistoryRecord {operationError?: string;needsBuild?: boolean;build?: CindyMakePersonalBuildState;+ /** The current completion card's test receipt, reconciled by the same Main controller. */+ test?: CindyMakeTestState;/** Why the action area is empty; derived from Main facts, never guessed by Renderer. */actionReason?: MakeHistoryActionReason;+ /** Main-owned permission to hide this entry after its workspace is reclaimed. */+ canHide?: boolean;}export interface CindyMakeHistoryState {items: CindyMakeHistoryItem[];@@ -99,9 +110,33 @@ export function makeHistoryActions(facts: {needsBuild?: boolean;buildSourceAvailable?: boolean;canEdit?: boolean;+ /** A different task owns the global project lock, but this task can still be ended safely. */+ allowCleanupWhileBusy?: boolean;+ /** Use the completion controller's receipt for admission as well as presentation. */+ test?: CindyMakeTestState;}): MakeHistoryAction[] {const actions: MakeHistoryAction[] = facts.sessionAvailable ? ['open'] : [];- if (facts.busy) return actions;+ 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.+ if (facts.test?.status === 'ready')+ return facts.completed &&+ facts.sessionAvailable &&+ facts.workspaceAvailable &&+ facts.lifecycle === 'ready' &&+ !facts.conflict+ ? [...actions, 'continue']+ : actions;+ if (facts.busy) {+ if (!facts.allowCleanupWhileBusy) return actions;+ if (facts.conflict || facts.lifecycle === 'preparing' || facts.lifecycle === 'running')+ return actions;+ if (facts.lifecycle === 'cleanup') return [...actions, 'retry-cleanup'];+ if (facts.lifecycle === 'ended' || !facts.sessionAvailable) return actions;+ if (facts.integration === 'unknown' && !(facts.sourceAvailable || !facts.workspaceAvailable))+ return actions;+ return [...actions, 'end'];+ }if (facts.recoverableFailure) return [...actions, 'retry'];if ((facts.buildFailed || facts.needsBuild) &&@@ -121,7 +156,6 @@ export function makeHistoryActions(facts: {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');}diff --git a/docs/cindy-make-upstream.md b/docs/cindy-make-upstream.mdindex ee40dbd6e1..253f11990c 100644--- a/docs/cindy-make-upstream.md+++ b/docs/cindy-make-upstream.md@@ -138,6 +138,8 @@ rebase 到新官方基线(禁止 update-refs 自动改动其他任务分支)运行资源及编译启动。启动期间禁用“继续修改”,Main 同样拒绝此操作;启动完成或失败后恢复。失败保留中断步骤和已知错误原因,提供“重试启动”,重试清除上次错误与步骤。步骤只记录白名单标识,不保存或展示终端原始输出;旧源码仍从固定阶段前缀读取粗粒度进度。+ 设置页历史直接投影同一完成记录的测试状态、步骤与错误,复用任务卡的消息推送和+ Main 启动控制器的重启恢复;失败显示同一重试入口,启动中不开放修改或清理。本机主日志的 `cindy-make-test` 记录任务/完成记录标识、阶段、耗时、退出码及白名单启动器失败码;失败标记后的跨块 `code=` 也会保留,不记录原始输出、环境或自由文本错误。见 [启动控制器](../apps/desktop/src/main/cindy-make/testController.ts) 和@@ -196,7 +198,10 @@ rebase 到新官方基线(禁止 update-refs 自动改动其他任务分支)[versionService](../apps/desktop/src/main/cindy-make/versionService.ts) 和[版本切换回归](../apps/desktop/src/main/cindy-make/__tests__/versionStartup.test.ts)。- 失败或取消时不发送需求;显式重试复用原任务和分支。取消单个任务不会取消共享的- 环境/源码准备;全局准备的停止入口仍在 Settings。重复点击、打开已有任务不会再次派发。+ 环境/源码准备;历史页重试由 Main 恢复原记录中的来源身份,显式冲突的身份仍拒绝。+ 全局准备的停止入口仍在 Settings。重复点击、打开已有任务不会再次派发。+ 准备与清理的实际执行完全结束后释放忙碌状态;保留的完成、失败、取消记录不阻止合入、+ 生成或版本切换,但取消后的进程收尾与最终持久化完成前仍保持占用。- 应用进程重启不静默重放请求。未完成的持久准备卡按已中断显示,用户可显式重试;不能仅凭已保存的用户消息推断 Agent 已成功执行。已确认完成的准备不会再次自动派发。清空任务立即取消本任务准备并使旧请求、旧卡片失效;清空前排队的首次请求不得再发送。@@ -215,9 +220,14 @@ rebase 到新官方基线(禁止 update-refs 自动改动其他任务分支)- 历史按当前数据 owner 持久化在源码目录之外,清理单个工作目录不会删除历史。老任务从准备卡、完成事实与实际 Git 合入提交核验回填;缺少证据时不伪造撤销依据。选中记录时核验源码、完成快照与保留的 Git 对象;Main 在操作入场再检查一次。- 当前正在制作只提供查看,完成后提供继续修改、隔离测试与合入;已合入不重复显示合入,+ 可以安全清理的历史记录提供“清理任务”入口;它只隐藏该条列表并沿用 Main 的任务清理管线,保留归档交流、+ 已合入提交和可撤销回执。当前正在制作的内容变更只提供查看,完成后提供继续修改、隔离测试与合入;已合入不重复显示合入,有新一轮修改后再提供合入,已撤销才提供重新合入。冲突和普通失败分别提供解决、重试。- 已结束不再显示编辑、测试和重复清理,但有效的合入记录仍可撤销。所有按钮复用统一边框。+ 已结束不再显示编辑、测试和重复的“结束制作”,但仍可隐藏历史;有效的合入记录仍可撤销。+ 所有按钮复用统一边框。+ Main 区分全局忙碌与目标任务忙碌:当前任务仍在准备、运行、测试、冲突处理或清理时,清理请求+ 立即返回 busy,详情保留原因提示;另一个任务占用项目资源时,空闲历史任务仍保留结束/重试清理,+ 请求进入同一项目队列,不因全局状态误隐藏清理入口。- 合入、撤销与重新合入共用已有项目互斥及独立冲突任务生命周期。首次正常合入保留功能分支的真实 merge;后续增量与撤销保存实际采纳前后的文件树。撤销逆序应用该制作尚有效的全部合入差异,并创建新的提交;重新合入反向应用那次撤销的实际差异。依赖冲突留在隔离@@ -245,6 +255,9 @@ rebase 到新官方基线(禁止 update-refs 自动改动其他任务分支)清理关联的制作目录。保留的合入提交和文件树使结束后仍能撤销;如果用户另行清空整个托管源码仓库,历史继续可看,但缺失 Git 对象的动作不再提供。清理失败不标记完成,cell 保留失败状态,操作区提供原因和「重试清理」;重试也必须弹窗确认。+ 目标任务仍在运行或其目录被测试/其它清理占用时,Main 不排队删除,直接返回 busy,+ 页面显示“任务仍在运行或目录正在使用”的提示;全局项目队列被其它任务占用时,目标任务若自身空闲,+ 仍可结束并清理。兼容旧版已删除任务的清理重试,不恢复已删除的交流记录,也不提供恢复入口。只操作从合法 runId 派生且由该个人项目 Git 注册的目录,拒绝符号链接/junction 替换、仍在使用的目录和账号切换后的旧操作。清理成功后才持久化完成标记。