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。

fix(worktree): isolate recovery ledger by data owner

Kafeifei63389c889698
diff --git a/apps/desktop/src/main/__tests__/remotePrecreatedWorktreeLedger.test.ts b/apps/desktop/src/main/__tests__/remotePrecreatedWorktreeLedger.test.ts
index 35ece7e127..abeca6fc60 100644
--- a/apps/desktop/src/main/__tests__/remotePrecreatedWorktreeLedger.test.ts
+++ b/apps/desktop/src/main/__tests__/remotePrecreatedWorktreeLedger.test.ts
@@ -1,4 +1,17 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { vi } from 'vitest';
+
+const activeOwner = { id: 'owner-a' };
+
+vi.mock('../appSessionState.js', () => ({
+ getActiveAppSession: () => ({
+ mode: 'cloud',
+ dataOwnerId: activeOwner.id,
+ generation: 1,
+ }),
+ ownerScopedUserDataPath: (...parts: string[]) =>
+ `/tmp/cindy-owner-${activeOwner.id}/${parts.join('/')}`,
+}));
import {
__testing,
@@ -26,12 +39,14 @@ class FakeLedgerStore {
const createdAt = Date.now();
const first: PendingRemotePrecreatedWorktree = {
+ dataOwnerId: 'owner-a',
deviceId: 'device-1',
sessionId: 'session-1',
recoveryKey: 'recovery-key-111111',
createdAt,
};
const second: PendingRemotePrecreatedWorktree = {
+ dataOwnerId: 'owner-a',
deviceId: 'device-2',
sessionId: 'session-2',
recoveryKey: 'recovery-key-222222',
@@ -42,6 +57,7 @@ describe('remotePrecreatedWorktreeLedger Main store', () => {
let store: FakeLedgerStore;
beforeEach(() => {
+ activeOwner.id = 'owner-a';
store = new FakeLedgerStore();
__testing.setStore(store);
__testing.resetMemory();
@@ -95,4 +111,50 @@ describe('remotePrecreatedWorktreeLedger Main store', () => {
storageReadable: false,
});
});
+
+ it('rejects a record from another owner before any persistent write', () => {
+ activeOwner.id = 'owner-b';
+
+ expect(registerRemotePrecreatedWorktreeLedgerRecord(first)).toBe(false);
+ expect(store.records).toEqual([]);
+ expect(listRemotePrecreatedWorktreeLedger()).toEqual({
+ records: [],
+ storageReadable: true,
+ });
+ });
+
+ it('quarantines foreign or legacy records instead of exposing them to the active owner', () => {
+ store.records = [
+ first,
+ {
+ deviceId: 'device-legacy',
+ sessionId: 'session-legacy',
+ path: '/repo/legacy',
+ createdAt,
+ },
+ ];
+
+ expect(listRemotePrecreatedWorktreeLedger()).toEqual({
+ records: [first],
+ storageReadable: false,
+ });
+ expect(store.records).toHaveLength(2);
+ });
+
+ it('does not reuse an in-memory obligation after switching owners', () => {
+ store.failWrite = true;
+ expect(registerRemotePrecreatedWorktreeLedgerRecord(first)).toBe(false);
+
+ activeOwner.id = 'owner-b';
+ expect(listRemotePrecreatedWorktreeLedger()).toEqual({
+ records: [],
+ storageReadable: true,
+ });
+
+ activeOwner.id = 'owner-a';
+ expect(listRemotePrecreatedWorktreeLedger()).toMatchObject({
+ records: [first],
+ storageReadable: true,
+ });
+ });
});
diff --git a/apps/desktop/src/main/remotePrecreatedWorktreeLedger.ts b/apps/desktop/src/main/remotePrecreatedWorktreeLedger.ts
index d5d6477c51..a7706cea59 100644
--- a/apps/desktop/src/main/remotePrecreatedWorktreeLedger.ts
+++ b/apps/desktop/src/main/remotePrecreatedWorktreeLedger.ts
@@ -7,6 +7,10 @@
import { ipcMain } from 'electron';
import Store from 'electron-store';
+import {
+ getActiveAppSession,
+ ownerScopedUserDataPath,
+} from './appSessionState.js';
import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';
import { throwIpcError } from './utils/ipcValidate.js';
import {
@@ -33,12 +37,30 @@ interface LedgerStoreLike {
}
let storeInstance: LedgerStoreLike | null = null;
-const memoryRecords = new Map<string, PendingRemotePrecreatedWorktree>();
+let storePath: string | null = null;
+const memoryRecordsByOwner = new Map<
+ string,
+ Map<string, PendingRemotePrecreatedWorktree>
+>();
+
+function currentOwnerId(): string | null {
+ const ownerId = getActiveAppSession().dataOwnerId;
+ return typeof ownerId === 'string' && ownerId.trim().length > 0
+ ? ownerId
+ : null;
+}
+
+function currentStorePath(): string {
+ return ownerScopedUserDataPath('remote-precreated-worktree-ledger');
+}
function getStore(): LedgerStoreLike {
- if (!storeInstance) {
+ if (storeInstance && storePath === '__testing__') return storeInstance;
+ const nextPath = currentStorePath();
+ if (!storeInstance || storePath !== nextPath) {
storeInstance = new Store<RemotePrecreatedWorktreeLedgerShape>({
name: 'remote-precreated-worktree-ledger',
+ cwd: nextPath,
defaults: { records: [] },
schema: {
records: {
@@ -47,11 +69,25 @@ function getStore(): LedgerStoreLike {
},
},
});
+ storePath = nextPath;
}
return storeInstance;
}
-function replaceMemoryRecords(records: readonly PendingRemotePrecreatedWorktree[]): void {
+function memoryRecordsFor(ownerId: string): Map<string, PendingRemotePrecreatedWorktree> {
+ let records = memoryRecordsByOwner.get(ownerId);
+ if (!records) {
+ records = new Map();
+ memoryRecordsByOwner.set(ownerId, records);
+ }
+ return records;
+}
+
+function replaceMemoryRecords(
+ ownerId: string,
+ records: readonly PendingRemotePrecreatedWorktree[],
+): void {
+ const memoryRecords = memoryRecordsFor(ownerId);
memoryRecords.clear();
for (const record of records) {
memoryRecords.set(remotePrecreatedWorktreeRecordKey(record), record);
@@ -59,6 +95,11 @@ function replaceMemoryRecords(records: readonly PendingRemotePrecreatedWorktree[
}
function readMergedRecords(): RemotePrecreatedWorktreeLedgerSnapshot {
+ const ownerId = currentOwnerId();
+ if (!ownerId) {
+ return { records: [], storageReadable: false };
+ }
+ const memoryRecords = memoryRecordsFor(ownerId);
let persisted: PendingRemotePrecreatedWorktree[];
try {
persisted = normalizePendingRemotePrecreatedWorktrees(
@@ -66,19 +107,36 @@ function readMergedRecords(): RemotePrecreatedWorktreeLedgerSnapshot {
);
} catch {
return {
- records: normalizePendingRemotePrecreatedWorktrees([...memoryRecords.values()]),
+ records: normalizePendingRemotePrecreatedWorktrees(
+ [...memoryRecords.values()].filter((record) => record.dataOwnerId === ownerId),
+ ),
storageReadable: false,
};
}
- const records = normalizePendingRemotePrecreatedWorktrees([
+ const mergedRecords = normalizePendingRemotePrecreatedWorktrees([
...memoryRecords.values(),
...persisted,
]);
- replaceMemoryRecords(records);
- return { records, storageReadable: true };
+ // A record without an owner can only come from an old global/localStorage
+ // ledger. Do not guess which account created it: quarantine it and fail
+ // closed instead of letting the current account delete another account's
+ // worktree.
+ const hasForeignOrLegacyRecords = mergedRecords.some(
+ (record) => record.dataOwnerId !== ownerId,
+ );
+ const records = mergedRecords.filter((record) => record.dataOwnerId === ownerId);
+ replaceMemoryRecords(ownerId, records);
+ return {
+ records,
+ storageReadable: !hasForeignOrLegacyRecords,
+ };
}
-function writeRecords(records: readonly PendingRemotePrecreatedWorktree[]): boolean {
+function writeRecords(
+ ownerId: string,
+ records: readonly PendingRemotePrecreatedWorktree[],
+): boolean {
+ if (records.some((record) => record.dataOwnerId !== ownerId)) return false;
try {
getStore().set(
'records',
@@ -95,7 +153,8 @@ export function listRemotePrecreatedWorktreeLedger(): RemotePrecreatedWorktreeLe
if (snapshot.storageReadable) {
// 顺手清理过期/损坏条目。写失败不把一次成功读取伪装成不可读;后续 register
// 会明确返回 persisted=false,阻止新的远端副作用。
- writeRecords(snapshot.records);
+ const ownerId = currentOwnerId();
+ if (ownerId) writeRecords(ownerId, snapshot.records);
}
return snapshot;
}
@@ -103,8 +162,10 @@ export function listRemotePrecreatedWorktreeLedger(): RemotePrecreatedWorktreeLe
export function registerRemotePrecreatedWorktreeLedgerRecord(
value: unknown,
): boolean {
- const record = coercePendingRemotePrecreatedWorktree(value);
- if (!record) return false;
+ const ownerId = currentOwnerId();
+ const rawRecord = coercePendingRemotePrecreatedWorktree(value);
+ if (!ownerId || !rawRecord || rawRecord.dataOwnerId !== ownerId) return false;
+ const record = rawRecord;
const current = readMergedRecords();
const next = normalizePendingRemotePrecreatedWorktrees([
record,
@@ -116,9 +177,9 @@ export function registerRemotePrecreatedWorktreeLedgerRecord(
]);
// 即使磁盘暂时不可用,也在 Main 内存镜像中承担 obligation;返回 false 只表示
// 尚未取得跨进程恢复保证,调用方不得创建远端 worktree。
- replaceMemoryRecords(next);
+ replaceMemoryRecords(ownerId, next);
if (!current.storageReadable) return false;
- return writeRecords(next);
+ return writeRecords(ownerId, next);
}
function targetMatches(
@@ -126,7 +187,8 @@ function targetMatches(
target: PendingRemotePrecreatedWorktreeTarget,
): boolean {
if (
- item.deviceId !== target.deviceId
+ item.dataOwnerId !== target.dataOwnerId
+ || item.deviceId !== target.deviceId
|| item.sessionId !== target.sessionId
) {
return false;
@@ -141,17 +203,18 @@ function targetMatches(
export function forgetRemotePrecreatedWorktreeLedgerRecord(
value: unknown,
): boolean {
+ const ownerId = currentOwnerId();
const target = coercePendingRemotePrecreatedWorktreeTarget(value);
- if (!target) return false;
+ if (!ownerId || !target || target.dataOwnerId !== ownerId) return false;
const current = readMergedRecords();
if (!current.storageReadable) return false;
const next = current.records.filter((item) => !targetMatches(item, target));
- if (!writeRecords(next)) {
+ if (!writeRecords(ownerId, next)) {
// 删除落盘失败时继续在内存保留,防止当前进程把未确认的持久账本当成已清。
- replaceMemoryRecords(current.records);
+ replaceMemoryRecords(ownerId, current.records);
return false;
}
- replaceMemoryRecords(next);
+ replaceMemoryRecords(ownerId, next);
return true;
}
@@ -192,8 +255,9 @@ export function registerRemotePrecreatedWorktreeLedgerIpc(): void {
export const __testing = {
setStore: (store: LedgerStoreLike | null): void => {
storeInstance = store;
+ storePath = store ? '__testing__' : null;
},
resetMemory: (): void => {
- memoryRecords.clear();
+ memoryRecordsByOwner.clear();
},
};
diff --git a/apps/desktop/src/renderer/__tests__/remotePrecreatedWorktree.test.ts b/apps/desktop/src/renderer/__tests__/remotePrecreatedWorktree.test.ts
index ddb6cb021b..ac1c8b7131 100644
--- a/apps/desktop/src/renderer/__tests__/remotePrecreatedWorktree.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remotePrecreatedWorktree.test.ts
@@ -313,6 +313,56 @@ describe('createRemoteSessionWithPrecreatedWorktree', () => {
await expect(listPendingRemotePrecreatedWorktrees()).resolves.toHaveLength(1);
});
+ it('does not recover another owner’s obligation after an account switch', async () => {
+ ledgerRecords = [{
+ dataOwnerId: 'owner-a',
+ deviceId: DEVICE_ID,
+ sessionId: SESSION_ID,
+ path: WORKTREE_PATH,
+ createdAt: Date.now(),
+ }];
+ const invoke = vi.fn();
+
+ await expect(
+ recoverPendingRemotePrecreatedWorktrees({
+ deviceId: DEVICE_ID,
+ dataOwnerId: 'owner-b',
+ invoke,
+ }),
+ ).resolves.toEqual({
+ attempted: 0,
+ recovered: 0,
+ retained: 0,
+ storageReadable: true,
+ });
+ expect(invoke).not.toHaveBeenCalled();
+ expect(ledgerRecords).toHaveLength(1);
+ });
+
+ it('does not attach an unowned legacy record to the current owner', async () => {
+ localStorage.setItem(__testing.storageKey, JSON.stringify({
+ version: 1,
+ records: [{
+ deviceId: DEVICE_ID,
+ sessionId: SESSION_ID,
+ path: WORKTREE_PATH,
+ createdAt: Date.now(),
+ }],
+ }));
+
+ await expect(
+ registerPendingRemotePrecreatedWorktree({
+ dataOwnerId: 'owner-b',
+ deviceId: DEVICE_ID,
+ sessionId: SESSION_ID,
+ path: WORKTREE_PATH,
+ createdAt: Date.now(),
+ }),
+ ).resolves.toBe(false);
+ expect(localStorage.getItem(__testing.storageKey)).not.toBeNull();
+ expect(ledgerRecords).toEqual([]);
+ });
+
it('uses the Main memory mirror when its persistent write fails', async () => {
ledgerWritable = false;
await expect(
@@ -343,6 +393,7 @@ describe('createRemoteSessionWithPrecreatedWorktree', () => {
localStorage.setItem(__testing.storageKey, JSON.stringify({
version: 1,
records: [{
+ dataOwnerId: 'owner-a',
deviceId: DEVICE_ID,
sessionId: SESSION_ID,
path: WORKTREE_PATH,
@@ -366,7 +417,7 @@ describe('createRemoteSessionWithPrecreatedWorktree', () => {
setItem.mockRestore();
removeItem.mockRestore();
expect(localStorage.getItem(__testing.storageKey)).toBe(persisted);
- await expect(listPendingRemotePrecreatedWorktrees()).resolves.toHaveLength(1);
+ await expect(listPendingRemotePrecreatedWorktrees('owner-a')).resolves.toHaveLength(1);
expect(localStorage.getItem(__testing.storageKey)).toBeNull();
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 013ab32aae..aa8e4c45c5 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -39,6 +39,7 @@ import { createWorkerLabel } from './workerLabel';
import { useNavigate, useOutletContext } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
+import { useAuth } from '@/contexts/AuthContext';
import { themeService } from '@/themes/theme-service';
import type { Theme as ColorTheme } from '@/themes/types';
import { ThemeBrandLockup } from '@/components/branding/ThemeBrandLockup';
@@ -458,6 +459,7 @@ interface DraftTargetRequest {
export function NewMakerDraftRoute() {
const { t } = useTranslation();
+ const { dataOwnerId } = useAuth();
const draft = useNewMakerDraft();
const navigate = useNavigate();
// 首参 914=内容封顶宽(→ inputWidth 封顶 934):大屏留出左右呼吸空间,不再顶满全宽;
@@ -2116,6 +2118,7 @@ export function NewMakerDraftRoute() {
const invokeRemote = (channel: string, args: unknown[]) =>
window.electronAPI.deviceLink.invoke(deviceId, channel, args);
const wt = selectedWorktree;
+ const ownerAtSend = dataOwnerId;
let remoteWorkingDir = effectiveWorkingDir?.trim() || undefined;
let presetSessionId: string | undefined;
let precreatedWorktree: {
@@ -2127,11 +2130,17 @@ export function NewMakerDraftRoute() {
// 勾选但环境不合格 / 探测未回时**静默按普通方式启动**,不报错不改勾选记忆
// ——状态只属于用户,合格性只影响这一次是否真的走 worktree(2026-07-29 裁决)。
if (effectiveWorkingDir && wt.enabled && wt.baseRepo) {
+ // 账本必须绑定发起时的账号/本地数据 owner。账号在后续 await
+ // 期间切换时,Main 会拒绝把这笔义务落入新 owner 的命名空间。
+ if (!ownerAtSend) {
+ throw new RemotePrecreatedWorktreeCleanupPendingError();
+ }
// 上次两步创建若在 create / probe / discard 都断线后失败,本地账本仍
// 承担 cleanup obligation。新建下一份前先恢复;无法确认回收/认领时
// 硬挡本次 worktree:create,避免每次重试生成一个新的受管目录。
const recovery = await recoverPendingRemotePrecreatedWorktrees({
deviceId,
+ dataOwnerId: ownerAtSend,
invoke: invokeRemote,
});
// 账本不可读时磁盘上是否还有旧 obligation 未知,也必须 fail
@@ -2148,6 +2157,7 @@ export function NewMakerDraftRoute() {
const reservation = {
deviceId,
sessionId: presetSessionId,
+ dataOwnerId: ownerAtSend,
recoveryKey,
createdAt,
};
@@ -2235,6 +2245,7 @@ export function NewMakerDraftRoute() {
sessionId: presetSessionId,
path: precreatedWorktree.path,
recoveryKey: precreatedWorktree.recoveryKey,
+ ...(ownerAtSend ? { dataOwnerId: ownerAtSend } : {}),
createdAt: precreatedWorktree.createdAt,
createArgs: createArgs,
invoke: invokeRemote,
@@ -2661,6 +2672,7 @@ export function NewMakerDraftRoute() {
deviceProvidersLoading,
effectiveDeviceLinkDeviceId,
effectiveDeviceLinkDeviceName,
+ dataOwnerId,
effectiveExtraDirs,
authVendor,
persistedAgentKind,
diff --git a/apps/desktop/src/renderer/features/cc-agent/remotePrecreatedWorktree.ts b/apps/desktop/src/renderer/features/cc-agent/remotePrecreatedWorktree.ts
index 3996953bea..60cfa10b1a 100644
--- a/apps/desktop/src/renderer/features/cc-agent/remotePrecreatedWorktree.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/remotePrecreatedWorktree.ts
@@ -17,6 +17,8 @@ export interface CreateRemoteSessionWithPrecreatedWorktreeInput {
sessionId: string;
path: string;
recoveryKey: string;
+ /** Owner captured when the remote worktree operation started. */
+ dataOwnerId?: string;
createdAt?: number;
createArgs: unknown;
invoke: RemoteWorktreeInvoke;
@@ -24,6 +26,8 @@ export interface CreateRemoteSessionWithPrecreatedWorktreeInput {
export interface RecoverPendingRemotePrecreatedWorktreesInput {
deviceId: string;
+ /** Owner whose obligations may be reconciled; prevents account-switch bleed. */
+ dataOwnerId?: string;
invoke: RemoteWorktreeInvoke;
}
@@ -83,7 +87,7 @@ function getLedgerApi(): RemotePrecreatedWorktreeLedgerApi {
* 每条都由 Main 原子 register;全部确认持久化后才删旧 key。多窗口同时迁移只会
* 幂等覆盖同一 device/session 记录,不会再产生整表 last-writer-wins。
*/
-async function migrateLegacyLedger(): Promise<boolean> {
+async function migrateLegacyLedger(dataOwnerId?: string): Promise<boolean> {
let raw: string | null;
try {
raw = localStorage.getItem(STORAGE_KEY);
@@ -99,6 +103,24 @@ async function migrateLegacyLedger(): Promise<boolean> {
// 未知旧真值不能按空账本覆盖;保留 key 并让创建 fail closed。
return false;
}
+ if (records.length === 0) {
+ try {
+ localStorage.removeItem(STORAGE_KEY);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+ // A legacy global key has no trustworthy account context. Never attach an
+ // unowned record (or one belonging to another owner) to the currently
+ // signed-in account; retaining the key makes the obligation fail closed
+ // until a caller with an explicit matching owner can migrate it.
+ if (
+ !dataOwnerId
+ || records.some((record) => record.dataOwnerId !== dataOwnerId)
+ ) {
+ return false;
+ }
try {
for (const record of records) {
@@ -112,20 +134,26 @@ async function migrateLegacyLedger(): Promise<boolean> {
}
}
-export async function listPendingRemotePrecreatedWorktrees(): Promise<
+export async function listPendingRemotePrecreatedWorktrees(
+ dataOwnerId?: string,
+): Promise<
PendingRemotePrecreatedWorktree[]
> {
- return (await readPendingRemotePrecreatedWorktreeLedger()).records;
+ return (await readPendingRemotePrecreatedWorktreeLedger(dataOwnerId)).records;
}
-async function readPendingRemotePrecreatedWorktreeLedger(): Promise<
+async function readPendingRemotePrecreatedWorktreeLedger(
+ dataOwnerId?: string,
+): Promise<
RemotePrecreatedWorktreeLedgerSnapshot
> {
- const legacyMigrated = await migrateLegacyLedger();
+ const legacyMigrated = await migrateLegacyLedger(dataOwnerId);
try {
const snapshot = await getLedgerApi().list();
return {
- records: snapshot.records,
+ records: snapshot.records.filter(
+ (record) => !dataOwnerId || record.dataOwnerId === dataOwnerId,
+ ),
storageReadable: legacyMigrated && snapshot.storageReadable,
};
} catch {
@@ -136,7 +164,7 @@ async function readPendingRemotePrecreatedWorktreeLedger(): Promise<
export async function registerPendingRemotePrecreatedWorktree(
record: PendingRemotePrecreatedWorktree,
): Promise<boolean> {
- if (!(await migrateLegacyLedger())) return false;
+ if (!(await migrateLegacyLedger(record.dataOwnerId))) return false;
try {
return (await getLedgerApi().register(record)).persisted;
} catch {
@@ -204,9 +232,24 @@ async function discardPendingRecord(
export async function recoverPendingRemotePrecreatedWorktrees(
input: RecoverPendingRemotePrecreatedWorktreesInput,
): Promise<RecoverPendingRemotePrecreatedWorktreesResult> {
- const ledger = await readPendingRemotePrecreatedWorktreeLedger();
+ const legacyMigrated = await migrateLegacyLedger(input.dataOwnerId);
+ let ledger: RemotePrecreatedWorktreeLedgerSnapshot;
+ try {
+ const snapshot = await getLedgerApi().list();
+ ledger = {
+ records: snapshot.records.filter(
+ (record) =>
+ (!input.dataOwnerId || record.dataOwnerId === input.dataOwnerId),
+ ),
+ storageReadable: legacyMigrated && snapshot.storageReadable,
+ };
+ } catch {
+ ledger = { records: [], storageReadable: false };
+ }
const records = ledger.records.filter(
- (record) => record.deviceId === input.deviceId,
+ (record) =>
+ record.deviceId === input.deviceId
+ && (!input.dataOwnerId || record.dataOwnerId === input.dataOwnerId),
);
const result: RecoverPendingRemotePrecreatedWorktreesResult = {
attempted: 0,
@@ -243,6 +286,7 @@ export async function createRemoteSessionWithPrecreatedWorktree(
path: input.path,
recoveryKey: input.recoveryKey,
createdAt: input.createdAt ?? Date.now(),
+ ...(input.dataOwnerId ? { dataOwnerId: input.dataOwnerId } : {}),
};
// Main 账本在首次 worktree:create 前已经按 recoveryKey 登记;这里补齐 path。
// 写盘失败时 Main 仍保留内存镜像,后续流程继续按 cleanup obligation 收敛。
diff --git a/apps/desktop/src/shared/remotePrecreatedWorktreeLedger.ts b/apps/desktop/src/shared/remotePrecreatedWorktreeLedger.ts
index 527457282c..7d68f82ef1 100644
--- a/apps/desktop/src/shared/remotePrecreatedWorktreeLedger.ts
+++ b/apps/desktop/src/shared/remotePrecreatedWorktreeLedger.ts
@@ -8,6 +8,13 @@ interface PendingRemotePrecreatedWorktreeBase {
deviceId: string;
sessionId: string;
createdAt: number;
+ /**
+ * Cindy account/local-data owner that created the obligation.
+ *
+ * Optional only for the one-time migration of records written by older
+ * renderers. New records must carry this field before Main persists them.
+ */
+ dataOwnerId?: string;
}
export type PendingRemotePrecreatedWorktree =
@@ -26,6 +33,7 @@ export type PendingRemotePrecreatedWorktree =
export type PendingRemotePrecreatedWorktreeTarget =
Pick<PendingRemotePrecreatedWorktree, 'deviceId' | 'sessionId'> & {
+ dataOwnerId?: string;
path?: string;
recoveryKey?: string;
createdAt?: number;
@@ -40,6 +48,7 @@ const MAX_RECORDS = 32;
const MAX_RECORD_AGE_MS = 30 * 24 * 60 * 60 * 1000;
const MAX_DEVICE_ID_LENGTH = 256;
const MAX_SESSION_ID_LENGTH = 256;
+const MAX_DATA_OWNER_ID_LENGTH = 256;
const MAX_PATH_LENGTH = 4_096;
const MIN_RECOVERY_KEY_LENGTH = 16;
const MAX_RECOVERY_KEY_LENGTH = 256;
@@ -67,9 +76,11 @@ function readRecoveryKey(value: unknown): string | null {
}
export function remotePrecreatedWorktreeRecordKey(
- record: Pick<PendingRemotePrecreatedWorktree, 'deviceId' | 'sessionId'>,
+ record: Pick<PendingRemotePrecreatedWorktree, 'deviceId' | 'sessionId'> & {
+ dataOwnerId?: string;
+ },
): string {
- return `${record.deviceId}\u0000${record.sessionId}`;
+ return `${record.dataOwnerId ?? 'legacy'}\u0000${record.deviceId}\u0000${record.sessionId}`;
}
export function coercePendingRemotePrecreatedWorktree(
@@ -79,16 +90,31 @@ export function coercePendingRemotePrecreatedWorktree(
if (!isRecord(value)) return null;
const deviceId = readString(value.deviceId, MAX_DEVICE_ID_LENGTH);
const sessionId = readString(value.sessionId, MAX_SESSION_ID_LENGTH);
+ const dataOwnerId =
+ value.dataOwnerId === undefined
+ ? undefined
+ : readString(value.dataOwnerId, MAX_DATA_OWNER_ID_LENGTH);
const path = readString(value.path, MAX_PATH_LENGTH);
const recoveryKey = readRecoveryKey(value.recoveryKey);
const createdAt =
typeof value.createdAt === 'number' && Number.isFinite(value.createdAt)
? value.createdAt
: 0;
- if (!deviceId || !sessionId || (!path && !recoveryKey) || createdAt <= 0) return null;
+ if (
+ !deviceId
+ || !sessionId
+ || (value.dataOwnerId !== undefined && !dataOwnerId)
+ || (!path && !recoveryKey)
+ || createdAt <= 0
+ ) return null;
if (createdAt > now + 5 * 60 * 1000) return null;
if (now - createdAt > MAX_RECORD_AGE_MS) return null;
- const base = { deviceId, sessionId, createdAt };
+ const base = {
+ deviceId,
+ sessionId,
+ createdAt,
+ ...(dataOwnerId ? { dataOwnerId } : {}),
+ };
if (path) {
return {
...base,
@@ -131,9 +157,18 @@ export function coercePendingRemotePrecreatedWorktreeTarget(
if (!isRecord(value)) return null;
const deviceId = readString(value.deviceId, MAX_DEVICE_ID_LENGTH);
const sessionId = readString(value.sessionId, MAX_SESSION_ID_LENGTH);
+ const dataOwnerId =
+ value.dataOwnerId === undefined
+ ? undefined
+ : readString(value.dataOwnerId, MAX_DATA_OWNER_ID_LENGTH);
const path = readString(value.path, MAX_PATH_LENGTH);
const recoveryKey = readRecoveryKey(value.recoveryKey);
- if (!deviceId || !sessionId || (!path && !recoveryKey)) return null;
+ if (
+ !deviceId
+ || !sessionId
+ || (value.dataOwnerId !== undefined && !dataOwnerId)
+ || (!path && !recoveryKey)
+ ) return null;
const createdAt =
typeof value.createdAt === 'number' && Number.isFinite(value.createdAt)
? value.createdAt
@@ -141,6 +176,7 @@ export function coercePendingRemotePrecreatedWorktreeTarget(
return {
deviceId,
sessionId,
+ ...(dataOwnerId ? { dataOwnerId } : {}),
...(path ? { path } : {}),
...(recoveryKey ? { recoveryKey } : {}),
...(createdAt !== undefined ? { createdAt } : {}),