From dfc7961b68d3859664a5be8467cb9bedcf16f70a Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:26:17 +0800 Subject: [PATCH] fix(sync): complete portable chat and preservation flows --- application/convergentSyncMigration.ts | 2 + .../locales/cloudSyncStrategyLocales.test.ts | 1 + application/i18n/locales/en/ai.ts | 1 + application/i18n/locales/en/terminal.ts | 1 + application/i18n/locales/es/ai.ts | 1 + application/i18n/locales/es/terminal.ts | 1 + application/i18n/locales/ru/ai.ts | 1 + application/i18n/locales/ru/terminal.ts | 1 + application/i18n/locales/zh-CN/ai.ts | 1 + application/i18n/locales/zh-CN/vault.ts | 1 + application/i18n/locales/zh-TW/ai.ts | 1 + application/i18n/locales/zh-TW/vault.ts | 1 + application/state/aiStateSnapshots.ts | 6 +- application/state/useAutoSync.ts | 14 +- application/state/useCloudSync.ts | 41 +++-- application/syncPayload.aiSessions.test.ts | 114 ++++++++++++++ application/syncPayload.ts | 64 ++++++-- components/ai/ChatMessageList.test.tsx | 42 +++++ components/ai/ChatMessageList.tsx | 14 +- components/ai/cattyHistoryReplay.test.ts | 58 +++++++ components/ai/cattyHistoryReplay.ts | 7 +- .../cloud-sync/CloudSyncDashboardTabs.tsx | 1 + domain/aiUndoLastTurn.test.ts | 60 ++++++++ domain/aiUndoLastTurn.ts | 7 +- domain/convergentSync/legacy.ts | 2 + .../convergentSync/legacyAiSessions.test.ts | 24 +++ domain/convergentSync/migration.ts | 73 ++++++++- domain/convergentSync/payload.ts | 4 + .../convergentSync/payloadMigration.test.ts | 60 ++++++++ domain/syncMerge.aiSessions.test.ts | 135 ++++++++++++++++- domain/syncMerge.preserveDeletions.test.ts | 27 ++++ domain/syncMerge.ts | 136 +++++++++++++---- domain/syncReliability.test.ts | 15 ++ domain/syncReliability.ts | 3 +- .../ai/harness/externalBridgeContext.ts | 7 +- infrastructure/ai/types.ts | 2 + infrastructure/services/CloudSyncManager.ts | 1 + .../convergentSyncRuntimeMethods.test.ts | 120 ++++++++++++++- .../cloudSync/convergentSyncRuntimeMethods.ts | 132 ++++++++++++++-- .../services/cloudSync/providerSyncMethods.ts | 23 ++- .../cloudSync/syncAllStorageMethods.test.ts | 143 ++++++++++++++++++ .../cloudSync/syncAllStorageMethods.ts | 27 +++- 42 files changed, 1275 insertions(+), 100 deletions(-) create mode 100644 application/syncPayload.aiSessions.test.ts create mode 100644 domain/convergentSync/legacyAiSessions.test.ts diff --git a/application/convergentSyncMigration.ts b/application/convergentSyncMigration.ts index 0651a72c3..85e4d0869 100644 --- a/application/convergentSyncMigration.ts +++ b/application/convergentSyncMigration.ts @@ -14,6 +14,7 @@ import { type ConvergentMigrationProviderInput, } from '../domain/convergentSync'; import { isProviderReadyForSync } from '../domain/sync'; +import { isPreserveDeletionsStrategy } from '../domain/syncStrategy'; import { getCloudSyncManager, type CloudSyncManager } from '../infrastructure/services/CloudSyncManager'; import { markConvergentSyncInitialized } from '../infrastructure/services/convergentSyncConfig'; import { applyProtectedSyncPayload } from './localVaultBackups'; @@ -113,6 +114,7 @@ export async function prepareConvergentSyncMigration( providers: inputs, deviceId: manager.getState().deviceId, now, + preserveDeletions: isPreserveDeletionsStrategy(manager.getState().syncStrategy), }); if (plan.state) { for (const seed of legacyBaselineSeeds) { diff --git a/application/i18n/locales/cloudSyncStrategyLocales.test.ts b/application/i18n/locales/cloudSyncStrategyLocales.test.ts index 3ff0f36e6..0cc7c48a6 100644 --- a/application/i18n/locales/cloudSyncStrategyLocales.test.ts +++ b/application/i18n/locales/cloudSyncStrategyLocales.test.ts @@ -19,6 +19,7 @@ const strategyKeys = [ "cloudSync.strategy.preferLocalDesc", "cloudSync.aiSessions.title", "cloudSync.aiSessions.desc", + "cloudSync.aiSessions.compatibility", ] as const; test("cloud sync strategy copy exists in every bundled locale", () => { diff --git a/application/i18n/locales/en/ai.ts b/application/i18n/locales/en/ai.ts index f63ffbe05..9b36ed8e7 100644 --- a/application/i18n/locales/en/ai.ts +++ b/application/i18n/locales/en/ai.ts @@ -1,6 +1,7 @@ import type { Messages } from '../types'; export const enAiMessages: Messages = { + 'ai.chat.attachmentContentUnavailable': 'Content not available on this device', // AI Settings 'ai.agentSettings': 'Agent Settings', 'ai.chat.preparing': 'Preparing…', diff --git a/application/i18n/locales/en/terminal.ts b/application/i18n/locales/en/terminal.ts index 56f6ba2fd..78b7398d5 100644 --- a/application/i18n/locales/en/terminal.ts +++ b/application/i18n/locales/en/terminal.ts @@ -387,6 +387,7 @@ export const enTerminalMessages: Messages = { 'cloudSync.strategy.smartMerge': 'Smart merge (recommended)', 'cloudSync.aiSessions.title': 'Sync AI chat history', 'cloudSync.aiSessions.desc': 'Include AI chat sessions in cloud sync. Messages merge append-only across devices; attachment contents stay on this device.', + 'cloudSync.aiSessions.compatibility': 'Older versions may overwrite chat history. Use an updated Netcatty on every synced device.', 'cloudSync.strategy.smartMergePreserve': 'Smart merge (never delete)', 'cloudSync.strategy.smartMergePreserveDesc': 'Combine changes from both sides and never propagate a one-sided deletion — an entry survives until it is removed on every device. Recommended when you restore backups or keep several machines in sync.', 'cloudSync.strategy.smartMergeDesc': 'Combine changes from both sides when possible; if Netcatty cannot decide safely, ask you to choose.', diff --git a/application/i18n/locales/es/ai.ts b/application/i18n/locales/es/ai.ts index 324e60b4c..2453bee25 100644 --- a/application/i18n/locales/es/ai.ts +++ b/application/i18n/locales/es/ai.ts @@ -1,6 +1,7 @@ import type { Messages } from '../types'; export const esAiMessages: Messages = { + 'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo', // AI Settings 'ai.agentSettings': 'Configuración del agente', 'ai.chat.preparing': 'Preparando…', diff --git a/application/i18n/locales/es/terminal.ts b/application/i18n/locales/es/terminal.ts index 72e885ace..7160d6370 100644 --- a/application/i18n/locales/es/terminal.ts +++ b/application/i18n/locales/es/terminal.ts @@ -386,6 +386,7 @@ export const esTerminalMessages: Messages = { 'cloudSync.strategy.smartMerge': 'Fusión inteligente (recomendada)', 'cloudSync.aiSessions.title': 'Sincronizar el historial de chats de IA', 'cloudSync.aiSessions.desc': 'Incluye las sesiones de chat de IA en la sincronización en la nube. Los mensajes se combinan de forma incremental entre dispositivos; el contenido de los adjuntos permanece en este dispositivo.', + 'cloudSync.aiSessions.compatibility': 'Las versiones antiguas pueden sobrescribir el historial. Actualiza Netcatty en todos los dispositivos sincronizados.', 'cloudSync.strategy.smartMergePreserve': 'Fusión inteligente (sin borrar)', 'cloudSync.strategy.smartMergePreserveDesc': 'Combina los cambios de ambos lados y nunca propaga un borrado de un solo lado: una entrada se conserva hasta que se elimina en todos los dispositivos. Recomendado al restaurar copias de seguridad o al usar varios equipos.', 'cloudSync.strategy.smartMergeDesc': 'Combina los cambios de ambos lados cuando sea posible; si Netcatty no puede decidir con seguridad, te pedirá que elijas.', diff --git a/application/i18n/locales/ru/ai.ts b/application/i18n/locales/ru/ai.ts index 216327ec8..94427c313 100644 --- a/application/i18n/locales/ru/ai.ts +++ b/application/i18n/locales/ru/ai.ts @@ -1,6 +1,7 @@ import type { Messages } from '../types'; export const ruAiMessages: Messages = { + 'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве', 'ai.chat.contextUsage': 'Контекст: {used} / {max} токенов', // AI Settings 'ai.agentSettings': 'Настройки агента', diff --git a/application/i18n/locales/ru/terminal.ts b/application/i18n/locales/ru/terminal.ts index b6ec6efb5..bb5ea37f7 100644 --- a/application/i18n/locales/ru/terminal.ts +++ b/application/i18n/locales/ru/terminal.ts @@ -405,6 +405,7 @@ export const ruTerminalMessages: Messages = { 'cloudSync.strategy.smartMerge': 'Умное объединение (рекомендуется)', 'cloudSync.aiSessions.title': 'Синхронизировать историю ИИ-чатов', 'cloudSync.aiSessions.desc': 'Включать сессии ИИ-чатов в облачную синхронизацию. Сообщения объединяются дополнением между устройствами; содержимое вложений остаётся на этом устройстве.', + 'cloudSync.aiSessions.compatibility': 'Старые версии могут перезаписать историю. Обновите Netcatty на всех синхронизируемых устройствах.', 'cloudSync.strategy.smartMergePreserve': 'Умное слияние (без удалений)', 'cloudSync.strategy.smartMergePreserveDesc': 'Объединяет изменения с обеих сторон и никогда не передаёт удаление с одной стороны: запись сохраняется, пока её не убрали на всех устройствах. Рекомендуется при восстановлении из резервных копий или при работе с несколькими машинами.', 'cloudSync.strategy.smartMergeDesc': 'По возможности объединять изменения с обеих сторон; если Netcatty не сможет безопасно выбрать, он попросит вас решить вручную.', diff --git a/application/i18n/locales/zh-CN/ai.ts b/application/i18n/locales/zh-CN/ai.ts index d331eed61..6dd666293 100644 --- a/application/i18n/locales/zh-CN/ai.ts +++ b/application/i18n/locales/zh-CN/ai.ts @@ -1,6 +1,7 @@ import type { Messages } from '../types'; export const zhCNAiMessages: Messages = { + 'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备', // AI Settings 'ai.agentSettings': 'Agent 设置', 'ai.chat.preparing': '准备中…', diff --git a/application/i18n/locales/zh-CN/vault.ts b/application/i18n/locales/zh-CN/vault.ts index 67fa73b91..5a5267466 100644 --- a/application/i18n/locales/zh-CN/vault.ts +++ b/application/i18n/locales/zh-CN/vault.ts @@ -790,6 +790,7 @@ export const zhCNVaultMessages: Messages = { 'cloudSync.strategy.smartMerge': '智能合并(推荐)', 'cloudSync.aiSessions.title': '同步 AI 对话记录', 'cloudSync.aiSessions.desc': '把 AI 对话记录纳入云同步。多设备的对话会按追加方式合并,附件内容仍保留在本机。', + 'cloudSync.aiSessions.compatibility': '旧版本可能覆盖对话记录,请先更新所有参与同步的设备。', 'cloudSync.strategy.smartMergePreserve': '智能合并(不传播删除)', 'cloudSync.strategy.smartMergePreserveDesc': '合并两边的变化,且单侧删除不会同步到其它设备——只有所有设备都删掉才会真正消失。恢复备份或多台机器同步时推荐使用。', 'cloudSync.strategy.smartMergeDesc': '尽量保留两边的变化;如果无法安全判断,会再让你手动选择。', diff --git a/application/i18n/locales/zh-TW/ai.ts b/application/i18n/locales/zh-TW/ai.ts index 3f14acdb3..bdde83be0 100644 --- a/application/i18n/locales/zh-TW/ai.ts +++ b/application/i18n/locales/zh-TW/ai.ts @@ -1,6 +1,7 @@ import type { Messages } from '../types'; export const zhTWAiMessages: Messages = { + 'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置', // AI Settings 'ai.agentSettings': 'Agent 設定', 'ai.chat.preparing': '準備中…', diff --git a/application/i18n/locales/zh-TW/vault.ts b/application/i18n/locales/zh-TW/vault.ts index 6666b93d0..2da39e57f 100644 --- a/application/i18n/locales/zh-TW/vault.ts +++ b/application/i18n/locales/zh-TW/vault.ts @@ -790,6 +790,7 @@ export const zhTWVaultMessages: Messages = { 'cloudSync.strategy.smartMerge': '智慧合併(推薦)', 'cloudSync.aiSessions.title': '同步 AI 對話記錄', 'cloudSync.aiSessions.desc': '把 AI 對話記錄納入雲同步。多裝置的對話會按追加方式合併,附件內容仍保留在本機。', + 'cloudSync.aiSessions.compatibility': '舊版本可能覆寫對話記錄,請先更新所有參與同步的裝置。', 'cloudSync.strategy.smartMergePreserve': '智慧合併(不傳播刪除)', 'cloudSync.strategy.smartMergePreserveDesc': '合併兩邊的變化,且單側刪除不會同步到其它裝置——只有所有裝置都刪掉才會真正消失。還原備份或多台機器同步時建議使用。', 'cloudSync.strategy.smartMergeDesc': '儘量保留兩邊的變化;如果無法安全判斷,會再讓你手動選擇。', diff --git a/application/state/aiStateSnapshots.ts b/application/state/aiStateSnapshots.ts index 3ddbdc58f..f3aae8a2e 100644 --- a/application/state/aiStateSnapshots.ts +++ b/application/state/aiStateSnapshots.ts @@ -47,12 +47,10 @@ export const AI_STATE_CHANGED_PANEL_VIEW_BY_SCOPE = 'netcatty:ai-panel-view-by-s export type DraftsByScope = Partial>; export type PanelViewByScope = Partial>; -export function cleanupSdkAgentSessions(sessionIds: string[]) { +export async function cleanupSdkAgentSessions(sessionIds: string[]): Promise { const bridge = getAIBridge(); if (sessionIds.length === 0) return; - for (const sessionId of sessionIds) { - void bridge?.aiSdkAgentCleanup?.(sessionId).catch(() => {}); - } + await Promise.all(sessionIds.map((sessionId) => bridge?.aiSdkAgentCleanup?.(sessionId).catch(() => {}))); } export function cleanupDeletedAIChatSessions(sessionIds: string[]) { diff --git a/application/state/useAutoSync.ts b/application/state/useAutoSync.ts index ac83250e8..11d6dca0b 100644 --- a/application/state/useAutoSync.ts +++ b/application/state/useAutoSync.ts @@ -28,6 +28,7 @@ import { import { SYNCABLE_SETTING_STORAGE_KEYS, collectCloudSyncableSettings, + collectAiSessionsForSync, getEffectivePortForwardingRulesForSync, hasCloudSyncEntityData, hasMeaningfulCloudSyncData, @@ -39,6 +40,8 @@ import { commitPluginSidecarsAfterSuccessfulSync } from '../pluginSyncSidecarBri import { readInterruptedVaultApply } from '../localVaultBackups'; import { STORAGE_KEY_VAULT_RESTORE_IN_PROGRESS_UNTIL, + STORAGE_KEY_AI_SESSIONS, + STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, } from '../../infrastructure/config/storageKeys'; import { LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, @@ -160,6 +163,7 @@ const getSyncPayloadDataHash = (payload: SyncPayload): string => { groupConfigs: payload.groupConfigs, settings: payload.settings, pluginSidecars: payload.pluginSidecars, + aiSessions: payload.aiSessions, }); }; @@ -244,7 +248,11 @@ export const useAutoSync = (config: AutoSyncConfig) => { const [syncableSettingsStorageVersion, setSyncableSettingsStorageVersion] = useState(0); useEffect(() => { const bumpIfSyncableSetting = (key: string | null | undefined) => { - if (!key || !SYNCABLE_SETTING_STORAGE_KEY_SET.has(key)) return; + if (!key) return; + const chatChanged = key === STORAGE_KEY_AI_SESSIONS + && localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled === true; + if (!SYNCABLE_SETTING_STORAGE_KEY_SET.has(key) + && key !== STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS && !chatChanged) return; setSyncableSettingsStorageVersion((v) => v + 1); }; @@ -300,8 +308,10 @@ export const useAutoSync = (config: AutoSyncConfig) => { const buildPayload = useCallback(async (): Promise => { const { withPluginSyncSidecars } = await import('../syncPayload'); const { collectPluginSyncSidecarsFromHost } = await import('../pluginSyncSidecarBridge'); + const aiSessions = collectAiSessionsForSync(); const base: SyncPayload = { ...getSyncSnapshot(), + ...(aiSessions !== undefined ? { aiSessions } : {}), settings: await collectCloudSyncableSettings(), syncedAt: Date.now(), }; @@ -782,7 +792,7 @@ export const useAutoSync = (config: AutoSyncConfig) => { } const conflictAction = resolveCloudSyncConflictAction(state.syncStrategy, { - hasConflict: inspection.remoteChanged, + hasConflict: inspection.remoteChanged || isPreserveDeletionsStrategy(state.syncStrategy), hasRemoteFile: Boolean(inspection.remoteFile), }); diff --git a/application/state/useCloudSync.ts b/application/state/useCloudSync.ts index a2035a182..11a2b90b9 100644 --- a/application/state/useCloudSync.ts +++ b/application/state/useCloudSync.ts @@ -7,7 +7,7 @@ */ import { useCloudSyncAutoUnlock } from './useCloudSyncAutoUnlock'; -import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react'; import { type CloudProvider, type SecurityState, @@ -28,7 +28,7 @@ import { isProviderReadyForSync, } from '../../domain/sync'; import type { CloudSyncStrategy } from '../../domain/syncStrategy'; -import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter'; +import { LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter'; import { STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS } from '../../infrastructure/config/storageKeys'; import type { CloudSyncConflictAction } from '../../domain/syncStrategy'; import { @@ -254,6 +254,25 @@ const getSnapshot = (): SyncManagerState => { return manager.getState(); }; +function readAiSessionsSyncEnabled(): boolean { + return localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled === true; +} + +function subscribeAiSessionsSyncEnabled(listener: () => void): () => void { + const storage = (event: StorageEvent) => { + if (event.key === STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS || event.key === null) listener(); + }; + const local = (event: Event) => { + if ((event as CustomEvent<{ key?: string }>).detail?.key === STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS) listener(); + }; + window.addEventListener('storage', storage); + window.addEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, local); + return () => { + window.removeEventListener('storage', storage); + window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, local); + }; +} + export const useCloudSync = (): CloudSyncHook => { // Use useSyncExternalStore for real-time state sync across all components const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); @@ -729,20 +748,11 @@ export const useCloudSync = (): CloudSyncHook => { manager.setDeviceName(name); }, []); - const [aiSessionsSyncEnabled, setAiSessionsSyncEnabledState] = useState(() => { - try { - return localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled === true; - } catch { - return false; - } - }); + const aiSessionsSyncEnabled = useSyncExternalStore( + subscribeAiSessionsSyncEnabled, readAiSessionsSyncEnabled, readAiSessionsSyncEnabled, + ); const setAiSessionsSyncEnabled = useCallback((enabled: boolean) => { - setAiSessionsSyncEnabledState(enabled); - try { - localStorageAdapter.write(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, { enabled }); - } catch { - // Preference storage unavailable — keep the in-memory value only. - } + localStorageAdapter.write(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, { enabled }); }, []); const setSyncStrategy = useCallback((strategy: CloudSyncStrategy) => { @@ -885,6 +895,7 @@ export const useCloudSync = (): CloudSyncHook => { } return manager.resolveConvergentConflict(addressKey, candidateDot, applyPayload, { pluginSidecars, + aiSessions: (await import('../syncPayload')).collectAiSessionsForSync(), }); }, [ensureUnlocked]); diff --git a/application/syncPayload.aiSessions.test.ts b/application/syncPayload.aiSessions.test.ts new file mode 100644 index 000000000..bb261180b --- /dev/null +++ b/application/syncPayload.aiSessions.test.ts @@ -0,0 +1,114 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import type { AISession } from '../infrastructure/ai/types'; +import type { SyncPayload } from '../domain/sync'; + +const storage = new Map(); +const events = new EventTarget(); +Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => storage.set(key, value), + removeItem: (key: string) => storage.delete(key), +} }); +Object.defineProperty(globalThis, 'window', { configurable: true, value: events }); +const keys = await import('../infrastructure/config/storageKeys'); +const snapshots = await import('./state/aiStateSnapshots'); +const { getAISessionsSnapshot } = await import('./state/aiSessionsStore'); +const { + buildCloudSyncPayload, buildLocalVaultPayload, collectAiSessionsForSync, + applySyncPayload, applyLocalVaultPayload, hasMeaningfulSyncData, +} = await import('./syncPayload'); + +const vault = { hosts: [], keys: [], identities: [], snippets: [], customGroups: [], knownHosts: [] }; +const session = (): AISession => ({ + id: 'chat', title: 'Chat', agentId: 'catty', scope: { type: 'global' }, createdAt: 1, updatedAt: 2, + messages: [{ id: 'message', role: 'user', content: 'Inspect', timestamp: 1, attachments: [{ + filename: 'terminal.log', mediaType: 'text/plain', terminalSelection: true, + base64Data: 'cHJpdmF0ZQ==', previewText: 'private', filePath: '/private/device/file', lineCount: 1, + }] }], +}); +function save(sessions: AISession[], enabled = true) { + snapshots.setLatestAISessionsSnapshot(sessions); + storage.set(keys.STORAGE_KEY_AI_SESSIONS, JSON.stringify(sessions)); + storage.set(keys.STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, JSON.stringify({ enabled })); +} +test.beforeEach(() => { storage.clear(); save([], false); }); + +test('actual manual upload and auto collector honor consent and explicit empty', async () => { + save([session()], false); + const options = { collectPluginSidecars: () => undefined }; + assert.equal((await buildCloudSyncPayload(vault, [], options)).aiSessions, undefined); + assert.equal(collectAiSessionsForSync(), undefined); + save([], true); + assert.deepEqual((await buildCloudSyncPayload(vault, [], options)).aiSessions, []); + assert.deepEqual(collectAiSessionsForSync(), []); + save([session()], true); + const cloud = await buildCloudSyncPayload(vault, [], options); + assert.equal(cloud.aiSessions?.length, 1); + assert.deepEqual(cloud.aiSessions, collectAiSessionsForSync()); + assert.equal(JSON.stringify(cloud).includes('cHJpdmF0ZQ=='), false); + assert.equal(JSON.stringify(cloud).includes('/private/device/file'), false); + assert.equal(JSON.stringify(cloud.aiSessions?.[0].messages[0].attachments).includes('private'), false); +}); + +test('local backup retains chat and attachment bytes with cloud consent off', async () => { + const local = session(); + save([local], false); + const backup = buildLocalVaultPayload(vault); + assert.deepEqual(backup.aiSessions, [local]); + assert.equal(hasMeaningfulSyncData({ ...vault, aiSessions: [local], syncedAt: 1 }), true); + save([], false); + await applyLocalVaultPayload(backup, { importVaultData: () => undefined }, { + prepareConvergentRestore: async () => async () => {}, + }); + assert.equal(getAISessionsSnapshot().sessions[0].messages[0].attachments?.[0].base64Data, 'cHJpdmF0ZQ=='); +}); + +test('download publishes immediately and keeps local attachment bytes on a newer message', async () => { + save([session()]); + const incoming = session(); + incoming.updatedAt = 3; + incoming.messages[0].content = 'Updated'; + incoming.messages[0].attachments = [{ base64Data: '', mediaType: 'text/plain', filename: 'terminal.log', terminalSelection: true, contentUnavailable: true }]; + const payload: SyncPayload = { ...vault, aiSessions: [incoming], syncedAt: 2 }; + await applySyncPayload(payload, { importVaultData: () => undefined }); + const current = getAISessionsSnapshot().sessions[0]; + assert.equal(current.messages[0].content, 'Updated'); + assert.equal(current.messages[0].attachments?.[0].base64Data, 'cHJpdmF0ZQ=='); + assert.equal(snapshots.latestAISessionsSnapshot?.[0], current); + assert.equal(JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!)[0].messages[0].content, 'Updated'); +}); + +test('restoring an old backup without chat leaves current chats alone', async () => { + const local = session(); + save([local], false); + await applyLocalVaultPayload({ ...vault, syncedAt: 1 }, { importVaultData: () => undefined }, { + prepareConvergentRestore: async () => async () => {}, + }); + assert.deepEqual(snapshots.latestAISessionsSnapshot, [local]); + assert.deepEqual(JSON.parse(storage.get(keys.STORAGE_KEY_AI_SESSIONS)!), [local]); +}); + +test('cloud restore never resumes a source device SDK thread, and preserves matching local threads', async () => { + const local = { ...session(), externalSessionId: 'local-native-thread' }; + save([local]); + const incoming = { ...session(), updatedAt: 3, externalSessionId: 'remote-native-thread' }; + const fresh = { ...incoming, id: 'new-chat' }; + await applySyncPayload({ ...vault, aiSessions: [incoming, fresh], syncedAt: 2 }, { importVaultData: () => undefined }); + const current = getAISessionsSnapshot().sessions; + assert.equal(current.find((s) => s.id === 'chat')?.externalSessionId, 'local-native-thread'); + assert.equal(current.find((s) => s.id === 'new-chat')?.externalSessionId, undefined); +}); + +test('changed remote transcript resets the local native SDK thread before continuing', async () => { + const cleanups: string[] = []; + Object.assign(window, { netcatty: { aiSdkAgentCleanup: async (id: string) => { cleanups.push(id); return { ok: true }; } } }); + save([{ ...session(), agentId: 'codex', externalSessionId: 'local-native-thread' }]); + const incoming = { ...session(), agentId: 'codex', updatedAt: 3, externalSessionId: 'remote-native-thread' }; + incoming.messages.push({ id: 'remote-turn', role: 'user', content: 'Added on another device', timestamp: 3 }); + await applySyncPayload({ ...vault, aiSessions: [incoming], syncedAt: 2 }, { importVaultData: () => undefined }); + assert.deepEqual(cleanups, ['chat']); + assert.equal(getAISessionsSnapshot().sessions[0].externalSessionId, undefined); + assert.equal(getAISessionsSnapshot().sessions[0].messages.at(-1)?.content, 'Added on another device'); + delete (window as unknown as { netcatty?: unknown }).netcatty; +}); diff --git a/application/syncPayload.ts b/application/syncPayload.ts index 99e465a01..6c1a9e25c 100644 --- a/application/syncPayload.ts +++ b/application/syncPayload.ts @@ -46,6 +46,13 @@ import { localStorageAdapter } from '../infrastructure/persistence/localStorageA import { decryptField, encryptField } from '../infrastructure/persistence/secureFieldAdapter'; import { sanitizeQuickMessages } from '../infrastructure/ai/quickMessages'; import { emitAIStateChanged } from './state/aiStateEvents'; +import { + latestAISessionsSnapshot, + setLatestAISessionsSnapshot, + writeSessionsForStorage, + cleanupSdkAgentSessions, +} from './state/aiStateSnapshots'; +import { getAISessionsSnapshot, publishAISessionsSnapshot } from './state/aiSessionsStore'; import { persistCommandBlocklistSetting, readCommandBlocklistSetting, @@ -128,7 +135,7 @@ import { STORAGE_KEY_AI_SESSIONS, STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS, } from '../infrastructure/config/storageKeys'; -import { mergeAiSessionLists, stripAiSessionPayloadForSync } from '../domain/syncMerge'; +import { mergeAiSessionLists, stripAiSessionDeviceState, stripAiSessionPayloadForSync } from '../domain/syncMerge'; import { isTerminalSidePanelAutoOpenTab } from '../domain/terminalSidePanelAutoOpen'; import { prepareRestoredPayloadConvergentWrites } from './convergentSyncReplica'; @@ -174,6 +181,7 @@ function hasMeaningfulPluginSidecars(payload: SyncPayload): boolean { */ export function hasMeaningfulSyncData(payload: SyncPayload): boolean { if (hasSyncPayloadEntityData(payload, SYNC_PAYLOAD_ENTITY_KEYS)) return true; + if (Array.isArray(payload.aiSessions) && payload.aiSessions.length > 0) return true; if ( payload.settings && Object.values(payload.settings).some((value) => value !== undefined) @@ -1031,24 +1039,24 @@ function pruneOrphanPerAgentBindings(): void { // Builders // --------------------------------------------------------------------------- -/** - * Build a complete `SyncPayload` from local data. - * - * Port-forwarding rules are optional because they are managed by a separate - * state hook (`usePortForwardingState`). Callers should strip transient - * runtime fields (status, error, lastUsedAt) before passing them in. - */ /** * AI chat sessions only leave the device when the user opted in. * Attachments are stripped — see {@link stripAiSessionPayloadForSync}. */ -function collectAiSessionsForSync(): SyncPayload['aiSessions'] { +export function collectAiSessionsForSync(): SyncPayload['aiSessions'] { const enabled = localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS); if (enabled?.enabled !== true) return undefined; - const sessions = localStorageAdapter.read(STORAGE_KEY_AI_SESSIONS) ?? []; + const sessions = collectLocalAiSessions(); return stripAiSessionPayloadForSync(sessions); } +function collectLocalAiSessions(): NonNullable { + return latestAISessionsSnapshot + ?? localStorageAdapter.read(STORAGE_KEY_AI_SESSIONS) + ?? []; +} + +/** Build the portable payload; device-local data is added by the backup builder. */ export function buildSyncPayload( vault: SyncableVaultData, portForwardingRules?: PortForwardingRule[], @@ -1066,7 +1074,7 @@ export function buildSyncPayload( noteGroups: vault.noteGroups, groupConfigs: vault.groupConfigs, portForwardingRules: sanitizePortForwardingRulesForSync(portForwardingRules), - ...(aiSessions && aiSessions.length > 0 ? { aiSessions } : {}), + ...(aiSessions !== undefined ? { aiSessions } : {}), settings: collectSyncableSettings(), syncedAt: Date.now(), }; @@ -1140,6 +1148,7 @@ export async function buildCloudSyncPayload( collectPluginSidecars?: PluginSyncSidecarCollector; }, ): Promise { + const aiSessions = collectAiSessionsForSync(); const base: SyncPayload = { hosts: sanitizeHostsForSync(vault.hosts), keys: vault.keys, @@ -1152,6 +1161,7 @@ export async function buildCloudSyncPayload( noteGroups: vault.noteGroups, groupConfigs: vault.groupConfigs, portForwardingRules: sanitizePortForwardingRulesForSync(portForwardingRules), + ...(aiSessions !== undefined ? { aiSessions } : {}), settings: await collectCloudSyncableSettings(), syncedAt: Date.now(), }; @@ -1171,6 +1181,8 @@ export function buildLocalVaultPayload( hosts: vault.hosts, settings: collectLocalBackupSettings(), knownHosts: vault.knownHosts, + // Cloud consent and cloud attachment stripping do not apply to local backups. + aiSessions: collectLocalAiSessions(), }; // Protective backups must capture plugin sidecars so restore can recover // plugin settings/baselines. Prefer the last successful host collect cache @@ -1294,11 +1306,33 @@ async function preparePayloadApply( // AI chat sessions merge append-only: a cloud snapshot may be missing // turns that only exist on this device, so union instead of replace. if (Array.isArray(sanitizedPayload.aiSessions)) { - const localSessions = localStorageAdapter.read(STORAGE_KEY_AI_SESSIONS) ?? []; - const mergedSessions = mergeAiSessionLists(localSessions, sanitizedPayload.aiSessions); - if (localStorageAdapter.write(STORAGE_KEY_AI_SESSIONS, mergedSessions)) { - emitAIStateChanged(STORAGE_KEY_AI_SESSIONS); + const localSessions = collectLocalAiSessions(); + const incoming = options.includeLocalOnlyData + ? sanitizedPayload.aiSessions + : sanitizedPayload.aiSessions.map(stripAiSessionDeviceState); + const localById = new Map(localSessions.map((session) => [session.id, session])); + const resetSdkSessions: string[] = []; + const mergedSessions = mergeAiSessionLists(localSessions, incoming).map((session) => { + // Native SDK threads belong to this device; a cloud copy can neither + // supply one nor replace the existing local thread for this chat. + if (options.includeLocalOnlyData) return session; + const local = localById.get(session.id); + const portableMessages = (value: typeof session) => stripAiSessionPayloadForSync([value])[0].messages; + const transcriptChanged = local + && JSON.stringify(portableMessages(local)) !== JSON.stringify(portableMessages(session)); + if (transcriptChanged) resetSdkSessions.push(session.id); + const { externalSessionId: _remoteThread, ...portable } = session; + return local?.externalSessionId && !transcriptChanged + ? { ...portable, externalSessionId: local.externalSessionId } + : portable; + }); + if (!writeSessionsForStorage(mergedSessions)) { + throw new Error('Unable to save downloaded AI chat history'); } + await cleanupSdkAgentSessions(resetSdkSessions); + setLatestAISessionsSnapshot(mergedSessions); + publishAISessionsSnapshot({ ...getAISessionsSnapshot(), sessions: mergedSessions }); + emitAIStateChanged(STORAGE_KEY_AI_SESSIONS); } // Apply synced settings diff --git a/components/ai/ChatMessageList.test.tsx b/components/ai/ChatMessageList.test.tsx index 123f420ee..04ad03466 100644 --- a/components/ai/ChatMessageList.test.tsx +++ b/components/ai/ChatMessageList.test.tsx @@ -22,6 +22,48 @@ const makeMessage = (index: number): ChatMessage => ({ timestamp: index, }); +for (const field of ["attachments", "images"] as const) { + test(`ChatMessageList shows unavailable restored ${field} without broken image previews`, () => { + const messages: ChatMessage[] = [{ + id: "restored-user", role: "user", content: "restored request", timestamp: 1, + [field]: [ + { base64Data: "", contentUnavailable: true, mediaType: "image/png", filename: "screenshot.png" }, + { base64Data: "", contentUnavailable: true, mediaType: "application/pdf", filename: "report.pdf" }, + { base64Data: "", contentUnavailable: true, mediaType: "text/plain", filename: "selection.log", terminalSelection: true }, + ], + }]; + const markup = renderToStaticMarkup( + + + , + ); + assert.match(markup, /screenshot\.png/); + assert.match(markup, /report\.pdf/); + assert.match(markup, /selection\.log/); + assert.match(markup, /Content not available on this device/); + assert.doesNotMatch(markup, / { + const messages: ChatMessage[] = [{ + id: "user", role: "user", content: "look", timestamp: 1, + attachments: [ + { base64Data: "cGljdHVyZQ==", mediaType: "image/png", filename: "local.png" }, + { base64Data: "", contentUnavailable: true, mediaType: "text/markdown", vaultNoteId: "note-1", vaultNoteTitle: "Runbook" }, + ], + }]; + const markup = renderToStaticMarkup( + + + , + ); + assert.match(markup, / { const previous = new Map(); for (let index = 0; index < 1_000; index += 1) previous.set(`old-${index}`, true); diff --git a/components/ai/ChatMessageList.tsx b/components/ai/ChatMessageList.tsx index d59918544..e2f46bdd6 100644 --- a/components/ai/ChatMessageList.tsx +++ b/components/ai/ChatMessageList.tsx @@ -710,7 +710,19 @@ const ChatMessageList: React.FC = ({ {isUser && !hideAttachments && (message.attachments ?? message.images)?.length && (
{(message.attachments ?? message.images)!.map((att, i) => ( - att.terminalSelection ? ( + !att.vaultNoteId && (att.contentUnavailable || !att.base64Data) ? ( +
+ {att.terminalSelection + ? + : } + {att.filename || (att.terminalSelection ? 'terminal selection' : 'file')} + {t('ai.chat.attachmentContentUnavailable')} +
+ ) : att.terminalSelection ? (
{ + const attachments: ChatMessageAttachment[] = [ + { base64Data: "", contentUnavailable: true, mediaType: "image/png", filename: "screenshot.png" }, + { base64Data: "", contentUnavailable: true, mediaType: "application/pdf", filename: "report.pdf" }, + { base64Data: "", contentUnavailable: true, mediaType: "text/plain", filename: "selection.log", terminalSelection: true, lineCount: 3 }, + ]; + const messages: ChatMessage[] = [{ + id: "restored-user", role: "user", content: "Inspect these files", timestamp: 1, + [field]: attachments, + }]; + const catty = buildCattySdkMessages({ + allMessages: messages, + includeCurrentUserMessage: true, + trimmed: "Please continue", + continuationContext: createContinuationContext("provider", "openai", "model", false), + chatSessionId: "restored-chat", + toolOutputStore: new ToolOutputStore(), + fieldsByMessage: new Map(), + }); + const external = buildExternalBridgeContextMessages(messages); + for (const history of [catty, external]) { + const content = String(history.find((message) => message.role === "user")?.content); + assert.match(content, /screenshot\.png/); + assert.match(content, /report\.pdf/); + assert.match(content, /selection\.log/); + assert.match(content, /lines=3/); + assert.equal(content.match(/content unavailable on this device/g)?.length, 3); + assert.doesNotMatch(content, /0 base64 chars|undefined/); + } + assert.equal(catty.at(-1)?.content, "Please continue"); + }); +} + +test("synced note metadata retains the reference needed to read the note", () => { + const replay = buildHistoricalUserReplayContent("check this note", [{ + base64Data: "", contentUnavailable: true, mediaType: "text/markdown", + vaultNoteId: "note-123", vaultNoteTitle: "Runbook", + }]); + assert.match(replay, /"noteId":"note-123"/); + assert.match(replay, /vault_notes_get/); +}); + +test("unavailable attachment placeholders do not expose stale local content fields", () => { + const replay = buildHistoricalUserReplayContent("check", [{ + base64Data: "", contentUnavailable: true, mediaType: "text/plain", terminalSelection: true, + previewText: "private terminal output", + }, { + base64Data: "", contentUnavailable: true, mediaType: "application/pdf", filePath: "/private/report.pdf", + }]); + assert.doesNotMatch(replay, /private terminal output|\/private\//); +}); + test("external recovery retains note identity before truncating a long user request", () => { const history = buildExternalBridgeContextMessages([{ id: "long-note-request", role: "user", timestamp: 1, content: "x".repeat(2500), diff --git a/components/ai/cattyHistoryReplay.ts b/components/ai/cattyHistoryReplay.ts index 22b2d94ec..fa7918d46 100644 --- a/components/ai/cattyHistoryReplay.ts +++ b/components/ai/cattyHistoryReplay.ts @@ -15,6 +15,9 @@ function truncateInline(value: string, maxChars: number): string { } function describeAttachmentSize(attachment: ChatMessageAttachment): string { + if (attachment.contentUnavailable || !attachment.base64Data) { + return "content unavailable on this device"; + } return `${attachment.base64Data.length} base64 chars`; } @@ -25,7 +28,7 @@ function formatTerminalSelectionPlaceholder( const details = [ `filename=${attachment.filename || `terminal-selection-${index + 1}.log`}`, attachment.lineCount != null ? `lines=${attachment.lineCount}` : undefined, - attachment.previewText ? `preview=${truncateInline(attachment.previewText, MAX_ATTACHMENT_PLACEHOLDER_DETAIL_CHARS)}` : undefined, + !attachment.contentUnavailable && attachment.previewText ? `preview=${truncateInline(attachment.previewText, MAX_ATTACHMENT_PLACEHOLDER_DETAIL_CHARS)}` : undefined, describeAttachmentSize(attachment), ].filter(Boolean).join(", "); @@ -39,7 +42,7 @@ function formatAttachmentPlaceholder( const label = attachment.mediaType.startsWith("image/") ? "image" : "file"; const details = [ attachment.filename ? `filename=${attachment.filename}` : undefined, - attachment.filePath ? `path=${attachment.filePath}` : undefined, + !attachment.contentUnavailable && attachment.filePath ? `path=${attachment.filePath}` : undefined, `mediaType=${attachment.mediaType}`, describeAttachmentSize(attachment), ].filter(Boolean).join(", "); diff --git a/components/cloud-sync/CloudSyncDashboardTabs.tsx b/components/cloud-sync/CloudSyncDashboardTabs.tsx index 23e6cff59..12d54376a 100644 --- a/components/cloud-sync/CloudSyncDashboardTabs.tsx +++ b/components/cloud-sync/CloudSyncDashboardTabs.tsx @@ -603,6 +603,7 @@ export const CloudSyncDashboardTabs: React.FC = ({
{t('cloudSync.aiSessions.title')}
{t('cloudSync.aiSessions.desc')} + {' '}{t('cloudSync.aiSessions.compatibility')}
{ + const [downloaded] = stripAiSessionPayloadForSync([session([{ + ...user('Inspect the attachments'), + [field]: [ + { base64Data: 'cGljdHVyZQ==', mediaType: 'image/png', filename: 'picture.png' }, + { base64Data: 'ZG9jdW1lbnQ=', mediaType: 'application/pdf', filename: 'document.pdf' }, + { base64Data: 'bG9n', mediaType: 'text/plain', filename: 'terminal.log', terminalSelection: true }, + { base64Data: '', mediaType: 'text/markdown', vaultNoteId: 'note-1', vaultNoteTitle: 'Runbook' }, + ], + }, assistant('Done')])]); + const result = buildUndoLastTurnBranch(downloaded, { newId: 'branch', now: 42 }); + assert.ok(result); + assert.equal(result.restored.text, 'Inspect the attachments'); + assert.deepEqual(result.restored.attachments.map((attachment) => attachment.vaultNoteId), ['note-1']); + + const messages = buildCattySdkMessages({ + allMessages: result.session.messages, + includeCurrentUserMessage: true, + trimmed: result.restored.text, + attachments: result.restored.attachments, + continuationContext: createContinuationContext('provider', 'openai', 'model', false), + chatSessionId: result.session.id, + toolOutputStore: new ToolOutputStore(), + fieldsByMessage: new Map(), + }); + assert.equal(messages.length, 1); + assert.equal(messages[0].role, 'user'); + assert.equal(typeof messages[0].content, 'string'); + assert.match(String(messages[0].content), /Inspect the attachments/); + assert.match(String(messages[0].content), /"noteId":"note-1"/); + assert.doesNotMatch(JSON.stringify(messages), /"type":"file"/); + }); +} + +test('undo skips attachment records whose body is absent and preserves real local files', () => { + const source = session([{ + ...user('Inspect'), + attachments: [ + // Older downloaded metadata did not retain base64Data or an availability marker. + JSON.parse('{"mediaType":"image/png","filename":"missing.png"}'), + { base64Data: '', mediaType: 'application/pdf', filename: 'empty.pdf' }, + { base64Data: 'YWJj', mediaType: 'text/plain', filename: 'local.log', terminalSelection: true }, + ], + }]); + const result = buildUndoLastTurnBranch(source, { newId: 'branch', now: 42 }); + assert.ok(result); + assert.equal(result.restored.attachments.length, 1); + assert.equal(result.restored.attachments[0].filename, 'local.log'); + assert.equal(result.restored.attachments[0].base64Data, 'YWJj'); + assert.equal(result.restored.attachments[0].dataUrl, 'data:text/plain;base64,YWJj'); + assert.equal(result.restored.attachments[0].terminalSelection, true); +}); + test('buildUndoLastTurnBranch restores the undone turn selected user skills', () => { const source = session([ user('first'), diff --git a/domain/aiUndoLastTurn.ts b/domain/aiUndoLastTurn.ts index 5323fa00b..e094ff667 100644 --- a/domain/aiUndoLastTurn.ts +++ b/domain/aiUndoLastTurn.ts @@ -86,7 +86,12 @@ export function buildRestoredAttachments( now: number, ): UploadedFile[] { const attachments: ChatMessageAttachment[] = message.attachments ?? message.images ?? []; - return attachments.map((attachment, index) => ({ + // Synced files retain display metadata only. They cannot be sent again + // until selected locally; note mentions remain usable through their ID. + return attachments.filter((attachment) => ( + Boolean(attachment.vaultNoteId) + || (!attachment.contentUnavailable && Boolean(attachment.base64Data)) + )).map((attachment, index) => ({ id: `undo_${now}_${index}`, filename: attachment.filename ?? '', mediaType: attachment.mediaType, diff --git a/domain/convergentSync/legacy.ts b/domain/convergentSync/legacy.ts index cc42e2fe2..cbc77ca3b 100644 --- a/domain/convergentSync/legacy.ts +++ b/domain/convergentSync/legacy.ts @@ -48,6 +48,7 @@ export function inheritOmittedLegacySyncFields( ...CONVERGENT_ENTITY_COLLECTIONS, ...CONVERGENT_STRING_COLLECTIONS, 'settings', + 'aiSessions', ]) { if (!hasDefinedOwnProperty(legacy, property)) { resultRecord[property] = baselineRecord[property]; @@ -127,6 +128,7 @@ export function cloudSyncPayloadsEqual(left: SyncPayload, right: SyncPayload): b .map((key) => [key, (sanitized as unknown as Record)[key] ?? []]), ), settings: sanitized.settings ?? {}, + aiSessions: sanitized.aiSessions ?? [], // Plugin sidecars are host-owned opaque data on the encrypted blob and // must participate in migration freshness / equality checks. pluginSidecars: sanitized.pluginSidecars ?? { version: 1, entries: [] }, diff --git a/domain/convergentSync/legacyAiSessions.test.ts b/domain/convergentSync/legacyAiSessions.test.ts new file mode 100644 index 000000000..e3ee04cb6 --- /dev/null +++ b/domain/convergentSync/legacyAiSessions.test.ts @@ -0,0 +1,24 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { cloudSyncPayloadsEqual, inheritOmittedLegacySyncFields } from './legacy'; +import type { SyncPayload } from '../sync'; + +const payload = (overrides: Partial = {}): SyncPayload => ({ + hosts: [], keys: [], snippets: [], customGroups: [], syncedAt: 0, ...overrides, +}); +const sessions = [{ id: 'chat-1', updatedAt: 1, messages: [{ id: 'm1', content: 'hello' }] }] as SyncPayload['aiSessions']; + +test('chat-only changes participate in cloud payload equality', () => { + const base = payload({ aiSessions: sessions }); + assert.equal(cloudSyncPayloadsEqual(base, payload({ aiSessions: sessions, syncedAt: 123 })), true); + assert.equal(cloudSyncPayloadsEqual(base, payload({ aiSessions: [] })), false); + const changed = structuredClone(base); + changed.aiSessions![0].messages[0].content = 'complete'; + assert.equal(cloudSyncPayloadsEqual(base, changed), false); +}); + +test('unsupported omitted chat fields inherit baseline, while explicit empty remains a reset', () => { + const base = payload({ aiSessions: sessions }); + assert.equal(cloudSyncPayloadsEqual(base, inheritOmittedLegacySyncFields(base, payload())), true); + assert.equal(cloudSyncPayloadsEqual(base, inheritOmittedLegacySyncFields(base, payload({ aiSessions: [] }))), false); +}); diff --git a/domain/convergentSync/migration.ts b/domain/convergentSync/migration.ts index 6335f6223..bd72b862b 100644 --- a/domain/convergentSync/migration.ts +++ b/domain/convergentSync/migration.ts @@ -1,5 +1,4 @@ import { - CLOUD_SYNC_PAYLOAD_ENTITY_KEYS, hasSyncPayloadEntityData, type CloudProvider, type ConvergentMigrationPreview, @@ -78,6 +77,15 @@ function mergeMigrationSidecarsWithBaselines(options: { return { version: 1, entries }; } +// Chats use their existing transcript merge, not a new CRDT collection. A +// chat-only difference therefore needs no causal vault baseline to migrate. +function vaultPayloadsEqual(left: SyncPayload, right: SyncPayload): boolean { + return cloudSyncPayloadsEqual( + { ...left, aiSessions: undefined }, + { ...right, aiSessions: undefined }, + ); +} + /* * A local snapshot with no cloud entities and no trusted base is a fresh * device, not an untrusted deletion. Settings are intentionally ignored here @@ -89,7 +97,7 @@ function shouldIncludeLegacyLocalSource( trustedBaseline: SyncPayload | null, ): boolean { return trustedBaseline !== null - || hasSyncPayloadEntityData(payload, CLOUD_SYNC_PAYLOAD_ENTITY_KEYS); + || hasSyncPayloadEntityData(payload, [...CONVERGENT_ENTITY_COLLECTIONS, ...CONVERGENT_STRING_COLLECTIONS]); } export type ConvergentMigrationProviderInput = @@ -157,6 +165,7 @@ export function planConvergentSyncMigration(options: { providers: ConvergentMigrationProviderInput[]; deviceId: string; now: number; + preserveDeletions?: boolean; }): ConvergentMigrationPlan { const providers = [...options.providers].sort((left, right) => left.provider.localeCompare(right.provider)); const blockedReasons: string[] = []; @@ -219,6 +228,10 @@ export function planConvergentSyncMigration(options: { let merged = seedFromProvider ? v1Inputs[0].payload : options.localPayload; if (seedFromProvider) { const seed = v1Inputs[0]; + merged = { + ...merged, + aiSessions: mergeSyncPayloads(null, options.localPayload, merged).payload.aiSessions, + }; const shrink = detectSuspiciousShrink( seed.payload, seed.trustedBaseline, @@ -232,18 +245,30 @@ export function planConvergentSyncMigration(options: { const remainingInputs = seedFromProvider ? v1Inputs.slice(1) : v1Inputs; for (const input of remainingInputs) { if (!input.trustedBaseline) { - if (!cloudSyncPayloadsEqual(merged, input.payload)) { + if (!vaultPayloadsEqual(merged, input.payload)) { blockedReasons.push(`${input.provider}: no trusted legacy baseline is available`); } + merged = { + ...merged, + aiSessions: mergeSyncPayloads(null, merged, input.payload).payload.aiSessions, + }; continue; } - const result = mergeSyncPayloads(input.trustedBaseline, merged, input.payload); + const result = mergeSyncPayloads(input.trustedBaseline, merged, input.payload, { + preserveDeletions: options.preserveDeletions, + }); + const vaultMerge = mergeSyncPayloads( + { ...input.trustedBaseline, aiSessions: undefined }, + { ...merged, aiSessions: undefined }, + { ...input.payload, aiSessions: undefined }, + { preserveDeletions: options.preserveDeletions }, + ); const changeSummary = summarizeSyncChanges( input.trustedBaseline, merged, input.payload, ); - if (result.hadConflicts || changeSummary.hasConflicts) { + if (vaultMerge.hadConflicts || changeSummary.conflicts.some((conflict) => conflict.entityType !== 'aiSessions')) { blockedReasons.push(`${input.provider}: legacy smart merge has unresolved conflicts`); } const shrink = detectSuspiciousShrink(result.payload, input.trustedBaseline, input.payload); @@ -268,6 +293,7 @@ export function planConvergentSyncMigration(options: { syncedAt: options.now, syncMeta: merged.syncMeta, ...(migrationSidecars ? { pluginSidecars: migrationSidecars } : {}), + ...(merged.aiSessions !== undefined ? { aiSessions: merged.aiSessions } : {}), }); } } else if (blockedReasons.length === 0) { @@ -288,9 +314,22 @@ export function planConvergentSyncMigration(options: { })), ], }); + let joinedAiPayload = options.localPayload; + for (const input of [...v2Inputs, ...v1Inputs]) { + joinedAiPayload = { + ...joinedAiPayload, + aiSessions: mergeSyncPayloads( + input.trustedBaseline ?? options.localTrustedBaseline, + joinedAiPayload, + input.payload, + { preserveDeletions: options.preserveDeletions }, + ).payload.aiSessions, + }; + } const joinedPayload = materializeSyncPayloadFromConvergentState(state, { syncedAt: options.now, ...(joinedSidecars ? { pluginSidecars: joinedSidecars } : {}), + ...(joinedAiPayload.aiSessions !== undefined ? { aiSessions: joinedAiPayload.aiSessions } : {}), }); const legacySources: Array<{ id: string; @@ -318,13 +357,15 @@ export function planConvergentSyncMigration(options: { ]; const branches: ConvergentSyncStateV2[] = []; for (const source of legacySources) { - if (cloudSyncPayloadsEqual(source.payload, joinedPayload)) continue; + if (vaultPayloadsEqual(source.payload, joinedPayload)) continue; if (!source.baseline) { blockedReasons.push(`${source.id}: no trusted legacy baseline is available`); continue; } const shrink = detectSuspiciousShrink( - inheritOmittedLegacySyncFields(source.baseline, source.payload), + options.preserveDeletions + ? mergeSyncPayloads(null, source.payload, joinedPayload, { preserveDeletions: true }).payload + : inheritOmittedLegacySyncFields(source.baseline, source.payload), source.baseline, ); if (shrink.suspicious) { @@ -344,10 +385,27 @@ export function planConvergentSyncMigration(options: { materialized = materializeSyncPayloadFromConvergentState(state, { syncedAt: options.now, ...(joinedSidecars ? { pluginSidecars: joinedSidecars } : {}), + ...(joinedAiPayload.aiSessions !== undefined ? { aiSessions: joinedAiPayload.aiSessions } : {}), }); } } + if (options.preserveDeletions && state && materialized && blockedReasons.length === 0) { + let retained = materialized; + for (const source of [options.localPayload, ...v1Inputs.map((input) => input.payload), ...v2Inputs.map((input) => input.payload)]) { + retained = mergeSyncPayloads(null, retained, source, { preserveDeletions: true }).payload; + } + state = applyLegacySyncPayload(state, materialized, { + ...retained, + settings: materialized.settings, + }, options.deviceId, options.now); + materialized = materializeSyncPayloadFromConvergentState(state, { + syncedAt: options.now, + pluginSidecars: materialized.pluginSidecars, + aiSessions: retained.aiSessions, + }); + } + const conflicts = state ? materializeConvergentSyncState(state).conflicts : []; if (conflicts.length > 0) blockedReasons.push('The convergent state contains unresolved field conflicts'); const canInitialize = blockedReasons.length === 0 && state !== null && materialized !== null; @@ -358,6 +416,7 @@ export function planConvergentSyncMigration(options: { ...(materialized?.pluginSidecars ? { pluginSidecars: materialized.pluginSidecars } : {}), + ...(materialized?.aiSessions !== undefined ? { aiSessions: materialized.aiSessions } : {}), }) : null; const previewPayload = materialized ?? options.localPayload; diff --git a/domain/convergentSync/payload.ts b/domain/convergentSync/payload.ts index 7902453cd..1fc4668fd 100644 --- a/domain/convergentSync/payload.ts +++ b/domain/convergentSync/payload.ts @@ -206,6 +206,8 @@ export function materializeSyncPayloadFromConvergentState( syncMeta?: SyncReliabilityMeta; /** Opaque plugin sidecars travel with the encrypted blob outside CRDT fields. */ pluginSidecars?: SyncPayload['pluginSidecars']; + /** Chat transcripts travel outside the vault's fixed CRDT collections. */ + aiSessions?: SyncPayload['aiSessions']; }, ): SyncPayload { requireKnownCollections(state); @@ -232,6 +234,7 @@ export function materializeSyncPayloadFromConvergentState( settings, syncedAt: options.syncedAt, ...(options.syncMeta ? { syncMeta: options.syncMeta } : {}), + ...(options.aiSessions !== undefined ? { aiSessions: options.aiSessions } : {}), // Preserve explicit empty bundles so lifecycle materializations (conflict // resolve / downgrade) can clear or re-upload sidecars rather than omit // the field and look like a legacy payload. @@ -532,6 +535,7 @@ export function withConvergentSyncEnvelope( syncedAt: number; syncMeta?: SyncReliabilityMeta; pluginSidecars?: SyncPayload['pluginSidecars']; + aiSessions?: SyncPayload['aiSessions']; }, ): SyncPayload { const payload = materializeSyncPayloadFromConvergentState(state, options); diff --git a/domain/convergentSync/payloadMigration.test.ts b/domain/convergentSync/payloadMigration.test.ts index 9be42cea0..894659ec9 100644 --- a/domain/convergentSync/payloadMigration.test.ts +++ b/domain/convergentSync/payloadMigration.test.ts @@ -92,6 +92,66 @@ function meta(overrides: Partial = {}): SyncFileMeta { }; } +for (const [existingV2, trusted] of [[false, true], [true, true], [false, false], [true, false]]) { + test(`${existingV2 ? 'v2 join' : 'v1 migration'} preserves independent chat turns ${trusted ? 'with' : 'without'} a trusted vault baseline`, () => { + const baseline = payload(); + const session = (ids: string[], updatedAt: number): NonNullable[number] => ({ + id: 'chat', title: 'Chat', agentId: 'catty', scope: { type: 'global' }, createdAt: NOW, updatedAt, + messages: ids.map((id, index) => ({ id, role: 'user', content: id, timestamp: NOW + index })), + }); + baseline.aiSessions = [session(['first'], NOW)]; + const local = { ...baseline, aiSessions: [session(['first', 'local'], NOW + 1)] }; + const remote = { ...baseline, aiSessions: [session(['first', 'remote'], NOW + 2)] }; + const state = createConvergentSyncStateFromPayload(remote, 'remote', NOW); + const remotePayload = existingV2 + ? withConvergentSyncEnvelope(state, { syncedAt: NOW, aiSessions: remote.aiSessions }) + : remote; + const plan = planConvergentSyncMigration({ + localPayload: local, localTrustedBaseline: trusted ? baseline : null, + providers: [{ provider: 'github', status: 'ready', meta: meta(existingV2 ? { syncSchemaVersion: 2 } : {}), payload: remotePayload, trustedBaseline: trusted ? baseline : null }], + deviceId: 'local', now: NOW + 3, + }); + assert.equal(plan.preview.canInitialize, true, plan.preview.blockedReasons.join('; ')); + assert.deepEqual(new Set(plan.payload?.aiSessions?.[0].messages.map((message) => message.id)), new Set(['first', 'local', 'remote'])); + assert.equal(plan.payload?.convergentSync?.state.collections.aiSessions, undefined); + assert.ok(validateConvergentSyncPayload({ syncSchemaVersion: 2 }, plan.payload!)); + }); +} + +for (const existingV2 of [false, true]) { + test(`${existingV2 ? 'v2 join' : 'v1 migration'} adopts a cloud vault while keeping fresh local chats`, () => { + const local = emptyPayload(); + local.aiSessions = [{ id: 'local-chat', title: 'Local', agentId: 'catty', scope: { type: 'global' }, createdAt: NOW, updatedAt: NOW, messages: [] }]; + const cloud = payload(); + const state = createConvergentSyncStateFromPayload(cloud, 'remote', NOW); + const plan = planConvergentSyncMigration({ + localPayload: local, localTrustedBaseline: null, + providers: [{ provider: 'github', status: 'ready', meta: meta(existingV2 ? { syncSchemaVersion: 2 } : {}), payload: existingV2 ? withConvergentSyncEnvelope(state, { syncedAt: NOW }) : cloud, trustedBaseline: null }], + deviceId: 'local', now: NOW + 1, + }); + assert.equal(plan.preview.canInitialize, true, plan.preview.blockedReasons.join('; ')); + assert.deepEqual(plan.payload?.hosts, cloud.hosts); + assert.deepEqual(plan.payload?.aiSessions, local.aiSessions); + }); + + test(`${existingV2 ? 'v2 join' : 'v1 migration'} honors preservation when one source deleted a host`, () => { + const baseline = payload(); + baseline.hosts.push({ ...baseline.hosts[0], id: 'survivor', label: 'Survivor' }); + const smaller = { ...baseline, hosts: baseline.hosts.slice(0, 1) }; + const state = createConvergentSyncStateFromPayload(baseline, 'seed', NOW); + const remotePayload = existingV2 + ? withConvergentSyncEnvelope(applyLegacySyncPayload(state, baseline, smaller, 'remote', NOW + 1), { syncedAt: NOW }) + : baseline; + const plan = planConvergentSyncMigration({ + localPayload: existingV2 ? baseline : smaller, localTrustedBaseline: baseline, + providers: [{ provider: 'github', status: 'ready', meta: meta(existingV2 ? { syncSchemaVersion: 2 } : {}), payload: remotePayload, trustedBaseline: baseline }], + deviceId: 'local', now: NOW + 3, preserveDeletions: true, + }); + assert.equal(plan.preview.canInitialize, true, plan.preview.blockedReasons.join('; ')); + assert.deepEqual(plan.payload?.hosts.map((host) => host.id).sort(), ['host-1', 'survivor']); + }); +} + test('encrypted envelope omits materialized winner values and hydrates exactly', () => { const state = createConvergentSyncStateFromPayload(payload(), 'device-a', NOW); const materialized = materializeSyncPayloadFromConvergentState(state, { syncedAt: NOW }); diff --git a/domain/syncMerge.aiSessions.test.ts b/domain/syncMerge.aiSessions.test.ts index 1f6148c67..61915af4d 100644 --- a/domain/syncMerge.aiSessions.test.ts +++ b/domain/syncMerge.aiSessions.test.ts @@ -1,8 +1,10 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { mergeSyncPayloads, stripAiSessionPayloadForSync } from "./syncMerge.ts"; +import { mergeAiSessionLists, mergeSyncPayloads, stripAiSessionDeviceState, stripAiSessionPayloadForSync } from "./syncMerge.ts"; import type { SyncPayload } from "./sync.ts"; +import { encodeSdkSessionIdentity } from "../infrastructure/ai/harness/sdkSessionIdentity.ts"; +import { buildExternalAgentHistoryMessagesForBridge } from "../components/ai/externalAgentHistory.ts"; type Session = NonNullable[number]; @@ -109,7 +111,8 @@ test("stripAiSessionPayloadForSync removes inline attachment blobs but keeps met const attachment = (stripped.messages?.[0] as unknown as { attachments?: Array> }).attachments?.[0]; assert.ok(attachment, "attachment metadata should survive"); - assert.equal(attachment?.base64Data, undefined, "inline blob must be stripped"); + assert.equal(attachment?.base64Data, "", "inline blob must be stripped"); + assert.equal(attachment?.contentUnavailable, true); assert.equal(attachment?.filename, "a.png"); assert.equal(attachment?.lineCount, 3); }); @@ -124,3 +127,131 @@ test("ai sessions: merge is idempotent", () => { const s1 = second.payload.aiSessions?.find((s) => s.id === "s1"); assert.deepEqual((s1?.messages ?? []).map((m) => m.id), ["m1", "m2", "m3"]); }); + + +test("ai sessions: old or opted-out clients omit chats without deleting the known baseline", () => { + const base = payload({ aiSessions: [session("s1", 100, [msg("m1", 1)])] }); + const oldClient = payload(); + delete oldClient.aiSessions; + for (const [local, remote] of [[oldClient, base], [base, oldClient], [oldClient, oldClient]]) { + assert.deepEqual(mergeSyncPayloads(base, local, remote).payload.aiSessions, base.aiSessions); + } + assert.deepEqual(mergeSyncPayloads(base, payload(), base).payload.aiSessions, []); + assert.equal(Object.hasOwn(mergeSyncPayloads(null, oldClient, oldClient).payload, 'aiSessions'), false); +}); + +test("ai sessions: completed messages replace their streamed copy on the newer side", () => { + const partial = session("s1", 100, [{ ...msg("m1", 1), content: "Hel" }]); + const complete = session("s1", 200, [{ ...msg("m1", 1), content: "Hello world" }]); + for (const [local, remote] of [[partial, complete], [complete, partial]]) { + const result = mergeAiSessionLists([local], [remote]); + assert.equal(result[0].messages.length, 1); + assert.equal(result[0].messages[0].content, "Hello world"); + } +}); + +test("ai sessions: a new turn survives deletion on the other device", () => { + const initial = session("s1", 100, [msg("m1", 1)]); + const edited = session("s1", 200, [msg("m1", 1), msg("m2", 2)]); + const base = payload({ aiSessions: [initial] }); + const modified = payload({ aiSessions: [edited] }); + for (const [local, remote] of [[modified, payload()], [payload(), modified]]) { + const result = mergeSyncPayloads(base, local, remote); + assert.deepEqual(result.payload.aiSessions, [edited]); + assert.equal(result.hadConflicts, true); + } +}); + +test("cloud attachment whitelist excludes previews, paths, data URLs and arbitrary body properties", () => { + const attachment = { + base64Data: "U0VDUkVU", mediaType: "text/plain", filename: "terminal.txt", + terminalSelection: true, vaultNoteId: "note-1", vaultNoteTitle: "My note", lineCount: 2, + previewText: "SECRET", filePath: "/private/file", dataUrl: "data:text/plain;base64,U0VDUkVU", + futureBody: "SECRET", + }; + const original = [{ messages: [{ attachments: [attachment], images: [attachment] }] }]; + const [stripped] = stripAiSessionPayloadForSync(original); + const expected = { + base64Data: "", contentUnavailable: true, mediaType: "text/plain", filename: "terminal.txt", + terminalSelection: true, vaultNoteId: "note-1", vaultNoteTitle: "My note", lineCount: 2, + }; + assert.deepEqual(stripped.messages[0].attachments, [expected]); + assert.deepEqual(stripped.messages[0].images, [expected]); + assert.equal(original[0].messages[0].attachments[0].base64Data, "U0VDUkVU"); +}); + +test("merging metadata-only history preserves available attachment bytes on this device", () => { + const attachment = { + base64Data: "U0VDUkVU", mediaType: "image/png", filename: "a.png", + previewText: "preview", filePath: "/private/a.png", + }; + const local = { ...session("s1", 100, [msg("m1", 1)]), messages: [{ ...msg("m1", 1), attachments: [attachment], images: [attachment] }] }; + const [incoming] = stripAiSessionPayloadForSync([{ ...local, updatedAt: 200, title: "remote title" }]); + const [merged] = mergeAiSessionLists([local], [incoming]); + assert.equal(merged.title, "remote title"); + assert.deepEqual(merged.messages[0].attachments, [attachment]); + assert.deepEqual(merged.messages[0].images, [attachment]); + assert.equal(incoming.messages[0].attachments[0].base64Data, ""); +}); + + +test("new attachment representation keeps bytes from the legacy image list", () => { + const attachment = { base64Data: "SU1BR0U=", mediaType: "image/png", filename: "a.png" }; + const local = { ...session("s1", 100, [msg("m1", 1)]), messages: [{ ...msg("m1", 1), images: [attachment] }] }; + const incoming = { ...session("s1", 200, [msg("m1", 1)]), messages: [{ ...msg("m1", 1), attachments: [{ ...attachment, base64Data: "", contentUnavailable: true }] }] }; + const [merged] = mergeAiSessionLists([local], [incoming]); + assert.equal(merged.messages[0].attachments?.[0].base64Data, "SU1BR0U="); +}); + + +test("cloud copies start a fresh external SDK thread and replay the saved history", () => { + for (const [backend, runtime] of [["claude", "sdk"], ["codex", "sdk"], ["codex", "app-server"], ["cursor", "sdk"]]) { + const original: Session = { + ...session("s1", 100, [msg("m1", 1)]), + externalSessionId: encodeSdkSessionIdentity("source-thread", backend, "/source/bin/agent", runtime), + }; + const [cloud] = stripAiSessionPayloadForSync([original]); + assert.equal(Object.hasOwn(cloud, "externalSessionId"), false, `${backend}/${runtime}`); + assert.equal(original.externalSessionId?.includes("source-thread"), true); + const restored = mergeAiSessionLists([], [cloud])[0]; + assert.equal(restored.externalSessionId, undefined); + assert.ok(buildExternalAgentHistoryMessagesForBridge(restored.messages, restored.externalSessionId)?.length); + } +}); + +test("cloud copies clear source-only work state while preserving portable replay metadata", () => { + const source: Session = { + ...session("s1", 100, [msg("m1", 1)]), + messages: [{ + id: "a1", role: "assistant", timestamp: 2, content: "Saved tool-output-source-123", + statusText: "Waiting for approval", executionStatus: "running", + pendingApproval: { approvalId: "source-approval", toolCallId: "call1", toolName: "exec", toolArgs: {}, status: "pending" }, + providerContinuation: { + source: { providerConfigId: "provider-1", providerType: "anthropic", modelId: "claude" }, + reasoningParts: [{ text: "checked", providerOptions: { anthropic: { signature: "signed-thinking" } } }], + }, + }], + contextCompaction: { summary: "Earlier context", compactedMessageCount: 1 }, + }; + const [cloud] = stripAiSessionPayloadForSync([source]); + assert.equal(cloud.messages[0].pendingApproval, undefined); + assert.equal(cloud.messages[0].statusText, undefined); + assert.equal(cloud.messages[0].executionStatus, "cancelled"); + assert.doesNotMatch(cloud.messages[0].content, /tool-output-source-123/); + assert.deepEqual(cloud.messages[0].providerContinuation, source.messages[0].providerContinuation); + assert.deepEqual(cloud.contextCompaction, source.contextCompaction); + assert.equal(source.messages[0].executionStatus, "running"); + assert.equal(source.messages[0].pendingApproval?.approvalId, "source-approval"); +}); + + +test("cloud application device cleanup preserves attachment bytes for existing local storage", () => { + const source: Session = { + ...session("s1", 100, [msg("m1", 1)]), externalSessionId: "source-thread", + messages: [{ ...msg("m1", 1), attachments: [{ mediaType: "image/png", base64Data: "SU1BR0U=", filename: "a.png", filePath: "/local/a.png" }] }], + }; + const clean = stripAiSessionDeviceState(source); + assert.equal(clean.externalSessionId, undefined); + assert.deepEqual(clean.messages[0].attachments, source.messages[0].attachments); + assert.equal(source.externalSessionId, "source-thread"); +}); diff --git a/domain/syncMerge.preserveDeletions.test.ts b/domain/syncMerge.preserveDeletions.test.ts index e4c7f67c9..9d856908b 100644 --- a/domain/syncMerge.preserveDeletions.test.ts +++ b/domain/syncMerge.preserveDeletions.test.ts @@ -142,3 +142,30 @@ test("preserveDeletions: deletions are still reported in the summary", () => { assert.equal(preserved.summary.deleted.local, 1, "summary should report the local deletion that was not propagated"); assert.ok(preserved.payload.hosts.some((h) => h.id === "b")); }); + + +test("preserveDeletions: no-base tombstones cannot suppress surviving entities or strings", () => { + const survivor = payload({ hosts: [host("a")], customGroups: ["group"], noteGroups: ["notes"] }); + const removed = payload({ + syncMeta: { + schemaVersion: 1, generatedAt: 10, localChanged: true, + changeSummary: { hasLocalChanges: true, hasRemoteChanges: false, hasConflicts: false, byEntity: {}, conflicts: [] }, + deletions: [ + { entityType: "hosts", id: "a", deletedAt: 10 }, + { entityType: "customGroups", id: "group", deletedAt: 10 }, + { entityType: "noteGroups", id: "notes", deletedAt: 10 }, + ], + }, + }); + for (const [local, remote] of [[survivor, removed], [removed, survivor]]) { + const normal = mergeSyncPayloads(null, local, remote).payload; + assert.deepEqual(normal.hosts, []); + assert.deepEqual(normal.customGroups, []); + assert.deepEqual(normal.noteGroups, []); + const preserved = mergeSyncPayloads(null, local, remote, { preserveDeletions: true }).payload; + assert.deepEqual(preserved.hosts.map((item) => item.id), ["a"]); + assert.deepEqual(preserved.customGroups, survivor.customGroups); + assert.deepEqual(preserved.noteGroups, survivor.noteGroups); + assert.equal(preserved.syncMeta?.deletions.length ?? 0, 0); + } +}); diff --git a/domain/syncMerge.ts b/domain/syncMerge.ts index 5e4f8593f..5fbe9a96e 100644 --- a/domain/syncMerge.ts +++ b/domain/syncMerge.ts @@ -35,6 +35,7 @@ import { type SyncPayload, } from './sync'; import { mergePluginSyncSidecarsThreeWay } from './pluginSyncSidecar'; +import { stripMessageContinuationState, type ForkMessageLike } from './aiSessionFork'; // --------------------------------------------------------------------------- // Public types @@ -80,6 +81,7 @@ const OPTIONAL_ENTITY_KEYS = new Set([ 'noteGroups', 'portForwardingRules', 'groupConfigs', + 'aiSessions', ]); // --------------------------------------------------------------------------- @@ -109,7 +111,7 @@ function entityArray( ): T[] { if ( OPTIONAL_ENTITY_KEYS.has(key) - && !Object.prototype.hasOwnProperty.call(payload, key) + && payload[key] === undefined ) { return fallback; } @@ -161,12 +163,12 @@ function mergeEntityArrays( const inLocal = localItem !== undefined; const inRemote = remoteItem !== undefined; - if (!inBase && inLocal && !inRemote && tombstones?.remote.has(id)) { + if (!options?.preserveDeletions && !inBase && inLocal && !inRemote && tombstones?.remote.has(id)) { // Remote explicitly records this entity as deleted. When no base is // available, this tombstone is the only durable signal that absence is // intentional rather than an old client omitting the entity. deleted.remote++; - } else if (!inBase && !inLocal && inRemote && tombstones?.local.has(id)) { + } else if (!options?.preserveDeletions && !inBase && !inLocal && inRemote && tombstones?.local.has(id)) { deleted.local++; } else if (!inBase && inLocal && !inRemote) { // Local addition @@ -244,33 +246,59 @@ function mergeEntityArrays( // AI session merge (messages are append-only) // --------------------------------------------------------------------------- +/** Remove work state that belongs to the source device, keeping local attachment bodies. */ +export function stripAiSessionDeviceState(session: T): T { + const messages = Array.isArray(session.messages) + ? session.messages.map((message) => { + if (!message || typeof message !== 'object') return message; + const source = message as Record; + const portable = typeof source.id === 'string' && typeof source.content === 'string' + && ['user', 'assistant', 'system', 'tool'].includes(source.role as string) + ? stripMessageContinuationState(source as ForkMessageLike) + : source; + const next: Record = { ...portable }; + delete next.statusText; + delete next.pendingApproval; + if (next.executionStatus === 'pending' || next.executionStatus === 'running') { + next.executionStatus = 'cancelled'; + } + return next; + }) + : []; + const portableSession: Record = { ...session, messages }; + // External SDK IDs refer to provider threads/local runtime files on the + // source device. Fresh receivers must replay the portable history instead. + delete portableSession.externalSessionId; + return portableSession as T; +} + /** * Strip inline attachment payloads before they enter a sync payload. * Base64 image/PDF blobs would multiply the encrypted vault size and can * carry data the user never intended to leave the device; only the metadata * (filename, media type, line count) is worth keeping for context. + * Device-owned external threads and active approvals cannot resume elsewhere. */ export function stripAiSessionPayloadForSync( sessions: T[] | undefined, ): T[] { if (!Array.isArray(sessions)) return []; return sessions.map((session) => { - const messages = Array.isArray((session as { messages?: unknown[] }).messages) - ? (session as { messages: Array> }).messages.map((message) => { - if (!message || typeof message !== 'object') return message; - const { attachments, images, ...rest } = message as Record & { - attachments?: unknown[]; - images?: unknown[]; - }; - if (attachments === undefined && images === undefined) return rest; - return { - ...rest, - ...(attachments ? { attachments: stripAttachmentBlobs(attachments) } : {}), - ...(images ? { images: stripAttachmentBlobs(images) } : {}), - }; - }) - : []; - return { ...session, messages } as T; + const portable = stripAiSessionDeviceState(session); + const messages = (portable.messages ?? []).map((message) => { + if (!message || typeof message !== 'object') return message; + const { attachments, images, ...rest } = message as Record & { + attachments?: unknown[]; + images?: unknown[]; + }; + if (attachments === undefined && images === undefined) return rest; + return { + ...rest, + ...(attachments ? { attachments: stripAttachmentBlobs(attachments) } : {}), + ...(images ? { images: stripAttachmentBlobs(images) } : {}), + }; + }); + return { ...portable, messages } as T; }); } @@ -278,8 +306,15 @@ function stripAttachmentBlobs(attachments: unknown[]): unknown[] { if (!Array.isArray(attachments)) return attachments; return attachments.map((attachment) => { if (!attachment || typeof attachment !== 'object') return attachment; - const { base64Data: _base64Data, ...meta } = attachment as Record & { base64Data?: string }; - return meta; + const source = attachment as Record; + // Persist only display metadata. In particular, terminal/note previews, + // data URLs and filesystem paths can contain the attachment's full body. + const metadata = Object.fromEntries( + ['mediaType', 'filename', 'terminalSelection', 'vaultNoteId', 'vaultNoteTitle', 'lineCount'] + .filter((key) => source[key] !== undefined) + .map((key) => [key, source[key]]), + ); + return { ...metadata, base64Data: '', contentUnavailable: true }; }); } @@ -342,8 +377,10 @@ function mergeAiSessionArrays([], local ?? [], incoming ?? []).merged; } +/** Keep available attachment bodies on this device when the chosen message is metadata-only. */ +function retainAvailableAttachments(preferred: M, other: M): M { + const result: Record = { ...preferred }; + const previous = other as M & Record; + for (const field of ['attachments', 'images']) { + const attachments = result[field]; + const available = previous[field] ?? previous[field === 'attachments' ? 'images' : 'attachments']; + if (!Array.isArray(attachments) || !Array.isArray(available)) continue; + result[field] = attachments.map((attachment: unknown) => { + if (!attachment || typeof attachment !== 'object') return attachment; + const metadata = attachment as Record; + if (typeof metadata.base64Data === 'string' && metadata.base64Data.length > 0) return attachment; + const match = available.find((candidate: unknown) => { + if (!candidate || typeof candidate !== 'object') return false; + const value = candidate as Record; + return typeof value.base64Data === 'string' && value.base64Data.length > 0 + && ['filename', 'mediaType', 'terminalSelection', 'vaultNoteId'] + .every((key) => value[key] === metadata[key]); + }) as Record | undefined; + if (!match) return attachment; + const restored: Record = { ...metadata, base64Data: match.base64Data }; + for (const key of ['previewText', 'dataUrl', 'filePath']) { + if (match[key] !== undefined) restored[key] = match[key]; + } + delete restored.contentUnavailable; + return restored; + }); + } + return result as M; +} + function mergeAiSessionPair }>( a: T, b: T, ): T { const newer = (b.updatedAt ?? 0) > (a.updatedAt ?? 0) ? b : a; - const seen = new Map ? M : never)>(); - for (const session of [a, b, newer]) { - for (const message of (session.messages ?? []) as Array<{ id?: string; timestamp?: number }>) { + const older = newer === a ? b : a; + const seen = new Map(); + // Later values replace matching IDs so a completed reply replaces the + // earlier streamed copy. Distinct turns remain append-only. + for (const session of [older, newer]) { + for (const message of session.messages ?? []) { const key = message.id ?? `${message.timestamp ?? 0}:${fingerprint(message)}`; - if (!seen.has(key)) seen.set(key, message); + const existing = seen.get(key); + seen.set(key, existing ? retainAvailableAttachments(message, existing) : message); } } const messages = [...seen.values()].sort((x, y) => (x.timestamp ?? 0) - (y.timestamp ?? 0)); @@ -417,9 +491,9 @@ function mergeStringArrays( const inLocal = localSet.has(value); const inRemote = remoteSet.has(value); - if (!inBase && inLocal && !inRemote && tombstones?.remote.has(value)) { + if (!options?.preserveDeletions && !inBase && inLocal && !inRemote && tombstones?.remote.has(value)) { // Remote tombstone wins over a stale local value when no base exists. - } else if (!inBase && !inLocal && inRemote && tombstones?.local.has(value)) { + } else if (!options?.preserveDeletions && !inBase && !inLocal && inRemote && tombstones?.local.has(value)) { // Local tombstone wins over a stale remote value when no base exists. } else if (!inBase) { // Addition — keep if either side added it @@ -837,7 +911,9 @@ export function mergeSyncPayloads( noteGroups, portForwardingRules: portForwardingRules.merged, groupConfigs, - aiSessions: aiSessions.merged, + ...(base?.aiSessions !== undefined || local.aiSessions !== undefined || remote.aiSessions !== undefined + ? { aiSessions: aiSessions.merged } + : {}), settings, ...(mergedSidecarEntries.length > 0 || anySideHadPluginSidecars ? { pluginSidecars: { version: 1 as const, entries: mergedSidecarEntries } } diff --git a/domain/syncReliability.test.ts b/domain/syncReliability.test.ts index 3d1c3d95d..7149b480e 100644 --- a/domain/syncReliability.test.ts +++ b/domain/syncReliability.test.ts @@ -317,3 +317,18 @@ test("withSyncReliabilityMeta attaches change summary and deletion records", () deviceId: "device-a", }]); }); + + +test("omitted AI sessions are unsupported data, while an explicit empty list records deletion", () => { + const sessions = [{ id: "chat-1", messages: [], updatedAt: 1 }] as SyncPayload["aiSessions"]; + const base = payload({ aiSessions: sessions }); + const omitted = payload(); + const cleared = payload({ aiSessions: [] }); + assert.deepEqual(collectSyncDeletions(base, omitted, { deletedAt: 2 }), []); + assert.equal(summarizeSyncChanges(base, omitted, base).hasLocalChanges, false); + assert.equal(summarizeSyncChanges(base, base, omitted).hasRemoteChanges, false); + assert.deepEqual(collectSyncDeletions(base, cleared, { deletedAt: 2 }), [ + { entityType: "aiSessions", id: "chat-1", deletedAt: 2 }, + ]); + assert.equal(summarizeSyncChanges(base, cleared).byEntity.aiSessions?.deleted.local, 1); +}); diff --git a/domain/syncReliability.ts b/domain/syncReliability.ts index 47041766a..e51822a6b 100644 --- a/domain/syncReliability.ts +++ b/domain/syncReliability.ts @@ -25,6 +25,7 @@ const OPTIONAL_ENTITY_KEYS = new Set([ 'snippetPackages', 'portForwardingRules', 'groupConfigs', + 'aiSessions', ]); function fingerprint(value: unknown): string { @@ -70,7 +71,7 @@ function payloadValues( if ( base && OPTIONAL_ENTITY_KEYS.has(entityType) - && !Object.prototype.hasOwnProperty.call(payload, entityType) + && payload[entityType] === undefined ) { return base[entityType]; } diff --git a/infrastructure/ai/harness/externalBridgeContext.ts b/infrastructure/ai/harness/externalBridgeContext.ts index 509454405..885b0e881 100644 --- a/infrastructure/ai/harness/externalBridgeContext.ts +++ b/infrastructure/ai/harness/externalBridgeContext.ts @@ -66,7 +66,7 @@ function getUserHistoryContent(message: ChatMessage): string { if (message.role !== "user") return message.content || ""; return buildHistoricalUserReplayContent( message.content || "", - message.attachments ?? [], + message.attachments ?? message.images ?? [], ); } @@ -174,10 +174,11 @@ function summarizeMessage( function summarizeDurableUserMessage(message: ChatMessage): string | null { if (message.role !== "user") return null; - const notes = message.attachments?.filter(isVaultNoteAttachment) ?? []; + const attachments = message.attachments ?? message.images; + const notes = attachments?.filter(isVaultNoteAttachment) ?? []; if (notes.length) { // Budget prose separately: the reference instruction must not consume the request's 280 characters. - const nonNotes = message.attachments?.filter((attachment) => !isVaultNoteAttachment(attachment)); + const nonNotes = attachments?.filter((attachment) => !isVaultNoteAttachment(attachment)); const request = truncateText(normalizeWhitespace(buildHistoricalUserReplayContent(message.content || '', nonNotes)), MAX_DURABLE_USER_MESSAGE_CHARS); return `User request: ${request}\n${formatVaultNoteReferences(notes)}`; } diff --git a/infrastructure/ai/types.ts b/infrastructure/ai/types.ts index cd9d044ce..eeaa99758 100644 --- a/infrastructure/ai/types.ts +++ b/infrastructure/ai/types.ts @@ -103,6 +103,8 @@ export interface ModelInfo { // Chat types export interface ChatMessageAttachment { base64Data: string; + /** Synced attachment metadata whose content is only available on the source device. */ + contentUnavailable?: boolean; mediaType: string; filename?: string; filePath?: string; // original filesystem path, when available diff --git a/infrastructure/services/CloudSyncManager.ts b/infrastructure/services/CloudSyncManager.ts index b6c209641..0a897dfff 100644 --- a/infrastructure/services/CloudSyncManager.ts +++ b/infrastructure/services/CloudSyncManager.ts @@ -962,6 +962,7 @@ export class CloudSyncManager { ) => Promise, options?: { pluginSidecars?: SyncPayload['pluginSidecars']; + aiSessions?: SyncPayload['aiSessions']; }, ): Promise<{ payload: SyncPayload; results: Map }> { return resolveConvergentConflictAndSyncImpl.call( diff --git a/infrastructure/services/cloudSync/convergentSyncRuntimeMethods.test.ts b/infrastructure/services/cloudSync/convergentSyncRuntimeMethods.test.ts index 20e4d83d3..88a0587bc 100644 --- a/infrastructure/services/cloudSync/convergentSyncRuntimeMethods.test.ts +++ b/infrastructure/services/cloudSync/convergentSyncRuntimeMethods.test.ts @@ -241,6 +241,121 @@ function installEncryptionDouble() { }; } +function chatSession(messageIds: string[], updatedAt = NOW): NonNullable[number] { + return { + id: 'chat', title: 'Chat', agentId: 'catty', scope: { type: 'global' }, + createdAt: NOW, updatedAt, + messages: messageIds.map((id, index) => ({ id, role: 'user', content: id, timestamp: NOW + index })), + }; +} + +test('chat-only convergent changes merge both transcripts, apply them, and remain idle afterwards', async () => { + const encryption = installEncryptionDouble(); + try { + const basePayload = payload('base'); + const state = createConvergentSyncStateFromPayload(basePayload, 'seed', NOW); + const remoteChats = [chatSession(['first', 'remote'], NOW + 2)]; + const github = adapter(encryption.register(withConvergentSyncEnvelope(state, { syncedAt: NOW, aiSessions: remoteChats }))); + const subject = manager(state, { github }); + const local = { ...basePayload, aiSessions: [chatSession(['first', 'local'], NOW + 1)] }; + let applied: SyncPayload | undefined; + const results = await syncConvergentProvidersUnlockedImpl.call(subject, local, { + now: () => NOW + 10, jitter: async () => {}, + applyPayload: async (incoming, commit) => { applied = incoming; await commit(); }, + }); + assert.equal(results.get('github')?.success, true); + assert.deepEqual(new Set(applied?.aiSessions?.[0].messages.map((message) => message.id)), new Set(['first', 'local', 'remote'])); + const uploaded = await EncryptionService.decryptPayload(github.remote!, 'pw'); + assert.deepEqual(uploaded.aiSessions, applied?.aiSessions); + assert.equal(uploaded.convergentSync?.state.collections.aiSessions, undefined, 'chats must not add an incompatible vault collection'); + assert.equal(github.uploads, 1); + await syncConvergentProvidersUnlockedImpl.call(subject, applied!, { now: () => NOW + 20, jitter: async () => {}, applyPayload: applyAndCommit }); + assert.equal(github.uploads, 1); + } finally { encryption.restore(); } +}); + +test('convergent verification rejects an upload whose chat history was dropped', async () => { + const encryption = installEncryptionDouble(); + try { + const local = { ...payload('base'), aiSessions: [chatSession(['local'])] }; + const state = createConvergentSyncStateFromPayload(local, 'seed', NOW); + const github = adapter(encryption.register(withConvergentSyncEnvelope(state, { syncedAt: NOW }))); + github.afterUpload = (file, transport) => { + const uploaded = encryption.payloads.get(file.payload)!; + transport.remote = encryption.register({ ...uploaded, aiSessions: [] }, file.meta.version); + }; + const subject = manager(state, { github }); + const results = await syncConvergentProvidersUnlockedImpl.call(subject, local, { + now: () => NOW + 10, jitter: async () => {}, applyPayload: applyAndCommit, + }); + assert.equal(results.get('github')?.success, false); + assert.match(results.get('github')?.error ?? '', /expected chat history/); + } finally { encryption.restore(); } +}); + +test('convergent downgrade retains cloud chats for an opted-out local device', async () => { + const encryption = installEncryptionDouble(); + const previousNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator'); + try { + Object.defineProperty(globalThis, 'navigator', { + configurable: true, + value: { locks: { request: async (_name: string, _options: unknown, callback: (lock: object) => unknown) => callback({}) } }, + }); + const local = payload('base'); + const state = createConvergentSyncStateFromPayload(local, 'seed', NOW); + const aiSessions = [chatSession(['remote'])]; + const github = adapter(encryption.register(withConvergentSyncEnvelope(state, { syncedAt: NOW, aiSessions }))); + const subject = manager(state, { github }); + let applied: SyncPayload | undefined; + const results = await downgradeConvergentSyncImpl.call(subject, true, () => local, async (incoming, commit) => { + applied = incoming; + await commit(); + }); + assert.equal(results.get('github')?.success, true); + assert.deepEqual(applied?.aiSessions, aiSessions); + const uploaded = await EncryptionService.decryptPayload(github.remote!, 'pw'); + assert.deepEqual(uploaded.aiSessions, aiSessions); + assert.equal(uploaded.convergentSync, undefined); + assert.deepEqual(subject.legacyCommits[0].payload.aiSessions, aiSessions); + } finally { + if (previousNavigator) Object.defineProperty(globalThis, 'navigator', previousNavigator); + else Reflect.deleteProperty(globalThis, 'navigator'); + encryption.restore(); + } +}); + +for (const uploadFails of [false, true]) { + test(`preserve strategy restores a survivor suppressed by a remote deletion${uploadFails ? ' even when upload fails' : ''}`, async () => { + const encryption = installEncryptionDouble(); + try { + const local = payloadWithHostCount(2); + const state = createConvergentSyncStateFromPayload(local, 'seed', NOW); + const remotePayload = { ...local, hosts: [{ ...local.hosts[0], label: 'Remote edit' }] }; + const deleted = remoteState(state, local, remotePayload, 'remote-device', NOW + 1); + const github = adapter(encryption.register(withConvergentSyncEnvelope(deleted, { syncedAt: NOW + 1 }))); + github.failUpload = uploadFails; + const subject = manager(state, { github }); + subject.state.syncStrategy = 'smartMergePreserve'; + let applied: SyncPayload | undefined; + const results = await syncConvergentProvidersUnlockedImpl.call(subject, local, { + now: () => NOW + 10, jitter: async () => {}, + applyPayload: async (incoming, commit) => { applied = incoming; await commit(); }, + }); + assert.equal(results.get('github')?.success, !uploadFails); + assert.deepEqual(applied?.hosts.map((host) => host.id).sort(), ['host-0', 'host-1']); + assert.equal(applied?.hosts[0].label, 'Remote edit'); + const persisted = materializeSyncPayloadFromConvergentState(subject.persisted.at(-1)!, { syncedAt: NOW }); + assert.deepEqual(persisted.hosts, applied?.hosts, 'the durable replica must match the protected local apply'); + if (!uploadFails) { + const uploaded = await EncryptionService.decryptPayload(github.remote!, 'pw'); + assert.deepEqual(uploaded.hosts, applied?.hosts); + await syncConvergentProvidersUnlockedImpl.call(subject, applied!, { now: () => NOW + 20, jitter: async () => {}, applyPayload: applyAndCommit }); + assert.equal(github.uploads, 1); + } + } finally { encryption.restore(); } + }); +} + test('unordered provider join preserves independent offline edits and persists before upload', async () => { const encryption = installEncryptionDouble(); try { @@ -367,14 +482,15 @@ test('recovery preview joins providers without persisting or uploading state', a const base = createConvergentSyncStateFromPayload(basePayload, 'seed', NOW); const githubState = remoteState(base, basePayload, payload('remote-label'), 'github-device', NOW + 1); const googleState = remoteState(base, basePayload, payload('base', 'remote-user'), 'google-device', NOW + 2); - const github = adapter(encryption.register(withConvergentSyncEnvelope(githubState, { syncedAt: NOW }), 2)); - const google = adapter(encryption.register(withConvergentSyncEnvelope(googleState, { syncedAt: NOW }), 2)); + const github = adapter(encryption.register(withConvergentSyncEnvelope(githubState, { syncedAt: NOW, aiSessions: [chatSession(['github'])] }), 2)); + const google = adapter(encryption.register(withConvergentSyncEnvelope(googleState, { syncedAt: NOW, aiSessions: [chatSession(['google'], NOW + 1)] }), 2)); const subject = manager(base, { github, google }); const preview = await previewConvergentRecoveryImpl.call(subject); assert.equal(preview?.hosts[0]?.label, 'remote-label'); assert.equal(preview?.hosts[0]?.username, 'remote-user'); + assert.deepEqual(new Set(preview?.aiSessions?.[0].messages.map((message) => message.id)), new Set(['github', 'google'])); assert.equal(subject.persisted.length, 0); assert.equal(github.uploads, 0); assert.equal(google.uploads, 0); diff --git a/infrastructure/services/cloudSync/convergentSyncRuntimeMethods.ts b/infrastructure/services/cloudSync/convergentSyncRuntimeMethods.ts index e76363c7e..2c569dc8a 100644 --- a/infrastructure/services/cloudSync/convergentSyncRuntimeMethods.ts +++ b/infrastructure/services/cloudSync/convergentSyncRuntimeMethods.ts @@ -25,8 +25,9 @@ import { versionVectorsEqual, withConvergentSyncEnvelope, } from '../../../domain/convergentSync'; -import type { CloudSyncStrategy } from '../../../domain/syncStrategy'; +import { isPreserveDeletionsStrategy, type CloudSyncStrategy } from '../../../domain/syncStrategy'; import type { CloudSyncConflictAction } from '../../../domain/syncStrategy'; +import { mergeAiSessionLists, mergeSyncPayloads } from '../../../domain/syncMerge'; import { detectSuspiciousShrink } from '../../../domain/syncGuards'; import { EncryptionService } from '../EncryptionService'; import type { CloudAdapter } from '../adapters'; @@ -144,15 +145,59 @@ function materializedPayload( state: ConvergentSyncStateV2, now: number, pluginSidecars?: SyncPayload['pluginSidecars'], + aiSessions?: SyncPayload['aiSessions'], ): SyncPayload { return materializeSyncPayloadFromConvergentState(state, { syncedAt: now, ...(pluginSidecars && Array.isArray(pluginSidecars.entries) ? { pluginSidecars } : {}), + ...(aiSessions !== undefined ? { aiSessions } : {}), }); } +function mergeRuntimeAiSessions( + local: SyncPayload, + remotes: ProviderRuntime[], + baselines: Map, + strategy: CloudSyncStrategy, +): SyncPayload['aiSessions'] { + let merged = local; + for (const runtime of remotes) { + const remote = runtime.latestRemotePayload ?? runtime.verifiedPayload; + if (!remote) continue; + const aiSessions = strategy === 'preferLocal' && local.aiSessions !== undefined + ? local.aiSessions + : strategy === 'preferCloud' && remote.aiSessions !== undefined + ? remote.aiSessions + : mergeSyncPayloads(baselines.get(runtime.provider) ?? null, merged, remote, { + preserveDeletions: isPreserveDeletionsStrategy(strategy), + }).payload.aiSessions; + merged = { ...merged, aiSessions }; + } + return merged.aiSessions; +} + +function chatPayloadsEqual(left: SyncPayload, aiSessions: SyncPayload['aiSessions']): boolean { + return cloudSyncPayloadsEqual(left, { ...left, aiSessions }); +} + +function preserveSurvivingState( + state: ConvergentSyncStateV2, + sources: SyncPayload[], + deviceId: string, + now: number, +): ConvergentSyncStateV2 { + const baseline = materializedPayload(state, now); + let retained = baseline; + for (const source of sources) { + retained = mergeSyncPayloads(null, retained, source, { preserveDeletions: true }).payload; + } + // Keep the CRDT's field winners and settings. Only missing survivors need + // ordinary causal upserts to supersede an observed deletion. + return applyLegacySyncPayload(state, baseline, { ...retained, settings: baseline.settings }, deviceId, now); +} + function sidecarBundleFromPayload( payload: SyncPayload | null | undefined, ): SyncPayload['pluginSidecars'] | undefined { @@ -293,6 +338,7 @@ async function runInitialDownloads( interface PreparedLocalState { canonical: ConvergentSyncStateV2; durableBeforeVerification: ConvergentSyncStateV2; + preservedSurvivors?: boolean; } function prepareLocalState( @@ -329,9 +375,14 @@ function prepareLocalState( deviceId, now, ); + const joined = mergeStates(withLocalWrites, remoteStates); + const canonical = isPreserveDeletionsStrategy(strategy) + ? preserveSurvivingState(joined, [localPayload, ...remoteStates.map((state) => materializedPayload(state, now))], deviceId, now) + : joined; return { - canonical: mergeStates(withLocalWrites, remoteStates), + canonical, durableBeforeVerification: withLocalWrites, + preservedSurvivors: !versionVectorsEqual(joined.vector, canonical.vector), }; } @@ -383,7 +434,7 @@ export async function syncConvergentProvidersUnlockedImpl( const strategy = options.strategyOverride ?? this.state.syncStrategy; const replicaPayload = materializedPayload(replica.state, now()); - if (strategy !== 'preferCloud') { + if (strategy !== 'preferCloud' && !isPreserveDeletionsStrategy(strategy)) { const finding = detectSuspiciousShrink( stripConvergentSyncEnvelope(inputPayload), replicaPayload, @@ -426,7 +477,7 @@ export async function syncConvergentProvidersUnlockedImpl( now(), ); let canonical = preparedLocal.canonical; - const durableBeforeVerification = preparedLocal.durableBeforeVerification; + let durableBeforeVerification = preparedLocal.durableBeforeVerification; // Persist locally-generated dots before every network write, but do not // commit downloaded remote-only dots until at least one provider verifies @@ -435,16 +486,31 @@ export async function syncConvergentProvidersUnlockedImpl( await persistReplica(this, durableBeforeVerification, now()); updateConflictState(this, durableBeforeVerification); + const applyPreservedSurvivors = async (state: ConvergentSyncStateV2) => { + if (!options.applyPayload) throw new Error('Preserving convergent survivors requires a protected payload applier'); + let committed = false; + await options.applyPayload(materializedPayload(state, now()), async () => { + await persistReplica(this, state, now()); + updateConflictState(this, state); + durableBeforeVerification = state; + committed = true; + }); + if (!committed) throw new Error('Preserved payload apply completed without committing its replica'); + }; + if (preparedLocal.preservedSurvivors) await applyPreservedSurvivors(canonical); + // Capture pre-cycle sidecar baselines per provider (never union across // providers). Cross-provider union invents a shared base that can treat one // provider's empty remote as deleting another provider's retained settings. const cycleBaseByProvider = new Map['entries']>(); + const cyclePayloadBaseByProvider = new Map(); if (typeof this.loadConvergentProviderBaseline === 'function') { for (const runtime of usable) { try { const baseline = await this.loadConvergentProviderBaseline(runtime.provider) as { materializedPayload?: SyncPayload; } | null; + if (baseline?.materializedPayload) cyclePayloadBaseByProvider.set(runtime.provider, baseline.materializedPayload); const baseBundle = baseline?.materializedPayload?.pluginSidecars; if (!baseBundle || !Array.isArray(baseBundle.entries)) continue; cycleBaseByProvider.set(runtime.provider, baseBundle.entries); @@ -469,6 +535,17 @@ export async function syncConvergentProvidersUnlockedImpl( })); canonical = mergeStates(canonical, preflight.flatMap((decoded) => decoded ? [decoded.state] : [])); + if (isPreserveDeletionsStrategy(strategy)) { + const preserved = preserveSurvivingState(canonical, [ + inputPayload, + ...usable.flatMap((runtime) => runtime.latestRemotePayload ? [runtime.latestRemotePayload] : []), + ], this.state.deviceId, now()); + if (!versionVectorsEqual(canonical.vector, preserved.vector)) { + canonical = preserved; + await applyPreservedSurvivors(canonical); + } + } + const expected = canonical; const preflightVerified = new Map(); await Promise.all(usable.map(async (runtime, index) => { @@ -559,19 +636,25 @@ export async function syncConvergentProvidersUnlockedImpl( if (runtime.error) return false; return providerSidecarMismatch(runtime); }); + const aiSessions = mergeRuntimeAiSessions(inputPayload, usable.filter((runtime) => !runtime.error), cyclePayloadBaseByProvider, strategy); + const providerChatMismatch = (runtime: ProviderRuntime) => { + const decoded = preflightVerified.get(runtime.provider); + return !decoded || !chatPayloadsEqual(decoded.payload, aiSessions); + }; const needsUpload = usable.some((runtime) => ( !runtime.error && !preflightVerified.has(runtime.provider) - )) || remoteSidecarMismatch; + )) || remoteSidecarMismatch || usable.some((runtime) => !runtime.error && providerChatMismatch(runtime)); const outgoingPayload = needsUpload ? withConvergentSyncEnvelope(expected, { syncedAt: now(), pluginSidecars, + aiSessions, }) : null; await Promise.all(usable.map(async (runtime) => { // Upload when CRDT preflight missed OR sidecars diverge for this provider. if (runtime.error) return; - if (preflightVerified.has(runtime.provider) && !providerSidecarMismatch(runtime)) return; + if (preflightVerified.has(runtime.provider) && !providerSidecarMismatch(runtime) && !providerChatMismatch(runtime)) return; if (!outgoingPayload) return; try { const remoteVersion = runtime.latestRemote?.meta.version ?? this.state.localVersion; @@ -610,6 +693,9 @@ export async function syncConvergentProvidersUnlockedImpl( if (!versionVectorDominates(decoded.state.vector, expected.vector)) { throw new Error('Remote verification did not retain the expected convergent state'); } + if (!chatPayloadsEqual(decoded.payload, aiSessions)) { + throw new Error('Remote verification did not retain the expected chat history'); + } await markProviderVerified(this, runtime, decoded); return decoded; } catch (error) { @@ -667,6 +753,8 @@ export async function syncConvergentProvidersUnlockedImpl( ...mergedPayloadBase, ...(finalPluginSidecars ? { pluginSidecars: finalPluginSidecars } : {}), }; + const finalAiSessions = mergeRuntimeAiSessions(inputPayload, successfulRuntimes, cyclePayloadBaseByProvider, strategy); + if (finalAiSessions !== undefined) mergedPayload.aiSessions = finalAiSessions; const localPayloadChanged = !cloudSyncPayloadsEqual(inputPayload, mergedPayload) || JSON.stringify(inputPayload.pluginSidecars ?? null) !== JSON.stringify(mergedPayload.pluginSidecars ?? null); @@ -850,7 +938,12 @@ export async function previewConvergentRecoveryImpl( )); if (remoteStates.length === 0) return null; const [first, ...rest] = remoteStates; - return materializedPayload(mergeStates(first, rest), Date.now()); + let aiSessions: SyncPayload['aiSessions']; + for (const runtime of runtimes) { + const sessions = runtime.latestRemotePayload?.aiSessions; + if (sessions !== undefined) aiSessions = mergeAiSessionLists(aiSessions, sessions); + } + return materializedPayload(mergeStates(first, rest), Date.now(), undefined, aiSessions); }); } @@ -860,6 +953,7 @@ async function prepareConvergentConflictResolutionImpl( candidateDot: string, now = Date.now(), pluginSidecars?: SyncPayload['pluginSidecars'], + aiSessions?: SyncPayload['aiSessions'], ): Promise<{ state: ConvergentSyncStateV2; payload: SyncPayload; now: number }> { const replica = await this.loadConvergentReplica(); if (!replica) throw new Error('Convergent sync replica is unavailable'); @@ -880,7 +974,7 @@ async function prepareConvergentConflictResolutionImpl( // preserves local sidecars (legacy missing-field semantics). return { state: resolved, - payload: materializedPayload(resolved, now, pluginSidecars), + payload: materializedPayload(resolved, now, pluginSidecars, aiSessions), now, }; } @@ -895,6 +989,7 @@ export async function resolveConvergentConflictAndSyncImpl( ) => Promise, options?: { pluginSidecars?: SyncPayload['pluginSidecars']; + aiSessions?: SyncPayload['aiSessions']; }, ): Promise<{ payload: SyncPayload; results: Map }> { return withConvergentSyncWebLock(async () => { @@ -904,6 +999,7 @@ export async function resolveConvergentConflictAndSyncImpl( candidateDot, Date.now(), options?.pluginSidecars, + options?.aiSessions, ); let committed = false; await applyPayload(prepared.payload, async () => { @@ -930,6 +1026,8 @@ export async function resolveConvergentConflictAndSyncImpl( finalReplica.state, Date.now(), sidecarBundleFromPayload(prepared.payload), + [...results.values()].find((result) => result.mergedPayload)?.mergedPayload?.aiSessions + ?? prepared.payload.aiSessions, ); return { payload: finalPayload, results }; }); @@ -977,6 +1075,14 @@ export async function downgradeConvergentSyncImpl( } const now = Date.now(); + const chatBaselines = new Map(); + if (typeof this.loadConvergentProviderBaseline === 'function') { + for (const runtime of runtimes) { + const baseline = await this.loadConvergentProviderBaseline(runtime.provider) as ConvergentProviderBaselineV2 | null; + if (baseline) chatBaselines.set(runtime.provider, baseline.materializedPayload); + } + } + const downgradeAiSessions = mergeRuntimeAiSessions(localPayload, runtimes, chatBaselines, this.state.syncStrategy); // Pausing v2 stops synchronization, not local editing. Convert every // vault change made since the last persisted replica into causal local // writes before joining provider states; otherwise downgrade would @@ -1026,10 +1132,16 @@ export async function downgradeConvergentSyncImpl( this.state.deviceId, now, ); - const canonical = mergeStates( + let canonical = mergeStates( withLocalWrites, runtimes.flatMap((runtime) => runtime.verifiedState ? [runtime.verifiedState] : []), ); + if (isPreserveDeletionsStrategy(this.state.syncStrategy)) { + canonical = preserveSurvivingState(canonical, [ + localPayload, + ...runtimes.flatMap((runtime) => runtime.latestRemotePayload ? [runtime.latestRemotePayload] : []), + ], this.state.deviceId, now); + } const conflicts = currentConflicts(canonical); if (conflicts.length > 0) { const message = `Resolve ${conflicts.length} convergent conflict(s) before downgrading`; @@ -1046,7 +1158,7 @@ export async function downgradeConvergentSyncImpl( return results; } - const outgoing = materializedPayload(canonical, now, downgradeSidecars); + const outgoing = materializedPayload(canonical, now, downgradeSidecars, downgradeAiSessions); assertSyncSecurityGeneration(this, syncSecurityGeneration); let committed = false; try { diff --git a/infrastructure/services/cloudSync/providerSyncMethods.ts b/infrastructure/services/cloudSync/providerSyncMethods.ts index 716468810..4934104d0 100644 --- a/infrastructure/services/cloudSync/providerSyncMethods.ts +++ b/infrastructure/services/cloudSync/providerSyncMethods.ts @@ -67,7 +67,7 @@ async function uploadLocalPayloadImpl(this: any, const directBase = await this.loadSyncBase(provider); assertSyncSecurityGeneration(this, syncSecurityGeneration); let directRemoteRef: SyncPayload | null = null; - if (!directBase && remoteFile) { + if ((!directBase || payload.aiSessions === undefined) && remoteFile) { assertSyncSecurityGeneration(this, syncSecurityGeneration); try { directRemoteRef = await EncryptionService.decryptPayload( @@ -79,6 +79,11 @@ async function uploadLocalPayloadImpl(this: any, } assertSyncSecurityGeneration(this, syncSecurityGeneration); } + // Whole-vault keep-local does not authorize deleting a collection this + // client omitted. Use the checked remote, which may be newer than the base. + if (payload.aiSessions === undefined && directRemoteRef?.aiSessions !== undefined) { + payload = { ...payload, aiSessions: directRemoteRef.aiSessions }; + } const metadataBase = directBase ?? directRemoteRef; const payloadForUpload = withSyncReliabilityMeta(payload, metadataBase, { deviceId: this.state.deviceId, @@ -428,6 +433,16 @@ export async function syncToProviderImpl(this: any, // unknown remote state. const checkResult = await this.checkProviderConflict(provider, adapter); assertSyncSecurityGeneration(this, syncSecurityGeneration); + assertConvergentSyncWriteCompatible(checkResult.remoteFile?.meta, payload); + // Opting out means this device has no chat changes to publish. Retain + // the provider's existing history even on a non-conflicting upload. + if (payload.aiSessions === undefined && checkResult.remoteFile && !checkResult.conflict) { + const remotePayload = await EncryptionService.decryptPayload(checkResult.remoteFile, this.masterPassword); + assertSyncSecurityGeneration(this, syncSecurityGeneration); + if (remotePayload.aiSessions !== undefined) { + payload = { ...payload, aiSessions: remotePayload.aiSessions }; + } + } const unchanged = await tryAcceptIdenticalRemoteImpl.call( this, provider, adapter, payload, checkResult.remoteFile, syncSecurityGeneration, providerIdentity, @@ -439,9 +454,11 @@ export async function syncToProviderImpl(this: any, return unchanged; } - if (checkResult.conflict && checkResult.remoteFile) { + if (checkResult.remoteFile && ( + checkResult.conflict || isPreserveDeletionsStrategy(this.state.syncStrategy) + )) { const conflictAction = resolveCloudSyncConflictAction(this.state.syncStrategy, { - hasConflict: checkResult.conflict, + hasConflict: true, hasRemoteFile: Boolean(checkResult.remoteFile), }); diff --git a/infrastructure/services/cloudSync/syncAllStorageMethods.test.ts b/infrastructure/services/cloudSync/syncAllStorageMethods.test.ts index 34859d6f1..183889ef3 100644 --- a/infrastructure/services/cloudSync/syncAllStorageMethods.test.ts +++ b/infrastructure/services/cloudSync/syncAllStorageMethods.test.ts @@ -74,6 +74,149 @@ function remoteFile(provider: CloudProvider, version: number, updatedAt: number) }; } +for (const syncAll of [false, true]) { + test(`${syncAll ? 'all providers' : 'one provider'} preserves a smaller restored vault against a current remote without a base`, async () => { + const originalDecrypt = EncryptionService.decryptPayload; + const originalEncrypt = EncryptionService.encryptPayload; + let remote = payloadWithHosts(['kept', 'survivor']); + const local = payload('kept'); + local.hosts[0].label = 'restored local edit'; + let uploads = 0; + let storedBase: SyncPayload | null = null; + let checkedFile = remoteFile('github', 3, 300); + EncryptionService.decryptPayload = async () => remote; + EncryptionService.encryptPayload = async (outgoing) => ({ ...checkedFile, payload: JSON.stringify(outgoing) }); + try { + const subject = { + masterPassword: 'pw', + adapters: new Map(), + providerDecryptSeq: { github: 0 }, + state: { + securityState: 'UNLOCKED', providers: { github: { status: 'connected' } }, + syncStrategy: 'smartMergePreserve', syncState: 'IDLE', lastError: null, + localVersion: 3, deviceId: 'local', deviceName: 'Local', + }, + getConnectedAdapter: async () => ({}), + checkProviderConflict: async () => ({ conflict: false, remoteFile: checkedFile }), + loadSyncBase: async () => storedBase, + saveSyncBase: async (incoming: SyncPayload) => { storedBase = incoming; }, + saveSyncAnchor: async () => {}, saveProviderConnection: async () => {}, + saveSyncConfig: () => {}, notifyStateChange: () => {}, updateProviderStatus: () => {}, + emit: () => {}, exitBlockedState: () => {}, addSyncHistoryEntry: () => {}, + uploadToProvider: async (provider: CloudProvider, _adapter: unknown, file: SyncedFile, outgoing: SyncPayload) => { + uploads += 1; + remote = outgoing; + storedBase = outgoing; + checkedFile = file; + return { success: true, provider, action: 'upload' as const, version: 4 }; + }, + }; + const result = syncAll + ? (await syncAllProvidersImpl.call(subject, local)).get('github')! + : await syncToProviderImpl.call(subject, 'github', local); + assert.equal(result.success, true); + assert.deepEqual(remote.hosts.map((host) => host.id).sort(), ['kept', 'survivor']); + assert.equal(remote.hosts.find((host) => host.id === 'kept')?.label, 'restored local edit'); + assert.equal(result.mergedPayload?.hosts.length, 2); + assert.equal(uploads, 1); + if (syncAll) await syncAllProvidersImpl.call(subject, remote); + else await syncToProviderImpl.call(subject, 'github', remote); + assert.equal(uploads, 1, 'a second unchanged sync must not upload'); + } finally { + EncryptionService.decryptPayload = originalDecrypt; + EncryptionService.encryptPayload = originalEncrypt; + } + }); + + test(`${syncAll ? 'all providers' : 'one provider'} retains cloud chats when the local device opts out`, async () => { + const originalDecrypt = EncryptionService.decryptPayload; + const originalEncrypt = EncryptionService.encryptPayload; + const remote = payload('kept'); + remote.aiSessions = [{ id: 'chat', title: 'Cloud history', agentId: 'catty', scope: { type: 'global' }, messages: [], createdAt: 0, updatedAt: 1 }]; + let outgoing: SyncPayload | undefined; + EncryptionService.decryptPayload = async () => remote; + EncryptionService.encryptPayload = async () => remoteFile('github', 4, 400); + try { + const subject = { + masterPassword: 'pw', adapters: new Map(), providerDecryptSeq: { github: 0 }, + state: { + securityState: 'UNLOCKED', providers: { github: { status: 'connected' } }, + syncStrategy: 'smartMerge', syncState: 'IDLE', lastError: null, + localVersion: 3, deviceId: 'local', deviceName: 'Local', + }, + getConnectedAdapter: async () => ({}), + checkProviderConflict: async () => ({ conflict: false, remoteFile: remoteFile('github', 3, 300) }), + loadSyncBase: async () => null, updateProviderStatus: () => {}, + notifyStateChange: () => {}, emit: () => {}, exitBlockedState: () => {}, + uploadToProvider: async (provider: CloudProvider, _adapter: unknown, _file: SyncedFile, incoming: SyncPayload) => { + outgoing = incoming; + return { success: true, provider, action: 'upload' as const }; + }, + }; + const local = payloadWithHosts(['kept', 'new-local-host']); + const result = syncAll + ? (await syncAllProvidersImpl.call(subject, local)).get('github')! + : await syncToProviderImpl.call(subject, 'github', local); + assert.equal(result.success, true); + assert.deepEqual(outgoing?.aiSessions, remote.aiSessions); + assert.equal(local.aiSessions, undefined, 'opt-out must not collect or mutate local history'); + } finally { + EncryptionService.decryptPayload = originalDecrypt; + EncryptionService.encryptPayload = originalEncrypt; + } + }); +} + +for (const mode of ['provider', 'all', 'override'] as const) { + for (const clearChats of [false, true]) { + test(`${mode} keep-local ${clearChats ? 'honors explicit chat clearing' : 'retains omitted chats from the newer conflicting remote'}`, async () => { + const originalDecrypt = EncryptionService.decryptPayload; + const originalEncrypt = EncryptionService.encryptPayload; + const session = (id: string): NonNullable[number] => ({ + id, title: id, agentId: 'catty', scope: { type: 'global' }, createdAt: 0, updatedAt: 1, messages: [], + }); + const base = { ...payload('same-host'), aiSessions: [session('old-chat')] }; + const remote = { ...payload('same-host'), aiSessions: [session('old-chat'), session('new-cloud-chat')] }; + remote.hosts[0].label = 'New cloud edit'; + const local = payload('same-host'); + local.hosts[0].label = 'Keep this local edit'; + if (clearChats) local.aiSessions = []; + let outgoing: SyncPayload | undefined; + EncryptionService.decryptPayload = async () => remote; + EncryptionService.encryptPayload = async () => remoteFile('github', 6, 600); + try { + const subject = { + masterPassword: 'pw', adapters: new Map(), providerDecryptSeq: { github: 0 }, + state: { + securityState: 'UNLOCKED', providers: { github: { status: 'connected' } }, + syncStrategy: mode === 'override' ? 'smartMerge' : 'preferLocal', + syncState: 'IDLE', lastError: null, localVersion: 3, deviceId: 'local', deviceName: 'Local', + }, + getConnectedAdapter: async () => ({}), + checkProviderConflict: async () => ({ conflict: true, remoteFile: remoteFile('github', 5, 500) }), + loadSyncBase: async () => base, + updateProviderStatus: () => {}, notifyStateChange: () => {}, + emit: () => {}, exitBlockedState: () => {}, + uploadToProvider: async (provider: CloudProvider, _adapter: unknown, _file: SyncedFile, incoming: SyncPayload) => { + outgoing = incoming; + return { success: true, provider, action: 'upload' as const }; + }, + }; + const result = mode === 'provider' + ? await syncToProviderImpl.call(subject, 'github', local) + : (await syncAllProvidersImpl.call(subject, local, mode === 'override' ? { conflictActionOverride: 'upload-local' } : {})).get('github'); + assert.equal(result?.success, true); + assert.equal(outgoing?.hosts[0].label, 'Keep this local edit'); + assert.deepEqual(outgoing?.aiSessions?.map((entry) => entry.id), clearChats ? [] : ['old-chat', 'new-cloud-chat']); + assert.deepEqual(local.aiSessions, clearChats ? [] : undefined); + } finally { + EncryptionService.decryptPayload = originalDecrypt; + EncryptionService.encryptPayload = originalEncrypt; + } + }); + } +} + test("provider identity changes clear v1 base, v2 baseline, and remote anchor together", () => { const removed: string[] = []; const manager = { diff --git a/infrastructure/services/cloudSync/syncAllStorageMethods.ts b/infrastructure/services/cloudSync/syncAllStorageMethods.ts index e97b9756e..4a23599fc 100644 --- a/infrastructure/services/cloudSync/syncAllStorageMethods.ts +++ b/infrastructure/services/cloudSync/syncAllStorageMethods.ts @@ -7,7 +7,7 @@ import { import packageJson from '../../../package.json'; import { EncryptionService } from '../EncryptionService'; import { decryptProviderSecrets } from '../../persistence/secureFieldAdapter'; -import { mergeSyncPayloads } from '../../../domain/syncMerge'; +import { mergeAiSessionLists, mergeSyncPayloads } from '../../../domain/syncMerge'; import { cloudSyncPayloadsEqual } from '../../../domain/convergentSync'; import { stripSyncPayloadEncryptedCredentials, healPoisonedSecretsForMerge } from '../../../domain/credentials'; import { @@ -473,6 +473,27 @@ export async function syncAllProvidersImpl(this: any, const checkResults = await Promise.all(checkTasks); + if (payload.aiSessions === undefined) { + let remoteSessions: SyncPayload['aiSessions']; + for (const entry of checkResults) { + if (entry.error || !entry.check?.remoteFile) continue; + try { + assertConvergentSyncWriteCompatible(entry.check.remoteFile.meta, payload); + const remote = await EncryptionService.decryptPayload(entry.check.remoteFile, this.masterPassword); + assertSyncSecurityGeneration(this, syncSecurityGeneration); + if (remote.aiSessions !== undefined) { + remoteSessions = mergeAiSessionLists(remoteSessions, remote.aiSessions); + } + } catch (error) { + assertSyncSecurityGeneration(this, syncSecurityGeneration); + // Leave conflicting/decrypt-failed files to the existing conflict + // flow, including an explicit password-change overwrite choice. + if (!entry.check.conflict) entry.error = String(error); + } + } + if (remoteSessions !== undefined) payload = { ...payload, aiSessions: remoteSessions }; + } + // 2. Analyze Results & Handle Conflicts — merge ALL conflicting providers // // Contract: every connected provider is assumed to mirror the *same* @@ -484,7 +505,9 @@ export async function syncAllProvidersImpl(this: any, // see I-1 and `docs/`). Until then, we log a diagnostic warning when // we detect cross-provider base divergence so the issue is visible in // support logs. - const conflicts = checkResults.filter((r) => !r.error && r.check?.conflict && r.check?.remoteFile); + const conflicts = checkResults.filter((r) => !r.error && r.check?.remoteFile && ( + r.check.conflict || isPreserveDeletionsStrategy(this.state.syncStrategy) + )); // Instrumentation only — detect divergent provider bases (an // unsupported configuration). Cheap: bases are already persisted