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): 个人版保存到 GitHub、单一「同步」与提交给官方 (#5343)

Lizie3141a2101a8
diff --git a/apps/desktop/src/main/__tests__/cindyMakeGithubIpc.test.ts b/apps/desktop/src/main/__tests__/cindyMakeGithubIpc.test.ts
new file mode 100644
index 0000000000..226e9ac83e
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/cindyMakeGithubIpc.test.ts
@@ -0,0 +1,85 @@
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { assertCindyMakeEnabled } from '../cindy-make/featureGate';
+
+const feature = vi.hoisted(() => ({ enabled: false }));
+vi.mock('@cindy/maker-shared/cindy-make-feature', () => ({
+ get CINDY_MAKE_ENABLED() {
+ return feature.enabled;
+ },
+}));
+
+const channels = [
+ 'app:cindy-make-personal-remote',
+ 'app:cindy-make-sync',
+ 'app:cindy-make-contribution',
+];
+const source = ts.createSourceFile(
+ 'bootstrap-electron.ts',
+ readFileSync(new URL('../bootstrap-electron.ts', import.meta.url), 'utf8'),
+ ts.ScriptTarget.ES2022,
+ true,
+);
+// Run the production callbacks without starting Electron or a GitHub controller.
+const registrations: string[] = [];
+function visit(node: ts.Node): void {
+ if (ts.isCallExpression(node) && node.expression.getText(source) === 'ipcMain.handle') {
+ const channel = node.arguments[0];
+ if (channel && ts.isStringLiteral(channel) && channels.includes(channel.text))
+ registrations.push(node.getText(source));
+ }
+ ts.forEachChild(node, visit);
+}
+visit(source);
+const compiled = ts.transpileModule(registrations.join(';\n'), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+}).outputText;
+
+function harness() {
+ const handlers = new Map<string, (event: unknown, request: unknown) => Promise<unknown>>();
+ const act = vi.fn(async (request: unknown) => request);
+ const deps = {
+ ipcMain: {
+ handle: (channel: string, handler: (event: unknown, request: unknown) => Promise<unknown>) =>
+ handlers.set(channel, handler),
+ },
+ assertTrustedAppRendererEvent: (event: unknown) => {
+ if (event !== 'trusted') throw new Error('untrusted');
+ },
+ assertCindyMakeEnabled,
+ actPersonalRemote: act,
+ actPersonalSync: act,
+ actCindyMakeContribution: act,
+ };
+ new Function(...Object.keys(deps), compiled)(...Object.values(deps));
+ expect([...handlers.keys()]).toEqual(channels);
+ return { handlers, act };
+}
+
+describe('Cindy Make GitHub IPC gates', () => {
+ beforeEach(() => {
+ feature.enabled = false;
+ });
+
+ it.each(channels)('rejects %s before any action when Make is disabled', async (channel) => {
+ const { handlers, act } = harness();
+ await expect(handlers.get(channel)!('trusted', { type: 'write' })).rejects.toMatchObject({
+ code: 'UNSUPPORTED_CAPABILITY',
+ });
+ expect(act).not.toHaveBeenCalled();
+ });
+
+ it.each(channels)(
+ 'only dispatches %s from a trusted renderer with Make enabled',
+ async (channel) => {
+ feature.enabled = true;
+ const { handlers, act } = harness();
+ const request = { type: 'write' };
+ await expect(handlers.get(channel)!('untrusted', request)).rejects.toThrow('untrusted');
+ expect(act).not.toHaveBeenCalled();
+ await expect(handlers.get(channel)!('trusted', request)).resolves.toBe(request);
+ expect(act).toHaveBeenCalledExactlyOnceWith(request);
+ },
+ );
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b7f0be0003..9c055ec17d 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -17,6 +17,12 @@ import {
actUpstreamMerge,
refreshUpstreamMergeProjection,
} from './cindy-make/upstreamMergeRuntime.js';
+import {
+ configurePersonalRemote,
+ actPersonalRemote,
+ actCindyMakeContribution,
+} from './cindy-make/personalRemoteRuntime.js';
+import { configurePersonalSync, actPersonalSync } from './cindy-make/personalSyncRuntime.js';
import {
configureMakeHistory,
getCindyMakeHistory,
@@ -7541,6 +7547,38 @@ const registerIpcHandlers = () => {
assertCindyMakeEnabled();
return actUpstreamMerge(input);
});
+ // Local Settings only: binding this machine's GitHub fork has no device-link grant.
+ // A failure here must not prevent the remaining IPC handlers from registering.
+ try {
+ configurePersonalRemote();
+ } catch (error) {
+ createLogger('cindy-make').warn('personal remote unavailable', {
+ error: error instanceof Error ? error.name : 'unknown',
+ });
+ }
+ ipcMain.handle('app:cindy-make-personal-remote', async (event, action: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ assertCindyMakeEnabled();
+ return actPersonalRemote(action);
+ });
+ // One Sync for every personal version; local Settings only, no device-link grant.
+ try {
+ configurePersonalSync();
+ } catch (error) {
+ createLogger('cindy-make').warn('personal sync unavailable', {
+ error: error instanceof Error ? error.name : 'unknown',
+ });
+ }
+ ipcMain.handle('app:cindy-make-sync', async (event, request: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ assertCindyMakeEnabled();
+ return actPersonalSync(request);
+ });
+ ipcMain.handle('app:cindy-make-contribution', async (event, request: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ assertCindyMakeEnabled();
+ return actCindyMakeContribution(request);
+ });
ipcMain.handle('app:get-cindy-make-source-status', async (event) => {
assertTrustedAppRendererEvent(event);
assertCindyMakeEnabled();
diff --git a/apps/desktop/src/main/cindy-make/__tests__/buildRollback.test.ts b/apps/desktop/src/main/cindy-make/__tests__/buildRollback.test.ts
index ddf8c609d3..e2c60d1a70 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/buildRollback.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/buildRollback.test.ts
@@ -1,8 +1,19 @@
import os from 'node:os';
import path from 'node:path';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { afterEach, expect, it, vi } from 'vitest';
-import { historyBuildRollback, rollbackUnbuiltHistory } from '../buildRollback';
+import {
+ hasUnbuiltPersonalChanges,
+ historyBuildRollback,
+ restoreBuildSource,
+ rollbackUnbuiltHistory,
+} from '../buildRollback';
+import {
+ hasPendingBuild,
+ initializePendingBuilds,
+ readPendingBuilds,
+ recordPendingBuild,
+} from '../pendingBuild';
import { CindyMakeHistoryStore } from '../historyStore';
import type { MakeFeatureReceipt } from '../../../shared/cindyMakeHistory';
import type { ContentGit } from '../sourceContent';
@@ -21,6 +32,7 @@ afterEach(() => {
function fixture() {
const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-build-rollback-'));
roots.push(root);
+ initializePendingBuilds(root);
const store = new CindyMakeHistoryStore(root);
let head = { commit: 'a'.repeat(40), tree: '1'.repeat(40) };
let dirty = false;
@@ -64,7 +76,7 @@ function fixture() {
return receipt;
};
const rollback = (isPublishedCommit?: (commit: string) => boolean) =>
- historyBuildRollback(store, root, isPublishedCommit).prepareRollback(head, git);
+ historyBuildRollback(store, root, isPublishedCommit, root).prepareRollback(head, git);
return {
store,
git,
@@ -82,6 +94,60 @@ function fixture() {
};
}
+it('a rollback drops the undone snapshots from the pending record as the source leaves them', async () => {
+ const h = fixture();
+ const saved = h.integrate('first', 'saved', 'b', '2');
+ h.store.version('first', { operationId: saved.id, commit: saved.commit });
+ recordPendingBuild(h.root, { commit: saved.commit, tree: saved.tree });
+ const undone = h.integrate('first', 'next-round', 'c', '3');
+ recordPendingBuild(h.root, { commit: undone.commit, tree: undone.tree });
+ await rollbackUnbuiltHistory(h.store, h.root, h.git, () => false, h.root);
+ expect(h.head()).toEqual({ commit: saved.commit, tree: saved.tree });
+ // The undone snapshot left the source: its fact is gone with it; the restored
+ // one keeps its own (it is still not generated here).
+ expect(readPendingBuilds(h.root)).toEqual([{ commit: saved.commit, tree: saved.tree }]);
+});
+
+it('a restore that finds the source already restored still drops the stale fact', async () => {
+ const h = fixture();
+ const stale = { commit: 'c'.repeat(40), tree: '3'.repeat(40) };
+ recordPendingBuild(h.root, stale);
+ await restoreBuildSource(h.git, h.root, h.head(), stale, h.root);
+ expect(readPendingBuilds(h.root)).toEqual([]);
+});
+
+it('a failed generation cannot clear unknown pending work belonging to another account', async () => {
+ const h = fixture();
+ const earlier = h.head();
+ h.integrate('current-owner-task', 'new-work', 'b', '2');
+ writeFileSync(path.join(h.root, 'pending-build.json'), 'broken');
+ await rollbackUnbuiltHistory(h.store, h.root, h.git, () => false, h.root);
+ expect(h.head()).toEqual(earlier);
+ expect(h.store.read('current-owner-task')?.receipts).toEqual([]);
+ expect(readPendingBuilds(h.root)).toBeUndefined();
+ expect(hasUnbuiltPersonalChanges(h.store, h.root, earlier, () => false)).toBe(true);
+ expect(
+ hasUnbuiltPersonalChanges(h.store, h.root, earlier, (commit) => commit === earlier.commit),
+ ).toBe(false);
+});
+
+it('a restore that refuses to touch changed source keeps the fact', async () => {
+ const h = fixture();
+ const receipt = h.integrate('task', 'operation', 'b', '2');
+ recordPendingBuild(h.root, { commit: receipt.commit, tree: receipt.tree });
+ h.dirty();
+ await expect(
+ restoreBuildSource(
+ h.git,
+ h.root,
+ { commit: receipt.baselineCommit, tree: receipt.beforeTree },
+ receipt,
+ h.root,
+ ),
+ ).rejects.toThrow('Personal source changed');
+ expect(hasPendingBuild(h.root, { commit: receipt.commit, tree: receipt.tree })).toBe(true);
+});
+
it('withdraws consecutive unpublished integrations but keeps the last generated source and task records', async () => {
const h = fixture();
const saved = h.integrate('first', 'saved', 'b', '2');
diff --git a/apps/desktop/src/main/cindy-make/__tests__/installScriptsTrust.test.ts b/apps/desktop/src/main/cindy-make/__tests__/installScriptsTrust.test.ts
new file mode 100644
index 0000000000..166c8214ce
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/installScriptsTrust.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ remoteContentScriptsUnverified,
+ type InstallScriptsTrust,
+} from '../installScriptsTrust';
+
+const A = 'a'.repeat(40);
+const B = 'b'.repeat(40);
+const TIP = 'c'.repeat(40);
+const FROM = 'd'.repeat(40);
+const REWRITTEN = 'e'.repeat(40);
+
+function trust(
+ overrides: Partial<InstallScriptsTrust> & { ancestry?: Array<[string, string]> } = {},
+): InstallScriptsTrust {
+ const ancestry = new Set((overrides.ancestry ?? []).map(([a, b]) => `${a}>${b}`));
+ return {
+ unverifiedRemote: overrides.unverifiedRemote ?? (() => []),
+ unverifiedRemoteOverflow: overrides.unverifiedRemoteOverflow,
+ rewrites: overrides.rewrites ?? (() => []),
+ published: overrides.published ?? (() => []),
+ contains: overrides.contains ?? (async (a, b) => a === b || ancestry.has(`${a}>${b}`)),
+ };
+}
+
+describe('remoteContentScriptsUnverified', () => {
+ it('runs the scripts of this computer’s own content', async () => {
+ await expect(remoteContentScriptsUnverified(A, trust())).resolves.toBe(false);
+ });
+
+ it('skips the scripts while a taken-over fork tip is not verified', async () => {
+ await expect(
+ remoteContentScriptsUnverified(A, {
+ ...trust({ ancestry: [[TIP, A]] }),
+ unverifiedRemote: () => [TIP],
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it('stays guarded when the trust ledger records an overflow', async () => {
+ await expect(
+ remoteContentScriptsUnverified(A, {
+ ...trust(),
+ unverifiedRemoteOverflow: () => true,
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it.each(['exact', 'descendant', 'rewrite'] as const)(
+ 'allows an overflowed ledger only when a published version covers the whole task base: %s',
+ async (coverage) => {
+ const facts = trust({
+ unverifiedRemoteOverflow: () => true,
+ published: () => [coverage === 'exact' ? A : B],
+ ancestry: coverage === 'descendant' ? [[A, B]] : [[REWRITTEN, B]],
+ rewrites: () => coverage === 'rewrite' ? [{ from: [A], to: REWRITTEN }] : [],
+ });
+ await expect(remoteContentScriptsUnverified(A, facts)).resolves.toBe(false);
+ // The persistent overflow is not cleared: a different, uncovered task base
+ // must still skip scripts, even after that generation.
+ await expect(remoteContentScriptsUnverified(TIP, facts)).resolves.toBe(true);
+ expect(facts.unverifiedRemoteOverflow?.()).toBe(true);
+ },
+ );
+
+ it('does not use an earlier or invalid published commit to settle an overflow', async () => {
+ await expect(remoteContentScriptsUnverified(A, trust({
+ unverifiedRemoteOverflow: () => true,
+ published: () => [B, 'invalid'],
+ ancestry: [[B, A]],
+ }))).resolves.toBe(true);
+ });
+
+ it('does not settle an overflow when published coverage cannot be read', async () => {
+ await expect(remoteContentScriptsUnverified(A, trust({
+ unverifiedRemoteOverflow: () => true,
+ published: () => [B],
+ contains: async () => { throw new Error('git failed'); },
+ }))).rejects.toThrow('git failed');
+ });
+
+ it('runs the scripts again once a generated personal version covers the tip', async () => {
+ await expect(
+ remoteContentScriptsUnverified(A, {
+ ...trust({ ancestry: [[TIP, A], [TIP, B]] }),
+ unverifiedRemote: () => [TIP],
+ published: () => [B],
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it('does not block on fork tips this task does not contain', async () => {
+ await expect(
+ remoteContentScriptsUnverified(A, {
+ ...trust(),
+ unverifiedRemote: () => [TIP],
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it('keeps the provenance across an adopted rewrite of the taken-over content', async () => {
+ // An official update rebased the personal commits: the content survives under
+ // new hashes, and the unverified tip travels through the rewrite record.
+ const rewritten = {
+ ...trust({ ancestry: [[TIP, FROM], [REWRITTEN, A]] }),
+ unverifiedRemote: () => [TIP],
+ rewrites: () => [{ from: [FROM], to: REWRITTEN }],
+ };
+ await expect(remoteContentScriptsUnverified(A, rewritten)).resolves.toBe(true);
+ // A version published from somewhere else does not verify the rewritten content…
+ await expect(
+ remoteContentScriptsUnverified(A, { ...rewritten, published: () => [B] }),
+ ).resolves.toBe(true);
+ // …but a generated personal version that covers it does.
+ await expect(
+ remoteContentScriptsUnverified(A, {
+ ...rewritten,
+ published: () => [B],
+ contains: async (a, b) =>
+ new Set([`${TIP}>${FROM}`, `${REWRITTEN}>${B}`]).has(`${a}>${b}`),
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it('decides conservatively for an unreadable base commit', async () => {
+ await expect(remoteContentScriptsUnverified('not-a-commit', trust())).resolves.toBe(true);
+ });
+
+ it('surfaces Git failures so the caller can skip the scripts', async () => {
+ await expect(
+ remoteContentScriptsUnverified(A, {
+ ...trust(),
+ unverifiedRemote: () => [TIP],
+ contains: async () => {
+ throw Object.assign(new Error('git failed'), { exitCode: 128 });
+ },
+ }),
+ ).rejects.toThrow('git failed');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/keepChanges.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/keepChanges.git-integration.test.ts
new file mode 100644
index 0000000000..fcba2b3f8b
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/keepChanges.git-integration.test.ts
@@ -0,0 +1,834 @@
+import os from 'node:os';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { expect, it } from 'vitest';
+import {
+ applyUpstreamMerge,
+ mergeWorktree,
+ preparePersonalCombine,
+ prepareUpstreamMerge,
+ uncarriedChanges,
+ type MergeGit,
+} from '../upstreamMerge';
+import { PERSONAL_TRACKING_REF } from '../personalRemote';
+import { PERSONAL_UPSTREAM_REF } from '../sourceContent';
+import { makeSourceCheckoutPath } from '../sourcePaths';
+import { runSourceGit } from '../sourceGit';
+import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
+
+/**
+ * Neither an official update nor a combine may lose a personal change unnoticed:
+ * every replayed change must be in the adopted result, or the user decides.
+ */
+const LINES = ['1', '2', '3', '4', '5', '6', '7', '8'];
+const text = (lines: string[]) => lines.join('\n') + '\n';
+const replace = (index: number, value: string, lines = LINES) =>
+ lines.map((line, at) => (at === index ? value : line));
+
+async function repos(initialLines = LINES) {
+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-keep-changes-'));
+ const source = makeSourceCheckoutPath(userData);
+ const official = path.join(userData, 'official');
+ const env = {
+ PATH: process.env.PATH,
+ SystemRoot: process.env.SystemRoot,
+ GIT_CONFIG_GLOBAL: path.join(userData, 'gitconfig'),
+ GIT_CONFIG_NOSYSTEM: '1',
+ };
+ const git: MergeGit = (args, cwd, indexFile) =>
+ runSourceGit(
+ { ...env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args.map((arg) => (arg === 'https://github.com/makecindy/cindy.git' ? official : arg)),
+ cwd,
+ AbortSignal.timeout(30_000),
+ );
+ const identity = (task: boolean) => [
+ '-c',
+ `user.name=${task ? 'Cindy Make' : 'Test'}`,
+ '-c',
+ `user.email=${task ? '[email protected]' : '[email protected]'}`,
+ '-c',
+ 'commit.gpgSign=false',
+ '-c',
+ 'core.editor=true',
+ ];
+ /** Task commits share one identity and message, like real ones; `at` keeps them apart. */
+ const commit = async (cwd: string, message: string, at?: number) => {
+ await git(['add', '-A'], cwd);
+ const task = at !== undefined;
+ const date = task ? [`--date=${1_700_000_000 + at} +0000`] : [];
+ await git(
+ [...identity(task), 'commit', '-s', ...date, '-m', task ? 'Cindy Make: complete personal change' : message],
+ cwd,
+ );
+ return (await git(['rev-parse', 'HEAD'], cwd)).trim();
+ };
+ const write = (cwd: string, file: string, lines: string[]) =>
+ writeFile(path.join(cwd, file), text(lines));
+ const clean = () => rm(userData, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
+ await writeFile(env.GIT_CONFIG_GLOBAL, '');
+ await mkdir(official);
+ await mkdir(path.dirname(source), { recursive: true });
+ await git(['init', '--initial-branch=main'], official);
+ await write(official, 'feature.txt', initialLines);
+ // A binary file in the base: binary changes have no lines to compare later.
+ await writeFile(path.join(official, 'logo.bin'), Buffer.from([0x00, 0x41, 0x00]));
+ const base = await commit(official, 'official base');
+ await git(['clone', official, source], userData);
+ await git(['checkout', '-b', 'cindy-personal'], source);
+ await git(['update-ref', PERSONAL_UPSTREAM_REF, base], source);
+ return { userData, source, official, git, identity, commit, write, clean, base };
+}
+type Repos = Awaited<ReturnType<typeof repos>>;
+
+const update = (h: Repos, upstreamCommit: string): CindyMakeMergeState => ({
+ id: randomUUID(),
+ status: 'fetching',
+ ref: 'v2',
+ upstreamCommit,
+});
+
+/** What a resolver does when it gives up a conflicting change instead of combining it. */
+const skip = (h: Repos, state: CindyMakeMergeState) =>
+ h.git([...h.identity(true), 'rebase', '--skip'], mergeWorktree(h.userData, state.id));
+
+it('names a personal change an official update dropped, and adopts only on the user’s word', async () => {
+ const h = await repos();
+ try {
+ await h.write(h.source, 'personal.txt', ['kept']);
+ await h.commit(h.source, '', 1_000);
+ await h.write(h.source, 'feature.txt', replace(0, 'mine'));
+ const dropped = await h.commit(h.source, '', 2_000);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+
+ const state = update(h, target);
+ const conflict = await prepareUpstreamMerge(h.userData, state, h.git, async () => {});
+ expect(conflict.status).toBe('conflict');
+ await skip(h, conflict);
+ const refused = await applyUpstreamMerge(h.userData, conflict, h.git).catch((error) => error);
+ expect(refused).toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [dropped] },
+ });
+ // Nothing moved on this computer.
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ text(replace(0, 'mine')),
+ );
+ // The decision is bound to the checked result: one changed since is checked again.
+ await expect(
+ applyUpstreamMerge(h.userData, conflict, h.git, () => true, { acceptMissing: true }),
+ ).rejects.toMatchObject({ code: 'checksFailed' });
+ const adopted = await applyUpstreamMerge(
+ h.userData,
+ { ...conflict, missing: refused.missing },
+ h.git,
+ () => true,
+ { acceptMissing: true },
+ );
+ expect(adopted.status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'personal.txt'), 'utf8')).toBe('kept\n');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ text(replace(0, 'official')),
+ );
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('adopts an official update that already contains a personal change as the same patch', async () => {
+ const h = await repos();
+ try {
+ await h.write(h.source, 'feature.txt', replace(3, 'adopted'));
+ await h.commit(h.source, '', 1_000);
+ // The official project took the change (for example a merged pull request).
+ await h.write(h.official, 'feature.txt', replace(3, 'adopted'));
+ await h.commit(h.official, 'feat: adopted upstream');
+ await h.write(h.official, 'other.txt', ['other']);
+ const target = await h.commit(h.official, 'official v2');
+ const result = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(result.status).toBe('merged');
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('asks before adopting a fused resolution whose task commits share one identity', async () => {
+ const h = await repos();
+ try {
+ // Two task commits in the same second: the clean one must not vouch for the conflicting one.
+ await h.write(h.source, 'feature.txt', replace(0, 'mine'));
+ const fused = await h.commit(h.source, '', 5_000);
+ await h.write(h.source, 'clean.txt', ['clean']);
+ await h.commit(h.source, '', 5_000);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ await h.write(worktree, 'feature.txt', replace(0, 'official and mine'));
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ const refused = await applyUpstreamMerge(h.userData, state, h.git).catch((error) => error);
+ expect(refused).toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [fused] },
+ });
+ // Text in a fused line cannot prove its original meaning; the user can still
+ // accept this exact reviewed result through the existing confirmation.
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ text(replace(0, 'mine')),
+ );
+ await expect(
+ applyUpstreamMerge(h.userData, { ...state, missing: refused.missing }, h.git, () => true, {
+ acceptMissing: true,
+ }),
+ ).resolves.toMatchObject({
+ status: 'merged',
+ });
+ expect(await readFile(path.join(h.source, 'clean.txt'), 'utf8')).toBe('clean\n');
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('refuses when the conflicting one of two same-second task commits is skipped', async () => {
+ const h = await repos();
+ try {
+ await h.write(h.source, 'feature.txt', replace(0, 'mine'));
+ const conflicting = await h.commit(h.source, '', 5_000);
+ await h.write(h.source, 'clean.txt', ['clean']);
+ await h.commit(h.source, '', 5_000);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ await skip(h, state);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ missing: { count: 1, commits: [conflicting] },
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('names a change whose edits a resolved rebase kept only half of', async () => {
+ const h = await repos();
+ try {
+ // One change, two edits; the conflict resolution keeps only the second one.
+ await h.write(h.source, 'feature.txt', replace(0, 'alpha', replace(4, 'beta')));
+ const partial = await h.commit(h.source, '', 3_000);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ // The replayed commit keeps the author, time and title of `partial`, but its
+ // first edit is gone: identity alone must not mark the change as kept.
+ await h.write(worktree, 'feature.txt', replace(0, 'official', replace(4, 'beta')));
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [partial] },
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it.each([
+ ['line comment', ['// deleteData()']],
+ ['hash comment', ['# deleteData()']],
+ ['SQL comment', ['-- deleteData()']],
+ ['block comment', ['/* deleteData() */']],
+ ['multiline block comment', ['/*', 'deleteData()', '*/']],
+ ['HTML comment', ['<!--', 'deleteData()', '-->']],
+ // A closing fragment alone is still ambiguous; this fallback must not parse HTML.
+ ['HTML end-bang comment fragment', ['deleteData() --!>']],
+ ['quoted text', ["const note = ' deleteData() ';"]],
+ ['template literal', ['const note = `', 'deleteData()', '`;']],
+ ['multiline quoted text', ['const note = "', 'deleteData()', '";']],
+ ['disabled single-line control flow', ['if (false) deleteData()']],
+ ['disabled block', ['if (false) {', 'deleteData()', '}']],
+ ['disabled loop', ['while (false) {', 'deleteData()', '}']],
+ ['early return', ['return', 'deleteData()']],
+] as const)(
+ 'does not vouch for an added call amid %s syntax',
+ async (_kind, resolution) => {
+ const h = await repos();
+ try {
+ await h.write(h.source, 'feature.txt', replace(0, 'deleteData()'));
+ const disabled = await h.commit(h.source, '', 4_050);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(
+ h.userData,
+ update(h, target),
+ h.git,
+ async () => {},
+ );
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ await h.write(worktree, 'feature.txt', [...resolution, ...LINES.slice(1)]);
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [disabled] },
+ });
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(disabled);
+ } finally {
+ await h.clean();
+ }
+ },
+ 60_000,
+);
+
+it.each(['current', 'older'] as const)(
+ 'does not vouch for the wrong repeated block with %s Git',
+ async (version) => {
+ const original = ['admin:', 'deny()', ...LINES, 'guest:', 'deny()', 'end'];
+ const h = await repos(original);
+ const git: MergeGit = (args, cwd, index) =>
+ version === 'older' && args[0] === 'merge-tree'
+ ? Promise.reject(Object.assign(new Error('usage'), { exitCode: 129 }))
+ : h.git(args, cwd, index);
+ try {
+ const intended = original.map((line, at) => (at === 1 ? 'allow()' : line));
+ await h.write(h.source, 'feature.txt', intended);
+ const misplaced = await h.commit(h.source, '', 4_075);
+ const upstream = original.map((line, at) => (at === 0 ? 'admin: official' : line));
+ await h.write(h.official, 'feature.txt', upstream);
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(
+ h.userData,
+ update(h, target),
+ h.git,
+ async () => {},
+ );
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ // The resolver preserves the rebase identity but applies -deny/+allow to guest.
+ await h.write(
+ worktree,
+ 'feature.txt',
+ upstream.map((line, at) => (at === original.length - 2 ? 'allow()' : line)),
+ );
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [misplaced] },
+ });
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(misplaced);
+ } finally {
+ await h.clean();
+ }
+ },
+ 60_000,
+);
+
+it('keeps sequential personal changes that intentionally supersede each other', async () => {
+ const h = await repos();
+ try {
+ await h.write(h.source, 'feature.txt', replace(3, 'alpha'));
+ await h.commit(h.source, '', 4_076);
+ await h.write(h.source, 'feature.txt', replace(3, 'beta'));
+ await h.commit(h.source, '', 4_077);
+ await h.write(h.official, 'official.txt', ['v2']);
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ text(replace(3, 'beta')),
+ );
+ expect(await readFile(path.join(h.source, 'official.txt'), 'utf8')).toBe('v2\n');
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('does not let patch-id equivalence hide a change in another repeated block', async () => {
+ const padding = Array.from({ length: 10 }, (_, i) => 'padding ' + i);
+ const block = [...padding, 'deny()', ...padding];
+ const original = ['admin:', ...block, 'guest:', ...block];
+ const h = await repos(original);
+ try {
+ await h.write(
+ h.source,
+ 'feature.txt',
+ original.map((line, at) => (at === 11 ? 'allow()' : line)),
+ );
+ const misplaced = await h.commit(h.source, '', 4_080);
+ await h.write(
+ h.official,
+ 'feature.txt',
+ original.map((line, at) => (at === 11 + block.length + 1 ? 'allow()' : line)),
+ );
+ const target = await h.commit(h.official, 'official v2');
+ await h.git(['fetch', h.official, target], h.source);
+ await expect(uncarriedChanges(h.git, h.source, misplaced, target, target)).resolves.toEqual([
+ misplaced,
+ ]);
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('names a change whose added line a resolved rebase only reordered', async () => {
+ const h = await repos();
+ try {
+ // One change adds a line; the conflict resolution keeps its words but flips
+ // their order — the same unordered word set, a different meaning.
+ await h.write(h.source, 'feature.txt', replace(0, 'return a - b'));
+ const reordered = await h.commit(h.source, '', 4_000);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ await h.write(worktree, 'feature.txt', replace(0, 'return b - a'));
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [reordered] },
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it.each(['lines', 'hunks'] as const)('rejects reordered added %s while accepting their original sequence', async (shape) => {
+ const h = await repos();
+ try {
+ const guarded = ['if (authorized) {', 'deleteData()', '}'];
+ const original = shape === 'lines'
+ ? [...guarded, ...LINES.slice(1)]
+ : replace(0, 'acquire()', replace(5, 'release()'));
+ await h.write(h.source, 'feature.txt', original);
+ const reordered = await h.commit(h.source, '', 4_100);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ await h.write(worktree, 'feature.txt', shape === 'lines'
+ ? [guarded[1], guarded[0], guarded[2], ...LINES.slice(1)]
+ : replace(0, 'release()', replace(5, 'acquire()')));
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ code: 'checksFailed', missing: { count: 1, commits: [reordered] },
+ });
+ await h.write(worktree, 'feature.txt', original);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).resolves.toMatchObject({ status: 'merged' });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('does not use baseline duplicate lines to vouch for a reordered added block', async () => {
+ const block = ['if (authorized) {', 'deleteData()', '}'];
+ const h = await repos([...block, ...LINES]);
+ try {
+ // The parent already has one copy. The next task adds a second copy, so the
+ // resolver must distinguish the new block from the baseline carriers.
+ await h.write(h.source, 'feature.txt', [
+ 'personal',
+ ...block,
+ 'if (authorized) {',
+ 'deleteData()',
+ '}',
+ ...LINES.slice(1),
+ ]);
+ const added = await h.commit(h.source, '', 4_200);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ // Keep the old guarded block, but place the newly added call before its guard.
+ await h.write(worktree, 'feature.txt', [
+ 'official',
+ ...block,
+ 'deleteData()',
+ 'if (authorized) {',
+ '}',
+ ...LINES.slice(1),
+ ]);
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ missing: { commits: expect.arrayContaining([added]) },
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('names a change whose deletion a resolved rebase kept only wrapped in punctuation', async () => {
+ const h = await repos();
+ try {
+ // One change deletes a line and edits another; the resolution keeps the edit
+ // but retains the deleted code wrapped in new punctuation (`2` as `(2)`) —
+ // the whitespace tokens cannot see through the wrap, yet the deletion was
+ // not applied and must not vouch for the change.
+ await h.write(h.source, 'feature.txt', [
+ 'mine',
+ ...LINES.slice(1).filter((line) => line !== '2'),
+ ]);
+ const deleted = await h.commit(h.source, '', 6_000);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ await h.write(worktree, 'feature.txt', ['mine', '(2)', ...LINES.slice(2)]);
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [deleted] },
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('names a binary change whose same-identity replacement has different content', async () => {
+ const h = await repos();
+ try {
+ // One change replaces the binary file; the official version replaces it too.
+ await writeFile(path.join(h.source, 'logo.bin'), Buffer.from([0x00, 0x58, 0x00, 0x01]));
+ const changed = await h.commit(h.source, '', 2_000);
+ await writeFile(path.join(h.official, 'logo.bin'), Buffer.from([0x00, 0x59, 0x00]));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ // The replayed commit keeps the author, time and title of `changed`, but the
+ // binary content is someone else's: after the `index` rows are dropped the two
+ // diffs read identically, so they must never be compared without the object IDs.
+ await writeFile(path.join(worktree, 'logo.bin'), Buffer.from([0x00, 0x5a]));
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [changed] },
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('names a change whose deleted line a resolved rebase kept adapted', async () => {
+ const h = await repos();
+ try {
+ // One change deletes `5` and edits another line.
+ await h.write(h.source, 'feature.txt', replace(0, 'mine', ['1', '2', '3', '4', '6', '7', '8']));
+ const dropped = await h.commit(h.source, '', 4_000);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ // The replayed commit keeps the text edit, but the deleted line survives in
+ // adapted form: the deletion did not happen and must not be vouched for.
+ await h.write(
+ worktree,
+ 'feature.txt',
+ replace(0, 'official and mine', ['1', '2', '3', '4', '5 // upstream note', '6', '7', '8']),
+ );
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [dropped] },
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('journals the adopted rewrite as unverified before the source moves', async () => {
+ const h = await repos();
+ try {
+ await h.write(h.source, 'feature.txt', replace(0, 'mine'));
+ await h.commit(h.source, '', 1_000);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ await h.write(worktree, 'feature.txt', replace(0, 'mine'));
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ const timeline: string[] = [];
+ const git: MergeGit = (args, cwd, index) => {
+ if (args[0] === 'reset' && args[1] === '--keep') timeline.push('moved');
+ return h.git(args, cwd, index);
+ };
+ const journaled: CindyMakeMergeState[] = [];
+ const merged = await applyUpstreamMerge(h.userData, state, git, () => true, {
+ journal: (record) => {
+ timeline.push('journaled');
+ journaled.push(record);
+ },
+ });
+ expect(merged).toMatchObject({ status: 'merged' });
+ // The rewritten result's provenance is durable before the source moves: a crash
+ // right after the move can never leave the carried content looking verified.
+ expect(timeline).toEqual(['journaled', 'moved']);
+ expect(journaled[0]).toMatchObject({ status: 'merged', commit: merged.commit });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('journals a clean fast-path adopt before the source moves', async () => {
+ const h = await repos();
+ try {
+ // No conflict at all: `prepareUpstreamMerge`'s own fast path adopts the
+ // result — and must journal its provenance before moving, like the task path.
+ await h.write(h.source, 'feature.txt', replace(3, 'mine'));
+ await h.commit(h.source, '', 1_000);
+ await h.write(h.official, 'other.txt', ['other']);
+ const target = await h.commit(h.official, 'official v2');
+ const timeline: string[] = [];
+ const git: MergeGit = (args, cwd, index) => {
+ if (args[0] === 'reset' && args[1] === '--keep') timeline.push('moved');
+ return h.git(args, cwd, index);
+ };
+ const journaled: CindyMakeMergeState[] = [];
+ const merged = await prepareUpstreamMerge(
+ h.userData,
+ update(h, target),
+ git,
+ async () => {},
+ () => true,
+ {
+ journal: (record) => {
+ timeline.push('journaled');
+ journaled.push(record);
+ },
+ },
+ );
+ expect(merged).toMatchObject({ status: 'merged' });
+ expect(timeline).toEqual(['journaled', 'moved']);
+ expect(journaled[0]).toMatchObject({ status: 'merged', commit: merged.commit });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('keeps the source in place when the provenance journal cannot be written', async () => {
+ const h = await repos();
+ try {
+ await h.write(h.source, 'feature.txt', replace(0, 'mine'));
+ await h.commit(h.source, '', 1_000);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ await h.write(worktree, 'feature.txt', replace(0, 'mine'));
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ const timeline: string[] = [];
+ const git: MergeGit = (args, cwd, index) => {
+ if (args[0] === 'reset' && args[1] === '--keep') timeline.push('moved');
+ return h.git(args, cwd, index);
+ };
+ const before = (await h.git(['rev-parse', 'HEAD'], h.source)).trim();
+ await expect(
+ applyUpstreamMerge(h.userData, state, git, () => true, {
+ // A full disk cannot record the carried content's provenance: the adoption
+ // itself must stop, never land unrecorded content in the source.
+ journal: () => {
+ throw Object.assign(new Error('disk full'), { code: 'ENOSPC' });
+ },
+ }),
+ ).rejects.toThrow('disk full');
+ expect(timeline).not.toContain('moved');
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(before);
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('names a change whose added duplicate line a resolved rebase dropped', async () => {
+ const h = await repos();
+ try {
+ // The change adds a line that already exists in the file and replaces
+ // another; the resolution fuses the replacement but drops the added copy —
+ // one pre-existing line must not vouch for the missing occurrence.
+ await h.write(h.source, 'feature.txt', ['2', ...replace(0, 'alpha')]);
+ const duplicated = await h.commit(h.source, '', 3_200);
+ await h.write(h.official, 'feature.txt', replace(0, 'official'));
+ const target = await h.commit(h.official, 'official v2');
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, state.id);
+ await h.write(worktree, 'feature.txt', replace(0, 'official and alpha'));
+ await h.git(['add', '-A'], worktree);
+ await h.git([...h.identity(true), 'rebase', '--continue'], worktree);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [duplicated] },
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('keeps a merge commit’s own edits: missing until the resolver puts them back', async () => {
+ const h = await repos();
+ try {
+ await h.git(['checkout', '-b', 'side'], h.source);
+ await h.write(h.source, 'side.txt', ['side']);
+ await h.commit(h.source, 'side change');
+ await h.git(['checkout', 'cindy-personal'], h.source);
+ await h.write(h.source, 'main.txt', ['main']);
+ await h.commit(h.source, 'main change');
+ // An edit made only in the merge commit itself.
+ await h.git([...h.identity(false), 'merge', '--no-commit', '--no-ff', 'side'], h.source);
+ await h.write(h.source, 'merge-only.txt', ['only in the merge']);
+ await h.commit(h.source, 'merge side');
+ const merge = (await h.git(['rev-parse', 'HEAD'], h.source)).trim();
+ await h.write(h.official, 'official.txt', ['v2']);
+ const target = await h.commit(h.official, 'official v2');
+
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), h.git, async () => {});
+ expect(state).toMatchObject({ status: 'conflict', rebaseReview: true });
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).rejects.toMatchObject({
+ missing: { count: 1, commits: [merge] },
+ });
+ const worktree = mergeWorktree(h.userData, state.id);
+ await h.write(worktree, 'merge-only.txt', ['only in the merge']);
+ await expect(applyUpstreamMerge(h.userData, state, h.git)).resolves.toMatchObject({
+ status: 'merged',
+ });
+ expect(await readFile(path.join(h.source, 'merge-only.txt'), 'utf8')).toBe(
+ 'only in the merge\n',
+ );
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('asks before accepting an adjacent rewrite that cannot be proved, then keeps it', async () => {
+ const h = await repos();
+ try {
+ const fork = path.join(h.userData, 'fork.git');
+ const other = path.join(h.userData, 'other');
+ // This computer's change, shared through GitHub.
+ await h.write(h.source, 'feature.txt', replace(4, 'mine'));
+ const mine = await h.commit(h.source, '', 1_000);
+ await h.git(['clone', '--bare', h.source, fork], h.userData);
+ // An official update right next to it: the other computer's rebase had to resolve it.
+ await h.write(h.official, 'feature.txt', replace(3, 'official'));
+ const officialV2 = await h.commit(h.official, 'official v2');
+ await h.git(['clone', '--branch', 'cindy-personal', fork, other], h.userData);
+ await h.git(['fetch', h.official, officialV2], other);
+ await h
+ .git([...h.identity(true), 'rebase', '--onto', officialV2, h.base], other)
+ .catch(() => '');
+ await h.write(other, 'feature.txt', replace(4, 'mine', replace(3, 'official')));
+ await h.git(['add', '-A'], other);
+ await h.git([...h.identity(true), 'rebase', '--continue'], other);
+ await h.git(['push', '--force', 'origin', 'cindy-personal'], other);
+ const remote = (await h.git(['rev-parse', 'HEAD'], other)).trim();
+ expect(remote).not.toBe(mine);
+
+ // Meanwhile this computer made another change on the older official version.
+ await h.write(h.source, 'later.txt', ['later']);
+ await h.commit(h.source, '', 2_000);
+ await h.git(['fetch', fork, `+refs/heads/cindy-personal:${PERSONAL_TRACKING_REF}`], h.source);
+ const state: CindyMakeMergeState = {
+ id: randomUUID(),
+ status: 'merging',
+ ref: 'github',
+ upstreamCommit: remote,
+ remote: { base: officialV2, commit: remote },
+ };
+ const result = await preparePersonalCombine(h.userData, state, h.git, async () => {});
+ if (result.status === 'conflict') {
+ // Replaying the original next to the resolved rewrite conflicts; the resolver keeps
+ // the rewrite, which leaves the original empty.
+ await skip(h, result);
+ const refused = await applyUpstreamMerge(h.userData, result, h.git).catch((error) => error);
+ expect(refused).toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [mine] },
+ });
+ // The adjacent official edit makes the three-tree proof ambiguous even
+ // though the resolver kept this line. Only the user's confirmation may
+ // accept that precise result; the source stays put until then.
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ text(replace(4, 'mine')),
+ );
+ await expect(
+ applyUpstreamMerge(h.userData, { ...result, missing: refused.missing }, h.git, () => true, {
+ acceptMissing: true,
+ }),
+ ).resolves.toMatchObject({
+ status: 'merged',
+ });
+ } else expect(result.status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ text(replace(4, 'mine', replace(3, 'official'))),
+ );
+ expect(await readFile(path.join(h.source, 'later.txt'), 'utf8')).toBe('later\n');
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('never trusts Git output cut at the capture limit', async () => {
+ const commit = 'a'.repeat(40);
+ const git: MergeGit = async (args) => {
+ if (args[0] === 'log') return ['b'.repeat(40), 'Cindy Make', 'x@y', '1', 's'].join('\0') + '\n';
+ if (args[0] === 'rev-list') return '2\n';
+ return '';
+ };
+ await expect(uncarriedChanges(git, '.', commit, commit, commit)).rejects.toMatchObject({
+ code: 'checksFailed',
+ });
+});
+
+it('checks a change is already there with an older Git that has no merge-tree --merge-base', async () => {
+ const h = await repos();
+ // Git before 2.40 rejects the option as a usage error (exit 129).
+ const olderGit: MergeGit = (args, cwd, index) =>
+ args[0] === 'merge-tree'
+ ? Promise.reject(Object.assign(new Error('usage'), { exitCode: 129 }))
+ : h.git(args, cwd, index);
+ try {
+ await h.git(['checkout', '-b', 'side'], h.source);
+ await h.write(h.source, 'side.txt', ['side']);
+ await h.commit(h.source, 'side change');
+ await h.git(['checkout', 'cindy-personal'], h.source);
+ await h.write(h.source, 'main.txt', ['main']);
+ await h.commit(h.source, 'main change');
+ await h.git([...h.identity(false), 'merge', '--no-commit', '--no-ff', 'side'], h.source);
+ await h.write(h.source, 'merge-only.txt', ['only in the merge']);
+ await h.commit(h.source, 'merge side');
+ const merge = (await h.git(['rev-parse', 'HEAD'], h.source)).trim();
+ await h.write(h.official, 'official.txt', ['v2']);
+ const target = await h.commit(h.official, 'official v2');
+
+ const state = await prepareUpstreamMerge(h.userData, update(h, target), olderGit, async () => {});
+ await expect(applyUpstreamMerge(h.userData, state, olderGit)).rejects.toMatchObject({
+ missing: { count: 1, commits: [merge] },
+ });
+ await h.write(mergeWorktree(h.userData, state.id), 'merge-only.txt', ['only in the merge']);
+ await expect(applyUpstreamMerge(h.userData, state, olderGit)).resolves.toMatchObject({
+ status: 'merged',
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
diff --git a/apps/desktop/src/main/cindy-make/__tests__/manager.test.ts b/apps/desktop/src/main/cindy-make/__tests__/manager.test.ts
index 9d340c9b2e..a7ba094040 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/manager.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/manager.test.ts
@@ -23,6 +23,26 @@ describe('CindyMakeManager', () => {
current = false;
expect(manager.getState().upstreamMerge).toMatchObject({ sessionId: undefined, ownedByAnotherAccount: true, hasWorkspace: true });
});
+ it('keeps a fork sync reading the checkout from being cleared without blocking builds', async () => {
+ const manager = new CindyMakeManager();
+ let release!: () => void;
+ const reading = manager.withSourceReader(
+ '/managed',
+ () => new Promise<void>((resolve) => (release = resolve)),
+ );
+ const run = vi.fn();
+ const clear = () =>
+ manager.prepareSource({ root: '/managed', clearOnly: true, signal: new AbortController().signal,
+ cancelled: vi.fn(), onProgress: vi.fn(), toStatus: vi.fn(), run,
+ });
+ await expect(clear()).rejects.toMatchObject({ code: 'busy' });
+ expect(run).not.toHaveBeenCalled();
+ // Builds only need the project queue, which the network phase does not hold.
+ manager.claimPersonalBuild()();
+ release();
+ await reading;
+ await expect(manager.withSourceReader('/managed', async () => 'done')).resolves.toBe('done');
+ });
it('blocks source preparation and reset while an unresolved merge workspace is retained', async () => {
const manager = new CindyMakeManager();
manager.setUpstreamMerge({ id: 'merge', ref: 'main', upstreamCommit: 'a'.repeat(40), status: 'failed', hasWorkspace: true });
diff --git a/apps/desktop/src/main/cindy-make/__tests__/pendingBuild.test.ts b/apps/desktop/src/main/cindy-make/__tests__/pendingBuild.test.ts
new file mode 100644
index 0000000000..c29c080ad3
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/pendingBuild.test.ts
@@ -0,0 +1,295 @@
+import path from 'node:path';
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
+import os from 'node:os';
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ dropPendingBuild,
+ hasPendingBuild,
+ initializePendingBuilds,
+ readPendingBuilds,
+ recordPendingBuild,
+ rewritePendingBuilds,
+ settlePendingBuilds,
+} from '../pendingBuild';
+import { hasUnbuiltPersonalChanges } from '../buildRollback';
+import { CindyMakeHistoryStore } from '../historyStore';
+import type { MakeFeatureReceipt } from '../../../shared/cindyMakeHistory';
+
+const roots: string[] = [];
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+function root() {
+ const directory = mkdtempSync(path.join(os.tmpdir(), 'cindy-pending-build-'));
+ roots.push(directory);
+ return directory;
+}
+const A = { commit: 'a'.repeat(40), tree: '1'.repeat(40) };
+const B = { commit: 'b'.repeat(40), tree: '2'.repeat(40) };
+const C = { commit: 'c'.repeat(40), tree: '3'.repeat(40) };
+
+/** The account that integrated `changes`, as `recordAppliedMerge` records them. */
+function account(directory: string, changes: Array<{ id: string; head: typeof A }>) {
+ const store = new CindyMakeHistoryStore(path.join(directory, 'history'));
+ store.seed({
+ runId: 'task',
+ sessionId: 'task',
+ title: 'task',
+ request: 'task',
+ createdAt: 1,
+ updatedAt: 1,
+ });
+ let before = { commit: '0'.repeat(40), tree: '0'.repeat(40) };
+ for (const change of changes) {
+ const receipt: MakeFeatureReceipt = {
+ id: change.id,
+ action: 'integrate',
+ at: 1,
+ baselineCommit: before.commit,
+ commit: change.head.commit,
+ beforeTree: before.tree,
+ tree: change.head.tree,
+ taskTree: change.head.tree,
+ };
+ recordPendingBuild(directory, change.head);
+ store.receipt('task', receipt);
+ before = change.head;
+ }
+ return store;
+}
+
+it('records the snapshot with its fact and keeps the newest entries', () => {
+ const dir = root();
+ recordPendingBuild(dir, A);
+ recordPendingBuild(dir, A);
+ recordPendingBuild(dir, B);
+ expect(readPendingBuilds(dir)).toEqual([A, B]);
+ expect(hasPendingBuild(dir, A)).toBe(true);
+ expect(hasPendingBuild(dir, C)).toBeUndefined();
+});
+
+it('initializes a fresh source as a trusted clean snapshot', () => {
+ const dir = root();
+ initializePendingBuilds(dir);
+ expect(readPendingBuilds(dir)).toEqual([]);
+ expect(hasPendingBuild(dir, A)).toBe(false);
+ writeFileSync(path.join(dir, 'pending-build.json'), '{ not json');
+ initializePendingBuilds(dir);
+ expect(readPendingBuilds(dir)).toBeUndefined();
+});
+
+it.each(['integration', 'rewrite'] as const)(
+ 'keeps a truncated %s ledger unknown after rolling back every retained snapshot',
+ (operation) => {
+ const dir = root();
+ initializePendingBuilds(dir);
+ recordPendingBuild(dir, A);
+ const later = Array.from({ length: 64 }, (_, i) => ({
+ commit: (i + 1).toString(16).padStart(40, '0'),
+ tree: (i + 1).toString(16).padStart(40, '0'),
+ }));
+ if (operation === 'integration') {
+ for (const snapshot of later) recordPendingBuild(dir, snapshot);
+ } else {
+ // A readable older ledger can exceed the current bound as well.
+ writeFileSync(path.join(dir, 'pending-build.json'), JSON.stringify({
+ schema: 1, snapshots: [A, ...later], trusted: true,
+ }));
+ rewritePendingBuilds(dir, [later.at(-1)!.commit], C);
+ }
+ expect(readPendingBuilds(dir)).toHaveLength(64);
+ for (const snapshot of readPendingBuilds(dir)!) dropPendingBuild(dir, snapshot);
+ expect(readPendingBuilds(dir)).toEqual([]);
+ expect(hasPendingBuild(dir, A)).toBeUndefined();
+ const otherAccount = new CindyMakeHistoryStore(path.join(dir, 'other-owner'));
+ expect(hasUnbuiltPersonalChanges(otherAccount, dir, A, () => false)).toBe(true);
+ settlePendingBuilds(dir);
+ expect(hasPendingBuild(dir, A)).toBe(false);
+ },
+);
+
+it('treats a missing or unreadable record as unknown until a generation settles it', () => {
+ const dir = root();
+ expect(readPendingBuilds(dir)).toBeUndefined();
+ expect(hasPendingBuild(dir, A)).toBeUndefined();
+ mkdirSync(path.join(dir), { recursive: true });
+ writeFileSync(path.join(dir, 'pending-build.json'), '{ not json');
+ expect(readPendingBuilds(dir)).toBeUndefined();
+ expect(hasPendingBuild(dir, A)).toBeUndefined();
+ const empty = new CindyMakeHistoryStore(path.join(dir, 'empty-history'));
+ expect(hasUnbuiltPersonalChanges(empty, dir, A, () => false)).toBe(true);
+ settlePendingBuilds(dir);
+ expect(readPendingBuilds(dir)).toEqual([]);
+ expect(hasPendingBuild(dir, A)).toBe(false);
+});
+
+it('does not clear an unreadable record when dropping a rolled-back snapshot', () => {
+ const dir = root();
+ writeFileSync(path.join(dir, 'pending-build.json'), '{ not json');
+ dropPendingBuild(dir, A);
+ expect(readPendingBuilds(dir)).toBeUndefined();
+ expect(hasPendingBuild(dir, A)).toBeUndefined();
+});
+
+it('accepts only Git SHA-1 or SHA-256 lengths', () => {
+ const dir = root();
+ expect(() => recordPendingBuild(dir, { commit: 'a'.repeat(41), tree: '1'.repeat(40) })).toThrow(
+ 'Invalid pending build snapshot',
+ );
+ expect(() => recordPendingBuild(dir, { commit: 'a'.repeat(40), tree: '1'.repeat(63) })).toThrow(
+ 'Invalid pending build snapshot',
+ );
+ expect(() =>
+ recordPendingBuild(dir, { commit: 'a'.repeat(64), tree: '1'.repeat(64) }),
+ ).not.toThrow();
+});
+
+it.each(['missing', 'corrupt'] as const)(
+ 'keeps an unknown %s baseline across integration, rewrite and rollback until generation',
+ (state) => {
+ const dir = root();
+ if (state === 'corrupt') writeFileSync(path.join(dir, 'pending-build.json'), 'broken');
+ const otherAccount = new CindyMakeHistoryStore(path.join(dir, 'other-owner'));
+ expect(hasUnbuiltPersonalChanges(otherAccount, dir, A, () => false)).toBe(true);
+ expect(hasUnbuiltPersonalChanges(otherAccount, dir, A, (commit) => commit === A.commit)).toBe(
+ false,
+ );
+
+ recordPendingBuild(dir, B);
+ expect(hasPendingBuild(dir, B)).toBe(true);
+ expect(hasPendingBuild(dir, A)).toBeUndefined();
+ rewritePendingBuilds(dir, [B.commit], C);
+ expect(hasPendingBuild(dir, C)).toBe(true);
+ expect(hasPendingBuild(dir, A)).toBeUndefined();
+ dropPendingBuild(dir, C);
+ expect(hasPendingBuild(dir, C)).toBeUndefined();
+ // Rolling back the new work must not hide another account's older work.
+ expect(hasUnbuiltPersonalChanges(otherAccount, dir, A, () => false)).toBe(true);
+
+ settlePendingBuilds(dir);
+ expect(hasUnbuiltPersonalChanges(otherAccount, dir, A, () => false)).toBe(false);
+ recordPendingBuild(dir, B);
+ expect(hasPendingBuild(dir, B)).toBe(true);
+ dropPendingBuild(dir, B);
+ expect(hasPendingBuild(dir, A)).toBe(false);
+ },
+);
+
+it.each([39, ...Array.from({ length: 23 }, (_, index) => index + 41), 65])(
+ 'rejects %i-character object IDs instead of treating a damaged record as settled',
+ (length) => {
+ const dir = root();
+ for (const field of ['commit', 'tree'] as const) {
+ const snapshot = { ...A, [field]: 'a'.repeat(length) };
+ writeFileSync(
+ path.join(dir, 'pending-build.json'),
+ JSON.stringify({ schema: 1, snapshots: [snapshot] }),
+ );
+ expect(readPendingBuilds(dir)).toBeUndefined();
+ expect(hasPendingBuild(dir, A)).toBeUndefined();
+ expect(() => recordPendingBuild(dir, snapshot)).toThrow('Invalid pending build snapshot');
+ }
+ },
+);
+
+it.each([40, 64])('accepts complete %i-character Git object IDs', (length) => {
+ const dir = root();
+ const snapshot = { commit: 'a'.repeat(length), tree: '1'.repeat(length) };
+ recordPendingBuild(dir, snapshot);
+ expect(readPendingBuilds(dir)).toEqual([snapshot]);
+ expect(hasPendingBuild(dir, snapshot)).toBe(true);
+});
+
+it('a generated personal version settles the pending generation', () => {
+ const dir = root();
+ recordPendingBuild(dir, A);
+ recordPendingBuild(dir, B);
+ settlePendingBuilds(dir);
+ expect(readPendingBuilds(dir)).toEqual([]);
+});
+
+it('a completed rollback or restore drops the snapshot the source left', () => {
+ const dir = root();
+ recordPendingBuild(dir, A);
+ recordPendingBuild(dir, B);
+ dropPendingBuild(dir, B);
+ expect(readPendingBuilds(dir)).toEqual([A]);
+});
+
+it('an adopted rewrite carries the fact to the result that contains it', () => {
+ const dir = root();
+ recordPendingBuild(dir, A);
+ recordPendingBuild(dir, B);
+ rewritePendingBuilds(dir, [A.commit], C);
+ expect(readPendingBuilds(dir)).toEqual([C, B]);
+ expect(hasPendingBuild(dir, C)).toBe(true);
+});
+
+describe('the unbuilt-changes decision', () => {
+ it('does not read the shared source through one account: another account still sees pending', () => {
+ const dir = root();
+ // Account A integrated `A`; the source carries it and no version covers it.
+ const accountA = account(dir, [{ id: 'first', head: A }]);
+ const accountB = new CindyMakeHistoryStore(path.join(dir, 'other-owner'));
+ // The account that made the change sees it through its own receipts…
+ expect(hasUnbuiltPersonalChanges(accountA, dir, A, () => false)).toBe(true);
+ // …and another account of the same device must not conclude "nothing is
+ // pending" just because its own history has no receipts for it.
+ expect(hasUnbuiltPersonalChanges(accountB, dir, A, () => false)).toBe(true);
+ });
+
+ it('a snapshot fetched from another computer is pending until this one generates it', () => {
+ const dir = root();
+ // The adoption hook records the fetched snapshot (see `recordUnbuilt`): the
+ // device has no build history for it at all.
+ recordPendingBuild(dir, B);
+ const empty = new CindyMakeHistoryStore(path.join(dir, 'history'));
+ expect(hasUnbuiltPersonalChanges(empty, dir, B, () => false)).toBe(true);
+ // This computer generated its own application from it: settled.
+ expect(hasUnbuiltPersonalChanges(empty, dir, B, (commit) => commit === B.commit)).toBe(false);
+ });
+
+ it('a generated personal version settles the account facts too', () => {
+ const dir = root();
+ const store = account(dir, [{ id: 'first', head: A }]);
+ settlePendingBuilds(dir);
+ expect(hasUnbuiltPersonalChanges(store, dir, A, (commit) => commit === A.commit)).toBe(false);
+ });
+
+ it('a pending build rollback is still pending', () => {
+ const dir = root();
+ const store = account(dir, [{ id: 'first', head: A }]);
+ store.saveBuildRollback([
+ {
+ runId: 'task',
+ receipt: {
+ id: 'first',
+ action: 'integrate',
+ at: 1,
+ baselineCommit: '0'.repeat(40),
+ commit: A.commit,
+ beforeTree: '0'.repeat(40),
+ tree: A.tree,
+ taskTree: A.tree,
+ },
+ },
+ ]);
+ dropPendingBuild(dir, A); // even with the device record gone…
+ expect(hasUnbuiltPersonalChanges(store, dir, A, () => true)).toBe(true); // …the rollback counts.
+ });
+
+ it('an unreadable record proves nothing: pending unless a version covers the snapshot', () => {
+ const dir = root();
+ mkdirSync(path.join(dir), { recursive: true });
+ writeFileSync(path.join(dir, 'pending-build.json'), 'broken');
+ const empty = new CindyMakeHistoryStore(path.join(dir, 'history'));
+ expect(hasUnbuiltPersonalChanges(empty, dir, A, () => false)).toBe(true);
+ expect(hasUnbuiltPersonalChanges(empty, dir, A, (commit) => commit === A.commit)).toBe(false);
+ });
+
+ it('a missing record fails closed even when no history fact exists', () => {
+ const dir = root();
+ const empty = new CindyMakeHistoryStore(path.join(dir, 'history'));
+ expect(hasUnbuiltPersonalChanges(empty, dir, A, () => false)).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/personalCombine.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/personalCombine.git-integration.test.ts
new file mode 100644
index 0000000000..b7ec88e861
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/personalCombine.git-integration.test.ts
@@ -0,0 +1,437 @@
+import os from 'node:os';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
+import { expect, it } from 'vitest';
+import {
+ applyUpstreamMerge,
+ cancelUpstreamMerge,
+ mergeWorktree,
+ preparePersonalCombine,
+} from '../upstreamMerge';
+import { PERSONAL_TRACKING_REF } from '../personalRemote';
+import { PERSONAL_UPSTREAM_REF } from '../sourceContent';
+import { makeSourceCheckoutPath } from '../sourcePaths';
+import { runSourceGit } from '../sourceGit';
+import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
+
+/**
+ * Official repository, the user's fork and two computers that each changed the
+ * shared personal version on the same official base.
+ */
+/**
+ * `generic`: personal commits use Cindy Make's shared task identity and message, as
+ * real task commits do, so only the author time tells them apart.
+ */
+async function fixture(sameFile: boolean, generic = false) {
+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-personal-combine-'));
+ const source = makeSourceCheckoutPath(userData);
+ const official = path.join(userData, 'official');
+ const fork = path.join(userData, 'fork.git');
+ const other = path.join(userData, 'other');
+ const env = {
+ PATH: process.env.PATH,
+ SystemRoot: process.env.SystemRoot,
+ GIT_CONFIG_GLOBAL: path.join(userData, 'gitconfig'),
+ GIT_CONFIG_NOSYSTEM: '1',
+ };
+ const git = (args: string[], cwd: string, indexFile?: string) =>
+ runSourceGit(
+ { ...env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args,
+ cwd,
+ AbortSignal.timeout(30_000),
+ );
+ const commit = async (cwd: string, message: string) => {
+ const task = generic && !message.startsWith('official');
+ await git(['add', '.'], cwd);
+ await git(
+ [
+ '-c',
+ `user.name=${task ? 'Cindy Make' : 'Test'}`,
+ '-c',
+ `user.email=${task ? '[email protected]' : '[email protected]'}`,
+ '-c',
+ 'commit.gpgSign=false',
+ 'commit',
+ '-s',
+ '-m',
+ task ? 'Cindy Make: complete personal change' : message,
+ ],
+ cwd,
+ );
+ };
+ const clean = () => rm(userData, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
+ try {
+ await writeFile(env.GIT_CONFIG_GLOBAL, '');
+ await mkdir(official);
+ await mkdir(path.dirname(source), { recursive: true });
+ await git(['init', '--initial-branch=main'], official);
+ await writeFile(path.join(official, 'feature.txt'), 'base\n');
+ await writeFile(path.join(official, 'other.txt'), 'other base\n');
+ await commit(official, 'official base');
+ const base = (await git(['rev-parse', 'HEAD'], official)).trim();
+ await git(['clone', '--bare', official, fork], userData);
+ await git(['clone', official, source], userData);
+ await git(['checkout', '-b', 'cindy-personal'], source);
+ await git(['update-ref', PERSONAL_UPSTREAM_REF, base], source);
+ await writeFile(path.join(source, 'shared.txt'), 'shared personal change\n');
+ await commit(source, 'shared personal change');
+ await git(['push', fork, 'cindy-personal'], source);
+
+ // The other computer uploads its change first.
+ await git(['clone', '--branch', 'cindy-personal', fork, other], userData);
+ await writeFile(
+ path.join(other, sameFile ? 'feature.txt' : 'other.txt'),
+ 'from the other computer\n',
+ );
+ await commit(other, 'other computer change');
+ await git(['push', 'origin', 'cindy-personal'], other);
+ const remoteTip = (await git(['rev-parse', 'HEAD'], other)).trim();
+
+ // This computer changed the same (or a different) file meanwhile.
+ await writeFile(path.join(source, 'feature.txt'), 'from this computer\n');
+ await commit(source, 'this computer change');
+ const local = (await git(['rev-parse', 'HEAD'], source)).trim();
+ // What the last sync fetched from the fork.
+ await git(['fetch', fork, `+refs/heads/cindy-personal:${PERSONAL_TRACKING_REF}`], source);
+ const main = (await git(['rev-parse', 'main'], source)).trim();
+
+ const state: CindyMakeMergeState = {
+ id: randomUUID(),
+ status: 'merging',
+ ref: 'github',
+ upstreamCommit: remoteTip,
+ remote: { base },
+ };
+ return { userData, source, git, clean, state, base, remoteTip, local, main };
+ } catch (error) {
+ await clean();
+ throw error;
+ }
+}
+
+it('keeps both computers’ changes through a conflict resolved in the isolated candidate', async () => {
+ const h = await fixture(true);
+ try {
+ const result = await preparePersonalCombine(h.userData, h.state, h.git, async () => {});
+ expect(result).toMatchObject({
+ status: 'conflict',
+ strategy: 'combine',
+ remote: { base: h.base },
+ });
+ // Nothing moved on this computer while the conflict waits.
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(h.local);
+ expect((await h.git(['rev-parse', 'main'], h.source)).trim()).toBe(h.main);
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('from this computer\n');
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+
+ // The resolution task combines both sides and finishes the rebase.
+ const worktree = mergeWorktree(h.userData, h.state.id);
+ expect(await h.git(['diff', '--name-only', '--diff-filter=U'], worktree)).toContain(
+ 'feature.txt',
+ );
+ await writeFile(
+ path.join(worktree, 'feature.txt'),
+ 'from the other computer\nfrom this computer\n',
+ );
+ await h.git(['add', '.'], worktree);
+ await h.git(
+ [
+ '-c',
+ 'user.name=Cindy Make',
+ '-c',
+ '-c',
+ 'core.editor=true',
+ '-c',
+ 'commit.gpgSign=false',
+ 'rebase',
+ '--continue',
+ ],
+ worktree,
+ );
+ const refused = await applyUpstreamMerge(h.userData, result, h.git).catch((error) => error);
+ expect(refused).toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [h.local] },
+ });
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(h.local);
+ const applied = await applyUpstreamMerge(
+ h.userData,
+ { ...result, missing: refused.missing },
+ h.git,
+ () => true,
+ { acceptMissing: true },
+ );
+ expect(applied.status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ 'from the other computer\nfrom this computer\n',
+ );
+ expect(await readFile(path.join(h.source, 'shared.txt'), 'utf8')).toBe(
+ 'shared personal change\n',
+ );
+ // The GitHub version is contained, the official base and main are unchanged.
+ await h.git(['merge-base', '--is-ancestor', h.remoteTip, 'cindy-personal'], h.source);
+ expect((await h.git(['rev-parse', PERSONAL_UPSTREAM_REF], h.source)).trim()).toBe(h.base);
+ expect((await h.git(['rev-parse', 'main'], h.source)).trim()).toBe(h.main);
+ // This computer's previous version stays recoverable.
+ expect(
+ (
+ await h.git(['rev-parse', `refs/cindy-make/backups/${h.state.id}/personal`], h.source)
+ ).trim(),
+ ).toBe(h.local);
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('adopts a combine without overlapping edits directly', async () => {
+ const h = await fixture(false);
+ try {
+ const result = await preparePersonalCombine(h.userData, h.state, h.git, async () => {});
+ expect(result.status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('from this computer\n');
+ expect(await readFile(path.join(h.source, 'other.txt'), 'utf8')).toBe(
+ 'from the other computer\n',
+ );
+ expect((await h.git(['rev-parse', 'cindy-personal^'], h.source)).trim()).toBe(h.remoteTip);
+ expect((await h.git(['rev-parse', PERSONAL_UPSTREAM_REF], h.source)).trim()).toBe(h.base);
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('refuses a GitHub version other than the one the last sync fetched', async () => {
+ const h = await fixture(true);
+ try {
+ await expect(
+ preparePersonalCombine(
+ h.userData,
+ { ...h.state, upstreamCommit: h.local },
+ h.git,
+ async () => {},
+ ),
+ ).rejects.toMatchObject({ code: 'baselineChanged' });
+ await expect(stat(mergeWorktree(h.userData, h.state.id))).rejects.toBeTruthy();
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(h.local);
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('cancels a conflicting combine and leaves this computer exactly as it was', async () => {
+ const h = await fixture(true);
+ try {
+ const result = await preparePersonalCombine(h.userData, h.state, h.git, async () => {});
+ expect(result.status).toBe('conflict');
+ await cancelUpstreamMerge(h.userData, result, h.git);
+ await expect(stat(mergeWorktree(h.userData, h.state.id))).rejects.toBeTruthy();
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(h.local);
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('from this computer\n');
+ expect(await h.git(['status', '--porcelain'], h.source)).toBe('');
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+/** One computer already moved its personal version to a newer official release. */
+async function versionsFixture(newer: 'remote' | 'local') {
+ const h = await fixture(false);
+ const official = path.join(h.userData, 'official');
+ const other = path.join(h.userData, 'other');
+ const fork = path.join(h.userData, 'fork.git');
+ const commit = async (cwd: string, message: string) => {
+ await h.git(['add', '.'], cwd);
+ await h.git(
+ ['-c', 'user.name=Test', '-c', '[email protected]', 'commit', '-m', message],
+ cwd,
+ );
+ };
+ await writeFile(path.join(official, 'release.txt'), 'official 2\n');
+ await commit(official, 'official release 2');
+ const newerBase = (await h.git(['rev-parse', 'HEAD'], official)).trim();
+ const rebaseOnto = async (cwd: string) => {
+ await h.git(['fetch', official, 'main'], cwd);
+ await h.git(
+ [
+ '-c',
+ 'user.name=Test',
+ '-c',
+ 'rebase',
+ '--onto',
+ newerBase,
+ h.base,
+ ],
+ cwd,
+ );
+ };
+ if (newer === 'remote') {
+ // The other computer updated to release 2 and uploaded.
+ await rebaseOnto(other);
+ await h.git(['push', '--force', 'origin', 'cindy-personal'], other);
+ } else {
+ // This computer updated to release 2 first.
+ await rebaseOnto(h.source);
+ await h.git(['update-ref', PERSONAL_UPSTREAM_REF, newerBase], h.source);
+ }
+ await h.git(['fetch', fork, `+refs/heads/cindy-personal:${PERSONAL_TRACKING_REF}`], h.source);
+ const remoteTip = (await h.git(['rev-parse', PERSONAL_TRACKING_REF], h.source)).trim();
+ const local = (await h.git(['rev-parse', 'HEAD'], h.source)).trim();
+ const state: CindyMakeMergeState = {
+ id: randomUUID(),
+ status: 'merging',
+ ref: 'github',
+ upstreamCommit: remoteTip,
+ remote: { base: newer === 'remote' ? newerBase : h.base, commit: remoteTip },
+ };
+ return { ...h, state, newerBase, remoteTip, local };
+}
+
+it.each(['remote', 'local'] as const)(
+ 'combines when the %s side is on the newer official version, keeping every change once',
+ async (newer) => {
+ const h = await versionsFixture(newer);
+ try {
+ const result = await preparePersonalCombine(h.userData, h.state, h.git, async () => {});
+ expect(result).toMatchObject({
+ status: 'merged',
+ upstreamCommit: newer === 'remote' ? h.remoteTip : h.local,
+ remote: { base: h.newerBase, commit: h.remoteTip },
+ });
+ for (const [file, content] of [
+ ['feature.txt', 'from this computer\n'],
+ ['other.txt', 'from the other computer\n'],
+ ['shared.txt', 'shared personal change\n'],
+ ['release.txt', 'official 2\n'],
+ ])
+ expect(await readFile(path.join(h.source, file), 'utf8')).toBe(content);
+ // The side on the newer version is kept as is; the official base is that version.
+ await h.git(
+ ['merge-base', '--is-ancestor', newer === 'remote' ? h.remoteTip : h.local, 'HEAD'],
+ h.source,
+ );
+ expect((await h.git(['rev-parse', PERSONAL_UPSTREAM_REF], h.source)).trim()).toBe(
+ h.newerBase,
+ );
+ // The shared personal change is not duplicated.
+ const personal = (
+ await h.git(['log', '--format=%s', `${h.newerBase}..HEAD`], h.source)
+ ).trim();
+ expect(personal.split('\n').filter((line) => line === 'shared personal change')).toHaveLength(
+ 1,
+ );
+ } finally {
+ await h.clean();
+ }
+ },
+ 60_000,
+);
+
+it.each([false, true])(
+ 'refuses to adopt a combine that dropped one side’s change (task identity: %s)',
+ async (generic) => {
+ const h = await fixture(true, generic);
+ try {
+ const result = await preparePersonalCombine(h.userData, h.state, h.git, async () => {});
+ expect(result.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, h.state.id);
+ // The resolver skips this computer's conflicting change instead of combining it.
+ await h.git(['-c', 'core.editor=true', 'rebase', '--skip'], worktree);
+ await expect(applyUpstreamMerge(h.userData, result, h.git)).rejects.toMatchObject({
+ code: 'checksFailed',
+ });
+ // Nothing was adopted; the candidate stays for the task.
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(h.local);
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
+ 'from this computer\n',
+ );
+ await expect(stat(worktree)).resolves.toBeTruthy();
+ } finally {
+ await h.clean();
+ }
+ },
+ 60_000,
+);
+
+it('asks before adopting a fused conflict between commits that share the task identity', async () => {
+ const h = await fixture(true, true);
+ try {
+ const result = await preparePersonalCombine(h.userData, h.state, h.git, async () => {});
+ expect(result.status).toBe('conflict');
+ const worktree = mergeWorktree(h.userData, h.state.id);
+ await writeFile(
+ path.join(worktree, 'feature.txt'),
+ 'from the other computer\nfrom this computer\n',
+ );
+ await h.git(['add', '.'], worktree);
+ await h.git(
+ [
+ '-c',
+ 'user.name=Cindy Make',
+ '-c',
+ '-c',
+ 'core.editor=true',
+ '-c',
+ 'commit.gpgSign=false',
+ 'rebase',
+ '--continue',
+ ],
+ worktree,
+ );
+ const refused = await applyUpstreamMerge(h.userData, result, h.git).catch((error) => error);
+ expect(refused).toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [h.local] },
+ });
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(h.local);
+ await expect(
+ applyUpstreamMerge(h.userData, { ...result, missing: refused.missing }, h.git, () => true, {
+ acceptMissing: true,
+ }),
+ ).resolves.toMatchObject({
+ status: 'merged',
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('adopts a combine whose replayed change was already present on the kept side', async () => {
+ const h = await fixture(false, true);
+ try {
+ // The other computer already has this computer's exact edit, made as its own commit.
+ const other = path.join(h.userData, 'other');
+ await writeFile(path.join(other, 'feature.txt'), 'from this computer\n');
+ await h.git(['add', '.'], other);
+ await h.git(
+ [
+ '-c',
+ 'user.name=Other',
+ '-c',
+ 'commit',
+ '-m',
+ 'same edit, written differently on the other computer',
+ ],
+ other,
+ );
+ await h.git(['push', 'origin', 'cindy-personal'], other);
+ const fork = path.join(h.userData, 'fork.git');
+ await h.git(['fetch', fork, `+refs/heads/cindy-personal:${PERSONAL_TRACKING_REF}`], h.source);
+ const remoteTip = (await h.git(['rev-parse', PERSONAL_TRACKING_REF], h.source)).trim();
+ const result = await preparePersonalCombine(
+ h.userData,
+ { ...h.state, upstreamCommit: remoteTip, remote: { base: h.base, commit: remoteTip } },
+ h.git,
+ async () => {},
+ );
+ expect(result.status).toBe('merged');
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('from this computer\n');
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
diff --git a/apps/desktop/src/main/cindy-make/__tests__/personalContribution.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/personalContribution.git-integration.test.ts
new file mode 100644
index 0000000000..143f76b3d5
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/personalContribution.git-integration.test.ts
@@ -0,0 +1,276 @@
+import os from 'node:os';
+import path from 'node:path';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { expect, it, vi } from 'vitest';
+import { PersonalContribution, type ContributionRecord } from '../personalContribution';
+import { personalGitEnv, type PersonalRemoteGitOptions } from '../personalRemote';
+import { makeSourceCheckoutPath } from '../sourcePaths';
+import { runSourceGit } from '../sourceGit';
+
+const TOKEN = 'gho_fake-token-for-tests';
+const FORK_URL = 'https://github.com/octo/cindy.git';
+const OFFICIAL_URL = 'https://github.com/makecindy/cindy.git';
+
+/** Official repository, the author's fork and a personal checkout with one finished change. */
+async function fixture(conflict: boolean) {
+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-contribution-'));
+ const source = makeSourceCheckoutPath(userData);
+ const official = path.join(userData, 'official');
+ const fork = path.join(userData, 'fork.git');
+ const env = {
+ PATH: process.env.PATH,
+ SystemRoot: process.env.SystemRoot,
+ GIT_CONFIG_GLOBAL: path.join(userData, 'gitconfig'),
+ GIT_CONFIG_NOSYSTEM: '1',
+ };
+ const raw = (args: string[], cwd: string) =>
+ runSourceGit(env, args, cwd, AbortSignal.timeout(30_000));
+ const git = async (args: string[], cwd: string, options?: PersonalRemoteGitOptions) => {
+ return runSourceGit(
+ personalGitEnv(env, options),
+ args.map((arg) => (arg === FORK_URL ? fork : arg === OFFICIAL_URL ? official : arg)),
+ cwd,
+ AbortSignal.timeout(30_000),
+ );
+ };
+ const commit = async (cwd: string, message: string) => {
+ await raw(['add', '.'], cwd);
+ await raw(
+ [
+ '-c',
+ 'user.name=Test',
+ '-c',
+ 'commit',
+ '-s',
+ '-m',
+ message,
+ ],
+ cwd,
+ );
+ };
+ await writeFile(env.GIT_CONFIG_GLOBAL, '');
+ await mkdir(official);
+ await mkdir(path.dirname(source), { recursive: true });
+ await raw(['init', '--initial-branch=main'], official);
+ await writeFile(path.join(official, 'app.txt'), 'line one\nline two\n');
+ await writeFile(path.join(official, 'other.txt'), 'other\n');
+ await commit(official, 'official base');
+ await raw(['clone', '--bare', official, fork], userData);
+ await raw(['clone', official, source], userData);
+ await raw(['checkout', '-b', 'cindy-personal'], source);
+ // An earlier personal change that must not be part of this contribution.
+ await writeFile(path.join(source, 'unrelated-personal.txt'), 'mine only\n');
+ await commit(source, 'unrelated personal change');
+ await raw(['remote', 'add', 'personal', fork], source);
+ // The task starts from the personal version and changes one line.
+ const baseTree = (await raw(['rev-parse', 'HEAD^{tree}'], source)).trim();
+ await writeFile(path.join(source, 'app.txt'), 'line one\nline two changed\n');
+ await commit(source, 'task change');
+ const tree = (await raw(['rev-parse', 'HEAD^{tree}'], source)).trim();
+ // Official main moves on before the contribution.
+ if (conflict) await writeFile(path.join(official, 'app.txt'), 'line one\nline two official\n');
+ else await writeFile(path.join(official, 'other.txt'), 'other updated\n');
+ await commit(official, 'official update');
+
+ let store: Record<string, ContributionRecord> = {};
+ let failNextStoreWrite = false;
+ const github = { number: 7, state: 'open' };
+ const pull = () => ({
+ number: github.number,
+ html_url: `https://github.com/makecindy/cindy/pull/${github.number}`,
+ state: github.state,
+ });
+ const fetchFn = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ const target = String(url);
+ if (
+ target === 'https://api.github.com/repos/makecindy/cindy/pulls' &&
+ init?.method === 'POST'
+ ) {
+ if (github.state === 'closed')
+ Object.assign(github, { number: github.number + 1, state: 'open' });
+ return new Response(JSON.stringify(pull()), { status: 201 });
+ }
+ if (target.endsWith(`/pulls/${github.number}`) && ['GET', 'PATCH'].includes(init?.method ?? ''))
+ return new Response(JSON.stringify(pull()), { status: 200 });
+ // The open-pull lookup for a head: a confirmed empty list (never a guess).
+ if (target.startsWith('https://api.github.com/repos/makecindy/cindy/pulls?state=open&head='))
+ return new Response('[]', { status: 200 });
+ return new Response('{}', { status: 404 });
+ });
+ const contribution = new PersonalContribution({
+ source,
+ ownerScope: () => 'owner-1',
+ binding: () => ({ schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' }),
+ identity: async () => ({ status: 'connected', identity: { login: 'octo', token: TOKEN } }),
+ inspectFork: async () => ({ repository: 'octo/cindy', archived: false, canPush: true }),
+ git,
+ change: (runId) =>
+ runId === 'run-1'
+ ? { title: '把第二行改得更清楚', request: '让第二行更清楚', baseTree, tree }
+ : undefined,
+ ledgerPath: () => 'ledger.json',
+ readStore: () => structuredClone(store),
+ writeStore: (_file, next) => {
+ if (failNextStoreWrite) {
+ failNextStoreWrite = false;
+ throw new Error('disk full');
+ }
+ store = structuredClone(next);
+ },
+ fetch: fetchFn as unknown as typeof fetch,
+ gitIdentity: async () => ({ name: 'Ada Author', email: '[email protected]' }),
+ withSourceUse: (run) => run(),
+ now: () => 1_000,
+ });
+ return {
+ userData,
+ source,
+ fork,
+ official,
+ raw,
+ contribution,
+ fetchFn,
+ github,
+ store: () => store,
+ failNextStoreWrite: () => {
+ failNextStoreWrite = true;
+ },
+ clean: () => rm(userData, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }),
+ };
+}
+
+it('opens a pull request with only this change, on the latest official main, signed by the author', async () => {
+ const h = await fixture(false);
+ try {
+ const draft = await h.contribution.draft('run-1');
+ expect(draft).toMatchObject({
+ title: 'feat: 把第二行改得更清楚',
+ name: 'Ada Author',
+ email: '[email protected]',
+ files: ['app.txt'],
+ touchesUi: false,
+ });
+ expect(draft.body).toContain('引用的设计规范:不涉及');
+
+ const view = await h.contribution.submit({ ...draft, runId: 'run-1' });
+ expect(view).toMatchObject({ number: 7, url: 'https://github.com/makecindy/cindy/pull/7' });
+ const branch = 'refs/heads/cindy-make-pr/run-1';
+ const head = (await h.raw(['rev-parse', branch], h.fork)).trim();
+ const officialMain = (await h.raw(['rev-parse', 'main'], h.official)).trim();
+ expect((await h.raw(['rev-parse', `${head}^`], h.fork)).trim()).toBe(officialMain);
+ expect((await h.raw(['show', `${head}:app.txt`], h.fork)).trim()).toBe(
+ 'line one\nline two changed',
+ );
+ expect((await h.raw(['show', `${head}:other.txt`], h.fork)).trim()).toBe('other updated');
+ await expect(h.raw(['show', `${head}:unrelated-personal.txt`], h.fork)).rejects.toBeTruthy();
+ expect((await h.raw(['log', '-1', '--format=%an <%ae>%n%B', head], h.fork)).trim()).toBe(
+ 'Ada Author <[email protected]>\nfeat: 把第二行改得更清楚\n\nSigned-off-by: Ada Author <[email protected]>',
+ );
+ const pullRequest = h.fetchFn.mock.calls.find(([, init]) => init?.method === 'POST');
+ expect(JSON.parse(String(pullRequest?.[1]?.body))).toMatchObject({
+ head: 'octo:cindy-make-pr/run-1',
+ base: 'main',
+ title: 'feat: 把第二行改得更清楚',
+ maintainer_can_modify: true,
+ });
+ expect(h.store()['run-1']).toMatchObject({
+ number: 7,
+ branch: 'cindy-make-pr/run-1',
+ commit: head,
+ });
+
+ // Submitting again updates the same branch and pull request.
+ await h.contribution.submit({ ...draft, runId: 'run-1', title: 'feat: 更新后的标题' });
+ expect(h.fetchFn.mock.calls.some(([, init]) => init?.method === 'PATCH')).toBe(true);
+ const patch = h.fetchFn.mock.calls.find(([, init]) => init?.method === 'PATCH')?.[1];
+ expect(JSON.parse(String(patch?.body))).toMatchObject({ base: 'main' });
+ expect((await h.raw(['log', '-1', '--format=%s', branch], h.fork)).trim()).toBe(
+ 'feat: 更新后的标题',
+ );
+
+ // Once maintainers close it and delete its branch, a resubmission is a new pull
+ // request from a recreated branch; the closed one is left exactly as it was.
+ h.github.state = 'closed';
+ await h.raw(['update-ref', '-d', branch], h.fork);
+ const patches = () =>
+ h.fetchFn.mock.calls.filter(([, init]) => init?.method === 'PATCH').length;
+ const patchedBefore = patches();
+ await expect(
+ h.contribution.submit({ ...draft, runId: 'run-1', title: 'feat: 再次提交' }),
+ ).resolves.toMatchObject({ number: 8, state: 'open' });
+ expect(h.fetchFn.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(2);
+ expect(patches()).toBe(patchedBefore);
+ expect((await h.raw(['log', '-1', '--format=%s', branch], h.fork)).trim()).toBe(
+ 'feat: 再次提交',
+ );
+ expect(h.store()['run-1']).toMatchObject({ number: 8, branch: 'cindy-make-pr/run-1' });
+
+ // With the closed pull request's branch still on the fork, the resubmission is
+ // again a new pull request — from a new branch, leaving the old commits alone.
+ h.github.state = 'closed';
+ const oldHead = (await h.raw(['rev-parse', branch], h.fork)).trim();
+ await expect(
+ h.contribution.submit({ ...draft, runId: 'run-1', title: 'feat: 不改写旧分支' }),
+ ).resolves.toMatchObject({ number: 9, state: 'open' });
+ expect((await h.raw(['rev-parse', branch], h.fork)).trim()).toBe(oldHead);
+ expect((await h.raw(['log', '-1', '--format=%s', branch], h.fork)).trim()).toBe(
+ 'feat: 再次提交',
+ );
+ const resubmitted = 'refs/heads/cindy-make-pr/run-1-2';
+ expect((await h.raw(['log', '-1', '--format=%s', resubmitted], h.fork)).trim()).toBe(
+ 'feat: 不改写旧分支',
+ );
+ expect(h.store()['run-1']).toMatchObject({ number: 9, branch: 'cindy-make-pr/run-1-2' });
+ const created = h.fetchFn.mock.calls.filter(([, init]) => init?.method === 'POST').at(-1);
+ expect(JSON.parse(String(created?.[1]?.body))).toMatchObject({
+ head: 'octo:cindy-make-pr/run-1-2',
+ });
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('reconciles a pushed update when its contribution ledger write fails', async () => {
+ const h = await fixture(false);
+ try {
+ const draft = await h.contribution.draft('run-1');
+ await h.contribution.submit({ ...draft, runId: 'run-1' });
+ const before = h.store()['run-1'].commit;
+ h.failNextStoreWrite();
+ await expect(
+ h.contribution.submit({ ...draft, runId: 'run-1', title: 'feat: 重试台账' }),
+ ).rejects.toThrow('disk full');
+ const branch = 'refs/heads/cindy-make-pr/run-1';
+ const remoteAfterFailure = (await h.raw(['rev-parse', branch], h.fork)).trim();
+ expect(remoteAfterFailure).not.toBe(before);
+
+ // The retry sees the old lease in its local ledger, fetches the branch tip,
+ // verifies its tree/parent/author, and records that already-pushed commit.
+ await expect(
+ h.contribution.submit({ ...draft, runId: 'run-1', title: 'feat: 重试台账' }),
+ ).resolves.toMatchObject({ number: 7, state: 'open' });
+ expect(h.store()['run-1'].commit).toBe(remoteAfterFailure);
+ expect(h.fetchFn.mock.calls.filter(([, init]) => init?.method === 'PATCH')).toHaveLength(1);
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('reports a conflict with the latest official code instead of submitting', async () => {
+ const h = await fixture(true);
+ try {
+ const draft = await h.contribution.draft('run-1');
+ await expect(h.contribution.submit({ ...draft, runId: 'run-1' })).rejects.toMatchObject({
+ code: 'conflict',
+ });
+ await expect(
+ h.raw(['rev-parse', 'refs/heads/cindy-make-pr/run-1'], h.fork),
+ ).rejects.toBeTruthy();
+ expect(h.fetchFn.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false);
+ // The personal checkout is untouched.
+ expect((await h.raw(['status', '--porcelain'], h.source)).trim()).toBe('');
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
diff --git a/apps/desktop/src/main/cindy-make/__tests__/personalContribution.test.ts b/apps/desktop/src/main/cindy-make/__tests__/personalContribution.test.ts
new file mode 100644
index 0000000000..def557d9f8
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/personalContribution.test.ts
@@ -0,0 +1,970 @@
+import { readFile, stat, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+import {
+ PersonalContribution,
+ contributionBody,
+ parseContributionStore,
+ type ContributionDeps,
+ type ContributionRecord,
+} from '../personalContribution';
+import { PersonalRemoteError } from '../personalRemote';
+
+const TOKEN = 'gho_fake-token-for-tests';
+const A = 'a'.repeat(40);
+const B = 'b'.repeat(40);
+
+async function fakeDiff(args: string[]): Promise<string> {
+ const output = args.find((arg) => arg.startsWith('--output='));
+ if (args.includes('--name-only') && output)
+ await writeFile(output.slice('--output='.length), 'app.txt\0');
+ return '';
+}
+const record = (runId: string, number: number): ContributionRecord => ({
+ runId,
+ number,
+ url: `https://github.com/makecindy/cindy/pull/${number}`,
+ branch: `cindy-make-pr/${runId}`,
+ commit: A,
+ submittedAt: 1,
+});
+
+function harness(overrides: Partial<ContributionDeps> = {}) {
+ let store: Record<string, ContributionRecord> = {};
+ const deps: ContributionDeps = {
+ source: 'source',
+ ownerScope: () => 'owner-1',
+ binding: () => ({ schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' }),
+ identity: async () => ({ status: 'connected', identity: { login: 'octo', token: TOKEN } }),
+ inspectFork: async () => ({ repository: 'octo/cindy', archived: false, canPush: true }),
+ git: vi.fn(async (args: string[]) => {
+ if (args[0] === 'diff') {
+ const output = args.find((arg) => arg.startsWith('--output='));
+ if (output) {
+ await writeFile(
+ output.slice('--output='.length),
+ 'apps/desktop/src/renderer/x.tsx\0docs/a.md\0',
+ );
+ return '';
+ }
+ return 'apps/desktop/src/renderer/x.tsx\0docs/a.md\0';
+ }
+ throw new Error('unexpected git ' + args.join(' '));
+ }),
+ change: (runId) =>
+ runId === 'run'
+ ? { title: '加一个按钮', request: '我想要按钮', baseTree: A, tree: B }
+ : undefined,
+ ledgerPath: () => 'ledger.json',
+ readStore: () => structuredClone(store),
+ writeStore: (_file, next) => {
+ store = structuredClone(next);
+ },
+ fetch: vi.fn(async () => new Response('{}', { status: 404 })) as unknown as typeof fetch,
+ gitIdentity: async () => ({}),
+ withSourceUse: (run) => run(),
+ now: () => 10_000,
+ ...overrides,
+ };
+ return {
+ contribution: new PersonalContribution(deps),
+ deps,
+ setStore: (next: typeof store) => (store = next),
+ };
+}
+
+describe('parseContributionStore', () => {
+ it('keeps only well-formed records pointing at official pull requests', () => {
+ expect(
+ parseContributionStore(
+ JSON.stringify({
+ good: record('good', 3),
+ wrong: { ...record('wrong', 4), url: 'https://example.com/pull/4' },
+ mismatch: record('other', 5),
+ }),
+ ),
+ ).toEqual({ good: record('good', 3) });
+ expect(parseContributionStore('nope')).toEqual({});
+ expect(parseContributionStore(null)).toEqual({});
+ });
+});
+
+describe('contributionBody', () => {
+ it('follows the PR template and asks for the design basis only for UI changes', () => {
+ const ui = contributionBody({
+ title: 'feat: x',
+ request: '需求',
+ files: ['a.css'],
+ touchesUi: true,
+ });
+ for (const heading of ['## 这次改了什么', '## 怎么验证的', '## 风险', '### 提交前检查'])
+ expect(ui).toContain(heading);
+ expect(ui).toContain('- [x] `feat` 新功能');
+ expect(ui).toContain('引用的设计规范:docs/design-rules/DESIGN.md');
+ expect(
+ contributionBody({ title: 'fix: y', request: '', files: ['a.ts'], touchesUi: false }),
+ ).toContain('引用的设计规范:不涉及:');
+ });
+});
+
+describe('PersonalContribution', () => {
+ it('rejects a submission when the recorded source changed after the draft was shown', async () => {
+ const change = { title: 'reviewed', request: 'reviewed', baseTree: A, tree: B };
+ const { contribution, deps } = harness({ change: () => change });
+ const draft = await contribution.draft('run');
+ vi.mocked(deps.git).mockClear();
+ // Mutating the original record must not mutate the issued confirmation.
+ change.tree = 'c'.repeat(40);
+ await expect(contribution.submit({ ...draft, email: '[email protected]' })).rejects.toMatchObject(
+ { code: 'changed' },
+ );
+ expect(deps.git).not.toHaveBeenCalled();
+ });
+
+ it.each(['missing', 'forged', 'another run'] as const)(
+ 'requires the exact Main-issued confirmation: %s',
+ async (kind) => {
+ const { contribution, deps } = harness();
+ const draft = await contribution.draft('run');
+ vi.mocked(deps.git).mockClear();
+ await expect(
+ contribution.submit({
+ ...draft,
+ email: '[email protected]',
+ ...(kind === 'another run'
+ ? { runId: 'other' }
+ : {
+ snapshotId: kind === 'missing' ? undefined! : 'not-issued',
+ }),
+ }),
+ ).rejects.toMatchObject({ code: 'changed' });
+ expect(deps.git).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['account', 'fork'] as const)('binds the draft to its %s', async (kind) => {
+ let scope = 'owner-1';
+ let repository = 'octo/cindy';
+ const { contribution, deps } = harness({
+ ownerScope: () => scope,
+ binding: () => ({ schema: 1, choice: 'github', login: 'octo', repository }),
+ });
+ const draft = await contribution.draft('run');
+ vi.mocked(deps.git).mockClear();
+ if (kind === 'account') scope = 'owner-2';
+ else repository = 'octo/another-fork';
+ await expect(contribution.submit({ ...draft, email: '[email protected]' })).rejects.toMatchObject(
+ {
+ code: kind === 'account' ? 'account' : 'changed',
+ },
+ );
+ expect(deps.git).not.toHaveBeenCalled();
+ });
+
+ it.each(['source lock', 'commit', 'retry'] as const)(
+ 'rechecks the confirmed snapshot after awaiting the %s',
+ async (phase) => {
+ const change = { title: 't', request: 'r', baseTree: A, tree: B };
+ const drift = () => {
+ change.tree = 'c'.repeat(40);
+ };
+ const pushes: string[][] = [];
+ const git = vi.fn(async (args: string[]) => {
+ if (args[0] === 'diff') return fakeDiff(args);
+ if (args[0] === 'rev-parse') return args[1].includes('{tree}') ? A : B;
+ if (args[0] === 'write-tree') return B;
+ if (args.includes('commit-tree')) {
+ if (phase === 'commit') drift();
+ return B;
+ }
+ if (args[0] === 'push') {
+ pushes.push(args);
+ drift();
+ throw new Error('remote ref already exists');
+ }
+ if (args[0] === 'ls-remote') return A + '\trefs/heads/cindy-make-pr/run';
+ return '';
+ });
+ const fetchFn = vi.fn(async () => new Response('[]', { status: 200 }));
+ const { contribution, deps } = harness({
+ change: () => change,
+ git,
+ fetch: fetchFn,
+ gitIdentity: async () => ({ name: 'Ada', email: '[email protected]' }),
+ withSourceUse: async (run) => {
+ if (phase === 'source lock') drift();
+ return run();
+ },
+ });
+ const draft = await contribution.draft('run');
+ await expect(contribution.submit(draft)).rejects.toMatchObject({ code: 'changed' });
+ expect(pushes).toHaveLength(phase === 'retry' ? 1 : 0);
+ expect(deps.readStore('ledger.json')).toEqual({});
+ expect(fetchFn).toHaveBeenCalledTimes(phase === 'retry' ? 1 : 0);
+ },
+ );
+
+ it('reads every contribution path beyond the Git capture limit before deciding its UI scope', async () => {
+ const files = [
+ ...Array.from(
+ { length: 2_000 },
+ (_, i) => 'docs/' + String(i).padStart(4, '0') + '-' + 'x'.repeat(45) + '.md',
+ ),
+ 'apps/desktop/src/renderer/last.tsx',
+ 'docs/trailing space ',
+ 'docs/line\nbreak.md',
+ ];
+ const listed = files.join('\0') + '\0';
+ expect(listed.length).toBeGreaterThan(64 * 1024);
+ let outputFile = '';
+ const { contribution } = harness({
+ git: vi.fn(async (args: string[]) => {
+ const output = args.find((arg) => arg.startsWith('--output='));
+ if (!output) return listed.slice(0, 64 * 1024);
+ outputFile = output.slice('--output='.length);
+ await writeFile(outputFile, listed);
+ return '';
+ }),
+ });
+ const draft = await contribution.draft('run');
+ expect(draft.files).toEqual(files);
+ expect(draft.touchesUi).toBe(true);
+ expect(draft.body).toContain('引用的设计规范:docs/design-rules/DESIGN.md');
+ expect(outputFile).not.toBe('');
+ await expect(stat(path.dirname(outputFile))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it.each(['git failure', 'missing output', 'incomplete output'] as const)(
+ 'refuses a contribution draft and cleans its temporary directory after %s',
+ async (failure) => {
+ let outputFile = '';
+ const { contribution } = harness({
+ git: vi.fn(async (args: string[]) => {
+ const output = args.find((arg) => arg.startsWith('--output='));
+ if (!output) return 'docs/a.md\0';
+ outputFile = output.slice('--output='.length);
+ if (failure !== 'missing output') await writeFile(outputFile, 'docs/a.md');
+ if (failure === 'git failure') throw new Error('git failed');
+ return '';
+ }),
+ });
+ await expect(contribution.draft('run')).rejects.toMatchObject({ code: 'unavailable' });
+ expect(outputFile).not.toBe('');
+ await expect(readFile(outputFile)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(stat(path.dirname(outputFile))).rejects.toMatchObject({ code: 'ENOENT' });
+ },
+ );
+
+ it('prefills a draft with the author identity from the GitHub profile when Git has none', async () => {
+ const fetchFn = vi.fn(
+ async () =>
+ new Response(JSON.stringify({ name: 'Octo Cat', email: '[email protected]' }), {
+ status: 200,
+ }),
+ );
+ const { contribution } = harness({ fetch: fetchFn as unknown as typeof fetch });
+ await expect(contribution.draft('run')).resolves.toMatchObject({
+ title: 'feat: 加一个按钮',
+ name: 'Octo Cat',
+ email: '[email protected]',
+ touchesUi: true,
+ files: ['apps/desktop/src/renderer/x.tsx', 'docs/a.md'],
+ repository: 'octo/cindy',
+ });
+ });
+
+ it('tells the draft whether the earlier pull request is still open', async () => {
+ const fetchFn = vi.fn(async (url: string | URL | Request) =>
+ String(url).endsWith('/pulls/3')
+ ? new Response(JSON.stringify({ state: 'closed', merged_at: null }), { status: 200 })
+ : new Response('{}', { status: 404 }),
+ );
+ const { contribution, setStore } = harness({ fetch: fetchFn as unknown as typeof fetch });
+ setStore({ run: record('run', 3) });
+ await expect(contribution.draft('run')).resolves.toMatchObject({
+ existing: { number: 3, state: 'closed' },
+ });
+ });
+
+ it('leaves the email for the author to fill in rather than inventing one', async () => {
+ const { contribution } = harness();
+ await expect(contribution.draft('run')).resolves.toMatchObject({ name: 'octo', email: '' });
+ });
+
+ it.each([
+ ['notBound', { binding: () => ({ schema: 1 as const }) }],
+ ['github', { identity: async () => ({ status: 'missing' as const }) }],
+ [
+ 'account',
+ {
+ identity: async () => ({
+ status: 'connected' as const,
+ identity: { login: 'someone', token: TOKEN },
+ }),
+ },
+ ],
+ ['unavailable', { change: () => undefined }],
+ ['empty', { change: () => ({ title: 't', request: 'r', baseTree: A, tree: A }) }],
+ [
+ 'notBound',
+ {
+ inspectFork: async () => {
+ throw new PersonalRemoteError('forkMissing');
+ },
+ },
+ ],
+ ])('refuses a draft when %s', async (code, overrides) => {
+ await expect(harness(overrides).contribution.draft('run')).rejects.toMatchObject({ code });
+ });
+
+ it('validates the confirmed fields before touching Git or GitHub', async () => {
+ const { contribution, deps } = harness();
+ for (const input of [
+ { title: '', body: '', name: 'Ada', email: '[email protected]' },
+ { title: 'feat: x', body: '', name: '', email: '[email protected]' },
+ { title: 'feat: x', body: '', name: 'Ada', email: 'not-an-email' },
+ { title: 'feat:\nx', body: '', name: 'Ada', email: '[email protected]' },
+ ])
+ await expect(
+ contribution.submit({ runId: 'run', snapshotId: 'unissued', ...input }),
+ ).rejects.toMatchObject({
+ code: 'invalid',
+ });
+ expect(deps.git).not.toHaveBeenCalled();
+ });
+
+ it.each(['created', 'duplicate'] as const)('invalidates the read-only resource after a successful submission: %s', async (creation) => {
+ const onChanged = vi.fn();
+ const git = vi.fn(async (args: string[]) => {
+ const op = args.includes('commit-tree')
+ ? 'commit-tree'
+ : args.includes('write-tree')
+ ? 'write-tree'
+ : args[0];
+ switch (op) {
+ case 'fetch':
+ case 'read-tree':
+ case 'apply':
+ case 'push':
+ return '';
+ case 'diff':
+ return fakeDiff(args);
+ case 'ls-files':
+ return '';
+ case 'rev-parse':
+ return args[1]?.includes('{tree}') ? A : B;
+ case 'write-tree':
+ case 'commit-tree':
+ return B;
+ default:
+ throw new Error('unexpected git ' + args.join(' '));
+ }
+ });
+ const pull = {
+ number: 9, html_url: 'https://github.com/makecindy/cindy/pull/9',
+ state: 'open', base: { ref: 'another-base' },
+ };
+ let posted = false;
+ const fetchFn = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ if (init?.method === 'POST') {
+ posted = true;
+ return creation === 'duplicate'
+ ? new Response('{}', { status: 422 })
+ : new Response(JSON.stringify(pull), { status: 201 });
+ }
+ if (String(url).includes('/pulls?state=open'))
+ return new Response(JSON.stringify(posted ? [pull] : []), { status: 200 });
+ if (String(url).endsWith('/pulls/9'))
+ return new Response(JSON.stringify(pull), { status: 200 });
+ return new Response('{}', { status: 404 });
+ });
+ const { contribution } = harness({
+ git: git as unknown as ContributionDeps['git'],
+ fetch: fetchFn as unknown as typeof fetch,
+ onChanged,
+ });
+ await expect(
+ contribution.submit({
+ snapshotId: (await contribution.draft('run')).snapshotId,
+ runId: 'run',
+ title: 'feat: x',
+ body: '',
+ name: 'Ada',
+ email: '[email protected]',
+ }),
+ ).resolves.toMatchObject({ number: 9, state: 'open' });
+ expect(onChanged).toHaveBeenCalledOnce();
+ expect(onChanged).toHaveBeenCalledWith('run');
+ if (creation === 'duplicate') {
+ const patch = fetchFn.mock.calls.find(([, init]) => init?.method === 'PATCH')?.[1];
+ expect(JSON.parse(String(patch?.body))).toMatchObject({ base: 'main' });
+ }
+ });
+
+ it('stops the submission when the Cindy account changes while it runs', async () => {
+ let scope = 'owner-1';
+ const writes: unknown[] = [];
+ const git = vi.fn(async (args: string[]) => {
+ const op = args.includes('commit-tree')
+ ? 'commit-tree'
+ : args.includes('write-tree')
+ ? 'write-tree'
+ : args[0];
+ switch (op) {
+ case 'fetch':
+ case 'read-tree':
+ case 'apply':
+ return '';
+ case 'diff':
+ return fakeDiff(args);
+ case 'ls-files':
+ return '';
+ case 'rev-parse':
+ return args[1]?.includes('{tree}') ? A : B;
+ case 'write-tree':
+ return B;
+ case 'commit-tree':
+ // The account switch happens while the submission is doing its Git work.
+ scope = 'owner-2';
+ return A;
+ default:
+ throw new Error('unexpected git ' + args.join(' '));
+ }
+ });
+ const { contribution } = harness({
+ ownerScope: () => scope,
+ git: git as unknown as ContributionDeps['git'],
+ writeStore: (_file, store) => {
+ writes.push(store);
+ },
+ });
+ await expect(
+ contribution.submit({
+ snapshotId: (await contribution.draft('run')).snapshotId,
+ runId: 'run',
+ title: 'feat: x',
+ body: '',
+ name: 'Ada',
+ email: '[email protected]',
+ }),
+ ).rejects.toMatchObject({ code: 'account' });
+ // The other account's ledger stays empty and its identity never pushes.
+ expect(writes).toEqual([]);
+ expect(git.mock.calls.some(([args]) => args[0] === 'push')).toBe(false);
+ });
+
+ it('records the moved branch and restores main when updating a retargeted pull request', async () => {
+ let store: Record<string, ContributionRecord> = {
+ run: {
+ runId: 'run',
+ number: 3,
+ url: 'https://github.com/makecindy/cindy/pull/3',
+ branch: 'cindy-make-pr/run',
+ commit: A,
+ submittedAt: 1,
+ },
+ };
+ const git = vi.fn(async (args: string[]) => {
+ const op = args.includes('commit-tree')
+ ? 'commit-tree'
+ : args.includes('write-tree')
+ ? 'write-tree'
+ : args[0];
+ switch (op) {
+ case 'fetch':
+ case 'read-tree':
+ case 'apply':
+ case 'push':
+ return '';
+ case 'diff':
+ return fakeDiff(args);
+ case 'ls-files':
+ return '';
+ case 'rev-parse':
+ return args[1]?.includes('{tree}') ? A : B;
+ case 'write-tree':
+ return B;
+ case 'commit-tree':
+ return B;
+ default:
+ throw new Error('unexpected git ' + args.join(' '));
+ }
+ });
+ const fetchFn = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ if (init?.method === 'PATCH') throw new Error('offline');
+ if (String(url).endsWith('/pulls/3'))
+ return new Response(
+ JSON.stringify({
+ number: 3,
+ html_url: 'https://github.com/makecindy/cindy/pull/3',
+ state: 'open',
+ base: { ref: 'another-base' },
+ }),
+ { status: 200 },
+ );
+ return new Response('{}', { status: 404 });
+ });
+ const { contribution } = harness({
+ git: git as unknown as ContributionDeps['git'],
+ fetch: fetchFn as unknown as typeof fetch,
+ ledgerPath: () => 'ledger.json',
+ readStore: () => structuredClone(store),
+ writeStore: (_file, next) => {
+ store = structuredClone(next);
+ },
+ });
+ await expect(
+ contribution.submit({
+ snapshotId: (await contribution.draft('run')).snapshotId,
+ runId: 'run',
+ title: 'feat: x',
+ body: '',
+ name: 'Ada',
+ email: '[email protected]',
+ }),
+ ).rejects.toMatchObject({ code: 'network' });
+ // The push this client already made is recorded: a retry leases against it
+ // instead of failing forever against a branch this client itself moved.
+ expect(store.run).toMatchObject({ number: 3, branch: 'cindy-make-pr/run', commit: B });
+ const patch = fetchFn.mock.calls.find(([, init]) => init?.method === 'PATCH')?.[1];
+ expect(JSON.parse(String(patch?.body))).toMatchObject({ base: 'main' });
+ });
+
+ it('records the pushed commit in the initiating ledger even when the account switches', async () => {
+ let scope = 'owner-1';
+ let store: Record<string, ContributionRecord> = {
+ run: {
+ runId: 'run',
+ number: 3,
+ url: 'https://github.com/makecindy/cindy/pull/3',
+ branch: 'cindy-make-pr/run',
+ commit: A,
+ submittedAt: 1,
+ },
+ };
+ const writes: Record<string, ContributionRecord>[] = [];
+ const git = vi.fn(async (args: string[]) => {
+ const op = args.includes('commit-tree')
+ ? 'commit-tree'
+ : args.includes('write-tree')
+ ? 'write-tree'
+ : args[0];
+ switch (op) {
+ case 'fetch':
+ case 'read-tree':
+ case 'apply':
+ return '';
+ case 'push':
+ // The account switches while the push is awaited.
+ scope = 'owner-2';
+ return '';
+ case 'diff':
+ return fakeDiff(args);
+ case 'ls-files':
+ return '';
+ case 'rev-parse':
+ return args[1]?.includes('{tree}') ? A : B;
+ case 'write-tree':
+ case 'commit-tree':
+ return B;
+ default:
+ throw new Error('unexpected git ' + args.join(' '));
+ }
+ });
+ const fetchFn = vi.fn(async (url: string | URL | Request) =>
+ String(url).endsWith('/pulls/3')
+ ? new Response(
+ JSON.stringify({
+ number: 3,
+ html_url: 'https://github.com/makecindy/cindy/pull/3',
+ state: 'open',
+ }),
+ { status: 200 },
+ )
+ : new Response('{}', { status: 404 }),
+ );
+ const { contribution } = harness({
+ ownerScope: () => scope,
+ git: git as unknown as ContributionDeps['git'],
+ fetch: fetchFn as unknown as typeof fetch,
+ ledgerPath: () => 'ledger.json',
+ readStore: () => structuredClone(store),
+ writeStore: (file, next) => {
+ expect(file).toBe('ledger.json');
+ writes.push(structuredClone(next));
+ store = structuredClone(next);
+ },
+ });
+ await expect(
+ contribution.submit({
+ snapshotId: (await contribution.draft('run')).snapshotId,
+ runId: 'run',
+ title: 'feat: x',
+ body: '',
+ name: 'Ada',
+ email: '[email protected]',
+ }),
+ ).rejects.toMatchObject({ code: 'account' });
+ // The push this client already made is recorded in the ledger pinned at entry:
+ // a retry leases against this commit instead of failing forever.
+ expect(writes.at(-1)?.run).toMatchObject({ number: 3, commit: B });
+ });
+
+ it('aborts instead of guessing when the earlier push lookup is unknown', async () => {
+ const git = vi.fn(async (args: string[]) => {
+ const op = args.includes('commit-tree')
+ ? 'commit-tree'
+ : args.includes('write-tree')
+ ? 'write-tree'
+ : args[0];
+ switch (op) {
+ case 'fetch':
+ case 'read-tree':
+ case 'apply':
+ return '';
+ case 'push':
+ throw Object.assign(new Error('rejected'), { stderr: ' ! [rejected] stale info' });
+ case 'diff':
+ return fakeDiff(args);
+ case 'ls-files':
+ return '';
+ case 'rev-parse':
+ return args[1]?.includes('{tree}') ? A : B;
+ case 'write-tree':
+ case 'commit-tree':
+ return B;
+ default:
+ throw new Error('unexpected git ' + args.join(' '));
+ }
+ });
+ const fetchFn = vi.fn(async (_url: string | URL | Request, _init?: RequestInit) => {
+ throw new Error('offline');
+ });
+ const { contribution } = harness({
+ git: git as unknown as ContributionDeps['git'],
+ fetch: fetchFn as unknown as typeof fetch,
+ });
+ await expect(
+ contribution.submit({
+ snapshotId: (await contribution.draft('run')).snapshotId,
+ runId: 'run',
+ title: 'feat: x',
+ body: '',
+ name: 'Ada',
+ email: '[email protected]',
+ }),
+ ).rejects.toMatchObject({ code: 'network' });
+ // Unknown is not "no pull request": nothing was opened behind the user's back.
+ expect(fetchFn.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false);
+ });
+
+ it('never guesses a new pull request when the earlier state is unknown', async () => {
+ let store: Record<string, ContributionRecord> = { run: record('run', 3) };
+ const git = vi.fn(async (args: string[]) => {
+ if (args[0] === 'diff') return fakeDiff(args);
+ throw new Error('unexpected git');
+ });
+ const fetchFn = vi.fn(async () => {
+ throw new Error('offline');
+ });
+ const { contribution } = harness({
+ git: git as unknown as ContributionDeps['git'],
+ fetch: fetchFn as unknown as typeof fetch,
+ ledgerPath: () => 'ledger.json',
+ readStore: () => structuredClone(store),
+ writeStore: (_file, next) => {
+ store = structuredClone(next);
+ },
+ });
+ const { snapshotId } = await contribution.draft('run');
+ git.mockClear();
+ await expect(
+ contribution.submit({
+ snapshotId,
+ runId: 'run',
+ title: 'feat: x',
+ body: '',
+ name: 'Ada',
+ email: '[email protected]',
+ }),
+ ).rejects.toMatchObject({ code: 'network' });
+ // Nothing moved and no second public PR was opened behind the user's back.
+ expect(git).not.toHaveBeenCalled();
+ });
+
+ it('aborts instead of opening a second pull request when the first closes mid-flight', async () => {
+ let store: Record<string, ContributionRecord> = {
+ run: {
+ runId: 'run',
+ number: 3,
+ url: 'https://github.com/makecindy/cindy/pull/3',
+ branch: 'cindy-make-pr/run',
+ commit: A,
+ submittedAt: 1,
+ },
+ };
+ const git = vi.fn(async (args: string[]) => {
+ const op = args.includes('commit-tree')
+ ? 'commit-tree'
+ : args.includes('write-tree')
+ ? 'write-tree'
+ : args[0];
+ switch (op) {
+ case 'fetch':
+ case 'read-tree':
+ case 'apply':
+ case 'push':
+ return '';
+ case 'diff':
+ return fakeDiff(args);
+ case 'ls-files':
+ return '';
+ case 'rev-parse':
+ return args[1]?.includes('{tree}') ? A : B;
+ case 'write-tree':
+ case 'commit-tree':
+ return B;
+ default:
+ throw new Error('unexpected git ' + args.join(' '));
+ }
+ });
+ let reads = 0;
+ const fetchFn = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ if (String(url).endsWith('/pulls/3')) {
+ reads += 1;
+ return new Response(
+ JSON.stringify({
+ number: 3,
+ html_url: 'https://github.com/makecindy/cindy/pull/3',
+ // Open when the submission checked, closed before it could update.
+ state: reads <= 2 ? 'open' : 'closed',
+ }),
+ { status: 200 },
+ );
+ }
+ return new Response('{}', { status: 404 });
+ });
+ const { contribution } = harness({
+ git: git as unknown as ContributionDeps['git'],
+ fetch: fetchFn as unknown as typeof fetch,
+ ledgerPath: () => 'ledger.json',
+ readStore: () => structuredClone(store),
+ writeStore: (_file, next) => {
+ store = structuredClone(next);
+ },
+ });
+ await expect(
+ contribution.submit({
+ snapshotId: (await contribution.draft('run')).snapshotId,
+ runId: 'run',
+ title: 'feat: x',
+ body: '',
+ name: 'Ada',
+ email: '[email protected]',
+ }),
+ ).rejects.toMatchObject({ code: 'failed' });
+ // The dialog promised "update": no second public PR was created behind it.
+ expect(fetchFn.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false);
+ });
+
+ it.each([2, 5])(
+ 'reconciles a lost pull request response on occupied candidate %i before renaming',
+ async (candidateNumber) => {
+ const HASH_TIP = 'd'.repeat(40);
+ const reconciledBranch = `cindy-make-pr/run-${candidateNumber}`;
+ const pushes: string[] = [];
+ const git = vi.fn(async (args: string[]) => {
+ const op = args.includes('commit-tree')
+ ? 'commit-tree'
+ : args.includes('write-tree')
+ ? 'write-tree'
+ : args[0];
+ switch (op) {
+ case 'fetch':
+ case 'read-tree':
+ case 'apply':
+ return '';
+ case 'push': {
+ const lease = args
+ .find((arg) => arg.startsWith('--force-with-lease='))!
+ .split(':')
+ .at(-1)!;
+ const branch = args.at(-1)!.split(':').at(-1)!;
+ pushes.push(`${branch}:${lease}`);
+ // The earlier names belong to closed pull requests; the last one
+ // is this client's own earlier push whose pull request
+ // response was lost (its absent lease fails).
+ if (lease === '') throw new Error('remote ref already exists');
+ return '';
+ }
+ case 'ls-remote':
+ return `${HASH_TIP}\trefs/heads/${args.at(-1)}\n`;
+ case 'diff':
+ return fakeDiff(args);
+ case 'ls-files':
+ return '';
+ case 'rev-parse':
+ return args[1]?.includes('{tree}') ? A : B;
+ case 'write-tree':
+ case 'commit-tree':
+ return B;
+ default:
+ throw new Error('unexpected git ' + args.join(' '));
+ }
+ });
+ const fetchFn = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ const target = String(url);
+ if (target.includes('/pulls?state=open')) {
+ const head = new URL(target).searchParams.get('head') ?? '';
+ // Earlier names have no open PR; the last candidate holds the PR
+ // whose creation response was lost.
+ return new Response(
+ JSON.stringify(
+ head.endsWith(reconciledBranch)
+ ? [{ number: 7, html_url: 'https://github.com/makecindy/cindy/pull/7' }]
+ : [],
+ ),
+ { status: 200 },
+ );
+ }
+ if (target.endsWith('/pulls/7'))
+ return new Response(
+ JSON.stringify({
+ number: 7,
+ html_url: 'https://github.com/makecindy/cindy/pull/7',
+ state: 'open',
+ }),
+ { status: 200 },
+ );
+ return new Response('{}', { status: 404 });
+ });
+ let store: Record<string, ContributionRecord> = {};
+ const { contribution } = harness({
+ git: git as unknown as ContributionDeps['git'],
+ fetch: fetchFn as unknown as typeof fetch,
+ ledgerPath: () => 'ledger.json',
+ readStore: () => structuredClone(store),
+ writeStore: (_file, next) => {
+ store = structuredClone(next);
+ },
+ });
+ await expect(
+ contribution.submit({
+ snapshotId: (await contribution.draft('run')).snapshotId,
+ runId: 'run',
+ title: 'feat: x',
+ body: '',
+ name: 'Ada',
+ email: '[email protected]',
+ }),
+ ).resolves.toMatchObject({ number: 7, state: 'open' });
+ // The occupied candidate is reconciled against its own open PR; no second
+ // public PR is published, including beyond the old four-attempt limit.
+ expect(pushes).toEqual([
+ 'refs/heads/cindy-make-pr/run:',
+ ...Array.from(
+ { length: candidateNumber - 1 },
+ (_, i) => `refs/heads/cindy-make-pr/run-${i + 2}:`,
+ ),
+ `refs/heads/${reconciledBranch}:${HASH_TIP}`,
+ ]);
+ expect(fetchFn.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false);
+ expect(fetchFn.mock.calls.some(([, init]) => init?.method === 'PATCH')).toBe(true);
+ const patch = fetchFn.mock.calls.find(([, init]) => init?.method === 'PATCH')?.[1];
+ expect(JSON.parse(String(patch?.body))).toMatchObject({ base: 'main' });
+ expect(store.run).toMatchObject({ number: 7, branch: reconciledBranch, commit: B });
+ },
+ );
+
+ it.each(['available', 'push fails'] as const)(
+ 'retries after four closed PRs only when the candidate is actually occupied: %s',
+ async (next) => {
+ const oldBranches = ['run', 'run-2', 'run-3', 'run-4'].map((name) => `cindy-make-pr/${name}`);
+ const refs = new Map(oldBranches.map((branch) => [branch, A]));
+ const attempts: string[] = [];
+ const git = vi.fn(async (args: string[]) => {
+ if (args[0] === 'diff') return fakeDiff(args);
+ if (args.includes('commit-tree') || args[0] === 'write-tree') return B;
+ if (args[0] === 'rev-parse') return A;
+ if (args[0] === 'ls-remote') {
+ const ref = args.at(-1)!;
+ const tip = refs.get(ref.replace('refs/heads/', ''));
+ return tip ? `${tip}\t${ref}\n` : '';
+ }
+ if (args[0] === 'push') {
+ const branch = args.at(-1)!.split(':refs/heads/')[1];
+ attempts.push(branch);
+ expect(args).toContain(`--force-with-lease=refs/heads/${branch}:`);
+ if (refs.has(branch) || next === 'push fails') throw new Error('push rejected');
+ refs.set(branch, B);
+ }
+ return '';
+ });
+ const fetchFn = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ const target = String(url);
+ if (target.endsWith('/pulls/4'))
+ return new Response(JSON.stringify({ state: 'closed', merged_at: null }), {
+ status: 200,
+ });
+ if (target.includes('/pulls?state=open')) return new Response('[]', { status: 200 });
+ if (target.endsWith('/pulls') && init?.method === 'POST') {
+ expect(JSON.parse(String(init.body))).toMatchObject({ head: 'octo:cindy-make-pr/run-5' });
+ return new Response(
+ JSON.stringify({
+ number: 5,
+ html_url: 'https://github.com/makecindy/cindy/pull/5',
+ state: 'open',
+ }),
+ { status: 201 },
+ );
+ }
+ return new Response('{}', { status: 404 });
+ });
+ const { contribution, deps, setStore } = harness({
+ git,
+ fetch: fetchFn as unknown as typeof fetch,
+ });
+ setStore({ run: { ...record('run', 4), branch: 'cindy-make-pr/run-4' } });
+ const result = contribution.submit({
+ snapshotId: (await contribution.draft('run')).snapshotId,
+ runId: 'run',
+ title: 'feat: x',
+ body: '',
+ name: 'Ada',
+ email: '[email protected]',
+ });
+ if (next === 'available') {
+ await expect(result).resolves.toMatchObject({ number: 5, state: 'open' });
+ expect(deps.readStore('ledger.json').run.branch).toBe('cindy-make-pr/run-5');
+ } else {
+ await expect(result).rejects.toMatchObject({ code: 'failed' });
+ expect(deps.readStore('ledger.json').run.number).toBe(4);
+ expect(fetchFn.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false);
+ }
+ expect(attempts).toEqual([...oldBranches, 'cindy-make-pr/run-5']);
+ for (const branch of oldBranches) expect(refs.get(branch)).toBe(A);
+ },
+ );
+
+ it('reports pull request states and caches them briefly', async () => {
+ const fetchFn = vi.fn(async (url: string | URL | Request) =>
+ String(url).endsWith('/1')
+ ? new Response(JSON.stringify({ state: 'closed', merged_at: '2026-10-01' }), {
+ status: 200,
+ })
+ : String(url).endsWith('/2')
+ ? new Response(JSON.stringify({ state: 'closed', merged_at: null }), { status: 200 })
+ : new Response(JSON.stringify({ state: 'open' }), { status: 200 }),
+ );
+ const { contribution, setStore } = harness({ fetch: fetchFn as unknown as typeof fetch });
+ setStore({ a: record('a', 1), b: record('b', 2), c: record('c', 3) });
+ const states = await contribution.statuses();
+ expect(Object.fromEntries(states.map((view) => [view.runId, view.state]))).toEqual({
+ a: 'merged',
+ b: 'closed',
+ c: 'open',
+ });
+ await contribution.statuses();
+ expect(fetchFn).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/personalRemote.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/personalRemote.git-integration.test.ts
new file mode 100644
index 0000000000..7bdafb7968
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/personalRemote.git-integration.test.ts
@@ -0,0 +1,416 @@
+import os from 'node:os';
+import path from 'node:path';
+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import { expect, it } from 'vitest';
+import {
+ PersonalRemoteController,
+ personalGitEnv,
+ type PersonalRemoteGitOptions,
+ type PersonalRemoteRecord,
+} from '../personalRemote';
+import { makeSourceCheckoutPath } from '../sourcePaths';
+import { runSourceGit } from '../sourceGit';
+
+const FORK_URL = 'https://github.com/octo/cindy.git';
+const TOKEN = 'gho_fake-token-for-tests';
+
+/** Official repository, the user's fork (a bare clone) and the managed personal checkout. */
+async function fixture() {
+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-personal-remote-'));
+ const source = makeSourceCheckoutPath(userData);
+ const official = path.join(userData, 'official');
+ const fork = path.join(userData, 'fork.git');
+ const env = {
+ PATH: process.env.PATH,
+ SystemRoot: process.env.SystemRoot,
+ GIT_CONFIG_GLOBAL: path.join(userData, 'gitconfig'),
+ GIT_CONFIG_NOSYSTEM: '1',
+ };
+ const raw = (args: string[], cwd: string, extra: NodeJS.ProcessEnv = {}) =>
+ runSourceGit({ ...env, ...extra }, args, cwd, AbortSignal.timeout(30_000));
+ // The controller only knows GitHub URLs; route them to the local bare fork.
+ const git = async (args: string[], cwd: string, options?: PersonalRemoteGitOptions) => {
+ const output = await runSourceGit(
+ personalGitEnv(env, options),
+ args.map((arg) => (arg === FORK_URL ? fork : arg)),
+ cwd,
+ AbortSignal.timeout(30_000),
+ );
+ return output === fork ? FORK_URL : output;
+ };
+ const commit = async (cwd: string, message: string) => {
+ await raw(['add', '.'], cwd);
+ await raw(
+ [
+ '-c',
+ 'user.name=Test',
+ '-c',
+ '-c',
+ 'commit.gpgSign=false',
+ 'commit',
+ '-s',
+ '-m',
+ message,
+ ],
+ cwd,
+ );
+ };
+ await writeFile(env.GIT_CONFIG_GLOBAL, '');
+ await mkdir(official);
+ await mkdir(path.dirname(source), { recursive: true });
+ await raw(['init', '--initial-branch=main'], official);
+ await writeFile(path.join(official, 'app.txt'), 'official\n');
+ await commit(official, 'official base');
+ await raw(['clone', '--bare', official, fork], userData);
+ await raw(['clone', official, source], userData);
+ await raw(['checkout', '-b', 'cindy-personal'], source);
+ await writeFile(path.join(source, 'personal.txt'), 'first change\n');
+ await commit(source, 'personal change');
+
+ let record: PersonalRemoteRecord = { schema: 1 };
+ const controller = new PersonalRemoteController({
+ source,
+ read: () => structuredClone(record),
+ write: (next) => {
+ record = structuredClone(next);
+ },
+ identity: async () => ({ status: 'connected', identity: { login: 'octo', token: TOKEN } }),
+ ensureFork: async () => 'octo/cindy',
+ git,
+ sourceExists: () => existsSync(path.join(source, '.git')),
+ withProject: (run) => run(),
+ withSourceUse: (run) => run(),
+ hasUnbuiltChanges: async () => false,
+ findPersonalFork: async () => undefined,
+ isBuilt: () => false,
+ sourceSettled: () => true,
+ // The official commit the personal branch was created from, as Settings reports it.
+ officialBase: async () =>
+ (
+ await raw(['merge-base', 'refs/heads/cindy-personal', 'refs/remotes/origin/main'], source)
+ ).trim(),
+ sourceChanged: () => {},
+ publish: () => {},
+ sleep: async () => {},
+ now: () => Date.now(),
+ });
+ const tip = (cwd: string, ref = 'refs/heads/cindy-personal') =>
+ raw(['rev-parse', '--verify', ref], cwd).then((value) => value.trim());
+ return {
+ userData,
+ source,
+ fork,
+ official,
+ git,
+ raw,
+ commit,
+ controller,
+ tip,
+ record: () => record,
+ clean: () => rm(userData, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }),
+ };
+}
+
+it('uploads, fast-forwards and never overwrites a fork that another computer advanced', async () => {
+ const h = await fixture();
+ try {
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.record()).toMatchObject({ repository: 'octo/cindy', sync: 'synced' });
+ expect(await h.tip(h.fork)).toBe(await h.tip(h.source));
+ // The official base is published next to it for other computers.
+ expect(await h.tip(h.fork, 'refs/heads/cindy-personal-base')).toBe(
+ await h.tip(h.source, 'refs/remotes/origin/main'),
+ );
+ expect(await h.tip(h.source, 'refs/remotes/personal/cindy-personal')).toBe(
+ await h.tip(h.source),
+ );
+ // The remote URL carries no credential and the local config holds no token.
+ expect((await h.raw(['config', '--get', 'remote.personal.url'], h.source)).trim()).toBe(h.fork);
+ expect(await h.raw(['config', '--list', '--local'], h.source)).not.toContain(TOKEN);
+
+ await writeFile(path.join(h.source, 'personal.txt'), 'second change\n');
+ await h.commit(h.source, 'second personal change');
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.record().sync).toBe('synced');
+ expect(await h.tip(h.fork)).toBe(await h.tip(h.source));
+
+ // Another computer pushes a newer personal version to the same fork.
+ const other = path.join(h.userData, 'other');
+ await h.raw(['clone', '--branch', 'cindy-personal', h.fork, other], h.userData);
+ await writeFile(path.join(other, 'other.txt'), 'from another computer\n');
+ await h.commit(other, 'another computer');
+ await h.raw(['push', 'origin', 'cindy-personal'], other);
+ const remote = await h.tip(h.fork);
+ const local = await h.tip(h.source);
+ h.controller.sync();
+ await h.controller.settled();
+ // This computer's changes are all in the newer upload: retrieve it, never overwrite it.
+ expect(h.record()).toMatchObject({ sync: 'retrieved', syncedCommit: remote });
+ expect(await h.tip(h.fork)).toBe(remote);
+ expect(await h.tip(h.source)).toBe(remote);
+ expect(await h.tip(h.source, `refs/cindy-make/backups/personal-remote-local/${local}`)).toBe(
+ local,
+ );
+ expect(await h.tip(h.source, 'refs/cindy-make/personal-upstream')).toBe(
+ await h.tip(h.fork, 'refs/heads/cindy-personal-base'),
+ );
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('commits legacy uncommitted personal files before uploading and can disconnect', async () => {
+ const h = await fixture();
+ try {
+ await writeFile(path.join(h.source, 'legacy.txt'), 'kept work\n');
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.record()).toMatchObject({ sync: 'synced' });
+ expect((await h.raw(['status', '--porcelain'], h.source)).trim()).toBe('');
+ expect((await h.raw(['log', '-1', '--format=%s'], h.source)).trim()).toBe(
+ 'Cindy Make: preserve personal changes',
+ );
+ expect((await h.raw(['show', 'refs/heads/cindy-personal:legacy.txt'], h.fork)).trim()).toBe(
+ 'kept work',
+ );
+
+ await h.controller.disconnect();
+ expect(h.record()).toEqual({ schema: 1, choice: 'local' });
+ await expect(h.raw(['config', '--get', 'remote.personal.url'], h.source)).rejects.toMatchObject(
+ {
+ exitCode: 1,
+ },
+ );
+ // The fork itself is untouched.
+ expect(await h.tip(h.fork)).toBe(await h.tip(h.source));
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('replaces its own upload after an official update rewrote the history, without running hooks', async () => {
+ const h = await fixture();
+ try {
+ h.controller.save();
+ await h.controller.settled();
+ const uploaded = await h.tip(h.fork);
+
+ // A repository hook that records the environment it sees whenever Git runs it.
+ const marker = path.join(h.userData, 'hook-env');
+ const hook = path.join(h.source, '.git', 'hooks', 'reference-transaction');
+ await writeFile(hook, `#!/bin/sh\nenv >> "${marker.split(path.sep).join('/')}"\n`);
+ await chmod(hook, 0o755);
+ await h.raw(['update-ref', 'refs/cindy-make/hook-probe', 'HEAD'], h.source);
+ const hooksWork = existsSync(marker);
+ await rm(marker, { force: true });
+
+ // Official update: the personal commit is replayed onto a newer official base.
+ const official = path.join(h.userData, 'official');
+ await writeFile(path.join(official, 'app.txt'), 'official update\n');
+ await h.commit(official, 'official update');
+ await h.raw(['fetch', official, '+main:refs/remotes/origin/main'], h.source);
+ await h.raw(
+ [
+ '-c',
+ 'user.name=Test',
+ '-c',
+ '-c',
+ 'core.hooksPath=' + path.join(h.userData, 'no-hooks'),
+ 'rebase',
+ '--onto',
+ 'refs/remotes/origin/main',
+ 'HEAD~1',
+ ],
+ h.source,
+ );
+ const rebased = await h.tip(h.source);
+ expect(rebased).not.toBe(uploaded);
+
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.record()).toMatchObject({ sync: 'synced', syncedCommit: rebased });
+ expect(await h.tip(h.fork)).toBe(rebased);
+ expect(await h.tip(h.source, `refs/cindy-make/backups/personal-remote/${uploaded}`)).toBe(
+ uploaded,
+ );
+ // Local ref updates may run hooks; commands that carry the credential never do.
+ expect(hooksWork).toBe(true);
+ const seen = existsSync(marker) ? await readFile(marker, 'utf8') : '';
+ expect(seen).not.toContain('extraheader');
+ expect(seen).not.toContain(Buffer.from(`x-access-token:${TOKEN}`).toString('base64'));
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('replaces its own upload that contained a feature integration merge after an official update', async () => {
+ const h = await fixture();
+ const identity = ['-c', 'user.name=Test', '-c', '[email protected]'];
+ try {
+ // A completed task is integrated into the personal version as a real --no-ff merge.
+ const base = await h.tip(h.source);
+ await h.raw(['checkout', '-b', 'cindy-make/task'], h.source);
+ await writeFile(path.join(h.source, 'feature.txt'), 'task change\n');
+ await h.commit(h.source, 'task change');
+ await h.raw(['checkout', 'cindy-personal'], h.source);
+ await h.raw(
+ [...identity, 'merge', '--no-ff', '-m', 'integrate task', 'cindy-make/task'],
+ h.source,
+ );
+ h.controller.save();
+ await h.controller.settled();
+ const uploaded = await h.tip(h.fork);
+ expect(h.record()).toMatchObject({ sync: 'synced', syncedCommit: uploaded });
+
+ // The official update replays personal commits linearly; the merge commit disappears.
+ const official = path.join(h.userData, 'official');
+ await writeFile(path.join(official, 'app.txt'), 'official update\n');
+ await h.commit(official, 'official update');
+ await h.raw(['fetch', official, '+main:refs/remotes/origin/main'], h.source);
+ const officialBase = (await h.raw(['rev-parse', `${base}~1`], h.source)).trim();
+ await h.raw(
+ [
+ ...identity,
+ '-c',
+ 'core.hooksPath=' + path.join(h.userData, 'no-hooks'),
+ 'rebase',
+ '--onto',
+ 'refs/remotes/origin/main',
+ officialBase,
+ 'cindy-personal',
+ ],
+ h.source,
+ );
+ const rebased = await h.tip(h.source);
+ expect(
+ (await h.raw(['rev-list', '--merges', `${officialBase}..${rebased}`], h.source)).trim(),
+ ).toBe('');
+
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.record()).toMatchObject({ sync: 'synced', syncedCommit: rebased });
+ expect(await h.tip(h.fork)).toBe(rebased);
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('starts a new computer from the personal version another computer saved', async () => {
+ const h = await fixture();
+ try {
+ h.controller.save();
+ await h.controller.settled();
+ const saved = await h.tip(h.fork);
+
+ // A second computer prepares a fresh official checkout and connects the same account.
+ const otherData = path.join(h.userData, 'second-computer');
+ const otherSource = makeSourceCheckoutPath(otherData);
+ await mkdir(path.dirname(otherSource), { recursive: true });
+ await h.raw(['clone', h.official, otherSource], h.userData);
+ await h.raw(['checkout', '-b', 'cindy-personal'], otherSource);
+ let record: PersonalRemoteRecord = { schema: 1 };
+ const second = new PersonalRemoteController({
+ source: otherSource,
+ read: () => structuredClone(record),
+ write: (next) => {
+ record = structuredClone(next);
+ },
+ identity: async () => ({ status: 'connected', identity: { login: 'octo', token: TOKEN } }),
+ ensureFork: async () => 'octo/cindy',
+ findPersonalFork: async () => 'octo/cindy',
+ git: h.git,
+ sourceExists: () => existsSync(path.join(otherSource, '.git')),
+ withProject: (run) => run(),
+ withSourceUse: (run) => run(),
+ hasUnbuiltChanges: async () => false,
+ isBuilt: () => false,
+ sourceSettled: () => true,
+ officialBase: async () => h.tip(otherSource, 'refs/remotes/origin/main'),
+ sourceChanged: () => {},
+ publish: () => {},
+ sleep: async () => {},
+ now: () => Date.now(),
+ });
+ expect((await second.refresh()).existingPersonal).toBe('octo/cindy');
+ second.save();
+ await second.settled();
+ expect(record).toMatchObject({
+ repository: 'octo/cindy',
+ sync: 'retrieved',
+ syncedCommit: saved,
+ });
+ expect(await h.tip(otherSource)).toBe(saved);
+ expect((await readFile(path.join(otherSource, 'personal.txt'), 'utf8')).trim()).toBe(
+ 'first change',
+ );
+ expect(await h.tip(h.fork)).toBe(saved);
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
+
+it('combines new changes from two computers and keeps a conflicting pair untouched', async () => {
+ const h = await fixture();
+ try {
+ h.controller.save();
+ await h.controller.settled();
+ const other = path.join(h.userData, 'other');
+ await h.raw(['clone', '--branch', 'cindy-personal', h.fork, other], h.userData);
+
+ // Each computer adds a different change on the same official base.
+ await writeFile(path.join(other, 'other.txt'), 'from another computer\n');
+ await h.commit(other, 'another computer');
+ await h.raw(['push', 'origin', 'cindy-personal'], other);
+ const remote = await h.tip(h.fork);
+ await writeFile(path.join(h.source, 'mine.txt'), 'from this computer\n');
+ await h.commit(h.source, 'this computer');
+ const local = await h.tip(h.source);
+
+ h.controller.sync();
+ await h.controller.settled();
+ const combined = await h.tip(h.source);
+ expect(h.record()).toMatchObject({ sync: 'retrieved', syncedCommit: combined });
+ expect(await h.tip(h.fork)).toBe(combined);
+ // The combined version builds on the fork's version and keeps both changes and the author.
+ expect((await h.raw(['rev-parse', `${combined}^`], h.source)).trim()).toBe(remote);
+ expect((await h.raw(['show', `${combined}:other.txt`], h.source)).trim()).toBe(
+ 'from another computer',
+ );
+ expect((await h.raw(['show', `${combined}:mine.txt`], h.source)).trim()).toBe(
+ 'from this computer',
+ );
+ expect((await h.raw(['log', '-1', '--format=%an <%ae>%n%B', combined], h.source)).trim()).toBe(
+ 'Test <[email protected]>\nthis computer\n\nSigned-off-by: Test <[email protected]>',
+ );
+ expect((await h.raw(['status', '--porcelain'], h.source)).trim()).toBe('');
+ expect(await h.tip(h.source, `refs/cindy-make/backups/personal-remote-local/${local}`)).toBe(
+ local,
+ );
+
+ // Both computers now edit the same line: nothing moves and both sides are reported.
+ await h.raw(['pull', '--ff-only', 'origin', 'cindy-personal'], other);
+ await writeFile(path.join(other, 'personal.txt'), 'edited over there\n');
+ await h.commit(other, 'conflicting change over there');
+ await h.raw(['push', 'origin', 'cindy-personal'], other);
+ const theirs = await h.tip(h.fork);
+ await writeFile(path.join(h.source, 'personal.txt'), 'edited here\n');
+ await h.commit(h.source, 'conflicting change here');
+ const ours = await h.tip(h.source);
+ h.controller.sync();
+ await h.controller.settled();
+ // Overlapping edits wait for the user to start a combine; nothing is chosen for them.
+ expect(h.record().sync).toBe('needsMerge');
+ expect(await h.tip(h.source)).toBe(ours);
+ expect(await h.tip(h.fork)).toBe(theirs);
+ expect((await readFile(path.join(h.source, 'personal.txt'), 'utf8')).trim()).toBe(
+ 'edited here',
+ );
+ } finally {
+ await h.clean();
+ }
+}, 60_000);
diff --git a/apps/desktop/src/main/cindy-make/__tests__/personalRemote.test.ts b/apps/desktop/src/main/cindy-make/__tests__/personalRemote.test.ts
new file mode 100644
index 0000000000..b109b3ffec
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/personalRemote.test.ts
@@ -0,0 +1,1665 @@
+import os from 'node:os';
+import path from 'node:path';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ PersonalRemoteController,
+ PersonalRemoteError,
+ classifyRemoteGitError,
+ ensureOfficialFork,
+ githubAuthEnv,
+ inspectPersonalFork,
+ parsePersonalRemoteRecord,
+ parsePersonalRemoteTrust,
+ readGithubIdentity,
+ writePersonalRemoteRecord,
+ type PersonalForkHealth,
+ type PersonalRemoteDeps,
+ type PersonalRemoteGitOptions,
+ type PersonalRemoteRecord,
+} from '../personalRemote';
+import type { CindyMakePersonalRemoteState } from '../../../shared/cindyMakePersonalRemote';
+import { readAtomicFileSync } from '../../utils/atomicWriteFile';
+
+vi.mock('../localHistory', async (load) => ({
+ ...(await load<typeof import('../localHistory')>()),
+ assertNoGitOperation: vi.fn(async () => {}),
+ commitPersonalFiles: vi.fn(async () => ({ commit: 'c'.repeat(40), tree: 't'.repeat(40) })),
+}));
+
+const TOKEN = 'gho_fake-token-for-tests';
+const LOCAL = 'a'.repeat(40);
+const OLDER = 'b'.repeat(40);
+const NEWER = 'c'.repeat(40);
+const OTHER = 'd'.repeat(40);
+const MERGED_TREE = '9'.repeat(40);
+const COMBINED = '8'.repeat(40);
+const FORK_URL = 'https://github.com/octo/cindy.git';
+const roots: string[] = [];
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+function storedRecord(raw: string | null) {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-personal-remote-'));
+ roots.push(root);
+ const file = path.join(root, 'personal-remote.json');
+ if (raw !== null) writeFileSync(file, raw);
+ return {
+ raw: () => readAtomicFileSync(file),
+ replaceRaw: (value: string) => writeFileSync(file, value),
+ read: () => parsePersonalRemoteRecord(readAtomicFileSync(file)),
+ write: (record: PersonalRemoteRecord) => writePersonalRemoteRecord(file, record),
+ };
+}
+
+const jsonResponse = (status: number, body: unknown) =>
+ new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+
+describe('parsePersonalRemoteRecord', () => {
+ it('keeps a consistent binding and drops invalid or inconsistent fields', () => {
+ expect(
+ parsePersonalRemoteRecord(
+ JSON.stringify({
+ schema: 1,
+ choice: 'github',
+ login: 'Octo',
+ repository: 'octo/cindy',
+ confirmedAt: 1,
+ sync: 'synced',
+ syncedAt: 2,
+ running: 'save',
+ }),
+ ),
+ ).toEqual({
+ schema: 1,
+ choice: 'github',
+ login: 'Octo',
+ repository: 'octo/cindy',
+ confirmedAt: 1,
+ sync: 'synced',
+ syncedAt: 2,
+ running: 'save',
+ });
+ expect(
+ parsePersonalRemoteRecord(
+ JSON.stringify({ schema: 1, login: 'octo', repository: 'someone/cindy', sync: 'synced' }),
+ ),
+ ).toEqual({ schema: 1 });
+ expect(
+ parsePersonalRemoteRecord(
+ JSON.stringify({ schema: 1, choice: 'cloud', repository: 'octo/../x', error: 'nope' }),
+ ),
+ ).toEqual({ schema: 1 });
+ expect(parsePersonalRemoteRecord('{not json')).toEqual({ schema: 1 });
+ expect(
+ parsePersonalRemoteRecord(
+ JSON.stringify({ schema: 1, unverifiedRemote: [OTHER, OTHER, 'zz', 3] }),
+ ),
+ ).toEqual({ schema: 1, unverifiedRemote: [OTHER] });
+ // Rewrite lineage survives a disconnect (no binding in the record any more).
+ expect(
+ parsePersonalRemoteRecord(
+ JSON.stringify({
+ schema: 1,
+ choice: 'local',
+ rewrites: [{ from: [OTHER], to: NEWER }],
+ unverifiedRemote: [OTHER],
+ unverifiedRemoteOverflow: true,
+ }),
+ ),
+ ).toEqual({
+ schema: 1,
+ choice: 'local',
+ rewrites: [{ from: [OTHER], to: NEWER }],
+ unverifiedRemote: [OTHER],
+ unverifiedRemoteOverflow: true,
+ });
+ expect(parsePersonalRemoteRecord(JSON.stringify({ schema: 2, choice: 'local' }))).toEqual({
+ schema: 1,
+ });
+ expect(parsePersonalRemoteRecord(null)).toEqual({ schema: 1 });
+ });
+});
+
+describe('parsePersonalRemoteTrust', () => {
+ it('reads the trust facts of a well-formed record and the absence of one', () => {
+ expect(parsePersonalRemoteTrust(null)).toEqual({});
+ expect(
+ parsePersonalRemoteTrust(
+ JSON.stringify({
+ schema: 1,
+ choice: 'local',
+ unverifiedRemote: [OTHER],
+ rewrites: [{ from: [LOCAL], to: NEWER }],
+ }),
+ ),
+ ).toEqual({ unverifiedRemote: [OTHER], rewrites: [{ from: [LOCAL], to: NEWER }] });
+ });
+
+ it('refuses to prove trust from corrupt content or an unknown schema', () => {
+ // A tip taken over before the file was corrupted must never read as "no
+ // unverified content": the guarded install path has to stay in place.
+ for (const raw of [
+ '{truncated',
+ 'null',
+ '[]',
+ JSON.stringify({ schema: 2, unverifiedRemote: [OTHER] }),
+ ]) {
+ expect(() => parsePersonalRemoteTrust(raw)).toThrow('unprovable content trust');
+ }
+ });
+});
+
+describe('persisted personal remote trust', () => {
+ it.each([
+ ['invalid JSON', '{truncated'],
+ ['unknown schema', JSON.stringify({ schema: 2, unverifiedRemote: [OTHER] })],
+ ['non-array tips', JSON.stringify({ schema: 1, unverifiedRemote: OTHER })],
+ ['invalid tip', JSON.stringify({ schema: 1, unverifiedRemote: [OTHER, 'damaged'] })],
+ ['too many tips', JSON.stringify({ schema: 1, unverifiedRemote: Array(513).fill(OTHER) })],
+ ['invalid overflow marker', JSON.stringify({ schema: 1, unverifiedRemoteOverflow: false })],
+ [
+ 'invalid rewrite',
+ JSON.stringify({ schema: 1, rewrites: [{ from: [OTHER], to: 'damaged' }] }),
+ ],
+ ])('keeps an unprovable record intact when a save starts: %s', async (_case, raw) => {
+ const store = storedRecord(raw);
+ const h = harness({ store });
+ try {
+ expect(() => h.controller.save()).toThrow('unprovable content trust');
+ } finally {
+ await h.controller.settled();
+ }
+ expect(store.raw()).toBe(raw);
+ expect(() => parsePersonalRemoteTrust(store.raw())).toThrow('unprovable content trust');
+ expect(h.calls).toEqual([]);
+ expect(h.ensureFork).not.toHaveBeenCalled();
+ expect(h.controller.state().running).toBeUndefined();
+ });
+
+ it('does not launder damaged trust while cleaning up an interrupted operation', () => {
+ const raw = JSON.stringify({
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ running: 'sync',
+ unverifiedRemote: OTHER,
+ });
+ const store = storedRecord(raw);
+ const h = harness({ store });
+ expect(store.raw()).toBe(raw);
+ expect(() => parsePersonalRemoteTrust(store.raw())).toThrow('unprovable content trust');
+ expect(h.calls).toEqual([]);
+ });
+
+ it('rechecks the stored trust before a local-only choice can overwrite it', () => {
+ const store = storedRecord(JSON.stringify({ schema: 1, choice: 'local' }));
+ const h = harness({ store });
+ // Damage can appear after construction; checking only startup is insufficient.
+ const raw = JSON.stringify({ schema: 1, rewrites: 'damaged' });
+ store.replaceRaw(raw);
+ expect(() => h.controller.keepLocal()).toThrow('unprovable content trust');
+ expect(store.raw()).toBe(raw);
+ });
+
+ it('keeps valid trust through interrupted-run cleanup, disconnect and a local-only choice', async () => {
+ const trust = { unverifiedRemote: [OTHER], rewrites: [{ from: [OTHER], to: NEWER }] };
+ const store = storedRecord(
+ JSON.stringify({
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ running: 'sync',
+ ...trust,
+ }),
+ );
+ const h = harness({ store });
+ expect(store.read()).toMatchObject({ error: 'interrupted', ...trust });
+ expect(store.read().running).toBeUndefined();
+ await h.controller.disconnect();
+ h.controller.keepLocal();
+ expect(store.read()).toEqual({ schema: 1, choice: 'local', ...trust });
+ expect(parsePersonalRemoteTrust(store.raw())).toEqual(trust);
+ expect(h.pushes()).toEqual([]);
+ });
+
+ it('allows a first local-only decision with no existing record', () => {
+ const store = storedRecord(null);
+ harness({ store }).controller.keepLocal();
+ expect(store.read()).toEqual({ schema: 1, choice: 'local' });
+ });
+});
+
+describe('githubAuthEnv', () => {
+ it('scopes the credential to the fork URL and disables other credential prompts', () => {
+ const env = githubAuthEnv('octo/cindy', TOKEN, {
+ PATH: 'x',
+ GIT_CONFIG_COUNT: '1',
+ GIT_CONFIG_KEY_0: 'core.longpaths',
+ GIT_CONFIG_VALUE_0: 'true',
+ });
+ expect(env).toMatchObject({
+ PATH: 'x',
+ GIT_CONFIG_KEY_0: 'core.longpaths',
+ GIT_CONFIG_COUNT: '6',
+ GIT_CONFIG_KEY_1: `http.${FORK_URL}.extraheader`,
+ GIT_CONFIG_KEY_2: 'credential.helper',
+ GIT_CONFIG_VALUE_2: '',
+ GIT_CONFIG_KEY_3: 'credential.https://github.com.helper',
+ GIT_CONFIG_VALUE_3: '',
+ GIT_CONFIG_KEY_4: 'core.hooksPath',
+ GIT_CONFIG_VALUE_4: os.devNull,
+ GIT_CONFIG_KEY_5: 'core.fsmonitor',
+ GIT_CONFIG_VALUE_5: 'false',
+ GIT_ASKPASS: '',
+ SSH_ASKPASS: '',
+ GIT_TERMINAL_PROMPT: '0',
+ });
+ expect(env.GIT_CONFIG_VALUE_1).toBe(
+ `AUTHORIZATION: basic ${Buffer.from(`x-access-token:${TOKEN}`).toString('base64')}`,
+ );
+ // The token only appears inside the header value, never in a key or URL.
+ const keys = Object.entries(env)
+ .filter(([key]) => key !== 'GIT_CONFIG_VALUE_1')
+ .map(([key, value]) => key + '=' + value)
+ .join('\n');
+ expect(keys).not.toContain(TOKEN);
+ expect(() => githubAuthEnv('octo/../../etc', TOKEN, {})).toThrow(PersonalRemoteError);
+ });
+});
+
+describe('classifyRemoteGitError', () => {
+ it.each([
+ [
+ {
+ stderr:
+ 'refusing to allow an OAuth App to create or update workflow without `workflow` scope',
+ },
+ 'workflowScope',
+ ],
+ [{ stderr: 'fatal: Authentication failed for [REDACTED_URL]' }, 'github'],
+ [
+ { stderr: 'fatal: unable to access [REDACTED_URL]: The requested URL returned error: 403' },
+ 'github',
+ ],
+ [
+ { stderr: 'fatal: unable to access [REDACTED_URL]: Could not resolve host: github.com' },
+ 'network',
+ ],
+ [{ code: 'cancelled' }, 'network'],
+ [{ code: 'busy' }, 'source'],
+ [{ stderr: ' ! [rejected] stale info' }, 'failed'],
+ [new PersonalRemoteError('forkConflict'), 'forkConflict'],
+ ])('maps %o to %s', (error, code) => {
+ expect(classifyRemoteGitError(error)).toBe(code);
+ });
+});
+
+describe('readGithubIdentity', () => {
+ it('reports a missing, rejected, unreachable or connected GitHub account', async () => {
+ const fetchOk = vi.fn(async () => jsonResponse(200, { login: 'octo' }));
+ await expect(
+ readGithubIdentity({ readToken: async () => null, fetch: fetchOk }),
+ ).resolves.toEqual({
+ status: 'missing',
+ });
+ await expect(
+ readGithubIdentity({
+ readToken: async () => TOKEN,
+ fetch: async () => jsonResponse(401, {}),
+ }),
+ ).resolves.toEqual({ status: 'missing' });
+ await expect(
+ readGithubIdentity({
+ readToken: async () => TOKEN,
+ fetch: async () => {
+ throw new Error('offline');
+ },
+ }),
+ ).resolves.toEqual({ status: 'unavailable' });
+ await expect(
+ readGithubIdentity({ readToken: async () => TOKEN, fetch: fetchOk }),
+ ).resolves.toEqual({
+ status: 'connected',
+ identity: { login: 'octo', token: TOKEN },
+ });
+ expect(fetchOk).toHaveBeenCalledWith(
+ 'https://api.github.com/user',
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: `Bearer ${TOKEN}` }),
+ }),
+ );
+ });
+});
+
+describe('ensureOfficialFork', () => {
+ const identity = { login: 'Octo', token: TOKEN };
+ const fork = {
+ full_name: 'octo/cindy-1',
+ fork: true,
+ owner: { login: 'octo' },
+ parent: { full_name: 'makecindy/cindy' },
+ };
+
+ it('accepts the account fork of the official repository, even when renamed', async () => {
+ const fetchFn = vi.fn(async () => jsonResponse(202, fork));
+ await expect(ensureOfficialFork(fetchFn, identity)).resolves.toBe('octo/cindy-1');
+ expect(fetchFn).toHaveBeenCalledWith(
+ 'https://api.github.com/repos/makecindy/cindy/forks',
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({ default_branch_only: true }),
+ }),
+ );
+ });
+
+ it('reads the repository when the fork response omits its parent', async () => {
+ const fetchFn = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse(202, { ...fork, parent: undefined }))
+ .mockResolvedValueOnce(jsonResponse(200, fork));
+ await expect(ensureOfficialFork(fetchFn, identity)).resolves.toBe('octo/cindy-1');
+ expect(fetchFn).toHaveBeenLastCalledWith(
+ 'https://api.github.com/repos/octo/cindy-1',
+ expect.objectContaining({ method: 'GET' }),
+ );
+ });
+
+ it.each([
+ [{ ...fork, fork: false }, 'forkConflict'],
+ [{ ...fork, parent: { full_name: 'someone/cindy' } }, 'forkConflict'],
+ [{ ...fork, full_name: 'someone/cindy', owner: { login: 'someone' } }, 'forkConflict'],
+ ])('rejects a repository that is not the account official fork', async (body, code) => {
+ await expect(
+ ensureOfficialFork(async () => jsonResponse(202, body), identity),
+ ).rejects.toMatchObject({ code });
+ });
+
+ it('maps rejected credentials and network failures', async () => {
+ await expect(
+ ensureOfficialFork(async () => jsonResponse(403, {}), identity),
+ ).rejects.toMatchObject({ code: 'github' });
+ await expect(
+ ensureOfficialFork(async () => {
+ throw new Error('offline');
+ }, identity),
+ ).rejects.toMatchObject({ code: 'network' });
+ });
+
+ it('reuses the account existing fork when a fork cannot be created again', async () => {
+ // A repeated fork request that cannot create anything answers 422 instead of
+ // the repository; the account's own fork is then accepted on the same checks.
+ const fetchFn = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse(422, {}))
+ .mockResolvedValueOnce(jsonResponse(200, fork));
+ await expect(ensureOfficialFork(fetchFn, identity)).resolves.toBe('octo/cindy-1');
+ expect(fetchFn).toHaveBeenLastCalledWith(
+ 'https://api.github.com/repos/Octo/cindy',
+ expect.objectContaining({ method: 'GET' }),
+ );
+ });
+
+ it('locates a renamed existing fork through the account repositories on 422', async () => {
+ const fetchFn = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse(422, {}))
+ .mockResolvedValueOnce(jsonResponse(404, {}))
+ .mockResolvedValueOnce(jsonResponse(200, [{ full_name: 'octo/cindy-1', fork: true }]))
+ .mockResolvedValueOnce(jsonResponse(200, fork));
+ await expect(ensureOfficialFork(fetchFn, identity)).resolves.toBe('octo/cindy-1');
+ });
+
+ it('still rejects on 422 when the account has no official fork', async () => {
+ const fetchFn = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse(422, {}))
+ .mockResolvedValueOnce(jsonResponse(200, { ...fork, fork: false }))
+ .mockResolvedValueOnce(jsonResponse(200, []));
+ await expect(ensureOfficialFork(fetchFn, identity)).rejects.toMatchObject({
+ code: 'forkConflict',
+ });
+ });
+
+ it('keeps looking past the first pages of the account repositories', async () => {
+ const page = (n: number) =>
+ jsonResponse(
+ 200,
+ Array.from({ length: 100 }, (_, i) => ({ full_name: `octo/r${n}-${i}`, fork: false })),
+ );
+ const fetchFn = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse(422, {}))
+ .mockResolvedValueOnce(jsonResponse(404, {}))
+ .mockResolvedValueOnce(page(1))
+ .mockResolvedValueOnce(page(2))
+ .mockResolvedValueOnce(page(3))
+ .mockResolvedValueOnce(jsonResponse(200, [{ full_name: 'octo/cindy-1', fork: true }]))
+ .mockResolvedValueOnce(jsonResponse(200, fork));
+ await expect(ensureOfficialFork(fetchFn, identity)).resolves.toBe('octo/cindy-1');
+ });
+});
+
+/** In-memory model of the managed checkout and the fork, driven by the exact Git commands. */
+function harness(
+ options: {
+ record?: PersonalRemoteRecord;
+ store?: Pick<PersonalRemoteDeps, 'read' | 'write'>;
+ remote?: string;
+ local?: string;
+ ancestors?: Array<[string, string]>;
+ unbuilt?: boolean;
+ identity?: 'connected' | 'missing';
+ login?: string;
+ pushError?: unknown;
+ forkReadyAfter?: number;
+ sourceExists?: boolean;
+ gitVersion?: string;
+ cherry?: string;
+ failedBuild?: boolean;
+ merges?: string[];
+ remergeDiff?: string;
+ clearing?: boolean;
+ remoteBase?: string;
+ officialBase?: string;
+ built?: string[];
+ settled?: boolean;
+ existing?: string;
+ forkPoint?: string;
+ /** Answer the plumbing that combines this computer's change onto the fork. */
+ replay?: boolean;
+ replayConflict?: boolean;
+ /** Commits that no longer exist locally (for example after clearing the source). */
+ missing?: string[];
+ /** Never answer this exact Git command, until the test releases it. */
+ hangOn?: string;
+ /** The source is reserved by Sync: busy for everyone except Sync's own run. */
+ reservedBySync?: boolean;
+ /** Another local operation moves the personal branch while the upload runs. */
+ movedDuringPush?: string;
+ /** What GitHub says about the bound repository. */
+ health?: PersonalForkHealth | Error;
+ assertTrust?: () => void;
+ } = {},
+) {
+ let record: PersonalRemoteRecord = options.record ?? { schema: 1 };
+ let remoteUrl: string | undefined;
+ let remoteTip = options.remote;
+ let remoteBase = options.remoteBase;
+ let localTip = options.local ?? LOCAL;
+ let now = 1_000;
+ let lsRemoteCalls = 0;
+ let released = false;
+ const pendingHang: Array<() => void> = [];
+ const calls: Array<{ args: string[]; auth: boolean }> = [];
+ const states: CindyMakePersonalRemoteState[] = [];
+ const ancestors = new Set((options.ancestors ?? []).map(([a, b]) => a + '>' + b));
+ const replayed: Array<{ identity?: PersonalRemoteGitOptions['identity']; message: string }> = [];
+ const git = vi.fn(async (args: string[], _cwd: string, opts?: PersonalRemoteGitOptions) => {
+ calls.push({ args, auth: !!opts?.auth });
+ if (options.hangOn === args.join(' '))
+ return new Promise<string>((resolve) => {
+ if (released) resolve(localTip);
+ else pendingHang.push(() => resolve(localTip));
+ });
+ // Fixture history and strict tree-proof answers. Real positional preservation
+ // is covered by the repeated-block Git journeys.
+ const changes = (options.cherry ?? '')
+ .split('\n')
+ .filter((line) => /^[+-] /.test(line))
+ .map((line) => line.slice(2).trim());
+ const unique = (options.cherry ?? '')
+ .split('\n')
+ .filter((line) => line.startsWith('+ '))
+ .map((line) => line.slice(2).trim());
+ if (args[0] === 'log') {
+ if (args.includes('--merges')) return (options.merges ?? []).join('\n');
+ if (args.includes('--left-only')) return '';
+ return changes
+ .map((commit) => [commit, 'Test', '[email protected]', '1', 'change'].join('\0'))
+ .join('\n');
+ }
+ if (args[0] === 'rev-list' && args.includes('--right-only'))
+ return args[1] === '--count' ? String(changes.length) : changes.join('\n');
+ if (args[0] === 'rev-list' && args.includes('--left-only')) return '0';
+ if (args[0] === 'rev-list' && args.includes('--merges'))
+ return args[1] === '--count'
+ ? String((options.merges ?? []).length)
+ : (options.merges ?? []).join('\n');
+ if (options.replay) {
+ if (args[0] === 'rev-list' && args[1] === '--reverse') return LOCAL;
+ if (args[0] === 'rev-list' && args[1] === '--count') return '1';
+ if (args[0] === 'merge-tree') {
+ // Git exits 1 when both sides changed the same lines.
+ if (options.replayConflict) throw Object.assign(new Error('conflict'), { exitCode: 1 });
+ return MERGED_TREE;
+ }
+ if (args[0] === 'cat-file')
+ return [
+ `tree ${'e'.repeat(40)}`,
+ `parent ${options.forkPoint}`,
+ 'author Ada Lovelace <[email protected]> 1700000000 +0800',
+ 'committer Someone Else <[email protected]> 1700000100 +0800',
+ 'gpgsig -----BEGIN PGP SIGNATURE-----',
+ ' ',
+ ' abc',
+ ' -----END PGP SIGNATURE-----',
+ '',
+ 'Add a blue button',
+ '',
+ 'Signed-off-by: Ada Lovelace <[email protected]>',
+ ].join('\n');
+ if (args.includes('commit-tree')) {
+ replayed.push({
+ identity: opts?.identity,
+ message: readFileSync(args[args.indexOf('-F') + 1], 'utf8'),
+ });
+ return COMBINED;
+ }
+ if (args.length === 2 && args[0] === 'rev-parse' && args[1].endsWith('^'))
+ return options.forkPoint ?? '';
+ }
+ if (args[0] === 'merge-tree') {
+ if (
+ unique.includes(args.at(-1)!) ||
+ (options.remergeDiff && options.merges?.includes(args.at(-1)!))
+ )
+ throw Object.assign(new Error('not carried'), { exitCode: 1 });
+ return 'e'.repeat(40);
+ }
+ if (opts?.auth)
+ expect(opts.auth).toEqual({
+ repository:
+ options.health && !(options.health instanceof Error)
+ ? options.health.repository
+ : 'octo/cindy',
+ token: TOKEN,
+ });
+ const command = args.join(' ');
+ if (command === '--version') return options.gitVersion ?? 'git version 2.45.1';
+ if (args[0] === 'rev-list' && args[1] === '--merges') return (options.merges ?? []).join('\n');
+ if (args[0] === 'show' && args[1] === '--remerge-diff') return options.remergeDiff ?? '';
+ if (args[0] === 'cherry') return options.cherry ?? '';
+ if (args[0] === 'show-ref') {
+ if (options.failedBuild) return '';
+ throw Object.assign(new Error('missing'), { exitCode: 1 });
+ }
+ if (command === 'rev-parse --verify --quiet refs/heads/cindy-personal^{commit}')
+ return localTip;
+ if (command === 'rev-parse --verify --quiet refs/remotes/personal/cindy-personal^{commit}')
+ return remoteTip ?? '';
+ if (command === 'rev-parse --verify --quiet refs/remotes/personal/cindy-personal-base^{commit}')
+ return remoteBase ?? '';
+ if (args[0] === 'reset' && args[1] === '--keep') {
+ localTip = args[2];
+ return '';
+ }
+ if (command === 'rev-parse --abbrev-ref HEAD') return 'cindy-personal';
+ if (command.startsWith('rev-parse ') && command.endsWith('^{tree}')) return 'e'.repeat(40);
+ if (command === 'status --porcelain') return '';
+ if (command === 'config --get remote.personal.url') {
+ if (remoteUrl === undefined) throw Object.assign(new Error('missing'), { exitCode: 1 });
+ return remoteUrl;
+ }
+ if (args[0] === 'remote' && (args[1] === 'add' || args[1] === 'set-url')) {
+ remoteUrl = args[3];
+ return '';
+ }
+ if (command === 'remote remove personal') {
+ remoteUrl = undefined;
+ return '';
+ }
+ if (command === `ls-remote --heads ${FORK_URL}`) {
+ lsRemoteCalls += 1;
+ if (lsRemoteCalls <= (options.forkReadyAfter ?? 0))
+ throw Object.assign(new Error('not found'), { stderr: 'fatal: repository not found' });
+ return `${OTHER}\trefs/heads/main`;
+ }
+ if (
+ command ===
+ 'ls-remote --refs personal refs/heads/cindy-personal refs/heads/cindy-personal-base'
+ )
+ return [
+ remoteTip ? `${remoteTip}\trefs/heads/cindy-personal` : '',
+ remoteBase ? `${remoteBase}\trefs/heads/cindy-personal-base` : '',
+ ].join('\n');
+ if (args[0] === 'fetch' || args[0] === 'update-ref') return '';
+ if (args[0] === 'merge-base' && options.missing?.some((commit) => args.includes(commit)))
+ throw Object.assign(new Error('not a valid commit'), { exitCode: 128 });
+ if (args[0] === 'merge-base' && args[1] !== '--is-ancestor') {
+ if (options.forkPoint) return options.forkPoint;
+ throw Object.assign(new Error('no merge base'), { exitCode: 1 });
+ }
+ if (args[0] === 'merge-base') {
+ if (ancestors.has(args[2] + '>' + args[3])) return '';
+ throw Object.assign(new Error('not ancestor'), { exitCode: 1 });
+ }
+ if (args[0] === 'push') {
+ if (options.pushError) throw options.pushError;
+ for (const spec of args.filter((arg) => /^[0-9a-f]{40}:refs\/heads\//.test(arg))) {
+ const [commit, ref] = spec.split(':');
+ if (ref === 'refs/heads/cindy-personal') remoteTip = commit;
+ if (ref === 'refs/heads/cindy-personal-base') remoteBase = commit;
+ }
+ if (options.movedDuringPush) localTip = options.movedDuringPush;
+ return '';
+ }
+ throw new Error('unexpected git ' + command);
+ });
+ const ensureFork = vi.fn(async () => 'octo/cindy');
+ const deps: PersonalRemoteDeps = {
+ source: 'source',
+ read: () => structuredClone(record),
+ assertTrust: options.assertTrust,
+ write: (next) => {
+ record = structuredClone(next);
+ },
+ ...options.store,
+ identity: async () =>
+ options.identity === 'missing'
+ ? { status: 'missing' }
+ : { status: 'connected', identity: { login: options.login ?? 'octo', token: TOKEN } },
+ ensureFork,
+ git,
+ sourceExists: () => options.sourceExists ?? true,
+ withProject: (run) => run(),
+ withSourceUse: (run) => {
+ if (options.clearing) throw Object.assign(new Error('clearing'), { code: 'busy' });
+ return run();
+ },
+ hasUnbuiltChanges: async () => options.unbuilt ?? false,
+ findPersonalFork: async () => options.existing,
+ ...(options.health
+ ? {
+ inspectFork: async () => {
+ if (options.health instanceof Error) throw options.health;
+ return options.health!;
+ },
+ }
+ : {}),
+ isBuilt: (commit) => (options.built ?? []).includes(commit),
+ sourceSettled: (withinSync) =>
+ options.reservedBySync ? withinSync : (options.settled ?? true),
+ officialBase: async () => options.officialBase,
+ sourceChanged: vi.fn(),
+ publish: (state) => states.push(state),
+ sleep: async (ms) => {
+ now += ms;
+ },
+ now: () => now,
+ };
+ const controller = new PersonalRemoteController(deps);
+ return {
+ controller,
+ calls,
+ states,
+ ensureFork,
+ releaseHang: () => {
+ released = true;
+ for (const release of pendingHang.splice(0)) release();
+ },
+ record: () => record,
+ remoteTip: () => remoteTip,
+ remoteBase: () => remoteBase,
+ localTip: () => localTip,
+ setLocal: (commit: string) => {
+ localTip = commit;
+ },
+ addAncestor: (ancestor: string, descendant: string) =>
+ ancestors.add(ancestor + '>' + descendant),
+ sourceChanged: deps.sourceChanged as ReturnType<typeof vi.fn>,
+ remoteUrl: () => remoteUrl,
+ pushes: () => calls.filter((call) => call.args[0] === 'push').map((call) => call.args),
+ replayed,
+ commands: () => calls.map((call) => call.args.join(' ')),
+ };
+}
+
+describe('inspectPersonalFork', () => {
+ const identity = { login: 'octo', token: TOKEN };
+ const reply = (status: number, body?: unknown, headers: Record<string, string> = {}) =>
+ new Response(body === undefined ? null : JSON.stringify(body), { status, headers });
+
+ it('reads the repository without following redirects with the credential', async () => {
+ const fetchFn = vi.fn(async () =>
+ reply(200, {
+ full_name: 'octo/cindy',
+ archived: false,
+ fork: true,
+ owner: { login: 'octo' },
+ parent: { full_name: 'makecindy/cindy' },
+ permissions: { push: true },
+ }),
+ );
+ await expect(
+ inspectPersonalFork(fetchFn as unknown as typeof fetch, identity, 'octo/cindy'),
+ ).resolves.toEqual({ repository: 'octo/cindy', archived: false, canPush: true });
+ expect(fetchFn).toHaveBeenCalledWith(
+ 'https://api.github.com/repos/octo/cindy',
+ expect.objectContaining({ redirect: 'manual' }),
+ );
+ });
+
+ it('reports a deleted repository and finds a renamed one through the account’s fork', async () => {
+ const missing = vi.fn(async () => reply(404));
+ await expect(
+ inspectPersonalFork(missing as unknown as typeof fetch, identity, 'octo/cindy'),
+ ).rejects.toMatchObject({ code: 'forkMissing' });
+
+ const renamed = vi.fn(async (url: string) => {
+ if (url.endsWith('/repos/octo/cindy'))
+ return reply(301, undefined, { Location: 'https://api.github.com/repositories/1' });
+ if (url === 'https://api.github.com/repositories/1')
+ return reply(200, {
+ full_name: 'octo/my-cindy',
+ archived: false,
+ fork: true,
+ owner: { login: 'octo' },
+ parent: { full_name: 'makecindy/cindy' },
+ permissions: { push: true },
+ });
+ throw new Error('unexpected ' + url);
+ });
+ await expect(
+ inspectPersonalFork(renamed as unknown as typeof fetch, identity, 'octo/cindy'),
+ ).resolves.toMatchObject({ repository: 'octo/my-cindy' });
+ // Never creates a fork, and never follows a redirect elsewhere with the credential.
+ expect(renamed.mock.calls.map(([url]) => url)).toEqual([
+ 'https://api.github.com/repos/octo/cindy',
+ 'https://api.github.com/repositories/1',
+ ]);
+ const elsewhere = vi.fn(async () =>
+ reply(301, undefined, { Location: 'https://example.com/repositories/1' }),
+ );
+ await expect(
+ inspectPersonalFork(elsewhere as unknown as typeof fetch, identity, 'octo/cindy'),
+ ).rejects.toMatchObject({ code: 'forkMissing' });
+ expect(elsewhere).toHaveBeenCalledOnce();
+ });
+
+ it('reports a stale binding when the saved name is no longer the official fork', async () => {
+ // The fork was deleted and an unrelated repository now answers under the name:
+ // the managed branches must never be pushed into it.
+ const unrelated = vi.fn(async () =>
+ reply(200, {
+ full_name: 'octo/cindy',
+ archived: false,
+ fork: false,
+ owner: { login: 'octo' },
+ permissions: { push: true },
+ }),
+ );
+ await expect(
+ inspectPersonalFork(unrelated as unknown as typeof fetch, identity, 'octo/cindy'),
+ ).rejects.toMatchObject({ code: 'forkMissing' });
+ const foreignFork = vi.fn(async () =>
+ reply(200, {
+ full_name: 'octo/cindy',
+ archived: false,
+ fork: true,
+ owner: { login: 'octo' },
+ parent: { full_name: 'someone/else' },
+ permissions: { push: true },
+ }),
+ );
+ await expect(
+ inspectPersonalFork(foreignFork as unknown as typeof fetch, identity, 'octo/cindy'),
+ ).rejects.toMatchObject({ code: 'forkMissing' });
+ });
+});
+
+describe('PersonalRemoteController', () => {
+ it('keeps offering GitHub until it is bound or the user keeps the version local', async () => {
+ const h = harness();
+ expect(await h.controller.refresh()).toMatchObject({ offerMigration: true, sourceReady: true });
+ expect((await harness({ identity: 'missing' }).controller.refresh()).offerMigration).toBe(
+ false,
+ );
+ // Without a prepared source the offer stays; saving prepares the source first.
+ expect(await harness({ sourceExists: false }).controller.refresh()).toMatchObject({
+ offerMigration: true,
+ sourceReady: false,
+ });
+ expect(
+ (await harness({ record: { schema: 1, choice: 'local' } }).controller.refresh())
+ .offerMigration,
+ ).toBe(false);
+ expect(
+ (
+ await harness({
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ }).controller.refresh()
+ ).offerMigration,
+ ).toBe(false);
+ });
+
+ it('tells a new computer that the account already has a personal version', async () => {
+ const h = harness({ existing: 'octo/cindy' });
+ expect((await h.controller.refresh()).existingPersonal).toBe('octo/cindy');
+ });
+
+ it('binds the fork and uploads the established personal version with an empty lease', async () => {
+ const h = harness();
+ expect(h.controller.save()).toMatchObject({ running: 'save', step: 'waiting' });
+ await h.controller.settled();
+ expect(h.record()).toMatchObject({
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ sync: 'synced',
+ syncedAt: expect.any(Number),
+ });
+ expect(h.record().running).toBeUndefined();
+ expect(h.remoteUrl()).toBe(FORK_URL);
+ expect(h.pushes()).toEqual([
+ [
+ 'push',
+ '--porcelain',
+ '--atomic',
+ '--no-verify',
+ '--no-follow-tags',
+ '--force-with-lease=refs/heads/cindy-personal:',
+ 'personal',
+ `${LOCAL}:refs/heads/cindy-personal`,
+ ],
+ ]);
+ // Only network commands carry the credential.
+ for (const call of h.calls)
+ expect(call.auth).toBe(['ls-remote', 'fetch', 'push'].includes(call.args[0]));
+ expect(h.record().syncedCommit).toBe(LOCAL);
+ expect(h.states.map((state) => state.step).filter(Boolean)).toEqual(
+ expect.arrayContaining(['waiting', 'preparing', 'fork', 'connecting', 'uploading']),
+ );
+ expect(h.states.at(-1)).toMatchObject({
+ repository: 'octo/cindy',
+ sync: 'synced',
+ offerMigration: false,
+ });
+ expect(h.states.at(-1)?.running).toBeUndefined();
+ });
+
+ it('fast-forwards the fork with a lease on the remote commit it was compared against', async () => {
+ const h = harness({ remote: OLDER, ancestors: [[OLDER, LOCAL]] });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.pushes()[0]).toContain(`--force-with-lease=refs/heads/cindy-personal:${OLDER}`);
+ expect(h.record().sync).toBe('synced');
+ });
+
+ it.each([
+ [{ remote: LOCAL }, 'synced'],
+ [{ remote: NEWER, ancestors: [[LOCAL, NEWER]] as Array<[string, string]> }, 'remoteAhead'],
+ [{ remote: OTHER }, 'diverged'],
+ [{ unbuilt: true }, 'pendingBuild'],
+ ])('never overwrites the fork when it is not strictly behind (%o)', async (options, sync) => {
+ const h = harness(options);
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.pushes()).toEqual([]);
+ expect(h.record()).toMatchObject({ repository: 'octo/cindy', sync });
+ expect(h.record().error).toBeUndefined();
+ });
+
+ it('waits for a newly created fork to serve refs', async () => {
+ const h = harness({ forkReadyAfter: 2 });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.record().sync).toBe('synced');
+ });
+
+ it('gives up on a fork that never becomes reachable, without binding it', async () => {
+ const h = harness({ forkReadyAfter: Number.POSITIVE_INFINITY });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.record()).toEqual({ schema: 1, error: 'forkUnavailable' });
+ // The offer stays, now carrying the reason, so saving again is the retry.
+ expect(h.controller.state()).toMatchObject({ offerMigration: true, error: 'forkUnavailable' });
+ });
+
+ it('retrieves a newer version another computer uploaded and keeps it marked until generated', async () => {
+ const BASE = 'e'.repeat(40);
+ const h = harness({
+ remote: NEWER,
+ remoteBase: BASE,
+ ancestors: [
+ [LOCAL, NEWER],
+ [BASE, NEWER],
+ ],
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.pushes()).toEqual([]);
+ expect(h.commands()).toContain(
+ `update-ref refs/cindy-make/backups/personal-remote-local/${LOCAL} ${LOCAL}`,
+ );
+ expect(h.commands()).toContain(`reset --keep ${NEWER}`);
+ expect(h.commands()).toContain(`update-ref refs/cindy-make/personal-upstream ${BASE}`);
+ expect(h.localTip()).toBe(NEWER);
+ expect(h.record()).toMatchObject({ sync: 'retrieved', syncedCommit: NEWER });
+ expect(h.sourceChanged).toHaveBeenCalledOnce();
+ // Still not generated: a later check keeps saying so.
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.record().sync).toBe('retrieved');
+ });
+
+ it('does not move the personal source while a generation or official update owns it', async () => {
+ const h = harness({
+ remote: NEWER,
+ remoteBase: 'e'.repeat(40),
+ ancestors: [[LOCAL, NEWER]],
+ settled: false,
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.localTip()).toBe(LOCAL);
+ // Reported as busy, so Sync says to try again rather than offering to replace anything.
+ expect(h.record().sync).toBe('pending');
+ });
+
+ it('starts a fresh computer from the version on GitHub', async () => {
+ const BASE = 'e'.repeat(40);
+ const h = harness({
+ remote: NEWER,
+ remoteBase: BASE,
+ officialBase: LOCAL,
+ cherry: `+ ${LOCAL}`,
+ ancestors: [[BASE, NEWER]],
+ });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.localTip()).toBe(NEWER);
+ expect(h.record()).toMatchObject({
+ repository: 'octo/cindy',
+ sync: 'retrieved',
+ // The taken-over fork tip is content this computer has not verified yet.
+ unverifiedRemote: [NEWER],
+ });
+ });
+
+ it('publishes the official base next to the personal version', async () => {
+ const BASE = 'e'.repeat(40);
+ const h = harness({ officialBase: BASE, ancestors: [[BASE, LOCAL]] });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.pushes()[0]).toEqual(
+ expect.arrayContaining([
+ '--force-with-lease=refs/heads/cindy-personal-base:',
+ `${BASE}:refs/heads/cindy-personal-base`,
+ ]),
+ );
+ expect(h.remoteBase()).toBe(BASE);
+ });
+
+ it('synchronizes once before a new task starts', async () => {
+ const h = harness({
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ await h.controller.syncBeforeTask();
+ expect(h.pushes()).toHaveLength(1);
+ await harness().controller.syncBeforeTask();
+ });
+
+ it('waits for an operation already running only up to the task budget', async () => {
+ const h = harness({
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ hangOn: 'rev-parse --verify --quiet refs/heads/cindy-personal^{commit}',
+ });
+ h.controller.sync();
+ const started = Date.now();
+ await h.controller.syncBeforeTask(25);
+ // The new task is not held hostage by the slow earlier operation.
+ expect(Date.now() - started).toBeLessThan(2_000);
+ h.releaseHang();
+ await h.controller.settled();
+ expect(h.pushes()).toHaveLength(1);
+ });
+
+ it('remembers taken-over fork tips without repeating them', () => {
+ const h = harness({
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ h.controller.recordUnverifiedRemote(OTHER);
+ h.controller.recordUnverifiedRemote(OTHER);
+ h.controller.recordUnverifiedRemote('not-a-commit');
+ expect(h.record().unverifiedRemote).toEqual([OTHER]);
+ // An adopted rewrite carries the unverified content under its new commit:
+ // the tip list follows the content, however often history is rewritten.
+ h.controller.recordRewrite([LOCAL], NEWER);
+ expect(h.record().unverifiedRemote).toEqual([OTHER, NEWER]);
+ // Old entries are never evicted by new ones: a live source stays listed until
+ // a generated personal version covers it (see `remoteContentScriptsUnverified`).
+ for (let i = 0; i < 20; i += 1) h.controller.recordUnverifiedRemote(String(i).padStart(40, 'a'));
+ expect(h.record().unverifiedRemote).toContain(OTHER);
+ expect(h.record().unverifiedRemote).toHaveLength(22);
+ });
+
+ it('keeps the trust ledger bounded and fails closed when it overflows', () => {
+ const tips = Array.from({ length: 512 }, (_, index) => index.toString(16).padStart(40, '0'));
+ const h = harness({ record: { schema: 1, unverifiedRemote: tips } });
+ const next = 'f'.repeat(40);
+ h.controller.recordUnverifiedRemote(next);
+ expect(h.record().unverifiedRemote).toEqual(tips);
+ expect(h.record().unverifiedRemoteOverflow).toBe(true);
+ expect(parsePersonalRemoteTrust(JSON.stringify(h.record()))).toMatchObject({
+ unverifiedRemote: tips,
+ unverifiedRemoteOverflow: true,
+ });
+ });
+
+ it('carries unverified provenance through rewrites even without a binding', () => {
+ const h = harness({ record: { schema: 1, unverifiedRemote: [OTHER] } });
+ h.controller.recordRewrite([LOCAL], NEWER);
+ expect(h.record().rewrites).toEqual([{ from: [LOCAL], to: NEWER }]);
+ expect(h.record().unverifiedRemote).toEqual([OTHER, NEWER]);
+ });
+
+ it('requires a connected GitHub account and the bound login', async () => {
+ const missing = harness({ identity: 'missing' });
+ missing.controller.save();
+ await missing.controller.settled();
+ expect(missing.ensureFork).not.toHaveBeenCalled();
+ expect(missing.record()).toEqual({ schema: 1, error: 'github' });
+
+ const mismatch = harness({
+ login: 'someone',
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ sync: 'synced',
+ },
+ });
+ expect((await mismatch.controller.refresh()).error).toBe('account');
+ mismatch.controller.sync();
+ await mismatch.controller.settled();
+ expect(mismatch.pushes()).toEqual([]);
+ expect(mismatch.record().error).toBe('account');
+ });
+
+ it('keeps the binding and marks the upload pending when pushing fails', async () => {
+ const h = harness({
+ pushError: Object.assign(new Error('push failed'), {
+ stderr:
+ 'refusing to allow an OAuth App to create or update workflow without workflow scope',
+ }),
+ });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.record()).toMatchObject({
+ repository: 'octo/cindy',
+ sync: 'pending',
+ error: 'workflowScope',
+ });
+ });
+
+ it('turns an operation interrupted by a restart into a visible, non-replayed failure', () => {
+ const h = harness({
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ running: 'sync',
+ },
+ });
+ expect(h.record()).toEqual({
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ error: 'interrupted',
+ });
+ expect(h.calls).toEqual([]);
+ });
+
+ it('does not rewrite a record when trust-bearing fields cannot be validated', () => {
+ const assertTrust = vi.fn(() => {
+ throw new Error('unprovable content trust');
+ });
+ const h = harness({
+ record: { schema: 1, running: 'sync' },
+ assertTrust,
+ });
+ expect(h.record()).toEqual({ schema: 1, running: 'sync' });
+ expect(assertTrust).toHaveBeenCalled();
+ });
+
+ it('records a local-only choice and disconnects without touching the fork', async () => {
+ const local = harness();
+ expect(local.controller.keepLocal()).toMatchObject({ choice: 'local', offerMigration: false });
+
+ const bound = harness();
+ bound.controller.save();
+ await bound.controller.settled();
+ await expect(bound.controller.disconnect()).resolves.toMatchObject({ choice: 'local' });
+ expect(bound.remoteUrl()).toBeUndefined();
+ expect(bound.record()).toEqual({ schema: 1, choice: 'local' });
+ expect(bound.pushes()).toHaveLength(1);
+ });
+
+ it('replaces its own upload after an official update rewrote the hashes, keeping a backup', async () => {
+ const h = harness({
+ remote: OLDER,
+ cherry: `- ${OLDER}`,
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ sync: 'synced',
+ syncedCommit: OLDER,
+ },
+ });
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.commands()).toContain(
+ `update-ref refs/cindy-make/backups/personal-remote/${OLDER} ${OLDER}`,
+ );
+ expect(h.pushes()[0]).toContain(`--force-with-lease=refs/heads/cindy-personal:${OLDER}`);
+ expect(h.record()).toMatchObject({ sync: 'synced', syncedCommit: LOCAL });
+ });
+
+ it('accepts integration merges that add nothing beyond their automatic result', async () => {
+ const h = harness({
+ remote: OLDER,
+ cherry: `- ${OLDER}`,
+ merges: [OTHER],
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ syncedCommit: OLDER,
+ },
+ });
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.record().sync).toBe('synced');
+ expect(h.commands()).toContain(
+ `show --remerge-diff --no-ext-diff --no-textconv --no-color --format= --name-only ${OTHER}`,
+ );
+ });
+
+ it.each([
+ ['another computer wrote the fork version', { syncedCommit: NEWER, cherry: `- ${OLDER}` }],
+ ['the fork has a change this computer lacks', { syncedCommit: OLDER, cherry: `+ ${OLDER}` }],
+ [
+ 'a merge on the fork carries its own resolution',
+ { syncedCommit: OLDER, cherry: `- ${OLDER}`, merges: [OTHER], remergeDiff: '+resolved' },
+ ],
+ ])('refuses to replace a rewritten fork when %s', async (_case, options) => {
+ const h = harness({
+ remote: OLDER,
+ cherry: options.cherry,
+ merges: 'merges' in options ? options.merges : undefined,
+ remergeDiff: 'remergeDiff' in options ? options.remergeDiff : undefined,
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ syncedCommit: options.syncedCommit,
+ },
+ });
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.pushes()).toEqual([]);
+ expect(h.record().sync).toBe('diverged');
+ });
+
+ const BASE = 'f'.repeat(40);
+ /** The fork and this computer each added a change on the same published official base. */
+ const bothChanged = {
+ remote: OTHER,
+ remoteBase: BASE,
+ cherry: `+ ${LOCAL}`,
+ officialBase: BASE,
+ forkPoint: BASE,
+ ancestors: [
+ [BASE, OTHER],
+ [BASE, BASE],
+ ] as Array<[string, string]>,
+ replay: true,
+ };
+
+ it('uploads the combined version first, then moves this computer to it', async () => {
+ const h = harness(bothChanged);
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.pushes()).toHaveLength(1);
+ expect(h.pushes()[0]).toContain(`${COMBINED}:refs/heads/cindy-personal`);
+ expect(h.pushes()[0]).toContain(`--force-with-lease=refs/heads/cindy-personal:${OTHER}`);
+ expect(h.localTip()).toBe(COMBINED);
+ expect(h.record()).toMatchObject({ sync: 'retrieved', syncedCommit: COMBINED });
+ const commands = h.commands();
+ expect(commands.indexOf(`reset --keep ${COMBINED}`)).toBeGreaterThan(
+ commands.findIndex((command) => command.startsWith('push ')),
+ );
+ expect(commands).toContain(
+ `update-ref refs/cindy-make/backups/personal-remote-local/${LOCAL} ${LOCAL}`,
+ );
+ // The raw commit keeps its author, date and exact message; signatures are not copied.
+ expect(h.replayed).toEqual([
+ {
+ identity: { name: 'Ada Lovelace', email: '[email protected]', date: '1700000000 +0800' },
+ message: 'Add a blue button\n\nSigned-off-by: Ada Lovelace <[email protected]>\n',
+ },
+ ]);
+ });
+
+ it('leaves this computer untouched when the combined upload fails', async () => {
+ const h = harness({
+ ...bothChanged,
+ pushError: Object.assign(new Error('offline'), { stderr: 'Could not resolve host' }),
+ });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.localTip()).toBe(LOCAL);
+ expect(h.commands().some((command) => command.startsWith('reset'))).toBe(false);
+ expect(h.record()).toMatchObject({ sync: 'pending', error: 'network' });
+ });
+
+ it('keeps a change made during the upload and combines again next time', async () => {
+ const h = harness({ ...bothChanged, movedDuringPush: NEWER });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.localTip()).toBe(NEWER);
+ expect(h.commands().some((command) => command.startsWith('reset'))).toBe(false);
+ // The fork holds what this computer uploaded, so a later sync may build on it.
+ expect(h.record()).toMatchObject({ sync: 'pending', syncedCommit: COMBINED });
+ });
+
+ it.each([
+ // An isolated rebase still works with an older Git; the user starts it.
+ ['Git cannot combine without a checkout', { gitVersion: 'git version 2.39.2' }, 'needsMerge'],
+ // Official lines that do not follow each other cannot be combined safely.
+ ['the fork is on an unrelated official version', { remoteBase: NEWER }, 'diverged'],
+ // Without a published base the fork may already contain a newer official version.
+ ['the fork publishes no official base', { remoteBase: undefined }, 'diverged'],
+ // Temporary: combined once the source is idle again.
+ ['a generation is still running', { settled: false }, 'pending'],
+ ])('reports both sides instead of combining them when %s', async (_case, extra, sync) => {
+ const h = harness({ ...bothChanged, ...extra });
+ h.controller.save();
+ await h.controller.settled();
+ // Read-only preservation checks may run, but no replay commit may be created.
+ expect(h.commands().some((command) => command.startsWith('commit-tree'))).toBe(false);
+ expect(h.pushes()).toEqual([]);
+ expect(h.localTip()).toBe(LOCAL);
+ expect(h.record().sync).toBe(sync);
+ });
+
+ it('asks for a combine when both sides changed the same place', async () => {
+ const h = harness({ ...bothChanged, replayConflict: true });
+ h.controller.save();
+ await h.controller.settled();
+ // The automatic replay hits a conflict: nothing moves, the user decides.
+ expect(h.pushes()).toEqual([]);
+ expect(h.localTip()).toBe(LOCAL);
+ expect(h.record().sync).toBe('needsMerge');
+ });
+
+ it('gives Sync the fetched GitHub version and marks the upload after its combine', async () => {
+ const h = harness({
+ ...bothChanged,
+ replayConflict: true,
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ syncedCommit: OLDER,
+ },
+ });
+ await expect(h.controller.syncNow()).resolves.toBe('needsMerge');
+ await expect(h.controller.fetchedTips()).resolves.toEqual({ commit: OTHER, base: BASE });
+ // Sync combined and adopted it: the upload says the other computer's changes need generating.
+ h.controller.recordRewrite([LOCAL, OTHER], COMBINED);
+ h.setLocal(COMBINED);
+ h.addAncestor(OTHER, COMBINED);
+ await expect(h.controller.syncNow()).resolves.toBe('retrieved');
+ expect(h.pushes()[0]).toContain(`${COMBINED}:refs/heads/cindy-personal`);
+ expect(h.record().syncedCommit).toBe(COMBINED);
+ });
+
+ it.each([
+ ['deleted', new PersonalRemoteError('forkMissing'), 'forkMissing'],
+ ['archived', { repository: 'octo/cindy', archived: true, canPush: true }, 'forkArchived'],
+ ['read-only', { repository: 'octo/cindy', archived: false, canPush: false }, 'github'],
+ ] as const)('stops before uploading to a %s repository', async (_case, health, error) => {
+ const h = harness({
+ health,
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ await expect(h.controller.syncNow()).rejects.toMatchObject({ code: error });
+ expect(h.pushes()).toEqual([]);
+ // The binding stays, so the row can offer the right fix.
+ expect(h.record().repository).toBe('octo/cindy');
+ });
+
+ it('follows a repository renamed on GitHub under the same account', async () => {
+ const h = harness({
+ health: { repository: 'octo/my-cindy', archived: false, canPush: true },
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ await h.controller.syncNow();
+ expect(h.record().repository).toBe('octo/my-cindy');
+ expect(h.remoteUrl()).toBe('https://github.com/octo/my-cindy.git');
+ });
+
+ it('never follows a rename to another account', async () => {
+ const h = harness({
+ health: { repository: 'mallory/cindy', archived: false, canPush: true },
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ await expect(h.controller.syncNow()).rejects.toMatchObject({ code: 'forkConflict' });
+ expect(h.record().repository).toBe('octo/cindy');
+ });
+
+ it('takes another computer’s rewrite of the version this computer last synced', async () => {
+ // Nothing new here since the last sync: the newer GitHub version is used as it is.
+ const h = harness({
+ ...bothChanged,
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ syncedCommit: LOCAL,
+ },
+ });
+ await expect(h.controller.syncNow()).resolves.toBe('retrieved');
+ expect(h.localTip()).toBe(OTHER);
+ expect(h.pushes()).toEqual([]);
+ expect(h.commands()).toContain(
+ `update-ref refs/cindy-make/backups/personal-remote-local/${LOCAL} ${LOCAL}`,
+ );
+ });
+
+ it('keeps the GitHub version when chosen, backing up this computer’s', async () => {
+ const h = harness({
+ ...bothChanged,
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ await expect(h.controller.keepSide('github')).resolves.toBe('retrieved');
+ expect(h.localTip()).toBe(OTHER);
+ expect(h.pushes()).toEqual([]);
+ expect(h.commands()).toContain(
+ `update-ref refs/cindy-make/backups/personal-remote-local/${LOCAL} ${LOCAL}`,
+ );
+ expect(h.record()).toMatchObject({ sync: 'retrieved', syncedCommit: OTHER });
+ });
+
+ it('keeps this computer’s version when chosen, backing up GitHub’s on GitHub too', async () => {
+ const h = harness({
+ ...bothChanged,
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ await expect(h.controller.keepSide('local')).resolves.toBe('synced');
+ const [push] = h.pushes();
+ expect(push).toEqual(
+ expect.arrayContaining([
+ '--atomic',
+ `--force-with-lease=refs/heads/cindy-personal-backup/${OTHER.slice(0, 12)}:`,
+ `--force-with-lease=refs/heads/cindy-personal:${OTHER}`,
+ `${OTHER}:refs/heads/cindy-personal-backup/${OTHER.slice(0, 12)}`,
+ `${LOCAL}:refs/heads/cindy-personal`,
+ ]),
+ );
+ expect(h.remoteTip()).toBe(LOCAL);
+ expect(h.localTip()).toBe(LOCAL);
+ });
+
+ it('never uploads a version that is not generated, even when chosen', async () => {
+ const h = harness({
+ ...bothChanged,
+ unbuilt: true,
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ await expect(h.controller.keepSide('local')).resolves.toBe('buildFirst');
+ expect(h.pushes()).toEqual([]);
+ });
+
+ it('asks to generate first when both computers changed it and this one’s are not generated', async () => {
+ const h = harness({
+ ...bothChanged,
+ unbuilt: true,
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ await expect(h.controller.syncNow()).resolves.toBe('buildFirst');
+ expect(h.pushes()).toEqual([]);
+ expect(h.localTip()).toBe(LOCAL);
+ });
+
+ it('decides on the current facts after a run that was already in progress', async () => {
+ const h = harness({
+ ...bothChanged,
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ // An automatic run started before Sync reserved the source.
+ h.controller.autoSync();
+ const synced = h.controller.syncNow();
+ await expect(synced).resolves.toBeDefined();
+ // Two runs: the automatic one and Sync's own.
+ expect(h.calls.filter((call) => call.args[0] === 'ls-remote')).toHaveLength(2);
+ });
+
+ it('reports a failed sync to the Sync pipeline as its error code', async () => {
+ const h = harness({
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ identity: 'missing',
+ });
+ await expect(h.controller.syncNow()).rejects.toMatchObject({ code: 'github' });
+ });
+
+ it.each([
+ // An official update whose conflict resolution changed this computer's patches.
+ ['an official update rewrote this computer’s upload', [[OLDER], COMBINED], OLDER],
+ // This computer was on the newer official version; GitHub's changes went onto it.
+ ['a combine carried GitHub’s version into this one', [[OLDER, OTHER], COMBINED], OTHER],
+ ] as const)('replaces the fork when %s', async (_case, [from, to], remote) => {
+ const h = harness({
+ remote,
+ local: COMBINED,
+ cherry: `+ ${remote}`,
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ syncedCommit: OLDER,
+ rewrites: [{ from: [...from], to }],
+ },
+ });
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.pushes()[0]).toContain(`--force-with-lease=refs/heads/cindy-personal:${remote}`);
+ expect(h.commands()).toContain(
+ `update-ref refs/cindy-make/backups/personal-remote/${remote} ${remote}`,
+ );
+ });
+
+ it('never lets old lineage replace the fork with a freshly prepared source', async () => {
+ const BASE = 'f'.repeat(40);
+ // The source was cleared and prepared again: only official commits, no personal ones.
+ const h = harness({
+ remote: COMBINED,
+ local: BASE,
+ officialBase: BASE,
+ ancestors: [[BASE, COMBINED]],
+ cherry: `+ ${COMBINED}`,
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ syncedCommit: COMBINED,
+ rewrites: [{ from: [OLDER], to: COMBINED }],
+ },
+ });
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.pushes()).toEqual([]);
+ expect(h.localTip()).toBe(COMBINED);
+ expect(h.record().sync).toBe('retrieved');
+ });
+
+ it('asks for a combine when one computer is on a newer official version', async () => {
+ const h = harness({
+ ...bothChanged,
+ remoteBase: NEWER,
+ ancestors: [...bothChanged.ancestors, [BASE, NEWER], [NEWER, OTHER]],
+ });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.commands().some((command) => command.startsWith('commit-tree'))).toBe(false);
+ expect(h.pushes()).toEqual([]);
+ expect(h.record().sync).toBe('needsMerge');
+ });
+
+ it('does not count Sync’s own source reservation as busy', async () => {
+ // Automatic syncs see the reserved source as busy and wait.
+ const automatic = harness({ ...bothChanged, replayConflict: true, reservedBySync: true });
+ automatic.controller.save();
+ await automatic.controller.settled();
+ expect(automatic.record().sync).toBe('pending');
+ // Sync's own run can still combine.
+ const own = harness({
+ ...bothChanged,
+ replayConflict: true,
+ reservedBySync: true,
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ await expect(own.controller.syncNow()).resolves.toBe('needsMerge');
+ });
+
+ it('ignores lineage about commits a re-prepared source no longer has', async () => {
+ const BASE = 'f'.repeat(40);
+ const GONE = '7'.repeat(40);
+ const h = harness({
+ remote: COMBINED,
+ local: BASE,
+ officialBase: BASE,
+ ancestors: [[BASE, COMBINED]],
+ missing: [GONE],
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ rewrites: [{ from: [GONE], to: GONE }],
+ },
+ });
+ // The stale record must not break Sync: GitHub's version is retrieved as usual.
+ await expect(h.controller.syncNow()).resolves.toBe('retrieved');
+ expect(h.localTip()).toBe(COMBINED);
+
+ // Also where the replace check consults the lineage: it proves nothing, nothing breaks.
+ const other = harness({
+ remote: COMBINED,
+ local: NEWER,
+ officialBase: NEWER,
+ missing: [GONE],
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ rewrites: [{ from: [GONE], to: GONE }],
+ },
+ });
+ await expect(other.controller.syncNow()).resolves.toBe('diverged');
+ expect(other.pushes()).toEqual([]);
+ });
+
+ it('records each adopted rewrite once and keeps the newest ones', () => {
+ const h = harness({
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ h.controller.recordRewrite([OLDER], NEWER);
+ h.controller.recordRewrite([OLDER], NEWER);
+ h.controller.recordRewrite(['not-a-commit'], OTHER);
+ expect(h.record().rewrites).toEqual([{ from: [OLDER], to: NEWER }]);
+ });
+
+ it('never uploads a commit retained by a failed generation', async () => {
+ const h = harness({ failedBuild: true });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.pushes()).toEqual([]);
+ expect(h.record().sync).toBe('pendingBuild');
+ });
+
+ it('stops before creating a fork when Git cannot carry a per-command credential', async () => {
+ const h = harness({ gitVersion: 'git version 2.35.1' });
+ h.controller.save();
+ await h.controller.settled();
+ expect(h.ensureFork).not.toHaveBeenCalled();
+ expect(h.record()).toEqual({ schema: 1, error: 'gitOutdated' });
+ });
+
+ it('clears connection errors that a reconnect or login switch resolved', async () => {
+ const github = harness({ record: { schema: 1, error: 'github' } });
+ expect((await github.controller.refresh()).error).toBeUndefined();
+ const account = harness({
+ record: { schema: 1, login: 'octo', repository: 'octo/cindy', error: 'account' },
+ });
+ expect((await account.controller.refresh()).error).toBeUndefined();
+ const workflow = harness({
+ record: { schema: 1, login: 'octo', repository: 'octo/cindy', error: 'workflowScope' },
+ });
+ expect((await workflow.controller.refresh()).error).toBe('workflowScope');
+ });
+
+ it('shows new local content as not yet synced', async () => {
+ const h = harness({
+ record: {
+ schema: 1,
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ sync: 'synced',
+ syncedCommit: OLDER,
+ },
+ });
+ expect((await h.controller.refresh()).sync).toBe('pending');
+ });
+
+ it('synchronizes automatically only for a bound GitHub choice', async () => {
+ const unbound = harness();
+ unbound.controller.autoSync();
+ await unbound.controller.settled();
+ expect(unbound.calls).toEqual([]);
+
+ const bound = harness({
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ bound.controller.autoSync();
+ await bound.controller.settled();
+ expect(bound.pushes()).toHaveLength(1);
+ expect(bound.record().sync).toBe('synced');
+ });
+
+ it('does not touch a checkout that is being cleared', async () => {
+ const h = harness({
+ clearing: true,
+ record: { schema: 1, choice: 'github', login: 'octo', repository: 'octo/cindy' },
+ });
+ h.controller.sync();
+ await h.controller.settled();
+ expect(h.calls).toEqual([]);
+ expect(h.record().error).toBe('source');
+ });
+
+ it('refuses a sync request without a bound repository', () => {
+ expect(() => harness().controller.sync()).toThrow(PersonalRemoteError);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/personalSync.test.ts b/apps/desktop/src/main/cindy-make/__tests__/personalSync.test.ts
new file mode 100644
index 0000000000..7de43a5380
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/personalSync.test.ts
@@ -0,0 +1,482 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ PersonalSync,
+ syncWaiting,
+ type PersonalSyncDeps,
+ type PersonalSyncRecord,
+ type PersonalSyncRemote,
+} from '../personalSync';
+import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
+import type { CindyMakeSyncState } from '../../../shared/cindyMakeSync';
+
+const BASE = 'b'.repeat(40);
+const TARGET = 'c'.repeat(40);
+const REMOTE = 'd'.repeat(40);
+const merged = (id: string, extra: Partial<CindyMakeMergeState> = {}): CindyMakeMergeState => ({
+ id,
+ status: 'merged',
+ ref: 'v1.2.0',
+ upstreamCommit: TARGET,
+ ...extra,
+});
+const conflict = (id: string, extra: Partial<CindyMakeMergeState> = {}): CindyMakeMergeState => ({
+ id,
+ status: 'resolving',
+ ref: 'v1.2.0',
+ upstreamCommit: TARGET,
+ hasWorkspace: true,
+ sessionId: 'resolver',
+ ...extra,
+});
+
+function harness(
+ options: {
+ remote?: PersonalSyncRemote;
+ base?: string;
+ held?: boolean;
+ record?: PersonalSyncRecord;
+ operation?: CindyMakeMergeState;
+ } = {},
+) {
+ let base: string | undefined = 'base' in options ? options.base : BASE;
+ let record: PersonalSyncRecord = options.record ?? {};
+ let operation = options.operation;
+ const release = vi.fn();
+ const states: CindyMakeSyncState[] = [];
+ // The shared lifecycle keeps the latest operation; every mock result becomes it.
+ const track = (state: CindyMakeMergeState | undefined) => {
+ operation = state;
+ return state;
+ };
+ const deps: PersonalSyncDeps = {
+ remote: () => options.remote,
+ target: vi.fn(async () => ({
+ ref: 'v1.2.0',
+ commit: TARGET,
+ ...(options.held ? { held: { ref: 'v1.3.0', commit: 'e'.repeat(40) } } : {}),
+ })),
+ base: vi.fn(async () => base),
+ isAncestor: async (ancestor, descendant) => ancestor === BASE && descendant === TARGET,
+ unbuilt: vi.fn(async () => false),
+ operation: () => operation,
+ resume: vi.fn(async () => operation),
+ combine: vi.fn(async () => track(merged('combine', { remote: { base: BASE, commit: REMOTE } }))),
+ update: vi.fn(async () => {
+ base = TARGET;
+ return track(merged('update'));
+ }),
+ abandon: vi.fn(async (id: string) =>
+ track({
+ ...(operation?.id === id ? operation : conflict(id)),
+ status: 'cancelled',
+ hasWorkspace: false,
+ sessionId: undefined,
+ }),
+ ),
+ accept: vi.fn(async (id: string) => track(merged(id))),
+ reserve: vi.fn(() => release),
+ load: () => record,
+ save: (next) => {
+ record = next;
+ },
+ publish: (state) => states.push(state),
+ now: () => 42,
+ };
+ const sync = new PersonalSync(deps);
+ return {
+ sync,
+ deps,
+ states,
+ release,
+ record: () => record,
+ setOperation: (state: CindyMakeMergeState | undefined) => {
+ operation = state;
+ sync.operationChanged(state);
+ },
+ track,
+ last: () => states.at(-1),
+ };
+}
+
+describe('the single Sync', () => {
+ it('without GitHub only moves to the official version, the same pipeline otherwise', async () => {
+ const h = harness({ held: true });
+ h.sync.sync({ agentKind: 'codex' });
+ await h.sync.settled();
+ expect(h.deps.update).toHaveBeenCalledWith(
+ expect.objectContaining({ ref: 'v1.2.0', commit: TARGET }),
+ { agentKind: 'codex' },
+ );
+ expect(h.deps.combine).not.toHaveBeenCalled();
+ // Nothing retained: no "continuing" flash.
+ expect(h.deps.resume).not.toHaveBeenCalled();
+ expect(h.states.map((state) => state.step).filter(Boolean)).toEqual(['official']);
+ expect(h.last()).toEqual({ done: { at: 42, ref: 'v1.2.0', held: 'v1.3.0' } });
+ // The result survives a restart.
+ expect(h.record()).toEqual({ done: { at: 42, ref: 'v1.2.0', held: 'v1.3.0' } });
+ });
+
+ it('does not touch a personal version already on (or past) the official version', async () => {
+ const h = harness({ base: TARGET });
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.deps.update).not.toHaveBeenCalled();
+ expect(h.last()?.done?.ref).toBe('v1.2.0');
+ });
+
+ it('stops before moving anything when the personal version has no known official base', async () => {
+ const h = harness({ base: undefined });
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.deps.update).not.toHaveBeenCalled();
+ expect(h.last()).toEqual({ error: 'source' });
+ });
+
+ it('with GitHub takes in other computers’ changes, combines, updates and uploads in order', async () => {
+ const calls: string[] = [];
+ const remote: PersonalSyncRemote = {
+ sync: vi.fn(async () => {
+ calls.push('github');
+ return calls.length === 1 ? ('needsMerge' as const) : ('synced' as const);
+ }),
+ tips: async () => ({ commit: REMOTE, base: BASE }),
+ keep: vi.fn(),
+ };
+ const h = harness({ remote });
+ vi.mocked(h.deps.combine).mockImplementation(async () => {
+ calls.push('combine');
+ return h.track(merged('combine', { remote: { base: BASE, commit: REMOTE } }));
+ });
+ vi.mocked(h.deps.update).mockImplementation(async () => {
+ calls.push('official');
+ return h.track(merged('update'));
+ });
+ h.sync.sync();
+ await h.sync.settled();
+ expect(calls).toEqual(['github', 'combine', 'official', 'github']);
+ expect(h.deps.combine).toHaveBeenCalledWith({ commit: REMOTE, base: BASE }, undefined);
+ expect(h.last()?.done).toBeTruthy();
+ });
+
+ it('waits for a conflict task and continues by itself once its result is adopted', async () => {
+ const remote: PersonalSyncRemote = {
+ sync: vi.fn(async () => 'needsMerge' as const),
+ tips: async () => ({ commit: REMOTE, base: BASE }),
+ keep: vi.fn(),
+ };
+ const h = harness({ remote });
+ vi.mocked(h.deps.combine).mockImplementationOnce(async () =>
+ h.track(conflict('combine', { remote: { base: BASE, commit: REMOTE } })),
+ );
+ h.sync.sync({ agentKind: 'codex' });
+ await h.sync.settled();
+ expect(h.last()).toEqual({
+ waiting: { kind: 'combine', reason: 'working', sessionId: 'resolver' },
+ });
+ expect(h.record().waiting).toBe('combine');
+ expect(h.deps.update).not.toHaveBeenCalled();
+
+ vi.mocked(remote.sync).mockResolvedValue('synced');
+ h.setOperation(merged('combine'));
+ await h.sync.settled();
+ expect(h.deps.update).toHaveBeenCalledWith(expect.anything(), { agentKind: 'codex' });
+ expect(h.last()?.done).toBeTruthy();
+ expect(h.record().waiting).toBeUndefined();
+ });
+
+ it('finishes an operation retained from before a restart first', async () => {
+ const remote: PersonalSyncRemote = { sync: vi.fn(), tips: vi.fn(), keep: vi.fn() };
+ const h = harness({ remote, operation: conflict('earlier', { status: 'conflict' }) });
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.deps.resume).toHaveBeenCalledOnce();
+ expect(h.last()?.waiting).toMatchObject({ kind: 'official', reason: 'working' });
+ expect(remote.sync).not.toHaveBeenCalled();
+ });
+
+ it('does not start while a change-history operation is retained', async () => {
+ const h = harness({
+ operation: conflict('feature', {
+ feature: {
+ runId: 'run',
+ taskSessionId: 'task',
+ action: 'integrate',
+ taskTree: 'a'.repeat(40),
+ steps: [],
+ nextStep: 0,
+ },
+ }),
+ });
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.deps.update).not.toHaveBeenCalled();
+ expect(h.last()).toEqual({ error: 'featurePending' });
+ });
+
+ it.each([
+ [{ needsInput: true, status: 'conflict' as const }, 'input'],
+ [{ status: 'conflict' as const, sessionId: undefined }, 'paused'],
+ [{ status: 'failed' as const, error: 'startFailed' as const, sessionId: undefined }, 'paused'],
+ // Its task was removed: Continue opens a new one for the same work.
+ [{ status: 'failed' as const, error: 'unavailable' as const }, 'paused'],
+ [{ status: 'failed' as const, error: 'interrupted' as const }, 'interrupted'],
+ [
+ { status: 'failed' as const, error: 'checksFailed' as const, missing: { count: 2, commits: [] } },
+ 'missing',
+ ],
+ [{ status: 'failed' as const, error: 'baselineChanged' as const }, 'stale'],
+ [{ status: 'failed' as const, error: 'gitFailed' as const }, 'failed'],
+ [{ status: 'checking' as const }, 'working'],
+ ])('names why it waits: %o → %s', (extra, reason) => {
+ expect(syncWaiting(conflict('x', extra))?.reason).toBe(reason);
+ });
+
+ it('shows an operation it did not start (task preparation) and continues once adopted', async () => {
+ const h = harness();
+ h.setOperation(conflict('task-prep', { status: 'conflict', needsInput: true }));
+ expect(h.last()).toEqual({
+ waiting: { kind: 'official', reason: 'input', sessionId: 'resolver' },
+ });
+ // Using it anyway adopts it on the user's behalf; Sync then continues.
+ h.setOperation(
+ conflict('task-prep', {
+ status: 'failed',
+ error: 'checksFailed',
+ missing: { count: 1, commits: [] },
+ }),
+ );
+ expect(h.last()?.waiting).toMatchObject({ reason: 'missing', missing: 1 });
+ await h.sync.accept();
+ expect(h.deps.accept).toHaveBeenCalledWith('task-prep');
+ await h.sync.settled();
+ expect(h.deps.target).toHaveBeenCalled();
+ expect(h.last()?.done).toBeTruthy();
+ });
+
+ it('keeps the line while Abandon is carried out, then says nothing changed', async () => {
+ const h = harness();
+ vi.mocked(h.deps.update).mockImplementationOnce(async () => h.track(conflict('stuck')));
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.record().waiting).toBe('stuck');
+ vi.mocked(h.deps.abandon).mockImplementationOnce(async (id) => {
+ // The lifecycle publishes its persisted decision before the candidate is gone.
+ h.setOperation(conflict(id, { cancellationRequested: true }));
+ expect(h.last()?.waiting).toMatchObject({ abandoning: true });
+ return h.track({ ...conflict(id), status: 'cancelled', hasWorkspace: false });
+ });
+ await h.sync.abandon();
+ expect(h.deps.abandon).toHaveBeenCalledWith('stuck');
+ expect(h.last()).toEqual({ error: 'cancelled', abandoned: 'official' });
+ expect(h.record().waiting).toBeUndefined();
+ });
+
+ it('says another account owns an operation, never runs over it, and continues it later', async () => {
+ const h = harness({ record: { waiting: 'mine' } });
+ h.setOperation(conflict('mine'));
+ expect(h.last()?.waiting).toBeTruthy();
+ h.setOperation({ ...conflict('mine'), ownedByAnotherAccount: true, sessionId: undefined });
+ expect(h.last()).toEqual({ waiting: { kind: 'official', reason: 'otherAccount' } });
+ expect(h.record().waiting).toBe('mine');
+ // Neither Sync nor Abandon touches it under this account.
+ h.sync.sync();
+ await h.sync.settled();
+ await h.sync.abandon();
+ expect(h.deps.update).not.toHaveBeenCalled();
+ expect(h.deps.abandon).not.toHaveBeenCalled();
+ h.setOperation(merged('mine'));
+ await h.sync.settled();
+ expect(h.deps.update).toHaveBeenCalledOnce();
+ });
+
+ it('does not continue unasked at startup for an operation adopted before the restart', () => {
+ const h = harness({ record: { waiting: 'old' }, operation: merged('old') });
+ expect(h.deps.reserve).not.toHaveBeenCalled();
+ expect(h.record().waiting).toBeUndefined();
+ });
+
+ it('restores the waiting line and the last result after a restart', () => {
+ const h = harness({
+ record: { waiting: 'old', done: { at: 1, ref: 'v1.1.0' } },
+ operation: conflict('old', { status: 'failed', error: 'interrupted' }),
+ });
+ expect(h.sync.state()).toEqual({
+ waiting: { kind: 'official', reason: 'interrupted', sessionId: 'resolver' },
+ done: { at: 1, ref: 'v1.1.0' },
+ });
+ });
+
+ it('forgets an operation replaced by a newer one', () => {
+ const h = harness({ record: { waiting: 'old' } });
+ h.setOperation(merged('newer'));
+ expect(h.record().waiting).toBeUndefined();
+ });
+
+ const diverged: PersonalSyncRemote['sync'] = async () => 'diverged';
+ const rejected: PersonalSyncRemote['sync'] = async () => {
+ throw Object.assign(new Error('account'), { code: 'account' });
+ };
+ it.each([
+ ['diverged', diverged, 'diverged'],
+ ['a GitHub error', rejected, 'github'],
+ ] as const)(
+ 'still updates this computer when %s, then says why sharing stopped',
+ async (_case, sync, error) => {
+ const remote: PersonalSyncRemote = { tips: vi.fn(), keep: vi.fn(), sync: vi.fn(sync) };
+ const h = harness({ remote });
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.deps.update).toHaveBeenCalledOnce();
+ // Nothing is uploaded after a failed GitHub step.
+ expect(remote.sync).toHaveBeenCalledOnce();
+ expect(h.last()).toEqual({ error, done: { at: 42, ref: 'v1.2.0' } });
+ },
+ );
+
+ it('reports a busy source instead of success and notes uploads that wait for a build', async () => {
+ const busy = harness({
+ remote: { tips: vi.fn(), keep: vi.fn(), sync: vi.fn(async () => 'pending' as const) },
+ });
+ busy.sync.sync();
+ await busy.sync.settled();
+ expect(busy.last()?.error).toBe('busy');
+
+ const later = harness({
+ remote: {
+ tips: vi.fn(),
+ keep: vi.fn(),
+ sync: vi.fn().mockResolvedValueOnce('synced').mockResolvedValueOnce('pendingBuild'),
+ },
+ });
+ later.sync.sync();
+ await later.sync.settled();
+ expect(later.last()).toEqual({
+ done: { at: 42, ref: 'v1.2.0', uploadAfterBuild: true },
+ });
+ });
+
+ it('asks to generate first when both computers changed and this one’s are not generated', async () => {
+ const remote: PersonalSyncRemote = { tips: vi.fn(), keep: vi.fn(), sync: vi.fn(async () => 'buildFirst' as const) };
+ const h = harness({ remote });
+ h.sync.sync();
+ await h.sync.settled();
+ // The official step still runs; nothing is uploaded.
+ expect(h.deps.update).toHaveBeenCalledOnce();
+ expect(remote.sync).toHaveBeenCalledOnce();
+ expect(h.last()).toEqual({ done: { at: 42, ref: 'v1.2.0', buildFirst: true } });
+ });
+
+ it('takes in an upload another computer made during Sync once more by itself', async () => {
+ const remote: PersonalSyncRemote = {
+ tips: vi.fn(),
+ keep: vi.fn(),
+ sync: vi
+ .fn()
+ .mockResolvedValueOnce('synced')
+ .mockResolvedValueOnce('remoteAhead')
+ .mockResolvedValue('synced'),
+ };
+ const h = harness({ remote });
+ h.sync.sync();
+ await h.sync.settled();
+ expect(remote.sync).toHaveBeenCalledTimes(4);
+ expect(h.last()).toEqual({ done: { at: 42, ref: 'v1.2.0' } });
+ });
+
+ it('says so when another computer keeps uploading during Sync', async () => {
+ const remote: PersonalSyncRemote = {
+ tips: vi.fn(),
+ keep: vi.fn(),
+ sync: vi.fn().mockResolvedValueOnce('synced').mockResolvedValue('remoteAhead'),
+ };
+ const h = harness({ remote });
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.last()?.error).toBe('changed');
+ });
+
+ it('names no version when another computer already moved past the target', async () => {
+ const h = harness({ base: 'f'.repeat(40) });
+ h.deps.isAncestor = async () => true;
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.deps.update).not.toHaveBeenCalled();
+ expect(h.last()).toEqual({ done: { at: 42, ahead: true } });
+ });
+
+ it('reserves the source for the whole run and releases it on every outcome', async () => {
+ const h = harness();
+ vi.mocked(h.deps.update).mockRejectedValueOnce(Object.assign(new Error('x'), { code: 'busy' }));
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.deps.reserve).toHaveBeenCalledOnce();
+ expect(h.release).toHaveBeenCalledOnce();
+ expect(h.last()?.error).toBe('busy');
+ });
+
+ it.each([
+ ['gitOutdated', 'gitOutdated'],
+ ['forkUnavailable', 'forkMissing'],
+ ['forkArchived', 'forkArchived'],
+ ['workflowScope', 'github'],
+ ])('reports the GitHub error %s as %s', async (code, error) => {
+ const remote: PersonalSyncRemote = {
+ tips: vi.fn(),
+ keep: vi.fn(),
+ sync: vi.fn(async () => {
+ throw Object.assign(new Error(code), { code });
+ }),
+ };
+ const h = harness({ remote });
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.last()?.error).toBe(error);
+ });
+
+ it('keeps one side when the two versions cannot be combined, then continues like Sync', async () => {
+ const remote: PersonalSyncRemote = {
+ tips: vi.fn(),
+ keep: vi.fn(async () => 'retrieved' as const),
+ sync: vi.fn().mockResolvedValueOnce('diverged').mockResolvedValue('synced'),
+ };
+ const h = harness({ remote });
+ // Only offered after unrelated versions or an abandoned combine.
+ h.sync.keep('github');
+ await h.sync.settled();
+ expect(remote.keep).not.toHaveBeenCalled();
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.last()?.error).toBe('diverged');
+ h.sync.keep('github', { agentKind: 'codex' });
+ await h.sync.settled();
+ expect(remote.keep).toHaveBeenCalledExactlyOnceWith('github');
+ expect(h.last()).toEqual({ done: { at: 42, ref: 'v1.2.0' } });
+ });
+
+ it('offers keeping one side after an abandoned combine, not after an abandoned update', async () => {
+ const h = harness({ remote: { tips: vi.fn(), keep: vi.fn(), sync: vi.fn() } });
+ h.setOperation(conflict('combine', { remote: { base: BASE, commit: REMOTE } }));
+ await h.sync.abandon();
+ expect(h.last()).toMatchObject({ error: 'cancelled', abandoned: 'combine' });
+ h.setOperation(conflict('update'));
+ await h.sync.abandon();
+ expect(h.last()).toMatchObject({ error: 'cancelled', abandoned: 'official' });
+ });
+
+ it('waits with an official update until changes are generated, and says so', async () => {
+ const h = harness();
+ vi.mocked(h.deps.unbuilt).mockResolvedValue(true);
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.deps.update).not.toHaveBeenCalled();
+ expect(h.last()).toEqual({ done: { at: 42, generateFirst: 'v1.2.0' } });
+ });
+
+ it('runs one Sync at a time', async () => {
+ const h = harness();
+ h.sync.sync();
+ h.sync.sync();
+ await h.sync.settled();
+ expect(h.deps.target).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/personalSyncRuntime.test.ts b/apps/desktop/src/main/cindy-make/__tests__/personalSyncRuntime.test.ts
new file mode 100644
index 0000000000..27cc3d3a7a
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/personalSyncRuntime.test.ts
@@ -0,0 +1,51 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const paths = vi.hoisted(() => ({ userData: '' }));
+vi.mock('electron', () => ({ app: { getPath: () => paths.userData } }));
+
+import {
+ actPersonalSync,
+ configurePersonalSync,
+ parseSyncRecord,
+} from '../personalSyncRuntime.js';
+
+describe('personal sync record', () => {
+ beforeEach(() => {
+ paths.userData = mkdtempSync(path.join(os.tmpdir(), 'cindy-make-sync-record-'));
+ mkdirSync(path.join(paths.userData, 'cindy-make'), { recursive: true });
+ });
+ afterEach(() => {
+ rmSync(paths.userData, { recursive: true, force: true });
+ });
+
+ it('keeps well-formed values and drops the rest', () => {
+ expect(parseSyncRecord(null)).toEqual({});
+ expect(
+ parseSyncRecord(
+ '{"waiting":"123e4567-e89b-12d3-a456-426614174000","done":{"at":5,"ref":"main","ahead":true}}',
+ ),
+ ).toEqual({
+ waiting: '123e4567-e89b-12d3-a456-426614174000',
+ done: { at: 5, ref: 'main', ahead: true },
+ });
+ });
+
+ it('returns the fresh record when the saved one is malformed', () => {
+ // Truncated JSON and JSON that parses to `null` or another non-object are a
+ // fresh start — the parse never throws.
+ expect(parseSyncRecord('{"wait')).toEqual({});
+ expect(parseSyncRecord('null')).toEqual({});
+ expect(parseSyncRecord('5')).toEqual({});
+ expect(parseSyncRecord('"text"')).toEqual({});
+ expect(parseSyncRecord('[]')).toEqual({});
+ });
+
+ it('starts Sync anyway when sync.json is malformed', async () => {
+ writeFileSync(path.join(paths.userData, 'cindy-make', 'sync.json'), 'null');
+ expect(() => configurePersonalSync()).not.toThrow();
+ await expect(actPersonalSync({ action: 'status' })).resolves.toEqual({});
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/pnpmWriteRoots.test.ts b/apps/desktop/src/main/cindy-make/__tests__/pnpmWriteRoots.test.ts
new file mode 100644
index 0000000000..bedca649fc
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/pnpmWriteRoots.test.ts
@@ -0,0 +1,177 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { create as tarCreate } from 'tar';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { assertPnpmConfigContained, assertPnpmInstallContained } from '../pnpmWriteRoots';
+
+let fixture: string;
+let worktree: string;
+
+beforeEach(async () => {
+ fixture = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-local-git-'));
+ worktree = path.join(fixture, 'worktree');
+ await mkdir(worktree);
+ await writeFile(
+ path.join(worktree, 'package.json'),
+ JSON.stringify({ name: 'app', version: '1.0.0' }),
+ );
+});
+
+afterEach(async () => {
+ await rm(fixture, { recursive: true, force: true });
+});
+
+describe.each([
+ { label: 'installation', check: assertPnpmInstallContained },
+ { label: 'cache warming', check: assertPnpmConfigContained },
+])('$label local Git dependency containment', ({ check }) => {
+ it.each([
+ 'manifest dependency',
+ 'override',
+ 'workspace catalog',
+ 'lockfile specifier',
+ 'lockfile version',
+ 'transitive dependency',
+ 'Git resolution',
+ ] as const)('refuses a repository outside the worktree in a %s', async (source) => {
+ // A file URL is a stable protocol representation; the path it names comes
+ // from this test's own temporary directory, never from a real user account.
+ const repo = pathToFileURL(path.join(fixture, 'private repo')).href;
+ const spec = `git+${repo}#main`;
+ if (source === 'manifest dependency' || source === 'override') {
+ await writeFile(
+ path.join(worktree, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ version: '1.0.0',
+ ...(source === 'manifest dependency'
+ ? { dependencies: { local: spec } }
+ : { pnpm: { overrides: { local: spec } } }),
+ }),
+ );
+ } else if (source === 'workspace catalog') {
+ await writeFile(
+ path.join(worktree, 'pnpm-workspace.yaml'),
+ JSON.stringify({
+ catalog: { local: spec },
+ }),
+ );
+ } else {
+ const graph =
+ source === 'Git resolution'
+ ? {
+ packages: {
+ '[email protected]': { resolution: { type: 'git', repo, commit: 'a'.repeat(40) } },
+ },
+ }
+ : source === 'transitive dependency'
+ ? { snapshots: { '[email protected]': { dependencies: { local: spec } } } }
+ : {
+ importers: {
+ '.': {
+ dependencies: {
+ local: {
+ specifier: source === 'lockfile specifier' ? spec : '*',
+ version: source === 'lockfile version' ? spec : '1.0.0',
+ },
+ },
+ },
+ },
+ };
+ await writeFile(
+ path.join(worktree, 'pnpm-lock.yaml'),
+ JSON.stringify({
+ lockfileVersion: '9.0',
+ ...graph,
+ }),
+ );
+ }
+ await expect(check(worktree)).rejects.toMatchObject({ code: 'gitFailed' });
+ });
+
+ it('refuses encoded parent traversal in a local Git URL', async () => {
+ const rootUrl = pathToFileURL(worktree + path.sep).href;
+ await writeFile(
+ path.join(worktree, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ dependencies: { local: `git+${rootUrl}%2e%2e/private#main` },
+ }),
+ );
+ await expect(check(worktree)).rejects.toMatchObject({ code: 'gitFailed' });
+ });
+
+ it('refuses an undecodable local Git URL without leaking the URL in its error', async () => {
+ const spec = 'git+file:///invalid%2Frepository#main';
+ await writeFile(
+ path.join(worktree, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ dependencies: { local: spec },
+ }),
+ );
+ const error = await check(worktree).then(
+ () => undefined,
+ (cause: unknown) => cause,
+ );
+ expect(error).toMatchObject({ code: 'gitFailed' });
+ expect(String(error)).not.toContain(spec);
+ });
+
+ it.each(['contained Git URL', 'remote Git URL', 'registry version'] as const)(
+ 'keeps a normal dependency available: %s',
+ async (source) => {
+ const repo = pathToFileURL(path.join(worktree, 'local repo')).href;
+ const spec =
+ source === 'contained Git URL'
+ ? `git+${repo}#main`
+ : source === 'remote Git URL'
+ ? 'git+https://example.invalid/local.git#main'
+ : '1.0.0';
+ await writeFile(
+ path.join(worktree, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ dependencies: { local: spec },
+ }),
+ );
+ if (source === 'contained Git URL') {
+ await writeFile(
+ path.join(worktree, 'pnpm-lock.yaml'),
+ JSON.stringify({
+ lockfileVersion: '9.0',
+ packages: {
+ '[email protected]': { resolution: { type: 'git', repo, commit: 'a'.repeat(40) } },
+ },
+ }),
+ );
+ }
+ await expect(check(worktree)).resolves.toBeUndefined();
+ },
+ );
+});
+
+it('refuses a local Git dependency hidden inside an installed archive', async () => {
+ const stage = path.join(fixture, 'archive');
+ await mkdir(path.join(stage, 'package'), { recursive: true });
+ await writeFile(
+ path.join(stage, 'package', 'package.json'),
+ JSON.stringify({
+ name: 'local',
+ version: '1.0.0',
+ dependencies: { local: `git+${pathToFileURL(path.join(fixture, 'private repo')).href}#main` },
+ }),
+ );
+ await tarCreate({ file: path.join(worktree, 'local.tar'), cwd: stage }, ['package']);
+ await writeFile(
+ path.join(worktree, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ dependencies: { local: 'file:./local.tar' },
+ }),
+ );
+ await expect(assertPnpmInstallContained(worktree)).rejects.toMatchObject({ code: 'gitFailed' });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/remoteProvider.test.ts b/apps/desktop/src/main/cindy-make/__tests__/remoteProvider.test.ts
index c9c60347b1..8ac616b296 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/remoteProvider.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/remoteProvider.test.ts
@@ -30,6 +30,61 @@ const project = (state: MakeRemoteSnapshot, dictionary: Record<string, unknown>
});
describe('portable Cindy Make cards', () => {
+ it.each([en, zh, tw, ja, ko])(
+ 'keeps read-only sync and PR status visible without workflow controls',
+ (dictionary) => {
+ for (const busy of [false, true]) {
+ const state = snapshot();
+ state.busy = busy;
+ state.completion = undefined;
+ state.personal = {
+ remote: { sync: 'synced' },
+ contributions: [{ number: 42, state: 'open' }],
+ };
+ const card = project(state, dictionary);
+ const body = card.blocks?.map((block) => block.fallbackMarkdown).join('\n\n');
+ expect(body).toContain(dictionary.cindyMake.storage.status.synced);
+ expect(body).toContain(
+ dictionary.cindyMake.contribution.state.open.replace('{{number}}', '42'),
+ );
+ expect(card.display.title).toBe(
+ busy ? dictionary.cindyMake.history.lifecycle.running : dictionary.cindyMake.title,
+ );
+ expect(card.blocks?.every((block) => block.primitive !== 'session-controls')).toBe(true);
+ expect(card.actions).toEqual([]);
+ }
+ },
+ );
+
+ it('does not add a status card when there is no personal status or workflow', () => {
+ const state = snapshot();
+ state.completion = undefined;
+ state.personal = {};
+ expect(project(state).blocks).toEqual([]);
+ expect(project(state).actions).toEqual([]);
+ });
+
+ it('projects personal sync and contribution status without adding remote write actions', () => {
+ const state = snapshot();
+ state.personal = {
+ remote: { sync: 'retrieved', error: 'network' },
+ personalSync: { running: true, step: 'official' },
+ contributions: [{ number: 42, state: 'open' }],
+ };
+ const card = project(state);
+ expect(card.display.subtitle).toContain(en.cindyMake.storage.status.retrieved);
+ expect(card.display.subtitle).toContain(en.cindyMake.storage.errors.network);
+ expect(card.display.subtitle).toContain(en.cindyMake.sync.step.official);
+ expect(card.display.subtitle).toContain(
+ en.cindyMake.contribution.state.open.replace('{{number}}', '42'),
+ );
+ expect(
+ card.actions?.some(
+ (action) => action.id.includes('sync') || action.id.includes('contribution'),
+ ),
+ ).toBe(false);
+ });
+
it('forwards the latest scrubbed line and removes it when stopped or finished', () => {
const state = snapshot();
state.sharedBuild = {
diff --git a/apps/desktop/src/main/cindy-make/__tests__/remoteRuntime.test.ts b/apps/desktop/src/main/cindy-make/__tests__/remoteRuntime.test.ts
index 8fc15b5118..487af62705 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/remoteRuntime.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/remoteRuntime.test.ts
@@ -18,6 +18,7 @@ const h = vi.hoisted(() => ({
changed: vi.fn(),
readBuild: vi.fn(),
cancel: vi.fn(),
+ personal: vi.fn(),
beforeRead: vi.fn(),
}));
vi.mock('@cindy/maker-shared/cindy-make-feature', async (importOriginal) => ({
@@ -49,6 +50,9 @@ vi.mock('../historyRuntime.js', () => ({
readCindyMakeBuildState: h.readBuild,
}));
vi.mock('../remoteBroadcast.js', () => ({ broadcastMakeRemoteChanged: h.changed }));
+vi.mock('../personalRemoteRuntime.js', () => ({
+ readPersonalRemoteProjection: h.personal,
+}));
import { sessions } from '../../localDb/schema';
import { remoteResourceRegistry } from '../../device-link/remoteResourceRegistry';
import { registerMakeRemoteResources } from '../remoteRuntime';
@@ -110,6 +114,7 @@ beforeEach(() => {
JSON.parse(h.rows.find((row) => row.clientId === completionId)!.agentMeta!)
.cindyMakeCompletion,
);
+ h.personal.mockResolvedValue(undefined);
vi.spyOn(remoteResourceRegistry, 'register').mockImplementation((next) => {
provider = next;
return () => {};
@@ -118,6 +123,21 @@ beforeEach(() => {
});
describe('Cindy Make mobile host adapter', () => {
+ it('includes personal sync and PR state as read-only resource content', async () => {
+ h.personal.mockResolvedValueOnce({
+ remote: { sync: 'synced' },
+ contributions: [{ number: 7, state: 'open' }],
+ });
+ const card = await get();
+ expect(card.display.subtitle).toContain('ja:cindyMake.storage.status.synced');
+ expect(card.display.subtitle).toContain('ja:cindyMake.contribution.state.open');
+ expect(
+ card.actions?.some(
+ (action) => action.id.includes('sync') || action.id.includes('contribution'),
+ ),
+ ).toBe(false);
+ });
+
it('does not register a remote resource or restore tasks while Make is disabled', () => {
h.enabled = false;
vi.mocked(remoteResourceRegistry.register).mockClear();
diff --git a/apps/desktop/src/main/cindy-make/__tests__/settingsStore.test.ts b/apps/desktop/src/main/cindy-make/__tests__/settingsStore.test.ts
index 3720c4f523..84f4a5a4fb 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/settingsStore.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/settingsStore.test.ts
@@ -29,10 +29,16 @@ describe('Cindy Make settings store', () => {
});
});
- it('persists explicit on and off choices until reset', () => {
+ it('reads a stored ON from an older version as off: builds never move the source', () => {
+ expect(__testing.normalize({ syncLatestBeforeBuild: true })).toEqual({
+ syncLatestBeforeBuild: false,
+ });
expect(writeCindyMakeSyncLatestBeforeBuild(true)).toEqual({
- syncLatestBeforeBuild: true,
+ syncLatestBeforeBuild: false,
});
+ });
+
+ it('persists explicit choices until reset', () => {
expect(writeCindyMakeSyncLatestBeforeBuild(false)).toEqual({
syncLatestBeforeBuild: false,
});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/sourcePnpm.test.ts b/apps/desktop/src/main/cindy-make/__tests__/sourcePnpm.test.ts
index 4daeb250b3..50d70dc789 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/sourcePnpm.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/sourcePnpm.test.ts
@@ -109,3 +109,28 @@ it('accepts fixed colon-separated script names while rejecting shell operators b
);
}
});
+
+it('accepts the pinned pnpm write roots while still rejecting arbitrary paths', async () => {
+ const signal = new AbortController().signal;
+ // The pinned write-root flags carry fixed relative paths; they pass the launch
+ // interlock (no spaces, quotes or shell metacharacters) and reach pnpm, where the
+ // CLI beats whatever the content's own `.npmrc` or `pnpm-workspace.yaml` sets.
+ for (const argument of [
+ '--config.modules-dir=node_modules',
+ '--config.virtual-store-dir=node_modules/.pnpm',
+ '--config.store-dir=node_modules/.cindy-make-store',
+ ]) {
+ await expect(runSourcePnpm({ PATH: '' }, ['install', argument], '.', signal)).rejects.toThrow(
+ 'pnpm not found',
+ );
+ }
+ for (const argument of [
+ '--store-dir=C:/Users/John Smith/store',
+ '--registry=https://attacker.invalid',
+ '--config.store-dir=node_modules & whoami',
+ ]) {
+ await expect(runSourcePnpm({ PATH: '' }, ['install', argument], '.', signal)).rejects.toThrow(
+ 'unsafe pnpm argument',
+ );
+ }
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/sourcePreparation.test.ts b/apps/desktop/src/main/cindy-make/__tests__/sourcePreparation.test.ts
index a477075f30..feaada4415 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/sourcePreparation.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/sourcePreparation.test.ts
@@ -17,10 +17,14 @@ import {
} from '../toolchainEnvironment.js';
import { runSourceGit } from '../sourceGit.js';
import { runSourcePnpm } from '../sourcePnpm.js';
+import { hasPendingBuild, readPendingBuilds } from '../pendingBuild.js';
import type { DoctorProbeResult } from '../doctor.js';
vi.mock('../sourceGit.js', () => ({ runSourceGit: vi.fn() }));
-vi.mock('../sourcePnpm.js', () => ({ runSourcePnpm: vi.fn(async () => undefined) }));
+vi.mock('../sourcePnpm.js', async (load) => ({
+ ...(await load<typeof import('../sourcePnpm.js')>()),
+ runSourcePnpm: vi.fn(async () => undefined),
+}));
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>();
return { ...actual, writeFile: vi.fn(actual.writeFile) };
@@ -167,11 +171,15 @@ describe('Source and dependency preparation', () => {
expect(checkout?.[2]).toBe(sourcePath);
expect(gitCalls.some(([, args]) => args[0] === 'reset')).toBe(false);
expect(runSourcePnpm).toHaveBeenCalledExactlyOnceWith(
+ // No `CINDY_*`/`XDT_*` generalization either: those prefixes carry real
+ // product secrets (`XDT_ELEVENLABS_API_KEY`), and a content `.npmrc`
+ // would expand them into a request to a host it chooses.
{
- CINDY_TEST_GIT: selectedGit,
- CINDY_TEST_NODE: path.join(root, source === 'system' ? 'system' : 'tools', 'node'),
- CINDY_TEST_PNPM: path.join(root, source === 'system' ? 'system' : 'tools', 'pnpm'),
- CINDY_TEST_PYTHON: undefined,
+ npm_config_userconfig: os.devNull,
+ npm_config_globalconfig: os.devNull,
+ COREPACK_ENV_FILE: '0',
+ COREPACK_ENABLE_PROJECT_SPEC: '0',
+ COREPACK_ENABLE_UNSAFE_CUSTOM_URLS: '0',
},
[
'fetch',
@@ -179,8 +187,10 @@ describe('Source and dependency preparation', () => {
'--prefer-offline',
'--prod=false',
'--ignore-scripts',
+ '--ignore-pnpmfile',
'--config.node-linker=isolated',
'--config.enable-modules-dir=false',
+ '--config.strict-ssl=true',
],
sourcePath,
expect.any(AbortSignal),
@@ -205,6 +215,10 @@ describe('Source and dependency preparation', () => {
expect(storage).not.toHaveBeenCalled();
const commands = vi.mocked(runSourceGit).mock.calls.map(([, args]) => args[0]);
expect(commands).toContain(existing ? 'checkout' : 'clone');
+ // The personal branch was just created from the official baseline, even
+ // when reusing a checkout that did not have a personal branch yet.
+ expect(readPendingBuilds(root)).toEqual([]);
+ expect(hasPendingBuild(root, { commit: 'a'.repeat(40), tree: '1'.repeat(40) })).toBe(false);
expect(commands).toContain('fetch');
if (existing) expect(commands).not.toContain('clone');
},
@@ -230,6 +244,27 @@ describe('Source and dependency preparation', () => {
});
});
+ it.each(['missing', 'corrupt'] as const)(
+ 'does not initialize a %s ledger when reusing an existing personal branch',
+ async (state) => {
+ if (state === 'corrupt') await writeFile(path.join(root, 'pending-build.json'), 'broken');
+ const result = await prepareCindySource(
+ env,
+ root,
+ { channel: 'dev', version: '0.0.0' },
+ new AbortController().signal,
+ );
+ expect(result.status).toBe('ready');
+ expect(readPendingBuilds(root)).toBeUndefined();
+ expect(
+ hasPendingBuild(root, { commit: 'a'.repeat(40), tree: '1'.repeat(40) }),
+ ).toBeUndefined();
+ expect(vi.mocked(runSourceGit).mock.calls.some(([, args]) => args[0] === 'clone')).toBe(
+ false,
+ );
+ },
+ );
+
it('warms the cache without installing baseline dependencies or running scripts', async () => {
const progress = vi.fn();
const result = await prepareCindySource(
diff --git a/apps/desktop/src/main/cindy-make/__tests__/sourceRevisions.test.ts b/apps/desktop/src/main/cindy-make/__tests__/sourceRevisions.test.ts
index e070cccce6..355efacd5b 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/sourceRevisions.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/sourceRevisions.test.ts
@@ -80,10 +80,23 @@ describe('source revision snapshot', () => {
await expect(read()).resolves.toMatchObject({ baseCommit: undefined, mainBehind: 4 });
});
- it('reports the explicitly adopted upstream even when personal HEAD has not moved', async () => {
+ it('reports the explicitly adopted upstream when it is the personal tip’s base', async () => {
outputs['rev-parse --verify refs/cindy-make/personal-upstream^{commit}'] = remoteMain;
+ outputs['merge-base ' + remoteMain + ' ' + personal] = remoteMain;
await expect(read()).resolves.toMatchObject({ baseCommit: remoteMain });
- expect(vi.mocked(runSourceGit).mock.calls.some(([, args]) => args[0] === 'merge-base')).toBe(false);
+ // Verified against the tip; the fallback derivation is not consulted.
+ expect(
+ vi
+ .mocked(runSourceGit)
+ .mock.calls.some(([, args]) => args.join(' ') === 'merge-base ' + personal + ' ' + remoteMain),
+ ).toBe(false);
+ });
+
+ it('ignores a recorded upstream that is not the personal tip’s base', async () => {
+ // An interrupted move left "old tip + new base": the wrong base is never used.
+ outputs['rev-parse --verify refs/cindy-make/personal-upstream^{commit}'] = remoteMain;
+ outputs['merge-base ' + remoteMain + ' ' + personal] = baseline;
+ await expect(read()).resolves.toMatchObject({ baseCommit: baseline });
});
it.each(['', '-1 2', '0 1.5', '0 9007199254740992', 'failed', new Error('count failed')])(
diff --git a/apps/desktop/src/main/cindy-make/__tests__/stateBroadcast.test.ts b/apps/desktop/src/main/cindy-make/__tests__/stateBroadcast.test.ts
new file mode 100644
index 0000000000..339808b0e2
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/stateBroadcast.test.ts
@@ -0,0 +1,121 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { CindyMakeGlobalState } from '../../../shared/cindyMakeDoctor';
+
+const h = vi.hoisted(() => ({
+ scope: { ownerScopeKey: 'owner-a', ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 } },
+ current: true,
+ tap: vi.fn(),
+}));
+const windows = [{ isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } }];
+
+vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => windows } }));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => h.scope,
+ isDataOwnerBroadcastScopeCurrent: () => h.current,
+ tapWindowBroadcast: h.tap,
+}));
+
+let broadcastCindyMakeState: typeof import('../stateBroadcast').broadcastCindyMakeState;
+const collectionEvents = () => h.tap.mock.calls.filter(([, event]) => !event.resourceRefs);
+
+beforeEach(async () => {
+ vi.resetModules();
+ ({ broadcastCindyMakeState } = await import('../stateBroadcast'));
+ h.scope = {
+ ownerScopeKey: 'owner-a',
+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 },
+ };
+ h.current = true;
+ h.tap.mockClear();
+ windows[0].webContents.send.mockClear();
+});
+
+describe('Cindy Make state broadcast', () => {
+ it('invalidates the collection for global personal state without a live task entry', () => {
+ const state: CindyMakeGlobalState = {
+ personalSync: { running: true, step: 'official' },
+ };
+ broadcastCindyMakeState(state);
+ expect(h.tap).toHaveBeenCalledExactlyOnceWith(
+ 'maker:remote-resources:changed',
+ { collectionId: 'cindy-make' },
+ h.scope.ownerStamp,
+ );
+ for (const personalSync of [
+ { running: false, waiting: { kind: 'official', reason: 'input' } },
+ { running: false, error: 'network' },
+ { running: false, done: { at: 1 } },
+ ] satisfies NonNullable<CindyMakeGlobalState['personalSync']>[])
+ broadcastCindyMakeState({ personalSync });
+ expect(collectionEvents()).toHaveLength(4);
+ });
+
+ it('does not repeat the collection invalidation for task-only changes', () => {
+ broadcastCindyMakeState({
+ personalSync: { running: true, step: 'official' },
+ tasks: {
+ run: {
+ runId: 'run',
+ platform: 'win32',
+ arch: 'x64',
+ status: 'running',
+ checks: [],
+ task: { sessionId: 'session', phase: 'source' },
+ },
+ },
+ });
+ h.tap.mockClear();
+ broadcastCindyMakeState({
+ personalSync: { running: true, step: 'official' },
+ tasks: {
+ run: {
+ runId: 'run',
+ platform: 'win32',
+ arch: 'x64',
+ status: 'running',
+ checks: [],
+ task: { sessionId: 'session', phase: 'workspace' },
+ },
+ },
+ });
+ expect(h.tap).toHaveBeenCalledExactlyOnceWith(
+ 'maker:remote-resources:changed',
+ {
+ collectionId: 'cindy-make',
+ resourceRefs: [{ collectionId: 'cindy-make', kind: 'session', id: 'session' }],
+ },
+ h.scope.ownerStamp,
+ );
+ expect(collectionEvents()).toHaveLength(0);
+ });
+
+ it('invalidates finished resources when the global GitHub state changes', () => {
+ const personalRemote: NonNullable<CindyMakeGlobalState['personalRemote']> = {
+ github: 'connected',
+ offerMigration: false,
+ sync: 'pending',
+ };
+ broadcastCindyMakeState({ personalRemote });
+ broadcastCindyMakeState({ personalRemote: { ...personalRemote, sync: 'synced' } });
+ expect(collectionEvents()).toHaveLength(2);
+ });
+
+ it('invalidates the same global projection for a new owner generation', () => {
+ const state: CindyMakeGlobalState = { personalSync: { running: false } };
+ broadcastCindyMakeState(state);
+ h.scope = { ...h.scope, ownerStamp: { ...h.scope.ownerStamp, ownerGeneration: 2 } };
+ broadcastCindyMakeState(state);
+ expect(collectionEvents()).toHaveLength(2);
+ expect(h.tap).toHaveBeenLastCalledWith(
+ 'maker:remote-resources:changed',
+ { collectionId: 'cindy-make' },
+ h.scope.ownerStamp,
+ );
+ });
+
+ it('does not invalidate resources for a stale captured owner', () => {
+ h.current = false;
+ broadcastCindyMakeState({ personalSync: { running: true, step: 'official' } });
+ expect(h.tap).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/syncJourneys.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/syncJourneys.git-integration.test.ts
new file mode 100644
index 0000000000..a43f256ce5
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/syncJourneys.git-integration.test.ts
@@ -0,0 +1,761 @@
+import os from 'node:os';
+import path from 'node:path';
+import { existsSync } from 'node:fs';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { expect, it } from 'vitest';
+import { PersonalSync, type PersonalSyncRecord } from '../personalSync';
+import {
+ PersonalRemoteController,
+ adoptedRewrite,
+ personalGitEnv,
+ type PersonalRemoteGitOptions,
+ type PersonalRemoteRecord,
+} from '../personalRemote';
+import { UpstreamMergeController, type SavedUpstreamMerge } from '../upstreamMergeController';
+import {
+ applyUpstreamMerge,
+ cancelUpstreamMerge,
+ cleanupMergedCandidate,
+ discardFeatureMerge,
+ mergeWorktree,
+ preparePersonalCombine,
+ prepareUpstreamMerge,
+ type MergeGit,
+} from '../upstreamMerge';
+import { PERSONAL_UPSTREAM_REF } from '../sourceContent';
+import { rollbackUnbuiltHistory, hasUnbuiltPersonalChanges } from '../buildRollback';
+import {
+ initializePendingBuilds,
+ recordPendingBuild,
+ rewritePendingBuilds,
+ settlePendingBuilds,
+} from '../pendingBuild';
+import { CindyMakeHistoryStore } from '../historyStore';
+import { CINDY_PERSONAL_BRANCH, makeSourceCheckoutPath, makeSourceRoot } from '../sourcePaths';
+import { runSourceGit } from '../sourceGit';
+import type { CindyMakeSyncState } from '../../../shared/cindyMakeSync';
+
+/**
+ * End-to-end journeys of the single Sync with real Git and the real controllers: an
+ * official repository that publishes releases, the user's fork on GitHub (a bare
+ * repository) and one or two computers. Only the conflict task's Agent is played by
+ * the test, the way a resolver works in its isolated folder.
+ */
+const OFFICIAL_URL = 'https://github.com/makecindy/cindy.git';
+const FORK_URL = 'https://github.com/octo/cindy.git';
+const TOKEN = 'gho_fake-token-for-tests';
+const TASK_IDENTITY = [
+ '-c',
+ 'user.name=Cindy Make',
+ '-c',
+ '-c',
+ 'commit.gpgSign=false',
+ '-c',
+ 'core.editor=true',
+];
+const LINES = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
+const text = (lines: string[]) => lines.join('\n') + '\n';
+const set = (index: number, value: string, lines = LINES) =>
+ lines.map((line, at) => (at === index ? value : line));
+
+async function world() {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-sync-journeys-'));
+ const official = path.join(root, 'official');
+ const fork = path.join(root, 'fork.git');
+ const env = {
+ PATH: process.env.PATH,
+ SystemRoot: process.env.SystemRoot,
+ GIT_CONFIG_GLOBAL: path.join(root, 'gitconfig'),
+ GIT_CONFIG_NOSYSTEM: '1',
+ };
+ await writeFile(env.GIT_CONFIG_GLOBAL, '');
+ const raw = (args: string[], cwd: string) =>
+ runSourceGit(env, args, cwd, AbortSignal.timeout(60_000));
+ const head = async (cwd: string, ref = 'HEAD') =>
+ (await raw(['rev-parse', '--verify', ref], cwd)).trim();
+ await mkdir(official);
+ await raw(['init', '--initial-branch=main'], official);
+ await writeFile(path.join(official, 'feature.txt'), text(LINES));
+ await raw(['add', '-A'], official);
+ await raw(
+ ['-c', 'user.name=Official', '-c', '[email protected]', 'commit', '-m', 'v1'],
+ official,
+ );
+ // The user's fork of the official repository, before any personal version is saved.
+ await raw(['clone', '--bare', official, fork], root);
+ /** The official project publishes a release; Sync targets it. */
+ const release = async (ref: string, file: string, lines: string[]) => {
+ await writeFile(path.join(official, file), text(lines));
+ await raw(['add', '-A'], official);
+ await raw(
+ ['-c', 'user.name=Official', '-c', '[email protected]', 'commit', '-m', ref],
+ official,
+ );
+ return { ref, commit: await head(official) };
+ };
+ const forkTip = (ref = 'refs/heads/cindy-personal') =>
+ head(fork, ref).catch(() => undefined);
+ return {
+ root,
+ official,
+ fork,
+ env,
+ raw,
+ head,
+ release,
+ forkTip,
+ clean: () => rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }),
+ };
+}
+type World = Awaited<ReturnType<typeof world>>;
+
+/**
+ * One computer: its managed source, the shared source-operation lifecycle, GitHub and Sync.
+ * `realGeneration` wires the real pending-generation facts (see `pendingBuild`): the
+ * device-level record beside the source, this device's generated versions and a real
+ * build history for the changes `change` integrates.
+ */
+async function computer(w: World, name: string, options: { realGeneration?: boolean } = {}) {
+ const userData = path.join(w.root, name);
+ const source = makeSourceCheckoutPath(userData);
+ const recordRoot = makeSourceRoot(userData);
+ const history = new CindyMakeHistoryStore(path.join(userData, 'history-owner'));
+ const generated = new Set<string>();
+ const isPublished = (commit: string) => generated.has(commit);
+ const unbuiltChanges = (commit: string, tree: string) =>
+ hasUnbuiltPersonalChanges(history, recordRoot, { commit, tree }, isPublished);
+ await mkdir(path.dirname(source), { recursive: true });
+ await w.raw(['clone', w.official, source], w.root);
+ await w.raw(['checkout', '-b', 'cindy-personal'], source);
+ await w.raw(['update-ref', PERSONAL_UPSTREAM_REF, await w.head(source)], source);
+ initializePendingBuilds(recordRoot);
+ const timeout = () => AbortSignal.timeout(60_000);
+ const mergeGit: MergeGit = (args, cwd, indexFile) =>
+ runSourceGit(
+ { ...w.env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args.map((arg) => (arg === OFFICIAL_URL ? w.official : arg)),
+ cwd,
+ timeout(),
+ );
+ const remoteGit = async (args: string[], cwd: string, options?: PersonalRemoteGitOptions) => {
+ const output = await runSourceGit(
+ personalGitEnv(w.env, options),
+ args.map((arg) => (arg === FORK_URL ? w.fork : arg)),
+ cwd,
+ timeout(),
+ );
+ return output.trim() === w.fork ? FORK_URL : output;
+ };
+ const readRef = async (ref: string) =>
+ (await w.raw(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], source).catch(() => ''))
+ .trim() || undefined;
+ const isAncestor = (ancestor: string, descendant: string) =>
+ w.raw(['merge-base', '--is-ancestor', ancestor, descendant], source).then(
+ () => true,
+ (error) => {
+ if ((error as { exitCode?: number }).exitCode === 1) return false;
+ throw error;
+ },
+ );
+
+ // Durable records survive a restart; the controllers are rebuilt from them.
+ let record: PersonalRemoteRecord = { schema: 1 };
+ let saved: SavedUpstreamMerge | undefined;
+ let syncRecord: PersonalSyncRecord = {};
+ let target = { ref: 'v1', commit: await w.head(source) };
+ const sessions: string[] = [];
+ const reminders: string[] = [];
+ const states: CindyMakeSyncState[] = [];
+ let remote!: PersonalRemoteController;
+ let merge!: UpstreamMergeController;
+ let sync: PersonalSync | undefined;
+
+ const build = () => {
+ sync = undefined;
+ remote = new PersonalRemoteController({
+ source,
+ read: () => structuredClone(record),
+ write: (next) => {
+ record = structuredClone(next);
+ },
+ identity: async () => ({ status: 'connected', identity: { login: 'octo', token: TOKEN } }),
+ ensureFork: async () => 'octo/cindy',
+ findPersonalFork: async () => ((await w.forkTip()) ? 'octo/cindy' : undefined),
+ git: remoteGit,
+ sourceExists: () => existsSync(path.join(source, '.git')),
+ withProject: (run) => run(),
+ withSourceUse: (run) => run(),
+ hasUnbuiltChanges: options.realGeneration
+ ? async (commit: string, tree: string) => unbuiltChanges(commit, tree)
+ : async () => false,
+ isBuilt: options.realGeneration ? isPublished : () => false,
+ ...(options.realGeneration
+ ? { recordUnbuilt: (snapshot: { commit: string; tree: string }) => recordPendingBuild(recordRoot, snapshot) }
+ : {}),
+ sourceSettled: () => true,
+ officialBase: () => readRef(PERSONAL_UPSTREAM_REF),
+ sourceChanged: () => {},
+ publish: () => {},
+ sleep: async () => {},
+ now: () => Date.now(),
+ });
+ merge = new UpstreamMergeController({
+ read: () => (saved ? structuredClone(saved) : undefined),
+ write: (next) => {
+ saved = structuredClone(next);
+ },
+ publish: (state) => {
+ // Every adopted update or combine is lineage for the next upload (as in the app),
+ // and a combine's fork tip is unverified here until a version covers it.
+ const rewrite = state && adoptedRewrite(state);
+ if (rewrite) {
+ if (state.remote?.commit) remote.recordUnverifiedRemote(state.remote.commit);
+ remote.recordRewrite(rewrite.from, rewrite.to);
+ if (options.realGeneration && state.commit && state.tree) {
+ rewritePendingBuilds(recordRoot, rewrite.from, {
+ commit: state.commit,
+ tree: state.tree,
+ });
+ // A combine carried in a GitHub version: its changes are not
+ // generated on this computer yet.
+ if (state.remote?.commit)
+ recordPendingBuild(recordRoot, { commit: state.commit, tree: state.tree });
+ }
+ }
+ sync?.operationChanged(state);
+ },
+ owner: () => 'owner',
+ hasWorkspace: (state) => existsSync(mergeWorktree(userData, state.id)),
+ exclusive: (run) => run(),
+ latest: async () => target,
+ prepare: (state, publish, isCurrent) =>
+ prepareUpstreamMerge(userData, state, mergeGit, publish, isCurrent),
+ prepareCombine: (state, publish, isCurrent) =>
+ preparePersonalCombine(userData, state, mergeGit, publish, isCurrent),
+ apply: (state, isCurrent, _publish, options) =>
+ applyUpstreamMerge(userData, state, mergeGit, isCurrent, options),
+ session: async (state, _options, bind) => {
+ const id = state.sessionId ?? `resolver-${sessions.length + 1}`;
+ bind(id);
+ if (!sessions.includes(id)) sessions.push(id);
+ return id;
+ },
+ running: () => false,
+ remind: async (state) => {
+ reminders.push(state.id);
+ },
+ sleep: async () => {},
+ refresh: async () => {},
+ cleanup: (state, isCurrent) => cleanupMergedCandidate(userData, state, mergeGit, isCurrent),
+ cancel: (state, isCurrent) => cancelUpstreamMerge(userData, state, mergeGit, isCurrent),
+ discard: (state, isCurrent) => discardFeatureMerge(userData, state, mergeGit, isCurrent),
+ });
+ sync = new PersonalSync({
+ remote: () =>
+ record.repository && record.choice === 'github'
+ ? {
+ sync: () => remote.syncNow(),
+ tips: () => remote.fetchedTips(),
+ keep: (side) => remote.keepSide(side),
+ }
+ : undefined,
+ // Like the app's target lookup, the returned commit is available locally.
+ target: async () => {
+ await w.raw(['fetch', '--no-tags', '--no-write-fetch-head', w.official, target.commit], source);
+ return target;
+ },
+ base: () => readRef(PERSONAL_UPSTREAM_REF),
+ isAncestor,
+ unbuilt: options.realGeneration
+ ? async () => {
+ const commit = await readRef(`refs/heads/${CINDY_PERSONAL_BRANCH}`);
+ if (!commit) return false;
+ const tree = (await w.raw(['rev-parse', `${commit}^{tree}`], source)).trim();
+ return unbuiltChanges(commit, tree);
+ }
+ : async () => false,
+ operation: () => merge.status(),
+ resume: (options) => merge.resumeForSync(options),
+ combine: (tips, options) => merge.combine(tips, options, true),
+ update: (next, options) => merge.update(options, undefined, { target: next, autoResolve: true }),
+ abandon: (id) => merge.abandon(id),
+ accept: (id) => merge.acceptMissing(id),
+ reserve: () => () => {},
+ load: () => structuredClone(syncRecord),
+ save: (next) => {
+ syncRecord = structuredClone(next);
+ },
+ publish: (state) => states.push(state),
+ now: () => 1,
+ });
+ };
+ build();
+
+ let at = 1_700_000_000 + name.charCodeAt(0) * 100_000;
+ let changes = 0;
+ /** A finished task's change, committed like Cindy Make does. */
+ const change = async (file: string, lines: string[]) => {
+ const before = await w.head(source);
+ const beforeTree = (await w.raw(['rev-parse', `${before}^{tree}`], source)).trim();
+ await writeFile(path.join(source, file), text(lines));
+ await w.raw(['add', '-A'], source);
+ at += 10;
+ await w.raw(
+ [
+ ...TASK_IDENTITY,
+ 'commit',
+ '-s',
+ `--date=${at} +0000`,
+ '-m',
+ 'Cindy Make: complete personal change',
+ ],
+ source,
+ );
+ const tip = await w.head(source);
+ if (options.realGeneration) {
+ // As `recordAppliedMerge` does when a task's change is integrated: the
+ // pending-generation fact lands with (actually before) its receipt.
+ const runId = `change-${++changes}`;
+ const tree = (await w.raw(['rev-parse', `${tip}^{tree}`], source)).trim();
+ history.seed({
+ runId,
+ sessionId: runId,
+ title: file,
+ request: file,
+ createdAt: at,
+ updatedAt: at,
+ });
+ history.receipt(runId, {
+ id: `op-${runId}`,
+ action: 'integrate',
+ at,
+ baselineCommit: before,
+ commit: tip,
+ beforeTree,
+ tree,
+ taskTree: tree,
+ });
+ recordPendingBuild(recordRoot, { commit: tip, tree });
+ }
+ return tip;
+ };
+ const operation = () => merge.status();
+ const run = async (step: () => unknown) => {
+ await step();
+ await sync!.settled();
+ return sync!.state();
+ };
+ /** The conflict task's Agent: resolve the files, finish the rebase, end its turn. */
+ const resolve = async (file: string, lines: string[] | 'skip') => {
+ const state = operation()!;
+ const worktree = mergeWorktree(userData, state.id);
+ if (lines === 'skip') await w.raw([...TASK_IDENTITY, 'rebase', '--skip'], worktree);
+ else {
+ await writeFile(path.join(worktree, file), text(lines));
+ await w.raw(['add', '-A'], worktree);
+ await w.raw([...TASK_IDENTITY, 'rebase', '--continue'], worktree);
+ }
+ await turnEnds();
+ };
+ const turnEnds = async () => {
+ const sessionId = operation()!.sessionId!;
+ merge.prepareTurn(sessionId)();
+ await merge.finish(sessionId);
+ await sync!.settled();
+ };
+ return {
+ userData,
+ source,
+ read: (file: string) => readFile(path.join(source, file), 'utf8'),
+ tip: () => w.head(source),
+ base: () => readRef(PERSONAL_UPSTREAM_REF),
+ change,
+ resolve,
+ turnEnds,
+ operation,
+ reminders,
+ states,
+ /** Generate the application from the current source: this device's own build. */
+ buildIt: async () => {
+ settlePendingBuilds(recordRoot);
+ generated.add(await w.head(source));
+ },
+ /** A failed generation rolls its unbuilt integrations back, as build cleanup does. */
+ failGeneration: () =>
+ rollbackUnbuiltHistory(
+ history,
+ source,
+ (args, cwd, indexFile) =>
+ runSourceGit(
+ { ...w.env, ...(indexFile ? { GIT_INDEX_FILE: indexFile } : {}) },
+ args,
+ cwd,
+ timeout(),
+ ),
+ isPublished,
+ recordRoot,
+ ),
+ /** The pending-generation judgement for the current personal version. */
+ unbuiltState: async () => {
+ const commit = await w.head(source);
+ const tree = (await w.raw(['rev-parse', `${commit}^{tree}`], source)).trim();
+ return unbuiltChanges(commit, tree);
+ },
+ target: (next: { ref: string; commit: string }) => {
+ target = next;
+ },
+ /** Save to GitHub through the consent card (also uses an existing personal version). */
+ save: async () => {
+ remote.save();
+ await remote.settled();
+ return structuredClone(record);
+ },
+ record: () => structuredClone(record),
+ sync: () => run(() => sync!.sync()),
+ abandon: () => run(() => sync!.abandon()),
+ accept: () => run(() => sync!.accept()),
+ keep: (side: 'github' | 'local') => run(() => sync!.keep(side)),
+ state: () => sync!.state(),
+ /** Cindy quits and starts again: everything is rebuilt from the durable records. */
+ restart: () => build(),
+ };
+}
+
+const journey = (name: string, body: (w: World) => Promise<void>) =>
+ it(
+ name,
+ async () => {
+ const w = await world();
+ try {
+ await body(w);
+ } finally {
+ await w.clean();
+ }
+ },
+ 180_000,
+ );
+
+journey('without GitHub: Sync moves the personal version to a new official release', async (w) => {
+ const a = await computer(w, 'a');
+ await a.change('personal.txt', ['mine']);
+ const v2 = await w.release('v2', 'official.txt', ['new']);
+ a.target(v2);
+ expect(await a.sync()).toEqual({ done: { at: 1, ref: 'v2' } });
+ expect(await a.read('personal.txt')).toBe('mine\n');
+ expect(await a.read('official.txt')).toBe('new\n');
+ expect(await a.base()).toBe(v2.commit);
+ // Already there: a second Sync changes nothing.
+ const tip = await a.tip();
+ expect(await a.sync()).toEqual({ done: { at: 1, ref: 'v2' } });
+ expect(await a.tip()).toBe(tip);
+});
+
+journey('without GitHub: a fused conflict waits for confirmation, then Sync continues', async (w) => {
+ const a = await computer(w, 'a');
+ await a.change('feature.txt', set(2, 'mine'));
+ const v2 = await w.release('v2', 'feature.txt', set(2, 'official'));
+ a.target(v2);
+ expect((await a.sync()).waiting).toMatchObject({ kind: 'official', reason: 'working' });
+ // Nothing moved on this computer while it waits.
+ expect(await a.read('feature.txt')).toBe(text(set(2, 'mine')));
+ await a.resolve('feature.txt', set(2, 'official and mine'));
+ expect(a.reminders).toHaveLength(1);
+ await a.turnEnds();
+ expect(a.state().waiting).toMatchObject({ reason: 'missing', missing: 1 });
+ await a.accept();
+ expect(a.state()).toEqual({ done: { at: 1, ref: 'v2' } });
+ expect(await a.read('feature.txt')).toBe(text(set(2, 'official and mine')));
+ expect(await a.base()).toBe(v2.commit);
+ expect(a.operation()).toMatchObject({ status: 'merged', hasWorkspace: false });
+});
+
+journey('a dropped change is noticed, the task is reminded once, then the user decides', async (w) => {
+ const a = await computer(w, 'a');
+ await a.change('kept.txt', ['kept']);
+ await a.change('feature.txt', set(2, 'mine'));
+ const v2 = await w.release('v2', 'feature.txt', set(2, 'official'));
+ a.target(v2);
+ await a.sync();
+ // The Agent gives the conflicting change up instead of combining it.
+ await a.resolve('feature.txt', 'skip');
+ expect(a.reminders).toHaveLength(1);
+ expect(a.state().waiting).toMatchObject({ reason: 'working' });
+ // It ends its next turn without putting it back: the user decides.
+ await a.turnEnds();
+ expect(a.state().waiting).toMatchObject({ reason: 'missing', missing: 1 });
+ expect(await a.read('feature.txt')).toBe(text(set(2, 'mine')));
+ expect(await a.accept()).toEqual({ done: { at: 1, ref: 'v2' } });
+ expect(await a.read('feature.txt')).toBe(text(set(2, 'official')));
+ expect(await a.read('kept.txt')).toBe('kept\n');
+});
+
+journey('a restart while the conflict is handled continues from the same task', async (w) => {
+ const a = await computer(w, 'a');
+ await a.change('feature.txt', set(2, 'mine'));
+ const v2 = await w.release('v2', 'feature.txt', set(2, 'official'));
+ a.target(v2);
+ await a.sync();
+ a.restart();
+ expect(a.state().waiting).toMatchObject({ kind: 'official', reason: 'interrupted' });
+ // The user says "continue" in the task; its Agent finishes the work.
+ await a.resolve('feature.txt', set(2, 'mine'));
+ expect(a.state()).toEqual({ done: { at: 1, ref: 'v2' } });
+ expect(await a.read('feature.txt')).toBe(text(set(2, 'mine')));
+});
+
+journey('Abandon leaves the personal version exactly as it was', async (w) => {
+ const a = await computer(w, 'a');
+ const tip = await a.change('feature.txt', set(2, 'mine'));
+ const v2 = await w.release('v2', 'feature.txt', set(2, 'official'));
+ a.target(v2);
+ await a.sync();
+ expect(await a.abandon()).toEqual({ error: 'cancelled', abandoned: 'official' });
+ expect(await a.tip()).toBe(tip);
+ expect(a.operation()).toMatchObject({ status: 'cancelled', hasWorkspace: false });
+ // Sync can be tried again later.
+ expect((await a.sync()).waiting).toMatchObject({ kind: 'official' });
+});
+
+journey('a second computer uses the personal version saved on GitHub', async (w) => {
+ const a = await computer(w, 'a');
+ await a.change('personal.txt', ['from a']);
+ expect(await a.save()).toMatchObject({ repository: 'octo/cindy', sync: 'synced' });
+ expect(await w.forkTip()).toBe(await a.tip());
+ expect(await w.forkTip('refs/heads/cindy-personal-base')).toBe(await a.base());
+
+ const b = await computer(w, 'b');
+ expect(await b.save()).toMatchObject({ repository: 'octo/cindy', sync: 'retrieved' });
+ expect(await b.tip()).toBe(await a.tip());
+ expect(await b.read('personal.txt')).toBe('from a\n');
+});
+
+journey(
+ 'a change is generated before it is shared; the other computer takes the same source over and generates it itself',
+ async (w) => {
+ const a = await computer(w, 'a', { realGeneration: true });
+ await a.change('mine.txt', ['mine']);
+ // Not generated yet: binding GitHub publishes nothing of it.
+ expect(await a.save()).toMatchObject({ repository: 'octo/cindy', sync: 'pendingBuild' });
+ expect(await w.forkTip()).toBeUndefined();
+ // This computer generates its own application: the change is established and shared.
+ await a.buildIt();
+ expect(await a.sync()).toMatchObject({ done: { ref: 'v1' } });
+ expect(await w.forkTip()).toBe(await a.tip());
+
+ // The second computer takes the same source over — without this computer's
+ // build history — and generates its own application from it.
+ const b = await computer(w, 'b', { realGeneration: true });
+ expect(await b.save()).toMatchObject({ repository: 'octo/cindy', sync: 'retrieved' });
+ expect(await b.tip()).toBe(await a.tip());
+ expect(await b.read('mine.txt')).toBe('mine\n');
+ expect(await b.unbuiltState()).toBe(true);
+ await b.buildIt();
+ expect(await b.unbuiltState()).toBe(false);
+ },
+);
+
+journey('a failed generation rolls back without publishing or replacing the GitHub version', async (w) => {
+ const a = await computer(w, 'a', { realGeneration: true });
+ const first = await a.change('first.txt', ['first']);
+ await a.save();
+ await a.buildIt();
+ expect(await a.sync()).toMatchObject({ done: { ref: 'v1' } });
+ expect(await w.forkTip()).toBe(first);
+
+ // A second change waits for its generation: nothing replaces the GitHub version.
+ await a.change('second.txt', ['second']);
+ const failed = await a.tip();
+ expect(await a.sync()).toMatchObject({ done: { uploadAfterBuild: true } });
+ expect(await w.forkTip()).toBe(first);
+
+ // The generation fails and its unbuilt integrations are rolled back…
+ await a.failGeneration();
+ expect(await a.tip()).toBe(first);
+ expect(await a.unbuiltState()).toBe(false);
+ // …the failed change never reached GitHub and the version there is untouched.
+ expect(await w.forkTip()).toBe(first);
+ expect(await a.sync()).toMatchObject({ done: { ref: 'v1' } });
+ expect(await w.forkTip()).toBe(first);
+ expect(await w.forkTip()).not.toBe(failed);
+});
+
+journey('both computers changed different places: Sync combines and both end up equal', async (w) => {
+ const a = await computer(w, 'a');
+ const b = await computer(w, 'b');
+ await a.change('a.txt', ['a']);
+ await a.save();
+ await b.save();
+ await a.change('a2.txt', ['a2']);
+ expect((await a.sync()).done).toBeTruthy();
+ await b.change('b.txt', ['b']);
+ expect(await b.sync()).toEqual({ done: { at: 1, ref: 'v1' } });
+ expect(await w.forkTip()).toBe(await b.tip());
+ expect(await a.sync()).toEqual({ done: { at: 1, ref: 'v1' } });
+ expect(await a.tip()).toBe(await b.tip());
+ for (const file of ['a.txt', 'a2.txt', 'b.txt']) expect(await a.read(file)).toBeTruthy();
+});
+
+journey('two matching edits in different repeated blocks are both kept', async (w) => {
+ const a = await computer(w, 'a');
+ const b = await computer(w, 'b');
+ const padding = Array.from({ length: 10 }, (_, i) => 'padding ' + i);
+ const block = [...padding, 'deny()', ...padding];
+ const original = ['admin:', ...block, 'guest:', ...block];
+ await a.change('feature.txt', original);
+ await a.save();
+ await b.save();
+ await a.change(
+ 'feature.txt',
+ original.map((line, at) => (at === 11 ? 'allow()' : line)),
+ );
+ await a.sync();
+ await b.change(
+ 'feature.txt',
+ original.map((line, at) => (at === 11 + block.length + 1 ? 'allow()' : line)),
+ );
+ expect(await b.sync()).toEqual({ done: { at: 1, ref: 'v1' } });
+ expect(await b.read('feature.txt')).toBe(
+ text(
+ original.map((line, at) => (at === 11 || at === 11 + block.length + 1 ? 'allow()' : line)),
+ ),
+ );
+ expect(await w.forkTip()).toBe(await b.tip());
+});
+
+journey('both computers changed the same line: the conflict task keeps both, then it is shared', async (w) => {
+ const a = await computer(w, 'a');
+ const b = await computer(w, 'b');
+ await a.save();
+ await b.save();
+ await a.change('feature.txt', set(4, 'from a'));
+ await a.sync();
+ await b.change('feature.txt', set(4, 'from b'));
+ expect((await b.sync()).waiting).toMatchObject({ kind: 'combine', reason: 'working' });
+ // GitHub keeps the other computer's version until the result is adopted.
+ expect(await w.forkTip()).toBe(await a.tip());
+ await b.resolve('feature.txt', set(4, 'from a and b'));
+ expect(b.reminders).toHaveLength(1);
+ await b.turnEnds();
+ expect(b.state().waiting).toMatchObject({ reason: 'missing', missing: 1 });
+ await b.accept();
+ expect(b.state()).toEqual({ done: { at: 1, ref: 'v1' } });
+ // The combine adopted the fork's tip through the shared merge lifecycle: its
+ // content is unverified on this computer until a generated version covers it.
+ expect(b.record().unverifiedRemote ?? []).toContain(await a.tip());
+ expect(await w.forkTip()).toBe(await b.tip());
+ await a.sync();
+ expect(await a.read('feature.txt')).toBe(text(set(4, 'from a and b')));
+});
+
+journey('a combine that cannot be settled: give it up, then keep one side (backed up)', async (w) => {
+ const a = await computer(w, 'a');
+ const b = await computer(w, 'b');
+ await a.save();
+ await b.save();
+ const fromA = await a.change('feature.txt', set(4, 'from a'));
+ await a.sync();
+ const fromB = await b.change('feature.txt', set(4, 'from b'));
+ await b.sync();
+ expect(await b.abandon()).toEqual({ error: 'cancelled', abandoned: 'combine' });
+ expect(await b.tip()).toBe(fromB);
+ expect(await w.forkTip()).toBe(fromA);
+
+ // B keeps its own version; the version on GitHub is backed up there first.
+ expect(await b.keep('local')).toEqual({ done: { at: 1, ref: 'v1' } });
+ expect(await w.forkTip()).toBe(fromB);
+ expect(await w.forkTip(`refs/heads/cindy-personal-backup/${fromA.slice(0, 12)}`)).toBe(fromA);
+
+ // A, with a new change of its own, meets the conflict too, gives it up and keeps the
+ // GitHub version instead; its own version stays in a local backup.
+ const a2 = await a.change('a2.txt', ['a2']);
+ await a.sync();
+ expect(a.state().waiting).toMatchObject({ kind: 'combine' });
+ await a.abandon();
+ expect(await a.keep('github')).toEqual({ done: { at: 1, ref: 'v1' } });
+ expect(await a.tip()).toBe(fromB);
+ expect(await a.read('feature.txt')).toBe(text(set(4, 'from b')));
+ expect(await w.head(a.source, `refs/cindy-make/backups/personal-remote-local/${a2}`)).toBe(a2);
+});
+
+journey('a computer with nothing new follows the version the other computer chose', async (w) => {
+ const a = await computer(w, 'a');
+ const b = await computer(w, 'b');
+ await a.save();
+ await b.save();
+ const fromA = await a.change('feature.txt', set(4, 'from a'));
+ await a.sync();
+ const fromB = await b.change('feature.txt', set(4, 'from b'));
+ await b.sync();
+ await b.abandon();
+ await b.keep('local');
+ // A changed nothing since it uploaded: it takes the chosen version, keeping a backup.
+ expect(await a.sync()).toEqual({ done: { at: 1, ref: 'v1' } });
+ expect(await a.tip()).toBe(fromB);
+ expect(await w.head(a.source, `refs/cindy-make/backups/personal-remote-local/${fromA}`)).toBe(
+ fromA,
+ );
+});
+
+journey('an official release reaches both computers through one update and GitHub', async (w) => {
+ const a = await computer(w, 'a');
+ const b = await computer(w, 'b');
+ await a.change('personal.txt', ['mine']);
+ await a.save();
+ await b.save();
+ const v2 = await w.release('v2', 'official.txt', ['new']);
+ a.target(v2);
+ b.target(v2);
+ expect(await a.sync()).toEqual({ done: { at: 1, ref: 'v2' } });
+ // The rewritten version replaces the old one on GitHub, with its new official base.
+ expect(await w.forkTip()).toBe(await a.tip());
+ expect(await w.forkTip('refs/heads/cindy-personal-base')).toBe(v2.commit);
+ // The other computer takes it in instead of updating again.
+ expect(await b.sync()).toEqual({ done: { at: 1, ref: 'v2' } });
+ expect(await b.tip()).toBe(await a.tip());
+ expect(await b.base()).toBe(v2.commit);
+ expect(b.operation()).toBeUndefined();
+});
+
+journey('a conflicting official release is resolved once; the other computer takes the result', async (w) => {
+ const a = await computer(w, 'a');
+ const b = await computer(w, 'b');
+ await a.change('feature.txt', set(2, 'mine'));
+ await a.save();
+ await b.save();
+ const v2 = await w.release('v2', 'feature.txt', set(2, 'official'));
+ a.target(v2);
+ b.target(v2);
+ expect((await a.sync()).waiting).toMatchObject({ kind: 'official' });
+ await a.resolve('feature.txt', set(2, 'official and mine'));
+ expect(a.reminders).toHaveLength(1);
+ await a.turnEnds();
+ expect(a.state().waiting).toMatchObject({ reason: 'missing', missing: 1 });
+ await a.accept();
+ expect(a.state()).toEqual({ done: { at: 1, ref: 'v2' } });
+ expect(await w.forkTip()).toBe(await a.tip());
+ // No second conflict on the other computer: it uses the resolved version.
+ expect(await b.sync()).toEqual({ done: { at: 1, ref: 'v2' } });
+ expect(b.operation()).toBeUndefined();
+ expect(await b.read('feature.txt')).toBe(text(set(2, 'official and mine')));
+});
+
+journey('a change made while the other computer updated is combined onto the newer version', async (w) => {
+ const a = await computer(w, 'a');
+ const b = await computer(w, 'b');
+ await a.change('a.txt', ['a']);
+ await a.save();
+ await b.save();
+ const v2 = await w.release('v2', 'official.txt', ['new']);
+ a.target(v2);
+ b.target(v2);
+ // A moves to v2 and shares it; B meanwhile adds a change on v1.
+ expect(await a.sync()).toEqual({ done: { at: 1, ref: 'v2' } });
+ await b.change('b.txt', ['b']);
+ expect(await b.sync()).toEqual({ done: { at: 1, ref: 'v2' } });
+ expect(await b.base()).toBe(v2.commit);
+ for (const file of ['a.txt', 'b.txt', 'official.txt']) expect(await b.read(file)).toBeTruthy();
+ expect(await w.forkTip()).toBe(await b.tip());
+ await a.sync();
+ expect(await a.tip()).toBe(await b.tip());
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/syncTarget.test.ts b/apps/desktop/src/main/cindy-make/__tests__/syncTarget.test.ts
new file mode 100644
index 0000000000..23a15d19ca
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/__tests__/syncTarget.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it, vi } from 'vitest';
+import { notBehindBase, pickSyncTarget, type SyncTargetDeps } from '../syncTarget';
+
+const LATEST = 'a'.repeat(40);
+const INSTALLED = 'b'.repeat(40);
+const latest = { ref: 'v1.3.0', commit: LATEST, channel: 'release' as const };
+
+function deps(overrides: Partial<SyncTargetDeps> = {}): SyncTargetDeps {
+ return {
+ latest,
+ original: { version: '1.2.0', commit: INSTALLED },
+ tagCommit: vi.fn(async () => INSTALLED),
+ fetch: vi.fn(async () => {}),
+ sameMigrations: vi.fn(async () => true),
+ isAncestor: vi.fn(async () => true),
+ ...overrides,
+ };
+}
+
+describe('task preparation and builds', () => {
+ it('never move the personal version to an older official version than its base', async () => {
+ const BASE = 'c'.repeat(40);
+ const target = { ref: 'v1.2.0', commit: INSTALLED };
+ await expect(notBehindBase(target, BASE, async () => true)).resolves.toEqual({
+ ref: 'v1.2.0',
+ commit: BASE,
+ });
+ await expect(notBehindBase(target, BASE, async () => false)).resolves.toEqual(target);
+ await expect(notBehindBase(target, undefined, async () => true)).resolves.toEqual(target);
+ });
+});
+
+describe('official version Sync moves to', () => {
+ it('follows the latest release while its database migrations match the installed Cindy', async () => {
+ await expect(pickSyncTarget(deps())).resolves.toEqual({ ref: 'v1.3.0', commit: LATEST });
+ });
+
+ it('stays on the installed version when the latest release changes the migrations', async () => {
+ const input = deps({ sameMigrations: vi.fn(async () => false) });
+ await expect(pickSyncTarget(input)).resolves.toEqual({
+ ref: 'v1.2.0',
+ commit: INSTALLED,
+ held: { ref: 'v1.3.0', commit: LATEST },
+ });
+ expect(input.fetch).toHaveBeenCalledWith([LATEST, INSTALLED]);
+ });
+
+ it('finds the installed version by its tag when the build commit is unknown or dirty', async () => {
+ const input = deps({
+ original: { version: '1.2.0', commit: INSTALLED, dirty: true },
+ sameMigrations: vi.fn(async () => false),
+ });
+ await expect(pickSyncTarget(input)).resolves.toMatchObject({ commit: INSTALLED });
+ expect(input.tagCommit).toHaveBeenCalledWith('v1.2.0');
+ });
+
+ it.each([
+ ['a development build', { latest: { ...latest, ref: 'main', channel: 'dev' as const } }],
+ ['an unknown original', { original: undefined }],
+ ['an original newer than the release', { isAncestor: vi.fn(async () => false) }],
+ ['the installed release itself', { original: { version: '1.3.0', commit: LATEST } }],
+ ])(
+ 'follows the latest version for %s, fetched before it is compared',
+ async (_case, overrides) => {
+ const input = deps({ sameMigrations: vi.fn(async () => false), ...overrides });
+ const target = await pickSyncTarget(input);
+ expect(target.held).toBeUndefined();
+ expect(target.commit).toBe(input.latest.commit);
+ expect(vi.mocked(input.fetch).mock.calls[0][0]).toContain(input.latest.commit);
+ },
+ );
+
+ it('stops when the known original cannot be resolved instead of following the latest release', async () => {
+ for (const original of [
+ // The build commit is missing and the tag does not exist.
+ { version: '1.2.0' },
+ // The build commit is dirty and the tag does not exist.
+ { version: '1.2.0', commit: INSTALLED, dirty: true },
+ ]) {
+ const input = deps({ original, tagCommit: vi.fn(async () => undefined) });
+ await expect(pickSyncTarget(input)).rejects.toMatchObject({ code: 'unavailable' });
+ // Without a resolvable installed commit there is nothing to compare against.
+ expect(input.sameMigrations).not.toHaveBeenCalled();
+ }
+ });
+
+ it('moves nothing when the installed release cannot be compared', async () => {
+ const input = deps({
+ fetch: vi.fn(async () => {
+ throw new Error('offline');
+ }),
+ });
+ await expect(pickSyncTarget(input)).rejects.toThrow('offline');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-make/__tests__/taskRuntime.test.ts b/apps/desktop/src/main/cindy-make/__tests__/taskRuntime.test.ts
index 548bc0995a..ada8c2bd52 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/taskRuntime.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/taskRuntime.test.ts
@@ -5,6 +5,7 @@ import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
const harness = vi.hoisted(() => ({
+ retainedOperation: false,
select: vi.fn(),
readBoundary: vi.fn(),
insert: vi.fn(),
@@ -48,6 +49,7 @@ vi.mock('../taskWorkspace.js', () => ({
}));
vi.mock('../upstreamMergeRuntime.js', () => ({
syncSourceBeforeCindyMakeTask: harness.syncSource,
+ hasRetainedSourceOperation: () => harness.retainedOperation,
}));
vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => client }));
vi.mock('../../localDb/ipc/messages.js', () => ({
@@ -61,7 +63,7 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({
captureDataOwnerBroadcastScope: () => ({}),
isDataOwnerBroadcastScopeCurrent: () => harness.current,
}));
-vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn(), info: vi.fn() }) }));
vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
vi.mock('../../maker-ipc/sessionRuntimeControl.js', () => ({
getSessionRuntimeControlSnapshot: () => ({ effectiveOverride: harness.effective }),
@@ -199,6 +201,21 @@ describe('Cindy Make task runtime', () => {
expect(harness.send).toHaveBeenCalledOnce();
});
+ it('starts from the current personal version while a Sync conflict waits in its task', async () => {
+ const start = input();
+ initialReads();
+ harness.retainedOperation = true;
+ try {
+ await startCindyMakeTask(start, 1);
+ await cindyMakeManager.waitForTask(start.runId);
+ } finally {
+ harness.retainedOperation = false;
+ }
+ expect(harness.syncSource).not.toHaveBeenCalled();
+ expect(harness.workspace).toHaveBeenCalledOnce();
+ expect(harness.send).toHaveBeenCalledOnce();
+ });
+
it('publishes a distinct personal source update phase while the task waits', async () => {
const start = input();
initialReads();
diff --git a/apps/desktop/src/main/cindy-make/__tests__/taskWorkspace.test.ts b/apps/desktop/src/main/cindy-make/__tests__/taskWorkspace.test.ts
index 07a7337397..5d1d4770f6 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/taskWorkspace.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/taskWorkspace.test.ts
@@ -1,6 +1,8 @@
-import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { create as tarCreate, Header, list as tarList } from 'tar';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
@@ -66,6 +68,731 @@ describe('prepareCindyMakeWorkspace', () => {
expect(phases).toEqual(['checking', 'creating', 'installing']);
});
+ /** Windows without Developer Mode cannot create symlinks; Git stores plain files there. */
+ const linkIfPossible = async (target: string, link: string): Promise<boolean> => {
+ try {
+ await symlink(target, link, 'dir');
+ return true;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'EPERM' || code === 'EACCES' || code === 'UNKNOWN') return false;
+ throw error;
+ }
+ };
+
+ const withManifest = async (runId: string): Promise<string> => {
+ const worktreePath = path.join(userData, 'cindy-make', 'worktrees', runId);
+ await mkdir(worktreePath, { recursive: true });
+ await writeFile(path.join(worktreePath, 'package.json'), '{"name":"app","version":"1.0.0"}');
+ return worktreePath;
+ };
+
+ /** Raw POSIX archive names retain aliases that tar's packer may normalize. */
+ const writeManifestArchive = async (
+ file: string,
+ entries: { name: string; dependencies: Record<string, string> }[],
+ ): Promise<void> => {
+ const blocks: Buffer[] = [];
+ for (const entry of entries) {
+ const body = Buffer.from(
+ JSON.stringify({ name: 'local', version: '1.0.0', dependencies: entry.dependencies }),
+ );
+ const header = new Header({ path: entry.name, type: 'File', mode: 0o644, size: body.length });
+ header.encode();
+ blocks.push(header.block!, body, Buffer.alloc((512 - (body.length % 512)) % 512));
+ }
+ await writeFile(file, Buffer.concat([...blocks, Buffer.alloc(1024)]));
+ };
+
+ const installUnverified = (
+ runId: string,
+ worktreePath: string,
+ deps: Parameters<typeof installCindyMakeWorktree>[3],
+ ) =>
+ installCindyMakeWorktree(
+ userData,
+ { path: worktreePath, branch: `cindy-make/${runId}`, baseCommit: 'b'.repeat(40) },
+ new AbortController().signal,
+ deps,
+ undefined,
+ undefined,
+ { ignoreScripts: true },
+ );
+
+ it('runs no lifecycle scripts and no pnpm hooks for unverified synced content', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-9');
+ await writeFile(
+ path.join(worktreePath, '.npmrc'),
+ 'node-linker=hoisted\nfrozen-lockfile=true\nengine-strict=true\n',
+ );
+ await writeFile(
+ path.join(worktreePath, 'pnpm-workspace.yaml'),
+ 'packages:\n - "apps/*"\n - "packages/*"\n',
+ );
+ await installUnverified('run-9', worktreePath, {
+ processEnvironment: { PATH: '', npm_config_registry: 'http://attacker.invalid' },
+ pnpm,
+ });
+ expect(pnpm).toHaveBeenCalledWith(
+ // No `npm_config_*` setting of the content's own can turn the guards back on;
+ // pnpm's write roots stay inside the worktree whatever `.npmrc` says; and the
+ // user's npm credentials are never loaded for this install.
+ {
+ PATH: '',
+ npm_config_userconfig: os.devNull,
+ npm_config_globalconfig: os.devNull,
+ COREPACK_ENV_FILE: '0',
+ COREPACK_ENABLE_PROJECT_SPEC: '0',
+ COREPACK_ENABLE_UNSAFE_CUSTOM_URLS: '0',
+ },
+ [
+ 'install',
+ '--frozen-lockfile',
+ '--prefer-offline',
+ '--prod=false',
+ '--ignore-scripts',
+ '--ignore-pnpmfile',
+ '--config.modules-dir=node_modules',
+ '--config.virtual-store-dir=node_modules/.pnpm',
+ '--config.store-dir=node_modules/.cindy-make-store',
+ '--config.strict-ssl=true',
+ ],
+ worktreePath,
+ expect.anything(),
+ );
+ });
+
+ it('keeps inherited secrets out of an unverified install environment', async () => {
+ let seen: NodeJS.ProcessEnv | undefined;
+ const pnpm = vi.fn(async (env: NodeJS.ProcessEnv) => {
+ seen = env;
+ });
+ const worktreePath = await withManifest('run-12');
+ await installUnverified('run-12', worktreePath, {
+ processEnvironment: {
+ PATH: '/tools',
+ SystemRoot: 'C:\\Windows',
+ HOME: '/home/me',
+ npm_config_python: '/tools/python',
+ npm_config_manage_package_manager_versions: 'false',
+ // How Cindy was launched must not reach a content `.npmrc`: its `${VAR}`
+ // expansion would send these to a registry the content chooses.
+ NPM_TOKEN: 'gho_secret-token',
+ GITHUB_TOKEN: 'ghp_secret-token',
+ AWS_SECRET_ACCESS_KEY: 'aws_secret-key',
+ HTTP_PROXY: 'http://user:[email protected]',
+ // Even under an allowlisted prefix, a credential stays out; the harmless
+ // Corepack setting next to it is forwarded.
+ COREPACK_NPM_TOKEN: 'corepack_secret-token',
+ COREPACK_NPM_PASSWORD: 'corepack_secret-password',
+ COREPACK_ENABLE: '0',
+ // The content must not configure Corepack itself: its project env and
+ // `packageManager` spec would run before pnpm's guards. Hostile values
+ // from the parent environment lose to the pins.
+ COREPACK_ENV_FILE: '/attacker/.corepack.env',
+ corepack_enable_project_spec: '1',
+ COREPACK_ENABLE_UNSAFE_CUSTOM_URLS: '1',
+ // Product secrets under real app prefixes are not generalized in either:
+ // `XDT_ELEVENLABS_API_KEY` is a working credential of the app's own.
+ XDT_ELEVENLABS_API_KEY: 'eleven_secret-key',
+ CINDY_CODEX_API_KEY: 'codex_secret-key',
+ },
+ pnpm,
+ });
+ expect(seen).toEqual({
+ PATH: '/tools',
+ SystemRoot: 'C:\\Windows',
+ HOME: '/home/me',
+ npm_config_python: '/tools/python',
+ npm_config_manage_package_manager_versions: 'false',
+ COREPACK_ENABLE: '0',
+ npm_config_userconfig: os.devNull,
+ npm_config_globalconfig: os.devNull,
+ COREPACK_ENV_FILE: '0',
+ COREPACK_ENABLE_PROJECT_SPEC: '0',
+ COREPACK_ENABLE_UNSAFE_CUSTOM_URLS: '0',
+ });
+ // No differently-cased twin of a pinned key survives (Windows env is
+ // case-insensitive and would keep whichever it met first).
+ expect(
+ Object.keys(seen!)
+ .filter((key) => /^corepack_/i.test(key))
+ .sort(),
+ ).toEqual([
+ 'COREPACK_ENABLE',
+ 'COREPACK_ENABLE_PROJECT_SPEC',
+ 'COREPACK_ENABLE_UNSAFE_CUSTOM_URLS',
+ 'COREPACK_ENV_FILE',
+ ]);
+ });
+
+ it('refuses unverified content whose config file is a symlink', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-13');
+ await writeFile(path.join(userData, 'evil-workspace.yaml'), 'configDependencies: {"x": "1"}\n');
+ // The link is read by pnpm but skipped by a scan that only checks plain files.
+ if (
+ !(await linkIfPossible(
+ path.join(userData, 'evil-workspace.yaml'),
+ path.join(worktreePath, 'pnpm-workspace.yaml'),
+ ))
+ )
+ return;
+ await expect(
+ installUnverified('run-13', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses unverified content with a dependency that escapes the worktree', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-14');
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ version: '1.0.0',
+ dependencies: { 'private-data': 'link:../private', innocuous: '1.0.0' },
+ }),
+ );
+ // A frozen lockfile can name a path dependency; pnpm would symlink the
+ // outside directory into the worktree at install time.
+ await expect(
+ installUnverified('run-14', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses unverified content whose pnpm overrides escape the worktree', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-18');
+ // `pnpm.overrides` values become installed dependency specs: a frozen
+ // lockfile honors them verbatim and links the outside directory in.
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ version: '1.0.0',
+ pnpm: { overrides: { 'private-data': 'link:../private' } },
+ }),
+ );
+ await expect(
+ installUnverified('run-18', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ // The same settings live in `pnpm-workspace.yaml` and nested override
+ // selectors; a patch path outside the worktree is refused just the same.
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ '{"name":"app","version":"1.0.0"}',
+ );
+ await writeFile(
+ path.join(worktreePath, 'pnpm-workspace.yaml'),
+ 'packages:\n - "apps/*"\noverrides:\n foo:\n ".": "file:../../private"\n',
+ );
+ await expect(
+ installUnverified('run-18', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ await writeFile(path.join(worktreePath, 'pnpm-workspace.yaml'), 'packages:\n - "apps/*"\n');
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ version: '1.0.0',
+ pnpm: { patchedDependencies: { '[email protected]': '../outside.patch' } },
+ }),
+ );
+ await expect(
+ installUnverified('run-18', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses unverified content with a traversal dependency name', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-19');
+ // pnpm joins each installed name under `node_modules`: a traversal name
+ // reaches outside the worktree whatever the write roots are, letting the
+ // install replace an occupied outside directory with a link to the payload.
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ version: '1.0.0',
+ dependencies: { '../../../../../autostart': 'link:./payload' },
+ }),
+ );
+ await expect(
+ installUnverified('run-19', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ // Override keys and package extension names travel the same join.
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ version: '1.0.0',
+ pnpm: { packageExtensions: { '../escape@1': { dependencies: { safe: '1.0.0' } } } },
+ }),
+ );
+ await expect(
+ installUnverified('run-19', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses when an installed link leaves the worktree', async () => {
+ const worktreePath = await withManifest('run-20');
+ // The pre-install scan cannot see into the write roots the install fills:
+ // whatever it linked is checked again before the content is handed on.
+ const pnpm = vi.fn(async () => {
+ await mkdir(path.join(worktreePath, 'node_modules'), { recursive: true });
+ if (!(await linkIfPossible(os.tmpdir(), path.join(worktreePath, 'node_modules', 'private-data'))))
+ throw new Error('symlink unavailable');
+ });
+ await expect(
+ installUnverified('run-20', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).toHaveBeenCalledOnce();
+ });
+
+ it('refuses unverified content whose lockfile dependency names traverse out', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-22');
+ // The frozen lockfile resolves the whole transitive graph pnpm installs:
+ // every dependency name in it is joined under the write roots, whatever
+ // manifest check saw the package metadata it came from.
+ await writeFile(
+ path.join(worktreePath, 'pnpm-lock.yaml'),
+ [
+ "lockfileVersion: '9.0'",
+ 'importers:',
+ ' .:',
+ ' dependencies:',
+ ' evil:',
+ ' specifier: file:./evil.tgz',
+ ' version: file:evil.tgz',
+ 'snapshots:',
+ " 'file:evil.tgz':",
+ ' dependencies:',
+ " '../../../../../../autostart': 1.0.0",
+ '',
+ ].join('\n'),
+ );
+ await expect(
+ installUnverified('run-22', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['root importer link', '.', 'link:../private'],
+ ['nested importer link', 'apps/client', 'link:../../../private'],
+ ['nested importer file version', 'apps/client', 'file:../private.tgz'],
+ ['package snapshot link', 'snapshots', 'link:../private'],
+ ['legacy package link', 'packages', 'link:../private'],
+ ])('refuses a lockfile path outside its actual resolution directory: %s', async (_name, section, version) => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('lockfile-context');
+ const dependency = { local: { specifier: 'link:./payload', version } };
+ const graph = section === 'snapshots' || section === 'packages'
+ ? { [section]: { '[email protected]': { dependencies: { local: version } } } }
+ : { importers: { [section]: { dependencies: dependency }, 'apps/other/deep': {} } };
+ await writeFile(
+ path.join(worktreePath, 'pnpm-lock.yaml'),
+ JSON.stringify({ lockfileVersion: '9.0', ...graph }),
+ );
+ await expect(
+ installUnverified('lockfile-context', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('keeps an importer-relative workspace link inside the worktree', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('lockfile-workspace');
+ await writeFile(
+ path.join(worktreePath, 'pnpm-lock.yaml'),
+ JSON.stringify({
+ lockfileVersion: '9.0',
+ importers: {
+ 'apps/client': {
+ dependencies: { local: { specifier: 'workspace:*', version: 'link:../../packages/local' } },
+ },
+ },
+ }),
+ );
+ await installUnverified('lockfile-workspace', worktreePath, { processEnvironment: {}, pnpm });
+ expect(pnpm).toHaveBeenCalledOnce();
+ });
+
+ it('checks file versions from the lockfile root rather than a nested importer', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('lockfile-file-version');
+ await writeManifestArchive(path.join(worktreePath, 'local.tar'), [{
+ name: 'package/package.json', dependencies: { '../../../../../autostart': '1.0.0' },
+ }]);
+ await writeFile(
+ path.join(worktreePath, 'pnpm-lock.yaml'),
+ JSON.stringify({
+ lockfileVersion: '9.0',
+ importers: {
+ 'apps/client': {
+ dependencies: { local: { specifier: 'file:../../local.tar', version: 'file:local.tar' } },
+ },
+ },
+ }),
+ );
+ await expect(
+ installUnverified('lockfile-file-version', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { directory: '../private', type: 'directory' },
+ { tarball: 'file:../private.tgz' },
+ ])('refuses a lockfile resolution outside the lockfile directory: %j', async (resolution) => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('lockfile-resolution');
+ await writeFile(path.join(worktreePath, 'pnpm-lock.yaml'), JSON.stringify({
+ lockfileVersion: '9.0', packages: { '[email protected]': { resolution } },
+ }));
+ await expect(installUnverified('lockfile-resolution', worktreePath, { processEnvironment: {}, pnpm }))
+ .rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses unverified content whose file dependency archive names traverse out', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-23');
+ // pnpm installs a `file:` dependency as a package out of the archive: the
+ // names inside its manifest are joined under the write roots like any other,
+ // and no walk of the tree sees into the archive.
+ const stage = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-archive-'));
+ try {
+ await mkdir(path.join(stage, 'package'), { recursive: true });
+ await writeFile(
+ path.join(stage, 'package', 'package.json'),
+ JSON.stringify({
+ name: 'evil',
+ version: '1.0.0',
+ dependencies: { '../../../../../autostart': 'link:./payload' },
+ }),
+ );
+ await tarCreate(
+ { gzip: true, file: path.join(worktreePath, 'evil.tgz'), cwd: stage },
+ ['package'],
+ );
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ version: '1.0.0',
+ dependencies: { evil: 'file:./evil.tgz' },
+ }),
+ );
+ await expect(
+ installUnverified('run-23', worktreePath, { processEnvironment: {}, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ } finally {
+ await rm(stage, { recursive: true, force: true });
+ }
+ });
+
+ it('refuses duplicate file dependency manifests before pnpm runs', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('duplicate-manifest');
+ const stage = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-duplicate-archive-'));
+ try {
+ await mkdir(path.join(stage, 'package'), { recursive: true });
+ await writeFile(
+ path.join(stage, 'package', 'package.json'),
+ JSON.stringify({ name: 'duplicate', version: '1.0.0', dependencies: { innocuous: '1.0.0' } }),
+ );
+ const archive = path.join(worktreePath, 'duplicate.tar');
+ const first = path.join(stage, 'first.tar');
+ await tarCreate({ file: first, cwd: stage }, ['package']);
+ const firstBytes = await readFile(first);
+ await writeFile(
+ path.join(stage, 'package', 'package.json'),
+ JSON.stringify({ name: 'duplicate', version: '1.0.0', dependencies: { '../../../../../autostart': '1.0.0' } }),
+ );
+ const second = path.join(stage, 'second.tar');
+ await tarCreate({ file: second, cwd: stage }, ['package']);
+ const secondBytes = await readFile(second);
+ // A tar archive ends with two zero blocks. Remove only those blocks from
+ // the first archive so its package data padding stays aligned, then put
+ // the second header immediately after it. Extraction would leave the
+ // later manifest on disk, so the validator must reject the archive.
+ expect(firstBytes.length % 512).toBe(0);
+ expect(firstBytes.subarray(-1024).every((byte) => byte === 0)).toBe(true);
+ await writeFile(archive, Buffer.concat([firstBytes.subarray(0, -1024), secondBytes]));
+ } finally {
+ await rm(stage, { recursive: true, force: true });
+ }
+ await writeFile(path.join(worktreePath, 'package.json'), JSON.stringify({
+ name: 'app', version: '1.0.0', dependencies: { duplicate: 'file:./duplicate.tar' },
+ }));
+ await expect(installUnverified('duplicate-manifest', worktreePath, { processEnvironment: {}, pnpm }))
+ .rejects.toMatchObject({ code: 'gitFailed', message: 'archive has duplicate manifests' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ 'package/./package.json',
+ 'package//package.json',
+ 'package/child/../package.json',
+ 'alternate/package.json',
+ './package/package.json',
+ '/package/package.json',
+ ])('checks the manifest extracted from the POSIX archive alias %s', async (name) => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('archive-alias');
+ const archive = path.join(worktreePath, 'local.tar');
+ await writeManifestArchive(archive, [{
+ name, dependencies: { '../../../../../autostart': '1.0.0' },
+ }]);
+ const names: string[] = [];
+ await tarList({ file: archive, onentry: (entry) => names.push(entry.path) });
+ expect(names).toEqual([name]);
+ await writeFile(path.join(worktreePath, 'package.json'), JSON.stringify({
+ name: 'app', version: '1.0.0', dependencies: { local: 'file:./local.tar' },
+ }));
+ await expect(installUnverified('archive-alias', worktreePath, { processEnvironment: {}, pnpm }))
+ .rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])('refuses a manifest overwritten through an archive alias: alias first %s', async (aliasFirst) => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('archive-alias-duplicate');
+ const entries: Parameters<typeof writeManifestArchive>[1] = [
+ { name: 'package/package.json', dependencies: { innocuous: '1.0.0' } },
+ { name: 'package/./package.json', dependencies: { '../../../../../autostart': '1.0.0' } },
+ ];
+ await writeManifestArchive(path.join(worktreePath, 'local.tar'), aliasFirst ? entries.reverse() : entries);
+ await writeFile(path.join(worktreePath, 'package.json'), JSON.stringify({
+ name: 'app', version: '1.0.0', dependencies: { local: 'file:./local.tar' },
+ }));
+ await expect(installUnverified('archive-alias-duplicate', worktreePath, { processEnvironment: {}, pnpm }))
+ .rejects.toMatchObject({ code: 'gitFailed', message: 'archive has duplicate manifests' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('allows a benign canonical archive manifest alias', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('archive-alias-benign');
+ await writeManifestArchive(path.join(worktreePath, 'local.tar'), [{
+ name: 'package/./package.json', dependencies: { innocuous: '1.0.0' },
+ }]);
+ await writeFile(path.join(worktreePath, 'package.json'), JSON.stringify({
+ name: 'app', version: '1.0.0', dependencies: { local: 'file:./local.tar' },
+ }));
+ await installUnverified('archive-alias-benign', worktreePath, { processEnvironment: {}, pnpm });
+ expect(pnpm).toHaveBeenCalledOnce();
+ });
+
+ it.each(['package/PACKAGE.JSON', 'package/package.json.'])(
+ 'matches archive manifest aliases using host filesystem semantics: %s', async (alias) => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('archive-host-alias');
+ await writeManifestArchive(path.join(worktreePath, 'local.tar'), [
+ { name: 'package/package.json', dependencies: { innocuous: '1.0.0' } },
+ { name: alias, dependencies: { innocuous: '1.0.0' } },
+ ]);
+ await writeFile(path.join(worktreePath, 'package.json'), JSON.stringify({
+ name: 'app', version: '1.0.0', dependencies: { local: 'file:./local.tar' },
+ }));
+ const install = installUnverified('archive-host-alias', worktreePath, { processEnvironment: {}, pnpm });
+ if (process.platform === 'win32') {
+ await expect(install).rejects.toMatchObject({ code: 'gitFailed', message: 'archive has duplicate manifests' });
+ expect(pnpm).not.toHaveBeenCalled();
+ } else {
+ await install;
+ expect(pnpm).toHaveBeenCalledOnce();
+ }
+ },
+ );
+
+ it('installs unverified content whose lockfile and archive metadata are benign', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-25');
+ // The monorepo's own frozen lockfile keeps installing: every real importer
+ // key, workspace link, override pattern and patched dependency must pass.
+ const lockfile = await readFile(
+ fileURLToPath(new URL('../../../../../../pnpm-lock.yaml', import.meta.url)),
+ 'utf8',
+ ).catch(() => undefined);
+ if (lockfile) await writeFile(path.join(worktreePath, 'pnpm-lock.yaml'), lockfile);
+ const stage = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-archive-'));
+ try {
+ await mkdir(path.join(stage, 'package'), { recursive: true });
+ await writeFile(
+ path.join(stage, 'package', 'package.json'),
+ JSON.stringify({
+ name: 'good',
+ version: '1.0.0',
+ dependencies: { innocuous: '1.0.0' },
+ }),
+ );
+ await tarCreate(
+ { gzip: true, file: path.join(worktreePath, 'good.tgz'), cwd: stage },
+ ['package'],
+ );
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ version: '1.0.0',
+ dependencies: { good: 'file:./good.tgz' },
+ }),
+ );
+ await installUnverified('run-25', worktreePath, { processEnvironment: {}, pnpm });
+ expect(pnpm).toHaveBeenCalledOnce();
+ } finally {
+ await rm(stage, { recursive: true, force: true });
+ }
+ });
+
+ it('installs unverified content whose overrides and links stay in the worktree', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-21');
+ await mkdir(path.join(worktreePath, 'local'), { recursive: true });
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ JSON.stringify({
+ name: 'app',
+ version: '1.0.0',
+ dependencies: { '@scope/innocuous': '1.0.0', local: 'link:./local' },
+ pnpm: {
+ overrides: { 'left-pad': '1.3.0', nested: { '.': 'npm:@scope/replacement@1' } },
+ catalog: { fast: 'file:./local' },
+ },
+ }),
+ );
+ await installUnverified('run-21', worktreePath, { processEnvironment: {}, pnpm });
+ expect(pnpm).toHaveBeenCalledOnce();
+ });
+
+ it('refuses to install unverified content through a node_modules link', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-10');
+ // The link is the write root: pnpm would create `<link>/<dependency name>`
+ // wherever it points.
+ if (!(await linkIfPossible(os.tmpdir(), path.join(worktreePath, 'node_modules')))) return;
+ await expect(
+ installUnverified('run-10', worktreePath, { processEnvironment: { PATH: '' }, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses unverified content whose links leave the worktree under any name', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-11');
+ if (!(await linkIfPossible(os.tmpdir(), path.join(worktreePath, '.m')))) return;
+ await expect(
+ installUnverified('run-11', worktreePath, { processEnvironment: { PATH: '' }, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses unverified content that redirects the pnpm store from .npmrc', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-12');
+ await writeFile(path.join(worktreePath, '.npmrc'), 'store-dir=/attacker/store\n');
+ await expect(
+ installUnverified('run-12', worktreePath, { processEnvironment: { PATH: '' }, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses unverified content that moves pnpm write roots from workspace settings', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-13');
+ await writeFile(
+ path.join(worktreePath, 'pnpm-workspace.yaml'),
+ 'packages:\n - "apps/*"\nvirtualStoreDir: .elsewhere\n',
+ );
+ await expect(
+ installUnverified('run-13', worktreePath, { processEnvironment: { PATH: '' }, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses unverified content whose configDependencies name escapes the worktree', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-17');
+ // pnpm joins each config dependency's package name under
+ // `node_modules/.pnpm-config`: a path-like name writes outside the worktree,
+ // wherever the write roots point, so unverified content configures none at all.
+ await writeFile(
+ path.join(worktreePath, 'pnpm-workspace.yaml'),
+ 'packages:\n - "apps/*"\nconfigDependencies:\n "../../../../../../autostart": "1.0.0"\n',
+ );
+ await expect(
+ installUnverified('run-17', worktreePath, { processEnvironment: { PATH: '' }, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ await writeFile(path.join(worktreePath, 'pnpm-workspace.yaml'), 'packages:\n - "apps/*"\n');
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ '{"name":"app","version":"1.0.0","pnpm":{"configDependencies":{"../../../../autostart":"1.0.0"}}}',
+ );
+ await expect(
+ installUnverified('run-17', worktreePath, { processEnvironment: { PATH: '' }, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses unverified workspace globs and manifest settings that leave the worktree', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-14');
+ await writeFile(
+ path.join(worktreePath, 'pnpm-workspace.yaml'),
+ 'packages:\n - "../*"\n',
+ );
+ await expect(
+ installUnverified('run-14', worktreePath, { processEnvironment: { PATH: '' }, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ await writeFile(path.join(worktreePath, 'pnpm-workspace.yaml'), 'packages:\n - "apps/*"\n');
+ await writeFile(
+ path.join(worktreePath, 'package.json'),
+ '{"name":"app","version":"1.0.0","pnpm":{"storeDir":"/attacker/store"}}',
+ );
+ await expect(
+ installUnverified('run-14', worktreePath, { processEnvironment: { PATH: '' }, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('refuses when an existing write root resolves outside the worktree', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-15');
+ await mkdir(path.join(worktreePath, 'node_modules'), { recursive: true });
+ if (!(await linkIfPossible(os.tmpdir(), path.join(worktreePath, 'node_modules', '.pnpm'))))
+ return;
+ await expect(
+ installUnverified('run-15', worktreePath, { processEnvironment: { PATH: '' }, pnpm }),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(pnpm).not.toHaveBeenCalled();
+ });
+
+ it('lets verified content configure the machine\'s own pnpm store', async () => {
+ const pnpm = vi.fn(async () => undefined);
+ const worktreePath = await withManifest('run-16');
+ await writeFile(
+ path.join(worktreePath, '.npmrc'),
+ `store-dir=${path.join(os.tmpdir(), 'own-store')}\n`,
+ );
+ await installCindyMakeWorktree(
+ userData,
+ { path: worktreePath, branch: 'cindy-make/run-16', baseCommit: 'b'.repeat(40) },
+ new AbortController().signal,
+ { processEnvironment: { PATH: '' }, pnpm },
+ );
+ expect(pnpm).toHaveBeenCalledOnce();
+ });
+
it('reuses an existing worktree on the task branch and refuses a foreign directory', async () => {
const worktreePath = path.join(userData, 'cindy-make', 'worktrees', 'run-2');
await mkdir(worktreePath, { recursive: true });
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts
index 6b4179dbce..df5d422161 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts
@@ -308,6 +308,47 @@ it('rebases locally committed personal changes onto the latest official main and
}
}, 30_000);
+it('records the new official baseline before moving the personal source so an interruption is clamped', async () => {
+ const h = await fixture(false);
+ try {
+ // The process dies right where the source would move: the baseline write
+ // has already happened and the tip has not.
+ const saved: CindyMakeMergeState[] = [];
+ const crashOnReset: typeof h.git = async (args, cwd, indexFile) => {
+ if (args[0] === 'reset')
+ throw Object.assign(new Error('simulated crash'), { code: 'gitFailed' });
+ return h.git(args, cwd, indexFile);
+ };
+ await expect(
+ prepareUpstreamMerge(h.userData, h.state, crashOnReset, async (state) => {
+ saved.push(state);
+ }),
+ ).rejects.toThrow('simulated crash');
+ // The new baseline is durably recorded first, while the personal tip is unchanged.
+ expect(await h.git(['rev-parse', PERSONAL_UPSTREAM_REF], h.source)).toBe(
+ h.state.upstreamCommit,
+ );
+ // Exactly the "old tip + new base" combination the base clamp detects: the
+ // recorded base is not the tip's ancestor, and clamping to the shared
+ // history recovers the base the tip really sits on.
+ await expect(
+ h.git(['merge-base', '--is-ancestor', h.state.upstreamCommit, 'cindy-personal'], h.source),
+ ).rejects.toMatchObject({ code: 'gitFailed' });
+ expect(
+ (await h.git(['merge-base', 'cindy-personal', PERSONAL_UPSTREAM_REF], h.source)).trim(),
+ ).toBe(h.baselineCommit);
+ // The retained operation completes the move the crash interrupted.
+ const result = await applyUpstreamMerge(h.userData, saved.at(-1)!, h.git);
+ expect(result.status).toBe('merged');
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(result.commit);
+ expect(await h.git(['rev-parse', PERSONAL_UPSTREAM_REF], h.source)).toBe(
+ h.state.upstreamCommit,
+ );
+ } finally {
+ await h.clean();
+ }
+}, 30_000);
+
it('preserves unfinished or session-owned candidates, new files and commits added after adoption', async () => {
const h = await fixture(false);
try {
@@ -558,17 +599,31 @@ it('isolates conflicts, preserves personal files, and applies a resolved merge i
expect(await h.git(['diff', '--name-only', '--diff-filter=U'], worktree)).toContain(
'feature.txt',
);
- await expect(applyUpstreamMerge(h.userData, result, h.git)).rejects.toMatchObject({
- code: 'dirty',
+ // A resolver turn that ended with conflicts left waits for the user's answer in its task.
+ await expect(applyUpstreamMerge(h.userData, result, h.git)).resolves.toMatchObject({
+ status: 'conflict',
+ needsInput: true,
});
+ expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe('local feature\n');
await writeFile(path.join(worktree, 'feature.txt'), 'local feature\nupstream fix\n');
await h.git(['add', '.'], worktree);
- const applied = await applyUpstreamMerge(h.userData, result, h.git);
+ const refused = await applyUpstreamMerge(h.userData, result, h.git).catch((error) => error);
+ expect(refused).toMatchObject({
+ code: 'checksFailed',
+ missing: { count: 1, commits: [result.baselineCommit] },
+ });
+ expect((await h.git(['rev-parse', 'HEAD'], h.source)).trim()).toBe(result.baselineCommit);
+ const confirmed = { ...result, missing: refused.missing };
+ const applied = await applyUpstreamMerge(h.userData, confirmed, h.git, () => true, {
+ acceptMissing: true,
+ });
expect(applied.status).toBe('merged');
expect(await readFile(path.join(h.source, 'feature.txt'), 'utf8')).toBe(
'local feature\nupstream fix\n',
);
- expect(await applyUpstreamMerge(h.userData, result, h.git)).toEqual(applied);
+ expect(
+ await applyUpstreamMerge(h.userData, confirmed, h.git, () => true, { acceptMissing: true }),
+ ).toEqual(applied);
expect(await h.git(['merge-base', 'main', 'cindy-personal'], h.source)).toBe(
h.state.upstreamCommit,
);
@@ -587,7 +642,13 @@ it('preserves personal work added during resolution and refuses to overwrite con
await h.git(['add', '.'], worktree);
await writeFile(path.join(h.source, 'new-personal.txt'), 'new feature\n');
- await expect(applyUpstreamMerge(h.userData, result, h.git)).rejects.toMatchObject({
+ const refused = await applyUpstreamMerge(h.userData, result, h.git).catch((error) => error);
+ expect(refused).toMatchObject({ code: 'checksFailed', missing: { count: 1 } });
+ await expect(
+ applyUpstreamMerge(h.userData, { ...result, missing: refused.missing }, h.git, () => true, {
+ acceptMissing: true,
+ }),
+ ).rejects.toMatchObject({
code: 'baselineChanged',
});
expect(await readFile(path.join(h.source, 'new-personal.txt'), 'utf8')).toBe('new feature\n');
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts
index 321e785bef..315429f864 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeController.test.ts
@@ -82,6 +82,177 @@ function harness(initial?: SavedUpstreamMerge, actualWorkspace = !!initial?.stat
},
};
}
+describe('combining with the personal version on GitHub', () => {
+ const remote = { commit: 'd'.repeat(40), base: 'e'.repeat(40) };
+
+ it('keeps a conflict for the explicit resolve decision, then resolves it in a task', async () => {
+ const h = harness();
+ h.deps.prepareCombine = vi.fn(async (state) => {
+ h.setWorkspace(true);
+ return { ...state, strategy: 'combine' as const, status: 'conflict' as const, hasWorkspace: true };
+ });
+ const result = await h.controller.combine(remote);
+ expect(h.deps.prepareCombine).toHaveBeenCalledWith(
+ expect.objectContaining({
+ status: 'merging',
+ ref: 'github',
+ upstreamCommit: remote.commit,
+ remote: { base: remote.base, commit: remote.commit },
+ }),
+ expect.any(Function),
+ expect.any(Function),
+ );
+ expect(result).toMatchObject({ status: 'conflict', remote: { base: remote.base } });
+ expect(result?.sessionId).toBeUndefined();
+ // Like a manual official update, no resolver is created without the user's decision.
+ expect(h.deps.session).not.toHaveBeenCalled();
+ // A retained candidate blocks other source operations until it is resolved or cancelled.
+ await expect(h.controller.combine(remote)).rejects.toMatchObject({ code: 'busy' });
+ await expect(h.controller.update()).resolves.toMatchObject({ status: 'conflict' });
+ const resolved = await h.controller.resolve(undefined, result!.id);
+ expect(resolved).toMatchObject({ status: 'resolving', sessionId: 'merge-session' });
+ expect(h.saved()?.state.remote).toEqual({ base: remote.base, commit: remote.commit });
+ });
+
+ it('opens the resolution task right away when Sync asked for it', async () => {
+ const h = harness();
+ h.deps.prepareCombine = vi.fn(async (state) => {
+ h.setWorkspace(true);
+ return { ...state, strategy: 'combine' as const, status: 'conflict' as const, hasWorkspace: true };
+ });
+ await expect(h.controller.combine(remote, { agentKind: 'codex' }, true)).resolves.toMatchObject(
+ { status: 'resolving', sessionId: 'merge-session' },
+ );
+ expect(h.deps.session).toHaveBeenCalledWith(
+ expect.anything(),
+ { agentKind: 'codex' },
+ expect.any(Function),
+ expect.any(Function),
+ );
+ });
+
+ it('updates to a pinned official version and resolves its conflict when Sync asked for it', async () => {
+ const h = harness();
+ h.deps.prepare = vi.fn(async (state) => {
+ h.setWorkspace(true);
+ return { ...state, strategy: 'rebase' as const, status: 'conflict' as const, hasWorkspace: true };
+ });
+ const target = { ref: 'v1.2.3', commit: 'f'.repeat(40) };
+ await expect(
+ h.controller.update({ agentKind: 'codex' }, undefined, { target, autoResolve: true }),
+ ).resolves.toMatchObject({ status: 'resolving', ref: 'v1.2.3', upstreamCommit: target.commit });
+ expect(h.deps.latest).not.toHaveBeenCalled();
+ });
+
+ it('adopts a combine without conflicts and cleans up its candidate', async () => {
+ const h = harness();
+ h.deps.prepareCombine = vi.fn(async (state) => {
+ h.setWorkspace(true);
+ return {
+ ...state,
+ strategy: 'combine' as const,
+ status: 'merged' as const,
+ hasWorkspace: true,
+ commit: 'c'.repeat(40),
+ tree: 'f'.repeat(40),
+ };
+ });
+ await expect(h.controller.combine(remote)).resolves.toMatchObject({
+ status: 'merged',
+ hasWorkspace: false,
+ });
+ expect(h.deps.cleanup).toHaveBeenCalledOnce();
+ });
+
+ it('abandons a Sync conflict whose resolver is open, adopting nothing', async () => {
+ const h = harness();
+ h.deps.prepareCombine = vi.fn(async (state) => {
+ h.setWorkspace(true);
+ return { ...state, strategy: 'combine' as const, status: 'conflict' as const, hasWorkspace: true };
+ });
+ const started = await h.controller.combine(remote, { agentKind: 'codex' }, true);
+ expect(started).toMatchObject({ status: 'resolving', sessionId: 'merge-session', taskOwned: true });
+ // A cancel without a resolver decision is refused; Abandon stops the resolver first.
+ await expect(h.controller.cancel(started!.id)).rejects.toMatchObject({ code: 'busy' });
+ await expect(h.controller.abandon(started!.id)).resolves.toMatchObject({
+ status: 'cancelled',
+ hasWorkspace: false,
+ });
+ expect(h.deps.discard).toHaveBeenCalledOnce();
+ expect(h.deps.apply).not.toHaveBeenCalled();
+ });
+
+ it('refuses to abandon while a result is being checked, and never half-owns an operation', async () => {
+ const checking = harness();
+ checking.deps.prepareCombine = vi.fn(async (state) => {
+ checking.setWorkspace(true);
+ return { ...state, strategy: 'combine' as const, status: 'conflict' as const, hasWorkspace: true };
+ });
+ const started = await checking.controller.combine(remote, undefined, true);
+ let adopt!: (state: CindyMakeMergeState) => void;
+ checking.deps.apply = vi.fn(
+ () => new Promise<CindyMakeMergeState>((resolve) => (adopt = resolve)),
+ );
+ const finishing = checking.controller.finish('merge-session');
+ await vi.waitFor(() => expect(checking.deps.apply).toHaveBeenCalled());
+ await expect(checking.controller.abandon(started!.id)).rejects.toMatchObject({ code: 'busy' });
+ expect(checking.deps.discard).not.toHaveBeenCalled();
+ adopt({ ...started!, status: 'merged', commit: 'c'.repeat(40), tree: 'f'.repeat(40) });
+ await finishing;
+
+ // Created while signed out: no owner can stop its resolver; nothing is persisted.
+ const ownerless = harness({
+ state: { ...candidate, status: 'failed', error: 'cancelFailed', cancellationRequested: true },
+ });
+ const writes = vi.mocked(ownerless.deps.write).mock.calls.length;
+ await expect(ownerless.controller.abandon(candidate.id)).rejects.toMatchObject({
+ code: 'busy',
+ });
+ expect(vi.mocked(ownerless.deps.write).mock.calls.length).toBe(writes);
+ });
+
+ it('stores a finished combine like an official update so older clients can read it', async () => {
+ const h = harness();
+ h.deps.prepareCombine = vi.fn(async (state) => ({
+ ...state,
+ strategy: 'combine' as const,
+ status: 'merged' as const,
+ hasWorkspace: false,
+ commit: 'c'.repeat(40),
+ tree: 'f'.repeat(40),
+ }));
+ await h.controller.combine(remote);
+ expect(h.saved()?.state).toMatchObject({
+ status: 'merged',
+ strategy: 'rebase',
+ remote: { base: remote.base, commit: remote.commit },
+ });
+ });
+
+ it('restores a saved combine and rejects one with an invalid base', () => {
+ const saved = {
+ sessionOwner: 'alice',
+ state: { ...candidate, strategy: 'combine' as const, remote: { base: 'e'.repeat(40) } },
+ };
+ expect(parseSavedUpstreamMerge(JSON.stringify(saved), '/user-data').state.remote).toEqual({
+ base: 'e'.repeat(40),
+ });
+ expect(() =>
+ parseSavedUpstreamMerge(
+ JSON.stringify({ ...saved, state: { ...saved.state, remote: { base: '../x' } } }),
+ '/user-data',
+ ),
+ ).toThrow();
+ // A combine always names the GitHub side; without it the state is not trusted.
+ expect(() =>
+ parseSavedUpstreamMerge(
+ JSON.stringify({ ...saved, state: { ...saved.state, remote: undefined } }),
+ '/user-data',
+ ),
+ ).toThrow();
+ });
+});
+
describe('upstream merge lifecycle', () => {
it('automatically resolves a task-owned source conflict and waits for adoption and cleanup', async () => {
const h = harness();
@@ -1024,6 +1195,147 @@ describe('upstream merge lifecycle', () => {
await h.controller.finish('task');
expect(h.saved()?.state.status).toBe('merged');
});
+ it('asks the resolver once to put lost changes back, then leaves the decision to the user', async () => {
+ const h = harness({
+ state: { ...candidate, strategy: 'rebase', sessionId: 'task', status: 'resolving' },
+ sessionOwner: 'alice',
+ });
+ const missing = { count: 1, commits: ['f'.repeat(40)] };
+ h.deps.remind = vi.fn(async () => {});
+ h.deps.apply = vi.fn(async () => {
+ throw Object.assign(mergeError('checksFailed'), { missing });
+ });
+ h.controller.prepareTurn('task')();
+ await h.controller.finish('task');
+ expect(h.deps.remind).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ missing, reminded: true }),
+ expect.any(Function),
+ );
+ expect(h.saved()?.state).toMatchObject({ status: 'resolving', missing, reminded: true });
+
+ // The reminded turn still loses it: the user decides between using it and Abandon.
+ h.controller.prepareTurn('task')();
+ await h.controller.finish('task');
+ expect(h.deps.remind).toHaveBeenCalledOnce();
+ expect(h.saved()?.state).toMatchObject({ status: 'failed', error: 'checksFailed', missing });
+
+ h.deps.apply = vi.fn(async (state) => ({ ...state, status: 'merged' as const }));
+ await expect(h.controller.acceptMissing(candidate.id)).resolves.toMatchObject({
+ status: 'merged',
+ });
+ expect(h.deps.apply).toHaveBeenCalledWith(
+ expect.objectContaining({ id: candidate.id }),
+ expect.any(Function),
+ expect.any(Function),
+ { acceptMissing: true },
+ );
+ });
+ it('accepts a lost change only for its owner, its own operation and an idle resolver', async () => {
+ const failed: SavedUpstreamMerge = {
+ state: {
+ ...candidate,
+ strategy: 'rebase',
+ sessionId: 'task',
+ status: 'failed',
+ error: 'checksFailed',
+ missing: { count: 1, commits: [] },
+ },
+ sessionOwner: 'alice',
+ };
+ const other = harness(failed);
+ other.setOwner('bob');
+ await expect(other.controller.acceptMissing(candidate.id)).rejects.toMatchObject({
+ code: 'busy',
+ });
+ const running = harness(failed);
+ running.deps.running = () => true;
+ await expect(running.controller.acceptMissing(candidate.id)).rejects.toMatchObject({
+ code: 'busy',
+ });
+ const stale = harness(failed);
+ await expect(stale.controller.acceptMissing('other')).rejects.toMatchObject({ code: 'busy' });
+ const checked = harness({ ...failed, state: { ...failed.state, missing: undefined } });
+ await expect(checked.controller.acceptMissing(candidate.id)).rejects.toMatchObject({
+ code: 'busy',
+ });
+ expect(other.deps.apply).not.toHaveBeenCalled();
+ expect(running.deps.apply).not.toHaveBeenCalled();
+ });
+ it('Sync reopens a resolver whose task is gone, keeping the candidate’s work', async () => {
+ const h = harness({
+ state: {
+ ...candidate,
+ strategy: 'rebase',
+ sessionId: 'removed-task',
+ status: 'failed',
+ error: 'unavailable',
+ },
+ sessionOwner: 'alice',
+ });
+ h.deps.session = vi.fn(async (_state, _options, bind) => {
+ bind('new-task');
+ return 'new-task';
+ });
+ await expect(h.controller.resumeForSync({ agentKind: 'codex' })).resolves.toMatchObject({
+ status: 'resolving',
+ sessionId: 'new-task',
+ });
+ expect(h.deps.apply).not.toHaveBeenCalled();
+ // The same candidate: nothing was prepared again.
+ expect(h.deps.prepare).not.toHaveBeenCalled();
+ });
+ it('Sync finishes an Abandon that could not finish before anything else', async () => {
+ const h = harness({
+ state: {
+ ...candidate,
+ strategy: 'rebase',
+ taskOwned: true,
+ status: 'failed',
+ error: 'cancelFailed',
+ cancellationRequested: true,
+ },
+ sessionOwner: 'alice',
+ });
+ await expect(h.controller.resumeForSync()).resolves.toMatchObject({
+ status: 'cancelled',
+ hasWorkspace: false,
+ });
+ expect(h.deps.discard).toHaveBeenCalledOnce();
+ });
+ it('Sync’s update reports busy instead of another operation’s result', async () => {
+ const h = harness();
+ let release!: () => void;
+ h.deps.prepare = vi.fn(
+ (state) =>
+ new Promise<CindyMakeMergeState>((resolve) => {
+ release = () => resolve({ ...state, status: 'merged' });
+ }),
+ );
+ const first = h.controller.update(undefined, undefined, { autoResolve: true });
+ await vi.waitFor(() => expect(h.deps.prepare).toHaveBeenCalled());
+ const second = h.controller.update(undefined, undefined, { autoResolve: true });
+ release();
+ await expect(first).resolves.toMatchObject({ status: 'merged' });
+ await expect(second).rejects.toMatchObject({ code: 'busy' });
+ });
+ it('waits for the user’s answer when the resolver stops with conflicts left', async () => {
+ const h = harness({
+ state: { ...candidate, strategy: 'rebase', sessionId: 'task', status: 'resolving' },
+ sessionOwner: 'alice',
+ });
+ h.deps.apply = vi.fn(async (state) => ({
+ ...state,
+ status: 'conflict' as const,
+ needsInput: true,
+ }));
+ h.controller.prepareTurn('task')();
+ await h.controller.finish('task');
+ expect(h.saved()?.state).toMatchObject({ status: 'conflict', needsInput: true });
+ // The user's answer is the next turn.
+ h.controller.prepareTurn('task')();
+ expect(h.saved()?.state.status).toBe('resolving');
+ expect(h.saved()?.state.needsInput).toBeUndefined();
+ });
it('waits for a terminal session to become idle before applying the candidate', async () => {
const h = harness({
state: { ...candidate, sessionId: 'task', status: 'resolving' },
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeRuntime.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeRuntime.test.ts
index 36ade8b66e..f2a57d5d9b 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeRuntime.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeRuntime.test.ts
@@ -36,6 +36,7 @@ const h = vi.hoisted(() => ({
ref: 'main',
} as MakeSourceStatus,
fetch: vi.fn(),
+ recordRef: vi.fn(async () => {}),
}));
vi.mock('electron', () => ({
app: {
@@ -92,11 +93,20 @@ vi.mock('../sourceContent.js', async (importOriginal) => ({
snapshotContent: async () => h.tree,
}));
vi.mock('../versionStore.js', () => ({ hasPublishedPersonalVersionCommit: () => false }));
+// No installed original is known here: Sync follows the latest version as before.
+vi.mock('../versionStartup.js', () => ({
+ describeOriginalVersion: () => {
+ throw new Error('unknown original');
+ },
+}));
vi.mock('../toolchainEnvironment.js', () => ({
createMakeToolchainEnvironment: async () => ({}),
resolveMakeToolEnvironment: async () => ({}),
}));
-vi.mock('../sourcePreparation.js', () => ({ readCurrentCindySourceStatus: async () => h.source }));
+vi.mock('../sourcePreparation.js', () => ({
+ readCurrentCindySourceStatus: async () => h.source,
+ recordCindySourceRef: h.recordRef,
+}));
vi.mock('../sourceGit.js', () => ({
runSourceGit: async (_env: unknown, args: string[]) => h.git(args),
}));
@@ -270,6 +280,8 @@ beforeEach(() => {
}
if (args[0] === 'status') return h.dirty ? ' M preserve-user-edit.txt' : '';
if (args[0] === 'merge-base') return '';
+ // The sync target is fetched before it is compared or used.
+ if (args[0] === 'fetch') return '';
if (args[0] === 'update-ref') {
if (args[1] === '-d') h.refs.delete(args[2]);
else h.refs.set(args[1], args[2]);
@@ -301,6 +313,8 @@ it.each(['dev', 'beta', 'release'] as const)(
ref,
upstreamCommit: 'f'.repeat(40),
});
+ // Settings now names the official version the personal version is on.
+ expect(h.recordRef).toHaveBeenCalledWith(expect.any(String), ref);
const api = 'https://api.github.com/repos/makecindy/cindy';
expect(h.fetch.mock.calls.map(([url]) => url)).toEqual([
...(channel === 'dev'
@@ -310,6 +324,36 @@ it.each(['dev', 'beta', 'release'] as const)(
]);
},
);
+it('keeps an operation with its account across a new sign-in of the same account', async () => {
+ const id = '12345678-1234-1234-1234-123456789abc';
+ // Written by an older client with the session generation in the owner.
+ h.saved = JSON.stringify({
+ state: {
+ id,
+ status: 'conflict',
+ ref: 'main',
+ upstreamCommit: 'a'.repeat(40),
+ baselineCommit: 'b'.repeat(40),
+ strategy: 'rebase',
+ hasWorkspace: true,
+ sessionId: 'resolver',
+ },
+ sessionOwner: 'cloud:user-1:1',
+ });
+ h.workspace = true;
+ h.current = 'cloud:user-1:2';
+ configureUpstreamMerge(() => false);
+ expect(h.projected).toMatchObject({ id, sessionId: 'resolver' });
+ expect(h.projected?.ownedByAnotherAccount).toBeUndefined();
+ h.current = 'cloud:user-2:3';
+ configureUpstreamMerge(() => false);
+ expect(h.projected).toMatchObject({ id, ownedByAnotherAccount: true });
+ // A stable owner is read back as it is, also when the account id is a number.
+ h.saved = JSON.stringify({ ...JSON.parse(h.saved!), sessionOwner: 'cloud:12345' });
+ h.current = 'cloud:12345:7';
+ configureUpstreamMerge(() => false);
+ expect(h.projected?.ownedByAnotherAccount).toBeUndefined();
+});
it('rejects a manual source sync during a personal build without queuing it', async () => {
h.building = true;
await expect(actUpstreamMerge({ action: 'update' })).rejects.toThrow('busy');
diff --git a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeSession.test.ts b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeSession.test.ts
index 14fd324164..8357296b9f 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeSession.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/upstreamMergeSession.test.ts
@@ -165,6 +165,27 @@ describe('dedicated upstream merge session', () => {
}
},
);
+ it('asks the resolver to keep both computers’ changes when combining with GitHub', async () => {
+ setMainLocale('zh-CN');
+ await ensureUpstreamMergeSession(
+ userData,
+ { ...state, strategy: 'combine', ref: 'github', remote: { base: 'e'.repeat(40) } },
+ { agentKind: 'codex' },
+ vi.fn(),
+ () => true,
+ );
+ expect(h.insert).toHaveBeenLastCalledWith(
+ expect.objectContaining({ title: '09-20 14:07 合并两台电脑的修改' }),
+ );
+ const prompt = String(h.dispatch.mock.calls.at(-1)?.[1]);
+ expect(prompt).toContain('两边的功能都不能丢');
+ expect(prompt).toContain(state.upstreamCommit);
+ expect(prompt).toContain(state.baselineCommit!);
+ expect(prompt).toContain('e'.repeat(40));
+ for (const forbidden of ['rebase --skip', 'reset --hard', 'ours/theirs', '禁止 push'])
+ expect(prompt).toContain(forbidden);
+ expect(prompt).not.toContain('最新官方版本');
+ });
it('reopens an existing task without changing its timestamp or dispatching the first message twice', async () => {
h.reads.push([row], [{ id: 'first-message' }]);
expect(
diff --git a/apps/desktop/src/main/cindy-make/__tests__/versionStore.test.ts b/apps/desktop/src/main/cindy-make/__tests__/versionStore.test.ts
index a7ec307246..0aaa00f273 100644
--- a/apps/desktop/src/main/cindy-make/__tests__/versionStore.test.ts
+++ b/apps/desktop/src/main/cindy-make/__tests__/versionStore.test.ts
@@ -25,6 +25,8 @@ import {
type VersionProfile,
} from '../versionStore';
import { cleanupPersonalVersions } from '../personalVersionCleanup';
+import * as pendingBuild from '../pendingBuild';
+import { makeSourceRoot } from '../sourcePaths';
vi.mock('../../logger', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
@@ -65,13 +67,13 @@ async function fixture() {
appPath: path.join(resources, 'app.asar'),
resources,
};
- const retain = () =>
+ const retain = (candidateCommit = commit) =>
retainPersonalVersion({
profile,
sourceDirectory: source,
appName: 'Cindy',
title: 'Blue background',
- commit,
+ commit: candidateCommit,
});
return {
root,
@@ -141,6 +143,65 @@ describe('local Cindy version snapshots', () => {
await rm(path.join(h.userData, 'cindy-make'), { recursive: true });
expect(await verifyPersonalVersion(h.userData, first, h.original)).toMatchObject({ id: first });
});
+ it('keeps the published personal version when settling the pending ledger fails', async () => {
+ const h = await fixture();
+ const first = (await h.retain())!;
+ publishPersonalVersion(h.userData, first);
+ const sourceRoot = makeSourceRoot(h.userData);
+ const pending = { commit: 'b'.repeat(40), tree: '1'.repeat(40) };
+ writeVersionJson(path.join(h.resources, 'cindy-source.json'), {
+ sourceCommit: pending.commit,
+ builtAt: h.builtAt,
+ });
+ const second = (await h.retain(pending.commit))!;
+ pendingBuild.recordPendingBuild(sourceRoot, pending);
+ const settle = vi.spyOn(pendingBuild, 'settlePendingBuilds').mockImplementation(() => {
+ throw new Error('disk full');
+ });
+ try {
+ expect(() => publishPersonalVersion(h.userData, second)).not.toThrow();
+ } finally {
+ settle.mockRestore();
+ }
+ expect(personalVersionId(h.userData)).toBe(second);
+ expect(pendingBuild.readPendingBuilds(sourceRoot)).toEqual([pending]);
+ expect(hasPublishedPersonalVersionCommit(h.userData, pending.commit)).toBe(true);
+ expect(await verifyPersonalVersion(h.userData, second, h.original)).toMatchObject({
+ id: second,
+ });
+ expect(fs.existsSync(path.join(versionDirectory(h.userData, second), 'version.json'))).toBe(
+ true,
+ );
+ });
+ it.each(['pending', 'unknown'] as const)(
+ 'leaves the %s ledger untouched when switching the personal slot fails',
+ async (state) => {
+ const h = await fixture();
+ const first = (await h.retain())!;
+ publishPersonalVersion(h.userData, first);
+ const second = (await h.retain())!;
+ const sourceRoot = makeSourceRoot(h.userData);
+ const pending = { commit: h.commit, tree: '1'.repeat(40) };
+ const ledgerPath = path.join(sourceRoot, 'pending-build.json');
+ if (state === 'pending') pendingBuild.recordPendingBuild(sourceRoot, pending);
+ else await writeFile(ledgerPath, '{ damaged');
+ const before = await readFile(ledgerPath, 'utf8');
+ const writeSelection = (file: string, value: unknown) => {
+ if (file === path.join(versionsRoot(h.userData), 'personal.json'))
+ throw new Error('disk full');
+ writeVersionJson(file, value);
+ };
+ expect(() => publishPersonalVersion(h.userData, second, writeSelection)).toThrow('disk full');
+ expect(personalVersionId(h.userData)).toBe(first);
+ expect(await readFile(ledgerPath, 'utf8')).toBe(before);
+ expect(pendingBuild.hasPendingBuild(sourceRoot, pending)).toBe(
+ state === 'pending' ? true : undefined,
+ );
+ expect(fs.existsSync(path.join(versionDirectory(h.userData, second), 'version.json'))).toBe(
+ true,
+ );
+ },
+ );
it('keeps only the latest personal slot while staging and preserves running files and publication facts', async () => {
const h = await fixture();
const first = (await h.retain())!;
diff --git a/apps/desktop/src/main/cindy-make/buildRollback.ts b/apps/desktop/src/main/cindy-make/buildRollback.ts
index 1572c16531..2bea06fe42 100644
--- a/apps/desktop/src/main/cindy-make/buildRollback.ts
+++ b/apps/desktop/src/main/cindy-make/buildRollback.ts
@@ -1,4 +1,5 @@
import type { CindyMakeHistoryStore, MakeBuildRollbackEntry } from './historyStore.js';
+import { hasPendingBuild, dropPendingBuild } from './pendingBuild.js';
import { contentRef, snapshotContent, taskContentRef, type ContentGit } from './sourceContent.js';
import { CINDY_PERSONAL_BRANCH } from './sourcePaths.js';
@@ -10,20 +11,26 @@ export async function rollbackUnbuiltHistory(
source: string,
git: ContentGit,
isPublishedCommit: IsPublishedCommit,
+ recordRoot?: string,
): Promise<void> {
- const rollback = historyBuildRollback(store, source, isPublishedCommit);
+ const rollback = historyBuildRollback(store, source, isPublishedCommit, recordRoot);
await rollback.recoverRollback(git);
const commit = (await git(['rev-parse', 'HEAD'], source)).trim();
const tree = await snapshotContent(git, source);
await rollback.prepareRollback({ commit, tree }, git)();
}
-/** Restore only an unchanged, unpublished build candidate; never discard user edits. */
+/**
+ * Restore only an unchanged, unpublished build candidate; never discard user edits.
+ * The restored-over snapshot leaves the source here, so its pending-generation
+ * fact is dropped with it (see `pendingBuild`).
+ */
export async function restoreBuildSource(
git: ContentGit,
source: string,
before: { commit: string; tree: string },
after: { commit: string; tree: string },
+ recordRoot?: string,
): Promise<void> {
const head = (await git(['rev-parse', 'HEAD'], source)).trim();
const tree = await snapshotContent(git, source);
@@ -32,7 +39,12 @@ export async function restoreBuildSource(
(await git(['status', '--porcelain'], source)).trim()
)
throw new Error('Personal source changed');
- if (head === before.commit && tree === before.tree) return;
+ if (head === before.commit && tree === before.tree) {
+ // The source never carried `after`, or an earlier restore got here first:
+ // its fact is stale either way.
+ if (recordRoot) dropPendingBuild(recordRoot, after);
+ return;
+ }
if (head !== after.commit || tree !== after.tree) throw new Error('Personal source changed');
// Retain the failed candidate independently of the personal branch and task worktree.
await git(['update-ref', 'refs/cindy-make/failed-builds/' + after.commit, after.commit], source);
@@ -42,6 +54,79 @@ export async function restoreBuildSource(
(await snapshotContent(git, source)) !== before.tree
)
throw new Error('Personal source recovery incomplete');
+ if (recordRoot) dropPendingBuild(recordRoot, after);
+}
+
+/**
+ * Walk back from `head` over the consecutive integrations that no saved version
+ * contains. These are exactly the receipts a failed generation would undo.
+ */
+function unbuiltHistoryEntries(
+ records: ReturnType<CindyMakeHistoryStore['list']>,
+ head: { commit: string; tree: string },
+ isPublishedCommit: IsPublishedCommit,
+): MakeBuildRollbackEntry[] {
+ const entries: MakeBuildRollbackEntry[] = [];
+ let current = head;
+ while (true) {
+ if (
+ isPublishedCommit(current.commit) ||
+ records.some((record) => record.versions.some((version) => version.commit === current.commit))
+ )
+ break;
+ const record = records
+ .sort((a, b) => (b.receipts.at(-1)?.at ?? 0) - (a.receipts.at(-1)?.at ?? 0))
+ .find((record) => {
+ const receipt = record.receipts.at(-1);
+ return receipt?.commit === current.commit && receipt.tree === current.tree;
+ });
+ if (
+ !record ||
+ record.versions.some((version) => version.operationId === record.receipts.at(-1)?.id)
+ )
+ break;
+ const receipt = record.receipts.pop()!;
+ const previous = record.receipts.at(-1);
+ entries.push({
+ runId: record.runId,
+ receipt,
+ previousTaskTree: previous?.action !== 'revert' ? previous?.taskTree : undefined,
+ });
+ current = { commit: receipt.baselineCommit, tree: receipt.beforeTree };
+ }
+ return entries;
+}
+
+/** A personal version with such integrations is still provisional and must not be shared. */
+export function hasUnbuiltHistory(
+ store: CindyMakeHistoryStore,
+ head: { commit: string; tree: string },
+ isPublishedCommit: IsPublishedCommit,
+): boolean {
+ return unbuiltHistoryEntries(store.list(), head, isPublishedCommit).length > 0;
+}
+
+/**
+ * Whether the personal version at `head` carries changes that are not generated
+ * on this computer yet and a failed generation could still undo. The managed
+ * source is shared by every Cindy account on the device while the build history
+ * stays account-isolated: the account's own facts answer for its own
+ * integrations, and the device-level record (see `pendingBuild`) answers for
+ * whatever another account or another computer carried in — "this account has
+ * no receipts for it" never reads as "nothing is pending".
+ */
+export function hasUnbuiltPersonalChanges(
+ store: CindyMakeHistoryStore,
+ recordRoot: string,
+ head: { commit: string; tree: string },
+ isPublishedCommit: IsPublishedCommit,
+): boolean {
+ if (store.readBuildRollback().length > 0) return true;
+ if (hasUnbuiltHistory(store, head, isPublishedCommit)) return true;
+ const pending = hasPendingBuild(recordRoot, head);
+ // A missing or unreadable record (`undefined`) proves nothing: pending unless a
+ // generated personal version already covers this snapshot.
+ return pending !== false && !isPublishedCommit(head.commit);
}
/** Build cleanup owns only the consecutive integrations not present in a saved version. */
@@ -49,6 +134,7 @@ export function historyBuildRollback(
store: CindyMakeHistoryStore,
source: string,
isPublishedCommit: IsPublishedCommit = () => false,
+ recordRoot?: string,
) {
const recover = async (git: ContentGit) => {
const entries = store.readBuildRollback();
@@ -74,6 +160,7 @@ export function historyBuildRollback(
source,
{ commit: receipt.baselineCommit, tree: receipt.beforeTree },
receipt,
+ recordRoot,
);
await git(
previousTaskTree ? ['update-ref', ref, previousTaskTree] : ['update-ref', '-d', ref],
@@ -87,37 +174,7 @@ export function historyBuildRollback(
return {
recoverRollback: recover,
prepareRollback: (head: { commit: string; tree: string }, git: ContentGit) => {
- const records = store.list();
- const entries: MakeBuildRollbackEntry[] = [];
- let current = head;
- while (true) {
- if (
- isPublishedCommit(current.commit) ||
- records.some((record) =>
- record.versions.some((version) => version.commit === current.commit),
- )
- )
- break;
- const record = records
- .sort((a, b) => (b.receipts.at(-1)?.at ?? 0) - (a.receipts.at(-1)?.at ?? 0))
- .find((record) => {
- const receipt = record.receipts.at(-1);
- return receipt?.commit === current.commit && receipt.tree === current.tree;
- });
- if (
- !record ||
- record.versions.some((version) => version.operationId === record.receipts.at(-1)?.id)
- )
- break;
- const receipt = record.receipts.pop()!;
- const previous = record.receipts.at(-1);
- entries.push({
- runId: record.runId,
- receipt,
- previousTaskTree: previous?.action !== 'revert' ? previous?.taskTree : undefined,
- });
- current = { commit: receipt.baselineCommit, tree: receipt.beforeTree };
- }
+ const entries = unbuiltHistoryEntries(store.list(), head, isPublishedCommit);
return async () => {
if (!entries.length) return;
store.saveBuildRollback(entries);
diff --git a/apps/desktop/src/main/cindy-make/carriedChanges.ts b/apps/desktop/src/main/cindy-make/carriedChanges.ts
new file mode 100644
index 0000000000..fba215fd46
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/carriedChanges.ts
@@ -0,0 +1,150 @@
+import os from 'node:os';
+import path from 'node:path';
+import { mkdtemp, rm } from 'node:fs/promises';
+
+import type { ContentGit } from './sourceContent.js';
+
+const COMMIT = /^[0-9a-f]{40}$/i;
+const IDENTITY_FORMAT = '%an%x00%ae%x00%at%x00%s';
+const checksFailed = () => Object.assign(new Error('checksFailed'), { code: 'checksFailed' });
+
+/** A truncated history must not silently omit a change from the preservation check. */
+async function listedCommits(git: ContentGit, cwd: string, args: string[]): Promise<string[]> {
+ const lines = (await git(['log', ...args], cwd)).split(/\r?\n/).filter(Boolean);
+ const count = Number(
+ (
+ await git(['rev-list', '--count', ...args.filter((arg) => !arg.startsWith('--format='))], cwd)
+ ).trim(),
+ );
+ if (!Number.isSafeInteger(count) || count !== lines.length) throw checksFailed();
+ return lines;
+}
+
+/** Reapplying the original three-tree change must leave the checked tree unchanged. */
+async function alreadyCarried(
+ git: ContentGit,
+ cwd: string,
+ base: string,
+ commit: string,
+ result: string,
+ resultTree: string,
+): Promise<boolean> {
+ if (!COMMIT.test(resultTree)) return false;
+ try {
+ const merged = await git(
+ ['merge-tree', '--write-tree', '--no-messages', `--merge-base=${base}`, result, commit],
+ cwd,
+ );
+ return merged.split(/\r?\n/)[0]?.trim() === resultTree;
+ } catch (error) {
+ if ((error as { exitCode?: number }).exitCode === 1) return false;
+ }
+ // Older Git has no merge-tree --merge-base. read-tree compares the original
+ // blobs and modes at their actual paths, without fuzzy patch placement. It
+ // cannot prove every text merge; an ambiguous result goes to user review.
+ const temporary = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-carried-'));
+ try {
+ const index = path.join(temporary, 'index');
+ await git(['read-tree', '-m', base, result, commit], cwd, index);
+ if ((await git(['ls-files', '--unmerged'], cwd, index)).trim()) return false;
+ return (await git(['write-tree'], cwd, index)).trim() === resultTree;
+ } catch {
+ return false;
+ } finally {
+ await rm(temporary, { recursive: true, force: true }).catch(() => undefined);
+ }
+}
+
+/**
+ * Changes missing from the adopted result. Identity only locates a possible
+ * rewrite: its original, position-aware tree change must be present there too.
+ * Neither patch-id (which drops hunk positions) nor words surviving somewhere in
+ * a file prove that an edit kept its target or its execution conditions.
+ */
+export async function uncarriedChanges(
+ git: ContentGit,
+ cwd: string,
+ replayed: string,
+ onto: string,
+ result: string,
+): Promise<string[]> {
+ if (!COMMIT.test(replayed) || !COMMIT.test(onto) || !COMMIT.test(result)) throw checksFailed();
+ const sides = `${result}...${replayed}`;
+ const candidates = await listedCommits(git, cwd, [
+ '--right-only',
+ '--no-merges',
+ `--format=%H%x00${IDENTITY_FORMAT}`,
+ sides,
+ ]);
+ const resultTree = (await git(['rev-parse', `${result}^{tree}`], cwd)).trim();
+ if (!COMMIT.test(resultTree)) throw checksFailed();
+ const missing: string[] = [];
+ type Voucher = { commit: string; key: string; used: boolean };
+ const vouchers = new Map<string, Voucher[]>();
+ for (const line of candidates) {
+ const [commit, ...fields] = line.split('\0');
+ if (!COMMIT.test(commit) || fields.length !== 4) throw checksFailed();
+ if (await alreadyCarried(git, cwd, `${commit}^`, commit, result, resultTree)) continue;
+ const key = fields.join('\0');
+ const email = fields[1];
+ let pool = vouchers.get(email);
+ if (!pool) {
+ pool = [];
+ for (const line of await listedCommits(git, cwd, [
+ '--left-only',
+ '--no-merges',
+ '--fixed-strings',
+ `--author=<${email}>`,
+ `--format=%H%x00${IDENTITY_FORMAT}`,
+ sides,
+ ])) {
+ const [hash, ...identity] = line.split('\0');
+ if (!COMMIT.test(hash) || identity.length !== 4) throw checksFailed();
+ pool.push({ commit: hash, key: identity.join('\0'), used: false });
+ }
+ vouchers.set(email, pool);
+ }
+ let vouched = false;
+ for (const voucher of pool) {
+ if (voucher.used || voucher.key !== key) continue;
+ const tree = (await git(['rev-parse', `${voucher.commit}^{tree}`], cwd)).trim();
+ if (!(await alreadyCarried(git, cwd, `${commit}^`, commit, voucher.commit, tree))) continue;
+ // A later personal change may intentionally supersede an earlier one. Its
+ // corresponding replay commit can prove that the earlier edit was applied,
+ // but one commit must never vouch for two same-identity changes.
+ voucher.used = true;
+ vouched = true;
+ break;
+ }
+ if (!vouched) missing.push(commit);
+ }
+ const merges = await listedCommits(git, cwd, [
+ '--merges',
+ '--format=%H',
+ `${result}..${replayed}`,
+ ]);
+ for (const merge of merges) {
+ if (!COMMIT.test(merge)) throw checksFailed();
+ if (
+ !(
+ await git(
+ [
+ 'show',
+ '--remerge-diff',
+ '--no-ext-diff',
+ '--no-textconv',
+ '--no-color',
+ '--format=',
+ '--name-only',
+ merge,
+ ],
+ cwd,
+ )
+ ).trim()
+ )
+ continue;
+ if (!(await alreadyCarried(git, cwd, `${merge}^1`, merge, result, resultTree)))
+ missing.push(merge);
+ }
+ return missing;
+}
diff --git a/apps/desktop/src/main/cindy-make/historyRuntime.ts b/apps/desktop/src/main/cindy-make/historyRuntime.ts
index 6806c260fc..697f6d8bbc 100644
--- a/apps/desktop/src/main/cindy-make/historyRuntime.ts
+++ b/apps/desktop/src/main/cindy-make/historyRuntime.ts
@@ -29,6 +29,7 @@ import type { CindyMakeMergeState } from '../../shared/cindyMakeMerge.js';
import type { MakeTestContext } from './testController.js';
import { manageCindyMakeTask } from './taskManagement.js';
import { historyBuildRollback, rollbackUnbuiltHistory } from './buildRollback.js';
+import { recordPendingBuild } from './pendingBuild.js';
import { makeBuildErrorDiagnostic } from './buildDiagnostic.js';
import { actCindyMakeTest, cindyMakeTestController } from './testRuntime.js';
import {
@@ -446,11 +447,19 @@ async function readCindyMakeHistory(
const legacy = await readLegacyFeatureReceipts(record, git, source);
h.check();
for (const receipt of legacy) {
- h.store.receipt(record.runId, receipt);
- record.receipts.push(receipt);
const built = record.completions.find(
(entry) => entry.personal?.commit === receipt.commit,
)?.personal;
+ // A legacy integration that is still unbuilt counts as pending just
+ // like a new one: the source carries it, and a failed generation could
+ // still undo it (see `pendingBuild`).
+ if (!built)
+ recordPendingBuild(makeSourceRoot(h.userData), {
+ commit: receipt.commit,
+ tree: receipt.tree,
+ });
+ h.store.receipt(record.runId, receipt);
+ record.receipts.push(receipt);
if (built)
h.store.version(record.runId, {
operationId: receipt.id,
@@ -634,7 +643,8 @@ async function readCindyMakeHistory(
!operation &&
!taskBuilding &&
test?.status !== 'starting' &&
- ['unintegrated', 'changed', 'reverted'].includes(integration),
+ // An undone change is restored only by its own Restore action, never by a batch build.
+ ['unintegrated', 'changed'].includes(integration),
canHide: !targetBusy && !['starting', 'ready'].includes(test?.status ?? ''),
});
}
@@ -1130,8 +1140,11 @@ export async function generateHistoryPersonalVersion(
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),
+ makeSourceRoot(h.userData),
),
features: () =>
h.store.list().flatMap((record) => {
@@ -1216,8 +1229,12 @@ export async function recoverHistoryBuildRollback(rollbackUnbuilt = false): Prom
);
};
const published = (commit: string) => hasPublishedPersonalVersionCommit(h.userData, commit);
- if (rollbackUnbuilt) await rollbackUnbuiltHistory(h.store, source, git, published);
- else await historyBuildRollback(h.store, source, published).recoverRollback(git);
+ if (rollbackUnbuilt)
+ await rollbackUnbuiltHistory(h.store, source, git, published, makeSourceRoot(h.userData));
+ else
+ await historyBuildRollback(h.store, source, published, makeSourceRoot(h.userData)).recoverRollback(
+ git,
+ );
});
} catch {
throw personalBuildError('cleanupFailed');
diff --git a/apps/desktop/src/main/cindy-make/installScriptsTrust.ts b/apps/desktop/src/main/cindy-make/installScriptsTrust.ts
new file mode 100644
index 0000000000..b62632ec59
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/installScriptsTrust.ts
@@ -0,0 +1,122 @@
+import path from 'node:path';
+
+import { readAtomicFileSync } from '../utils/atomicWriteFile.js';
+import { parsePersonalRemoteTrust, type PersonalRewrite } from './personalRemote.js';
+import { runSourceGit } from './sourceGit.js';
+import { makeSourceCheckoutPath, makeSourceRoot } from './sourcePaths.js';
+import { publishedPersonalVersionCommits } from './versionStore.js';
+
+const COMMIT = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i;
+
+export interface InstallScriptsTrust {
+ /** Fork tips taken over before this computer verified them (see `recordUnverifiedRemote`). */
+ unverifiedRemote(): string[];
+ /** A bounded ledger overflowed; omitted provenance must remain guarded. */
+ unverifiedRemoteOverflow?(): boolean;
+ /** Adopted history rewrites (official updates and combines), see `recordRewrite`. */
+ rewrites(): PersonalRewrite[];
+ /** Commits a generated personal version was published from. */
+ published(): string[];
+ /** Git ancestry in the managed checkout. */
+ contains(ancestor: string, descendant: string): Promise<boolean>;
+}
+
+/**
+ * `tip`'s content reached `target`, directly or through the adopted history rewrites:
+ * an official update or combine replays content under new commits, and the provenance
+ * travels with it (see `PersonalRemoteController.carriedByRewrites`).
+ */
+async function reaches(
+ trust: InstallScriptsTrust,
+ tip: string,
+ target: string,
+): Promise<boolean> {
+ const carried = [tip];
+ for (const rewrite of trust.rewrites()) {
+ for (const input of rewrite.from) {
+ let included = false;
+ for (const known of carried)
+ if (await trust.contains(known, input)) {
+ included = true;
+ break;
+ }
+ if (included) {
+ if (!carried.includes(rewrite.to)) carried.push(rewrite.to);
+ break;
+ }
+ }
+ }
+ for (const commit of carried) if (await trust.contains(commit, target)) return true;
+ return false;
+}
+
+/**
+ * Whether the automatic task-worktree install must skip lifecycle scripts and
+ * pnpm hooks.
+ *
+ * Sync can take over `cindy-personal` content pushed to the user's fork by anyone
+ * with write access to it. Installing that content would run its `postinstall` or
+ * `.pnpmfile.cjs` at task creation, before anyone looks at it. Content is considered
+ * verified — adopted by the user — once a generated personal version covers it:
+ * generating runs the content's own checks and produces the application the user
+ * chose to run. Until then the automatic install runs with `--ignore-scripts
+ * --ignore-pnpmfile`; a task that really needs the scripts runs its own install,
+ * visibly, as part of its work.
+ */
+export async function remoteContentScriptsUnverified(
+ baseCommit: string,
+ trust: InstallScriptsTrust,
+): Promise<boolean> {
+ if (!COMMIT.test(baseCommit)) return true;
+ if (trust.unverifiedRemoteOverflow?.()) {
+ // Omitted tips cannot be vouched for individually. A generated version must
+ // instead cover this task's *whole base*. Keep the overflow marker so later
+ // content which that generation did not cover is still guarded.
+ for (const commit of trust.published())
+ if (COMMIT.test(commit) && (await reaches(trust, baseCommit, commit))) return false;
+ return true;
+ }
+ for (const tip of trust.unverifiedRemote()) {
+ if (!COMMIT.test(tip) || !(await reaches(trust, tip, baseCommit))) continue;
+ let verified = false;
+ for (const commit of trust.published())
+ if (COMMIT.test(commit) && (await reaches(trust, tip, commit))) {
+ verified = true;
+ break;
+ }
+ if (!verified) return true;
+ }
+ return false;
+}
+
+/** The real facts from the managed checkout and the published personal versions. */
+export function installScriptsTrust(
+ userData: string,
+ env: NodeJS.ProcessEnv,
+ signal: AbortSignal,
+): InstallScriptsTrust {
+ const source = makeSourceCheckoutPath(userData);
+ const git = (args: string[]) => runSourceGit(env, args, source, signal);
+ const record = () =>
+ // Corrupt content or an unknown schema proves nothing about trust: it throws,
+ // and the caller keeps the guarded install path (see `parsePersonalRemoteTrust`).
+ parsePersonalRemoteTrust(
+ readAtomicFileSync(path.join(makeSourceRoot(userData), 'personal-remote.json')),
+ );
+ return {
+ unverifiedRemote: () => record().unverifiedRemote ?? [],
+ unverifiedRemoteOverflow: () => record().unverifiedRemoteOverflow === true,
+ rewrites: () => record().rewrites ?? [],
+ published: () => publishedPersonalVersionCommits(userData),
+ contains: async (ancestor, descendant) => {
+ try {
+ await git(['merge-base', '--is-ancestor', ancestor, descendant]);
+ return true;
+ } catch (error) {
+ // Exit 1 is a plain "not an ancestor"; anything else decides nothing.
+ if ((error as { exitCode?: number }).exitCode === 1) return false;
+ throw error;
+ }
+ },
+ };
+}
diff --git a/apps/desktop/src/main/cindy-make/manager.ts b/apps/desktop/src/main/cindy-make/manager.ts
index d7aee735df..f3cf36ff53 100644
--- a/apps/desktop/src/main/cindy-make/manager.ts
+++ b/apps/desktop/src/main/cindy-make/manager.ts
@@ -98,6 +98,8 @@ export class CindyMakeManager {
private readonly sourceJobs = new Map<string, SharedSourceJob>();
private readonly projectJobs = new Map<string, Promise<unknown>>();
private readonly projectUsers = new Map<string, number>();
+ /** Fork synchronization reading the checkout outside the project queue (network phases). */
+ private readonly sourceReaders = new Map<string, number>();
private personalBuild: { sessionIds: string[]; isCurrent: () => boolean } | undefined;
private manualSourceSync = false;
private readonly reports = new Map<
@@ -145,6 +147,7 @@ export class CindyMakeManager {
private projectInUse(root: string): boolean {
return (
(this.projectUsers.get(root) ?? 0) > 0 ||
+ (this.sourceReaders.get(root) ?? 0) > 0 ||
this.isProjectBusy(root) ||
this.hasPendingUpstreamMerge()
);
@@ -167,6 +170,17 @@ export class CindyMakeManager {
return !!this.personalBuild;
}
+ /** Nothing else may move `cindy-personal`: no build, manual sync, open merge or source job. */
+ /** `ownManualSync`: the caller runs inside the manual source sync that holds the reservation. */
+ isSourceSettled(root: string, ownManualSync = false): boolean {
+ return (
+ !this.personalBuild &&
+ (ownManualSync || !this.manualSourceSync) &&
+ !this.hasPendingUpstreamMerge() &&
+ !this.sourceJobs.has(root)
+ );
+ }
+
/** Reserve a manual source update before its first asynchronous step. */
claimManualSourceSync(): () => void {
if (this.personalBuild || this.manualSourceSync)
@@ -179,6 +193,30 @@ export class CindyMakeManager {
};
}
+ isManualSourceSyncRunning(): boolean {
+ return this.manualSourceSync;
+ }
+
+ /** Resolves once no Sync or manual source update holds the source. */
+ whenManualSourceSyncIdle(signal: AbortSignal): Promise<void> {
+ signal.throwIfAborted();
+ if (!this.manualSourceSync) return Promise.resolve();
+ return new Promise<void>((resolve, reject) => {
+ let unsubscribe = () => {};
+ const abort = () => {
+ unsubscribe();
+ reject(signal.reason);
+ };
+ unsubscribe = this.subscribe(() => {
+ if (this.manualSourceSync) return;
+ unsubscribe();
+ signal.removeEventListener('abort', abort);
+ resolve();
+ });
+ signal.addEventListener('abort', abort, { once: true });
+ });
+ }
+
/** Both entry points reserve synchronously, before any asynchronous build work. */
claimPersonalBuild(
sessionIds: readonly string[] = [],
@@ -213,6 +251,33 @@ export class CindyMakeManager {
this.notify();
}
+ setPersonalRemote(state: CindyMakeGlobalState['personalRemote']): void {
+ this.states.personalRemote = state;
+ this.notify();
+ }
+
+ setPersonalSync(state: CindyMakeGlobalState['personalSync']): void {
+ this.states.personalSync = state;
+ this.notify();
+ }
+
+ /**
+ * Keep the checkout from being cleared while Git reads it outside the project queue.
+ * Unlike withProjectUse this does not block personal builds, which only need the queue.
+ */
+ async withSourceReader<T>(root: string, run: () => Promise<T>): Promise<T> {
+ if (this.sourceJobs.get(root)?.clearOnly)
+ throw Object.assign(new Error('project is being cleared'), { code: 'busy' });
+ this.sourceReaders.set(root, (this.sourceReaders.get(root) ?? 0) + 1);
+ try {
+ return await run();
+ } finally {
+ const readers = (this.sourceReaders.get(root) ?? 1) - 1;
+ if (readers === 0) this.sourceReaders.delete(root);
+ else this.sourceReaders.set(root, readers);
+ }
+ }
+
async withProjectUse<T>(root: string, run: () => Promise<T>): Promise<T> {
if (this.sourceJobs.get(root)?.clearOnly)
throw Object.assign(new Error('project is being cleared'), { code: 'busy' });
diff --git a/apps/desktop/src/main/cindy-make/pendingBuild.ts b/apps/desktop/src/main/cindy-make/pendingBuild.ts
new file mode 100644
index 0000000000..d048e3a0ed
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/pendingBuild.ts
@@ -0,0 +1,205 @@
+import { lstatSync, mkdirSync } from 'node:fs';
+import path from 'node:path';
+
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+
+/**
+ * The device-level fact "the source at this snapshot carries personal changes
+ * that are not generated on this computer yet and a failed generation could
+ * still undo": recorded together with the source snapshot it describes, beside
+ * the managed source (`makeSourceRoot`), never in the per-account build history.
+ *
+ * The managed source is shared by every Cindy account on the device while the
+ * build history stays account-isolated, so "the current account has no receipts
+ * for it" must never read as "the source has no pending generation". The
+ * record's transitions keep the fact consistent with the source:
+ *
+ * - integrating a change records the resulting snapshot (before its receipt
+ * lands, so a crash in between never hides an unbuilt integration);
+ * - generating a personal version settles the snapshot it was built from;
+ * - a completed rollback or source restore drops the undone snapshot;
+ * - an adopted rewrite (official update / combine) carries recorded snapshots
+ * over to the rewritten result that contains them.
+ *
+ * A missing or unreadable record proves nothing and must never read as
+ * "nothing pending" (see hasPendingBuild). A valid record marked untrusted
+ * preserves its snapshots but remains unknown until a successful generation.
+ */
+
+const FILE = 'pending-build.json';
+const HASH = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
+const MAX_FILE_BYTES = 256 * 1024;
+/**
+ * Generous bound against a damaged file growing without end. Newest entries are
+ * kept: the snapshot the source is at is always the most recent one recorded,
+ * and only a rollback chain longer than this could lose its oldest link.
+ */
+const MAX_SNAPSHOTS = 64;
+
+export interface PendingBuildSnapshot {
+ commit: string;
+ tree: string;
+}
+
+interface PendingBuildLedger {
+ snapshots: PendingBuildSnapshot[];
+ readable: boolean;
+ trusted: boolean;
+}
+
+const file = (root: string) => path.join(root, FILE);
+
+/**
+ * The recorded snapshots, oldest first. `undefined` means the record is
+ * missing or unreadable — which proves nothing and must never read as
+ * "nothing pending".
+ */
+function readLedger(root: string): PendingBuildLedger {
+ let info;
+ try {
+ info = lstatSync(file(root));
+ if (!info.isFile() || info.isSymbolicLink())
+ return { snapshots: [], readable: false, trusted: false };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ return { snapshots: [], readable: false, trusted: false };
+ return { snapshots: [], readable: false, trusted: false };
+ }
+ const raw = readAtomicFileSync(file(root));
+ if (raw === null || raw.length > MAX_FILE_BYTES)
+ return { snapshots: [], readable: false, trusted: false };
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ return { snapshots: [], readable: false, trusted: false };
+ }
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ return { snapshots: [], readable: false, trusted: false };
+ const input = value as Record<string, unknown>;
+ if (
+ input.schema !== 1 ||
+ !Array.isArray(input.snapshots) ||
+ (input.trusted !== undefined && typeof input.trusted !== 'boolean')
+ )
+ return { snapshots: [], readable: false, trusted: false };
+ const snapshots: PendingBuildSnapshot[] = [];
+ for (const entry of input.snapshots) {
+ const snapshot = entry as { commit?: unknown; tree?: unknown } | null;
+ if (
+ !snapshot ||
+ typeof snapshot !== 'object' ||
+ typeof snapshot.commit !== 'string' ||
+ !HASH.test(snapshot.commit) ||
+ typeof snapshot.tree !== 'string' ||
+ !HASH.test(snapshot.tree)
+ )
+ return { snapshots: [], readable: false, trusted: false };
+ snapshots.push({ commit: snapshot.commit, tree: snapshot.tree });
+ }
+ return { snapshots, readable: true, trusted: input.trusted !== false };
+}
+
+export function readPendingBuilds(root: string): PendingBuildSnapshot[] | undefined {
+ const ledger = readLedger(root);
+ return ledger.readable ? ledger.snapshots : undefined;
+}
+
+function writePendingBuilds(root: string, snapshots: PendingBuildSnapshot[], trusted = true): void {
+ mkdirSync(root, { recursive: true });
+ atomicWriteFileSync(file(root), JSON.stringify({ schema: 1, snapshots, trusted }));
+}
+
+/** Establish a clean ledger only for a newly-created source with no prior record. */
+export function initializePendingBuilds(root: string): void {
+ try {
+ lstatSync(file(root));
+ return;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return;
+ }
+ writePendingBuilds(root, []);
+}
+
+/** The snapshot no longer exists in the source: its fact is stale. Absent record: nothing to do. */
+export function dropPendingBuild(root: string, snapshot: { commit: string; tree?: string }): void {
+ const ledger = readLedger(root);
+ const kept = ledger.snapshots.filter((entry) => entry.commit !== snapshot.commit);
+ if (kept.length !== ledger.snapshots.length) writePendingBuilds(root, kept, ledger.trusted);
+}
+
+/**
+ * The source moved to `snapshot` with changes that are not generated here yet.
+ * Earlier snapshots stay recorded: a rollback chain steps back over them, and
+ * each undone snapshot is dropped as the source leaves it.
+ */
+export function recordPendingBuild(root: string, snapshot: PendingBuildSnapshot): void {
+ if (!HASH.test(snapshot.commit) || !HASH.test(snapshot.tree))
+ throw new Error('Invalid pending build snapshot');
+ const ledger = readLedger(root);
+ const entries = ledger.snapshots.filter(
+ (entry) => entry.commit !== snapshot.commit || entry.tree !== snapshot.tree,
+ );
+ entries.push(snapshot);
+ const bounded = entries.slice(-MAX_SNAPSHOTS);
+ // Losing an older snapshot also loses the proof that a rollback can still be
+ // explained. Keep the entries for diagnostics, but force the next decision
+ // through the unknown/failed-closed path until a generation settles them.
+ writePendingBuilds(root, bounded, ledger.trusted && bounded.length === entries.length);
+}
+
+/**
+ * A generated personal version settles the pending generation it was built
+ * from, and with it every earlier snapshot its content carries: nothing left in
+ * the source keeps waiting for a generation that already covered it. Source
+ * moves queue behind the same project lock a build holds, so nothing can be
+ * recorded against the built source in between.
+ */
+export function settlePendingBuilds(root: string): void {
+ const ledger = readLedger(root);
+ // A successful generation is the proof that settles even an unknown ledger.
+ if (!ledger.trusted || ledger.snapshots.length) writePendingBuilds(root, []);
+}
+
+/**
+ * An adopted rewrite (official update / combine) carried the recorded changes
+ * into its result: the fact follows the content to the snapshot that now holds it.
+ */
+export function rewritePendingBuilds(
+ root: string,
+ from: readonly string[],
+ to: PendingBuildSnapshot,
+): void {
+ if (!HASH.test(to.commit) || !HASH.test(to.tree)) return;
+ const ledger = readLedger(root);
+ const known = ledger.snapshots;
+ const carried = new Set(from);
+ const entries = known.map((entry) => (carried.has(entry.commit) ? to : entry));
+ if (entries.some((entry) => entry === to)) {
+ const unique = entries.filter(
+ (entry, at) => entries.findIndex((other) => other === entry) === at,
+ );
+ const bounded = unique.slice(-MAX_SNAPSHOTS);
+ writePendingBuilds(root, bounded, ledger.trusted && bounded.length === unique.length);
+ return;
+ }
+ const bounded = entries.slice(-MAX_SNAPSHOTS);
+ writePendingBuilds(root, bounded, ledger.trusted && bounded.length === entries.length);
+}
+
+/**
+ * Whether the snapshot is recorded as carrying a pending generation. `undefined`
+ * when the record cannot prove anything either way: the caller must then treat
+ * the snapshot as pending unless a generated version already covers it.
+ *
+ * A commit names exactly one source snapshot, so the commit identifies the
+ * record entry; the tree is kept with it as the snapshot's content identity.
+ */
+export function hasPendingBuild(
+ root: string,
+ head: { commit: string; tree: string },
+): boolean | undefined {
+ const ledger = readLedger(root);
+ if (ledger.snapshots.some((entry) => entry.commit === head.commit)) return true;
+ return ledger.trusted ? false : undefined;
+}
diff --git a/apps/desktop/src/main/cindy-make/personalBuild.ts b/apps/desktop/src/main/cindy-make/personalBuild.ts
index 512b928821..8d25910005 100644
--- a/apps/desktop/src/main/cindy-make/personalBuild.ts
+++ b/apps/desktop/src/main/cindy-make/personalBuild.ts
@@ -607,10 +607,16 @@ export async function buildCindyPersonal(
if (!published) {
try {
if (adopted && original && editingTask) {
- await restoreBuildSource(recoveryGit, source, original, {
- commit: baseline,
- tree: candidateTree,
- });
+ await restoreBuildSource(
+ recoveryGit,
+ source,
+ original,
+ {
+ commit: baseline,
+ tree: candidateTree,
+ },
+ makeSourceRoot(task.userData),
+ );
const ref = taskContentRef(editingTask.runId, 'integrated');
await recoveryGit(
previousTaskTree ? ['update-ref', ref, previousTaskTree] : ['update-ref', '-d', ref],
diff --git a/apps/desktop/src/main/cindy-make/personalContribution.ts b/apps/desktop/src/main/cindy-make/personalContribution.ts
new file mode 100644
index 0000000000..af509acb28
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/personalContribution.ts
@@ -0,0 +1,886 @@
+import path from 'node:path';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import { randomUUID } from 'node:crypto';
+
+import {
+ CONTRIBUTION_LIMITS,
+ isContributionEmail,
+ touchesUiPath,
+ type CindyMakeContributionDraft,
+ type CindyMakeContributionError,
+ type CindyMakeContributionState,
+ type CindyMakeContributionView,
+} from '../../shared/cindyMakeContribution.js';
+import { isGithubRepository, sameGithubLogin } from '../../shared/cindyMakePersonalRemote.js';
+import {
+ OFFICIAL_GITHUB_REPOSITORY,
+ PERSONAL_REMOTE_NAME,
+ PersonalRemoteError,
+ classifyRemoteGitError,
+ type GithubIdentity,
+ type GithubIdentityResult,
+ type PersonalForkHealth,
+ type PersonalRemoteGitOptions,
+ type PersonalRemoteRecord,
+} from './personalRemote.js';
+
+const API = 'https://api.github.com';
+const OFFICIAL_URL = `https://github.com/${OFFICIAL_GITHUB_REPOSITORY}.git`;
+const OFFICIAL_MAIN_REF = 'refs/cindy-make/contribution/main';
+const HASH = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i;
+const RUN_ID = /^[A-Za-z0-9-]{1,128}$/;
+
+function remoteTip(output: string): string | undefined {
+ const tip = output.trim().split(/\s/)[0]?.trim();
+ return tip && HASH.test(tip) ? tip : undefined;
+}
+
+/** Durable record of one submitted change; owner-private like the Make history. */
+export interface ContributionRecord {
+ runId: string;
+ number: number;
+ url: string;
+ branch: string;
+ commit: string;
+ submittedAt: number;
+}
+
+export function parseContributionStore(raw: string | null): Record<string, ContributionRecord> {
+ if (raw === null) return {};
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ return {};
+ }
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
+ const store: Record<string, ContributionRecord> = {};
+ for (const [runId, entry] of Object.entries(value as Record<string, unknown>)) {
+ const record = entry as Partial<ContributionRecord> | null;
+ if (
+ RUN_ID.test(runId) &&
+ record?.runId === runId &&
+ Number.isSafeInteger(record.number) &&
+ record.number! > 0 &&
+ typeof record.url === 'string' &&
+ record.url.startsWith(`https://github.com/${OFFICIAL_GITHUB_REPOSITORY}/pull/`) &&
+ typeof record.branch === 'string' &&
+ /^cindy-make-pr\/[A-Za-z0-9-]{1,64}$/.test(record.branch) &&
+ typeof record.commit === 'string' &&
+ HASH.test(record.commit) &&
+ Number.isSafeInteger(record.submittedAt)
+ )
+ store[runId] = record as ContributionRecord;
+ }
+ return store;
+}
+
+export class ContributionError extends Error {
+ constructor(readonly code: CindyMakeContributionError) {
+ super(code);
+ }
+}
+const fail = (code: CindyMakeContributionError) => new ContributionError(code);
+
+/** The change as this computer recorded it: the task's creation baseline and final content. */
+export interface ContributionChange {
+ title: string;
+ request: string;
+ baseTree: string;
+ tree: string;
+}
+
+interface ContributionSnapshot {
+ scope: string;
+ ledger: string;
+ runId: string;
+ repository: string;
+ login: string;
+ change: ContributionChange;
+}
+
+export interface ContributionDeps {
+ source: string;
+ /** Stable key of the signed-in Cindy account that started the operation. */
+ ownerScope(): string;
+ binding(): PersonalRemoteRecord;
+ identity(): Promise<GithubIdentityResult>;
+ /** The bound repository as GitHub sees it now (see `inspectPersonalFork`). */
+ inspectFork(identity: GithubIdentity, repository: string): Promise<PersonalForkHealth>;
+ git(args: string[], cwd: string, options?: PersonalRemoteGitOptions): Promise<string>;
+ change(runId: string): ContributionChange | undefined;
+ /** Ledger file of the account that started the operation (pinned at entry). */
+ ledgerPath(): string;
+ readStore(file: string): Record<string, ContributionRecord>;
+ writeStore(file: string, store: Record<string, ContributionRecord>): void;
+ /** Invalidate read-only Cindy Make resources after the ledger changes. */
+ onChanged?(runId: string): void;
+ fetch: typeof fetch;
+ /** The author's own Git identity, if configured on this computer. */
+ gitIdentity(): Promise<{ name?: string; email?: string }>;
+ withSourceUse<T>(run: () => Promise<T>): Promise<T>;
+ now(): number;
+}
+
+const githubHeaders = (token: string): Record<string, string> => ({
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/vnd.github+json',
+ 'X-GitHub-Api-Version': '2022-11-28',
+});
+
+/** Prefilled body following `.github/PULL_REQUEST_TEMPLATE.md`; the author edits it before submitting. */
+export function contributionBody(input: {
+ title: string;
+ request: string;
+ files: string[];
+ touchesUi: boolean;
+}): string {
+ const type = /^([a-z]+)(?:\([^)]*\))?:/.exec(input.title)?.[1];
+ const box = (value: string) => (type === value ? 'x' : ' ');
+ const shown = input.files.slice(0, 30).map((file) => ` - \`${file}\``);
+ if (input.files.length > shown.length)
+ shown.push(` - 另有 ${input.files.length - shown.length} 个文件`);
+ return [
+ '## 这次改了什么',
+ '',
+ '### 摘要',
+ '',
+ input.request.trim() || input.title,
+ '',
+ '### 变更类型',
+ '',
+ `- [${box('feat')}] \`feat\` 新功能`,
+ `- [${box('fix')}] \`fix\` 缺陷修复`,
+ `- [${type === 'refactor' || type === 'perf' ? 'x' : ' '}] \`refactor\` / \`perf\` 重构或性能优化`,
+ `- [${['docs', 'test', 'chore'].includes(type ?? '') ? 'x' : ' '}] \`docs\` / \`test\` / \`chore\` 文档、测试或工程维护`,
+ '- [ ] 其他:',
+ '',
+ '### 范围',
+ '',
+ '- 关联 Issue / 需求:无',
+ `- 本 PR 包含:${input.title}`,
+ '- 明确不包含:作者个人版中的其他修改',
+ '- 用户可见变化:见摘要',
+ '- 是否存在 breaking change:无',
+ '',
+ '### UI 变化',
+ '',
+ input.touchesUi ? '修改涉及界面,截图请作者补充。' : '不涉及',
+ '',
+ input.touchesUi
+ ? '- 引用的设计规范:docs/design-rules/DESIGN.md(请作者补充具体章节)'
+ : '- 引用的设计规范:不涉及:本修改不改界面代码',
+ '',
+ '## 怎么验证的',
+ '',
+ '### 自动验证',
+ '',
+ '```text',
+ '本 PR 分支由 Cindy Make 在官方最新 main 上单独整理,未在本机运行检查,以 CI 结果为准。',
+ '```',
+ '',
+ '### 手工验证',
+ '',
+ '请作者补充:是否在自己的个人版中实际使用过这项修改,以及怎么验证的。',
+ '',
+ '### 未执行的验证',
+ '',
+ '本 PR 分支未在本机单独运行测试。',
+ '',
+ '## 风险',
+ '',
+ '### 风险分类',
+ '',
+ '- [ ] 无已知风险',
+ '- [ ] 其他:请维护者评估',
+ '',
+ '### 影响与回滚',
+ '',
+ '- 影响范围:',
+ ...shown,
+ '- 回滚 / 降级方式:回滚本 PR',
+ '',
+ '### 提交前检查',
+ '',
+ '- [x] 每个 commit 都带 DCO 签名(`git commit -s`,见 [DCO](../DCO))',
+ '- [x] 未提交凭证、令牌或授权文件',
+ '',
+ '由 Cindy Make 制作。',
+ '',
+ ].join('\n');
+}
+
+/**
+ * Turns one recorded change into an official pull request through the repository's
+ * normal flow: a single DCO-signed commit by the author on top of the latest
+ * official `main`, pushed to the author's fork, opened against `makecindy/cindy`.
+ * Only this change is included; the author's other personal changes stay out.
+ */
+export class PersonalContribution {
+ private statusCache: { at: number; states: Map<number, CindyMakeContributionState> } | undefined;
+ /** Only Main can issue a confirmation for the exact source shown in a draft. */
+ private readonly snapshots = new Map<string, ContributionSnapshot>();
+
+ constructor(private readonly deps: ContributionDeps) {}
+
+ private async requireBinding(): Promise<{ repository: string; identity: GithubIdentity }> {
+ const record = this.deps.binding();
+ if (!record.repository || !isGithubRepository(record.repository) || record.choice !== 'github')
+ throw fail('notBound');
+ const identity = await this.deps.identity();
+ if (identity.status !== 'connected') throw fail('github');
+ if (!sameGithubLogin(record.login, identity.identity.login)) throw fail('account');
+ // The saved name must still be this account's official fork: after a deletion,
+ // an unrelated repository can answer under it, and nothing is ever pushed there.
+ try {
+ await this.deps.inspectFork(identity.identity, record.repository);
+ } catch (error) {
+ const code = error instanceof PersonalRemoteError ? error.code : undefined;
+ throw fail(
+ code === 'forkMissing'
+ ? 'notBound'
+ : code === 'github'
+ ? 'github'
+ : code === 'network'
+ ? 'network'
+ : 'failed',
+ );
+ }
+ return { repository: record.repository, identity: identity.identity };
+ }
+
+ /**
+ * Every owner-scoped read or write of a submission belongs to the account that
+ * started it: a Cindy account switch in the middle of the awaits must not read
+ * another account's history, push with its identity or write its ledger.
+ */
+ private assertScope(scope: string): void {
+ if (this.deps.ownerScope() !== scope) throw fail('account');
+ }
+
+ private requireChange(runId: string, scope: string): ContributionChange {
+ if (!RUN_ID.test(runId)) throw fail('invalid');
+ this.assertScope(scope);
+ const change = this.deps.change(runId);
+ if (!change || !HASH.test(change.baseTree) || !HASH.test(change.tree))
+ throw fail('unavailable');
+ if (change.baseTree === change.tree) throw fail('empty');
+ return { ...change };
+ }
+
+ private assertSnapshot(snapshot: ContributionSnapshot): void {
+ this.assertScope(snapshot.scope);
+ const binding = this.deps.binding();
+ const current = this.deps.change(snapshot.runId);
+ if (
+ this.deps.ledgerPath() !== snapshot.ledger ||
+ binding.choice !== 'github' ||
+ binding.repository?.toLowerCase() !== snapshot.repository.toLowerCase() ||
+ !sameGithubLogin(binding.login, snapshot.login) ||
+ !current ||
+ current.baseTree !== snapshot.change.baseTree ||
+ current.tree !== snapshot.change.tree ||
+ current.title !== snapshot.change.title ||
+ current.request !== snapshot.change.request
+ )
+ throw fail('changed');
+ }
+
+ private git(args: string[], options?: PersonalRemoteGitOptions): Promise<string> {
+ return this.deps.git(args, this.deps.source, options);
+ }
+
+ private async changedFiles(change: ContributionChange): Promise<string[]> {
+ let temporary: string | undefined;
+ try {
+ // The confirmation must describe the whole patch, including UI paths past
+ // runSourceGit's stdout capture limit. Keep the NUL-delimited list on disk
+ // so neither truncation nor stdout trimming can hide submitted paths.
+ temporary = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-contribution-files-'));
+ const file = path.join(temporary, 'paths');
+ await this.git([
+ 'diff',
+ '--name-only',
+ '--no-renames',
+ '--no-ext-diff',
+ '--no-textconv',
+ '-z',
+ '--output=' + file,
+ change.baseTree,
+ change.tree,
+ '--',
+ ]);
+ const output = await readFile(file, 'utf8');
+ if (output && !output.endsWith('\0')) throw fail('unavailable');
+ return output.split('\0').filter(Boolean);
+ } catch {
+ throw fail('unavailable');
+ } finally {
+ if (temporary) await rm(temporary, { recursive: true, force: true }).catch(() => undefined);
+ }
+ }
+
+ /** The author's real identity: their Git configuration, then their public GitHub profile. */
+ private async author(identity: GithubIdentity): Promise<{ name: string; email: string }> {
+ const local = await this.deps
+ .gitIdentity()
+ .catch(() => ({}) as { name?: string; email?: string });
+ let name = local.name?.trim() ?? '';
+ let email = local.email?.trim() ?? '';
+ if (!name || !email) {
+ try {
+ const response = await this.deps.fetch(`${API}/user`, {
+ headers: githubHeaders(identity.token),
+ redirect: 'error',
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (response.ok) {
+ const profile = (await response.json()) as { name?: unknown; email?: unknown };
+ if (!name && typeof profile.name === 'string') name = profile.name.trim();
+ if (!email && typeof profile.email === 'string') email = profile.email.trim();
+ } else await response.body?.cancel();
+ } catch {
+ // The author fills in what is missing in the confirmation dialog.
+ }
+ }
+ return { name: name || identity.login, email: isContributionEmail(email) ? email : '' };
+ }
+
+ private view(
+ record: ContributionRecord,
+ state?: CindyMakeContributionState,
+ ): CindyMakeContributionView {
+ return {
+ runId: record.runId,
+ number: record.number,
+ url: record.url,
+ submittedAt: record.submittedAt,
+ ...(state ? { state } : {}),
+ };
+ }
+
+ async draft(runId: string): Promise<CindyMakeContributionDraft> {
+ const scope = this.deps.ownerScope();
+ const ledger = this.deps.ledgerPath();
+ const { repository, identity } = await this.requireBinding();
+ const change = this.requireChange(runId, scope);
+ const files = await this.changedFiles(change);
+ const touchesUi = files.some(touchesUiPath);
+ const title = `feat: ${change.title.trim() || change.request.trim().split('\n')[0]}`.slice(
+ 0,
+ CONTRIBUTION_LIMITS.title,
+ );
+ const author = await this.author(identity);
+ this.assertScope(scope);
+ const existing = this.deps.readStore(ledger)[runId];
+ const state = existing && (await this.pullState(existing, githubHeaders(identity.token)));
+ const snapshot = { scope, ledger, runId, repository, login: identity.login, change };
+ this.assertSnapshot(snapshot);
+ const snapshotId = randomUUID();
+ this.snapshots.set(snapshotId, snapshot);
+ // A closed dialog need not retain its confirmation forever. Evicted drafts
+ // fail closed and can be reopened; no source or author data is persisted here.
+ if (this.snapshots.size > 64) this.snapshots.delete(this.snapshots.keys().next().value!);
+ return {
+ runId,
+ snapshotId,
+ title,
+ body: contributionBody({ title, request: change.request, files, touchesUi }),
+ ...author,
+ files,
+ touchesUi,
+ repository,
+ ...(existing ? { existing: this.view(existing, state) } : {}),
+ };
+ }
+
+ private async pullState(
+ record: ContributionRecord,
+ headers: Record<string, string>,
+ ): Promise<CindyMakeContributionState | undefined> {
+ try {
+ const response = await this.deps.fetch(
+ `${API}/repos/${OFFICIAL_GITHUB_REPOSITORY}/pulls/${record.number}`,
+ { method: 'GET', headers, redirect: 'error', signal: AbortSignal.timeout(15_000) },
+ );
+ if (!response.ok) {
+ await response.body?.cancel();
+ return undefined;
+ }
+ const pull = (await response.json()) as { state?: unknown; merged_at?: unknown };
+ return pull.merged_at ? 'merged' : pull.state === 'closed' ? 'closed' : 'open';
+ } catch {
+ // Unknown state is shown as "submitted"; nothing is guessed.
+ return undefined;
+ }
+ }
+
+ /** PR states for submitted changes; cached briefly so the history list stays cheap. */
+ async statuses(): Promise<CindyMakeContributionView[]> {
+ const records = Object.values(this.deps.readStore(this.deps.ledgerPath()));
+ if (!records.length) return [];
+ if (!this.statusCache || this.deps.now() - this.statusCache.at > 5 * 60_000) {
+ const states = new Map<number, CindyMakeContributionState>();
+ const identity = await this.deps.identity().catch(() => undefined);
+ const headers =
+ identity?.status === 'connected'
+ ? githubHeaders(identity.identity.token)
+ : { Accept: 'application/vnd.github+json' };
+ await Promise.all(
+ records.map(async (record) => {
+ const state = await this.pullState(record, headers);
+ if (state) states.set(record.number, state);
+ }),
+ );
+ this.statusCache = { at: this.deps.now(), states };
+ }
+ return records.map((record) => this.view(record, this.statusCache!.states.get(record.number)));
+ }
+
+ async submit(input: {
+ runId: string;
+ snapshotId: string;
+ title: string;
+ body: string;
+ name: string;
+ email: string;
+ }): Promise<CindyMakeContributionView> {
+ const title = input.title.trim();
+ const name = input.name.trim();
+ const email = input.email.trim();
+ if (
+ !title ||
+ title.length > CONTRIBUTION_LIMITS.title ||
+ /[\r\n]/.test(title) ||
+ input.body.length > CONTRIBUTION_LIMITS.body ||
+ !name ||
+ name.length > CONTRIBUTION_LIMITS.name ||
+ /[<>\r\n]/.test(name) ||
+ !isContributionEmail(email)
+ )
+ throw fail('invalid');
+ const scope = this.deps.ownerScope();
+ const ledger = this.deps.ledgerPath();
+ const snapshot = this.snapshots.get(input.snapshotId);
+ if (!snapshot || snapshot.runId !== input.runId) throw fail('changed');
+ this.assertSnapshot(snapshot);
+ const { repository, identity } = await this.requireBinding();
+ if (
+ repository.toLowerCase() !== snapshot.repository.toLowerCase() ||
+ !sameGithubLogin(identity.login, snapshot.login)
+ )
+ throw fail('changed');
+ const change = snapshot.change;
+ const auth = { repository, token: identity.token };
+ return this.deps.withSourceUse(async () => {
+ // 1. What an earlier submission's branch may receive is decided *before* any
+ // Git work: a pull request the maintainers closed keeps its branch and its
+ // commits exactly as they are, and the resubmission starts a new branch.
+ this.assertSnapshot(snapshot);
+ const store = this.deps.readStore(ledger);
+ const existing = store[input.runId];
+ const prior = existing
+ ? await this.pullState(existing, githubHeaders(identity.token))
+ : undefined;
+ // An unknown state never guesses: only a confirmed closed or merged pull
+ // request may be left behind for a new one — the dialog promised "update",
+ // and a transient lookup failure must not publish a second PR.
+ if (existing && prior === undefined) throw fail('network');
+ const updating = prior === 'open' ? existing : undefined;
+ // 2. The latest official main, independent of the personal version and its baseline.
+ try {
+ await this.git([
+ 'fetch',
+ '--no-tags',
+ '--no-write-fetch-head',
+ '--no-auto-maintenance',
+ OFFICIAL_URL,
+ `+refs/heads/main:${OFFICIAL_MAIN_REF}`,
+ ]);
+ } catch (error) {
+ throw fail(classifyRemoteGitError(error) === 'network' ? 'network' : 'failed');
+ }
+ const main = (
+ await this.git(['rev-parse', '--verify', `${OFFICIAL_MAIN_REF}^{commit}`])
+ ).trim();
+ if (!HASH.test(main)) throw fail('failed');
+
+ // 3. Only this change, applied to main in a private index; the checkout is untouched.
+ const temporary = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-contribution-'));
+ try {
+ const index = path.join(temporary, 'index');
+ const patch = path.join(temporary, 'change.patch');
+ const message = path.join(temporary, 'message');
+ await this.git(['read-tree', main], { indexFile: index });
+ await this.git([
+ 'diff',
+ '--binary',
+ '--full-index',
+ '--no-ext-diff',
+ '--no-textconv',
+ '--no-renames',
+ `--output=${patch}`,
+ change.baseTree,
+ change.tree,
+ '--',
+ ]);
+ try {
+ await this.git(['apply', '--cached', '--3way', '--whitespace=nowarn', patch], {
+ indexFile: index,
+ });
+ } catch {
+ throw fail('conflict');
+ }
+ if ((await this.git(['ls-files', '--unmerged'], { indexFile: index })).trim())
+ throw fail('conflict');
+ const tree = (await this.git(['write-tree'], { indexFile: index })).trim();
+ if (tree === (await this.git(['rev-parse', `${main}^{tree}`])).trim()) throw fail('empty');
+
+ // 4. One commit by the author, signed off with the same identity (DCO).
+ await writeFile(message, `${title}\n\nSigned-off-by: ${name} <${email}>\n`, 'utf8');
+ let commit = (
+ await this.git(
+ ['-c', 'commit.gpgSign=false', 'commit-tree', tree, '-p', main, '-F', message],
+ { indexFile: index, identity: { name, email } },
+ )
+ ).trim();
+ if (!HASH.test(commit)) throw fail('failed');
+
+ // 5. Push the branch to the author's fork, never rewriting an earlier one.
+ this.assertScope(scope);
+ const base = `cindy-make-pr/${input.runId.slice(0, 36)}`;
+ const push = (branch: string, lease: string) => {
+ // A task can finish another round while this operation awaits Git or
+ // GitHub, including while it waits for the source lock or retries a
+ // taken branch name. Never publish beyond the confirmed snapshot.
+ this.assertSnapshot(snapshot);
+ return this.git(
+ [
+ 'push',
+ '--porcelain',
+ '--no-verify',
+ '--no-follow-tags',
+ `--force-with-lease=refs/heads/${branch}:${lease}`,
+ PERSONAL_REMOTE_NAME,
+ `${commit}:refs/heads/${branch}`,
+ ],
+ { auth },
+ );
+ };
+ const pushFailed = (error: unknown) => {
+ if (error instanceof ContributionError) return error;
+ const code = classifyRemoteGitError(error);
+ return fail(
+ code === 'workflowScope' || code === 'github' || code === 'network' ? code : 'failed',
+ );
+ };
+ let branch = '';
+ let reconciled: ContributionRecord | undefined;
+ this.assertScope(scope);
+ if (updating) {
+ branch = updating.branch;
+ try {
+ await push(branch, updating.commit);
+ } catch (error) {
+ if (error instanceof ContributionError) throw error;
+ if (classifyRemoteGitError(error) !== 'failed') throw pushFailed(error);
+ // The lease only fails when the branch moved; retry once if it no longer exists.
+ const current = await this.git(
+ ['ls-remote', '--refs', PERSONAL_REMOTE_NAME, `refs/heads/${branch}`],
+ { auth },
+ ).catch((lookup: unknown) => {
+ throw pushFailed(lookup);
+ });
+ if (current.trim()) {
+ // The push may already have succeeded before a local ledger write
+ // failed. Reusing a remote tip is safe only when it is exactly the
+ // commit this submission intended (same tree, parent and author);
+ // an unrelated collaborator update keeps the lease failure fatal.
+ this.assertScope(scope);
+ const recovered = await this.reconcilePushedCommit(
+ branch,
+ remoteTip(current),
+ tree,
+ main,
+ { name, email },
+ auth,
+ );
+ this.assertScope(scope);
+ if (!recovered) throw pushFailed(error);
+ commit = recovered;
+ } else {
+ await push(branch, '').catch((retry: unknown) => {
+ throw pushFailed(retry);
+ });
+ }
+ }
+ // The moved branch is recorded before the PR API call and before any
+ // scope assertion — in the ledger pinned to the account that started the
+ // submission. If that call or an account switch interrupts, a retry
+ // leases against this commit instead of failing forever against a branch
+ // this client itself moved.
+ this.deps.writeStore(ledger, {
+ ...this.deps.readStore(ledger),
+ [input.runId]: { ...updating, commit },
+ });
+ this.assertScope(scope);
+ } else {
+ // The lease requires the branch not to exist yet, so an earlier submission's
+ // branch (whatever its pull request's state) is never rewritten.
+ for (let attempt = 0; ; attempt += 1) {
+ this.assertScope(scope);
+ const candidate = attempt ? `${base}-${attempt + 1}` : base;
+ try {
+ await push(candidate, '');
+ branch = candidate;
+ break;
+ } catch (error) {
+ if (error instanceof ContributionError) throw error;
+ // The name is taken — for example by the earlier submission's own
+ // branch, which is never rewritten — or the push failed; a taken
+ // name is retried under a new one.
+ if (classifyRemoteGitError(error) !== 'failed') throw pushFailed(error);
+ // Any occupied candidate can be this client's own earlier push whose
+ // pull request response was lost — the canonical name may belong to
+ // an earlier closed pull request, sending this change to `-2` before
+ // its own response is lost in turn. Reconcile the pull request of
+ // this exact candidate instead of publishing a second one, and only
+ // leave the name behind when it has no open pull request.
+ const found = await this.openPullFor(candidate, identity);
+ const tip = (
+ await this.git(
+ ['ls-remote', '--refs', PERSONAL_REMOTE_NAME, `refs/heads/${candidate}`],
+ { auth },
+ ).catch((lookup: unknown) => {
+ throw pushFailed(lookup);
+ })
+ )
+ .split(/\s/)[0]
+ ?.trim();
+ // Only a confirmed occupied name advances the suffix. An unrelated
+ // push failure must stop instead of retrying names indefinitely.
+ if (!tip || !HASH.test(tip)) throw pushFailed(error);
+ if (found) {
+ this.assertScope(scope);
+ await push(candidate, tip).catch((retry: unknown) => {
+ throw pushFailed(retry);
+ });
+ branch = candidate;
+ reconciled = found;
+ break;
+ }
+ }
+ }
+ }
+
+ // 6. Open the pull request, or update the one this change already has.
+ this.assertScope(scope);
+ const pull = await this.openPull({
+ identity,
+ branch,
+ title,
+ body: input.body,
+ existing: reconciled ?? updating,
+ });
+ this.assertScope(scope);
+ const record: ContributionRecord = {
+ runId: input.runId,
+ number: pull.number,
+ url: pull.url,
+ branch,
+ commit,
+ submittedAt: this.deps.now(),
+ };
+ this.deps.writeStore(ledger, { ...this.deps.readStore(ledger), [input.runId]: record });
+ this.statusCache = undefined;
+ try {
+ this.deps.onChanged?.(input.runId);
+ } catch {
+ // Resource invalidation is advisory; never turn a committed submission into a failure.
+ }
+ return this.view(record, 'open');
+ } finally {
+ await rm(temporary, { recursive: true, force: true });
+ }
+ });
+ }
+
+ /**
+ * A successful remote push can race the local contribution ledger write. On
+ * retry, adopt that remote commit only after fetching and checking its complete
+ * identity; never turn an arbitrary branch movement into this user's lease.
+ */
+ private async reconcilePushedCommit(
+ branch: string,
+ observed: string | undefined,
+ tree: string,
+ parent: string,
+ author: { name: string; email: string },
+ auth: { repository: string; token: string },
+ ): Promise<string | undefined> {
+ if (!observed) return undefined;
+ try {
+ await this.git(
+ [
+ 'fetch',
+ '--no-tags',
+ '--no-write-fetch-head',
+ '--no-auto-maintenance',
+ PERSONAL_REMOTE_NAME,
+ 'refs/heads/' + branch,
+ ],
+ { auth },
+ );
+ const current = remoteTip(
+ await this.git(['ls-remote', '--refs', PERSONAL_REMOTE_NAME, 'refs/heads/' + branch], { auth }),
+ );
+ if (current !== observed) return undefined;
+ if ((await this.git(['cat-file', '-t', observed])).trim() !== 'commit') return undefined;
+ if ((await this.git(['rev-parse', '--verify', observed + '^{tree}'])).trim() !== tree)
+ return undefined;
+ const parents = (await this.git(['show', '-s', '--format=%P', observed]))
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean);
+ if (parents.length !== 1 || parents[0] !== parent) return undefined;
+ const identity = (await this.git(['show', '-s', '--format=%an%x00%ae', observed])).trim();
+ if (identity !== author.name + '\0' + author.email) return undefined;
+ return observed;
+ } catch (error) {
+ const code = classifyRemoteGitError(error);
+ if (code === 'network' || code === 'github' || code === 'workflowScope') throw fail(code);
+ return undefined;
+ }
+ }
+
+ /** The open pull request an earlier attempt already opened for this branch. */
+ private async openPullFor(
+ branch: string,
+ identity: GithubIdentity,
+ ): Promise<ContributionRecord | undefined> {
+ let response: Response;
+ try {
+ response = await this.deps.fetch(
+ `${API}/repos/${OFFICIAL_GITHUB_REPOSITORY}/pulls?state=open&head=${encodeURIComponent(
+ `${identity.login}:${branch}`,
+ )}`,
+ {
+ method: 'GET',
+ headers: githubHeaders(identity.token),
+ redirect: 'error',
+ signal: AbortSignal.timeout(15_000),
+ },
+ );
+ } catch {
+ throw fail('network');
+ }
+ if (!response.ok) {
+ await response.body?.cancel();
+ // Unknown is not "no pull request": only a confirmed empty list lets the
+ // caller open a new branch, so a lookup failure aborts for a retry.
+ throw fail('network');
+ }
+ const body = (await response.json().catch(() => undefined)) as unknown;
+ if (!Array.isArray(body)) throw fail('network');
+ const first = body[0] as { number?: unknown; html_url?: unknown } | undefined;
+ if (!first) return undefined;
+ if (
+ !Number.isSafeInteger(first.number) ||
+ typeof first.html_url !== 'string' ||
+ !first.html_url.startsWith(`https://github.com/${OFFICIAL_GITHUB_REPOSITORY}/pull/`)
+ )
+ throw fail('failed');
+ return {
+ runId: '',
+ number: first.number as number,
+ url: first.html_url,
+ branch,
+ commit: '',
+ submittedAt: this.deps.now(),
+ };
+ }
+
+ private async openPull(input: {
+ identity: GithubIdentity;
+ branch: string;
+ title: string;
+ body: string;
+ existing?: ContributionRecord;
+ }): Promise<{ number: number; url: string; closed: boolean }> {
+ const request = async (url: string, init: RequestInit): Promise<Response> => {
+ try {
+ return await this.deps.fetch(url, {
+ ...init,
+ headers: { ...githubHeaders(input.identity.token), 'Content-Type': 'application/json' },
+ redirect: 'error',
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch {
+ throw fail('network');
+ }
+ };
+ const parse = async (
+ response: Response,
+ ): Promise<{ number: number; url: string; closed: boolean }> => {
+ const pull = (await response.json().catch(() => ({}))) as {
+ number?: unknown;
+ html_url?: unknown;
+ state?: unknown;
+ };
+ if (
+ !Number.isSafeInteger(pull.number) ||
+ typeof pull.html_url !== 'string' ||
+ !pull.html_url.startsWith(`https://github.com/${OFFICIAL_GITHUB_REPOSITORY}/pull/`)
+ )
+ throw fail('failed');
+ return { number: pull.number as number, url: pull.html_url, closed: pull.state === 'closed' };
+ };
+ const pulls = `${API}/repos/${OFFICIAL_GITHUB_REPOSITORY}/pulls`;
+ const update = async (number: number): Promise<{ number: number; url: string; closed: boolean }> => {
+ // The dialog promised "update": this pull request is edited in place. A state
+ // that changed under way (a maintainer closed it mid-flight) aborts instead of
+ // publishing a second PR the user never confirmed.
+ const current = await request(`${pulls}/${number}`, { method: 'GET' });
+ const open = current.ok ? !(await parse(current)).closed : false;
+ if (!current.ok) await current.body?.cancel();
+ if (!open) throw fail('failed');
+ const response = await request(`${pulls}/${number}`, {
+ method: 'PATCH',
+ // This commit contains only the confirmed change on official main. A
+ // maintainer may have retargeted the PR since the last submission.
+ body: JSON.stringify({ title: input.title, body: input.body, base: 'main' }),
+ });
+ if (response.ok) return parse(response);
+ await response.body?.cancel();
+ throw fail('failed');
+ };
+ if (input.existing) return update(input.existing.number);
+ const created = await request(pulls, {
+ method: 'POST',
+ body: JSON.stringify({
+ title: input.title,
+ body: input.body,
+ head: `${input.identity.login}:${input.branch}`,
+ base: 'main',
+ maintainer_can_modify: true,
+ }),
+ });
+ if (created.ok) return parse(created);
+ const status = created.status;
+ await created.body?.cancel();
+ if (status === 422) {
+ // GitHub refuses a duplicate; reuse the open pull request for this branch.
+ const listed = await request(
+ `${pulls}?state=open&head=${encodeURIComponent(`${input.identity.login}:${input.branch}`)}`,
+ { method: 'GET' },
+ );
+ if (listed.ok) {
+ const pullsFound = (await listed.json().catch(() => [])) as unknown[];
+ const first = Array.isArray(pullsFound) ? pullsFound[0] : undefined;
+ if (first) return update((await parse(new Response(JSON.stringify(first)))).number);
+ } else await listed.body?.cancel();
+ }
+ throw fail([401, 403, 404].includes(status) ? 'github' : 'failed');
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/personalRemote.ts b/apps/desktop/src/main/cindy-make/personalRemote.ts
new file mode 100644
index 0000000000..1c49e642c1
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/personalRemote.ts
@@ -0,0 +1,1730 @@
+import os from 'node:os';
+import path from 'node:path';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import type {
+ CindyMakePersonalRemoteState,
+ CindyMakeRemoteError,
+ CindyMakeRemoteStep,
+ CindyMakeRemoteSync,
+} from '../../shared/cindyMakePersonalRemote.js';
+import {
+ CINDY_MAKE_REMOTE_ERRORS,
+ CINDY_MAKE_REMOTE_SYNC,
+ isGithubLogin,
+ isGithubRepository,
+ sameGithubLogin,
+} from '../../shared/cindyMakePersonalRemote.js';
+import { assertNoGitOperation, commitPersonalFiles } from './localHistory.js';
+import { PERSONAL_UPSTREAM_REF, type ContentGit } from './sourceContent.js';
+import { uncarriedChanges } from './carriedChanges.js';
+import { CINDY_PERSONAL_BRANCH } from './sourcePaths.js';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+
+export const OFFICIAL_GITHUB_REPOSITORY = 'makecindy/cindy';
+/** Remote name for the user's fork; `origin` keeps pointing at the official repository. */
+export const PERSONAL_REMOTE_NAME = 'personal';
+const BRANCH_REF = `refs/heads/${CINDY_PERSONAL_BRANCH}`;
+/** The fork's personal version as last fetched by a sync. */
+export const PERSONAL_TRACKING_REF = `refs/remotes/${PERSONAL_REMOTE_NAME}/${CINDY_PERSONAL_BRANCH}`;
+const TRACKING_REF = PERSONAL_TRACKING_REF;
+/** The official commit the shared personal version is based on, published next to it. */
+export const PERSONAL_BASE_BRANCH = `${CINDY_PERSONAL_BRANCH}-base`;
+const BASE_BRANCH_REF = `refs/heads/${PERSONAL_BASE_BRANCH}`;
+const BASE_TRACKING_REF = `refs/remotes/${PERSONAL_REMOTE_NAME}/${PERSONAL_BASE_BRANCH}`;
+const COMMIT = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i;
+/** Same identity as `MAKE_GIT_IDENTITY`, for commits written through the environment. */
+const MAKE_IDENTITY = { name: 'Cindy Make', email: '[email protected]' };
+const FORK_WAIT_MS = 5 * 60_000;
+const API = 'https://api.github.com';
+
+type RemoteRunKind = NonNullable<CindyMakePersonalRemoteState['running']>;
+
+/**
+ * Persisted binding. It lives beside the managed checkout rather than inside it,
+ * so clearing the source keeps the user's decision and bound repository.
+ */
+export interface PersonalRewrite {
+ /** This computer's version before the rewrite, then any GitHub version combined into it. */
+ from: string[];
+ to: string;
+}
+const MAX_REWRITES = 16;
+/**
+ * Unverified sources are kept until a generated personal version covers them.
+ * The bounded list is diagnostic storage; if it fills, an overflow marker keeps
+ * the install decision fail-closed instead of evicting a live source.
+ */
+const MAX_UNVERIFIED_REMOTE = 512;
+
+export interface PersonalRemoteRecord {
+ schema: 1;
+ choice?: 'github' | 'local';
+ login?: string;
+ repository?: string;
+ confirmedAt?: number;
+ sync?: CindyMakeRemoteSync;
+ syncedAt?: number;
+ /** Local commit this computer last confirmed on the fork; it may replace only its own upload. */
+ syncedCommit?: string;
+ /**
+ * Adopted history rewrites (official updates and combines), oldest first: every
+ * commit in `from` is contained in `to`. They prove an upload that replaces the
+ * fork's version loses nothing even when the rewrite changed patches.
+ */
+ rewrites?: PersonalRewrite[];
+ /**
+ * Fork tips this computer took over before generating a personal version that
+ * covers them. Their content is not verified yet: the automatic task install
+ * must not run lifecycle scripts on worktrees that contain them.
+ */
+ unverifiedRemote?: string[];
+ /** True when an older source tip could not fit in the bounded list; this is fail-closed. */
+ unverifiedRemoteOverflow?: boolean;
+ error?: CindyMakeRemoteError;
+ /** Present only while an operation runs; a restart turns it into `interrupted`. */
+ running?: RemoteRunKind;
+}
+
+const isTimestamp = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
+const oneOf = <T extends string>(values: readonly T[], value: unknown): value is T =>
+ typeof value === 'string' && (values as readonly string[]).includes(value);
+
+/** Unknown or corrupt content falls back to "never decided"; it never invents a binding. */
+export function parsePersonalRemoteRecord(raw: string | null): PersonalRemoteRecord {
+ if (raw === null) return { schema: 1 };
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ return { schema: 1 };
+ }
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { schema: 1 };
+ const input = value as Record<string, unknown>;
+ if (input.schema !== 1) return { schema: 1 };
+ const record: PersonalRemoteRecord = { schema: 1 };
+ if (input.choice === 'github' || input.choice === 'local') record.choice = input.choice;
+ if (
+ isGithubLogin(input.login) &&
+ isGithubRepository(input.repository) &&
+ sameGithubLogin(input.login, input.repository.split('/')[0])
+ ) {
+ record.login = input.login;
+ record.repository = input.repository;
+ if (isTimestamp(input.confirmedAt)) record.confirmedAt = input.confirmedAt;
+ if (oneOf(CINDY_MAKE_REMOTE_SYNC, input.sync)) record.sync = input.sync;
+ if (isTimestamp(input.syncedAt)) record.syncedAt = input.syncedAt;
+ if (typeof input.syncedCommit === 'string' && COMMIT.test(input.syncedCommit))
+ record.syncedCommit = input.syncedCommit;
+ }
+ if (Array.isArray(input.unverifiedRemote)) {
+ const tips = input.unverifiedRemote.filter(
+ (tip): tip is string => typeof tip === 'string' && COMMIT.test(tip),
+ );
+ if (tips.length) record.unverifiedRemote = [...new Set(tips)].slice(-MAX_UNVERIFIED_REMOTE);
+ }
+ if (input.unverifiedRemoteOverflow === true) record.unverifiedRemoteOverflow = true;
+ // Rewrite lineage is provenance of already-taken-over content, not binding
+ // state: it survives a disconnect (where `login`/`repository` are cleared) or
+ // it would silently orphan the unverified tips it carries.
+ if (Array.isArray(input.rewrites)) {
+ const rewrites = input.rewrites.filter(
+ (entry): entry is PersonalRewrite =>
+ !!entry &&
+ typeof entry === 'object' &&
+ Array.isArray((entry as PersonalRewrite).from) &&
+ (entry as PersonalRewrite).from.length > 0 &&
+ (entry as PersonalRewrite).from.length <= 2 &&
+ (entry as PersonalRewrite).from.every(
+ (commit) => typeof commit === 'string' && COMMIT.test(commit),
+ ) &&
+ typeof (entry as PersonalRewrite).to === 'string' &&
+ COMMIT.test((entry as PersonalRewrite).to),
+ );
+ if (rewrites.length) record.rewrites = rewrites.slice(-MAX_REWRITES);
+ }
+ if (oneOf(CINDY_MAKE_REMOTE_ERRORS, input.error)) record.error = input.error;
+ if (input.running === 'save' || input.running === 'sync' || input.running === 'disconnect')
+ record.running = input.running;
+ return record;
+}
+
+/**
+ * The content-trust facts of a record file, for the install decision. A missing
+ * file proves there is nothing to carry; corrupt content or an unknown schema
+ * proves nothing and must never read as "no unverified content" — it throws so
+ * the install keeps its guarded path (anything unclear counts as unverified).
+ */
+export function parsePersonalRemoteTrust(
+ raw: string | null,
+): Pick<PersonalRemoteRecord, 'unverifiedRemote' | 'unverifiedRemoteOverflow' | 'rewrites'> {
+ if (raw === null) return {};
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ throw new Error('unprovable content trust');
+ }
+ if (
+ !value ||
+ typeof value !== 'object' ||
+ Array.isArray(value) ||
+ (value as { schema?: unknown }).schema !== 1
+ )
+ throw new Error('unprovable content trust');
+ const record = parsePersonalRemoteRecord(raw);
+ // A malformed trust field proves nothing either: the entries a lenient parse
+ // drops could be the very sources still on disk, so silence must never read as
+ // "no unverified content".
+ const input = value as Record<string, unknown>;
+ const rawTips = input.unverifiedRemote;
+ if (
+ rawTips !== undefined &&
+ (!Array.isArray(rawTips) ||
+ rawTips.length > MAX_UNVERIFIED_REMOTE ||
+ rawTips.some((tip) => typeof tip !== 'string' || !COMMIT.test(tip)))
+ )
+ throw new Error('unprovable content trust');
+ if (input.unverifiedRemoteOverflow !== undefined && input.unverifiedRemoteOverflow !== true)
+ throw new Error('unprovable content trust');
+ const rawRewrites = input.rewrites;
+ const wellFormedRewrite = (entry: unknown): boolean => {
+ const rewrite = entry as { from?: unknown; to?: unknown } | null;
+ return (
+ !!rewrite &&
+ typeof rewrite === 'object' &&
+ Array.isArray(rewrite.from) &&
+ rewrite.from.length > 0 &&
+ rewrite.from.length <= 2 &&
+ rewrite.from.every((commit) => typeof commit === 'string' && COMMIT.test(commit)) &&
+ typeof rewrite.to === 'string' &&
+ COMMIT.test(rewrite.to)
+ );
+ };
+ if (rawRewrites !== undefined && (!Array.isArray(rawRewrites) || !rawRewrites.every(wellFormedRewrite)))
+ throw new Error('unprovable content trust');
+ return {
+ ...(record.unverifiedRemote ? { unverifiedRemote: record.unverifiedRemote } : {}),
+ ...(record.unverifiedRemoteOverflow ? { unverifiedRemoteOverflow: true } : {}),
+ ...(record.rewrites ? { rewrites: record.rewrites } : {}),
+ };
+}
+
+/** Persist a binding together with the content-trust facts kept beside the source. */
+export function writePersonalRemoteRecord(file: string, record: PersonalRemoteRecord): void {
+ // A lenient state read is useful for rendering, but never let a write turn a
+ // malformed trust field into a valid record that makes unverified content look
+ // safe. The existing bytes must be proven before they can be replaced.
+ parsePersonalRemoteTrust(readAtomicFileSync(file));
+ atomicWriteFileSync(file, JSON.stringify(record));
+}
+
+export class PersonalRemoteError extends Error {
+ constructor(readonly code: CindyMakeRemoteError) {
+ super(code);
+ }
+}
+const remoteError = (code: CindyMakeRemoteError) => new PersonalRemoteError(code);
+
+/** Map a redacted Git failure to a user-facing reason without keeping its output. */
+export function classifyRemoteGitError(error: unknown): CindyMakeRemoteError {
+ if (error instanceof PersonalRemoteError) return error.code;
+ const failure = error as { code?: unknown; stderr?: unknown } | undefined;
+ if (failure?.code === 'cancelled') return 'network';
+ if (failure?.code === 'busy' || failure?.code === 'dirty') return 'source';
+ const text = typeof failure?.stderr === 'string' ? failure.stderr : '';
+ if (/workflow/i.test(text) && /(scope|permission|refusing)/i.test(text)) return 'workflowScope';
+ if (
+ /(authentication failed|could not read username|terminal prompts disabled|permission to .* denied|invalid username or password|returned error: 40[13])/i.test(
+ text,
+ )
+ )
+ return 'github';
+ if (
+ /(could not resolve host|failed to connect|timed out|connection (?:reset|refused|was reset)|unable to access|network is unreachable|ssl|tls)/i.test(
+ text,
+ )
+ )
+ return 'network';
+ return 'failed';
+}
+
+export interface GithubIdentity {
+ login: string;
+ token: string;
+}
+export type GithubIdentityResult =
+ { status: 'connected'; identity: GithubIdentity } | { status: 'missing' | 'unavailable' };
+
+const githubHeaders = (token: string): Record<string, string> => ({
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/vnd.github+json',
+ 'X-GitHub-Api-Version': '2022-11-28',
+});
+
+/** The token stays in memory for the caller; it is never part of any returned state. */
+export async function readGithubIdentity(deps: {
+ readToken(): Promise<string | null>;
+ fetch: typeof fetch;
+}): Promise<GithubIdentityResult> {
+ let token: string | null;
+ try {
+ token = await deps.readToken();
+ } catch {
+ return { status: 'unavailable' };
+ }
+ if (!token) return { status: 'missing' };
+ try {
+ const response = await deps.fetch(`${API}/user`, {
+ headers: githubHeaders(token),
+ redirect: 'error',
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!response.ok) {
+ await response.body?.cancel();
+ // An expired or revoked credential needs a new connection, not a retry.
+ return { status: response.status === 401 ? 'missing' : 'unavailable' };
+ }
+ const data = (await response.json()) as { login?: unknown };
+ return isGithubLogin(data.login)
+ ? { status: 'connected', identity: { login: data.login, token } }
+ : { status: 'unavailable' };
+ } catch {
+ return { status: 'unavailable' };
+ }
+}
+
+interface GithubRepositoryInfo {
+ full_name?: unknown;
+ fork?: unknown;
+ owner?: { login?: unknown };
+ parent?: { full_name?: unknown };
+ source?: { full_name?: unknown };
+}
+
+/**
+ * Create the user's fork, or receive the existing one: GitHub answers a repeated
+ * fork request with the account's current fork, including a renamed one. Only a
+ * fork of the official repository owned by the connected login is accepted.
+ * When another fork cannot be created any more (422) instead of that repository
+ * being returned, the account's existing fork is located and validated exactly
+ * as strictly as a creation response.
+ */
+export async function ensureOfficialFork(
+ fetchFn: typeof fetch,
+ identity: GithubIdentity,
+): Promise<string> {
+ const request = async (
+ url: string,
+ init: RequestInit,
+ /** The create request reuses the account's existing fork on 422 instead of failing. */
+ tolerate422 = false,
+ ): Promise<GithubRepositoryInfo | undefined> => {
+ let response: Response;
+ try {
+ response = await fetchFn(url, {
+ ...init,
+ headers: { ...githubHeaders(identity.token), ...(init.headers as Record<string, string>) },
+ redirect: 'error',
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch {
+ throw remoteError('network');
+ }
+ if (!response.ok) {
+ await response.body?.cancel();
+ if ([401, 403, 404].includes(response.status)) throw remoteError('github');
+ if (tolerate422 && response.status === 422) return undefined;
+ throw remoteError(response.status === 422 ? 'forkConflict' : 'failed');
+ }
+ try {
+ return (await response.json()) as GithubRepositoryInfo;
+ } catch {
+ throw remoteError('failed');
+ }
+ };
+ /** A read that only proves a credential works: a missing or redirected address is absent. */
+ const read = async (url: string): Promise<unknown> => {
+ let response: Response;
+ try {
+ response = await fetchFn(url, {
+ method: 'GET',
+ headers: githubHeaders(identity.token),
+ // A renamed fork answers the saved name with a redirect; it is never
+ // followed with the credential. The listing below finds the new name.
+ redirect: 'manual',
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch {
+ throw remoteError('network');
+ }
+ if (!response.ok) {
+ await response.body?.cancel();
+ if ([401, 403].includes(response.status)) throw remoteError('github');
+ return undefined;
+ }
+ return (await response.json().catch(() => undefined)) as unknown;
+ };
+ const official = (name: unknown) =>
+ typeof name === 'string' && name.toLowerCase() === OFFICIAL_GITHUB_REPOSITORY;
+ /** The strict check of a creation response also applies to a located fork. */
+ const accepted = (repository: GithubRepositoryInfo): string | undefined => {
+ const name = repository.full_name;
+ return isGithubRepository(name) &&
+ repository.fork === true &&
+ sameGithubLogin(name.split('/')[0], identity.login) &&
+ sameGithubLogin(
+ typeof repository.owner?.login === 'string' ? repository.owner.login : undefined,
+ identity.login,
+ ) &&
+ (official(repository.parent?.full_name) || official(repository.source?.full_name))
+ ? name
+ : undefined;
+ };
+ /** The account's own fork of the official repository, wherever it was renamed to. */
+ const existingFork = async (): Promise<GithubRepositoryInfo> => {
+ const canonical = await read(`${API}/repos/${identity.login}/cindy`);
+ if (canonical && accepted(canonical as GithubRepositoryInfo))
+ return canonical as GithubRepositoryInfo;
+ // Follow the pages to the end: a fork outside the first screens must still be
+ // found, because the create endpoint cannot make a second one.
+ for (let page = 1; ; page += 1) {
+ const listed = await read(
+ `${API}/user/repos?per_page=100&page=${page}&affiliation=owner&sort=pushed`,
+ );
+ if (!Array.isArray(listed)) break;
+ for (const entry of listed as Array<{ full_name?: unknown; fork?: unknown }>) {
+ if (entry?.fork !== true || !isGithubRepository(entry.full_name)) continue;
+ const full = await read(`${API}/repos/${entry.full_name}`);
+ if (full && accepted(full as GithubRepositoryInfo)) return full as GithubRepositoryInfo;
+ }
+ if ((listed as unknown[]).length < 100) break;
+ }
+ throw remoteError('forkConflict');
+ };
+ let repository = await request(
+ `${API}/repos/${OFFICIAL_GITHUB_REPOSITORY}/forks`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ default_branch_only: true }),
+ },
+ true,
+ );
+ if (!repository) repository = await existingFork();
+ else if (
+ isGithubRepository(repository.full_name) &&
+ repository.parent === undefined &&
+ repository.source === undefined
+ )
+ repository = await request(`${API}/repos/${repository.full_name}`, { method: 'GET' });
+ const name = repository ? accepted(repository) : undefined;
+ if (!name) throw remoteError('forkConflict');
+ return name;
+}
+
+/**
+ * The history rewrite an adopted official update or combine made: this computer's
+ * version (and the GitHub version combined into it) became `to`. It is the lineage
+ * that lets an upload replace the fork's version without losing a change.
+ */
+export function adoptedRewrite(state: {
+ status: string;
+ feature?: unknown;
+ baselineCommit?: string;
+ commit?: string;
+ remote?: { commit?: string };
+}): PersonalRewrite | undefined {
+ if (state.status !== 'merged' || state.feature || !state.baselineCommit || !state.commit)
+ return undefined;
+ return {
+ from: [
+ state.baselineCommit,
+ ...(state.remote?.commit && state.remote.commit !== state.baselineCommit
+ ? [state.remote.commit]
+ : []),
+ ],
+ to: state.commit,
+ };
+}
+
+export interface PersonalForkHealth {
+ /** The repository's current name; GitHub keeps serving Git under an old one after a rename. */
+ repository: string;
+ archived: boolean;
+ canPush: boolean;
+}
+
+/**
+ * The bound repository as GitHub sees it now. A renamed repository is followed through
+ * GitHub's redirect to its id (once, on the API host); the caller accepts the new name
+ * only under the same account. A deleted one is reported, never recreated.
+ */
+export async function inspectPersonalFork(
+ fetchFn: typeof fetch,
+ identity: GithubIdentity,
+ repository: string,
+ followRename = true,
+): Promise<PersonalForkHealth> {
+ let response: Response;
+ try {
+ // `repository` is `<owner>/<name>`, or the by-id address GitHub redirected to.
+ response = await fetchFn(followRename ? `${API}/repos/${repository}` : repository, {
+ headers: githubHeaders(identity.token),
+ // A renamed repository answers with a redirect; it is never followed with the credential.
+ redirect: 'manual',
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch {
+ throw remoteError('network');
+ }
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ // Renamed or transferred: GitHub points at the repository by id on its own API host.
+ const location = response.headers.get('location') ?? '';
+ const moved = /^https:\/\/api\.github\.com\/repositories\/\d{1,20}$/.test(location);
+ if (moved && followRename) return inspectPersonalFork(fetchFn, identity, location, false);
+ if (response.status === 404 || (response.status >= 300 && response.status < 400))
+ throw remoteError('forkMissing');
+ throw remoteError([401, 403].includes(response.status) ? 'github' : 'failed');
+ }
+ let info: {
+ full_name?: unknown;
+ archived?: unknown;
+ fork?: unknown;
+ owner?: { login?: unknown };
+ parent?: { full_name?: unknown };
+ source?: { full_name?: unknown };
+ permissions?: { push?: unknown };
+ };
+ try {
+ info = (await response.json()) as typeof info;
+ } catch {
+ throw remoteError('failed');
+ }
+ if (!isGithubRepository(info.full_name)) throw remoteError('failed');
+ // The saved name must still be this account's fork of the official repository:
+ // after the fork was deleted, an unrelated repository can answer under the same
+ // name, and the managed branches must never be pushed into it. A stale binding
+ // is reported (like a deleted one), never used.
+ const official = (name: unknown) =>
+ typeof name === 'string' && name.toLowerCase() === OFFICIAL_GITHUB_REPOSITORY;
+ if (
+ info.fork !== true ||
+ !sameGithubLogin(
+ typeof info.owner?.login === 'string' ? info.owner.login : undefined,
+ identity.login,
+ ) ||
+ !(official(info.parent?.full_name) || official(info.source?.full_name))
+ )
+ throw remoteError('forkMissing');
+ return {
+ repository: info.full_name,
+ archived: info.archived === true,
+ canPush: info.permissions?.push !== false,
+ };
+}
+
+/**
+ * Read-only probe before consent: does the account's usual fork already hold a
+ * personal version (another computer saved it)? A renamed fork is found later by
+ * the fork request itself; this only adjusts what the consent card says.
+ */
+export async function findPersonalFork(
+ fetchFn: typeof fetch,
+ identity: GithubIdentity,
+): Promise<string | undefined> {
+ const read = async (url: string): Promise<Response | undefined> => {
+ try {
+ return await fetchFn(url, {
+ headers: githubHeaders(identity.token),
+ redirect: 'error',
+ signal: AbortSignal.timeout(15_000),
+ });
+ } catch {
+ return undefined;
+ }
+ };
+ const repository = `${identity.login}/cindy`;
+ if (!isGithubRepository(repository)) return undefined;
+ const info = await read(`${API}/repos/${repository}`);
+ if (!info?.ok) {
+ await info?.body?.cancel();
+ return undefined;
+ }
+ const data = (await info.json().catch(() => ({}))) as GithubRepositoryInfo;
+ const official = (name: unknown) =>
+ typeof name === 'string' && name.toLowerCase() === OFFICIAL_GITHUB_REPOSITORY;
+ if (
+ data.fork !== true ||
+ !isGithubRepository(data.full_name) ||
+ !(official(data.parent?.full_name) || official(data.source?.full_name))
+ )
+ return undefined;
+ const branch = await read(`${API}/repos/${data.full_name}/branches/${CINDY_PERSONAL_BRANCH}`);
+ await branch?.body?.cancel();
+ return branch?.ok ? data.full_name : undefined;
+}
+
+export function githubRepositoryUrl(repository: string): string {
+ if (!isGithubRepository(repository)) throw remoteError('failed');
+ return `https://github.com/${repository}.git`;
+}
+
+/**
+ * Credentials for one Git child process. The header is scoped to the exact fork
+ * URL through `GIT_CONFIG_*`, so it never appears in argv, `.git/config`, the
+ * remote URL, or logs. Credential helpers and askpass prompts are disabled so
+ * a rejected token fails instead of opening a system credential dialog, and
+ * repository hooks never run with the credential in their environment.
+ */
+export function githubAuthEnv(
+ repository: string,
+ token: string,
+ base: NodeJS.ProcessEnv,
+): NodeJS.ProcessEnv {
+ const existing = Number.parseInt(base.GIT_CONFIG_COUNT ?? '', 10);
+ const start = Number.isSafeInteger(existing) && existing > 0 ? existing : 0;
+ const entries: Array<[string, string]> = [
+ [
+ `http.${githubRepositoryUrl(repository)}.extraheader`,
+ `AUTHORIZATION: basic ${Buffer.from(`x-access-token:${token}`).toString('base64')}`,
+ ],
+ ['credential.helper', ''],
+ ['credential.https://github.com.helper', ''],
+ // Repository hooks and fsmonitor programs must not run with the credential in their environment.
+ ['core.hooksPath', os.devNull],
+ ['core.fsmonitor', 'false'],
+ ];
+ const env: NodeJS.ProcessEnv = {
+ ...base,
+ GIT_ASKPASS: '',
+ SSH_ASKPASS: '',
+ GIT_TERMINAL_PROMPT: '0',
+ GIT_CONFIG_COUNT: String(start + entries.length),
+ };
+ entries.forEach(([key, value], index) => {
+ env[`GIT_CONFIG_KEY_${start + index}`] = key;
+ env[`GIT_CONFIG_VALUE_${start + index}`] = value;
+ });
+ return env;
+}
+
+/** A commit identity applied through the environment, which outranks any Git configuration. */
+export interface GitCommitIdentity {
+ name: string;
+ email: string;
+ /** Git internal date format (`<unix seconds> <+hhmm>`); omitted means now. */
+ date?: string;
+}
+
+export interface PersonalRemoteGitOptions {
+ auth?: { repository: string; token: string };
+ indexFile?: string;
+ identity?: GitCommitIdentity;
+}
+
+/** Process environment for one Git command run on behalf of the personal version. */
+export function personalGitEnv(
+ base: NodeJS.ProcessEnv,
+ options?: PersonalRemoteGitOptions,
+): NodeJS.ProcessEnv {
+ let env: NodeJS.ProcessEnv = options?.indexFile
+ ? { ...base, GIT_INDEX_FILE: options.indexFile }
+ : base;
+ if (options?.identity) {
+ const { name, email, date } = options.identity;
+ env = {
+ ...env,
+ GIT_AUTHOR_NAME: name,
+ GIT_AUTHOR_EMAIL: email,
+ GIT_COMMITTER_NAME: name,
+ GIT_COMMITTER_EMAIL: email,
+ };
+ if (date) env.GIT_AUTHOR_DATE = date;
+ else delete env.GIT_AUTHOR_DATE;
+ delete env.GIT_COMMITTER_DATE;
+ }
+ return options?.auth ? githubAuthEnv(options.auth.repository, options.auth.token, env) : env;
+}
+
+export interface PersonalRemoteDeps {
+ /** The managed checkout that owns `cindy-personal`. */
+ source: string;
+ read(): PersonalRemoteRecord;
+ /** Refuse to rewrite the record while trust-bearing fields are malformed. */
+ assertTrust?(): void;
+ write(record: PersonalRemoteRecord): void;
+ identity(): Promise<GithubIdentityResult>;
+ ensureFork(identity: GithubIdentity): Promise<string>;
+ /** The account's official fork that already holds a personal version, if any. */
+ findPersonalFork(identity: GithubIdentity): Promise<string | undefined>;
+ /** The bound repository as GitHub sees it now (see `inspectPersonalFork`). */
+ inspectFork?(identity: GithubIdentity, repository: string): Promise<PersonalForkHealth>;
+ git(args: string[], cwd: string, options?: PersonalRemoteGitOptions): Promise<string>;
+ sourceExists(): boolean;
+ /** Serialize with every other Git write to the managed source. */
+ withProject<T>(run: () => Promise<T>): Promise<T>;
+ /** Keep the checkout from being cleared for the whole operation, including network phases. */
+ withSourceUse<T>(run: () => Promise<T>): Promise<T>;
+ /** True while the commit carries integrations a failed generation could still undo. */
+ hasUnbuiltChanges(commit: string, tree: string): Promise<boolean>;
+ /**
+ * The source is about to move to a snapshot carrying changes that are not
+ * generated on this computer yet (another device's, or another account's whose
+ * history this one may not read). Recorded with the snapshot it describes so
+ * the fact travels with the source (see `pendingBuild`).
+ */
+ recordUnbuilt?(snapshot: { commit: string; tree: string }): void;
+ /** A generated personal version was built from this commit. */
+ isBuilt(commit: string): boolean;
+ /** No generation, unresolved official update or manual source sync owns `cindy-personal`. */
+ /** `withinSync`: Sync holds the source reservation itself, which does not count as busy. */
+ sourceSettled(withinSync: boolean): boolean;
+ /** The official commit the local personal version is based on, as shown in Settings. */
+ officialBase(): Promise<string | undefined>;
+ /** `cindy-personal` changed; refresh the Settings source summary. */
+ sourceChanged(): void;
+ publish(state: CindyMakePersonalRemoteState): void;
+ sleep(ms: number): Promise<void>;
+ now(): number;
+ log?: { info(message: string, meta?: object): void; warn(message: string, meta?: object): void };
+}
+
+type UploadDecision =
+ | { local: string; sync: CindyMakeRemoteSync }
+ | { local: string; push: true; replace?: boolean; base?: string }
+ | { local: string; adopt: true; base: string }
+ /** This computer's own changes replayed on top of the fork's version (`local` is the result). */
+ | { local: string; push: true; merged: { previous: string; base: string }; base: string };
+
+/**
+ * Main-owned binding between the local personal version and the user's GitHub fork.
+ *
+ * Only established content is uploaded: the fork either receives the exact local
+ * `cindy-personal` commit (never a commit that a failed generation could still
+ * undo) or nothing. Every upload uses explicit refspecs with leases, so content
+ * pushed by another computer is never overwritten. A newer version on GitHub is
+ * retrieved only when every local change is already in it. Network commands run
+ * outside the project lock; each decision is taken on a locked snapshot.
+ * Operations run in the background; nothing is replayed after a restart.
+ */
+export class PersonalRemoteController {
+ private identityResult: GithubIdentityResult | undefined;
+ private sourceAvailable = false;
+ /** Local `cindy-personal` tip at the last refresh, to show content still awaiting upload. */
+ private localTip: string | undefined;
+ /** Repository of an existing personal version on the account, shown before binding. */
+ private existingPersonal: string | undefined;
+ private gitChecked = false;
+ /** The current run belongs to Sync, which reserved the source itself. */
+ private withinSync = false;
+ /** `merge-tree --merge-base` (Git 2.40) replays changes without a checkout. */
+ private canReplay = false;
+ private lastAutomaticSync = 0;
+ private runningKind: RemoteRunKind | undefined;
+ private step: CindyMakeRemoteStep | undefined;
+ private current: Promise<void> | undefined;
+
+ constructor(private readonly deps: PersonalRemoteDeps) {
+ try {
+ const record = deps.read();
+ deps.assertTrust?.();
+ if (record.running) {
+ const { running: _interrupted, ...rest } = record;
+ this.write({ ...rest, error: 'interrupted' });
+ }
+ } catch (error) {
+ deps.log?.warn('cindy-make personal remote record unavailable', {
+ code: (error as { code?: unknown })?.code,
+ });
+ }
+ }
+
+ /** Settles the operation started by the most recent action, if any. */
+ settled(): Promise<void> {
+ return this.current ?? Promise.resolve();
+ }
+
+ state(): CindyMakePersonalRemoteState {
+ const record = this.deps.read();
+ const identity = this.identityResult;
+ const githubLogin = identity?.status === 'connected' ? identity.identity.login : undefined;
+ const accountMismatch =
+ !!record.repository && !!githubLogin && !sameGithubLogin(record.login, githubLogin);
+ const error = accountMismatch && !this.runningKind ? 'account' : record.error;
+ // New local content (a generation or an official update) that has not been uploaded yet.
+ const stale =
+ record.sync === 'synced' &&
+ !!record.syncedCommit &&
+ !!this.localTip &&
+ this.localTip !== record.syncedCommit;
+ return {
+ ...(record.choice ? { choice: record.choice } : {}),
+ ...(record.repository ? { repository: record.repository, login: record.login } : {}),
+ github: identity?.status ?? 'unavailable',
+ ...(githubLogin ? { githubLogin } : {}),
+ ...(this.runningKind ? { running: this.runningKind, step: this.step } : {}),
+ ...(record.repository && record.sync ? { sync: stale ? 'pending' : record.sync } : {}),
+ ...(error && !this.runningKind ? { error } : {}),
+ ...(record.repository && record.syncedAt ? { syncedAt: record.syncedAt } : {}),
+ ...(!record.repository && this.existingPersonal
+ ? { existingPersonal: this.existingPersonal }
+ : {}),
+ sourceReady: this.sourceAvailable,
+ // Until a repository is bound, the offer stays: only an explicit local-only choice collapses it.
+ offerMigration:
+ !!githubLogin && !record.repository && record.choice !== 'local' && !this.runningKind,
+ };
+ }
+
+ /** Re-read the GitHub connection and local source; cheap enough per Settings visit. */
+ async refresh(): Promise<CindyMakePersonalRemoteState> {
+ const [identity, tip] = await Promise.all([this.deps.identity(), this.readLocalTip()]);
+ this.identityResult = identity;
+ this.localTip = tip;
+ this.sourceAvailable = !!tip;
+ // Reconnecting, or switching back to the bound login, resolves these without another upload.
+ const record = this.deps.read();
+ if (
+ !this.runningKind &&
+ identity.status === 'connected' &&
+ (record.error === 'github' ||
+ (record.error === 'account' && sameGithubLogin(record.login, identity.identity.login)))
+ ) {
+ const { error: _resolved, ...rest } = record;
+ this.write(rest);
+ }
+ if (identity.status === 'connected' && !record.repository) {
+ try {
+ this.existingPersonal = await this.deps.findPersonalFork(identity.identity);
+ } catch {
+ this.existingPersonal = undefined;
+ }
+ } else this.existingPersonal = undefined;
+ const state = this.publish();
+ // A Settings visit also picks up changes another computer uploaded; at most once a minute.
+ if (
+ identity.status === 'connected' &&
+ record.repository &&
+ record.choice === 'github' &&
+ !this.runningKind &&
+ this.deps.now() - this.lastAutomaticSync >= 60_000
+ ) {
+ this.lastAutomaticSync = this.deps.now();
+ return this.sync();
+ }
+ return state;
+ }
+
+ async status(): Promise<CindyMakePersonalRemoteState> {
+ return this.identityResult ? this.state() : this.refresh();
+ }
+
+ /** The user's one-time consent: create or reuse the fork, bind it and synchronize. */
+ save(): CindyMakePersonalRemoteState {
+ if (this.runningKind) return this.state();
+ return this.start('save', async (setStep) => {
+ const identity = await this.requireIdentity();
+ const record = this.deps.read();
+ if (record.repository && !sameGithubLogin(record.login, identity.login))
+ throw remoteError('account');
+ if (!(await this.readLocalTip())) throw remoteError('source');
+ await this.requireGitVersion();
+ await this.deps.withProject(async () => {
+ setStep('preparing');
+ await this.normalizeSource();
+ });
+ setStep('fork');
+ const repository = await this.deps.ensureFork(identity);
+ await this.waitForFork(repository, identity);
+ this.update({
+ choice: 'github',
+ login: identity.login,
+ repository,
+ confirmedAt: this.deps.now(),
+ });
+ this.existingPersonal = undefined;
+ this.deps.log?.info('cindy-make personal remote bound', { step: 'bound' });
+ await this.upload(repository, identity, setStep);
+ });
+ }
+
+ /** Explicit retry for a bound repository ("立即同步"); also retrieves newer GitHub content. */
+ sync(): CindyMakePersonalRemoteState {
+ if (this.runningKind) return this.state();
+ const record = this.deps.read();
+ if (!record.repository) throw remoteError('source');
+ const repository = record.repository;
+ return this.start('sync', async (setStep) => {
+ const identity = await this.requireIdentity();
+ if (!sameGithubLogin(record.login, identity.login)) throw remoteError('account');
+ if (!(await this.readLocalTip())) throw remoteError('source');
+ await this.requireGitVersion();
+ await this.upload(repository, identity, setStep);
+ });
+ }
+
+ /**
+ * After a generation finishes or an official update is adopted. The upload rules
+ * decide whether anything is established enough to share; unbound users are untouched.
+ */
+ autoSync(): void {
+ const record = this.deps.read();
+ if (this.runningKind || !record.repository || record.choice !== 'github') return;
+ this.sync();
+ }
+
+ /**
+ * Before a new task branches from `cindy-personal`, so it starts from changes made on
+ * other computers too. Failures never block the task; the Settings row reports them.
+ */
+ async syncBeforeTask(timeoutMs = 120_000): Promise<void> {
+ const record = this.deps.read();
+ if (!record.repository || record.choice !== 'github') return;
+ // One budget covers the whole wait: an operation already running is awaited
+ // within it too, so a new task never stalls here longer than `timeoutMs`
+ // even when an earlier sync waits for fork readiness or network.
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const budget = new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, timeoutMs);
+ });
+ try {
+ await Promise.race([this.settled(), budget]);
+ if (!this.runningKind) this.sync();
+ await Promise.race([this.settled(), budget]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ }
+
+ /**
+ * One sync, awaited; its result for the single Sync pipeline, which holds the source
+ * reservation for this run. Errors are thrown as their code.
+ */
+ async syncNow(): Promise<CindyMakeRemoteSync | undefined> {
+ // A run already in progress started before this Sync moved the source: let it end,
+ // then decide again on the current facts.
+ while (this.runningKind) await this.settled();
+ this.withinSync = true;
+ try {
+ this.sync();
+ await this.settled();
+ } finally {
+ this.withinSync = false;
+ }
+ const record = this.deps.read();
+ if (record.error) throw remoteError(record.error);
+ return record.sync;
+ }
+
+ /** The GitHub version the last fetch saw, with the official base published next to it. */
+ async fetchedTips(): Promise<{ commit: string; base: string } | undefined> {
+ const commit = await this.readCommit(TRACKING_REF);
+ const base = await this.readCommit(BASE_TRACKING_REF);
+ return commit && base ? { commit, base } : undefined;
+ }
+
+ keepLocal(): CindyMakePersonalRemoteState {
+ const record = this.deps.read();
+ if (this.runningKind || record.repository) return this.state();
+ // Stopping the sharing keeps the content trust facts of what was already taken
+ // over, including the rewrite history that carries their provenance.
+ this.write({
+ schema: 1,
+ choice: 'local',
+ ...(record.unverifiedRemote ? { unverifiedRemote: record.unverifiedRemote } : {}),
+ ...(record.unverifiedRemoteOverflow ? { unverifiedRemoteOverflow: true } : {}),
+ ...(record.rewrites ? { rewrites: record.rewrites } : {}),
+ });
+ return this.publish();
+ }
+
+ /** Stop synchronizing: remove the local remote only; the fork and local source stay. */
+ async disconnect(): Promise<CindyMakePersonalRemoteState> {
+ if (this.runningKind) throw Object.assign(new Error('busy'), { code: 'busy' });
+ this.start('disconnect', async () => {
+ await this.deps.withProject(async () => {
+ if (this.deps.sourceExists() && (await this.remoteUrl()) !== undefined)
+ await this.git(['remote', 'remove', PERSONAL_REMOTE_NAME]);
+ });
+ const { unverifiedRemote, unverifiedRemoteOverflow, rewrites } = this.deps.read();
+ this.write({
+ schema: 1,
+ choice: 'local',
+ ...(unverifiedRemote ? { unverifiedRemote } : {}),
+ ...(unverifiedRemoteOverflow ? { unverifiedRemoteOverflow: true } : {}),
+ ...(rewrites ? { rewrites } : {}),
+ });
+ });
+ await this.settled();
+ return this.state();
+ }
+
+ private publish(): CindyMakePersonalRemoteState {
+ const state = this.state();
+ this.deps.publish(state);
+ return state;
+ }
+
+ private update(patch: Partial<PersonalRemoteRecord>): void {
+ this.write({ ...this.deps.read(), ...patch, schema: 1 });
+ }
+
+ private write(record: PersonalRemoteRecord): void {
+ this.deps.assertTrust?.();
+ this.deps.write(record);
+ }
+
+ private start(
+ kind: RemoteRunKind,
+ body: (setStep: (step: CindyMakeRemoteStep) => void) => Promise<void>,
+ ): CindyMakePersonalRemoteState {
+ // Persist the run marker first: if that fails nothing has started.
+ const { error: _previous, ...record } = this.deps.read();
+ this.write({ ...record, running: kind });
+ this.runningKind = kind;
+ this.step = 'waiting';
+ const setStep = (step: CindyMakeRemoteStep) => {
+ this.step = step;
+ this.publish();
+ };
+ this.current = (async () => {
+ let failure: CindyMakeRemoteError | undefined;
+ try {
+ await this.deps.withSourceUse(async () => {
+ try {
+ await body(setStep);
+ } finally {
+ // Read the tip while the checkout is still protected from clearing.
+ this.localTip = await this.readLocalTip();
+ }
+ });
+ } catch (error) {
+ failure = classifyRemoteGitError(error);
+ this.deps.log?.warn('cindy-make personal remote failed', {
+ operation: kind,
+ step: this.step,
+ code: failure,
+ });
+ } finally {
+ try {
+ const { running: _done, error: _stale, ...rest } = this.deps.read();
+ this.write({ ...rest, ...(failure ? { error: failure } : {}) });
+ } catch {
+ // The in-memory state below must still settle; a restart reports the run as interrupted.
+ }
+ this.runningKind = undefined;
+ this.step = undefined;
+ this.publish();
+ }
+ })();
+ return this.publish();
+ }
+
+ private async requireIdentity(): Promise<GithubIdentity> {
+ this.identityResult = await this.deps.identity();
+ if (this.identityResult.status !== 'connected') throw remoteError('github');
+ return this.identityResult.identity;
+ }
+
+ /**
+ * `GIT_CONFIG_COUNT` needs Git 2.31 (older Git silently drops the credential) and the
+ * merge comparison needs `--remerge-diff` from Git 2.36.
+ */
+ private async requireGitVersion(): Promise<void> {
+ if (this.gitChecked) return;
+ const match = /git version (\d+)\.(\d+)/.exec(await this.git(['--version']));
+ const [major, minor] = match ? [Number(match[1]), Number(match[2])] : [0, 0];
+ if (major < 2 || (major === 2 && minor < 36)) throw remoteError('gitOutdated');
+ this.canReplay = major > 2 || minor >= 40;
+ this.gitChecked = true;
+ }
+
+ private git(args: string[], options?: PersonalRemoteGitOptions): Promise<string> {
+ return this.deps.git(args, this.deps.source, options);
+ }
+
+ private async readCommit(ref: string): Promise<string | undefined> {
+ try {
+ const commit = (
+ await this.git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])
+ ).trim();
+ return COMMIT.test(commit) ? commit : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+
+ private async readLocalTip(): Promise<string | undefined> {
+ if (!this.deps.sourceExists()) return undefined;
+ return this.readCommit(BRANCH_REF);
+ }
+
+ /** Legacy uncommitted personal files become a local commit before anything is uploaded. */
+ private async normalizeSource(): Promise<void> {
+ const git: ContentGit = (args, cwd, indexFile) =>
+ this.deps.git(args, cwd, indexFile ? { indexFile } : undefined);
+ if ((await this.git(['rev-parse', '--abbrev-ref', 'HEAD'])).trim() !== CINDY_PERSONAL_BRANCH)
+ throw remoteError('source');
+ await assertNoGitOperation(git, this.deps.source);
+ if ((await this.git(['status', '--porcelain'])).trim())
+ await commitPersonalFiles(git, this.deps.source);
+ }
+
+ private async remoteUrl(): Promise<string | undefined> {
+ try {
+ return (await this.git(['config', '--get', `remote.${PERSONAL_REMOTE_NAME}.url`])).trim();
+ } catch (error) {
+ if ((error as { exitCode?: number }).exitCode === 1) return undefined;
+ throw error;
+ }
+ }
+
+ private async exitsZero(args: string[]): Promise<boolean> {
+ try {
+ await this.git(args);
+ return true;
+ } catch (error) {
+ if ((error as { exitCode?: number }).exitCode === 1) return false;
+ throw error;
+ }
+ }
+
+ private isAncestor(ancestor: string, descendant: string): Promise<boolean> {
+ return this.exitsZero(['merge-base', '--is-ancestor', ancestor, descendant]);
+ }
+
+ /** The same position-aware proof used before adopting an official update. */
+ private async containsChanges(into: string, from: string): Promise<boolean> {
+ const git: ContentGit = (args, _cwd, indexFile) =>
+ this.git(args, indexFile ? { indexFile } : undefined);
+ try {
+ return (await uncarriedChanges(git, this.deps.source, from, into, into)).length === 0;
+ } catch {
+ return false;
+ }
+ }
+
+ /** Commit hashes for `rev-list` arguments; undefined when Git output was cut at its capture limit. */
+ private async commits(args: string[]): Promise<string[] | undefined> {
+ const listed = (await this.git(['rev-list', ...args]))
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => COMMIT.test(line));
+ const count = Number((await this.git(['rev-list', '--count', ...args])).trim());
+ return Number.isSafeInteger(count) && count === listed.length ? listed : undefined;
+ }
+
+ /** The local personal version consists of official commits only (a fresh computer). */
+ private async hasNoPersonalCommits(local: string): Promise<boolean> {
+ const base = await this.deps.officialBase();
+ return !!base && COMMIT.test(base) && (base === local || (await this.isAncestor(local, base)));
+ }
+
+ /** The official base to publish next to `local`; omitted when it cannot be proven. */
+ private async publishableBase(local: string): Promise<string | undefined> {
+ const base = await this.deps.officialBase();
+ if (!base || !COMMIT.test(base)) return undefined;
+ return (await this.isAncestor(base, local)) ? base : undefined;
+ }
+
+ /** GitHub creates forks asynchronously; wait until the repository serves refs. */
+ private async waitForFork(repository: string, identity: GithubIdentity): Promise<void> {
+ const started = this.deps.now();
+ const auth = { repository, token: identity.token };
+ for (let attempt = 0; ; attempt += 1) {
+ try {
+ const refs = await this.git(['ls-remote', '--heads', githubRepositoryUrl(repository)], {
+ auth,
+ });
+ if (/\trefs\/heads\//.test(refs)) return;
+ } catch (error) {
+ // A brand-new fork answers "not found" until GitHub finishes creating it;
+ // keep waiting for that, but a rejected credential will not recover.
+ if (classifyRemoteGitError(error) === 'github') throw error;
+ }
+ if (this.deps.now() - started >= FORK_WAIT_MS) throw remoteError('forkUnavailable');
+ await this.deps.sleep(Math.min(2_000 * 2 ** attempt, 10_000));
+ }
+ }
+
+ /**
+ * Both computers added changes on the same official base. Replays this computer's
+ * changes the fork does not have yet, oldest first, on top of the fork's version
+ * using only Git objects: no checkout, worktree or hook runs, and nothing moves
+ * until every change applied cleanly. A conflict, a merge commit that adds edits
+ * of its own, or an older Git leaves both sides untouched.
+ */
+ private async replayOnto(
+ local: string,
+ remote: string,
+ base: string,
+ ): Promise<string | undefined> {
+ if (!this.canReplay) return undefined;
+ const fork = (await this.git(['merge-base', local, remote]).catch(() => '')).trim();
+ if (!COMMIT.test(fork) || !(await this.isAncestor(base, fork))) return undefined;
+ const merges = await this.commits(['--merges', `${fork}..${local}`]);
+ if (!merges) return undefined;
+ for (const merge of merges) {
+ const extra = await this.git([
+ 'show',
+ '--remerge-diff',
+ '--no-ext-diff',
+ '--no-color',
+ '--format=',
+ merge,
+ ]).catch(() => undefined);
+ if (extra === undefined || extra.trim()) return undefined;
+ }
+ // Output is size-limited; a truncated list must not silently drop the newest changes.
+ // patch-id drops positions: identical edits in two repeated blocks are two
+ // distinct changes. Reapply every non-ancestor commit; merge-tree determines
+ // whether the original change is already carried without fuzzy placement.
+ const unique = await this.commits(['--right-only', '--no-merges', `${remote}...${local}`]);
+ const range = await this.commits(['--reverse', '--topo-order', '--no-merges', `${fork}..${local}`]);
+ if (!unique || !range) return undefined;
+ const missing = new Set(unique);
+ const commits = range.filter((commit) => missing.has(commit));
+ let tip = remote;
+ let tree = (await this.git(['rev-parse', `${remote}^{tree}`])).trim();
+ const temporary = await mkdtemp(path.join(os.tmpdir(), 'cindy-make-replay-'));
+ try {
+ for (const commit of commits) {
+ const parent = (await this.git(['rev-parse', `${commit}^`])).trim();
+ let merged: string;
+ try {
+ merged = (
+ await this.git([
+ 'merge-tree',
+ '--write-tree',
+ '--no-messages',
+ `--merge-base=${parent}`,
+ tip,
+ commit,
+ ])
+ )
+ .split(/\r?\n/)[0]
+ .trim();
+ } catch {
+ return undefined;
+ }
+ if (!COMMIT.test(merged)) return undefined;
+ if (merged === tree) continue;
+ // The raw object, unaffected by log formatting, signature display or user config.
+ const object = await this.git(['cat-file', 'commit', commit]);
+ const split = object.indexOf('\n\n');
+ const headers = split < 0 ? object : object.slice(0, split);
+ const author = /^author (.*) <([^<>\n]*)> (\d+ [+-]\d{4})$/m.exec(headers);
+ const message = path.join(temporary, 'message');
+ const body = split < 0 ? '' : object.slice(split + 2);
+ await writeFile(message, body.endsWith('\n') ? body : body + '\n', 'utf8');
+ // The replayed change keeps its author and date; an unreadable one falls back to Cindy Make.
+ tip = (
+ await this.git(
+ ['-c', 'commit.gpgSign=false', 'commit-tree', merged, '-p', tip, '-F', message],
+ {
+ identity:
+ author && author[1].trim() && author[2].trim()
+ ? { name: author[1].trim(), email: author[2].trim(), date: author[3] }
+ : MAKE_IDENTITY,
+ },
+ )
+ ).trim();
+ if (!COMMIT.test(tip)) return undefined;
+ tree = merged;
+ }
+ } finally {
+ await rm(temporary, { recursive: true, force: true });
+ }
+ return tip;
+ }
+
+ /** `commit` is contained in `local` through the adopted rewrites (patches may differ). */
+ private async carriedByRewrites(commit: string, local: string): Promise<boolean> {
+ // Records survive clearing the source; commits that no longer exist prove nothing.
+ const contains = async (ancestor: string, descendant: string) => {
+ if (ancestor === descendant) return true;
+ try {
+ return await this.isAncestor(ancestor, descendant);
+ } catch {
+ return false;
+ }
+ };
+ const carried = [commit];
+ for (const rewrite of this.deps.read().rewrites ?? []) {
+ let included = false;
+ for (const input of rewrite.from) {
+ for (const known of carried)
+ if (await contains(known, input)) {
+ included = true;
+ break;
+ }
+ if (included) break;
+ }
+ if (included) carried.push(rewrite.to);
+ }
+ for (const result of carried.slice(1)) if (await contains(result, local)) return true;
+ return false;
+ }
+
+ /**
+ * Remember an adopted history rewrite; called for every completed official update
+ * or combine, including one restored at startup. Repeats are ignored.
+ */
+ recordRewrite(from: string[], to: string): void {
+ if (!COMMIT.test(to) || !from.length || from.length > 2 || !from.every((c) => COMMIT.test(c)))
+ return;
+ const record = this.deps.read();
+ const same = (rewrite: PersonalRewrite) =>
+ rewrite.to === to &&
+ rewrite.from.length === from.length &&
+ rewrite.from.every((commit, index) => commit === from[index]);
+ // Provenance must survive without a binding: the rewrite history carries the
+ // unverified content through official updates even after a disconnect, so it
+ // is recorded whenever there is content to carry.
+ if (
+ (!record.repository && !(record.unverifiedRemote ?? []).length) ||
+ (record.rewrites ?? []).some(same)
+ )
+ return;
+ const tips = record.unverifiedRemote ?? [];
+ const nextTips =
+ tips.length && !tips.includes(to) && tips.length < MAX_UNVERIFIED_REMOTE
+ ? [...tips, to]
+ : tips;
+ this.update({
+ rewrites: [...(record.rewrites ?? []), { from, to }].slice(-MAX_REWRITES),
+ // Unverified content this rewrite carried keeps its provenance under the new
+ // commit. If the bounded diagnostic list is full, keep the old entries and
+ // mark the omitted result unknown instead of evicting a live source.
+ ...(tips.length && !tips.includes(to)
+ ? {
+ unverifiedRemote: nextTips,
+ ...(nextTips === tips ? { unverifiedRemoteOverflow: true } : {}),
+ }
+ : {}),
+ });
+ }
+
+ /**
+ * Remember a tip taken over from the fork before this computer verified it:
+ * until a generated personal version covers it, the automatic task install
+ * must not run lifecycle scripts on worktrees containing it.
+ */
+ recordUnverifiedRemote(commit: string): void {
+ if (!COMMIT.test(commit)) return;
+ const record = this.deps.read();
+ const known = (record.unverifiedRemote ?? []).filter((tip) => !this.deps.isBuilt(tip));
+ if (known.includes(commit)) return;
+ if (this.deps.isBuilt(commit)) {
+ if (known.length !== (record.unverifiedRemote ?? []).length)
+ this.update({ unverifiedRemote: known });
+ return;
+ }
+ if (known.length >= MAX_UNVERIFIED_REMOTE) {
+ // Never evict an unverified source just to keep the JSON parseable. The
+ // overflow marker makes the guarded install path stay active for the
+ // omitted facts, while later syncs remain writable and can retain the
+ // bounded list for diagnostics.
+ this.update({ unverifiedRemote: known, unverifiedRemoteOverflow: true });
+ return;
+ }
+ this.update({
+ unverifiedRemote: [...known, commit],
+ ...(record.unverifiedRemoteOverflow ? { unverifiedRemoteOverflow: true } : {}),
+ });
+ }
+
+ /** Moving the checkout needs an idle, clean source on the personal branch. */
+ private async movable(): Promise<boolean> {
+ return (
+ this.deps.sourceSettled(this.withinSync) &&
+ !(await this.git(['status', '--porcelain'])).trim() &&
+ (await this.git(['rev-parse', '--abbrev-ref', 'HEAD'])).trim() === CINDY_PERSONAL_BRANCH
+ );
+ }
+
+ /** Decide on a locked snapshot what to upload, retrieve or only report. */
+ private async decide(
+ remote: string | undefined,
+ remoteBase: string | undefined,
+ ): Promise<UploadDecision> {
+ const local = await this.readLocalTip();
+ if (!local) throw remoteError('source');
+ const record = this.deps.read();
+ const tree = (await this.git(['rev-parse', `${local}^{tree}`])).trim();
+ const established = !(
+ (await this.deps.hasUnbuiltChanges(local, tree)) ||
+ (await this.exitsZero([
+ 'show-ref',
+ '--verify',
+ '--quiet',
+ `refs/cindy-make/failed-builds/${local}`,
+ ]))
+ );
+ if (remote === local)
+ return {
+ local,
+ sync: record.sync === 'retrieved' && !this.deps.isBuilt(local) ? 'retrieved' : 'synced',
+ };
+ /**
+ * Take the GitHub version. Only when the source can move now: otherwise the reason
+ * is reported as it is (not generated yet, or busy), never as unrelated versions,
+ * which would offer replacing the GitHub version.
+ */
+ const retrieve = async (blocked: CindyMakeRemoteSync): Promise<UploadDecision> => {
+ if (!remote) return { local, sync: blocked };
+ if (!established) return { local, sync: 'buildFirst' };
+ if (!(await this.movable())) return { local, sync: 'pending' };
+ // The fork's own base when it publishes one; otherwise this computer's base still applies.
+ const candidates = [remoteBase, await this.deps.officialBase()];
+ for (const base of candidates)
+ if (base && COMMIT.test(base) && (await this.isAncestor(base, remote)))
+ return { local, adopt: true, base };
+ return { local, sync: blocked };
+ };
+ if (!remote)
+ return established
+ ? { local, push: true, base: await this.publishableBase(local) }
+ : { local, sync: 'pendingBuild' };
+ if (await this.isAncestor(remote, local))
+ return established
+ ? { local, push: true, base: await this.publishableBase(local) }
+ : { local, sync: 'pendingBuild' };
+ if (await this.isAncestor(local, remote)) return retrieve('remoteAhead');
+ // An official update or a combine rewrote history. Replace the fork's version only
+ // when every change in it is proven to be here: it is this computer's own upload with
+ // the same patches, or adopted rewrites carried it into this version.
+ if (
+ (remote === record.syncedCommit && (await this.containsChanges(local, remote))) ||
+ (await this.carriedByRewrites(remote, local))
+ )
+ return established
+ ? { local, push: true, replace: true, base: await this.publishableBase(local) }
+ : { local, sync: 'pendingBuild' };
+ // Another computer uploaded a rewritten or newer version that already has every local
+ // change, or this computer has nothing GitHub did not already have (no personal changes
+ // of its own, or none since its last sync — another computer then updated that same
+ // version, for example resolving an official update once for both): retrieve it.
+ if (
+ local === record.syncedCommit ||
+ (await this.containsChanges(remote, local)) ||
+ (await this.hasNoPersonalCommits(local))
+ )
+ return retrieve('diverged');
+ // Both sides have changes of their own. This computer's changes are combined only once
+ // they are established (generated) and the source is idle and clean.
+ if (!established) return { local, sync: 'buildFirst' };
+ if (!(await this.movable())) return { local, sync: 'pending' };
+ // Without a published official base the fork may already be on a newer official
+ // version that cannot be told apart from personal changes: only reported.
+ const base = await this.deps.officialBase();
+ if (!base || !COMMIT.test(base) || !remoteBase || !(await this.isAncestor(remoteBase, remote)))
+ return { local, sync: 'diverged' };
+ // One side is already on a newer official version: the isolated combine replays the
+ // other side's own changes onto it. Unrelated official lines are only reported.
+ if (remoteBase !== base)
+ return (await this.isAncestor(base, remoteBase)) || (await this.isAncestor(remoteBase, base))
+ ? { local, sync: 'needsMerge' }
+ : { local, sync: 'diverged' };
+ const combined = await this.replayOnto(local, remote, base);
+ // Overlapping edits (or history plumbing cannot replay) are combined by Sync's isolated rebase.
+ return combined
+ ? { local: combined, push: true, merged: { previous: local, base }, base }
+ : { local, sync: 'needsMerge' };
+ }
+
+ /**
+ * Check the bound repository, point the `personal` remote at it and fetch its
+ * version and published official base into the tracking refs.
+ */
+ private async connect(
+ repository: string,
+ identity: GithubIdentity,
+ setStep: (step: CindyMakeRemoteStep) => void,
+ ): Promise<{
+ auth: { repository: string; token: string };
+ remote?: string;
+ remoteBase?: string;
+ }> {
+ if (this.deps.inspectFork) {
+ setStep('connecting');
+ const health = await this.deps.inspectFork(identity, repository);
+ if (health.repository !== repository) {
+ // Renamed on GitHub: follow it, still only under the connected account.
+ if (!sameGithubLogin(health.repository.split('/')[0], identity.login))
+ throw remoteError('forkConflict');
+ this.update({ repository: health.repository });
+ repository = health.repository;
+ }
+ if (health.archived) throw remoteError('forkArchived');
+ if (!health.canPush) throw remoteError('github');
+ }
+ const auth = { repository, token: identity.token };
+ const url = githubRepositoryUrl(repository);
+ // The project queue may still be finishing a generation or another source operation.
+ setStep('waiting');
+ await this.deps.withProject(async () => {
+ setStep('connecting');
+ const current = await this.remoteUrl();
+ if (current === undefined) await this.git(['remote', 'add', PERSONAL_REMOTE_NAME, url]);
+ else if (current !== url) await this.git(['remote', 'set-url', PERSONAL_REMOTE_NAME, url]);
+ });
+ setStep('connecting');
+ const listed = await this.git(
+ ['ls-remote', '--refs', PERSONAL_REMOTE_NAME, BRANCH_REF, BASE_BRANCH_REF],
+ { auth },
+ );
+ const tips = new Map(
+ listed
+ .split(/\r?\n/)
+ .map((line) => line.trim().split(/\s+/))
+ .filter(([commit, ref]) => COMMIT.test(commit ?? '') && !!ref)
+ .map(([commit, ref]) => [ref, commit] as const),
+ );
+ const remote = tips.get(BRANCH_REF);
+ const remoteBase = tips.get(BASE_BRANCH_REF);
+ const refspecs = [
+ ...(remote ? [`+${BRANCH_REF}:${TRACKING_REF}`] : []),
+ ...(remoteBase ? [`+${BASE_BRANCH_REF}:${BASE_TRACKING_REF}`] : []),
+ ];
+ if (refspecs.length)
+ await this.git(
+ [
+ 'fetch',
+ '--no-tags',
+ '--no-write-fetch-head',
+ // Background maintenance must not repack while a build uses the same repository.
+ '--no-auto-maintenance',
+ PERSONAL_REMOTE_NAME,
+ ...refspecs,
+ ],
+ { auth },
+ );
+ if (!remote) await this.git(['update-ref', '-d', TRACKING_REF]).catch(() => undefined);
+ if (!remoteBase) await this.git(['update-ref', '-d', BASE_TRACKING_REF]).catch(() => undefined);
+ return { auth, remote, remoteBase };
+ }
+
+ /**
+ * The way out when the two personal versions cannot be combined (unrelated official
+ * versions, or the user gave up a combine): keep one side, as the user chose. The
+ * other side stays recoverable: this computer's version in a local backup ref, the
+ * GitHub version in a local backup ref and, when it is replaced, in a backup branch
+ * on the user's repository. Called under Sync's source reservation.
+ */
+ async keepSide(side: 'github' | 'local'): Promise<CindyMakeRemoteSync | undefined> {
+ const record = this.deps.read();
+ if (!record.repository) throw remoteError('source');
+ const repository = record.repository;
+ while (this.runningKind) await this.settled();
+ this.withinSync = true;
+ try {
+ this.start('sync', async (setStep) => {
+ const identity = await this.requireIdentity();
+ if (!sameGithubLogin(record.login, identity.login)) throw remoteError('account');
+ if (!(await this.readLocalTip())) throw remoteError('source');
+ await this.requireGitVersion();
+ const { auth, remote, remoteBase } = await this.connect(repository, identity, setStep);
+ if (!remote) throw remoteError('source');
+ setStep('waiting');
+ await this.deps.withProject(async () => {
+ setStep(side === 'github' ? 'retrieving' : 'uploading');
+ const local = await this.readLocalTip();
+ if (!local) throw remoteError('source');
+ await this.git(['update-ref', `refs/cindy-make/backups/personal-remote/${remote}`, remote]);
+ await this.git([
+ 'update-ref',
+ `refs/cindy-make/backups/personal-remote-local/${local}`,
+ local,
+ ]);
+ // A failed generation could still need to roll back what is here: generate first.
+ const tree = (await this.git(['rev-parse', `${local}^{tree}`])).trim();
+ if (await this.deps.hasUnbuiltChanges(local, tree)) {
+ this.update({ sync: 'buildFirst' });
+ return;
+ }
+ if (side === 'github') {
+ // Its own official base is needed to continue from it.
+ if (!remoteBase || !(await this.isAncestor(remoteBase, remote)))
+ throw remoteError('failed');
+ if (!(await this.movable())) throw remoteError('source');
+ // Recorded before the move: an interrupted run must never lose the
+ // provenance of content that is already on disk; over-marking after a
+ // failed move is safe.
+ this.recordUnverifiedRemote(remote);
+ // The adopted tip's own changes are not generated here yet: recorded
+ // with the snapshot so the fact travels with the source (see
+ // `pendingBuild`). The fork's own base proves "no changes of its own".
+ if (remote !== remoteBase) {
+ const adoptedTree = (await this.git(['rev-parse', `${remote}^{tree}`])).trim();
+ this.deps.recordUnbuilt?.({ commit: remote, tree: adoptedTree });
+ }
+ // The base ref moves first: interrupted between the two writes, the
+ // conservative fact is the new base — never a new tip under a stale one.
+ await this.git(['update-ref', PERSONAL_UPSTREAM_REF, remoteBase]);
+ await this.git(['reset', '--keep', remote]);
+ if ((await this.readLocalTip()) !== remote) throw remoteError('source');
+ this.update({
+ sync: this.deps.isBuilt(remote) ? 'synced' : 'retrieved',
+ syncedAt: this.deps.now(),
+ syncedCommit: remote,
+ });
+ this.deps.sourceChanged();
+ return;
+ }
+ const base = await this.publishableBase(local);
+ const backup = `refs/heads/cindy-personal-backup/${remote.slice(0, 12)}`;
+ await this.git(
+ [
+ 'push',
+ '--porcelain',
+ '--atomic',
+ '--no-verify',
+ '--no-follow-tags',
+ `--force-with-lease=${backup}:`,
+ `--force-with-lease=${BRANCH_REF}:${remote}`,
+ ...(base ? [`--force-with-lease=${BASE_BRANCH_REF}:${remoteBase ?? ''}`] : []),
+ PERSONAL_REMOTE_NAME,
+ `${remote}:${backup}`,
+ `${local}:${BRANCH_REF}`,
+ ...(base ? [`${base}:${BASE_BRANCH_REF}`] : []),
+ ],
+ { auth },
+ );
+ await this.git(['update-ref', TRACKING_REF, local]);
+ if (base) await this.git(['update-ref', BASE_TRACKING_REF, base]);
+ this.update({ sync: 'synced', syncedAt: this.deps.now(), syncedCommit: local });
+ });
+ });
+ await this.settled();
+ } finally {
+ this.withinSync = false;
+ }
+ const after = this.deps.read();
+ if (after.error) throw remoteError(after.error);
+ return after.sync;
+ }
+
+ private async upload(
+ repository: string,
+ identity: GithubIdentity,
+ setStep: (step: CindyMakeRemoteStep) => void,
+ ): Promise<void> {
+ const { auth, remote, remoteBase } = await this.connect(repository, identity, setStep);
+
+ setStep('waiting');
+ const decision = await this.deps.withProject(async (): Promise<UploadDecision> => {
+ setStep('connecting');
+ const decided = await this.decide(remote, remoteBase);
+ // A combined version is uploaded first; this computer moves to it afterwards.
+ if (!('adopt' in decided) || !remote) return decided;
+ // Retrieve: keep this computer's version reachable, then move to the GitHub version.
+ setStep('retrieving');
+ await this.git([
+ 'update-ref',
+ `refs/cindy-make/backups/personal-remote-local/${decided.local}`,
+ decided.local,
+ ]);
+ // Recorded before the move: an interrupted run must never lose the provenance
+ // of content that is already on disk (over-marking is safe).
+ this.recordUnverifiedRemote(remote);
+ // The adopted tip's changes are not generated here yet (see `pendingBuild`).
+ if (remote !== remoteBase) {
+ const adoptedTree = (await this.git(['rev-parse', `${remote}^{tree}`])).trim();
+ this.deps.recordUnbuilt?.({ commit: remote, tree: adoptedTree });
+ }
+ // The base ref moves first for the same reason (see `keepSide`).
+ await this.git(['update-ref', PERSONAL_UPSTREAM_REF, decided.base]);
+ await this.git(['reset', '--keep', remote]);
+ if ((await this.readLocalTip()) !== remote) throw remoteError('source');
+ return decided;
+ });
+
+ let sync: CindyMakeRemoteSync;
+ let confirmed = decision.local;
+ let uploaded = false;
+ const { rewrites } = this.deps.read();
+ if ('sync' in decision) sync = decision.sync;
+ else if ('adopt' in decision) {
+ confirmed = remote!;
+ sync = this.deps.isBuilt(confirmed) ? 'synced' : 'retrieved';
+ this.deps.sourceChanged();
+ } else {
+ setStep('uploading');
+ if ('replace' in decision && decision.replace && remote)
+ await this.git(['update-ref', `refs/cindy-make/backups/personal-remote/${remote}`, remote]);
+ try {
+ await this.git(
+ [
+ 'push',
+ '--porcelain',
+ '--atomic',
+ '--no-verify',
+ '--no-follow-tags',
+ `--force-with-lease=${BRANCH_REF}:${remote ?? ''}`,
+ ...(decision.base ? [`--force-with-lease=${BASE_BRANCH_REF}:${remoteBase ?? ''}`] : []),
+ PERSONAL_REMOTE_NAME,
+ `${decision.local}:${BRANCH_REF}`,
+ ...(decision.base ? [`${decision.base}:${BASE_BRANCH_REF}`] : []),
+ ],
+ { auth },
+ );
+ } catch (error) {
+ this.update({ sync: 'pending' });
+ throw error;
+ }
+ await this.git(['update-ref', TRACKING_REF, decision.local]);
+ if (decision.base) await this.git(['update-ref', BASE_TRACKING_REF, decision.base]);
+ uploaded = true;
+ // A combine brought the other computer's changes into this upload; they still
+ // have to be generated before this computer uses them.
+ sync =
+ !('merged' in decision) &&
+ remote &&
+ (rewrites ?? []).some((rewrite) => rewrite.from.slice(1).includes(remote)) &&
+ !this.deps.isBuilt(decision.local)
+ ? 'retrieved'
+ : 'synced';
+ if ('merged' in decision) {
+ const { previous, base } = decision.merged;
+ setStep('retrieving');
+ const moved = await this.deps.withProject(async () => {
+ // Something changed here while uploading: keep it; the next sync combines again.
+ if ((await this.readLocalTip()) !== previous || !(await this.movable())) return false;
+ await this.git([
+ 'update-ref',
+ `refs/cindy-make/backups/personal-remote-local/${previous}`,
+ previous,
+ ]);
+ // Recorded before the move (over-marking after a failed move is safe).
+ if (remote) this.recordUnverifiedRemote(remote);
+ // The combined result carries the GitHub side's changes, which are not
+ // generated on this computer yet (see `pendingBuild`).
+ {
+ const combinedTree = (await this.git(['rev-parse', `${decision.local}^{tree}`])).trim();
+ this.deps.recordUnbuilt?.({ commit: decision.local, tree: combinedTree });
+ }
+ await this.git(['update-ref', PERSONAL_UPSTREAM_REF, base]);
+ await this.git(['reset', '--keep', decision.local]);
+ if ((await this.readLocalTip()) !== decision.local) throw remoteError('source');
+ return true;
+ });
+ if (moved) {
+ this.deps.sourceChanged();
+ // The combined version still has to be generated before this computer uses it.
+ if (!this.deps.isBuilt(decision.local)) sync = 'retrieved';
+ } else sync = 'pending';
+ }
+ }
+ this.update({
+ sync,
+ // The fork's version was written by this computer even when it could not move to it yet.
+ ...(sync === 'synced' || sync === 'retrieved' || uploaded
+ ? { syncedAt: this.deps.now(), syncedCommit: confirmed }
+ : {}),
+ });
+ this.deps.log?.info('cindy-make personal remote checked', { sync });
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/personalRemoteRuntime.ts b/apps/desktop/src/main/cindy-make/personalRemoteRuntime.ts
new file mode 100644
index 0000000000..fbe40479e2
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/personalRemoteRuntime.ts
@@ -0,0 +1,387 @@
+import path from 'node:path';
+import { existsSync, mkdirSync } from 'node:fs';
+import { app } from 'electron';
+
+import {
+ CINDY_MAKE_REMOTE_ACTIONS,
+ type CindyMakePersonalRemoteAction,
+ type CindyMakePersonalRemoteState,
+} from '../../shared/cindyMakePersonalRemote.js';
+import { getSharedGhCliTokenSource } from '../git-context/ghCliTokenSource.js';
+import { outboundFetch } from '../maker-host/outbound-fetch.js';
+import { readGhostSecret } from '../secrets/providerSecretStore.js';
+import { readAtomicFileSync, atomicWriteFileSync } from '../utils/atomicWriteFile.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { createLogger } from '../logger.js';
+import { hasUnbuiltPersonalChanges as unbuiltPersonalChanges } from './buildRollback.js';
+import { recordPendingBuild, rewritePendingBuilds } from './pendingBuild.js';
+import type { PersonalSyncRemote } from './personalSync.js';
+import type { MakeRemotePersonalSnapshot } from './remoteProjection.js';
+import { captureMakeHistoryStore } from './historyOwner.js';
+import { broadcastMakeRemoteChanged } from './remoteBroadcast.js';
+import { cindyMakeManager } from './manager.js';
+import {
+ PersonalRemoteController,
+ PersonalRemoteError,
+ adoptedRewrite,
+ ensureOfficialFork,
+ findPersonalFork,
+ inspectPersonalFork,
+ parsePersonalRemoteRecord,
+ parsePersonalRemoteTrust,
+ personalGitEnv,
+ readGithubIdentity,
+ writePersonalRemoteRecord,
+ type PersonalRemoteGitOptions,
+} from './personalRemote.js';
+import { runSourceGit } from './sourceGit.js';
+import { readCurrentCindySourceStatus } from './sourcePreparation.js';
+import { makeSourceCheckoutPath, makeSourceRoot } from './sourcePaths.js';
+import {
+ createMakeToolchainEnvironment,
+ resolveMakeToolEnvironment,
+} from './toolchainEnvironment.js';
+import { hasPublishedPersonalVersionCommit } from './versionStore.js';
+import {
+ ContributionError,
+ PersonalContribution,
+ parseContributionStore,
+} from './personalContribution.js';
+import { activeOwnerScopeKey, ownerScopedUserDataPath } from '../appSessionState.js';
+import {
+ CONTRIBUTION_LIMITS,
+ type CindyMakeContributionDraft,
+ type CindyMakeContributionView,
+} from '../../shared/cindyMakeContribution.js';
+
+const log = createLogger('cindy-make');
+let controller: PersonalRemoteController | undefined;
+let contribution: PersonalContribution | undefined;
+
+/** Called explicitly at bootstrap; the module itself has no import-time side effects. */
+export function configurePersonalRemote(): void {
+ const userData = app.getPath('userData');
+ const root = makeSourceRoot(userData);
+ const file = path.join(root, 'personal-remote.json');
+ const source = makeSourceCheckoutPath(userData);
+ const readRaw = () => readAtomicFileSync(file);
+ const read = () => parsePersonalRemoteRecord(readRaw());
+ // Same credential order as the shared GitHub connection: the gh login, then
+ // the current account's saved token. Neither is ever returned to the renderer.
+ const identity = () =>
+ readGithubIdentity({
+ readToken: async () =>
+ (await getSharedGhCliTokenSource().readToken()) ??
+ readGhostSecret('cindy-github', 'github_pat'),
+ fetch: outboundFetch,
+ });
+ const git = async (args: string[], cwd: string, options?: PersonalRemoteGitOptions) => {
+ const signal = AbortSignal.timeout(3 * 60_000);
+ const tools = await createMakeToolchainEnvironment(userData);
+ const env = await resolveMakeToolEnvironment(tools, ['git'], signal);
+ return runSourceGit(personalGitEnv(env, options), args, cwd, signal);
+ };
+ controller = new PersonalRemoteController({
+ source,
+ read,
+ assertTrust: () => {
+ parsePersonalRemoteTrust(readRaw());
+ },
+ write: (record) => writePersonalRemoteRecord(file, record),
+ identity,
+ ensureFork: (identity) => ensureOfficialFork(outboundFetch, identity),
+ findPersonalFork: (identity) => findPersonalFork(outboundFetch, identity),
+ inspectFork: (identity, repository) => inspectPersonalFork(outboundFetch, identity, repository),
+ git,
+ sourceExists: () => existsSync(path.join(source, '.git')),
+ withProject: (run) =>
+ cindyMakeManager.withProjectUse(root, () => cindyMakeManager.withProject(root, run)),
+ withSourceUse: (run) => cindyMakeManager.withSourceReader(root, run),
+ hasUnbuiltChanges: (commit, tree) => hasUnbuiltPersonalChanges(commit, tree),
+ recordUnbuilt: (snapshot) => recordPendingBuild(root, snapshot),
+ isBuilt: (commit) => hasPublishedPersonalVersionCommit(userData, commit),
+ sourceSettled: (withinSync) => cindyMakeManager.isSourceSettled(root, withinSync),
+ officialBase: async () => {
+ const tools = await createMakeToolchainEnvironment(userData);
+ return (await readCurrentCindySourceStatus(root, tools)).baseCommit;
+ },
+ sourceChanged: () => {
+ void (async () => {
+ const tools = await createMakeToolchainEnvironment(userData);
+ await cindyMakeManager.refreshSourceStatus(() => readCurrentCindySourceStatus(root, tools));
+ })().catch(() => undefined);
+ },
+ publish: (state) => cindyMakeManager.setPersonalRemote(state),
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+ now: Date.now,
+ log,
+ });
+ const contributions = () => ownerScopedUserDataPath('cindy-make-contributions.json');
+ contribution = new PersonalContribution({
+ source,
+ ownerScope: () => activeOwnerScopeKey(),
+ binding: read,
+ identity,
+ inspectFork: (identity, repository) => inspectPersonalFork(outboundFetch, identity, repository),
+ git,
+ // The latest completed round of this computer's change: its creation baseline and content.
+ change: (runId) => {
+ const record = captureMakeHistoryStore().read(runId);
+ const completion = record?.completions.findLast((entry) => entry.tree && entry.baseTree);
+ return record && completion?.tree && completion.baseTree
+ ? {
+ title: record.title,
+ request: record.request,
+ baseTree: completion.baseTree,
+ tree: completion.tree,
+ }
+ : undefined;
+ },
+ ledgerPath: contributions,
+ readStore: (file) => parseContributionStore(readAtomicFileSync(file)),
+ writeStore: (file, store) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ atomicWriteFileSync(file, JSON.stringify(store));
+ },
+ fetch: outboundFetch,
+ gitIdentity: async () => {
+ const value = async (key: string) =>
+ (await git(['config', '--get', key], source).catch(() => '')).trim() || undefined;
+ return { name: await value('user.name'), email: await value('user.email') };
+ },
+ withSourceUse: (run) => cindyMakeManager.withSourceReader(root, run),
+ onChanged: (runId) => {
+ try {
+ const sessionId = captureMakeHistoryStore().read(runId)?.sessionId;
+ if (sessionId) broadcastMakeRemoteChanged(sessionId);
+ } catch {
+ // A missing or malformed history record must not affect a successful submission.
+ }
+ },
+ now: Date.now,
+ });
+ // Share each newly established personal version: after a generation settles
+ // (a failed one has already been rolled back) and after an official update this
+ // session watched being adopted. A result restored at startup is not replayed.
+ let building = cindyMakeManager.isPersonalBuildRunning();
+ let merge = cindyMakeManager.getState().upstreamMerge;
+ let recorded = '';
+ cindyMakeManager.subscribe((state) => {
+ let changed = false;
+ const running = cindyMakeManager.isPersonalBuildRunning();
+ if (building && !running) changed = true;
+ building = running;
+ const next = state.upstreamMerge;
+ // Every adopted official update or combine (also one restored at startup) is lineage
+ // that lets the upload replace the fork's version without losing a change.
+ const rewrite = next && adoptedRewrite(next);
+ const lineage = rewrite ? `${next!.id}:${rewrite.to}` : '';
+ // Only an adopted result is recorded here (and by the pre-move journal): a
+ // candidate the user abandons must never evict a real, still-reachable
+ // source from the trust ledger.
+ if (rewrite && lineage !== recorded) {
+ recorded = lineage;
+ try {
+ journalMergeProvenance(next!);
+ } catch (error) {
+ // A late re-record of an already-adopted result may fail harmlessly: the
+ // pre-move journal has guarded the adoption itself (see
+ // `journalMergeProvenance`).
+ log.warn('cindy-make personal remote: lineage not recorded', {
+ error: error instanceof Error ? error.name : 'unknown',
+ });
+ }
+ }
+ if (
+ next?.status === 'merged' &&
+ !next.feature &&
+ merge?.id === next.id &&
+ merge.status !== 'merged'
+ )
+ changed = true;
+ merge = next;
+ if (changed) controller?.autoSync();
+ });
+}
+
+/**
+ * Whether the personal version at `commit` carries changes that are not generated
+ * on this computer yet and a failed generation could still undo (or a build
+ * rollback is pending): it is not established yet. The managed source is shared
+ * by every Cindy account on the device while the build history stays
+ * account-isolated, so the answer combines the account's own facts with the
+ * device-level record kept beside the source (see `pendingBuild`): "this account
+ * has no receipts for it" never reads as "nothing is pending".
+ */
+export async function hasUnbuiltPersonalChanges(commit: string, tree: string): Promise<boolean> {
+ const userData = app.getPath('userData');
+ return unbuiltPersonalChanges(
+ captureMakeHistoryStore(),
+ makeSourceRoot(userData),
+ { commit, tree },
+ (candidate) => hasPublishedPersonalVersionCommit(userData, candidate),
+ );
+}
+
+/**
+ * Durably record where an adopted update or combine carried content this computer
+ * has not verified yet, and the rewrite that carries it under new commits. Called
+ * before the personal source moves to the rewritten result: afterwards the old tip
+ * is no longer an ancestor of the result, and a crash between the move and the
+ * merged-state publish must never leave the carried content looking verified.
+ * A failure to write these facts must stop the adoption, so it is never swallowed
+ * here — only the subscriber's late re-record may tolerate one.
+ */
+export function journalMergeProvenance(state: {
+ status: string;
+ feature?: unknown;
+ baselineCommit?: string;
+ commit?: string;
+ tree?: string;
+ remote?: { commit?: string };
+}): void {
+ const rewrite = adoptedRewrite(state);
+ if (!rewrite) return;
+ if (!controller) throw new Error('personal remote not configured');
+ if (state.remote?.commit) controller.recordUnverifiedRemote(state.remote.commit);
+ controller.recordRewrite(rewrite.from, rewrite.to);
+ // Recorded pending facts follow the content into the rewritten result that
+ // carries them; a result that combined in a GitHub version carries changes
+ // that are not generated on this computer yet either way (see `pendingBuild`).
+ if (state.commit && state.tree) {
+ const root = makeSourceRoot(app.getPath('userData'));
+ rewritePendingBuilds(root, rewrite.from, { commit: state.commit, tree: state.tree });
+ if (state.remote?.commit) recordPendingBuild(root, { commit: state.commit, tree: state.tree });
+ }
+}
+
+/** The GitHub steps of Sync; undefined when the personal version is not shared there. */
+export function personalRemoteForSync(): PersonalSyncRemote | undefined {
+ const remote = controller;
+ const state = remote?.state();
+ if (!remote || !state?.repository || state.choice !== 'github') return undefined;
+ return {
+ sync: () => remote.syncNow(),
+ tips: () => remote.fetchedTips(),
+ keep: (side) => remote.keepSide(side),
+ };
+}
+
+/** Public, read-only facts for Mobile's Cindy Make task resource. */
+export async function readPersonalRemoteProjection(): Promise<
+ MakeRemotePersonalSnapshot | undefined
+> {
+ let remote: MakeRemotePersonalSnapshot['remote'];
+ let personalSync: MakeRemotePersonalSnapshot['personalSync'];
+ try {
+ const state = controller?.state();
+ if (state?.sync || state?.error)
+ remote = {
+ ...(state.sync ? { sync: state.sync } : {}),
+ ...(state.error ? { error: state.error } : {}),
+ };
+ } catch {
+ // A malformed trust ledger remains unreadable and must not be normalized for a remote read.
+ }
+ personalSync = cindyMakeManager.getState().personalSync;
+ let contributions: MakeRemotePersonalSnapshot['contributions'];
+ try {
+ contributions = await Promise.race([
+ contribution?.statuses() ?? Promise.resolve([]),
+ new Promise<undefined>((resolve) => setTimeout(() => resolve(undefined), 1_000)),
+ ]);
+ } catch {
+ contributions = undefined;
+ }
+ if (!remote && !personalSync && !contributions?.length) return undefined;
+ return {
+ ...(remote ? { remote } : {}),
+ ...(personalSync ? { personalSync } : {}),
+ ...(contributions?.length
+ ? {
+ contributions: contributions.slice(-8).map(({ number, state }) => ({ number, state })),
+ }
+ : {}),
+ };
+}
+
+/** A new task branches from `cindy-personal`: include changes saved by other computers first. */
+export async function syncPersonalRemoteBeforeTask(): Promise<void> {
+ try {
+ await controller?.syncBeforeTask();
+ } catch {
+ // Never block a task; the Settings row reports a failed synchronization.
+ }
+}
+
+/** IPC body for `app:cindy-make-personal-remote`; local Desktop only, no device-link grant. */
+export async function actPersonalRemote(raw: unknown): Promise<CindyMakePersonalRemoteState> {
+ if (typeof raw !== 'string' || !(CINDY_MAKE_REMOTE_ACTIONS as readonly string[]).includes(raw))
+ throwIpcError('INVALID_PARAMS', 'Invalid personal remote action');
+ if (!controller) throwIpcError('PRECONDITION_FAILED', 'Personal remote is unavailable');
+ const action = raw as CindyMakePersonalRemoteAction;
+ try {
+ switch (action) {
+ case 'status':
+ return await controller.status();
+ case 'refresh':
+ return await controller.refresh();
+ case 'save':
+ return controller.save();
+ case 'sync':
+ return controller.sync();
+ case 'keep-local':
+ return controller.keepLocal();
+ case 'disconnect':
+ return await controller.disconnect();
+ }
+ } catch (error) {
+ if (error instanceof PersonalRemoteError) throwIpcError('PRECONDITION_FAILED', error.code);
+ if ((error as { code?: unknown })?.code === 'busy')
+ throwIpcError('PRECONDITION_FAILED', 'busy');
+ throwIpcError('PRECONDITION_FAILED', 'Personal remote is unavailable');
+ }
+}
+
+const textField = (value: unknown, max: number): value is string =>
+ typeof value === 'string' && value.length <= max;
+
+/** IPC body for `app:cindy-make-contribution`; submitting is local Desktop only. */
+export async function actCindyMakeContribution(
+ raw: unknown,
+): Promise<CindyMakeContributionView[] | CindyMakeContributionDraft | CindyMakeContributionView> {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
+ throwIpcError('INVALID_PARAMS', 'Invalid contribution request');
+ const input = raw as Record<string, unknown>;
+ const service = contribution;
+ if (!service) throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ if (input.action === 'status') return service.statuses();
+ if (typeof input.runId !== 'string' || !/^[A-Za-z0-9-]{1,128}$/.test(input.runId))
+ throwIpcError('INVALID_PARAMS', 'Invalid contribution change');
+ const runId = input.runId;
+ if (input.action === 'submit' && !textField(input.snapshotId, 128))
+ throwIpcError('PRECONDITION_FAILED', 'changed');
+ const submit =
+ input.action === 'submit' &&
+ textField(input.title, CONTRIBUTION_LIMITS.title) &&
+ textField(input.body, CONTRIBUTION_LIMITS.body) &&
+ textField(input.name, CONTRIBUTION_LIMITS.name) &&
+ textField(input.email, CONTRIBUTION_LIMITS.email);
+ if (input.action !== 'draft' && !submit)
+ throwIpcError('INVALID_PARAMS', 'Invalid contribution request');
+ try {
+ return input.action === 'draft'
+ ? await service.draft(runId)
+ : await service.submit({
+ runId,
+ snapshotId: input.snapshotId as string,
+ title: input.title as string,
+ body: input.body as string,
+ name: input.name as string,
+ email: input.email as string,
+ });
+ } catch (error) {
+ if (error instanceof ContributionError) throwIpcError('PRECONDITION_FAILED', error.code);
+ throwIpcError('PRECONDITION_FAILED', 'failed');
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/personalSync.ts b/apps/desktop/src/main/cindy-make/personalSync.ts
new file mode 100644
index 0000000000..86a87fb34e
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/personalSync.ts
@@ -0,0 +1,429 @@
+import type { CindyMakeTaskOptions } from '../../shared/cindyMakeDoctor.js';
+import type { CindyMakeMergeState } from '../../shared/cindyMakeMerge.js';
+import type { CindyMakeRemoteSync } from '../../shared/cindyMakePersonalRemote.js';
+import type {
+ CindyMakeSyncDone,
+ CindyMakeSyncError,
+ CindyMakeSyncState,
+ CindyMakeSyncStep,
+ CindyMakeSyncWaiting,
+} from '../../shared/cindyMakeSync.js';
+import type { SyncTarget } from './syncTarget.js';
+import { resumable } from './upstreamMergeController.js';
+
+/** Sharing through the user's GitHub; absent when the personal version stays on this computer. */
+export interface PersonalSyncRemote {
+ /** Fetch, take over what is safe and upload established changes; the resulting state. */
+ sync(): Promise<CindyMakeRemoteSync | undefined>;
+ /** The GitHub version the last fetch saw, with its official base. */
+ tips(): Promise<{ commit: string; base: string } | undefined>;
+ /** Keep one side when the two cannot be combined; the other stays backed up. */
+ keep(side: 'github' | 'local'): Promise<CindyMakeRemoteSync | undefined>;
+}
+
+/** What survives a restart: the operation Sync waits for, and the last result. */
+export interface PersonalSyncRecord {
+ waiting?: string;
+ done?: CindyMakeSyncDone;
+}
+
+export interface PersonalSyncDeps {
+ remote(): PersonalSyncRemote | undefined;
+ target(): Promise<SyncTarget>;
+ /**
+ * Official commit this computer's personal version is based on. Recorded on first
+ * use when an older source has none, so every later step reads the same base.
+ */
+ base(): Promise<string | undefined>;
+ isAncestor(ancestor: string, descendant: string): Promise<boolean>;
+ /**
+ * The personal version carries changes not generated yet. An official update would
+ * rewrite them out of reach of the rollback a failed generation needs, so it waits.
+ */
+ unbuilt(): Promise<boolean>;
+ /** The retained source operation, if any. */
+ operation(): CindyMakeMergeState | undefined;
+ /** Finish a retained source operation first; opens its conflict task when it has none. */
+ resume(options?: CindyMakeTaskOptions): Promise<CindyMakeMergeState | undefined>;
+ combine(
+ remote: { commit: string; base: string },
+ options?: CindyMakeTaskOptions,
+ ): Promise<CindyMakeMergeState | undefined>;
+ update(
+ target: { ref: string; commit: string },
+ options?: CindyMakeTaskOptions,
+ ): Promise<CindyMakeMergeState | undefined>;
+ /** Stop the conflict task and discard its candidate; nothing is adopted. */
+ abandon(operationId: string): Promise<CindyMakeMergeState | undefined>;
+ /** Use a checked result although some changes are missing from it (the user's decision). */
+ accept(operationId: string): Promise<CindyMakeMergeState | undefined>;
+ /** Keep builds from starting while Sync moves the source; returns the release. */
+ reserve(): () => void;
+ load(): PersonalSyncRecord;
+ save(record: PersonalSyncRecord): void;
+ publish(state: CindyMakeSyncState): void;
+ now(): number;
+ log?: { warn(message: string, data?: Record<string, unknown>): void };
+}
+
+const syncError = (code: CindyMakeSyncError) => Object.assign(new Error(code), { syncCode: code });
+function classify(error: unknown): CindyMakeSyncError {
+ const own = (error as { syncCode?: CindyMakeSyncError })?.syncCode;
+ if (own) return own;
+ const code = (error as { code?: string })?.code;
+ if (code === 'busy') return 'busy';
+ if (code === 'github' || code === 'account' || code === 'workflowScope') return 'github';
+ if (code === 'network') return 'network';
+ if (code === 'gitOutdated') return 'gitOutdated';
+ if (code === 'forkMissing' || code === 'forkUnavailable') return 'forkMissing';
+ if (code === 'forkArchived') return 'forkArchived';
+ if (code === 'source' || code === 'dirty' || code === 'baselineChanged') return 'source';
+ if (code === 'unavailable') return 'unavailable';
+ return 'failed';
+}
+
+/**
+ * The line a retained source operation shows while it is not adopted, or undefined
+ * when it is not Sync's to show (finished, a change-history operation, or another
+ * account's).
+ */
+export function syncWaiting(state: CindyMakeMergeState | undefined): CindyMakeSyncWaiting | undefined {
+ if (
+ !state ||
+ state.feature ||
+ state.hasWorkspace !== true ||
+ !['conflict', 'resolving', 'checking', 'failed'].includes(state.status)
+ )
+ return undefined;
+ // Shown, never handled here: only its own account may continue or abandon it.
+ if (state.ownedByAnotherAccount)
+ return { kind: state.remote ? 'combine' : 'official', reason: 'otherAccount' };
+ // A cancellation that failed is offered again through Abandon, not shown as progress.
+ const abandoning = !!state.cancellationRequested && state.status !== 'failed';
+ const reason: CindyMakeSyncWaiting['reason'] = abandoning
+ ? 'working'
+ : state.needsInput
+ ? 'input'
+ : resumable(state)
+ ? 'paused'
+ : state.status !== 'failed'
+ ? 'working'
+ : state.error === 'interrupted'
+ ? 'interrupted'
+ : state.error === 'checksFailed' && state.missing
+ ? 'missing'
+ : state.error === 'baselineChanged'
+ ? 'stale'
+ : 'failed';
+ return {
+ kind: state.remote ? 'combine' : 'official',
+ reason,
+ ...(state.sessionId ? { sessionId: state.sessionId } : {}),
+ ...(reason === 'missing' ? { missing: state.missing!.count } : {}),
+ ...(abandoning ? { abandoning: true } : {}),
+ };
+}
+
+const sameWaiting = (a?: CindyMakeSyncWaiting, b?: CindyMakeSyncWaiting) =>
+ JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
+
+/**
+ * The single Sync of a personal version. Every step decides from the current Git
+ * facts what is left to do, so pressing Sync again, a restart or a finished
+ * conflict task simply continue where the work stopped. Durable state lives in
+ * the shared source-merge lifecycle and the GitHub binding; Sync only remembers
+ * which operation it waits for and its last result.
+ */
+export class PersonalSync {
+ private current: CindyMakeSyncState = {};
+ private active?: Promise<void>;
+ /** The operation this Sync waits for, and the preferences to continue with. */
+ private waitingFor?: { operationId: string; options?: CindyMakeTaskOptions };
+ private done?: CindyMakeSyncDone;
+
+ constructor(private readonly deps: PersonalSyncDeps) {
+ let record: PersonalSyncRecord = {};
+ try {
+ record = deps.load();
+ } catch {
+ // Nothing to continue: Sync starts fresh.
+ }
+ if (record.waiting) this.waitingFor = { operationId: record.waiting };
+ this.done = record.done;
+ this.current = this.done ? { done: this.done } : {};
+ this.operationChanged(deps.operation(), true);
+ }
+
+ state(): CindyMakeSyncState {
+ return this.current;
+ }
+
+ /** Start Sync (a no-op while one runs); progress arrives through `publish`. */
+ sync(options?: CindyMakeTaskOptions, keep?: 'github' | 'local'): CindyMakeSyncState {
+ if (!this.active) {
+ this.active = this.run(options, keep).finally(() => {
+ this.active = undefined;
+ // An operation that changed while Sync ran is shown now.
+ this.operationChanged(this.deps.operation());
+ });
+ }
+ return this.current;
+ }
+
+ settled(): Promise<void> {
+ return this.active ?? Promise.resolve();
+ }
+
+ /** Give up the operation Sync waits for; both versions stay as they were. */
+ async abandon(): Promise<CindyMakeSyncState> {
+ const operation = this.deps.operation();
+ const line = syncWaiting(operation);
+ if (this.active || !operation || !line || line.reason === 'otherAccount') return this.current;
+ this.adopt(operation.id);
+ try {
+ this.operationChanged(await this.deps.abandon(operation.id));
+ } catch (error) {
+ this.set({ ...this.current, error: classify(error) });
+ }
+ return this.current;
+ }
+
+ /**
+ * The two personal versions cannot be combined, or the user gave up combining them:
+ * keep one side as chosen, then continue like Sync. Only offered with GitHub.
+ */
+ keep(side: 'github' | 'local', options?: CindyMakeTaskOptions): CindyMakeSyncState {
+ const choosable =
+ this.current.error === 'diverged' ||
+ (this.current.error === 'cancelled' && this.current.abandoned === 'combine');
+ if (this.active || !choosable || !this.deps.remote()) return this.current;
+ return this.sync(options, side);
+ }
+
+ /** Use the result although the named changes are missing; Sync then continues. */
+ async accept(): Promise<CindyMakeSyncState> {
+ const operation = this.deps.operation();
+ if (this.active || !operation || syncWaiting(operation)?.reason !== 'missing')
+ return this.current;
+ this.adopt(operation.id);
+ try {
+ this.operationChanged(await this.deps.accept(operation.id));
+ } catch (error) {
+ this.set({ ...this.current, error: classify(error) });
+ }
+ return this.current;
+ }
+
+ /**
+ * The shared source operation changed: continue a Sync that waited for it, or show it.
+ * At startup an operation adopted before the restart is not continued unasked.
+ */
+ operationChanged(state: CindyMakeMergeState | undefined, restoring = false): void {
+ const waiting = this.waitingFor;
+ if (waiting && state?.id === waiting.operationId) {
+ if (state.status === 'merged') {
+ this.wait(undefined);
+ if (!restoring) this.sync(waiting.options);
+ return;
+ }
+ if (state.status === 'cancelled') {
+ this.wait(undefined);
+ if (!this.active)
+ this.set({
+ error: 'cancelled',
+ abandoned: state.remote ? 'combine' : 'official',
+ ...this.kept(),
+ });
+ return;
+ }
+ } else if (waiting && state && state.id !== waiting.operationId) {
+ // Replaced by a newer operation: there is nothing of the old one to continue.
+ this.wait(undefined);
+ }
+ // While Sync runs it publishes its own steps.
+ if (this.active) return;
+ const line = syncWaiting(state);
+ if (line) {
+ if (!sameWaiting(this.current.waiting, line)) this.set({ waiting: line, ...this.kept() });
+ } else if (this.current.waiting) {
+ this.set(this.kept());
+ }
+ }
+
+ private set(next: CindyMakeSyncState): void {
+ this.current = next;
+ this.deps.publish(next);
+ }
+
+ private kept(): Pick<CindyMakeSyncState, 'done'> {
+ return this.done ? { done: this.done } : {};
+ }
+
+ private persist(): void {
+ try {
+ this.deps.save({
+ ...(this.waitingFor ? { waiting: this.waitingFor.operationId } : {}),
+ ...(this.done ? { done: this.done } : {}),
+ });
+ } catch {
+ // The in-memory state still continues Sync in this session.
+ }
+ }
+
+ private wait(waiting: PersonalSync['waitingFor']): void {
+ this.waitingFor = waiting;
+ this.persist();
+ }
+
+ /** Sync continues once this operation is adopted, whoever started it. */
+ private adopt(operationId: string): void {
+ if (this.waitingFor?.operationId !== operationId)
+ this.wait({ operationId, options: this.waitingFor?.options });
+ }
+
+ private step(step: CindyMakeSyncStep): void {
+ if (this.current.running && this.current.step === step) return;
+ this.set({ running: true, step, ...this.kept() });
+ }
+
+ /** The operation needs its task or the user: remember it and stop until it is adopted. */
+ private waits(
+ result: CindyMakeMergeState | undefined,
+ options: CindyMakeTaskOptions | undefined,
+ ): boolean {
+ const line = syncWaiting(result);
+ if (!line) return false;
+ this.wait({ operationId: result!.id, options });
+ this.set({ waiting: line, ...this.kept() });
+ return true;
+ }
+
+ private adopted(result: CindyMakeMergeState | undefined): void {
+ if (result?.status === 'merged') return;
+ if (result?.status === 'cancelled') throw syncError('cancelled');
+ throw Object.assign(new Error(result?.error ?? 'failed'), { code: result?.error });
+ }
+
+ private async run(options?: CindyMakeTaskOptions, keep?: 'github' | 'local'): Promise<void> {
+ let release: (() => void) | undefined;
+ try {
+ release = this.deps.reserve();
+ // 1. An earlier operation (this session or before a restart) is finished first.
+ const retained = this.deps.operation();
+ if (retained?.feature && retained.hasWorkspace && retained.status !== 'merged')
+ throw syncError('featurePending');
+ if (syncWaiting(retained)?.reason === 'otherAccount') {
+ this.set({ waiting: syncWaiting(retained)!, ...this.kept() });
+ return;
+ }
+ if ((retained?.hasWorkspace || retained?.cancellationRequested) && retained.status !== 'merged') {
+ this.step('resuming');
+ if (this.waits(await this.deps.resume(options), options)) return;
+ }
+ this.step(this.deps.remote() ? 'github' : 'official');
+ if (!(await this.deps.base())) throw syncError('source');
+ if (keep) {
+ const remote = this.deps.remote();
+ if (!remote) throw syncError('source');
+ await remote.keep(keep);
+ }
+
+ let done: Omit<CindyMakeSyncDone, 'at'> = {};
+ let sharing: CindyMakeSyncError | undefined;
+ // Another computer may upload while this one combines: take that in once more.
+ for (let round = 0; round < 2; round += 1) {
+ const outcome = await this.round(options);
+ if (outcome === 'waiting') return;
+ ({ done, sharing } = outcome);
+ if (sharing !== 'changed') break;
+ }
+ this.done = { at: this.deps.now(), ...done };
+ this.persist();
+ this.set(sharing ? { error: sharing, done: this.done } : { done: this.done });
+ } catch (error) {
+ const code = classify(error);
+ this.deps.log?.warn('cindy-make sync stopped', { code });
+ this.set({ error: code, ...this.kept() });
+ } finally {
+ release?.();
+ }
+ }
+
+ /** Take in GitHub's changes, move to the official version and upload once. */
+ private async round(
+ options: CindyMakeTaskOptions | undefined,
+ ): Promise<'waiting' | { done: Omit<CindyMakeSyncDone, 'at'>; sharing?: CindyMakeSyncError }> {
+ // 2. Changes saved by other computers. Safe cases are taken over by the binding;
+ // overlapping ones are combined in the shared lifecycle. A GitHub problem never
+ // stops the official update on this computer; it is reported at the end.
+ const remote = this.deps.remote();
+ let sharing: CindyMakeSyncError | undefined;
+ let buildFirst = false;
+ let tips: { commit: string; base: string } | undefined;
+ if (remote) {
+ this.step('github');
+ try {
+ const shared = await remote.sync();
+ if (shared === 'diverged') sharing = 'diverged';
+ // The source was busy or dirty: nothing was taken in or uploaded this time.
+ else if (shared === 'pending') sharing = 'busy';
+ else if (shared === 'buildFirst') buildFirst = true;
+ else if (shared === 'needsMerge') tips = (await remote.tips()) ?? undefined;
+ } catch (error) {
+ sharing = classify(error);
+ }
+ if (tips) {
+ this.step('combine');
+ const result = await this.deps.combine(tips, options);
+ if (this.waits(result, options)) return 'waiting';
+ this.adopted(result);
+ }
+ }
+
+ // 3. The official version, never moving backwards.
+ this.step('official');
+ const target = await this.deps.target();
+ let base = await this.deps.base();
+ if (!base) throw syncError('source');
+ let generateFirst = false;
+ if (base !== target.commit && !(await this.deps.isAncestor(target.commit, base))) {
+ if (await this.deps.unbuilt()) generateFirst = true;
+ else {
+ const result = await this.deps.update(target, options);
+ if (this.waits(result, options)) return 'waiting';
+ this.adopted(result);
+ base = target.commit;
+ }
+ }
+
+ // 4. Share the result.
+ let uploadAfterBuild = false;
+ if (remote && !sharing && !buildFirst) {
+ this.step('upload');
+ try {
+ const shared = await remote.sync();
+ if (shared === 'diverged') sharing = 'diverged';
+ else if (shared === 'pending') sharing = 'busy';
+ // Not generated yet: it is uploaded automatically after the next generation.
+ else if (shared === 'pendingBuild') uploadAfterBuild = true;
+ else if (shared === 'buildFirst') buildFirst = true;
+ // Another computer uploaded meanwhile.
+ else if (shared === 'needsMerge' || shared === 'remoteAhead') sharing = 'changed';
+ } catch (error) {
+ sharing = classify(error);
+ }
+ }
+ return {
+ done: {
+ // On a newer official version than the target (another computer's): no version name;
+ // still on an older one because changes wait to be generated: named by Settings.
+ ...(base === target.commit ? { ref: target.ref } : generateFirst ? {} : { ahead: true }),
+ ...(target.held ? { held: target.held.ref } : {}),
+ ...(uploadAfterBuild ? { uploadAfterBuild: true } : {}),
+ ...(buildFirst ? { buildFirst: true } : {}),
+ ...(generateFirst ? { generateFirst: target.ref } : {}),
+ },
+ ...(sharing ? { sharing } : {}),
+ };
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/personalSyncRuntime.ts b/apps/desktop/src/main/cindy-make/personalSyncRuntime.ts
new file mode 100644
index 0000000000..c431cfdd0b
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/personalSyncRuntime.ts
@@ -0,0 +1,181 @@
+import path from 'node:path';
+import { mkdirSync } from 'node:fs';
+import { app } from 'electron';
+import type { CindyMakeSyncDone, CindyMakeSyncState } from '../../shared/cindyMakeSync.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+import { createLogger } from '../logger.js';
+import { cindyMakeManager } from './manager.js';
+import { PersonalSync, type PersonalSyncRecord } from './personalSync.js';
+import { hasUnbuiltPersonalChanges, personalRemoteForSync } from './personalRemoteRuntime.js';
+import { PERSONAL_UPSTREAM_REF } from './sourceContent.js';
+import { runSourceGit } from './sourceGit.js';
+import { CINDY_PERSONAL_BRANCH, makeSourceCheckoutPath, makeSourceRoot } from './sourcePaths.js';
+import { readCurrentCindySourceStatus } from './sourcePreparation.js';
+import { validateCindyMakeTaskStart } from './taskRuntime.js';
+import {
+ createMakeToolchainEnvironment,
+ resolveMakeToolEnvironment,
+} from './toolchainEnvironment.js';
+import {
+ abandonForSync,
+ acceptForSync,
+ combineForSync,
+ resolveSyncTarget,
+ resumeForSync,
+ sourceOperation,
+ updateForSync,
+} from './upstreamMergeRuntime.js';
+
+const COMMIT = /^[0-9a-f]{40}$/i;
+const OPERATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+/** Only well-formed values survive; anything else is a fresh start. */
+export function parseSyncRecord(raw: string | null): PersonalSyncRecord {
+ let saved: { waiting?: unknown; done?: unknown } = {};
+ try {
+ const parsed: unknown = JSON.parse(raw ?? '{}');
+ // A truncated or otherwise malformed record is a fresh start, never a throw:
+ // `load` runs at bootstrap, and the fresh record the contract promises must
+ // not depend on a caller catching for it.
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
+ saved = parsed as { waiting?: unknown; done?: unknown };
+ } catch {
+ saved = {};
+ }
+ const record: PersonalSyncRecord = {};
+ if (typeof saved.waiting === 'string' && OPERATION_ID.test(saved.waiting))
+ record.waiting = saved.waiting;
+ const done = saved.done as Partial<CindyMakeSyncDone> | undefined;
+ if (done && typeof done === 'object' && Number.isSafeInteger(done.at)) {
+ const text = (value: unknown) =>
+ typeof value === 'string' && value.length > 0 && value.length <= 128 ? value : undefined;
+ const ref = text(done.ref);
+ const held = text(done.held);
+ record.done = {
+ at: done.at!,
+ ...(ref ? { ref } : {}),
+ ...(held ? { held } : {}),
+ ...(done.ahead === true ? { ahead: true } : {}),
+ ...(done.uploadAfterBuild === true ? { uploadAfterBuild: true } : {}),
+ ...(done.buildFirst === true ? { buildFirst: true } : {}),
+ ...(text(done.generateFirst) ? { generateFirst: text(done.generateFirst) } : {}),
+ };
+ }
+ return record;
+}
+
+const log = createLogger('cindy-make');
+let sync: PersonalSync | undefined;
+
+/** Called at bootstrap after the source-merge lifecycle and the GitHub binding. */
+export function configurePersonalSync(): void {
+ const userData = app.getPath('userData');
+ const root = makeSourceRoot(userData);
+ const source = makeSourceCheckoutPath(userData);
+ // Beside the checkout like the other source-operation records; not owner data.
+ const recordFile = path.join(root, 'sync.json');
+ const git = async (args: string[]) => {
+ const signal = AbortSignal.timeout(60_000);
+ const tools = await createMakeToolchainEnvironment(userData);
+ const env = await resolveMakeToolEnvironment(tools, ['git'], signal);
+ return runSourceGit(env, args, source, signal);
+ };
+ const isAncestor = (ancestor: string, descendant: string) =>
+ git(['merge-base', '--is-ancestor', ancestor, descendant]).then(
+ () => true,
+ (error) => {
+ if ((error as { exitCode?: number }).exitCode === 1) return false;
+ throw error;
+ },
+ );
+ const readCommit = async (ref: string) => {
+ const commit = (
+ await git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).catch(() => '')
+ ).trim();
+ return COMMIT.test(commit) ? commit : undefined;
+ };
+ sync = new PersonalSync({
+ remote: personalRemoteForSync,
+ target: resolveSyncTarget,
+ base: async () => {
+ const recorded = await readCommit(PERSONAL_UPSTREAM_REF);
+ const personal = await readCommit(`refs/heads/${CINDY_PERSONAL_BRANCH}`);
+ // The recorded base is trusted only as the personal tip's ancestor — the
+ // same clamp as the source-status and merge-runtime reads: an interrupted
+ // move leaves "old tip + new base", and Sync seeing that base would skip
+ // the update it needs while the source stays old. The shared history of
+ // the two recovers the base the tip really sits on.
+ if (recorded && (!personal || (await isAncestor(recorded, personal)))) return recorded;
+ const clamped =
+ recorded && personal
+ ? (await git(['merge-base', personal, recorded]).catch(() => '')).trim()
+ : '';
+ if (COMMIT.test(clamped)) return clamped;
+ // Sources prepared before the base was recorded: the official commit they were made
+ // from (the same fallback the status uses). Recorded once so the combine reads it too.
+ const tools = await createMakeToolchainEnvironment(userData);
+ const derived = (await readCurrentCindySourceStatus(root, tools)).baseCommit;
+ if (!derived || !COMMIT.test(derived) || !personal || !(await isAncestor(derived, personal)))
+ return undefined;
+ // Create-only: never overwrites a base recorded meanwhile.
+ await git(['update-ref', PERSONAL_UPSTREAM_REF, derived, '']).catch(() => undefined);
+ return readCommit(PERSONAL_UPSTREAM_REF);
+ },
+ isAncestor,
+ unbuilt: async () => {
+ const commit = await readCommit(`refs/heads/${CINDY_PERSONAL_BRANCH}`);
+ if (!commit) return false;
+ const tree = (await git(['rev-parse', `${commit}^{tree}`])).trim();
+ return hasUnbuiltPersonalChanges(commit, tree);
+ },
+ operation: sourceOperation,
+ resume: resumeForSync,
+ combine: combineForSync,
+ update: updateForSync,
+ abandon: abandonForSync,
+ accept: acceptForSync,
+ reserve: () => cindyMakeManager.claimManualSourceSync(),
+ load: () => parseSyncRecord(readAtomicFileSync(recordFile)),
+ save: (record) => {
+ mkdirSync(path.dirname(recordFile), { recursive: true });
+ atomicWriteFileSync(recordFile, JSON.stringify(record));
+ },
+ publish: (state) => cindyMakeManager.setPersonalSync(state),
+ now: Date.now,
+ log,
+ });
+ cindyMakeManager.setPersonalSync(sync.state());
+ // A conflict task Sync waited for was adopted (or abandoned): continue or report.
+ cindyMakeManager.subscribe((state) => sync?.operationChanged(state.upstreamMerge));
+}
+
+/** IPC body for `app:cindy-make-sync`; local Desktop only, no device-link grant. */
+export async function actPersonalSync(raw: unknown): Promise<CindyMakeSyncState> {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
+ throwIpcError('INVALID_PARAMS', 'Invalid sync request');
+ const { action, createOptions, side } = raw as Record<string, unknown>;
+ if (
+ action !== 'sync' &&
+ action !== 'status' &&
+ action !== 'abandon' &&
+ action !== 'accept' &&
+ action !== 'keep'
+ )
+ throwIpcError('INVALID_PARAMS', 'Invalid sync action');
+ if (action === 'keep' && side !== 'github' && side !== 'local')
+ throwIpcError('INVALID_PARAMS', 'Invalid sync side');
+ if (!sync) throwIpcError('PRECONDITION_FAILED', 'unavailable');
+ if (action === 'status') return sync.state();
+ if (action === 'abandon') return sync.abandon();
+ if (action === 'accept') return sync.accept();
+ const options = validateCindyMakeTaskStart({
+ runId: 'sync',
+ request: 'sync',
+ title: 'sync',
+ createOptions,
+ }).createOptions;
+ return action === 'keep'
+ ? sync.keep(side as 'github' | 'local', options)
+ : sync.sync(options);
+}
diff --git a/apps/desktop/src/main/cindy-make/pnpmWriteRoots.ts b/apps/desktop/src/main/cindy-make/pnpmWriteRoots.ts
new file mode 100644
index 0000000000..284f3d4188
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/pnpmWriteRoots.ts
@@ -0,0 +1,810 @@
+import { lstat, readFile, readdir, readlink, realpath } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import yaml from 'js-yaml';
+import { list as tarList, type ReadEntry } from 'tar';
+
+/**
+ * Containment for dependency installation of content nobody has verified yet
+ * (fork collaborators' synced commits, see `remoteContentScriptsUnverified`).
+ *
+ * `pnpm install --ignore-scripts --ignore-pnpmfile` keeps content-controlled code
+ * from running at install time, but pnpm still writes wherever its write roots
+ * point, and content controls those: a tracked `node_modules` symlink makes it
+ * install through the link (pnpm creates `<write root>/<dependency name>`, so the
+ * link location is the write root), and `.npmrc` / `pnpm-workspace.yaml` settings
+ * such as `store-dir`, `modules-dir` or `virtualStoreDir` move the write roots
+ * outright. Before such an install every pnpm write root must be a real
+ * descendant of the worktree:
+ *
+ * - no symlink anywhere in the content resolves outside the worktree;
+ * - no content-controlled setting may move a write root or pick which code runs
+ * the install (path-shaped config keys and version-management switches are
+ * refused; the store then comes from the machine's own trusted user-level
+ * configuration or pnpm's default);
+ * - the prospective write roots themselves (`node_modules` and its virtual store
+ * under every package directory) still resolve inside the worktree when they
+ * already exist as links from a previous run;
+ * - every dependency name and every setting that generates dependency specs
+ * (`pnpm.overrides` and friends, even honored by a frozen lockfile) keeps
+ * inside the worktree: pnpm joins each installed name under its write roots,
+ * so a traversal name escapes no matter where the write roots point. That
+ * includes the transitive names of the frozen lockfile and of the archives a
+ * `file:` dependency installs from — no manifest check sees into those.
+ * - after the install, no link pnpm created may resolve outside the worktree
+ * (`assertPnpmInstallLinksContained`) — the pre-install scan cannot see into
+ * the write roots the install is about to populate.
+ *
+ * The check runs on the filesystem, not `git ls-files`: Git's captured output is
+ * truncated and quoted paths are escaped, and a reused worktree may hold links
+ * that are no longer tracked.
+ */
+
+const MAX_SCANNED_ENTRIES = 200_000;
+const MAX_CONFIG_BYTES = 8 * 1024 * 1024;
+const MAX_DEPTH = 128;
+const MAX_ARCHIVES = 512;
+const MAX_ARCHIVE_ENTRIES = 2048;
+
+function refuse(message: string): Error {
+ return Object.assign(new Error(message), { code: 'gitFailed' });
+}
+
+/** Config keys that move pnpm's writes or select the code that performs them. */
+const REFUSED_SETTINGS = new Set([
+ 'usenodeversion',
+ 'managepackagemanagerversions',
+ 'packagemanagerstrict',
+ 'userconfig',
+ 'globalconfig',
+ 'prefix',
+ 'globalprefix',
+ 'tmp',
+ 'temp',
+]);
+
+/**
+ * Whether a pnpm config key names a location. `store-dir`, `virtual-store-dir`,
+ * `modules-dir`, `userConfig` and friends do; `frozen-lockfile`, `node-linker`
+ * and `engine-strict` do not and keep working. Single-word location keys are in
+ * `REFUSED_SETTINGS` above. Kebab/underscore keys are matched on segment
+ * boundaries (`lockfile` is not a `-file` key); camelCase keys on the capital
+ * suffix (`storeDir`). pnpm itself only reads the kebab form in `.npmrc` and the
+ * camelCase form in `pnpm-workspace.yaml`; the wider net costs a refusal at
+ * worst, never an escape.
+ */
+function refusedSetting(key: string): boolean {
+ const name = key.trim();
+ if (!name) return false;
+ const normalized = name.toLowerCase().replace(/[^a-z0-9]/g, '');
+ if (REFUSED_SETTINGS.has(normalized)) return true;
+ // `configDependencies` (and any sub-key of it) selects the code that performs
+ // the writes: pnpm joins each entry's package name under `node_modules/.pnpm-config`,
+ // so a path-like name escapes the worktree no matter where the write roots point.
+ // Nothing unverified may configure dependencies at all.
+ if (normalized.startsWith('configdependencies')) return true;
+ return (
+ /(?:^|[-_])(?:dir|path|home|file|config)$/i.test(name) ||
+ /[a-z](?:Dir|Path|Home|File|Config)$/.test(name)
+ );
+}
+
+/**
+ * A name (or override key) that could turn into a path outside `node_modules`:
+ * `..` segments, absolute/drive paths, `~` and backslashes. Override keys stay
+ * patterns (`foo@^1`, `bar>baz`, `*`, the nested `.` selector), so this wider
+ * net only refuses names that could never match a package either.
+ */
+function refusedPathLikeName(name: string): boolean {
+ return (
+ !name ||
+ name.includes('\0') ||
+ name.includes('\\') ||
+ name.startsWith('~') ||
+ path.isAbsolute(name) ||
+ /^[a-zA-Z]:/.test(name) ||
+ /(^|\/)\.\.(\/|$)/.test(name)
+ );
+}
+
+/**
+ * An installed package name. pnpm joins it under `node_modules`, so anything
+ * outside `[@scope/]name` (leading dots, extra slashes, drive letters) can
+ * escape the write roots no matter where they point.
+ */
+function refusedDependencyName(name: string): boolean {
+ return (
+ refusedPathLikeName(name) ||
+ !/^(?:@[a-zA-Z0-9~][a-zA-Z0-9\-._~]*\/)?[a-zA-Z0-9_\-][a-zA-Z0-9\-._~]*$/.test(name)
+ );
+}
+
+/** Workspace globs stay relative and inside the tree: `..`, absolute paths and `~` leave it. */
+function refusedWorkspacePattern(value: unknown): boolean {
+ return (
+ typeof value !== 'string' ||
+ !value ||
+ path.isAbsolute(value) ||
+ /^[a-zA-Z]:/.test(value) ||
+ value.includes('\\') ||
+ value.startsWith('~') ||
+ /(^|\/)\.\.($|\/)/.test(value)
+ );
+}
+
+async function readConfig(file: string): Promise<string> {
+ const text = await readFile(file, 'utf8');
+ if (text.length > MAX_CONFIG_BYTES) throw refuse(`pnpm config too large: ${path.basename(file)}`);
+ return text;
+}
+
+/** The recognized pnpm configuration files: never accepted behind a symlink. */
+function isPnpmConfigName(name: string): boolean {
+ return (
+ name === '.npmrc' ||
+ name === 'pnpm-workspace.yaml' ||
+ name === 'pnpm-workspace.yml' ||
+ name === 'pnpm-lock.yaml' ||
+ name === 'pnpm-lock.yml' ||
+ name === 'package.json' ||
+ /pnpmfile\.(?:c|m)?js$/i.test(name)
+ );
+}
+
+/**
+ * The root configuration and frozen dependency graph pnpm reads first, checked
+ * without walking the tree: cache warming (`pnpm fetch`) skips entirely when
+ * content configures its own code (`configDependencies`), redirects writes or
+ * reads outside the tree. Installs run the full `assertPnpmInstallContained` walk.
+ */
+export async function assertPnpmConfigContained(root: string): Promise<void> {
+ for (const name of [
+ '.npmrc',
+ 'pnpm-workspace.yaml',
+ 'pnpm-workspace.yml',
+ 'package.json',
+ 'pnpm-lock.yaml',
+ 'pnpm-lock.yml',
+ ]) {
+ const full = path.join(root, name);
+ let entry;
+ try {
+ entry = await lstat(full);
+ } catch {
+ continue;
+ }
+ if (entry.isSymbolicLink()) throw refuse(`pnpm config is a symlink: ${name}`);
+ if (!entry.isFile()) continue;
+ if (name === '.npmrc') checkIni(full, await readConfig(full));
+ else if (name === 'package.json') checkPackageJson(full, root, await readConfig(full));
+ else if (name === 'pnpm-lock.yaml' || name === 'pnpm-lock.yml')
+ checkLockfile(full, root, await readConfig(full), new Set());
+ else checkWorkspaceYaml(full, root, await readConfig(full));
+ }
+}
+
+function checkIni(file: string, text: string): void {
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line || line.startsWith(';') || line.startsWith('#') || line.startsWith('[')) continue;
+ // npm's INI reads a bare line as a key set to true; treat it the same.
+ const separator = line.indexOf('=');
+ const key = (separator >= 0 ? line.slice(0, separator) : line).trim();
+ if (refusedSetting(key)) throw refuse(`pnpm config redirects writes: ${key}`);
+ }
+}
+
+function checkSettings(
+ where: string,
+ settings: Record<string, unknown>,
+ file: string,
+ base: string,
+ opts: SpecOptions = {},
+): void {
+ for (const [key, value] of Object.entries(settings)) {
+ if (refusedSetting(key)) throw refuse(`pnpm config redirects writes: ${key} in ${where}`);
+ if (key === 'packages' || key === 'workspaces') {
+ const patterns = Array.isArray(value) ? value : [value];
+ for (const pattern of patterns)
+ if (refusedWorkspacePattern(pattern))
+ throw refuse(`pnpm workspace leaves the worktree: ${String(pattern)}`);
+ }
+ // Settings that generate dependency specs when pnpm resolves: a frozen
+ // lockfile honors `overrides` values verbatim, so `link:../private` links
+ // the outside directory in even with every direct dependency checked.
+ if (key === 'overrides' || key === 'resolutions' || key === 'patchedDependencies')
+ checkSpecMap(file, base, `${where}#${key}`, value, 'pattern', 0, opts);
+ else if (key === 'catalog' || key === 'catalogs' || key === 'packageExtensions')
+ checkSpecMap(file, base, `${where}#${key}`, value, 'name', 0, opts);
+ }
+}
+
+/** The lockfile fields whose keys pnpm joins into write-root paths. */
+const LOCKFILE_DEPENDENCY_FIELDS = new Map<string, 'name' | 'pattern'>([
+ ['dependencies', 'name'],
+ ['devDependencies', 'name'],
+ ['optionalDependencies', 'name'],
+ ['peerDependencies', 'name'],
+ ['specifiers', 'name'],
+ ['overrides', 'pattern'],
+ ['resolutions', 'pattern'],
+ ['patchedDependencies', 'pattern'],
+ ['catalog', 'name'],
+ ['catalogs', 'name'],
+ ['packageExtensions', 'name'],
+]);
+
+/** Lockfile sections keyed by resolved package identifiers. */
+const LOCKFILE_ID_SECTIONS = new Set(['packages', 'snapshots']);
+
+/** A package identifier whose `..` segments could name the store directory. */
+function refusedLockfileId(id: string): boolean {
+ if (!id || id.includes('\0')) return true;
+ // `link+` identifiers name a workspace path pnpm symlinks to (checked through
+ // the spec); every other identifier materializes a store directory of its own.
+ return !id.startsWith('link+') && /(^|[\\/:])\.\.([\\/:]|$)/.test(id);
+}
+
+/**
+ * The frozen lockfile carries the whole transitive graph pnpm installs: its
+ * dependency names — including those of package metadata no manifest check
+ * ever saw — are joined under the write roots exactly like manifest names.
+ * Importer links resolve against that importer's directory. Resolved `file:`
+ * versions and package-snapshot links resolve against the lockfile directory;
+ * a different importer or the virtual store must never make an escape pass.
+ * `file:` values name the archives checked next.
+ */
+function checkLockfile(file: string, base: string, text: string, archives: Set<string>): void {
+ let lockfile: unknown;
+ try {
+ lockfile = yaml.load(text);
+ } catch {
+ throw refuse(`unparseable ${path.basename(file)}`);
+ }
+ if (lockfile === null || lockfile === undefined) return;
+ if (typeof lockfile !== 'object' || Array.isArray(lockfile))
+ throw refuse(`unrecognized ${path.basename(file)}`);
+ const root = path.dirname(file);
+ const { importers, ...graph } = lockfile as Record<string, unknown>;
+ checkLockfileNode(file, base, root, path.basename(file), graph, 0, archives);
+ if (importers !== undefined) {
+ if (typeof importers !== 'object' || importers === null || Array.isArray(importers))
+ throw refuse(`unrecognized ${path.basename(file)} importers`);
+ for (const [name, importer] of Object.entries(importers)) {
+ if (refusedWorkspacePattern(name))
+ throw refuse(`pnpm lockfile importer leaves the worktree: ${name}`);
+ checkLockfileNode(
+ file,
+ base,
+ path.resolve(root, name),
+ `${path.basename(file)}#importers#${name}`,
+ importer,
+ 0,
+ archives,
+ );
+ }
+ }
+}
+
+function checkLockfileNode(
+ file: string,
+ base: string,
+ directory: string,
+ where: string,
+ node: unknown,
+ depth: number,
+ archives: Set<string>,
+): void {
+ if (depth > 16) throw refuse(`pnpm lockfile nests too deeply: ${where}`);
+ if (Array.isArray(node)) {
+ for (const nested of node)
+ checkLockfileNode(file, base, directory, where, nested, depth + 1, archives);
+ return;
+ }
+ if (typeof node !== 'object' || node === null) return;
+ for (const [key, nested] of Object.entries(node as Record<string, unknown>)) {
+ const fields = LOCKFILE_DEPENDENCY_FIELDS.get(key);
+ if (fields) {
+ if (typeof nested !== 'object' || nested === null || Array.isArray(nested)) continue;
+ for (const [name, spec] of Object.entries(nested as Record<string, unknown>)) {
+ if (fields === 'name' ? refusedDependencyName(name) : refusedPathLikeName(name))
+ throw refuse(`pnpm dependency name leaves the worktree: ${name} in ${where}`);
+ const specWhere = `${where}#${key}#${name}`;
+ const resolvedDirectory = (value: unknown) =>
+ typeof value === 'string' && /^file:/i.test(value.trim())
+ ? path.dirname(file)
+ : directory;
+ if (typeof spec === 'object' && spec !== null && !Array.isArray(spec)) {
+ // Inline importer records contain both the requested specifier
+ // (importer-relative) and its frozen version (`file:` is root-relative).
+ const { version, ...metadata } = spec as Record<string, unknown>;
+ checkSpecMap(file, base, specWhere, metadata, fields, depth + 2, { archives, directory });
+ checkSpecMap(file, base, `${specWhere}#version`, version, fields, depth + 2, {
+ archives,
+ directory: resolvedDirectory(version),
+ });
+ continue;
+ }
+ checkSpecMap(file, base, specWhere, spec, fields, depth + 2, {
+ archives,
+ directory: key === 'specifiers' ? directory : resolvedDirectory(spec),
+ });
+ }
+ continue;
+ }
+ if (LOCKFILE_ID_SECTIONS.has(key) && typeof nested === 'object' && nested !== null) {
+ // Identifiers name the directories the store materializes packages into.
+ if (Array.isArray(nested)) throw refuse(`unrecognized ${where}`);
+ for (const id of Object.keys(nested as Record<string, unknown>))
+ if (refusedLockfileId(id))
+ throw refuse(`pnpm package identifier leaves the worktree: ${id}`);
+ }
+ if (key === 'resolution' && typeof nested === 'object' && nested !== null) {
+ const resolution = nested as Record<string, unknown>;
+ for (const field of ['directory', 'tarball', 'repo']) {
+ const value = resolution[field];
+ if (typeof value === 'string') {
+ // Git resolutions omit the `git+` prefix. Their file URLs still
+ // need URL decoding, not relative dependency-path interpretation.
+ const spec = field === 'repo' && /^file:/i.test(value.trim())
+ ? `git+${value.trim()}`
+ : value;
+ checkDependencySpec(file, base, `${where}#resolution#${field}`, spec, {
+ archives,
+ directory: path.dirname(file),
+ });
+ }
+ }
+ }
+ checkLockfileNode(file, base, directory, `${where}#${key}`, nested, depth + 1, archives);
+ }
+}
+
+/**
+ * A map whose values pnpm turns into installed dependency specs (or, for
+ * `patchedDependencies`, patch paths): values naming paths must resolve inside
+ * the worktree, and keys must not traverse out of the write roots. Nested
+ * entries (npm-style `"foo": { ".": "1" }` overrides, `catalogs`, package
+ * extension fields) recurse under the same rule.
+ */
+function checkSpecMap(
+ file: string,
+ base: string,
+ where: string,
+ value: unknown,
+ keys: 'name' | 'pattern',
+ depth = 0,
+ opts: SpecOptions = {},
+): void {
+ if (depth > 16) throw refuse(`pnpm dependency config nests too deeply: ${where}`);
+ if (typeof value === 'string') return checkDependencySpec(file, base, where, value, opts);
+ if (Array.isArray(value)) {
+ for (const nested of value) checkSpecMap(file, base, where, nested, keys, depth + 1, opts);
+ return;
+ }
+ if (typeof value !== 'object' || value === null) return;
+ for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
+ if (keys === 'name' ? refusedDependencyName(key) : refusedPathLikeName(key))
+ throw refuse(`pnpm dependency name leaves the worktree: ${key} in ${where}`);
+ checkSpecMap(file, base, `${where}#${key}`, nested, keys, depth + 1, opts);
+ }
+}
+
+/** The path a dependency spec names, or undefined for registry specs. */
+function specPathTarget(spec: string): string | undefined {
+ const value = spec.trim();
+ if (/^git\+file:/i.test(value)) {
+ try {
+ // Git refs are URL fragments, not part of the filesystem path. Node also
+ // decodes escaped names and Windows drive/UNC paths; slicing `file:`
+ // would check a different path from the one Git clones.
+ return fileURLToPath(new URL(value.slice('git+'.length)));
+ } catch {
+ throw refuse('pnpm dependency has an invalid local Git URL');
+ }
+ }
+ const linked = /^(?:link|file):/i.exec(value);
+ const target = linked ? value.slice(linked[0].length) : value;
+ const namedPath =
+ !!linked ||
+ target.startsWith('./') ||
+ target.startsWith('../') ||
+ path.isAbsolute(target) ||
+ /^[a-zA-Z]:/.test(target) ||
+ target.startsWith('~') ||
+ target.includes('\\') ||
+ /(^|\/)\.\.(\/|$)/.test(target);
+ return namedPath ? target : undefined;
+}
+
+/**
+ * A path dependency (`link:`, `file:`, `git+file:`, a relative or absolute path)
+ * makes pnpm symlink or copy whatever it names — including outside the worktree, where a
+ * collaborator can point at credentials or user data. Unverified content may
+ * depend on registry packages or on paths that stay inside the tree only.
+ * `file:` targets are collected for the archive check below: pnpm reads the
+ * package metadata out of them, never out of a manifest we see.
+ */
+/** The one directory pnpm actually uses for this spec. */
+interface SpecOptions {
+ archives?: Set<string>;
+ directory?: string;
+}
+
+function checkDependencySpec(
+ file: string,
+ base: string,
+ name: string,
+ spec: string,
+ opts: SpecOptions = {},
+): void {
+ const target = specPathTarget(spec);
+ if (target === undefined) return;
+ const resolved = path.resolve(opts.directory ?? path.dirname(file), target);
+ const relative = path.relative(base, resolved);
+ if (relative.startsWith('..') || path.isAbsolute(relative))
+ throw refuse(`pnpm dependency leaves the worktree: ${name}`);
+ if (opts.archives && /^file:/i.test(spec.trim())) opts.archives.add(resolved);
+}
+
+function checkDependencySpecs(
+ file: string,
+ base: string,
+ manifest: Record<string, unknown>,
+ opts: SpecOptions = {},
+): void {
+ for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {
+ const specs = manifest[field];
+ if (typeof specs !== 'object' || specs === null || Array.isArray(specs)) continue;
+ for (const [name, spec] of Object.entries(specs as Record<string, unknown>)) {
+ // pnpm joins each installed name under its write roots: a traversal name
+ // escapes wherever those point (`node_modules/../../..` reaches outside
+ // the worktree), so names are checked before any spec.
+ if (refusedDependencyName(name))
+ throw refuse(`pnpm dependency name leaves the worktree: ${name}`);
+ if (typeof spec === 'string') checkDependencySpec(file, base, name, spec, opts);
+ }
+ }
+}
+
+/**
+ * The manifest of a package pnpm installs out of an archive: no manifest check
+ * sees into `file:` tarballs, yet pnpm joins the names inside under the write
+ * roots. Names must be package names, and specs may not name paths at all — a
+ * path resolves against the store location pnpm extracts to, not the tree.
+ */
+function checkArchiveManifest(where: string, text: string): void {
+ let manifest: unknown;
+ try {
+ manifest = JSON.parse(text.replace(/^\uFEFF/, ''));
+ } catch {
+ throw refuse(`unparseable ${where}`);
+ }
+ if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest))
+ throw refuse(`unrecognized ${where}`);
+ const record = manifest as Record<string, unknown>;
+ const checkMap = (specs: unknown, keys: 'name' | 'pattern', depth = 0): void => {
+ if (depth > 16) throw refuse(`archive manifest nests too deeply: ${where}`);
+ if (Array.isArray(specs)) {
+ for (const nested of specs) checkMap(nested, keys, depth + 1);
+ return;
+ }
+ if (typeof specs !== 'object' || specs === null) return;
+ for (const [name, spec] of Object.entries(specs as Record<string, unknown>)) {
+ if (keys === 'name' ? refusedDependencyName(name) : refusedPathLikeName(name))
+ throw refuse(`pnpm dependency name leaves the worktree: ${name} in ${where}`);
+ if (typeof spec === 'string') {
+ if (specPathTarget(spec) !== undefined)
+ throw refuse(`pnpm dependency leaves the worktree: ${name} in ${where}`);
+ } else checkMap(spec, keys, depth + 1);
+ }
+ };
+ for (const field of ['dependencies', 'devDependencies', 'optionalDependencies'])
+ checkMap(record[field], 'name');
+ for (const key of ['overrides', 'resolutions'])
+ if (key in record) checkMap(record[key], 'pattern');
+ const pnpm = record.pnpm;
+ if (typeof pnpm === 'object' && pnpm !== null && !Array.isArray(pnpm)) {
+ for (const [key, value] of Object.entries(pnpm as Record<string, unknown>)) {
+ if (key === 'overrides' || key === 'resolutions' || key === 'patchedDependencies')
+ checkMap(value, 'pattern');
+ else if (key === 'catalog' || key === 'catalogs' || key === 'packageExtensions')
+ checkMap(value, 'name');
+ }
+ }
+}
+
+/** `package.json` out of an archive pnpm installs from, without extracting it. */
+async function readArchiveManifest(file: string): Promise<string | undefined> {
+ let manifest: string | undefined;
+ let manifestCount = 0;
+ let entries = 0;
+ let overflow = false;
+ let failure: Error | undefined;
+ await tarList({
+ file,
+ filter: (entryPath: string, entry?: { size?: number }) => {
+ if (++entries > MAX_ARCHIVE_ENTRIES) {
+ failure ??= refuse('archive holds too many entries');
+ return false;
+ }
+ // pnpm strips the archive's first directory when unpacking. Dot segments
+ // and repeated separators can name the same extracted manifest even
+ // though tar reports distinct entry names. Count that destination once.
+ const archivePath = entryPath.replace(/\\/g, '/');
+ if (path.posix.isAbsolute(archivePath) || /^[a-zA-Z]:/.test(archivePath)) {
+ // Unpackers can strip absolute prefixes before applying `strip: 1`.
+ // Refuse these instead of guessing which manifest would be installed.
+ failure ??= refuse('archive has an absolute entry');
+ return false;
+ }
+ const normalized = path.posix.normalize(archivePath);
+ const extracted = normalized.split('/').slice(1).join('/');
+ const canonical =
+ process.platform === 'win32'
+ ? extracted.split('/').map((part) => part.replace(/[ .]+$/, '').toLowerCase()).join('/')
+ : extracted;
+ if (canonical !== 'package.json') return false;
+ if (++manifestCount > 1) {
+ failure ??= refuse('archive has duplicate manifests');
+ return false;
+ }
+ if ((entry?.size ?? 0) > MAX_CONFIG_BYTES) {
+ failure ??= refuse('archive manifest too large');
+ return false;
+ }
+ return true;
+ },
+ onentry: (entry: ReadEntry) => {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ entry.on('data', (chunk: Buffer | string) => {
+ const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
+ size += buffer.length;
+ if (size > MAX_CONFIG_BYTES) overflow = true;
+ else chunks.push(buffer);
+ });
+ entry.on('end', () => {
+ if (manifest === undefined && !overflow) manifest = Buffer.concat(chunks).toString('utf8');
+ });
+ },
+ });
+ if (failure) throw failure;
+ if (overflow) throw refuse('archive manifest too large');
+ return manifest;
+}
+
+function checkWorkspaceYaml(
+ file: string,
+ base: string,
+ text: string,
+ opts: SpecOptions = {},
+): void {
+ let settings: unknown;
+ try {
+ settings = yaml.load(text);
+ } catch {
+ // Content pnpm could not parse either; never install content we cannot check.
+ throw refuse(`unparseable ${path.basename(file)}`);
+ }
+ if (settings === null || settings === undefined) return;
+ if (typeof settings !== 'object' || Array.isArray(settings))
+ throw refuse(`unrecognized ${path.basename(file)}`);
+ checkSettings(path.basename(file), settings as Record<string, unknown>, file, base, opts);
+}
+
+function checkPackageJson(file: string, base: string, text: string, opts: SpecOptions = {}): void {
+ let manifest: unknown;
+ try {
+ // JSON.parse is exactly what pnpm reads, modulo a byte-order mark.
+ manifest = JSON.parse(text.replace(/^\uFEFF/, ''));
+ } catch {
+ // A fixture pnpm never reads; it cannot configure anything either.
+ return;
+ }
+ if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) return;
+ const record = manifest as Record<string, unknown>;
+ const pnpm = record.pnpm;
+ if (typeof pnpm === 'object' && pnpm !== null && !Array.isArray(pnpm))
+ checkSettings(`${path.basename(file)}#pnpm`, pnpm as Record<string, unknown>, file, base, opts);
+ checkDependencySpecs(file, base, record, opts);
+ // npm-style top-level `overrides` and yarn-style `resolutions` generate
+ // dependency specs just like `pnpm.overrides` does.
+ for (const key of ['overrides', 'resolutions'])
+ if (key in record)
+ checkSpecMap(file, base, `${path.basename(file)}#${key}`, record[key], 'pattern', 0, opts);
+ if ('workspaces' in record) {
+ const value = record.workspaces;
+ const patterns =
+ typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? (value as { packages?: unknown }).packages ?? []
+ : value;
+ for (const pattern of Array.isArray(patterns) ? patterns : [patterns])
+ if (refusedWorkspacePattern(pattern))
+ throw refuse(`npm workspace leaves the worktree: ${String(pattern)}`);
+ }
+}
+
+async function contained(link: string, resolved: string, root: string, rootReal: string): Promise<void> {
+ const within = (target: string, base: string) => {
+ const relative = path.relative(base, target);
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
+ };
+ const canonical = (value: string) =>
+ process.platform === 'win32' ? value.toLowerCase() : value;
+ if (!within(canonical(resolved), canonical(root)))
+ throw refuse(`symlink leaves the worktree: ${path.relative(root, link)}`);
+ // The resolved target may sit under further links; the whole chain must stay in.
+ try {
+ const chain = await realpath(link);
+ if (!within(canonical(chain), canonical(rootReal)))
+ throw refuse(`symlink chain leaves the worktree: ${path.relative(root, link)}`);
+ } catch (error) {
+ // A dangling link is judged by its textual target above (fail closed).
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+}
+
+/**
+ * Every prospective write root under `directory` (its `node_modules` and the
+ * virtual store pnpm keeps inside) must be a real descendant of the worktree:
+ * within it textually, and with every existing part of the path resolving within
+ * it, so a leftover link from a previous run cannot point the writes outside.
+ */
+async function assertWriteRootDescends(root: string, rootReal: string, directory: string): Promise<void> {
+ const within = (target: string, base: string) => {
+ const relative = path.relative(base, target);
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
+ };
+ const canonical = (value: string) =>
+ process.platform === 'win32' ? value.toLowerCase() : value;
+ for (const name of [
+ 'node_modules',
+ path.join('node_modules', '.pnpm'),
+ // The store `installCindyMakeWorktree` pins for unverified content.
+ path.join('node_modules', '.cindy-make-store'),
+ ]) {
+ const target = path.resolve(directory, name);
+ if (!within(canonical(target), canonical(root))) throw refuse('write root outside the worktree');
+ for (let probe = target; ; ) {
+ try {
+ const resolved = await realpath(probe);
+ if (!within(canonical(resolved), canonical(rootReal)))
+ throw refuse(`write root leaves the worktree: ${path.relative(root, target)}`);
+ break;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ if ((error as { code?: string }).code === 'gitFailed') throw error;
+ throw refuse('unreadable write root');
+ }
+ const parent = path.dirname(probe);
+ if (parent === probe) break;
+ probe = parent;
+ }
+ }
+ }
+}
+
+/**
+ * Refuse installation of unverified content whose pnpm writes could leave the
+ * worktree; see the module comment for what is checked and why. An install of
+ * content the user has verified does not run this: its `.npmrc` may configure
+ * the machine's own store as the user chose.
+ */
+export async function assertPnpmInstallContained(root: string): Promise<void> {
+ const base = path.resolve(root);
+ let rootReal = base;
+ try {
+ rootReal = await realpath(base);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; // nothing to install into
+ throw refuse('unreadable worktree');
+ }
+ const packageDirectories: string[] = [base];
+ const archives = new Set<string>();
+ let scanned = 0;
+ const walk = async (directory: string, depth: number): Promise<void> => {
+ if (depth > MAX_DEPTH) throw refuse('worktree nests too deeply');
+ let entries;
+ try {
+ entries = await readdir(directory, { withFileTypes: true });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw refuse('unreadable worktree');
+ }
+ for (const entry of entries) {
+ if (++scanned > MAX_SCANNED_ENTRIES) throw refuse('worktree holds too many entries');
+ const full = path.join(directory, entry.name);
+ if (entry.isSymbolicLink()) {
+ // A recognized config behind a link is never walked past: pnpm follows
+ // the link and reads what this scan would have skipped.
+ if (isPnpmConfigName(entry.name))
+ throw refuse(`pnpm config is a symlink: ${path.relative(base, full)}`);
+ await contained(full, path.resolve(directory, await readlink(full)), base, rootReal);
+ continue; // never walk through a link
+ }
+ if (!entry.isFile()) {
+ // `.git` bookkeeping and installed dependencies are the harness's and
+ // pnpm's own; the `node_modules` entry itself is checked as a link above.
+ if (entry.isDirectory() && entry.name !== '.git' && entry.name !== 'node_modules')
+ await walk(full, depth + 1);
+ continue;
+ }
+ if (entry.name === '.npmrc') checkIni(full, await readConfig(full));
+ else if (entry.name === 'pnpm-workspace.yaml' || entry.name === 'pnpm-workspace.yml')
+ checkWorkspaceYaml(full, base, await readConfig(full), { archives });
+ else if (entry.name === 'pnpm-lock.yaml' || entry.name === 'pnpm-lock.yml')
+ checkLockfile(full, base, await readConfig(full), archives);
+ else if (entry.name === 'package.json') {
+ packageDirectories.push(directory);
+ checkPackageJson(full, base, await readConfig(full), { archives });
+ }
+ }
+ };
+ await walk(base, 0);
+ for (const directory of packageDirectories)
+ await assertWriteRootDescends(base, rootReal, directory);
+ // A `file:` dependency installs as a package out of an archive: the names pnpm
+ // joins under the write roots come from the manifest inside it, which no walk
+ // of the tree can see. Every referenced archive is checked too.
+ let scannedArchives = 0;
+ for (const archive of archives) {
+ if (++scannedArchives > MAX_ARCHIVES) throw refuse('worktree holds too many archives');
+ const entry = await lstat(archive).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
+ throw refuse('unreadable archive');
+ });
+ // A missing archive fails the install on its own; a directory dependency's
+ // manifest was already walked above.
+ if (!entry || entry.isDirectory()) continue;
+ if (entry.isSymbolicLink() || !entry.isFile())
+ throw refuse(`unrecognized archive: ${path.relative(base, archive)}`);
+ const manifest = await readArchiveManifest(archive).catch((error) => {
+ if ((error as { code?: string }).code === 'gitFailed') throw error;
+ throw refuse(`unreadable archive: ${path.relative(base, archive)}`);
+ });
+ if (manifest !== undefined)
+ checkArchiveManifest(`${path.relative(base, archive)}#package.json`, manifest);
+ }
+}
+
+/**
+ * After installing unverified content, every link the install created under the
+ * write roots must resolve within the worktree: a frozen lockfile carries specs
+ * the pre-install manifest checks never saw, and installed package content may
+ * ship links of its own. Plain files are skipped — only directories and links
+ * can lead a later read outside the tree.
+ */
+export async function assertPnpmInstallLinksContained(root: string): Promise<void> {
+ const base = path.resolve(root);
+ let rootReal = base;
+ try {
+ rootReal = await realpath(base);
+ } catch {
+ throw refuse('unreadable worktree');
+ }
+ let scanned = 0;
+ const walk = async (directory: string, depth: number): Promise<void> => {
+ if (depth > MAX_DEPTH) throw refuse('worktree nests too deeply');
+ let entries;
+ try {
+ entries = await readdir(directory, { withFileTypes: true });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw refuse('unreadable worktree');
+ }
+ for (const entry of entries) {
+ const full = path.join(directory, entry.name);
+ if (entry.isSymbolicLink()) {
+ if (++scanned > MAX_SCANNED_ENTRIES) throw refuse('worktree holds too many entries');
+ await contained(full, path.resolve(directory, await readlink(full)), base, rootReal);
+ continue; // never walk through a link
+ }
+ if (!entry.isDirectory() || entry.name === '.git') continue;
+ if (++scanned > MAX_SCANNED_ENTRIES) throw refuse('worktree holds too many entries');
+ await walk(full, depth + 1);
+ }
+ };
+ await walk(base, 0);
+}
diff --git a/apps/desktop/src/main/cindy-make/remoteBroadcast.ts b/apps/desktop/src/main/cindy-make/remoteBroadcast.ts
index 217c985422..21bc909997 100644
--- a/apps/desktop/src/main/cindy-make/remoteBroadcast.ts
+++ b/apps/desktop/src/main/cindy-make/remoteBroadcast.ts
@@ -25,3 +25,19 @@ export function broadcastMakeRemoteChanged(
// A disconnected controller must not fail a persisted local operation.
}
}
+
+/** Invalidate every Cindy Make resource because its global projection changed. */
+export function broadcastMakeRemoteCollectionChanged(
+ scope = captureDataOwnerBroadcastScope(),
+): void {
+ if (!isDataOwnerBroadcastScopeCurrent(scope)) return;
+ try {
+ tapWindowBroadcast(
+ REMOTE_RESOURCE_CHANGED_CHANNEL,
+ { collectionId: MAKE_REMOTE_COLLECTION },
+ scope.ownerStamp,
+ );
+ } catch {
+ // A disconnected controller must not fail a persisted local operation.
+ }
+}
diff --git a/apps/desktop/src/main/cindy-make/remoteProjection.ts b/apps/desktop/src/main/cindy-make/remoteProjection.ts
index 259e8cc1fd..f85a825de9 100644
--- a/apps/desktop/src/main/cindy-make/remoteProjection.ts
+++ b/apps/desktop/src/main/cindy-make/remoteProjection.ts
@@ -4,10 +4,16 @@ import {
parseCindyMakeBuildOutput,
} from '../../shared/cindyMakeBuildDiagnostic.js';
import type { MakeDoctorReport } from '../../shared/cindyMakeDoctor.js';
+import type { CindyMakeContributionState } from '../../shared/cindyMakeContribution.js';
import type {
CindyMakeCompletionMeta,
CindyMakePersonalBuildState,
} from '../../shared/cindyMakeSession.js';
+import type {
+ CindyMakeRemoteError,
+ CindyMakeRemoteSync,
+} from '../../shared/cindyMakePersonalRemote.js';
+import type { CindyMakeSyncState } from '../../shared/cindyMakeSync.js';
export const MAKE_REMOTE_COLLECTION = 'cindy-make';
export const makeRemoteRef = (sessionId: string) => ({
@@ -24,6 +30,19 @@ export interface MakeRemoteSnapshot {
sharedBuild?: CindyMakePersonalBuildState;
recoverable: boolean;
sourceMergePending?: boolean;
+ personal?: MakeRemotePersonalSnapshot;
+}
+
+export interface MakeRemotePersonalSnapshot {
+ remote?: { sync?: CindyMakeRemoteSync; error?: CindyMakeRemoteError };
+ /** The single local Sync pipeline, projected separately from GitHub storage status. */
+ personalSync?: CindyMakeSyncState;
+ contributions?: readonly MakeRemoteContributionSnapshot[];
+}
+
+export interface MakeRemoteContributionSnapshot {
+ number: number;
+ state?: CindyMakeContributionState;
}
type Translate = (key: string, values?: Record<string, string>) => string;
@@ -214,6 +233,54 @@ export function projectMakeRemoteCard(source: MakeRemoteSnapshot, t: Translate):
source.sourceMergePending,
);
}
+ const personalDetails: string[] = [];
+ if (source.personal?.remote?.sync)
+ personalDetails.push(t('cindyMake.storage.status.' + source.personal.remote.sync));
+ if (source.personal?.remote?.error)
+ personalDetails.push(t('cindyMake.storage.errors.' + source.personal.remote.error));
+ const personalSync = source.personal?.personalSync;
+ if (personalSync?.running && personalSync.step)
+ personalDetails.push(t('cindyMake.sync.step.' + personalSync.step));
+ const waiting = personalSync?.waiting;
+ if (waiting) {
+ const waitingKey = waiting.abandoning
+ ? 'cindyMake.sync.waiting.abandoning'
+ : waiting.reason === 'working'
+ ? 'cindyMake.sync.waiting.working.' + waiting.kind
+ : waiting.reason === 'interrupted'
+ ? 'cindyMake.sync.waiting.interrupted.' + (waiting.sessionId ? 'task' : 'start')
+ : 'cindyMake.sync.waiting.' + waiting.reason;
+ personalDetails.push(t(waitingKey, { count: String(waiting.missing ?? 0) }));
+ }
+ const done = personalSync?.done;
+ if (done && !done.generateFirst) {
+ personalDetails.push(
+ !done.ref
+ ? t('cindyMake.sync.doneCurrent')
+ : done.ref === 'main'
+ ? t('cindyMake.sync.doneDevelopment')
+ : t('cindyMake.sync.done', { ref: done.ref }),
+ );
+ }
+ if (done?.generateFirst)
+ personalDetails.push(t('cindyMake.sync.generateFirst', { ref: done.generateFirst }));
+ if (done?.ahead) personalDetails.push(t('cindyMake.sync.ahead'));
+ if (done?.buildFirst) personalDetails.push(t('cindyMake.sync.buildFirst'));
+ if (done?.uploadAfterBuild && !done.buildFirst)
+ personalDetails.push(t('cindyMake.sync.uploadAfterBuild'));
+ if (done?.held && !done.ahead) personalDetails.push(t('cindyMake.sync.held', { ref: done.held }));
+ if (personalSync?.error) personalDetails.push(t('cindyMake.sync.errors.' + personalSync.error));
+ for (const contribution of source.personal?.contributions ?? []) {
+ personalDetails.push(
+ t('cindyMake.contribution.state.' + (contribution.state ?? 'submitted'), {
+ number: String(contribution.number),
+ }),
+ );
+ }
+ if (personalDetails.length)
+ description = [description, ...personalDetails].filter(Boolean).join('\n\n');
+ const hasWorkflow = blocked || (!source.busy && source.recoverable);
+ if (!hasWorkflow && personalDetails.length && !source.busy) title = t('cindyMake.title');
const fallbackMarkdown = [title, description, ...details].filter(Boolean).join('\n\n');
return {
ref: makeRemoteRef(source.sessionId),
@@ -225,7 +292,7 @@ export function projectMakeRemoteCard(source: MakeRemoteSnapshot, t: Translate):
},
links,
blocks:
- blocked || (!source.busy && source.recoverable)
+ hasWorkflow
? [
{
id: 'workflow',
@@ -234,7 +301,9 @@ export function projectMakeRemoteCard(source: MakeRemoteSnapshot, t: Translate):
data: { input: blocked ? 'blocked' : 'available', busy },
},
]
- : [],
+ : personalDetails.length
+ ? [{ id: 'personal-status', primitive: 'markdown', fallbackMarkdown }]
+ : [],
actions,
};
}
diff --git a/apps/desktop/src/main/cindy-make/remoteRuntime.ts b/apps/desktop/src/main/cindy-make/remoteRuntime.ts
index 4d5534849b..440fcc7542 100644
--- a/apps/desktop/src/main/cindy-make/remoteRuntime.ts
+++ b/apps/desktop/src/main/cindy-make/remoteRuntime.ts
@@ -25,6 +25,7 @@ import { broadcastMakeRemoteChanged } from './remoteBroadcast.js';
import { projectMakeRemoteCard, type MakeRemoteSnapshot } from './remoteProjection.js';
import type { CindyMakeCompletionMeta } from '../../shared/cindyMakeSession.js';
import { CINDY_MAKE_ENABLED } from '@cindy/maker-shared/cindy-make-feature';
+import { readPersonalRemoteProjection } from './personalRemoteRuntime.js';
const unavailable = () =>
new RemoteResourceRegistryError('NOT_FOUND', 'Cindy Make task is unavailable');
@@ -124,6 +125,8 @@ export function registerMakeRemoteResources(isRunning: (id: string) => boolean):
);
const sharedBuild = readCindyMakeBuildState();
const merge = cindyMakeManager.getState().upstreamMerge;
+ const personal = await readPersonalRemoteProjection().catch(() => undefined);
+ if (!isCurrent()) throw unavailable();
const snapshot: MakeRemoteSnapshot = {
sessionId,
revision: '',
@@ -139,6 +142,7 @@ export function registerMakeRemoteResources(isRunning: (id: string) => boolean):
recoverable,
sourceMergePending:
!!merge && merge.status !== 'merged' && (merge.hasWorkspace || merge.cancellationRequested),
+ ...(personal ? { personal } : {}),
};
snapshot.revision = createHash('sha256')
.update(JSON.stringify([snapshot, rows[0]?.clientId, session.clearedAt]))
diff --git a/apps/desktop/src/main/cindy-make/settingsStore.ts b/apps/desktop/src/main/cindy-make/settingsStore.ts
index d5383e1ddc..538d693f80 100644
--- a/apps/desktop/src/main/cindy-make/settingsStore.ts
+++ b/apps/desktop/src/main/cindy-make/settingsStore.ts
@@ -18,13 +18,10 @@ function normalize(raw: unknown): CindyMakeSettings {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
return { ...DEFAULT_CINDY_MAKE_SETTINGS };
}
- const value = raw as Record<string, unknown>;
- return {
- syncLatestBeforeBuild:
- typeof value.syncLatestBeforeBuild === 'boolean'
- ? value.syncLatestBeforeBuild
- : DEFAULT_CINDY_MAKE_SETTINGS.syncLatestBeforeBuild,
- };
+ // Retired 2026-10-01: Sync is the one place the personal version moves to a newer
+ // official version, so a build always uses the source as Sync left it. A stored ON
+ // from an older version is read as off.
+ return { syncLatestBeforeBuild: false };
}
const store = createOverrideSettingsFile<CindyMakeSettings>({
diff --git a/apps/desktop/src/main/cindy-make/sourcePnpm.ts b/apps/desktop/src/main/cindy-make/sourcePnpm.ts
index 733ac149f5..e798815e46 100644
--- a/apps/desktop/src/main/cindy-make/sourcePnpm.ts
+++ b/apps/desktop/src/main/cindy-make/sourcePnpm.ts
@@ -1,11 +1,50 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { constants } from 'node:fs';
import { access, stat } from 'node:fs/promises';
+import os from 'node:os';
import path from 'node:path';
import type { CindyMakeTaskPreparation } from '../../shared/cindyMakeDoctor.js';
import { createMakeBuildOutput } from './buildDiagnostic.js';
import { createMakeBuildLineOutput } from './buildProgress.js';
+/**
+ * The credential-free environment an install or cache warm of unverified content
+ * may see: process essentials and Cindy's own toolchain settings only. Anything
+ * else — above all credentials inherited from how Cindy was launched — stays out,
+ * because `${VAR}` in a content `.npmrc` expands it into a request to a host the
+ * content chooses; even an allowlisted name is dropped when it names a credential.
+ * `userconfig` is pinned to the null device so the user's own `.npmrc` is not
+ * loaded either. Corepack may not take anything from unverified content: a
+ * project `.corepack.env` and the `packageManager` field can name, cache-poison
+ * or point at a custom URL for the package manager Corepack runs before pnpm's
+ * own guards apply, so its project env and project spec are disabled outright.
+ */
+export function unverifiedPnpmEnv(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
+ return {
+ ...Object.fromEntries(
+ Object.entries(environment).filter(
+ ([key]) =>
+ /^(?:path|systemroot|windir|comspec|tmp|temp|home|userprofile|lang|lc_.*|tz|corepack_.*|pnpm_manage_package_manager_versions|pythondontwritebytecode|pythonutf8|python|npm_config_(?:manage_package_manager_versions|managepackagemanagerversions|python))$/i.test(
+ key,
+ ) &&
+ !/(?:token|password|auth|secret|credential|key)/i.test(key) &&
+ // Pinned below unconditionally; a differently-cased twin must not
+ // survive to fight the pin on case-insensitive environments.
+ !/^corepack_(?:env_file|enable_project_spec|enable_unsafe_custom_urls)$/i.test(key),
+ ),
+ ),
+ npm_config_userconfig: os.devNull,
+ // The global config may hold registry credentials of its own.
+ npm_config_globalconfig: os.devNull,
+ // Corepack must not read the content's `.corepack.env` or follow its
+ // `packageManager` spec: together they can make the Corepack shim execute
+ // attacker-chosen code before `--ignore-scripts` applies.
+ COREPACK_ENV_FILE: '0',
+ COREPACK_ENABLE_PROJECT_SPEC: '0',
+ COREPACK_ENABLE_UNSAFE_CUSTOM_URLS: '0',
+ };
+}
+
export function parseMakeDependencyProgress(
text: string,
previous?: CindyMakeTaskPreparation['dependencies'],
@@ -91,7 +130,10 @@ export async function runSourcePnpm(
signal.throwIfAborted();
// Keep progress visible in a non-TTY/CI process, including lifecycle scripts.
args = ['install', 'fetch'].includes(args[0]) ? [...args, '--reporter=append-only'] : args;
- if (args.some((arg) => !/^[\w.:=-]+$/.test(arg))) {
+ // The pinned pnpm write roots are fixed relative paths (no spaces, quotes or shell
+ // metacharacters); every other argument stays in the tight literal charset.
+ const writeRoot = /^--(?:config\.)?(?:modules-dir|virtual-store-dir|store-dir|cache-dir)=[\w.:/\\-]+$/;
+ if (args.some((arg) => !/^[\w.:=-]+$/.test(arg) && !writeRoot.test(arg))) {
throw Object.assign(new Error('unsafe pnpm argument'), { code: 'installFailed' });
}
const file = await resolvePnpm(env);
diff --git a/apps/desktop/src/main/cindy-make/sourcePreparation.ts b/apps/desktop/src/main/cindy-make/sourcePreparation.ts
index 3ebe859be7..d13f830338 100644
--- a/apps/desktop/src/main/cindy-make/sourcePreparation.ts
+++ b/apps/desktop/src/main/cindy-make/sourcePreparation.ts
@@ -9,9 +9,12 @@ import {
} from './toolchainEnvironment.js';
import type { MakeSourceGitProgress, MakeSourceStatus } from '../../shared/cindyMakeDoctor.js';
import { runSourceGit } from './sourceGit.js';
-import { runSourcePnpm } from './sourcePnpm.js';
+import { runSourcePnpm, unverifiedPnpmEnv } from './sourcePnpm.js';
+import { assertPnpmConfigContained } from './pnpmWriteRoots.js';
import { readSourceRevisions, type SourceRevisions } from './sourceRevisions.js';
import { CINDY_PERSONAL_BRANCH } from './sourcePaths.js';
+import { PERSONAL_UPSTREAM_REF } from './sourceContent.js';
+import { initializePendingBuilds } from './pendingBuild.js';
import { checkMakeToolVersion, untilAborted } from './doctor.js';
export const CINDY_SOURCE_REPOSITORY = 'https://github.com/makecindy/cindy.git';
export { makeSourceRoot, makeSourceCheckoutPath } from './sourcePaths.js';
@@ -41,6 +44,17 @@ async function persistSourceStatus(root: string, status: MakeSourceStatus): Prom
}
}
+/**
+ * An official update was adopted: the personal version is now on this official ref,
+ * so Settings names it (and resolves its commit) instead of the ref it was created from.
+ */
+export async function recordCindySourceRef(root: string, ref: string): Promise<void> {
+ if (!/^(?:main|v\d[0-9A-Za-z.+-]{0,63})$/.test(ref)) return;
+ const status = await readCindySourceStatus(root);
+ if (status.status !== 'ready' || status.ref === ref) return;
+ await persistSourceStatus(root, { ...status, ref });
+}
+
/** Read the last managed checkout summary without invoking Git or exposing arbitrary paths. */
export async function readCindySourceStatus(root: string): Promise<MakeSourceStatus> {
const fallback: MakeSourceStatus = { status: 'missing', path: path.resolve(root, 'source') };
@@ -617,6 +631,14 @@ async function prepareCindySourceInternal(
);
if (!hasPersonal.trim()) {
await git(env, ['branch', CINDY_PERSONAL_BRANCH, upstreamCommit], sourcePath, signal);
+ // Sync, combine and upload all read the official base of the personal version here.
+ await git(
+ env,
+ ['update-ref', PERSONAL_UPSTREAM_REF, upstreamCommit.trim(), ''],
+ sourcePath,
+ signal,
+ ).catch(() => undefined);
+ initializePendingBuilds(root);
}
await emitProgress({
status: 'preparing',
@@ -637,22 +659,40 @@ async function prepareCindySourceInternal(
phase: 'caching',
});
const processEnvironment = await resolveMakeToolEnvironment(env, ['node', 'pnpm'], signal);
+ // Cache warming never executes content-controlled configuration: refused
+ // settings (`configDependencies` runs code, path keys redirect writes) or a
+ // config symlink skip the warming entirely — the install paths run their own
+ // full check (see `pnpmWriteRoots`), and a skipped warm costs only downloads.
+ // When it does run, it sees the same credential-free environment as an
+ // unverified install (see `unverifiedPnpmEnv`): a content `.npmrc` must not
+ // expand an inherited `${NPM_TOKEN}` into a credential sent to its registry.
+ const warmable = await assertPnpmConfigContained(sourcePath).then(
+ () => true,
+ () => false,
+ );
// Settings and preflight warm the same pnpm store. Check the current lockfile
// and cache each time, filling changed or evicted packages without trusting a
// stale ready marker. The personal baseline needs no installed dependencies.
- await runSourcePnpm(
- processEnvironment,
+ if (warmable)
+ await runSourcePnpm(
+ unverifiedPnpmEnv(processEnvironment),
[
'fetch',
'--frozen-lockfile',
'--prefer-offline',
'--prod=false',
'--ignore-scripts',
+ // Pure cache warming from the lockfile: no content-controlled hook runs here
+ // either. Unverified synced content must not get code execution out of the
+ // silent preparation; worktree installs of verified content still honour
+ // the repository's own `.pnpmfile.cjs`.
+ '--ignore-pnpmfile',
// The hoisted linker imports packages even with modules disabled. Override
// only this command; worktree installs keep the repository's linker and
// run the required lifecycle scripts as usual.
'--config.node-linker=isolated',
'--config.enable-modules-dir=false',
+ '--config.strict-ssl=true',
],
sourcePath,
signal,
diff --git a/apps/desktop/src/main/cindy-make/sourceRevisions.ts b/apps/desktop/src/main/cindy-make/sourceRevisions.ts
index 0cfd625ced..34e523fe0d 100644
--- a/apps/desktop/src/main/cindy-make/sourceRevisions.ts
+++ b/apps/desktop/src/main/cindy-make/sourceRevisions.ts
@@ -50,8 +50,14 @@ export async function readSourceRevisions(
'--verify',
'refs/cindy-make/personal-upstream^{commit}',
]);
+ // The recorded base must be the personal tip's ancestor: an interrupted move can
+ // leave "old tip + new base", and no later step may trust that wrong base.
+ const recordedIsBase =
+ recordedUpstream !== undefined &&
+ personalCommit !== '' &&
+ (await readCommit(['merge-base', recordedUpstream, personalCommit])) === recordedUpstream;
const baseCommit =
- recordedUpstream ??
+ (recordedIsBase ? recordedUpstream : undefined) ??
(upstreamCommit ? await readCommit(['merge-base', personalCommit, upstreamCommit]) : undefined);
const mainCommit = await readCommit(['rev-parse', '--verify', 'refs/heads/main^{commit}']);
const mainRemoteCommit = await readCommit([
diff --git a/apps/desktop/src/main/cindy-make/stateBroadcast.ts b/apps/desktop/src/main/cindy-make/stateBroadcast.ts
index 709af2d383..940ff901bd 100644
--- a/apps/desktop/src/main/cindy-make/stateBroadcast.ts
+++ b/apps/desktop/src/main/cindy-make/stateBroadcast.ts
@@ -3,18 +3,38 @@ import { BrowserWindow } from 'electron';
import { MAKER_PUSH } from '../maker-ipc/channels.js';
import { captureDataOwnerBroadcastScope } from '../device-link/broadcast-tap.js';
import type { CindyMakeGlobalState } from '../../shared/cindyMakeDoctor.js';
-import { broadcastMakeRemoteChanged } from './remoteBroadcast.js';
+import {
+ broadcastMakeRemoteChanged,
+ broadcastMakeRemoteCollectionChanged,
+} from './remoteBroadcast.js';
+
+let lastGlobalProjection: string | undefined;
/** Push the Main-owned Cindy Make snapshot to every trusted renderer window. */
export function broadcastCindyMakeState(state: CindyMakeGlobalState): void {
+ const scope = captureDataOwnerBroadcastScope();
for (const report of Object.values(state.tasks ?? {}))
- if (report.task?.sessionId) broadcastMakeRemoteChanged(report.task.sessionId);
+ if (report.task?.sessionId) broadcastMakeRemoteChanged(report.task.sessionId, scope);
+ // personalRemote/personalSync are device-level projections that also appear in
+ // finished task resources. Those tasks are intentionally omitted from
+ // state.tasks, so a collection-level invalidation is required when the global
+ // projection changes.
+ const globalProjection = JSON.stringify([
+ scope.ownerScopeKey,
+ scope.ownerStamp,
+ state.personalRemote,
+ state.personalSync,
+ ]);
+ if (globalProjection !== lastGlobalProjection) {
+ lastGlobalProjection = globalProjection;
+ broadcastMakeRemoteCollectionChanged(scope);
+ }
for (const window of BrowserWindow.getAllWindows()) {
if (window.isDestroyed()) continue;
try {
window.webContents.send(MAKER_PUSH.CINDY_MAKE_STATE_CHANGED, {
...state,
- ownerStamp: captureDataOwnerBroadcastScope().ownerStamp,
+ ownerStamp: scope.ownerStamp,
});
} catch {
// A closing renderer must not affect the operation running in Main.
diff --git a/apps/desktop/src/main/cindy-make/syncTarget.ts b/apps/desktop/src/main/cindy-make/syncTarget.ts
new file mode 100644
index 0000000000..01b4955a4d
--- /dev/null
+++ b/apps/desktop/src/main/cindy-make/syncTarget.ts
@@ -0,0 +1,86 @@
+/**
+ * Which official version Sync moves the personal version to.
+ *
+ * A personal version can only replace this computer's original Cindy when both
+ * use the same database migrations (see `versionStore`). The personal app never
+ * updates itself, so following a release whose migrations differ from the
+ * installed original would produce a version that cannot be switched to. Sync
+ * therefore follows the latest release only while its migrations match, and
+ * otherwise stays on the original's own official version until Cindy is updated.
+ */
+
+const COMMIT = /^[0-9a-f]{40}$/i;
+/** Database migrations shipped with the desktop app; their identity gates version switching. */
+export const MIGRATIONS_PATH = 'apps/desktop/drizzle';
+
+export interface SyncTargetVersion {
+ ref: string;
+ commit: string;
+}
+export interface SyncTarget extends SyncTargetVersion {
+ /** A newer release whose migrations need this computer's Cindy updated first. */
+ held?: SyncTargetVersion;
+}
+
+export interface SyncTargetDeps {
+ latest: SyncTargetVersion & { channel: 'dev' | 'beta' | 'release' };
+ /** The installed original Cindy, when known. */
+ original?: { version?: string; commit?: string; dirty?: boolean };
+ /** Commit of an official tag, or undefined when it does not exist. */
+ tagCommit(tag: string): Promise<string | undefined>;
+ /** Make official commits available locally (fetched by hash). */
+ fetch(commits: string[]): Promise<void>;
+ /** `git diff --quiet` exit status for the migrations between two commits: true when equal. */
+ sameMigrations(from: string, to: string): Promise<boolean>;
+ isAncestor(ancestor: string, descendant: string): Promise<boolean>;
+}
+
+/**
+ * Never move a personal version to an older official version than it is on: when
+ * the target is behind the current base (for example the base came from another
+ * computer), the base itself is the target.
+ */
+export async function notBehindBase(
+ target: SyncTargetVersion,
+ base: string | undefined,
+ isAncestor: (ancestor: string, descendant: string) => Promise<boolean>,
+): Promise<SyncTargetVersion> {
+ if (!base || !COMMIT.test(base) || base === target.commit) return target;
+ return (await isAncestor(target.commit, base)) ? { ref: target.ref, commit: base } : target;
+}
+
+/**
+ * The returned commit is always available locally. Development builds and an
+ * unknown original follow the latest version; a known installed release that
+ * cannot be compared fails closed (the caller reports it and moves nothing).
+ */
+export async function pickSyncTarget(deps: SyncTargetDeps): Promise<SyncTarget> {
+ const { latest, original } = deps;
+ const follow: SyncTarget = { ref: latest.ref, commit: latest.commit };
+ // Development builds follow main and are not switched against an installed release.
+ if (latest.channel === 'dev' || !original?.version) {
+ await deps.fetch([latest.commit]);
+ return follow;
+ }
+ const tag = `v${original.version}`;
+ const installed =
+ original.commit && !original.dirty && COMMIT.test(original.commit)
+ ? original.commit
+ : await deps.tagCommit(tag);
+ // The original's version is known but its commit cannot be resolved (the build
+ // commit is missing or dirty and the `v<version>` tag does not exist): the
+ // migrations cannot be compared. Stop here and let the caller report it —
+ // following the latest release unchecked could move the personal version onto
+ // an incompatible database migration (docs/cindy-make-upstream.md).
+ if (!installed || !COMMIT.test(installed))
+ throw Object.assign(new Error('unavailable'), { code: 'unavailable' });
+ if (installed === latest.commit) {
+ await deps.fetch([latest.commit]);
+ return follow;
+ }
+ await deps.fetch([latest.commit, installed]);
+ // A newer original (for example a beta) is never held back to an older release.
+ if (!(await deps.isAncestor(installed, latest.commit))) return follow;
+ if (await deps.sameMigrations(installed, latest.commit)) return follow;
+ return { ref: tag, commit: installed, held: { ref: latest.ref, commit: latest.commit } };
+}
diff --git a/apps/desktop/src/main/cindy-make/taskRuntime.ts b/apps/desktop/src/main/cindy-make/taskRuntime.ts
index 3437989e97..33ff0d5135 100644
--- a/apps/desktop/src/main/cindy-make/taskRuntime.ts
+++ b/apps/desktop/src/main/cindy-make/taskRuntime.ts
@@ -2,6 +2,11 @@ import { randomUUID } from 'node:crypto';
import { normalizeDbAgentKind, dbToMakerAgentKind } from '../../shared/agentKindConversion.js';
import { and, desc, eq, gt, isNull, like, or } from 'drizzle-orm';
import { app } from 'electron';
+import { syncPersonalRemoteBeforeTask } from './personalRemoteRuntime.js';
+import {
+ hasRetainedSourceOperation,
+ syncSourceBeforeCindyMakeTask,
+} from './upstreamMergeRuntime.js';
import { cindyMakeManager } from './manager.js';
import {
createMakeToolchainEnvironment,
@@ -12,6 +17,7 @@ import { prepareCindyMakeEnvironment } from './prepare.js';
import { untilAborted } from './doctor.js';
import { prepareCindySource, readCurrentCindySourceStatus } from './sourcePreparation.js';
import { createCindyMakeWorktree, installCindyMakeWorktree } from './taskWorkspace.js';
+import { installScriptsTrust, remoteContentScriptsUnverified } from './installScriptsTrust.js';
import { CINDY_MAKE_RUN_ID_PATTERN, makeSourceRoot, makeTaskWorktreePath } from './sourcePaths.js';
import { makeToolRoot } from './toolInstaller.js';
import { getDbClient } from '../localDb/client/current.js';
@@ -539,8 +545,31 @@ export async function startCindyMakeTask(raw: unknown, sender: number): Promise<
// The task worktree must branch from the latest verified personal source.
// Keep the visible task shell while this runs so conflicts and Stop remain recoverable.
phase('updatingSource', publish);
- const { syncSourceBeforeCindyMakeTask } = await import('./upstreamMergeRuntime.js');
- await syncSourceBeforeCindyMakeTask(signal, taskOptions);
+ for (let attempt = 0; ; attempt += 1) {
+ // A Sync in progress finishes first; the task then starts from its result.
+ await cindyMakeManager.whenManualSourceSyncIdle(signal);
+ checkPreparationCurrent();
+ // A conflict still waiting in its task leaves the personal version as it is: the new
+ // task starts from it instead of waiting for (or failing on) that conflict.
+ if (hasRetainedSourceOperation()) break;
+ try {
+ // Changes saved from another computer come first, so the official update replays them too.
+ await untilAborted(syncPersonalRemoteBeforeTask(), signal);
+ checkPreparationCurrent();
+ await syncSourceBeforeCindyMakeTask(signal, taskOptions);
+ break;
+ } catch (error) {
+ // A Sync that started meanwhile owns the source: wait for it, then decide again.
+ if (
+ attempt < 2 &&
+ !signal.aborted &&
+ (error as { code?: string })?.code === 'busy' &&
+ cindyMakeManager.isManualSourceSyncRunning()
+ )
+ continue;
+ throw error;
+ }
+ }
checkPreparationCurrent();
signal.throwIfAborted();
source = await readCurrentCindySourceStatus(root, env);
@@ -563,6 +592,16 @@ export async function startCindyMakeTask(raw: unknown, sender: number): Promise<
signal.throwIfAborted();
report = { ...report, source: { status: 'ready', ...workspace } };
phase('dependencies', publish);
+ // Content taken over from the user's fork before this computer generated
+ // a personal version from it never has its lifecycle scripts run here:
+ // task creation must not execute code a collaborator pushed. Anything
+ // unclear counts as unverified (see `remoteContentScriptsUnverified`).
+ const ignoreScripts = await remoteContentScriptsUnverified(
+ workspace.baseCommit,
+ installScriptsTrust(userData, processEnvironment, signal),
+ ).catch(() => true);
+ if (ignoreScripts)
+ log.info('task install skips lifecycle scripts on unverified synced content');
await installCindyMakeWorktree(
userData,
workspace,
@@ -575,6 +614,7 @@ export async function startCindyMakeTask(raw: unknown, sender: number): Promise<
publish(report);
}
},
+ { ignoreScripts },
);
},
signal,
diff --git a/apps/desktop/src/main/cindy-make/taskWorkspace.ts b/apps/desktop/src/main/cindy-make/taskWorkspace.ts
index fe760d1a25..a21d57ccfb 100644
--- a/apps/desktop/src/main/cindy-make/taskWorkspace.ts
+++ b/apps/desktop/src/main/cindy-make/taskWorkspace.ts
@@ -3,7 +3,8 @@ import path from 'node:path';
import type { CindyMakeTaskPreparation, MakeTaskWorkspace } from '../../shared/cindyMakeDoctor.js';
import { runSourceGit } from './sourceGit.js';
import { contentRef, snapshotContent, applyContent, taskContentRef } from './sourceContent.js';
-import { runSourcePnpm } from './sourcePnpm.js';
+import { assertPnpmInstallContained, assertPnpmInstallLinksContained } from './pnpmWriteRoots.js';
+import { runSourcePnpm, unverifiedPnpmEnv } from './sourcePnpm.js';
import {
CINDY_MAKE_RUN_ID_PATTERN,
CINDY_PERSONAL_BRANCH,
@@ -16,6 +17,8 @@ import {
export type TaskWorkspacePhase = 'checking' | 'creating' | 'installing';
+/** What an unverified install may see of the environment: see `unverifiedPnpmEnv`. */
+
export interface TaskWorkspaceDeps {
/** Toolchain PATH (system tools first, managed copies otherwise). */
processEnvironment: NodeJS.ProcessEnv;
@@ -156,6 +159,8 @@ export async function installCindyMakeWorktree(
deps: TaskWorkspaceDeps,
onPhase: (phase: TaskWorkspacePhase) => void = () => {},
onProgress?: (progress: NonNullable<CindyMakeTaskPreparation['dependencies']>) => void,
+ /** `ignoreScripts`: the content is not verified yet; its lifecycle scripts do not run. */
+ options: { ignoreScripts?: boolean } = {},
): Promise<MakeTaskWorkspace> {
const pnpm = deps.pnpm ?? runSourcePnpm;
onPhase('installing');
@@ -163,14 +168,49 @@ export async function installCindyMakeWorktree(
if (!isCindyMakeWorktreePath(userData, workspace.path)) {
throw Object.assign(new Error('invalid task workspace'), { code: 'gitFailed' });
}
+ if (options.ignoreScripts) {
+ // Unverified synced content must not point pnpm's write roots outside the
+ // worktree: a tracked `node_modules` symlink would have it install through
+ // the link, and content `.npmrc` / `pnpm-workspace.yaml` settings move the
+ // write roots outright. Every write root must be a real descendant of the
+ // worktree (see `pnpmWriteRoots`).
+ await assertPnpmInstallContained(workspace.path);
+ }
await pnpm(
- deps.processEnvironment,
- ['install', '--frozen-lockfile', '--prefer-offline', '--prod=false'],
+ options.ignoreScripts
+ ? // Unverified synced content runs no install-time code and sees only the
+ // credential-free environment (see `unverifiedPnpmEnv`): no lifecycle
+ // scripts, no `.pnpmfile.cjs` hooks (which `--ignore-scripts` alone would
+ // still execute), the write roots pinned over any `.npmrc` of the
+ // content's own, and no inherited variable to expand into a credential
+ // sent to a registry the content chooses.
+ unverifiedPnpmEnv(deps.processEnvironment)
+ : deps.processEnvironment,
+ [
+ 'install',
+ '--frozen-lockfile',
+ '--prefer-offline',
+ '--prod=false',
+ ...(options.ignoreScripts
+ ? [
+ '--ignore-scripts',
+ '--ignore-pnpmfile',
+ '--config.modules-dir=node_modules',
+ '--config.virtual-store-dir=node_modules/.pnpm',
+ '--config.store-dir=node_modules/.cindy-make-store',
+ '--config.strict-ssl=true',
+ ]
+ : []),
+ ],
workspace.path,
signal,
...(onProgress ? [onProgress] : []),
);
signal.throwIfAborted();
+ // The install populated the write roots the pre-install scan could not see
+ // into: whatever it linked must resolve inside the worktree (see
+ // `pnpmWriteRoots`).
+ if (options.ignoreScripts) await assertPnpmInstallLinksContained(workspace.path);
return workspace;
}
diff --git a/apps/desktop/src/main/cindy-make/upstreamMerge.ts b/apps/desktop/src/main/cindy-make/upstreamMerge.ts
index 01ffe468e0..085ec3b50f 100644
--- a/apps/desktop/src/main/cindy-make/upstreamMerge.ts
+++ b/apps/desktop/src/main/cindy-make/upstreamMerge.ts
@@ -1,5 +1,5 @@
import path from 'node:path';
-import { lstat, mkdir, readFile, realpath } from 'node:fs/promises';
+import { lstat, mkdir, readFile, realpath, rm } from 'node:fs/promises';
import type {
CindyMakeMergeError,
CindyMakeMergeState,
@@ -7,6 +7,8 @@ import type {
} from '../../shared/cindyMakeMerge.js';
import { CINDY_PERSONAL_BRANCH, makeSourceCheckoutPath, makeSourceRoot } from './sourcePaths.js';
import { removeMergeWorktreeResidue } from './mergeCleanupResidue.js';
+import { PERSONAL_TRACKING_REF } from './personalRemote.js';
+import { uncarriedChanges } from './carriedChanges.js';
import {
snapshotContent,
@@ -22,6 +24,7 @@ import {
MAKE_GIT_IDENTITY,
} from './localHistory.js';
+export { uncarriedChanges };
export type MergeGit = ContentGit;
function ownedGit(git: MergeGit, isCurrent: () => boolean): MergeGit {
return (args, cwd, indexFile) => {
@@ -30,6 +33,9 @@ function ownedGit(git: MergeGit, isCurrent: () => boolean): MergeGit {
};
}
const COMMIT = /^[0-9a-f]{40}$/i;
+/** Both strategies replay commits with `git rebase` in the retained candidate. */
+const rebases = (state: CindyMakeMergeState) =>
+ state.strategy === 'rebase' || state.strategy === 'combine';
const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
export const mergeError = (code: CindyMakeMergeError) => Object.assign(new Error(code), { code });
const samePath = (a: string, b: string) =>
@@ -73,7 +79,7 @@ export async function verifyMergeWorktree(
throw mergeError('unavailable');
const source = makeSourceCheckoutPath(userData);
let branch = (await git(['branch', '--show-current'], worktree)).trim();
- if (!branch && state.strategy === 'rebase') {
+ if (!branch && rebases(state)) {
for (const backend of ['rebase-merge', 'rebase-apply']) {
const nameFile = (
await git(
@@ -331,18 +337,44 @@ export async function discardFeatureMerge(
return true;
}
+/** At most this many uncarried changes are named in the state and the task prompt. */
+const MAX_NAMED_MISSING = 50;
+
+/** The side whose own commits a rebase replays: GitHub's when this computer's is kept. */
+function replayedSide(state: CindyMakeMergeState): string | undefined {
+ const github = state.remote?.commit;
+ return github && github !== state.upstreamCommit ? github : state.baselineCommit;
+}
+
+/** `result`: the checked result; using it anyway is bound to exactly that commit. */
+const missingError = (missing: string[], result: string) =>
+ Object.assign(mergeError('checksFailed'), {
+ missing: { count: missing.length, commits: missing.slice(0, MAX_NAMED_MISSING), result },
+ });
+
+/** Durably record the carried content's trust facts before the source moves. */
+export type MergeJournal = (merged: CindyMakeMergeState) => void;
+
/** Rebase only in the retained candidate, then move the clean personal checkout to its result. */
export async function applyUpstreamMerge(
userData: string,
state: CindyMakeMergeState,
git: MergeGit,
isCurrent: () => boolean = () => true,
+ /** The user chose to use the result although some changes are not in it (see `uncarriedChanges`). */
+ options: {
+ acceptMissing?: boolean;
+ /** Durably record the carried content's trust facts before the source moves (see `adoptedRewrite`). */
+ journal?: MergeJournal;
+ } = {},
): Promise<CindyMakeMergeState> {
if (!isCurrent()) throw mergeError('busy');
const worktree = await verifyMergeWorktree(userData, state, git);
if (state.feature) return applyFeatureMerge(userData, state, git, isCurrent);
- if (state.strategy === 'rebase') {
- if ((await git(['ls-files', '--unmerged'], worktree)).trim()) throw mergeError('dirty');
+ if (rebases(state)) {
+ // The resolver stopped with conflicts left (it asks the user): keep waiting for its task.
+ if ((await git(['ls-files', '--unmerged'], worktree)).trim())
+ return { ...state, status: 'conflict', needsInput: true, error: undefined };
if (
(await gitOperationExists(git, worktree, 'rebase-merge')) ||
(await gitOperationExists(git, worktree, 'rebase-apply'))
@@ -351,12 +383,28 @@ export async function applyUpstreamMerge(
await git([...MAKE_GIT_IDENTITY, 'rebase', '--continue'], worktree);
} catch (error) {
if ((await git(['ls-files', '--unmerged'], worktree)).trim())
- return { ...state, status: 'conflict', error: undefined };
+ return { ...state, status: 'conflict', needsInput: true, error: undefined };
throw error;
}
}
const result = await commitLocalFiles(git, worktree, 'Cindy Make: resolve upstream rebase');
await git(['merge-base', '--is-ancestor', state.upstreamCommit, result.commit], worktree);
+ // The user agreed to leave out what this exact result lacks; anything newer is checked again.
+ if (options.acceptMissing && state.missing?.result !== result.commit)
+ throw mergeError('checksFailed');
+ // Neither an official update nor a combine may lose a personal change unnoticed.
+ if (!options.acceptMissing) {
+ const replayed = replayedSide(state);
+ if (!replayed) throw mergeError('checksFailed');
+ const missing = await uncarriedChanges(
+ git,
+ worktree,
+ replayed,
+ state.upstreamCommit,
+ result.commit,
+ );
+ if (missing.length) throw missingError(missing, result.commit);
+ }
try {
await git(['diff', '--check', state.upstreamCommit, result.commit], worktree);
} catch {
@@ -375,16 +423,31 @@ export async function applyUpstreamMerge(
)
throw mergeError('baselineChanged');
if (!isCurrent()) throw mergeError('busy');
- if (!alreadyApplied) await git(['reset', '--keep', result.commit], source);
- if ((await snapshotContent(git, source)) !== result.tree) throw mergeError('baselineChanged');
- await git(['update-ref', PERSONAL_UPSTREAM_REF, state.upstreamCommit], source);
- return {
+ const merged: CindyMakeMergeState = {
...state,
status: 'merged',
commit: result.commit,
tree: result.tree,
error: undefined,
+ needsInput: undefined,
+ missing: undefined,
};
+ // The result carries the replayed content under new commits: its provenance must
+ // be durable before the source moves to it, so a crash right after the move can
+ // never leave still-unverified content looking trusted (over-marking is safe).
+ options.journal?.(merged);
+ // Combining with the fork keeps the shared official base; an official update moves to it.
+ // The new baseline is recorded before the source moves — the same order the
+ // remote-tip adoption uses. An interruption in between leaves "old tip + new
+ // base", which the base clamp detects and recovers; the reverse ("new tip +
+ // old base") looks like ordinary ancestry and could be published elsewhere.
+ await git(
+ ['update-ref', PERSONAL_UPSTREAM_REF, state.remote?.base ?? state.upstreamCommit],
+ source,
+ );
+ if (!alreadyApplied) await git(['reset', '--keep', result.commit], source);
+ if ((await snapshotContent(git, source)) !== result.tree) throw mergeError('baselineChanged');
+ return merged;
}
const commit = (await git(['rev-parse', 'HEAD'], worktree)).trim();
if (state.baselineTree && commit !== state.baselineCommit) throw mergeError('baselineChanged');
@@ -611,6 +674,89 @@ export async function applyFeatureMerge(
};
}
+/**
+ * Combine the personal version saved on the user's GitHub with this computer's.
+ * The side on the newer official version is kept as it is and the other side's
+ * own changes are replayed onto it (both on the same base: this computer's onto
+ * GitHub's). Neither side is lost: the kept side must be contained in the result,
+ * this computer's version is backed up, and GitHub keeps its version until the
+ * result is uploaded with a lease.
+ */
+export async function preparePersonalCombine(
+ userData: string,
+ initial: CindyMakeMergeState,
+ git: MergeGit,
+ publish: (state: CindyMakeMergeState) => Promise<void>,
+ isCurrent: () => boolean = () => true,
+ /** Passed through to the clean fast path: its adoption needs the same journal. */
+ options: { journal?: MergeJournal } = {},
+): Promise<CindyMakeMergeState> {
+ git = ownedGit(git, isCurrent);
+ const remote = initial.remote?.commit ?? initial.upstreamCommit;
+ const remoteBase = initial.remote?.base;
+ if (!COMMIT.test(remote) || !remoteBase || !COMMIT.test(remoteBase))
+ throw mergeError('unavailable');
+ const source = await assertSource(userData, git);
+ await assertNoGitOperation(git, source);
+ // Combine exactly the GitHub version the last sync fetched.
+ const tracked = (
+ await git(['rev-parse', '--verify', '--quiet', PERSONAL_TRACKING_REF + '^{commit}'], source).catch(
+ () => '',
+ )
+ ).trim();
+ if (tracked !== remote) throw mergeError('baselineChanged');
+ const personal = await commitPersonalFiles(git, source);
+ const localBase = (
+ await git(['rev-parse', '--verify', '--quiet', PERSONAL_UPSTREAM_REF + '^{commit}'], source).catch(
+ () => '',
+ )
+ ).trim();
+ if (!COMMIT.test(localBase)) throw mergeError('unavailable');
+ const isAncestor = async (ancestor: string, descendant: string) => {
+ try {
+ await git(['merge-base', '--is-ancestor', ancestor, descendant], source);
+ return true;
+ } catch (error) {
+ if ((error as { exitCode?: number }).exitCode === 1) return false;
+ throw error;
+ }
+ };
+ // Official versions only move forward; unrelated lines cannot be combined safely.
+ let ontoLocal: boolean;
+ if (localBase === remoteBase || (await isAncestor(localBase, remoteBase))) ontoLocal = false;
+ else if (await isAncestor(remoteBase, localBase)) ontoLocal = true;
+ else throw mergeError('unavailable');
+ if (!(await isAncestor(remoteBase, remote))) throw mergeError('unavailable');
+ const onto = ontoLocal ? personal.commit : remote;
+ const replay = ontoLocal ? remote : personal.commit;
+ const fork = (await git(['merge-base', replay, onto], source)).trim();
+ if (!COMMIT.test(fork)) throw mergeError('unavailable');
+ // Only the replayed side's own changes move: its official base must be behind the fork point.
+ if (!(await isAncestor(ontoLocal ? remoteBase : localBase, fork))) throw mergeError('unavailable');
+ // GitHub's version stays recoverable here even after the result replaces it there.
+ if (!ID.test(initial.id)) throw mergeError('unavailable');
+ await git(['update-ref', `refs/cindy-make/backups/${initial.id}/github`, remote], source);
+ return startRebaseCandidate(
+ userData,
+ {
+ ...initial,
+ upstreamCommit: onto,
+ remote: { base: ontoLocal ? localBase : remoteBase, commit: remote },
+ },
+ git,
+ publish,
+ isCurrent,
+ {
+ source,
+ baselineCommit: personal.commit,
+ baselineTree: personal.tree,
+ rebaseBase: fork,
+ replay,
+ journal: options.journal,
+ },
+ );
+}
+
/** Fetch a pinned official commit and try the merge away from the user's personal checkout. */
export async function prepareUpstreamMerge(
userData: string,
@@ -618,6 +764,8 @@ export async function prepareUpstreamMerge(
git: MergeGit,
publish: (state: CindyMakeMergeState) => Promise<void>,
isCurrent: () => boolean = () => true,
+ /** Passed through to the clean fast path: its adoption needs the same journal. */
+ options: { journal?: MergeJournal } = {},
): Promise<CindyMakeMergeState> {
git = ownedGit(git, isCurrent);
const worktree = mergeWorktree(userData, initial.id);
@@ -667,9 +815,43 @@ export async function prepareUpstreamMerge(
).trim() || (await git(['merge-base', baselineCommit, initial.upstreamCommit], source)).trim();
if (!COMMIT.test(previousUpstream)) throw mergeError('unavailable');
await git(['merge-base', '--is-ancestor', previousUpstream, baselineCommit], source);
- const merges = (
- await git(['rev-list', '--merges', previousUpstream + '..' + baselineCommit], source)
- )
+ return startRebaseCandidate(userData, initial, git, publish, isCurrent, {
+ source,
+ baselineCommit,
+ baselineTree,
+ rebaseBase: previousUpstream,
+ journal: options.journal,
+ });
+}
+
+/**
+ * Replay `rebaseBase..baselineCommit` onto `upstreamCommit` in a new retained
+ * candidate, never in the personal checkout. A conflict, or merge commits whose
+ * own edits a rebase cannot carry, leaves the candidate for a resolution task.
+ */
+async function startRebaseCandidate(
+ userData: string,
+ initial: CindyMakeMergeState,
+ git: MergeGit,
+ publish: (state: CindyMakeMergeState) => Promise<void>,
+ isCurrent: () => boolean,
+ start: {
+ source: string;
+ /** This computer's personal version; it must be unchanged when the result is adopted. */
+ baselineCommit: string;
+ baselineTree: string;
+ rebaseBase: string;
+ /** The commits replayed onto `upstreamCommit` end here; defaults to the baseline. */
+ replay?: string;
+ /** Durably record the carried content's trust facts before a clean adopt moves. */
+ journal?: MergeJournal;
+ },
+): Promise<CindyMakeMergeState> {
+ const { source, baselineCommit, baselineTree } = start;
+ const previousUpstream = start.rebaseBase;
+ const replay = start.replay ?? baselineCommit;
+ const worktree = mergeWorktree(userData, initial.id);
+ const merges = (await git(['rev-list', '--merges', previousUpstream + '..' + replay], source))
.trim()
.split(/\s+/)
.filter(Boolean);
@@ -688,7 +870,7 @@ export async function prepareUpstreamMerge(
...initial,
baselineCommit,
baselineTree,
- strategy: 'rebase',
+ strategy: initial.remote ? 'combine' : 'rebase',
rebaseBase: previousUpstream,
...(rebaseReview ? { rebaseReview: true } : {}),
status: 'merging',
@@ -696,7 +878,7 @@ export async function prepareUpstreamMerge(
};
// Save intent before creating the worktree so a crash cannot lose its identity.
await publish(state);
- await git(['worktree', 'add', '-b', mergeBranch(state.id), worktree, baselineCommit], source);
+ await git(['worktree', 'add', '-b', mergeBranch(state.id), worktree, replay], source);
await git(['update-ref', 'refs/cindy-make/backups/' + state.id + '/files', baselineTree], source);
try {
await git(
@@ -721,5 +903,14 @@ export async function prepareUpstreamMerge(
}
// Rebase does not replay edits introduced only in a merge commit. Never silently adopt their loss.
if (state.rebaseReview) return { ...state, status: 'conflict' };
- return applyUpstreamMerge(userData, state, git, isCurrent);
+ try {
+ // The clean fast path adopts the same way: its journal runs before the move too.
+ return await applyUpstreamMerge(userData, state, git, isCurrent, { journal: start.journal });
+ } catch (error) {
+ // A clean rebase that still lost a change (for example a merge's own edits): its task
+ // puts the named changes back before anything is adopted.
+ const missing = (error as { missing?: CindyMakeMergeState['missing'] }).missing;
+ if (!missing) throw error;
+ return { ...state, status: 'conflict', rebaseReview: true, missing };
+ }
}
diff --git a/apps/desktop/src/main/cindy-make/upstreamMergeController.ts b/apps/desktop/src/main/cindy-make/upstreamMergeController.ts
index 21a4e7c1d8..9a1bf57e54 100644
--- a/apps/desktop/src/main/cindy-make/upstreamMergeController.ts
+++ b/apps/desktop/src/main/cindy-make/upstreamMergeController.ts
@@ -27,15 +27,35 @@ export function parseSavedUpstreamMerge(raw: string, userData: string): SavedUps
typeof state.upstreamCommit !== 'string' ||
(state.upstreamCommit !== '' && !/^[0-9a-f]{40}$/i.test(state.upstreamCommit)) ||
(state.baselineTree !== undefined && !/^[0-9a-f]{40,64}$/i.test(state.baselineTree)) ||
- (state.strategy !== undefined && state.strategy !== 'rebase') ||
+ (state.strategy !== undefined && state.strategy !== 'rebase' && state.strategy !== 'combine') ||
+ (state.strategy === 'combine' && !state.remote) ||
(state.rebaseBase !== undefined && !/^[0-9a-f]{40}$/i.test(state.rebaseBase)) ||
(state.rebaseReview !== undefined && typeof state.rebaseReview !== 'boolean') ||
+ (state.needsInput !== undefined && typeof state.needsInput !== 'boolean') ||
+ (state.reminded !== undefined && typeof state.reminded !== 'boolean') ||
+ (state.missing !== undefined &&
+ (!state.missing ||
+ !Number.isSafeInteger(state.missing.count) ||
+ state.missing.count < 1 ||
+ !Array.isArray(state.missing.commits) ||
+ state.missing.commits.length > 50 ||
+ state.missing.commits.length > state.missing.count ||
+ !state.missing.commits.every((commit) => /^[0-9a-f]{40}$/i.test(commit)) ||
+ (state.missing.result !== undefined && !/^[0-9a-f]{40}$/i.test(state.missing.result)))) ||
(state.cancellationRequested !== undefined &&
typeof state.cancellationRequested !== 'boolean') ||
(state.cleanupPending !== undefined && typeof state.cleanupPending !== 'boolean') ||
(state.taskOwned !== undefined &&
(typeof state.taskOwned !== 'boolean' || (state.taskOwned && !saved.sessionOwner))) ||
(state.feature !== undefined && (!validFeaturePlan(state.feature) || !saved.sessionOwner)) ||
+ (state.remote !== undefined &&
+ (!state.remote ||
+ typeof state.remote.base !== 'string' ||
+ !/^[0-9a-f]{40}$/i.test(state.remote.base) ||
+ (state.remote.commit !== undefined &&
+ (typeof state.remote.commit !== 'string' ||
+ !/^[0-9a-f]{40}$/i.test(state.remote.commit))) ||
+ state.feature !== undefined)) ||
(state.tree !== undefined && !/^[0-9a-f]{40,64}$/i.test(state.tree)) ||
(state.baselineCommit !== undefined && !/^[0-9a-f]{40}$/i.test(state.baselineCommit)) ||
(state.sessionId !== undefined &&
@@ -68,6 +88,22 @@ function validFeaturePlan(feature: MakeFeatureMergePlan): boolean {
feature.nextStep <= (feature.mergeCommit ? 1 : feature.steps.length)
);
}
+/**
+ * A retained candidate whose resolver task is not there: it never opened, failed to
+ * open, or was removed. Sync opens (or reopens) it, keeping the candidate's work.
+ */
+export function resumable(state: CindyMakeMergeState): boolean {
+ return (
+ !state.feature &&
+ !state.ownedByAnotherAccount &&
+ !state.cancellationRequested &&
+ !!state.hasWorkspace &&
+ ((!state.sessionId &&
+ (state.status === 'conflict' || (state.status === 'failed' && state.error === 'startFailed'))) ||
+ (state.status === 'failed' && state.error === 'unavailable'))
+ );
+}
+
export interface UpstreamMergeDependencies {
read: () => SavedUpstreamMerge | undefined;
write: (saved: SavedUpstreamMerge) => void;
@@ -85,6 +121,8 @@ export interface UpstreamMergeDependencies {
state: CindyMakeMergeState,
isCurrent: () => boolean,
publish?: (state: CindyMakeMergeState) => Promise<void>,
+ /** The user chose to use a result that does not carry every change. */
+ options?: { acceptMissing?: boolean },
) => Promise<CindyMakeMergeState>;
prepareFeature?: (
state: CindyMakeMergeState,
@@ -93,6 +131,12 @@ export interface UpstreamMergeDependencies {
isCurrent: () => boolean,
) => Promise<CindyMakeMergeState>;
applied?: (state: CindyMakeMergeState, isCurrent: () => boolean) => Promise<void>;
+ /** Combine the fork's personal version with this computer's (see `preparePersonalCombine`). */
+ prepareCombine?: (
+ state: CindyMakeMergeState,
+ publish: (state: CindyMakeMergeState) => Promise<void>,
+ isCurrent: () => boolean,
+ ) => Promise<CindyMakeMergeState>;
session: (
state: CindyMakeMergeState,
options: CindyMakeTaskOptions | undefined,
@@ -100,6 +144,8 @@ export interface UpstreamMergeDependencies {
isCurrent: () => boolean,
) => Promise<string>;
running: (sessionId: string) => boolean;
+ /** Ask the resolver, in its own task, to put the changes the result lost back. */
+ remind?: (state: CindyMakeMergeState, isCurrent: () => boolean) => Promise<void>;
/** Wait between terminal observation and the provider's idle state. */
sleep?: (milliseconds: number) => Promise<void>;
refresh: () => Promise<void>;
@@ -233,6 +279,16 @@ export class UpstreamMergeController {
);
}
private save(state: CindyMakeMergeState): void {
+ // A finished combine is stored like an official update: older clients reject
+ // `combine`, and nothing of it remains to resume.
+ if (
+ state.strategy === 'combine' &&
+ (state.status === 'merged' || state.status === 'cancelled') &&
+ !state.hasWorkspace &&
+ !state.cleanupPending &&
+ !state.cancellationRequested
+ )
+ state = { ...state, strategy: 'rebase' };
// In-flight Git/session callbacks cannot erase a persisted Stop decision.
if (
this.saved?.state.id === state.id &&
@@ -256,11 +312,14 @@ export class UpstreamMergeController {
const state = this.saved?.state;
if (!state) return;
const code = (error as { code?: string })?.code;
+ // A failure says what is missing now, never an older list.
+ const missing = (error as { missing?: CindyMakeMergeState['missing'] })?.missing;
this.save({
...state,
status: 'failed',
hasWorkspace: this.deps.hasWorkspace(state),
error: errors.has(code ?? '') ? (code as CindyMakeMergeState['error']) : 'gitFailed',
+ missing,
});
}
private async acceptResult(result: CindyMakeMergeState, isCurrent: () => boolean): Promise<void> {
@@ -336,6 +395,12 @@ export class UpstreamMergeController {
async update(
options?: CindyMakeTaskOptions,
signal?: AbortSignal,
+ /**
+ * `target` pins the official version the caller already chose; `autoResolve`
+ * opens the resolution task on conflict without another decision (the user's
+ * Sync is that decision). Task-owned updates always resolve automatically.
+ */
+ extra: { target?: { ref: string; commit: string }; autoResolve?: boolean } = {},
): Promise<CindyMakeMergeState | undefined> {
signal?.throwIfAborted();
await this.finishPreviousCleanup();
@@ -382,7 +447,8 @@ export class UpstreamMergeController {
status: 'fetching',
ref: '',
upstreamCommit: '',
- ...(signal ? { taskOwned: true } : {}),
+ // Sync and task preparation own their candidate: either may abandon it.
+ ...(signal || (extra.autoResolve && owner) ? { taskOwned: true } : {}),
},
};
this.save(this.saved.state);
@@ -390,7 +456,7 @@ export class UpstreamMergeController {
signal?.addEventListener('abort', markCancelled, { once: true });
markCancelled();
signal?.throwIfAborted();
- const latest = await this.deps.latest();
+ const latest = extra.target ?? (await this.deps.latest());
signal?.throwIfAborted();
if (signal && this.deps.owner() !== owner) throw mergeError('busy');
this.save({ ...this.saved!.state, ref: latest.ref, upstreamCommit: latest.commit });
@@ -401,19 +467,18 @@ export class UpstreamMergeController {
() => !signal || this.deps.owner() === owner,
);
this.save(result);
- // Task preparation authorizes its existing dedicated conflict task.
- // Manual Settings updates still wait for the explicit resolve decision.
+ // Task preparation and Sync authorize their dedicated conflict task.
if (
- signal &&
- !signal.aborted &&
+ (signal || extra.autoResolve) &&
+ !signal?.aborted &&
this.deps.owner() === owner &&
result.status === 'conflict'
)
await this.createResolutionTask(options, owner, signal);
await this.deps.refresh().catch(() => undefined);
});
- if (signal && !operationId) {
- signal.throwIfAborted();
+ if ((signal || extra.autoResolve) && !operationId) {
+ signal?.throwIfAborted();
throw mergeError('busy');
}
return result;
@@ -640,6 +705,144 @@ export class UpstreamMergeController {
signal?.removeEventListener('abort', markCancelled);
}
}
+ /**
+ * Combine the GitHub version `remote.commit` with this computer's personal
+ * version. A conflict opens its resolution task when `autoResolve` (Sync);
+ * otherwise it waits for the explicit resolve decision.
+ */
+ async combine(
+ remote: { commit: string; base: string },
+ options?: CindyMakeTaskOptions,
+ autoResolve = false,
+ ): Promise<CindyMakeMergeState | undefined> {
+ const hash = /^[0-9a-f]{40}$/i;
+ if (!hash.test(remote.commit) || !hash.test(remote.base) || !this.deps.prepareCombine)
+ throw mergeError('unavailable');
+ await this.finishPreviousCleanup();
+ const owner = this.deps.owner();
+ if (
+ !owner ||
+ this.active ||
+ this.saved?.state.cancellationRequested ||
+ (this.saved?.state.hasWorkspace && this.saved.state.status !== 'merged')
+ )
+ throw mergeError('busy');
+ let started = false;
+ const result = await this.run(async () => {
+ if (
+ this.deps.owner() !== owner ||
+ this.saved?.state.cancellationRequested ||
+ (this.saved?.state.hasWorkspace && this.saved.state.status !== 'merged')
+ )
+ return;
+ this.saved = {
+ sessionOwner: owner,
+ state: {
+ id: randomUUID(),
+ status: 'merging',
+ ref: 'github',
+ upstreamCommit: remote.commit,
+ remote: { base: remote.base, commit: remote.commit },
+ ...(autoResolve ? { taskOwned: true } : {}),
+ },
+ };
+ this.save(this.saved.state);
+ started = true;
+ const result = await this.deps.prepareCombine!(
+ this.saved.state,
+ async (next) => this.save(next),
+ () => this.deps.owner() === owner,
+ );
+ this.save(result);
+ if (autoResolve && result.status === 'conflict' && this.deps.owner() === owner)
+ await this.createResolutionTask(options, owner);
+ await this.deps.refresh().catch(() => undefined);
+ });
+ if (!started) throw mergeError('busy');
+ return result;
+ }
+ /**
+ * Give up a source operation that waits for its conflict (Sync's Abandon): stop its
+ * resolver and discard the candidate. Nothing is adopted; both versions stay as they were.
+ */
+ async abandon(operationId: string): Promise<CindyMakeMergeState | undefined> {
+ const state = this.saved?.state;
+ const owner = this.deps.owner();
+ // While its result is being checked or adopted, Abandon could no longer promise that
+ // nothing changes; it waits until that settles.
+ if (
+ !state ||
+ state.id !== operationId ||
+ state.feature ||
+ state.status === 'merged' ||
+ state.status === 'cancelled' ||
+ state.status === 'checking' ||
+ this.active ||
+ (this.saved?.sessionOwner && this.saved.sessionOwner !== owner)
+ )
+ throw mergeError('busy');
+ if (!state.sessionId && !state.cancellationRequested && !state.taskOwned)
+ return this.cancel(operationId);
+ // Stopping a resolver needs the owning account; never persist a half-owned state.
+ if (!owner || this.saved?.sessionOwner !== owner) throw mergeError('busy');
+ if (!state.taskOwned) this.save({ ...state, taskOwned: true });
+ return this.cancelBuild(operationId);
+ }
+ /**
+ * Sync finishes a retained source operation before anything else: an Abandon that
+ * could not finish is completed, a conflict without a task gets its resolver. A
+ * candidate interrupted before its rebase ran waits for Abandon instead of an Agent
+ * that cannot act; everything else is returned as it is for Sync to show.
+ */
+ async resumeForSync(options?: CindyMakeTaskOptions): Promise<CindyMakeMergeState | undefined> {
+ const state = this.status();
+ if (!state || state.feature || state.ownedByAnotherAccount) return state;
+ if (state.cancellationRequested)
+ return state.taskOwned ? this.cancelBuild(state.id) : this.cancel(state.id);
+ if (resumable(state)) return this.resolve(options, state.id);
+ return state;
+ }
+ /**
+ * The user chose to use a checked result although some of their changes are not in
+ * it (Sync's "use it anyway"). Both original versions stay in backup refs.
+ */
+ async acceptMissing(operationId: string): Promise<CindyMakeMergeState | undefined> {
+ const state = this.saved?.state;
+ const owner = this.deps.owner();
+ if (
+ this.active ||
+ !owner ||
+ !state ||
+ state.id !== operationId ||
+ state.feature ||
+ state.status !== 'failed' ||
+ state.error !== 'checksFailed' ||
+ !state.missing ||
+ !state.sessionId ||
+ !state.hasWorkspace ||
+ state.cancellationRequested ||
+ this.saved?.sessionOwner !== owner ||
+ this.deps.running(state.sessionId)
+ )
+ throw mergeError('busy');
+ const sessionId = state.sessionId;
+ return this.run(async () => {
+ const isCurrent = () =>
+ this.saved?.state.id === operationId &&
+ !this.saved.state.cancellationRequested &&
+ this.saved.sessionOwner === owner &&
+ this.deps.owner() === owner &&
+ !this.deps.running(sessionId);
+ if (!isCurrent()) throw mergeError('busy');
+ this.interruption = undefined;
+ this.save({ ...state, status: 'checking', error: undefined });
+ const result = await this.deps.apply(state, isCurrent, async (next) => this.save(next), {
+ acceptMissing: true,
+ });
+ await this.acceptResult(result, isCurrent);
+ await this.deps.refresh().catch(() => undefined);
+ });
+ }
private async createResolutionTask(
options: CindyMakeTaskOptions | undefined,
owner: string,
@@ -730,9 +933,17 @@ export class UpstreamMergeController {
this.deps.owner() === owner &&
!this.deps.running(sessionId)
: isCurrent();
- const result = await this.deps.apply(state, canFinishAdoption, async (next) =>
- this.save(next),
- );
+ let result: CindyMakeMergeState;
+ try {
+ result = await this.deps.apply(state, canFinishAdoption, async (next) => this.save(next));
+ } catch (error) {
+ const missing = (error as { missing?: CindyMakeMergeState['missing'] })?.missing;
+ // The result lost changes: the resolver is asked once, in its task, to put them back.
+ if (!missing || state.reminded || !this.deps.remind || !isCurrent()) throw error;
+ this.save({ ...state, status: 'resolving', missing, reminded: true, error: undefined });
+ await this.deps.remind(this.saved!.state, isCurrent);
+ return;
+ }
await this.acceptResult(result, canFinishAdoption);
if (result.feature && result.status === 'conflict' && isCurrent()) {
// Unresolved files from this turn are not a new conflict. Stop waiting
@@ -797,8 +1008,19 @@ export class UpstreamMergeController {
accepted = true;
this.acceptedTurn += 1;
this.interruption = undefined;
- if (state.status === 'failed' && state.error === 'interrupted')
- this.save({ ...state, status: 'resolving', error: undefined });
+ // The user answered the resolver, or continued it after an interruption or a failed check.
+ if (
+ (state.status === 'failed' && state.error === 'interrupted') ||
+ state.needsInput ||
+ (state.status === 'failed' && state.missing)
+ )
+ this.save({
+ ...state,
+ status: 'resolving',
+ error: undefined,
+ needsInput: undefined,
+ missing: undefined,
+ });
};
}
}
diff --git a/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts b/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts
index a0bbd4b693..e1f604d0e6 100644
--- a/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts
+++ b/apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts
@@ -11,24 +11,38 @@ import { throwIpcError } from '../utils/ipcValidate.js';
import { captureDataOwnerBroadcastScope } from '../device-link/broadcast-tap.js';
import { createLogger } from '../logger.js';
import { CINDY_PERSONAL_BRANCH, makeSourceRoot, makeSourceCheckoutPath } from './sourcePaths.js';
-import { snapshotContent } from './sourceContent.js';
+import { PERSONAL_UPSTREAM_REF, snapshotContent } from './sourceContent.js';
import { rollbackUnbuiltHistory } from './buildRollback.js';
+import { recordPendingBuild } from './pendingBuild.js';
import { hasPublishedPersonalVersionCommit } from './versionStore.js';
import {
createMakeToolchainEnvironment,
resolveMakeToolEnvironment,
} from './toolchainEnvironment.js';
-import { readCurrentCindySourceStatus } from './sourcePreparation.js';
+import { readCurrentCindySourceStatus, recordCindySourceRef } from './sourcePreparation.js';
import { createLatestSourceVersionReader, sourceChannel } from './latestSourceVersion.js';
import { runSourceGit } from './sourceGit.js';
+import { describeOriginalVersion } from './versionStartup.js';
+import {
+ MIGRATIONS_PATH,
+ notBehindBase,
+ pickSyncTarget,
+ type SyncTarget,
+} from './syncTarget.js';
import { cindyMakeManager } from './manager.js';
import { validateCindyMakeTaskStart } from './taskRuntime.js';
+import { journalMergeProvenance } from './personalRemoteRuntime.js';
import { cleanupCompletedMakeMergeTask } from './taskManagement.js';
-import { ensureUpstreamMergeSession, assertUpstreamMergeSession } from './upstreamMergeSession.js';
+import {
+ ensureUpstreamMergeSession,
+ assertUpstreamMergeSession,
+ remindUpstreamMergeSession,
+} from './upstreamMergeSession.js';
import { withSessionRouteLock } from '../localDb/sessionRouteLock.js';
import { UpstreamMergeController, parseSavedUpstreamMerge } from './upstreamMergeController.js';
import {
prepareUpstreamMerge,
+ preparePersonalCombine,
applyUpstreamMerge,
verifyMergeWorktree,
mergeWorktree,
@@ -42,11 +56,29 @@ import {
} from './upstreamMerge.js';
const log = createLogger('cindy-make');
+const OFFICIAL_URL = 'https://github.com/makecindy/cindy.git';
let controller: UpstreamMergeController | undefined;
+let syncTarget: (() => Promise<SyncTarget>) | undefined;
let unavailable = false;
-const ownerKey = () => captureDataOwnerBroadcastScope().ownerScopeKey ?? '';
+/**
+ * The account a retained operation belongs to. Signing in again as the same account
+ * advances the session generation but keeps its operations; async staleness is still
+ * checked with the full owner scope.
+ */
+const stableOwner = (key: string | undefined) => {
+ // `<mode>:<owner>:<generation>`; an already stable `<mode>:<owner>` is kept as it is.
+ const parts = key?.split(':') ?? [];
+ return parts.length >= 3 && /^\d+$/.test(parts.at(-1)!)
+ ? parts.slice(0, -1).join(':')
+ : (key ?? '');
+};
+const ownerKey = () => stableOwner(captureDataOwnerBroadcastScope().ownerScopeKey);
-function recordAppliedMerge(state: CindyMakeMergeState, isCurrent: () => boolean): void {
+function recordAppliedMerge(
+ userData: string,
+ state: CindyMakeMergeState,
+ isCurrent: () => boolean,
+): void {
if (
!state.feature ||
!state.commit ||
@@ -56,6 +88,10 @@ function recordAppliedMerge(state: CindyMakeMergeState, isCurrent: () => boolean
)
return;
if (!isCurrent()) throw mergeError('busy');
+ // The pending-generation fact lands before its receipt (see `pendingBuild`):
+ // a crash in between must never leave an unbuilt integration invisible to the
+ // other accounts sharing this source.
+ recordPendingBuild(makeSourceRoot(userData), { commit: state.commit, tree: state.tree });
captureMakeHistoryStore().receipt(state.feature.runId, {
id: state.id,
action: state.feature.action,
@@ -121,7 +157,7 @@ async function recoverAppliedMergeReceipt(
)
throw mergeError('baselineChanged');
await command(['merge-base', '--is-ancestor', state.baselineCommit, commit], source);
- recordAppliedMerge({ ...state, commit, tree }, isCurrent);
+ recordAppliedMerge(userData, { ...state, commit, tree }, isCurrent);
}
/** Called explicitly at bootstrap, before source reset can be invoked. */
@@ -142,16 +178,86 @@ export function configureUpstreamMerge(isRunning: (id: string) => boolean): void
signal,
);
};
+ // Settings names the official version the personal version is on now.
+ const recordOfficialRef = async (state: CindyMakeMergeState) => {
+ if (state.status === 'merged' && !state.feature && !state.remote && state.ref)
+ await recordCindySourceRef(root, state.ref).catch(() => undefined);
+ return state;
+ };
const refresh = async () => {
const env = await createMakeToolchainEnvironment(userData);
await cindyMakeManager.refreshSourceStatus(() => readCurrentCindySourceStatus(root, env));
};
+ // The newest official release this computer's original Cindy can switch with.
+ syncTarget = async () => {
+ const env = await createMakeToolchainEnvironment(userData);
+ const source = await readCurrentCindySourceStatus(root, env);
+ const fallbackChannel = !app.isPackaged
+ ? 'dev'
+ : /-beta(?:\.|$)/i.test(app.getVersion())
+ ? 'beta'
+ : 'release';
+ const channel = sourceChannel(source, fallbackChannel);
+ // An explicit update gets a fresh pin rather than the Settings display cache.
+ const { latestVersion } = await createLatestSourceVersionReader((url, init) =>
+ net.fetch(url, init),
+ )(source, channel);
+ if (latestVersion?.status !== 'ready') throw mergeError('unavailable');
+ const command = await git();
+ const checkout = makeSourceCheckoutPath(userData);
+ const exitsZero = (args: string[]) =>
+ command(args, checkout).then(
+ () => true,
+ (error) => {
+ if ((error as { exitCode?: number }).exitCode === 1) return false;
+ throw error;
+ },
+ );
+ let original: ReturnType<typeof describeOriginalVersion> | undefined;
+ try {
+ original = describeOriginalVersion();
+ } catch {
+ // Unknown original: keep following the latest release.
+ }
+ return pickSyncTarget({
+ latest: latestVersion,
+ original,
+ tagCommit: async (tag) => {
+ const lines = (
+ await command(
+ ['ls-remote', '--tags', OFFICIAL_URL, `refs/tags/${tag}`, `refs/tags/${tag}^{}`],
+ checkout,
+ )
+ )
+ .split(/\r?\n/)
+ .map((line) => line.trim().split(/\s+/));
+ // An annotated tag points at its tag object; the peeled line names the commit.
+ return (
+ lines.find(([, ref]) => ref === `refs/tags/${tag}^{}`)?.[0] ??
+ lines.find(([, ref]) => ref === `refs/tags/${tag}`)?.[0]
+ );
+ },
+ fetch: async (commits) => {
+ await command(
+ ['fetch', '--no-tags', '--no-write-fetch-head', '--no-auto-maintenance', OFFICIAL_URL, ...commits],
+ checkout,
+ );
+ },
+ sameMigrations: (from, to) => exitsZero(['diff', '--quiet', from, to, '--', MIGRATIONS_PATH]),
+ isAncestor: (ancestor, descendant) =>
+ exitsZero(['merge-base', '--is-ancestor', ancestor, descendant]),
+ });
+ };
try {
controller = new UpstreamMergeController({
read: () => {
const raw = readAtomicFileSync(stateFile);
if (raw === null) return;
- const saved = parseSavedUpstreamMerge(raw, userData);
+ const parsed = parseSavedUpstreamMerge(raw, userData);
+ // Records written before owners were per account carry the session generation.
+ const saved = parsed.sessionOwner
+ ? { ...parsed, sessionOwner: stableOwner(parsed.sessionOwner) }
+ : parsed;
savedOwner = saved.sessionOwner;
return saved;
},
@@ -170,30 +276,57 @@ export function configureUpstreamMerge(isRunning: (id: string) => boolean): void
return run();
}),
),
+ // Task preparation and builds follow the same compatible official version as Sync,
+ // and never move the personal version to an older official version than it is on.
latest: async () => {
- const env = await createMakeToolchainEnvironment(userData);
- const source = await readCurrentCindySourceStatus(root, env);
- const fallbackChannel = !app.isPackaged
- ? 'dev'
- : /-beta(?:\.|$)/i.test(app.getVersion())
- ? 'beta'
- : 'release';
- const channel = sourceChannel(source, fallbackChannel);
- // An explicit update gets a fresh pin rather than the Settings display cache.
- const { latestVersion } = await createLatestSourceVersionReader((url, init) =>
- net.fetch(url, init),
- )(source, channel);
- if (latestVersion?.status !== 'ready') throw mergeError('unavailable');
- return latestVersion;
+ const { ref, commit } = await syncTarget!();
+ const command = await git();
+ const checkout = makeSourceCheckoutPath(userData);
+ const isAncestor = (ancestor: string, descendant: string) =>
+ command(['merge-base', '--is-ancestor', ancestor, descendant], checkout).then(
+ () => true,
+ (error) => {
+ if ((error as { exitCode?: number }).exitCode === 1) return false;
+ throw error;
+ },
+ );
+ const base = (
+ await command(
+ ['rev-parse', '--verify', '--quiet', `${PERSONAL_UPSTREAM_REF}^{commit}`],
+ checkout,
+ ).catch(() => '')
+ ).trim();
+ // The recorded base is trusted only as the personal tip's ancestor: an
+ // interrupted move can leave "old tip + new base", and clamping to the
+ // shared history of the two recovers the base that tip really sits on.
+ const tip = (
+ await command(
+ ['rev-parse', '--verify', '--quiet', 'refs/heads/cindy-personal^{commit}'],
+ checkout,
+ ).catch(() => '')
+ ).trim();
+ const clamped =
+ !base || !tip || (await isAncestor(base, tip))
+ ? base
+ : (await command(['merge-base', tip, base], checkout).catch(() => '')).trim();
+ return notBehindBase({ ref, commit }, clamped, isAncestor);
},
prepare: async (state, publish, isCurrent) =>
- prepareUpstreamMerge(userData, state, await git(), publish, isCurrent),
+ recordOfficialRef(
+ await prepareUpstreamMerge(userData, state, await git(), publish, isCurrent, {
+ journal: journalMergeProvenance,
+ }),
+ ),
+ prepareCombine: async (state, publish, isCurrent) =>
+ preparePersonalCombine(userData, state, await git(), publish, isCurrent, {
+ journal: journalMergeProvenance,
+ }),
prepareFeature: async (state, plan, publish, isCurrent) => {
if (!isCurrent() || isRunning(plan.taskSessionId)) throw mergeError('busy');
return prepareFeatureMerge(userData, state, plan, await git(), publish, isCurrent);
},
- applied: async (state, isCurrent) => recordAppliedMerge(state, isCurrent),
- apply: async (state, isCurrent, publish) => {
+ applied: async (state, isCurrent) => recordAppliedMerge(userData, state, isCurrent),
+ apply: async (state, isCurrent, publish, options) => {
if (state.feature && (!state.sessionId || state.commit))
return applyFeatureMerge(userData, state, await git(), isCurrent, publish);
if (!state.sessionId) throw mergeError('unavailable');
@@ -202,9 +335,17 @@ export function configureUpstreamMerge(isRunning: (id: string) => boolean): void
await assertUpstreamMergeSession(userData, state);
return state.feature
? applyFeatureMerge(userData, state, await git(), isCurrent, publish)
- : applyUpstreamMerge(userData, state, await git(), isCurrent);
+ : recordOfficialRef(
+ await applyUpstreamMerge(userData, state, await git(), isCurrent, {
+ ...options,
+ // Durable content-trust facts before the source moves to the
+ // rewritten result (see `journalMergeProvenance`).
+ journal: journalMergeProvenance,
+ }),
+ );
});
},
+ remind: (state, isCurrent) => remindUpstreamMergeSession(state, isCurrent),
session: async (state, options, bind, isCurrent) => {
if (!ownerKey()) throw mergeError('unavailable');
await verifyMergeWorktree(userData, state, await git());
@@ -243,6 +384,7 @@ export function configureUpstreamMerge(isRunning: (id: string) => boolean): void
return command(args, cwd, index);
},
(commit) => hasPublishedPersonalVersionCommit(userData, commit),
+ root,
);
return true;
});
@@ -344,6 +486,65 @@ export async function actUpstreamMerge(raw: unknown): Promise<CindyMakeMergeStat
}
}
+/** The official version Sync moves the personal version to (see `pickSyncTarget`). */
+export async function resolveSyncTarget(): Promise<SyncTarget> {
+ if (!syncTarget) throw mergeError('unavailable');
+ return syncTarget();
+}
+
+/** Sync's official update: pinned to the version it showed, resolving conflicts in a task. */
+export async function updateForSync(
+ target: { ref: string; commit: string },
+ options?: CindyMakeTaskOptions,
+): Promise<CindyMakeMergeState | undefined> {
+ if (!controller || unavailable) throw mergeError('unavailable');
+ return controller.update(options, undefined, { target, autoResolve: true });
+}
+
+/** Sync's combine with the GitHub version, resolving conflicts in a task. */
+export async function combineForSync(
+ remote: { commit: string; base: string },
+ options?: CindyMakeTaskOptions,
+): Promise<CindyMakeMergeState | undefined> {
+ if (!controller || unavailable) throw mergeError('unavailable');
+ return controller.combine(remote, options, true);
+}
+
+/** Sync's "use it anyway" for a result that does not carry every personal change. */
+export async function acceptForSync(
+ operationId: string,
+): Promise<CindyMakeMergeState | undefined> {
+ if (!controller || unavailable) throw mergeError('unavailable');
+ return controller.acceptMissing(operationId);
+}
+
+/** A candidate waits for its task or a decision; the personal version stays as it is meanwhile. */
+export function hasRetainedSourceOperation(): boolean {
+ const state = controller && !unavailable ? controller.status() : undefined;
+ return !!state?.hasWorkspace && state.status !== 'merged';
+}
+
+/** The retained source operation, if any (Sync shows and continues it). */
+export function sourceOperation(): CindyMakeMergeState | undefined {
+ return controller && !unavailable ? controller.status() : undefined;
+}
+
+/** A retained source operation Sync must finish first: open its task if it has none yet. */
+export async function resumeForSync(
+ options?: CindyMakeTaskOptions,
+): Promise<CindyMakeMergeState | undefined> {
+ if (!controller || unavailable) throw mergeError('unavailable');
+ return controller.resumeForSync(options);
+}
+
+/** Sync's Abandon: stop the conflict task and discard the candidate; nothing is adopted. */
+export async function abandonForSync(
+ operationId: string,
+): Promise<CindyMakeMergeState | undefined> {
+ if (!controller || unavailable) throw mergeError('unavailable');
+ return controller.abandon(operationId);
+}
+
/** Only Main passes verified task facts here; renderer requests go through history admission. */
export async function integrateMakeHistory(
plan: MakeFeatureMergePlan,
diff --git a/apps/desktop/src/main/cindy-make/upstreamMergeSession.ts b/apps/desktop/src/main/cindy-make/upstreamMergeSession.ts
index 0339562f2d..db1aa91353 100644
--- a/apps/desktop/src/main/cindy-make/upstreamMergeSession.ts
+++ b/apps/desktop/src/main/cindy-make/upstreamMergeSession.ts
@@ -20,15 +20,44 @@ import { dispatchCindyMakeMergeTask } from './taskRuntime.js';
import { mergeError, mergeWorktree } from './upstreamMerge.js';
import { t } from '../i18n.js';
+/** What to do about personal changes the check found missing from the result. */
+export function missingChangesPrompt(state: CindyMakeMergeState): string {
+ const missing = state.missing;
+ if (!missing) return '';
+ return `Cindy 核对发现结果里缺少 ${missing.count} 项个人修改:${missing.commits.join('、')}${missing.count > missing.commits.length ? ' 等' : ''}。请用 git show 逐个查看它们实现的功能,在当前目录把这些功能补回到结果里(可以直接修改文件,不需要提交,Cindy 会在本轮结束后提交并重新核对),然后运行相关验证并说明结果。确实应当舍弃其中某项时,向用户说明原因,并请用户在 Cindy 设置页的同步状态里自己选择「仍然使用这个结果」;不要自行舍弃。`;
+}
+
export function upstreamMergePrompt(state: CindyMakeMergeState): string {
+ const missing = state.missing ? missingChangesPrompt(state) + '\n' : '';
if (state.feature)
return `请在当前独立工作目录解决 Cindy Make 的${state.feature.action === 'revert' ? '撤销合入' : '合入个人版'}冲突。
Cindy 已应用当前这一步的改动,冲突仅在当前目录。先检查 git status 和冲突文件;不要重新执行 merge、revert、rebase 或 reset,不要 push,也不要修改 main、cindy-personal 或其他工作目录。
本步之前的个人版本:${state.baselineCommit}。对应制作标记:${state.feature.runId}。
${state.feature.action === 'revert' ? '目标是撤销本次制作的个人功能,同时保留官方更新和其他制作的修改。不要把整个项目恢复到旧版本;遇到后续功能依赖它且无法判断取舍时询问用户。' : '保留本次制作的功能,也保留个人版已有的其他功能和官方更新。逐项理解冲突,不整批选择 ours/theirs。'}
解决后可以 git add 标记完成,不要自行提交;运行受影响的测试与类型检查,并说明结果。Cindy 会在正常结束后核验原个人目录未变化,创建本地提交;若本次撤销还有后续改动需要处理,将由 Cindy 继续应用。此任务不生成个人版。`;
+ if (state.remote && state.strategy === 'combine') {
+ const github = state.remote.commit ?? state.upstreamCommit;
+ // This computer is on the newer official version: GitHub's own changes go onto it.
+ const ontoLocal = github !== state.upstreamCommit;
+ return (
+ missing +
+ (state.rebaseReview
+ ? `注意:${ontoLocal ? 'GitHub 上' : '这台电脑'}的个人历史包含在合并提交中额外完成的修改,普通 rebase 不会自动保留它们。本目录的 rebase 可能已经完成,即使没有文本冲突,也必须对照下方${ontoLocal ? 'GitHub 上' : '这台电脑'}的个人版提交逐项核对功能,补回遗漏的处理结果并验证;不要重新开始 rebase。\n`
+ : '') +
+ `请在当前独立工作目录中合并两台电脑的 Cindy 个人版修改。目标是两边的功能都不能丢:GitHub 上的修改和这台电脑的修改都是用户自己做的,必须同时保留。
+GitHub 上的个人版(由另一台电脑上传):${github}
+这台电脑的个人版:${state.baselineCommit}
+合并结果基于的官方版本:${state.remote.base}
+Cindy 已在当前隔离目录启动 rebase,${ontoLocal ? '这台电脑已在更新的官方版本上,正把 GitHub 上独有的修改逐个放到这台电脑的版本之上' : '正把这台电脑独有的修改逐个放到 GitHub 版本之上'}。先检查 git status、当前冲突与待重放提交,并用 git log/git show 查看两边各自的提交,理解每一边想实现的功能。不要重新执行 git merge 或重新开始 rebase,不要使用 rebase --skip、reset --hard,也不要整批选择 ours/theirs——那会丢掉其中一边的功能。
+逐个冲突把两边的功能合在一起;确实无法同时保留时,向用户说明两边各自的行为并请用户决定,不要自行舍弃。
+只在当前工作目录处理冲突,可以 git add 标记解决。每次解决后继续现有 rebase:git -c user.name="Cindy Make" -c [email protected] -c core.editor=true -c commit.gpgSign=false rebase --continue。后续再次遇到冲突则逐项处理,直到 rebase 完整结束。保留提交的 Signed-off-by,禁止 push,不修改 main、cindy-personal 或其他工作目录。
+按仓库规则运行受影响测试和类型检查;如需修改非冲突代码,留在本目录由 Cindy 在完成时本地提交。最后分别说明 GitHub 一侧和这台电脑一侧保留了哪些功能、冲突如何处理、验证结果与未验证项。
+Cindy 会在本轮正常结束后核实没有未完成的 rebase/冲突、作为基础的一边已完整包含、这台电脑的个人版未被并发修改,再把 cindy-personal 更新到这份结果并上传到用户的 GitHub;这台电脑原来的个人版会留有备份。此任务不生成个人版。`
+ );
+ }
if (state.strategy === 'rebase')
return (
+ missing +
(state.rebaseReview
? '注意:原个人历史包含在合并提交中额外完成的修改,普通 rebase 不会自动保留它们。本目录的 rebase 可能已经完成,即使没有文本冲突,也必须对照下方原个人分支提交逐项核对功能,补回遗漏的合并处理结果并验证;不要重新开始 rebase。\n'
: '') +
@@ -115,7 +144,9 @@ export async function ensureUpstreamMergeSession(
? state.feature.action === 'revert'
? 'cindyMake.history.revertTaskTitle'
: 'cindyMake.history.mergeTaskTitle'
- : 'cindyMake.merge.taskTitle',
+ : state.remote
+ ? 'cindyMake.merge.combine.taskTitle'
+ : 'cindyMake.merge.taskTitle',
),
createdAt,
),
@@ -169,6 +200,43 @@ export async function ensureUpstreamMergeSession(
return id;
}
+/** One follow-up message in the resolver's own task; never a second task. */
+export async function remindUpstreamMergeSession(
+ state: CindyMakeMergeState,
+ isCurrent: () => boolean,
+): Promise<void> {
+ if (!state.sessionId || !state.missing) throw mergeError('unavailable');
+ const dbClient = getDbClient();
+ const owner = captureDataOwnerBroadcastScope();
+ const current = () =>
+ isCurrent() && isDataOwnerBroadcastScopeCurrent(owner) && getDbClient() === dbClient;
+ const [row] = await dbClient.drizzle
+ .select()
+ .from(sessions)
+ .where(eq(sessions.id, state.sessionId))
+ .limit(1);
+ if (!current()) throw mergeError('busy');
+ if (!row || row.status !== 'active' || row.source !== CINDY_MAKE_MERGE_SESSION_SOURCE)
+ throw mergeError('unavailable');
+ await dispatchCindyMakeMergeTask(
+ row.id,
+ missingChangesPrompt(state),
+ {
+ id: row.id,
+ agentKind: dbToMakerAgentKind(row.agentKind),
+ workingDir: row.workingDir,
+ model: row.model,
+ effort: row.effort,
+ providerId: row.providerId,
+ fastMode: row.fastMode,
+ permissionMode: row.permissionMode,
+ planMode: row.planModeEnabled,
+ },
+ current,
+ `cindy-make-merge-check-${state.id}`,
+ );
+}
+
export async function assertUpstreamMergeSession(
userData: string,
state: CindyMakeMergeState,
diff --git a/apps/desktop/src/main/cindy-make/versionStore.ts b/apps/desktop/src/main/cindy-make/versionStore.ts
index 1bf8617f99..c2c7076e94 100644
--- a/apps/desktop/src/main/cindy-make/versionStore.ts
+++ b/apps/desktop/src/main/cindy-make/versionStore.ts
@@ -4,10 +4,15 @@ import { createHash, randomUUID } from 'node:crypto';
import originalFs from 'original-fs';
import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
+import { createLogger } from '../logger.js';
import { createMigrationRuntimeManifest } from '../localDb/migrationRunner.js';
import { CINDY_VERSION_PROTOCOL, type CindyVersionInfo } from '../../shared/cindyVersions.js';
+import { settlePendingBuilds } from './pendingBuild.js';
+import { makeSourceRoot } from './sourcePaths.js';
import type { CindyVersionEndpointSnapshot } from './versionRuntimeIdentity.js';
+const log = createLogger('CindyMakeVersionStore');
+
export const VERSION_ID = /^[a-f0-9-]{36}$/;
export const ORIGINAL_DEV_ENV_KEYS = [
'PATH',
@@ -191,6 +196,20 @@ export function hasPublishedPersonalVersionCommit(profile: string, commit: strin
}
});
}
+/** Commits a generated personal version was published from; one of them vouches for its content. */
+export function publishedPersonalVersionCommits(profile: string): string[] {
+ const root = path.join(versionsRoot(profile), 'versions');
+ if (!fs.existsSync(root)) return [];
+ assertVersionDirectory(profile, root);
+ return fs.readdirSync(root).flatMap((id) => {
+ if (!VERSION_ID.test(id) || !fs.existsSync(path.join(root, id, 'version.json'))) return [];
+ try {
+ return [readPersonalVersionRecord(profile, id).commit];
+ } catch {
+ return [];
+ }
+ });
+}
export function migrationIdentity(directory: string): string {
return createHash('sha256')
.update(JSON.stringify(createMigrationRuntimeManifest(directory).migrations))
@@ -251,7 +270,11 @@ async function assertRuntimeLinksInside(directory: string): Promise<void> {
};
await walk(directory);
}
-export function publishPersonalVersion(profile: string, id: string): void {
+export function publishPersonalVersion(
+ profile: string,
+ id: string,
+ writeSelection: typeof writeVersionJson = writeVersionJson,
+): void {
const directory = versionDirectory(profile, id);
assertVersionDirectory(profile, directory);
const staged = readVersionJson<PersonalVersion>(path.join(directory, 'staged.json'));
@@ -259,7 +282,16 @@ export function publishPersonalVersion(profile: string, id: string): void {
writeVersionJson(path.join(directory, 'version.json'), staged);
// The slot changes only after the complete application has been saved. UUIDs are
// private immutable generations, not additional user-selectable personal versions.
- writeVersionJson(path.join(versionsRoot(profile), 'personal.json'), { id });
+ // This is the commit point: on failure the pending ledger is still untouched;
+ // after success no bookkeeping error may make build cleanup remove this version.
+ writeSelection(path.join(versionsRoot(profile), 'personal.json'), { id });
+ try {
+ settlePendingBuilds(makeSourceRoot(profile));
+ } catch {
+ // A stale/unknown ledger is conservative. The saved version independently
+ // proves its generated commit; rolling it back could instead lose that proof.
+ log.warn('Personal version published; pending-build ledger could not be settled');
+ }
try {
fs.unlinkSync(path.join(directory, 'staged.json'));
} catch {}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 9d48200132..828618340c 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4018,6 +4018,17 @@ contextBridge.exposeInMainWorld('electronAPI', {
input: import('../shared/cindyMakeMerge').CindyMakeMergeRequest,
): Promise<import('../shared/cindyMakeMerge').CindyMakeMergeState | undefined> =>
ipcRenderer.invoke('app:cindy-make-merge', input),
+ cindyMakePersonalRemote: (
+ action: import('../shared/cindyMakePersonalRemote').CindyMakePersonalRemoteAction,
+ ): Promise<import('../shared/cindyMakePersonalRemote').CindyMakePersonalRemoteState> =>
+ ipcRenderer.invoke('app:cindy-make-personal-remote', action),
+ cindyMakeContribution: (
+ request: import('../shared/cindyMakeContribution').CindyMakeContributionRequest,
+ ): Promise<unknown> => ipcRenderer.invoke('app:cindy-make-contribution', request),
+ cindyMakeSync: (
+ request: import('../shared/cindyMakeSync').CindyMakeSyncRequest,
+ ): Promise<import('../shared/cindyMakeSync').CindyMakeSyncState> =>
+ ipcRenderer.invoke('app:cindy-make-sync', request),
getCindyMakeSettings: (): Promise<import('../shared/cindyMakeSettings').CindyMakeSettings> =>
ipcRenderer.invoke('app:get-cindy-make-settings'),
setCindyMakeSyncLatestBeforeBuild: (
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeContribution.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeContribution.tsx
new file mode 100644
index 0000000000..175a6e1e8d
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeContribution.tsx
@@ -0,0 +1,401 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { FormField } from '@/components/ui/form-field';
+import { Input, Textarea } from '@/components/ui/input';
+import { Spinner } from '@/components/ui/spinner';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { toast } from '@/lib/toast';
+import { extractIpcError } from '@/utils/ipcError';
+import {
+ CINDY_MAKE_CONTRIBUTION_ERRORS,
+ CONTRIBUTION_LIMITS,
+ isContributionEmail,
+ type CindyMakeContributionDraft,
+ type CindyMakeContributionError,
+ type CindyMakeContributionView,
+} from '../../../shared/cindyMakeContribution';
+
+const key = 'cindyMake.contribution';
+
+function contributionError(error: unknown): CindyMakeContributionError {
+ const reason = extractIpcError(error)
+ ?.message?.replace(/^\[PRECONDITION_FAILED\]\s*/, '')
+ .trim();
+ return (CINDY_MAKE_CONTRIBUTION_ERRORS as readonly string[]).includes(reason ?? '')
+ ? (reason as CindyMakeContributionError)
+ : 'failed';
+}
+
+/** Pull requests already opened for history entries; states come from GitHub through Main. */
+export function useCindyMakeContributions(active: boolean) {
+ const [snapshot, setSnapshot] = useState<{
+ owner: ReturnType<typeof getDataOwnerGeneration>;
+ views: Record<string, CindyMakeContributionView>;
+ }>();
+ const request = useRef(0);
+ const refresh = useCallback(async () => {
+ const invoke = window.electronAPI.cindyMakeContribution;
+ if (!invoke) return;
+ const owner = getDataOwnerGeneration();
+ const generation = ++request.current;
+ try {
+ const views = await invoke({ action: 'status' });
+ if (generation === request.current && isDataOwnerGenerationCurrent(owner))
+ setSnapshot({ owner, views: Object.fromEntries(views.map((view) => [view.runId, view])) });
+ } catch {
+ // Without states the history still works; nothing is shown for the PR.
+ }
+ }, []);
+ useEffect(() => {
+ if (active) void refresh();
+ }, [active, refresh]);
+ const record = useCallback((view: CindyMakeContributionView) => {
+ request.current += 1;
+ const owner = getDataOwnerGeneration();
+ setSnapshot((previous) => ({
+ owner,
+ views: {
+ ...(previous && isDataOwnerGenerationCurrent(previous.owner) ? previous.views : {}),
+ [view.runId]: view,
+ },
+ }));
+ }, []);
+ const views = snapshot && isDataOwnerGenerationCurrent(snapshot.owner) ? snapshot.views : {};
+ return { views, refresh, record };
+}
+
+/** One line under the history entry: where its pull request stands. */
+export function CindyMakeContributionStatus({ view }: { view: CindyMakeContributionView }) {
+ const { t } = useTranslation();
+ return (
+ <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-12 text-[var(--text-secondary)]">
+ <span>{t(`${key}.state.${view.state ?? 'submitted'}`, { number: view.number })}</span>
+ <Button
+ variant="secondary"
+ tone="quiet"
+ size="sm"
+ compact
+ onClick={() => void window.electronAPI.openExternal(view.url)}
+ >
+ {t(`${key}.view`)}
+ </Button>
+ </p>
+ );
+}
+
+/** The action-bar label for a history entry, given its existing pull request. */
+export function contributionActionKey(view?: CindyMakeContributionView): string | undefined {
+ if (!view) return `${key}.action`;
+ if (view.state === 'merged') return undefined;
+ return view.state === 'closed' ? `${key}.resubmit` : `${key}.update`;
+}
+
+/**
+ * Reviews the prefilled pull request before anything leaves this computer. The
+ * author confirms the public title, body and DCO identity; Main validates again.
+ */
+export function CindyMakeContributionDialog({
+ runId,
+ onOpenChange,
+ onSubmitted,
+}: {
+ runId: string;
+ onOpenChange(open: boolean): void;
+ onSubmitted(view: CindyMakeContributionView): void;
+}) {
+ const { t } = useTranslation();
+ const owner = useRef(getDataOwnerGeneration());
+ const [draft, setDraft] = useState<CindyMakeContributionDraft>();
+ const [loadError, setLoadError] = useState<CindyMakeContributionError>();
+ const [title, setTitle] = useState('');
+ const [body, setBody] = useState('');
+ const [name, setName] = useState('');
+ const [email, setEmail] = useState('');
+ const [signed, setSigned] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+ const [submitError, setSubmitError] = useState<CindyMakeContributionError>();
+ const busy = useRef(false);
+ const mounted = useRef(true);
+ const returnFocusRef = useRef(
+ document.activeElement instanceof HTMLElement ? document.activeElement : null,
+ );
+
+ useEffect(() => {
+ mounted.current = true;
+ const invoke = window.electronAPI.cindyMakeContribution;
+ if (!invoke) {
+ setLoadError('failed');
+ return;
+ }
+ void invoke({ action: 'draft', runId }).then(
+ (next) => {
+ if (!mounted.current || !isDataOwnerGenerationCurrent(owner.current)) return;
+ setDraft(next);
+ setTitle(next.title);
+ setBody(next.body);
+ setName(next.name);
+ setEmail(next.email);
+ },
+ (error: unknown) => {
+ if (mounted.current) setLoadError(contributionError(error));
+ },
+ );
+ return () => {
+ mounted.current = false;
+ };
+ }, [runId]);
+
+ const titleValid =
+ !!title.trim() && title.length <= CONTRIBUTION_LIMITS.title && !/[\r\n]/.test(title);
+ const nameValid =
+ !!name.trim() && name.length <= CONTRIBUTION_LIMITS.name && !/[<>\r\n]/.test(name);
+ const emailValid = isContributionEmail(email.trim());
+ const valid = !!draft && titleValid && nameValid && emailValid && signed;
+ // An open (or unconfirmed) pull request is updated; a closed or merged one stays as it is.
+ const update =
+ !!draft?.existing && draft.existing.state !== 'closed' && draft.existing.state !== 'merged';
+
+ const submit = async () => {
+ const invoke = window.electronAPI.cindyMakeContribution;
+ if (!valid || busy.current || !invoke) return;
+ if (!isDataOwnerGenerationCurrent(owner.current)) {
+ onOpenChange(false);
+ return;
+ }
+ busy.current = true;
+ setSubmitting(true);
+ setSubmitError(undefined);
+ try {
+ const view = await invoke({
+ action: 'submit',
+ runId,
+ snapshotId: draft.snapshotId,
+ title,
+ body,
+ name,
+ email,
+ });
+ if (!isDataOwnerGenerationCurrent(owner.current)) return;
+ toast.success(t(`${key}.submitted`, { number: view.number }));
+ onSubmitted(view);
+ onOpenChange(false);
+ } catch (error) {
+ if (mounted.current && isDataOwnerGenerationCurrent(owner.current)) {
+ const reason = contributionError(error);
+ if (reason === 'changed') {
+ setSigned(false);
+ setDraft(undefined);
+ setLoadError(reason);
+ } else setSubmitError(reason);
+ }
+ } finally {
+ busy.current = false;
+ if (mounted.current) setSubmitting(false);
+ }
+ };
+
+ return (
+ <Dialog.Root open onOpenChange={(open) => !busy.current && onOpenChange(open)}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[10000] modal-scrim" />
+ <Dialog.Content
+ onPointerDownOutside={(event) => event.preventDefault()}
+ className="modal-panel fixed left-1/2 top-1/2 z-[10001] flex max-h-[85vh] w-[min(560px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 flex-col overflow-y-auto p-4 outline-none"
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ if (returnFocusRef.current?.isConnected) returnFocusRef.current.focus();
+ }}
+ onEscapeKeyDown={(event) => {
+ if (event.isComposing || event.keyCode === 229) event.preventDefault();
+ }}
+ >
+ <Dialog.Title className="text-16 font-semibold text-[var(--confirm-title)]">
+ {t(`${key}.dialog.title`)}
+ </Dialog.Title>
+ <Dialog.Description className="mt-2 text-13 leading-relaxed text-[var(--confirm-desc)]">
+ {t(`${key}.dialog.description`)}
+ </Dialog.Description>
+ {!draft && !loadError && (
+ <p
+ role="status"
+ className="mt-4 flex items-center gap-2 text-13 text-[var(--text-secondary)]"
+ >
+ <Spinner size={14} />
+ {t(`${key}.dialog.loading`)}
+ </p>
+ )}
+ {loadError && (
+ <div className="mt-4 flex flex-col gap-4">
+ <p role="alert" className="text-13 text-[var(--error-fg)]">
+ {t(`${key}.errors.${loadError}`)}
+ </p>
+ <div className="flex justify-end">
+ <Dialog.Close asChild>
+ <Button type="button" variant="secondary" size="lg" palette="confirmation">
+ {t(`${key}.dialog.close`)}
+ </Button>
+ </Dialog.Close>
+ </div>
+ </div>
+ )}
+ {draft && (
+ <form
+ className="mt-4 flex flex-col gap-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ {draft.existing && (
+ <p className="text-13 text-[var(--confirm-desc)]">
+ {t(`${key}.dialog.${update ? 'existing' : 'reopen'}`, {
+ number: draft.existing.number,
+ })}
+ </p>
+ )}
+ <FormField
+ label={t(`${key}.dialog.prTitle`)}
+ hint={t(`${key}.dialog.prTitleHint`)}
+ error={title && !titleValid ? t(`${key}.errors.invalid`) : undefined}
+ required
+ >
+ {(control) => (
+ <Input
+ {...control}
+ value={title}
+ onChange={setTitle}
+ maxLength={CONTRIBUTION_LIMITS.title}
+ disabled={submitting}
+ />
+ )}
+ </FormField>
+ <FormField label={t(`${key}.dialog.body`)} hint={t(`${key}.dialog.bodyHint`)}>
+ {(control) => (
+ <Textarea
+ {...control}
+ value={body}
+ onChange={setBody}
+ rows={10}
+ maxLength={CONTRIBUTION_LIMITS.body}
+ disabled={submitting}
+ className="min-h-[180px] resize-y font-mono text-12"
+ />
+ )}
+ </FormField>
+ <fieldset className="flex flex-col gap-2">
+ <legend className="text-13 font-medium text-[var(--text-primary)]">
+ {t(`${key}.dialog.author`)}
+ </legend>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <FormField
+ label={t(`${key}.dialog.name`)}
+ error={!nameValid ? t(`${key}.dialog.nameRequired`) : undefined}
+ required
+ >
+ {(control) => (
+ <Input
+ {...control}
+ value={name}
+ onChange={(value) => {
+ setName(value);
+ // The sign-off was confirmed for the previous identity.
+ setSigned(false);
+ }}
+ maxLength={CONTRIBUTION_LIMITS.name}
+ disabled={submitting}
+ autoComplete="name"
+ />
+ )}
+ </FormField>
+ <FormField
+ label={t(`${key}.dialog.email`)}
+ error={!emailValid ? t(`${key}.dialog.emailRequired`) : undefined}
+ required
+ >
+ {(control) => (
+ <Input
+ {...control}
+ type="email"
+ value={email}
+ onChange={(value) => {
+ setEmail(value);
+ setSigned(false);
+ }}
+ maxLength={CONTRIBUTION_LIMITS.email}
+ disabled={submitting}
+ autoComplete="email"
+ />
+ )}
+ </FormField>
+ </div>
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t(`${key}.dialog.authorHint`)}
+ </p>
+ </fieldset>
+ <details className="text-12 text-[var(--text-secondary)]">
+ <summary className="min-h-8 cursor-pointer py-2">
+ {t(`${key}.dialog.files`, { count: draft.files.length })}
+ </summary>
+ <ul className="mt-1 max-h-40 space-y-1 overflow-y-auto font-mono">
+ {draft.files.map((file) => (
+ <li key={file} className="break-all">
+ {file}
+ </li>
+ ))}
+ </ul>
+ </details>
+ <ul className="list-disc space-y-1 pl-5 text-12 text-[var(--text-secondary)]">
+ <li>{t(`${key}.dialog.onlyThis`)}</li>
+ <li>{t(`${key}.dialog.public`, { repository: draft.repository })}</li>
+ {draft.touchesUi && <li>{t(`${key}.dialog.uiNote`)}</li>}
+ </ul>
+ <label className="flex min-h-8 cursor-pointer items-start gap-2 text-13 text-[var(--text-primary)]">
+ <input
+ type="checkbox"
+ checked={signed}
+ disabled={submitting}
+ onChange={(event) => setSigned(event.target.checked)}
+ className="mt-0.5 size-4 shrink-0 accent-[var(--confirm-btn-primary-bg)]"
+ />
+ <span>{t(`${key}.dialog.dco`, { name: name.trim(), email: email.trim() })}</span>
+ </label>
+ {submitError && (
+ <p role="alert" className="text-13 text-[var(--error-fg)]">
+ {t(`${key}.errors.${submitError}`)}
+ </p>
+ )}
+ <div className="flex flex-wrap justify-end gap-2">
+ <Dialog.Close asChild>
+ <Button
+ type="button"
+ variant="secondary"
+ size="lg"
+ disabled={submitting}
+ palette="confirmation"
+ >
+ {t(`${key}.dialog.cancel`)}
+ </Button>
+ </Dialog.Close>
+ <Button
+ type="submit"
+ size="lg"
+ disabled={!valid}
+ loading={submitting}
+ palette="confirmation"
+ >
+ {t(`${key}.dialog.${update ? 'update' : 'submit'}`)}
+ </Button>
+ </div>
+ </form>
+ )}
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx
index 0071254fad..c35291e533 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeHistoryPanel.tsx
@@ -28,16 +28,25 @@ import { CindyMakeBuildProgress } from './CindyMakeBuildProgress';
import { CindyMakeBuildFailure } from './CindyMakeBuildFailure';
import { cindyMakeBuildStatusKey } from './cindyMakeBuildStatus';
import { useCindyMakeBuildStop } from './useCindyMakeBuildStop';
+import {
+ CindyMakeContributionDialog,
+ CindyMakeContributionStatus,
+ contributionActionKey,
+ useCindyMakeContributions,
+} from './CindyMakeContribution';
type Filter = 'all' | 'pending' | 'integrated' | 'ended';
/** Historical facts and allowed actions come from Main; an old button cannot authorize a write. */
export function CindyMakeHistoryPanel({
active = true,
hasPersonalVersion = false,
+ canGenerate = hasPersonalVersion,
onState,
}: {
active?: boolean;
hasPersonalVersion?: boolean;
+ /** Generating is offered for a first personal version too once there is something to use. */
+ canGenerate?: boolean;
onState?: (state: CindyMakeHistoryState) => void;
}) {
const { t, i18n } = useTranslation();
@@ -63,6 +72,8 @@ export function CindyMakeHistoryPanel({
// A failed build is persisted so it can still be retried, but an old failure
// should not reappear as a fresh red banner every time this panel is opened.
const [showBuildFailure, setShowBuildFailure] = useState(false);
+ const [contributing, setContributing] = useState<string>();
+ const contributions = useCindyMakeContributions(active);
const request = useRef(0);
const acting = useRef(false);
const actionGeneration = useRef(0);
@@ -179,7 +190,7 @@ export function CindyMakeHistoryPanel({
? filter === 'all' || item.lifecycle === 'ended'
: filter === 'integrated'
? item.integration === 'integrated'
- : ['unintegrated', 'changed', 'reverted'].includes(item.integration) &&
+ : ['unintegrated', 'changed'].includes(item.integration) &&
item.lifecycle !== 'ended'),
);
const selected = visible.find((item) => item.runId === selectedId) ?? visible[0];
@@ -242,6 +253,20 @@ export function CindyMakeHistoryPanel({
)
: [];
if (selected?.canHide && !selectedActions.includes('retry-cleanup')) selectedActions.push('hide');
+ // A finished change can go to the official repository; Main checks it again on draft.
+ const contributedRound = selected?.completions.findLast(
+ (completion) => completion.tree && completion.baseTree,
+ );
+ const selectedContribution = selected && contributions.views[selected.runId];
+ const contributionKey =
+ selected &&
+ contributedRound &&
+ contributedRound.tree !== contributedRound.baseTree &&
+ !selected.operation &&
+ !['preparing', 'running'].includes(selected.lifecycle) &&
+ !['reverted', 'unchanged'].includes(selected.integration)
+ ? contributionActionKey(selectedContribution)
+ : undefined;
useEffect(() => {
const nextId = selected?.runId ?? '';
if (nextId !== selectedId) select(nextId);
@@ -408,7 +433,7 @@ export function CindyMakeHistoryPanel({
const rebuildPersonal = async () => {
if (
acting.current ||
- !hasPersonalVersion ||
+ !canGenerate ||
!state?.canBuild ||
building ||
!isDataOwnerGenerationCurrent(owner)
@@ -536,14 +561,18 @@ export function CindyMakeHistoryPanel({
{t('cindyMake.history.title')} ·{' '}
{t('cindyMake.history.taskCount', { count: items.length })}
</h3>
- {hasPersonalVersion && (
+ {canGenerate && (
<Button
variant="secondary"
disabled={!!pending || failed || !state?.canBuild || building}
loading={pending === 'rebuild-personal'}
onClick={() => void rebuildPersonal()}
>
- {t('cindyMake.history.regeneratePersonal')}
+ {t(
+ hasPersonalVersion
+ ? 'cindyMake.history.regeneratePersonal'
+ : 'cindyMake.history.generatePersonal',
+ )}
</Button>
)}
</div>
@@ -554,7 +583,7 @@ export function CindyMakeHistoryPanel({
total: items.length,
pending: items.filter(
(item) =>
- ['unintegrated', 'changed', 'reverted'].includes(item.integration) &&
+ ['unintegrated', 'changed'].includes(item.integration) &&
item.lifecycle !== 'ended',
).length,
integrated: items.filter((item) => item.integration === 'integrated').length,
@@ -811,6 +840,7 @@ export function CindyMakeHistoryPanel({
: statusKey(selected)),
)}
</p>
+ {selectedContribution && <CindyMakeContributionStatus view={selectedContribution} />}
<CindyMakeTestStep test={selected.test} />
{!selectedIsGlobalFailure && (
<>
@@ -874,10 +904,26 @@ export function CindyMakeHistoryPanel({
)}
</Button>
))}
+ {contributionKey && (
+ <Button
+ variant="secondary"
+ disabled={!!pending || failed}
+ onClick={() => setContributing(selected.runId)}
+ >
+ {t(contributionKey)}
+ </Button>
+ )}
</div>
</div>
)}
</div>
+ {contributing && (
+ <CindyMakeContributionDialog
+ runId={contributing}
+ onOpenChange={(open) => !open && setContributing(undefined)}
+ onSubmitted={contributions.record}
+ />
+ )}
</section>
);
}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeMergeNotice.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeMergeNotice.tsx
deleted file mode 100644
index bf88a8fa21..0000000000
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeMergeNotice.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import type { ReactNode } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Button } from '@/components/ui/button';
-import { Tip } from '@/components/ui/tooltip';
-import { Spinner } from '@/components/ui/spinner';
-import { useCindyMakeMergeResolution } from './useCindyMakeMergeResolution';
-import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
-import { CindyMakeMergeTaskLink } from './CindyMakeMergeTaskLink';
-
-function ResolveMergeButton({
- state,
- disabled,
-}: {
- state: CindyMakeMergeState;
- disabled?: boolean;
-}) {
- const { t } = useTranslation();
- const { resolveMerge, busy } = useCindyMakeMergeResolution();
- const cancelling = state.cancellationRequested || state.error === 'cancelFailed';
- return (
- <Tip
- text={t(cancelling ? 'cindyMake.merge.errors.cancelFailed' : 'cindyMake.merge.resolveHint')}
- >
- <Button
- variant="secondary"
- disabled={busy || disabled}
- onClick={() => void resolveMerge(state)}
- >
- {busy && <Spinner size={14} />}
- {t(cancelling ? 'cindyMake.merge.retryCancel' : 'cindyMake.merge.resolve')}
- </Button>
- </Tip>
- );
-}
-
-/** Source updates keep recovery in the same action slot as their normal update button. */
-export function CindyMakeMergeActions({
- state,
- busy,
- children,
-}: {
- state?: CindyMakeMergeState;
- busy?: boolean;
- children?: ReactNode;
-}) {
- if (!state || state.ownedByAnotherAccount) return children;
- const active = ['fetching', 'merging', 'checking'].includes(state.status);
- const canResolve =
- (!state.sessionId || (state.status === 'failed' && state.error !== 'interrupted')) &&
- !active &&
- (state.hasWorkspace || state.cancellationRequested || state.error === 'cancelFailed') &&
- state.status !== 'merged' &&
- state.status !== 'cancelled';
- if (!state.sessionId && !canResolve) return children;
- return (
- <>
- {state.sessionId && <CindyMakeMergeTaskLink sessionId={state.sessionId} />}
- {canResolve && <ResolveMergeButton state={state} disabled={busy} />}
- </>
- );
-}
-
-export function CindyMakeMergeNotice({
- state,
- busy,
- showActions = true,
-}: {
- state: CindyMakeMergeState;
- busy?: boolean;
- showActions?: boolean;
-}) {
- const { t } = useTranslation();
- const active = ['fetching', 'merging', 'checking'].includes(state.status);
- return (
- <div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--border-default)] px-4 py-3 text-12">
- <div className="min-w-0 flex-1 space-y-1 text-[var(--text-secondary)]" role="status">
- <p className="flex items-center gap-2">
- {active && <Spinner size={14} />}
- {t(`cindyMake.merge.status.${state.status}`)}
- </p>
- {state.error && (
- <p className="text-[var(--error-fg)]">{t(`cindyMake.merge.errors.${state.error}`)}</p>
- )}
- {state.ownedByAnotherAccount && <p>{t('cindyMake.merge.otherAccount')}</p>}
- </div>
- {showActions && <CindyMakeMergeActions state={state} busy={busy} />}
- </div>
- );
-}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakePersonalRemote.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakePersonalRemote.tsx
new file mode 100644
index 0000000000..23b3e74f1e
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakePersonalRemote.tsx
@@ -0,0 +1,365 @@
+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
+import { CircleCheck } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { Spinner } from '@/components/ui/spinner';
+import { GithubSetupDialog } from '@/features/cc-agent/GithubSetupDialog';
+import { useCindyMakeState } from '@/lib/cindyMakeState';
+import { toast } from '@/lib/toast';
+import {
+ isGithubRepository,
+ type CindyMakePersonalRemoteAction,
+ type CindyMakePersonalRemoteState,
+} from '../../../shared/cindyMakePersonalRemote';
+
+const key = 'cindyMake.storage';
+
+/**
+ * Main-owned GitHub binding of the personal version. Settings reads it on entry
+ * and after GitHub connects; progress of background work arrives by broadcast.
+ */
+export function useCindyMakePersonalRemote() {
+ const { t } = useTranslation();
+ const state = useCindyMakeState().personalRemote;
+ const [pending, setPending] = useState<CindyMakePersonalRemoteAction>();
+ const act = useCallback(
+ async (action: CindyMakePersonalRemoteAction) => {
+ const invoke = window.electronAPI.cindyMakePersonalRemote;
+ if (!invoke) return;
+ setPending(action);
+ try {
+ await invoke(action);
+ } catch {
+ if (action !== 'refresh') toast.error(t(`${key}.actionFailed`));
+ } finally {
+ setPending(undefined);
+ }
+ },
+ [t],
+ );
+ useEffect(() => {
+ void act('refresh');
+ return window.electronAPI.gitContext?.onGithubConnected?.(() => void act('refresh'));
+ }, [act]);
+ return { state, act, pending };
+}
+
+/**
+ * Consent to create or reuse the user's public fork. It stays until a repository
+ * is bound or the user explicitly keeps the personal version on this computer.
+ */
+export function CindyMakeStorageCard({
+ state,
+ pending,
+ preparing = false,
+ onSave,
+ onKeepLocal,
+}: {
+ state: CindyMakePersonalRemoteState;
+ pending?: CindyMakePersonalRemoteAction;
+ /** The personal source is being prepared before saving. */
+ preparing?: boolean;
+ onSave(): void;
+ onKeepLocal(): void;
+}) {
+ const { t } = useTranslation();
+ const login = state.githubLogin ?? '';
+ const existing = isGithubRepository(state.existingPersonal) ? state.existingPersonal : undefined;
+ return (
+ <section
+ aria-labelledby="cindy-make-storage-card-title"
+ className="rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] p-5"
+ >
+ <h3
+ id="cindy-make-storage-card-title"
+ className="text-14 font-medium text-[var(--text-primary)]"
+ >
+ {t(`${key}.card.${existing ? 'existingTitle' : 'title'}`)}
+ </h3>
+ <p className="mt-2 text-13 leading-[1.5] text-[var(--text-secondary)]">
+ {existing
+ ? t(`${key}.card.existingIntro`, { login, repository: existing })
+ : t(`${key}.card.intro`, { login })}
+ </p>
+ {!existing && (
+ <ul className="mt-1 list-disc space-y-0.5 pl-5 text-13 leading-[1.5] text-[var(--text-secondary)]">
+ <li>{t(`${key}.card.otherComputers`)}</li>
+ <li>{t(`${key}.card.contribute`)}</li>
+ <li>{t(`${key}.card.autoSync`)}</li>
+ </ul>
+ )}
+ <div className="mt-3 space-y-1 rounded-lg bg-[var(--surface-hover)] px-3 py-2.5 text-12 leading-[1.5] text-[var(--text-secondary)]">
+ <p>
+ <strong className="font-medium text-[var(--text-primary)]">
+ {t(`${key}.card.public`, { repository: existing ?? `${login}/cindy` })}
+ </strong>
+ </p>
+ <p>{t(`${key}.card.${existing ? 'existingKeeps' : 'unchanged'}`)}</p>
+ {state.sourceReady === false && <p>{t(`${key}.card.prepareFirst`)}</p>}
+ </div>
+ {state.error && (
+ <p role="status" className="mt-3 text-12 leading-[1.5] text-[var(--error-fg)]">
+ {t(`${key}.errors.${state.error}`)}
+ </p>
+ )}
+ <div className="mt-4 flex flex-wrap gap-2">
+ <Button
+ variant="cta"
+ loading={pending === 'save' || preparing}
+ disabled={!!pending || preparing}
+ onClick={onSave}
+ >
+ {t(`${key}.actions.${existing ? 'useExisting' : 'save'}`)}
+ </Button>
+ <Button
+ variant="secondary"
+ loading={pending === 'keep-local'}
+ disabled={!!pending || preparing}
+ onClick={onKeepLocal}
+ >
+ {t(`${key}.actions.${existing ? 'keepSeparate' : 'keepLocal'}`)}
+ </Button>
+ </div>
+ </section>
+ );
+}
+
+/** "保存位置" row inside the version overview. */
+export function CindyMakeStorageRow({
+ state,
+ pending,
+ act,
+ onOffer,
+}: {
+ state?: CindyMakePersonalRemoteState;
+ pending?: CindyMakePersonalRemoteAction;
+ act(action: CindyMakePersonalRemoteAction): Promise<void>;
+ /** Show the consent card again for a user who previously postponed or declined. */
+ onOffer(): void;
+}) {
+ const { t } = useTranslation();
+ const { confirm } = useConfirmDialog();
+ const [connectOpen, setConnectOpen] = useState(false);
+ const confirming = useRef(false);
+ if (!state) return null;
+ const repository = isGithubRepository(state.repository) ? state.repository : undefined;
+ const connected = state.github === 'connected';
+ const busy = !!pending || !!state.running;
+ const stop = async () => {
+ if (confirming.current || busy) return;
+ confirming.current = true;
+ try {
+ const confirmed = await confirm({
+ title: t(`${key}.stopConfirm.title`),
+ description: t(`${key}.stopConfirm.description`),
+ confirmText: t(`${key}.stopConfirm.confirm`),
+ cancelText: t(`${key}.stopConfirm.cancel`),
+ });
+ if (confirmed) await act('disconnect');
+ } finally {
+ confirming.current = false;
+ }
+ };
+
+ let value: string;
+ let status: ReactNode = null;
+ let description: string | undefined;
+ let descriptionTone = 'text-[var(--text-secondary)]';
+ const actions: ReactNode[] = [];
+ const connectButton = (label: 'connect' | 'reconnect') => (
+ <Button
+ key="connect"
+ variant="secondary"
+ size="sm"
+ compact
+ onClick={() => setConnectOpen(true)}
+ >
+ {t(`${key}.actions.${label}`)}
+ </Button>
+ );
+
+ if (state.running) {
+ value = t(`${key}.running.${state.running}`);
+ status = (
+ <span className="inline-flex items-center gap-1.5 text-12 font-normal text-[var(--text-secondary)]">
+ <Spinner size={12} />
+ {state.step ? t(`${key}.step.${state.step}`) : null}
+ </span>
+ );
+ } else if (repository) {
+ value = t(`${key}.github`, { repository });
+ if (state.error === 'account') {
+ description = t(`${key}.status.account`, { login: state.githubLogin ?? '' });
+ descriptionTone = 'text-[var(--upgrade-banner-fg)]';
+ } else if (state.error) {
+ description = t(`${key}.errors.${state.error}`);
+ descriptionTone = 'text-[var(--error-fg)]';
+ } else if (state.sync === 'synced') {
+ status = (
+ <span className="inline-flex items-center gap-1 text-12 font-normal text-[var(--status-success)]">
+ <CircleCheck size={13} aria-hidden />
+ {t(`${key}.status.synced`)}
+ </span>
+ );
+ } else if (state.sync) {
+ status = (
+ <span className="text-12 font-normal text-[var(--text-secondary)]">
+ {t(`${key}.status.${state.sync}`)}
+ </span>
+ );
+ }
+ // Both sides changed: Sync combines them; its progress and conflicts show under the summary.
+ if (state.sync === 'needsMerge' && !state.error) description = t(`${key}.needsMergeHint`);
+ else if (state.sync === 'buildFirst' && !state.error) description = t(`${key}.buildFirstHint`);
+ if (!connected && state.error !== 'account')
+ description = t(
+ `${key}.${state.github === 'missing' ? 'disconnectedHint' : 'unavailableHint'}`,
+ );
+ if (state.github === 'unavailable')
+ actions.push(
+ <Button
+ key="recheck"
+ variant="secondary"
+ size="sm"
+ compact
+ loading={pending === 'refresh'}
+ disabled={busy}
+ onClick={() => void act('refresh')}
+ >
+ {t(`${key}.actions.recheck`)}
+ </Button>,
+ );
+ else if (!connected) actions.push(connectButton('connect'));
+ // A revoked or narrow authorization is fixed by reconnecting; Sync then retries the upload.
+ else if (state.error === 'github' || state.error === 'workflowScope' || state.error === 'account')
+ actions.push(connectButton('reconnect'));
+ // The repository is gone: stop syncing with it and save to a new one, with consent again.
+ else if (state.error === 'forkMissing')
+ actions.push(
+ <Button
+ key="save-again"
+ variant="secondary"
+ size="sm"
+ compact
+ loading={pending === 'disconnect'}
+ disabled={busy}
+ onClick={() =>
+ void act('disconnect').then(() => {
+ onOffer();
+ })
+ }
+ >
+ {t(`${key}.actions.saveAgain`)}
+ </Button>,
+ );
+ actions.push(
+ <Button
+ key="view"
+ variant="secondary"
+ tone="quiet"
+ size="sm"
+ compact
+ onClick={() =>
+ void window.electronAPI.openExternal(
+ `https://github.com/${repository}/tree/cindy-personal`,
+ )
+ }
+ >
+ {t(`${key}.actions.view`)}
+ </Button>,
+ <Button
+ key="stop"
+ variant="secondary"
+ tone="quiet"
+ size="sm"
+ compact
+ loading={pending === 'disconnect'}
+ disabled={busy}
+ onClick={() => void stop()}
+ >
+ {t(`${key}.actions.stop`)}
+ </Button>,
+ );
+ } else {
+ value = t(`${key}.localOnly`);
+ if (state.error) {
+ description = t(`${key}.errors.${state.error}`);
+ descriptionTone = 'text-[var(--error-fg)]';
+ } else
+ description = t(
+ `${key}.${
+ state.github === 'unavailable'
+ ? 'unavailableHint'
+ : connected && state.choice === 'local'
+ ? 'localChosenHint'
+ : 'localOnlyHint'
+ }`,
+ );
+ if (state.github === 'missing') actions.push(connectButton('connect'));
+ else if (state.github === 'unavailable')
+ actions.push(
+ <Button
+ key="recheck"
+ variant="secondary"
+ size="sm"
+ compact
+ loading={pending === 'refresh'}
+ disabled={busy}
+ onClick={() => void act('refresh')}
+ >
+ {t(`${key}.actions.recheck`)}
+ </Button>,
+ );
+ else {
+ if (state.error === 'github' || state.error === 'workflowScope')
+ actions.push(connectButton('reconnect'));
+ // A retry asks again: the connected login may differ from the one the user agreed to.
+ if (!state.offerMigration)
+ actions.push(
+ <Button
+ key="save"
+ variant="secondary"
+ size="sm"
+ compact
+ disabled={busy}
+ onClick={onOffer}
+ >
+ {t(`${key}.actions.${state.error ? 'retry' : 'save'}`)}
+ </Button>,
+ );
+ }
+ }
+
+ return (
+ <section
+ aria-label={t(`${key}.title`)}
+ className="border-t border-[var(--border-default)] px-4 py-3"
+ >
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <span className="w-[72px] shrink-0 text-12 text-[var(--text-secondary)]">
+ {t(`${key}.title`)}
+ </span>
+ <div className="min-w-0 flex-[1_1_240px]" role="status">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-13 font-medium text-[var(--text-primary)]">
+ <span className="min-w-0 break-all">{value}</span>
+ {status}
+ </div>
+ {description && (
+ <p className={`mt-0.5 text-12 leading-[1.45] ${descriptionTone}`}>{description}</p>
+ )}
+ </div>
+ {actions.length > 0 && (
+ <div className="ml-auto flex shrink-0 flex-wrap justify-end gap-1.5">{actions}</div>
+ )}
+ </div>
+ {connectOpen && (
+ <GithubSetupDialog
+ onClose={() => setConnectOpen(false)}
+ onConnected={() => void act('refresh')}
+ />
+ )}
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakePreflightDialog.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakePreflightDialog.tsx
index c32759e037..2e20fdef65 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakePreflightDialog.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakePreflightDialog.tsx
@@ -23,6 +23,12 @@ export interface CindyMakePreflightProps {
onOpenChange: (open: boolean) => void;
}
+/**
+ * Continue is offered once the official lookup finished, also when it failed: not
+ * knowing whether a similar official change exists never blocks making one.
+ */
+const LOOKUP_FINISHED = ['found', 'notFound', 'failed'];
+
/** Checks belong to this dialog; only Continue creates a persistent task. */
export function CindyMakePreflightDialog({
request,
@@ -87,7 +93,7 @@ export function CindyMakePreflightDialog({
submitting.current ||
confirmClose ||
report?.status !== 'completed' ||
- !['found', 'notFound'].includes(report.upstream?.status ?? '')
+ !LOOKUP_FINISHED.includes(report.upstream?.status ?? '')
)
return;
submitting.current = true;
@@ -141,8 +147,7 @@ export function CindyMakePreflightDialog({
: report?.source?.status === 'preparing'
? 'source'
: 'environment'
- : report.status === 'completed' &&
- ['found', 'notFound'].includes(report.upstream?.status ?? '')
+ : report.status === 'completed' && LOOKUP_FINISHED.includes(report.upstream?.status ?? '')
? 'ready'
: 'incomplete';
@@ -219,8 +224,13 @@ export function CindyMakePreflightDialog({
)}
</div>
{report?.status === 'completed' &&
- ['found', 'notFound'].includes(report.upstream?.status ?? '') && (
- <div className="flex shrink-0 flex-wrap justify-end gap-2">
+ LOOKUP_FINISHED.includes(report.upstream?.status ?? '') && (
+ <div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
+ {report.upstream?.status === 'failed' && (
+ <p className="mr-auto text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.upstream.failedContinue')}
+ </p>
+ )}
<Button
variant="primary"
className="border-[var(--border-default)] enabled:hover:border-[var(--button-primary-hover)] enabled:active:border-[var(--button-primary-pressed)]"
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeSourceDetails.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeSourceDetails.tsx
index c0badc4431..4bf8118a2d 100644
--- a/apps/desktop/src/renderer/components/cindy-make/CindyMakeSourceDetails.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeSourceDetails.tsx
@@ -6,18 +6,14 @@ import type {
MakeSourcePreparation,
} from '../../../shared/cindyMakeDoctor';
-export function CindyMakeSourceDetails({
- source,
- latestVersion,
- showComparison = true,
-}: {
- source: MakeSourcePreparation;
- latestVersion?: MakeSourceLatestVersion;
- /** Progress and errors may occupy the status area while version facts remain visible. */
- showComparison?: boolean;
-}) {
- const { t } = useTranslation();
- const unknown = t('cindyMake.source.details.unknown');
+/**
+ * Verified relationship between the personal source, local main and the online target.
+ * Shared by the plain-language summary and the technical comparison so both always agree.
+ */
+export function compareCindyMakeSource(
+ source: MakeSourcePreparation,
+ latestVersion?: MakeSourceLatestVersion,
+) {
const { personalAhead: ahead, personalBehind: behind } = source;
const comparison =
!source.commit || !source.mainCommit
@@ -33,7 +29,6 @@ export function CindyMakeSourceDetails({
: 'diverged';
const latestChannel = latestVersion?.channel ?? source.channel;
const latestLabel = latestChannel ?? (source.ref === 'main' ? 'dev' : 'unknown');
- const onlineLabel = t('cindyMake.source.details.latest.' + latestLabel);
const mainMatchesOnline =
latestVersion?.status === 'ready' && source.mainCommit === latestVersion.commit;
const personalIncludesMain = comparison === 'same' || comparison === 'personalAhead';
@@ -62,11 +57,51 @@ export function CindyMakeSourceDetails({
(comparison === 'same' ||
(ahead !== undefined && ahead < latestVersion.behind) ||
(latestVersion.ahead === 0 && behind !== undefined && behind > 0)));
- const personalStatus = personalIsLatest
+ const personalStatus: 'upToDate' | 'updateAvailable' | 'unverified' = personalIsLatest
? 'upToDate'
: personalNeedsUpdate
? 'updateAvailable'
: 'unverified';
+ return {
+ ahead,
+ behind,
+ comparison,
+ latestLabel,
+ mainMatchesOnline,
+ personalMatchesOnline,
+ personalIsLatest,
+ personalNeedsUpdate,
+ personalStatus,
+ };
+}
+
+export function CindyMakeSourceDetails({
+ source,
+ latestVersion,
+ showComparison = true,
+ announce = true,
+}: {
+ source: MakeSourcePreparation;
+ latestVersion?: MakeSourceLatestVersion;
+ /** Progress and errors may occupy the status area while version facts remain visible. */
+ showComparison?: boolean;
+ /** Off when a plain-language summary elsewhere already announces the same status. */
+ announce?: boolean;
+}) {
+ const { t } = useTranslation();
+ const unknown = t('cindyMake.source.details.unknown');
+ const {
+ ahead,
+ behind,
+ comparison,
+ latestLabel,
+ mainMatchesOnline,
+ personalMatchesOnline,
+ personalIsLatest,
+ personalNeedsUpdate,
+ personalStatus,
+ } = compareCindyMakeSource(source, latestVersion);
+ const onlineLabel = t('cindyMake.source.details.latest.' + latestLabel);
const PersonalStatusIcon = personalIsLatest
? CircleCheck
: personalNeedsUpdate
@@ -163,8 +198,10 @@ export function CindyMakeSourceDetails({
<dt>
<Tip text={showComparison ? personalStatusDescription : undefined}>
<span
- role={showComparison ? 'status' : undefined}
- aria-label={showComparison ? `${personalName} · ${personalStatusLabel}` : undefined}
+ role={showComparison && announce ? 'status' : undefined}
+ aria-label={
+ showComparison && announce ? `${personalName} · ${personalStatusLabel}` : undefined
+ }
tabIndex={showComparison ? 0 : undefined}
className={`inline-flex max-w-full items-center gap-1.5 rounded-full font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] ${
!showComparison
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeSync.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeSync.tsx
new file mode 100644
index 0000000000..c5feaa4138
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeSync.tsx
@@ -0,0 +1,199 @@
+import { useTranslation } from 'react-i18next';
+import { CircleCheck } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+import { getDraft, getFastModeForModel } from '@/state/newMakerDraft';
+import { isSelectableVendor } from '@/lib/agentVendors';
+import type { CindyMakeTaskOptions } from '../../../shared/cindyMakeDoctor';
+import type { CindyMakeSyncState, CindyMakeSyncWaiting } from '../../../shared/cindyMakeSync';
+import { CindyMakeMergeTaskLink } from './CindyMakeMergeTaskLink';
+
+const key = 'cindyMake.sync';
+
+/** A conflict task opened by Sync uses the same Agent preferences as a new Cindy Make task. */
+export function cindyMakeSyncTaskOptions(): CindyMakeTaskOptions {
+ const draft = getDraft();
+ const vendor = isSelectableVendor(draft.vendor) ? draft.vendor : 'cc';
+ const prefs = draft.lastByVendor[vendor];
+ return {
+ agentKind: vendor,
+ model: prefs.model,
+ effort: prefs.effort,
+ providerId: prefs.providerId,
+ permissionMode: prefs.permissionMode,
+ fastMode: getFastModeForModel(prefs.model),
+ planModeEnabled: false,
+ };
+}
+
+/** What the user reads while Sync waits, from the operation's reason. */
+function waitingText(waiting: CindyMakeSyncWaiting): string {
+ if (waiting.abandoning) return `${key}.waiting.abandoning`;
+ if (waiting.reason === 'working') return `${key}.waiting.working.${waiting.kind}`;
+ if (waiting.reason === 'interrupted')
+ return `${key}.waiting.interrupted.${waiting.sessionId ? 'task' : 'start'}`;
+ return `${key}.waiting.${waiting.reason}`;
+}
+
+/**
+ * One line under the version summary: what Sync is doing, what it waits for, or
+ * how it ended, with the at most few actions that belong to it. Polite live text;
+ * the summary keeps the single status region.
+ */
+export function CindyMakeSyncStatus({
+ state,
+ onAbandon,
+ abandoning = false,
+ onAccept,
+ accepting = false,
+ needsGenerate = false,
+ onGenerate,
+ generating = false,
+ onKeep,
+ keeping,
+ onResume,
+ resuming = false,
+}: {
+ state?: CindyMakeSyncState;
+ /** Give up the operation Sync waits for (asks first). */
+ onAbandon?: () => void;
+ abandoning?: boolean;
+ /** Use a result that lost changes (asks first). */
+ onAccept?: () => void;
+ accepting?: boolean;
+ /** The personal version changed since it was last generated. */
+ needsGenerate?: boolean;
+ onGenerate?: () => void;
+ generating?: boolean;
+ /** Keep one side when the two personal versions cannot be combined (asks first). */
+ onKeep?: (side: 'github' | 'local') => void;
+ keeping?: 'github' | 'local';
+ /** Open a task for an operation whose task is not there (the same as Sync). */
+ onResume?: () => void;
+ resuming?: boolean;
+}) {
+ const { t } = useTranslation();
+ if (state?.running && state.step)
+ return (
+ <p
+ aria-live="polite"
+ className="flex items-center gap-2 text-12 text-[var(--text-secondary)]"
+ >
+ <Spinner size={12} />
+ {t(`${key}.step.${state.step}`)}
+ </p>
+ );
+ const waiting = state?.waiting;
+ if (waiting)
+ return (
+ <div className="space-y-2">
+ <p
+ aria-live="polite"
+ className={`flex items-center gap-2 text-12 ${
+ ['working', 'input'].includes(waiting.reason) || waiting.abandoning
+ ? 'text-[var(--text-secondary)]'
+ : 'text-[var(--upgrade-banner-fg)]'
+ }`}
+ >
+ {(waiting.abandoning || waiting.reason === 'working') && <Spinner size={12} />}
+ {t(waitingText(waiting), { count: waiting.missing ?? 0 })}
+ </p>
+ {!waiting.abandoning && waiting.reason !== 'otherAccount' && (
+ <div className="flex flex-wrap items-center gap-2">
+ {waiting.reason === 'paused' && onResume && (
+ <Button variant="secondary" size="md" loading={resuming} onClick={onResume}>
+ {t(`${key}.resume`)}
+ </Button>
+ )}
+ {waiting.sessionId && waiting.reason !== 'paused' && (
+ <CindyMakeMergeTaskLink sessionId={waiting.sessionId} />
+ )}
+ {waiting.reason === 'missing' && onAccept && (
+ <Button variant="secondary" size="md" loading={accepting} onClick={onAccept}>
+ {t(`${key}.accept.action`)}
+ </Button>
+ )}
+ {onAbandon && (
+ <Button
+ variant="secondary"
+ tone="quiet"
+ size="md"
+ loading={abandoning}
+ onClick={onAbandon}
+ >
+ {t(`${key}.abandon.action`)}
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ const done = state?.done;
+ const error = state?.error;
+ const generate = needsGenerate && onGenerate && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <p className="text-[var(--text-secondary)]">{t(`${key}.needsGenerate`)}</p>
+ <Button variant="secondary" size="md" loading={generating} onClick={onGenerate}>
+ {t('cindyMake.history.generatePersonal')}
+ </Button>
+ </div>
+ );
+ if (!done && !error)
+ return generate ? (
+ <div aria-live="polite" className="text-12">
+ {generate}
+ </div>
+ ) : null;
+ return (
+ <div aria-live="polite" className="space-y-1 text-12">
+ {/* A GitHub problem after a completed local update keeps the result visible above it. */}
+ {done && !done.generateFirst && (
+ <p className="flex items-center gap-1.5 text-[var(--status-success)]">
+ <CircleCheck size={13} aria-hidden />
+ {!done.ref
+ ? t(`${key}.doneCurrent`)
+ : done.ref === 'main'
+ ? t(`${key}.doneDevelopment`)
+ : t(`${key}.done`, { ref: done.ref })}
+ </p>
+ )}
+ {done?.generateFirst && (
+ <p className="text-[var(--upgrade-banner-fg)]">
+ {t(`${key}.generateFirst`, { ref: done.generateFirst })}
+ </p>
+ )}
+ {done?.ahead && <p className="text-[var(--upgrade-banner-fg)]">{t(`${key}.ahead`)}</p>}
+ {done?.buildFirst && (
+ <p className="text-[var(--upgrade-banner-fg)]">{t(`${key}.buildFirst`)}</p>
+ )}
+ {done?.uploadAfterBuild && !done.buildFirst && (
+ <p className="text-[var(--text-secondary)]">{t(`${key}.uploadAfterBuild`)}</p>
+ )}
+ {done?.held && !done.ahead && (
+ <p className="text-[var(--upgrade-banner-fg)]">{t(`${key}.held`, { ref: done.held })}</p>
+ )}
+ {error && <p className="text-[var(--error-fg)]">{t(`${key}.errors.${error}`)}</p>}
+ {onKeep &&
+ (error === 'diverged' || (error === 'cancelled' && state?.abandoned === 'combine')) && (
+ <div className="space-y-2 pt-1">
+ <p className="text-[var(--text-secondary)]">{t(`${key}.keep.hint`)}</p>
+ <div className="flex flex-wrap items-center gap-2">
+ {(['github', 'local'] as const).map((side) => (
+ <Button
+ key={side}
+ variant="secondary"
+ size="md"
+ loading={keeping === side}
+ disabled={!!keeping}
+ onClick={() => onKeep(side)}
+ >
+ {t(`${key}.keep.${side}`)}
+ </Button>
+ ))}
+ </div>
+ </div>
+ )}
+ {generate}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/CindyMakeVersionSummary.tsx b/apps/desktop/src/renderer/components/cindy-make/CindyMakeVersionSummary.tsx
new file mode 100644
index 0000000000..9d0dbb55c6
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/CindyMakeVersionSummary.tsx
@@ -0,0 +1,87 @@
+import { useTranslation } from 'react-i18next';
+import { CircleCheck, CircleHelp, Download } from 'lucide-react';
+import type {
+ MakeSourceLatestVersion,
+ MakeSourcePreparation,
+} from '../../../shared/cindyMakeDoctor';
+import { compareCindyMakeSource } from './CindyMakeSourceDetails';
+
+const key = 'cindyMake.summary';
+
+/**
+ * The personal version in plain words: which official version it is based on, how
+ * many of the user's changes it carries, and whether it has the latest official
+ * release. Hashes, branches and local main stay in the technical details.
+ */
+export function CindyMakeVersionSummary({
+ source,
+ latestVersion,
+ changes,
+ showComparison = true,
+}: {
+ source: MakeSourcePreparation;
+ latestVersion?: MakeSourceLatestVersion;
+ /** Changes from this computer's history that are part of the personal version. */
+ changes?: number;
+ /** Progress may replace the comparison while the version facts remain visible. */
+ showComparison?: boolean;
+}) {
+ const { t } = useTranslation();
+ const { personalIsLatest, personalNeedsUpdate, personalStatus } = compareCindyMakeSource(
+ source,
+ latestVersion,
+ );
+ const channel = latestVersion?.channel ?? source.channel;
+ // A base that is the latest release (for example taken in from another computer) is named
+ // by that release; otherwise by the official version it was last updated to.
+ const ref =
+ latestVersion?.status === 'ready' &&
+ latestVersion.channel !== 'dev' &&
+ !!source.baseCommit &&
+ latestVersion.commit === source.baseCommit
+ ? latestVersion.ref
+ : source.ref;
+ const development = channel === 'dev' || ref === 'main';
+ const version = development
+ ? t(`${key}.development`)
+ : ref || source.version
+ ? t(`${key}.official`, { version: ref || source.version })
+ : t(`${key}.officialUnknown`);
+ const basis =
+ changes !== undefined && changes > 0
+ ? t(`${key}.withChanges`, { version, count: changes })
+ : (source.personalAhead ?? 0) > 0
+ ? t(`${key}.withOwnChanges`, { version })
+ : t(`${key}.noChanges`, { version });
+ const latest =
+ latestVersion?.status === 'ready'
+ ? latestVersion.channel === 'dev'
+ ? t(`${key}.latest.dev`)
+ : t(`${key}.latest.${latestVersion.channel}`, { version: latestVersion.ref })
+ : latestVersion?.status === 'unavailable'
+ ? t(`${key}.latest.unavailable`)
+ : t(`${key}.latest.unknown`);
+ const StatusIcon = personalIsLatest ? CircleCheck : personalNeedsUpdate ? Download : CircleHelp;
+ const statusColor = personalIsLatest
+ ? 'text-[var(--status-success)]'
+ : personalNeedsUpdate
+ ? 'text-[var(--upgrade-banner-fg)]'
+ : 'text-[var(--text-secondary)]';
+ return (
+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 text-13">
+ <dt className="text-[var(--text-secondary)]">{t(`${key}.personal`)}</dt>
+ <dd className="min-w-0 break-words text-[var(--text-primary)]">{basis}</dd>
+ <dt className="text-[var(--text-secondary)]">{t(`${key}.latestLabel`)}</dt>
+ <dd className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
+ <span className="text-[var(--text-primary)]">{latest}</span>
+ {showComparison && (
+ // The single live status region; the collapsed technical comparison stays silent.
+ <span role="status" className={`inline-flex items-center gap-1.5 ${statusColor}`}>
+ <StatusIcon size={14} className="shrink-0" aria-hidden />
+ {t(`${key}.included.${personalStatus}`)}
+ </span>
+ )}
+ </dd>
+ </dl>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeContribution.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeContribution.test.tsx
new file mode 100644
index 0000000000..47038665c5
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeContribution.test.tsx
@@ -0,0 +1,249 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createInstance } from 'i18next';
+import { I18nextProvider } from 'react-i18next';
+import zhCN from '@/i18n/locales/zh-CN/common.json';
+import en from '@/i18n/locales/en/common.json';
+import zhTW from '@/i18n/locales/zh-TW/common.json';
+import ja from '@/i18n/locales/ja/common.json';
+import ko from '@/i18n/locales/ko/common.json';
+import {
+ CindyMakeContributionDialog,
+ CindyMakeContributionStatus,
+ contributionActionKey,
+} from '../CindyMakeContribution';
+import {
+ CINDY_MAKE_CONTRIBUTION_ERRORS,
+ type CindyMakeContributionDraft,
+} from '../../../../shared/cindyMakeContribution';
+
+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+const copy = zhCN.cindyMake.contribution;
+
+async function i18nFor(locale: string, resource: object) {
+ const i18n = createInstance();
+ await i18n.init({
+ lng: locale,
+ fallbackLng: false,
+ interpolation: { escapeValue: false },
+ resources: { [locale]: { translation: resource } },
+ });
+ return i18n;
+}
+
+const draft: CindyMakeContributionDraft = {
+ runId: 'run-1',
+ snapshotId: 'confirmed-snapshot',
+ title: 'feat: 加一个按钮',
+ body: '## 这次改了什么',
+ name: 'Ada',
+ email: '',
+ files: ['apps/desktop/src/renderer/x.tsx'],
+ touchesUi: true,
+ repository: 'octo/cindy',
+};
+
+async function renderDialog(invoke: ReturnType<typeof vi.fn>) {
+ vi.stubGlobal('electronAPI', {
+ cindyMakeContribution: invoke,
+ openExternal: vi.fn(async () => ({ success: true })),
+ });
+ const onOpenChange = vi.fn();
+ const onSubmitted = vi.fn();
+ render(
+ <I18nextProvider i18n={await i18nFor('zh-CN', zhCN)}>
+ <CindyMakeContributionDialog
+ runId="run-1"
+ onOpenChange={onOpenChange}
+ onSubmitted={onSubmitted}
+ />
+ </I18nextProvider>,
+ );
+ return { onOpenChange, onSubmitted };
+}
+
+beforeEach(() => {
+ vi.stubGlobal('electronAPI', { openExternal: vi.fn(async () => ({ success: true })) });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('CindyMakeContributionDialog', () => {
+ it('submits only after the author fills in a real email and confirms the DCO sign-off', async () => {
+ const view = {
+ runId: 'run-1',
+ number: 12,
+ url: 'https://github.com/makecindy/cindy/pull/12',
+ state: 'open' as const,
+ submittedAt: 1,
+ };
+ const invoke = vi.fn(async (request: { action: string }) =>
+ request.action === 'draft' ? draft : view,
+ );
+ const { onSubmitted, onOpenChange } = await renderDialog(invoke);
+ await screen.findByDisplayValue(draft.title);
+ expect(screen.getByText(copy.dialog.uiNote)).toBeTruthy();
+ expect(
+ screen.getByText(copy.dialog.public.replace('{{repository}}', 'octo/cindy')),
+ ).toBeTruthy();
+ const submit = screen.getByRole('button', { name: copy.dialog.submit });
+ expect((submit as HTMLButtonElement).disabled).toBe(true);
+
+ fireEvent.change(screen.getByLabelText(new RegExp(copy.dialog.email)), {
+ target: { value: '[email protected]' },
+ });
+ expect((submit as HTMLButtonElement).disabled).toBe(true);
+ fireEvent.click(screen.getByRole('checkbox'));
+ expect(screen.getByRole('checkbox').closest('label')?.textContent).toContain(
+ );
+ expect((submit as HTMLButtonElement).disabled).toBe(false);
+ fireEvent.click(submit);
+ await waitFor(() => expect(onSubmitted).toHaveBeenCalledWith(view));
+ expect(invoke).toHaveBeenLastCalledWith({
+ action: 'submit',
+ runId: 'run-1',
+ snapshotId: draft.snapshotId,
+ title: draft.title,
+ body: draft.body,
+ name: 'Ada',
+ email: '[email protected]',
+ });
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('explains why a change cannot be submitted instead of showing the form', async () => {
+ const invoke = vi.fn(async () => {
+ throw new Error('[PRECONDITION_FAILED] notBound');
+ });
+ await renderDialog(invoke);
+ expect((await screen.findByRole('alert')).textContent).toBe(copy.errors.notBound);
+ expect(screen.queryByRole('button', { name: copy.dialog.submit })).toBeNull();
+ });
+
+ it('keeps the form open with the reason when GitHub refuses the submission', async () => {
+ const invoke = vi.fn(async (request: { action: string }) => {
+ if (request.action === 'draft') return { ...draft, email: '[email protected]' };
+ throw new Error('[PRECONDITION_FAILED] conflict');
+ });
+ const { onOpenChange } = await renderDialog(invoke);
+ await screen.findByDisplayValue(draft.title);
+ fireEvent.click(screen.getByRole('checkbox'));
+ fireEvent.click(screen.getByRole('button', { name: copy.dialog.submit }));
+ expect((await screen.findByRole('alert')).textContent).toBe(copy.errors.conflict);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('asks to confirm the sign-off again after the name or email changes', async () => {
+ const invoke = vi.fn(async () => ({ ...draft, email: '[email protected]' }));
+ await renderDialog(invoke);
+ await screen.findByDisplayValue(draft.title);
+ const checkbox = screen.getByRole('checkbox') as HTMLInputElement;
+ fireEvent.click(checkbox);
+ expect(checkbox.checked).toBe(true);
+ fireEvent.change(screen.getByLabelText(new RegExp(copy.dialog.email)), {
+ target: { value: '[email protected]' },
+ });
+ expect(checkbox.checked).toBe(false);
+ expect(
+ (screen.getByRole('button', { name: copy.dialog.submit }) as HTMLButtonElement).disabled,
+ ).toBe(true);
+ });
+
+ it('withdraws an expired confirmation instead of resubmitting unseen content', async () => {
+ const invoke = vi.fn(async (request: { action: string }) => {
+ if (request.action === 'draft') return { ...draft, email: '[email protected]' };
+ throw new Error('[PRECONDITION_FAILED] changed');
+ });
+ const { onOpenChange, onSubmitted } = await renderDialog(invoke);
+ await screen.findByDisplayValue(draft.title);
+ fireEvent.click(screen.getByRole('checkbox'));
+ fireEvent.click(screen.getByRole('button', { name: copy.dialog.submit }));
+ expect((await screen.findByRole('alert')).textContent).toBe(copy.errors.changed);
+ expect(screen.queryByRole('checkbox')).toBeNull();
+ expect(screen.queryByRole('button', { name: copy.dialog.submit })).toBeNull();
+ expect(onSubmitted).not.toHaveBeenCalled();
+ expect(invoke).toHaveBeenCalledTimes(2);
+ fireEvent.click(screen.getByRole('button', { name: copy.dialog.close }));
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('opens a new pull request when the earlier one was closed', async () => {
+ const invoke = vi.fn(async () => ({
+ ...draft,
+ existing: {
+ runId: 'run-1',
+ number: 3,
+ url: 'https://github.com/makecindy/cindy/pull/3',
+ state: 'closed' as const,
+ submittedAt: 1,
+ },
+ }));
+ await renderDialog(invoke);
+ await screen.findByText(copy.dialog.reopen.replace('{{number}}', '3'));
+ expect(screen.getByRole('button', { name: copy.dialog.submit })).toBeTruthy();
+ });
+
+ it('says a resubmission updates the open pull request', async () => {
+ const invoke = vi.fn(async () => ({
+ ...draft,
+ existing: {
+ runId: 'run-1',
+ number: 3,
+ url: 'https://github.com/makecindy/cindy/pull/3',
+ submittedAt: 1,
+ },
+ }));
+ await renderDialog(invoke);
+ await screen.findByText(copy.dialog.existing.replace('{{number}}', '3'));
+ expect(screen.getByRole('button', { name: copy.dialog.update })).toBeTruthy();
+ });
+});
+
+describe('CindyMakeContributionStatus', () => {
+ it('shows the review state in plain words and opens the pull request', async () => {
+ const openExternal = vi.fn(async () => ({ success: true }));
+ vi.stubGlobal('electronAPI', { openExternal });
+ const url = 'https://github.com/makecindy/cindy/pull/9';
+ render(
+ <I18nextProvider i18n={await i18nFor('zh-CN', zhCN)}>
+ <CindyMakeContributionStatus
+ view={{ runId: 'r', number: 9, url, state: 'merged', submittedAt: 1 }}
+ />
+ </I18nextProvider>,
+ );
+ expect(screen.getByText(copy.state.merged.replace('{{number}}', '9'))).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: copy.view }));
+ expect(openExternal).toHaveBeenCalledWith(url);
+ });
+
+ it('offers no new submission once the change is accepted', () => {
+ const view = { runId: 'r', number: 1, url: '', submittedAt: 1 };
+ expect(contributionActionKey()).toBe('cindyMake.contribution.action');
+ expect(contributionActionKey({ ...view, state: 'open' })).toBe('cindyMake.contribution.update');
+ expect(contributionActionKey({ ...view, state: 'closed' })).toBe(
+ 'cindyMake.contribution.resubmit',
+ );
+ expect(contributionActionKey({ ...view, state: 'merged' })).toBeUndefined();
+ });
+});
+
+describe('contribution copy', () => {
+ it.each([
+ ['zh-CN', zhCN],
+ ['zh-TW', zhTW],
+ ['en', en],
+ ['ja', ja],
+ ['ko', ko],
+ ] as const)('covers every error and state in %s', (_locale, resource) => {
+ const strings = resource.cindyMake.contribution;
+ for (const code of CINDY_MAKE_CONTRIBUTION_ERRORS)
+ expect(strings.errors[code], code).toBeTruthy();
+ for (const state of ['submitted', 'open', 'merged', 'closed'] as const)
+ expect(strings.state[state]).toContain('{{number}}');
+ });
+});
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 781ea62074..eb1353f023 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
@@ -13,7 +13,7 @@ import ko from '@/i18n/locales/ko/common.json';
import type { CindyMakeHistoryState } from '../../../../shared/cindyMakeHistory';
import { CindyMakeHistoryPanel } from '../CindyMakeHistoryPanel';
import { CindyMakeVersionsPanel } from '../CindyMakeVersionsPanel';
-import { CindyMakeMergeNotice } from '../CindyMakeMergeNotice';
+import { CindyMakeSyncStatus } from '../CindyMakeSync';
const h = vi.hoisted(() => ({ make: {}, error: vi.fn(), success: vi.fn() }));
vi.mock('@/lib/cindyMakeState', () => ({ useCindyMakeState: () => h.make }));
@@ -313,15 +313,12 @@ describe('Cindy Make history with real translations', () => {
<I18nextProvider i18n={i18n}>
<CindyMakeVersionsPanel />
<CindyMakeHistoryPanel hasPersonalVersion />
- <CindyMakeMergeNotice
+ <CindyMakeSyncStatus
state={{
- id: 'merge',
- status: 'conflict',
- error: 'checksFailed',
- ref: 'main',
- upstreamCommit: 'a'.repeat(40),
- hasWorkspace: true,
+ waiting: { kind: 'official', reason: 'missing', missing: 2, sessionId: 'merge' },
}}
+ onAccept={() => undefined}
+ onAbandon={() => undefined}
/>
</I18nextProvider>
</MemoryRouter>,
@@ -355,7 +352,10 @@ describe('Cindy Make history with real translations', () => {
'round-a',
'round-b',
]);
- expect(screen.getByRole('button', { name: resource.cindyMake.merge.resolve })).toBeTruthy();
+ expect(
+ screen.getByRole('button', { name: resource.cindyMake.sync.accept.action }),
+ ).toBeTruthy();
+ expect(screen.getByRole('button', { name: resource.cindyMake.merge.openTask })).toBeTruthy();
expect(i18n.t('settings.cindyMake.tabs.versions')).toBe(
resource.settings.cindyMake.tabs.versions,
);
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 63800f8494..4b2aa34a34 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
@@ -270,6 +270,35 @@ describe('Make history controls', () => {
expect(f.read).toHaveBeenCalled();
});
+ it('offers submitting a finished change to Cindy and shows where its pull request stands', async () => {
+ const A = 'a'.repeat(40);
+ const B = 'b'.repeat(40);
+ const finished = { id: 'round-a', reportedAt: 1, baseTree: A, tree: B };
+ harness([
+ item({ runId: 'done', completions: [finished], integration: 'integrated' }),
+ item({ runId: 'noop', completions: [{ ...finished, tree: A }], createdAt: 0 }),
+ ]);
+ const api = window.electronAPI as unknown as Record<string, unknown>;
+ const contribution = vi.fn(async (request: { action: string }) =>
+ request.action === 'status'
+ ? [{ runId: 'done', number: 4, url: 'https://github.com/makecindy/cindy/pull/4', state: 'open', submittedAt: 1 }]
+ : new Promise(() => {}),
+ );
+ api.cindyMakeContribution = contribution;
+ api.openExternal = vi.fn();
+ render(<CindyMakeHistoryPanel />);
+ expect(await screen.findByText('cindyMake.contribution.state.open')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.contribution.update' }));
+ expect(await screen.findByRole('dialog')).toBeTruthy();
+ expect(contribution).toHaveBeenCalledWith({ action: 'draft', runId: 'done' });
+
+ cleanup();
+ harness([item({ runId: 'noop', completions: [{ ...finished, tree: A }] })]);
+ render(<CindyMakeHistoryPanel />);
+ await screen.findByText('cindyMake.history.rounds');
+ expect(screen.queryByRole('button', { name: 'cindyMake.contribution.action' })).toBeNull();
+ });
+
it('keeps an explicit retry for a failed integration without presenting it as generation', async () => {
const f = harness([item({ actions: ['open', 'retry'], operationError: 'checksFailed' })]);
render(<CindyMakeHistoryPanel />);
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeMergeNotice.i18n.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeMergeNotice.i18n.test.tsx
deleted file mode 100644
index ef26aebed4..0000000000
--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeMergeNotice.i18n.test.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { createInstance } from 'i18next';
-import { I18nextProvider } from 'react-i18next';
-import { MemoryRouter, useLocation } from 'react-router-dom';
-import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
-import { CindyMakeMergeNotice } from '../CindyMakeMergeNotice';
-import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
-import en from '@/i18n/locales/en/common.json';
-import zhCN from '@/i18n/locales/zh-CN/common.json';
-import zhTW from '@/i18n/locales/zh-TW/common.json';
-import ja from '@/i18n/locales/ja/common.json';
-import ko from '@/i18n/locales/ko/common.json';
-
-const locales = [
- ['en', en, 'Source update has conflicts'],
- ['zh-CN', zhCN, '源码更新遇到冲突'],
- ['zh-TW', zhTW, '原始碼更新遇到衝突'],
- ['ja', ja, 'ソース更新で競合が発生しました'],
- ['ko', ko, '소스 업데이트 중 충돌 발생'],
-] as const;
-function CurrentTask() {
- return <output data-testid="current-task">{useLocation().pathname}</output>;
-}
-afterEach(() => {
- cleanup();
- vi.unstubAllGlobals();
-});
-
-describe('source conflict confirmation translations', () => {
- it.each(locales)('renders distinct local main errors in %s', async (locale, resource) => {
- const i18n = createInstance();
- await i18n.init({
- lng: locale,
- fallbackLng: false,
- resources: { [locale]: { translation: resource } },
- });
- const renderError = (error: 'localMain' | 'localMainAhead') => (
- <MemoryRouter>
- <I18nextProvider i18n={i18n}>
- <CindyMakeMergeNotice
- state={{
- id: 'merge',
- status: 'failed',
- ref: 'v1.2.3',
- upstreamCommit: 'a'.repeat(40),
- error,
- hasWorkspace: false,
- }}
- />
- </I18nextProvider>
- </MemoryRouter>
- );
- const view = render(renderError('localMain'));
- expect(screen.getByRole('status').textContent).toContain(resource.cindyMake.merge.errors.localMain);
- view.rerender(renderError('localMainAhead'));
- expect(screen.getByRole('status').textContent).toContain(resource.cindyMake.merge.errors.localMainAhead);
- expect(screen.queryByText(resource.cindyMake.merge.errors.localMain)).toBeNull();
- expect(screen.getByRole('status').textContent).toContain('Cindy Make');
- expect(screen.getByRole('status').textContent).not.toMatch(/cindyMake[.]|[?]{2,}|�/);
- });
- it.each(locales)(
- 'opens retained task records in %s without recreating a cleaned workspace',
- async (locale, resource) => {
- const api = vi.fn();
- vi.stubGlobal('electronAPI', { cindyMakeMerge: api });
- const i18n = createInstance();
- await i18n.init({ lng: locale, resources: { [locale]: { translation: resource } } });
- render(
- <MemoryRouter>
- <I18nextProvider i18n={i18n}>
- <CindyMakeMergeNotice
- state={{
- id: 'merge',
- status: 'merged',
- ref: 'personal',
- upstreamCommit: '',
- sessionId: 'resolver',
- hasWorkspace: false,
- }}
- />
- <CurrentTask />
- </I18nextProvider>
- </MemoryRouter>,
- );
- fireEvent.click(screen.getByRole('button', { name: resource.cindyMake.merge.openTask }));
- expect(screen.getByTestId('current-task').textContent).toBe('/cc-agent/resolver');
- expect(api).not.toHaveBeenCalled();
- },
- );
- it('dismisses an old account prompt without cancelling and lets the current account decide again', async () => {
- const operation = {
- id: '12345678-1234-1234-1234-123456789abc',
- status: 'conflict' as const,
- ref: 'main',
- upstreamCommit: 'a'.repeat(40),
- hasWorkspace: true,
- };
- const api = vi.fn(async () => ({ ...operation, status: 'cancelled', hasWorkspace: false }));
- vi.stubGlobal('electronAPI', { cindyMakeMerge: api });
- const i18n = createInstance();
- await i18n.init({ lng: 'en', resources: { en: { translation: en } } });
- const ui = () => (
- <MemoryRouter>
- <I18nextProvider i18n={i18n}>
- <ConfirmDialogProvider>
- <CindyMakeMergeNotice state={operation} />
- </ConfirmDialogProvider>
- </I18nextProvider>
- </MemoryRouter>
- );
- setDataOwnerGeneration('merge-owner');
- const view = render(ui());
- fireEvent.click(screen.getByRole('button', { name: en.cindyMake.merge.resolve }));
- await screen.findByRole('alertdialog');
- setDataOwnerGeneration('merge-owner');
- view.rerender(ui());
- await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());
- expect(api).not.toHaveBeenCalled();
- const resolve = screen.getByRole('button', { name: en.cindyMake.merge.resolve });
- expect(resolve.hasAttribute('disabled')).toBe(false);
- fireEvent.click(resolve);
- const dialog = await screen.findByRole('alertdialog');
- fireEvent.click(
- within(dialog).getByRole('button', { name: en.cindyMake.merge.conflictConfirm.cancel }),
- );
- await waitFor(() =>
- expect(api).toHaveBeenCalledExactlyOnceWith({ action: 'cancel', operationId: operation.id }),
- );
- });
- it.each(locales)(
- 'explains the decision and cancels without starting an Agent in %s',
- async (locale, resource, title) => {
- const operation = {
- id: '12345678-1234-1234-1234-123456789abc',
- status: 'conflict' as const,
- ref: 'main',
- upstreamCommit: 'a'.repeat(40),
- hasWorkspace: true,
- };
- const api = vi.fn(async () => ({ ...operation, status: 'cancelled', hasWorkspace: false }));
- vi.stubGlobal('electronAPI', { cindyMakeMerge: api });
- const i18n = createInstance();
- await i18n.init({
- lng: locale,
- fallbackLng: false,
- resources: { [locale]: { translation: resource } },
- });
- render(
- <MemoryRouter>
- <I18nextProvider i18n={i18n}>
- <ConfirmDialogProvider>
- <CindyMakeMergeNotice state={operation} />
- </ConfirmDialogProvider>
- </I18nextProvider>
- </MemoryRouter>,
- );
- fireEvent.click(screen.getByRole('button', { name: resource.cindyMake.merge.resolve }));
- const dialog = await screen.findByRole('alertdialog');
- expect(within(dialog).getByText(title)).toBeTruthy();
- expect(
- within(dialog).getByText(resource.cindyMake.merge.conflictConfirm.description),
- ).toBeTruthy();
- expect(
- within(dialog).getByRole('button', {
- name: resource.cindyMake.merge.conflictConfirm.confirm,
- }),
- ).toBeTruthy();
- expect(dialog.textContent).not.toMatch(/cindyMake[.]|[?]{2,}|�/);
- expect(api).not.toHaveBeenCalled();
- fireEvent.click(
- within(dialog).getByRole('button', {
- name: resource.cindyMake.merge.conflictConfirm.cancel,
- }),
- );
- await waitFor(() =>
- expect(api).toHaveBeenCalledExactlyOnceWith({
- action: 'cancel',
- operationId: operation.id,
- }),
- );
- },
- );
-});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePersonalRemote.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePersonalRemote.test.tsx
new file mode 100644
index 0000000000..25db511d8f
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePersonalRemote.test.tsx
@@ -0,0 +1,282 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createInstance } from 'i18next';
+import { I18nextProvider } from 'react-i18next';
+import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
+import zhCN from '@/i18n/locales/zh-CN/common.json';
+import en from '@/i18n/locales/en/common.json';
+import zhTW from '@/i18n/locales/zh-TW/common.json';
+import ja from '@/i18n/locales/ja/common.json';
+import ko from '@/i18n/locales/ko/common.json';
+import { CindyMakeStorageCard, CindyMakeStorageRow } from '../CindyMakePersonalRemote';
+import type { CindyMakePersonalRemoteState } from '../../../../shared/cindyMakePersonalRemote';
+
+vi.mock('@/features/cc-agent/GithubSetupDialog', () => ({
+ GithubSetupDialog: () => <div role="dialog">github-setup</div>,
+}));
+
+const copy = zhCN.cindyMake.storage;
+
+async function i18nFor(locale: string, resource: object) {
+ const i18n = createInstance();
+ // Mirror the app: React escapes rendered text, so i18next must not escape again.
+ await i18n.init({
+ lng: locale,
+ fallbackLng: false,
+ interpolation: { escapeValue: false },
+ resources: { [locale]: { translation: resource } },
+ });
+ return i18n;
+}
+
+async function renderRow(state: CindyMakePersonalRemoteState, act = vi.fn(async () => {})) {
+ const onOffer = vi.fn();
+ render(
+ <I18nextProvider i18n={await i18nFor('zh-CN', zhCN)}>
+ <ConfirmDialogProvider>
+ <CindyMakeStorageRow state={state} act={act} onOffer={onOffer} />
+ </ConfirmDialogProvider>
+ </I18nextProvider>,
+ );
+ return { act, onOffer };
+}
+
+beforeEach(() => {
+ vi.stubGlobal('electronAPI', { openExternal: vi.fn(async () => ({ success: true })) });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('CindyMakeStorageRow', () => {
+ const bound: CindyMakePersonalRemoteState = {
+ github: 'connected',
+ githubLogin: 'octo',
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ sync: 'needsMerge',
+ offerMigration: false,
+ };
+
+ it('points to the single Sync when both computers changed the same place', async () => {
+ const { act } = await renderRow(bound);
+ expect(screen.getByRole('status').textContent).toContain(copy.status.needsMerge);
+ expect(screen.getByRole('status').textContent).toContain(copy.needsMergeHint);
+ // The row has no sync or combine button of its own; Sync above does both.
+ expect(screen.queryByRole('button', { name: copy.actions.syncNow })).toBeNull();
+ expect(act).not.toHaveBeenCalled();
+ });
+
+ it('asks to generate first when this computer’s side of a combine is not generated', async () => {
+ await renderRow({ ...bound, sync: 'buildFirst' });
+ expect(screen.getByRole('status').textContent).toContain(copy.status.buildFirst);
+ expect(screen.getByRole('status').textContent).toContain(copy.buildFirstHint);
+ });
+
+ it('saves to a new repository, with consent again, when the old one is gone', async () => {
+ const { act, onOffer } = await renderRow({ ...bound, sync: 'synced', error: 'forkMissing' });
+ expect(screen.getByRole('status').textContent).toContain(copy.errors.forkMissing);
+ fireEvent.click(screen.getByRole('button', { name: copy.actions.saveAgain }));
+ await waitFor(() => expect(onOffer).toHaveBeenCalledOnce());
+ expect(act).toHaveBeenCalledExactlyOnceWith('disconnect');
+ });
+
+ it('offers reconnecting when GitHub is connected as another account', async () => {
+ await renderRow({ ...bound, sync: 'synced', githubLogin: 'other', error: 'account' });
+ fireEvent.click(screen.getByRole('button', { name: copy.actions.reconnect }));
+ expect(screen.getByRole('dialog').textContent).toBe('github-setup');
+ });
+
+ it('explains the local-only limitation and offers to connect GitHub', async () => {
+ await renderRow({ github: 'missing', offerMigration: false });
+ expect(screen.getByRole('status').textContent).toContain(copy.localOnly);
+ expect(screen.getByRole('status').textContent).toContain(copy.localOnlyHint);
+ fireEvent.click(screen.getByRole('button', { name: copy.actions.connect }));
+ expect(screen.getByRole('dialog').textContent).toBe('github-setup');
+ });
+
+ it('lets a user who kept the version local reopen the GitHub consent', async () => {
+ const { onOffer, act } = await renderRow({
+ github: 'connected',
+ githubLogin: 'octo',
+ choice: 'local',
+ offerMigration: false,
+ });
+ expect(screen.getByRole('status').textContent).toContain(copy.localChosenHint);
+ fireEvent.click(screen.getByRole('button', { name: copy.actions.save }));
+ expect(onOffer).toHaveBeenCalledOnce();
+ expect(act).not.toHaveBeenCalled();
+ });
+
+ it('asks for consent again before retrying a failed save', async () => {
+ const { act, onOffer } = await renderRow({
+ github: 'connected',
+ githubLogin: 'octo',
+ error: 'network',
+ offerMigration: false,
+ });
+ expect(screen.getByRole('status').textContent).toContain(copy.errors.network);
+ fireEvent.click(screen.getByRole('button', { name: copy.actions.retry }));
+ expect(onOffer).toHaveBeenCalledOnce();
+ expect(act).not.toHaveBeenCalled();
+ });
+
+ it('offers reconnecting after a rejected authorization; Sync then retries', async () => {
+ const { act } = await renderRow({
+ github: 'connected',
+ githubLogin: 'octo',
+ login: 'octo',
+ repository: 'octo/cindy',
+ sync: 'pending',
+ error: 'workflowScope',
+ offerMigration: false,
+ });
+ expect(screen.getByRole('status').textContent).toContain(copy.errors.workflowScope);
+ expect(screen.getByRole('button', { name: copy.actions.reconnect })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: copy.actions.syncNow })).toBeNull();
+ expect(act).not.toHaveBeenCalled();
+ });
+
+ it('shows a synced repository and stops syncing only after confirmation', async () => {
+ const { act } = await renderRow({
+ github: 'connected',
+ githubLogin: 'octo',
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ sync: 'synced',
+ offerMigration: false,
+ });
+ expect(screen.getByRole('status').textContent).toContain('你的 GitHub · octo/cindy');
+ expect(screen.getByRole('status').textContent).toContain(copy.status.synced);
+ // Checking for changes from another computer is the single Sync above, not a row button.
+ expect(screen.queryByRole('button', { name: copy.actions.syncNow })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: copy.actions.view }));
+ expect(window.electronAPI.openExternal).toHaveBeenCalledWith(
+ 'https://github.com/octo/cindy/tree/cindy-personal',
+ );
+ fireEvent.click(screen.getByRole('button', { name: copy.actions.stop }));
+ expect(act).not.toHaveBeenCalled();
+ fireEvent.click(await screen.findByRole('button', { name: copy.stopConfirm.confirm }));
+ await waitFor(() => expect(act).toHaveBeenCalledWith('disconnect'));
+ });
+
+ it('pauses on an account mismatch without offering to upload', async () => {
+ await renderRow({
+ github: 'connected',
+ githubLogin: 'someone',
+ choice: 'github',
+ login: 'octo',
+ repository: 'octo/cindy',
+ sync: 'synced',
+ error: 'account',
+ offerMigration: false,
+ });
+ expect(screen.getByRole('status').textContent).toContain(
+ copy.status.account.replace('{{login}}', 'someone'),
+ );
+ expect(screen.queryByRole('button', { name: copy.actions.syncNow })).toBeNull();
+ });
+
+ it('shows running progress without actions that could race it', async () => {
+ await renderRow({
+ github: 'connected',
+ githubLogin: 'octo',
+ running: 'save',
+ step: 'fork',
+ offerMigration: false,
+ });
+ expect(screen.getByRole('status').textContent).toContain(copy.running.save);
+ expect(screen.getByRole('status').textContent).toContain(copy.step.fork);
+ expect(screen.queryAllByRole('button')).toEqual([]);
+ });
+});
+
+describe('CindyMakeStorageCard', () => {
+ it.each([
+ ['zh-CN', zhCN],
+ ['zh-TW', zhTW],
+ ['en', en],
+ ['ja', ja],
+ ['ko', ko],
+ ] as const)(
+ 'states that the fork is public and stays until a choice in %s',
+ async (locale, resource) => {
+ const onSave = vi.fn();
+ const onKeepLocal = vi.fn();
+ render(
+ <I18nextProvider i18n={await i18nFor(locale, resource)}>
+ <CindyMakeStorageCard
+ state={{
+ github: 'connected',
+ githubLogin: 'octo',
+ offerMigration: true,
+ sourceReady: true,
+ }}
+ onSave={onSave}
+ onKeepLocal={onKeepLocal}
+ />
+ </I18nextProvider>,
+ );
+ const strings = resource.cindyMake.storage;
+ expect(screen.getByRole('heading').textContent).toBe(strings.card.title);
+ expect(document.body.textContent).toContain(
+ strings.card.public.replace('{{repository}}', 'octo/cindy'),
+ );
+ // No "not now": the offer only ends by binding or an explicit local-only choice.
+ expect(screen.getAllByRole('button')).toHaveLength(2);
+ fireEvent.click(screen.getByRole('button', { name: strings.actions.save }));
+ fireEvent.click(screen.getByRole('button', { name: strings.actions.keepLocal }));
+ expect([onSave, onKeepLocal].map((fn) => fn.mock.calls.length)).toEqual([1, 1]);
+ },
+ );
+
+ it('offers a new computer the personal version already on GitHub', async () => {
+ const onSave = vi.fn();
+ render(
+ <I18nextProvider i18n={await i18nFor('zh-CN', zhCN)}>
+ <CindyMakeStorageCard
+ state={{
+ github: 'connected',
+ githubLogin: 'octo',
+ existingPersonal: 'octo/cindy-1',
+ sourceReady: false,
+ error: 'network',
+ offerMigration: true,
+ }}
+ onSave={onSave}
+ onKeepLocal={vi.fn()}
+ />
+ </I18nextProvider>,
+ );
+ expect(screen.getByRole('heading').textContent).toBe(copy.card.existingTitle);
+ expect(document.body.textContent).toContain(copy.card.existingKeeps);
+ expect(document.body.textContent).toContain(copy.card.prepareFirst);
+ expect(screen.getByRole('status').textContent).toBe(copy.errors.network);
+ fireEvent.click(screen.getByRole('button', { name: copy.actions.useExisting }));
+ expect(onSave).toHaveBeenCalledOnce();
+ });
+
+ it('keeps both choices disabled while the source is prepared before saving', async () => {
+ render(
+ <I18nextProvider i18n={await i18nFor('zh-CN', zhCN)}>
+ <CindyMakeStorageCard
+ state={{
+ github: 'connected',
+ githubLogin: 'octo',
+ offerMigration: true,
+ sourceReady: false,
+ }}
+ preparing
+ onSave={vi.fn()}
+ onKeepLocal={vi.fn()}
+ />
+ </I18nextProvider>,
+ );
+ for (const button of screen.getAllByRole('button'))
+ expect(button).toHaveProperty('disabled', true);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePreflightDialog.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePreflightDialog.test.tsx
index 8912438e60..6d8dd8ceae 100644
--- a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePreflightDialog.test.tsx
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakePreflightDialog.test.tsx
@@ -148,6 +148,14 @@ describe('Make preflight confirmation boundary', () => {
},
);
+ it('lets the user continue when the official lookup failed, and says so', async () => {
+ open();
+ await finishChecks();
+ act(() => h.publish!({ ...ready, upstream: { status: 'failed', items: [] } }));
+ expect(screen.getByText('cindyMake.upstream.failedContinue')).toBeTruthy();
+ expect((continueButton() as HTMLButtonElement).disabled).toBe(false);
+ });
+
it.each(['found', 'notFound'] as const)(
'keeps Continue in the footer and confirms closing after a %s upstream result',
async (status) => {
@@ -208,7 +216,8 @@ describe('Make preflight confirmation boundary', () => {
{ stage: 'ready', report: { ...ready, upstream: { status: 'found', items: [] } } },
{ stage: 'incomplete', report: { ...ready, status: 'failed' } },
{ stage: 'incomplete', report: { ...ready, status: 'cancelled' } },
- { stage: 'incomplete', report: { ...ready, upstream: { status: 'failed', items: [] } } },
+ // A failed official lookup does not block making the change.
+ { stage: 'ready', report: { ...ready, upstream: { status: 'failed', items: [] } } },
{
stage: 'incomplete',
report: { ...ready, source: undefined, upstream: { status: 'pending', items: [] } },
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeSync.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeSync.test.tsx
new file mode 100644
index 0000000000..7ec01476a4
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeSync.test.tsx
@@ -0,0 +1,172 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createInstance } from 'i18next';
+import { I18nextProvider } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import zhCN from '@/i18n/locales/zh-CN/common.json';
+import en from '@/i18n/locales/en/common.json';
+import zhTW from '@/i18n/locales/zh-TW/common.json';
+import ja from '@/i18n/locales/ja/common.json';
+import ko from '@/i18n/locales/ko/common.json';
+import { CindyMakeSyncStatus } from '../CindyMakeSync';
+import {
+ CINDY_MAKE_SYNC_ERRORS,
+ CINDY_MAKE_SYNC_STEPS,
+ type CindyMakeSyncState,
+ type CindyMakeSyncWaiting,
+} from '../../../../shared/cindyMakeSync';
+
+const locales = { 'zh-CN': zhCN, 'zh-TW': zhTW, en, ja, ko };
+async function show(
+ state: CindyMakeSyncState,
+ locale: keyof typeof locales = 'zh-CN',
+ props: Partial<Parameters<typeof CindyMakeSyncStatus>[0]> = {},
+) {
+ const i18n = createInstance();
+ await i18n.init({
+ lng: locale,
+ fallbackLng: false,
+ interpolation: { escapeValue: false },
+ resources: { [locale]: { translation: locales[locale] } },
+ });
+ return render(
+ <MemoryRouter>
+ <I18nextProvider i18n={i18n}>
+ <CindyMakeSyncStatus state={state} {...props} />
+ </I18nextProvider>
+ </MemoryRouter>,
+ );
+}
+
+afterEach(cleanup);
+
+const waits: CindyMakeSyncWaiting[] = [
+ { kind: 'combine', reason: 'working', sessionId: 'task' },
+ { kind: 'official', reason: 'working', sessionId: 'task' },
+ { kind: 'official', reason: 'input', sessionId: 'task' },
+ { kind: 'official', reason: 'interrupted', sessionId: 'task' },
+ { kind: 'combine', reason: 'interrupted' },
+ { kind: 'combine', reason: 'missing', missing: 3, sessionId: 'task' },
+ { kind: 'official', reason: 'stale', sessionId: 'task' },
+ { kind: 'official', reason: 'failed', sessionId: 'task' },
+ { kind: 'official', reason: 'working', abandoning: true },
+ { kind: 'combine', reason: 'paused', sessionId: 'task' },
+ { kind: 'official', reason: 'otherAccount' },
+];
+
+describe('Sync status line', () => {
+ it('says which official version Sync reached and what waits for a Cindy update', async () => {
+ await show({ done: { at: 1, ref: 'v1.2.0', held: 'v1.3.0' } });
+ expect(screen.getByText('已同步到官方 v1.2.0')).toBeTruthy();
+ expect(screen.getByText(/官方 v1\.3\.0 已发布/)).toBeTruthy();
+ // Polite live text; the version summary keeps the single status region.
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+
+ it('shows the running step and the conflict it waits for in plain words', async () => {
+ const running = await show({ running: true, step: 'combine' });
+ expect(running.container.textContent).toBe(zhCN.cindyMake.sync.step.combine);
+ running.unmount();
+ const waiting = await show({ waiting: waits[0] });
+ expect(waiting.container.textContent).toContain(zhCN.cindyMake.sync.waiting.working.combine);
+ expect(screen.getByRole('button', { name: zhCN.cindyMake.merge.openTask })).toBeTruthy();
+ });
+
+ it('offers abandoning the operation Sync waits for', async () => {
+ const onAbandon = vi.fn();
+ await show({ waiting: waits[1] }, 'zh-CN', { onAbandon });
+ fireEvent.click(screen.getByRole('button', { name: zhCN.cindyMake.sync.abandon.action }));
+ expect(onAbandon).toHaveBeenCalledOnce();
+ });
+
+ it('lets the user use a result that lost changes, and says how many', async () => {
+ const onAccept = vi.fn();
+ const { container } = await show({ waiting: waits[5] }, 'zh-CN', { onAccept });
+ expect(container.textContent).toContain('少了 3 项');
+ fireEvent.click(screen.getByRole('button', { name: zhCN.cindyMake.sync.accept.action }));
+ expect(onAccept).toHaveBeenCalledOnce();
+ });
+
+ it('continues an operation whose task is gone, and leaves another account’s alone', async () => {
+ const onResume = vi.fn();
+ const paused = await show({ waiting: waits[9] }, 'zh-CN', { onResume, onAbandon: vi.fn() });
+ expect(screen.queryByRole('button', { name: zhCN.cindyMake.merge.openTask })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: zhCN.cindyMake.sync.resume }));
+ expect(onResume).toHaveBeenCalledOnce();
+ paused.unmount();
+ await show({ waiting: waits[10] }, 'zh-CN', { onResume, onAbandon: vi.fn() });
+ expect(screen.getByText(zhCN.cindyMake.sync.waiting.otherAccount)).toBeTruthy();
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ it('offers nothing but progress while Abandon is carried out', async () => {
+ await show({ waiting: waits[8] }, 'zh-CN', { onAbandon: vi.fn(), onAccept: vi.fn() });
+ expect(screen.getByText(zhCN.cindyMake.sync.waiting.abandoning)).toBeTruthy();
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ it('points to generating when the personal version changed since it was generated', async () => {
+ const onGenerate = vi.fn();
+ await show({ done: { at: 1, ref: 'v1.2.0' } }, 'zh-CN', { needsGenerate: true, onGenerate });
+ expect(screen.getByText(zhCN.cindyMake.sync.needsGenerate)).toBeTruthy();
+ fireEvent.click(
+ screen.getByRole('button', { name: zhCN.cindyMake.history.generatePersonal }),
+ );
+ expect(onGenerate).toHaveBeenCalledOnce();
+ });
+
+ it('offers keeping one side when the two versions cannot be combined', async () => {
+ const onKeep = vi.fn();
+ const { unmount } = await show({ error: 'diverged' }, 'zh-CN', { onKeep });
+ fireEvent.click(screen.getByRole('button', { name: zhCN.cindyMake.sync.keep.local }));
+ expect(onKeep).toHaveBeenCalledWith('local');
+ unmount();
+ // Not after an abandoned official update: there is nothing to choose between.
+ await show({ error: 'cancelled', abandoned: 'official' }, 'zh-CN', { onKeep });
+ expect(screen.queryByRole('button', { name: zhCN.cindyMake.sync.keep.github })).toBeNull();
+ });
+
+ it('keeps the completed local update visible above a GitHub problem', async () => {
+ const { container } = await show({ error: 'github', done: { at: 1, ref: 'v1.2.0' } });
+ expect(container.textContent).toContain('已同步到官方 v1.2.0');
+ expect(container.textContent).toContain(zhCN.cindyMake.sync.errors.github);
+ });
+
+ it('explains a personal version already ahead of this computer’s Cindy', async () => {
+ const { container } = await show({ done: { at: 1, ahead: true } });
+ expect(container.textContent).toContain(zhCN.cindyMake.sync.doneCurrent);
+ expect(container.textContent).toContain(zhCN.cindyMake.sync.ahead);
+ });
+
+ it.each(Object.keys(locales) as (keyof typeof locales)[])(
+ 'has complete copy for every step, wait and error in %s',
+ async (locale) => {
+ const states: CindyMakeSyncState[] = [
+ ...CINDY_MAKE_SYNC_STEPS.map((step) => ({ running: true, step })),
+ ...waits.map((waiting) => ({ waiting })),
+ ...CINDY_MAKE_SYNC_ERRORS.map((error) => ({ error })),
+ { done: { at: 1, ref: 'main' } },
+ { done: { at: 1, ref: 'v1.2.0', held: 'v1.3.0' } },
+ { done: { at: 1, ahead: true } },
+ { done: { at: 1, ref: 'v1.2.0', uploadAfterBuild: true } },
+ { done: { at: 1, ref: 'v1.2.0', buildFirst: true } },
+ { error: 'cancelled', abandoned: 'combine' },
+ { done: { at: 1, generateFirst: 'v1.3.0' } },
+ ];
+ for (const state of states) {
+ const { container, unmount } = await show(state, locale, {
+ onAbandon: () => undefined,
+ onAccept: () => undefined,
+ needsGenerate: true,
+ onGenerate: () => undefined,
+ onKeep: () => undefined,
+ onResume: () => undefined,
+ });
+ expect(container.textContent?.trim(), JSON.stringify(state)).toBeTruthy();
+ expect(container.textContent).not.toMatch(/cindyMake\.|\{\{/);
+ unmount();
+ }
+ },
+ );
+});
diff --git a/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeVersionSummary.test.tsx b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeVersionSummary.test.tsx
new file mode 100644
index 0000000000..b30de70ba1
--- /dev/null
+++ b/apps/desktop/src/renderer/components/cindy-make/__tests__/CindyMakeVersionSummary.test.tsx
@@ -0,0 +1,112 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createInstance } from 'i18next';
+import { I18nextProvider } from 'react-i18next';
+import { CindyMakeVersionSummary } from '../CindyMakeVersionSummary';
+import type {
+ MakeSourceLatestVersion,
+ MakeSourcePreparation,
+} from '../../../../shared/cindyMakeDoctor';
+import en from '@/i18n/locales/en/common.json';
+import zhCN from '@/i18n/locales/zh-CN/common.json';
+import zhTW from '@/i18n/locales/zh-TW/common.json';
+import ja from '@/i18n/locales/ja/common.json';
+import ko from '@/i18n/locales/ko/common.json';
+
+const MAIN = 'c'.repeat(40);
+const source: MakeSourcePreparation = {
+ status: 'ready',
+ path: 'managed-source',
+ branch: 'cindy-personal',
+ channel: 'release',
+ ref: 'v0.9.3',
+ commit: 'a'.repeat(40),
+ mainCommit: MAIN,
+ personalAhead: 4,
+ personalBehind: 0,
+};
+const latest: MakeSourceLatestVersion = {
+ status: 'ready',
+ channel: 'release',
+ ref: 'v0.9.3',
+ commit: MAIN,
+ ahead: 0,
+ behind: 0,
+};
+
+const locales = { en, 'zh-CN': zhCN, 'zh-TW': zhTW, ja, ko };
+async function show(
+ props: {
+ source?: Partial<MakeSourcePreparation>;
+ latestVersion?: MakeSourceLatestVersion;
+ changes?: number;
+ } = {},
+ locale: keyof typeof locales = 'zh-CN',
+) {
+ const i18n = createInstance();
+ await i18n.init({
+ lng: locale,
+ interpolation: { escapeValue: false },
+ resources: { [locale]: { translation: locales[locale] } },
+ });
+ return render(
+ <I18nextProvider i18n={i18n}>
+ <CindyMakeVersionSummary
+ source={{ ...source, ...props.source }}
+ latestVersion={'latestVersion' in props ? props.latestVersion : latest}
+ changes={props.changes}
+ />
+ </I18nextProvider>,
+ );
+}
+
+afterEach(cleanup);
+
+describe('Cindy Make version summary', () => {
+ it('describes the personal version in plain words without hashes or branches', async () => {
+ const { container } = await show({ changes: 3 });
+ expect(screen.getByText('官方 v0.9.3 + 你的 3 项修改')).toBeTruthy();
+ expect(screen.getByText('正式版 v0.9.3')).toBeTruthy();
+ expect(screen.getByRole('status').textContent).toBe('个人版已包含');
+ expect(screen.getByRole('status').className).toContain('--status-success');
+ const text = container.textContent ?? '';
+ for (const technical of ['cindy-personal', 'main', MAIN.slice(0, 12), 'SHA'])
+ expect(text).not.toContain(technical);
+ });
+
+ it('says when an official release is not in the personal version yet', async () => {
+ await show({
+ source: { mainCommit: 'b'.repeat(40), personalAhead: 2, personalBehind: 0 },
+ latestVersion: { ...latest, ref: 'v0.9.4', ahead: 0, behind: 5 },
+ });
+ expect(screen.getByText('正式版 v0.9.4')).toBeTruthy();
+ expect(screen.getByRole('status').textContent).toBe('个人版还没包含');
+ expect(screen.getByRole('status').className).toContain('--upgrade-banner-fg');
+ });
+
+ it.each([
+ [{ changes: 0, source: { personalAhead: 0 } }, '官方 v0.9.3,还没有你的修改'],
+ // Changes made on another computer are not in this computer's history.
+ [{ changes: 0 }, '官方 v0.9.3 + 你的修改'],
+ [{ source: { channel: 'dev' as const, ref: 'main' } }, '官方开发中的版本 + 你的修改'],
+ ])('names the basis of the personal version (%o)', async (props, expected) => {
+ await show(props);
+ expect(screen.getByText(expected)).toBeTruthy();
+ });
+
+ it('never claims the version is included when the lookup failed', async () => {
+ await show({ latestVersion: { status: 'unavailable', channel: 'release' } });
+ expect(screen.getByText('暂时查不到')).toBeTruthy();
+ expect(screen.getByRole('status').textContent).toBe('还不能确认个人版是否已包含');
+ expect(screen.getByRole('status').className).not.toContain('--status-success');
+ });
+
+ it.each(Object.keys(locales) as (keyof typeof locales)[])(
+ 'renders complete copy in %s',
+ async (locale) => {
+ const { container } = await show({ changes: 1 }, locale);
+ expect(container.textContent).not.toMatch(/cindyMake\.|\{\{/);
+ },
+ );
+});
diff --git a/apps/desktop/src/renderer/components/cindy-make/useCindyMakeMergeResolution.ts b/apps/desktop/src/renderer/components/cindy-make/useCindyMakeMergeResolution.ts
deleted file mode 100644
index 035805e03e..0000000000
--- a/apps/desktop/src/renderer/components/cindy-make/useCindyMakeMergeResolution.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { useEffect, useRef, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
-import { useTranslation } from 'react-i18next';
-import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
-import {
- getDataOwnerGeneration,
- isDataOwnerGenerationCurrent,
-} from '@/contexts/dataOwnerGeneration';
-import { isSelectableVendor } from '@/lib/agentVendors';
-import { toast } from '@/lib/toast';
-import type { CindyMakeMergeState } from '../../../shared/cindyMakeMerge';
-import type { CindyMakeTaskOptions } from '../../../shared/cindyMakeDoctor';
-
-/** Fresh and retained conflicts use the same decision before starting a resolution task. */
-export function useCindyMakeMergeResolution() {
- const { t } = useTranslation();
- const { confirm } = useConfirmDialog();
- const navigate = useNavigate();
- const submitting = useRef(false);
- const lifetime = useRef<AbortController | undefined>(undefined);
- const [busy, setBusy] = useState(false);
- const generation = getDataOwnerGeneration();
- useEffect(() => {
- const controller = new AbortController();
- lifetime.current = controller;
- submitting.current = false;
- setBusy(false);
- return () => controller.abort();
- }, [generation.dataOwnerId, generation.generation]);
-
- const resolveMerge = async (state: CindyMakeMergeState, options?: CindyMakeTaskOptions) => {
- const signal = lifetime.current?.signal;
- if (submitting.current || !signal || signal.aborted) return;
- const owner = getDataOwnerGeneration();
- const isCurrent = () => !signal.aborted && isDataOwnerGenerationCurrent(owner);
- submitting.current = true;
- setBusy(true);
- try {
- let confirmed = !state.cancellationRequested && state.error !== 'cancelFailed';
- if (confirmed && !state.feature && !state.sessionId && state.status === 'conflict') {
- confirmed = await confirm(
- {
- presentation: 'standard',
- title: t('cindyMake.merge.conflictConfirm.title'),
- description: t('cindyMake.merge.conflictConfirm.description'),
- confirmText: t('cindyMake.merge.conflictConfirm.confirm'),
- cancelText: t('cindyMake.merge.conflictConfirm.cancel'),
- },
- signal,
- );
- }
- // Leaving Settings or changing accounts dismisses the prompt without discarding work.
- if (!isCurrent()) return;
- if (confirmed && !options) {
- const draftState = await import('@/state/newMakerDraft');
- if (!isCurrent()) return;
- const draft = draftState.getDraft();
- const vendor = isSelectableVendor(draft.vendor) ? draft.vendor : 'cc';
- const prefs = draft.lastByVendor[vendor];
- options = {
- agentKind: vendor,
- model: prefs.model,
- effort: prefs.effort,
- providerId: prefs.providerId,
- permissionMode: prefs.permissionMode,
- fastMode: draftState.getFastModeForModel(prefs.model),
- planModeEnabled: false,
- };
- }
- const result = await window.electronAPI.cindyMakeMerge({
- action: confirmed ? 'resolve' : 'cancel',
- operationId: state.id,
- ...(confirmed ? { createOptions: options } : {}),
- });
- if (!isCurrent()) return;
- if (result?.status === 'failed') {
- toast.error(
- t(
- result.error
- ? `cindyMake.merge.errors.${result.error}`
- : 'cindyMake.merge.status.failed',
- ),
- );
- } else if (confirmed) {
- if (result?.sessionId) navigate(`/cc-agent/${result.sessionId}`);
- else if (result?.status !== 'merged') toast.error(t('cindyMake.merge.errors.startFailed'));
- }
- } catch {
- if (isCurrent()) toast.error(t('cindyMake.merge.errors.unavailable'));
- } finally {
- if (lifetime.current?.signal === signal) {
- submitting.current = false;
- if (!signal.aborted) setBusy(false);
- }
- }
- };
- return { resolveMerge, busy };
-}
diff --git a/apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx b/apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx
index 3252e90eb8..b9417f1329 100644
--- a/apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx
@@ -1,5 +1,5 @@
import { useEffect, useId, useRef, useState } from 'react';
-import { FolderOpen, Download, Trash2, Wrench } from 'lucide-react';
+import { FolderOpen, RefreshCw, Trash2, Wrench } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Switch } from '@/components/ui/switch';
@@ -9,15 +9,20 @@ import { Spinner } from '@/components/ui/spinner';
import { Tip } from '@/components/ui/tooltip';
import { MakeDoctorReportCard } from '@/components/chat/CindyMakeDoctorCard';
import { CindyMakeSourceDetails } from '@/components/cindy-make/CindyMakeSourceDetails';
+import { CindyMakeVersionSummary } from '@/components/cindy-make/CindyMakeVersionSummary';
import { CindyMakeCreateDialog } from '@/components/cindy-make/CindyMakeCreateDialog';
import { CindyMakeDependencyProgress } from '@/components/cindy-make/CindyMakeDependencyProgress';
import { CindyMakeHistoryPanel } from '@/components/cindy-make/CindyMakeHistoryPanel';
import { CindyMakeVersionsPanel } from '@/components/cindy-make/CindyMakeVersionsPanel';
import {
- CindyMakeMergeActions,
- CindyMakeMergeNotice,
-} from '@/components/cindy-make/CindyMakeMergeNotice';
-import { useCindyMakeMergeResolution } from '@/components/cindy-make/useCindyMakeMergeResolution';
+ CindyMakeSyncStatus,
+ cindyMakeSyncTaskOptions,
+} from '@/components/cindy-make/CindyMakeSync';
+import {
+ CindyMakeStorageCard,
+ CindyMakeStorageRow,
+ useCindyMakePersonalRemote,
+} from '@/components/cindy-make/CindyMakePersonalRemote';
import {
getDataOwnerGeneration,
isDataOwnerGenerationCurrent,
@@ -28,11 +33,10 @@ import type { CindyVersionsState } from '../../../shared/cindyVersions';
import { useCindyMakeState } from '@/lib/cindyMakeState';
import { cancelMakeDoctor, startMakeDoctor } from '@/lib/cindyMakeDoctor';
import { useCindyMakeSettings } from '@/lib/cindyMakeSettings';
-import { isSelectableVendor } from '@/lib/agentVendors';
-import { getDraft, getFastModeForModel } from '@/state/newMakerDraft';
import { toast } from '@/lib/toast';
import { extractIpcError } from '@/utils/ipcError';
import type { MakeDoctorReport, MakeSourceStatus } from '../../../shared/cindyMakeDoctor';
+import type { CindyMakeSyncState } from '../../../shared/cindyMakeSync';
const CINDY_MAKE_SETTINGS_TABS = ['versions', 'environment'] as const;
type CindyMakeSettingsTab = (typeof CINDY_MAKE_SETTINGS_TABS)[number];
@@ -43,9 +47,6 @@ export function CindyMakeSection() {
const tabId = useId();
const tabButtons = useRef<Array<HTMLButtonElement | null>>([]);
const { forceManagedTools, setForceManagedTools } = useCindyMakeSettings();
- const [syncLatestBeforeBuild, setSyncLatestBeforeBuild] = useState(false);
- const [syncLatestSettingLoaded, setSyncLatestSettingLoaded] = useState(false);
- const [syncLatestSettingPending, setSyncLatestSettingPending] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [report, setReport] = useState<MakeDoctorReport>();
const makeState = useCindyMakeState();
@@ -66,99 +67,155 @@ export function CindyMakeSection() {
}>();
const sourceStatus = makeState.source;
const [sourceRunPending, setSourceRunPending] = useState(false);
+ const personalRemote = useCindyMakePersonalRemote();
+ const [storageOffered, setStorageOffered] = useState(false);
+ // Saving needs a prepared personal source; prepare it first, then save once it is ready.
+ const [saveAfterPrepare, setSaveAfterPrepare] = useState(false);
+ const saveAfterPrepareStarted = useRef(false);
+ const remoteState = personalRemote.state;
+ const showStorageCard =
+ !!remoteState &&
+ !remoteState.repository &&
+ remoteState.github === 'connected' &&
+ !remoteState.running &&
+ (remoteState.offerMigration || storageOffered || saveAfterPrepare);
const { confirm } = useConfirmDialog();
- const { resolveMerge } = useCindyMakeMergeResolution();
- const mergeSubmitting = useRef(false);
- const previousMergeId = useRef<string | undefined>(undefined);
- const [mergePending, setMergePending] = useState(false);
const operation = makeState.upstreamMerge;
const merge = operation?.feature ? undefined : operation;
const mergeActive = !!operation && ['fetching', 'merging', 'checking'].includes(operation.status);
const mergeBlocked =
- mergePending ||
mergeActive ||
!!operation?.cancellationRequested ||
(!!operation?.hasWorkspace && operation.status !== 'merged');
- const updateSource = async () => {
- if (mergeSubmitting.current || mergeBlocked || buildRunningRef.current) return;
+ const syncState = makeState.personalSync;
+ const [syncPending, setSyncPending] = useState(false);
+ const [abandoning, setAbandoning] = useState(false);
+ // Giving up the conflict Sync waits for keeps both personal versions as they were.
+ const abandonSync = async () => {
+ if (abandoning) return;
const owner = getDataOwnerGeneration();
- mergeSubmitting.current = true;
+ const confirmed = await confirm({
+ title: t('cindyMake.sync.abandon.title'),
+ description: t('cindyMake.sync.abandon.description'),
+ confirmText: t('cindyMake.sync.abandon.confirm'),
+ cancelText: t('cindyMake.sync.abandon.cancel'),
+ confirmVariant: 'destructive',
+ });
+ if (!confirmed || !isDataOwnerGenerationCurrent(owner)) return;
+ setAbandoning(true);
try {
- const confirmed = await confirm({
- title: t('cindyMake.merge.confirmTitle'),
- description: t('cindyMake.merge.confirmDescription'),
- confirmText: t('cindyMake.merge.confirm'),
- cancelText: t('settings.cindyMake.source.resetConfirm.cancel'),
+ await window.electronAPI.cindyMakeSync?.({ action: 'abandon' });
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) toast.error(t('cindyMake.sync.errors.failed'));
+ } finally {
+ setAbandoning(false);
+ }
+ };
+ const [accepting, setAccepting] = useState(false);
+ // Using a result that lost changes is the user's decision; both originals stay backed up.
+ const acceptSync = async () => {
+ if (accepting) return;
+ const owner = getDataOwnerGeneration();
+ const confirmed = await confirm({
+ title: t('cindyMake.sync.accept.title'),
+ description: t('cindyMake.sync.accept.description', {
+ count: syncState?.waiting?.missing ?? 0,
+ }),
+ confirmText: t('cindyMake.sync.accept.confirm'),
+ cancelText: t('cindyMake.sync.accept.cancel'),
+ confirmVariant: 'destructive',
+ });
+ if (!confirmed || !isDataOwnerGenerationCurrent(owner)) return;
+ setAccepting(true);
+ try {
+ await window.electronAPI.cindyMakeSync?.({ action: 'accept' });
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) toast.error(t('cindyMake.sync.errors.failed'));
+ } finally {
+ setAccepting(false);
+ }
+ };
+ const [keeping, setKeeping] = useState<'github' | 'local'>();
+ // Keeping one side replaces the other; both stay backed up, so it asks once.
+ const keepSide = async (side: 'github' | 'local') => {
+ if (keeping) return;
+ const owner = getDataOwnerGeneration();
+ const confirmed = await confirm({
+ title: t(`cindyMake.sync.keep.${side}Title`),
+ description: t(`cindyMake.sync.keep.${side}Description`),
+ confirmText: t(`cindyMake.sync.keep.${side}`),
+ cancelText: t('cindyMake.sync.keep.cancel'),
+ confirmVariant: 'destructive',
+ });
+ if (!confirmed || !isDataOwnerGenerationCurrent(owner)) return;
+ setKeeping(side);
+ try {
+ await window.electronAPI.cindyMakeSync?.({
+ action: 'keep',
+ side,
+ createOptions: cindyMakeSyncTaskOptions(),
});
- if (!confirmed || !isDataOwnerGenerationCurrent(owner) || buildRunningRef.current) return;
- previousMergeId.current = operation?.id;
- setMergePending(true);
- const draft = getDraft();
- const vendor = isSelectableVendor(draft.vendor) ? draft.vendor : 'cc';
- const prefs = draft.lastByVendor[vendor];
- const createOptions = {
- agentKind: vendor,
- model: prefs.model,
- effort: prefs.effort,
- providerId: prefs.providerId,
- permissionMode: prefs.permissionMode,
- fastMode: getFastModeForModel(prefs.model),
- planModeEnabled: false,
- };
- const result = await window.electronAPI.cindyMakeMerge({
- action: 'update',
- createOptions,
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) toast.error(t('cindyMake.sync.errors.failed'));
+ } finally {
+ setKeeping(undefined);
+ }
+ };
+ const [generating, setGenerating] = useState(false);
+ const generatePersonal = async () => {
+ if (generating || buildRunningRef.current || !historyState?.canBuild) return;
+ const owner = getDataOwnerGeneration();
+ setGenerating(true);
+ try {
+ await window.electronAPI.generateCindyMakePersonal();
+ } catch {
+ if (isDataOwnerGenerationCurrent(owner)) toast.error(t('cindyMake.history.actionFailed'));
+ } finally {
+ setGenerating(false);
+ }
+ };
+ const personalVersion = versionsState?.versions.find((version) => version.kind === 'personal');
+ const sameCommit = (a?: string, b?: string) =>
+ !!a && !!b && (a.startsWith(b) || b.startsWith(a));
+ // The source moved since the last generation (a Sync, a retrieved change, an undo), or a
+ // computer that never generated has personal changes to use.
+ const needsGenerate =
+ sourceStatus?.status === 'ready' &&
+ !!sourceStatus.commit &&
+ !buildRunning &&
+ !!historyState?.canBuild &&
+ (personalVersion
+ ? !!personalVersion.commit && !sameCommit(personalVersion.commit, sourceStatus.commit)
+ : !!sourceStatus.baseCommit && !sameCommit(sourceStatus.commit, sourceStatus.baseCommit));
+ const syncSubmitting = useRef(false);
+ // One Sync for every personal version; conflicts open their task without another prompt.
+ const startSync = async () => {
+ if (syncSubmitting.current || syncState?.running || buildRunningRef.current) return;
+ const owner = getDataOwnerGeneration();
+ syncSubmitting.current = true;
+ setSyncPending(true);
+ try {
+ await window.electronAPI.cindyMakeSync?.({
+ action: 'sync',
+ createOptions: cindyMakeSyncTaskOptions(),
});
- if (!isDataOwnerGenerationCurrent(owner)) return;
- if (result?.status === 'conflict' && !result.sessionId && !result.feature)
- await resolveMerge(result, createOptions);
- if (result?.status === 'merged') toast.success(t('cindyMake.merge.status.merged'));
- else if (result?.status === 'failed')
- toast.error(
- t(
- result.error
- ? `cindyMake.merge.errors.${result.error}`
- : 'cindyMake.merge.status.failed',
- ),
- );
- // Refresh failure must not turn a completed update into a second, failure toast.
- await window.electronAPI.getCindyMakeSourceStatus().catch(() => undefined);
} catch (error) {
if (isDataOwnerGenerationCurrent(owner))
toast.error(
t(
extractIpcError(error)?.message?.replace(/^\[PRECONDITION_FAILED\]\s*/, '') === 'busy'
- ? 'cindyMake.merge.errors.busy'
- : 'cindyMake.merge.errors.unavailable',
+ ? 'cindyMake.sync.errors.busy'
+ : 'cindyMake.sync.errors.failed',
),
);
} finally {
- mergeSubmitting.current = false;
- setMergePending(false);
+ syncSubmitting.current = false;
+ setSyncPending(false);
}
};
useEffect(() => {
void window.electronAPI.getCindyMakeSourceStatus?.().catch(() => undefined);
}, []);
- useEffect(() => {
- const load = window.electronAPI.getCindyMakeSettings;
- if (!load) {
- setSyncLatestSettingLoaded(true);
- return;
- }
- let current = true;
- void load()
- .then((settings) => {
- if (current) setSyncLatestBeforeBuild(settings.syncLatestBeforeBuild);
- })
- .catch(() => undefined)
- .finally(() => {
- if (current) setSyncLatestSettingLoaded(true);
- });
- return () => {
- current = false;
- };
- }, []);
const previousSourceStatus = useRef(sourceStatus?.status);
useEffect(() => {
const previous = previousSourceStatus.current;
@@ -201,6 +258,19 @@ export function CindyMakeSection() {
return () => controller.abort();
}, [forceManagedTools, checkVersion, runMode, runVersion]);
const sourceBusy = sourceRunPending || sourceStatus?.status === 'preparing';
+ useEffect(() => {
+ if (!saveAfterPrepare) return;
+ const status = sourceStatus?.status;
+ if (status === 'preparing') saveAfterPrepareStarted.current = true;
+ if (status === 'ready' && !sourceRunPending) {
+ setSaveAfterPrepare(false);
+ void personalRemote.act('save');
+ } else if (
+ saveAfterPrepareStarted.current &&
+ (status === 'failed' || status === 'cancelled')
+ )
+ setSaveAfterPrepare(false);
+ }, [saveAfterPrepare, sourceStatus?.status, sourceRunPending, personalRemote.act]);
const preparation = makeState.environmentPrepare;
const check = makeState.environmentCheck;
useEffect(() => {
@@ -385,37 +455,29 @@ export function CindyMakeSection() {
<Button className="self-start" onClick={() => setCreateOpen(true)}>
{t('settings.cindyMake.create.title')}
</Button>
- <div className="flex items-start justify-between gap-4 rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] p-5">
- <div className="min-w-0">
- <p className="text-13 font-medium text-[var(--settings-section-sublabel)]">
- {t('settings.cindyMake.syncBeforeBuild.title')}
- </p>
- <p className="mt-1 text-12 leading-[1.45] text-[var(--settings-section-desc)]">
- {t('settings.cindyMake.syncBeforeBuild.description')}
- </p>
- </div>
- <Switch
- checked={syncLatestBeforeBuild}
- disabled={!syncLatestSettingLoaded || syncLatestSettingPending}
- onCheckedChange={(checked) => {
- if (syncLatestSettingPending) return;
- const previous = syncLatestBeforeBuild;
- setSyncLatestBeforeBuild(checked);
- setSyncLatestSettingPending(true);
- void window.electronAPI
- .setCindyMakeSyncLatestBeforeBuild(checked)
- .then((settings) => {
- setSyncLatestBeforeBuild(settings.syncLatestBeforeBuild);
- })
- .catch(() => {
- setSyncLatestBeforeBuild(previous);
- toast.error(t('settings.cindyMake.syncBeforeBuild.saveFailed'));
- })
- .finally(() => setSyncLatestSettingPending(false));
+ {showStorageCard && remoteState && (
+ <CindyMakeStorageCard
+ state={remoteState}
+ pending={personalRemote.pending}
+ preparing={saveAfterPrepare}
+ onSave={() => {
+ setStorageOffered(false);
+ if (sourceStatus?.status === 'ready') {
+ void personalRemote.act('save');
+ return;
+ }
+ if (sourceBusy) return;
+ saveAfterPrepareStarted.current = false;
+ setSaveAfterPrepare(true);
+ setSourceRunPending(true);
+ setSourceRun({ makeAction: 'prepare-source', forceManagedTools });
+ }}
+ onKeepLocal={() => {
+ setStorageOffered(false);
+ void personalRemote.act('keep-local');
}}
- aria-label={t('settings.cindyMake.syncBeforeBuild.ariaLabel')}
/>
- </div>
+ )}
<CindyMakeVersionsPanel
active={activeTab === 'versions'}
busy={historyState?.activeWork ?? historyState?.busy}
@@ -433,17 +495,31 @@ export function CindyMakeSection() {
>
<CindyMakeSourceStatusCard
status={sourceStatus}
+ changes={
+ historyState?.items.filter((item) =>
+ ['integrated', 'changed'].includes(item.integration),
+ ).length
+ }
preparing={sourceBusy}
- merge={mergePending && merge?.id === previousMergeId.current ? undefined : merge}
+ merge={merge}
mergeBlocked={mergeBlocked}
buildRunning={buildRunning}
- updating={mergePending || (mergeActive && !!merge)}
+ updating={mergeActive && !!merge}
+ sync={syncState}
+ syncing={syncPending || !!syncState?.running}
+ onSync={() => void startSync()}
+ onAbandon={() => void abandonSync()}
+ abandoning={abandoning}
+ onAccept={() => void acceptSync()}
+ accepting={accepting}
+ needsGenerate={needsGenerate}
+ onGenerate={() => void generatePersonal()}
+ generating={generating}
+ onKeep={(side) => void keepSide(side)}
+ keeping={keeping}
+ onResume={() => void startSync()}
onPrepare={() => {
- if (!sourceStatus || sourceBusy) return;
- if (sourceStatus.status === 'ready') {
- void updateSource();
- return;
- }
+ if (!sourceStatus || sourceBusy || sourceStatus.status === 'ready') return;
setSourceRunPending(true);
setSourceRun({ makeAction: 'prepare-source', forceManagedTools });
}}
@@ -468,12 +544,17 @@ export function CindyMakeSection() {
setSourceRun({ makeAction: 'clear-source', forceManagedTools });
}}
/>
+ <CindyMakeStorageRow
+ state={remoteState}
+ pending={personalRemote.pending}
+ act={personalRemote.act}
+ onOffer={() => setStorageOffered(true)}
+ />
</CindyMakeVersionsPanel>
<CindyMakeHistoryPanel
active={activeTab === 'versions'}
- hasPersonalVersion={versionsState?.versions.some(
- (version) => version.kind === 'personal',
- )}
+ hasPersonalVersion={!!personalVersion}
+ canGenerate={!!personalVersion || needsGenerate}
onState={setHistoryState}
/>
</div>
@@ -484,6 +565,7 @@ export function CindyMakeSection() {
function CindyMakeSourceStatusCard({
status,
+ changes,
preparing = false,
onPrepare,
onStop,
@@ -492,8 +574,23 @@ function CindyMakeSourceStatusCard({
mergeBlocked = false,
buildRunning = false,
updating = false,
+ sync,
+ syncing = false,
+ onSync,
+ onAbandon,
+ abandoning = false,
+ onAccept,
+ accepting = false,
+ needsGenerate = false,
+ onGenerate,
+ generating = false,
+ onKeep,
+ keeping,
+ onResume,
}: {
status?: MakeSourceStatus;
+ /** This computer's changes included in the personal version, from the history. */
+ changes?: number;
preparing?: boolean;
onPrepare?: () => void;
onStop?: () => void;
@@ -502,24 +599,29 @@ function CindyMakeSourceStatusCard({
mergeBlocked?: boolean;
buildRunning?: boolean;
updating?: boolean;
+ sync?: CindyMakeSyncState;
+ /** A Sync request is pending or running. */
+ syncing?: boolean;
+ onSync?: () => void;
+ onAbandon?: () => void;
+ abandoning?: boolean;
+ onAccept?: () => void;
+ accepting?: boolean;
+ needsGenerate?: boolean;
+ onGenerate?: () => void;
+ generating?: boolean;
+ onKeep?: (side: 'github' | 'local') => void;
+ keeping?: 'github' | 'local';
+ onResume?: () => void;
}) {
const { t } = useTranslation();
const displayStatus = preparing ? 'preparing' : status?.status;
// A click is pending before Main publishes the new run. Never reuse the last
// run's phase, counters or error in that window.
const activeStatus = preparing && status?.status === 'preparing' ? status : undefined;
- const displayMerge =
- !preparing &&
- (updating ||
- !status ||
- status.status === 'ready' ||
- merge?.hasWorkspace ||
- merge?.cancellationRequested ||
- merge?.error === 'cancelFailed')
- ? merge?.status === 'merged' || merge?.status === 'cancelled'
- ? undefined
- : merge
- : undefined;
+ // A retained source operation is shown and handled by Sync's line below the summary.
+ const pendingMerge =
+ !!merge && merge.status !== 'merged' && merge.status !== 'cancelled' && !!merge.hasWorkspace;
const statusClass = updating
? 'text-[var(--text-secondary)]'
: displayStatus === 'ready'
@@ -548,72 +650,110 @@ function CindyMakeSourceStatusCard({
{status &&
(status.branch || status.commit || status.status === 'ready') &&
!preparing && (
- <CindyMakeSourceDetails
+ <CindyMakeVersionSummary
source={status}
latestVersion={status.latestVersion}
- showComparison={!updating && !displayMerge && status.status === 'ready'}
+ changes={changes}
+ showComparison={!updating && !pendingMerge && status.status === 'ready'}
/>
)}
+ {status?.status === 'ready' && !preparing && (
+ <div className="mt-2">
+ <CindyMakeSyncStatus
+ state={sync}
+ onAbandon={onAbandon}
+ abandoning={abandoning}
+ onAccept={onAccept}
+ accepting={accepting}
+ needsGenerate={needsGenerate && !sync?.waiting && !sync?.running}
+ onGenerate={onGenerate}
+ generating={generating}
+ onKeep={onKeep}
+ keeping={keeping}
+ onResume={onResume}
+ resuming={syncing}
+ />
+ </div>
+ )}
</div>
<div className="ml-auto flex flex-wrap justify-end gap-2">
- <CindyMakeMergeActions state={displayMerge} busy={updating}>
- {status?.status === 'ready' && onPrepare && (
- <Tip
- text={t(buildRunning ? 'cindyMake.merge.buildingHint' : 'cindyMake.merge.updateHint')}
+ {status?.status === 'ready' && onSync && (
+ <Tip
+ text={t(
+ buildRunning
+ ? 'cindyMake.sync.buildingHint'
+ : sync?.waiting
+ ? 'cindyMake.sync.waitingHint'
+ : 'cindyMake.sync.hint',
+ )}
+ >
+ <Button
+ variant="secondary"
+ className="gap-2"
+ disabled={preparing || updating || buildRunning || syncing || !!sync?.waiting}
+ loading={syncing}
+ onClick={onSync}
>
- <Button
- variant="secondary"
- className="gap-2"
- disabled={preparing || mergeBlocked || buildRunning}
- loading={updating}
- onClick={onPrepare}
- >
- {!updating && <Download size={14} aria-hidden />}
- <span className="relative top-px">{t('cindyMake.merge.getLatest')}</span>
- </Button>
- </Tip>
- )}
- </CindyMakeMergeActions>
+ {!syncing && <RefreshCw size={14} aria-hidden />}
+ <span className="relative top-px">{t('cindyMake.sync.action')}</span>
+ </Button>
+ </Tip>
+ )}
</div>
</div>
{status && (
- <div className="border-t border-[var(--border-default)] pt-3">
- <p className="text-12 text-[var(--text-secondary)]">
- {t('settings.cindyMake.source.path')}
- </p>
- <div className="flex items-center gap-3">
- <p className="min-w-0 flex-1 break-all font-mono text-12 text-[var(--text-secondary)]">
- {status.path}
- </p>
- <div className="ml-auto flex shrink-0 items-center gap-1">
- {status && status.status !== 'missing' && (
- <Tip text={t('settings.cindyMake.source.openDir')}>
- <Button
- variant="secondary"
- className="w-8 border-transparent bg-transparent px-0 text-[var(--text-tertiary)]"
- aria-label={t('settings.cindyMake.source.openDir')}
- onClick={openSourceDir}
- >
- <FolderOpen size={14} aria-hidden />
- </Button>
- </Tip>
- )}
- {onClear && status && !preparing && status.status !== 'missing' && (
- <Tip text={t('settings.cindyMake.source.reset')}>
- <Button
- variant="secondary"
- onClick={() => void onClear()}
- disabled={mergeBlocked}
- aria-label={t('settings.cindyMake.source.reset')}
- className="w-8 border-transparent bg-transparent px-0 text-[var(--text-tertiary)]"
- >
- <Trash2 size={14} aria-hidden />
- </Button>
- </Tip>
- )}
+ <details className="border-t border-[var(--border-default)] pt-1">
+ <summary className="min-h-8 cursor-pointer py-2 text-12 text-[var(--text-secondary)]">
+ {t('cindyMake.summary.technical')}
+ </summary>
+ <div className="space-y-3 pb-1 pt-2">
+ {(status.branch || status.commit || status.status === 'ready') && !preparing && (
+ <CindyMakeSourceDetails
+ source={status}
+ latestVersion={status.latestVersion}
+ showComparison={!updating && !pendingMerge && status.status === 'ready'}
+ announce={false}
+ />
+ )}
+ <div className="space-y-1">
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t('settings.cindyMake.source.path')}
+ </p>
+ <div className="flex items-center gap-3">
+ <p className="min-w-0 flex-1 break-all font-mono text-12 text-[var(--text-secondary)]">
+ {status.path}
+ </p>
+ <div className="ml-auto flex shrink-0 items-center gap-1">
+ {status && status.status !== 'missing' && (
+ <Tip text={t('settings.cindyMake.source.openDir')}>
+ <Button
+ variant="secondary"
+ className="w-8 border-transparent bg-transparent px-0 text-[var(--text-tertiary)]"
+ aria-label={t('settings.cindyMake.source.openDir')}
+ onClick={openSourceDir}
+ >
+ <FolderOpen size={14} aria-hidden />
+ </Button>
+ </Tip>
+ )}
+ {onClear && status && !preparing && status.status !== 'missing' && (
+ <Tip text={t('settings.cindyMake.source.reset')}>
+ <Button
+ variant="secondary"
+ onClick={() => void onClear()}
+ disabled={mergeBlocked}
+ aria-label={t('settings.cindyMake.source.reset')}
+ className="w-8 border-transparent bg-transparent px-0 text-[var(--text-tertiary)]"
+ >
+ <Trash2 size={14} aria-hidden />
+ </Button>
+ </Tip>
+ )}
+ </div>
+ </div>
</div>
</div>
- </div>
+ </details>
)}
{activeStatus?.progress?.message && (
<p className="break-all font-mono text-11 text-[var(--text-tertiary)]">
@@ -621,15 +761,13 @@ function CindyMakeSourceStatusCard({
</p>
)}
</div>
- {displayMerge ? (
- <CindyMakeMergeNotice state={displayMerge} showActions={false} />
- ) : status && (preparing || updating || status.status !== 'ready') ? (
+ {status && (preparing || (updating && !sync?.running) || status.status !== 'ready') ? (
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-[var(--border-default)] px-4 py-3">
<div className={`min-w-0 flex-1 space-y-1 text-13 ${statusClass}`} role="status">
<div>
{t(
updating
- ? 'cindyMake.merge.status.fetching'
+ ? `cindyMake.merge.status.${merge?.status ?? 'fetching'}`
: `settings.cindyMake.source.status.${displayStatus}`,
)}
{activeStatus?.phase ? ` · ${t(`cindyMake.source.phase.${activeStatus.phase}`)}` : ''}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CindyMakeSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CindyMakeSection.test.tsx
index d79184fb6f..8fa7a0689b 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/CindyMakeSection.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/CindyMakeSection.test.tsx
@@ -6,6 +6,7 @@ import { isValidElement } from 'react';
import { CindyMakeSection } from '../CindyMakeSection';
import type { CindyMakeMergeState, CindyMakeMergeRequest } from '../../../../shared/cindyMakeMerge';
import type { CindyMakePersonalBuildState } from '../../../../shared/cindyMakeSession';
+import type { CindyMakeSyncRequest, CindyMakeSyncState } from '../../../../shared/cindyMakeSync';
import { startMakeDoctor } from '@/lib/cindyMakeDoctor';
import { setCindyMakeForceManagedTools } from '@/lib/cindyMakeSettings';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
@@ -47,7 +48,12 @@ type Listener = Parameters<NonNullable<Api>['onDesktopCommandTriggered']>[0];
type Result = Awaited<ReturnType<NonNullable<Api>['executeDesktopCommand']>>;
function harness(
- history: { busy: boolean; activeWork?: boolean; build?: CindyMakePersonalBuildState } = {
+ history: {
+ busy: boolean;
+ activeWork?: boolean;
+ build?: CindyMakePersonalBuildState;
+ canBuild?: boolean;
+ } = {
busy: false,
},
) {
@@ -65,6 +71,12 @@ function harness(
async (_request: CindyMakeMergeRequest): Promise<CindyMakeMergeState | undefined> =>
undefined,
),
+ cindyMakeSync: vi.fn(
+ async (_request: CindyMakeSyncRequest): Promise<CindyMakeSyncState> => ({
+ running: true,
+ step: 'resuming',
+ }),
+ ),
getCindyMakeState: vi.fn(async (): Promise<CindyMakeGlobalState> => ({
...globalState,
source: globalState.source ?? (await api.getCindyMakeSourceStatus()),
@@ -100,8 +112,8 @@ function harness(
};
vi.stubGlobal('electronAPI', {
getCindyMakeHistory: async () => ({
- ...history,
canBuild: false,
+ ...history,
items: Object.values(globalState.tasks ?? {})
.filter((report) => report.task)
.map((report) => ({
@@ -123,6 +135,7 @@ function harness(
getCindyMakeSettings: api.getCindyMakeSettings,
setCindyMakeSyncLatestBeforeBuild: api.setCindyMakeSyncLatestBeforeBuild,
cindyMakeMerge: api.cindyMakeMerge,
+ cindyMakeSync: api.cindyMakeSync,
maker: api,
getCindyMakeState: api.getCindyMakeState,
onCindyMakeState: api.onCindyMakeState,
@@ -234,11 +247,11 @@ describe('Settings > Cindy Make', () => {
{ name: 'settings.cindyMake.source.title' },
),
).toBeTruthy();
- const syncBeforeBuild = await screen.findByRole('switch', {
- name: 'settings.cindyMake.syncBeforeBuild.ariaLabel',
- });
- expect(syncBeforeBuild.getAttribute('aria-checked')).toBe('false');
expect(await screen.findByText('0.1.99')).toBeTruthy();
+ // Sync is the one place the personal version moves; generating has no sync switch.
+ expect(
+ screen.queryByRole('switch', { name: 'settings.cindyMake.syncBeforeBuild.ariaLabel' }),
+ ).toBeNull();
const create =
within(screen.getByRole('tabpanel', { name: 'settings.cindyMake.tabs.versions' })).getByRole(
'button',
@@ -278,20 +291,6 @@ describe('Settings > Cindy Make', () => {
await waitFor(() => expect(getVersions).toHaveBeenCalledTimes(3));
expect(h.starts()).toHaveLength(1);
});
- it('persists the opt-in build-time source sync and updates the switch immediately', async () => {
- const h = harness();
- renderVersions(<CindyMakeSection />);
- const toggle = await screen.findByRole('switch', {
- name: 'settings.cindyMake.syncBeforeBuild.ariaLabel',
- });
-
- fireEvent.click(toggle);
-
- expect(toggle.getAttribute('aria-checked')).toBe('true');
- await waitFor(() =>
- expect(h.api.setCindyMakeSyncLatestBeforeBuild).toHaveBeenCalledWith(true),
- );
- });
it('keeps background preparation, expansion and task search intact while switching tabs', async () => {
const h = harness();
renderVersions(
@@ -356,7 +355,33 @@ describe('Settings > Cindy Make', () => {
).toBe(false);
expect(h.api.cancelCindyMakeSource).not.toHaveBeenCalled();
});
- it('keeps only the update icon, confirms it and does nothing on cancel', async () => {
+ it('leads with a plain-language summary and keeps hashes and the source folder in collapsed technical details', async () => {
+ const h = harness();
+ h.api.getCindyMakeSourceStatus.mockResolvedValue({
+ status: 'ready',
+ path: '/managed/source',
+ ref: 'main',
+ commit: 'a'.repeat(40),
+ mainCommit: 'c'.repeat(40),
+ } satisfies MakeSourceStatus);
+ renderVersions(<CindyMakeSection />);
+ const card = await screen.findByRole('region', { name: 'settings.cindyMake.source.title' });
+ await waitFor(() => expect(within(card).getByText('cindyMake.summary.personal')).toBeTruthy());
+ const details = within(card)
+ .getByText('cindyMake.summary.technical')
+ .closest('details') as HTMLDetailsElement;
+ expect(details.open).toBe(false);
+ // The summary sits outside the technical details; hashes, local main and the folder sit inside.
+ expect(details.contains(within(card).getByText('cindyMake.summary.personal'))).toBe(false);
+ expect(details.contains(within(card).getByText('cindyMake.overview.localMain'))).toBe(true);
+ expect(details.contains(within(card).getByText('/managed/source'))).toBe(true);
+ expect(
+ details.contains(
+ within(card).getByRole('button', { name: 'settings.cindyMake.source.reset' }),
+ ),
+ ).toBe(true);
+ });
+ it('starts one Sync without another confirmation and passes the Agent preferences', async () => {
const h = harness();
const source: MakeSourceStatus = {
status: 'ready',
@@ -366,29 +391,18 @@ describe('Settings > Cindy Make', () => {
};
h.api.getCindyMakeSourceStatus.mockResolvedValue(source);
renderVersions(<CindyMakeSection />);
- const button = await screen.findByRole('button', { name: 'cindyMake.merge.getLatest' });
- expect(screen.getAllByRole('button', { name: 'cindyMake.merge.getLatest' })).toHaveLength(1);
+ const button = await screen.findByRole('button', { name: 'cindyMake.sync.action' });
+ expect(screen.getAllByRole('button', { name: 'cindyMake.sync.action' })).toHaveLength(1);
expect(screen.queryByRole('button', { name: 'settings.cindyMake.source.update' })).toBeNull();
- confirmMerge.mockResolvedValueOnce(false);
fireEvent.click(button);
await waitFor(() =>
- expect(confirmMerge).toHaveBeenCalledWith(
- expect.objectContaining({
- title: 'cindyMake.merge.confirmTitle',
- description: 'cindyMake.merge.confirmDescription',
- }),
- ),
+ expect(h.api.cindyMakeSync).toHaveBeenCalledExactlyOnceWith({
+ action: 'sync',
+ createOptions: expect.objectContaining({ agentKind: 'codex', model: 'test-model' }),
+ }),
);
+ expect(confirmMerge).not.toHaveBeenCalled();
expect(h.api.cindyMakeMerge).not.toHaveBeenCalled();
- fireEvent.click(button);
- await waitFor(() =>
- expect(h.api.cindyMakeMerge).toHaveBeenCalledWith(
- expect.objectContaining({
- action: 'update',
- createOptions: expect.objectContaining({ agentKind: 'codex', model: 'test-model' }),
- }),
- ),
- );
expect(h.starts().filter(([, ctx]) => ctx.makeAction === 'prepare-source')).toHaveLength(0);
});
it.each(['merged', 'failed'] as const)(
@@ -419,13 +433,6 @@ describe('Settings > Cindy Make', () => {
h.api.getCindyMakeSourceStatus.mockResolvedValue(source);
const view = renderVersions(<CindyMakeSection />);
await h.pushState({ source, upstreamMerge: previous });
- let finish!: (state: CindyMakeMergeState) => void;
- h.api.cindyMakeMerge.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- finish = resolve;
- }),
- );
const card = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
const expectVersionsVisible = (region: HTMLElement) => {
for (const commit of ['a', 'c']) {
@@ -436,23 +443,22 @@ describe('Settings > Cindy Make', () => {
expect(within(region).getByText(/cindyMake.source.details.latest.behind/)).toBeTruthy();
};
expectVersionsVisible(card);
- fireEvent.click(within(card).getByRole('button', { name: 'cindyMake.merge.getLatest' }));
- await waitFor(() => expect(h.api.cindyMakeMerge).toHaveBeenCalledOnce());
+ fireEvent.click(within(card).getByRole('button', { name: 'cindyMake.sync.action' }));
+ await waitFor(() => expect(h.api.cindyMakeSync).toHaveBeenCalledOnce());
expectVersionsVisible(card);
- expect(within(card).getByRole('status').textContent).toBe('cindyMake.merge.status.fetching');
expect(within(card).queryByText('cindyMake.merge.status.merged')).toBeNull();
const current = { ...previous, id: 'current-update' };
+ const running = { running: true, step: 'official' as const };
for (const status of ['fetching', 'merging', 'checking'] as const) {
- await h.pushState({ source, upstreamMerge: { ...current, status } });
+ await h.pushState({ source, upstreamMerge: { ...current, status }, personalSync: running });
+ expect(within(card).getByText('cindyMake.sync.step.official')).toBeTruthy();
expectVersionsVisible(card);
- expect(within(card).getAllByRole('status')).toHaveLength(1);
- expect(within(card).getByRole('status').textContent).toBe(
- 'cindyMake.merge.status.' + status,
- );
+ // One line says what Sync does; no second, technical status for the same work.
+ expect(within(card).queryByText('cindyMake.merge.status.' + status)).toBeNull();
expect(within(card).queryByText('settings.cindyMake.source.status.ready')).toBeNull();
expect(
within(card)
- .getByRole('button', { name: 'cindyMake.merge.getLatest' })
+ .getByRole('button', { name: 'cindyMake.sync.action' })
.getAttribute('aria-busy'),
).toBe('true');
}
@@ -461,36 +467,31 @@ describe('Settings > Cindy Make', () => {
status: result,
...(result === 'failed' ? { error: 'gitFailed' as const } : {}),
};
- await h.pushState({ source, upstreamMerge: finalState });
- if (result === 'failed')
- expect(within(card).getByText('cindyMake.merge.status.failed')).toBeTruthy();
- if (result === 'merged')
- h.api.getCindyMakeSourceStatus.mockRejectedValueOnce(new Error('refresh failed'));
- await act(async () => finish(finalState));
- const notify = result === 'merged' ? toast.success : toast.error;
- expect(notify).toHaveBeenCalledExactlyOnceWith(
- result === 'merged' ? 'cindyMake.merge.status.merged' : 'cindyMake.merge.errors.gitFailed',
- );
- expect(result === 'merged' ? toast.error : toast.success).not.toHaveBeenCalled();
- await h.pushState({ source, upstreamMerge: finalState });
+ const ended: CindyMakeSyncState =
+ result === 'merged'
+ ? { done: { at: 1, ref: 'main' } }
+ : { error: 'failed' };
+ await h.pushState({ source, upstreamMerge: finalState, personalSync: ended });
+ if (result === 'failed') {
+ expect(within(card).queryByText('cindyMake.merge.status.failed')).toBeNull();
+ expect(within(card).getByText('cindyMake.sync.errors.failed')).toBeTruthy();
+ } else expect(within(card).getByText('cindyMake.sync.doneDevelopment')).toBeTruthy();
+ // The result stays in the card; Sync does not add a toast on top.
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(toast.error).not.toHaveBeenCalled();
view.unmount();
renderVersions(<CindyMakeSection />);
const reopened = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
await waitFor(() =>
expect(
within(reopened).getByText(
- result === 'merged'
- ? 'cindyMake.overview.comparison.different'
- : 'cindyMake.merge.status.failed',
+ result === 'merged' ? 'cindyMake.sync.doneDevelopment' : 'cindyMake.sync.errors.failed',
),
).toBeTruthy(),
);
expectVersionsVisible(reopened);
expect(within(reopened).getAllByRole('status')).toHaveLength(1);
expect(within(reopened).queryByText('settings.cindyMake.source.status.ready')).toBeNull();
- if (result === 'failed')
- expect(within(reopened).getByText('cindyMake.merge.errors.gitFailed')).toBeTruthy();
- expect(notify).toHaveBeenCalledTimes(1);
},
);
it('shows the source card immediately and keeps local details visible while the latest lookup waits', async () => {
@@ -507,7 +508,7 @@ describe('Settings > Cindy Make', () => {
expect(
within(card).queryByRole('button', { name: 'settings.cindyMake.source.prepare' }),
).toBeNull();
- expect(within(card).queryByRole('button', { name: 'cindyMake.merge.getLatest' })).toBeNull();
+ expect(within(card).queryByRole('button', { name: 'cindyMake.sync.action' })).toBeNull();
const source: MakeSourceStatus = {
status: 'ready',
@@ -518,7 +519,7 @@ describe('Settings > Cindy Make', () => {
await h.pushState({ source });
expect(within(card).getByText(source.path)).toBeTruthy();
expect(within(card).getByText('a'.repeat(12))).toBeTruthy();
- expect(within(card).getByRole('button', { name: 'cindyMake.merge.getLatest' })).toBeTruthy();
+ expect(within(card).getByRole('button', { name: 'cindyMake.sync.action' })).toBeTruthy();
await act(async () =>
finish({
...source,
@@ -555,7 +556,7 @@ describe('Settings > Cindy Make', () => {
expect(within(card).queryByText('cindyMake.merge.status.merged')).toBeNull();
expect(within(card).queryByText('settings.cindyMake.source.status.ready')).toBeNull();
- for (const status of ['fetching', 'merging', 'checking', 'conflict', 'resolving'] as const) {
+ for (const status of ['fetching', 'merging', 'checking'] as const) {
await h.pushState({
source,
upstreamMerge: { ...merge, status, hasWorkspace: true },
@@ -565,6 +566,14 @@ describe('Settings > Cindy Make', () => {
expect(within(card).getByRole('status').textContent).toBe(`cindyMake.merge.status.${status}`);
expect(within(card).queryByText('cindyMake.overview.comparison.mainAhead')).toBeNull();
}
+ // A conflict waits on Sync's line, whoever started the update.
+ await h.pushState({
+ source,
+ upstreamMerge: { ...merge, status: 'resolving', hasWorkspace: true, sessionId: 'task' },
+ personalSync: { waiting: { kind: 'official', reason: 'working', sessionId: 'task' } },
+ });
+ expect(within(card).getByText('cindyMake.sync.waiting.working.official')).toBeTruthy();
+ expect(within(card).queryByText('cindyMake.overview.comparison.mainAhead')).toBeNull();
await h.pushState({
source: { ...source, commit: 'd'.repeat(40), mainCommit: 'd'.repeat(40), personalBehind: 0 },
upstreamMerge: { ...merge, status: 'merged' },
@@ -572,8 +581,9 @@ describe('Settings > Cindy Make', () => {
expect(within(card).getAllByText('d'.repeat(12))).toHaveLength(1);
expect(within(card).queryByText('b'.repeat(12))).toBeNull();
expect(within(card).queryByText('c'.repeat(12))).toBeNull();
- expect(within(card).getByRole('status').getAttribute('aria-label')).toBe(
- 'cindyMake.overview.personal · cindyMake.overview.personalStatus.unverified',
+ // The plain-language summary announces the status; the technical comparison stays silent.
+ expect(within(card).getByRole('status').textContent).toBe(
+ 'cindyMake.summary.included.unverified',
);
expect(within(card).getByText('cindyMake.overview.comparison.same')).toBeTruthy();
expect(within(card).queryByText('cindyMake.merge.status.merged')).toBeNull();
@@ -600,10 +610,7 @@ describe('Settings > Cindy Make', () => {
},
});
const card = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
- expect(within(card).getByRole('status').textContent).toContain(
- 'cindyMake.merge.errors.gitFailed',
- );
- expect(within(card).queryByText('settings.cindyMake.source.status.ready')).toBeNull();
+ expect(within(card).queryByText('cindyMake.merge.errors.gitFailed')).toBeNull();
await h.pushSource(source);
expect(within(card).getByRole('status').textContent).toContain(
@@ -634,109 +641,47 @@ describe('Settings > Cindy Make', () => {
expect(h.api.cancelCindyMakeSource).toHaveBeenCalledTimes(1);
},
);
- it.each([true, false])(
- 'waits for the second confirmation after an update conflicts (confirm=%s)',
- async (confirmed) => {
- const h = harness();
- const source: MakeSourceStatus = { status: 'ready', path: '/managed/source', ref: 'main' };
- const conflict: CindyMakeMergeState = {
+ it('lets a Sync conflict continue in its task without asking again', async () => {
+ const h = harness();
+ const source: MakeSourceStatus = { status: 'ready', path: '/managed/source', ref: 'main' };
+ renderVersions(<CindyMakeSection />);
+ await h.pushState({
+ source,
+ upstreamMerge: {
id: 'update-conflict',
- status: 'conflict',
- ref: 'main',
- upstreamCommit: 'a'.repeat(40),
- hasWorkspace: true,
- };
- const result: CindyMakeMergeState = confirmed
- ? { ...conflict, status: 'resolving', sessionId: 'merge-task' }
- : { ...conflict, status: 'cancelled', hasWorkspace: false };
- let decide!: (confirmed: boolean) => void;
- confirmMerge.mockResolvedValueOnce(true).mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- decide = resolve;
- }),
- );
- h.api.cindyMakeMerge.mockResolvedValueOnce(conflict).mockResolvedValueOnce(result);
- function Location() {
- return <output data-testid="location">{useLocation().pathname}</output>;
- }
- renderVersions(
- <>
- <CindyMakeSection />
- <Location />
- </>,
- );
- await h.pushSource(source);
- const update = screen.getByRole('button', { name: 'cindyMake.merge.getLatest' });
- fireEvent.click(update);
- await waitFor(() => expect(confirmMerge).toHaveBeenCalledTimes(2));
- expect(confirmMerge.mock.calls[1][0]).toMatchObject({
- title: 'cindyMake.merge.conflictConfirm.title',
- description: 'cindyMake.merge.conflictConfirm.description',
- confirmText: 'cindyMake.merge.conflictConfirm.confirm',
- cancelText: 'cindyMake.merge.conflictConfirm.cancel',
- });
- await h.pushState({ source, upstreamMerge: conflict });
- expect(h.api.cindyMakeMerge).toHaveBeenCalledTimes(1);
- fireEvent.click(update);
- fireEvent.click(screen.getByRole('button', { name: 'cindyMake.merge.resolve' }));
- expect(confirmMerge).toHaveBeenCalledTimes(2);
- expect(screen.getByTestId('location').textContent).toBe('/');
- await act(async () => decide(confirmed));
- await waitFor(() => expect(h.api.cindyMakeMerge).toHaveBeenCalledTimes(2));
- expect(h.api.cindyMakeMerge.mock.calls[1][0]).toEqual(
- confirmed
- ? {
- action: 'resolve',
- operationId: conflict.id,
- createOptions: expect.objectContaining({ agentKind: 'codex', model: 'test-model' }),
- }
- : { action: 'cancel', operationId: conflict.id },
- );
- await h.pushState({ source, upstreamMerge: result });
- expect(screen.getByTestId('location').textContent).toBe(
- confirmed ? '/cc-agent/merge-task' : '/',
- );
- if (!confirmed) {
- expect(
- screen
- .getByRole('button', { name: 'cindyMake.merge.getLatest' })
- .hasAttribute('disabled'),
- ).toBe(false);
- expect(screen.queryByText('cindyMake.merge.status.conflict')).toBeNull();
- expect(screen.queryByRole('button', { name: 'cindyMake.merge.resolve' })).toBeNull();
- }
- },
- );
- it.each(['unmount', 'account'] as const)(
- 'does not apply a conflict decision after %s',
- async (change) => {
- const h = harness();
- const source: MakeSourceStatus = { status: 'ready', path: '/managed/source', ref: 'main' };
- h.api.cindyMakeMerge.mockResolvedValue({
- id: 'conflict',
- status: 'conflict',
+ status: 'resolving',
ref: 'main',
upstreamCommit: 'a'.repeat(40),
hasWorkspace: true,
- });
- let decide!: (confirmed: boolean) => void;
- confirmMerge.mockResolvedValueOnce(true).mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- decide = resolve;
- }),
- );
- const view = renderVersions(<CindyMakeSection />);
- await h.pushSource(source);
- fireEvent.click(screen.getByRole('button', { name: 'cindyMake.merge.getLatest' }));
- await waitFor(() => expect(confirmMerge).toHaveBeenCalledTimes(2));
- if (change === 'unmount') view.unmount();
- else await act(async () => setDataOwnerGeneration('another-owner'));
- await act(async () => decide(false));
- expect(h.api.cindyMakeMerge).toHaveBeenCalledTimes(1);
- },
- );
+ sessionId: 'merge-task',
+ },
+ personalSync: {
+ waiting: { kind: 'official', reason: 'working', sessionId: 'merge-task' },
+ },
+ });
+ const card = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
+ expect(within(card).getByText('cindyMake.sync.waiting.working.official')).toBeTruthy();
+ expect(within(card).getByRole('button', { name: 'cindyMake.merge.openTask' })).toBeTruthy();
+ // Sync itself waits: pressing it again would only show the same conflict.
+ expect(
+ within(card).getByRole('button', { name: 'cindyMake.sync.action' }).hasAttribute('disabled'),
+ ).toBe(true);
+ expect(confirmMerge).not.toHaveBeenCalled();
+
+ // Abandoning asks once, then gives the decision to Main.
+ confirmMerge.mockResolvedValueOnce(false);
+ fireEvent.click(within(card).getByRole('button', { name: 'cindyMake.sync.abandon.action' }));
+ await waitFor(() => expect(confirmMerge).toHaveBeenCalledOnce());
+ expect(h.api.cindyMakeSync).not.toHaveBeenCalled();
+ fireEvent.click(within(card).getByRole('button', { name: 'cindyMake.sync.abandon.action' }));
+ await waitFor(() =>
+ expect(h.api.cindyMakeSync).toHaveBeenCalledExactlyOnceWith({ action: 'abandon' }),
+ );
+ expect(confirmMerge.mock.calls[1][0]).toMatchObject({
+ title: 'cindyMake.sync.abandon.title',
+ confirmVariant: 'destructive',
+ });
+ });
it('allows version switching with retained conflicts and during active work', async () => {
const history = { busy: true, activeWork: false };
const h = harness(history);
@@ -778,92 +723,112 @@ describe('Settings > Cindy Make', () => {
history.activeWork = false;
await h.pushState({ source, upstreamMerge: { ...conflict } });
await waitFor(() => expect(button.hasAttribute('disabled')).toBe(false));
- expect(screen.getByRole('button', { name: 'cindyMake.merge.resolve' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'cindyMake.merge.resolve' })).toBeNull();
});
- it('offers conflict resolution only after a conflict and creates a task only on confirmation', async () => {
- const h = harness();
- const source: MakeSourceStatus = { status: 'ready', path: '/managed/source', ref: 'main' };
- const merge: CindyMakeMergeState = {
- id: 'merge',
- status: 'conflict',
- ref: 'main',
- upstreamCommit: 'a'.repeat(40),
- hasWorkspace: true,
+ it('offers generating once the personal version changed since it was last generated', async () => {
+ const h = harness({ busy: false, canBuild: true });
+ const versions = {
+ currentId: 'original',
+ selectedId: 'original',
+ switching: false,
+ versions: [
+ { id: 'original', kind: 'original', available: true, compatible: true },
+ { id: 'personal', kind: 'personal', available: true, compatible: true, commit: 'b'.repeat(40) },
+ ],
};
+ const generate = vi.fn(async () => ({ items: [], busy: false, canBuild: false }));
+ vi.stubGlobal('electronAPI', {
+ ...window.electronAPI,
+ getCindyVersions: async () => versions,
+ generateCindyMakePersonal: generate,
+ });
renderVersions(
<MemoryRouter>
<CindyMakeSection />
</MemoryRouter>,
);
- await h.pushState({ source, upstreamMerge: merge });
+ await h.pushState({
+ source: {
+ status: 'ready',
+ path: '/managed/source',
+ ref: 'main',
+ commit: 'c'.repeat(40),
+ baseCommit: 'a'.repeat(40),
+ },
+ personalSync: { done: { at: 1, ref: 'main' } },
+ });
const card = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
- expect(within(card).getByRole('status').textContent).toBe('cindyMake.merge.status.conflict');
- expect(within(card).queryByText('settings.cindyMake.source.status.ready')).toBeNull();
- expect(h.api.cindyMakeMerge).not.toHaveBeenCalled();
- expect(screen.queryByRole('button', { name: 'cindyMake.merge.getLatest' })).toBeNull();
- const resolve = screen.getByRole('button', { name: 'cindyMake.merge.resolve' });
- expect(resolve.hasAttribute('disabled')).toBe(false);
- expect(within(card).getAllByRole('button', { name: 'cindyMake.merge.resolve' })).toHaveLength(
- 1,
+ expect(await within(card).findByText('cindyMake.sync.needsGenerate')).toBeTruthy();
+ fireEvent.click(
+ within(card).getByRole('button', { name: 'cindyMake.history.generatePersonal' }),
);
- expect(
- resolve.compareDocumentPosition(within(card).getByText('settings.cindyMake.source.path')) &
- Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- await h.pushSource({ ...source, status: 'failed', error: 'dirty' });
- expect(within(card).getByRole('status').textContent).toBe('cindyMake.merge.status.conflict');
- expect(
- within(card).queryByRole('button', { name: 'settings.cindyMake.source.retry' }),
- ).toBeNull();
- h.api.cindyMakeMerge.mockResolvedValue({
- ...merge,
- status: 'resolving',
- sessionId: 'merge-task',
+ await waitFor(() => expect(generate).toHaveBeenCalledOnce());
+ });
+ it('lets the user use a result that lost changes, after confirming, from Sync’s line', async () => {
+ const h = harness();
+ const source: MakeSourceStatus = { status: 'ready', path: '/managed/source', ref: 'main' };
+ renderVersions(
+ <MemoryRouter>
+ <CindyMakeSection />
+ </MemoryRouter>,
+ );
+ await h.pushState({
+ source,
+ upstreamMerge: {
+ id: 'merge',
+ status: 'failed',
+ error: 'checksFailed',
+ missing: { count: 2, commits: [] },
+ ref: 'github',
+ upstreamCommit: 'a'.repeat(40),
+ remote: { base: 'b'.repeat(40) },
+ hasWorkspace: true,
+ sessionId: 'merge-task',
+ },
+ personalSync: {
+ waiting: { kind: 'combine', reason: 'missing', missing: 2, sessionId: 'merge-task' },
+ },
});
- fireEvent.click(screen.getByRole('button', { name: 'cindyMake.merge.resolve' }));
+ const card = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
+ expect(within(card).getByText('cindyMake.sync.waiting.missing')).toBeTruthy();
+ // No resolve button of the old lifecycle next to Sync.
+ expect(screen.queryByRole('button', { name: 'cindyMake.merge.resolve' })).toBeNull();
+ confirmMerge.mockResolvedValueOnce(false);
+ fireEvent.click(within(card).getByRole('button', { name: 'cindyMake.sync.accept.action' }));
+ await waitFor(() => expect(confirmMerge).toHaveBeenCalledOnce());
+ expect(h.api.cindyMakeSync).not.toHaveBeenCalled();
+ fireEvent.click(within(card).getByRole('button', { name: 'cindyMake.sync.accept.action' }));
await waitFor(() =>
- expect(h.api.cindyMakeMerge).toHaveBeenCalledWith(
- expect.objectContaining({ action: 'resolve' }),
- ),
+ expect(h.api.cindyMakeSync).toHaveBeenCalledExactlyOnceWith({ action: 'accept' }),
);
+ expect(confirmMerge.mock.calls[1][0]).toMatchObject({
+ title: 'cindyMake.sync.accept.title',
+ confirmVariant: 'destructive',
+ });
+ expect(h.api.cindyMakeMerge).not.toHaveBeenCalled();
});
- it('retries cancellation without asking to resolve, even after the temporary directory is gone', async () => {
+ it('leaves an unfinished cancellation to Sync, which completes it first', async () => {
const h = harness();
const source: MakeSourceStatus = { status: 'ready', path: '/managed/source', ref: 'main' };
- const merge: CindyMakeMergeState = {
- id: 'merge',
- status: 'failed',
- error: 'cancelFailed',
- cancellationRequested: true,
- ref: 'main',
- upstreamCommit: 'a'.repeat(40),
- hasWorkspace: false,
- };
renderVersions(<CindyMakeSection />);
- await h.pushState({ source, upstreamMerge: merge });
- expect(screen.queryByRole('button', { name: 'cindyMake.merge.getLatest' })).toBeNull();
- expect(screen.queryByRole('button', { name: 'cindyMake.merge.resolve' })).toBeNull();
- await h.pushSource({ ...source, status: 'failed', error: 'dirty' });
- const cancelled: CindyMakeMergeState = {
- ...merge,
- status: 'cancelled',
- error: undefined,
- cancellationRequested: undefined,
- };
- h.api.cindyMakeMerge.mockResolvedValue(cancelled);
- fireEvent.click(screen.getByRole('button', { name: 'cindyMake.merge.retryCancel' }));
+ await h.pushState({
+ source,
+ upstreamMerge: {
+ id: 'merge',
+ status: 'failed',
+ error: 'cancelFailed',
+ cancellationRequested: true,
+ ref: 'main',
+ upstreamCommit: 'a'.repeat(40),
+ hasWorkspace: false,
+ },
+ });
+ expect(screen.queryByRole('button', { name: 'cindyMake.merge.retryCancel' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.sync.action' }));
await waitFor(() =>
- expect(h.api.cindyMakeMerge).toHaveBeenCalledExactlyOnceWith({
- action: 'cancel',
- operationId: merge.id,
- }),
+ expect(h.api.cindyMakeSync).toHaveBeenCalledWith(expect.objectContaining({ action: 'sync' })),
);
- expect(confirmMerge).not.toHaveBeenCalled();
- await h.pushState({ source, upstreamMerge: cancelled });
- expect(
- screen.getByRole('button', { name: 'cindyMake.merge.getLatest' }).hasAttribute('disabled'),
- ).toBe(false);
- expect(screen.queryByText('cindyMake.merge.errors.cancelFailed')).toBeNull();
+ expect(h.api.cindyMakeMerge).not.toHaveBeenCalled();
});
it.each(['resolving', 'failed'] as const)(
'keeps a %s upstream task outside the unfinished production list',
@@ -877,7 +842,17 @@ describe('Settings > Cindy Make', () => {
hasWorkspace: true,
sessionId: 'merge-task',
};
- h.api.getCindyMakeState.mockResolvedValue({ upstreamMerge: merge });
+ h.api.getCindyMakeState.mockResolvedValue({
+ source: { status: 'ready', path: '/managed/source', ref: 'main' },
+ upstreamMerge: merge,
+ personalSync: {
+ waiting: {
+ kind: 'official',
+ reason: status === 'failed' ? 'failed' : 'working',
+ sessionId: 'merge-task',
+ },
+ },
+ });
renderVersions(
<MemoryRouter>
<CindyMakeSection />
@@ -1213,6 +1188,7 @@ describe('Settings > Cindy Make', () => {
vi.stubGlobal('electronAPI', {
...window.electronAPI,
cindyMakeMerge: h.api.cindyMakeMerge,
+ cindyMakeSync: h.api.cindyMakeSync,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -1242,7 +1218,7 @@ describe('Settings > Cindy Make', () => {
expect(within(sourceCard).queryByText('feature/next')).toBeNull();
expect(within(sourceCard).getByText('e'.repeat(12))).toBeTruthy();
expect(
- within(sourceCard).getByRole('button', { name: 'cindyMake.merge.getLatest' }),
+ within(sourceCard).getByRole('button', { name: 'cindyMake.sync.action' }),
).toBeTruthy();
expect(
within(sourceCard).getByRole('button', { name: 'settings.cindyMake.source.reset' }),
@@ -1319,16 +1295,16 @@ describe('Settings > Cindy Make', () => {
const sourceReads = h.api.getCindyMakeSourceStatus.mock.calls.length;
await h.pushSource({ status: 'ready', path: source.path });
expect(h.api.getCindyMakeSourceStatus).toHaveBeenCalledTimes(sourceReads + 1);
- expect(within(sourceCard).getByRole('status').getAttribute('aria-label')).toBe(
- 'cindyMake.overview.personal · cindyMake.overview.personalStatus.unverified',
+ expect(within(sourceCard).getByRole('status').textContent).toBe(
+ 'cindyMake.summary.included.unverified',
);
expect(within(sourceCard).getByText('cindyMake.overview.comparison.unknown')).toBeTruthy();
expect(
- within(sourceCard).queryByRole('button', { name: 'cindyMake.merge.getLatest' }),
+ within(sourceCard).queryByRole('button', { name: 'cindyMake.sync.action' }),
).toBeTruthy();
expect(within(sourceCard).getByText(source.path)).toBeTruthy();
expect(
- within(sourceCard).getByRole('button', { name: 'cindyMake.merge.getLatest' }),
+ within(sourceCard).getByRole('button', { name: 'cindyMake.sync.action' }),
).toBeTruthy();
},
);
@@ -1347,6 +1323,7 @@ describe('Settings > Cindy Make', () => {
vi.stubGlobal('electronAPI', {
...window.electronAPI,
cindyMakeMerge: h.api.cindyMakeMerge,
+ cindyMakeSync: h.api.cindyMakeSync,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -1374,6 +1351,7 @@ describe('Settings > Cindy Make', () => {
vi.stubGlobal('electronAPI', {
...window.electronAPI,
cindyMakeMerge: h.api.cindyMakeMerge,
+ cindyMakeSync: h.api.cindyMakeSync,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -1397,6 +1375,7 @@ describe('Settings > Cindy Make', () => {
vi.stubGlobal('electronAPI', {
...window.electronAPI,
cindyMakeMerge: h.api.cindyMakeMerge,
+ cindyMakeSync: h.api.cindyMakeSync,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -1408,15 +1387,13 @@ describe('Settings > Cindy Make', () => {
});
renderVersions(<CindyMakeSection />);
await waitFor(() =>
- expect(screen.getByRole('button', { name: 'cindyMake.merge.getLatest' })).toBeTruthy(),
+ expect(screen.getByRole('button', { name: 'cindyMake.sync.action' })).toBeTruthy(),
);
- fireEvent.click(screen.getByRole('button', { name: 'cindyMake.merge.getLatest' }));
+ fireEvent.click(screen.getByRole('button', { name: 'cindyMake.sync.action' }));
await waitFor(() =>
- expect(h.api.cindyMakeMerge).toHaveBeenCalledWith(
- expect.objectContaining({ action: 'update' }),
- ),
+ expect(h.api.cindyMakeSync).toHaveBeenCalledWith(expect.objectContaining({ action: 'sync' })),
);
- expect(h.starts()).toHaveLength(3);
+ expect(h.api.cindyMakeMerge).not.toHaveBeenCalled();
});
it('disables manual source sync while a personal version is being built', async () => {
@@ -1427,10 +1404,11 @@ describe('Settings > Cindy Make', () => {
ref: 'main',
});
renderVersions(<CindyMakeSection />);
- const button = await screen.findByRole('button', { name: 'cindyMake.merge.getLatest' });
+ const button = await screen.findByRole('button', { name: 'cindyMake.sync.action' });
await waitFor(() => expect((button as HTMLButtonElement).disabled).toBe(true));
fireEvent.click(button);
expect(h.api.cindyMakeMerge).not.toHaveBeenCalled();
+ expect(h.api.cindyMakeSync).not.toHaveBeenCalled();
});
it('confirms and starts clearing the source without re-pulling it', async () => {
@@ -1446,6 +1424,7 @@ describe('Settings > Cindy Make', () => {
vi.stubGlobal('electronAPI', {
...window.electronAPI,
cindyMakeMerge: h.api.cindyMakeMerge,
+ cindyMakeSync: h.api.cindyMakeSync,
maker: h.api,
getCindyMakeState: h.api.getCindyMakeState,
onCindyMakeState: h.api.onCindyMakeState,
@@ -1475,7 +1454,7 @@ describe('Settings > Cindy Make', () => {
const previousEnvironment = environmentCard.textContent;
fireEvent.click(screen.getByRole('tab', { name: 'settings.cindyMake.tabs.versions' }));
const sourceCard = screen.getByRole('region', { name: 'settings.cindyMake.source.title' });
- fireEvent.click(within(sourceCard).getByRole('button', { name: 'cindyMake.merge.getLatest' }));
+ fireEvent.click(within(sourceCard).getByRole('button', { name: 'cindyMake.sync.action' }));
expect(within(sourceCard).getByText('settings.cindyMake.source.path')).toBeTruthy();
expect(environmentCard.textContent).toBe(previousEnvironment);
await h.pushSource({
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 6063d3f2f9..911d102391 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -15166,7 +15166,8 @@
"included": "Included in the running version",
"notIncluded": "Not in the running version",
"unknown": "Inclusion in the running version is unverified"
- }
+ },
+ "failedContinue": "Couldn’t check whether the official project already has a similar change. You can continue anyway."
},
"title": "Cindy Make",
"stepEnvironment": "1 · Prepare environment",
@@ -15563,7 +15564,8 @@
"rounds_one": "{{count}} editing round",
"rounds_other": "{{count}} editing rounds",
"files_one": "{{count}} file changed",
- "files_other": "{{count}} files changed"
+ "files_other": "{{count}} files changed",
+ "generatePersonal": "Generate personal version"
},
"merge": {
"getLatest": "Sync latest source",
@@ -15606,7 +15608,267 @@
"interrupted": "The operation was interrupted. Your changes are kept; please retry.",
"startFailed": "Could not open the resolution task. Please retry.",
"cancelFailed": "Could not cancel this update. Please retry. Your personal source has been kept."
+ },
+ "combine": {
+ "taskTitle": "Combine changes from two computers",
+ "status": {
+ "fetching": "Preparing to combine…",
+ "merging": "Combining both sides’ changes…",
+ "conflict": "Both sides changed the same place and need attention",
+ "resolving": "Resolving conflicts",
+ "checking": "Checking the combined result…",
+ "merged": "Both sides’ changes are combined",
+ "failed": "Combining didn't finish",
+ "cancelled": "Combining cancelled. Neither personal version changed."
+ },
+ "conflictConfirm": {
+ "title": "Both computers changed the same place",
+ "description": "Confirming creates a separate task where the Agent combines both sides' changes and keeps both sides' features. If both can't be kept, you're asked first. Cancelling abandons this combine and leaves both personal versions unchanged.",
+ "confirm": "Confirm and resolve",
+ "cancel": "Cancel combining"
+ }
}
+ },
+ "storage": {
+ "title": "Saved in",
+ "github": "Your GitHub · {{repository}}",
+ "localOnly": "Only on this computer",
+ "localOnlyHint": "Connect GitHub to use this personal version on your other computers and to submit changes to Cindy. A personal version kept only on this computer can't be recovered after you switch computers or reinstall.",
+ "localChosenHint": "You chose to keep it on this computer only. A personal version kept only on this computer can't be recovered after you switch computers or reinstall.",
+ "disconnectedHint": "This computer isn't connected to GitHub yet. Connect it to sync.",
+ "unavailableHint": "Can't confirm your GitHub connection right now.",
+ "actionFailed": "That didn't finish. Please try again.",
+ "running": {
+ "save": "Saving to your GitHub",
+ "sync": "Syncing to your GitHub",
+ "disconnect": "Stopping sync"
+ },
+ "step": {
+ "waiting": "Waiting for other source operations to finish",
+ "preparing": "Tidying up the changes on this computer",
+ "fork": "Creating your copy on GitHub",
+ "connecting": "Connecting to your GitHub",
+ "retrieving": "Retrieving changes from another computer",
+ "uploading": "Uploading your personal version"
+ },
+ "status": {
+ "synced": "Synced",
+ "pendingBuild": "Syncs after you generate the personal version",
+ "retrieved": "Changes from another computer retrieved; generate the personal version to use them",
+ "pending": "Not synced to GitHub yet",
+ "remoteAhead": "GitHub has new changes from another computer",
+ "diverged": "GitHub and this computer both have new changes that can't be combined automatically yet",
+ "account": "The connected GitHub account ({{login}}) doesn't own this repository. Sync is paused.",
+ "needsMerge": "GitHub and this computer both have new changes to combine",
+ "buildFirst": "Generate first, then Sync"
+ },
+ "errors": {
+ "github": "Your GitHub connection is no longer valid. Reconnect GitHub.",
+ "account": "The connected GitHub account doesn't match where this is saved. Sync is paused.",
+ "forkConflict": "Couldn't create Cindy's copy on your GitHub: a repository with that name isn't a copy of the official repository, and Cindy left it untouched.",
+ "forkUnavailable": "Your copy on GitHub isn't ready yet. Try again later.",
+ "network": "Can't reach GitHub. Check your network and try again.",
+ "workflowScope": "Your GitHub authorization can't upload workflow files. Reconnect GitHub and try again.",
+ "source": "The personal version source isn't available right now. Prepare the source first.",
+ "gitOutdated": "Git on this computer is too old. Update Git from Environment, then try again.",
+ "interrupted": "The last operation was interrupted and didn't continue automatically.",
+ "failed": "Sync didn't finish. Please try again.",
+ "forkMissing": "The GitHub repository that stores your personal version can’t be found; it may have been deleted. You can save it to your GitHub again.",
+ "forkArchived": "The GitHub repository that stores your personal version is archived, so GitHub accepts no uploads. Unarchive it on GitHub, then Sync again."
+ },
+ "card": {
+ "title": "Save your personal version to your GitHub?",
+ "intro": "You're connected to GitHub as {{login}}. After saving:",
+ "otherComputers": "Your other computers using the same GitHub account can use this personal version",
+ "contribute": "You can submit your changes to Cindy later",
+ "autoSync": "It syncs automatically from then on",
+ "public": "It's saved to Cindy's copy under your GitHub account (usually {{repository}}), a public copy of the official repository: everyone on GitHub can see your changes.",
+ "unchanged": "The personal version, Make history and work in progress on this computer stay as they are.",
+ "existingTitle": "Your GitHub already has a personal version",
+ "existingIntro": "{{repository}} on account {{login}} holds a personal version saved from another computer. After saving, this computer uses it too and stays in sync.",
+ "existingKeeps": "If this computer has no changes of its own yet, it uses the personal version from GitHub directly; changes already on this computer are never overwritten.",
+ "prepareFirst": "The personal version source is prepared first, which takes a few minutes."
+ },
+ "actions": {
+ "connect": "Connect GitHub",
+ "reconnect": "Reconnect GitHub",
+ "save": "Save to GitHub",
+ "keepLocal": "Keep on this computer",
+ "syncNow": "Sync now",
+ "retry": "Retry",
+ "recheck": "Check again",
+ "view": "View on GitHub",
+ "stop": "Stop syncing",
+ "useExisting": "Use on this computer",
+ "saveAgain": "Save to GitHub again",
+ "keepSeparate": "No, keep a separate one on this computer"
+ },
+ "stopConfirm": {
+ "title": "Stop syncing to GitHub?",
+ "description": "This computer will stop uploading the personal version. The repository on your GitHub and the personal version on this computer both stay, and you can enable sync again later.",
+ "confirm": "Stop syncing",
+ "cancel": "Cancel"
+ },
+ "needsMergeHint": "Sync above combines both sides' changes and keeps both sides' features. If both changed the same place, a task resolves it automatically.",
+ "buildFirstHint": "Both computers have new changes, and this computer’s aren’t generated yet. Generate your personal version, then press Sync to combine both."
+ },
+ "contribution": {
+ "action": "Submit to Cindy",
+ "update": "Update submission",
+ "resubmit": "Submit again",
+ "view": "View on GitHub",
+ "submitted": "Submitted to Cindy as #{{number}}",
+ "state": {
+ "submitted": "Submitted to Cindy as #{{number}}",
+ "open": "Submitted to Cindy as #{{number}} · Waiting for review",
+ "merged": "Accepted by Cindy · #{{number}}",
+ "closed": "Not accepted by Cindy · #{{number}}"
+ },
+ "dialog": {
+ "title": "Submit to Cindy",
+ "description": "Submit this change as a pull request on the official Cindy repository for the maintainers to review.",
+ "loading": "Preparing this change…",
+ "existing": "You already submitted this change (#{{number}}). Submitting again updates it.",
+ "reopen": "The earlier submission #{{number}} was closed. Submitting again opens a new one.",
+ "prTitle": "Title",
+ "prTitleHint": "Start with a type such as feat: or fix:",
+ "body": "Description",
+ "bodyHint": "Prefilled from the official template. Edit it as you like.",
+ "author": "Signed by",
+ "name": "Name",
+ "email": "Email",
+ "nameRequired": "Enter your name",
+ "emailRequired": "Enter a valid email address",
+ "authorHint": "Shown publicly on GitHub as the author and sign-off of this change.",
+ "files": "Includes {{count}} files",
+ "files_one": "Includes {{count}} file",
+ "files_other": "Includes {{count}} files",
+ "onlyThis": "Only this change is included. Your other personal changes stay out.",
+ "public": "Submitted from your GitHub repository {{repository}} and visible to everyone.",
+ "uiNote": "This change touches the interface. After submitting, add screenshots on GitHub and name the design guidelines it follows.",
+ "dco": "I am submitting this change myself and sign the Developer Certificate of Origin (DCO) as {{name}} <{{email}}>.",
+ "submit": "Submit",
+ "update": "Update submission",
+ "cancel": "Cancel",
+ "close": "Close"
+ },
+ "errors": {
+ "notBound": "To submit to the official project, first save your personal version to your GitHub under “Saved in” above.",
+ "github": "Your GitHub connection is no longer valid. Reconnect GitHub in Settings and try again.",
+ "account": "The connected GitHub account isn't the one your personal version is saved to. Switch back and try again.",
+ "unavailable": "This change's content is no longer on this computer, so it can't be submitted.",
+ "changed": "Review the submission again. Close this window, reopen it, and check the file list before submitting.",
+ "conflict": "This change touches the same place as the latest official code, so it can’t be turned into a submission with only this change. Make the change again on your latest personal version, then submit it.",
+ "empty": "The latest official code already includes this change. There is nothing to submit.",
+ "invalid": "Check the title, name and email. The title must be a single line.",
+ "network": "Can't reach GitHub. Check your network and try again.",
+ "workflowScope": "This change edits GitHub workflow files, which your GitHub authorization can't upload. Reconnect GitHub and try again.",
+ "failed": "The submission didn't finish. Please try again later."
+ }
+ },
+ "summary": {
+ "personal": "Personal version",
+ "latestLabel": "Latest official",
+ "official": "Official {{version}}",
+ "officialUnknown": "Official version",
+ "development": "Official in-progress version",
+ "withChanges": "{{version}} + {{count}} of your changes",
+ "withChanges_one": "{{version}} + {{count}} of your changes",
+ "withChanges_other": "{{version}} + {{count}} of your changes",
+ "withOwnChanges": "{{version}} + your changes",
+ "noChanges": "{{version}}, no changes of yours yet",
+ "latest": {
+ "release": "Release {{version}}",
+ "beta": "Beta {{version}}",
+ "dev": "Latest official code on GitHub",
+ "unavailable": "Can't check right now",
+ "unknown": "Not checked yet"
+ },
+ "included": {
+ "upToDate": "Included in your personal version",
+ "updateAvailable": "Not in your personal version yet",
+ "unverified": "Can't confirm whether your personal version includes it"
+ },
+ "technical": "Technical details (for developers)"
+ },
+ "sync": {
+ "action": "Sync",
+ "hint": "Update your personal version to the official version. When it is saved to GitHub, this also brings in changes from your other computers and uploads the result. Conflicts are handled automatically in a task.",
+ "buildingHint": "Your personal version is being generated. Sync after it finishes or stops.",
+ "step": {
+ "resuming": "Continuing the last sync…",
+ "github": "Bringing in changes from your other computers…",
+ "combine": "Combining both sides’ changes…",
+ "official": "Updating to the official version…",
+ "upload": "Uploading to your GitHub…"
+ },
+ "done": "Synced to official {{ref}}",
+ "doneDevelopment": "Synced to the latest official code",
+ "held": "Official {{ref}} is out, but it changes the data format: switch to the original, update Cindy, then Sync to include it.",
+ "errors": {
+ "busy": "Another operation is in progress. Sync again shortly.",
+ "source": "The personal version source isn't ready or just changed. Sync again shortly.",
+ "github": "Something went wrong with GitHub. Check the connection under “Saved in” below, then Sync again.",
+ "network": "Can't reach the network. Check it, then Sync again.",
+ "diverged": "The personal version on GitHub and this computer's are based on unrelated official versions and can't be combined automatically yet.",
+ "unavailable": "Can't look up the official version right now. Sync again shortly.",
+ "cancelled": "Abandoned this combine. Neither your personal version nor the one on GitHub changed.",
+ "failed": "Sync didn't finish. Please try again.",
+ "changed": "Another computer uploaded new changes during Sync. Sync again to bring them in.",
+ "featurePending": "A change in your change history is being added or undone. Sync again when it is done.",
+ "gitOutdated": "Git on this computer is too old to sync with GitHub. Update Git to 2.36 or later.",
+ "forkMissing": "The GitHub repository that stores your personal version can’t be found; it may have been deleted. Save it to GitHub again under “Saved in” below.",
+ "forkArchived": "The GitHub repository that stores your personal version is archived, so GitHub accepts no uploads. Unarchive it on GitHub, then Sync again."
+ },
+ "doneCurrent": "Synced",
+ "ahead": "Your personal version is on a newer official version than this computer's Cindy (from another computer). If switching says the versions are incompatible, switch to the original and update Cindy first.",
+ "abandon": {
+ "action": "Abandon this combine",
+ "title": "Abandon resolving this conflict?",
+ "description": "The conflict task stops and its intermediate result is deleted. Your personal version stays as it was, and so does the version saved on GitHub. You can Sync again later.",
+ "confirm": "Abandon",
+ "cancel": "Keep working"
+ },
+ "uploadAfterBuild": "This computer's changes upload to your GitHub automatically after you generate the personal version.",
+ "waiting": {
+ "working": {
+ "combine": "Both computers changed the same place. A task is combining them, and Sync continues by itself when it is done.",
+ "official": "The official update and your changes touched the same place. A task is handling it, and Sync continues by itself when it is done."
+ },
+ "input": "The task handling the conflict is waiting for your answer. Open it to reply.",
+ "interrupted": {
+ "task": "Cindy closed while the conflict was being handled. Open the task and say “continue” to pick it up, or abandon it.",
+ "start": "The last Sync was interrupted. Abandon it, then press Sync again."
+ },
+ "missing": "Changes of yours missing from the result: {{count}}. Ask the task to put them back, or use the result anyway if you don’t need them.",
+ "stale": "Your personal version changed while this was being handled, so the result is out of date. Abandon it and Sync again.",
+ "failed": "This combine didn’t finish. Open the task to see why, or abandon it and Sync again.",
+ "abandoning": "Abandoning this combine…",
+ "paused": "The task handling this combine is gone. Press “Continue” to open a new task for it; the work done so far is kept.",
+ "otherAccount": "This combine was started while another account was signed in. Switch back to that account to continue or abandon it."
+ },
+ "waitingHint": "Finish or abandon the combine in progress first.",
+ "accept": {
+ "action": "Use anyway",
+ "title": "Use this result anyway?",
+ "description": "The {{count}} changes missing from it won’t be in your personal version. The original versions on both sides are kept as backups.",
+ "confirm": "Use anyway",
+ "cancel": "Not now"
+ },
+ "buildFirst": "This computer has changes that aren’t generated yet. Generate your personal version first; Sync can then bring in the other computer’s changes.",
+ "needsGenerate": "Your personal version has new changes. Generate it to use them on this computer.",
+ "keep": {
+ "hint": "When the two sides’ changes can’t be combined, keep one side; the other is backed up.",
+ "github": "Keep the GitHub version",
+ "local": "Keep this computer’s version",
+ "githubTitle": "Keep the personal version on GitHub?",
+ "githubDescription": "This computer switches to the personal version on GitHub (from another computer). This computer’s current personal version is backed up, and the changes in your change history can be added back later.",
+ "localTitle": "Keep this computer’s personal version?",
+ "localDescription": "The personal version on GitHub is replaced by this computer’s. A backup branch is kept in your GitHub repository first, so the other computer’s changes can be recovered from it.",
+ "cancel": "Not now"
+ },
+ "resume": "Continue",
+ "generateFirst": "Your personal version has changes that aren’t generated yet. Generate it first, then Sync to official {{ref}}."
}
},
"taskTags": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 8a3753f2a8..f917a04a09 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -15114,7 +15114,8 @@
"included": "実行中のバージョンに含まれます",
"notIncluded": "実行中のバージョンには含まれません",
"unknown": "実行中のバージョンに含まれるか未確認"
- }
+ },
+ "failedContinue": "公式に似た変更があるか確認できませんでしたが、このまま続けられます。"
},
"title": "Cindy Make",
"stepEnvironment": "1 · 環境の準備",
@@ -15509,7 +15510,8 @@
"installerReady": "インストーラーの準備完了"
},
"rounds_other": "編集 {{count}} 回",
- "files_other": "{{count}} ファイルを変更"
+ "files_other": "{{count}} ファイルを変更",
+ "generatePersonal": "個人版を生成"
},
"merge": {
"getLatest": "最新ソースを同期",
@@ -15552,7 +15554,265 @@
"interrupted": "操作が中断されました。変更は保持されています。再試行してください。",
"startFailed": "解決用タスクを開けませんでした。再試行してください。",
"cancelFailed": "更新をキャンセルできませんでした。再試行してください。個人ソースは保持されています。"
+ },
+ "combine": {
+ "taskTitle": "2 台のコンピューターの変更をまとめる",
+ "status": {
+ "fetching": "まとめる準備をしています…",
+ "merging": "両方の変更をまとめています…",
+ "conflict": "両方で同じ箇所が変更されており、対応が必要です",
+ "resolving": "競合を解決しています",
+ "checking": "まとめた結果を確認しています…",
+ "merged": "両方の変更をまとめました",
+ "failed": "まとめる作業が完了しませんでした",
+ "cancelled": "まとめる作業を取り消しました。どちらの個人版も変わっていません"
+ },
+ "conflictConfirm": {
+ "title": "2 台のコンピューターで同じ箇所が変更されています",
+ "description": "確認すると独立したタスクが作成され、Agent が両方の変更をまとめ、両方の機能を残します。両方を残せない場合は先に確認します。キャンセルするとこのまとめ作業を中止し、どちらの個人版も変わりません。",
+ "confirm": "確認して解決",
+ "cancel": "まとめるのをやめる"
+ }
}
+ },
+ "storage": {
+ "title": "保存先",
+ "github": "あなたの GitHub · {{repository}}",
+ "localOnly": "このコンピューターのみ",
+ "localOnlyHint": "GitHub に接続すると、この個人版をほかのコンピューターでも使え、変更を公式に提出することもできます。このコンピューターにだけある個人版は、コンピューターの買い替えや再インストール後に復元できません。",
+ "localChosenHint": "このコンピューターにだけ保存する設定です。このコンピューターにだけある個人版は、コンピューターの買い替えや再インストール後に復元できません。",
+ "disconnectedHint": "このコンピューターはまだ GitHub に接続されていません。同期するには接続してください。",
+ "unavailableHint": "現在 GitHub への接続を確認できません。",
+ "actionFailed": "操作を完了できませんでした。もう一度お試しください。",
+ "running": {
+ "save": "GitHub に保存しています",
+ "sync": "GitHub と同期しています",
+ "disconnect": "同期を停止しています"
+ },
+ "step": {
+ "waiting": "ほかのソース操作の完了を待っています",
+ "preparing": "このコンピューターの変更を整理しています",
+ "fork": "GitHub にコピーを作成しています",
+ "connecting": "GitHub に接続しています",
+ "retrieving": "ほかのコンピューターの変更を取得しています",
+ "uploading": "個人版をアップロードしています"
+ },
+ "status": {
+ "synced": "同期済み",
+ "pendingBuild": "個人版の生成後に同期します",
+ "retrieved": "ほかのコンピューターの変更を取得しました。個人版を生成すると使えます",
+ "pending": "まだ GitHub と同期していません",
+ "remoteAhead": "GitHub にほかのコンピューターの新しい変更があります",
+ "diverged": "GitHub とこのコンピューターの両方に新しい変更があり、今は自動でまとめられません",
+ "account": "接続中の GitHub アカウント({{login}})はこのリポジトリの所有者ではないため、同期を一時停止しています。",
+ "needsMerge": "GitHub とこのコンピューターの両方に新しい変更があり、まとめる必要があります",
+ "buildFirst": "先に生成してから同期"
+ },
+ "errors": {
+ "github": "GitHub の接続が無効になりました。GitHub に再接続してください。",
+ "account": "接続中の GitHub アカウントが保存先と一致しないため、同期を一時停止しています。",
+ "forkConflict": "GitHub に Cindy のコピーを作成できませんでした。同じ名前のリポジトリが公式リポジトリのコピーではないため、Cindy は変更していません。",
+ "forkUnavailable": "GitHub のコピーの準備がまだ終わっていません。しばらくしてからお試しください。",
+ "network": "GitHub に接続できません。ネットワークを確認してからもう一度お試しください。",
+ "workflowScope": "現在の GitHub の認可ではワークフローファイルをアップロードできません。GitHub に再接続してからもう一度お試しください。",
+ "source": "個人版のソースを現在使用できません。先にソースを準備してください。",
+ "gitOutdated": "このコンピューターの Git が古すぎます。環境準備で Git を更新してからもう一度お試しください。",
+ "interrupted": "前回の操作は中断され、自動では再開されませんでした。",
+ "failed": "同期を完了できませんでした。もう一度お試しください。",
+ "forkMissing": "個人版を保存している GitHub リポジトリが見つかりません。削除された可能性があります。もう一度 GitHub に保存できます。",
+ "forkArchived": "個人版を保存している GitHub リポジトリがアーカイブされているため、アップロードできません。GitHub でアーカイブを解除してから同期してください。"
+ },
+ "card": {
+ "title": "個人版をあなたの GitHub に保存しますか?",
+ "intro": "GitHub アカウント {{login}} に接続しています。保存すると:",
+ "otherComputers": "同じ GitHub アカウントを使うほかのコンピューターでも、この個人版を使えます",
+ "contribute": "あとで変更を Cindy の公式に提出できます",
+ "autoSync": "以降は自動で同期されます",
+ "public": "あなたの GitHub アカウントにある Cindy のコピー(通常は {{repository}})に保存されます。これは公式リポジトリの公開コピーのため、変更は GitHub 上で誰でも閲覧できます。",
+ "unchanged": "このコンピューターの個人版、制作履歴、進行中の制作は変わりません。",
+ "existingTitle": "あなたの GitHub にはすでに個人版があります",
+ "existingIntro": "アカウント {{login}} の {{repository}} に、ほかのコンピューターで保存した個人版があります。保存すると、このコンピューターでもそれを使い、以降は自動で同期されます。",
+ "existingKeeps": "このコンピューターにまだ独自の変更がなければ、GitHub の個人版をそのまま使います。このコンピューターにある変更が上書きされることはありません。",
+ "prepareFirst": "先に個人版のソースを準備します。数分かかります。"
+ },
+ "actions": {
+ "connect": "GitHub に接続",
+ "reconnect": "GitHub に再接続",
+ "save": "GitHub に保存",
+ "keepLocal": "このコンピューターにだけ保存",
+ "syncNow": "今すぐ同期",
+ "retry": "再試行",
+ "recheck": "再確認",
+ "view": "GitHub で表示",
+ "stop": "同期を停止",
+ "useExisting": "このコンピューターで使う",
+ "saveAgain": "もう一度 GitHub に保存",
+ "keepSeparate": "使わず、このコンピューターで別に作る"
+ },
+ "stopConfirm": {
+ "title": "GitHub との同期を停止しますか?",
+ "description": "このコンピューターは今後、個人版をアップロードしません。GitHub のリポジトリとこのコンピューターの個人版はどちらも残り、あとで再開できます。",
+ "confirm": "同期を停止",
+ "cancel": "キャンセル"
+ },
+ "needsMergeHint": "上の「同期」で両方の変更をまとめ、両方の機能を残します。同じ箇所が変更されていた場合はタスクで自動的に解決します。",
+ "buildFirstHint": "両方のコンピューターに新しい変更があり、このコンピューターの変更はまだ生成されていません。個人版を生成してから「同期」すると両方をまとめられます。"
+ },
+ "contribution": {
+ "action": "公式に提出",
+ "update": "提出内容を更新",
+ "resubmit": "もう一度提出",
+ "view": "GitHub で表示",
+ "submitted": "公式に提出しました(#{{number}})",
+ "state": {
+ "submitted": "公式に提出済み #{{number}}",
+ "open": "公式に提出済み #{{number}} · レビュー待ち",
+ "merged": "公式に採用されました #{{number}}",
+ "closed": "公式に採用されませんでした #{{number}}"
+ },
+ "dialog": {
+ "title": "公式に提出",
+ "description": "この変更を Pull Request にまとめて Cindy の公式リポジトリに提出し、メンテナーのレビューを受けます。",
+ "loading": "この変更を準備しています…",
+ "existing": "この変更はすでに提出済みです(#{{number}})。もう一度提出すると更新されます。",
+ "reopen": "前回の提出 #{{number}} はクローズされています。もう一度提出すると新しく作成されます。",
+ "prTitle": "タイトル",
+ "prTitleHint": "feat: や fix: などの種類から始めてください",
+ "body": "説明",
+ "bodyHint": "公式のテンプレートで入力済みです。自由に編集できます。",
+ "author": "署名",
+ "name": "名前",
+ "email": "メールアドレス",
+ "nameRequired": "名前を入力してください",
+ "emailRequired": "有効なメールアドレスを入力してください",
+ "authorHint": "この変更の作成者と署名として GitHub 上に公開されます。",
+ "files": "{{count}} ファイルを含む",
+ "onlyThis": "この変更だけが含まれます。個人版のほかの変更は含まれません。",
+ "public": "あなたの GitHub リポジトリ {{repository}} から提出され、誰でも閲覧できます。",
+ "uiNote": "この変更は画面に関わります。提出後、GitHub でスクリーンショットを追加し、根拠となるデザイン規約を記載してください。",
+ "dco": "この変更を自分で提出し、{{name}} <{{email}}> として開発者原産地証明(DCO)に署名することを確認します。",
+ "submit": "提出",
+ "update": "提出内容を更新",
+ "cancel": "キャンセル",
+ "close": "閉じる",
+ "files_other": "{{count}} ファイルを含む"
+ },
+ "errors": {
+ "notBound": "公式に提出するには、まずこのページ上部の「保存先」で個人版を GitHub に保存してください。",
+ "github": "GitHub の接続が無効になりました。設定で GitHub に再接続してからもう一度お試しください。",
+ "account": "接続中の GitHub アカウントが個人版の保存先と一致しません。元のアカウントに戻してからお試しください。",
+ "unavailable": "この変更の内容がこのコンピューターにもうないため、提出できません。",
+ "changed": "提出内容をもう一度確認してください。このウィンドウを閉じて開き直し、ファイル一覧を確認してから提出してください。",
+ "conflict": "この変更は最新の公式コードと同じ箇所に関わっているため、この変更だけの提出に自動でまとめられません。最新の個人版でこの変更を作り直してから提出してください。",
+ "empty": "公式の最新コードにはすでにこの変更が含まれています。提出は不要です。",
+ "invalid": "タイトル、名前、メールアドレスを確認してください。タイトルは 1 行で入力してください。",
+ "network": "GitHub に接続できません。ネットワークを確認してからもう一度お試しください。",
+ "workflowScope": "この変更は GitHub のワークフローファイルを変更するため、現在の GitHub 認可ではアップロードできません。GitHub に再接続してからお試しください。",
+ "failed": "提出できませんでした。しばらくしてからもう一度お試しください。"
+ }
+ },
+ "summary": {
+ "personal": "個人版",
+ "latestLabel": "公式の最新",
+ "official": "公式 {{version}}",
+ "officialUnknown": "公式バージョン",
+ "development": "公式の開発中のバージョン",
+ "withChanges": "{{version}} + あなたの変更 {{count}} 件",
+ "withOwnChanges": "{{version}} + あなたの変更",
+ "noChanges": "{{version}}(あなたの変更はまだありません)",
+ "latest": {
+ "release": "正式版 {{version}}",
+ "beta": "beta 版 {{version}}",
+ "dev": "GitHub 上の公式の最新コード",
+ "unavailable": "今は確認できません",
+ "unknown": "まだ確認していません"
+ },
+ "included": {
+ "upToDate": "個人版に含まれています",
+ "updateAvailable": "個人版にはまだ含まれていません",
+ "unverified": "個人版に含まれているか確認できません"
+ },
+ "technical": "技術的な詳細(開発者向け)",
+ "withChanges_other": "{{version}} + あなたの変更 {{count}} 件"
+ },
+ "sync": {
+ "action": "同期",
+ "hint": "個人版を公式バージョンに更新します。GitHub に保存している場合は、ほかのコンピューターの変更も取り込んでアップロードします。競合はタスクで自動的に解決します。",
+ "buildingHint": "個人版を生成中です。完了または停止してから同期してください。",
+ "step": {
+ "resuming": "前回の同期を続けています…",
+ "github": "ほかのコンピューターの変更を取り込んでいます…",
+ "combine": "両方の変更をまとめています…",
+ "official": "公式バージョンに更新しています…",
+ "upload": "GitHub にアップロードしています…"
+ },
+ "done": "公式 {{ref}} に同期しました",
+ "doneDevelopment": "公式の最新コードに同期しました",
+ "held": "公式 {{ref}} が公開されましたが、データ形式が変わります。原版に切り替えて Cindy を更新してから同期すると含まれます。",
+ "errors": {
+ "busy": "ほかの操作が進行中です。しばらくしてから同期してください。",
+ "source": "個人版のソースが準備できていないか、変更されたばかりです。しばらくしてから同期してください。",
+ "github": "GitHub との接続でエラーが発生しました。下の「保存先」で接続を確認してから同期してください。",
+ "network": "ネットワークに接続できません。確認してから同期してください。",
+ "diverged": "GitHub の個人版とこのコンピューターの個人版は無関係な公式バージョンに基づいているため、今は自動でまとめられません。",
+ "unavailable": "公式バージョンの情報を取得できません。しばらくしてから同期してください。",
+ "cancelled": "このまとめ作業を中止しました。個人版も GitHub のバージョンも変わっていません。",
+ "failed": "同期が完了しませんでした。もう一度お試しください。",
+ "changed": "同期中にほかのコンピューターが新しい変更をアップロードしました。もう一度「同期」すると取り込めます。",
+ "featurePending": "変更履歴の変更を追加または取り消し中です。終わってから同期してください。",
+ "gitOutdated": "このコンピューターの Git が古いため、GitHub と同期できません。Git を 2.36 以降に更新してください。",
+ "forkMissing": "個人版を保存している GitHub リポジトリが見つかりません。削除された可能性があります。下の「保存先」からもう一度 GitHub に保存できます。",
+ "forkArchived": "個人版を保存している GitHub リポジトリがアーカイブされているため、アップロードできません。GitHub でアーカイブを解除してから同期してください。"
+ },
+ "doneCurrent": "同期しました",
+ "ahead": "個人版は、このコンピューターの Cindy より新しい公式バージョン上にあります(ほかのコンピューターから)。切り替え時に互換性がないと表示された場合は、原版に切り替えて Cindy を更新してください。",
+ "abandon": {
+ "action": "このまとめ作業を中止",
+ "title": "この競合の解決を中止しますか?",
+ "description": "解決タスクは停止し、途中の結果は削除されます。個人版も GitHub に保存されているバージョンもそのまま残り、あとで再度同期できます。",
+ "confirm": "中止する",
+ "cancel": "続ける"
+ },
+ "uploadAfterBuild": "このコンピューターの変更は、個人版を生成すると自動的に GitHub にアップロードされます。",
+ "waiting": {
+ "working": {
+ "combine": "2 台のコンピューターで同じ箇所が変更されています。タスクでまとめている最中で、終わると自動的に同期を続けます。",
+ "official": "公式の更新とあなたの変更が同じ箇所に関わっています。タスクで対応中で、終わると自動的に同期を続けます。"
+ },
+ "input": "競合を処理しているタスクがあなたの回答を待っています。タスクを開いて確認してください。",
+ "interrupted": {
+ "task": "競合の処理中に Cindy が終了しました。タスクを開いて「続けて」と伝えると再開できます。中止することもできます。",
+ "start": "前回の同期が中断されました。中止してから、もう一度「同期」してください。"
+ },
+ "missing": "結果に含まれていないあなたの変更:{{count}} 件。タスクで戻してもらうか、不要であればこの結果をそのまま使えます。",
+ "stale": "処理中に個人版が変更されたため、この結果は古くなりました。中止してから同期し直してください。",
+ "failed": "このまとめ作業は完了しませんでした。タスクを開いて確認するか、中止してから同期し直してください。",
+ "abandoning": "このまとめ作業を中止しています…",
+ "paused": "このまとめ作業のタスクが見つかりません。「続ける」を押すと新しいタスクで続きを行い、これまでの作業は残ります。",
+ "otherAccount": "このまとめ作業は別のアカウントでログインしていたときに始まりました。そのアカウントに戻すと続けたり中止したりできます。"
+ },
+ "waitingHint": "進行中のまとめ作業を先に終えるか、中止してください。",
+ "accept": {
+ "action": "そのまま使う",
+ "title": "この結果をそのまま使いますか?",
+ "description": "結果に含まれていない {{count}} 件の変更は個人版に入りません。両方の元のバージョンはバックアップとして残ります。",
+ "confirm": "そのまま使う",
+ "cancel": "やめておく"
+ },
+ "buildFirst": "このコンピューターにまだ生成していない変更があります。先に個人版を生成すると、同期でほかのコンピューターの変更を取り込めます。",
+ "needsGenerate": "個人版に新しい変更があります。生成すると、このコンピューターで使えるようになります。",
+ "keep": {
+ "hint": "両方の変更をまとめられないときは、どちらかを残せます。もう一方はバックアップされます。",
+ "github": "GitHub の個人版を残す",
+ "local": "このコンピューターの個人版を残す",
+ "githubTitle": "GitHub の個人版を残しますか?",
+ "githubDescription": "このコンピューターは GitHub の個人版(ほかのコンピューターのもの)に切り替わります。このコンピューターの現在の個人版はバックアップされ、変更履歴の変更はあとから追加し直せます。",
+ "localTitle": "このコンピューターの個人版を残しますか?",
+ "localDescription": "GitHub の個人版はこのコンピューターのものに置き換わります。置き換える前に GitHub リポジトリにバックアップのブランチを残すので、ほかのコンピューターの変更はそこから取り戻せます。",
+ "cancel": "やめておく"
+ },
+ "resume": "続ける",
+ "generateFirst": "個人版にまだ生成していない変更があります。先に個人版を生成してから、公式 {{ref}} に同期してください。"
}
},
"taskTags": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index de433011b8..4a812337ff 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -15114,7 +15114,8 @@
"included": "실행 중인 버전에 포함됨",
"notIncluded": "실행 중인 버전에 포함되지 않음",
"unknown": "실행 중인 버전의 포함 여부 미확인"
- }
+ },
+ "failedContinue": "공식에 비슷한 변경이 있는지 확인하지 못했지만 그대로 계속할 수 있습니다."
},
"title": "Cindy Make",
"stepEnvironment": "1 · 환경 준비",
@@ -15509,7 +15510,8 @@
"installerReady": "설치 파일 준비 완료"
},
"rounds_other": "수정 {{count}}회",
- "files_other": "파일 {{count}}개 변경"
+ "files_other": "파일 {{count}}개 변경",
+ "generatePersonal": "개인 버전 생성"
},
"merge": {
"getLatest": "최신 소스 동기화",
@@ -15552,7 +15554,265 @@
"interrupted": "작업이 중단되었습니다. 변경 사항은 유지됩니다. 다시 시도해 주세요.",
"startFailed": "해결 작업을 열지 못했습니다. 다시 시도해 주세요.",
"cancelFailed": "업데이트를 취소하지 못했습니다. 다시 시도해 주세요. 개인 소스는 유지됩니다."
+ },
+ "combine": {
+ "taskTitle": "두 컴퓨터의 변경 사항 합치기",
+ "status": {
+ "fetching": "합칠 준비를 하는 중…",
+ "merging": "양쪽 변경 사항을 합치는 중…",
+ "conflict": "양쪽에서 같은 부분을 바꿔 처리가 필요합니다",
+ "resolving": "충돌을 해결하는 중",
+ "checking": "합친 결과를 확인하는 중…",
+ "merged": "양쪽 변경 사항을 합쳤습니다",
+ "failed": "합치기를 완료하지 못했습니다",
+ "cancelled": "합치기를 취소했습니다. 양쪽 개인 버전 모두 바뀌지 않았습니다."
+ },
+ "conflictConfirm": {
+ "title": "두 컴퓨터에서 같은 부분을 바꿨습니다",
+ "description": "확인하면 별도 작업이 만들어지고 Agent가 양쪽 변경 사항을 합쳐 양쪽 기능을 모두 유지합니다. 둘 다 유지할 수 없으면 먼저 물어봅니다. 취소하면 이번 합치기를 중단하며 양쪽 개인 버전은 바뀌지 않습니다.",
+ "confirm": "확인하고 해결",
+ "cancel": "합치기 취소"
+ }
}
+ },
+ "storage": {
+ "title": "저장 위치",
+ "github": "내 GitHub · {{repository}}",
+ "localOnly": "이 컴퓨터에만",
+ "localOnlyHint": "GitHub에 연결하면 이 개인 버전을 다른 컴퓨터에서도 사용하고, 변경 사항을 공식에 제출할 수도 있습니다. 이 컴퓨터에만 있는 개인 버전은 컴퓨터를 바꾸거나 다시 설치하면 복구할 수 없습니다.",
+ "localChosenHint": "이 컴퓨터에만 두기로 선택했습니다. 이 컴퓨터에만 있는 개인 버전은 컴퓨터를 바꾸거나 다시 설치하면 복구할 수 없습니다.",
+ "disconnectedHint": "이 컴퓨터는 아직 GitHub에 연결되지 않았습니다. 동기화하려면 연결하세요.",
+ "unavailableHint": "지금은 GitHub 연결을 확인할 수 없습니다.",
+ "actionFailed": "작업을 완료하지 못했습니다. 다시 시도해 주세요.",
+ "running": {
+ "save": "내 GitHub에 저장하는 중",
+ "sync": "내 GitHub와 동기화하는 중",
+ "disconnect": "동기화를 중지하는 중"
+ },
+ "step": {
+ "waiting": "다른 소스 작업이 끝나기를 기다리는 중",
+ "preparing": "이 컴퓨터의 변경 사항을 정리하는 중",
+ "fork": "내 GitHub에 사본을 만드는 중",
+ "connecting": "내 GitHub에 연결하는 중",
+ "retrieving": "다른 컴퓨터의 변경 사항을 가져오는 중",
+ "uploading": "개인 버전을 업로드하는 중"
+ },
+ "status": {
+ "synced": "동기화됨",
+ "pendingBuild": "개인 버전을 생성한 뒤 동기화됩니다",
+ "retrieved": "다른 컴퓨터의 변경 사항을 가져왔습니다. 개인 버전을 생성하면 사용할 수 있습니다",
+ "pending": "아직 GitHub와 동기화되지 않았습니다",
+ "remoteAhead": "GitHub에 다른 컴퓨터의 새 변경 사항이 있습니다",
+ "diverged": "GitHub와 이 컴퓨터에 각각 새 변경 사항이 있어 지금은 자동으로 합칠 수 없습니다",
+ "account": "현재 연결된 GitHub 계정({{login}})은 이 저장소의 소유자가 아니어서 동기화를 일시 중지했습니다.",
+ "needsMerge": "GitHub와 이 컴퓨터에 각각 새 변경 사항이 있어 합쳐야 합니다",
+ "buildFirst": "먼저 생성한 뒤 동기화"
+ },
+ "errors": {
+ "github": "GitHub 연결이 더 이상 유효하지 않습니다. GitHub에 다시 연결하세요.",
+ "account": "현재 연결된 GitHub 계정이 저장 위치와 일치하지 않아 동기화를 일시 중지했습니다.",
+ "forkConflict": "내 GitHub에 Cindy 사본을 만들지 못했습니다. 같은 이름의 저장소가 공식 저장소의 사본이 아니어서 Cindy는 이를 변경하지 않았습니다.",
+ "forkUnavailable": "GitHub의 사본이 아직 준비되지 않았습니다. 잠시 후 다시 시도해 주세요.",
+ "network": "GitHub에 연결할 수 없습니다. 네트워크를 확인한 뒤 다시 시도해 주세요.",
+ "workflowScope": "현재 GitHub 권한으로는 워크플로 파일을 업로드할 수 없습니다. GitHub에 다시 연결한 뒤 다시 시도해 주세요.",
+ "source": "지금은 개인 버전 소스를 사용할 수 없습니다. 먼저 소스를 준비하세요.",
+ "gitOutdated": "이 컴퓨터의 Git 버전이 너무 오래되었습니다. 환경 준비에서 Git을 업데이트한 뒤 다시 시도해 주세요.",
+ "interrupted": "이전 작업이 중단되었으며 자동으로 이어서 진행하지 않았습니다.",
+ "failed": "동기화를 완료하지 못했습니다. 다시 시도해 주세요.",
+ "forkMissing": "개인 버전을 저장한 GitHub 저장소를 찾을 수 없습니다. 삭제되었을 수 있습니다. 다시 GitHub에 저장할 수 있습니다.",
+ "forkArchived": "개인 버전을 저장한 GitHub 저장소가 보관 처리되어 업로드할 수 없습니다. GitHub에서 보관을 해제한 뒤 다시 동기화하세요."
+ },
+ "card": {
+ "title": "개인 버전을 내 GitHub에 저장할까요?",
+ "intro": "GitHub 계정 {{login}}에 연결되어 있습니다. 저장하면:",
+ "otherComputers": "같은 GitHub 계정을 사용하는 다른 컴퓨터에서도 이 개인 버전을 사용할 수 있습니다",
+ "contribute": "나중에 변경 사항을 Cindy 공식에 제출할 수 있습니다",
+ "autoSync": "이후에는 자동으로 동기화됩니다",
+ "public": "내 GitHub 계정의 Cindy 사본(보통 {{repository}})에 저장됩니다. 공식 저장소의 공개 사본이므로 변경 사항을 GitHub에서 누구나 볼 수 있습니다.",
+ "unchanged": "이 컴퓨터의 개인 버전, 제작 기록, 진행 중인 제작은 바뀌지 않습니다.",
+ "existingTitle": "내 GitHub에 이미 개인 버전이 있습니다",
+ "existingIntro": "계정 {{login}}의 {{repository}}에 다른 컴퓨터에서 저장한 개인 버전이 있습니다. 저장하면 이 컴퓨터에서도 이를 사용하고 이후 자동으로 동기화됩니다.",
+ "existingKeeps": "이 컴퓨터에 아직 자체 변경 사항이 없으면 GitHub의 개인 버전을 그대로 사용합니다. 이 컴퓨터에 있는 변경 사항은 덮어쓰지 않습니다.",
+ "prepareFirst": "먼저 개인 버전 소스를 준비합니다. 몇 분 정도 걸립니다."
+ },
+ "actions": {
+ "connect": "GitHub 연결",
+ "reconnect": "GitHub 다시 연결",
+ "save": "GitHub에 저장",
+ "keepLocal": "이 컴퓨터에만 두기",
+ "syncNow": "지금 동기화",
+ "retry": "다시 시도",
+ "recheck": "다시 확인",
+ "view": "GitHub에서 보기",
+ "stop": "동기화 중지",
+ "useExisting": "이 컴퓨터에서 사용",
+ "saveAgain": "다시 GitHub에 저장",
+ "keepSeparate": "아니요, 이 컴퓨터에서 따로 만들기"
+ },
+ "stopConfirm": {
+ "title": "GitHub 동기화를 중지할까요?",
+ "description": "이 컴퓨터는 앞으로 개인 버전을 업로드하지 않습니다. GitHub의 저장소와 이 컴퓨터의 개인 버전은 모두 유지되며 나중에 다시 켤 수 있습니다.",
+ "confirm": "동기화 중지",
+ "cancel": "취소"
+ },
+ "needsMergeHint": "위의 「동기화」로 양쪽 변경 사항을 합치며 양쪽 기능이 모두 유지됩니다. 같은 부분을 바꿨다면 작업에서 자동으로 해결합니다.",
+ "buildFirstHint": "두 컴퓨터 모두 새 변경 사항이 있고, 이 컴퓨터의 변경 사항은 아직 생성되지 않았습니다. 개인 버전을 생성한 뒤 「동기화」하면 양쪽을 합칠 수 있습니다."
+ },
+ "contribution": {
+ "action": "공식에 제출",
+ "update": "제출 내용 업데이트",
+ "resubmit": "다시 제출",
+ "view": "GitHub에서 보기",
+ "submitted": "공식에 제출했습니다(#{{number}})",
+ "state": {
+ "submitted": "공식에 제출됨 #{{number}}",
+ "open": "공식에 제출됨 #{{number}} · 검토 대기 중",
+ "merged": "공식에 채택됨 #{{number}}",
+ "closed": "공식에 채택되지 않음 #{{number}}"
+ },
+ "dialog": {
+ "title": "공식에 제출",
+ "description": "이 변경 사항을 Pull Request로 정리해 Cindy 공식 저장소에 제출하고 메인테이너의 검토를 받습니다.",
+ "loading": "이 변경 사항을 준비하는 중…",
+ "existing": "이 변경 사항은 이미 제출되었습니다(#{{number}}). 다시 제출하면 업데이트됩니다.",
+ "reopen": "이전 제출 #{{number}}은(는) 닫혔습니다. 다시 제출하면 새로 만들어집니다.",
+ "prTitle": "제목",
+ "prTitleHint": "feat: 또는 fix: 같은 유형으로 시작하세요",
+ "body": "설명",
+ "bodyHint": "공식 템플릿으로 미리 채워 두었습니다. 자유롭게 수정하세요.",
+ "author": "서명",
+ "name": "이름",
+ "email": "이메일",
+ "nameRequired": "이름을 입력하세요",
+ "emailRequired": "올바른 이메일 주소를 입력하세요",
+ "authorHint": "이 변경 사항의 작성자와 서명으로 GitHub에 공개됩니다.",
+ "files": "파일 {{count}}개 포함",
+ "onlyThis": "이 변경 사항만 포함됩니다. 개인 버전의 다른 변경 사항은 포함되지 않습니다.",
+ "public": "내 GitHub 저장소 {{repository}}에서 제출되며 누구나 볼 수 있습니다.",
+ "uiNote": "이 변경 사항은 화면과 관련이 있습니다. 제출한 뒤 GitHub에서 스크린샷을 추가하고 근거가 된 디자인 규칙을 적어 주세요.",
+ "dco": "이 변경 사항을 직접 제출하며 {{name}} <{{email}}>(으)로 개발자 원산지 증명(DCO)에 서명함을 확인합니다.",
+ "submit": "제출",
+ "update": "제출 내용 업데이트",
+ "cancel": "취소",
+ "close": "닫기",
+ "files_other": "파일 {{count}}개 포함"
+ },
+ "errors": {
+ "notBound": "공식에 제출하려면 먼저 이 페이지 위쪽 「저장 위치」에서 개인 버전을 GitHub에 저장하세요.",
+ "github": "GitHub 연결이 더 이상 유효하지 않습니다. 설정에서 GitHub에 다시 연결한 뒤 시도해 주세요.",
+ "account": "연결된 GitHub 계정이 개인 버전을 저장한 계정과 다릅니다. 원래 계정으로 바꾼 뒤 다시 시도해 주세요.",
+ "unavailable": "이 컴퓨터에 이 변경 사항의 내용이 더 이상 없어 제출할 수 없습니다.",
+ "changed": "제출 내용을 다시 확인하세요. 이 창을 닫았다가 다시 열고 파일 목록을 확인한 후 제출하세요.",
+ "conflict": "이 변경 사항은 최신 공식 코드와 같은 부분에 걸쳐 있어 이 변경만 담은 제출로 자동 정리할 수 없습니다. 최신 개인 버전에서 이 변경을 다시 만든 뒤 제출하세요.",
+ "empty": "공식 최신 코드에 이미 이 변경 사항이 포함되어 있어 제출할 필요가 없습니다.",
+ "invalid": "제목, 이름, 이메일을 확인하세요. 제목은 한 줄로 입력해야 합니다.",
+ "network": "GitHub에 연결할 수 없습니다. 네트워크를 확인한 뒤 다시 시도해 주세요.",
+ "workflowScope": "이 변경 사항은 GitHub 워크플로 파일을 수정하므로 현재 GitHub 권한으로는 업로드할 수 없습니다. GitHub에 다시 연결한 뒤 시도해 주세요.",
+ "failed": "제출하지 못했습니다. 잠시 후 다시 시도해 주세요."
+ }
+ },
+ "summary": {
+ "personal": "개인 버전",
+ "latestLabel": "공식 최신",
+ "official": "공식 {{version}}",
+ "officialUnknown": "공식 버전",
+ "development": "공식 개발 중 버전",
+ "withChanges": "{{version}} + 내 변경 사항 {{count}}개",
+ "withOwnChanges": "{{version}} + 내 변경 사항",
+ "noChanges": "{{version}}, 아직 내 변경 사항 없음",
+ "latest": {
+ "release": "정식 버전 {{version}}",
+ "beta": "beta 버전 {{version}}",
+ "dev": "GitHub의 공식 최신 코드",
+ "unavailable": "지금은 확인할 수 없음",
+ "unknown": "아직 확인하지 않음"
+ },
+ "included": {
+ "upToDate": "개인 버전에 포함됨",
+ "updateAvailable": "개인 버전에 아직 포함되지 않음",
+ "unverified": "개인 버전에 포함되었는지 확인할 수 없음"
+ },
+ "technical": "개발자용 세부 정보",
+ "withChanges_other": "{{version}} + 내 변경 사항 {{count}}개"
+ },
+ "sync": {
+ "action": "동기화",
+ "hint": "개인 버전을 공식 버전으로 업데이트합니다. GitHub에 저장한 경우 다른 컴퓨터의 변경 사항도 가져와 업로드합니다. 충돌은 작업에서 자동으로 해결합니다.",
+ "buildingHint": "개인 버전을 생성하는 중입니다. 완료되거나 중지된 뒤 동기화하세요.",
+ "step": {
+ "resuming": "지난 동기화를 이어서 진행하는 중…",
+ "github": "다른 컴퓨터의 변경 사항을 가져오는 중…",
+ "combine": "양쪽 변경 사항을 합치는 중…",
+ "official": "공식 버전으로 업데이트하는 중…",
+ "upload": "내 GitHub에 업로드하는 중…"
+ },
+ "done": "공식 {{ref}}(으)로 동기화했습니다",
+ "doneDevelopment": "공식 최신 코드로 동기화했습니다",
+ "held": "공식 {{ref}}이(가) 나왔지만 데이터 형식이 바뀝니다. 원본으로 전환해 Cindy를 업데이트한 뒤 동기화하면 포함됩니다.",
+ "errors": {
+ "busy": "다른 작업이 진행 중입니다. 잠시 후 다시 동기화하세요.",
+ "source": "개인 버전 소스가 준비되지 않았거나 방금 바뀌었습니다. 잠시 후 다시 동기화하세요.",
+ "github": "GitHub 연결에 문제가 있습니다. 아래 「저장 위치」에서 연결을 확인한 뒤 다시 동기화하세요.",
+ "network": "네트워크에 연결할 수 없습니다. 확인한 뒤 다시 동기화하세요.",
+ "diverged": "GitHub의 개인 버전과 이 컴퓨터의 개인 버전이 서로 관련 없는 공식 버전을 기반으로 해서 지금은 자동으로 합칠 수 없습니다.",
+ "unavailable": "지금은 공식 버전 정보를 확인할 수 없습니다. 잠시 후 다시 동기화하세요.",
+ "cancelled": "이번 합치기를 중단했습니다. 개인 버전과 GitHub의 버전 모두 바뀌지 않았습니다.",
+ "failed": "동기화를 완료하지 못했습니다. 다시 시도해 주세요.",
+ "changed": "동기화하는 동안 다른 컴퓨터가 새 변경 사항을 업로드했습니다. 다시 「동기화」하면 가져옵니다.",
+ "featurePending": "변경 기록의 변경 사항을 추가하거나 되돌리는 중입니다. 끝난 뒤 다시 동기화하세요.",
+ "gitOutdated": "이 컴퓨터의 Git이 너무 오래되어 GitHub와 동기화할 수 없습니다. Git을 2.36 이상으로 업데이트하세요.",
+ "forkMissing": "개인 버전을 저장한 GitHub 저장소를 찾을 수 없습니다. 삭제되었을 수 있습니다. 아래 「저장 위치」에서 다시 GitHub에 저장하세요.",
+ "forkArchived": "개인 버전을 저장한 GitHub 저장소가 보관 처리되어 업로드할 수 없습니다. GitHub에서 보관을 해제한 뒤 다시 동기화하세요."
+ },
+ "doneCurrent": "동기화했습니다",
+ "ahead": "개인 버전이 이 컴퓨터의 Cindy보다 새로운 공식 버전에 있습니다(다른 컴퓨터에서 가져옴). 전환할 때 호환되지 않는다고 나오면 먼저 원본으로 전환해 Cindy를 업데이트하세요.",
+ "abandon": {
+ "action": "이번 합치기 중단",
+ "title": "이 충돌 해결을 중단할까요?",
+ "description": "해결 작업이 멈추고 중간 결과가 삭제됩니다. 개인 버전과 GitHub에 저장된 버전은 그대로이며 나중에 다시 동기화할 수 있습니다.",
+ "confirm": "중단",
+ "cancel": "계속 진행"
+ },
+ "uploadAfterBuild": "이 컴퓨터의 변경 사항은 개인 버전을 생성하면 자동으로 GitHub에 업로드됩니다.",
+ "waiting": {
+ "working": {
+ "combine": "두 컴퓨터에서 같은 부분을 바꿨습니다. 작업에서 합치는 중이며, 끝나면 자동으로 동기화를 이어 갑니다.",
+ "official": "공식 업데이트와 내 변경 사항이 같은 부분에 걸쳐 있습니다. 작업에서 처리하는 중이며, 끝나면 자동으로 동기화를 이어 갑니다."
+ },
+ "input": "충돌을 처리하는 작업이 답변을 기다리고 있습니다. 작업을 열어 확인하세요.",
+ "interrupted": {
+ "task": "충돌을 처리하는 중에 Cindy가 종료되었습니다. 작업을 열고 「계속」이라고 말하면 이어서 처리합니다. 중단할 수도 있습니다.",
+ "start": "지난 동기화가 중단되었습니다. 중단한 뒤 다시 「동기화」하세요."
+ },
+ "missing": "결과에 없는 내 변경 사항: {{count}}개. 작업에서 되살리게 하거나, 필요 없다면 이 결과를 그대로 사용할 수 있습니다.",
+ "stale": "처리하는 동안 개인 버전이 바뀌어 이 결과는 오래되었습니다. 중단한 뒤 다시 동기화하세요.",
+ "failed": "이번 합치기를 완료하지 못했습니다. 작업을 열어 확인하거나, 중단한 뒤 다시 동기화하세요.",
+ "abandoning": "이번 합치기를 중단하는 중…",
+ "paused": "이번 합치기를 처리하던 작업이 없습니다. 「계속」을 누르면 새 작업으로 이어서 처리하며, 지금까지 한 작업은 유지됩니다.",
+ "otherAccount": "이번 합치기는 다른 계정으로 로그인했을 때 시작되었습니다. 그 계정으로 돌아가야 계속하거나 중단할 수 있습니다."
+ },
+ "waitingHint": "진행 중인 합치기를 먼저 끝내거나 중단하세요.",
+ "accept": {
+ "action": "그대로 사용",
+ "title": "이 결과를 그대로 사용할까요?",
+ "description": "결과에 없는 변경 사항 {{count}}개는 개인 버전에 포함되지 않습니다. 양쪽의 원래 버전은 백업으로 남습니다.",
+ "confirm": "그대로 사용",
+ "cancel": "다시 생각하기"
+ },
+ "buildFirst": "이 컴퓨터에 아직 생성하지 않은 변경 사항이 있습니다. 먼저 개인 버전을 생성하면 동기화로 다른 컴퓨터의 변경 사항을 가져올 수 있습니다.",
+ "needsGenerate": "개인 버전에 새 변경 사항이 있습니다. 생성하면 이 컴퓨터에서 사용할 수 있습니다.",
+ "keep": {
+ "hint": "양쪽 변경 사항을 합칠 수 없으면 한쪽을 남길 수 있습니다. 다른 쪽은 백업됩니다.",
+ "github": "GitHub의 개인 버전 남기기",
+ "local": "이 컴퓨터의 개인 버전 남기기",
+ "githubTitle": "GitHub의 개인 버전을 남길까요?",
+ "githubDescription": "이 컴퓨터는 GitHub의 개인 버전(다른 컴퓨터의 것)으로 바뀝니다. 이 컴퓨터의 현재 개인 버전은 백업되며, 변경 기록의 변경 사항은 나중에 다시 추가할 수 있습니다.",
+ "localTitle": "이 컴퓨터의 개인 버전을 남길까요?",
+ "localDescription": "GitHub의 개인 버전이 이 컴퓨터의 것으로 바뀝니다. 바꾸기 전에 GitHub 저장소에 백업 브랜치를 남기므로 다른 컴퓨터의 변경 사항은 거기서 되찾을 수 있습니다.",
+ "cancel": "다시 생각하기"
+ },
+ "resume": "계속",
+ "generateFirst": "개인 버전에 아직 생성하지 않은 변경 사항이 있습니다. 먼저 개인 버전을 생성한 뒤 공식 {{ref}}(으)로 동기화하세요."
}
},
"taskTags": {
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 05ec077263..0b80ef02ae 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -15114,7 +15114,8 @@
"included": "当前运行版本已包含",
"notIncluded": "当前运行版本未包含",
"unknown": "是否包含尚未确认"
- }
+ },
+ "failedContinue": "没能查到官方是否已有类似修改,可以直接继续制作。"
},
"title": "Cindy Make",
"stepEnvironment": "1 · 准备环境",
@@ -15509,7 +15510,8 @@
"installerReady": "安装包已就绪"
},
"rounds_other": "{{count}} 轮修改",
- "files_other": "改动 {{count}} 个文件"
+ "files_other": "改动 {{count}} 个文件",
+ "generatePersonal": "生成个人版"
},
"merge": {
"getLatest": "同步最新源码",
@@ -15552,7 +15554,265 @@
"interrupted": "操作已中断,改动已保留,请重试。",
"startFailed": "无法打开处理任务,请重试。",
"cancelFailed": "未能取消本次更新,请重试。个人版源码已保留。"
+ },
+ "combine": {
+ "taskTitle": "合并两台电脑的修改",
+ "status": {
+ "fetching": "正在准备合并…",
+ "merging": "正在合并两边的修改…",
+ "conflict": "两边改到了同一处,需要处理",
+ "resolving": "正在处理冲突",
+ "checking": "正在检查合并结果…",
+ "merged": "两边的修改已合并",
+ "failed": "合并没有完成",
+ "cancelled": "已取消合并,两边的个人版都没有变化"
+ },
+ "conflictConfirm": {
+ "title": "两台电脑改到了同一处",
+ "description": "确认后会创建独立任务,由 Agent 把两边的修改合在一起,两边的功能都会保留;无法同时保留时会先问你。取消将放弃本次合并,两边的个人版都不变。",
+ "confirm": "确认并处理",
+ "cancel": "取消合并"
+ }
+ }
+ },
+ "storage": {
+ "title": "保存位置",
+ "github": "你的 GitHub · {{repository}}",
+ "localOnly": "只在这台电脑",
+ "localOnlyHint": "连接 GitHub 后,可以在其他电脑上使用这个个人版,也能把修改提交给官方。换电脑或重装系统后,只存在本机的个人版无法找回。",
+ "localChosenHint": "你选择了只留在这台电脑。换电脑或重装系统后,只存在本机的个人版无法找回。",
+ "disconnectedHint": "这台电脑还没有连接 GitHub,连接后才能同步。",
+ "unavailableHint": "暂时无法确认 GitHub 连接。",
+ "actionFailed": "操作没有完成,请重试。",
+ "running": {
+ "save": "正在保存到你的 GitHub",
+ "sync": "正在同步到你的 GitHub",
+ "disconnect": "正在停止同步"
+ },
+ "step": {
+ "waiting": "等待其他工程操作完成",
+ "preparing": "整理这台电脑上的修改",
+ "fork": "在你的 GitHub 上创建副本",
+ "connecting": "连接你的 GitHub",
+ "retrieving": "取回另一台电脑的修改",
+ "uploading": "上传个人版"
+ },
+ "status": {
+ "synced": "已同步",
+ "pendingBuild": "生成个人版后同步",
+ "retrieved": "已取回另一台电脑的修改,生成个人版后可用",
+ "pending": "还没同步到 GitHub",
+ "remoteAhead": "GitHub 上有另一台电脑的新修改",
+ "diverged": "GitHub 和这台电脑各有新的修改,暂时没法自动合在一起",
+ "account": "当前连接的 GitHub 账号({{login}})不是这个仓库的所有者,已暂停同步。",
+ "needsMerge": "GitHub 和这台电脑各有新修改,需要合并",
+ "buildFirst": "先生成个人版,再同步"
+ },
+ "errors": {
+ "github": "GitHub 连接已失效,请重新连接 GitHub。",
+ "account": "当前连接的 GitHub 账号与保存位置不一致,已暂停同步。",
+ "forkConflict": "没能在你的 GitHub 上创建 Cindy 的副本:同名仓库不是官方仓库的副本,Cindy 没有改动它。",
+ "forkUnavailable": "GitHub 上的副本迟迟没有准备好,请稍后重试。",
+ "network": "连不上 GitHub,请检查网络后重试。",
+ "workflowScope": "当前 GitHub 授权缺少上传工作流文件的权限,请重新连接 GitHub 后重试。",
+ "source": "个人版源码暂时不可用,请先准备好源码再试。",
+ "gitOutdated": "这台电脑的 Git 版本太旧,请在「环境准备」里更新 Git 后重试。",
+ "interrupted": "上次操作被中断,没有自动继续。",
+ "failed": "同步没有完成,请重试。",
+ "forkMissing": "在 GitHub 上找不到保存个人版的仓库,它可能被删除了。可以重新保存到你的 GitHub。",
+ "forkArchived": "保存个人版的 GitHub 仓库已归档,GitHub 不再接受上传。在 GitHub 上取消归档后再同步。"
+ },
+ "card": {
+ "title": "把个人版保存到你的 GitHub?",
+ "intro": "你已连接 GitHub 账号 {{login}}。保存后:",
+ "otherComputers": "用同一个 GitHub 账号的其他电脑,可以使用这个个人版",
+ "contribute": "以后可以把你的修改提交给 Cindy 官方",
+ "autoSync": "之后会自动同步,不用再管",
+ "public": "会保存到你 GitHub 账号下的 Cindy 副本(通常是 {{repository}}),它是官方仓库的公开副本:你的修改在 GitHub 上所有人可见。",
+ "unchanged": "这台电脑上的个人版、制作历史和正在进行的制作都不会改变。",
+ "existingTitle": "你的 GitHub 上已经有个人版",
+ "existingIntro": "账号 {{login}} 的 {{repository}} 里有在其他电脑上保存的个人版。保存后,这台电脑也使用它,之后自动同步。",
+ "existingKeeps": "如果这台电脑还没有自己的修改,会直接使用 GitHub 上的个人版;这台电脑已有的修改不会被覆盖。",
+ "prepareFirst": "会先准备个人版源码,需要几分钟。"
+ },
+ "actions": {
+ "connect": "连接 GitHub",
+ "reconnect": "重新连接 GitHub",
+ "save": "保存到 GitHub",
+ "keepLocal": "只留在这台电脑",
+ "syncNow": "立即同步",
+ "retry": "重试",
+ "recheck": "重新检查",
+ "view": "在 GitHub 查看",
+ "stop": "停止同步",
+ "useExisting": "在这台电脑使用",
+ "saveAgain": "重新保存到 GitHub",
+ "keepSeparate": "不用,这台电脑单独做一个"
+ },
+ "stopConfirm": {
+ "title": "停止同步到 GitHub?",
+ "description": "这台电脑之后不再上传个人版。你 GitHub 上的仓库和这台电脑上的个人版都会保留,之后可以重新开启。",
+ "confirm": "停止同步",
+ "cancel": "取消"
+ },
+ "needsMergeHint": "点上方「同步」合并两边的修改,两边的功能都会保留;改到同一处时会自动开任务处理。",
+ "buildFirstHint": "两台电脑都有新修改,这台电脑的还没生成。先生成个人版,再点「同步」就能把两边合在一起。"
+ },
+ "contribution": {
+ "action": "提交给官方",
+ "update": "更新提交",
+ "resubmit": "重新提交",
+ "view": "在 GitHub 查看",
+ "submitted": "已提交给官方 #{{number}}",
+ "state": {
+ "submitted": "已提交给官方 #{{number}}",
+ "open": "已提交给官方 #{{number}} · 等待审核",
+ "merged": "已被官方采纳 #{{number}}",
+ "closed": "官方未采纳 #{{number}}"
+ },
+ "dialog": {
+ "title": "提交给官方",
+ "description": "把这项修改整理成一个 Pull Request,提交到 Cindy 官方仓库,由维护者审核。",
+ "loading": "正在整理这项修改…",
+ "existing": "这项修改已经提交过(#{{number}}),再次提交会更新它。",
+ "reopen": "这项修改上次提交的 #{{number}} 已关闭,再次提交会新开一个。",
+ "prTitle": "标题",
+ "prTitleHint": "建议以 feat、fix 等英文类型加英文冒号开头",
+ "body": "说明",
+ "bodyHint": "已按官方的提交模板预填,可以直接修改。",
+ "author": "署名",
+ "name": "名字",
+ "email": "邮箱",
+ "nameRequired": "请填写名字",
+ "emailRequired": "请填写有效的邮箱",
+ "authorHint": "会作为修改的作者和签名,公开显示在 GitHub 上。",
+ "files": "包含 {{count}} 个文件",
+ "onlyThis": "只包含这一项修改,你个人版里的其他修改不会带上。",
+ "public": "从你的 GitHub 仓库 {{repository}} 发起,所有人都能看到。",
+ "uiNote": "这项修改涉及界面。提交后请在 GitHub 上补充截图,并写明依据的设计规范。",
+ "dco": "我确认这项修改由我提交,同意以 {{name}} <{{email}}> 签署开发者原创声明(DCO)。",
+ "submit": "提交",
+ "update": "更新提交",
+ "cancel": "取消",
+ "close": "关闭",
+ "files_other": "包含 {{count}} 个文件"
+ },
+ "errors": {
+ "notBound": "要提交给官方,先在本页上方「保存位置」把个人版保存到你的 GitHub。",
+ "github": "GitHub 连接已失效,请在设置里重新连接 GitHub 后再试。",
+ "account": "当前连接的 GitHub 账号和保存个人版的账号不一致,请换回原来的账号再试。",
+ "unavailable": "这台电脑上已经找不到这项修改的内容,无法提交。",
+ "changed": "请重新确认提交内容。关闭窗口后重新打开,核对文件清单再提交。",
+ "conflict": "这项修改和官方最新的代码改到了同一处,没法自动整理成只含这项修改的提交。可以在最新的个人版上重新制作这项修改,再提交给官方。",
+ "empty": "官方最新的代码已经包含这项修改,不需要再提交。",
+ "invalid": "请检查标题、名字和邮箱是否填写正确。标题只能写一行。",
+ "network": "连不上 GitHub,请检查网络后重试。",
+ "workflowScope": "这项修改改动了 GitHub 工作流文件,当前的 GitHub 授权不能上传。请重新连接 GitHub 后再试。",
+ "failed": "没有提交成功,请稍后重试。"
}
+ },
+ "summary": {
+ "personal": "个人版",
+ "latestLabel": "官方最新",
+ "official": "官方 {{version}}",
+ "officialUnknown": "官方版本",
+ "development": "官方开发中的版本",
+ "withChanges": "{{version}} + 你的 {{count}} 项修改",
+ "withOwnChanges": "{{version}} + 你的修改",
+ "noChanges": "{{version}},还没有你的修改",
+ "latest": {
+ "release": "正式版 {{version}}",
+ "beta": "beta 版 {{version}}",
+ "dev": "GitHub 上的官方最新代码",
+ "unavailable": "暂时查不到",
+ "unknown": "还没查询"
+ },
+ "included": {
+ "upToDate": "个人版已包含",
+ "updateAvailable": "个人版还没包含",
+ "unverified": "还不能确认个人版是否已包含"
+ },
+ "technical": "技术详情(给开发者)",
+ "withChanges_other": "{{version}} + 你的 {{count}} 项修改"
+ },
+ "sync": {
+ "action": "同步",
+ "hint": "把个人版更新到官方版本;保存到 GitHub 时还会取回其他电脑的修改并上传。有冲突会自动开任务处理。",
+ "buildingHint": "个人版正在生成,完成或停止后才能同步。",
+ "step": {
+ "resuming": "正在继续上次没完成的同步…",
+ "github": "正在取回其他电脑的修改…",
+ "combine": "正在合并两边的修改…",
+ "official": "正在更新到官方版本…",
+ "upload": "正在上传到你的 GitHub…"
+ },
+ "done": "已同步到官方 {{ref}}",
+ "doneDevelopment": "已同步到官方最新代码",
+ "held": "官方 {{ref}} 已发布,但它更新了数据格式:先切换到原版并更新 Cindy,再同步即可包含。",
+ "errors": {
+ "busy": "其他操作正在进行,请稍后再同步。",
+ "source": "个人版源码还没准备好,或刚刚有了变化,请稍后再同步。",
+ "github": "连接 GitHub 时出错,请在下方「保存位置」检查连接后再同步。",
+ "network": "连不上网络,请检查后再同步。",
+ "diverged": "GitHub 上的个人版和这台电脑基于互不相关的官方版本,暂时没法自动合并。",
+ "unavailable": "暂时查不到官方版本信息,请稍后再同步。",
+ "cancelled": "已放弃这次合并,个人版和 GitHub 上的版本都没有变化。",
+ "failed": "同步没有完成,请重试。",
+ "changed": "同步期间另一台电脑又上传了新修改,再点一次「同步」即可取回。",
+ "featurePending": "修改记录里有一项修改正在加入或撤销,处理完后再同步。",
+ "gitOutdated": "这台电脑的 Git 版本太旧,没法和 GitHub 同步。请把 Git 更新到 2.36 或更新的版本。",
+ "forkMissing": "找不到保存个人版的 GitHub 仓库,它可能被删除了。可以在下方「保存位置」重新保存到 GitHub。",
+ "forkArchived": "保存个人版的 GitHub 仓库已归档,GitHub 不再接受上传。在 GitHub 上取消归档后再同步。"
+ },
+ "doneCurrent": "已同步",
+ "ahead": "个人版已在比这台电脑的 Cindy 更新的官方版本上(来自另一台电脑)。如果切换时提示版本不兼容,先切换到原版并更新 Cindy。",
+ "abandon": {
+ "action": "放弃这次合并",
+ "title": "放弃处理这个冲突?",
+ "description": "处理任务会停止,中间结果会删除。个人版保持原样,保存在 GitHub 上的版本也不会变,之后可以再同步。",
+ "confirm": "放弃",
+ "cancel": "继续处理"
+ },
+ "uploadAfterBuild": "这台电脑的修改会在生成个人版后自动上传到你的 GitHub。",
+ "waiting": {
+ "working": {
+ "combine": "两台电脑改到了同一处,正在一个任务里合并,处理完会自动继续同步。",
+ "official": "官方更新和你的修改改到了同一处,正在一个任务里处理,处理完会自动继续同步。"
+ },
+ "input": "处理冲突的任务在等你回答,打开任务看看。",
+ "interrupted": {
+ "task": "处理冲突时 Cindy 被关闭了。打开任务说一句「继续」就能接着处理,也可以放弃。",
+ "start": "上次同步被中断了。放弃后再点一次「同步」即可。"
+ },
+ "missing": "合并结果里少了 {{count}} 项你的修改。可以在任务里让它补回,或者确认不需要后仍然使用这个结果。",
+ "stale": "处理期间个人版又有了变化,这次合并已经过时,请放弃后重新同步。",
+ "failed": "这次合并没能完成。可以打开任务看看,或者放弃后重新同步。",
+ "abandoning": "正在放弃这次合并…",
+ "paused": "这次合并的处理任务不在了。点「继续处理」开一个新任务接着做,已经做好的部分会保留。",
+ "otherAccount": "这次合并是用另一个账号登录时开始的,切回那个账号后才能继续或放弃。"
+ },
+ "waitingHint": "先处理完正在进行的合并,或者放弃它。",
+ "accept": {
+ "action": "仍然使用",
+ "title": "仍然使用这个合并结果?",
+ "description": "结果里没有的 {{count}} 项修改不会出现在个人版里。两边原来的版本都留有备份。",
+ "confirm": "仍然使用",
+ "cancel": "再想想"
+ },
+ "buildFirst": "这台电脑有还没生成的修改。先生成个人版,再同步就能取回另一台电脑的修改。",
+ "needsGenerate": "个人版有了新的变化,生成后才会在这台电脑上用上。",
+ "keep": {
+ "hint": "两边的修改合不到一起时,可以选一边为准;另一边会留有备份。",
+ "github": "以 GitHub 上的为准",
+ "local": "以这台电脑的为准",
+ "githubTitle": "以 GitHub 上的个人版为准?",
+ "githubDescription": "这台电脑会改用 GitHub 上的个人版(来自另一台电脑)。这台电脑现在的个人版会留有备份,修改记录里的修改之后还可以重新加入。",
+ "localTitle": "以这台电脑的个人版为准?",
+ "localDescription": "GitHub 上的个人版会被这台电脑的替换。替换前会在你的 GitHub 仓库里留一个备份分支,另一台电脑的修改可以从那里找回。",
+ "cancel": "再想想"
+ },
+ "resume": "继续处理",
+ "generateFirst": "个人版里有还没生成的修改。先生成个人版,再同步到官方 {{ref}}。"
}
},
"taskTags": {
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 fce83553d6..02ad464939 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -15114,7 +15114,8 @@
"included": "目前執行版本已包含",
"notIncluded": "目前執行版本未包含",
"unknown": "是否包含尚未確認"
- }
+ },
+ "failedContinue": "沒能查到官方是否已有類似修改,可以直接繼續製作。"
},
"title": "Cindy Make",
"stepEnvironment": "1 · 準備環境",
@@ -15509,7 +15510,8 @@
"installerReady": "安裝程式已就緒"
},
"rounds_other": "{{count}} 輪修改",
- "files_other": "改動 {{count}} 個檔案"
+ "files_other": "改動 {{count}} 個檔案",
+ "generatePersonal": "產生個人版"
},
"merge": {
"getLatest": "同步最新原始碼",
@@ -15552,7 +15554,265 @@
"interrupted": "操作已中斷,改動已保留,請重試。",
"startFailed": "無法開啟處理任務,請重試。",
"cancelFailed": "未能取消本次更新,請重試。個人版原始碼已保留。"
+ },
+ "combine": {
+ "taskTitle": "合併兩台電腦的修改",
+ "status": {
+ "fetching": "正在準備合併…",
+ "merging": "正在合併兩邊的修改…",
+ "conflict": "兩邊改到了同一處,需要處理",
+ "resolving": "正在處理衝突",
+ "checking": "正在檢查合併結果…",
+ "merged": "兩邊的修改已合併",
+ "failed": "合併沒有完成",
+ "cancelled": "已取消合併,兩邊的個人版都沒有變化"
+ },
+ "conflictConfirm": {
+ "title": "兩台電腦改到了同一處",
+ "description": "確認後會建立獨立任務,由 Agent 把兩邊的修改合在一起,兩邊的功能都會保留;無法同時保留時會先問你。取消將放棄本次合併,兩邊的個人版都不變。",
+ "confirm": "確認並處理",
+ "cancel": "取消合併"
+ }
+ }
+ },
+ "storage": {
+ "title": "儲存位置",
+ "github": "你的 GitHub · {{repository}}",
+ "localOnly": "只在這台電腦",
+ "localOnlyHint": "連接 GitHub 後,可以在其他電腦上使用這個個人版,也能把修改提交給官方。換電腦或重裝系統後,只存在本機的個人版無法找回。",
+ "localChosenHint": "你選擇了只留在這台電腦。換電腦或重裝系統後,只存在本機的個人版無法找回。",
+ "disconnectedHint": "這台電腦還沒有連接 GitHub,連接後才能同步。",
+ "unavailableHint": "暫時無法確認 GitHub 連線。",
+ "actionFailed": "操作沒有完成,請重試。",
+ "running": {
+ "save": "正在儲存到你的 GitHub",
+ "sync": "正在同步到你的 GitHub",
+ "disconnect": "正在停止同步"
+ },
+ "step": {
+ "waiting": "等待其他工程操作完成",
+ "preparing": "整理這台電腦上的修改",
+ "fork": "在你的 GitHub 上建立副本",
+ "connecting": "連接你的 GitHub",
+ "retrieving": "取回另一台電腦的修改",
+ "uploading": "上傳個人版"
+ },
+ "status": {
+ "synced": "已同步",
+ "pendingBuild": "產生個人版後同步",
+ "retrieved": "已取回另一台電腦的修改,產生個人版後可用",
+ "pending": "還沒同步到 GitHub",
+ "remoteAhead": "GitHub 上有另一台電腦的新修改",
+ "diverged": "GitHub 和這台電腦各有新的修改,暫時沒辦法自動合在一起",
+ "account": "目前連接的 GitHub 帳號({{login}})不是這個儲存庫的擁有者,已暫停同步。",
+ "needsMerge": "GitHub 和這台電腦各有新修改,需要合併",
+ "buildFirst": "先產生個人版,再同步"
+ },
+ "errors": {
+ "github": "GitHub 連線已失效,請重新連接 GitHub。",
+ "account": "目前連接的 GitHub 帳號與儲存位置不一致,已暫停同步。",
+ "forkConflict": "沒能在你的 GitHub 上建立 Cindy 的副本:同名儲存庫不是官方儲存庫的副本,Cindy 沒有改動它。",
+ "forkUnavailable": "GitHub 上的副本遲遲沒有準備好,請稍後重試。",
+ "network": "連不上 GitHub,請檢查網路後重試。",
+ "workflowScope": "目前的 GitHub 授權缺少上傳工作流程檔案的權限,請重新連接 GitHub 後重試。",
+ "source": "個人版原始碼暫時無法使用,請先準備好原始碼再試。",
+ "gitOutdated": "這台電腦的 Git 版本太舊,請在「環境準備」裡更新 Git 後重試。",
+ "interrupted": "上次操作被中斷,沒有自動繼續。",
+ "failed": "同步沒有完成,請重試。",
+ "forkMissing": "在 GitHub 上找不到儲存個人版的儲存庫,它可能被刪除了。可以重新儲存到你的 GitHub。",
+ "forkArchived": "儲存個人版的 GitHub 儲存庫已封存,GitHub 不再接受上傳。在 GitHub 上取消封存後再同步。"
+ },
+ "card": {
+ "title": "把個人版儲存到你的 GitHub?",
+ "intro": "你已連接 GitHub 帳號 {{login}}。儲存後:",
+ "otherComputers": "使用同一個 GitHub 帳號的其他電腦,可以使用這個個人版",
+ "contribute": "以後可以把你的修改提交給 Cindy 官方",
+ "autoSync": "之後會自動同步,不用再管",
+ "public": "會儲存到你 GitHub 帳號下的 Cindy 副本(通常是 {{repository}}),它是官方儲存庫的公開副本:你的修改在 GitHub 上所有人都看得到。",
+ "unchanged": "這台電腦上的個人版、製作歷史和正在進行的製作都不會改變。",
+ "existingTitle": "你的 GitHub 上已經有個人版",
+ "existingIntro": "帳號 {{login}} 的 {{repository}} 裡有在其他電腦上儲存的個人版。儲存後,這台電腦也使用它,之後自動同步。",
+ "existingKeeps": "如果這台電腦還沒有自己的修改,會直接使用 GitHub 上的個人版;這台電腦已有的修改不會被覆蓋。",
+ "prepareFirst": "會先準備個人版原始碼,需要幾分鐘。"
+ },
+ "actions": {
+ "connect": "連接 GitHub",
+ "reconnect": "重新連接 GitHub",
+ "save": "儲存到 GitHub",
+ "keepLocal": "只留在這台電腦",
+ "syncNow": "立即同步",
+ "retry": "重試",
+ "recheck": "重新檢查",
+ "view": "在 GitHub 查看",
+ "stop": "停止同步",
+ "useExisting": "在這台電腦使用",
+ "saveAgain": "重新儲存到 GitHub",
+ "keepSeparate": "不用,這台電腦單獨做一個"
+ },
+ "stopConfirm": {
+ "title": "停止同步到 GitHub?",
+ "description": "這台電腦之後不再上傳個人版。你 GitHub 上的儲存庫和這台電腦上的個人版都會保留,之後可以重新開啟。",
+ "confirm": "停止同步",
+ "cancel": "取消"
+ },
+ "needsMergeHint": "點上方「同步」合併兩邊的修改,兩邊的功能都會保留;改到同一處時會自動開任務處理。",
+ "buildFirstHint": "兩台電腦都有新修改,這台電腦的還沒產生。先產生個人版,再點「同步」就能把兩邊合在一起。"
+ },
+ "contribution": {
+ "action": "提交給官方",
+ "update": "更新提交",
+ "resubmit": "重新提交",
+ "view": "在 GitHub 查看",
+ "submitted": "已提交給官方 #{{number}}",
+ "state": {
+ "submitted": "已提交給官方 #{{number}}",
+ "open": "已提交給官方 #{{number}} · 等待審核",
+ "merged": "已被官方採納 #{{number}}",
+ "closed": "官方未採納 #{{number}}"
+ },
+ "dialog": {
+ "title": "提交給官方",
+ "description": "把這項修改整理成一個 Pull Request,提交到 Cindy 官方儲存庫,由維護者審核。",
+ "loading": "正在整理這項修改…",
+ "existing": "這項修改已經提交過(#{{number}}),再次提交會更新它。",
+ "reopen": "這項修改上次提交的 #{{number}} 已關閉,再次提交會新開一個。",
+ "prTitle": "標題",
+ "prTitleHint": "建議以 feat、fix 等英文類型加英文冒號開頭",
+ "body": "說明",
+ "bodyHint": "已按官方的提交範本預填,可以直接修改。",
+ "author": "署名",
+ "name": "名字",
+ "email": "電子郵件",
+ "nameRequired": "請填寫名字",
+ "emailRequired": "請填寫有效的電子郵件",
+ "authorHint": "會作為修改的作者和簽名,公開顯示在 GitHub 上。",
+ "files": "包含 {{count}} 個檔案",
+ "onlyThis": "只包含這一項修改,你個人版裡的其他修改不會帶上。",
+ "public": "從你的 GitHub 儲存庫 {{repository}} 發起,所有人都看得到。",
+ "uiNote": "這項修改涉及介面。提交後請在 GitHub 上補充截圖,並寫明依據的設計規範。",
+ "dco": "我確認這項修改由我提交,同意以 {{name}} <{{email}}> 簽署開發者原創聲明(DCO)。",
+ "submit": "提交",
+ "update": "更新提交",
+ "cancel": "取消",
+ "close": "關閉",
+ "files_other": "包含 {{count}} 個檔案"
+ },
+ "errors": {
+ "notBound": "要提交給官方,先在本頁上方「儲存位置」把個人版儲存到你的 GitHub。",
+ "github": "GitHub 連線已失效,請在設定裡重新連接 GitHub 後再試。",
+ "account": "目前連接的 GitHub 帳號和儲存個人版的帳號不一致,請換回原來的帳號再試。",
+ "unavailable": "這台電腦上已經找不到這項修改的內容,無法提交。",
+ "changed": "請重新確認提交內容。關閉視窗後重新開啟,核對檔案清單再提交。",
+ "conflict": "這項修改和官方最新的程式碼改到了同一處,沒辦法自動整理成只含這項修改的提交。可以在最新的個人版上重新製作這項修改,再提交給官方。",
+ "empty": "官方最新的程式碼已經包含這項修改,不需要再提交。",
+ "invalid": "請檢查標題、名字和電子郵件是否填寫正確。標題只能寫一行。",
+ "network": "連不上 GitHub,請檢查網路後重試。",
+ "workflowScope": "這項修改改動了 GitHub 工作流程檔案,目前的 GitHub 授權不能上傳。請重新連接 GitHub 後再試。",
+ "failed": "沒有提交成功,請稍後重試。"
}
+ },
+ "summary": {
+ "personal": "個人版",
+ "latestLabel": "官方最新",
+ "official": "官方 {{version}}",
+ "officialUnknown": "官方版本",
+ "development": "官方開發中的版本",
+ "withChanges": "{{version}} + 你的 {{count}} 項修改",
+ "withOwnChanges": "{{version}} + 你的修改",
+ "noChanges": "{{version}},還沒有你的修改",
+ "latest": {
+ "release": "正式版 {{version}}",
+ "beta": "beta 版 {{version}}",
+ "dev": "GitHub 上的官方最新程式碼",
+ "unavailable": "暫時查不到",
+ "unknown": "還沒查詢"
+ },
+ "included": {
+ "upToDate": "個人版已包含",
+ "updateAvailable": "個人版還沒包含",
+ "unverified": "還不能確認個人版是否已包含"
+ },
+ "technical": "技術詳情(給開發者)",
+ "withChanges_other": "{{version}} + 你的 {{count}} 項修改"
+ },
+ "sync": {
+ "action": "同步",
+ "hint": "把個人版更新到官方版本;儲存到 GitHub 時還會取回其他電腦的修改並上傳。有衝突會自動開任務處理。",
+ "buildingHint": "個人版正在產生,完成或停止後才能同步。",
+ "step": {
+ "resuming": "正在繼續上次沒完成的同步…",
+ "github": "正在取回其他電腦的修改…",
+ "combine": "正在合併兩邊的修改…",
+ "official": "正在更新到官方版本…",
+ "upload": "正在上傳到你的 GitHub…"
+ },
+ "done": "已同步到官方 {{ref}}",
+ "doneDevelopment": "已同步到官方最新程式碼",
+ "held": "官方 {{ref}} 已發布,但它更新了資料格式:先切換到原版並更新 Cindy,再同步即可包含。",
+ "errors": {
+ "busy": "其他操作正在進行,請稍後再同步。",
+ "source": "個人版原始碼還沒準備好,或剛剛有了變化,請稍後再同步。",
+ "github": "連接 GitHub 時出錯,請在下方「儲存位置」檢查連線後再同步。",
+ "network": "連不上網路,請檢查後再同步。",
+ "diverged": "GitHub 上的個人版和這台電腦基於互不相關的官方版本,暫時沒辦法自動合併。",
+ "unavailable": "暫時查不到官方版本資訊,請稍後再同步。",
+ "cancelled": "已放棄這次合併,個人版和 GitHub 上的版本都沒有變化。",
+ "failed": "同步沒有完成,請重試。",
+ "changed": "同步期間另一台電腦又上傳了新修改,再點一次「同步」即可取回。",
+ "featurePending": "修改記錄裡有一項修改正在加入或撤銷,處理完後再同步。",
+ "gitOutdated": "這台電腦的 Git 版本太舊,沒辦法和 GitHub 同步。請把 Git 更新到 2.36 或更新的版本。",
+ "forkMissing": "找不到儲存個人版的 GitHub 儲存庫,它可能被刪除了。可以在下方「儲存位置」重新儲存到 GitHub。",
+ "forkArchived": "儲存個人版的 GitHub 儲存庫已封存,GitHub 不再接受上傳。在 GitHub 上取消封存後再同步。"
+ },
+ "doneCurrent": "已同步",
+ "ahead": "個人版已在比這台電腦的 Cindy 更新的官方版本上(來自另一台電腦)。如果切換時提示版本不相容,請先切換到原版並更新 Cindy。",
+ "abandon": {
+ "action": "放棄這次合併",
+ "title": "放棄處理這個衝突?",
+ "description": "處理任務會停止,中間結果會刪除。個人版保持原樣,儲存在 GitHub 上的版本也不會變,之後可以再同步。",
+ "confirm": "放棄",
+ "cancel": "繼續處理"
+ },
+ "uploadAfterBuild": "這台電腦的修改會在產生個人版後自動上傳到你的 GitHub。",
+ "waiting": {
+ "working": {
+ "combine": "兩台電腦改到了同一處,正在一個任務裡合併,處理完會自動繼續同步。",
+ "official": "官方更新和你的修改改到了同一處,正在一個任務裡處理,處理完會自動繼續同步。"
+ },
+ "input": "處理衝突的任務在等你回答,打開任務看看。",
+ "interrupted": {
+ "task": "處理衝突時 Cindy 被關閉了。打開任務說一句「繼續」就能接著處理,也可以放棄。",
+ "start": "上次同步被中斷了。放棄後再點一次「同步」即可。"
+ },
+ "missing": "合併結果裡少了 {{count}} 項你的修改。可以在任務裡讓它補回,或者確認不需要後仍然使用這個結果。",
+ "stale": "處理期間個人版又有了變化,這次合併已經過時,請放棄後重新同步。",
+ "failed": "這次合併沒能完成。可以打開任務看看,或者放棄後重新同步。",
+ "abandoning": "正在放棄這次合併…",
+ "paused": "這次合併的處理任務不在了。點「繼續處理」開一個新任務接著做,已經做好的部分會保留。",
+ "otherAccount": "這次合併是用另一個帳號登入時開始的,切回那個帳號後才能繼續或放棄。"
+ },
+ "waitingHint": "先處理完正在進行的合併,或者放棄它。",
+ "accept": {
+ "action": "仍然使用",
+ "title": "仍然使用這個合併結果?",
+ "description": "結果裡沒有的 {{count}} 項修改不會出現在個人版裡。兩邊原來的版本都留有備份。",
+ "confirm": "仍然使用",
+ "cancel": "再想想"
+ },
+ "buildFirst": "這台電腦有還沒產生的修改。先產生個人版,再同步就能取回另一台電腦的修改。",
+ "needsGenerate": "個人版有了新的變化,產生後才會在這台電腦上用上。",
+ "keep": {
+ "hint": "兩邊的修改合不到一起時,可以選一邊為準;另一邊會留有備份。",
+ "github": "以 GitHub 上的為準",
+ "local": "以這台電腦的為準",
+ "githubTitle": "以 GitHub 上的個人版為準?",
+ "githubDescription": "這台電腦會改用 GitHub 上的個人版(來自另一台電腦)。這台電腦現在的個人版會留有備份,修改記錄裡的修改之後還可以重新加入。",
+ "localTitle": "以這台電腦的個人版為準?",
+ "localDescription": "GitHub 上的個人版會被這台電腦的取代。取代前會在你的 GitHub 儲存庫裡留一個備份分支,另一台電腦的修改可以從那裡找回。",
+ "cancel": "再想想"
+ },
+ "resume": "繼續處理",
+ "generateFirst": "個人版裡有還沒產生的修改。先產生個人版,再同步到官方 {{ref}}。"
}
},
"taskTags": {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 4f0615e77a..6bfccf2548 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3080,6 +3080,29 @@ interface ElectronAPI {
cindyMakeMerge: (
input: import('../shared/cindyMakeMerge').CindyMakeMergeRequest,
) => Promise<import('../shared/cindyMakeMerge').CindyMakeMergeState | undefined>;
+ /** Settings → Cindy Make: bind the personal version to the user's GitHub fork. */
+ cindyMakePersonalRemote: (
+ action: import('../shared/cindyMakePersonalRemote').CindyMakePersonalRemoteAction,
+ ) => Promise<import('../shared/cindyMakePersonalRemote').CindyMakePersonalRemoteState>;
+ /** The single Sync of the personal version: GitHub steps run only when shared there. */
+ cindyMakeSync?: (
+ request: import('../shared/cindyMakeSync').CindyMakeSyncRequest,
+ ) => Promise<import('../shared/cindyMakeSync').CindyMakeSyncState>;
+ /** Submit one Cindy Make change to the official repository as a pull request. */
+ cindyMakeContribution: {
+ (request: { action: 'status' }): Promise<
+ import('../shared/cindyMakeContribution').CindyMakeContributionView[]
+ >;
+ (request: { action: 'draft'; runId: string }): Promise<
+ import('../shared/cindyMakeContribution').CindyMakeContributionDraft
+ >;
+ (
+ request: Extract<
+ import('../shared/cindyMakeContribution').CindyMakeContributionRequest,
+ { action: 'submit' }
+ >,
+ ): Promise<import('../shared/cindyMakeContribution').CindyMakeContributionView>;
+ };
getCindyMakeSettings: () => Promise<import('../shared/cindyMakeSettings').CindyMakeSettings>;
setCindyMakeSyncLatestBeforeBuild: (
enabled: boolean,
diff --git a/apps/desktop/src/shared/cindyMakeContribution.ts b/apps/desktop/src/shared/cindyMakeContribution.ts
new file mode 100644
index 0000000000..0202431feb
--- /dev/null
+++ b/apps/desktop/src/shared/cindyMakeContribution.ts
@@ -0,0 +1,98 @@
+/**
+ * Submitting one Cindy Make change to the official repository as a pull request.
+ * Only public facts cross to the renderer: PR number, URL, state, file paths.
+ */
+
+export type CindyMakeContributionState = 'open' | 'merged' | 'closed';
+
+export interface CindyMakeContributionView {
+ runId: string;
+ number: number;
+ url: string;
+ state?: CindyMakeContributionState;
+ submittedAt: number;
+}
+
+/** Prefilled pull request; the user reviews and edits every field before submitting. */
+export interface CindyMakeContributionDraft {
+ runId: string;
+ /** Opaque Main-issued confirmation, bound to this source, account and fork. */
+ snapshotId: string;
+ title: string;
+ body: string;
+ /** Commit author and DCO sign-off identity. */
+ name: string;
+ email: string;
+ files: string[];
+ /** The change touches UI paths, so the design-basis field must be filled in. */
+ touchesUi: boolean;
+ repository: string;
+ /** An earlier submission of this change; submitting again updates it. */
+ existing?: CindyMakeContributionView;
+}
+
+export type CindyMakeContributionRequest =
+ | { action: 'status' }
+ | { action: 'draft'; runId: string }
+ | {
+ action: 'submit';
+ runId: string;
+ snapshotId: string;
+ title: string;
+ body: string;
+ name: string;
+ email: string;
+ };
+
+export const CINDY_MAKE_CONTRIBUTION_ERRORS = [
+ /** The personal version is not saved to the user's GitHub yet. */
+ 'notBound',
+ 'github',
+ 'account',
+ /** The change or its saved content is no longer available on this computer. */
+ 'unavailable',
+ /** The shown source or its confirmation is no longer current. Review a new draft. */
+ 'changed',
+ /** The change does not apply cleanly to the latest official code. */
+ 'conflict',
+ /** The change has no difference from the latest official code. */
+ 'empty',
+ 'invalid',
+ 'network',
+ 'workflowScope',
+ 'failed',
+] as const;
+export type CindyMakeContributionError = (typeof CINDY_MAKE_CONTRIBUTION_ERRORS)[number];
+
+export const CONTRIBUTION_LIMITS = { title: 200, body: 60_000, name: 100, email: 254 } as const;
+
+/**
+ * Mirrors the UI path heuristic of `scripts/check-pr-design-basis.mjs`; keep both lists
+ * in sync so a prefilled PR body asks for the design basis exactly when CI will.
+ */
+const UI_PATH_PREFIXES = [
+ 'apps/desktop/src/renderer/',
+ 'apps/mobile/app/',
+ 'apps/mobile/src/auth/',
+ 'apps/mobile/src/components/',
+ 'apps/mobile/src/i18n/',
+ 'apps/mobile/src/notifications/',
+ 'apps/mobile/src/session/',
+ 'apps/mobile/src/settings/',
+ 'apps/mobile/src/theme/',
+];
+const UI_FILE_SUFFIXES = ['.css', '.scss', '.less'];
+
+export function touchesUiPath(path: string): boolean {
+ return (
+ UI_PATH_PREFIXES.some((prefix) => path.startsWith(prefix)) ||
+ UI_FILE_SUFFIXES.some((suffix) => path.endsWith(suffix))
+ );
+}
+
+/** A plain address check; DCO only needs a real, reachable identity, verified by the author. */
+export function isContributionEmail(value: string): boolean {
+ return (
+ /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(value) && value.length <= CONTRIBUTION_LIMITS.email
+ );
+}
diff --git a/apps/desktop/src/shared/cindyMakeDoctor.ts b/apps/desktop/src/shared/cindyMakeDoctor.ts
index 2db19f162f..b4ef6f81e6 100644
--- a/apps/desktop/src/shared/cindyMakeDoctor.ts
+++ b/apps/desktop/src/shared/cindyMakeDoctor.ts
@@ -136,6 +136,10 @@ export interface CindyMakeTaskActionState {
export interface CindyMakeGlobalState {
upstreamMerge?: import('./cindyMakeMerge').CindyMakeMergeState;
+ /** Device-level GitHub binding of the personal version; absent until first read. */
+ personalRemote?: import('./cindyMakePersonalRemote').CindyMakePersonalRemoteState;
+ /** The single Sync of the personal version (GitHub steps only when shared there). */
+ personalSync?: import('./cindyMakeSync').CindyMakeSyncState;
ownerStamp?: import('./dataOwnerPush').DataOwnerPushStamp;
environmentCheck?: CindyMakeOperationSnapshot;
environmentPrepare?: CindyMakeOperationSnapshot;
diff --git a/apps/desktop/src/shared/cindyMakeMerge.ts b/apps/desktop/src/shared/cindyMakeMerge.ts
index 4bcd8d7749..ff045e0766 100644
--- a/apps/desktop/src/shared/cindyMakeMerge.ts
+++ b/apps/desktop/src/shared/cindyMakeMerge.ts
@@ -45,15 +45,35 @@ export interface CindyMakeMergeState {
upstreamCommit: string;
baselineCommit?: string;
baselineTree?: string;
- /** Missing on retained file-only operations from older clients. */
- strategy?: 'rebase';
+ /**
+ * Missing on retained file-only operations from older clients. `combine` is the
+ * same rebase lifecycle for combining with the GitHub version; older clients
+ * reject it instead of finishing it as an official update.
+ */
+ strategy?: 'rebase' | 'combine';
rebaseBase?: string;
/** Merge-only resolutions need an explicit content review before a flattened rebase is adopted. */
rebaseReview?: boolean;
/** Native feature integration/undo shares the same retained conflict lifecycle. */
feature?: MakeFeatureMergePlan;
+ /**
+ * Combining the personal version saved on the user's GitHub (`commit`) with this
+ * computer's. The other side's own changes are replayed onto `upstreamCommit`
+ * (GitHub's version, or this computer's when it is on the newer official version);
+ * the result's official base is `base`. The same rebase lifecycle applies.
+ */
+ remote?: { base: string; commit?: string };
/** Source sync started while preparing a task; stopping preparation owns its candidate. */
taskOwned?: boolean;
+ /** The resolver ended its turn with conflicts left: it waits for the user's answer in its task. */
+ needsInput?: boolean;
+ /**
+ * Personal changes the result does not carry (named ones first, at most 50). The task is
+ * reminded once; then the user decides between using the result anyway and Abandon.
+ */
+ missing?: { count: number; commits: string[]; result?: string };
+ /** The resolver was already asked to put the missing changes back. */
+ reminded?: boolean;
tree?: string;
commit?: string;
sessionId?: string;
diff --git a/apps/desktop/src/shared/cindyMakePersonalRemote.ts b/apps/desktop/src/shared/cindyMakePersonalRemote.ts
new file mode 100644
index 0000000000..265e63d5ab
--- /dev/null
+++ b/apps/desktop/src/shared/cindyMakePersonalRemote.ts
@@ -0,0 +1,128 @@
+/**
+ * Renderer-visible state of the personal-version GitHub binding.
+ *
+ * Only public facts cross this boundary: the GitHub login and `<owner>/<repo>`
+ * name. Tokens, authenticated URLs, local paths and raw Git output never do.
+ */
+
+export const CINDY_MAKE_REMOTE_STEPS = [
+ 'waiting',
+ 'preparing',
+ 'fork',
+ 'connecting',
+ 'retrieving',
+ 'uploading',
+] as const;
+export type CindyMakeRemoteStep = (typeof CINDY_MAKE_REMOTE_STEPS)[number];
+
+export const CINDY_MAKE_REMOTE_ERRORS = [
+ /** No usable GitHub connection, or GitHub rejected the credential. */
+ 'github',
+ /** The connected GitHub login differs from the bound repository owner. */
+ 'account',
+ /** The account already has a same-named repository that is not an official fork. */
+ 'forkConflict',
+ /** GitHub accepted the fork request, but the repository never became reachable. */
+ 'forkUnavailable',
+ /** The bound repository no longer exists on GitHub (deleted, or renamed beyond recognition). */
+ 'forkMissing',
+ /** The bound repository is archived: GitHub accepts no uploads. */
+ 'forkArchived',
+ 'network',
+ /** The credential lacks the `workflow` scope needed to push workflow file changes. */
+ 'workflowScope',
+ /** The managed personal source is missing or not in a state that can be synchronized. */
+ 'source',
+ /** Git older than 2.36 cannot receive a per-command credential or compare merges. */
+ 'gitOutdated',
+ /** The application stopped while an operation was running; nothing is replayed. */
+ 'interrupted',
+ 'failed',
+] as const;
+export type CindyMakeRemoteError = (typeof CINDY_MAKE_REMOTE_ERRORS)[number];
+
+export const CINDY_MAKE_REMOTE_SYNC = [
+ /** GitHub holds exactly the local established personal version. */
+ 'synced',
+ /** Local changes are not generated yet; only generated content is uploaded. */
+ 'pendingBuild',
+ /**
+ * Both sides have changes, and this computer's are not generated yet: generating
+ * first lets the next Sync combine them with the other computer's.
+ */
+ 'buildFirst',
+ /** Changes from another computer were retrieved; generating makes them usable here. */
+ 'retrieved',
+ /** Uploading failed; the local personal version is unaffected. */
+ 'pending',
+ /** GitHub has changes from another computer that this computer does not have. */
+ 'remoteAhead',
+ /** GitHub and this computer both have changes the other lacks. */
+ 'diverged',
+ /**
+ * Both sides have changes that could not be taken over automatically; Sync
+ * combines them in an isolated folder, with a conflict task when needed.
+ */
+ 'needsMerge',
+] as const;
+export type CindyMakeRemoteSync = (typeof CINDY_MAKE_REMOTE_SYNC)[number];
+
+export interface CindyMakePersonalRemoteState {
+ /** The user's persisted storage decision; undefined until they choose. */
+ choice?: 'github' | 'local';
+ /** Bound repository, `<owner>/<name>`. */
+ repository?: string;
+ /** GitHub login the repository was bound with. */
+ login?: string;
+ /** Live GitHub connection of this computer. */
+ github: 'connected' | 'missing' | 'unavailable';
+ githubLogin?: string;
+ running?: 'save' | 'sync' | 'disconnect';
+ step?: CindyMakeRemoteStep;
+ sync?: CindyMakeRemoteSync;
+ error?: CindyMakeRemoteError;
+ syncedAt?: number;
+ /** Before binding: the account already holds a personal version saved by another computer. */
+ existingPersonal?: string;
+ /** This computer has a prepared personal source. */
+ sourceReady?: boolean;
+ /** Keep offering "save to your GitHub" until bound or explicitly declined. */
+ offerMigration: boolean;
+}
+
+export const CINDY_MAKE_REMOTE_ACTIONS = [
+ 'status',
+ 'refresh',
+ 'save',
+ 'sync',
+ 'keep-local',
+ 'disconnect',
+] as const;
+export type CindyMakePersonalRemoteAction = (typeof CINDY_MAKE_REMOTE_ACTIONS)[number];
+
+const GITHUB_LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;
+const GITHUB_REPOSITORY_NAME = /^[A-Za-z0-9._-]{1,100}$/;
+
+export function isGithubLogin(value: unknown): value is string {
+ return typeof value === 'string' && GITHUB_LOGIN.test(value);
+}
+
+/** `<owner>/<name>` with GitHub's character rules; `.` and `..` are not repository names. */
+export function isGithubRepository(value: unknown): value is string {
+ if (typeof value !== 'string') return false;
+ const [owner, name, ...rest] = value.split('/');
+ return (
+ rest.length === 0 &&
+ isGithubLogin(owner) &&
+ typeof name === 'string' &&
+ GITHUB_REPOSITORY_NAME.test(name) &&
+ name !== '.' &&
+ name !== '..' &&
+ !name.endsWith('.git')
+ );
+}
+
+/** GitHub logins are case-insensitive. */
+export function sameGithubLogin(left: string | undefined, right: string | undefined): boolean {
+ return !!left && !!right && left.toLowerCase() === right.toLowerCase();
+}
diff --git a/apps/desktop/src/shared/cindyMakeSync.ts b/apps/desktop/src/shared/cindyMakeSync.ts
new file mode 100644
index 0000000000..cbc2c89533
--- /dev/null
+++ b/apps/desktop/src/shared/cindyMakeSync.ts
@@ -0,0 +1,117 @@
+/**
+ * One Sync for every personal version: bring in changes saved on the user's
+ * GitHub (when shared there), move to the official version, and upload. Without
+ * GitHub the same pipeline runs with the sharing steps skipped.
+ */
+
+export const CINDY_MAKE_SYNC_STEPS = [
+ /** Finishing an earlier conflict before anything else. */
+ 'resuming',
+ /** Fetching and taking over changes saved by other computers. */
+ 'github',
+ /** Combining both sides' changes in an isolated folder. */
+ 'combine',
+ /** Moving to the official version. */
+ 'official',
+ /** Uploading the result to the user's GitHub. */
+ 'upload',
+] as const;
+export type CindyMakeSyncStep = (typeof CINDY_MAKE_SYNC_STEPS)[number];
+
+export const CINDY_MAKE_SYNC_ERRORS = [
+ 'busy',
+ /** The managed source is missing or not ready. */
+ 'source',
+ /** The GitHub connection or upload failed; the local result is kept. */
+ 'github',
+ 'network',
+ /** The two personal versions follow unrelated official lines. */
+ 'diverged',
+ /** The official version could not be looked up. */
+ 'unavailable',
+ /** The conflict task was cancelled; nothing was adopted. */
+ 'cancelled',
+ /** GitHub received a newer version from another computer during Sync. */
+ 'changed',
+ /** A change in the change history is being added or undone; Sync waits for it. */
+ 'featurePending',
+ /** This computer's Git is too old for sharing through GitHub. */
+ 'gitOutdated',
+ /** The saved GitHub repository no longer exists or cannot be written. */
+ 'forkMissing',
+ /** The saved GitHub repository is archived: GitHub accepts no uploads. */
+ 'forkArchived',
+ 'failed',
+] as const;
+export type CindyMakeSyncError = (typeof CINDY_MAKE_SYNC_ERRORS)[number];
+
+/** Why Sync stopped at a source operation, from the user's point of view. */
+export type CindyMakeSyncWaitReason =
+ /** Its task is resolving the conflict; Sync continues by itself once it is adopted. */
+ | 'working'
+ /** The task asked the user something and waits for the answer. */
+ | 'input'
+ /** The app stopped while it was being handled. */
+ | 'interrupted'
+ /** The result lost some of the user's changes: use it anyway, or abandon. */
+ | 'missing'
+ /** The personal version changed meanwhile; the work has to start over. */
+ | 'stale'
+ /** Its task is not there (never opened, or removed): Continue opens one for the same work. */
+ | 'paused'
+ /** It belongs to the account signed in when it started; switching back continues it. */
+ | 'otherAccount'
+ | 'failed';
+
+export interface CindyMakeSyncWaiting {
+ kind: 'combine' | 'official';
+ reason: CindyMakeSyncWaitReason;
+ sessionId?: string;
+ /** For `missing`: how many changes are not in the result. */
+ missing?: number;
+ /** Abandon was requested and is being carried out. */
+ abandoning?: boolean;
+}
+
+export interface CindyMakeSyncDone {
+ at: number;
+ /** Official version the personal version is on now. */
+ ref?: string;
+ /** Already on a newer official version than this computer's Cindy can follow. */
+ ahead?: boolean;
+ /** A newer official release that needs this computer's Cindy updated first. */
+ held?: string;
+ /** This computer's changes reach GitHub once they are generated. */
+ uploadAfterBuild?: boolean;
+ /** Both computers changed it and this computer's changes are not generated yet. */
+ buildFirst?: boolean;
+ /** The official version (ref) waits until this computer's changes are generated. */
+ generateFirst?: string;
+}
+
+export interface CindyMakeSyncState {
+ running?: boolean;
+ step?: CindyMakeSyncStep;
+ /** A source operation Sync waits for (a conflict being resolved, or a decision). */
+ waiting?: CindyMakeSyncWaiting;
+ error?: CindyMakeSyncError;
+ /**
+ * With `cancelled`: what was given up. After a combine (or with `diverged`) the user
+ * can keep one side instead.
+ */
+ abandoned?: 'combine' | 'official';
+ /** The last completed Sync (also kept when its GitHub step failed). */
+ done?: CindyMakeSyncDone;
+}
+
+export interface CindyMakeSyncRequest {
+ /**
+ * `abandon` gives up the operation Sync waits for (nothing is adopted); `accept` uses
+ * a result that lost changes the user agreed to leave out.
+ */
+ action: 'sync' | 'status' | 'abandon' | 'accept' | 'keep';
+ /** For `keep`: which personal version stays when the two cannot be combined. */
+ side?: 'github' | 'local';
+ /** Agent preferences for a conflict task, chosen like a new Cindy Make task. */
+ createOptions?: import('./cindyMakeDoctor').CindyMakeTaskOptions;
+}
diff --git a/apps/mobile/src/__tests__/SessionResourceCards.test.tsx b/apps/mobile/src/__tests__/SessionResourceCards.test.tsx
index eb8091711c..7f0886db83 100644
--- a/apps/mobile/src/__tests__/SessionResourceCards.test.tsx
+++ b/apps/mobile/src/__tests__/SessionResourceCards.test.tsx
@@ -92,6 +92,31 @@ afterEach(() => {
});
describe("SessionResourceCards failure presentation", () => {
+ it("shows read-only sync and PR status without workflow controls", () => {
+ render(
+ state({
+ resources: [
+ {
+ ...card,
+ display: { title: "Cindy Make" },
+ blocks: [
+ {
+ id: "personal-status",
+ primitive: "markdown",
+ fallbackMarkdown: "Cindy Make\n\nSynced\n\nSubmitted #42",
+ },
+ ],
+ actions: [],
+ },
+ ],
+ }),
+ );
+ expect(host.textContent).toContain("Synced");
+ expect(host.textContent).toContain("Submitted #42");
+ expect(host.querySelector("button")).toBeNull();
+ expect(host.querySelector("progress")).toBeNull();
+ });
+
it("renders nothing when the first manifest read fails", () => {
render(state({ failed: true, fresh: false }));
expect(host.textContent).toBe("");
diff --git a/docs/cindy-make-upstream.md b/docs/cindy-make-upstream.md
index ff00472b6a..145e3017a9 100644
--- a/docs/cindy-make-upstream.md
+++ b/docs/cindy-make-upstream.md
@@ -72,15 +72,15 @@ Main 负责网络和 Git,UI 只消费报告;运行版本摘要在结果详
### 文件与分支边界(2026-09-18 用户更新裁决)
用户选择本地提交、合并与 rebase,替代此前只应用文件且永不提交的模型。`main` 只包含
-官方提交,永不推送到官方仓。Cindy Make 对远端的唯一写操作是「个人 fork 同步」一节
-允许的推送:仅 `cindy-personal` 与其官方基线记录,仅推到用户自己显式绑定的 fork
-(2026-09-22 用户裁决,替代此前“永不推送远端”)。模型在任务 worktree 修改、验证并回报完成后,宿主在
+官方提交,永不推送到官方仓。Cindy Make 对远端的写操作只有「个人版 GitHub 同步与提交给官方」
+一节列出的几项:推送 `cindy-personal`、同步 fork 的 `main`、推送单项修改的
+提交分支并创建 PR,且只写用户自己显式绑定的 fork 与用户逐次确认的 PR(2026-09-22 用户裁决
+替代此前“永不推送远端”,2026-09-30 扩展到提交给官方;该节部分实现,剩余项见该节状态清单)。模型在任务 worktree 修改、验证并回报完成后,宿主在
该任务分支创建带 DCO 签名的本地提交;未成功结束的轮次不提交或生成完成卡。没有新改动
不制造空提交。通用自动保存点仍跳过托管目录,避免在明确完成边界之外提交。
-生成个人版是否先同步最新官方源码,由设置页「生成前同步最新源码」控制,默认关闭。开启时先
-复用既有官方源码同步流程,同步完成后把功能分支的提交合入 `cindy-personal`;关闭时直接使用
-当前 `cindy-personal`。随后都从这个实际源码目录安装依赖、
+生成个人版直接使用当前 `cindy-personal`,不先同步官方源码(原设置页「生成前同步最新源码」开关
+已于 2026-10-01 取消,旧的开启值按关闭读取;同步是唯一会把个人版移到新官方版本的地方)。随后都从这个实际源码目录安装依赖、
检查、构建。临时目录用于检测冲突并形成候选合并提交,不在那里构建。成功合入后的
个人源码工作区保持干净。按 2026-09-20 用户裁决,生成失败/取消时自动撤回尚未生成成功版本的
连续合入,恢复此前个人源码,保留任务分支、每轮修改与已经生成的版本;再次生成会自动重新合入。
@@ -95,7 +95,7 @@ rebase 到新官方基线(禁止 update-refs 自动改动其他任务分支)
手动同步时先弹窗询问,确认后才创建独立任务并沿用当前模型设置;取消则放弃本次合入、保留个人版。冲突解决并完整结束 rebase、校验个人源码未并发
变化后,才更新 cindy-personal。结果是“最新 main + 个人提交”,不是要求两者 hash 相等;
官方更新不再堆积在未提交列表中。旧版遗留冲突现场仍可完成并迁移,新旧路径均不推送官方仓;
-采纳后若已开启 fork 同步,由宿主按「个人 fork 同步」一节推送 `cindy-personal`。
+采纳后若已开启 GitHub 同步,由宿主按「个人版 GitHub 同步与提交给官方」一节推送 `cindy-personal`。
实现见 [localHistory](../apps/desktop/src/main/cindy-make/localHistory.ts) 与
[真实 Git 回归](../apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts)。
@@ -106,12 +106,10 @@ worktree。停止准备会停止本次准备所拥有的冲突任务并清理候
同步成功后才从更新后的 `cindy-personal` 创建任务分支,因此任务从一开始就在最新个人版源码上
修改。制作任务准备卡在“准备个人项目源码”和“创建任务分支和工作目录”之间单独显示
“正在更新个人版源码”;发生冲突时该步骤保持进行中,直到独立冲突任务完成采纳与清理。
-Settings 的手动“同步最新源码”继续可用。创建制作任务前的同步仍为固定流程;另设的
-“生成前同步最新源码”开关只控制打包入场,默认关闭。
+Settings 的「同步」继续可用。创建制作任务前的同步仍为固定流程(同步进行中先等它结束;有冲突留在
+处理任务里时不同步,新任务从当前个人版开始)。
-生成个人版时,若“生成前同步最新源码”已开启,则先把 `cindy-personal` 更新到当前渠道的最新
-官方基线;该步骤在进度中单独显示,冲突沿用既有独立处理任务,完成后才继续合入修改和打包。
-开关关闭时把任务修改合入当前个人版基线后直接检查和打包。后续生成失败只撤回未生成成功版本的功能
+生成个人版时把任务修改合入当前个人版基线后直接检查和打包。后续生成失败只撤回未生成成功版本的功能
合入。手机/远程资源沿用主机翻译后的准备状态和既有动作。实现与回归见
[任务准备](../apps/desktop/src/main/cindy-make/taskRuntime.ts)、
[同步运行时](../apps/desktop/src/main/cindy-make/upstreamMergeRuntime.ts) 和
@@ -129,7 +127,8 @@ Settings 的手动“同步最新源码”继续可用。创建制作任务前
Main 主动通知设置页重读历史与版本,5 秒轮询只作异常兜底,不作为正常完成反馈。页签支持方向键、Home/End 及独立面板标识。
- 输入 /cindy-make 需求后,在当前页面弹窗检查环境、准备个人版源码并查询上游;
这段前置流程不创建任务、不创建 worktree;源码准备与 Settings 共用同一流程,
- 准备 Git 内容后按锁文件预热依赖缓存,不生成个人分支的依赖目录或执行安装脚本。
+ 准备 Git 内容后按锁文件预热依赖缓存,不生成个人分支的依赖目录或执行安装脚本,也不执行 `.pnpmfile.cjs` 等
+ pnpm 钩子(预热只是按锁文件取包,正确性由后续安装负责)。
关闭弹窗不会留下空任务。Settings 的制作入口与侧栏入口复用同一个弹窗。
前置弹窗通过右上角关闭图标退出,不再单设底部取消;图标、Esc 和遮罩点击均先二次确认,
提示随当前阶段更新,说明关闭会停止什么、保留什么;环境/源码准备还须说明设置页共享作业也会停止。
@@ -145,7 +144,8 @@ Settings 的手动“同步最新源码”继续可用。创建制作任务前
- Settings、消息卡片/弹窗和侧栏读取同一个 Main 快照;准备卡显示实际阶段、工具下载量、
Git 阶段以及 pnpm 的解析/复用/下载/添加数量;安装开始与安装脚本执行另有状态提示,
不伪造总进度。Settings 和前置弹窗均显示缓存预热的解析/复用/下载数量;
- 缓存缺失或版本变化时按需补下载,任务 worktree 再复用缓存独立安装并执行安装脚本。
+ 缓存缺失或版本变化时按需补下载,任务 worktree 再复用缓存独立安装并执行安装脚本
+ (来自 GitHub、这台电脑尚未生成覆盖的未验证内容除外,见下文「同步:一个按钮」)。
Settings 源码准备和更新共用一个状态区域:区分等待其他工程操作、Git 检查、上游版本查询和本地源码检查。
源码目录直接显示,打开和删除按钮在路径行最右侧对齐,不提供源码详情折叠入口。
源码准备失败或停止时保留结果和原因,按钮为「重试准备」;更新失败或冲突时显示原因及处理入口。
@@ -355,9 +355,10 @@ Settings 的手动“同步最新源码”继续可用。创建制作任务前
commit 的祖先关系误判已经撤销或无法撤销。Git 采纳和历史写入之间中断可显式重试,
历史回执按操作 ID 去重;重启不静默重放写操作。
- 制作历史卡右上角的「重新生成个人版」是全局动作,只构建当前本地 `cindy-personal`,不使用
- 某条历史快照,也不自动加入尚未合入的任务。设置页「生成前同步最新源码」开启时,它与完成卡、
- 批量制作共用同一前置同步步骤;关闭时不访问 GitHub,默认关闭。
- 筛选「待合入」时,工具栏右侧保留「制作个人版」进入多选;支持全选当前搜索列表,
+ 某条历史快照,也不自动加入尚未合入的任务,也不访问 GitHub。还没有生成过个人版、但个人版已有可用的
+ 变化(例如新电脑取回了另一台电脑的修改)时,同一位置显示「生成个人版」。
+ 筛选「待合入」时(只含未合入与有新改动的记录;已撤销的只能通过它自己的「重新加入个人版」恢复,
+ 批量制作不会把它加回),工具栏右侧保留「制作个人版」进入多选;支持全选当前搜索列表,
二次确认按创建时间从老到新列出所选记录。Main 固定已确认的完成记录、commit 与文件树,
先停止所选记录正在运行的隔离测试,再核验全部选择,逐条合入并且只在全部成功后生成一次。
合入期间显示当前条目与总数;离开设置不取消流程。冲突或取消停止后续合入与打包,
@@ -434,7 +435,7 @@ Settings 的手动“同步最新源码”继续可用。创建制作任务前
生成个人版卡片。 首条用户需求由 Main 固定组装,要求理解双方修改、保留本地功能、
安全解决冲突,并按仓库规则验证。允许暂存并继续现有 rebase,不重新开始、不跳过个人
提交、不修改其他目录,也不推送;结束后宿主提交必要的附加修复。任务本身永不推送;
- 采纳后向 fork 的推送只由宿主按「个人 fork 同步」一节执行。
+ 采纳后向 fork 的推送只由宿主按「个人版 GitHub 同步与提交给官方」一节执行。
- 正常执行结束后,Main 核验目录归属、分支身份、原有 HEAD、文件冲突状态及
`git diff --check`,再应用结果。自动检查不代表功能测试已通过;功能验证由解决冲突的
任务执行并如实说明。个人版期间发生变化则停止应用并保留现场;中断、失败或
@@ -489,138 +490,438 @@ Settings 的手动“同步最新源码”继续可用。创建制作任务前
[真实 Git 回归](../apps/desktop/src/main/cindy-make/__tests__/upstreamMerge.git-integration.test.ts)
覆盖无冲突自动应用、冲突隔离与期间新增未提交个人改动的保护。
-## 个人 fork 同步(2026-09-22 用户裁决,设计稿,尚未实现)
-
-目标:本机检测到可用的个人 GitHub 身份时,个人版源码以用户自己 fork 出来的
-`<login>/cindy` 作为「个人版远端仓库」。`cindy-personal` 仍是唯一的个人版分支,仍在本机
-记录、合入与生成;区别只是它同时被推送到 fork,换一台机器、同一 GitHub 账号即可取回,
-fork 也为日后向官方仓提 PR 留出入口。没有可用身份时,行为与本节之前完全一致。
-
-### 身份来源与凭证边界
-
-- 第一阶段只接受 GitHub CLI 的登录态,复用
- [ghCliTokenSource](../apps/desktop/src/main/git-context/ghCliTokenSource.ts):`gh` 未安装、
- 未登录、超时都视为“没有身份”,源码与生成逻辑走原路径。身份只在「首次选择」一步和
- Settings 的「开启同步」处被询问;不在其他时机弹窗、不自动安装 gh。
- git credential helper、SSH key、粘贴 PAT 与 Cindy 内置 GitHub 登录(OAuth Device Flow)
- 都不在第一阶段范围;后者需要仓外注册 OAuth App,用户裁决本轮不做。
-- token 只在内存,沿用 ghCliTokenSource 的缓存。Git 访问 fork 时用进程环境
- `GIT_CONFIG_COUNT/KEY/VALUE` 注入 `http.https://github.com/<login>/<repo>.git.extraheader`
- (Basic `x-access-token:<token>`),不写 `.git/config`、不进 argv、不落盘、不进日志;
- 不依赖用户是否配置过 `gh auth setup-git`。remote URL 本身不带凭证。
- 错误输出沿用 `sourceGit` 的脱敏;主日志只记阶段、结果码与 ahead/behind 数。
-- 绑定的是 login,不是 token:确认开启时用 `GET /user` 取 login,连同 fork 仓库名
- 写入 `cindy-make-settings.json`(非秘密:`personalRemote: { login, repository, confirmedAt }`)。
- 之后每次操作先核对当前 gh 登录的 login 与绑定一致;不一致时停止推送与拉取,Settings 显示
- “当前 GitHub CLI 登录账号与已绑定的 fork 不一致”,不自动改绑、不推到另一账号的仓库。
-- Renderer 只传动作与版本 ID,不传 login、URL 或 token;fork 名、URL 与凭证一律由 Main 解析。
-
-### Fork 的发现、创建与确认
-
-- 首次选择(2026-09-22 用户裁决):本机还没有托管源码、且 `cindy-make-settings.json` 没有
- 记录存放方式时,两个会触发首次源码准备的入口(Settings 版本控制页的准备入口、`/cindy-make`
- 前置弹窗)在 clone 开始前插入一步“个人版存放方式”,两个选项:
- - 「存到我的 GitHub(`<login>/cindy`)」:gh 已登录时默认选中;说明将使用的账号、fork 名、
- **fork 公开可见**(`makecindy/cindy` 为公开仓,GitHub 不允许其 fork 设为私有,因此个人版
- 的修改会公开)、只推送 `cindy-personal` 及其官方基线记录、可随时关闭。
- - 「只存这台电脑」:gh 不可用时默认选中,此时上一项置灰并说明“安装并登录 GitHub CLI
- (`gh auth login`)后可用,换电脑也能取回个人版”,提供「我已配置好,重新检测」按钮,
- 重新检测绕过 ghCliTokenSource 的负缓存。
- 选择结果持久化后开始准备,之后不再询问;改主意在 Settings「开启/关闭同步」。选择
- 「存到 GitHub」即构成建 fork 这一外部写操作的显式授权,不再另设第二个确认弹窗。
- 已有托管源码的老用户不经过这一步,只能从 Settings 开启。若准备由其他路径触发而没有记录
- (例如旧版残留状态),按「只存这台电脑」处理。
-- 选择「存到 GitHub」或从 Settings 开启后,先 `GET /repos/<login>/cindy`:存在且 `fork === true`
- 且 `parent.full_name === 'makecindy/cindy'` 才视为可用;不存在则
- `POST /repos/makecindy/cindy/forks` 并轮询直到可 `ls-remote`;存在但不是官方仓的 fork
- (用户自己的同名仓)则拒绝并说明,不覆盖、不改名,允许用户手填 `<login>/<name>` 指定已有
- fork,同样校验 `parent` 后才绑定。
-- 首次选择时若 fork 存在且远端已有 `cindy-personal`(换机器场景),该步直接在「存到 GitHub」
- 选项下说明“你的 GitHub 上已有个人版(基于官方 vX、N 个个人提交),将以它作为这台电脑的
- 起点”,不再单独弹窗;准备时按下节从 fork 恢复基线。选「只存这台电脑」则按原逻辑从官方
- ref 建基线,之后开启同步时按分叉流程处理。
-- 本机已有 `cindy-personal`(此前无 gh 或未开启)、后来从 Settings 开启同步:这是就地
- 转换,不重新 clone、不改 `origin`、不动任务分支/worktree/依赖/制作历史/已生成版本。
- 步骤与失败语义:① 先按 `commitPersonalFiles` 把遗留未提交内容转成本地提交(旧 HEAD、
- 暂存区、文件树先备份到 `refs/cindy-make/history-backups/*`),失败则一切未变;② 检查/
- 创建 fork,纯远端操作,失败只提示原因、可重试;③ `remote add personal`;④ fork 上没有
- `cindy-personal` 时按显式 refspec 初始推送本机 tip 与 `personal-upstream`,只向远端追加,
- 失败标“待推送”、本地照常可用。fork 上已有另一台机器的个人版时,确认弹窗额外显示两边的
- 官方基线与个人提交数,默认操作为「合并并开启同步」,走下节分叉流程(候选目录内 rebase、
- `refs/cindy-make/backups/<ID>/personal` 备份、成功才采纳),冲突则建任务,成功后才推送;
- 同时提供「以 fork 为准」「以本机为准」两个备份后覆盖的兜底,均需二次确认。
- 确认弹窗须写明现有个人版的官方基线、个人提交数、将被整理的未提交修改数,以及“本机源码、
- 任务和已生成的版本不会改动”。开启同步排在项目队列中,与准备、测试、生成互斥,等待时显示
- “等待其他工程操作”。首次选择之后 gh 可用性再变化不主动弹窗,只在 Settings 概览卡出现
- 「开启同步」;选过「只存这台电脑」的用户,概览卡保留一行“安装并登录 GitHub CLI 后可将
- 个人版同步到你的 GitHub”。
-
-### 本地仓库布局与推送内容
-
-- `origin` 仍指向官方仓,所有官方逻辑(`origin/main` 语义、`clearOnly` 的 URL 校验、
- 运行版本查询、迁移基线计算)不变;新增名为 `personal` 的 remote 指向 fork(不带凭证的
- HTTPS URL)。常量放在 `sourcePaths`。清理源码时一并删除 `personal` remote 与
- `refs/remotes/personal/*`;关闭同步只删 remote 与远端跟踪 ref,不删 fork、不删本地分支。
- 用户可见的说法始终是“个人版源码仓库 = 你的 fork”,不暴露 remote 名。
-- 只推送两个 ref:`refs/heads/cindy-personal` 与 `refs/cindy-make/personal-upstream`
- (推到 fork 的同名 ref)。不推 `main`、任务分支 `cindy-make/*`、`cindy-merge/*`,也不推
- `refs/cindy-make/tasks|features|backups|failed-builds|history-backups/*`——这些是本机的
- 工作快照与恢复引用,另一台机器无法复用。
-- 推送时机只有三个,都在 `cindy-personal` 已成为**最终状态**之后:
- 1. 个人版生成成功并登记到版本列表之后(`buildCindyPersonal` 发布、`onBuildState` 进入
- `ready` 之后),推送该次生成实际使用的 commit(`artifact.commit`),而不是分支当前名下
- 可能已经变化的 tip。功能合入采纳的那一刻**不推送**:合入在生成成功前是临时的,检查或
- 打包失败会撤回;若此时已推,远端会保留本地已撤回的提交,下次同步会把本机误快进回去。
- 2. 官方更新采纳之后(Settings 手动同步或创建制作任务前的自动同步)。官方更新的采纳不参与失败回退,
- 属于最终状态,可以立即推送。
- 3. 首次开启同步时的一次初始推送。
- 推送在项目锁外、当次操作的 Git 采纳与版本登记全部完成后进行,失败不改变本地结果,
- 只在状态里记“待推送”,完成卡与 Settings 的生成结果显示“已同步到 fork/未同步”,
- Settings 提供「立即同步」;重启不自动重放推送,下一次让 `cindy-personal` 前进的操作
- 入场时作为可见的前置步骤补推。
-- 一律以显式 refspec 推送已核验的 commit:
- `push personal <commit>:refs/heads/cindy-personal --force-with-lease=refs/heads/cindy-personal:<refs/remotes/personal/cindy-personal>`
- (`personal-upstream` 同样按 commit 推)。官方更新 rebase 会改写历史,普通 push 必被拒;
- lease 保证不覆盖另一台机器已推送的内容。推送前核验该 commit 仍是本地 `cindy-personal`
- 的 tip 或其祖先,否则放弃本次推送并标记待推送。lease 失败即视为分叉,进入下节流程,
- 绝不追加 `--force`。
-
-### 多机同步:拉取、快进与分叉(阶段 2)
-
-- 任何让 `cindy-personal` 前进的操作(合入、官方更新、生成、「立即同步」)入场时,若身份可用,
- 先 `fetch personal cindy-personal personal-upstream`。网络失败不阻止本地操作,但本次标记
- “远端状态未知、未推送”。
-- 比较本地与远端 `cindy-personal`:相同则无事;远端是本地祖先则本地领先,直接推送;本地是远端
- 祖先则先 `commitPersonalFiles` 保证工作区干净,再 `reset --keep` 快进本地并采用远端的
- `personal-upstream`,任务 worktree 不受影响。
-- 两边分叉时自动处理,复用官方更新的机制(`merge-worktrees/<ID>` 候选目录、`cindy-merge/<ID>`
- 分支、`refs/cindy-make/backups/<ID>/*` 备份、同一确认弹窗与 `cindy-make-merge` 任务):
- 1. 先统一官方基线。读取两边的 `personal-upstream`(缺失时以 `merge-base(cindy-personal,
- origin/main)` 代替),取较新者为目标基线;落后的一侧先用既有官方更新 rebase 抬到该基线
- (远端一侧在候选目录内完成,不改动 fork)。两个基线互不为祖先时不自动处理,见下。
- 2. 再把本机独有的个人提交 rebase 到远端个人版之上(`rebase --onto <远端 tip> <目标基线>`,
- Git 按 patch-id 跳过两边已相同的提交),`--no-update-refs --signoff` 与官方更新一致。
- 3. 无冲突:核验后 `reset --keep` 到结果、更新 `personal-upstream`、推送;有冲突:与官方更新
- 相同,先弹窗确认,确认后创建冲突任务,取消则保留本机个人版、本次不推送、远端不动。
-- 无法自动处理的情况(基线互不为祖先、远端 `cindy-personal` 不含任何官方提交、fork 不再是
- 官方仓的 fork 等)只报告原因,并提供两个明确操作:「以远端为准」把本地 `cindy-personal`
- 备份到 `refs/cindy-make/backups/*` 后重置为远端;「以本机为准」先把远端旧 tip 推到 fork 的
- `refs/cindy-make/backups/*` 再强推。两者都要二次确认,都不删除任务分支与已生成版本。
-- 同步期间与其他 Git 写操作共用项目队列;分叉处理占用的候选目录与冲突任务沿用现有清理、
- 取消与重启恢复规则。手机端只读投影同步状态,不新增远控写操作。
-
-### Settings 呈现
-
-- 版本控制页概览卡在个人版 hash 行下新增一行“个人版远端”:未开启/`<login>/cindy` 已同步/
- 待推送/分叉(本机领先 a、远端领先 b)/账号不一致/远端状态未知。状态字段进
- `MakeSourceStatus.personalRemote`,与源码状态同一刷新代次,迟到结果不能覆盖较新状态。
-- 操作只放同一处:未开启显示「开启同步」,待推送或分叉显示「立即同步」,已开启时提供「关闭
- 同步」;分叉无法自动处理时在此处展开「以远端为准」「以本机为准」。文案走 i18n,术语先查
- `i18n/GLOSSARY.md`(fork、个人版、同步)。
-
-### 不做与待定
-
-- 第一阶段不做:其他身份通道、向官方仓提 PR、同步任务分支或制作历史。
-- 提 PR(阶段 3)前必须先解决作者身份:`commitLocalFiles` 当前以
- `Cindy Make <[email protected]>` 作者并 signoff,官方仓 DCO 要求 sign-off 与
- author 一致且为真实身份,所以贡献路径需要以用户身份重做提交,届时另立裁决。
+## 个人版 GitHub 同步与提交给官方(2026-09-30 用户裁决,设计已定,部分实现)
+
+本节替代 2026-09-22 的「个人 fork 同步」设计稿。交互设计稿见
+[cindy-make-personal-version.html](../prototypes/cindy-make-personal-version.html)(单文件,含各场景与 Light/Dark)。
+
+实现进度(2026-10-01):
+- 已实现:一个「同步」按钮的统一管线(见「同步:一个按钮」)、GitHub 绑定与存量用户迁移(设置页「保存位置」
+ 一行与确认卡)、上传、从另一台电脑取回、
+ 新电脑起步、创建制作任务前同步、两台电脑各有新修改时的自动合并(无冲突时)、提交给官方(修改记录
+ 中的单项修改 → 官方 PR,含状态回显)、设置页白话概览(「个人版:官方 vX + 你的 N 项修改」「官方最新:
+ … · 个人版已包含/还没包含」,hash、本地 main、源码目录与清理放进默认折叠的「技术详情(给开发者)」)。
+ Main 侧见 [personalRemote](../apps/desktop/src/main/cindy-make/personalRemote.ts)、
+ [personalContribution](../apps/desktop/src/main/cindy-make/personalContribution.ts)、
+ [运行时接线](../apps/desktop/src/main/cindy-make/personalRemoteRuntime.ts);回归见同目录
+ `__tests__/personalRemote*.test.ts` 与 `__tests__/personalContribution*.test.ts`(含真实 Git 回归)。
+- 两边改到同一处、或两边在不同官方版本上时,由「同步」在独立目录合并,冲突自动开处理任务(已实现,见下文
+ 「拉取与多台电脑」)。
+- 未实现:跨电脑修改记录 trailer、
+ 设置页顶部「下一步」横幅与修改记录新状态/筛选、「更新个人版」与原版更新编排(涉及更新服务,须先
+ 按 `docs/dev-rules/cindy-updater.md` 单独确认方案)、采纳后从个人版替换为官方版本。
+
+### 面向普通用户的五条体验目标
+
+1. 可以简单地创建个人版。
+2. 同一个 GitHub 账号登录的不同电脑共用同一个个人版:本质是一份代码,打包始终来自
+ `cindy-personal` 这一个分支,每台电脑各自生成应用。
+3. 个人版的单项修改可以提交给官方(PR)。
+4. 个人版的每一项修改都有记录、可查看、可撤销和恢复。
+5. 个人版始终与真实线上版本同步:官方发布新版本后,个人版能一键跟上,修改自动保留。
+
+所有面向用户的文案必须让非开发者看懂。主界面不出现 hash、分支、main、提交数、rebase、
+合入等词;版本关系统一写成「官方 vX + 你的 N 项修改」;这些技术事实只放在默认折叠的
+「技术详情(给开发者)」里。用户看到的词:个人版、原版、修改、待生效、生成个人版、撤销/恢复、
+保存位置、你的 GitHub、提交给官方。术语落地前按 `i18n/GLOSSARY.md` 流程登记:「制作历史」改称
+「修改记录」、「从个人版移除/重新加入个人版」在列表中简称「撤销/恢复」、新增「提交给官方」
+「待生效」「保存位置」。
+
+### 用户裁决(2026-09-30)
+
+- 默认使用官方仓的 fork。`makecindy/cindy` 是公开仓,fork 必然公开,确认卡必须写明修改
+ 及修改标题在 GitHub 上公开可见。私有仓库(非 fork)作为以后可选项,本轮不做。
+- 已在本机使用的用户:自动检测、一次确认、之后全自动。建 fork 属于对外发布,不做完全静默。
+- 从 GitHub 取回其他电脑的新修改后,不自动生成个人版,只提示一键生成。
+- 提交给官方直接走本仓的 PR 流程(PR 模板、DCO 签名),以作者真实身份署名:预填本机 Git 的
+ `user.name`/`user.email`,没有时取 GitHub 公开资料,作者在确认弹窗里可改;不使用 noreply 匿名
+ 身份(2026-10-01 用户裁决,取代 2026-09-30 的 noreply 署名)。个人版自身的提交照旧由本机 Git
+ 身份署名,已有提交不改写。
+- 个人版只通过用户自己的 GitHub 仓库共享。没有 GitHub 账号的用户本质上不能共享个人版,
+ 也不能提交给官方;不以 Cindy 账号或服务端存储代替同步,也不由官方机器人代为提交修改。
+
+### 没有 GitHub 账号的用户
+
+- 创建个人版、修改记录、撤销/恢复、跟随官方更新都与有账号时完全相同。官方源码从公开
+ 仓匿名下载,不需要账号(仍需能访问 GitHub,这点与现状相同)。
+- 只少两项:多台电脑共用、提交给官方。设置页「保存位置」显示「只在这台电脑」,并如实说明
+ 「换电脑或重装系统后,只存在本机的个人版无法找回」,旁边提供「连接 GitHub」。
+- 点「提交给官方」时说明需要 GitHub,并引导连接;不弹其他提醒,不反复打扰。
+- 连接复用 Cindy 已有的 GitHub 连接流程(受管安装 gh + 网页验证码授权,无需用户自己装
+ 工具);弹窗说明没有账号可以在 github.com 免费注册。连接成功后进入下文的存量迁移。
+
+### 同步:一个按钮(2026-10-01 用户裁决,已实现)
+
+用户裁决:对用户只有一个「同步」按钮;整个过程要简单到非技术人员也能看懂;需要合并、解决冲突时在流程里自动开任务处理完,只有不确定的取舍才问用户;过程要稳定、可持续、可恢复。有没有 GitHub 账号的体验只在 GitHub 授权初始化和能否多台电脑共用上有区别,其他完全一样,架构上也只有一份逻辑。
+
+- 一条管线(Main [personalSync](../apps/desktop/src/main/cindy-make/personalSync.ts),接线见
+ [personalSyncRuntime](../apps/desktop/src/main/cindy-make/personalSyncRuntime.ts)),每一步都按当前 Git
+ 事实决定还剩什么要做:
+ 1. 先把上次没处理完的操作接着做完(重启前留下的、任务准备时留下的也算):已有任务就等它;真正的冲突
+ 还没有任务就直接开;没做完的放弃先做完;重放还没开始就被中断的候选目录不开任务(Agent 无从处理),
+ 等用户「放弃这次合并」。修改记录里有一项修改正在加入或撤销时不开始,说明原因。
+ 个人版缺少官方基线记录(较早准备的源码)时,先按设置页同样的规则推算一次并记下(只新建、不覆盖);
+ 新准备的源码在创建个人分支时就记下基线。
+ 2. 已保存到 GitHub 时:取回其他电脑的修改;能安全接过的(快进、无冲突自动合并)由 GitHub 同步完成,
+ 两边都有新修改时在独立目录合并(见下文「拉取与多台电脑」)。GitHub 出错(连接、网络、版本互不相关)
+ 不挡住这台电脑的官方更新,只在最后说明原因。
+ 3. 更新到官方版本(规则见下条),从不往回退。
+ 4. 已保存到 GitHub 时:上传结果;同步期间另一台电脑又上传了,就自动从第 2 步再来一次,仍然如此才提示。
+ GitHub 同步的「立即同步」先等已在进行的那次结束,再按当前事实重新判断,不拿旧结果充数。
+ 没有 GitHub 时跳过 2、4,1、3 完全相同;Settings 与任务卡看到的是同一个状态。同步期间占用源码
+ (与手动源码同步同一个占位),生成个人版要等它结束;同步自己的 GitHub 步骤不把这个占位当成「源码忙」。
+ 源码正忙时如实报告,未生成的修改提示「生成个人版后会自动上传」,都不报成功。
+- 冲突:同步发起的合并与官方更新在冲突时直接开 `cindy-make-merge` 处理任务,不再弹确认;任务处理完被采纳后,
+ 同步自动从下一步继续。Agent 无法同时保留两边功能时在任务里问用户:它带着没解决的冲突结束这一轮时,操作记为
+ 「在等你回答」(`needsInput`),不报失败;用户回答(新的一轮)后照常继续。
+- 不丢修改([uncarriedChanges](../apps/desktop/src/main/cindy-make/carriedChanges.ts)):官方更新、合并两台电脑的
+ 修改和同步直接取回版本用同一套核对。每个不在结果祖先中的修改,都要以原父提交为基线,核对把它再合到结果上
+ 是否完全不改变 Git 树;作者、作者时间与说明只能帮助定位对应的改写提交,不能单独证明保留。对应提交也必须
+ 通过同样的树核对,一对一使用,允许后续个人修改有意覆盖此前已应用的改动。不会因 `patch-id` 相同或去掉 hunk
+ 位置后补丁相同就跳过:不同代码块里的同一行是两项修改。Git 2.40 起用 `merge-tree --merge-base`;更旧的 Git
+ 使用系统临时目录中的私有索引做 `read-tree -m` 三树核对,必须没有未合并项且写出的树与待采纳结果完全相同。
+ 旧 Git 无法证明的同文件文本合并同样进入缺失修改流程。合并提交里额外做的修改按「把整个合并再应用一次不产生
+ 变化」核对。Git 输出到达捕获上限时一律不信任(数量对不上即视为核对
+ 失败)。没有冲突的 rebase 若仍漏了修改,候选目录交给处理任务先补回。处理任务结束后仍漏了修改:先在同一个任务
+ 里提醒一次(列出缺少的提交);仍缺时停下,由用户在同步状态里选择「仍然使用」(二次确认,说明缺少几项、两边
+ 原来的版本都留有备份)或「放弃这次合并」。「仍然使用」只对当时核对过的那个结果有效,之后又有变化就重新核对;
+ 每次失败都只带这次的缺失清单。不用逐词后备匹配猜测文字是否仍会执行;冲突解决融合同一行、把调用放进失活
+ 分支或注释、移动到另一个重复块等结果,以及相邻官方文本变化导致无法证明的改写,都走上述确认流程,不静默采纳。
+ 对应回归见 [keepChanges.git-integration.test.ts](../apps/desktop/src/main/cindy-make/__tests__/keepChanges.git-integration.test.ts)。
+- 放弃:等待中的同步可以「放弃这次合并」:停止处理任务、删除候选目录,个人版与 GitHub 上的版本都不变(同步
+ 发起的操作标记为 `taskOwned`,走与停止制作相同的回收路径)。放弃进行中时显示「正在放弃」,完成后说明「个人版和
+ GitHub 上的版本都没有变化」,放弃没能完成时可以再放弃一次。结果正在核对或采纳时不能放弃;没有所属账号的
+ 操作不会被写成半归属状态。属于其他账号的操作只是不显示,切回该账号后照常继续。
+- 等待原因:同步状态按操作的事实说明在等什么并给出对应操作——任务在处理(自动继续)、在等你回答、处理时 Cindy
+ 被关闭(打开任务说一句「继续」;还没开任务时放弃后再同步)、处理任务不在了(还没开出来、开失败或被删掉:
+ 「继续处理」用同一个候选目录开新任务)、结果少了 N 项修改(仍然使用/放弃)、处理期间个人版又变了(放弃后
+ 重新同步)、属于另一个账号(只说明,切回那个账号再处理,同步与放弃都不碰它)、其他失败(打开任务或放弃)。
+ 等待期间「同步」按钮不可点;同步发起的官方更新若因另一个操作正在进行而没有开始,报告「忙」,不拿那个操作的
+ 结果当成功。
+- 有还没生成的修改时不更新官方版本:官方更新会改写这些修改的提交,生成失败时就撤不回它们,也可能被当成已确定的
+ 内容上传。此时同步跳过官方更新,提示「先生成个人版,再同步到官方 vX」。
+- 两边合不到一起时选一边:基线互不相关(`diverged`),或用户放弃了合并两台电脑的修改之后,同步状态提供「以 GitHub
+ 上的为准」「以这台电脑的为准」,都需二次确认。以 GitHub 为准:这台电脑的版本留在
+ `refs/cindy-make/backups/personal-remote-local/<commit>`,改用 GitHub 的版本与它发布的官方基线。以这台电脑为准:
+ 一次 `--atomic` 推送先把 GitHub 原来的版本写进用户仓库的 `cindy-personal-backup/<12 位>` 分支(租约要求它
+ 不存在),再带租约替换;本机还有没生成的修改时照例不上传,提示先生成。之后照常完成同步其余步骤。
+- 另一台电脑改写了同一版本:这台电脑自上次同步后没有任何新内容(本机版本就是上次同步确认的版本)而 GitHub 上
+ 已是另一台电脑改写后的版本(例如它解决了官方更新的冲突,或用户在那边选了「以这台电脑为准」)时,直接取回并
+ 备份本机版本,同一个冲突只需在一台电脑上处理一次。
+- 可恢复:同步本身只记住正在等哪个操作与上次的结果(`source` 旁的 `sync.json`),其余耐久状态都在共享的合并
+ 生命周期(保留的候选目录、处理任务、重启恢复、取消)和 GitHub 绑定记录里。重启后冲突任务处理完仍会自动继续;
+ 重启前已采纳的不在启动时擅自继续;任何时候再点一次「同步」都从停下的地方继续。合并操作的归属按账号记录
+ (去掉会话代次),同一账号重新登录后仍是自己的操作;旧记录读取时自动换算。
+- 创建制作任务前:同步正在进行时先等它结束;整个等待(含等已在进行的那次)最多 120 秒,超时就直接继续
+ 准备、同步在后台做完,不让新任务在源码更新阶段等上数分钟。有冲突留在处理任务里(任何保留的候选目录)时不做
+ 源码同步,新任务直接从当前个人版开始,不因那个冲突失败。等待结束后又有同步抢先开始而报「忙」时,再等它
+ 结束重新判断(至多两次)。
+- 任务 worktree 安装依赖时,来自 GitHub、这台电脑还没生成过个人版覆盖的内容不执行生命周期脚本、也不执行
+ `.pnpmfile.cjs` 等 pnpm 钩子(`pnpm install --ignore-scripts --ignore-pnpmfile`,并从子进程环境剔除
+ `npm_config_*`):同步会取回 fork 上有写权限者推送的内容,任务创建前的静默安装不得替它执行 `postinstall`、
+ pnpmfile 钩子等安装期代码(攻击者只需往根 `package.json` 加一个 `postinstall`,或放一个 `.pnpmfile.cjs`,
+ 不需要动锁文件)。判定看绑定记录里「取回且未验证」的 tip(`unverifiedRemote`):任务基线包含它、且没有任一
+ 已生成个人版本的提交包含它,即视为未验证;读不到这些事实时按未验证处理。绑定记录的信任字段损坏时,
+ 保存、同步、停止同步和启动恢复等写入都必须保留原文件并拒绝覆盖,不能把宽松读取后的缺失字段写回成
+ 「没有未验证内容」;回归见 `personalRemote.test.ts` 的持久信任记录用例。官方更新/合并改写了个人提交的哈希时,
+ 未验证身份随改写记录(`rewrites`)传递,不会因换哈希而脱管。生成个人版是用户显式动作(会运行这份内容自己的
+ 检查并产出用户要运行的应用),它覆盖到该内容后,后续任务恢复正常执行安装脚本。脚本被跳过时写入任务准备
+ 日志;任务确实需要时由 Agent 在任务里自行安装,那是可见的正常工作。
+ 安装前还按 pnpm 实际解析位置检查路径:importer 的 `link:` 相对该 importer,锁文件中的 `file:` 版本、
+ 包快照链接与 resolution 相对锁文件目录,不借用其他 importer 或虚拟 store 放行越界路径。`git+file:`
+ 依赖按文件 URL 解码为本机路径后检查范围,提交或分支片段不算路径;锁文件 Git resolution 的 `repo`
+ 同样检查,缓存预热前也核对根锁文件,避免静默复制工作区外的本地仓库。回归见
+ [pnpmWriteRoots.test.ts](../apps/desktop/src/main/cindy-make/__tests__/pnpmWriteRoots.test.ts)。归档中的清单按
+ 解包目标规范化后校验,同一清单经不同路径别名重复出现时拒绝安装;回归见 `taskWorkspace.test.ts`。
+ 未验证来源超过账本上限时保留溢出标记;只有已生成版本能证明覆盖当前任务的整个基线时才恢复该基线的脚本。
+ 不清掉溢出标记,之后未被生成版本覆盖的新基线仍受保护;回归见 `installScriptsTrust.test.ts`。
+- 生成个人版不再先同步源码:设置页「生成前同步最新源码」开关已取消,旧版本保存的开启值按关闭读取;同步是唯一
+ 会把个人版移到新官方版本的地方。
+- GitHub 仓库检查:每次与 GitHub 同步先读取保存个人版的仓库(不带凭证跟随重定向)。仓库已删除时提示并在「保存位置」
+ 提供「重新保存到 GitHub」(停止同步后重新走确认卡);改了名时按 GitHub 的重定向(只接受指向
+ `api.github.com/repositories/<id>` 的地址,跟随一次)找到新名字,且只接受仍属于同一账号的仓库,从不为此新建
+ fork;同一名字指向的仓库还必须仍是本账号的官方 fork(fork、归属、上游 `makecindy/cindy` 同样严格校验),否则
+ 按绑定已失效处理并提示重新保存,绝不向它推送;已归档时说明需先取消归档;没有写入权限时提示重新连接。取回只在源码能移动时进行:还没生成时提示先生成,
+ 源码正忙时报告「忙」,都不会被误报成「版本互不相关」而引出替换 GitHub 版本的选项。比较两边内容的 Git 输出
+ 同样有数量核对。以 GitHub 为准同样要求本机内容都已生成(有待撤回的生成时不动)。
+- 合并两台电脑修改的合并类型是 `combine`(与官方更新同一套 rebase 生命周期);进行中时旧版本客户端不认识它,
+ 会拒绝接手,而不是把它当成官方更新完成并把官方基线设错;完成或取消且没有候选目录后改存为 `rebase`,不让
+ 旧版本客户端(例如没跟着更新的个人版)因此无法使用源码功能。
+- 官方版本([syncTarget](../apps/desktop/src/main/cindy-make/syncTarget.ts)):个人版只能在与本机原版
+ 数据库迁移完全一致时切换,而个人版运行时不会自己更新。因此跟随当前渠道最新发布版,前提是它的
+ `apps/desktop/drizzle` 与本机原版的版本一致;不一致时停在本机原版所在的官方版本,并提示「官方 vX 已发布,
+ 但它更新了数据格式:先切换到原版并更新 Cindy,再同步即可包含」。开发版跟随 main;查不到原版信息时沿用
+ 旧行为跟随最新;本机原版已知但查不到对比结果时不动(报「暂时查不到官方版本信息」)。目标提交在比较前总会先
+ 取到本地。创建制作任务前与生成前的源码同步也用同一规则,并且从不把个人版移到比它当前官方版本更旧的版本
+ (例如另一台电脑带来了更新的官方版本时保持不动,同步结果提示「个人版已在比这台电脑的 Cindy 更新的官方版本上」)。
+ 不改更新服务。
+- 历史改写记录:每次被采纳的官方更新与合并都记下「这些版本的内容都在这个结果里」
+ (`personal-remote.json` 的 `rewrites`,最多 16 条,按完整记录去重,启动时从已持久化的合并结果补记)。上传时,
+ 即使官方更新解决冲突改变了补丁,只要记录能证明 GitHub 上的版本已被带进本机版本,就可以带租约替换并留备份;
+ 记录里本地已不存在的提交(例如清理源码后)一律视为「证明不了」,既不会让同步出错,也不会让刚重新准备的
+ 源码覆盖 GitHub。
+- 待生成记录:「这台电脑还没生成、失败生成仍可能撤回」这一事实与它对应的源码快照共同记录在
+ `userData/cindy-make/pending-build.json`(设备级,随托管源码一起持久化,不进按账号隔离的制作历史)。
+ 合入修改时先记事实再落回执;生成个人版成功时清账;回滚与源码恢复完成时,随源码离开的快照一并撤账;
+ 个人版槽位成功保存后才结算账本,槽位保存失败不改账本;槽位已保存而结算失败时保留已发布版本与原账本,
+ 不再把已发布版本当作失败生成删除(见 `versionStore.ts` 与 `versionStore.test.ts`)。
+ 官方更新/合并改写提交时随改写记录(`rewrites`)传递到携带它的结果,合并带进的 GitHub 修改同样记为
+ 待生成。判定「有没有还没生成的修改」时,账号自己的回执链照旧回答自己的合入,其余由这份设备级记录
+ 回答——**不能因为当前账号查不到本机制作记录就判定源码没有待生成修改**;记录缺失(包括升级前源码)或
+ 读不出来时按有待生成处理,除非这台电脑已生成的个人版本覆盖该快照。合入、改写与回滚都保留这种未知状态,
+ 增量记录仍须保留未知标记,不能将它变成可信的空账本;成功生成后才能清账。仅从官方版本新建的、尚无个人修改的
+ 个人分支可初始化空账本;复用既有个人分支不做初始化,也不覆盖现有损坏记录。记录中的 Git 对象 ID 只接受
+ 完整的 40 位或 64 位十六进制值,其他长度按损坏处理。实现与回归见 `pendingBuild.ts`、`pendingBuild.test.ts`、
+ `buildRollback.test.ts` 与 `sourcePreparation.test.ts`。制作历史继续按账号隔离;源码版本(有哪些修改)与本机生成
+ 状态(这些修改是否已在这台电脑生效)分别处理。
+- 界面:版本概览卡只有一个「同步」按钮,下面一行白话说明进度、等待的冲突任务、失败原因或「已同步到官方 vX」;
+ 个人版自上次生成后有了变化(或新电脑取回了修改而从未生成)时,同一行提示「生成后才会在这台电脑上用上」并提供
+ 「生成个人版」,修改记录标题旁同样提供。旧的「处理冲突」「重试取消」按钮与重复的合并状态提示已移除,所有非修改
+ 记录的源码操作都在这一行显示与处理。「保存位置」一行只保留连接、在 GitHub 查看、停止同步,不再有单独的
+ 「立即同步」「合并修改」;两边都改了而这台电脑的还没生成时提示先生成。版本名按个人版实际所在的官方版本显示:
+ 官方更新采纳后记下新的版本名;基线就是最新发布版时直接用它的名字。
+
+### 身份与凭证
+
+- 使用 Cindy 的 GitHub 连接当前的有效凭证(`ghCliTokenSource`/`githubConnection`),
+ token 只在 Main 内存中使用,不写 `.git/config`、remote URL、argv、日志或磁盘。Git 访问 fork
+ 时用进程环境 `GIT_CONFIG_COUNT/KEY/VALUE` 注入仅限该仓库 URL 的 `http.<url>.extraheader`。
+- 绑定的是 `{ login, repository, confirmedAt }` 与存放方式选择,写入托管源码目录旁的
+ `userData/cindy-make/personal-remote.json`(非秘密;清理源码不删除它,也不属于「恢复默认」的
+ 设置项)。每次同步前核对当前登录的 login;不一致时暂停同步并提示,不自动改绑、不推到其他账号。
+ 运行中的操作只在文件里留运行标记,重启后显示「上次操作被中断」,不自动重放。
+- 带凭证的 Git 命令同时覆盖 `core.hooksPath`(指向空设备)与 `core.fsmonitor`,推送加
+ `--no-verify --no-follow-tags`:仓库钩子与 fsmonitor 程序不在带凭证的环境中运行,也不会顺带推送标签。
+ 需要 Git 2.36 以上(2.31 起支持环境变量注入配置,2.36 起支持 `--remerge-diff`),更旧的 Git
+ 直接提示更新,不静默丢失凭证。
+- 需要 `repo` 与 `workflow` 权限。Cindy 自己的登录流程已申请 `workflow`;用户在终端自行
+ 登录的 gh 可能缺少它,推送含 `.github/workflows` 变化时被 GitHub 拒绝,此时识别该错误并
+ 引导「重新授权 GitHub」,不改用其他凭证、不跳过这些文件。
+- Renderer 只传动作与记录 ID,不传 login、URL 或 token。
+
+### 仓库角色与推送内容
+
+- `origin` 仍指向官方仓,官方代码、渠道 tag、版本查询与冲突处理只读官方仓,逻辑不变。
+ 新增名为 `personal`、不带凭证的 HTTPS remote 指向用户的 fork。界面只说「你的 GitHub ·
+ <login>/<repo>」,不暴露 remote 名。
+- 同步 `refs/heads/cindy-personal`,并随同推送 `refs/heads/cindy-personal-base`(个人版所基于的
+ 官方提交,必须是个人版的祖先,无法证明时不推);两者用 `--atomic` 一起更新。另一台电脑取回时
+ 优先用它确定官方基线,没有时退回本机自己的基线;不推送 `refs/cindy-make/personal-upstream` 等
+ `refs/cindy-make/*` 自定义引用。任务分支、
+ `cindy-merge/*`、`refs/cindy-make/{tasks,features,backups,failed-builds,history-backups}/*`、
+ 交流记录和生成的应用都不同步;每台电脑自己生成应用。
+- fork 上只放「已确定的内容」:生成成功的修改,或官方更新、跨电脑合并的结果。生成失败时
+ 可能被撤回的合入(`buildRollback` 仍能回退的收据)不推送。
+- 推送一律使用显式 refspec 与租约:
+ `push personal <commit>:refs/heads/cindy-personal --force-with-lease=refs/heads/cindy-personal:<上次取得的远端值>`;
+ 租约失败即视为另一台电脑已推送,进入拉取判断,绝不追加 `--force`。
+- 推送时机:每次生成结束(失败的生成已先撤回)与每次官方更新采纳后自动检查;迁移时首次推送;
+ 进入设置页时至多每分钟自动检查一次;创建制作任务前先同步一次(最多等 2 分钟,失败不阻止创建);
+ 设置页始终提供「立即同步」。上传前在项目锁内取一次本地快照决定推什么,网络命令都在锁外执行;
+ 整个同步期间登记为源码读取者,清理源码会被拒绝,但不阻止生成个人版排队。
+ 仍有生成失败可撤回的收据、待完成的回退记录或 `refs/cindy-make/failed-builds/<commit>` 时一律
+ 不推。失败只标记「待同步」,不改变本地结果;重启不重放推送。
+- fork 是本机上次上传的版本(记录在 `syncedCommit`),而本机历史被官方更新改写时,只有 fork 中
+ 每个修改在本机都有同样内容(`git cherry` 无 `+`,其中的合入 merge 提交 remerge diff 为空)才替换,替换前在本机留
+ 备份引用;否则按分叉处理,不覆盖。
+
+### 首次使用与新电脑
+
+- 本机还没有托管源码、也没有记录存放方式时,首次准备前插入「个人版存放方式」:已连接
+ GitHub 默认「存到我的 GitHub」,未连接默认「只存这台电脑」并提供「连接 GitHub」。选择即
+ 构成建 fork 与后续同步推送的授权,不再二次确认;之后在设置页「保存位置」修改。
+- 找到或创建 fork:调用创建 fork 接口(已有 fork 时通常应返回已有仓库;不能再建而返回 422 时改为
+ 定位账号已有的官方 fork 复用),校验它属于当前 login、是 fork 且上游为 `makecindy/cindy`(定位到的
+ 已有 fork 与创建成功同样严格校验,不会误用别人的或非官方 fork);账号下已有同名的其他仓库时,GitHub
+ 会给新副本加后缀,Cindy 不覆盖、不改动已有仓库。轮询到 `ls-remote` 可用后才继续。确认卡显示
+ 「通常是 <login>/cindy」,实际名称在绑定后显示。重试失败的保存会重新显示确认卡。
+- 新电脑:fork 上已有 `cindy-personal` 时,确认卡改为「你的 GitHub 上已有个人版」并说明本机会改用
+ 它(主按钮「在这台电脑使用」);托管源码还没准备时先准备源码再继续。照旧从官方仓 clone,本机
+ 没有自己的修改(只有官方提交)时直接取回 fork 的个人版作为起点;之后提示一键生成,不自动生成、
+ 不自动切换。
+
+### 已在本机使用的用户:自动迁移
+
+- 检测条件:本机已有个人版源码、已连接 GitHub、未绑定 fork、用户未选择「只留在这台电脑」。
+ 检测时机:进入设置页版本控制、刚完成 GitHub 连接、下一次创建制作任务或生成个人版前。
+ 以卡片呈现,不打断进行中的制作、测试或生成。
+- 确认卡写明:账号与仓库名、它是官方仓库的公开副本且修改所有人可见、其他电脑可以使用、以后
+ 可以提交给官方、「这台电脑上的个人版、制作历史和正在进行的制作都不会改变」。操作:「保存到
+ GitHub」「只留在这台电脑」。没有「以后再说」:确认卡一直显示,直到绑定成功或用户选择「只留在
+ 这台电脑」(之后可在「保存位置」重新选择)(2026-10-01 用户裁决)。
+- 确认后进入项目队列(与准备、测试、生成互斥,等待时显示「等待其他工程操作」),每步可中断、
+ 可重试,进度持久化,重启只恢复状态、不自动重放:
+ 1. 按 `commitPersonalFiles` 把遗留未提交内容转成本地提交,先备份引用;失败则什么都没变。
+ 2. 找到或创建 fork;纯远端操作,失败只提示原因、可重试。
+ 3. 添加 `personal` remote,取回远端 `cindy-personal`。
+ 4. 远端没有个人版:推送本机个人版;本机尚有未生成成功的修改时,等下次生成成功后再推。
+ 远端已有另一台电脑的个人版:按下文拉取判断合并,确认弹窗显示两边的官方版本与修改数。
+ 5. 保存绑定,之后自动同步。
+- 不重新 clone、不改 `origin`、不动任务分支/worktree/依赖/修改记录/已生成的版本。
+
+### 拉取与多台电脑
+
+- 拉取时机:创建制作任务前(让新任务包含其他电脑的修改)、生成个人版前、官方更新前、进入
+ 设置页。不做后台轮询。网络失败不阻止本地操作,只显示「GitHub 状态未知」。
+- 判断按内容而非 hash(官方更新会改写 hash):
+ - 两边相同:不做任何事。
+ - 本机是远端的祖先、本机独有修改都已在远端(通过上述保留修改的 Git 树核对),或本机只有官方
+ 提交:在本机 `refs/cindy-make/backups/personal-remote-local/<旧 commit>` 备份后 `reset --keep`
+ 到远端,官方基线取 fork 的 `cindy-personal-base`(没有时用本机基线,且必须是远端的祖先)。
+ 只在源码空闲、工作区干净、当前分支是 `cindy-personal` 且本机内容已确定时取回;否则只报告「GitHub
+ 上有另一台电脑的新修改」。进行中的任务不受影响,之后照现有流程合到最新个人版上。
+ 提示「已取回另一台电脑的修改,生成个人版后可用」。
+ - 远端已包含本机:推送。
+ - 两边都有独有修改(已实现无冲突的情况):fork 发布的 `cindy-personal-base` 必须与本机官方基线
+ 完全一致(没有发布基线时不合并:fork 可能已在更新的官方版本上),且本机内容已确定、源码空闲且
+ 干净时,把本机不在远端祖先中的修改从旧到新逐个放到远端版本之上,树核对确认已包含的修改不再生成提交:只用 Git
+ 对象完成(`merge-tree --write-tree --merge-base` + `commit-tree`,需要 Git 2.40),不检出、不建
+ worktree、不运行钩子;作者、作者时间与完整说明从原始提交对象(`cat-file commit`)读取,经环境变量
+ 写入,不受用户 Git 配置影响,签名不复制。全部无冲突后先带租约快进推送合并结果,成功后再在项目锁内
+ 确认本机仍停在合并起点、源码空闲干净,才备份本机版本并 `reset --keep` 到合并结果,状态显示「已取回
+ 另一台电脑的修改,生成个人版后可用」;推送失败时本机完全不变;上传期间本机又有新变化时保留本机、
+ 记为待同步,下次同步再合并。本机的合入 merge 提交 remerge diff 不为空、任一修改冲突或 Git 太旧时
+ 什么都不动,只报告。
+ - 两边改到同一处或在不同官方版本上(已实现):自动合并遇到冲突(或 Git 低于 2.40、合入 merge 提交带自有
+ 修改、两边官方版本不同)时,GitHub 同步只报告「需要合并」,什么都不动,由「同步」接着处理。它与官方
+ 更新是同一个合并生命周期(`CindyMakeMergeState.remote`,项目锁、保留的候选目录、重启恢复、取消):
+ 先核对要合并的正是上次同步取回的 GitHub 版本(`refs/remotes/personal/cindy-personal`);在官方版本更新的
+ 一边保持不动,把另一边自己的修改(按共同点之后的提交)在 `merge-worktrees/<ID>` rebase 到它之上,两边都有的
+ 修改不会重复;无冲突直接采纳,有冲突直接创建 `cindy-make-merge` 处理任务(「同步」即是用户的决定,不再弹
+ 确认)。任务提示要求同时保留两边的功能,禁止 `rebase --skip`、`reset --hard`、整批
+ ours/theirs,无法同时保留时先问用户。采纳前核实 rebase 已完成、GitHub 版本是结果的祖先、这台电脑的
+ 个人版未被并发修改;官方基线取两边较新的那一个;这台电脑原来的版本留在
+ `refs/cindy-make/backups/<ID>/personal`。采纳后由同步自动快进上传,状态显示「已取回另一台电脑的修改,
+ 生成个人版后可用」(只认这次合并记下的 GitHub 版本,普通上传不会误报)。合并期间与官方更新冲突一样,
+ 其他源码操作会等它处理完或取消。官方版本互不相关(谁也不是谁的祖先)时只报告,不自动合并。
+ - 无法自动处理(基线互不为祖先,或用户放弃了合并):报告原因,提供「以 GitHub 上的为准」「以这台
+ 电脑的为准」(已实现,规则见上文「同步:一个按钮」),两者都先备份(以这台电脑为准时把 GitHub 原来的
+ 版本推到用户仓库的 `cindy-personal-backup/*` 分支)、都需二次确认,都不删除任务分支与已生成的版本。
+- 与其他 Git 写操作共用项目队列;候选目录与冲突任务沿用现有清理、取消与重启恢复规则。
+
+### 与真实线上版本保持同步
+
+- 「真实线上版本」指当前渠道最新发布版(正式版取最新正式 tag,测试版取最新 beta tag,Dev 仍
+ 跟随 GitHub main)。设置页「官方最新」一行显示它,以及个人版是否已包含。
+- 数据版本约束:个人版切换要求其数据库迁移集合与本机原版完全一致
+ ([versionStore](../apps/desktop/src/main/cindy-make/versionStore.ts) 的 `migrationHash` 核对)。
+ 现有同步目标取线上最新,而正在使用个人版的电脑上原版不会自动更新;官方新版一旦带来新的
+ 迁移,基于新版生成的个人版就会被判为不兼容。这是现有流程的缺口,本节一并解决。
+- 已取消「生成前同步最新源码」开关(2026-10-01):按「同步:一个按钮」裁决,生成个人版不再先同步,
+ 个人版只在用户点「同步」时移到新官方版本;「官方最新」一行与同步状态告诉用户是否已包含。
+- 官方发布新版本时,设置页和个人版应用内提示「官方发布了 vX」,并提供一键「更新个人版」:
+ 1. 后台把个人版同步到 vX 并生成新的个人版,期间照常使用;此时不改动原版和当前个人版。
+ 2. 新个人版生成成功后提示「重启完成更新」。原版已是 vX 时直接切换;否则按用户已确认的
+ 更新计划:切到原版 → 由原版既有更新服务更新到 vX 并完成数据迁移 → 自动切到新个人版。
+ 更新计划持久化并显示进度与停止;任一步失败都停在可用的原版,并说明原因。
+ 3. 先生成、后更新原版,保证原版更新后一定有可用的新个人版可切换。
+- 做官方更新前先看 fork:远端个人版已基于目标版本且本机没有独有修改时,直接采用远端结果,
+ 不在本机重做,冲突只需在一台电脑上处理一次。
+- fork 的 `main`:官方更新采纳后调用 GitHub merge-upstream 接口,只做快进;fork 的 main 有用户
+ 自己的提交时不动,只在技术详情里提示。Cindy 取官方代码不经过 fork 的 main,这一步不影响正确性。
+- 两台电脑原版版本不同:官方基线以较新的一方为准;落后的电脑显示「另一台电脑已更新到官方 vX,
+ 这台电脑需要先更新」,并走同一「更新个人版」流程;在此之前本机已生成的个人版照常可用。
+- 该流程涉及更新服务与版本切换,实施前必须先读 `docs/dev-rules/cindy-updater.md` 并单独确认
+ 技术方案。
+
+### 修改记录
+
+- 以「修改」为单位列出每次制作(同一次制作的多轮完成算一项),附带系统自动记录(例如「官方更新到
+ vX,你的修改已自动保留」)。状态只显示一个:制作中/已生效/待生效/已撤销/官方已采纳;
+ PR 状态作为附加标签。筛选:全部、已生效、待生效、已撤销、已提交给官方。
+- 「待生效」统一表示已改变个人版源码但尚未生成到应用里的变化(新加入、撤销、恢复、从 GitHub
+ 取回)。顶部横幅汇总为「有 N 项变化还没生效」,并提供「生成个人版」。
+- 撤销/恢复沿用现有反向提交机制,不改写历史;撤销需一次确认,说明「生成后生效、随时可以恢复」。
+- 跨电脑:绑定 GitHub 后,Cindy Make 生成的每个提交在说明末尾附加 trailer
+ `Cindy-Make-Change: <runId>` 与 `Cindy-Make-Title: <标题>`(官方 rebase 后仍保留)。另一台电脑
+ 据此在修改记录中显示「在另一台电脑上制作」的条目,可以查看改动、撤销/恢复、提交给官方,不能
+ 「打开任务」或「继续修改」(交流记录在原电脑上)。标题会随 fork 公开,确认卡已写明。
+
+### 提交给官方
+
+已按以下规则实现(2026-10-01):
+
+- 入口:修改记录中已完成、有实际改动的单项修改(未撤销、不在进行中),按钮「提交给官方」;已提交过
+ 的显示「更新提交」,官方未采纳的显示「重新提交」,已被采纳的不再提供。没有把个人版保存到 GitHub
+ 时弹窗只说明需要先保存到 GitHub,不提供提交。
+- 确认弹窗:标题(预填 `feat: <修改标题>`)、说明(按 `.github/PULL_REQUEST_TEMPLATE.md` 预填摘要、
+ 范围、验证与风险,涉及界面路径时提示补充截图与设计依据,可编辑)、署名名字与邮箱、包含的文件列表、
+ 「只包含这一项修改」「从你的 GitHub 仓库发起、所有人可见」,以及必须勾选的 DCO 确认(显示将要签名的
+ `名字 <邮箱>`)。每一次提交都需要用户逐次确认。
+ 文件清单通过 Git 写入唯一的系统临时文件后完整读取,不受标准输出捕获上限影响,并用整份清单判断是否涉及界面。
+ 读取失败或缺少最终 NUL 结束符时不出示不完整草稿;成功与失败均清理临时目录。回归见
+ [personalContribution.test.ts](../apps/desktop/src/main/cindy-make/__tests__/personalContribution.test.ts)。
+ Main 为草稿签发不可伪造的确认标识,绑定当时的源码基线与结果、任务、Cindy 账号和 GitHub 仓库;提交必须带回
+ 已签发的标识,等待源码锁后及每次推送前都重新核对。内容、账号或保存位置变化后不提交,撤掉原确认并提示
+ 关闭窗口、重新打开查看文件清单和勾选 DCO。标识仅在 Main 内存有限保存,失效时同样需要重新查看,不持久化。
+- 执行(全程钉在发起提交的 Cindy 账号作用域上,期间切换账号即中止:不会读到另一个账号的修改、用它的
+ 身份推送或写它的台账;推送前同样校验保存的仓库仍是本账号的官方 fork,绑定已失效时提示重新保存、不推送):
+ 取官方最新 `main` 到 `refs/cindy-make/contribution/main`;在临时索引里以它为底,把这项修改从
+ 创建基线到最后一轮完成内容的差异用 `apply --cached --3way` 放上去(只含这一项,个人版里的其他修改不
+ 带上,本机工作区不动);用作者身份 `commit-tree` 一个提交,说明末尾带同一身份的 `Signed-off-by`;
+ 带租约推送到 fork 的 `cindy-make-pr/<runId>`(与本机任务分支 `cindy-make/<runId>` 区分;分支已在
+ GitHub 上被删除时按「不存在」重新租约推送一次),再在官方仓
+ 创建 PR(`maintainer_can_modify: true`)。放不上去(与官方最新代码冲突)或官方已包含时说明原因,
+ 不推送。PR 分支不在本机重新运行检查,说明里如实写「以 CI 结果为准」。
+- 再次提交:先读取原 PR 状态(查不到状态时按「不动旧分支」处理),仍开着时更新同一分支与 PR 的标题和说明,
+ 同时将目标分支恢复为官方 `main`,保证 PR 只展示确认的单项修改;创建响应丢失后复用已有 PR 时也走相同更新。
+ 已关闭或已合并时从一个新的分支新开一个 PR,原 PR 的分支与提交原样保留、绝不改写(新分支按「必须不存在」的
+ 租约推送,名字被占用就换下一个),不修改维护者已处理的 PR(确认弹窗同样按原 PR 状态说明「会更新」或「会新开」)。
+ 旧分支数量不限制再次提交;每个被占用的名字先核对是否已有打开的 PR,只有确认没有且分支仍存在才继续换名,
+ 查询失败或未占用分支的推送失败会停止并报错,不无限重试。回归见 `personalContribution.test.ts`。
+ 更新分支成功后立即记下新提交,再改 PR 与写记录;中途失败或切号后重试按新提交租约,不会永久卡死。作者与
+ 签名身份经环境变量写入,用户 Git 配置里的 `author.name` 等不会改掉它。改了名字或邮箱后需重新勾选 DCO。
+- 状态回显:修改记录详情显示「已提交给官方 #N · 等待审核/已被官方采纳/官方未采纳」,并可在 GitHub
+ 查看;状态每 5 分钟至多查询一次。提交记录保存在按账号隔离的
+ `userData/.../cindy-make-contributions.json`,只含 PR 编号、链接、分支与提交,不含凭证。
+- 未实现:「官方请你修改」的细分状态;采纳后下一次官方更新时从个人版中移除已被官方包含的该修改提交,
+ 修改记录显示「官方已采纳,个人版改用官方版本」(自动判断不了时进入既有冲突处理)。
+
+### 设置页呈现(版本控制页签)
+
+- 顶部一张「下一步」横幅,只说一件事、至多一个主按钮,优先级:冲突处理中 → 正在生成或更新 →
+ 官方发布新版本 → 有变化待生效 → 迁移提示 → 一切最新。
+- 概览卡四行,每行一句话、至多一个操作(已实现:正在使用、个人版、官方最新、保存位置四行;「你的 N 项修改」
+ 按本机修改记录中已在个人版里的项计数,另一台电脑做的修改尚无记录时写「+ 你的修改」):
+ - 正在使用:个人版/原版,「切换到原版/切换到个人版」。
+ - 个人版:「官方 vX + 你的 N 项修改」与「已生效/N 项变化待生效/正在生成」。
+ - 官方最新:「vY 正式版(或测试版、开发版日期)」与「个人版已包含/个人版还没包含」。
+ - 保存位置:「你的 GitHub · <login>/<repo>」与「已同步/待同步/状态未知/账号不一致」;
+ 或「只在这台电脑」与「连接 GitHub」。管理菜单:在 GitHub 查看、立即同步、停止同步
+ (只断开连接,不删除 fork,也不删除本机个人版)。
+- 下方为修改记录,右上角「新增修改」(首次为顶部横幅的「创建个人版」)。
+- 最底部默认折叠「技术详情(给开发者)」:个人版分支与 hash、官方基线、本地 main、GitHub 仓库、
+ 源码目录、打开源码目录、清理源码。
+- 本呈现取代 `docs/design-rules/DESIGN.md` 中「Cindy Make source comparison」的豁免条目,实施 UI
+ 时须同步更新该条并完成 Light/Dark。
+- 手机只读显示同步状态与 PR 状态,不新增远控写操作;投影新增字段按
+ `docs/dev-rules/protocol-compatibility.md` 保证旧客户端可忽略。
+ 已通过现有 Remote Resource 接入;没有准备、测试或生成流程卡片时,仍以只读 Markdown 块
+ 显示状态,避免通用手机卡片过滤只有摘要的资源。空闲时标题为 Cindy Make,不误报正在运行;
+ 有流程时沿用原卡片及其输入状态与操作。实现与回归见
+ [remoteProjection](../apps/desktop/src/main/cindy-make/remoteProjection.ts)、
+ [remoteProvider.test](../apps/desktop/src/main/cindy-make/__tests__/remoteProvider.test.ts) 与
+ [SessionResourceCards.test](../apps/mobile/src/__tests__/SessionResourceCards.test.tsx)。
+
+### 简单创建的配套改进
+
+- 上游相关 PR 查询失败不再阻止「继续制作个人版」,改为说明「没能查询官方是否已有类似修改,可以
+ 继续」。
+- 磁盘空间低于 10 GiB 只提示风险、允许继续;低于 2 GiB 或不可写才阻止。
+- 缺少系统编译工具时给出面向普通用户的安装引导(打开官方安装页,完成后一键重新检测),仍不代装、
+ 不执行管理员命令。
+
+### 分期
+
+1. 同步基础:GitHub 身份与绑定、首次选择、存量迁移、推送与拉取(相同/取回/推送三种情况)、
+ 新电脑使用、提交 trailer、设置页新呈现(横幅、四行概览、修改记录新状态、技术详情折叠)。
+2. 与线上同步:官方新版提示与「更新个人版」完整流程、数据版本不一致提示、官方更新复用远端结果、
+ fork main 同步、取消「生成前同步最新源码」开关。
+3. 多台电脑并发:分叉合并与冲突、兜底操作、另一台电脑修改的撤销/恢复。
+4. 提交给官方:PR 流程、状态回显、再次提交(已实现);采纳后替换(未实现)。
+
+### 不做
+
+- 私有仓库、GitHub 以外的托管平台、同步任务分支与交流记录、自动生成个人版、自动提交 PR。
+- 没有 GitHub 账号时的替代共享与提交通道:Cindy 账号/服务端同步、device-link 直传、官方机器人代提交
+ 修改建议(2026-09-30 用户裁决不做)。
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 5653cadc5e..c8191c887d 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -231,7 +231,7 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n
> **Additional narrowly-scoped exceptions** (documented in their respective component specs, do NOT generalize as system semantic colors):
>
-> - **Cindy Make source comparison** — the owner-approved source overview (2026-09-20, refined 2026-09-21) combines local main and the online target in one row, with personal below. Matching main hashes appear once in `--status-success`; differing hashes show the local value in `--text-secondary` → the verified online target in `--status-success`, with a `--text-tertiary` arrow. The online green identifies the official target even when local main is behind; difference counts remain explicit. Personal uses an icon-first label flush with the main row's left edge, without chip fill or inset padding: status icon, then `cindy-personal` with the localized status in parentheses, followed by the SHA and change count. The icon, name and parenthesized status inherit one color. Latest uses a check and `--status-success`; missing official updates use a download icon and the existing Light/Dark update foreground `--upgrade-banner-fg`; an inconclusive comparison uses a help icon and `--text-secondary`. The status stays visible; the shared hover/focus `Tip` may explain it further. This is informational, with no click action. During operations that replace the comparison, keep the name neutral and omit the status icon, suffix and tooltip. Personal-only changes do not invalidate latest; unavailable lookups never imply latest or an available update. Each source row wraps independently. Both modes use existing tokens; no other version surface inherits this treatment.
+> - **Cindy Make source comparison** — the owner-approved source overview (2026-09-20, refined 2026-09-21) combines local main and the online target in one row, with personal below. Matching main hashes appear once in `--status-success`; differing hashes show the local value in `--text-secondary` → the verified online target in `--status-success`, with a `--text-tertiary` arrow. The online green identifies the official target even when local main is behind; difference counts remain explicit. Personal uses an icon-first label flush with the main row's left edge, without chip fill or inset padding: status icon, then `cindy-personal` with the localized status in parentheses, followed by the SHA and change count. The icon, name and parenthesized status inherit one color. Latest uses a check and `--status-success`; missing official updates use a download icon and the existing Light/Dark update foreground `--upgrade-banner-fg`; an inconclusive comparison uses a help icon and `--text-secondary`. The status stays visible; the shared hover/focus `Tip` may explain it further. This is informational, with no click action. During operations that replace the comparison, keep the name neutral and omit the status icon, suffix and tooltip. Personal-only changes do not invalidate latest; unavailable lookups never imply latest or an available update. Each source row wraps independently. Both modes use existing tokens; no other version surface inherits this treatment. Since 2026-10-01 (owner-approved plain-language Settings, [cindy-make-upstream.md](../cindy-make-upstream.md)), this hash comparison, the source path and its open/clear buttons sit inside the default-collapsed native `details` disclosure “Technical details (for developers)”; the visible overview is the plain-language `CindyMakeVersionSummary` (personal: official version + N changes; latest official: release/beta/dev label + included / not yet / can't confirm). The summary reuses the same verified comparison, the same check / download / help icons and `--status-success` / `--upgrade-banner-fg` / `--text-secondary` colors, shows no hash, branch or main, and is plain text because the technical comparison keeps the single live status region.
> - **Shared-task mobile confirmations** — only the management page is full-screen. Remove, leave, close-current and close-all use compact confirmations. iOS retains `showConfirm` and the system Alert with supported Liquid Glass / older-system fallback. On 2026-09-20 the user rejected Android's default green-text system Alert: Android uses a centered content-height card, container radius 12, themed elevated surface, neutral outlined Cancel and pill-shaped solid danger action using `sharedTaskConfirmBackground/Foreground`. Reuse Mobile action primitives, minimum target 44, wrap actions when needed, and scroll long descriptions. Android Back cancels; the scrim does not dismiss. Cancellation preserves the task, page, tab and scroll position. An in-task guest exits directly from task details, without another management page. No native configuration changes or simulated iOS glass. Desktop retains the Plan B shared window.
> - **CINDY checked Switch** — `--switch-track-on` uses blue `#417CDD` in CINDY Light and Dark (owner decision 2026-09-15, §15.17). This is an enabled-state signal, independently adjustable from focus, caret and Auto Approval despite sharing their current hue. Other themes retain their own checked-track colors.
> - **Windows taskbar attention badge** — the native OS overlay uses a fixed red background (`#D91F37`) and white digits with no outline (`#FFFFFF`) in both Light and Dark taskbars. This is the app-wide count of active tasks needing attention, not an error-only status. The image-specific semantic pair lives in `apps/desktop/src/main/windowsBadgeIcon.ts`; it is not an in-app theme token. Keep a 16-logical-pixel transparent canvas and center the circle and digits at 80% of their original size (user refinement, 2026-09-16). Render using the highest connected display scale and pass that physical-size image directly to the Windows Shell through the native taskbar bridge (Electron 41 otherwise forces overlays to 16 physical pixels). Redraw after display/DPI changes and taskbar recreation; keep the multi-resolution Electron overlay as a failure fallback. Use a circle for one digit, a rounded square for multiple digits, and `99+` above 99. The accessibility description keeps the exact total. Only the OS image may use its fitted 8–12px system-font digits; web typography and status-dot color rules are unchanged.
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 66b93ca9ce..b4eb58d09c 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -38,7 +38,7 @@
| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 5 | 4 | 3 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 28 | 0 | 49 |
-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 137 | 100 | 543 |
+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 137 | 100 | 542 |
| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts, apps/desktop/src/renderer/components/sidebar/useHoverOpenMenu.ts, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 144 | 46 | 200 |
| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginManagementLayout, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx | 35 | 0 | 43 |
| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 43 | 0 | 37 |
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 7ff2796829..bf44314c5d 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -215,6 +215,10 @@ Cindy AI 个人账号的免费会员身份标签。只在服务端明确下发 a
用户通过 /cindy-make 显式开启的本机定制流程。输入区承接准备与每轮完成选择;修改时使用普通输入框。完成后可继续修改、启动隔离测试或生成个人版,版本切换由原生客户端处理。Doctor 自身只检查。
+### Submit to Cindy
+
+把 Cindy Make 的一项修改整理成 Pull Request 提交到官方仓库。面向普通用户写「提交给官方」,对话框说明里才出现 Pull Request;状态写「等待审核 / 已被官方采纳 / 官方未采纳」,不写 open / merged / closed。
+
### Make history
Cindy Make 设置中保留全部制作、修改轮次与合入记录的列表;结束制作及清理工作目录后仍可回看。
@@ -223,6 +227,10 @@ Cindy Make 设置中保留全部制作、修改轮次与合入记录的列表;
重新应用之前明确撤销的制作改动,区别于把尚未合入的新修改首次加入个人源码。
+### Saved in
+
+Cindy Make 版本控制概览中的一行,说明个人版保存在哪里:只在这台电脑,或用户自己 GitHub 上官方仓库的公开副本(fork)。面向普通用户不写 fork,写「你的 GitHub」。
+
### Remove from personal version
从个人版移除单次制作已经加入的全部改动,保留其他制作与已有应用成品;底层通过新的反向提交实现,不改写 Git 历史。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 7277c364e5..c4196f3b33 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -128,6 +128,30 @@
},
"note": "Cindy Make 生成的本机定制应用成品。可与原版切换并沿用同一份日常数据,与使用独立数据的隔离测试版区分。"
},
+ {
+ "id": "cindy-make-storage-location",
+ "status": "proposed",
+ "en": "Saved in",
+ "translations": {
+ "zh-CN": "保存位置",
+ "zh-TW": "儲存位置",
+ "ja": "保存先",
+ "ko": "저장 위치"
+ },
+ "note": "Cindy Make 版本控制概览中的一行,说明个人版保存在哪里:只在这台电脑,或用户自己 GitHub 上官方仓库的公开副本(fork)。面向普通用户不写 fork,写「你的 GitHub」。"
+ },
+ {
+ "id": "cindy-make-contribution",
+ "status": "proposed",
+ "en": "Submit to Cindy",
+ "translations": {
+ "zh-CN": "提交给官方",
+ "zh-TW": "提交給官方",
+ "ja": "公式に提出",
+ "ko": "공식에 제출"
+ },
+ "note": "把 Cindy Make 的一项修改整理成 Pull Request 提交到官方仓库。面向普通用户写「提交给官方」,对话框说明里才出现 Pull Request;状态写「等待审核 / 已被官方采纳 / 官方未采纳」,不写 open / merged / closed。"
+ },
{
"id": "task-tag",
"status": "proposed",
diff --git a/prototypes/cindy-make-personal-version.html b/prototypes/cindy-make-personal-version.html
new file mode 100644
index 0000000000..faf2b95888
--- /dev/null
+++ b/prototypes/cindy-make-personal-version.html
@@ -0,0 +1,366 @@
+<!doctype html>
+<html lang="zh-CN" data-theme="light">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Cindy Make 个人版 · 设置页设计稿</title>
+<style>
+:root{--surface:#f8f8f6;--card:#fff;--board:#d7d7d4;--text:#262626;--text2:#737373;--text3:#a3a3a3;--chip:#e5e5e5;--success:#177C3C;--update:#92400e;--error:#dc2626;--cta-bg:#000;--cta-fg:#fff;--hover:#f0f0ee;--focus:#417CDD;--scrim:rgba(0,0,0,.32)}
+[data-theme=dark]{--surface:#1f1f1e;--card:#2c2c2a;--board:#3c3c3a;--text:#d4d4d4;--text2:#a3a3a3;--text3:#737373;--chip:#3c3c3a;--success:#2AAE5B;--update:#FBBF24;--error:#f87171;--cta-bg:#fff;--cta-fg:#000;--hover:#353533;--scrim:rgba(0,0,0,.55)}
+*{box-sizing:border-box}
+body{margin:0;background:var(--surface);color:var(--text);font:14px/1.5 Inter,system-ui,-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
+button{font:inherit;color:inherit}
+:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
+svg{width:16px;height:16px;flex:none;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
+.proto{position:sticky;top:0;z-index:5;background:var(--card);border-bottom:1px solid var(--board);padding:8px 12px}
+.proto .line{display:flex;gap:6px;overflow-x:auto;align-items:center;padding-bottom:2px;scrollbar-width:none}
+.proto .hint{font-size:12px;color:var(--text3);margin:0 0 6px}
+.seg{flex:none;border:1px solid var(--board);background:var(--card);border-radius:999px;height:28px;padding:0 12px;font-size:12px;cursor:pointer;white-space:nowrap}
+.seg[aria-pressed=true]{background:var(--chip);border-color:var(--chip);font-weight:500}
+main{max-width:760px;margin:0 auto;padding:20px 16px 72px}
+h1{font-size:18px;font-weight:500;margin:0;display:flex;align-items:center;gap:8px}
+.badge{font-size:11px;font-weight:500;border:1px solid var(--board);border-radius:999px;padding:0 7px;color:var(--text2)}
+.tabs{display:flex;gap:20px;border-bottom:1px solid var(--board);margin:14px 0 16px}
+.tab{padding:8px 0;font-size:13px;color:var(--text2);border-bottom:2px solid transparent;margin-bottom:-1px}
+.tab.on{color:var(--text);border-color:var(--text);font-weight:500}
+.card{background:var(--card);border:1px solid var(--board);border-radius:12px;margin-bottom:14px}
+.banner{padding:16px;display:flex;gap:12px;align-items:flex-start}
+.banner>svg{width:20px;height:20px;margin-top:1px}
+.banner h2{font-size:15px;font-weight:500;margin:0 0 2px}
+.banner p{margin:4px 0 0;color:var(--text2);font-size:13px}
+.banner ul{margin:6px 0 0;padding-left:18px;color:var(--text2);font-size:13px}
+.note{margin-top:10px;padding:10px 12px;border-radius:8px;background:var(--surface);font-size:12px;color:var(--text2)}
+.acts{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}
+.btn{height:32px;padding:0 18px;border-radius:999px;font-weight:500;font-size:13px;border:1px solid var(--board);background:var(--card);cursor:pointer;white-space:nowrap;display:inline-flex;align-items:center;gap:6px}
+.btn.sm{height:28px;padding:0 12px;font-size:12px}
+.btn.primary{background:var(--chip);border-color:var(--chip)}
+.btn.cta{background:var(--cta-bg);color:var(--cta-fg);border-color:var(--cta-bg)}
+.btn.quiet{border-color:transparent;background:transparent;color:var(--text2);padding:0 8px}
+.btn.danger{color:var(--error)}
+.btn:hover{background:var(--hover)}.btn.cta:hover{opacity:.88;background:var(--cta-bg)}.btn.quiet:hover{color:var(--text)}
+.btn[disabled]{opacity:.6;pointer-events:none}
+.row{display:flex;gap:12px;padding:13px 16px;border-top:1px solid var(--board);align-items:center}
+.row:first-child{border-top:0}
+.k{width:72px;flex:none;color:var(--text2);font-size:13px}
+.v{flex:1;min-width:0}
+.v .main{font-weight:500;display:flex;flex-wrap:wrap;gap:4px 10px;align-items:center}
+.v .sub{font-size:12px;color:var(--text2);margin-top:2px}
+.tag{display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:400;color:var(--text2)}
+.tag svg{width:14px;height:14px}
+.ok{color:var(--success)}.up{color:var(--update)}.err{color:var(--error)}
+.formula{font-weight:500}.formula .plus{color:var(--text3);margin:0 4px;font-weight:400}
+.sec-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:14px 16px 6px}
+.sec-head h3{margin:0;font-size:14px;font-weight:500}
+.chips{display:flex;gap:6px;overflow-x:auto;padding:4px 16px 10px;scrollbar-width:none}
+.chip{flex:none;height:26px;padding:0 10px;border-radius:999px;border:1px solid var(--board);background:transparent;font-size:12px;color:var(--text2);cursor:pointer}
+.chip[aria-pressed=true]{background:var(--chip);border-color:var(--chip);color:var(--text);font-weight:500}
+.item{padding:12px 16px;border-top:1px solid var(--board)}
+.item .t{display:flex;gap:8px;align-items:baseline;justify-content:space-between}
+.item .title{font-weight:500}
+.item .meta{font-size:12px;color:var(--text2);margin-top:2px;display:flex;flex-wrap:wrap;gap:2px 10px;align-items:center}
+.item .meta svg{width:13px;height:13px}
+.item .ia{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
+.item.system .title{font-weight:400;color:var(--text2)}
+.state{flex:none;font-size:12px;display:inline-flex;align-items:center;gap:4px;white-space:nowrap}
+.state svg{width:13px;height:13px}
+.files{margin-top:8px;padding:8px 10px;border-radius:8px;background:var(--surface);font-size:12px;color:var(--text2)}
+.files code{font:12px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--text);display:block}
+.empty{padding:18px 16px 20px;color:var(--text2);font-size:13px}
+details.tech{border:1px solid var(--board);border-radius:12px;background:var(--card)}
+details.tech summary{padding:12px 16px;cursor:pointer;color:var(--text2);font-size:13px;list-style:none;display:flex;align-items:center;gap:6px}
+details.tech summary::-webkit-details-marker{display:none}
+details.tech[open] summary svg{transform:rotate(90deg)}
+.tech dl{margin:0;padding:0 16px 14px;display:grid;grid-template-columns:max-content 1fr;gap:6px 14px;font-size:12px}
+.tech dt{color:var(--text2)}.tech dd{margin:0;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;word-break:break-all}
+.steps{margin:10px 0 0;padding:0;list-style:none;font-size:13px}
+.steps li{display:flex;gap:8px;align-items:center;padding:3px 0;color:var(--text3)}
+.steps li.done{color:var(--text2)}.steps li.now{color:var(--text);font-weight:500}
+.steps li svg{width:14px;height:14px}
+.log{margin-top:6px;font:12px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.spin{animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}
+.scrim{position:fixed;inset:0;background:var(--scrim);display:none;align-items:center;justify-content:center;padding:16px;z-index:20}
+.scrim.on{display:flex}
+.dialog{background:var(--card);border:1px solid var(--board);border-radius:12px;width:100%;max-width:520px;max-height:90vh;overflow:auto;padding:18px}
+.dialog h2{font-size:16px;font-weight:500;margin:0 0 4px}
+.dialog p{color:var(--text2);font-size:13px;margin:6px 0}
+.dialog label.f{display:block;font-size:12px;color:var(--text2);margin:12px 0 4px}
+.dialog input[type=text],.dialog textarea{width:100%;border:1px solid var(--board);border-radius:8px;background:var(--card);color:var(--text);font:13px/1.5 inherit;padding:8px 10px}
+.dialog textarea{min-height:120px;resize:vertical}
+.check{display:flex;gap:8px;align-items:flex-start;font-size:13px;margin-top:12px}
+.check input{margin-top:3px}
+.dialog .acts{justify-content:flex-end}
+.toast{position:fixed;left:50%;bottom:20px;transform:translateX(-50%);background:var(--card);border:1px solid var(--board);border-radius:999px;padding:8px 16px;font-size:13px;box-shadow:0 4px 16px rgba(0,0,0,.12);display:none;z-index:30;max-width:calc(100% - 32px)}
+.toast.on{display:block}
+@media (max-width:540px){.row{flex-wrap:wrap}.k{width:100%}.row .btn{margin-left:0}}
+</style>
+</head>
+<body>
+<div class="proto" aria-label="设计稿控制">
+ <p class="hint">设计稿:点下面切换场景(这一栏不是产品界面)</p>
+ <div class="line" id="scenarios"></div>
+</div>
+
+<main>
+ <h1>Cindy Make <span class="badge">Beta</span></h1>
+ <div class="tabs" role="tablist"><span class="tab on">版本控制</span><span class="tab">环境准备</span></div>
+ <section class="card" id="banner" aria-live="polite"></section>
+ <section class="card" id="overview"></section>
+ <section class="card" id="changes"></section>
+ <details class="tech" id="tech"></details>
+</main>
+
+<div class="scrim" id="scrim"><div class="dialog" role="dialog" aria-modal="true" id="dialog"></div></div>
+<div class="toast" id="toast" role="status"></div>
+
+<script>
+const I = {
+ check:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>',
+ down:'<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/></svg>',
+ dot:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="2" fill="currentColor"/></svg>',
+ cloud:'<svg viewBox="0 0 24 24"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>',
+ laptop:'<svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M2 20h20"/></svg>',
+ pr:'<svg viewBox="0 0 24 24"><circle cx="18" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><path d="M13 6h3a2 2 0 0 1 2 2v7"/><path d="M6 9v12"/></svg>',
+ warn:'<svg viewBox="0 0 24 24"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>',
+ load:'<svg viewBox="0 0 24 24" class="spin"><path d="M21 12a9 9 0 1 1-6.22-8.56"/></svg>',
+ circle:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/></svg>',
+ undo:'<svg viewBox="0 0 24 24"><path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/></svg>',
+ plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',
+ chev:'<svg viewBox="0 0 24 24"><path d="m9 18 6-6-6-6"/></svg>',
+ sparkle:'<svg viewBox="0 0 24 24"><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/></svg>',
+};
+
+const baseChanges = () => ([
+ {id:1,title:'给任务列表加上颜色标记',date:'今天',where:'this',status:'making'},
+ {id:2,title:'侧栏任务标题显示完整日期',date:'9月28日',where:'this',status:'active',files:['apps/desktop/…/SidebarTaskRow.tsx','apps/desktop/…/formatDate.ts','i18n: zh-CN / en']},
+ {id:3,title:'深色模式下代码块背景更柔和',date:'9月26日',where:'other',status:'active',pr:'review',files:['apps/desktop/…/codeBlock.css']},
+ {id:4,title:'输入框用 Ctrl+Enter 换行',date:'9月25日',where:'this',status:'removed',files:['apps/desktop/…/ChatInput.tsx']},
+ {id:5,title:'默认字号改成 15px',date:'9月24日',where:'this',status:'upstreamed',pr:'merged',files:['apps/desktop/…/appearance.ts']},
+ {id:6,system:true,title:'官方更新到 v1.4.2,你的修改已自动保留',date:'9月23日'},
+ {id:7,title:'设置页加上快捷键说明',date:'9月20日',where:'this',status:'active',files:['apps/desktop/…/ShortcutsSection.tsx']},
+]);
+
+let S = {};
+const scenarios = {
+ first:{label:'首次使用',github:false,hasPersonal:false,banner:'first'},
+ newdevice:{label:'新电脑(GitHub 上已有)',github:true,hasPersonal:false,banner:'newdevice'},
+ local:{label:'最新 · 只在本机',github:false,hasPersonal:true,banner:'ok'},
+ synced:{label:'最新 · 已同步 GitHub',github:true,hasPersonal:true,banner:'ok'},
+ migrate:{label:'刚连接 GitHub',github:true,bound:false,hasPersonal:true,banner:'migrate'},
+ pending:{label:'有变化待生效',github:true,hasPersonal:true,banner:'pending',mutate:c=>{c.find(x=>x.id===4).status='pending-add';c.find(x=>x.id===7).status='pending-remove';c.splice(1,0,{id:8,title:'任务完成时播放提示音',date:'今天',where:'other',status:'pending-add',files:['apps/desktop/…/notifySound.ts']});}},
+ building:{label:'正在生成',github:true,hasPersonal:true,banner:'building'},
+ official:{label:'官方发布新版本',github:true,hasPersonal:true,banner:'official'},
+ conflict:{label:'官方更新有冲突',github:true,hasPersonal:true,banner:'conflict'},
+};
+const extra = [{id:'theme',label:'切换明暗'}];
+
+function load(key){
+ const sc = scenarios[key];
+ S = {key, github:sc.github, bound:sc.bound!==false && sc.github, hasPersonal:sc.hasPersonal, banner:sc.banner, using:'personal', filter:'all', open:{}};
+ S.changes = sc.hasPersonal ? baseChanges() : [];
+ sc.mutate && sc.mutate(S.changes);
+ render();
+}
+
+const pendingCount = () => S.changes.filter(c=>c.status==='pending-add'||c.status==='pending-remove').length;
+const activeCount = () => S.changes.filter(c=>c.status==='active'||c.status==='pending-remove').length;
+
+function renderScenarios(){
+ document.getElementById('scenarios').innerHTML =
+ Object.entries(scenarios).map(([k,v])=>`<button class="seg" aria-pressed="${S.key===k}" onclick="load('${k}')">${v.label}</button>`).join('') +
+ `<button class="seg" onclick="toggleTheme()">切换明暗</button>`;
+}
+
+function banner(){
+ const b = S.banner, n = pendingCount();
+ if (b==='first') return `<div class="banner">${I.sparkle}<div><h2>做一个属于你的 Cindy</h2>
+ <p>告诉 Cindy 你想改什么,它会在官方最新版本上帮你改好,生成一个只属于你的「个人版」。原版一直保留,随时可以切回去。</p>
+ <ul><li>每一项修改都有记录,随时可以撤销</li><li>官方发布新版本时,你的修改会自动带过去</li><li>连接 GitHub 后,还能在别的电脑上用,也能把好的修改提交给官方</li></ul>
+ <div class="acts"><button class="btn cta" onclick="toast('打开「创建个人版」对话框:写下你想改什么')">创建个人版</button></div></div></div>`;
+ if (b==='newdevice') return `<div class="banner">${I.cloud}<div><h2>你的 GitHub 上已经有个人版</h2>
+ <p>来自账号 <b>lizi</b>:官方 v1.4.2 + 你的 3 项修改。可以直接在这台电脑上使用,不用重新做。</p>
+ <div class="note">Cindy 会下载个人版并在这台电脑上生成一次(约 15 分钟,期间可以正常使用),完成后提示你切换。</div>
+ <div class="acts"><button class="btn cta" onclick="toast('开始:下载个人版 → 准备环境 → 生成')">在这台电脑使用</button><button class="btn quiet" onclick="toast('打开「创建个人版」对话框')">重新做一个</button></div></div></div>`;
+ if (b==='ok') return `<div class="banner"><span class="ok">${I.check}</span><div><h2>个人版是最新的</h2>
+ <p>包含官方 v1.4.2 的全部内容,以及你的 ${activeCount()} 项修改。${S.github?'已同步到你的 GitHub。':''}</p></div></div>`;
+ if (b==='pending') return `<div class="banner"><span class="up">${I.dot}</span><div><h2>有 ${n} 项变化还没生效</h2>
+ <p>生成个人版后才会用上${summaryPending()}。大约需要 15 分钟,期间可以正常使用。</p>
+ <div class="acts"><button class="btn cta" onclick="S.banner='building';render()">生成个人版</button></div></div></div>`;
+ if (b==='building') return `<div class="banner">${I.load}<div style="flex:1;min-width:0"><h2>正在生成个人版</h2>
+ <p>离开这个页面也会继续。完成后会提示你重启使用。</p>
+ <ol class="steps"><li class="done">${I.check}加入你的修改</li><li class="now">${I.load}检查修改能正常运行(约 8 分钟)</li><li>${I.circle}打包</li><li>${I.circle}保存并同步到 GitHub</li></ol>
+ <div class="log">正在运行自动测试 · 已通过 312 项</div>
+ <div class="acts"><button class="btn" onclick="confirmStop()">停止</button></div></div></div>`;
+ if (b==='done') return `<div class="banner"><span class="ok">${I.check}</span><div><h2>新的个人版已准备好</h2>
+ <p>重启后使用。账号、设置和任务都会保留。${S.github?'已同步到你的 GitHub,其他电脑也能取到。':''}</p>
+ <div class="acts"><button class="btn cta" onclick="S.banner='ok';S.changes.forEach(c=>{if(c.status==='pending-add')c.status='active';if(c.status==='pending-remove')c.status='removed'});render();toast('(演示)已重启到新的个人版')">重启使用</button><button class="btn quiet" onclick="S.banner='ok';render()">稍后</button></div></div></div>`;
+ if (b==='official') return `<div class="banner"><span class="up">${I.down}</span><div><h2>官方发布了 v1.4.3</h2>
+ <p>更新后,个人版会包含官方的新内容,你的 ${activeCount()} 项修改都会保留。Cindy 先在后台准备好新的个人版(约 15 分钟,期间照常使用),准备好后重启一次即可。</p>
+ <div class="note">为了让原版和个人版能继续用同一份数据,重启时原版也会一起更新到 v1.4.3。</div>
+ <div class="acts"><button class="btn cta" onclick="S.banner='building';render()">更新个人版</button><button class="btn quiet" onclick="toast('打开 v1.4.3 更新说明')">看看更新了什么</button></div></div></div>`;
+ if (b==='conflict') return `<div class="banner"><span class="up">${I.warn}</span><div><h2>官方更新和你的 1 项修改改到了同一处</h2>
+ <p>Cindy 正在自动处理「侧栏任务标题显示完整日期」,处理完会自动继续更新到 v1.4.3。你现在用的个人版不受影响。</p>
+ <div class="acts"><button class="btn" onclick="toast('打开冲突处理任务')">查看处理进度</button><button class="btn quiet" onclick="toast('确认后停止本次更新,个人版保持 v1.4.2')">停止更新</button></div></div></div>`;
+ if (b==='migrate') return `<div class="banner">${I.cloud}<div><h2>把个人版保存到你的 GitHub?</h2>
+ <p>你已连接 GitHub 账号 <b>lizi</b>。保存后:</p>
+ <ul><li>用同一个 GitHub 账号的其他电脑,可以直接使用这个个人版</li><li>可以把你的修改提交给 Cindy 官方</li><li>之后每次生成成功都会自动同步,不用再管</li></ul>
+ <div class="note">会保存到 <b>lizi/cindy</b>,它是官方仓库的公开副本:<b>你的修改和修改标题在 GitHub 上所有人可见</b>。这台电脑上的个人版、修改记录和正在进行的制作都不会改变。</div>
+ <div class="acts"><button class="btn cta" onclick="migrate()">保存到 GitHub</button><button class="btn" onclick="S.github=true;S.bound=false;S.declined=true;S.banner='ok';render();toast('好的,只留在这台电脑。以后可以在下面「保存位置」里改')">只留在这台电脑</button><button class="btn quiet" onclick="S.banner='ok';render()">以后再说</button></div></div></div>`;
+ if (b==='migrating') return `<div class="banner">${I.load}<div><h2>正在保存到你的 GitHub</h2>
+ <ol class="steps"><li class="done">${I.check}整理这台电脑上的修改</li><li class="now">${I.load}创建 lizi/cindy</li><li>${I.circle}上传个人版</li></ol>
+ <p>不影响你继续使用。网络中断也没关系,下次会接着做。</p></div></div>`;
+ return '';
+}
+function summaryPending(){
+ const add = S.changes.filter(c=>c.status==='pending-add'), rm = S.changes.filter(c=>c.status==='pending-remove');
+ const other = add.filter(c=>c.where==='other').length;
+ const parts=[]; if(add.length-other) parts.push(`新加入 ${add.length-other} 项`); if(other) parts.push(`另一台电脑的 ${other} 项`); if(rm.length) parts.push(`撤销 ${rm.length} 项`);
+ return parts.length?`(${parts.join('、')})`:'';
+}
+
+function overview(){
+ if (!S.hasPersonal) return `<div class="row"><div class="k">正在使用</div><div class="v"><div class="main">原版 · v1.4.2 正式版</div><div class="sub">官方发布的 Cindy</div></div></div>` + storageRow();
+ const base = S.banner==='official'||S.banner==='conflict' ? 'v1.4.2' : 'v1.4.2';
+ const latestRow = (S.banner==='official'||S.banner==='conflict')
+ ? `<div class="main">v1.4.3 正式版 <span class="tag up">${I.down}个人版还没包含</span></div><div class="sub">9月30日发布</div>`
+ : `<div class="main">v1.4.2 正式版 <span class="tag ok">${I.check}个人版已包含</span></div><div class="sub">9月23日发布 · 刚刚检查过</div>`;
+ const n = pendingCount();
+ const using = S.using==='personal'
+ ? `<div class="main">个人版</div><div class="sub">原版也保留在这台电脑上,切换会重启,账号、设置和任务都保留</div></div><button class="btn sm" onclick="S.using='original';render();toast('(演示)重启到原版')">切换到原版</button>`
+ : `<div class="main">原版</div><div class="sub">官方发布的 Cindy</div></div><button class="btn sm" onclick="S.using='personal';render();toast('(演示)重启到个人版')">切换到个人版</button>`;
+ return `<div class="row"><div class="k">正在使用</div><div class="v">${using}</div>
+ <div class="row"><div class="k">个人版</div><div class="v"><div class="main"><span class="formula">官方 ${base}<span class="plus">+</span>你的 ${activeCount()} 项修改</span>
+ ${n?`<span class="tag up">${I.dot}${n} 项变化待生效</span>`:S.banner==='building'?`<span class="tag">${I.load}正在生成</span>`:`<span class="tag ok">${I.check}已生效</span>`}</div>
+ <div class="sub">上次生成:9月28日 · 在这台电脑</div></div></div>
+ <div class="row"><div class="k">官方最新</div><div class="v">${latestRow}</div></div>` + storageRow();
+}
+function storageRow(){
+ if (!S.hasPersonal && S.github && S.bound) return `<div class="row"><div class="k">保存位置</div><div class="v"><div class="main">你的 GitHub · lizi/cindy</div><div class="sub">上面有你在其他电脑上做的个人版</div></div></div>`;
+ if (S.github && S.bound) return `<div class="row"><div class="k">保存位置</div><div class="v"><div class="main">你的 GitHub · lizi/cindy
+ ${S.banner==='pending'?`<span class="tag ok">${I.check}已取回另一台电脑的修改</span>`:S.banner==='building'?`<span class="tag">生成完成后自动同步</span>`:`<span class="tag ok">${I.check}已同步</span>`}</div>
+ <div class="sub">在其他电脑上用同一个 GitHub 账号登录,打开 Cindy Make 就能使用这个个人版</div></div>
+ <button class="btn sm quiet" onclick="storageMenu()">管理</button></div>`;
+ const declined = S.github && !S.bound;
+ return `<div class="row"><div class="k">保存位置</div><div class="v"><div class="main">只在这台电脑</div>
+ <div class="sub">${declined?'你选择了只留在这台电脑。':'连接 GitHub 后,可以在其他电脑上使用这个个人版,也能把修改提交给官方。'}换电脑或重装系统后,只存在本机的个人版无法找回。</div></div>
+ <button class="btn sm" onclick="${declined?"S.banner='migrate';render()":'connect()'}">${declined?'保存到 GitHub':'连接 GitHub'}</button></div>`;
+}
+
+const STATUS = {
+ making:['制作中',I.load,''],
+ active:['已生效',I.check,'ok'],
+ 'pending-add':['待生效',I.dot,'up'],
+ 'pending-remove':['已撤销 · 待生效',I.dot,'up'],
+ removed:['已撤销',I.undo,''],
+ upstreamed:['官方已采纳',I.check,'ok'],
+};
+const PR = {review:['官方审核中',''],changes:['官方请你修改','up'],merged:['已包含在官方 v1.4.2','ok']};
+const FILTERS = [['all','全部'],['active','已生效'],['pending','待生效'],['removed','已撤销'],['pr','已提交给官方']];
+function match(c){
+ if (S.filter==='all') return true;
+ if (c.system) return false;
+ if (S.filter==='active') return c.status==='active';
+ if (S.filter==='pending') return c.status==='pending-add'||c.status==='pending-remove';
+ if (S.filter==='removed') return c.status==='removed';
+ if (S.filter==='pr') return !!c.pr;
+}
+function changes(){
+ const head = `<div class="sec-head"><h3>修改记录</h3>${S.hasPersonal?`<button class="btn sm" onclick="toast('打开「新增修改」对话框:写下你想改什么')">${I.plus}新增修改</button>`:''}</div>`;
+ if (!S.hasPersonal) return head + `<div class="empty">还没有修改。创建个人版后,你让 Cindy 做的每一项修改都会记在这里,可以查看、撤销,也可以提交给官方。</div>`;
+ const chips = `<div class="chips">${FILTERS.map(([k,l])=>`<button class="chip" aria-pressed="${S.filter===k}" onclick="S.filter='${k}';render()">${l}</button>`).join('')}</div>`;
+ const list = S.changes.filter(match).map(item).join('') || `<div class="empty">没有符合条件的修改。</div>`;
+ return head + chips + list;
+}
+function item(c){
+ if (c.system) return `<div class="item system"><div class="t"><span class="title">${c.title}</span></div><div class="meta">${c.date} · 自动记录</div></div>`;
+ const [label,icon,cls] = STATUS[c.status];
+ const where = c.where==='this'?`${I.laptop}这台电脑`:`${I.cloud}在另一台电脑上制作`;
+ const pr = c.pr&&c.status!=='upstreamed'?`<span class="tag ${PR[c.pr][1]}">${I.pr}${PR[c.pr][0]}</span>`:'';
+ const acts = [];
+ if (c.status==='making') acts.push(`<button class="btn sm" onclick="toast('打开这个制作任务')">打开任务</button>`);
+ if (c.status==='active'||c.status==='pending-add') acts.push(`<button class="btn sm" onclick="undo(${c.id})">撤销</button>`);
+ if (c.status==='removed'||c.status==='pending-remove') acts.push(`<button class="btn sm" onclick="redo(${c.id})">恢复</button>`);
+ if ((c.status==='active')&&!c.pr) acts.push(`<button class="btn sm" onclick="openPr(${c.id})">${I.pr}提交给官方</button>`);
+ if (c.pr==='review') acts.push(`<button class="btn sm quiet" onclick="toast('在 GitHub 打开这条提交')">在 GitHub 查看</button>`);
+ if (c.files) acts.push(`<button class="btn sm quiet" onclick="S.open[${c.id}]=!S.open[${c.id}];render()">${S.open[c.id]?'收起':'改了什么'}</button>`);
+ const note = c.status==='upstreamed'?`<div class="meta">官方已经采纳这项修改,个人版改用官方的版本,不再单独保留。</div>`:'';
+ const files = S.open[c.id]&&c.files?`<div class="files">改动了 ${c.files.length} 个文件<code>${c.files.join('<br>')}</code></div>`:'';
+ return `<div class="item"><div class="t"><span class="title">${c.title}</span><span class="state ${cls}">${icon}${label}</span></div>
+ <div class="meta"><span>${c.date}</span><span style="display:inline-flex;gap:4px;align-items:center">${where}</span>${pr}</div>${note}${files}
+ ${acts.length?`<div class="ia">${acts.join('')}</div>`:''}</div>`;
+}
+
+function tech(){
+ return `<summary>${I.chev}技术详情(给开发者)</summary><dl>
+ <dt>个人版分支</dt><dd>cindy-personal · 3f2a9c1d8e04</dd>
+ <dt>官方基线</dt><dd>v1.4.2 · 8b71d0e5a2c9</dd>
+ ${S.github&&S.bound?'<dt>GitHub 仓库</dt><dd>github.com/lizi/cindy</dd>':''}
+ <dt>源码目录</dt><dd>C:\\Users\\lizi\\AppData\\Roaming\\Cindy\\cindy-make\\source</dd>
+ </dl><div style="padding:0 16px 14px;display:flex;gap:8px;flex-wrap:wrap"><button class="btn sm">打开源码目录</button><button class="btn sm danger">清理源码</button></div>`;
+}
+
+function render(){
+ renderScenarios();
+ const bn = banner();
+ document.getElementById('banner').style.display = bn?'':'none';
+ document.getElementById('banner').innerHTML = bn;
+ document.getElementById('overview').innerHTML = overview();
+ document.getElementById('changes').innerHTML = changes();
+ const t = document.getElementById('tech'); const open = t.open; t.innerHTML = tech(); t.open = open;
+}
+
+function toast(msg){const t=document.getElementById('toast');t.textContent=msg;t.classList.add('on');clearTimeout(toast.h);toast.h=setTimeout(()=>t.classList.remove('on'),2600);}
+function dialog(html){document.getElementById('dialog').innerHTML=html;document.getElementById('scrim').classList.add('on');}
+function closeDialog(){document.getElementById('scrim').classList.remove('on');}
+document.getElementById('scrim').addEventListener('click',e=>{if(e.target.id==='scrim')closeDialog()});
+function refreshBanner(){ if(['ok','pending','done'].includes(S.banner)) S.banner = pendingCount()?'pending':'ok'; }
+function undo(id){
+ const c=S.changes.find(x=>x.id===id);
+ dialog(`<h2>撤销「${c.title}」?</h2><p>撤销后,重新生成个人版时就不再包含这项修改。你的其他修改不受影响,之后随时可以恢复。</p>
+ <div class="acts"><button class="btn" onclick="closeDialog()">取消</button><button class="btn primary" onclick="doUndo(${id})">撤销</button></div>`);
+}
+function doUndo(id){const c=S.changes.find(x=>x.id===id);c.status=c.status==='pending-add'?'removed':'pending-remove';closeDialog();refreshBanner();render();toast('已撤销,生成个人版后生效');}
+function redo(id){const c=S.changes.find(x=>x.id===id);c.status=c.status==='pending-remove'?'active':'pending-add';refreshBanner();render();toast('已恢复,生成个人版后生效');}
+function openPr(id){
+ const c=S.changes.find(x=>x.id===id);
+ if(!(S.github&&S.bound)){
+ dialog(`<h2>提交给官方需要 GitHub</h2><p>修改会以你的 GitHub 账号提交给 Cindy 官方审核。连接后,个人版也会保存到你的 GitHub,其他电脑可以直接使用。</p>
+ <div class="acts"><button class="btn" onclick="closeDialog()">取消</button><button class="btn cta" onclick="closeDialog();${S.github?"S.banner='migrate';render()":'connect()'}">${S.github?'保存到 GitHub':'连接 GitHub'}</button></div>`);return;
+ }
+ dialog(`<h2>把这项修改提交给 Cindy 官方</h2>
+ <p>官方维护者审核后,可能采纳、请你修改或不采纳。采纳后会出现在之后的官方版本里,所有人都能用上。</p>
+ <label class="f" for="prt">标题</label><input type="text" id="prt" value="${c.title}">
+ <label class="f" for="prd">说明(Cindy 已根据制作过程写好,可以修改)</label>
+ <textarea id="prd">想解决的问题:${c.title}。
+
+改了什么:${(c.files||[]).length} 个文件,只包含这一项修改。
+
+怎么验证的:生成个人版时已通过自动测试和类型检查,并在隔离测试版里试用过。
+
+由 Cindy Make 制作。</textarea>
+ <div class="note">提交前 Cindy 会把这项修改单独放到官方最新代码上再检查一遍(约 10 分钟),不会带上你的其他修改。提交后在 GitHub 上公开可见。</div>
+ <label class="check"><input type="checkbox" id="dco" onchange="document.getElementById('prgo').disabled=!this.checked">我确认有权提交这项修改,并同意用我的 GitHub 账号(lizi)署名提交。</label>
+ <div class="acts"><button class="btn" onclick="closeDialog()">取消</button><button class="btn cta" id="prgo" disabled onclick="submitPr(${id})">提交给官方</button></div>`);
+}
+function submitPr(id){S.changes.find(x=>x.id===id).pr='review';closeDialog();render();toast('已提交。官方的审核结果会显示在这条记录上');}
+function connect(){
+ dialog(`<h2>连接 GitHub</h2><p>Cindy 会打开 GitHub 授权页,按页面提示输入验证码即可,不需要安装任何东西。</p>
+ <p>还没有 GitHub 账号?可以在 github.com 免费注册一个。</p>
+ <div class="acts"><button class="btn" onclick="closeDialog()">取消</button><button class="btn cta" onclick="closeDialog();S.github=true;S.bound=false;S.banner=S.hasPersonal?'migrate':'first';render();toast('(演示)已连接 GitHub 账号 lizi')">继续</button></div>`);
+}
+function migrate(){S.banner='migrating';render();setTimeout(()=>{S.bound=true;S.banner='ok';render();toast('已保存到 lizi/cindy,之后会自动同步');},1800);}
+function confirmStop(){
+ dialog(`<h2>停止生成个人版?</h2><p>这次加入的变化会退回到「待生效」,你现在用的个人版不变。之后可以再次生成。</p>
+ <div class="acts"><button class="btn" onclick="closeDialog()">继续生成</button><button class="btn primary" onclick="closeDialog();S.banner=pendingCount()?'pending':'ok';render();toast('已停止')">停止</button></div>`);
+}
+function storageMenu(){
+ dialog(`<h2>保存位置</h2><p>个人版保存在你的 GitHub(lizi/cindy),每次生成成功后自动同步。</p>
+ <div class="acts" style="justify-content:flex-start"><button class="btn sm" onclick="toast('在 GitHub 打开 lizi/cindy')">在 GitHub 查看</button><button class="btn sm" onclick="toast('(演示)立即同步')">立即同步</button><button class="btn sm danger" onclick="closeDialog();S.bound=false;render();toast('已停止同步。GitHub 上的仓库和这台电脑的个人版都保留')">停止同步</button></div>
+ <div class="acts"><button class="btn" onclick="closeDialog()">关闭</button></div>`);
+}
+function toggleTheme(){const h=document.documentElement;h.dataset.theme=h.dataset.theme==='dark'?'light':'dark';}
+// Demo: building finishes after a few seconds.
+setInterval(()=>{ if(S.banner==='building'){ S._b=(S._b||0)+1; if(S._b>3){S._b=0;S.banner='done';render();} } else S._b=0; },1500);
+load('synced');
+</script>
+</body>
+</html>