mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-17 13:01:24 +00:00
* feat(plugins): add sync providers and encrypted sidecar sync
Implement PR 8 of the plugin platform (#2269): namespaced sync Providers
with provider.sync, encrypted-object storage operations, WebDAV through the
shared storage surface, dynamic cloud provider IDs, and non-cascade sidecars
for sync:true plugin settings plus account/CRDT baselines.
Related to #2269
* fix(plugins): wire sync providers and sidecars into production paths
Close PR 8 integration gaps: dynamic plugin provider registry and
getConnectedAdapter createPluginStorage, WebDAV through EncryptedObjectStorage,
cloud payload collect/apply for pluginSidecars, and IPC/preload bridges.
Related to #2269
* fix(plugins): preserve WebDAV auth reuse and resourceId through EOS wrap
encryptedObjectStorageAsCloudAdapter now reports initiallyAuthenticated when
config exists (matching raw WebDAVAdapter) so getConnectedAdapter reuses the
cached instance, and preserves/refreshes resourceId from the backing adapter
instead of always forcing the default object key.
Related to #2269
* fix(plugins): address Codex PR 8 review findings
Carry pluginSidecars through merge/convergent uploads, lazy-connect before
object I/O with revision-aware writes, fail closed on sidecar collect errors,
expose connectPluginProvider, preserve remote timestamps, and drop deleted
installed-plugin settings from collection.
Related to #2269
* fix(plugins): close remaining Codex P1/P2 sync issues
Lazy stream cancel for inline sync reads, must-not-exist conditional writes,
three-way sidecar merge for local resets, validated apply path for settings,
and merge remote sidecars into convergent uploads.
Related to #2269
* fix(plugins): harden sidecar collect/apply and write verification
Preserve last-known sidecars when the host is offline, apply remote
deletions for installed plugins, force convergent upload on sidecar
divergence, verify plugin object writes, and pick plugin providers in
auto-sync startup checks.
Related to #2269
* fix(plugins): close remaining Codex sidecar/sync path gaps
Include sidecars in auto-sync payload and hash, keep explicit empty bundles,
fail apply when host is offline, require getCapabilities, and carry merged
sidecars into convergent local apply/upload decisions.
Related to #2269
* fix(plugins): close Codex P1 sidecar collect/apply/merge gaps
Treat null host responses as unavailable, persist collected settings into
the non-cascade table, retain decoded convergent payloads, use three-way
sidecar merge for deletions, and fail apply only on operational errors.
Also treat non-empty plugin sidecars as meaningful sync data and re-run
auto-sync when plugin contributions change.
Related to #2269
* fix(plugins): close remaining Codex P1 sidecar and provider gaps
Replay offline-cached sidecars before collect, keep explicit empty
sidecar fields after three-way merge, thread sidecars through convergent
conflict/downgrade materialization, keep gated-off plugin providers from
joining sync as connected, and rebind plugin EOS sessions after runtime
replacement.
Related to #2269
* fix(plugins): separate pending remote sidecars from last-known cache
Replay only host-offline remote applies into the DB, keep last-known as
upload fallback, use contribution reset for deleted settings, probe real
plugin host readiness, rebind storage events for plugin providers, clear
plugin bases on reset, and swallow disconnect rejections.
Related to #2269
* fix(plugins): hydrate retained sidecars and gate missing providers
Materialize installed-plugin settings from retained sidecars before
collect pruning, clear sidecars on setting reset, fail closed when
pending remote replay fails, and only restore plugin providers that are
contribution-available. Also initialize dynamic provider counters on
connect.
Related to #2269
* fix(plugins): surface plugin sync providers and preserve conflict sidecars
Collect live sidecars before convergent conflict apply/upload, include
dynamic providers in status and disconnect paths, and list plugin sync
providers in Cloud Sync settings for connect/disconnect.
Related to #2269
* fix(plugins): per-provider sidecar baselines and safer collect/UI
Merge convergent sidecars against each provider's own baseline, keep
retained settings in sidecars without unvalidated plugin_settings writes,
guard isConnectDisabled for never-connected plugins, and fall back plugin
provider labels/icons in the status popup.
Related to #2269
* fix(plugins): correct plugin provider discovery and sidecar reverify
Read nested contribution metadata for sync provider cards, gate empty-config
connects, enforce single-provider disconnect for plugins, and re-verify after
sidecar-only convergent uploads so baselines track the post-write payload.
Related to #2269
* fix(plugins): refresh sync provider availability from live contributions
Replace the contribution-available provider ID set when plugins change so
disabled or uninstalled sync providers leave the auto-sync ready set and
drop to disconnected with config retained.
Related to #2269
* fix(plugins): preserve sidecars in backups, pending queue, and migration
Attach last-known plugin sidecars to protective local vault backups, fail
operationally when pending/last-known storage writes are rejected, carry
sidecars through convergent migration publish, and reject trailing garbage
on encrypted object parse.
Related to #2269
* fix(plugins): abort conflict collect failures and merge migration sidecars
Rethrow operational sidecar collection errors during convergent conflict
resolution, LWW-union all local/provider sidecars during convergent
migration, re-collect last-known after apply, and prefer live host collect
for protective local vault backups.
Related to #2269
* fix(plugins): restore pluginBridge tests, fix import path, union downgrade sidecars
Correct SettingsSyncTab dynamic import path so production builds resolve,
add ipcMain.on to the plugin bridge test double, union all provider
sidecars on convergent downgrade, keep empty last-known resets, and skip
force-delete when contribution reset validation rejects.
Related to #2269
* fix(plugins): abort backup collect failures and honor empty remote wipes
Only fall back to last-known sidecars when the host is unavailable during
protective backups, treat explicit empty remote sidecar bundles as
authoritative wipes, remove lint-blocking anys from harness tests, and
use a stable equal-timestamp sidecar tie-break.
Related to #2269
* fix(plugins): include sidecars in equality, preserve merge base on reconnect
Compare pluginSidecars in cloudSyncPayloadsEqual for migration freshness,
clear plugin merge state only when account/resource changes on reconnect,
cancel accepted sync read streams on failure, and stop re-connecting the
plugin EOS adapter on every I/O.
Related to #2269
* fix(plugins): drop cached adapters on contribution refresh
Invalidate plugin sync adapters when live contributions change so a
restarted runtime gets a fresh connect, take offline any non-disconnected
missing providers, and latch version-change backups only after cancellation
checks pass.
Related to #2269
* fix(plugins): preserve omitted sidecars and hydrate on plugin enable
Treat missing pluginSidecars as legacy/unsupported in three-way merge
(only explicit empty is a wipe), hydrate retained settings when a plugin
enables, and re-enable retained provider configs when contributions return.
Related to #2269
* fix(plugins): keep newer retained sidecars over older stored settings
When collection merges existing sidecars with plugin_settings rows, prefer
the newer updatedAt so a schema-rejected remote value retained only in
the sidecar table is not overwritten by a stale local setting.
Related to #2269
* fix(plugins): seal plugin provider config and clear base on config change
Encrypt opaque plugin provider configuration before persistence, clear
merge state when reconnect configuration changes, and stream sync objects
below a base64-safe inline threshold so control-plane JSON stays in budget.
Related to #2269
* fix(plugins): seal plugin configs by provider id and hydrate before start
Encrypt plugin provider configuration only for non-builtin provider IDs
so field-name collisions cannot skip sealing, hydrate retained sidecars
before plugin enable starts the runtime, and stop tearing down live
adapters on no-op availability refreshes.
Related to #2269
* fix(plugins): seal scalar configs, safe inline reads, stable config fingerprint
Encrypt any non-builtin plugin configuration JSON shape, enforce the
base64-safe inline read cutoff, and compare reconnect configurations with
order-independent fingerprints so merge bases are not cleared spuriously.
Related to #2269
* fix(plugins): thread sync credentials and harden availability checks
Pass SyncConnectPayload.credential through the object-storage and IPC host
path, treat only null/undefined config as missing, and avoid wiping the
plugin provider availability catalog on transient discovery failures.
Related to #2269
* fix(plugins): unblock schema-required sync connect and scalar configs
Add a JSON config dialog for plugin sync providers that declare a
required configurationSchema, reuse retained configs on reconnect, and
treat falsy scalar configs as present in readiness and adapter lookup.
Related to #2269
* fix(plugins): rebind sync adapters on contribution refresh
Drop cached plugin sync adapters when live contributions still include
the provider so replaced runtimes get a fresh connect, and seal falsy
scalar plugin configs with nullish presence checks end-to-end.
Related to #2269
* fix(plugins): apply sidecars under current declared setting scopes
When a plugin update changes a syncable setting scope, write under the
live declaration and drop the obsolete scope row so collection does not
republish duplicates.
Related to #2269
* fix(plugins): seal config envelopes and stabilize provider counters
Use an unambiguous host-owned sealed-config envelope, initialize
dynamic-provider sequence counters before cross-window decrypt, keep
three-way sidecar deletions during convergent migration, and create the
sidecar table for existing schema-1 plugin databases.
Related to #2269
* fix(plugins): avoid mid-sync adapter drops and sidecar resurrection
Keep plugin adapters across setting-only contribution refreshes and
rebind sessions on ensureConnected; stop preserving local-only missing
plugin sidecars when remote already mentions the plugin; compare configs
with nullish semantics across windows; swallow quick-connect failures
after toasting.
Related to #2269
* fix(plugins): restore remoteKeys for installed sidecar resets
Reintroduce the remote key set used when dropping installed-plugin
settings the remote no longer carries so applyFromSync cannot throw
after replacing the sidecar table.
Related to #2269
* fix(plugins): honor conflict policy and re-key scoped sidecars
Pass preferCloud/preferLocal into three-way sidecar merge, use
per-provider baselines on convergent downgrade so local resets are not
resurrected, and re-key applied settings under the current declared
scope coordinates.
Related to #2269
* fix(plugins): keep strategy on final sidecar merge and block dual legacy
Pass preferCloud/preferLocal through the final verified sidecar merge,
avoid auto-reactivating a retained plugin while another legacy provider
is already connected, cache plugin adapters only after initializeSync,
and preserve explicit null configuration values.
Related to #2269
* fix(plugins): strip plugin avatars and protect last-known sidecars
Do not load plugin-supplied avatar URLs in the main renderer, and avoid
overwriting last-known sidecars with an unmerged remote bundle when the
post-apply collect fails or is non-authoritative.
Related to #2269
* fix(plugins): strip top-bar plugin avatars and stop always-rebind
Hide plugin avatar URLs in the sync status popover, drop always-on
rebindSession for plugin adapters, and read convergent mode from the
local config module when deciding whether to auto-reactivate providers.
Related to #2269
* fix(plugins): use window.netcatty for sync IPC and allow null configs
Read plugin sync and sidecar APIs from the production preload global,
and treat an explicit config property (including JSON null) as present
for readiness and adapter lookup.
Related to #2269
* fix(plugins): close residual Codex P2 sync edge cases
Three-way merge sidecars during v2 convergent migration so local
resets are not resurrected, preserve explicit null plugin configs on
adapter rebuild, rebind EOS sessions after I/O failure for replaced
runtimes, and accept the public inlineObjectBytes limit on readObject.
Related to #2269
* fix(plugins): keep inline read cutoff under control-plane budget
Restore the base64-safe inline cutoff so advertised-size reads cannot
overflow the 128 KiB provider JSON envelope; providers near the public
inlineObjectBytes limit must stream.
Related to #2269
* fix(plugins): harden sidecar empty-vault, hydrate LWW, and credential seals
Close remaining Codex/review gaps for PR8: keep empty sidecar shells from
bypassing upload guards, skip startup hydrate when local settings are newer,
seal/validate durable plugin credential refs, and cover schema 1→2 migration.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): rebind plugin sync sessions and keep null configs
Address Codex P2 on 8ae52c54: re-issue connect after runtime replacement,
and treat stored config:null as present in the dashboard reconnect path.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): defer empty sidecar last-known until sync succeeds
Keep prior non-empty last-known across an authoritative empty collect so the
empty-vault guard can still recognize a plugin-only reset, then commit the
empty cache after a successful upload.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): avoid restricted localStorage global in sidecar test
Bind the mock to a local binding so eslint no-restricted-globals stays clean.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): commit applied sidecar cache and reset orphan settings
Prefer merged payload sidecars when updating last-known after sync, and clear
syncable plugin_settings that lack sidecar rows on authoritative remote deletes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): reseal marker-shaped plugin configs instead of skipping
Exact __netcatty_plugin_config_v1 collisions no longer bypass encryption; trusted
host envelopes are unwrapped then resealed, and false collisions are sealed whole.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): keep merged sidecars in last-known after apply collect fails
Return applyFromSync entries from IPC and use them when follow-up collect fails,
so preserved missing-plugin rows are not dropped from the offline upload cache.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): delete stale-scope settings at stored coordinates on reset
After resetSetting against the current declared scope, also remove the row at
the sidecar's stored scope so scope migrations cannot republish remote deletes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): close sync-provider credential, stream, and sidecar gaps
Make SecretRef usable end-to-end via lease-bound network.request, keep
renderer/main transfers abortable and bounded, and stop sidecar
last-known/pending from corrupting backups and conflict apply.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): harden single-provider, secret schema, and conditional conflicts
Keep legacy restart from dual-connecting providers, extract writeOnly schema
secrets into OS storage, and surface conditional-write precondition failures
as conflict UI instead of a generic sync error.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): dedupe sync type imports for lint
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: address Codex review on PR #2713
* fix(plugins): wait for sidecar host before version backup latch
Defer the one-shot upgrade snapshot until the plugin sidecar host is ready (or a short grace), and catch getDataHash failures so pending/baseline paths do not reject unhandled.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): require sidecar grace before version backup
Always wait for contributions/grace tick before the upgrade snapshot, and only latch after a non-cancelled attempt so cleanup cannot suppress retries.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
1188 lines
51 KiB
TypeScript
1188 lines
51 KiB
TypeScript
/**
|
|
* Sync Payload Builders — Single source of truth for constructing and applying
|
|
* the encrypted cloud-sync payload.
|
|
*
|
|
* Both the main window (App.tsx) and the settings window (SettingsSyncTab.tsx)
|
|
* must use these helpers to guarantee every field is included and no data is
|
|
* silently dropped.
|
|
*/
|
|
|
|
import type {
|
|
GroupConfig,
|
|
Host,
|
|
Identity,
|
|
KnownHost,
|
|
PortForwardingRule,
|
|
ProxyProfile,
|
|
SftpBookmark,
|
|
Snippet,
|
|
SSHKey,
|
|
VaultNote,
|
|
} from '../domain/models';
|
|
import {
|
|
CLOUD_SYNC_PAYLOAD_ENTITY_KEYS,
|
|
SYNC_PAYLOAD_ENTITY_KEYS,
|
|
SYNC_STORAGE_KEYS,
|
|
hasSyncPayloadEntityData,
|
|
type SyncPayload,
|
|
} from '../domain/sync';
|
|
import { migrateHostsFromLegacyLineTimestamps } from '../domain/host';
|
|
import {
|
|
nextCustomKeyBindingsSyncVersion,
|
|
parseCustomKeyBindingsStorageRecord,
|
|
serializeCustomKeyBindingsStorageRecord,
|
|
} from '../domain/customKeyBindings';
|
|
import { isEncryptedCredentialPlaceholder } from '../domain/credentials';
|
|
import { localStorageAdapter } from '../infrastructure/persistence/localStorageAdapter';
|
|
import { decryptField, encryptField } from '../infrastructure/persistence/secureFieldAdapter';
|
|
import { sanitizeQuickMessages } from '../infrastructure/ai/quickMessages';
|
|
import { emitAIStateChanged } from './state/aiStateEvents';
|
|
import { rehydrateGlobalSftpBookmarks } from './state/sftp/globalSftpBookmarks';
|
|
import {
|
|
nextTerminalFontSizeSyncVersion,
|
|
parseTerminalFontSizeRecord,
|
|
serializeTerminalFontSizeRecord,
|
|
} from './state/terminalFontSizeSync';
|
|
import {
|
|
parseCustomAccentRecord,
|
|
serializeCustomAccentRecord,
|
|
} from './state/customAccentSync';
|
|
import {
|
|
STORAGE_KEY_THEME,
|
|
STORAGE_KEY_UI_THEME_LIGHT,
|
|
STORAGE_KEY_UI_THEME_DARK,
|
|
STORAGE_KEY_ACCENT_MODE,
|
|
STORAGE_KEY_COLOR,
|
|
STORAGE_KEY_UI_FONT_FAMILY,
|
|
STORAGE_KEY_UI_LANGUAGE,
|
|
STORAGE_KEY_CUSTOM_CSS,
|
|
STORAGE_KEY_TERM_THEME,
|
|
STORAGE_KEY_TERM_FOLLOW_APP_THEME,
|
|
STORAGE_KEY_TERM_THEME_DARK,
|
|
STORAGE_KEY_TERM_THEME_LIGHT,
|
|
STORAGE_KEY_TERM_FONT_FAMILY,
|
|
STORAGE_KEY_TERM_FONT_SIZE,
|
|
STORAGE_KEY_TERM_SETTINGS,
|
|
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
|
|
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
|
|
STORAGE_KEY_CUSTOM_KEY_BINDINGS,
|
|
STORAGE_KEY_EDITOR_WORD_WRAP,
|
|
STORAGE_KEY_SFTP_DOUBLE_CLICK_BEHAVIOR,
|
|
STORAGE_KEY_SFTP_AUTO_SYNC,
|
|
STORAGE_KEY_SFTP_SHOW_HIDDEN_FILES,
|
|
STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD,
|
|
STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR,
|
|
STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD,
|
|
STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE,
|
|
STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS,
|
|
STORAGE_KEY_CUSTOM_THEMES,
|
|
STORAGE_KEY_SHOW_RECENT_HOSTS,
|
|
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
|
|
STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT,
|
|
STORAGE_KEY_SHOW_SFTP_TAB,
|
|
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
|
|
STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
|
|
STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM,
|
|
STORAGE_KEY_WORKSPACE_FOCUS_STYLE,
|
|
STORAGE_KEY_AI_PROVIDERS,
|
|
STORAGE_KEY_AI_ACTIVE_PROVIDER,
|
|
STORAGE_KEY_AI_ACTIVE_MODEL,
|
|
STORAGE_KEY_AI_PERMISSION_MODE,
|
|
STORAGE_KEY_AI_TOOL_INTEGRATION_MODE,
|
|
STORAGE_KEY_AI_HOST_PERMISSIONS,
|
|
STORAGE_KEY_AI_DEFAULT_AGENT,
|
|
STORAGE_KEY_AI_COMMAND_BLOCKLIST,
|
|
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
|
STORAGE_KEY_AI_MAX_ITERATIONS,
|
|
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
|
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
|
STORAGE_KEY_AI_WEB_SEARCH,
|
|
STORAGE_KEY_AI_QUICK_MESSAGES,
|
|
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
|
STORAGE_KEY_PORT_FORWARDING,
|
|
} from '../infrastructure/config/storageKeys';
|
|
import { isTerminalSidePanelAutoOpenTab } from '../domain/terminalSidePanelAutoOpen';
|
|
import { prepareRestoredPayloadConvergentWrites } from './convergentSyncReplica';
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Input types
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const CUSTOM_KEY_BINDINGS_SYNC_PAYLOAD_ORIGIN = 'sync-payload';
|
|
|
|
/** Vault-owned data. Some fields are local-only and excluded from cloud sync. */
|
|
export interface SyncableVaultData {
|
|
hosts: Host[];
|
|
keys: SSHKey[];
|
|
identities: Identity[];
|
|
proxyProfiles?: ProxyProfile[];
|
|
snippets: Snippet[];
|
|
customGroups: string[];
|
|
snippetPackages?: string[];
|
|
notes?: VaultNote[];
|
|
noteGroups?: string[];
|
|
/** Local trust records. Kept in local backups, excluded from cloud sync. */
|
|
knownHosts: KnownHost[];
|
|
groupConfigs?: GroupConfig[];
|
|
}
|
|
|
|
/**
|
|
* Returns true when the payload carries non-empty plugin sidecar entries.
|
|
*
|
|
* An explicit empty `{entries:[]}` bundle is intentionally NOT treated as
|
|
* meaningful by itself — last-known cache alone must not authorize pushing a
|
|
* wiped hosts/keys vault to cloud (empty-vault upload guard). Sidecar-only
|
|
* wipes still sync when the vault also has entities/settings, or via Force Push.
|
|
*/
|
|
function hasMeaningfulPluginSidecars(payload: SyncPayload): boolean {
|
|
return Array.isArray(payload.pluginSidecars?.entries)
|
|
&& payload.pluginSidecars.entries.length > 0;
|
|
}
|
|
|
|
/**
|
|
* Returns true when a payload contains entities, settings, or meaningful
|
|
* plugin sidecars worth syncing / protecting with empty-vault guards.
|
|
* Local-only trust records are intentionally ignored by the cloud variant.
|
|
*/
|
|
export function hasMeaningfulSyncData(payload: SyncPayload): boolean {
|
|
if (hasSyncPayloadEntityData(payload, SYNC_PAYLOAD_ENTITY_KEYS)) return true;
|
|
|
|
if (
|
|
payload.settings && Object.values(payload.settings).some((value) => value !== undefined)
|
|
) {
|
|
return true;
|
|
}
|
|
|
|
return hasMeaningfulPluginSidecars(payload);
|
|
}
|
|
|
|
/**
|
|
* Returns true when a payload contains cloud-sync data.
|
|
* Local-only trust records are intentionally ignored.
|
|
*/
|
|
export function hasMeaningfulCloudSyncData(payload: SyncPayload): boolean {
|
|
if (hasSyncPayloadEntityData(payload, CLOUD_SYNC_PAYLOAD_ENTITY_KEYS)) return true;
|
|
|
|
if (
|
|
payload.settings && Object.values(payload.settings).some((value) => value !== undefined)
|
|
) {
|
|
return true;
|
|
}
|
|
|
|
// Plugin-only profiles (settings/baselines, no vault entities) must still sync.
|
|
return hasMeaningfulPluginSidecars(payload);
|
|
}
|
|
|
|
/**
|
|
* Returns true only when the payload contains synced vault entities.
|
|
* Settings are intentionally ignored so default settings written on first
|
|
* launch do not make a new device look non-empty during cloud restore checks.
|
|
*/
|
|
export function hasCloudSyncEntityData(payload: SyncPayload): boolean {
|
|
return hasSyncPayloadEntityData(payload, CLOUD_SYNC_PAYLOAD_ENTITY_KEYS);
|
|
}
|
|
|
|
export function shouldPromptCloudVaultRecovery(
|
|
localPayload: SyncPayload,
|
|
remotePayload: SyncPayload,
|
|
): boolean {
|
|
return !hasCloudSyncEntityData(localPayload) && hasCloudSyncEntityData(remotePayload);
|
|
}
|
|
|
|
export function sanitizePortForwardingRulesForSync(
|
|
rules: PortForwardingRule[] | undefined,
|
|
): PortForwardingRule[] | undefined {
|
|
if (!rules) return rules;
|
|
return rules.map((rule) => ({
|
|
...rule,
|
|
status: 'inactive' as const,
|
|
error: undefined,
|
|
lastUsedAt: undefined,
|
|
}));
|
|
}
|
|
|
|
export function getEffectivePortForwardingRulesForSync(
|
|
rules: PortForwardingRule[] | undefined,
|
|
): PortForwardingRule[] | undefined {
|
|
let effectiveRules = rules;
|
|
if (!effectiveRules || effectiveRules.length === 0) {
|
|
const stored = localStorageAdapter.read<PortForwardingRule[]>(STORAGE_KEY_PORT_FORWARDING);
|
|
if (Array.isArray(stored) && stored.length > 0) {
|
|
effectiveRules = stored;
|
|
}
|
|
}
|
|
|
|
return sanitizePortForwardingRulesForSync(effectiveRules);
|
|
}
|
|
|
|
/** Callbacks used by `applySyncPayload` to import data into local state. */
|
|
interface SyncPayloadImporters {
|
|
/** Import vault data. Cloud sync excludes local-only known hosts by default. */
|
|
importVaultData: (jsonString: string) => void | Promise<void>;
|
|
/** Import port-forwarding rules (lives outside the vault hook). */
|
|
importPortForwardingRules?: (rules: PortForwardingRule[]) => void;
|
|
/** Called after synced settings have been written to localStorage. */
|
|
onSettingsApplied?: () => void;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Settings sync helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** Terminal settings keys that are safe to sync (platform-agnostic). */
|
|
const SYNCABLE_TERMINAL_KEYS = [
|
|
'startupCommandDelayMs',
|
|
'scrollback', 'drawBoldInBrightColors', 'terminalEmulationType',
|
|
'fontLigatures', 'fontSmoothing', 'fontWeight', 'fontWeightBold', 'fallbackFont',
|
|
'linePadding', 'cursorShape', 'cursorBlink', 'highlightCursorLine', 'minimumContrastRatio',
|
|
'altAsMeta', 'optionArrowWordJump', 'shiftEnterNewlineEnabled', 'shiftEnterNewlineText',
|
|
'kittyKeyboardProtocolEnabled',
|
|
'scrollOnInput', 'scrollOnOutput', 'scrollOnKeyPress', 'scrollOnPaste',
|
|
'smoothScrolling',
|
|
'rightClickBehavior', 'showContextMenuOverFullscreenApps', 'middleClickBehavior', 'copyOnSelect', 'normalizeTextOnCopy', 'middleClickPaste', 'wordSeparators',
|
|
'linkModifier', 'keywordHighlightEnabled', 'keywordHighlightRules',
|
|
'keepaliveInterval', 'keepaliveCountMax', 'disableBracketedPaste', 'clearWipesScrollback',
|
|
'autoUploadClipboardImageOnPaste',
|
|
'preserveSelectionOnInput', 'forcePromptNewLine', 'osc52Clipboard', 'dynamicTabTitleMode',
|
|
'autoCloseOnExit',
|
|
'showHostInfoBar', 'hostInfoBarTitleMode', 'showServerStats',
|
|
'serverStatsRefreshInterval',
|
|
'systemManagerProcessRefreshInterval', 'systemManagerTmuxRefreshInterval',
|
|
'systemManagerDockerListRefreshInterval', 'systemManagerDockerStatsRefreshInterval',
|
|
'rendererType',
|
|
// Inline image protocol switches are a preference and sync; the per-terminal
|
|
// memory limits stay local because they are tuned per device (like hibernate*).
|
|
'inlineImagesEnabled', 'inlineImageKittyEnabled', 'inlineImageSixelEnabled', 'inlineImageIipEnabled',
|
|
'autocompleteEnabled', 'autocompleteGhostText', 'autocompletePopupMenu',
|
|
'autocompleteDebounceMs', 'autocompleteMinChars', 'autocompleteMaxSuggestions',
|
|
'autocompleteHistoryScope',
|
|
] as const;
|
|
|
|
export const SYNCABLE_SETTING_STORAGE_KEYS = [
|
|
STORAGE_KEY_THEME,
|
|
STORAGE_KEY_UI_THEME_LIGHT,
|
|
STORAGE_KEY_UI_THEME_DARK,
|
|
STORAGE_KEY_ACCENT_MODE,
|
|
STORAGE_KEY_COLOR,
|
|
STORAGE_KEY_UI_FONT_FAMILY,
|
|
STORAGE_KEY_UI_LANGUAGE,
|
|
STORAGE_KEY_CUSTOM_CSS,
|
|
STORAGE_KEY_TERM_THEME,
|
|
STORAGE_KEY_TERM_FOLLOW_APP_THEME,
|
|
STORAGE_KEY_TERM_THEME_DARK,
|
|
STORAGE_KEY_TERM_THEME_LIGHT,
|
|
STORAGE_KEY_TERM_FONT_FAMILY,
|
|
STORAGE_KEY_TERM_FONT_SIZE,
|
|
STORAGE_KEY_TERM_SETTINGS,
|
|
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
|
|
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
|
|
STORAGE_KEY_CUSTOM_THEMES,
|
|
STORAGE_KEY_CUSTOM_KEY_BINDINGS,
|
|
STORAGE_KEY_EDITOR_WORD_WRAP,
|
|
STORAGE_KEY_SFTP_DOUBLE_CLICK_BEHAVIOR,
|
|
STORAGE_KEY_SFTP_AUTO_SYNC,
|
|
STORAGE_KEY_SFTP_SHOW_HIDDEN_FILES,
|
|
STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD,
|
|
STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR,
|
|
STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD,
|
|
STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE,
|
|
STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS,
|
|
STORAGE_KEY_SHOW_RECENT_HOSTS,
|
|
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
|
|
STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT,
|
|
STORAGE_KEY_SHOW_SFTP_TAB,
|
|
STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
|
|
STORAGE_KEY_WORKSPACE_FOCUS_STYLE,
|
|
STORAGE_KEY_AI_PROVIDERS,
|
|
STORAGE_KEY_AI_ACTIVE_PROVIDER,
|
|
STORAGE_KEY_AI_ACTIVE_MODEL,
|
|
STORAGE_KEY_AI_PERMISSION_MODE,
|
|
STORAGE_KEY_AI_TOOL_INTEGRATION_MODE,
|
|
STORAGE_KEY_AI_HOST_PERMISSIONS,
|
|
STORAGE_KEY_AI_DEFAULT_AGENT,
|
|
STORAGE_KEY_AI_COMMAND_BLOCKLIST,
|
|
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
|
STORAGE_KEY_AI_MAX_ITERATIONS,
|
|
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
|
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
|
STORAGE_KEY_AI_WEB_SEARCH,
|
|
STORAGE_KEY_AI_QUICK_MESSAGES,
|
|
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
|
] as const;
|
|
|
|
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
|
|
const readArraySetting = <T = Record<string, unknown>>(key: string): T[] | null => {
|
|
const value = localStorageAdapter.read<T[]>(key);
|
|
return Array.isArray(value) ? value : null;
|
|
};
|
|
|
|
const readRecordSetting = <T extends Record<string, unknown> = Record<string, unknown>>(key: string): T | null => {
|
|
const value = localStorageAdapter.read<T>(key);
|
|
return isRecord(value) ? value as T : null;
|
|
};
|
|
|
|
const stripDeviceBoundApiKey = <T extends Record<string, unknown>>(value: T): T => {
|
|
if (!isEncryptedCredentialPlaceholder(value.apiKey as string | undefined)) return value;
|
|
const next = { ...value };
|
|
delete next.apiKey;
|
|
return next;
|
|
};
|
|
|
|
const getApiKeyLabel = (value: Record<string, unknown>): string => {
|
|
if (typeof value.name === 'string' && value.name.trim()) return value.name;
|
|
if (typeof value.id === 'string' && value.id.trim()) return value.id;
|
|
if (typeof value.providerId === 'string' && value.providerId.trim()) return value.providerId;
|
|
return 'configured provider';
|
|
};
|
|
|
|
const withPortableApiKey = async <T extends Record<string, unknown>>(value: T): Promise<T> => {
|
|
const apiKey = value.apiKey;
|
|
if (typeof apiKey !== 'string' || !isEncryptedCredentialPlaceholder(apiKey)) return value;
|
|
|
|
const decrypted = await decryptField(apiKey).catch(() => undefined);
|
|
if (!decrypted || decrypted === apiKey || isEncryptedCredentialPlaceholder(decrypted)) {
|
|
throw new Error(`Unable to decrypt AI API key for ${getApiKeyLabel(value)}. Sync was stopped to avoid removing the key from cloud sync.`);
|
|
}
|
|
return { ...value, apiKey: decrypted };
|
|
};
|
|
|
|
const withLocalEncryptedApiKey = async <T extends Record<string, unknown>>(value: T): Promise<T> => {
|
|
const apiKey = value.apiKey;
|
|
if (typeof apiKey !== 'string' || isEncryptedCredentialPlaceholder(apiKey)) return value;
|
|
|
|
const encrypted = await encryptField(apiKey).catch(() => undefined);
|
|
return { ...value, apiKey: encrypted ?? apiKey };
|
|
};
|
|
|
|
/**
|
|
* `collectSyncableSettings` strips device-bound encrypted apiKeys before upload,
|
|
* so an incoming providers array typically has no apiKey for providers that
|
|
* already exist locally. Re-attach the local apiKey by id; without this merge,
|
|
* applying any synced settings change would silently wipe credentials on the
|
|
* receiving device.
|
|
*/
|
|
const mergeAiProvidersPreservingLocalApiKeys = (
|
|
incoming: Array<Record<string, unknown>>,
|
|
): Array<Record<string, unknown>> => {
|
|
const local = readArraySetting(STORAGE_KEY_AI_PROVIDERS) ?? [];
|
|
const localById = new Map<string, Record<string, unknown>>();
|
|
for (const provider of local) {
|
|
if (typeof provider?.id === 'string') localById.set(provider.id, provider);
|
|
}
|
|
return incoming.map((provider) => {
|
|
if (provider.apiKey != null) return provider;
|
|
const id = typeof provider.id === 'string' ? provider.id : undefined;
|
|
const localProvider = id != null ? localById.get(id) : undefined;
|
|
if (localProvider && typeof localProvider.apiKey === 'string') {
|
|
return { ...provider, apiKey: localProvider.apiKey };
|
|
}
|
|
return provider;
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Same rationale as `mergeAiProvidersPreservingLocalApiKeys`. Only restores the
|
|
* local apiKey when the incoming config still points at the same providerId —
|
|
* switching providers must not silently leak a key meant for a different one.
|
|
*/
|
|
const mergeWebSearchConfigPreservingLocalApiKey = (
|
|
incoming: Record<string, unknown>,
|
|
): Record<string, unknown> => {
|
|
if (incoming.apiKey != null) return incoming;
|
|
const local = readRecordSetting(STORAGE_KEY_AI_WEB_SEARCH);
|
|
if (!local || typeof local.apiKey !== 'string') return incoming;
|
|
if (local.providerId !== incoming.providerId) return incoming;
|
|
return { ...incoming, apiKey: local.apiKey };
|
|
};
|
|
|
|
/**
|
|
* Collect all syncable settings from localStorage.
|
|
*/
|
|
export function collectSyncableSettings(): SyncPayload['settings'] {
|
|
const settings: SyncPayload['settings'] = {};
|
|
|
|
// Theme & Appearance
|
|
const theme = localStorageAdapter.readString(STORAGE_KEY_THEME);
|
|
if (theme === 'light' || theme === 'dark' || theme === 'system') settings.theme = theme;
|
|
const lightUi = localStorageAdapter.readString(STORAGE_KEY_UI_THEME_LIGHT);
|
|
if (lightUi) settings.lightUiThemeId = lightUi;
|
|
const darkUi = localStorageAdapter.readString(STORAGE_KEY_UI_THEME_DARK);
|
|
if (darkUi) settings.darkUiThemeId = darkUi;
|
|
const accentMode = localStorageAdapter.readString(STORAGE_KEY_ACCENT_MODE);
|
|
if (accentMode === 'theme' || accentMode === 'custom') settings.accentMode = accentMode;
|
|
const accentRaw = localStorageAdapter.readString(STORAGE_KEY_COLOR);
|
|
if (accentRaw) settings.customAccent = parseCustomAccentRecord(accentRaw).color;
|
|
const uiFont = localStorageAdapter.readString(STORAGE_KEY_UI_FONT_FAMILY);
|
|
if (uiFont) settings.uiFontFamilyId = uiFont;
|
|
const lang = localStorageAdapter.readString(STORAGE_KEY_UI_LANGUAGE);
|
|
if (lang) settings.uiLanguage = lang;
|
|
const css = localStorageAdapter.readString(STORAGE_KEY_CUSTOM_CSS);
|
|
if (css != null) settings.customCSS = css;
|
|
|
|
// Terminal
|
|
const termTheme = localStorageAdapter.readString(STORAGE_KEY_TERM_THEME);
|
|
if (termTheme) settings.terminalTheme = termTheme;
|
|
const followAppTermTheme = localStorageAdapter.readString(STORAGE_KEY_TERM_FOLLOW_APP_THEME);
|
|
if (followAppTermTheme === 'true' || followAppTermTheme === 'false') {
|
|
settings.followAppTerminalTheme = followAppTermTheme === 'true';
|
|
}
|
|
const termThemeDark = localStorageAdapter.readString(STORAGE_KEY_TERM_THEME_DARK);
|
|
if (termThemeDark) settings.terminalThemeDark = termThemeDark;
|
|
const termThemeLight = localStorageAdapter.readString(STORAGE_KEY_TERM_THEME_LIGHT);
|
|
if (termThemeLight) settings.terminalThemeLight = termThemeLight;
|
|
const termFont = localStorageAdapter.readString(STORAGE_KEY_TERM_FONT_FAMILY);
|
|
if (termFont) settings.terminalFontFamily = termFont;
|
|
const termSizeRaw = localStorageAdapter.readString(STORAGE_KEY_TERM_FONT_SIZE);
|
|
if (termSizeRaw != null && termSizeRaw !== '') {
|
|
settings.terminalFontSize = parseTerminalFontSizeRecord(termSizeRaw).fontSize;
|
|
}
|
|
const terminalSidePanelAutoOpen = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
|
|
if (terminalSidePanelAutoOpen != null) settings.terminalSidePanelAutoOpen = terminalSidePanelAutoOpen;
|
|
const terminalSidePanelAutoOpenTab = localStorageAdapter.readString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB);
|
|
if (isTerminalSidePanelAutoOpenTab(terminalSidePanelAutoOpenTab)) {
|
|
settings.terminalSidePanelAutoOpenTab = terminalSidePanelAutoOpenTab;
|
|
}
|
|
|
|
// Terminal settings (syncable subset only)
|
|
const termSettingsRaw = localStorageAdapter.readString(STORAGE_KEY_TERM_SETTINGS);
|
|
if (termSettingsRaw) {
|
|
try {
|
|
const full = JSON.parse(termSettingsRaw);
|
|
const subset: Record<string, unknown> = {};
|
|
for (const key of SYNCABLE_TERMINAL_KEYS) {
|
|
if (key in full) subset[key] = full[key];
|
|
}
|
|
if (Object.keys(subset).length > 0) settings.terminalSettings = subset;
|
|
} catch { /* ignore corrupt data */ }
|
|
}
|
|
|
|
// Custom terminal themes
|
|
const customThemesRaw = localStorageAdapter.readString(STORAGE_KEY_CUSTOM_THEMES);
|
|
if (customThemesRaw) {
|
|
try {
|
|
const parsed = JSON.parse(customThemesRaw);
|
|
if (Array.isArray(parsed)) settings.customTerminalThemes = parsed;
|
|
} catch { /* ignore */ }
|
|
}
|
|
|
|
// Keyboard
|
|
const kb = localStorageAdapter.readString(STORAGE_KEY_CUSTOM_KEY_BINDINGS);
|
|
if (kb) {
|
|
const parsed = parseCustomKeyBindingsStorageRecord(kb);
|
|
if (parsed) settings.customKeyBindings = parsed.bindings;
|
|
}
|
|
|
|
// Editor
|
|
const wordWrap = localStorageAdapter.readString(STORAGE_KEY_EDITOR_WORD_WRAP);
|
|
if (wordWrap === 'true' || wordWrap === 'false') settings.editorWordWrap = wordWrap === 'true';
|
|
|
|
// SFTP
|
|
const dblClick = localStorageAdapter.readString(STORAGE_KEY_SFTP_DOUBLE_CLICK_BEHAVIOR);
|
|
if (dblClick === 'open' || dblClick === 'transfer') settings.sftpDoubleClickBehavior = dblClick;
|
|
const autoSync = localStorageAdapter.readString(STORAGE_KEY_SFTP_AUTO_SYNC);
|
|
if (autoSync === 'true' || autoSync === 'false') settings.sftpAutoSync = autoSync === 'true';
|
|
const hidden = localStorageAdapter.readString(STORAGE_KEY_SFTP_SHOW_HIDDEN_FILES);
|
|
if (hidden === 'true' || hidden === 'false') settings.sftpShowHiddenFiles = hidden === 'true';
|
|
const compress = localStorageAdapter.readString(STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD);
|
|
if (compress === 'true' || compress === 'false') settings.sftpUseCompressedUpload = compress === 'true';
|
|
const autoOpenSidebar = localStorageAdapter.readString(STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR);
|
|
if (autoOpenSidebar === 'true' || autoOpenSidebar === 'false') settings.sftpAutoOpenSidebar = autoOpenSidebar === 'true';
|
|
const followTerminalCwd = localStorageAdapter.readString(STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD);
|
|
if (followTerminalCwd === 'true' || followTerminalCwd === 'false') settings.sftpFollowTerminalCwd = followTerminalCwd === 'true';
|
|
const defaultViewMode = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE);
|
|
if (defaultViewMode === 'list' || defaultViewMode === 'tree') settings.sftpDefaultViewMode = defaultViewMode;
|
|
|
|
// SFTP Bookmarks (global only — local bookmarks are device-specific)
|
|
const globalBookmarks = localStorageAdapter.read<SftpBookmark[]>(STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS);
|
|
if (globalBookmarks && Array.isArray(globalBookmarks)) settings.sftpGlobalBookmarks = globalBookmarks;
|
|
|
|
|
|
const showRecent = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_RECENT_HOSTS);
|
|
if (showRecent != null) settings.showRecentHosts = showRecent;
|
|
const hostClickBehavior = localStorageAdapter.readString(STORAGE_KEY_HOST_CLICK_BEHAVIOR);
|
|
if (hostClickBehavior === 'connect' || hostClickBehavior === 'select') {
|
|
settings.hostClickBehavior = hostClickBehavior;
|
|
}
|
|
const showOnlyUngroupedHostsInRoot = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT);
|
|
if (showOnlyUngroupedHostsInRoot != null) settings.showOnlyUngroupedHostsInRoot = showOnlyUngroupedHostsInRoot;
|
|
const showSftpTab = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_SFTP_TAB);
|
|
if (showSftpTab != null) settings.showSftpTab = showSftpTab;
|
|
const shellOnlyTabNumberShortcuts = localStorageAdapter.readBoolean(STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS);
|
|
if (shellOnlyTabNumberShortcuts != null) settings.shellOnlyTabNumberShortcuts = shellOnlyTabNumberShortcuts;
|
|
const disableTerminalFontZoom = localStorageAdapter.readBoolean(STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM);
|
|
if (disableTerminalFontZoom != null) settings.disableTerminalFontZoom = disableTerminalFontZoom;
|
|
const showHostTreeSidebar = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
|
|
if (showHostTreeSidebar != null) settings.showHostTreeSidebar = showHostTreeSidebar;
|
|
const workspaceFocusStyle = localStorageAdapter.readString(STORAGE_KEY_WORKSPACE_FOCUS_STYLE);
|
|
if (workspaceFocusStyle === 'dim' || workspaceFocusStyle === 'border') {
|
|
settings.workspaceFocusStyle = workspaceFocusStyle;
|
|
}
|
|
|
|
const ai: NonNullable<SyncPayload['settings']>['ai'] = {};
|
|
const providers = readArraySetting(STORAGE_KEY_AI_PROVIDERS);
|
|
if (providers) ai.providers = providers.map(stripDeviceBoundApiKey);
|
|
const activeProviderId = localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_PROVIDER);
|
|
if (activeProviderId != null) ai.activeProviderId = activeProviderId;
|
|
const activeModelId = localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_MODEL);
|
|
if (activeModelId != null) ai.activeModelId = activeModelId;
|
|
const permissionMode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
|
if (permissionMode === 'observer' || permissionMode === 'confirm' || permissionMode === 'auto') {
|
|
ai.globalPermissionMode = permissionMode;
|
|
}
|
|
const toolIntegrationMode = localStorageAdapter.readString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE);
|
|
if (toolIntegrationMode === 'mcp' || toolIntegrationMode === 'skills') {
|
|
ai.toolIntegrationMode = toolIntegrationMode;
|
|
}
|
|
const hostPermissions = readArraySetting(STORAGE_KEY_AI_HOST_PERMISSIONS);
|
|
if (hostPermissions) ai.hostPermissions = hostPermissions;
|
|
// externalAgents intentionally not collected: command/args/env are device-local.
|
|
const defaultAgentId = localStorageAdapter.readString(STORAGE_KEY_AI_DEFAULT_AGENT);
|
|
if (defaultAgentId != null) ai.defaultAgentId = defaultAgentId;
|
|
const commandBlocklist = localStorageAdapter.read<string[]>(STORAGE_KEY_AI_COMMAND_BLOCKLIST);
|
|
if (Array.isArray(commandBlocklist)) ai.commandBlocklist = commandBlocklist;
|
|
const commandTimeout = localStorageAdapter.readNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT);
|
|
if (commandTimeout != null && Number.isFinite(commandTimeout)) ai.commandTimeout = commandTimeout;
|
|
const maxIterations = localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS);
|
|
if (maxIterations != null && Number.isFinite(maxIterations)) ai.maxIterations = maxIterations;
|
|
const agentModelMap = readRecordSetting<Record<string, string>>(STORAGE_KEY_AI_AGENT_MODEL_MAP);
|
|
if (agentModelMap) ai.agentModelMap = agentModelMap;
|
|
const agentProviderMap = readRecordSetting<Record<string, string>>(STORAGE_KEY_AI_AGENT_PROVIDER_MAP);
|
|
if (agentProviderMap) ai.agentProviderMap = agentProviderMap;
|
|
const webSearchConfig = readRecordSetting(STORAGE_KEY_AI_WEB_SEARCH);
|
|
if (webSearchConfig) ai.webSearchConfig = stripDeviceBoundApiKey(webSearchConfig);
|
|
const quickMessages = readArraySetting(STORAGE_KEY_AI_QUICK_MESSAGES);
|
|
if (quickMessages) ai.quickMessages = sanitizeQuickMessages(quickMessages) as unknown as Array<Record<string, unknown>>;
|
|
const showTerminalSelectionAction = localStorageAdapter.readBoolean(STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION);
|
|
if (showTerminalSelectionAction != null) {
|
|
ai.showTerminalSelectionAction = showTerminalSelectionAction;
|
|
}
|
|
if (Object.keys(ai).length > 0) settings.ai = ai;
|
|
|
|
return Object.keys(settings).length > 0 ? settings : undefined;
|
|
}
|
|
|
|
export async function collectCloudSyncableSettings(): Promise<SyncPayload['settings']> {
|
|
const settings = collectSyncableSettings();
|
|
|
|
const providers = readArraySetting(STORAGE_KEY_AI_PROVIDERS);
|
|
const webSearchConfig = readRecordSetting(STORAGE_KEY_AI_WEB_SEARCH);
|
|
if (!providers && !webSearchConfig) return settings;
|
|
|
|
const nextSettings: SyncPayload['settings'] = settings ? { ...settings } : {};
|
|
const ai: NonNullable<SyncPayload['settings']>['ai'] = {
|
|
...(settings?.ai ?? {}),
|
|
};
|
|
|
|
if (providers) {
|
|
ai.providers = await Promise.all(providers.map(withPortableApiKey));
|
|
}
|
|
if (webSearchConfig) {
|
|
ai.webSearchConfig = await withPortableApiKey(webSearchConfig);
|
|
}
|
|
|
|
nextSettings.ai = ai;
|
|
return Object.keys(nextSettings).length > 0 ? nextSettings : undefined;
|
|
}
|
|
|
|
function collectLocalBackupSettings(): SyncPayload['settings'] {
|
|
const settings = collectSyncableSettings();
|
|
|
|
const providers = readArraySetting(STORAGE_KEY_AI_PROVIDERS);
|
|
const webSearchConfig = readRecordSetting(STORAGE_KEY_AI_WEB_SEARCH);
|
|
if (!providers && !webSearchConfig) return settings;
|
|
|
|
const nextSettings: SyncPayload['settings'] = settings ? { ...settings } : {};
|
|
const ai: NonNullable<SyncPayload['settings']>['ai'] = {
|
|
...(settings?.ai ?? {}),
|
|
};
|
|
|
|
if (providers) {
|
|
ai.providers = providers;
|
|
}
|
|
if (webSearchConfig) {
|
|
ai.webSearchConfig = webSearchConfig;
|
|
}
|
|
|
|
nextSettings.ai = ai;
|
|
return Object.keys(nextSettings).length > 0 ? nextSettings : undefined;
|
|
}
|
|
|
|
/**
|
|
* Apply synced settings to localStorage. Merges terminal settings
|
|
* to preserve platform-specific fields.
|
|
*/
|
|
async function applySyncableSettings(settings: NonNullable<SyncPayload['settings']>): Promise<void> {
|
|
// Theme & Appearance
|
|
if (settings.theme != null) localStorageAdapter.writeString(STORAGE_KEY_THEME, settings.theme);
|
|
if (settings.lightUiThemeId != null) localStorageAdapter.writeString(STORAGE_KEY_UI_THEME_LIGHT, settings.lightUiThemeId);
|
|
if (settings.darkUiThemeId != null) localStorageAdapter.writeString(STORAGE_KEY_UI_THEME_DARK, settings.darkUiThemeId);
|
|
if (settings.accentMode != null) localStorageAdapter.writeString(STORAGE_KEY_ACCENT_MODE, settings.accentMode);
|
|
if (settings.customAccent != null) {
|
|
const existing = parseCustomAccentRecord(localStorageAdapter.readString(STORAGE_KEY_COLOR));
|
|
localStorageAdapter.writeString(
|
|
STORAGE_KEY_COLOR,
|
|
serializeCustomAccentRecord({
|
|
color: parseCustomAccentRecord(settings.customAccent).color,
|
|
// Bump so peer windows' version gates accept the synced value.
|
|
version: Math.max(existing.version, 0) + 1,
|
|
}),
|
|
);
|
|
}
|
|
if (settings.uiFontFamilyId != null) localStorageAdapter.writeString(STORAGE_KEY_UI_FONT_FAMILY, settings.uiFontFamilyId);
|
|
if (settings.uiLanguage != null) localStorageAdapter.writeString(STORAGE_KEY_UI_LANGUAGE, settings.uiLanguage);
|
|
if (settings.customCSS != null) localStorageAdapter.writeString(STORAGE_KEY_CUSTOM_CSS, settings.customCSS);
|
|
|
|
// Terminal
|
|
if (settings.terminalTheme != null) localStorageAdapter.writeString(STORAGE_KEY_TERM_THEME, settings.terminalTheme);
|
|
if (settings.followAppTerminalTheme != null) {
|
|
localStorageAdapter.writeString(STORAGE_KEY_TERM_FOLLOW_APP_THEME, String(settings.followAppTerminalTheme));
|
|
}
|
|
if (settings.terminalThemeDark != null) localStorageAdapter.writeString(STORAGE_KEY_TERM_THEME_DARK, settings.terminalThemeDark);
|
|
if (settings.terminalThemeLight != null) localStorageAdapter.writeString(STORAGE_KEY_TERM_THEME_LIGHT, settings.terminalThemeLight);
|
|
if (settings.terminalFontFamily != null) localStorageAdapter.writeString(STORAGE_KEY_TERM_FONT_FAMILY, settings.terminalFontFamily);
|
|
if (settings.terminalFontSize != null) {
|
|
const existing = parseTerminalFontSizeRecord(
|
|
localStorageAdapter.readString(STORAGE_KEY_TERM_FONT_SIZE),
|
|
);
|
|
localStorageAdapter.writeString(
|
|
STORAGE_KEY_TERM_FONT_SIZE,
|
|
serializeTerminalFontSizeRecord({
|
|
fontSize: settings.terminalFontSize,
|
|
// Bump so peer windows' version gates accept the synced value.
|
|
version: nextTerminalFontSizeSyncVersion(existing.version, existing.version),
|
|
origin: 'sync-payload',
|
|
}),
|
|
);
|
|
}
|
|
if (settings.terminalSidePanelAutoOpen != null) {
|
|
localStorageAdapter.writeBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN, settings.terminalSidePanelAutoOpen);
|
|
}
|
|
if (isTerminalSidePanelAutoOpenTab(settings.terminalSidePanelAutoOpenTab)) {
|
|
localStorageAdapter.writeString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB, settings.terminalSidePanelAutoOpenTab);
|
|
}
|
|
|
|
// Terminal settings — merge with existing to preserve platform-specific keys
|
|
if (settings.terminalSettings) {
|
|
let existing: Record<string, unknown> = {};
|
|
const raw = localStorageAdapter.readString(STORAGE_KEY_TERM_SETTINGS);
|
|
if (raw) {
|
|
try { existing = JSON.parse(raw); } catch { /* ignore */ }
|
|
}
|
|
const merged = { ...existing };
|
|
const hasIncomingMiddleClickBehavior = 'middleClickBehavior' in settings.terminalSettings;
|
|
const hasIncomingMiddleClickPaste = 'middleClickPaste' in settings.terminalSettings;
|
|
for (const key of SYNCABLE_TERMINAL_KEYS) {
|
|
if (key in settings.terminalSettings) {
|
|
merged[key] = settings.terminalSettings[key];
|
|
}
|
|
}
|
|
if (hasIncomingMiddleClickBehavior) {
|
|
const behavior = settings.terminalSettings.middleClickBehavior;
|
|
if (
|
|
behavior === 'context-menu' ||
|
|
behavior === 'paste' ||
|
|
behavior === 'disabled'
|
|
) {
|
|
merged.middleClickPaste = behavior === 'paste';
|
|
}
|
|
} else if (hasIncomingMiddleClickPaste) {
|
|
merged.middleClickBehavior = settings.terminalSettings.middleClickPaste === false
|
|
? 'disabled'
|
|
: 'paste';
|
|
}
|
|
localStorageAdapter.writeString(STORAGE_KEY_TERM_SETTINGS, JSON.stringify(merged));
|
|
}
|
|
|
|
// Custom terminal themes
|
|
if (settings.customTerminalThemes != null) {
|
|
localStorageAdapter.writeString(STORAGE_KEY_CUSTOM_THEMES, JSON.stringify(settings.customTerminalThemes));
|
|
}
|
|
|
|
// Keyboard
|
|
if (settings.customKeyBindings != null) {
|
|
const previous = parseCustomKeyBindingsStorageRecord(
|
|
localStorageAdapter.readString(STORAGE_KEY_CUSTOM_KEY_BINDINGS),
|
|
);
|
|
localStorageAdapter.writeString(
|
|
STORAGE_KEY_CUSTOM_KEY_BINDINGS,
|
|
serializeCustomKeyBindingsStorageRecord({
|
|
version: nextCustomKeyBindingsSyncVersion(previous?.version || 0),
|
|
origin: CUSTOM_KEY_BINDINGS_SYNC_PAYLOAD_ORIGIN,
|
|
bindings: settings.customKeyBindings,
|
|
}),
|
|
);
|
|
}
|
|
|
|
// Editor
|
|
if (settings.editorWordWrap != null) localStorageAdapter.writeString(STORAGE_KEY_EDITOR_WORD_WRAP, String(settings.editorWordWrap));
|
|
|
|
// SFTP
|
|
if (settings.sftpDoubleClickBehavior != null) localStorageAdapter.writeString(STORAGE_KEY_SFTP_DOUBLE_CLICK_BEHAVIOR, settings.sftpDoubleClickBehavior);
|
|
if (settings.sftpAutoSync != null) localStorageAdapter.writeString(STORAGE_KEY_SFTP_AUTO_SYNC, String(settings.sftpAutoSync));
|
|
if (settings.sftpShowHiddenFiles != null) localStorageAdapter.writeString(STORAGE_KEY_SFTP_SHOW_HIDDEN_FILES, String(settings.sftpShowHiddenFiles));
|
|
if (settings.sftpUseCompressedUpload != null) localStorageAdapter.writeString(STORAGE_KEY_SFTP_USE_COMPRESSED_UPLOAD, String(settings.sftpUseCompressedUpload));
|
|
if (settings.sftpAutoOpenSidebar != null) localStorageAdapter.writeString(STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR, String(settings.sftpAutoOpenSidebar));
|
|
if (settings.sftpFollowTerminalCwd != null) localStorageAdapter.writeString(STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD, String(settings.sftpFollowTerminalCwd));
|
|
if (settings.sftpDefaultViewMode != null) {
|
|
localStorageAdapter.writeString(STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE, settings.sftpDefaultViewMode);
|
|
}
|
|
|
|
// SFTP Bookmarks (global only)
|
|
if (settings.sftpGlobalBookmarks != null) localStorageAdapter.write(STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS, settings.sftpGlobalBookmarks);
|
|
|
|
if (settings.showRecentHosts != null) localStorageAdapter.writeBoolean(STORAGE_KEY_SHOW_RECENT_HOSTS, settings.showRecentHosts);
|
|
if (settings.hostClickBehavior === 'connect' || settings.hostClickBehavior === 'select') {
|
|
localStorageAdapter.writeString(STORAGE_KEY_HOST_CLICK_BEHAVIOR, settings.hostClickBehavior);
|
|
}
|
|
if (settings.showOnlyUngroupedHostsInRoot != null) {
|
|
localStorageAdapter.writeBoolean(
|
|
STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT,
|
|
settings.showOnlyUngroupedHostsInRoot,
|
|
);
|
|
}
|
|
if (settings.showSftpTab != null) {
|
|
localStorageAdapter.writeBoolean(STORAGE_KEY_SHOW_SFTP_TAB, settings.showSftpTab);
|
|
}
|
|
if (settings.shellOnlyTabNumberShortcuts != null) {
|
|
localStorageAdapter.writeBoolean(STORAGE_KEY_SHELL_ONLY_TAB_NUMBER_SHORTCUTS, settings.shellOnlyTabNumberShortcuts);
|
|
}
|
|
if (settings.disableTerminalFontZoom != null) {
|
|
localStorageAdapter.writeBoolean(STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM, settings.disableTerminalFontZoom);
|
|
}
|
|
if (settings.showHostTreeSidebar != null) {
|
|
localStorageAdapter.writeBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR, settings.showHostTreeSidebar);
|
|
}
|
|
if (settings.workspaceFocusStyle != null) {
|
|
localStorageAdapter.writeString(STORAGE_KEY_WORKSPACE_FOCUS_STYLE, settings.workspaceFocusStyle);
|
|
}
|
|
|
|
const ai = settings.ai;
|
|
if (ai) {
|
|
if (ai.providers != null) {
|
|
const providers = await Promise.all(ai.providers.map(withLocalEncryptedApiKey));
|
|
localStorageAdapter.write(
|
|
STORAGE_KEY_AI_PROVIDERS,
|
|
mergeAiProvidersPreservingLocalApiKeys(providers),
|
|
);
|
|
}
|
|
if (ai.activeProviderId != null) localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, ai.activeProviderId);
|
|
if (ai.activeModelId != null) localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_MODEL, ai.activeModelId);
|
|
if (ai.globalPermissionMode != null) localStorageAdapter.writeString(STORAGE_KEY_AI_PERMISSION_MODE, ai.globalPermissionMode);
|
|
if (ai.toolIntegrationMode != null) localStorageAdapter.writeString(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE, ai.toolIntegrationMode);
|
|
if (ai.hostPermissions != null) localStorageAdapter.write(STORAGE_KEY_AI_HOST_PERMISSIONS, ai.hostPermissions);
|
|
// externalAgents intentionally not applied: device-local. Legacy snapshots
|
|
// that still carry an `externalAgents` field are silently ignored.
|
|
if (ai.defaultAgentId != null) localStorageAdapter.writeString(STORAGE_KEY_AI_DEFAULT_AGENT, ai.defaultAgentId);
|
|
if (ai.commandBlocklist != null) localStorageAdapter.write(STORAGE_KEY_AI_COMMAND_BLOCKLIST, ai.commandBlocklist);
|
|
if (ai.commandTimeout != null) localStorageAdapter.writeNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT, ai.commandTimeout);
|
|
if (ai.maxIterations != null) localStorageAdapter.writeNumber(STORAGE_KEY_AI_MAX_ITERATIONS, ai.maxIterations);
|
|
if (ai.agentModelMap != null) localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, ai.agentModelMap);
|
|
if (ai.agentProviderMap != null) localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, ai.agentProviderMap);
|
|
if (ai.webSearchConfig !== undefined) {
|
|
if (ai.webSearchConfig === null) {
|
|
localStorageAdapter.remove(STORAGE_KEY_AI_WEB_SEARCH);
|
|
} else {
|
|
const webSearchConfig = await withLocalEncryptedApiKey(ai.webSearchConfig);
|
|
localStorageAdapter.write(
|
|
STORAGE_KEY_AI_WEB_SEARCH,
|
|
mergeWebSearchConfigPreservingLocalApiKey(webSearchConfig),
|
|
);
|
|
}
|
|
}
|
|
if (ai.quickMessages != null) {
|
|
localStorageAdapter.write(STORAGE_KEY_AI_QUICK_MESSAGES, sanitizeQuickMessages(ai.quickMessages));
|
|
}
|
|
if (ai.showTerminalSelectionAction != null) {
|
|
localStorageAdapter.writeBoolean(
|
|
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
|
ai.showTerminalSelectionAction,
|
|
);
|
|
}
|
|
// After all AI writes, reconcile per-agent bindings against the final
|
|
// provider list. Sync payloads can land with a new `providers` set but
|
|
// no `agentProviderMap`, or with a stale `agentProviderMap` that
|
|
// points at ids the synced provider set doesn't include — either way
|
|
// we'd leak overrides bound to ghost providers. Mirrors the same
|
|
// cleanup `removeProvider` does for explicit user deletes.
|
|
pruneOrphanPerAgentBindings();
|
|
// Nudge same-window AI state listeners. localStorage writes only fire
|
|
// `storage` events in *other* windows; without this nudge the open
|
|
// chat panel keeps showing pre-sync providers/bindings until reload.
|
|
notifyAIStateAfterSync(ai);
|
|
}
|
|
}
|
|
|
|
function notifyAIStateAfterSync(ai: NonNullable<SyncPayload['settings']>['ai']): void {
|
|
if (!ai) return;
|
|
// Every AI storage key that `applySyncableSettings` may have touched
|
|
// gets a same-window nudge. `useAIState` listens for these and refreshes
|
|
// the corresponding React state by re-reading localStorage.
|
|
const touched: Array<string> = [];
|
|
if (ai.providers != null) touched.push(STORAGE_KEY_AI_PROVIDERS);
|
|
if (ai.activeProviderId != null) touched.push(STORAGE_KEY_AI_ACTIVE_PROVIDER);
|
|
if (ai.activeModelId != null) touched.push(STORAGE_KEY_AI_ACTIVE_MODEL);
|
|
if (ai.globalPermissionMode != null) touched.push(STORAGE_KEY_AI_PERMISSION_MODE);
|
|
if (ai.toolIntegrationMode != null) touched.push(STORAGE_KEY_AI_TOOL_INTEGRATION_MODE);
|
|
if (ai.hostPermissions != null) touched.push(STORAGE_KEY_AI_HOST_PERMISSIONS);
|
|
if (ai.defaultAgentId != null) touched.push(STORAGE_KEY_AI_DEFAULT_AGENT);
|
|
if (ai.commandBlocklist != null) touched.push(STORAGE_KEY_AI_COMMAND_BLOCKLIST);
|
|
if (ai.commandTimeout != null) touched.push(STORAGE_KEY_AI_COMMAND_TIMEOUT);
|
|
if (ai.maxIterations != null) touched.push(STORAGE_KEY_AI_MAX_ITERATIONS);
|
|
if (ai.agentModelMap != null) touched.push(STORAGE_KEY_AI_AGENT_MODEL_MAP);
|
|
// agentProviderMap is *always* potentially mutated because the reconcile
|
|
// step may have pruned it even if the payload didn't ship one.
|
|
touched.push(STORAGE_KEY_AI_AGENT_PROVIDER_MAP);
|
|
// The reconcile may also have pruned saved models alongside provider
|
|
// bindings, so always nudge the model map too.
|
|
if (!touched.includes(STORAGE_KEY_AI_AGENT_MODEL_MAP)) {
|
|
touched.push(STORAGE_KEY_AI_AGENT_MODEL_MAP);
|
|
}
|
|
if (ai.webSearchConfig !== undefined) touched.push(STORAGE_KEY_AI_WEB_SEARCH);
|
|
if (ai.quickMessages != null) touched.push(STORAGE_KEY_AI_QUICK_MESSAGES);
|
|
if (ai.showTerminalSelectionAction != null) {
|
|
touched.push(STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION);
|
|
}
|
|
for (const key of touched) {
|
|
emitAIStateChanged(key);
|
|
}
|
|
}
|
|
|
|
function pruneOrphanPerAgentBindings(): void {
|
|
const providers = localStorageAdapter.read<Array<{ id?: string }>>(STORAGE_KEY_AI_PROVIDERS) ?? [];
|
|
const validIds = new Set(
|
|
providers
|
|
.map((p) => p?.id)
|
|
.filter((id): id is string => typeof id === 'string' && id.length > 0),
|
|
);
|
|
const providerMap = localStorageAdapter.read<Record<string, string>>(STORAGE_KEY_AI_AGENT_PROVIDER_MAP) ?? {};
|
|
const modelMap = localStorageAdapter.read<Record<string, string>>(STORAGE_KEY_AI_AGENT_MODEL_MAP) ?? {};
|
|
let providerChanged = false;
|
|
let modelChanged = false;
|
|
const nextProviderMap: Record<string, string> = {};
|
|
const nextModelMap: Record<string, string> = { ...modelMap };
|
|
for (const agentId of Object.keys(providerMap)) {
|
|
const providerId = providerMap[agentId];
|
|
if (providerId && validIds.has(providerId)) {
|
|
nextProviderMap[agentId] = providerId;
|
|
} else {
|
|
providerChanged = true;
|
|
// Drop the saved model too — that id belonged to the now-missing
|
|
// provider and isn't trustworthy against any other binding.
|
|
if (agentId in nextModelMap) {
|
|
delete nextModelMap[agentId];
|
|
modelChanged = true;
|
|
}
|
|
}
|
|
}
|
|
if (providerChanged) {
|
|
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, nextProviderMap);
|
|
}
|
|
if (modelChanged) {
|
|
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, nextModelMap);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Builders
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/**
|
|
* Build a complete `SyncPayload` from local data.
|
|
*
|
|
* Port-forwarding rules are optional because they are managed by a separate
|
|
* state hook (`usePortForwardingState`). Callers should strip transient
|
|
* runtime fields (status, error, lastUsedAt) before passing them in.
|
|
*/
|
|
export function buildSyncPayload(
|
|
vault: SyncableVaultData,
|
|
portForwardingRules?: PortForwardingRule[],
|
|
): SyncPayload {
|
|
return {
|
|
hosts: vault.hosts,
|
|
keys: vault.keys,
|
|
identities: vault.identities,
|
|
proxyProfiles: vault.proxyProfiles,
|
|
snippets: vault.snippets,
|
|
customGroups: vault.customGroups,
|
|
snippetPackages: vault.snippetPackages,
|
|
notes: vault.notes,
|
|
noteGroups: vault.noteGroups,
|
|
groupConfigs: vault.groupConfigs,
|
|
portForwardingRules: sanitizePortForwardingRulesForSync(portForwardingRules),
|
|
settings: collectSyncableSettings(),
|
|
syncedAt: Date.now(),
|
|
};
|
|
}
|
|
|
|
export type PluginSyncSidecarCollector = () =>
|
|
| Promise<SyncPayload['pluginSidecars'] | null | undefined>
|
|
| SyncPayload['pluginSidecars']
|
|
| null
|
|
| undefined;
|
|
|
|
export type PluginSyncSidecarApplier = (
|
|
sidecars: SyncPayload['pluginSidecars'] | null | undefined,
|
|
) => Promise<void> | void;
|
|
|
|
/**
|
|
* Attach a host-collected plugin sidecar bundle to a cloud payload.
|
|
* Secrets must already be excluded by the collector; this only drops empty bundles.
|
|
*/
|
|
export function withPluginSyncSidecars(
|
|
payload: SyncPayload,
|
|
sidecars: SyncPayload['pluginSidecars'] | null | undefined,
|
|
): SyncPayload {
|
|
// null/undefined: collector unavailable — leave payload field unchanged
|
|
// (callers should reattach last-known before upload).
|
|
if (sidecars == null) {
|
|
return payload;
|
|
}
|
|
// Explicit empty entries is a real reset and must remain on the wire so
|
|
// apply paths can distinguish it from a legacy payload missing the field.
|
|
return {
|
|
...payload,
|
|
pluginSidecars: {
|
|
version: 1,
|
|
entries: Array.isArray(sidecars.entries) ? sidecars.entries : [],
|
|
},
|
|
};
|
|
}
|
|
|
|
async function defaultCollectPluginSyncSidecars(): Promise<SyncPayload['pluginSidecars'] | null | undefined> {
|
|
const { collectPluginSyncSidecarsFromHost } = await import('./pluginSyncSidecarBridge');
|
|
// Let operational failures (DB/runtime) propagate so cloud upload does not
|
|
// silently strip previously synced sidecars from the remote snapshot.
|
|
return collectPluginSyncSidecarsFromHost();
|
|
}
|
|
|
|
async function defaultApplyPluginSyncSidecars(
|
|
sidecars: SyncPayload['pluginSidecars'] | null | undefined,
|
|
): Promise<void> {
|
|
const {
|
|
applyPluginSyncSidecarsFromHost,
|
|
isPluginSidecarHostUnavailableError,
|
|
} = await import('./pluginSyncSidecarBridge');
|
|
try {
|
|
await applyPluginSyncSidecarsFromHost(sidecars);
|
|
} catch (error) {
|
|
// Only tolerate the host-gated-off / manager-unavailable path so a later
|
|
// plugin-enabled session can still apply from last-known cache. DB/runtime
|
|
// failures must fail the surrounding sync so the same remote is retried.
|
|
if (isPluginSidecarHostUnavailableError(error)) {
|
|
return;
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function buildCloudSyncPayload(
|
|
vault: SyncableVaultData,
|
|
portForwardingRules?: PortForwardingRule[],
|
|
options?: {
|
|
collectPluginSidecars?: PluginSyncSidecarCollector;
|
|
},
|
|
): Promise<SyncPayload> {
|
|
const base: SyncPayload = {
|
|
hosts: vault.hosts,
|
|
keys: vault.keys,
|
|
identities: vault.identities,
|
|
proxyProfiles: vault.proxyProfiles,
|
|
snippets: vault.snippets,
|
|
customGroups: vault.customGroups,
|
|
snippetPackages: vault.snippetPackages,
|
|
notes: vault.notes,
|
|
noteGroups: vault.noteGroups,
|
|
groupConfigs: vault.groupConfigs,
|
|
portForwardingRules: sanitizePortForwardingRulesForSync(portForwardingRules),
|
|
settings: await collectCloudSyncableSettings(),
|
|
syncedAt: Date.now(),
|
|
};
|
|
const collect = options?.collectPluginSidecars ?? defaultCollectPluginSyncSidecars;
|
|
const sidecars = await collect();
|
|
return withPluginSyncSidecars(base, sidecars);
|
|
}
|
|
|
|
/** Build a local backup/restore payload, including local-only trust records. */
|
|
export function buildLocalVaultPayload(
|
|
vault: SyncableVaultData,
|
|
portForwardingRules?: PortForwardingRule[],
|
|
): SyncPayload {
|
|
const base: SyncPayload = {
|
|
...buildSyncPayload(vault, portForwardingRules),
|
|
settings: collectLocalBackupSettings(),
|
|
knownHosts: vault.knownHosts,
|
|
};
|
|
// Protective backups must capture plugin sidecars so restore can recover
|
|
// plugin settings/baselines. Prefer the last successful host collect cache
|
|
// (sync). Callers that can await should use buildLocalVaultPayloadAsync.
|
|
try {
|
|
const raw = localStorageAdapter.read<{ version?: number; entries?: unknown }>(
|
|
SYNC_STORAGE_KEYS.PLUGIN_SIDECARS_LAST_KNOWN,
|
|
);
|
|
if (raw && Array.isArray(raw.entries)) {
|
|
return withPluginSyncSidecars(base, {
|
|
version: 1,
|
|
entries: raw.entries as NonNullable<SyncPayload['pluginSidecars']>['entries'],
|
|
});
|
|
}
|
|
} catch {
|
|
// ignore cache read failures; backup still carries vault entities
|
|
}
|
|
return base;
|
|
}
|
|
|
|
/**
|
|
* Async local backup payload that prefers a live host collect when available,
|
|
* then falls back to last-known cache. Use for protective/version-change backups.
|
|
*/
|
|
export async function buildLocalVaultPayloadAsync(
|
|
vault: SyncableVaultData,
|
|
portForwardingRules?: PortForwardingRule[],
|
|
): Promise<SyncPayload> {
|
|
const base = buildLocalVaultPayload(vault, portForwardingRules);
|
|
const {
|
|
collectPluginSyncSidecarsFromHost,
|
|
isPluginSidecarHostUnavailableError,
|
|
} = await import('./pluginSyncSidecarBridge');
|
|
try {
|
|
const live = await collectPluginSyncSidecarsFromHost();
|
|
if (live) {
|
|
// Live collect may return authoritative-empty while still deferring the
|
|
// last-known cache wipe until a successful sync commit. Protective
|
|
// backups must keep the non-empty last-known already attached to `base`.
|
|
const liveEmpty = !Array.isArray(live.entries) || live.entries.length === 0;
|
|
const baseHasEntries = Array.isArray(base.pluginSidecars?.entries)
|
|
&& base.pluginSidecars.entries.length > 0;
|
|
if (liveEmpty && baseHasEntries) {
|
|
return base;
|
|
}
|
|
return withPluginSyncSidecars(base, live);
|
|
}
|
|
} catch (error) {
|
|
// Only fall back to last-known when the host is gated off. Operational
|
|
// failures must abort protective backups so we never apply over data that
|
|
// was not captured in the safety snapshot.
|
|
if (!isPluginSidecarHostUnavailableError(error)) {
|
|
throw error;
|
|
}
|
|
}
|
|
return base;
|
|
}
|
|
|
|
/**
|
|
* Apply a downloaded `SyncPayload` to local state via the provided importers.
|
|
*
|
|
* This ensures both vault data and port-forwarding rules are imported
|
|
* consistently across windows.
|
|
*/
|
|
function applyPayload(
|
|
payload: SyncPayload,
|
|
importers: SyncPayloadImporters,
|
|
options: {
|
|
includeLocalOnlyData: boolean;
|
|
applyPluginSidecars?: PluginSyncSidecarApplier;
|
|
},
|
|
): Promise<void> {
|
|
const legacyLineTimestampsEnabled = payload.settings?.terminalSettings?.showLineTimestamps === true;
|
|
// Build the vault import object. Cloud sync intentionally ignores
|
|
// local-only trust records even if legacy cloud snapshots still carry them.
|
|
const vaultImport: Record<string, unknown> = {
|
|
hosts: migrateHostsFromLegacyLineTimestamps(payload.hosts, legacyLineTimestampsEnabled),
|
|
keys: payload.keys,
|
|
identities: payload.identities,
|
|
proxyProfiles: payload.proxyProfiles,
|
|
snippets: payload.snippets,
|
|
customGroups: payload.customGroups,
|
|
};
|
|
if (payload.snippetPackages !== undefined) {
|
|
vaultImport.snippetPackages = payload.snippetPackages;
|
|
}
|
|
if (payload.notes !== undefined) {
|
|
vaultImport.notes = payload.notes;
|
|
}
|
|
if (payload.noteGroups !== undefined) {
|
|
vaultImport.noteGroups = payload.noteGroups;
|
|
}
|
|
if (options.includeLocalOnlyData && payload.knownHosts !== undefined) {
|
|
vaultImport.knownHosts = payload.knownHosts;
|
|
}
|
|
if (Array.isArray(payload.groupConfigs)) {
|
|
vaultImport.groupConfigs = payload.groupConfigs;
|
|
}
|
|
|
|
return Promise.resolve(importers.importVaultData(JSON.stringify(vaultImport))).then(async () => {
|
|
// Only import port-forwarding rules when the payload explicitly carries
|
|
// them. Absent field = "payload was created before this feature existed",
|
|
// so local rules are preserved. Explicitly present [] = "remote has no
|
|
// rules, clear local state".
|
|
if (payload.portForwardingRules !== undefined && importers.importPortForwardingRules) {
|
|
importers.importPortForwardingRules(payload.portForwardingRules);
|
|
}
|
|
|
|
// Apply synced settings
|
|
if (payload.settings) {
|
|
await applySyncableSettings(payload.settings);
|
|
// Rehydrate in-memory bookmark snapshot after localStorage was updated
|
|
if (payload.settings.sftpGlobalBookmarks != null) rehydrateGlobalSftpBookmarks();
|
|
importers.onSettingsApplied?.();
|
|
}
|
|
|
|
// Plugin encrypted sidecars: only apply when the field is present so
|
|
// legacy payloads without pluginSidecars do not wipe installed settings.
|
|
if (Object.prototype.hasOwnProperty.call(payload, 'pluginSidecars')) {
|
|
const applySidecars = options.applyPluginSidecars ?? defaultApplyPluginSyncSidecars;
|
|
await applySidecars(payload.pluginSidecars ?? { version: 1, entries: [] });
|
|
}
|
|
});
|
|
}
|
|
|
|
export function applySyncPayload(
|
|
payload: SyncPayload,
|
|
importers: SyncPayloadImporters,
|
|
options?: {
|
|
applyPluginSidecars?: PluginSyncSidecarApplier;
|
|
},
|
|
): Promise<void> {
|
|
return applyPayload(payload, importers, {
|
|
includeLocalOnlyData: false,
|
|
applyPluginSidecars: options?.applyPluginSidecars,
|
|
});
|
|
}
|
|
|
|
export async function prepareLocalVaultPayloadApply(
|
|
payload: SyncPayload,
|
|
importers: SyncPayloadImporters,
|
|
dependencies: {
|
|
prepareConvergentRestore?: (
|
|
payload: SyncPayload,
|
|
) => Promise<() => Promise<void>>;
|
|
} = {},
|
|
): Promise<() => Promise<void>> {
|
|
const prepareConvergentRestore = dependencies.prepareConvergentRestore
|
|
?? prepareRestoredPayloadConvergentWrites;
|
|
const commitConvergentRestore = await prepareConvergentRestore(payload);
|
|
return async () => {
|
|
await applyPayload(payload, importers, { includeLocalOnlyData: true });
|
|
await commitConvergentRestore();
|
|
};
|
|
}
|
|
|
|
export async function applyLocalVaultPayload(
|
|
payload: SyncPayload,
|
|
importers: SyncPayloadImporters,
|
|
dependencies: {
|
|
prepareConvergentRestore?: (
|
|
payload: SyncPayload,
|
|
) => Promise<() => Promise<void>>;
|
|
} = {},
|
|
): Promise<void> {
|
|
const applyPreparedPayload = await prepareLocalVaultPayloadApply(
|
|
payload,
|
|
importers,
|
|
dependencies,
|
|
);
|
|
await applyPreparedPayload();
|
|
}
|