feat(panel): add opt-in cross-client session migration for CLI, Desktop App, and Legacy IDE

This commit is contained in:
fish
2026-11-21 23:19:15 +09:00
parent 3eb9e0e2a5
commit 0769a88796
17 changed files with 4681 additions and 5 deletions
+868 -2
View File
@@ -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,