From 0769a887961ebce409779163a2ae6de8fff882e7 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sat, 21 Nov 2026 22:54:33 +0900 Subject: [PATCH] feat(panel): add opt-in cross-client session migration for CLI, Desktop App, and Legacy IDE --- sidecars/panel/app.js | 870 +++++++++- sidecars/panel/backend/api-actions.mjs | 67 + sidecars/panel/backend/proto-wire.mjs | 129 ++ sidecars/panel/backend/session-migrator.mjs | 1427 +++++++++++++++++ sidecars/panel/index.html | 4 +- sidecars/panel/scripts/build-bundle.mjs | 1 + .../panel/shared/window-bridge-protocol.mjs | 10 + .../settings/SessionMigrationCard.js | 750 +++++++++ sidecars/panel/src/i18n/en-US.js | 35 + sidecars/panel/src/i18n/zh-CN.js | 35 + sidecars/panel/src/store/telemetryStore.js | 30 + sidecars/panel/src/styles/views-settings.css | 328 ++++ .../src/views/settings/SettingsOtherTab.js | 12 + sidecars/panel/styles.css | 328 ++++ sidecars/panel/test/backend-harness.mjs | 1 + .../test/cross-module-regressions.test.mjs | 4 +- .../panel/test/session-migration.test.mjs | 655 ++++++++ 17 files changed, 4681 insertions(+), 5 deletions(-) create mode 100644 sidecars/panel/backend/session-migrator.mjs create mode 100644 sidecars/panel/src/components/settings/SessionMigrationCard.js create mode 100644 sidecars/panel/test/session-migration.test.mjs diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index b9f63a7..e871774 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -843,6 +843,16 @@ const BRIDGE_API_ROUTE_DEFS = Object.freeze([ Object.freeze({ path: '/api/cloud-sync', method: 'POST', action: 'cloud_sync' }), Object.freeze({ path: '/api/plugin-update', method: 'POST', action: 'plugin_update' }), Object.freeze({ path: '/api/bridge/relaunch', method: 'POST', action: 'bridge_relaunch' }), + Object.freeze({ + path: '/api/session-migration/catalog', + method: 'GET', + action: 'session_migration_catalog', + }), + Object.freeze({ + path: '/api/session-migration/migrate', + method: 'POST', + action: 'session_migration_migrate', + }), ]); const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)); @@ -1809,6 +1819,41 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.exportDone': '配置 JSON 已导出', 'settings.oth.importDone': '已恢复 {count} 项偏好设置', 'settings.oth.importInvalid': '导入失败:JSON 无效或未包含可识别的偏好项', + 'settings.oth.migTitle': '跨端会话迁移', + 'settings.oth.migDesc': '按需把选定会话迁往另一端,迁移前自动备份摘要库和源库', + 'settings.oth.migRefreshBtn': '刷新列表', + 'settings.oth.migSourceLabel': '来源端', + 'settings.oth.migTargetLabel': '目标端', + 'settings.oth.migModeLabel': '迁移方式', + 'settings.oth.migModeMove': '完整迁移(推荐)', + 'settings.oth.migModeClone': '克隆副本', + 'settings.oth.migModeMoveHint': '保留原 ID 和全部历史步序明细,备份后移出源端(零重复计费)', + 'settings.oth.migModeCloneHint': '保留源会话并生成新 ID,新副本仅统计迁入后的新步骤', + 'settings.oth.migProjectLabel': '绑定目标项目', + 'settings.oth.migProjectOutside': '独立会话(无所属项目)', + 'settings.oth.migClientDesktop': '桌面端 App / 新版 IDE', + 'settings.oth.migClientCli': 'Antigravity CLI', + 'settings.oth.migClientIdeLegacy': '旧版 IDE (.db)', + 'settings.oth.migSearchPlaceholder': '按标题或工作区筛选会话…', + 'settings.oth.migSelectAll': '全选', + 'settings.oth.migClearSel': '清空', + 'settings.oth.migSelectedCount': '已选 {selected} / {total}', + 'settings.oth.migRunningTag': '运行中', + 'settings.oth.migStepsUnit': '{count} 步', + 'settings.oth.migEmpty': '当前来源端暂无可迁移会话', + 'settings.oth.migNoMatch': '没有匹配的会话', + 'settings.oth.migActionBtn': '迁移选定会话 ({count})', + 'settings.oth.migRunningBtn': '迁移中…', + 'settings.oth.migDoneDesktop': '已成功迁移 {count} 条会话到「{project}」,在桌面端按 Ctrl+R 即可在左侧看到', + 'settings.oth.migDoneCli': '已成功迁移 {count} 条会话到 CLI,可使用下方命令恢复对话', + 'settings.oth.migPartialWarn': '(另有 {failed} 条跳过或失败)', + 'settings.oth.migReloadBtn': '刷新窗口', + 'settings.oth.migCopyCmd': '复制命令', + 'settings.oth.migCopied': '已复制', + 'settings.oth.migErrLocked': '源会话文件正被原端占用,请先关闭对应终端/窗口后重试,或切换为「克隆副本」', + 'settings.oth.migErrExists': '目标端已存在同 ID 会话,无需重复移动(可切换为「克隆副本」)', + 'settings.oth.migErrRunning': '该会话正在运行中,请待空闲后再迁移', + 'settings.oth.migFailed': '迁移失败:{reason}', // Structured Live Activity Actions 'live.act.run_command': '执行命令', @@ -2571,6 +2616,41 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.exportDone': 'Preferences JSON exported', 'settings.oth.importDone': 'Restored {count} preference settings', 'settings.oth.importInvalid': 'Import failed: invalid JSON or no recognized settings', + 'settings.oth.migTitle': 'Cross-Client Session Migration', + 'settings.oth.migDesc': 'Migrate selected sessions on demand with automatic source and summary backups', + 'settings.oth.migRefreshBtn': 'Refresh', + 'settings.oth.migSourceLabel': 'Source Client', + 'settings.oth.migTargetLabel': 'Target Client', + 'settings.oth.migModeLabel': 'Migration Mode', + 'settings.oth.migModeMove': 'Full Move (Recommended)', + 'settings.oth.migModeClone': 'Clone Copy', + 'settings.oth.migModeMoveHint': 'Preserves original ID and full historical steps/details; archives source backup before moving', + 'settings.oth.migModeCloneHint': 'Keeps source intact with a fresh UUID; only counts new steps generated after cloning', + 'settings.oth.migProjectLabel': 'Target Project', + 'settings.oth.migProjectOutside': 'Standalone (No Project)', + 'settings.oth.migClientDesktop': 'Desktop App / Modern IDE', + 'settings.oth.migClientCli': 'Antigravity CLI', + 'settings.oth.migClientIdeLegacy': 'Legacy IDE (.db)', + 'settings.oth.migSearchPlaceholder': 'Filter sessions by title or workspace…', + 'settings.oth.migSelectAll': 'Select all', + 'settings.oth.migClearSel': 'Clear', + 'settings.oth.migSelectedCount': '{selected} / {total} selected', + 'settings.oth.migRunningTag': 'Running', + 'settings.oth.migStepsUnit': '{count} steps', + 'settings.oth.migEmpty': 'No migratable sessions in this source client', + 'settings.oth.migNoMatch': 'No matching sessions', + 'settings.oth.migActionBtn': 'Migrate Selected ({count})', + 'settings.oth.migRunningBtn': 'Migrating…', + 'settings.oth.migDoneDesktop': 'Migrated {count} session(s) to "{project}". Press Ctrl+R in Desktop App to refresh the sidebar', + 'settings.oth.migDoneCli': 'Migrated {count} session(s) to CLI. Use the command below to resume', + 'settings.oth.migPartialWarn': ' ({failed} skipped or failed)', + 'settings.oth.migReloadBtn': 'Reload Window', + 'settings.oth.migCopyCmd': 'Copy', + 'settings.oth.migCopied': 'Copied', + 'settings.oth.migErrLocked': 'Source database is locked by its open client. Close that terminal/window first, or switch to Clone Copy', + 'settings.oth.migErrExists': 'A session with the same ID already exists in target (switch to Clone Copy if you want a duplicate)', + 'settings.oth.migErrRunning': 'Session is currently running; wait until idle before migrating', + 'settings.oth.migFailed': 'Migration failed: {reason}', // Structured Live Activity Actions 'live.act.run_command': 'Run Command', @@ -5527,7 +5607,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView }; })(); // --- src/store/telemetryStore.js --- -const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientCliStatusLineSlots, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { +const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientCliStatusLineSlots, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -7466,6 +7546,36 @@ async function triggerCliStatusLineAction(action) { return res; } +async function fetchSessionMigrationCatalog() { + try { + return await callSidecarApi('/api/session-migration/catalog', { method: 'GET' }); + } catch { + return callSidecarApi('/api/settings', { + method: 'POST', + body: { __sessionMigrationAction: 'catalog' }, + }); + } +} + +async function executeSessionMigration(payload) { + let res; + try { + res = await callSidecarApi('/api/session-migration/migrate', { + method: 'POST', + body: payload || {}, + }); + } catch { + res = await callSidecarApi('/api/settings', { + method: 'POST', + body: { __sessionMigrationAction: 'migrate', payload: payload || {} }, + }); + } + if (res?.migratedCount > 0) { + void fetchTelemetry({ force: true }).catch(() => {}); + } + return res; +} + async function triggerPluginUpdate() { const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} }); if (res?.ok && res?.restarting) { @@ -7723,7 +7833,7 @@ function isMacHostPlatform(telemetry) { } return false; } -return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientCliStatusLineSlots, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; +return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientCliStatusLineSlots, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -20351,6 +20461,751 @@ const BridgeStatusNotice = defineComponent({ return { BridgeStatusNotice }; })(); +// --- src/components/settings/SessionMigrationCard.js --- +const { SessionMigrationCard } = (() => { +/** + * @fileoverview 跨端会话按需迁移设置卡片 (`SessionMigrationCard.js`)。 + * 仅当本机检测到 ≥2 个 Antigravity 客户端目录时展示,支持自由勾选根会话以新 UUID 无损克隆到目标端。 + */ + + +const SMIG_OUTSIDE_PROJECT_ID = 'outside-of-project'; + +async function smigCopyText(text) { + try { + if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text); + return true; + } + } catch { + // 退回受限 Webview 的隐藏文本域复制 + } + try { + if (typeof document === 'undefined' || !document.body) return false; + const area = document.createElement('textarea'); + area.value = text; + area.setAttribute('readonly', 'true'); + area.style.cssText = 'position:fixed;left:-9999px;top:-9999px;opacity:0;'; + document.body.appendChild(area); + area.select?.(); + const ok = Boolean(document.execCommand?.('copy')); + document.body.removeChild(area); + return ok; + } catch { + return false; + } +} + +function smigGetClientLabel(clientId) { + if (clientId === 'cli') return t('settings.oth.migClientCli'); + if (clientId === 'ide_legacy') return t('settings.oth.migClientIdeLegacy'); + return t('settings.oth.migClientDesktop'); +} + +function smigFormatAge(epochMs) { + const ts = Number(epochMs || 0); + if (!Number.isFinite(ts) || ts <= 0) return ''; + const diffSec = Math.max(0, Math.floor((Date.now() - ts) / 1000)); + const isEn = isEnglishLocale(); + if (diffSec < 60) return isEn ? 'just now' : '刚刚'; + const diffMin = Math.floor(diffSec / 60); + if (diffMin < 60) return isEn ? `${diffMin}m ago` : `${diffMin}分钟前`; + const diffHr = Math.floor(diffMin / 60); + if (diffHr < 24) return isEn ? `${diffHr}h ago` : `${diffHr}小时前`; + const diffDay = Math.floor(diffHr / 24); + return isEn ? `${diffDay}d ago` : `${diffDay}天前`; +} + +const SessionMigrationCard = defineComponent({ + name: 'SessionMigrationCard', + setup({ props, onCleanup }) { + const loadCatalogFn = + typeof props?.loadCatalog === 'function' ? props.loadCatalog : fetchSessionMigrationCatalog; + const runMigrateFn = + typeof props?.runMigrate === 'function' ? props.runMigrate : executeSessionMigration; + + let catalog = null; + let hasLoadedOnce = false; + let isLoading = false; + let isMigrating = false; + let destroyed = false; + let bodyMounted = false; + let sourceClient = ''; + let targetClient = ''; + let migrationMode = 'move'; + let targetProjectId = ''; + let searchQuery = ''; + const selectedIds = new Set(); + let lastResult = null; + let copiedCmdId = ''; + let copiedTimer = null; + + let titleEl = null; + let descEl = null; + let refreshBtnText = null; + let refreshBtn = null; + let sourceLabelEl = null; + let targetLabelEl = null; + let modeLabelEl = null; + let modeMoveBtn = null; + let modeCloneBtn = null; + let modeHintEl = null; + let projectLabelEl = null; + let sourceSelect = null; + let targetSelect = null; + let projectSelect = null; + let projectFieldWrap = null; + let searchInput = null; + let toggleAllBtn = null; + let selectedCountEl = null; + let listEl = null; + let migrateBtnText = null; + let migrateBtn = null; + let resultBoxEl = null; + + const rootEl = h('section', { className: 'panel smig-panel', hidden: true }); + + function ensureBodyMounted() { + if (bodyMounted) return; + bodyMounted = true; + + titleEl = h('span', { text: t('settings.oth.migTitle') }); + descEl = h('p', { className: 'smig-desc', text: t('settings.oth.migDesc') }); + refreshBtnText = h('span', { text: t('settings.oth.migRefreshBtn') }); + refreshBtn = h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm smig-refresh-btn', + onClick: () => { + void loadCatalog(true); + }, + }, + [createSvgIcon('refresh', { size: 12 }), refreshBtnText] + ); + + sourceLabelEl = h('span', { className: 'smig-field-label', text: t('settings.oth.migSourceLabel') }); + targetLabelEl = h('span', { className: 'smig-field-label', text: t('settings.oth.migTargetLabel') }); + modeLabelEl = h('span', { className: 'smig-field-label', text: t('settings.oth.migModeLabel') }); + modeMoveBtn = h('button', { + type: 'button', + className: 'smig-mode-btn is-active', + text: t('settings.oth.migModeMove'), + onClick: () => { + if (migrationMode === 'move') return; + migrationMode = 'move'; + lastResult = null; + syncModeControls(); + renderResultBox(); + }, + }); + modeCloneBtn = h('button', { + type: 'button', + className: 'smig-mode-btn', + text: t('settings.oth.migModeClone'), + onClick: () => { + if (migrationMode === 'clone') return; + migrationMode = 'clone'; + lastResult = null; + syncModeControls(); + renderResultBox(); + }, + }); + modeHintEl = h('span', { + className: 'smig-mode-hint', + text: t('settings.oth.migModeMoveHint'), + }); + projectLabelEl = h('span', { className: 'smig-field-label', text: t('settings.oth.migProjectLabel') }); + + sourceSelect = CustomSelect({ + ariaLabel: t('settings.oth.migSourceLabel'), + modelValue: '', + options: [], + onUpdateModelValue: (val) => { + if (!val || val === sourceClient) return; + sourceClient = val; + selectedIds.clear(); + lastResult = null; + ensureValidTarget(); + syncControlsAndList(); + }, + }); + + targetSelect = CustomSelect({ + ariaLabel: t('settings.oth.migTargetLabel'), + modelValue: '', + options: [], + onUpdateModelValue: (val) => { + if (!val || val === targetClient) return; + targetClient = val; + lastResult = null; + syncControlsAndList(); + }, + }); + + projectSelect = CustomSelect({ + ariaLabel: t('settings.oth.migProjectLabel'), + modelValue: '', + options: [], + className: 'smig-project-select', + onUpdateModelValue: (val) => { + targetProjectId = String(val || ''); + }, + }); + + projectFieldWrap = h('div', { className: 'smig-field' }, [ + projectLabelEl, + projectSelect.el, + ]); + + searchInput = h('input', { + type: 'text', + className: 'settings-text-input smig-search-input', + placeholder: t('settings.oth.migSearchPlaceholder'), + value: '', + }); + searchInput.addEventListener?.('input', () => { + searchQuery = String(searchInput.value || '').trim(); + renderSessionList(); + }); + + toggleAllBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm smig-toggle-all-btn', + text: t('settings.oth.migSelectAll'), + onClick: () => { + const selectable = getFilteredSessions().filter((s) => !s.isRunning); + if (selectable.length === 0) return; + const allSelected = selectable.every((s) => selectedIds.has(s.cascadeId)); + if (allSelected) { + for (const s of selectable) selectedIds.delete(s.cascadeId); + } else { + for (const s of selectable) selectedIds.add(s.cascadeId); + } + renderSessionList(); + }, + }); + + selectedCountEl = h('span', { className: 'smig-count-meta', text: '' }); + listEl = h('div', { className: 'smig-list', role: 'list' }); + + migrateBtnText = h('span', { + text: t('settings.oth.migActionBtn', { count: 0 }), + }); + migrateBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary smig-migrate-btn', + disabled: true, + onClick: () => { + void handleMigrate(); + }, + }, + [createSvgIcon('copy', { size: 12 }), migrateBtnText] + ); + + resultBoxEl = h('div', { className: 'smig-result', hidden: true }); + + const children = [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('layers', { size: 13 }), + titleEl, + ]), + refreshBtn, + ]), + descEl, + h('div', { className: 'smig-direction-grid' }, [ + h('div', { className: 'smig-field' }, [sourceLabelEl, sourceSelect.el]), + h('div', { className: 'smig-field' }, [targetLabelEl, targetSelect.el]), + ]), + h('div', { className: 'smig-field' }, [ + modeLabelEl, + h('div', { className: 'smig-mode-bar' }, [modeMoveBtn, modeCloneBtn]), + modeHintEl, + ]), + projectFieldWrap, + h('div', { className: 'smig-toolbar' }, [ + searchInput, + toggleAllBtn, + selectedCountEl, + ]), + listEl, + h('div', { className: 'smig-footer' }, [migrateBtn]), + resultBoxEl, + ]; + for (const child of children) { + rootEl.appendChild(child); + } + } + + function getDetectedClients() { + return Array.isArray(catalog?.clients) ? catalog.clients.filter((c) => c.exists) : []; + } + + function getTargetClientsFor(srcId) { + return getDetectedClients().filter((c) => c.canBeTarget && c.id !== srcId); + } + + function ensureValidSelectionDefaults() { + const detected = getDetectedClients(); + if (detected.length < 2) { + sourceClient = ''; + targetClient = ''; + return; + } + const validSources = detected.filter((c) => getTargetClientsFor(c.id).length > 0); + if (!validSources.some((c) => c.id === sourceClient)) { + const cliClient = validSources.find((c) => c.id === 'cli' && c.sessionCount > 0); + const firstWithSessions = validSources.find((c) => c.sessionCount > 0); + sourceClient = (cliClient || firstWithSessions || validSources[0])?.id || ''; + } + ensureValidTarget(); + + const projects = Array.isArray(catalog?.desktopProjects) ? catalog.desktopProjects : []; + if (!projects.some((p) => p.projectId === targetProjectId)) { + const preferred = projects.find((p) => !p.isOutsideProject) || projects[0]; + targetProjectId = preferred?.projectId || SMIG_OUTSIDE_PROJECT_ID; + } + } + + function ensureValidTarget() { + const targets = getTargetClientsFor(sourceClient); + if (!targets.some((c) => c.id === targetClient)) { + const preferDesktop = targets.find((c) => c.id === 'desktop'); + targetClient = (preferDesktop || targets[0])?.id || ''; + } + } + + function getCurrentSourceSessions() { + const list = catalog?.sessionsByClient?.[sourceClient]; + return Array.isArray(list) ? list : []; + } + + function getFilteredSessions() { + const all = getCurrentSourceSessions(); + if (!searchQuery) return all; + const needle = searchQuery.toLowerCase(); + return all.filter((item) => { + const haystack = [ + item.title, + item.workspaceName, + item.workspacePath, + item.cascadeId, + ] + .filter(Boolean) + .join(' ') + .toLowerCase(); + return haystack.includes(needle); + }); + } + + function resolveProjectDisplayLabel(projectId) { + if (!projectId || projectId === SMIG_OUTSIDE_PROJECT_ID) { + return t('settings.oth.migProjectOutside'); + } + const projects = Array.isArray(catalog?.desktopProjects) ? catalog.desktopProjects : []; + const found = projects.find((p) => p.projectId === projectId); + return found?.name || projectId.slice(0, 8); + } + + function syncModeControls() { + if (!bodyMounted) return; + patchClasses(modeMoveBtn, { 'is-active': migrationMode === 'move' }); + patchClasses(modeCloneBtn, { 'is-active': migrationMode === 'clone' }); + patchText( + modeHintEl, + migrationMode === 'clone' + ? t('settings.oth.migModeCloneHint') + : t('settings.oth.migModeMoveHint') + ); + } + + function formatMigrationError(code) { + if (code === 'source_locked') return t('settings.oth.migErrLocked'); + if (code === 'target_already_exists') return t('settings.oth.migErrExists'); + if (code === 'session_running') return t('settings.oth.migErrRunning'); + return t('settings.oth.migFailed', { reason: code || 'unknown_error' }); + } + + function syncControlsAndList() { + const visible = Boolean(catalog?.available); + patchAttr(rootEl, 'hidden', !visible); + if (!visible) { + props?.onLayoutChange?.(); + return; + } + ensureBodyMounted(); + syncModeControls(); + + const detected = getDetectedClients(); + const sourceOptions = detected + .filter((c) => getTargetClientsFor(c.id).length > 0) + .map((c) => ({ + value: c.id, + label: smigGetClientLabel(c.id), + meta: String(c.sessionCount), + })); + const targetOptions = getTargetClientsFor(sourceClient).map((c) => ({ + value: c.id, + label: smigGetClientLabel(c.id), + })); + const projectOptions = (catalog?.desktopProjects || []).map((p) => + p.isOutsideProject + ? { value: p.projectId, label: t('settings.oth.migProjectOutside') } + : { + value: p.projectId, + label: p.name || p.projectId.slice(0, 8), + meta: p.workspacePath || '', + } + ); + + sourceSelect.setProps({ + ariaLabel: t('settings.oth.migSourceLabel'), + modelValue: sourceClient, + options: sourceOptions, + }); + targetSelect.setProps({ + ariaLabel: t('settings.oth.migTargetLabel'), + modelValue: targetClient, + options: targetOptions, + }); + projectSelect.setProps({ + ariaLabel: t('settings.oth.migProjectLabel'), + modelValue: targetProjectId, + options: projectOptions, + }); + patchAttr(projectFieldWrap, 'hidden', targetClient !== 'desktop'); + + renderSessionList(); + renderResultBox(); + props?.onLayoutChange?.(); + } + + function renderSessionList() { + const all = getCurrentSourceSessions(); + const filtered = getFilteredSessions(); + + // 清理已不在当前来源中的选中 ID + const validSet = new Set(all.filter((s) => !s.isRunning).map((s) => s.cascadeId)); + for (const id of [...selectedIds]) { + if (!validSet.has(id)) selectedIds.delete(id); + } + + const selectableFiltered = filtered.filter((s) => !s.isRunning); + const allSelected = + selectableFiltered.length > 0 && + selectableFiltered.every((s) => selectedIds.has(s.cascadeId)); + patchText( + toggleAllBtn, + allSelected ? t('settings.oth.migClearSel') : t('settings.oth.migSelectAll') + ); + patchAttr(toggleAllBtn, 'disabled', selectableFiltered.length === 0 || isMigrating); + patchText( + selectedCountEl, + t('settings.oth.migSelectedCount', { + selected: selectedIds.size, + total: filtered.length, + }) + ); + + while (listEl.firstChild) { + listEl.removeChild(listEl.firstChild); + } + + if (all.length === 0) { + listEl.appendChild(h('div', { className: 'smig-empty', text: t('settings.oth.migEmpty') })); + } else if (filtered.length === 0) { + listEl.appendChild( + h('div', { className: 'smig-empty', text: t('settings.oth.migNoMatch') }) + ); + } else { + for (const item of filtered) { + const checked = selectedIds.has(item.cascadeId); + const checkboxEl = h('input', { + type: 'checkbox', + className: 'smig-checkbox', + checked, + disabled: Boolean(item.isRunning || isMigrating), + }); + checkboxEl.checked = checked; + const toggleItem = () => { + if (item.isRunning || isMigrating) return; + if (selectedIds.has(item.cascadeId)) { + selectedIds.delete(item.cascadeId); + } else { + selectedIds.add(item.cascadeId); + } + renderSessionList(); + }; + checkboxEl.addEventListener?.('change', toggleItem); + + const metaParts = [t('settings.oth.migStepsUnit', { count: item.stepCount })]; + const age = smigFormatAge(item.lastModifiedMs); + if (age) metaParts.push(age); + + const subChildren = []; + if (item.workspacePath || item.workspaceName) { + subChildren.push( + h('span', { + className: 'smig-item-ws', + text: item.workspacePath || item.workspaceName, + title: item.workspacePath || item.workspaceName, + }) + ); + } + if (item.isRunning) { + subChildren.push( + h('span', { + className: 'smig-item-running', + text: t('settings.oth.migRunningTag'), + }) + ); + } + + const rowEl = h( + 'div', + { + className: `smig-item${checked ? ' is-selected' : ''}${item.isRunning ? ' is-running' : ''}`, + role: 'listitem', + onClick: (ev) => { + if (ev?.target === checkboxEl) return; + toggleItem(); + }, + }, + [ + checkboxEl, + h('div', { className: 'smig-item-body' }, [ + h('div', { className: 'smig-item-top' }, [ + h('span', { + className: 'smig-item-title', + text: item.title || item.cascadeId.slice(0, 8), + title: item.title || item.cascadeId, + }), + h('span', { className: 'smig-item-meta', text: metaParts.join(' · ') }), + ]), + ...(subChildren.length > 0 + ? [h('div', { className: 'smig-item-sub' }, subChildren)] + : []), + ]), + ] + ); + listEl.appendChild(rowEl); + } + } + + patchAttr(migrateBtn, 'disabled', isMigrating || selectedIds.size === 0 || !targetClient); + patchText( + migrateBtnText, + isMigrating + ? t('settings.oth.migRunningBtn') + : t('settings.oth.migActionBtn', { count: selectedIds.size }) + ); + } + + function renderResultBox() { + if (!lastResult) { + patchAttr(resultBoxEl, 'hidden', true); + return; + } + patchAttr(resultBoxEl, 'hidden', false); + patchClasses(resultBoxEl, { + 'is-ok': Boolean(lastResult.ok), + 'is-err': !lastResult.ok, + }); + + while (resultBoxEl.firstChild) { + resultBoxEl.removeChild(resultBoxEl.firstChild); + } + + if (!lastResult.ok) { + resultBoxEl.appendChild( + h('div', { + className: 'smig-result-msg', + text: formatMigrationError(lastResult.error), + }) + ); + return; + } + + const partialSuffix = + lastResult.failedCount > 0 + ? t('settings.oth.migPartialWarn', { failed: lastResult.failedCount }) + : ''; + const baseMsg = + lastResult.targetClient === 'cli' + ? t('settings.oth.migDoneCli', { count: lastResult.migratedCount }) + : t('settings.oth.migDoneDesktop', { + count: lastResult.migratedCount, + project: resolveProjectDisplayLabel(lastResult.targetProjectId), + }); + + resultBoxEl.appendChild( + h('div', { className: 'smig-result-msg', text: `${baseMsg}${partialSuffix}` }) + ); + + if (lastResult.targetClient === 'desktop' && isWindowOverlayMode()) { + resultBoxEl.appendChild( + h('div', { className: 'smig-result-actions' }, [ + h( + 'button', + { + type: 'button', + className: 'btn-secondary smig-result-btn', + onClick: () => { + if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') { + window.location.reload(); + } + }, + }, + [createSvgIcon('refresh', { size: 11 }), h('span', { text: t('settings.oth.migReloadBtn') })] + ), + ]) + ); + } + + if (lastResult.targetClient === 'cli') { + const okItems = (lastResult.results || []).filter((r) => r.ok && r.resumeCommand); + if (okItems.length > 0) { + const cmdWrap = h('div', { className: 'smig-cmd-list' }); + for (const item of okItems.slice(0, 6)) { + const isCopied = copiedCmdId === item.newCascadeId; + const copyBtn = h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm smig-cmd-copy', + text: isCopied ? t('settings.oth.migCopied') : t('settings.oth.migCopyCmd'), + onClick: async () => { + const ok = await smigCopyText(item.resumeCommand); + if (!ok || destroyed) return; + copiedCmdId = item.newCascadeId; + renderResultBox(); + if (copiedTimer) clearTimeout(copiedTimer); + copiedTimer = setTimeout(() => { + copiedTimer = null; + if (!destroyed && copiedCmdId === item.newCascadeId) { + copiedCmdId = ''; + renderResultBox(); + } + }, 2000); + }, + } + ); + cmdWrap.appendChild( + h('div', { className: 'smig-cmd-row' }, [ + h('code', { className: 'smig-cmd-code', text: item.resumeCommand }), + copyBtn, + ]) + ); + } + resultBoxEl.appendChild(cmdWrap); + } + } + } + + async function loadCatalog(force = false) { + if (isLoading || (hasLoadedOnce && !force)) return; + isLoading = true; + if (refreshBtn) patchAttr(refreshBtn, 'disabled', true); + try { + const res = await loadCatalogFn(); + if (destroyed) return; + hasLoadedOnce = true; + if (res && typeof res === 'object') { + catalog = res; + ensureValidSelectionDefaults(); + syncControlsAndList(); + } + } catch { + // 本地目录或 API 暂不可用时静默隐藏卡片,避免干扰其他设置项 + if (!destroyed && !catalog) { + patchAttr(rootEl, 'hidden', true); + } + } finally { + isLoading = false; + if (refreshBtn) patchAttr(refreshBtn, 'disabled', false); + } + } + + async function handleMigrate() { + if (isMigrating || selectedIds.size === 0 || !sourceClient || !targetClient) return; + isMigrating = true; + lastResult = null; + renderSessionList(); + renderResultBox(); + try { + const payload = { + sourceClient, + targetClient, + mode: migrationMode, + cascadeIds: [...selectedIds], + ...(targetClient === 'desktop' ? { targetProjectId } : {}), + }; + const res = await runMigrateFn(payload); + if (destroyed) return; + lastResult = res || { ok: false, error: 'empty_response' }; + if (res?.ok) { + selectedIds.clear(); + void loadCatalog(true); + } + } catch (err) { + if (!destroyed) { + lastResult = { ok: false, error: err?.message || 'request_failed' }; + } + } finally { + isMigrating = false; + if (!destroyed) { + renderSessionList(); + renderResultBox(); + props?.onLayoutChange?.(); + } + } + } + + function refreshLabels() { + if (!bodyMounted) return; + patchText(titleEl, t('settings.oth.migTitle')); + patchText(descEl, t('settings.oth.migDesc')); + patchText(refreshBtnText, t('settings.oth.migRefreshBtn')); + patchText(sourceLabelEl, t('settings.oth.migSourceLabel')); + patchText(targetLabelEl, t('settings.oth.migTargetLabel')); + patchText(modeLabelEl, t('settings.oth.migModeLabel')); + patchText(modeMoveBtn, t('settings.oth.migModeMove')); + patchText(modeCloneBtn, t('settings.oth.migModeClone')); + syncModeControls(); + patchText(projectLabelEl, t('settings.oth.migProjectLabel')); + patchAttr(searchInput, 'placeholder', t('settings.oth.migSearchPlaceholder')); + if (catalog?.available) { + syncControlsAndList(); + } + } + + onCleanup(() => { + destroyed = true; + if (copiedTimer) { + clearTimeout(copiedTimer); + copiedTimer = null; + } + sourceSelect?.destroy?.(); + targetSelect?.destroy?.(); + projectSelect?.destroy?.(); + }); + + return { + el: rootEl, + refs: { + ensureLoaded: () => loadCatalog(false), + reload: () => loadCatalog(true), + refreshLabels, + }, + }; + }, +}); +return { SessionMigrationCard }; +})(); + // --- src/views/settings/SettingsGeneralTab.js --- const { SettingsGeneralTab } = (() => { /** @@ -22935,10 +23790,17 @@ const SettingsOtherTab = defineComponent({ ]), ]); + const sessionMigrationCard = SessionMigrationCard({ + onLayoutChange: () => { + getProps()?.onLayoutChange?.(); + }, + }); + const rootEl = h('div', { className: 'settings-tab-stack' }, [ modelPanel, baselinePanel, maintPanel, + sessionMigrationCard.el, ]); function renderSettings( @@ -22969,6 +23831,7 @@ const SettingsOtherTab = defineComponent({ options: getOrchestratorIdDisplayOptions(), }); renderContextWindows(); + void sessionMigrationCard.refs.ensureLoaded(); } function refreshLabels() { @@ -23005,6 +23868,7 @@ const SettingsOtherTab = defineComponent({ modelValue: draftOrchestratorIdMode, options: getOrchestratorIdDisplayOptions(), }); + sessionMigrationCard.refs.refreshLabels(); } onCleanup(() => { @@ -23016,6 +23880,7 @@ const SettingsOtherTab = defineComponent({ ctxBridgeNotice.destroy(); ctxModelSelect.destroy(); ctxWindowSelect.destroy(); + sessionMigrationCard.destroy(); }); return { @@ -23026,6 +23891,7 @@ const SettingsOtherTab = defineComponent({ ctxBridgeNotice, ctxModelSelect, ctxWindowSelect, + sessionMigrationCard, rebuildCacheBtn, resetAllBtn, exportJsonBtn, diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 68e4e62..cdf6640 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -63,6 +63,7 @@ import { resolveDevToolsPortCandidates, startDefaultWindowBridge, } from './window-bridge.mjs'; +import { getSessionMigrationCatalog, migrateSessions } from './session-migrator.mjs'; import { ensureCliStatusLineConfigured, getCliStatusLineRuntimeStatus, @@ -678,6 +679,62 @@ export function executeCliStatusLineAction(rawAction) { }; } +export function executeSessionMigrationCatalogAction(data = undefined, opts = {}) { + const epCtx = resolveActionEndpoint(data, opts); + if (!epCtx.ok) { + return buildEndpointErrorResponse(epCtx); + } + if (epCtx.isRemote) { + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ + available: false, + sqliteSupported: false, + clients: [], + sessionsByClient: {}, + desktopProjects: [], + error: 'unsupported_remote', + }), + }; + } + const catalog = getSessionMigrationCatalog(); + return { + status: 200, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify(catalog), + }; +} + +export function executeSessionMigrationMigrateAction(data = undefined, opts = {}) { + const epCtx = resolveActionEndpoint(data, opts); + if (!epCtx.ok) { + return buildEndpointErrorResponse(epCtx); + } + if (epCtx.isRemote) { + return { + status: 400, + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify({ ok: false, error: 'unsupported_remote', results: [] }), + }; + } + const cleanData = stripEndpointField(data); + const result = migrateSessions(cleanData); + if (result.migratedCount > 0) { + clearScannerRuntimeMemos(LOCAL_ENDPOINT_ID); + clearTelemetryBuilderMemo(LOCAL_ENDPOINT_ID); + } + return { + status: Number(result.status || (result.ok ? 200 : 400)), + contentType: 'application/json', + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify(result), + }; +} + const BRIDGE_ROUTE_LOOKUP = new Map( BRIDGE_API_ROUTE_DEFS.map((r) => [`${r.method}:${r.path}`, r.action]) ); @@ -694,6 +751,12 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un if (isPlainObject(data) && typeof data.__cliStatusLineAction === 'string') { return executeCliStatusLineAction(data.__cliStatusLineAction); } + if (isPlainObject(data) && data.__sessionMigrationAction === 'catalog') { + return executeSessionMigrationCatalogAction(data, opts); + } + if (isPlainObject(data) && data.__sessionMigrationAction === 'migrate') { + return executeSessionMigrationMigrateAction(data.payload || data, opts); + } return executeSettingsAction(data); case 'accounts_get': return executeAccountCredentialAction(undefined, opts); @@ -711,6 +774,10 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un return executePluginUpdateAction(); case 'bridge_relaunch': return executeBridgeRelaunchAction(); + case 'session_migration_catalog': + return executeSessionMigrationCatalogAction(data, opts); + case 'session_migration_migrate': + return executeSessionMigrationMigrateAction(data, opts); default: return { status: 404, diff --git a/sidecars/panel/backend/proto-wire.mjs b/sidecars/panel/backend/proto-wire.mjs index ca6c225..be2288f 100644 --- a/sidecars/panel/backend/proto-wire.mjs +++ b/sidecars/panel/backend/proto-wire.mjs @@ -208,3 +208,132 @@ export function decodeProtoMapStringEntry(buf, state, end) { state.off = end; return [key, val]; } + +// --------------------------------------------------------------------------- +// 无损 Protobuf Wire 编码及按字段号定向修补原语(保留所有未知/未触碰字段原字节) +// --------------------------------------------------------------------------- + +export function encodeProtoVarint(value) { + let n = typeof value === 'bigint' ? value : BigInt(Math.trunc(Number(value) || 0)); + if (n < 0n) n = BigInt.asUintN(64, n); + const bytes = []; + do { + let b = Number(n & 0x7fn); + n >>= 7n; + if (n > 0n) b |= 0x80; + bytes.push(b); + } while (n > 0n); + return Buffer.from(bytes); +} + +export function encodeProtoTag(fieldNumber, wireType) { + return encodeProtoVarint((BigInt(fieldNumber) << 3n) | BigInt(wireType & 7)); +} + +export function encodeProtoVarintField(fieldNumber, value) { + return Buffer.concat([encodeProtoTag(fieldNumber, 0), encodeProtoVarint(value)]); +} + +export function encodeProtoBytesField(fieldNumber, payload) { + const buf = payload instanceof Buffer ? payload : Buffer.from(payload || []); + return Buffer.concat([encodeProtoTag(fieldNumber, 2), encodeProtoVarint(buf.length), buf]); +} + +export function encodeProtoStringField(fieldNumber, text) { + return encodeProtoBytesField(fieldNumber, Buffer.from(String(text ?? ''), 'utf8')); +} + +export function encodeProtoTimestamp(epochMs) { + const ms = Number(epochMs); + if (!Number.isFinite(ms) || ms <= 0) return Buffer.alloc(0); + const seconds = Math.floor(ms / 1000); + const nanos = Math.floor((ms - seconds * 1000) * 1_000_000); + const parts = [encodeProtoVarintField(1, seconds)]; + if (nanos > 0) { + parts.push(encodeProtoVarintField(2, nanos)); + } + return Buffer.concat(parts); +} + +/** + * 将原始 Protobuf 二进制消息拆分为顶层原始字段切片,确保未知字段零损透传。 + * + * @param {Uint8Array | Buffer} raw + * @returns {Array<{ fn: number, wt: number, raw: Buffer, payload: Buffer }>} + */ +export function splitProtoRawFields(raw) { + const u8 = toUint8Array(raw); + if (!u8 || u8.byteLength === 0) return []; + const buf = Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength); + const state = { off: 0 }; + const limit = buf.length; + const fields = []; + while (state.off < limit) { + const start = state.off; + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 0) break; + let payloadStart = state.off; + let payloadEnd = state.off; + if (wt === 0) { + readProtoVarint(buf, state, limit); + payloadEnd = state.off; + } else if (wt === 1) { + state.off = Math.min(limit, state.off + 8); + payloadEnd = state.off; + } else if (wt === 5) { + state.off = Math.min(limit, state.off + 4); + payloadEnd = state.off; + } else if (wt === 2) { + const end = readSubEnd(buf, state, limit); + payloadStart = state.off; + state.off = end; + payloadEnd = end; + } else if (wt === 3) { + skipProtoField(buf, state, 3, limit); + payloadEnd = state.off; + } else { + break; + } + fields.push({ + fn, + wt, + raw: buf.subarray(start, state.off), + payload: buf.subarray(payloadStart, payloadEnd), + }); + } + return fields; +} + +/** + * 按字段号定向替换、删除(传 `null`)或追加 Protobuf 顶层字段,其余未知字段原字节无损保留。 + * + * @param {Uint8Array | Buffer} raw + * @param {Map} replacements + * @returns {Buffer} + */ +export function patchProtoMessageFields(raw, replacements) { + const fields = splitProtoRawFields(raw); + const handled = new Set(); + const out = []; + for (const field of fields) { + if (replacements.has(field.fn)) { + if (!handled.has(field.fn)) { + handled.add(field.fn); + const rep = replacements.get(field.fn); + if (rep && rep.length > 0) { + out.push(Buffer.from(rep)); + } + } + } else { + out.push(field.raw); + } + } + for (const [fn, rep] of replacements.entries()) { + if (!handled.has(fn) && rep && rep.length > 0) { + out.push(Buffer.from(rep)); + } + } + return Buffer.concat(out); +} diff --git a/sidecars/panel/backend/session-migrator.mjs b/sidecars/panel/backend/session-migrator.mjs new file mode 100644 index 0000000..b538ecc --- /dev/null +++ b/sidecars/panel/backend/session-migrator.mjs @@ -0,0 +1,1427 @@ +/** + * @fileoverview 跨端会话按需迁移器 (`session-migrator.mjs`)。 + * + * 支持两种显式模式: + * 1. `move`(默认「完整迁移」):保留原 `cascade_id` 和 `trajectory_id`,先将源 `.db` 一致性快照备份归档, + * 再安全移入目标端并清理源端 `.db` 及摘要行——迁入后完整保留全部历史步序(#1/#3/#5…)、上下文和调用明细, + * 且全局仅存一份天然零重复计费;若源 `.db` 正被原客户端锁住(`EBUSY`/`EPERM`),安全回滚并提示关闭原端; + * 2. `clone`(可选「克隆副本」):生成全新 UUID,源端 100% 保持不动;保留历史步骤原有的 `originCascadeId`, + * 由 `cli-sqlite-reader.mjs` 自动跳过克隆历史步,仅统计迁入后新产生的步骤(避免跨端双倍计费)。 + * + * 支持方向:`CLI -> App / IDE`、`App / IDE -> CLI` 以及 `旧版 IDE (.db) -> App / CLI`。 + */ + +import { randomUUID } from 'node:crypto'; +import { + cpSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { basename, join } from 'node:path'; +import { homedir } from 'node:os'; +import { parseIsoMs } from '../trajectory-metrics.mjs'; +import { DATA_DIR } from './config.mjs'; +import { + getNodeSqliteDatabaseSync, + hasBuiltinNodeSqlite, + isSqliteBusyError, + normalizeSqliteIsoTime, + withReadOnlySqliteDb, +} from './sqlite-client.mjs'; +import { + encodeProtoBytesField, + encodeProtoStringField, + encodeProtoTimestamp, + encodeProtoVarintField, + patchProtoMessageFields, + readProtoString, + readProtoVarint, + readSubEnd, + skipProtoField, + splitProtoRawFields, + toUint8Array, +} from './proto-wire.mjs'; +import { parseAnnotationPbtxtTitle } from './cli-sqlite-reader.mjs'; + +const MIGRATOR_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const MIGRATOR_MAX_SESSIONS_PER_CLIENT = 200; +const MIGRATOR_MAX_BATCH_SIZE = 50; +const MIGRATOR_MAX_BACKUPS = 5; +const MIGRATOR_OUTSIDE_PROJECT_ID = 'outside-of-project'; +const MIGRATOR_CLI_PROJECT_ID = 'default-cli-project'; + +const MIGRATOR_CLIENT_DEFS = Object.freeze([ + Object.freeze({ + id: 'desktop', + dirName: 'antigravity', + appDataDir: 'antigravity', + trajectorySourceNum: 1, + allowTarget: true, + }), + Object.freeze({ + id: 'cli', + dirName: 'antigravity-cli', + appDataDir: 'antigravity-cli', + trajectorySourceNum: 17, + allowTarget: true, + }), + Object.freeze({ + id: 'ide_legacy', + dirName: 'antigravity-ide', + appDataDir: 'antigravity-ide', + trajectorySourceNum: 1, + allowTarget: false, + }), +]); + +function migratorResolveGeminiDir(explicitGeminiDir) { + const override = String(explicitGeminiDir || '').trim(); + if (override) return override; + const envDir = String(process.env.ANTIGRAVITY_GEMINI_DIR || '').trim(); + return envDir || join(homedir(), '.gemini'); +} + +function migratorResolveBackupRoot(explicitBackupDir) { + const override = String(explicitBackupDir || '').trim(); + if (override) return override; + return join(DATA_DIR, 'session-migration-backups'); +} + +function migratorGetClientDef(clientId) { + const id = String(clientId || '').trim().toLowerCase(); + return MIGRATOR_CLIENT_DEFS.find((item) => item.id === id) || null; +} + +function migratorFormatSqliteUtcTime(epochMs) { + const date = new Date(Number.isFinite(Number(epochMs)) && Number(epochMs) > 0 ? Number(epochMs) : Date.now()); + const pad = (n, w = 2) => String(n).padStart(w, '0'); + return ( + `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ` + + `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}.` + + `${pad(date.getUTCMilliseconds(), 3)}0000+00:00` + ); +} + +/** + * 将 `file://` URI 或本地路径规整为未转义冒号的原始 `file:///` URI(供 Workspace `fn 1`/`fn 2` 及 CLI 摘要使用)。 + * + * @param {string} rawInput + * @returns {string} + */ +export function migratorToRawFileUri(rawInput) { + const raw = String(rawInput || '').trim(); + if (!raw) return ''; + if (/^file:\/\//i.test(raw)) { + let body = raw.replace(/^file:\/\/\/?/i, ''); + try { + body = decodeURIComponent(body); + } catch { + body = body.replace(/%3A/gi, ':'); + } + body = body.replace(/\\/g, '/').replace(/^\/+/, ''); + if (/^[a-zA-Z]:/.test(body)) { + return `file:///${body}`; + } + return `file:///${body}`; + } + const normalized = raw.replace(/\\/g, '/'); + if (/^[a-zA-Z]:\//.test(normalized)) { + return `file:///${normalized}`; + } + if (normalized.startsWith('/')) { + return `file://${normalized}`; + } + return `file:///${normalized}`; +} + +/** + * 将 `file://` URI 或本地路径规整为 Antigravity 桌面端标准编码格式(Windows 盘符小写 + `%3A`)。 + * + * @param {string} rawInput + * @returns {string} + */ +export function migratorToDesktopEncodedUri(rawInput) { + const raw = String(rawInput || '').trim(); + if (!raw) return ''; + if (/^file:\/\/\/[a-z]%3A\//i.test(raw)) { + return raw.replace(/^file:\/\/\/([a-zA-Z])%3A\//i, (_, d) => `file:///${d.toLowerCase()}%3A/`); + } + const unencoded = migratorToRawFileUri(raw); + const body = unencoded.replace(/^file:\/\/\//i, ''); + const winMatch = body.match(/^([a-zA-Z]):(.*)$/); + if (winMatch) { + const drive = winMatch[1].toLowerCase(); + const rest = winMatch[2] + .split('/') + .map((seg) => (seg ? encodeURIComponent(seg) : '')) + .join('/'); + return `file:///${drive}%3A${rest}`; + } + const encodedPath = body + .split('/') + .map((seg) => (seg ? encodeURIComponent(seg) : '')) + .join('/'); + return `file:///${encodedPath}`; +} + +/** + * 从 `file:///` URI 提取可读路径和末级项目显示名。 + * + * @param {string} rawUri + * @returns {{ name: string, displayPath: string }} + */ +export function migratorParseWorkspaceLabel(rawUri) { + const raw = String(rawUri || '').trim(); + if (!raw) return { name: '', displayPath: '' }; + let decoded = raw.replace(/^file:\/\/\/?/i, ''); + try { + decoded = decodeURIComponent(decoded); + } catch { + decoded = decoded.replace(/%3A/gi, ':'); + } + decoded = decoded.replace(/\\/g, '/').replace(/\/+$/, ''); + if (!decoded) return { name: '', displayPath: '' }; + const parts = decoded.split('/').filter(Boolean); + const name = parts.length > 0 ? parts[parts.length - 1] : decoded; + return { name, displayPath: decoded }; +} + +function migratorParseWorkspaceUrisColumn(rawVal) { + const str = String(rawVal || '').trim(); + if (!str) return []; + if (str.startsWith('[')) { + try { + const parsed = JSON.parse(str); + if (Array.isArray(parsed)) { + return parsed.map((item) => String(item || '').trim()).filter(Boolean); + } + } catch { + // 退回单值解析 + } + } + return [str]; +} + +function migratorEscapePbtxtString(text) { + return String(text || '') + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/\r/g, '\\r') + .replace(/\n/g, '\\n'); +} + +function migratorCleanPromptTitle(rawText, maxChars = 72) { + const cleaned = String(rawText || '') + .replace(/[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '') + .replace(/[\s\S]*$/i, '') + .replace(/[\s\S]*$/i, ''); + const reqMatches = [...cleaned.matchAll(/([\s\S]*?)<\/USER_REQUEST>/gi)]; + const target = reqMatches.length > 0 ? reqMatches[reqMatches.length - 1][1] : cleaned; + const singleLine = target.replace(/\s+/g, ' ').trim(); + if (!singleLine) return ''; + return singleLine.length <= maxChars ? singleLine : `${singleLine.slice(0, maxChars - 1).trimEnd()}…`; +} + +function migratorDecodeUserPromptFromStepPayload(rawBlob) { + const buf = toUint8Array(rawBlob); + if (!buf || buf.byteLength === 0) return ''; + const state = { off: 0 }; + const end = buf.byteLength; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 19 && wt === 2) { + const uiEnd = readSubEnd(buf, state, end); + let query = ''; + let userResponse = ''; + const items = []; + while (state.off < uiEnd) { + const uTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, uiEnd))); + const uFn = uTag >>> 3; + const uWt = uTag & 7; + if (uFn === 1 && uWt === 2) { + query = readProtoString(buf, state, uiEnd); + } else if (uFn === 2 && uWt === 2) { + userResponse = readProtoString(buf, state, uiEnd); + } else if (uFn === 3 && uWt === 2) { + const itEnd = readSubEnd(buf, state, uiEnd); + while (state.off < itEnd) { + const iTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, itEnd))); + if ((iTag >>> 3) === 1 && (iTag & 7) === 2) { + const txt = readProtoString(buf, state, itEnd); + if (txt) items.push(txt); + } else { + skipProtoField(buf, state, iTag & 7, itEnd); + } + } + state.off = itEnd; + } else { + skipProtoField(buf, state, uWt, uiEnd); + } + } + state.off = uiEnd; + const merged = userResponse || items.join(' ') || query; + if (merged) return migratorCleanPromptTitle(merged); + } else { + skipProtoField(buf, state, wt, end); + } + } + return ''; +} + +function migratorDecodeMetaBlobLight(rawBlob) { + const fields = splitProtoRawFields(rawBlob); + let workspaceUri = ''; + let projectId = ''; + let parentConversationId = ''; + let createdMs = 0; + for (const field of fields) { + if (field.fn === 7 && field.wt === 2 && !workspaceUri) { + workspaceUri = field.payload.toString('utf8').trim(); + } else if (field.fn === 1 && field.wt === 2 && !workspaceUri) { + const wsFields = splitProtoRawFields(field.payload); + const fn1 = wsFields.find((item) => item.fn === 1 && item.wt === 2); + if (fn1) workspaceUri = fn1.payload.toString('utf8').trim(); + } else if (field.fn === 18 && field.wt === 2) { + projectId = field.payload.toString('utf8').trim(); + } else if (field.fn === 9 && field.wt === 2) { + parentConversationId = field.payload.toString('utf8').trim().toLowerCase(); + } else if (field.fn === 2 && field.wt === 2 && !createdMs) { + const tsFields = splitProtoRawFields(field.payload); + const secField = tsFields.find((item) => item.fn === 1 && item.wt === 0); + if (secField) { + const st = { off: 0 }; + const sec = Number(BigInt.asIntN(64, readProtoVarint(secField.payload, st, secField.payload.length))); + if (Number.isFinite(sec) && sec > 0) createdMs = sec * 1000; + } + } + } + return { workspaceUri, projectId, parentConversationId, createdMs }; +} + +function migratorInspectConversationDbLight(dbPath, { needPromptTitle = false } = {}) { + try { + return withReadOnlySqliteDb(dbPath, (db) => { + let trajectoryType = 0; + let sourceNum = 0; + try { + const metaRow = db + .prepare('SELECT trajectory_type, source FROM trajectory_meta LIMIT 1') + .get(); + trajectoryType = Number(metaRow?.trajectory_type || 0); + sourceNum = Number(metaRow?.source || 0); + } catch { + // 兼容最小表结构 + } + + let stepCount = 0; + let lastUserInputStepIndex = -1; + let firstPromptTitle = ''; + try { + const cntRow = db.prepare('SELECT count(*) AS cnt FROM steps').get(); + stepCount = Math.max(0, Number(cntRow?.cnt || 0)); + const lastUiRow = db + .prepare('SELECT max(idx) AS max_idx FROM steps WHERE step_type = 14') + .get(); + if (lastUiRow && lastUiRow.max_idx != null) { + lastUserInputStepIndex = Number(lastUiRow.max_idx); + } + if (needPromptTitle && stepCount > 0) { + const uiRows = db + .prepare('SELECT step_payload FROM steps WHERE step_type = 14 ORDER BY idx ASC LIMIT 3') + .all(); + for (const row of uiRows || []) { + if (!row?.step_payload) continue; + const extracted = migratorDecodeUserPromptFromStepPayload(row.step_payload); + if (extracted) { + firstPromptTitle = extracted; + break; + } + } + } + } catch { + // 忽略步骤读取异常 + } + + let metaBlobInfo = { workspaceUri: '', projectId: '', parentConversationId: '', createdMs: 0 }; + try { + const blobRow = db + .prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main' LIMIT 1") + .get(); + if (blobRow?.data) { + metaBlobInfo = migratorDecodeMetaBlobLight(blobRow.data); + } + } catch { + // 忽略 blob 缺失 + } + + return { + trajectoryType, + sourceNum, + stepCount, + lastUserInputStepIndex, + firstPromptTitle, + ...metaBlobInfo, + }; + }); + } catch { + return null; + } +} + +function migratorReadClientSummaryMap(clientRoot, expectedAppDataDir) { + const sumDbPath = join(clientRoot, 'conversation_summaries.db'); + const map = new Map(); + if (!existsSync(sumDbPath)) { + return { hasSummaryDb: false, map }; + } + try { + withReadOnlySqliteDb(sumDbPath, (db) => { + let rows = []; + try { + rows = db + .prepare( + `SELECT + conversation_id, + title, + preview, + step_count, + last_modified_time, + workspace_uris, + status, + source, + project_id, + agent_name, + parent_conversation_id, + nesting_depth, + not_fully_idle, + killed, + last_user_input_time, + last_user_input_step_index, + app_data_dir, + raw_summary + FROM conversation_summaries` + ) + .all(); + } catch { + rows = db + .prepare( + `SELECT + conversation_id, + title, + step_count, + last_modified_time, + workspace_uris, + status, + project_id, + parent_conversation_id, + nesting_depth, + not_fully_idle, + killed, + app_data_dir + FROM conversation_summaries` + ) + .all(); + } + for (const row of rows || []) { + const cid = String(row?.conversation_id || '').trim().toLowerCase(); + if (!cid || !MIGRATOR_UUID_RE.test(cid)) continue; + const rowDir = String(row?.app_data_dir || '').trim().toLowerCase(); + const isNative = !rowDir || rowDir === expectedAppDataDir; + const prev = map.get(cid); + if (!prev || (isNative && !prev._isNative)) { + map.set(cid, { ...row, _isNative: isNative }); + } + } + }); + return { hasSummaryDb: true, map }; + } catch { + return { hasSummaryDb: true, map }; + } +} + +function migratorExtractDesktopProjects(summaryMap) { + const byProjectId = new Map(); + for (const row of summaryMap.values()) { + const source = String(row?.source || '').trim(); + const projectId = String(row?.project_id || '').trim(); + if (source === 'CORTEX_TRAJECTORY_SOURCE_CLI') continue; + if (!projectId || projectId === MIGRATOR_CLI_PROJECT_ID || projectId === MIGRATOR_OUTSIDE_PROJECT_ID) { + continue; + } + const uris = migratorParseWorkspaceUrisColumn(row?.workspace_uris); + const primaryUri = uris[0] || ''; + const lastModifiedMs = parseIsoMs(normalizeSqliteIsoTime(row?.last_modified_time)) || 0; + const prev = byProjectId.get(projectId); + if (!prev) { + const { name, displayPath } = migratorParseWorkspaceLabel(primaryUri); + byProjectId.set(projectId, { + projectId, + name: name || projectId.slice(0, 8), + workspaceUri: primaryUri, + workspacePath: displayPath, + conversationCount: 1, + lastModifiedMs, + }); + } else { + prev.conversationCount += 1; + if (lastModifiedMs > prev.lastModifiedMs) { + prev.lastModifiedMs = lastModifiedMs; + if (primaryUri) { + const { name, displayPath } = migratorParseWorkspaceLabel(primaryUri); + prev.workspaceUri = primaryUri; + prev.workspacePath = displayPath; + if (name) prev.name = name; + } + } + } + } + const sorted = [...byProjectId.values()].sort( + (a, b) => b.lastModifiedMs - a.lastModifiedMs || b.conversationCount - a.conversationCount + ); + sorted.push({ + projectId: MIGRATOR_OUTSIDE_PROJECT_ID, + name: '', + workspaceUri: '', + workspacePath: '', + conversationCount: 0, + lastModifiedMs: 0, + isOutsideProject: true, + }); + return sorted; +} + +function migratorReadAnnotationTitle(clientRoot, cid) { + const annPath = join(clientRoot, 'annotations', `${cid}.pbtxt`); + if (!existsSync(annPath)) return ''; + try { + return parseAnnotationPbtxtTitle(readFileSync(annPath, 'utf8')); + } catch { + return ''; + } +} + +function migratorComputeDbFileInfo(convDir, cid) { + const dbPath = join(convDir, `${cid}.db`); + if (!existsSync(dbPath)) return null; + try { + const dbStat = statSync(dbPath); + let sizeBytes = Number(dbStat.size || 0); + let mtimeMs = Number(dbStat.mtimeMs || 0); + const walPath = `${dbPath}-wal`; + if (existsSync(walPath)) { + try { + const walStat = statSync(walPath); + sizeBytes += Number(walStat.size || 0); + mtimeMs = Math.max(mtimeMs, Number(walStat.mtimeMs || 0)); + } catch { + // 忽略 WAL stat 异常 + } + } + return { dbPath, sizeBytes, mtimeMs }; + } catch { + return null; + } +} + +function migratorListClientSessions(clientDef, clientRoot, summaryMap, runningSet) { + const convDir = join(clientRoot, 'conversations'); + if (!existsSync(convDir)) return []; + let entries = []; + try { + entries = readdirSync(convDir); + } catch { + return []; + } + + const dbCandidates = []; + for (const name of entries) { + if (!name.endsWith('.db')) continue; + const cid = name.slice(0, -3).toLowerCase(); + if (!MIGRATOR_UUID_RE.test(cid)) continue; + const info = migratorComputeDbFileInfo(convDir, cid); + if (!info) continue; + const summary = summaryMap.get(cid) || null; + const summaryLastModMs = summary + ? parseIsoMs(normalizeSqliteIsoTime(summary.last_modified_time)) || 0 + : 0; + dbCandidates.push({ + cid, + summary, + info, + sortMs: Math.max(summaryLastModMs, info.mtimeMs), + }); + } + + dbCandidates.sort((a, b) => b.sortMs - a.sortMs); + + const sessions = []; + for (const cand of dbCandidates) { + if (sessions.length >= MIGRATOR_MAX_SESSIONS_PER_CLIENT) break; + const { cid, summary, info } = cand; + + if (summary) { + const parentId = String(summary.parent_conversation_id || '').trim(); + const depth = Number(summary.nesting_depth || 0); + if (parentId || depth > 0) continue; + if (summary.raw_summary) { + const rawFields = splitProtoRawFields(summary.raw_summary); + const ttField = rawFields.find((f) => f.fn === 22 && f.wt === 0); + if (ttField) { + const st = { off: 0 }; + const ttVal = Number(BigInt.asUintN(32, readProtoVarint(ttField.payload, st, ttField.payload.length))); + if (ttVal === 22) continue; // 跳过旁路提问 + } + } + } + + const annTitle = migratorReadAnnotationTitle(clientRoot, cid); + const sumTitle = String(summary?.title || '').trim(); + const sumPreview = String(summary?.preview || '').trim(); + const summaryStepCount = summary ? Math.max(0, Number(summary.step_count || 0)) : -1; + if (summary && summaryStepCount === 0 && !runningSet.has(cid)) { + continue; + } + + const needDbInspect = !summary || (!annTitle && !sumTitle && !sumPreview); + let dbLight = null; + if (needDbInspect) { + dbLight = migratorInspectConversationDbLight(info.dbPath, { + needPromptTitle: !annTitle && !sumTitle && !sumPreview, + }); + } + + if (dbLight) { + if (dbLight.trajectoryType === 22 || dbLight.parentConversationId) continue; + } + + const stepCount = + summaryStepCount >= 0 ? summaryStepCount : Math.max(0, Number(dbLight?.stepCount || 0)); + if (stepCount === 0) continue; + + const title = + annTitle || + sumTitle || + sumPreview || + String(dbLight?.firstPromptTitle || '').trim() || + cid.slice(0, 8); + + const uris = summary ? migratorParseWorkspaceUrisColumn(summary.workspace_uris) : []; + const workspaceUri = uris[0] || String(dbLight?.workspaceUri || '').trim(); + const { name: workspaceName, displayPath: workspacePath } = + migratorParseWorkspaceLabel(workspaceUri); + + const rawStatus = String(summary?.status || '').trim(); + const killed = Boolean(Number(summary?.killed || 0)); + const notFullyIdle = Boolean(Number(summary?.not_fully_idle || 0)); + const isRunning = + runningSet.has(cid) || + (!killed && + (rawStatus === 'CASCADE_RUN_STATUS_RUNNING' || + (notFullyIdle && rawStatus !== 'CASCADE_RUN_STATUS_IDLE'))); + + sessions.push({ + cascadeId: cid, + clientId: clientDef.id, + title, + stepCount, + lastModifiedMs: cand.sortMs, + workspaceUri, + workspaceName, + workspacePath, + projectId: String(summary?.project_id || dbLight?.projectId || '').trim(), + sizeBytes: info.sizeBytes, + hasBrain: existsSync(join(clientRoot, 'brain', cid)), + isRunning, + }); + } + + return sessions; +} + +/** + * 探测本机多端 Antigravity 目录、各端可迁移根会话列表及桌面端目标项目列表。 + * + * @param {{ + * geminiDir?: string, + * runningCascadeIds?: Iterable, + * }} [options={}] + */ +export function getSessionMigrationCatalog(options = {}) { + const sqliteSupported = hasBuiltinNodeSqlite(); + const geminiDir = migratorResolveGeminiDir(options.geminiDir); + const runningSet = new Set(); + if (options.runningCascadeIds) { + for (const id of options.runningCascadeIds) { + const norm = String(id || '').trim().toLowerCase(); + if (norm) runningSet.add(norm); + } + } + + const clients = []; + const sessionsByClient = {}; + let desktopProjects = []; + + for (const def of MIGRATOR_CLIENT_DEFS) { + const root = join(geminiDir, def.dirName); + const convDir = join(root, 'conversations'); + const sumDbPath = join(root, 'conversation_summaries.db'); + const rootExists = existsSync(root); + const convExists = rootExists && existsSync(convDir); + const hasSummaryDb = rootExists && existsSync(sumDbPath); + + let summaryMap = new Map(); + if (sqliteSupported && hasSummaryDb) { + summaryMap = migratorReadClientSummaryMap(root, def.appDataDir).map; + } + + if (def.id === 'desktop') { + desktopProjects = migratorExtractDesktopProjects(summaryMap); + } + + const sessions = + sqliteSupported && convExists + ? migratorListClientSessions(def, root, summaryMap, runningSet) + : []; + + const hasUsableData = convExists && (hasSummaryDb || sessions.length > 0); + const canBeTarget = Boolean(def.allowTarget && rootExists && convExists && hasSummaryDb); + const canBeSource = Boolean(convExists && sessions.length > 0); + + sessionsByClient[def.id] = sessions; + clients.push({ + id: def.id, + dirName: def.dirName, + rootPath: root, + exists: hasUsableData, + hasSummaryDb, + canBeSource, + canBeTarget, + sessionCount: sessions.length, + }); + } + + const detectedClients = clients.filter((c) => c.exists); + const hasAnyTarget = detectedClients.some((c) => c.canBeTarget); + const available = Boolean(sqliteSupported && detectedClients.length >= 2 && hasAnyTarget); + + return { + available, + sqliteSupported, + clients, + sessionsByClient, + desktopProjects, + }; +} + +function migratorBackupSummaryDb(targetSumDbPath, targetClientId, backupRoot) { + if (!existsSync(targetSumDbPath)) return ''; + mkdirSync(backupRoot, { recursive: true }); + const stamp = new Date().toISOString().replace(/[:.]/g, '-'); + const baseName = `conversation_summaries_${targetClientId}_${stamp}.db`; + const dstPath = join(backupRoot, baseName); + cpSync(targetSumDbPath, dstPath, { force: true }); + const walPath = `${targetSumDbPath}-wal`; + if (existsSync(walPath)) { + try { + cpSync(walPath, `${dstPath}-wal`, { force: true }); + } catch { + // 忽略瞬时 WAL 拷贝异常 + } + } + + // 滚动清理超出上限的旧备份,防止磁盘无限增长 + try { + const prefix = `conversation_summaries_${targetClientId}_`; + const backupFiles = readdirSync(backupRoot) + .filter((name) => name.startsWith(prefix) && name.endsWith('.db')) + .sort() + .reverse(); + for (const stale of backupFiles.slice(MIGRATOR_MAX_BACKUPS)) { + const staleDb = join(backupRoot, stale); + try { + rmSync(staleDb, { force: true }); + rmSync(`${staleDb}-wal`, { force: true }); + } catch { + // 忽略旧备份删除异常 + } + } + } catch { + // 忽略备份目录列举异常 + } + + return dstPath; +} + +function migratorBuildWorkspaceSubmessage(rawUri, targetClientId) { + if (!rawUri) return Buffer.alloc(0); + if (targetClientId === 'cli') { + return Buffer.concat([encodeProtoStringField(1, rawUri), encodeProtoStringField(3, '')]); + } + return Buffer.concat([encodeProtoStringField(1, rawUri), encodeProtoStringField(2, rawUri)]); +} + +function migratorBuildSummaryMetaBlob(sourceMetaBlob, { newCid, targetClientId, targetProjectId, rawUri, encodedUri }) { + const wsBytes = migratorBuildWorkspaceSubmessage(rawUri, targetClientId); + const primaryUri = targetClientId === 'cli' ? rawUri : encodedUri; + const replacements = new Map([ + [1, wsBytes.length > 0 ? encodeProtoBytesField(1, wsBytes) : null], + [6, encodeProtoStringField(6, newCid)], + [7, primaryUri ? encodeProtoStringField(7, primaryUri) : null], + [15, null], // 摘要中的 trajectoryMetadata 不必携带庞大实验配置块 + [18, encodeProtoStringField(18, targetProjectId)], + ]); + if (sourceMetaBlob && sourceMetaBlob.byteLength > 0) { + return patchProtoMessageFields(sourceMetaBlob, replacements); + } + const parts = []; + if (wsBytes.length > 0) parts.push(encodeProtoBytesField(1, wsBytes)); + parts.push(encodeProtoStringField(6, newCid)); + if (primaryUri) parts.push(encodeProtoStringField(7, primaryUri)); + parts.push(encodeProtoStringField(18, targetProjectId)); + return Buffer.concat(parts); +} + +function migratorBuildPatchedRawSummary({ + sourceRawSummary, + sourceMetaBlob, + newCid, + newTid, + title, + stepCount, + nowMs, + createdMs, + lastUserInputMs, + lastUserInputStepIndex, + trajectoryType, + targetClientId, + targetProjectId, + rawUri, + encodedUri, +}) { + const wsBytes = migratorBuildWorkspaceSubmessage(rawUri, targetClientId); + const nowTsBytes = encodeProtoTimestamp(nowMs); + const annSub = Buffer.concat([ + encodeProtoStringField(1, title), + ...(targetClientId === 'desktop' ? [encodeProtoBytesField(7, nowTsBytes)] : []), + ]); + + if (sourceRawSummary && sourceRawSummary.byteLength > 0) { + const rawFields = splitProtoRawFields(sourceRawSummary); + const fn17 = rawFields.find((f) => f.fn === 17 && f.wt === 2); + const patchedFn17 = migratorBuildSummaryMetaBlob(fn17?.payload || sourceMetaBlob, { + newCid, + targetClientId, + targetProjectId, + rawUri, + encodedUri, + }); + return patchProtoMessageFields( + sourceRawSummary, + new Map([ + [1, encodeProtoStringField(1, title)], + [2, encodeProtoVarintField(2, stepCount)], + [3, encodeProtoBytesField(3, nowTsBytes)], + [4, encodeProtoStringField(4, newTid)], + [5, encodeProtoVarintField(5, 1)], // CASCADE_RUN_STATUS_IDLE + [9, wsBytes.length > 0 ? encodeProtoBytesField(9, wsBytes) : null], + [15, encodeProtoBytesField(15, annSub)], + [17, encodeProtoBytesField(17, patchedFn17)], + [20, null], // 清除来源覆盖标记,交由目标端原生识别 + [21, null], // 清除未空闲标志 + [23, null], // 清除终止标志 + ]) + ); + } + + // 源端不含 conversation_summaries.db(如旧版 antigravity-ide)时从实体库元数据合成标准 raw_summary + const createdTsBytes = encodeProtoTimestamp(createdMs || nowMs); + const lastUiTsBytes = encodeProtoTimestamp(lastUserInputMs || nowMs); + const synthMeta = migratorBuildSummaryMetaBlob(sourceMetaBlob, { + newCid, + targetClientId, + targetProjectId, + rawUri, + encodedUri, + }); + const parts = [ + encodeProtoStringField(1, title), + encodeProtoVarintField(2, stepCount), + encodeProtoBytesField(3, nowTsBytes), + encodeProtoStringField(4, newTid), + encodeProtoVarintField(5, 1), + encodeProtoBytesField(7, createdTsBytes), + ]; + if (wsBytes.length > 0) { + parts.push(encodeProtoBytesField(9, wsBytes)); + } + parts.push( + encodeProtoBytesField(10, lastUiTsBytes), + encodeProtoBytesField(15, annSub), + ...(lastUserInputStepIndex >= 0 ? [encodeProtoVarintField(16, lastUserInputStepIndex)] : []), + encodeProtoBytesField(17, synthMeta), + encodeProtoVarintField(22, trajectoryType || 4), + encodeProtoVarintField(28, 4) + ); + return Buffer.concat(parts); +} + +function migratorOpenWritableDbWithRetry(dbPath, fn) { + const DatabaseSync = getNodeSqliteDatabaseSync(); + if (!DatabaseSync) { + throw new Error('Built-in node:sqlite is unavailable'); + } + for (let attempt = 0; attempt < 3; attempt++) { + let db = null; + try { + db = new DatabaseSync(dbPath); + db.exec('PRAGMA busy_timeout = 3000;'); + return fn(db); + } catch (err) { + if (attempt < 2 && isSqliteBusyError(err)) { + continue; + } + throw err; + } finally { + if (db) { + try { + db.close(); + } catch { + // 忽略关闭异常 + } + } + } + } + return null; +} + +function migratorIsFileLockError(err) { + const code = String(err?.code || '').toUpperCase(); + const msg = String(err?.message || ''); + return ( + code === 'EBUSY' || + code === 'EPERM' || + code === 'EACCES' || + /EBUSY|EPERM|resource busy|locked/i.test(msg) + ); +} + +function migratorCleanupTargetArtifacts({ dstDbPath, dstAnnPath, dstBrainDir, removeBrain = true }) { + for (const cleanupPath of [dstDbPath, `${dstDbPath}-wal`, `${dstDbPath}-shm`, dstAnnPath]) { + try { + if (cleanupPath && existsSync(cleanupPath)) rmSync(cleanupPath, { force: true }); + } catch { + // 忽略清理异常 + } + } + if (removeBrain && dstBrainDir) { + try { + if (existsSync(dstBrainDir)) rmSync(dstBrainDir, { recursive: true, force: true }); + } catch { + // 忽略目录清理异常 + } + } +} + +/** + * 将用户选定的单条或多条会话按选定模式(默认 `move` 完整迁移,可选 `clone` 新 UUID 克隆)迁移到目标端目录。 + * + * @param {{ + * sourceClient: string, + * targetClient: string, + * mode?: 'move' | 'clone', + * cascadeIds: string[], + * targetProjectId?: string, + * targetWorkspaceUri?: string, + * titlePrefix?: string, + * }} params + * @param {{ + * geminiDir?: string, + * backupDir?: string, + * runningCascadeIds?: Iterable, + * }} [options={}] + */ +export function migrateSessions(params = {}, options = {}) { + if (!hasBuiltinNodeSqlite()) { + return { ok: false, status: 503, error: 'sqlite_unavailable', results: [] }; + } + + const mode = String(params.mode || '').trim().toLowerCase() === 'clone' ? 'clone' : 'move'; + const srcDef = migratorGetClientDef(params.sourceClient); + const dstDef = migratorGetClientDef(params.targetClient); + if (!srcDef || !dstDef || srcDef.id === dstDef.id || !dstDef.allowTarget) { + return { ok: false, status: 400, error: 'invalid_client_direction', results: [] }; + } + + const rawIds = Array.isArray(params.cascadeIds) ? params.cascadeIds : []; + const uniqueIds = []; + const seenIds = new Set(); + for (const item of rawIds) { + const cid = String(item || '').trim().toLowerCase(); + if (!MIGRATOR_UUID_RE.test(cid) || seenIds.has(cid)) continue; + seenIds.add(cid); + uniqueIds.push(cid); + if (uniqueIds.length >= MIGRATOR_MAX_BATCH_SIZE) break; + } + if (uniqueIds.length === 0) { + return { ok: false, status: 400, error: 'no_sessions_selected', results: [] }; + } + + const geminiDir = migratorResolveGeminiDir(options.geminiDir); + const srcRoot = join(geminiDir, srcDef.dirName); + const dstRoot = join(geminiDir, dstDef.dirName); + const srcConvDir = join(srcRoot, 'conversations'); + const dstConvDir = join(dstRoot, 'conversations'); + const srcSumDbPath = join(srcRoot, 'conversation_summaries.db'); + const dstSumDbPath = join(dstRoot, 'conversation_summaries.db'); + + if (!existsSync(srcConvDir) || !existsSync(dstRoot) || !existsSync(dstSumDbPath)) { + return { ok: false, status: 400, error: 'client_storage_missing', results: [] }; + } + mkdirSync(dstConvDir, { recursive: true }); + + const runningSet = new Set(); + if (options.runningCascadeIds) { + for (const id of options.runningCascadeIds) { + const norm = String(id || '').trim().toLowerCase(); + if (norm) runningSet.add(norm); + } + } + + const srcSummaryMap = migratorReadClientSummaryMap(srcRoot, srcDef.appDataDir).map; + const dstSummaryMap = migratorReadClientSummaryMap(dstRoot, dstDef.appDataDir).map; + const desktopProjects = + dstDef.id === 'desktop' ? migratorExtractDesktopProjects(dstSummaryMap) : []; + + const requestedProjectId = String(params.targetProjectId || '').trim(); + const matchedProject = + dstDef.id === 'desktop' && requestedProjectId + ? desktopProjects.find((p) => p.projectId === requestedProjectId) || null + : null; + + const resolvedProjectId = + dstDef.id === 'cli' + ? MIGRATOR_CLI_PROJECT_ID + : matchedProject + ? matchedProject.projectId + : requestedProjectId || MIGRATOR_OUTSIDE_PROJECT_ID; + + const explicitTargetWsUri = String(params.targetWorkspaceUri || '').trim(); + const titlePrefix = String(params.titlePrefix || '').trim(); + + // 写入目标摘要库前自动留存滚动备份(移动模式同时备份源摘要库) + const backupRoot = migratorResolveBackupRoot(options.backupDir); + let backupPath = ''; + try { + backupPath = migratorBackupSummaryDb(dstSumDbPath, dstDef.id, backupRoot); + if (mode === 'move' && existsSync(srcSumDbPath)) { + migratorBackupSummaryDb(srcSumDbPath, srcDef.id, backupRoot); + } + } catch { + backupPath = ''; + } + + const archiveSrcDir = join(backupRoot, 'archived-sources', srcDef.id); + if (mode === 'move') { + mkdirSync(archiveSrcDir, { recursive: true }); + } + + mkdirSync(join(dstRoot, 'annotations'), { recursive: true }); + mkdirSync(join(dstRoot, 'brain'), { recursive: true }); + + const results = []; + const pendingSummaryInserts = []; + const baseNowMs = Date.now(); + const batchStamp = new Date(baseNowMs).toISOString().replace(/[:.]/g, '-'); + + for (let i = 0; i < uniqueIds.length; i += 1) { + const srcCid = uniqueIds[i]; + const srcDbPath = join(srcConvDir, `${srcCid}.db`); + if (!existsSync(srcDbPath)) { + results.push({ ok: false, sourceCascadeId: srcCid, error: 'source_not_found' }); + continue; + } + + const srcSummary = srcSummaryMap.get(srcCid) || null; + const rawStatus = String(srcSummary?.status || '').trim(); + const killed = Boolean(Number(srcSummary?.killed || 0)); + const notFullyIdle = Boolean(Number(srcSummary?.not_fully_idle || 0)); + const isRunning = + runningSet.has(srcCid) || + (!killed && + (rawStatus === 'CASCADE_RUN_STATUS_RUNNING' || + (notFullyIdle && rawStatus !== 'CASCADE_RUN_STATUS_IDLE'))); + if (isRunning) { + results.push({ ok: false, sourceCascadeId: srcCid, error: 'session_running' }); + continue; + } + + const annTitle = migratorReadAnnotationTitle(srcRoot, srcCid); + const dbLight = migratorInspectConversationDbLight(srcDbPath, { + needPromptTitle: !annTitle && !srcSummary?.title && !srcSummary?.preview, + }); + const stepCount = Math.max( + 0, + Number(srcSummary?.step_count ?? dbLight?.stepCount ?? 0) + ); + if (stepCount === 0) { + results.push({ ok: false, sourceCascadeId: srcCid, error: 'empty_session' }); + continue; + } + + const baseTitle = + annTitle || + String(srcSummary?.title || '').trim() || + String(srcSummary?.preview || '').trim() || + String(dbLight?.firstPromptTitle || '').trim() || + srcCid.slice(0, 8); + const finalTitle = titlePrefix ? `${titlePrefix} ${baseTitle}`.trim() : baseTitle; + + const srcUris = srcSummary ? migratorParseWorkspaceUrisColumn(srcSummary.workspace_uris) : []; + const srcPrimaryUri = srcUris[0] || String(dbLight?.workspaceUri || '').trim(); + + let effectiveWsInput = ''; + if (dstDef.id === 'desktop') { + if (resolvedProjectId === MIGRATOR_OUTSIDE_PROJECT_ID) { + effectiveWsInput = explicitTargetWsUri || ''; + } else { + effectiveWsInput = explicitTargetWsUri || matchedProject?.workspaceUri || srcPrimaryUri; + } + } else { + effectiveWsInput = explicitTargetWsUri || srcPrimaryUri; + } + + const rawUri = migratorToRawFileUri(effectiveWsInput); + const encodedUri = migratorToDesktopEncodedUri(effectiveWsInput); + + const newCid = mode === 'move' ? srcCid : randomUUID(); + const dstDbPath = join(dstConvDir, `${newCid}.db`); + if (mode === 'move' && existsSync(dstDbPath)) { + results.push({ ok: false, sourceCascadeId: srcCid, error: 'target_already_exists' }); + continue; + } + + let newTid = randomUUID(); + const itemNowMs = baseNowMs + i; + const itemNowSql = migratorFormatSqliteUtcTime(itemNowMs); + const dstBrainDir = join(dstRoot, 'brain', newCid); + const dstBrainExistedBefore = existsSync(dstBrainDir); + const dstAnnPath = join(dstRoot, 'annotations', `${newCid}.pbtxt`); + const srcAnnPath = join(srcRoot, 'annotations', `${srcCid}.pbtxt`); + const archivedSrcDbPath = + mode === 'move' ? join(archiveSrcDir, `${srcCid}_${batchStamp}.db`) : ''; + + try { + // 1. SQLite VACUUM INTO 一致性脱机快照(移动模式先留一份完整归档备份,再写入目标端) + withReadOnlySqliteDb(srcDbPath, (srcDb) => { + if (mode === 'move' && archivedSrcDbPath) { + const escapedArchive = archivedSrcDbPath.replace(/'/g, "''"); + srcDb.exec(`VACUUM INTO '${escapedArchive}'`); + } + const escapedDst = dstDbPath.replace(/'/g, "''"); + srcDb.exec(`VACUUM INTO '${escapedDst}'`); + }); + + // 2. 在目标库中改写 trajectory_meta 和 trajectory_metadata_blob + // 移动模式保留原 trajectory_id 和 cascade_id,使所有历史步序(#1/#3/#5…)在目标端完整连贯呈现 + let sourceMetaBlob = null; + migratorOpenWritableDbWithRetry(dstDbPath, (dstDb) => { + if (mode === 'move') { + const origMeta = dstDb.prepare('SELECT trajectory_id FROM trajectory_meta LIMIT 1').get(); + if (origMeta?.trajectory_id) { + newTid = String(origMeta.trajectory_id).trim(); + } + dstDb + .prepare('UPDATE trajectory_meta SET source = ?') + .run(dstDef.trajectorySourceNum); + } else { + dstDb + .prepare('UPDATE trajectory_meta SET trajectory_id = ?, cascade_id = ?, source = ?') + .run(newTid, newCid, dstDef.trajectorySourceNum); + } + + const metaRow = dstDb + .prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main' LIMIT 1") + .get(); + if (metaRow?.data) { + sourceMetaBlob = Buffer.from(metaRow.data); + const wsBytes = migratorBuildWorkspaceSubmessage(rawUri, dstDef.id); + const primaryMetaUri = dstDef.id === 'cli' ? rawUri : encodedUri; + const patchedMeta = patchProtoMessageFields( + sourceMetaBlob, + new Map([ + [1, wsBytes.length > 0 ? encodeProtoBytesField(1, wsBytes) : null], + [6, encodeProtoStringField(6, newCid)], + [7, primaryMetaUri ? encodeProtoStringField(7, primaryMetaUri) : null], + [18, encodeProtoStringField(18, resolvedProjectId)], + ]) + ); + dstDb + .prepare("UPDATE trajectory_metadata_blob SET data = ? WHERE id = 'main'") + .run(patchedMeta); + } + }); + + // 3. 拷贝 brain/ -> brain/(保留源 brain 中的媒体文件不删,确保历史图片绝对路径持续有效) + const srcBrainDir = join(srcRoot, 'brain', srcCid); + if (existsSync(srcBrainDir)) { + cpSync(srcBrainDir, dstBrainDir, { recursive: true, force: true }); + } + + // 4. 写入 annotations/.pbtxt,保障标题立即可见 + const escapedTitle = migratorEscapePbtxtString(finalTitle); + const annContent = + dstDef.id === 'desktop' + ? `title:"${escapedTitle}" last_user_view_time:{seconds:${Math.floor(itemNowMs / 1000)} nanos:0}\n` + : `title:"${escapedTitle}"\n`; + writeFileSync(dstAnnPath, annContent, 'utf8'); + + // 5. 移动模式下,在写入摘要库之前先移除源 `.db`(若被原端锁定则立即干净回滚,不留双份脑裂) + if (mode === 'move') { + try { + rmSync(srcDbPath, { force: true }); + for (const sidecarFile of [`${srcDbPath}-wal`, `${srcDbPath}-shm`]) { + if (existsSync(sidecarFile)) { + rmSync(sidecarFile, { force: true }); + } + } + if (existsSync(srcAnnPath)) { + try { + rmSync(srcAnnPath, { force: true }); + } catch { + // 忽略源注释清理失败 + } + } + } catch (unlinkErr) { + migratorCleanupTargetArtifacts({ + dstDbPath, + dstAnnPath, + dstBrainDir, + removeBrain: !dstBrainExistedBefore, + }); + results.push({ + ok: false, + sourceCascadeId: srcCid, + error: migratorIsFileLockError(unlinkErr) + ? 'source_locked' + : unlinkErr?.message || 'source_remove_failed', + }); + continue; + } + } + + // 6. 准备摘要库写入记录 + const lastUserInputSql = + String(srcSummary?.last_user_input_time || '').trim() || itemNowSql; + const lastUserInputMs = parseIsoMs(normalizeSqliteIsoTime(lastUserInputSql)) || itemNowMs; + const lastUserInputStepIndex = + srcSummary?.last_user_input_step_index != null + ? Number(srcSummary.last_user_input_step_index) + : Number(dbLight?.lastUserInputStepIndex ?? -1); + + const patchedRawSummary = migratorBuildPatchedRawSummary({ + sourceRawSummary: srcSummary?.raw_summary || null, + sourceMetaBlob, + newCid, + newTid, + title: finalTitle, + stepCount, + nowMs: itemNowMs, + createdMs: dbLight?.createdMs || lastUserInputMs, + lastUserInputMs, + lastUserInputStepIndex, + trajectoryType: dbLight?.trajectoryType || 4, + targetClientId: dstDef.id, + targetProjectId: resolvedProjectId, + rawUri, + encodedUri, + }); + + const workspaceUrisCol = + dstDef.id === 'cli' + ? rawUri + ? JSON.stringify([rawUri]) + : '[]' + : encodedUri + ? JSON.stringify([encodedUri]) + : ''; + + pendingSummaryInserts.push({ + srcCid, + newCid, + newTid, + title: finalTitle, + stepCount, + nowSql: itemNowSql, + workspaceUrisCol, + projectId: resolvedProjectId, + lastUserInputSql, + lastUserInputStepIndex, + appDataDir: dstDef.appDataDir, + patchedRawSummary, + srcDbPath, + archivedSrcDbPath, + dstDbPath, + dstBrainDir, + dstBrainExistedBefore, + dstAnnPath, + }); + } catch (err) { + migratorCleanupTargetArtifacts({ + dstDbPath, + dstAnnPath, + dstBrainDir, + removeBrain: !dstBrainExistedBefore, + }); + results.push({ + ok: false, + sourceCascadeId: srcCid, + error: err?.message || 'migrate_failed', + }); + } + } + + // 7. 在单事务中把成功迁移的会话摘要写入目标 conversation_summaries.db(移动模式同步从源摘要库移除) + if (pendingSummaryInserts.length > 0) { + try { + migratorOpenWritableDbWithRetry(dstSumDbPath, (dstSumDb) => { + const insertStmt = dstSumDb.prepare( + `INSERT OR REPLACE INTO conversation_summaries ( + conversation_id, title, preview, step_count, last_modified_time, + workspace_uris, status, source, project_id, agent_name, + parent_conversation_id, nesting_depth, battle_id, winning_conversation_id, + not_fully_idle, killed, last_user_input_time, last_user_input_step_index, + app_data_dir, raw_summary, group_id + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ); + dstSumDb.exec('BEGIN IMMEDIATE'); + try { + for (const item of pendingSummaryInserts) { + insertStmt.run( + item.newCid, + item.title, + item.title, + item.stepCount, + item.nowSql, + item.workspaceUrisCol, + 'CASCADE_RUN_STATUS_IDLE', + '', + item.projectId, + '', + '', + 0, + '', + '', + 0, + 0, + item.lastUserInputSql, + item.lastUserInputStepIndex, + item.appDataDir, + item.patchedRawSummary, + '' + ); + } + dstSumDb.exec('COMMIT'); + } catch (txErr) { + try { + dstSumDb.exec('ROLLBACK'); + } catch { + // 忽略回滚异常 + } + throw txErr; + } + }); + + if (mode === 'move' && existsSync(srcSumDbPath)) { + try { + migratorOpenWritableDbWithRetry(srcSumDbPath, (srcSumDb) => { + const delSum = srcSumDb.prepare('DELETE FROM conversation_summaries WHERE conversation_id = ?'); + let delFts = null; + try { + delFts = srcSumDb.prepare('DELETE FROM conversations_fts WHERE conversation_id = ?'); + } catch { + delFts = null; + } + srcSumDb.exec('BEGIN IMMEDIATE'); + try { + for (const item of pendingSummaryInserts) { + delSum.run(item.srcCid); + if (delFts) delFts.run(item.srcCid); + } + srcSumDb.exec('COMMIT'); + } catch (txErr) { + try { + srcSumDb.exec('ROLLBACK'); + } catch { + // 忽略回滚异常 + } + throw txErr; + } + }); + } catch { + // 源摘要库清理失败不影响目标端正常使用(源实体 .db 已移出) + } + } + + for (const item of pendingSummaryInserts) { + results.push({ + ok: true, + mode, + sourceCascadeId: item.srcCid, + newCascadeId: item.newCid, + title: item.title, + stepCount: item.stepCount, + projectId: item.projectId, + ...(item.archivedSrcDbPath ? { archivedSourcePath: item.archivedSrcDbPath } : {}), + ...(dstDef.id === 'cli' ? { resumeCommand: `agy --conversation ${item.newCid}` } : {}), + }); + } + } catch (sumErr) { + // 摘要库写入失败时完整回滚本批次已创建的副本文件,并在移动模式下恢复源 `.db` + for (const item of pendingSummaryInserts) { + migratorCleanupTargetArtifacts({ + dstDbPath: item.dstDbPath, + dstAnnPath: item.dstAnnPath, + dstBrainDir: item.dstBrainDir, + removeBrain: !item.dstBrainExistedBefore, + }); + if (mode === 'move' && item.archivedSrcDbPath && existsSync(item.archivedSrcDbPath)) { + try { + cpSync(item.archivedSrcDbPath, item.srcDbPath, { force: true }); + } catch { + // 忽略恢复异常(归档备份仍保留在 backupDir) + } + } + results.push({ + ok: false, + sourceCascadeId: item.srcCid, + error: sumErr?.message || 'summary_write_failed', + }); + } + } + } + + const migratedCount = results.filter((r) => r.ok).length; + const failedCount = results.length - migratedCount; + const firstError = migratedCount === 0 ? results.find((r) => !r.ok)?.error || 'migrate_failed' : ''; + return { + ok: migratedCount > 0, + status: migratedCount > 0 ? 200 : 400, + ...(firstError ? { error: firstError } : {}), + mode, + sourceClient: srcDef.id, + targetClient: dstDef.id, + targetProjectId: resolvedProjectId, + migratedCount, + failedCount, + backupPath, + needsWindowReload: dstDef.id === 'desktop' && migratedCount > 0, + results, + }; +} diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index a36f6d8..06b70b9 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index c3c4b11..6f08d01 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -558,6 +558,7 @@ export function buildBundle(panelDir = PANEL_DIR) { 'src/components/settings/EditableSlotList.js', 'src/components/settings/ThemeColorPicker.js', 'src/components/settings/BridgeStatusNotice.js', + 'src/components/settings/SessionMigrationCard.js', 'src/views/settings/SettingsGeneralTab.js', 'src/views/settings/SettingsStructureTab.js', 'src/views/settings/SettingsOtherTab.js', diff --git a/sidecars/panel/shared/window-bridge-protocol.mjs b/sidecars/panel/shared/window-bridge-protocol.mjs index 42a5338..4362fb3 100644 --- a/sidecars/panel/shared/window-bridge-protocol.mjs +++ b/sidecars/panel/shared/window-bridge-protocol.mjs @@ -28,6 +28,16 @@ export const BRIDGE_API_ROUTE_DEFS = Object.freeze([ Object.freeze({ path: '/api/cloud-sync', method: 'POST', action: 'cloud_sync' }), Object.freeze({ path: '/api/plugin-update', method: 'POST', action: 'plugin_update' }), Object.freeze({ path: '/api/bridge/relaunch', method: 'POST', action: 'bridge_relaunch' }), + Object.freeze({ + path: '/api/session-migration/catalog', + method: 'GET', + action: 'session_migration_catalog', + }), + Object.freeze({ + path: '/api/session-migration/migrate', + method: 'POST', + action: 'session_migration_migrate', + }), ]); export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)); diff --git a/sidecars/panel/src/components/settings/SessionMigrationCard.js b/sidecars/panel/src/components/settings/SessionMigrationCard.js new file mode 100644 index 0000000..daba0b3 --- /dev/null +++ b/sidecars/panel/src/components/settings/SessionMigrationCard.js @@ -0,0 +1,750 @@ +/** + * @fileoverview 跨端会话按需迁移设置卡片 (`SessionMigrationCard.js`)。 + * 仅当本机检测到 ≥2 个 Antigravity 客户端目录时展示,支持自由勾选根会话以新 UUID 无损克隆到目标端。 + */ + +import { defineComponent } from '../../core/component.js'; +import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; +import { isWindowOverlayMode } from '../../core/httpClient.js'; +import { createSvgIcon } from '../../icons/SvgIcon.js'; +import { isEnglishLocale, t } from '../../i18n/index.js'; +import { + executeSessionMigration, + fetchSessionMigrationCatalog, +} from '../../store/telemetryStore.js'; +import { CustomSelect } from '../ui/CustomSelect.js'; + +const SMIG_OUTSIDE_PROJECT_ID = 'outside-of-project'; + +async function smigCopyText(text) { + try { + if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text); + return true; + } + } catch { + // 退回受限 Webview 的隐藏文本域复制 + } + try { + if (typeof document === 'undefined' || !document.body) return false; + const area = document.createElement('textarea'); + area.value = text; + area.setAttribute('readonly', 'true'); + area.style.cssText = 'position:fixed;left:-9999px;top:-9999px;opacity:0;'; + document.body.appendChild(area); + area.select?.(); + const ok = Boolean(document.execCommand?.('copy')); + document.body.removeChild(area); + return ok; + } catch { + return false; + } +} + +function smigGetClientLabel(clientId) { + if (clientId === 'cli') return t('settings.oth.migClientCli'); + if (clientId === 'ide_legacy') return t('settings.oth.migClientIdeLegacy'); + return t('settings.oth.migClientDesktop'); +} + +function smigFormatAge(epochMs) { + const ts = Number(epochMs || 0); + if (!Number.isFinite(ts) || ts <= 0) return ''; + const diffSec = Math.max(0, Math.floor((Date.now() - ts) / 1000)); + const isEn = isEnglishLocale(); + if (diffSec < 60) return isEn ? 'just now' : '刚刚'; + const diffMin = Math.floor(diffSec / 60); + if (diffMin < 60) return isEn ? `${diffMin}m ago` : `${diffMin}分钟前`; + const diffHr = Math.floor(diffMin / 60); + if (diffHr < 24) return isEn ? `${diffHr}h ago` : `${diffHr}小时前`; + const diffDay = Math.floor(diffHr / 24); + return isEn ? `${diffDay}d ago` : `${diffDay}天前`; +} + +export const SessionMigrationCard = defineComponent({ + name: 'SessionMigrationCard', + setup({ props, onCleanup }) { + const loadCatalogFn = + typeof props?.loadCatalog === 'function' ? props.loadCatalog : fetchSessionMigrationCatalog; + const runMigrateFn = + typeof props?.runMigrate === 'function' ? props.runMigrate : executeSessionMigration; + + let catalog = null; + let hasLoadedOnce = false; + let isLoading = false; + let isMigrating = false; + let destroyed = false; + let bodyMounted = false; + let sourceClient = ''; + let targetClient = ''; + let migrationMode = 'move'; + let targetProjectId = ''; + let searchQuery = ''; + const selectedIds = new Set(); + let lastResult = null; + let copiedCmdId = ''; + let copiedTimer = null; + + let titleEl = null; + let descEl = null; + let refreshBtnText = null; + let refreshBtn = null; + let sourceLabelEl = null; + let targetLabelEl = null; + let modeLabelEl = null; + let modeMoveBtn = null; + let modeCloneBtn = null; + let modeHintEl = null; + let projectLabelEl = null; + let sourceSelect = null; + let targetSelect = null; + let projectSelect = null; + let projectFieldWrap = null; + let searchInput = null; + let toggleAllBtn = null; + let selectedCountEl = null; + let listEl = null; + let migrateBtnText = null; + let migrateBtn = null; + let resultBoxEl = null; + + const rootEl = h('section', { className: 'panel smig-panel', hidden: true }); + + function ensureBodyMounted() { + if (bodyMounted) return; + bodyMounted = true; + + titleEl = h('span', { text: t('settings.oth.migTitle') }); + descEl = h('p', { className: 'smig-desc', text: t('settings.oth.migDesc') }); + refreshBtnText = h('span', { text: t('settings.oth.migRefreshBtn') }); + refreshBtn = h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm smig-refresh-btn', + onClick: () => { + void loadCatalog(true); + }, + }, + [createSvgIcon('refresh', { size: 12 }), refreshBtnText] + ); + + sourceLabelEl = h('span', { className: 'smig-field-label', text: t('settings.oth.migSourceLabel') }); + targetLabelEl = h('span', { className: 'smig-field-label', text: t('settings.oth.migTargetLabel') }); + modeLabelEl = h('span', { className: 'smig-field-label', text: t('settings.oth.migModeLabel') }); + modeMoveBtn = h('button', { + type: 'button', + className: 'smig-mode-btn is-active', + text: t('settings.oth.migModeMove'), + onClick: () => { + if (migrationMode === 'move') return; + migrationMode = 'move'; + lastResult = null; + syncModeControls(); + renderResultBox(); + }, + }); + modeCloneBtn = h('button', { + type: 'button', + className: 'smig-mode-btn', + text: t('settings.oth.migModeClone'), + onClick: () => { + if (migrationMode === 'clone') return; + migrationMode = 'clone'; + lastResult = null; + syncModeControls(); + renderResultBox(); + }, + }); + modeHintEl = h('span', { + className: 'smig-mode-hint', + text: t('settings.oth.migModeMoveHint'), + }); + projectLabelEl = h('span', { className: 'smig-field-label', text: t('settings.oth.migProjectLabel') }); + + sourceSelect = CustomSelect({ + ariaLabel: t('settings.oth.migSourceLabel'), + modelValue: '', + options: [], + onUpdateModelValue: (val) => { + if (!val || val === sourceClient) return; + sourceClient = val; + selectedIds.clear(); + lastResult = null; + ensureValidTarget(); + syncControlsAndList(); + }, + }); + + targetSelect = CustomSelect({ + ariaLabel: t('settings.oth.migTargetLabel'), + modelValue: '', + options: [], + onUpdateModelValue: (val) => { + if (!val || val === targetClient) return; + targetClient = val; + lastResult = null; + syncControlsAndList(); + }, + }); + + projectSelect = CustomSelect({ + ariaLabel: t('settings.oth.migProjectLabel'), + modelValue: '', + options: [], + className: 'smig-project-select', + onUpdateModelValue: (val) => { + targetProjectId = String(val || ''); + }, + }); + + projectFieldWrap = h('div', { className: 'smig-field' }, [ + projectLabelEl, + projectSelect.el, + ]); + + searchInput = h('input', { + type: 'text', + className: 'settings-text-input smig-search-input', + placeholder: t('settings.oth.migSearchPlaceholder'), + value: '', + }); + searchInput.addEventListener?.('input', () => { + searchQuery = String(searchInput.value || '').trim(); + renderSessionList(); + }); + + toggleAllBtn = h('button', { + type: 'button', + className: 'btn-ghost-sm smig-toggle-all-btn', + text: t('settings.oth.migSelectAll'), + onClick: () => { + const selectable = getFilteredSessions().filter((s) => !s.isRunning); + if (selectable.length === 0) return; + const allSelected = selectable.every((s) => selectedIds.has(s.cascadeId)); + if (allSelected) { + for (const s of selectable) selectedIds.delete(s.cascadeId); + } else { + for (const s of selectable) selectedIds.add(s.cascadeId); + } + renderSessionList(); + }, + }); + + selectedCountEl = h('span', { className: 'smig-count-meta', text: '' }); + listEl = h('div', { className: 'smig-list', role: 'list' }); + + migrateBtnText = h('span', { + text: t('settings.oth.migActionBtn', { count: 0 }), + }); + migrateBtn = h( + 'button', + { + type: 'button', + className: 'btn-secondary smig-migrate-btn', + disabled: true, + onClick: () => { + void handleMigrate(); + }, + }, + [createSvgIcon('copy', { size: 12 }), migrateBtnText] + ); + + resultBoxEl = h('div', { className: 'smig-result', hidden: true }); + + const children = [ + h('div', { className: 'panel-header' }, [ + h('span', { className: 'panel-title' }, [ + createSvgIcon('layers', { size: 13 }), + titleEl, + ]), + refreshBtn, + ]), + descEl, + h('div', { className: 'smig-direction-grid' }, [ + h('div', { className: 'smig-field' }, [sourceLabelEl, sourceSelect.el]), + h('div', { className: 'smig-field' }, [targetLabelEl, targetSelect.el]), + ]), + h('div', { className: 'smig-field' }, [ + modeLabelEl, + h('div', { className: 'smig-mode-bar' }, [modeMoveBtn, modeCloneBtn]), + modeHintEl, + ]), + projectFieldWrap, + h('div', { className: 'smig-toolbar' }, [ + searchInput, + toggleAllBtn, + selectedCountEl, + ]), + listEl, + h('div', { className: 'smig-footer' }, [migrateBtn]), + resultBoxEl, + ]; + for (const child of children) { + rootEl.appendChild(child); + } + } + + function getDetectedClients() { + return Array.isArray(catalog?.clients) ? catalog.clients.filter((c) => c.exists) : []; + } + + function getTargetClientsFor(srcId) { + return getDetectedClients().filter((c) => c.canBeTarget && c.id !== srcId); + } + + function ensureValidSelectionDefaults() { + const detected = getDetectedClients(); + if (detected.length < 2) { + sourceClient = ''; + targetClient = ''; + return; + } + const validSources = detected.filter((c) => getTargetClientsFor(c.id).length > 0); + if (!validSources.some((c) => c.id === sourceClient)) { + const cliClient = validSources.find((c) => c.id === 'cli' && c.sessionCount > 0); + const firstWithSessions = validSources.find((c) => c.sessionCount > 0); + sourceClient = (cliClient || firstWithSessions || validSources[0])?.id || ''; + } + ensureValidTarget(); + + const projects = Array.isArray(catalog?.desktopProjects) ? catalog.desktopProjects : []; + if (!projects.some((p) => p.projectId === targetProjectId)) { + const preferred = projects.find((p) => !p.isOutsideProject) || projects[0]; + targetProjectId = preferred?.projectId || SMIG_OUTSIDE_PROJECT_ID; + } + } + + function ensureValidTarget() { + const targets = getTargetClientsFor(sourceClient); + if (!targets.some((c) => c.id === targetClient)) { + const preferDesktop = targets.find((c) => c.id === 'desktop'); + targetClient = (preferDesktop || targets[0])?.id || ''; + } + } + + function getCurrentSourceSessions() { + const list = catalog?.sessionsByClient?.[sourceClient]; + return Array.isArray(list) ? list : []; + } + + function getFilteredSessions() { + const all = getCurrentSourceSessions(); + if (!searchQuery) return all; + const needle = searchQuery.toLowerCase(); + return all.filter((item) => { + const haystack = [ + item.title, + item.workspaceName, + item.workspacePath, + item.cascadeId, + ] + .filter(Boolean) + .join(' ') + .toLowerCase(); + return haystack.includes(needle); + }); + } + + function resolveProjectDisplayLabel(projectId) { + if (!projectId || projectId === SMIG_OUTSIDE_PROJECT_ID) { + return t('settings.oth.migProjectOutside'); + } + const projects = Array.isArray(catalog?.desktopProjects) ? catalog.desktopProjects : []; + const found = projects.find((p) => p.projectId === projectId); + return found?.name || projectId.slice(0, 8); + } + + function syncModeControls() { + if (!bodyMounted) return; + patchClasses(modeMoveBtn, { 'is-active': migrationMode === 'move' }); + patchClasses(modeCloneBtn, { 'is-active': migrationMode === 'clone' }); + patchText( + modeHintEl, + migrationMode === 'clone' + ? t('settings.oth.migModeCloneHint') + : t('settings.oth.migModeMoveHint') + ); + } + + function formatMigrationError(code) { + if (code === 'source_locked') return t('settings.oth.migErrLocked'); + if (code === 'target_already_exists') return t('settings.oth.migErrExists'); + if (code === 'session_running') return t('settings.oth.migErrRunning'); + return t('settings.oth.migFailed', { reason: code || 'unknown_error' }); + } + + function syncControlsAndList() { + const visible = Boolean(catalog?.available); + patchAttr(rootEl, 'hidden', !visible); + if (!visible) { + props?.onLayoutChange?.(); + return; + } + ensureBodyMounted(); + syncModeControls(); + + const detected = getDetectedClients(); + const sourceOptions = detected + .filter((c) => getTargetClientsFor(c.id).length > 0) + .map((c) => ({ + value: c.id, + label: smigGetClientLabel(c.id), + meta: String(c.sessionCount), + })); + const targetOptions = getTargetClientsFor(sourceClient).map((c) => ({ + value: c.id, + label: smigGetClientLabel(c.id), + })); + const projectOptions = (catalog?.desktopProjects || []).map((p) => + p.isOutsideProject + ? { value: p.projectId, label: t('settings.oth.migProjectOutside') } + : { + value: p.projectId, + label: p.name || p.projectId.slice(0, 8), + meta: p.workspacePath || '', + } + ); + + sourceSelect.setProps({ + ariaLabel: t('settings.oth.migSourceLabel'), + modelValue: sourceClient, + options: sourceOptions, + }); + targetSelect.setProps({ + ariaLabel: t('settings.oth.migTargetLabel'), + modelValue: targetClient, + options: targetOptions, + }); + projectSelect.setProps({ + ariaLabel: t('settings.oth.migProjectLabel'), + modelValue: targetProjectId, + options: projectOptions, + }); + patchAttr(projectFieldWrap, 'hidden', targetClient !== 'desktop'); + + renderSessionList(); + renderResultBox(); + props?.onLayoutChange?.(); + } + + function renderSessionList() { + const all = getCurrentSourceSessions(); + const filtered = getFilteredSessions(); + + // 清理已不在当前来源中的选中 ID + const validSet = new Set(all.filter((s) => !s.isRunning).map((s) => s.cascadeId)); + for (const id of [...selectedIds]) { + if (!validSet.has(id)) selectedIds.delete(id); + } + + const selectableFiltered = filtered.filter((s) => !s.isRunning); + const allSelected = + selectableFiltered.length > 0 && + selectableFiltered.every((s) => selectedIds.has(s.cascadeId)); + patchText( + toggleAllBtn, + allSelected ? t('settings.oth.migClearSel') : t('settings.oth.migSelectAll') + ); + patchAttr(toggleAllBtn, 'disabled', selectableFiltered.length === 0 || isMigrating); + patchText( + selectedCountEl, + t('settings.oth.migSelectedCount', { + selected: selectedIds.size, + total: filtered.length, + }) + ); + + while (listEl.firstChild) { + listEl.removeChild(listEl.firstChild); + } + + if (all.length === 0) { + listEl.appendChild(h('div', { className: 'smig-empty', text: t('settings.oth.migEmpty') })); + } else if (filtered.length === 0) { + listEl.appendChild( + h('div', { className: 'smig-empty', text: t('settings.oth.migNoMatch') }) + ); + } else { + for (const item of filtered) { + const checked = selectedIds.has(item.cascadeId); + const checkboxEl = h('input', { + type: 'checkbox', + className: 'smig-checkbox', + checked, + disabled: Boolean(item.isRunning || isMigrating), + }); + checkboxEl.checked = checked; + const toggleItem = () => { + if (item.isRunning || isMigrating) return; + if (selectedIds.has(item.cascadeId)) { + selectedIds.delete(item.cascadeId); + } else { + selectedIds.add(item.cascadeId); + } + renderSessionList(); + }; + checkboxEl.addEventListener?.('change', toggleItem); + + const metaParts = [t('settings.oth.migStepsUnit', { count: item.stepCount })]; + const age = smigFormatAge(item.lastModifiedMs); + if (age) metaParts.push(age); + + const subChildren = []; + if (item.workspacePath || item.workspaceName) { + subChildren.push( + h('span', { + className: 'smig-item-ws', + text: item.workspacePath || item.workspaceName, + title: item.workspacePath || item.workspaceName, + }) + ); + } + if (item.isRunning) { + subChildren.push( + h('span', { + className: 'smig-item-running', + text: t('settings.oth.migRunningTag'), + }) + ); + } + + const rowEl = h( + 'div', + { + className: `smig-item${checked ? ' is-selected' : ''}${item.isRunning ? ' is-running' : ''}`, + role: 'listitem', + onClick: (ev) => { + if (ev?.target === checkboxEl) return; + toggleItem(); + }, + }, + [ + checkboxEl, + h('div', { className: 'smig-item-body' }, [ + h('div', { className: 'smig-item-top' }, [ + h('span', { + className: 'smig-item-title', + text: item.title || item.cascadeId.slice(0, 8), + title: item.title || item.cascadeId, + }), + h('span', { className: 'smig-item-meta', text: metaParts.join(' · ') }), + ]), + ...(subChildren.length > 0 + ? [h('div', { className: 'smig-item-sub' }, subChildren)] + : []), + ]), + ] + ); + listEl.appendChild(rowEl); + } + } + + patchAttr(migrateBtn, 'disabled', isMigrating || selectedIds.size === 0 || !targetClient); + patchText( + migrateBtnText, + isMigrating + ? t('settings.oth.migRunningBtn') + : t('settings.oth.migActionBtn', { count: selectedIds.size }) + ); + } + + function renderResultBox() { + if (!lastResult) { + patchAttr(resultBoxEl, 'hidden', true); + return; + } + patchAttr(resultBoxEl, 'hidden', false); + patchClasses(resultBoxEl, { + 'is-ok': Boolean(lastResult.ok), + 'is-err': !lastResult.ok, + }); + + while (resultBoxEl.firstChild) { + resultBoxEl.removeChild(resultBoxEl.firstChild); + } + + if (!lastResult.ok) { + resultBoxEl.appendChild( + h('div', { + className: 'smig-result-msg', + text: formatMigrationError(lastResult.error), + }) + ); + return; + } + + const partialSuffix = + lastResult.failedCount > 0 + ? t('settings.oth.migPartialWarn', { failed: lastResult.failedCount }) + : ''; + const baseMsg = + lastResult.targetClient === 'cli' + ? t('settings.oth.migDoneCli', { count: lastResult.migratedCount }) + : t('settings.oth.migDoneDesktop', { + count: lastResult.migratedCount, + project: resolveProjectDisplayLabel(lastResult.targetProjectId), + }); + + resultBoxEl.appendChild( + h('div', { className: 'smig-result-msg', text: `${baseMsg}${partialSuffix}` }) + ); + + if (lastResult.targetClient === 'desktop' && isWindowOverlayMode()) { + resultBoxEl.appendChild( + h('div', { className: 'smig-result-actions' }, [ + h( + 'button', + { + type: 'button', + className: 'btn-secondary smig-result-btn', + onClick: () => { + if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') { + window.location.reload(); + } + }, + }, + [createSvgIcon('refresh', { size: 11 }), h('span', { text: t('settings.oth.migReloadBtn') })] + ), + ]) + ); + } + + if (lastResult.targetClient === 'cli') { + const okItems = (lastResult.results || []).filter((r) => r.ok && r.resumeCommand); + if (okItems.length > 0) { + const cmdWrap = h('div', { className: 'smig-cmd-list' }); + for (const item of okItems.slice(0, 6)) { + const isCopied = copiedCmdId === item.newCascadeId; + const copyBtn = h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm smig-cmd-copy', + text: isCopied ? t('settings.oth.migCopied') : t('settings.oth.migCopyCmd'), + onClick: async () => { + const ok = await smigCopyText(item.resumeCommand); + if (!ok || destroyed) return; + copiedCmdId = item.newCascadeId; + renderResultBox(); + if (copiedTimer) clearTimeout(copiedTimer); + copiedTimer = setTimeout(() => { + copiedTimer = null; + if (!destroyed && copiedCmdId === item.newCascadeId) { + copiedCmdId = ''; + renderResultBox(); + } + }, 2000); + }, + } + ); + cmdWrap.appendChild( + h('div', { className: 'smig-cmd-row' }, [ + h('code', { className: 'smig-cmd-code', text: item.resumeCommand }), + copyBtn, + ]) + ); + } + resultBoxEl.appendChild(cmdWrap); + } + } + } + + async function loadCatalog(force = false) { + if (isLoading || (hasLoadedOnce && !force)) return; + isLoading = true; + if (refreshBtn) patchAttr(refreshBtn, 'disabled', true); + try { + const res = await loadCatalogFn(); + if (destroyed) return; + hasLoadedOnce = true; + if (res && typeof res === 'object') { + catalog = res; + ensureValidSelectionDefaults(); + syncControlsAndList(); + } + } catch { + // 本地目录或 API 暂不可用时静默隐藏卡片,避免干扰其他设置项 + if (!destroyed && !catalog) { + patchAttr(rootEl, 'hidden', true); + } + } finally { + isLoading = false; + if (refreshBtn) patchAttr(refreshBtn, 'disabled', false); + } + } + + async function handleMigrate() { + if (isMigrating || selectedIds.size === 0 || !sourceClient || !targetClient) return; + isMigrating = true; + lastResult = null; + renderSessionList(); + renderResultBox(); + try { + const payload = { + sourceClient, + targetClient, + mode: migrationMode, + cascadeIds: [...selectedIds], + ...(targetClient === 'desktop' ? { targetProjectId } : {}), + }; + const res = await runMigrateFn(payload); + if (destroyed) return; + lastResult = res || { ok: false, error: 'empty_response' }; + if (res?.ok) { + selectedIds.clear(); + void loadCatalog(true); + } + } catch (err) { + if (!destroyed) { + lastResult = { ok: false, error: err?.message || 'request_failed' }; + } + } finally { + isMigrating = false; + if (!destroyed) { + renderSessionList(); + renderResultBox(); + props?.onLayoutChange?.(); + } + } + } + + function refreshLabels() { + if (!bodyMounted) return; + patchText(titleEl, t('settings.oth.migTitle')); + patchText(descEl, t('settings.oth.migDesc')); + patchText(refreshBtnText, t('settings.oth.migRefreshBtn')); + patchText(sourceLabelEl, t('settings.oth.migSourceLabel')); + patchText(targetLabelEl, t('settings.oth.migTargetLabel')); + patchText(modeLabelEl, t('settings.oth.migModeLabel')); + patchText(modeMoveBtn, t('settings.oth.migModeMove')); + patchText(modeCloneBtn, t('settings.oth.migModeClone')); + syncModeControls(); + patchText(projectLabelEl, t('settings.oth.migProjectLabel')); + patchAttr(searchInput, 'placeholder', t('settings.oth.migSearchPlaceholder')); + if (catalog?.available) { + syncControlsAndList(); + } + } + + onCleanup(() => { + destroyed = true; + if (copiedTimer) { + clearTimeout(copiedTimer); + copiedTimer = null; + } + sourceSelect?.destroy?.(); + targetSelect?.destroy?.(); + projectSelect?.destroy?.(); + }); + + return { + el: rootEl, + refs: { + ensureLoaded: () => loadCatalog(false), + reload: () => loadCatalog(true), + refreshLabels, + }, + }; + }, +}); diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index bede5ef..bcff001 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -659,6 +659,41 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.exportDone': 'Preferences JSON exported', 'settings.oth.importDone': 'Restored {count} preference settings', 'settings.oth.importInvalid': 'Import failed: invalid JSON or no recognized settings', + 'settings.oth.migTitle': 'Cross-Client Session Migration', + 'settings.oth.migDesc': 'Migrate selected sessions on demand with automatic source and summary backups', + 'settings.oth.migRefreshBtn': 'Refresh', + 'settings.oth.migSourceLabel': 'Source Client', + 'settings.oth.migTargetLabel': 'Target Client', + 'settings.oth.migModeLabel': 'Migration Mode', + 'settings.oth.migModeMove': 'Full Move (Recommended)', + 'settings.oth.migModeClone': 'Clone Copy', + 'settings.oth.migModeMoveHint': 'Preserves original ID and full historical steps/details; archives source backup before moving', + 'settings.oth.migModeCloneHint': 'Keeps source intact with a fresh UUID; only counts new steps generated after cloning', + 'settings.oth.migProjectLabel': 'Target Project', + 'settings.oth.migProjectOutside': 'Standalone (No Project)', + 'settings.oth.migClientDesktop': 'Desktop App / Modern IDE', + 'settings.oth.migClientCli': 'Antigravity CLI', + 'settings.oth.migClientIdeLegacy': 'Legacy IDE (.db)', + 'settings.oth.migSearchPlaceholder': 'Filter sessions by title or workspace…', + 'settings.oth.migSelectAll': 'Select all', + 'settings.oth.migClearSel': 'Clear', + 'settings.oth.migSelectedCount': '{selected} / {total} selected', + 'settings.oth.migRunningTag': 'Running', + 'settings.oth.migStepsUnit': '{count} steps', + 'settings.oth.migEmpty': 'No migratable sessions in this source client', + 'settings.oth.migNoMatch': 'No matching sessions', + 'settings.oth.migActionBtn': 'Migrate Selected ({count})', + 'settings.oth.migRunningBtn': 'Migrating…', + 'settings.oth.migDoneDesktop': 'Migrated {count} session(s) to "{project}". Press Ctrl+R in Desktop App to refresh the sidebar', + 'settings.oth.migDoneCli': 'Migrated {count} session(s) to CLI. Use the command below to resume', + 'settings.oth.migPartialWarn': ' ({failed} skipped or failed)', + 'settings.oth.migReloadBtn': 'Reload Window', + 'settings.oth.migCopyCmd': 'Copy', + 'settings.oth.migCopied': 'Copied', + 'settings.oth.migErrLocked': 'Source database is locked by its open client. Close that terminal/window first, or switch to Clone Copy', + 'settings.oth.migErrExists': 'A session with the same ID already exists in target (switch to Clone Copy if you want a duplicate)', + 'settings.oth.migErrRunning': 'Session is currently running; wait until idle before migrating', + 'settings.oth.migFailed': 'Migration failed: {reason}', // Structured Live Activity Actions 'live.act.run_command': 'Run Command', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 1282a5e..3809970 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -659,6 +659,41 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.exportDone': '配置 JSON 已导出', 'settings.oth.importDone': '已恢复 {count} 项偏好设置', 'settings.oth.importInvalid': '导入失败:JSON 无效或未包含可识别的偏好项', + 'settings.oth.migTitle': '跨端会话迁移', + 'settings.oth.migDesc': '按需把选定会话迁往另一端,迁移前自动备份摘要库和源库', + 'settings.oth.migRefreshBtn': '刷新列表', + 'settings.oth.migSourceLabel': '来源端', + 'settings.oth.migTargetLabel': '目标端', + 'settings.oth.migModeLabel': '迁移方式', + 'settings.oth.migModeMove': '完整迁移(推荐)', + 'settings.oth.migModeClone': '克隆副本', + 'settings.oth.migModeMoveHint': '保留原 ID 和全部历史步序明细,备份后移出源端(零重复计费)', + 'settings.oth.migModeCloneHint': '保留源会话并生成新 ID,新副本仅统计迁入后的新步骤', + 'settings.oth.migProjectLabel': '绑定目标项目', + 'settings.oth.migProjectOutside': '独立会话(无所属项目)', + 'settings.oth.migClientDesktop': '桌面端 App / 新版 IDE', + 'settings.oth.migClientCli': 'Antigravity CLI', + 'settings.oth.migClientIdeLegacy': '旧版 IDE (.db)', + 'settings.oth.migSearchPlaceholder': '按标题或工作区筛选会话…', + 'settings.oth.migSelectAll': '全选', + 'settings.oth.migClearSel': '清空', + 'settings.oth.migSelectedCount': '已选 {selected} / {total}', + 'settings.oth.migRunningTag': '运行中', + 'settings.oth.migStepsUnit': '{count} 步', + 'settings.oth.migEmpty': '当前来源端暂无可迁移会话', + 'settings.oth.migNoMatch': '没有匹配的会话', + 'settings.oth.migActionBtn': '迁移选定会话 ({count})', + 'settings.oth.migRunningBtn': '迁移中…', + 'settings.oth.migDoneDesktop': '已成功迁移 {count} 条会话到「{project}」,在桌面端按 Ctrl+R 即可在左侧看到', + 'settings.oth.migDoneCli': '已成功迁移 {count} 条会话到 CLI,可使用下方命令恢复对话', + 'settings.oth.migPartialWarn': '(另有 {failed} 条跳过或失败)', + 'settings.oth.migReloadBtn': '刷新窗口', + 'settings.oth.migCopyCmd': '复制命令', + 'settings.oth.migCopied': '已复制', + 'settings.oth.migErrLocked': '源会话文件正被原端占用,请先关闭对应终端/窗口后重试,或切换为「克隆副本」', + 'settings.oth.migErrExists': '目标端已存在同 ID 会话,无需重复移动(可切换为「克隆副本」)', + 'settings.oth.migErrRunning': '该会话正在运行中,请待空闲后再迁移', + 'settings.oth.migFailed': '迁移失败:{reason}', // Structured Live Activity Actions 'live.act.run_command': '执行命令', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index c7d6e72..1b48196 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -1997,6 +1997,36 @@ export async function triggerCliStatusLineAction(action) { return res; } +export async function fetchSessionMigrationCatalog() { + try { + return await callSidecarApi('/api/session-migration/catalog', { method: 'GET' }); + } catch { + return callSidecarApi('/api/settings', { + method: 'POST', + body: { __sessionMigrationAction: 'catalog' }, + }); + } +} + +export async function executeSessionMigration(payload) { + let res; + try { + res = await callSidecarApi('/api/session-migration/migrate', { + method: 'POST', + body: payload || {}, + }); + } catch { + res = await callSidecarApi('/api/settings', { + method: 'POST', + body: { __sessionMigrationAction: 'migrate', payload: payload || {} }, + }); + } + if (res?.migratedCount > 0) { + void fetchTelemetry({ force: true }).catch(() => {}); + } + return res; +} + export async function triggerPluginUpdate() { const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} }); if (res?.ok && res?.restarting) { diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index 7e8c73c..e68a71d 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -996,6 +996,334 @@ display: none !important; } +/* --- 其他页:跨端会话按需迁移卡片 (.smig-panel) --- */ +.smig-panel[hidden] { + display: none !important; +} + +.smig-desc { + margin: 0 0 var(--space-3); + font-size: var(--fs-sm); + line-height: 1.48; + color: var(--text-secondary); +} + +.smig-refresh-btn { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: var(--fs-xs); +} + +.smig-direction-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-2); + margin-bottom: var(--space-2); +} + +.smig-field { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; + margin-bottom: var(--space-2); +} + +.smig-direction-grid .smig-field { + margin-bottom: 0; +} + +.smig-field[hidden] { + display: none !important; +} + +.smig-field-label { + font-size: var(--fs-xs); + font-weight: 600; + color: var(--text-secondary); +} + +.smig-mode-bar { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 6px; +} + +.smig-mode-btn { + min-height: calc(26px * var(--ui-font-scale, 1)); + padding: 2px 8px; + border-radius: var(--radius-xs); + border: 1px solid var(--border-hairline); + background: var(--surface-subtle); + color: var(--text-secondary); + font-size: var(--fs-xs); + font-weight: 500; + cursor: pointer; + transition: + border-color var(--dur-instant) var(--ease-fast), + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); +} + +.smig-mode-btn:hover { + border-color: var(--border-default); + color: var(--text-primary); +} + +.smig-mode-btn.is-active { + border-color: var(--accent-primary-border); + background: var(--accent-primary-soft); + color: var(--accent-primary); + font-weight: 600; +} + +.smig-mode-hint { + font-size: var(--fs-xs); + line-height: 1.4; + color: var(--text-muted); +} + +.smig-project-select .select-option-meta { + max-width: 58%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.smig-toolbar { + display: flex; + align-items: center; + gap: var(--space-2); + margin-bottom: var(--space-2); +} + +.smig-search-input { + flex: 1; + min-width: 0; +} + +.smig-toggle-all-btn { + flex-shrink: 0; + font-size: var(--fs-xs); +} + +.smig-count-meta { + flex-shrink: 0; + font-size: var(--fs-xs); + color: var(--text-secondary); + font-variant-numeric: tabular-nums; +} + +.smig-list { + display: flex; + flex-direction: column; + gap: 4px; + max-height: 220px; + overflow-y: auto; + padding: 6px; + border-radius: var(--radius-xs); + border: 1px solid var(--border-hairline); + background: var(--surface-subtle); +} + +.smig-empty { + padding: var(--space-4) var(--space-2); + text-align: center; + font-size: var(--fs-sm); + color: var(--text-secondary); +} + +.smig-item { + display: flex; + align-items: flex-start; + gap: 8px; + padding: 6px 8px; + border-radius: var(--radius-xs); + border: 1px solid transparent; + background: var(--surface-panel); + cursor: pointer; + transition: + border-color var(--dur-instant) var(--ease-fast), + background-color var(--dur-instant) var(--ease-fast); +} + +.smig-item:hover:not(.is-running) { + border-color: var(--border-default); +} + +.smig-item.is-selected { + border-color: var(--accent-primary-border); + background: var(--accent-primary-soft); +} + +.smig-item.is-running { + opacity: 0.62; + cursor: not-allowed; +} + +.smig-checkbox { + margin-top: 2px; + flex-shrink: 0; + accent-color: var(--accent-primary); + cursor: inherit; +} + +.smig-item-body { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; + flex: 1; +} + +.smig-item-top { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + min-width: 0; +} + +.smig-item-title { + font-size: var(--fs-sm); + font-weight: 500; + color: var(--text-primary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + flex: 1; +} + +.smig-item-meta { + font-size: var(--fs-xs); + color: var(--text-secondary); + font-variant-numeric: tabular-nums; + white-space: nowrap; + flex-shrink: 0; +} + +.smig-item-sub { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + min-width: 0; +} + +.smig-item-ws { + font-size: var(--fs-xs); + font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); + color: var(--text-muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + flex: 1; +} + +.smig-item-running { + flex-shrink: 0; + padding: 0 5px; + border-radius: var(--radius-xs); + font-size: var(--fs-xs); + font-weight: 600; + color: var(--metric-warn); + background: color-mix(in srgb, var(--metric-warn) 14%, transparent); +} + +.smig-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: var(--space-2); + margin-top: var(--space-3); +} + +.smig-migrate-btn { + display: inline-flex; + align-items: center; + gap: 5px; +} + +.smig-result { + margin-top: var(--space-2); + padding: var(--space-2) var(--space-3); + border-radius: var(--radius-xs); + border: 1px solid var(--border-hairline); + background: var(--surface-subtle); + display: flex; + flex-direction: column; + gap: 6px; +} + +.smig-result[hidden] { + display: none !important; +} + +.smig-result.is-ok { + border-color: color-mix(in srgb, var(--metric-good) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 90%, var(--metric-good) 7%); +} + +.smig-result.is-err { + border-color: color-mix(in srgb, var(--metric-danger) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 90%, var(--metric-danger) 7%); +} + +.smig-result-msg { + font-size: var(--fs-sm); + line-height: 1.45; + color: var(--text-primary); +} + +.smig-result-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.smig-result-btn { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: var(--fs-xs); +} + +.smig-cmd-list { + display: flex; + flex-direction: column; + gap: 4px; +} + +.smig-cmd-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + padding: 4px 6px; + border-radius: var(--radius-xs); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); +} + +.smig-cmd-code { + font-size: var(--fs-xs); + font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); + color: var(--text-primary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + flex: 1; +} + +.smig-cmd-copy { + flex-shrink: 0; + font-size: var(--fs-xs); +} + /* --- Antigravity CLI 底部状态胶囊专属配置块(仅检测到 CLI 时展示) --- */ .cli-statusline-group { display: flex; diff --git a/sidecars/panel/src/views/settings/SettingsOtherTab.js b/sidecars/panel/src/views/settings/SettingsOtherTab.js index f8ba33c..28a2b5e 100644 --- a/sidecars/panel/src/views/settings/SettingsOtherTab.js +++ b/sidecars/panel/src/views/settings/SettingsOtherTab.js @@ -23,6 +23,7 @@ import { } from '../../store/telemetryStore.js'; import { CustomSelect } from '../../components/ui/CustomSelect.js'; import { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js'; +import { SessionMigrationCard } from '../../components/settings/SessionMigrationCard.js'; function getStepModelDisplayOptions() { return [ @@ -597,10 +598,17 @@ export const SettingsOtherTab = defineComponent({ ]), ]); + const sessionMigrationCard = SessionMigrationCard({ + onLayoutChange: () => { + getProps()?.onLayoutChange?.(); + }, + }); + const rootEl = h('div', { className: 'settings-tab-stack' }, [ modelPanel, baselinePanel, maintPanel, + sessionMigrationCard.el, ]); function renderSettings( @@ -631,6 +639,7 @@ export const SettingsOtherTab = defineComponent({ options: getOrchestratorIdDisplayOptions(), }); renderContextWindows(); + void sessionMigrationCard.refs.ensureLoaded(); } function refreshLabels() { @@ -667,6 +676,7 @@ export const SettingsOtherTab = defineComponent({ modelValue: draftOrchestratorIdMode, options: getOrchestratorIdDisplayOptions(), }); + sessionMigrationCard.refs.refreshLabels(); } onCleanup(() => { @@ -678,6 +688,7 @@ export const SettingsOtherTab = defineComponent({ ctxBridgeNotice.destroy(); ctxModelSelect.destroy(); ctxWindowSelect.destroy(); + sessionMigrationCard.destroy(); }); return { @@ -688,6 +699,7 @@ export const SettingsOtherTab = defineComponent({ ctxBridgeNotice, ctxModelSelect, ctxWindowSelect, + sessionMigrationCard, rebuildCacheBtn, resetAllBtn, exportJsonBtn, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index b96d084..6634312 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -5704,6 +5704,334 @@ html[data-standalone="true"] .app-shell { display: none !important; } +/* --- 其他页:跨端会话按需迁移卡片 (.smig-panel) --- */ +.smig-panel[hidden] { + display: none !important; +} + +.smig-desc { + margin: 0 0 var(--space-3); + font-size: var(--fs-sm); + line-height: 1.48; + color: var(--text-secondary); +} + +.smig-refresh-btn { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: var(--fs-xs); +} + +.smig-direction-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-2); + margin-bottom: var(--space-2); +} + +.smig-field { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; + margin-bottom: var(--space-2); +} + +.smig-direction-grid .smig-field { + margin-bottom: 0; +} + +.smig-field[hidden] { + display: none !important; +} + +.smig-field-label { + font-size: var(--fs-xs); + font-weight: 600; + color: var(--text-secondary); +} + +.smig-mode-bar { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 6px; +} + +.smig-mode-btn { + min-height: calc(26px * var(--ui-font-scale, 1)); + padding: 2px 8px; + border-radius: var(--radius-xs); + border: 1px solid var(--border-hairline); + background: var(--surface-subtle); + color: var(--text-secondary); + font-size: var(--fs-xs); + font-weight: 500; + cursor: pointer; + transition: + border-color var(--dur-instant) var(--ease-fast), + background-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast); +} + +.smig-mode-btn:hover { + border-color: var(--border-default); + color: var(--text-primary); +} + +.smig-mode-btn.is-active { + border-color: var(--accent-primary-border); + background: var(--accent-primary-soft); + color: var(--accent-primary); + font-weight: 600; +} + +.smig-mode-hint { + font-size: var(--fs-xs); + line-height: 1.4; + color: var(--text-muted); +} + +.smig-project-select .select-option-meta { + max-width: 58%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.smig-toolbar { + display: flex; + align-items: center; + gap: var(--space-2); + margin-bottom: var(--space-2); +} + +.smig-search-input { + flex: 1; + min-width: 0; +} + +.smig-toggle-all-btn { + flex-shrink: 0; + font-size: var(--fs-xs); +} + +.smig-count-meta { + flex-shrink: 0; + font-size: var(--fs-xs); + color: var(--text-secondary); + font-variant-numeric: tabular-nums; +} + +.smig-list { + display: flex; + flex-direction: column; + gap: 4px; + max-height: 220px; + overflow-y: auto; + padding: 6px; + border-radius: var(--radius-xs); + border: 1px solid var(--border-hairline); + background: var(--surface-subtle); +} + +.smig-empty { + padding: var(--space-4) var(--space-2); + text-align: center; + font-size: var(--fs-sm); + color: var(--text-secondary); +} + +.smig-item { + display: flex; + align-items: flex-start; + gap: 8px; + padding: 6px 8px; + border-radius: var(--radius-xs); + border: 1px solid transparent; + background: var(--surface-panel); + cursor: pointer; + transition: + border-color var(--dur-instant) var(--ease-fast), + background-color var(--dur-instant) var(--ease-fast); +} + +.smig-item:hover:not(.is-running) { + border-color: var(--border-default); +} + +.smig-item.is-selected { + border-color: var(--accent-primary-border); + background: var(--accent-primary-soft); +} + +.smig-item.is-running { + opacity: 0.62; + cursor: not-allowed; +} + +.smig-checkbox { + margin-top: 2px; + flex-shrink: 0; + accent-color: var(--accent-primary); + cursor: inherit; +} + +.smig-item-body { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; + flex: 1; +} + +.smig-item-top { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + min-width: 0; +} + +.smig-item-title { + font-size: var(--fs-sm); + font-weight: 500; + color: var(--text-primary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + flex: 1; +} + +.smig-item-meta { + font-size: var(--fs-xs); + color: var(--text-secondary); + font-variant-numeric: tabular-nums; + white-space: nowrap; + flex-shrink: 0; +} + +.smig-item-sub { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + min-width: 0; +} + +.smig-item-ws { + font-size: var(--fs-xs); + font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); + color: var(--text-muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + flex: 1; +} + +.smig-item-running { + flex-shrink: 0; + padding: 0 5px; + border-radius: var(--radius-xs); + font-size: var(--fs-xs); + font-weight: 600; + color: var(--metric-warn); + background: color-mix(in srgb, var(--metric-warn) 14%, transparent); +} + +.smig-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: var(--space-2); + margin-top: var(--space-3); +} + +.smig-migrate-btn { + display: inline-flex; + align-items: center; + gap: 5px; +} + +.smig-result { + margin-top: var(--space-2); + padding: var(--space-2) var(--space-3); + border-radius: var(--radius-xs); + border: 1px solid var(--border-hairline); + background: var(--surface-subtle); + display: flex; + flex-direction: column; + gap: 6px; +} + +.smig-result[hidden] { + display: none !important; +} + +.smig-result.is-ok { + border-color: color-mix(in srgb, var(--metric-good) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 90%, var(--metric-good) 7%); +} + +.smig-result.is-err { + border-color: color-mix(in srgb, var(--metric-danger) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 90%, var(--metric-danger) 7%); +} + +.smig-result-msg { + font-size: var(--fs-sm); + line-height: 1.45; + color: var(--text-primary); +} + +.smig-result-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.smig-result-btn { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: var(--fs-xs); +} + +.smig-cmd-list { + display: flex; + flex-direction: column; + gap: 4px; +} + +.smig-cmd-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + padding: 4px 6px; + border-radius: var(--radius-xs); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); +} + +.smig-cmd-code { + font-size: var(--fs-xs); + font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); + color: var(--text-primary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; + flex: 1; +} + +.smig-cmd-copy { + flex-shrink: 0; + font-size: var(--fs-xs); +} + /* --- Antigravity CLI 底部状态胶囊专属配置块(仅检测到 CLI 时展示) --- */ .cli-statusline-group { display: flex; diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index 7967a2c..d6c6e22 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -31,6 +31,7 @@ const BACKEND_MODULE_FILES = [ '../backend/proto-wire.mjs', '../backend/cli-sqlite-reader.mjs', '../backend/cli-statusline-config.mjs', + '../backend/session-migrator.mjs', '../backend/ls-discovery.mjs', '../backend/pricing-catalog.mjs', '../backend/plugin-updater.mjs', diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index 62e5ee1..ec14256 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1126,8 +1126,10 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen assert.equal(normalizeI18nLanguage('system'), 'auto'); assert.equal(typeof isEquivalentTelemetry, 'function'); - assert.equal(BRIDGE_API_ROUTE_DEFS.length, 10); + assert.equal(BRIDGE_API_ROUTE_DEFS.length, 12); assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/bridge/relaunch')); + assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/catalog')); + assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/migrate')); // 1. Third-party pool parity across backend, CLI statusline, and frontend metricRegistry const h = backendHarness(); diff --git a/sidecars/panel/test/session-migration.test.mjs b/sidecars/panel/test/session-migration.test.mjs new file mode 100644 index 0000000..c145493 --- /dev/null +++ b/sidecars/panel/test/session-migration.test.mjs @@ -0,0 +1,655 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { DatabaseSync } from 'node:sqlite'; +import { + encodeProtoBytesField, + encodeProtoStringField, + encodeProtoTimestamp, + encodeProtoVarintField, + splitProtoRawFields, +} from '../backend/proto-wire.mjs'; +import { + getSessionMigrationCatalog, + migrateSessions, + migratorParseWorkspaceLabel, + migratorToDesktopEncodedUri, + migratorToRawFileUri, +} from '../backend/session-migrator.mjs'; +import { readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs'; +import { createMockDom } from './mock-dom.mjs'; + +function initSummaryDb(dbPath) { + const db = new DatabaseSync(dbPath); + db.exec(` + CREATE TABLE conversation_summaries ( + conversation_id text PRIMARY KEY, + title text NOT NULL DEFAULT "", + preview text NOT NULL DEFAULT "", + step_count integer NOT NULL DEFAULT 0, + last_modified_time datetime NOT NULL, + workspace_uris text NOT NULL, + status text NOT NULL DEFAULT "", + source text NOT NULL DEFAULT "", + project_id text NOT NULL DEFAULT "", + agent_name text NOT NULL DEFAULT "", + parent_conversation_id text NOT NULL DEFAULT "", + nesting_depth integer NOT NULL DEFAULT 0, + battle_id text NOT NULL DEFAULT "", + winning_conversation_id text NOT NULL DEFAULT "", + not_fully_idle numeric NOT NULL DEFAULT false, + killed numeric NOT NULL DEFAULT false, + last_user_input_time datetime NOT NULL, + last_user_input_step_index integer NOT NULL DEFAULT -1, + app_data_dir text NOT NULL DEFAULT "", + raw_summary blob, + group_id text NOT NULL DEFAULT "" + ); + `); + return db; +} + +function createConvDb(dbPath, { cid, tid, source = 17, projectId = 'default-cli-project', wsUri = 'file:///C:/Users/Test', promptText = 'hello from cli', stepCount = 2, preserveTag15 = true }) { + const db = new DatabaseSync(dbPath); + db.exec(` + CREATE TABLE trajectory_meta ( + trajectory_id text PRIMARY KEY, + cascade_id text, + trajectory_type integer, + source integer + ); + CREATE TABLE steps ( + idx integer PRIMARY KEY, + step_type integer NOT NULL DEFAULT 0, + status integer NOT NULL DEFAULT 0, + has_subtrajectory numeric NOT NULL DEFAULT false, + metadata blob, + error_details blob, + permissions blob, + task_details blob, + render_info blob, + step_payload blob, + step_format integer NOT NULL DEFAULT 0 + ); + CREATE TABLE gen_metadata ( + idx integer PRIMARY KEY, + data blob, + size integer NOT NULL DEFAULT 0 + ); + CREATE TABLE executor_metadata (idx integer PRIMARY KEY, data blob); + CREATE TABLE parent_references (idx integer PRIMARY KEY, data blob); + CREATE TABLE trajectory_metadata_blob (id text PRIMARY KEY DEFAULT "main", data blob); + CREATE TABLE battle_mode_infos (idx integer PRIMARY KEY, data blob); + `); + + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 4, ?)').run(tid, cid, source); + + const wsSub = Buffer.concat([encodeProtoStringField(1, wsUri), encodeProtoStringField(3, '')]); + const metaParts = [ + encodeProtoBytesField(1, wsSub), + encodeProtoBytesField(2, encodeProtoTimestamp(1795000000000)), + encodeProtoStringField(6, cid), + encodeProtoStringField(7, wsUri), + encodeProtoStringField(18, projectId), + ]; + if (preserveTag15) { + metaParts.push(encodeProtoBytesField(15, Buffer.from([0xde, 0xad, 0xbe, 0xef]))); + } + db.prepare("INSERT INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run( + Buffer.concat(metaParts) + ); + + for (let i = 0; i < stepCount; i++) { + const isUser = i % 2 === 0; + const srcInfo = Buffer.concat([ + encodeProtoStringField(1, tid), + encodeProtoVarintField(2, i), + encodeProtoStringField(4, cid), + ]); + const stepMeta = encodeProtoBytesField(20, srcInfo); + const stepPayload = isUser + ? encodeProtoBytesField(19, encodeProtoStringField(2, promptText)) + : encodeProtoBytesField(20, encodeProtoStringField(1, 'ok reply')); + db.prepare( + 'INSERT INTO steps (idx, step_type, status, metadata, step_payload) VALUES (?, ?, 3, ?, ?)' + ).run(i, isUser ? 14 : 15, stepMeta, stepPayload); + } + db.close(); +} + +test('Cross-client session migration clones CLI/Legacy-IDE/Desktop SQLite sessions safely with fork dedup and rolling backups', () => { + const tempRoot = mkdtempSync(join(tmpdir(), 'ag-mig-test-')); + const geminiDir = join(tempRoot, '.gemini'); + const backupDir = join(tempRoot, 'backups'); + + try { + // URI helper checks + assert.equal( + migratorToRawFileUri('file:///f%3A/ppt/1111/antigravity-usage-monitor'), + 'file:///f:/ppt/1111/antigravity-usage-monitor' + ); + assert.equal( + migratorToDesktopEncodedUri('file:///F:/ppt/1111/antigravity-usage-monitor'), + 'file:///f%3A/ppt/1111/antigravity-usage-monitor' + ); + assert.deepEqual( + migratorParseWorkspaceLabel('file:///f%3A/ppt/1111/antigravity-usage-monitor'), + { name: 'antigravity-usage-monitor', displayPath: 'f:/ppt/1111/antigravity-usage-monitor' } + ); + + // 1. Single client only -> available must be false + const deskRoot = join(geminiDir, 'antigravity'); + mkdirSync(join(deskRoot, 'conversations'), { recursive: true }); + mkdirSync(join(deskRoot, 'annotations'), { recursive: true }); + mkdirSync(join(deskRoot, 'brain'), { recursive: true }); + + const deskCid = '11111111-1111-4111-8111-111111111111'; + const deskTid = '11111111-1111-4111-8111-111111111112'; + const projId = '99a28d35-a873-4c32-b8d1-81a62e23c33d'; + const projWsEnc = 'file:///f%3A/ppt/1111/antigravity-usage-monitor'; + + createConvDb(join(deskRoot, 'conversations', `${deskCid}.db`), { + cid: deskCid, + tid: deskTid, + source: 1, + projectId: projId, + wsUri: 'file:///f:/ppt/1111/antigravity-usage-monitor', + promptText: 'desktop session prompt', + stepCount: 4, + }); + writeFileSync(join(deskRoot, 'annotations', `${deskCid}.pbtxt`), 'title:"Desktop Main Chat"\n', 'utf8'); + + const deskSum = initSummaryDb(join(deskRoot, 'conversation_summaries.db')); + deskSum + .prepare( + `INSERT INTO conversation_summaries ( + conversation_id, title, preview, step_count, last_modified_time, + workspace_uris, status, source, project_id, last_user_input_time, + last_user_input_step_index, app_data_dir, raw_summary + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ) + .run( + deskCid, + 'Desktop Main Chat', + 'Desktop Main Chat', + 4, + '2026-11-21 10:00:00.000000+00:00', + JSON.stringify([projWsEnc]), + 'CASCADE_RUN_STATUS_IDLE', + '', + projId, + '2026-11-21 09:59:00.000000+00:00', + 2, + 'antigravity', + Buffer.concat([ + encodeProtoStringField(1, 'Desktop Main Chat'), + encodeProtoVarintField(2, 4), + encodeProtoStringField(4, deskTid), + encodeProtoVarintField(5, 1), + encodeProtoVarintField(22, 4), + ]) + ); + deskSum.close(); + + const singleCat = getSessionMigrationCatalog({ geminiDir }); + assert.equal(singleCat.available, false, 'Single client hides migration feature'); + + // 2. Add CLI client (1 idle untitled, 1 running, 1 subagent, 1 empty 0-step) + Legacy IDE client + const cliRoot = join(geminiDir, 'antigravity-cli'); + mkdirSync(join(cliRoot, 'conversations'), { recursive: true }); + mkdirSync(join(cliRoot, 'annotations'), { recursive: true }); + mkdirSync(join(cliRoot, 'brain'), { recursive: true }); + + const cliIdleCid = '22222222-2222-4222-8222-222222222221'; + const cliRunCid = '22222222-2222-4222-8222-222222222222'; + const cliSubCid = '22222222-2222-4222-8222-222222222223'; + const cliEmptyCid = '22222222-2222-4222-8222-222222222224'; + + createConvDb(join(cliRoot, 'conversations', `${cliIdleCid}.db`), { + cid: cliIdleCid, + tid: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1', + source: 17, + promptText: 'Fix Braille progress bar width', + stepCount: 6, + }); + mkdirSync(join(cliRoot, 'brain', cliIdleCid, '.user_uploaded'), { recursive: true }); + writeFileSync(join(cliRoot, 'brain', cliIdleCid, '.user_uploaded', 'shot.png'), 'pngdata', 'utf8'); + + createConvDb(join(cliRoot, 'conversations', `${cliRunCid}.db`), { + cid: cliRunCid, + tid: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2', + source: 17, + stepCount: 4, + }); + createConvDb(join(cliRoot, 'conversations', `${cliSubCid}.db`), { + cid: cliSubCid, + tid: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa3', + source: 17, + stepCount: 2, + }); + createConvDb(join(cliRoot, 'conversations', `${cliEmptyCid}.db`), { + cid: cliEmptyCid, + tid: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa4', + source: 17, + stepCount: 0, + }); + + const cliSum = initSummaryDb(join(cliRoot, 'conversation_summaries.db')); + const insertCliSum = cliSum.prepare( + `INSERT INTO conversation_summaries ( + conversation_id, title, preview, step_count, last_modified_time, + workspace_uris, status, source, project_id, parent_conversation_id, + nesting_depth, not_fully_idle, killed, last_user_input_time, + last_user_input_step_index, app_data_dir, raw_summary + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ); + insertCliSum.run( + cliIdleCid, + '', + '', + 6, + '2026-11-21 12:00:00.000000+00:00', + '["file:///C:/Users/Administrator"]', + 'CASCADE_RUN_STATUS_IDLE', + '', + 'default-cli-project', + '', + 0, + 0, + 0, + '2026-11-21 11:58:00.000000+00:00', + 4, + 'antigravity-cli', + Buffer.concat([ + encodeProtoVarintField(2, 6), + encodeProtoStringField(4, 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1'), + encodeProtoVarintField(5, 1), + encodeProtoVarintField(20, 17), // CLI source tag that must be stripped + encodeProtoVarintField(22, 4), + ]) + ); + insertCliSum.run( + cliRunCid, + 'Active CLI Task', + 'Active CLI Task', + 4, + '2026-11-21 12:05:00.000000+00:00', + '["file:///C:/Users/Administrator"]', + 'CASCADE_RUN_STATUS_RUNNING', + '', + 'default-cli-project', + '', + 0, + 1, + 0, + '2026-11-21 12:04:00.000000+00:00', + 2, + 'antigravity-cli', + null + ); + insertCliSum.run( + cliSubCid, + 'Subagent Child', + '', + 2, + '2026-11-21 11:50:00.000000+00:00', + '["file:///C:/Users/Administrator"]', + 'CASCADE_RUN_STATUS_IDLE', + '', + 'default-cli-project', + cliIdleCid, + 1, + 0, + 0, + '2026-11-21 11:50:00.000000+00:00', + 0, + 'antigravity-cli', + null + ); + insertCliSum.run( + cliEmptyCid, + '', + '', + 0, + '0001-01-01 00:00:00+00:00', + '["file:///C:/Users/Administrator"]', + 'CASCADE_RUN_STATUS_IDLE', + '', + 'default-cli-project', + '', + 0, + 0, + 0, + '0001-01-01 00:00:00+00:00', + -1, + 'antigravity-cli', + null + ); + cliSum.close(); + + // Legacy IDE (.db without conversation_summaries.db) + const legacyRoot = join(geminiDir, 'antigravity-ide'); + mkdirSync(join(legacyRoot, 'conversations'), { recursive: true }); + const legacyCid = '33333333-3333-4333-8333-333333333331'; + createConvDb(join(legacyRoot, 'conversations', `${legacyCid}.db`), { + cid: legacyCid, + tid: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1', + source: 1, + projectId: '', + wsUri: 'file:///e:/legacy-app', + promptText: 'Refactor legacy sidebar', + stepCount: 4, + }); + + const cat = getSessionMigrationCatalog({ geminiDir }); + assert.equal(cat.available, true, 'Multi-client setup exposes migration catalog'); + assert.equal(cat.sessionsByClient.cli.length, 2, 'Excludes subagent and 0-step empty CLI sessions'); + const idleItem = cat.sessionsByClient.cli.find((s) => s.cascadeId === cliIdleCid); + const runItem = cat.sessionsByClient.cli.find((s) => s.cascadeId === cliRunCid); + assert.equal(idleItem.title, 'Fix Braille progress bar width', 'Falls back to cleaned first user prompt title'); + assert.equal(idleItem.isRunning, false); + assert.equal(runItem.isRunning, true); + assert.equal(cat.sessionsByClient.ide_legacy.length, 1); + assert.equal(cat.sessionsByClient.ide_legacy[0].title, 'Refactor legacy sidebar'); + assert.ok(cat.desktopProjects.some((p) => p.projectId === projId && p.name === 'antigravity-usage-monitor')); + assert.ok(cat.desktopProjects.some((p) => p.projectId === 'outside-of-project' && p.isOutsideProject)); + + // 3. Default FULL MOVE mode: CLI -> Desktop (1 idle + 1 running -> idle moves with original UUID & ALL historical steps!) + const migRes = migrateSessions( + { + sourceClient: 'cli', + targetClient: 'desktop', + cascadeIds: [cliIdleCid, cliRunCid], + targetProjectId: projId, + }, + { geminiDir, backupDir } + ); + assert.equal(migRes.ok, true); + assert.equal(migRes.mode, 'move'); + assert.equal(migRes.migratedCount, 1); + assert.equal(migRes.failedCount, 1); + assert.equal(migRes.needsWindowReload, true); + assert.ok(migRes.backupPath && existsSync(migRes.backupPath), 'Creates backup before modifying target summary DB'); + + const okItem = migRes.results.find((r) => r.ok); + const runErr = migRes.results.find((r) => !r.ok); + assert.equal(runErr.error, 'session_running'); + assert.equal(okItem.newCascadeId, cliIdleCid, 'Full move preserves original cascadeId so historical steps stay intact'); + assert.ok( + okItem.archivedSourcePath && existsSync(okItem.archivedSourcePath), + 'Archives source DB snapshot before removing from source client' + ); + + // Verify source CLI .db removed & summary deleted, while brain media remains readable + assert.equal(existsSync(join(cliRoot, 'conversations', `${cliIdleCid}.db`)), false); + assert.ok(existsSync(join(cliRoot, 'brain', cliIdleCid, '.user_uploaded', 'shot.png'))); + const checkCliSumDb = new DatabaseSync(join(cliRoot, 'conversation_summaries.db'), { readOnly: true }); + assert.equal( + checkCliSumDb + .prepare('SELECT count(*) as c FROM conversation_summaries WHERE conversation_id = ?') + .get(cliIdleCid).c, + 0, + 'Removes moved session from source client summary DB' + ); + checkCliSumDb.close(); + + // Verify moved Desktop artifacts + const movedDbPath = join(deskRoot, 'conversations', `${okItem.newCascadeId}.db`); + assert.ok(existsSync(movedDbPath)); + assert.ok(existsSync(join(deskRoot, 'brain', okItem.newCascadeId, '.user_uploaded', 'shot.png'))); + const annText = readFileSync(join(deskRoot, 'annotations', `${okItem.newCascadeId}.pbtxt`), 'utf8'); + assert.ok(annText.includes('Fix Braille progress bar width')); + + // Inspect moved DB metadata & unknown field 15 preservation + const movedDb = new DatabaseSync(movedDbPath, { readOnly: true }); + const metaRow = movedDb.prepare('SELECT * FROM trajectory_meta').get(); + assert.equal(metaRow.cascade_id, cliIdleCid); + assert.equal(metaRow.trajectory_id, 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1'); + assert.equal(metaRow.source, 1); + const blobRow = movedDb.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get(); + const blobFields = splitProtoRawFields(blobRow.data); + assert.equal(blobFields.find((f) => f.fn === 6)?.payload.toString('utf8'), cliIdleCid); + assert.equal(blobFields.find((f) => f.fn === 7)?.payload.toString('utf8'), projWsEnc); + assert.equal(blobFields.find((f) => f.fn === 18)?.payload.toString('utf8'), projId); + assert.deepEqual( + blobFields.find((f) => f.fn === 15)?.payload, + Buffer.from([0xde, 0xad, 0xbe, 0xef]), + 'Preserves unknown protobuf fields byte-for-byte' + ); + movedDb.close(); + + // Verify ALL historical steps (#0..#5, including #1/#3/#5 planner responses) are preserved in telemetry! + const decodedMoved = readLocalSqliteTrajectory(movedDbPath, { cascadeId: cliIdleCid }); + assert.ok(decodedMoved, 'Moved session decodes cleanly via cli-sqlite-reader'); + assert.equal(decodedMoved.numTotalSteps, 6, 'All 6 historical steps (#0..#5) stay intact after full move'); + assert.deepEqual( + decodedMoved.steps.map((s) => s.idx), + [0, 1, 2, 3, 4, 5], + 'Historical step numbering remains continuous without jumping' + ); + + // Verify target summary DB row & stripped fn 20 CLI source tag + const checkSumDb = new DatabaseSync(join(deskRoot, 'conversation_summaries.db'), { readOnly: true }); + const sumRow = checkSumDb + .prepare('SELECT * FROM conversation_summaries WHERE conversation_id = ?') + .get(cliIdleCid); + assert.equal(sumRow.project_id, projId); + assert.equal(sumRow.source, ''); + assert.equal(sumRow.app_data_dir, 'antigravity'); + assert.equal(sumRow.workspace_uris, JSON.stringify([projWsEnc])); + const rawSumFields = splitProtoRawFields(sumRow.raw_summary); + assert.equal(rawSumFields.some((f) => f.fn === 20), false, 'Strips CLI source enum from raw_summary'); + checkSumDb.close(); + + // 4. Optional CLONE mode: Desktop -> CLI (fresh UUID, source untouched, zero double-billing) + const revRes = migrateSessions( + { + sourceClient: 'desktop', + targetClient: 'cli', + mode: 'clone', + cascadeIds: [deskCid], + }, + { geminiDir, backupDir } + ); + assert.equal(revRes.ok, true); + assert.equal(revRes.mode, 'clone'); + assert.equal(revRes.needsWindowReload, false); + const cliClone = revRes.results[0]; + assert.notEqual(cliClone.newCascadeId, deskCid, 'Clone mode assigns fresh UUID'); + assert.ok(existsSync(join(deskRoot, 'conversations', `${deskCid}.db`)), 'Clone mode leaves source untouched'); + assert.equal(cliClone.resumeCommand, `agy --conversation ${cliClone.newCascadeId}`); + const cliCloneDbPath = join(cliRoot, 'conversations', `${cliClone.newCascadeId}.db`); + const cliCloneDb = new DatabaseSync(cliCloneDbPath, { readOnly: true }); + assert.equal(cliCloneDb.prepare('SELECT source FROM trajectory_meta').get().source, 17); + cliCloneDb.close(); + assert.equal( + readLocalSqliteTrajectory(cliCloneDbPath, { cascadeId: cliClone.newCascadeId }), + null, + 'Clone mode deduplicates cloned historical steps so global billing never double-counts' + ); + + // 5. Legacy IDE (no summary DB) -> Desktop App in clone mode synthesizes valid raw_summary + const legRes = migrateSessions( + { + sourceClient: 'ide_legacy', + targetClient: 'desktop', + mode: 'clone', + cascadeIds: [legacyCid], + targetProjectId: 'outside-of-project', + }, + { geminiDir, backupDir } + ); + assert.equal(legRes.ok, true); + const legSumDb = new DatabaseSync(join(deskRoot, 'conversation_summaries.db'), { readOnly: true }); + const legSumRow = legSumDb + .prepare('SELECT project_id, title, raw_summary FROM conversation_summaries WHERE conversation_id = ?') + .get(legRes.results[0].newCascadeId); + assert.equal(legSumRow.project_id, 'outside-of-project'); + assert.equal(legSumRow.title, 'Refactor legacy sidebar'); + assert.ok(legSumRow.raw_summary.byteLength > 20); + legSumDb.close(); + + // 6. Rolling backups stay capped at <= 5 + for (let k = 0; k < 6; k++) { + migrateSessions( + { + sourceClient: 'ide_legacy', + targetClient: 'desktop', + mode: 'clone', + cascadeIds: [legacyCid], + targetProjectId: 'outside-of-project', + }, + { geminiDir, backupDir } + ); + } + const deskBackups = readdirSync(backupDir).filter( + (n) => n.startsWith('conversation_summaries_desktop_') && n.endsWith('.db') + ); + assert.ok(deskBackups.length <= 5, `Rolling backup cap enforced (got ${deskBackups.length})`); + } finally { + rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('SessionMigrationCard stays hidden for single-client hosts and renders multi-select migration workflow', async () => { + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const { document: doc } = createMockDom(); + globalThis.document = doc; + globalThis.window = { document: doc }; + + try { + const { SessionMigrationCard } = await import( + '../src/components/settings/SessionMigrationCard.js' + ); + + // 1. Single client -> hidden + const hiddenCard = SessionMigrationCard({ + loadCatalog: async () => ({ + available: false, + clients: [{ id: 'desktop', exists: true, canBeTarget: true, sessionCount: 5 }], + sessionsByClient: { desktop: [] }, + desktopProjects: [], + }), + }); + assert.equal(hiddenCard.el.hasAttribute('hidden'), true); + await hiddenCard.refs.ensureLoaded(); + assert.equal(hiddenCard.el.hasAttribute('hidden'), true); + hiddenCard.destroy(); + + // 2. Multi-client -> visible, selects CLI session, migrates to Desktop project + let capturedPayload = null; + const card = SessionMigrationCard({ + loadCatalog: async () => ({ + available: true, + clients: [ + { id: 'desktop', exists: true, canBeSource: true, canBeTarget: true, sessionCount: 2 }, + { id: 'cli', exists: true, canBeSource: true, canBeTarget: true, sessionCount: 2 }, + ], + sessionsByClient: { + cli: [ + { + cascadeId: '22222222-2222-4222-8222-222222222221', + title: 'CLI Debug Session', + stepCount: 12, + lastModifiedMs: Date.now() - 120000, + workspaceName: 'Administrator', + workspacePath: 'C:/Users/Administrator', + isRunning: false, + }, + { + cascadeId: '22222222-2222-4222-8222-222222222222', + title: 'Live Active Session', + stepCount: 4, + lastModifiedMs: Date.now(), + workspaceName: 'Administrator', + workspacePath: 'C:/Users/Administrator', + isRunning: true, + }, + ], + desktop: [], + }, + desktopProjects: [ + { + projectId: '99a28d35-a873-4c32-b8d1-81a62e23c33d', + name: 'antigravity-usage-monitor', + workspaceUri: 'file:///f%3A/ppt/1111/antigravity-usage-monitor', + workspacePath: 'f:/ppt/1111/antigravity-usage-monitor', + }, + { + projectId: 'outside-of-project', + name: '', + isOutsideProject: true, + }, + ], + }), + runMigrate: async (payload) => { + capturedPayload = payload; + return { + ok: true, + sourceClient: payload.sourceClient, + targetClient: payload.targetClient, + targetProjectId: payload.targetProjectId, + migratedCount: payload.cascadeIds.length, + failedCount: 0, + needsWindowReload: true, + results: [ + { + ok: true, + sourceCascadeId: payload.cascadeIds[0], + newCascadeId: '99999999-9999-4999-8999-999999999999', + title: 'CLI Debug Session', + }, + ], + }; + }, + }); + + await card.refs.ensureLoaded(); + assert.equal(card.el.hasAttribute('hidden'), false, 'Card becomes visible when >=2 clients detected'); + + const rows = card.el.querySelectorAll('.smig-item'); + assert.equal(rows.length, 2); + const migrateBtn = card.el.querySelector('.smig-migrate-btn'); + assert.equal(migrateBtn.hasAttribute('disabled'), true); + + // Clicking running session does not select it + rows[1].dispatchEvent({ type: 'click', target: rows[1] }); + assert.equal(migrateBtn.hasAttribute('disabled'), true); + + // Clicking idle session selects it and enables Migrate button + rows[0].dispatchEvent({ type: 'click', target: rows[0] }); + assert.equal(migrateBtn.hasAttribute('disabled'), false); + + // Trigger migration (defaults to full move mode) + await migrateBtn.dispatchEvent({ type: 'click', target: migrateBtn }); + await new Promise((r) => setTimeout(r, 10)); + assert.deepEqual(capturedPayload, { + sourceClient: 'cli', + targetClient: 'desktop', + mode: 'move', + cascadeIds: ['22222222-2222-4222-8222-222222222221'], + targetProjectId: '99a28d35-a873-4c32-b8d1-81a62e23c33d', + }); + + // Switch to clone mode and verify payload reflects mode: 'clone' + const modeBtns = card.el.querySelectorAll('.smig-mode-btn'); + assert.equal(modeBtns.length, 2); + modeBtns[1].dispatchEvent({ type: 'click', target: modeBtns[1] }); + const rows2 = card.el.querySelectorAll('.smig-item'); + rows2[0].dispatchEvent({ type: 'click', target: rows2[0] }); + await migrateBtn.dispatchEvent({ type: 'click', target: migrateBtn }); + await new Promise((r) => setTimeout(r, 10)); + assert.equal(capturedPayload.mode, 'clone'); + + const resultBox = card.el.querySelector('.smig-result'); + assert.equal(resultBox.hasAttribute('hidden'), false); + assert.ok(resultBox.textContent.includes('Ctrl+R')); + card.destroy(); + } finally { + globalThis.document = prevDoc; + globalThis.window = prevWin; + } +});