feat(desktop): two-way cloud sync with mobile and web
Rewrites the desktop mirror as services/sync/SyncEngine: a persistent outbox, per-account server-clock keyset cursors with paging, pulls that never overwrite unsent local edits, deletions both ways through sync_tombstones and per-row failure isolation. It now covers history titles and favorites, dictionary, every meeting's memos and documents, memo tags, user commands and dictation/meeting templates, and registers the desktop as a device that the phone can disconnect. Fixes shipped defects: the first pull after sign-in fetched nothing, only the first meeting's children were pushed, team meetings leaked into the personal database and lost team_id on re-push, and Realtime never connected because Electron's Node 20 has no global WebSocket (ws is now the transport). Anonymous local-mode records are imported into the first account that signs in. The settings sync section is translated and shows pending/rejected changes; synced screens reload on app:dataChanged.
This commit is contained in:
parent
b5c9ff9f31
commit
0a4f5aee64
49 changed files with 3940 additions and 1033 deletions
|
|
@ -85,7 +85,7 @@ function archiveLegacyDbIfExists(): void {
|
|||
// 스키마 적용 (테이블 생성 + 인라인 ALTER 마이그레이션)
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
function applySchema(s: Database.Database): void {
|
||||
export function applySchema(s: Database.Database): void {
|
||||
s.pragma('journal_mode = WAL')
|
||||
s.pragma('foreign_keys = ON')
|
||||
s.pragma('busy_timeout = 5000')
|
||||
|
|
@ -378,6 +378,49 @@ function applySchema(s: Database.Database): void {
|
|||
`summary_text migration check failed: ${err instanceof Error ? err.message : String(err)}`
|
||||
)
|
||||
}
|
||||
|
||||
// 기기 간 동기화: 모바일과 같은 필드(즐겨찾기, 메모 수정 시각) + 로컬 outbox/커서
|
||||
addColumnIfMissing(s, 'history', 'is_favorite', 'INTEGER NOT NULL DEFAULT 0')
|
||||
addColumnIfMissing(s, 'meeting_memos', 'updated_at', 'INTEGER')
|
||||
s.exec(`
|
||||
CREATE TABLE IF NOT EXISTS sync_outbox (
|
||||
entity TEXT NOT NULL,
|
||||
row_id TEXT NOT NULL,
|
||||
op TEXT NOT NULL,
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
queued_at INTEGER NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_attempt_at INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT,
|
||||
PRIMARY KEY (entity, row_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sync_outbox_due ON sync_outbox(next_attempt_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_state (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
`)
|
||||
}
|
||||
|
||||
function addColumnIfMissing(
|
||||
s: Database.Database,
|
||||
table: string,
|
||||
column: string,
|
||||
definition: string
|
||||
): void {
|
||||
try {
|
||||
const columns = s.pragma(`table_info(${table})`) as Array<{ name: string }>
|
||||
if (!columns.some((c) => c.name === column)) {
|
||||
s.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`)
|
||||
logger.info(`Migrated: added ${column} column to ${table}`)
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
`${table}.${column} migration check failed: ${err instanceof Error ? err.message : String(err)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
|
@ -494,6 +537,102 @@ export function isDatabaseOpen(): boolean {
|
|||
return db !== null
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// 익명 로컬 데이터 → 계정 DB 가져오기
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** 가져올 테이블. 입력 텔레메트리·RAG 색인 등 기기 전용 데이터는 옮기지 않는다. */
|
||||
const IMPORTABLE_TABLES = [
|
||||
'history',
|
||||
'dictionary',
|
||||
'memo_tags',
|
||||
'meeting_sessions',
|
||||
'meeting_memos',
|
||||
'meeting_documents',
|
||||
] as const
|
||||
|
||||
const LOCAL_CLAIM_KEY = 'claimedBy'
|
||||
const IMPORT_DONE_KEY = 'localImport:v1'
|
||||
|
||||
export interface LocalImportResult {
|
||||
imported: number
|
||||
tables: Record<string, number>
|
||||
}
|
||||
|
||||
function tableColumns(s: Database.Database, schemaName: string, table: string): string[] {
|
||||
const rows = s.pragma(`${schemaName}.table_info(${table})`) as Array<{ name: string }>
|
||||
return rows.map((r) => r.name)
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그인 전(익명 로컬 모드)에 쌓인 기록을 현재 열린 계정 DB로 복사한다.
|
||||
* - 계정 DB마다 한 번만(sync_state 플래그), 익명 DB는 처음 가져간 계정 하나만(claimedBy) 가져간다.
|
||||
* - 원본은 지우지 않는다. 같은 id·같은 단어는 건너뛴다(INSERT OR IGNORE).
|
||||
* - 옛 DB는 컬럼 순서가 다를 수 있어 양쪽에 모두 있는 컬럼만 이름으로 복사한다.
|
||||
* 가져온 행은 이후 동기화의 최초 대조(backfill)가 서버로 올린다.
|
||||
*/
|
||||
export function importLocalModeData(): LocalImportResult | null {
|
||||
if (!sqlite || !currentUserId || currentUserId === LOCAL_USER_ID) return null
|
||||
const s = sqlite
|
||||
const userId = currentUserId
|
||||
const done = s.prepare('SELECT value FROM sync_state WHERE key = ?').get(IMPORT_DONE_KEY) as
|
||||
| { value: string }
|
||||
| undefined
|
||||
if (done) return null
|
||||
|
||||
const localPath = getUserDbPath(LOCAL_USER_ID)
|
||||
const markDone = (): void => {
|
||||
s.prepare(
|
||||
'INSERT OR REPLACE INTO sync_state(key, value, updated_at) VALUES (?, ?, ?)'
|
||||
).run(IMPORT_DONE_KEY, String(Date.now()), Date.now())
|
||||
}
|
||||
if (!fs.existsSync(localPath)) {
|
||||
markDone()
|
||||
return null
|
||||
}
|
||||
|
||||
s.prepare('ATTACH DATABASE ? AS anon').run(localPath)
|
||||
try {
|
||||
s.exec(`CREATE TABLE IF NOT EXISTS anon.sync_state (
|
||||
key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at INTEGER NOT NULL
|
||||
)`)
|
||||
const claim = s.prepare('SELECT value FROM anon.sync_state WHERE key = ?').get(LOCAL_CLAIM_KEY) as
|
||||
| { value: string }
|
||||
| undefined
|
||||
if (claim && claim.value !== userId) {
|
||||
logger.info(`Local-mode data already imported by another account; skipping for ${userId}`)
|
||||
markDone()
|
||||
return null
|
||||
}
|
||||
|
||||
const result: LocalImportResult = { imported: 0, tables: {} }
|
||||
const copy = s.transaction(() => {
|
||||
for (const table of IMPORTABLE_TABLES) {
|
||||
const sourceColumns = tableColumns(s, 'anon', table)
|
||||
if (sourceColumns.length === 0) continue
|
||||
const targetColumns = new Set(tableColumns(s, 'main', table))
|
||||
const columns = sourceColumns.filter((c) => targetColumns.has(c)).map((c) => `"${c}"`)
|
||||
if (columns.length === 0) continue
|
||||
const list = columns.join(', ')
|
||||
const info = s
|
||||
.prepare(`INSERT OR IGNORE INTO main.${table} (${list}) SELECT ${list} FROM anon.${table}`)
|
||||
.run()
|
||||
result.tables[table] = info.changes
|
||||
result.imported += info.changes
|
||||
}
|
||||
s.prepare(
|
||||
'INSERT OR REPLACE INTO anon.sync_state(key, value, updated_at) VALUES (?, ?, ?)'
|
||||
).run(LOCAL_CLAIM_KEY, userId, Date.now())
|
||||
markDone()
|
||||
})
|
||||
copy()
|
||||
logger.info(`Imported ${result.imported} local-mode row(s) into ${userId}: ${JSON.stringify(result.tables)}`)
|
||||
return result
|
||||
} finally {
|
||||
s.exec('DETACH DATABASE anon')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트/개발용 — 현재 오픈된 DB 경로 조회.
|
||||
*/
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue