Files
Netcatty/domain/sync.ts
T
陈大猫andClaude Opus 4.7 53d3e05bb4 Per-agent provider switcher chip in the Catty Agent chat input (#1107)
* feat(ai): provider switcher chip in the Catty Agent chat input

Catty Agent currently has no model chip in the chat input — modelPresets
is empty for the catty agentId so `hasModelPicker` is false. The
provider/model the chat ends up using comes from the global
`activeProviderId` / `activeModelId`, which means switching providers
requires opening Settings → AI → Providers. Closes the gap surfaced in
the original feedback on #1101 (problem 2) and partially addresses
#986 (per-context model switching) by going per-agent.

State layer adds an `agentProviderMap` (`Record<agentId, providerId>`)
alongside the existing `agentModelMap`. Both are written together when
the user picks from the new dropdown; together they form a per-agent
override that beats the global active provider/model when set. Cross-
window sync mirrors the agentModelMap pattern.

ChatInput grows a `providerSwitcher` prop carrying the enabled
ProviderConfigs, the selected (providerId, modelId), and an onSelect
callback. When supplied, the model chip switches from the Cpu glyph
to the provider's ProviderIconBadge + `providerName · modelId`, and
the popover renders a two-column layout — providers on the left
(icon + name + default model caption), that provider's known model(s)
on the right. ACP agents (Claude/Codex) are untouched because they
plumb their provider through the CLI, not the Vercel AI SDK.

AIChatSidePanel resolves `effectiveActiveProvider` /
`effectiveActiveModelId` for the catty agent from the per-agent map,
falling back to the global selection. handleSend now passes those
through to sendToCattyAgent so a provider picked in one Catty session
applies everywhere Catty runs.

For v1, each provider's right column shows just its configured
`defaultModel`. The two-level structure is in place to absorb richer
listings (cached /models, manual additions) later without UI
surgery — left a note in the popover code.

Refs #1101, #986.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* polish(ai): flatten provider picker to a single list

Two-level dropdown was theatre — each ProviderConfig exposes exactly
one model (its `defaultModel`), so the right column ended up showing
the same string already captioned on the left row. Picking a provider
implicitly picks its model; one click is enough.

Also drops the `p.enabled !== false` filter on the picker list. The
user's expectation, confirmed by feedback on the first cut, is that
the chat-input list mirrors what Settings → AI → Providers shows. The
per-provider `enabled` toggle is an "active-ish" flag, not a
visibility gate; hiding disabled providers in the picker silently
made everything but the one currently active disappear, which is what
the reviewer hit.

Pares the popover down to a vertical list — provider icon + name +
default-model caption (mono if set, italic "configure default model"
hint if not) + a Check on the bound row. Removes the `hoveredProviderId`
state along with the right-column rendering since it's no longer
driving anything.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* polish(ai): tune provider icon sizes in the chat input

Chip icon was sitting at sm (20px badge) and crowded the h-6 toolbar
chip alongside the truncated label; popover rows used the same sm, so
nothing differentiated the picker from the chip visually.

Adds an xs size to ProviderIconBadge (16px badge, 10px glyph, 9px
letter fallback) and uses it on the chip. Popover rows step up to md
(32px badge, 16px glyph) and the row padding grows accordingly so the
larger brand mark has room to breathe — the picker now reads like a
list of choices, the chip reads like a status line.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ai): keep per-agent override honest in model fallback + chip label

Two codex P1/P2 findings on #1107:

P1 — When Catty has a per-agent provider override but no per-agent
model (agentModelMap['catty'] empty), cattyAgentModelId fell through
to the global `activeModelId`. That id belongs to whichever provider
was globally active, not the one Catty is now bound to, so e.g.
overriding to DeepSeek without a defaultModel happily sent gpt-4o
(global) to DeepSeek and produced a wrong-model error. The fallback
is now: stored agent model → override provider's defaultModel → empty.
Only the no-override path keeps the activeModelId tail; the
no-provider send guard catches the empty case for everyone else.

P2 — ChatInput's selectedSwitcherProvider used `?? providers[0]` so
the chip always displayed *some* provider even when none was actually
bound (selectedProviderId missing). The rest of the pipeline (send
guard, agentProviderMap) treats that as "no provider", so the chip
was lying. Dropped the fallback; when nothing is bound the chip now
shows a generic Cpu glyph + "Select provider" label until the user
picks one from the popover. Adds `ai.chat.selectProvider` in en /
zh-CN / ru.

Refs codex review on #1107.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ai): purge per-agent binding when the bound provider is deleted

Codex local review (round 2) flagged that a saved Catty model id could
outlive its provider. The chain:
- catty bound to provider A (DeepSeek): agentProviderMap['catty']='A',
  agentModelMap['catty']='deepseek-v4-flash'
- user deletes provider A
- cattyAgentProvider falls back to the global active provider (B, OpenAI)
- cattyAgentModelId still returned the saved 'deepseek-v4-flash'
- send dispatched the DeepSeek model id to OpenAI → wrong-model error

Two layers of fix:

1. **Defensive resolution** (AIChatSidePanel) — cattyAgentModelId now
   looks at the override provider before trusting the stored model id.
   If the override is stale (provider deleted), the stored model id is
   treated as orphan and the resolution falls back to the global active
   selection just like cattyAgentProvider already does.

2. **Cleanup on remove** (useAIState.removeProvider) — when a provider
   is deleted, any agent whose agentProviderMap entry pointed at it
   gets both maps cleared (provider override + saved model). Same
   rationale: that model id is now meaningless against every other
   provider. Mirrors the existing activeProviderId cleanup.

Adds a small agentProviderMapRef so removeProvider can snapshot which
agents to clean up without relying on the captured-at-callback-create
state (which would be stale).

Refs codex local review on #1107.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ai): include agentProviderMap in settings sync + block empty-model send

Codex local review (round 3) found two issues:

P2 — `agentProviderMap` was missing from the cross-device sync surface.
Added it to the sync key list, the build path, the apply path, and the
SyncPayload type alongside the existing `agentModelMap`. Sync tests in
`syncPayload.test.ts` now cover the new field on both the build and
apply sides.

P2 — Provider rows with no `defaultModel` were still clickable in the
chat-input picker, so selecting one would save a binding with empty
model id; the send path then dispatched an empty model name and the
SDK would surface a vague backend error. Two changes:

1. ChatInput disables the row (\`disabled\`, \`aria-disabled\`, dimmed
   styling, tooltip pointing the user to Settings) when the provider
   has no \`defaultModel\`. Click is suppressed.
2. AIChatSidePanel \`handleSend\` adds a model-required guard mirroring
   the existing no-provider guard — surfaces \`ai.chat.noProviderModel\`
   as an assistant message. Catches stale bindings (e.g. user edited
   the provider's \`defaultModel\` to empty after binding) before they
   reach the SDK.

Refs codex local review on #1107.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ai): trim whitespace-only model ids + reconcile orphan bindings on sync

Codex local review (round 4) found two more leaks:

P2 — Whitespace-only `defaultModel` passed the picker's `disabled` gate
(which trims) but every other layer (cattyAgentModelId resolution,
the send-guard `!sendActiveModelId` check, the SDK call) compared the
raw string. A provider whose default model was "   " could still reach
the SDK and surface a vague backend error. Normalized: trim at the
resolution boundary (catty model fallback chain) and trim before the
send-guard's existence check.

P2 — Sync apply did not reconcile per-agent bindings against the
incoming provider set. A payload could change `providers` without
shipping a fresh `agentProviderMap`, leaving local overrides pointing
to provider ids the synced set no longer includes — the same ghost-
binding bug that `removeProvider` already handles for explicit user
deletes. Added `pruneOrphanPerAgentBindings()` that runs after every
AI settings apply: it walks `agentProviderMap`, drops any entry whose
provider id isn't in the current `providers` list, and clears the
saved model id for those agents alongside it (mirroring removeProvider
cleanup). A new test in `syncPayload.test.ts` exercises the ghost-
binding case end-to-end.

Refs codex local review on #1107.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ai): notify open AI state of cross-device sync apply in the same window

Codex local review (round 4) flagged that `applySyncPayload` writes
straight to localStorage but `useAIState` only re-reads on browser
`storage` events. Those events only fire in *other* windows — the
window doing the apply (the one with the active chat panel) keeps
showing pre-sync providers and per-agent bindings until reload.
Concrete leak: cloud sync swaps in a new provider set, pruning runs,
localStorage is correct, but the open Catty chip still references the
ghost provider binding until the user reloads.

Extracts the existing `AI_STATE_CHANGED_EVENT` constant +
`emitAIStateChanged` helper out of `useAIState` and into a new
`application/state/aiStateEvents.ts` so non-React call sites (sync
apply, future IPC handlers) can fire it without pulling in the hook.
After AI settings apply, `syncPayload.ts` walks every AI key it
touched (including the agentProviderMap / agentModelMap that the
reconcile step may have mutated even when the payload didn't ship
them) and emits a same-window nudge. `useAIState`'s existing local
listener routes unknown keys back through its storage handler, so
each affected piece of React state rehydrates from localStorage.

Adds a regression test in `syncPayload.test.ts` that asserts the
expected `netcatty:ai-state-changed` keys are dispatched for the
providers + per-agent map keys.

Refs codex local review on #1107.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 00:03:08 +08:00

562 lines
17 KiB
TypeScript

/**
* Cloud Sync Domain Types & Interfaces
*
* Zero-Knowledge Encrypted Multi-Cloud Sync System
* Supports: GitHub Gist, Google Drive, Microsoft OneDrive, WebDAV, S3 Compatible
*/
import type { ShrinkFinding } from './syncGuards';
// ============================================================================
// Security State Machine
// ============================================================================
/**
* Global Security State Machine
* Controls access to sync operations based on master key status
*/
export type SecurityState =
| 'NO_KEY' // User has not set up a master key - block all sync
| 'LOCKED' // Master key exists but not in memory - show unlock screen
| 'UNLOCKED'; // Master key in memory - sync operations allowed
/**
* Sync Operation State Machine
* Tracks the current sync operation status
*/
export type SyncState =
| 'IDLE' // Waiting for sync trigger
| 'SYNCING' // Active sync operation in progress
| 'CONFLICT' // Version conflict detected - needs resolution
| 'BLOCKED' // Outgoing payload would delete too much — user must choose restore or force-push
| 'ERROR'; // Operation failed - needs attention
/**
* Conflict Resolution Strategy
*/
export type ConflictResolution =
| 'USE_REMOTE' // Download cloud data, overwrite local
| 'USE_LOCAL' // Upload local data, overwrite cloud
| 'AUTO_MERGED'; // Three-way merge was applied automatically
// ============================================================================
// Cloud Provider Types
// ============================================================================
/**
* Supported cloud storage providers
*/
export type CloudProvider = 'github' | 'google' | 'onedrive' | 'webdav' | 's3';
export type WebDAVAuthType = 'basic' | 'digest' | 'token';
export interface WebDAVConfig {
endpoint: string;
authType: WebDAVAuthType;
username?: string;
password?: string;
token?: string;
allowInsecure?: boolean;
}
export interface S3Config {
endpoint: string;
region: string;
bucket: string;
accessKeyId: string;
secretAccessKey: string;
sessionToken?: string;
prefix?: string;
forcePathStyle?: boolean;
}
/**
* Provider-specific connection status
*/
type ProviderConnectionStatus =
| 'disconnected'
| 'connecting'
| 'connected'
| 'syncing'
| 'error';
/**
* OAuth token storage structure
*/
export interface OAuthTokens {
accessToken: string;
refreshToken?: string;
expiresAt?: number; // Unix timestamp
tokenType: string;
scope?: string;
}
/**
* Provider account information
*/
export interface ProviderAccount {
id: string;
email?: string;
name?: string;
avatarUrl?: string;
}
/**
* Cloud provider connection state
*/
export interface ProviderConnection {
provider: CloudProvider;
status: ProviderConnectionStatus;
account?: ProviderAccount;
tokens?: OAuthTokens;
config?: WebDAVConfig | S3Config;
lastSync?: number; // Unix timestamp
lastSyncVersion?: number;
resourceId?: string; // gistId / fileId / itemId
error?: string;
}
const hasProviderConnectionData = (
connection: Pick<ProviderConnection, 'tokens' | 'config'>,
): boolean => Boolean(connection.tokens || connection.config);
export const isProviderReadyForSync = (
connection: Pick<ProviderConnection, 'status' | 'tokens' | 'config'>,
): boolean =>
connection.status === 'connected'
|| connection.status === 'syncing'
|| (connection.status === 'error' && hasProviderConnectionData(connection));
// ============================================================================
// Encrypted Sync File Schema
// ============================================================================
/**
* Sync file metadata (stored in plaintext for version control)
*/
export interface SyncFileMeta {
version: number; // Incremental version number
updatedAt: number; // Unix timestamp (ms)
deviceId: string; // UUID identifying the device
deviceName?: string; // Human-readable device name
appVersion: string; // App version that created this sync
iv: string; // AES-GCM initialization vector (Base64)
salt: string; // KDF salt for key derivation (Base64)
algorithm: 'AES-256-GCM'; // Encryption algorithm identifier
kdf: 'PBKDF2' | 'Argon2id'; // Key derivation function
kdfIterations?: number; // PBKDF2 iterations (if applicable)
}
/**
* Complete synced file structure
* The payload contains all encrypted user data
*/
export interface SyncedFile {
meta: SyncFileMeta;
payload: string; // Base64 encrypted ciphertext
}
/**
* Decrypted payload structure - contains all syncable data
*/
export interface SyncPayload {
// Core vault data
hosts: import('./models').Host[];
keys: import('./models').SSHKey[];
identities?: import('./models').Identity[];
proxyProfiles?: import('./models').ProxyProfile[];
snippets: import('./models').Snippet[];
customGroups: string[];
snippetPackages?: string[];
// Group configs (connection defaults per host group)
groupConfigs?: import('./models').GroupConfig[];
// Port forwarding rules
portForwardingRules?: import('./models').PortForwardingRule[];
// Known hosts
knownHosts?: import('./models').KnownHost[];
// Settings
settings?: {
// Theme & Appearance
theme?: 'light' | 'dark' | 'system';
lightUiThemeId?: string;
darkUiThemeId?: string;
accentMode?: 'theme' | 'custom';
customAccent?: string;
uiFontFamilyId?: string;
uiLanguage?: string;
customCSS?: string;
// Terminal
terminalTheme?: string;
followAppTerminalTheme?: boolean;
terminalThemeDark?: string;
terminalThemeLight?: string;
terminalFontFamily?: string;
terminalFontSize?: number;
terminalSettings?: Record<string, unknown>;
customTerminalThemes?: Array<{ id: string; name: string; colors: Record<string, string> }>;
// Keyboard
customKeyBindings?: Record<string, { mac?: string; pc?: string }>;
// Editor
editorWordWrap?: boolean;
// SFTP
sftpDoubleClickBehavior?: 'open' | 'transfer';
sftpAutoSync?: boolean;
sftpShowHiddenFiles?: boolean;
sftpUseCompressedUpload?: boolean;
sftpAutoOpenSidebar?: boolean;
sftpDefaultViewMode?: 'list' | 'tree';
sftpGlobalBookmarks?: import('./models').SftpBookmark[];
// Immersive mode
immersiveMode?: boolean;
// Vault: show recently connected hosts
showRecentHosts?: boolean;
// Vault: root list shows only ungrouped hosts
showOnlyUngroupedHostsInRoot?: boolean;
// Top tabs: show standalone SFTP view tab
showSftpTab?: boolean;
// Workspace focus indicator style
workspaceFocusStyle?: 'dim' | 'border';
// AI configuration
ai?: {
providers?: Array<Record<string, unknown>>;
activeProviderId?: string;
activeModelId?: string;
globalPermissionMode?: 'observer' | 'confirm' | 'autonomous';
toolIntegrationMode?: 'mcp' | 'skills';
hostPermissions?: Array<Record<string, unknown>>;
// externalAgents intentionally omitted: command/args/env are device-local
// (binary paths, OS-specific values) and don't survive cross-device sync.
defaultAgentId?: string;
commandBlocklist?: string[];
commandTimeout?: number;
maxIterations?: number;
agentModelMap?: Record<string, string>;
agentProviderMap?: Record<string, string>;
webSearchConfig?: Record<string, unknown> | null;
};
};
// Sync metadata
syncedAt: number; // When this payload was created
}
export const SYNC_PAYLOAD_ENTITY_KEYS = [
'hosts',
'keys',
'identities',
'proxyProfiles',
'snippets',
'customGroups',
'snippetPackages',
'portForwardingRules',
'knownHosts',
'groupConfigs',
] as const;
export const CLOUD_SYNC_PAYLOAD_ENTITY_KEYS = [
'hosts',
'keys',
'identities',
'proxyProfiles',
'snippets',
'customGroups',
'snippetPackages',
'portForwardingRules',
'groupConfigs',
] as const;
export type SyncPayloadEntityKey = typeof SYNC_PAYLOAD_ENTITY_KEYS[number];
export type CloudSyncPayloadEntityKey = typeof CLOUD_SYNC_PAYLOAD_ENTITY_KEYS[number];
export function hasSyncPayloadEntityData(
payload: SyncPayload,
keys: readonly SyncPayloadEntityKey[] = SYNC_PAYLOAD_ENTITY_KEYS,
): boolean {
return keys.some((key) => {
const value = payload[key];
return Array.isArray(value) && value.length > 0;
});
}
// ============================================================================
// Encryption Types
// ============================================================================
/**
* Encryption result
*/
export interface EncryptionResult {
ciphertext: Uint8Array;
iv: Uint8Array;
salt: Uint8Array;
algorithm: 'AES-256-GCM';
kdf: 'PBKDF2' | 'Argon2id';
kdfIterations?: number;
}
/**
* Decryption input
*/
export interface DecryptionInput {
ciphertext: Uint8Array;
iv: Uint8Array;
salt: Uint8Array;
kdf: 'PBKDF2' | 'Argon2id';
kdfIterations?: number;
}
// ============================================================================
// Master Key Types
// ============================================================================
/**
* Master key configuration stored in safeStorage
*/
export interface MasterKeyConfig {
// Verification hash to confirm correct password
verificationHash: string; // Base64 of hash(derived_key)
salt: string; // Base64 KDF salt
kdf: 'PBKDF2' | 'Argon2id';
kdfIterations?: number;
createdAt: number;
}
/**
* Unlocked master key state (in memory only)
*/
export interface UnlockedMasterKey {
derivedKey: CryptoKey; // AES-256-GCM key
salt: Uint8Array;
unlockedAt: number;
}
// ============================================================================
// Sync Manager Types
// ============================================================================
/**
* Sync operation result
*/
export interface SyncResult {
success: boolean;
provider: CloudProvider;
action: 'upload' | 'download' | 'merge' | 'none';
version?: number;
error?: string;
conflictDetected?: boolean;
/** Present when action === 'merge'; caller should apply this to update local state */
mergedPayload?: import('./sync').SyncPayload;
/** True when a shrink-detection guard blocked the upload */
shrinkBlocked?: boolean;
/** The finding that triggered the shrink block or force-push */
finding?: ShrinkFinding;
}
/**
* Conflict information for UI
*/
export interface ConflictInfo {
provider: CloudProvider;
localVersion: number;
localUpdatedAt: number;
localDeviceName?: string;
remoteVersion: number;
remoteUpdatedAt: number;
remoteDeviceName?: string;
}
/**
* Sync history record entry
*/
export interface SyncHistoryEntry {
id: string;
timestamp: number;
provider: CloudProvider;
action: 'upload' | 'download' | 'merge' | 'conflict_resolved';
success: boolean;
localVersion: number;
remoteVersion?: number;
deviceName?: string;
error?: string;
}
// ============================================================================
// OAuth Flow Types
// ============================================================================
/**
* GitHub Device Flow response
*/
export interface GitHubDeviceCodeResponse {
device_code: string;
user_code: string;
verification_uri: string;
expires_in: number;
interval: number;
}
/**
* OAuth PKCE challenge
*/
export interface PKCEChallenge {
codeVerifier: string;
codeChallenge: string;
state: string;
}
// ============================================================================
// Event Types
// ============================================================================
/**
* Sync event for UI updates
*/
export type SyncEvent =
| { type: 'SYNC_STARTED'; provider: CloudProvider }
| { type: 'SYNC_PROGRESS'; provider: CloudProvider; progress: number; message: string }
| { type: 'SYNC_COMPLETED'; provider: CloudProvider; result: SyncResult }
| { type: 'SYNC_ERROR'; provider: CloudProvider; error: string }
| { type: 'CONFLICT_DETECTED'; conflict: ConflictInfo }
| { type: 'SYNC_BLOCKED_SHRINK'; provider: CloudProvider; finding: ShrinkFinding }
| { type: 'SYNC_FORCED'; provider: CloudProvider; finding: ShrinkFinding }
| { type: 'CONFLICT_RESOLVED'; resolution: ConflictResolution }
| { type: 'AUTH_REQUIRED'; provider: CloudProvider }
| { type: 'AUTH_COMPLETED'; provider: CloudProvider; account: ProviderAccount }
| { type: 'SECURITY_STATE_CHANGED'; state: SecurityState }
| { type: 'SYNC_BLOCKED_CLEARED' }
| {
type: 'PROVIDERS_DIVERGED';
summaries: Array<{
provider: CloudProvider;
hosts: number;
keys: number;
snippets: number;
}>;
};
// ============================================================================
// Storage Keys
// ============================================================================
export const SYNC_STORAGE_KEYS = {
MASTER_KEY_CONFIG: 'netcatty_master_key_config_v1',
DEVICE_ID: 'netcatty_device_id_v1',
DEVICE_NAME: 'netcatty_device_name_v1',
SYNC_CONFIG: 'netcatty_sync_config_v2',
PROVIDER_GITHUB: 'netcatty_provider_github_v1',
PROVIDER_GOOGLE: 'netcatty_provider_google_v1',
PROVIDER_ONEDRIVE: 'netcatty_provider_onedrive_v1',
PROVIDER_WEBDAV: 'netcatty_provider_webdav_v1',
PROVIDER_S3: 'netcatty_provider_s3_v1',
PROVIDER_SMB: 'netcatty_provider_smb_v1',
LOCAL_SYNC_META: 'netcatty_local_sync_meta_v1',
SYNC_BASE_PAYLOAD: 'netcatty_sync_base_payload_v1',
} as const;
// ============================================================================
// Constants
// ============================================================================
const readBuildEnv = (key: string): string | undefined => {
const env = (import.meta as { env?: Record<string, string | undefined> }).env;
const value = env?.[key];
return value && value.trim().length ? value : undefined;
};
export const SYNC_CONSTANTS = {
// Encryption
AES_KEY_LENGTH: 256,
GCM_IV_LENGTH: 12, // bytes
GCM_TAG_LENGTH: 128, // bits
SALT_LENGTH: 32, // bytes
// PBKDF2
PBKDF2_ITERATIONS: 600000, // OWASP recommended minimum
PBKDF2_HASH: 'SHA-256',
// Sync
SYNC_FILE_NAME: 'netcatty-vault.json',
GIST_DESCRIPTION: 'Netcatty Encrypted Vault (DO NOT EDIT MANUALLY)',
// Auto-sync
DEFAULT_AUTO_SYNC_INTERVAL: 5, // minutes
MIN_SYNC_INTERVAL: 1, // minutes
MAX_SYNC_INTERVAL: 60, // minutes
// OAuth
GITHUB_CLIENT_ID: readBuildEnv('VITE_SYNC_GITHUB_CLIENT_ID') || '', // Public client ID for Device Flow
GOOGLE_CLIENT_ID: readBuildEnv('VITE_SYNC_GOOGLE_CLIENT_ID') || '',
GOOGLE_CLIENT_SECRET: readBuildEnv('VITE_SYNC_GOOGLE_CLIENT_SECRET') || '',
ONEDRIVE_CLIENT_ID: readBuildEnv('VITE_SYNC_ONEDRIVE_CLIENT_ID') || '',
// API endpoints
GITHUB_DEVICE_CODE_URL: 'https://github.com/login/device/code',
GITHUB_ACCESS_TOKEN_URL: 'https://github.com/login/oauth/access_token',
GITHUB_API_BASE: 'https://api.github.com',
GOOGLE_AUTH_URL: 'https://accounts.google.com/o/oauth2/v2/auth',
GOOGLE_TOKEN_URL: 'https://oauth2.googleapis.com/token',
GOOGLE_DRIVE_API: 'https://www.googleapis.com/drive/v3',
ONEDRIVE_AUTH_URL: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize',
ONEDRIVE_TOKEN_URL: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token',
ONEDRIVE_GRAPH_API: 'https://graph.microsoft.com/v1.0',
} as const;
// ============================================================================
// Helper Functions
// ============================================================================
/**
* Generate a unique device ID
*/
export const generateDeviceId = (): string => {
return crypto.randomUUID();
};
/**
* Get default device name based on OS
*/
export const getDefaultDeviceName = (): string => {
const platform = navigator.platform || 'Unknown';
const hostname = 'Netcatty';
return `${hostname} (${platform})`;
};
/**
* Format last sync time for display
*/
export const formatLastSync = (timestamp?: number): string => {
if (!timestamp) return 'Never synced';
const now = Date.now();
const diff = now - timestamp;
if (diff < 60000) return 'Just now';
if (diff < 3600000) return `${Math.floor(diff / 60000)} min ago`;
if (diff < 86400000) {
const date = new Date(timestamp);
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
const date = new Date(timestamp);
return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
};
/**
* Get status dot color class
*/
export const getSyncDotColor = (status: ProviderConnectionStatus): string => {
switch (status) {
case 'connected': return 'bg-green-500';
case 'syncing': return 'bg-blue-500';
case 'error': return 'bg-red-500';
case 'connecting': return 'bg-yellow-500';
default: return 'bg-muted-foreground';
}
};