Compare commits
No commits in common. "3f1fb8eed5d493995f4bc854f8457a3b456cb3c5" and "3d9faedf7de257bc01703c4d95a263878a91b65c" have entirely different histories.
3f1fb8eed5
...
3d9faedf7d
66 changed files with 124 additions and 1548 deletions
19
CHANGELOG.md
19
CHANGELOG.md
|
|
@ -12,25 +12,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
- Additional Whisper model management UI
|
||||
- Plugin system for custom pipelines
|
||||
|
||||
## [1.8.0] - 2026-09-27
|
||||
|
||||
> Published from an annotated tag. Installer and update metadata are served by the
|
||||
> canonical Forgejo feed; no binaries are committed to this repository.
|
||||
|
||||
### Added
|
||||
- **Knowledge base syncs with your phone.** Documents added on the desktop can be
|
||||
searched on the phone and web, and documents added there appear on the desktop and
|
||||
are indexed with the local model. Deleting one removes it everywhere.
|
||||
- **Recordings sync and play anywhere.** Desktop recordings are uploaded (up to 50 MB
|
||||
each, can be turned off in Settings > Cloud) so the phone can play them, and each
|
||||
history card has a play button that also plays recordings made on the phone.
|
||||
- **Shared settings.** Language (Korean/English), light/dark/system theme,
|
||||
auto-polish on or off and the active command follow the phone.
|
||||
|
||||
### Fixed
|
||||
- A document's text is kept even when the local embedding model is unavailable, so
|
||||
it can be indexed later without the original file.
|
||||
|
||||
## [1.7.0] - 2026-09-27
|
||||
|
||||
> Published from an annotated tag. Installer and update metadata are served by the
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
"info": {
|
||||
"title": "D3RO-VOICE Admin API",
|
||||
"description": "Admin CRM Edge Functions for user management, subscription CRUD, payment history, and audit logs.",
|
||||
"version": "1.8.0"
|
||||
"version": "1.7.0"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/admin",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice Admin CRM — SaaS 관리 도구",
|
||||
"scripts": {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Version>1.8.0</Version>
|
||||
<Version>1.7.0</Version>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/desktop",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"productName": "d3ro-voice",
|
||||
"description": "로컬 AI 음성 어시스턴트 (Electron)",
|
||||
"main": "./out/main/index.js",
|
||||
|
|
|
|||
|
|
@ -6,9 +6,6 @@ import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
|||
import { ipcSuccess, ipcError, ErrorCode, D3ROError } from '@d3ro/core/errors'
|
||||
import { getCloudSyncService } from '../services/CloudSyncService'
|
||||
import { getLogger } from '../services/LoggerService'
|
||||
import { onConfigChanged } from '../services/ConfigService'
|
||||
import { isApplyingRemoteSettings } from '../services/sync/settings-sync'
|
||||
import { reapplyThemeToAllPopups } from '../windows/WindowManager'
|
||||
|
||||
const logger = getLogger('cloud-sync-handlers')
|
||||
|
||||
|
|
@ -118,13 +115,6 @@ export function registerCloudSyncHandlers(): void {
|
|||
broadcast(IPC_CHANNELS.CLOUD_SYNC.SYNC_ERROR, payload)
|
||||
})
|
||||
// 다른 기기의 변경이 반영되면 앱 공통 새로고침 신호로 알린다 (이력·사전·회의·명령 화면이 구독).
|
||||
// 동기화가 메인에서 바꾼 설정(언어·테마 등)을 화면에도 알린다 — IPC로 바꿀 때만 방송되던 경로.
|
||||
onConfigChanged((event) => {
|
||||
if (!isApplyingRemoteSettings()) return
|
||||
broadcast(IPC_CHANNELS.CONFIG.CHANGED, event)
|
||||
if (event.key === 'theme') reapplyThemeToAllPopups()
|
||||
})
|
||||
|
||||
sync.on('data-changed', (payload) => {
|
||||
broadcast(IPC_CHANNELS.APP.DATA_CHANGED, { type: 'cloud-sync', entities: payload.entities })
|
||||
})
|
||||
|
|
|
|||
|
|
@ -3,22 +3,15 @@
|
|||
import { ipcMain } from 'electron'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
|
||||
import fs from 'fs'
|
||||
import { getHistoryService } from '../services/HistoryService'
|
||||
import { getCloudSyncService } from '../services/CloudSyncService'
|
||||
import { audioMimeType } from '../services/sync/audio-sync'
|
||||
import type {
|
||||
HistoryQueryParams,
|
||||
HistoryGetByIdParams,
|
||||
HistoryDeleteParams,
|
||||
HistorySearchParams,
|
||||
HistorySetFavoriteParams,
|
||||
HistoryAudioSource
|
||||
HistorySetFavoriteParams
|
||||
} from '@d3ro/core/types'
|
||||
|
||||
/** 렌더러로 넘기는 로컬 녹음 상한. 넘으면 재생하지 않는다(IPC 복사 비용). */
|
||||
const MAX_LOCAL_AUDIO_BYTES = 100 * 1024 * 1024
|
||||
|
||||
export function registerHistoryHandlers(): void {
|
||||
ipcMain.handle(IPC_CHANNELS.HISTORY.GET_ALL, async (_event, params: HistoryQueryParams) => {
|
||||
try {
|
||||
|
|
@ -74,27 +67,6 @@ export function registerHistoryHandlers(): void {
|
|||
}
|
||||
})
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.HISTORY.GET_AUDIO, async (_event, params: HistoryGetByIdParams) => {
|
||||
try {
|
||||
const entry = getHistoryService().getById(params.id)
|
||||
if (!entry) return ipcError(ErrorCode.HistoryNotFound, `History entry not found: ${params.id}`)
|
||||
const localPath = entry.audioLocalPath
|
||||
if (localPath && fs.existsSync(localPath) && fs.statSync(localPath).size <= MAX_LOCAL_AUDIO_BYTES) {
|
||||
const source: HistoryAudioSource = {
|
||||
kind: 'local',
|
||||
bytes: new Uint8Array(fs.readFileSync(localPath)),
|
||||
mimeType: audioMimeType(localPath) ?? 'audio/wav',
|
||||
}
|
||||
return ipcSuccess(source)
|
||||
}
|
||||
const url = await getCloudSyncService().createHistoryAudioUrl(params.id)
|
||||
return ipcSuccess(url ? ({ kind: 'remote', url } satisfies HistoryAudioSource) : null)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return ipcError(ErrorCode.DBQueryFailed, `Failed to load audio: ${message}`)
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.HISTORY.SEARCH, async (_event, params: HistorySearchParams) => {
|
||||
try {
|
||||
return ipcSuccess(getHistoryService().search(params))
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import {
|
|||
type RealtimeChannel
|
||||
} from '@supabase/supabase-js'
|
||||
import { getLogger } from './LoggerService'
|
||||
import { configGet, configSet, onConfigChanged } from './ConfigService'
|
||||
import { configGet, configSet } from './ConfigService'
|
||||
import { SUPABASE_URL, SUPABASE_ANON_KEY } from '@d3ro/core/supabase-config'
|
||||
import { openForUser, openLocal, closeCurrent, getCurrentUserId, importLocalModeData } from '../db'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
|
|
@ -24,8 +24,6 @@ import { enqueueChange, getSyncState, setSyncState } from './sync/sync-outbox'
|
|||
import { checkInDesktopDevice, currentDeviceInfo, unregisterDesktopDevice } from './sync/device-registration'
|
||||
import type { SyncEntity, SyncRunResult } from './sync/sync-types'
|
||||
import { nodeRealtimeTransport } from './sync/realtime-transport'
|
||||
import { SETTINGS_ROW_ID, SYNCED_CONFIG_KEYS, isApplyingRemoteSettings } from './sync/settings-sync'
|
||||
import { AUDIO_BUCKET, listLocalAudioOwners } from './sync/audio-sync'
|
||||
|
||||
const logger = getLogger('CloudSyncService')
|
||||
|
||||
|
|
@ -48,8 +46,6 @@ const REALTIME_TABLES = [
|
|||
'memo_tags',
|
||||
'custom_instructions',
|
||||
'user_templates',
|
||||
'knowledge_documents',
|
||||
'user_settings',
|
||||
'sync_tombstones',
|
||||
] as const
|
||||
|
||||
|
|
@ -129,23 +125,6 @@ class CloudSyncService extends EventEmitter {
|
|||
|
||||
this._lastSyncAt = (configGet('cloudSyncLastAt') as number | undefined) ?? null
|
||||
|
||||
// 언어·테마·자동 다듬기·활성 명령이 바뀌면 모바일 user_settings 로 올린다(원격 반영 중엔 제외).
|
||||
onConfigChanged((event) => {
|
||||
if (isApplyingRemoteSettings()) return
|
||||
if ((SYNCED_CONFIG_KEYS as readonly string[]).includes(event.key)) {
|
||||
this.pushOne('user_settings', SETTINGS_ROW_ID)
|
||||
}
|
||||
// 녹음 동기화를 켜면 그동안 올리지 않은 녹음을 올린다.
|
||||
if (event.key === 'cloudSyncAudio' && event.value === true && this._engine) {
|
||||
try {
|
||||
for (const id of listLocalAudioOwners('history')) this.pushOne('history_audio', id)
|
||||
for (const id of listLocalAudioOwners('meeting')) this.pushOne('meeting_audio', id)
|
||||
} catch (err) {
|
||||
logger.warn(`Audio re-queue failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 저장된 refresh token 복원
|
||||
const stored = this._loadStoredRefreshToken()
|
||||
if (stored) {
|
||||
|
|
@ -934,29 +913,6 @@ class CloudSyncService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 다른 기기(모바일·웹)에서 녹음한 기록의 재생 URL(5분 서명). 로컬 파일이 없을 때만 쓴다.
|
||||
* 로그인 전이거나 서버에 녹음이 없으면 null.
|
||||
*/
|
||||
async createHistoryAudioUrl(historyId: string): Promise<string | null> {
|
||||
const client = this._client
|
||||
const session = this._session
|
||||
if (!client || !session) return null
|
||||
const { data, error } = await client
|
||||
.from('audio_files')
|
||||
.select('storage_key,upload_status')
|
||||
.eq('user_id', session.user.id)
|
||||
.eq('history_id', historyId)
|
||||
.eq('upload_status', 'uploaded')
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (error || !data || typeof data.storage_key !== 'string') return null
|
||||
if (!data.storage_key.startsWith(`${session.user.id}/`)) return null
|
||||
const signed = await client.storage.from(AUDIO_BUCKET).createSignedUrl(data.storage_key, 300)
|
||||
return signed.error ? null : signed.data.signedUrl
|
||||
}
|
||||
|
||||
getSyncStatus(): SyncStatus | null {
|
||||
if (!this._engine) return null
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -158,7 +158,6 @@ const CONFIG_DEFAULTS: AppConfig = {
|
|||
supabaseAnonKey: '',
|
||||
cloudSyncLastAt: null,
|
||||
deviceInstallationId: null,
|
||||
cloudSyncAudio: true,
|
||||
onboardingCompleted: false,
|
||||
// Phase 6/10+: AppConfig 키 기본값 (WS2 SSOT 강화 대응).
|
||||
// as never 제거 후 configGet이 이 키들을 반환 — 기존 사용자 config(0.1.x)에
|
||||
|
|
|
|||
|
|
@ -41,7 +41,6 @@ class HistoryService {
|
|||
|
||||
// Phase 3.3: 로그인 상태면 자동 push (fire-and-forget, 로컬 write는 차단하지 않음)
|
||||
void getCloudSyncService().pushOne('history', id)
|
||||
if (input.audioLocalPath) getCloudSyncService().pushOne('history_audio', id)
|
||||
|
||||
// 비동기로 LLM 타이틀 자동 생성 (fire-and-forget)
|
||||
this.generateTitle(id).catch(() => { /* ignore */ })
|
||||
|
|
|
|||
|
|
@ -369,7 +369,6 @@ class MeetingModeService extends EventEmitter {
|
|||
if (!fs.existsSync(audioDir)) fs.mkdirSync(audioDir, { recursive: true })
|
||||
const wavPath = path.join(audioDir, `${sessionId}.wav`)
|
||||
this._saveWav(wavPath, Buffer.concat(this._audioBuffersForFile))
|
||||
getCloudSyncService().pushOne('meeting_audio', sessionId)
|
||||
logger.info(`회의 오디오 저장: ${wavPath}`)
|
||||
} catch (err) {
|
||||
logger.warn(`오디오 저장 실패: ${err instanceof Error ? err.message : String(err)}`)
|
||||
|
|
|
|||
|
|
@ -4,15 +4,13 @@
|
|||
|
||||
import { EventEmitter } from 'events'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { asc, eq } from 'drizzle-orm'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { getLogger } from './LoggerService'
|
||||
import { getPremiumLLMService } from './PremiumLLMService'
|
||||
import { getOllamaServerUrl } from './LocalLLMService'
|
||||
import { getDatabase } from '../db'
|
||||
import { ragDocuments, ragChunks } from '../db/schema'
|
||||
import { getMainWindow } from '../windows/WindowManager'
|
||||
import { getCloudSyncService } from './CloudSyncService'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
import type {
|
||||
|
|
@ -135,12 +133,8 @@ class RAGService extends EventEmitter {
|
|||
addedAt: Date.now(),
|
||||
}).run()
|
||||
|
||||
// 청크 원문을 먼저 저장한다 — 임베딩이 실패해도 원문은 남아 재색인·기기 간 동기화가 가능하다.
|
||||
this._storeChunks(docId, chunks)
|
||||
getCloudSyncService().pushOne('knowledge_documents', docId)
|
||||
|
||||
// 비동기 인덱싱 (임베딩 생성)
|
||||
this._embedStoredChunks(docId, fileName).catch((err) => {
|
||||
this._indexDocument(docId, fileName, chunks).catch((err) => {
|
||||
logger.error(`Indexing failed for ${fileName}:`, err)
|
||||
})
|
||||
|
||||
|
|
@ -160,59 +154,10 @@ class RAGService extends EventEmitter {
|
|||
* 문서 제거 (청크 포함)
|
||||
*/
|
||||
removeDocument(documentId: string): void {
|
||||
this.removeRemote(documentId)
|
||||
getCloudSyncService().pushDelete('knowledge_documents', documentId)
|
||||
logger.info(`RAG document removed: ${documentId}`)
|
||||
}
|
||||
|
||||
/** 동기화: 다른 기기에서 지운 문서를 지운다(outbox에 넣지 않는다). */
|
||||
removeRemote(documentId: string): boolean {
|
||||
const db = getDatabase()
|
||||
db.delete(ragChunks).where(eq(ragChunks.documentId, documentId)).run()
|
||||
return db.delete(ragDocuments).where(eq(ragDocuments.id, documentId)).run().changes > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 동기화: 다른 기기(모바일·웹)의 지식 문서를 원문 청크로 받아 저장하고, 이 기기의 임베딩 모델로 색인한다.
|
||||
* 임베딩 공간이 기기마다 달라 벡터는 옮기지 않는다. 원본 파일은 없으므로 filePath는 비워 둔다.
|
||||
*/
|
||||
applyRemoteDocument(doc: {
|
||||
id: string
|
||||
fileName: string
|
||||
fileType: RAGDocument['fileType']
|
||||
chunks: string[]
|
||||
addedAt: number
|
||||
}): boolean {
|
||||
const db = getDatabase()
|
||||
if (db.select({ id: ragDocuments.id }).from(ragDocuments).where(eq(ragDocuments.id, doc.id)).get()) return false
|
||||
const chunks = doc.chunks.filter((c) => c.trim().length > 0)
|
||||
if (chunks.length === 0) return false
|
||||
db.insert(ragDocuments).values({
|
||||
id: doc.id,
|
||||
fileName: doc.fileName,
|
||||
filePath: '',
|
||||
fileType: doc.fileType,
|
||||
chunkCount: chunks.length,
|
||||
indexed: false,
|
||||
indexedAt: null,
|
||||
addedAt: doc.addedAt,
|
||||
}).run()
|
||||
this._storeChunks(doc.id, chunks)
|
||||
this._embedStoredChunks(doc.id, doc.fileName).catch((err) => {
|
||||
logger.warn(`Synced document ${doc.fileName} is stored but not embedded yet:`, err)
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
/** 저장된 청크 원문(chunkIndex 순) — 동기화 업로드용 */
|
||||
getStoredChunks(documentId: string): string[] {
|
||||
return getDatabase()
|
||||
.select({ content: ragChunks.content })
|
||||
.from(ragChunks)
|
||||
.where(eq(ragChunks.documentId, documentId))
|
||||
.orderBy(asc(ragChunks.chunkIndex))
|
||||
.all()
|
||||
.map((r) => r.content)
|
||||
db.delete(ragDocuments).where(eq(ragDocuments.id, documentId)).run()
|
||||
logger.info(`RAG document removed: ${documentId}`)
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -226,11 +171,8 @@ class RAGService extends EventEmitter {
|
|||
}
|
||||
const doc = rows[0]
|
||||
|
||||
// 원본 파일이 없으면(다른 기기에서 동기화된 문서 등) 저장된 원문 청크로 다시 임베딩한다.
|
||||
if (!doc.filePath || !fs.existsSync(doc.filePath)) {
|
||||
await this._embedStoredChunks(documentId, doc.fileName, { force: true })
|
||||
return
|
||||
}
|
||||
// 기존 청크 삭제
|
||||
db.delete(ragChunks).where(eq(ragChunks.documentId, documentId)).run()
|
||||
|
||||
// 텍스트 재추출 + 재인덱싱
|
||||
const content = await this._extractText(doc.filePath, doc.fileType as RAGDocument['fileType'])
|
||||
|
|
@ -241,9 +183,7 @@ class RAGService extends EventEmitter {
|
|||
.where(eq(ragDocuments.id, documentId))
|
||||
.run()
|
||||
|
||||
this._storeChunks(documentId, chunks)
|
||||
getCloudSyncService().pushOne('knowledge_documents', documentId)
|
||||
await this._embedStoredChunks(documentId, doc.fileName)
|
||||
await this._indexDocument(documentId, doc.fileName, chunks)
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -254,8 +194,7 @@ class RAGService extends EventEmitter {
|
|||
|
||||
try {
|
||||
const db = getDatabase()
|
||||
// 원문만 있고 아직 임베딩되지 않은 청크는 검색 대상이 아니다.
|
||||
const allChunks = db.select().from(ragChunks).all().filter((c) => c.embedding.length > 0)
|
||||
const allChunks = db.select().from(ragChunks).all()
|
||||
if (allChunks.length === 0) {
|
||||
throw new D3ROError(ErrorCode.RAGQueryFailed, 'No indexed chunks to query')
|
||||
}
|
||||
|
|
@ -306,37 +245,9 @@ ${context}`
|
|||
|
||||
// ── 내부 메서드 ──
|
||||
|
||||
/** 청크 원문을 (다시) 저장한다. 임베딩은 비워 두고 _embedStoredChunks 가 채운다. */
|
||||
private _storeChunks(docId: string, chunks: string[]): void {
|
||||
const db = getDatabase()
|
||||
db.transaction((tx) => {
|
||||
tx.delete(ragChunks).where(eq(ragChunks.documentId, docId)).run()
|
||||
chunks.forEach((content, index) => {
|
||||
tx.insert(ragChunks).values({
|
||||
id: crypto.randomUUID(),
|
||||
documentId: docId,
|
||||
content,
|
||||
embedding: '',
|
||||
chunkIndex: index,
|
||||
}).run()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** 저장된 청크 중 임베딩이 없는 것(force면 전부)을 이 기기의 임베딩 모델로 채운다. */
|
||||
private async _embedStoredChunks(
|
||||
docId: string,
|
||||
fileName: string,
|
||||
options: { force?: boolean } = {}
|
||||
): Promise<void> {
|
||||
private async _indexDocument(docId: string, fileName: string, chunks: string[]): Promise<void> {
|
||||
this._state = 'indexing'
|
||||
const db = getDatabase()
|
||||
const chunks = db
|
||||
.select()
|
||||
.from(ragChunks)
|
||||
.where(eq(ragChunks.documentId, docId))
|
||||
.orderBy(asc(ragChunks.chunkIndex))
|
||||
.all()
|
||||
|
||||
logger.info(`RAG indexing started: ${fileName} (${chunks.length} chunks)`)
|
||||
|
||||
|
|
@ -351,21 +262,21 @@ ${context}`
|
|||
|
||||
let successCount = 0
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
const chunk = chunks[i]
|
||||
if (chunk.embedding.length > 0 && !options.force) {
|
||||
successCount++
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const embedding = await this._embed(chunk.content)
|
||||
db.update(ragChunks)
|
||||
.set({ embedding: JSON.stringify(embedding) })
|
||||
.where(eq(ragChunks.id, chunk.id))
|
||||
.run()
|
||||
const embedding = await this._embed(chunks[i])
|
||||
|
||||
db.insert(ragChunks).values({
|
||||
id: crypto.randomUUID(),
|
||||
documentId: docId,
|
||||
content: chunks[i],
|
||||
embedding: JSON.stringify(embedding),
|
||||
chunkIndex: i,
|
||||
}).run()
|
||||
|
||||
successCount++
|
||||
} catch (err) {
|
||||
logger.warn(`RAG embedding failed for chunk ${i}/${chunks.length} of ${fileName}:`, err)
|
||||
// 개별 청크 실패는 건너뛰고 계속 진행 — 원문은 남아 있어 재색인할 수 있다
|
||||
// 개별 청크 실패는 건너뛰고 계속 진행
|
||||
}
|
||||
|
||||
const progress: RAGIndexProgress = {
|
||||
|
|
@ -396,9 +307,9 @@ ${context}`
|
|||
)
|
||||
}
|
||||
|
||||
// 인덱싱 완료 표시 (chunkCount는 원문 청크 수 — 서버·모바일과 같은 기준)
|
||||
// 인덱싱 완료 표시
|
||||
db.update(ragDocuments)
|
||||
.set({ indexed: true, indexedAt: Date.now(), chunkCount: chunks.length })
|
||||
.set({ indexed: true, indexedAt: Date.now(), chunkCount: successCount })
|
||||
.where(eq(ragDocuments.id, docId))
|
||||
.run()
|
||||
|
||||
|
|
|
|||
|
|
@ -18,8 +18,6 @@ import {
|
|||
pushMemoTagRemovals,
|
||||
reconcileMemoTags,
|
||||
} from './memo-tag-sync'
|
||||
import { fetchRemoteAudioOwners, isAudioSyncEnabled, listLocalAudioOwners, pushAudio } from './audio-sync'
|
||||
import { SETTINGS_ROW_ID, applyRemoteSettings, fetchRemoteSettings, pushSettings } from './settings-sync'
|
||||
import {
|
||||
completeEntry,
|
||||
dropEntry,
|
||||
|
|
@ -217,25 +215,6 @@ export class SyncEngine extends EventEmitter {
|
|||
}
|
||||
}
|
||||
}
|
||||
const ctx: PushContext = { remote: this.remote, userId: this.userId }
|
||||
// 설정: 서버에 행이 없을 때만 로컬 값을 올린다. 있으면 다른 기기의 선택이 우선(pull이 반영).
|
||||
if (!(await fetchRemoteSettings(ctx))) {
|
||||
enqueueChange('user_settings', SETTINGS_ROW_ID, 'upsert', now)
|
||||
queued++
|
||||
}
|
||||
if (isAudioSyncEnabled()) {
|
||||
for (const owner of ['history', 'meeting'] as const) {
|
||||
const local = listLocalAudioOwners(owner)
|
||||
if (local.length === 0) continue
|
||||
const remote = await fetchRemoteAudioOwners(this.remote, this.userId, owner)
|
||||
for (const id of local) {
|
||||
if (!remote.has(id)) {
|
||||
enqueueChange(owner === 'history' ? 'history_audio' : 'meeting_audio', id, 'upsert', now)
|
||||
queued++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
setSyncState(BACKFILL_FLAG, 'done', now)
|
||||
logger.info(`Backfill queued ${queued} local change(s) for ${this.userId}`)
|
||||
}
|
||||
|
|
@ -290,51 +269,31 @@ export class SyncEngine extends EventEmitter {
|
|||
'meeting_memos',
|
||||
'meeting_documents',
|
||||
'custom_instructions',
|
||||
'user_settings',
|
||||
'user_templates',
|
||||
'knowledge_documents',
|
||||
'memo_tags',
|
||||
'history_audio',
|
||||
'meeting_audio',
|
||||
]
|
||||
let networkDown = false
|
||||
for (const entity of upsertOrder) {
|
||||
const bucket = byEntity.get(entity)
|
||||
if (!bucket || bucket.upserts.length === 0 || networkDown) continue
|
||||
const ids = bucket.upserts.map((e) => e.rowId)
|
||||
const outcomes = await this.pushUpserts(ctx, entity, ids)
|
||||
const outcomes =
|
||||
entity === 'memo_tags'
|
||||
? await pushMemoTagAdds(ctx, bucket.upserts.map((e) => e.rowId))
|
||||
: await this.requireAdapter(entity).push(ctx, bucket.upserts.map((e) => e.rowId))
|
||||
networkDown = this.settle(bucket.upserts, outcomes, result, entity)
|
||||
}
|
||||
// 자식 먼저 delete (서버 cascade가 있어도 순서를 지켜 FK 오류를 피한다)
|
||||
for (const entity of [...order].reverse()) {
|
||||
const bucket = byEntity.get(entity)
|
||||
if (!bucket || bucket.deletes.length === 0 || networkDown) continue
|
||||
const ids = bucket.deletes.map((e) => e.rowId)
|
||||
const outcomes =
|
||||
entity === 'memo_tags'
|
||||
? await pushMemoTagRemovals(ctx, ids)
|
||||
: adapterFor(entity)
|
||||
? await this.requireAdapter(entity).pushDeletes(ctx, ids)
|
||||
: ids.map((id) => ({ id, error: null }))
|
||||
? await pushMemoTagRemovals(ctx, bucket.deletes.map((e) => e.rowId))
|
||||
: await this.requireAdapter(entity).pushDeletes(ctx, bucket.deletes.map((e) => e.rowId))
|
||||
networkDown = this.settle(bucket.deletes, outcomes, result, entity)
|
||||
}
|
||||
}
|
||||
|
||||
private async pushUpserts(ctx: PushContext, entity: SyncEntity, ids: string[]): Promise<PushOutcome[]> {
|
||||
switch (entity) {
|
||||
case 'memo_tags':
|
||||
return pushMemoTagAdds(ctx, ids)
|
||||
case 'user_settings':
|
||||
return [{ id: SETTINGS_ROW_ID, error: await pushSettings(ctx) }]
|
||||
case 'history_audio':
|
||||
return pushAudio(ctx, 'history', ids)
|
||||
case 'meeting_audio':
|
||||
return pushAudio(ctx, 'meeting', ids)
|
||||
default:
|
||||
return this.requireAdapter(entity).push(ctx, ids)
|
||||
}
|
||||
}
|
||||
|
||||
/** outbox를 결과대로 정리. 네트워크 계열 실패가 있었으면 true(이번 flush 중단). */
|
||||
private settle(entries: OutboxEntry[], outcomes: PushOutcome[], result: SyncRunResult, entity: SyncEntity): boolean {
|
||||
const byId = new Map(outcomes.map((o) => [o.id, o.error]))
|
||||
|
|
@ -402,20 +361,6 @@ export class SyncEngine extends EventEmitter {
|
|||
logger.warn(`Reconcile memo_tags failed: ${message}`)
|
||||
}
|
||||
|
||||
try {
|
||||
if (!pendingOps('user_settings').has(SETTINGS_ROW_ID)) {
|
||||
const row = await fetchRemoteSettings({ remote: this.remote, userId: this.userId })
|
||||
if (row && applyRemoteSettings(row)) {
|
||||
changed.add('user_settings')
|
||||
result.pulled++
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
result.errors.push(`user_settings: ${message}`)
|
||||
logger.warn(`Pull user_settings failed: ${message}`)
|
||||
}
|
||||
|
||||
result.changed = [...changed]
|
||||
if (result.errors.length === 0) setSyncState('lastPullAt', String(this.now()))
|
||||
}
|
||||
|
|
@ -444,7 +389,7 @@ export class SyncEngine extends EventEmitter {
|
|||
const id = typeof row.id === 'string' ? row.id : null
|
||||
if (id && !pending.has(id)) {
|
||||
try {
|
||||
if (await adapter.applyRemote(row, { remote: this.remote, userId: this.userId })) applied++
|
||||
if (adapter.applyRemote(row)) applied++
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
`Apply ${adapter.entity}/${id} failed: ${err instanceof Error ? err.message : String(err)}`
|
||||
|
|
|
|||
|
|
@ -1,219 +0,0 @@
|
|||
// src/main/services/sync/audio-sync.ts
|
||||
// 데스크톱 녹음 파일을 모바일과 같은 저장소 계약(`audio` 버킷, `{userId}/...` 경로, audio_files 행)으로 올린다.
|
||||
// 모바일은 audio_files 로 재생 URL을 만들고, 데스크톱은 반대로 모바일 녹음을 재생할 때 서명 URL을 받는다.
|
||||
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { createHash } from 'crypto'
|
||||
import { app } from 'electron'
|
||||
import { eq, isNotNull } from 'drizzle-orm'
|
||||
import { getDatabase } from '../../db'
|
||||
import { history, meetingSessions } from '../../db/schema'
|
||||
import { configGet } from '../ConfigService'
|
||||
import { getLogger } from '../LoggerService'
|
||||
import { isUuid, type PushContext } from './sync-adapters'
|
||||
import { toSyncRemoteError, type PushOutcome, type RemoteCursor, type SyncRemote } from './sync-types'
|
||||
|
||||
const logger = getLogger('AudioSync')
|
||||
|
||||
export const AUDIO_BUCKET = 'audio'
|
||||
/** Supabase Storage 파일 한도(config.toml storage 50MiB). 넘는 파일은 올리지 않는다. */
|
||||
export const MAX_AUDIO_BYTES = 50 * 1024 * 1024
|
||||
|
||||
export type AudioOwner = 'history' | 'meeting'
|
||||
|
||||
const OWNER_COLUMN: Record<AudioOwner, 'history_id' | 'meeting_id'> = {
|
||||
history: 'history_id',
|
||||
meeting: 'meeting_id',
|
||||
}
|
||||
|
||||
/** audio 버킷이 허용하는 형식만(서버 allowed_mime_types). 그 밖의 파일은 올리지 않는다. */
|
||||
const AUDIO_MIME: Record<string, string> = {
|
||||
'.wav': 'audio/wav',
|
||||
'.webm': 'audio/webm',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.m4a': 'audio/x-m4a',
|
||||
'.aac': 'audio/aac',
|
||||
'.ogg': 'audio/ogg',
|
||||
'.flac': 'audio/flac',
|
||||
'.mp4': 'video/mp4',
|
||||
'.mov': 'video/quicktime',
|
||||
}
|
||||
|
||||
export function audioMimeType(filePath: string): string | null {
|
||||
return AUDIO_MIME[path.extname(filePath).toLowerCase()] ?? null
|
||||
}
|
||||
|
||||
export function audioStorageKey(userId: string, owner: AudioOwner, id: string, extension = '.wav'): string {
|
||||
return `${userId}/desktop/${owner}/${id}${extension.toLowerCase()}`
|
||||
}
|
||||
|
||||
export function isAudioSyncEnabled(): boolean {
|
||||
return configGet('cloudSyncAudio') !== false
|
||||
}
|
||||
|
||||
function meetingAudioPath(id: string): string {
|
||||
return path.join(app.getPath('userData'), 'meeting-audio', `${id}.wav`)
|
||||
}
|
||||
|
||||
/** 로컬 녹음 파일 경로. 파일이 없으면 null */
|
||||
export function localAudioPath(owner: AudioOwner, id: string): string | null {
|
||||
let candidate: string | null
|
||||
if (owner === 'history') {
|
||||
const row = getDatabase()
|
||||
.select({ audioLocalPath: history.audioLocalPath })
|
||||
.from(history)
|
||||
.where(eq(history.id, id))
|
||||
.get()
|
||||
candidate = row?.audioLocalPath ?? null
|
||||
} else {
|
||||
candidate = meetingAudioPath(id)
|
||||
}
|
||||
return candidate && fs.existsSync(candidate) ? candidate : null
|
||||
}
|
||||
|
||||
/** 녹음이 있는 로컬 항목 id (최초 대조용) */
|
||||
export function listLocalAudioOwners(owner: AudioOwner): string[] {
|
||||
if (owner === 'history') {
|
||||
return getDatabase()
|
||||
.select({ id: history.id, audioLocalPath: history.audioLocalPath })
|
||||
.from(history)
|
||||
.where(isNotNull(history.audioLocalPath))
|
||||
.all()
|
||||
.filter((r) => isUuid(r.id) && r.audioLocalPath !== null && fs.existsSync(r.audioLocalPath))
|
||||
.map((r) => r.id)
|
||||
}
|
||||
return getDatabase()
|
||||
.select({ id: meetingSessions.id })
|
||||
.from(meetingSessions)
|
||||
.all()
|
||||
.filter((r) => isUuid(r.id) && fs.existsSync(meetingAudioPath(r.id)))
|
||||
.map((r) => r.id)
|
||||
}
|
||||
|
||||
function durationMs(owner: AudioOwner, id: string): number | null {
|
||||
if (owner === 'history') {
|
||||
const row = getDatabase().select({ duration: history.duration }).from(history).where(eq(history.id, id)).get()
|
||||
return row ? Math.round(row.duration * 1000) : null
|
||||
}
|
||||
const row = getDatabase()
|
||||
.select({ durationMs: meetingSessions.durationMs })
|
||||
.from(meetingSessions)
|
||||
.where(eq(meetingSessions.id, id))
|
||||
.get()
|
||||
return row?.durationMs ?? null
|
||||
}
|
||||
|
||||
export async function pushAudio(ctx: PushContext, owner: AudioOwner, ids: string[]): Promise<PushOutcome[]> {
|
||||
const outcomes: PushOutcome[] = []
|
||||
const column = OWNER_COLUMN[owner]
|
||||
for (const id of ids) {
|
||||
const filePath = isAudioSyncEnabled() && isUuid(id) ? localAudioPath(owner, id) : null
|
||||
const mimeType = filePath ? audioMimeType(filePath) : null
|
||||
if (!filePath || !mimeType) {
|
||||
outcomes.push({ id, error: null })
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const size = fs.statSync(filePath).size
|
||||
if (size > MAX_AUDIO_BYTES) {
|
||||
logger.info(`Audio ${owner}/${id} is ${size} bytes — over the storage limit, kept local only`)
|
||||
outcomes.push({ id, error: null })
|
||||
continue
|
||||
}
|
||||
const bytes = fs.readFileSync(filePath)
|
||||
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
||||
const existing = await ctx.remote.selectWhere(
|
||||
'audio_files',
|
||||
ctx.userId,
|
||||
[
|
||||
{ column, op: 'eq', value: id },
|
||||
{ column: 'sha256', op: 'eq', value: sha256 },
|
||||
{ column: 'upload_status', op: 'eq', value: 'uploaded' },
|
||||
],
|
||||
'id'
|
||||
)
|
||||
if (existing.length > 0) {
|
||||
outcomes.push({ id, error: null })
|
||||
continue
|
||||
}
|
||||
const key = audioStorageKey(ctx.userId, owner, id, path.extname(filePath))
|
||||
await ctx.remote.uploadObject(AUDIO_BUCKET, key, new Uint8Array(bytes), mimeType)
|
||||
await ctx.remote.upsert(
|
||||
'audio_files',
|
||||
[
|
||||
{
|
||||
user_id: ctx.userId,
|
||||
[column]: id,
|
||||
source: 'recording',
|
||||
original_name: path.basename(filePath),
|
||||
storage_key: key,
|
||||
mime_type: mimeType,
|
||||
size_bytes: size,
|
||||
duration_ms: durationMs(owner, id),
|
||||
sha256,
|
||||
upload_status: 'uploaded',
|
||||
},
|
||||
],
|
||||
'user_id,sha256,storage_key'
|
||||
)
|
||||
outcomes.push({ id, error: null })
|
||||
} catch (err) {
|
||||
outcomes.push({ id, error: toSyncRemoteError(err) })
|
||||
}
|
||||
}
|
||||
return outcomes
|
||||
}
|
||||
|
||||
/** 서버에 이미 올라간 녹음의 주인 id (최초 대조용) */
|
||||
export async function fetchRemoteAudioOwners(remote: SyncRemote, userId: string, owner: AudioOwner): Promise<Set<string>> {
|
||||
const column = OWNER_COLUMN[owner]
|
||||
const owners = new Set<string>()
|
||||
let after: RemoteCursor | null = null
|
||||
for (;;) {
|
||||
const page = await remote.fetchPage({
|
||||
table: 'audio_files',
|
||||
userId,
|
||||
cursorColumn: 'updated_at',
|
||||
after,
|
||||
limit: 1000,
|
||||
columns: `id,${column},updated_at`,
|
||||
filters: [{ column: 'upload_status', op: 'eq', value: 'uploaded' }],
|
||||
})
|
||||
for (const row of page) {
|
||||
const value = row[column]
|
||||
if (isUuid(value)) owners.add(value)
|
||||
}
|
||||
if (page.length < 1000) break
|
||||
const last = page[page.length - 1]
|
||||
if (typeof last.updated_at !== 'string' || typeof last.id !== 'string') break
|
||||
after = { ts: last.updated_at, id: last.id }
|
||||
}
|
||||
return owners
|
||||
}
|
||||
|
||||
/**
|
||||
* 지운 기록·회의의 녹음을 저장소와 audio_files 에서 지운다.
|
||||
* 부모 행이 지워지면 audio_files 는 SET NULL 로 고아가 되므로 부모보다 먼저 지운다. 실패해도 부모 삭제는 진행한다.
|
||||
*/
|
||||
export async function purgeRemoteAudio(ctx: PushContext, column: 'history_id' | 'meeting_id', ids: string[]): Promise<void> {
|
||||
for (const id of ids.filter(isUuid)) {
|
||||
try {
|
||||
const rows = await ctx.remote.selectWhere(
|
||||
'audio_files',
|
||||
ctx.userId,
|
||||
[{ column, op: 'eq', value: id }],
|
||||
'id,storage_key'
|
||||
)
|
||||
const keys = rows.map((r) => r.storage_key).filter((k): k is string => typeof k === 'string')
|
||||
await ctx.remote.removeObjects(AUDIO_BUCKET, keys)
|
||||
await ctx.remote.deleteByIds(
|
||||
'audio_files',
|
||||
ctx.userId,
|
||||
rows.map((r) => r.id).filter(isUuid)
|
||||
)
|
||||
} catch (err) {
|
||||
logger.warn(`Audio cleanup for ${column}=${id} failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,169 +0,0 @@
|
|||
// src/main/services/sync/settings-sync.ts
|
||||
// 모바일 user_settings(한 행, revision 낙관적 동시성)와 데스크톱 설정 중 뜻이 같은 것만 맞춘다.
|
||||
// locale ↔ language (모바일이 받는 ko/en만)
|
||||
// theme_mode ↔ theme (system/light/dark 만 — 데스크톱 전용 테마는 로컬에 둔다)
|
||||
// auto_polish_enabled ↔ defaultLLMAction ('none' 이면 꺼짐)
|
||||
// active_instruction_id ↔ activeInstructionId (양쪽에 있는 사용자 명령일 때만)
|
||||
|
||||
import type { LLMActionSelection, ThemeMode } from '@d3ro/core/types'
|
||||
import { configGet, configSet } from '../ConfigService'
|
||||
import { getCustomInstructionService } from '../CustomInstructionService'
|
||||
import { isUuid, type PushContext } from './sync-adapters'
|
||||
import { toSyncRemoteError, type RemoteRow, type SyncRemoteError } from './sync-types'
|
||||
|
||||
export const SETTINGS_ROW_ID = 'self'
|
||||
|
||||
/** 이 키들이 바뀌면 설정 동기화 대상이다 */
|
||||
export const SYNCED_CONFIG_KEYS = ['language', 'theme', 'defaultLLMAction', 'activeInstructionId'] as const
|
||||
|
||||
const SETTINGS_COLUMNS = 'user_id,locale,theme_mode,auto_polish_enabled,active_instruction_id,revision'
|
||||
|
||||
let applyingRemote = false
|
||||
|
||||
/** 원격 설정을 반영하는 중인지 — 이 동안의 설정 변경은 다시 올리지 않는다(에코 방지) */
|
||||
export function isApplyingRemoteSettings(): boolean {
|
||||
return applyingRemote
|
||||
}
|
||||
|
||||
export interface LocalSettings {
|
||||
language: string
|
||||
theme: ThemeMode
|
||||
defaultLLMAction: LLMActionSelection
|
||||
activeInstructionId: string
|
||||
}
|
||||
|
||||
export interface RemoteSettingsPatch {
|
||||
locale?: 'ko' | 'en'
|
||||
theme_mode?: 'system' | 'light' | 'dark'
|
||||
auto_polish_enabled: boolean
|
||||
}
|
||||
|
||||
export function readLocalSettings(): LocalSettings {
|
||||
return {
|
||||
language: String(configGet('language') ?? 'ko'),
|
||||
theme: (configGet('theme') ?? 'auto') as ThemeMode,
|
||||
defaultLLMAction: (configGet('defaultLLMAction') ?? 'refine') as LLMActionSelection,
|
||||
activeInstructionId: String(configGet('activeInstructionId') ?? ''),
|
||||
}
|
||||
}
|
||||
|
||||
export function toRemoteSettings(local: LocalSettings): RemoteSettingsPatch {
|
||||
const patch: RemoteSettingsPatch = { auto_polish_enabled: local.defaultLLMAction !== 'none' }
|
||||
if (local.language === 'ko' || local.language === 'en') patch.locale = local.language
|
||||
if (local.theme === 'auto') patch.theme_mode = 'system'
|
||||
else if (local.theme === 'light' || local.theme === 'dark') patch.theme_mode = local.theme
|
||||
return patch
|
||||
}
|
||||
|
||||
/** 원격 행이 요구하는 로컬 변경만 돌려준다(같으면 빈 객체). */
|
||||
export function remoteToLocalPatch(
|
||||
row: RemoteRow,
|
||||
local: LocalSettings,
|
||||
userInstructionIds: ReadonlySet<string>
|
||||
): Partial<LocalSettings> {
|
||||
const patch: Partial<LocalSettings> = {}
|
||||
if ((row.locale === 'ko' || row.locale === 'en') && row.locale !== local.language) patch.language = row.locale
|
||||
|
||||
const sharedTheme = local.theme === 'auto' || local.theme === 'light' || local.theme === 'dark'
|
||||
if (sharedTheme) {
|
||||
const theme: ThemeMode | null =
|
||||
row.theme_mode === 'system' ? 'auto' : row.theme_mode === 'light' || row.theme_mode === 'dark' ? row.theme_mode : null
|
||||
if (theme && theme !== local.theme) patch.theme = theme
|
||||
}
|
||||
|
||||
if (row.auto_polish_enabled === false && local.defaultLLMAction !== 'none') patch.defaultLLMAction = 'none'
|
||||
if (row.auto_polish_enabled === true && local.defaultLLMAction === 'none') patch.defaultLLMAction = 'refine'
|
||||
|
||||
const remoteActive = row.active_instruction_id
|
||||
if (isUuid(remoteActive)) {
|
||||
if (userInstructionIds.has(remoteActive) && remoteActive !== local.activeInstructionId) {
|
||||
patch.activeInstructionId = remoteActive
|
||||
}
|
||||
} else if (remoteActive === null && userInstructionIds.has(local.activeInstructionId)) {
|
||||
// 사용자 명령이 해제됐다. 데스크톱 프리셋(builtin-*)이 켜져 있으면 모바일이 알 수 없으므로 둔다.
|
||||
patch.activeInstructionId = ''
|
||||
}
|
||||
return patch
|
||||
}
|
||||
|
||||
function userInstructionIds(): Set<string> {
|
||||
return new Set(
|
||||
getCustomInstructionService()
|
||||
.getAll()
|
||||
.filter((i) => !i.isBuiltin && isUuid(i.id))
|
||||
.map((i) => i.id)
|
||||
)
|
||||
}
|
||||
|
||||
export async function fetchRemoteSettings(ctx: PushContext): Promise<RemoteRow | null> {
|
||||
const rows = await ctx.remote.selectWhere('user_settings', ctx.userId, [], SETTINGS_COLUMNS)
|
||||
return rows[0] ?? null
|
||||
}
|
||||
|
||||
/** 로컬 설정을 올린다. 모바일과 같은 revision 규칙(재조회 → revision 조건부 수정, 최대 3회). */
|
||||
export async function pushSettings(ctx: PushContext): Promise<SyncRemoteError | null> {
|
||||
const local = readLocalSettings()
|
||||
const desired = toRemoteSettings(local)
|
||||
try {
|
||||
let remote: RemoteRow | null = null
|
||||
let saved = false
|
||||
for (let attempt = 0; attempt < 3 && !saved; attempt++) {
|
||||
remote = await fetchRemoteSettings(ctx)
|
||||
if (!remote) {
|
||||
try {
|
||||
await ctx.remote.insert('user_settings', [{ user_id: ctx.userId, ...desired }])
|
||||
saved = true
|
||||
} catch (err) {
|
||||
const error = toSyncRemoteError(err)
|
||||
if (error.code !== '23505') throw error
|
||||
}
|
||||
continue
|
||||
}
|
||||
const revision = Number(remote.revision ?? 1)
|
||||
// 이미 같으면 쓰지 않는다 — revision만 올리면 다른 기기에 가짜 변경이 전파된다.
|
||||
const current = remote
|
||||
if ((Object.keys(desired) as Array<keyof RemoteSettingsPatch>).every((k) => current[k] === desired[k])) {
|
||||
saved = true
|
||||
break
|
||||
}
|
||||
const changed = await ctx.remote.updateMatching(
|
||||
'user_settings',
|
||||
ctx.userId,
|
||||
{ revision },
|
||||
{ ...desired, revision: revision + 1 }
|
||||
)
|
||||
saved = changed > 0
|
||||
}
|
||||
if (!saved) return toSyncRemoteError({ code: '40001', message: 'user_settings changed repeatedly on another device' })
|
||||
|
||||
// 활성 명령: 양쪽에 있는 사용자 명령이거나 '없음'일 때만 올린다(프리셋은 모바일에 없다).
|
||||
const ids = userInstructionIds()
|
||||
const active = local.activeInstructionId
|
||||
const remoteActive = remote?.active_instruction_id ?? null
|
||||
if (active === '' && remoteActive !== null) {
|
||||
await ctx.remote.rpc('set_active_custom_instruction', { instruction_id: null })
|
||||
} else if (ids.has(active) && remoteActive !== active) {
|
||||
await ctx.remote.rpc('set_active_custom_instruction', { instruction_id: active })
|
||||
}
|
||||
return null
|
||||
} catch (err) {
|
||||
return toSyncRemoteError(err)
|
||||
}
|
||||
}
|
||||
|
||||
/** 원격 설정을 로컬에 반영한다. 바꾼 것이 있으면 true */
|
||||
export function applyRemoteSettings(row: RemoteRow): boolean {
|
||||
const patch = remoteToLocalPatch(row, readLocalSettings(), userInstructionIds())
|
||||
const keys = Object.keys(patch) as Array<keyof LocalSettings>
|
||||
if (keys.length === 0) return false
|
||||
applyingRemote = true
|
||||
try {
|
||||
if (patch.language !== undefined) configSet('language', patch.language)
|
||||
if (patch.theme !== undefined) configSet('theme', patch.theme)
|
||||
if (patch.defaultLLMAction !== undefined) configSet('defaultLLMAction', patch.defaultLLMAction)
|
||||
if (patch.activeInstructionId !== undefined) configSet('activeInstructionId', patch.activeInstructionId)
|
||||
} finally {
|
||||
applyingRemote = false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
|
@ -76,66 +76,9 @@ export class SupabaseSyncRemote implements SyncRemote {
|
|||
return rowsOf(data)
|
||||
}
|
||||
|
||||
async selectChildren(
|
||||
table: string,
|
||||
parentColumn: string,
|
||||
parentId: string,
|
||||
columns: string,
|
||||
orderBy: string
|
||||
): Promise<RemoteRow[]> {
|
||||
const { data, error } = await this.client
|
||||
.from(table)
|
||||
.select(columns)
|
||||
.eq(parentColumn, parentId)
|
||||
.order(orderBy, { ascending: true })
|
||||
if (error) throw toSyncRemoteError(error)
|
||||
return rowsOf(data)
|
||||
}
|
||||
|
||||
async upsert(table: string, rows: RemoteRow[], onConflict = 'id'): Promise<void> {
|
||||
async upsert(table: string, rows: RemoteRow[]): Promise<void> {
|
||||
if (rows.length === 0) return
|
||||
const { error } = await this.client.from(table).upsert(rows, { onConflict })
|
||||
if (error) throw toSyncRemoteError(error)
|
||||
}
|
||||
|
||||
async insert(table: string, rows: RemoteRow[]): Promise<void> {
|
||||
if (rows.length === 0) return
|
||||
const { error } = await this.client.from(table).insert(rows)
|
||||
if (error) throw toSyncRemoteError(error)
|
||||
}
|
||||
|
||||
async updateMatching(
|
||||
table: string,
|
||||
userId: string,
|
||||
match: Record<string, string | number>,
|
||||
patch: RemoteRow
|
||||
): Promise<number> {
|
||||
let query = this.client.from(table).update(patch).eq('user_id', userId)
|
||||
for (const [column, value] of Object.entries(match)) query = query.eq(column, value)
|
||||
const { data, error } = await query.select('user_id')
|
||||
if (error) throw toSyncRemoteError(error)
|
||||
return rowsOf(data).length
|
||||
}
|
||||
|
||||
async deleteChildren(table: string, parentColumn: string, parentId: string): Promise<void> {
|
||||
const { error } = await this.client.from(table).delete().eq(parentColumn, parentId)
|
||||
if (error) throw toSyncRemoteError(error)
|
||||
}
|
||||
|
||||
async invokeFunction(name: string, body: Record<string, unknown>): Promise<unknown> {
|
||||
const { data, error } = await this.client.functions.invoke(name, { body })
|
||||
if (error) throw toSyncRemoteError(error)
|
||||
return data
|
||||
}
|
||||
|
||||
async uploadObject(bucket: string, key: string, bytes: Uint8Array, contentType: string): Promise<void> {
|
||||
const { error } = await this.client.storage.from(bucket).upload(key, bytes, { contentType, upsert: true })
|
||||
if (error) throw toSyncRemoteError(error)
|
||||
}
|
||||
|
||||
async removeObjects(bucket: string, keys: string[]): Promise<void> {
|
||||
if (keys.length === 0) return
|
||||
const { error } = await this.client.storage.from(bucket).remove(keys)
|
||||
const { error } = await this.client.from(table).upsert(rows, { onConflict: 'id' })
|
||||
if (error) throw toSyncRemoteError(error)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,14 +10,11 @@ import {
|
|||
meetingMemos,
|
||||
meetingSessions,
|
||||
memoTags,
|
||||
ragDocuments,
|
||||
} from '../../db/schema'
|
||||
import type { CustomInstruction, DictationTemplate, MeetingDocTemplate, TemplateField } from '@d3ro/core/types'
|
||||
import { getCustomInstructionService } from '../CustomInstructionService'
|
||||
import { getDictationTemplateService } from '../DictationTemplateService'
|
||||
import { getMeetingDocTemplateService } from '../MeetingDocTemplateService'
|
||||
import { getRAGService } from '../RAGService'
|
||||
import { purgeRemoteAudio } from './audio-sync'
|
||||
import { dropEntry } from './sync-outbox'
|
||||
import {
|
||||
SyncRemoteError,
|
||||
|
|
@ -46,8 +43,8 @@ export interface SyncAdapter {
|
|||
listLocalVersions(): LocalVersion[]
|
||||
push(ctx: PushContext, ids: string[]): Promise<PushOutcome[]>
|
||||
pushDeletes(ctx: PushContext, ids: string[]): Promise<PushOutcome[]>
|
||||
/** 원격 행을 로컬에 반영. 반영했으면 true. 자식 행을 더 읽어야 하는 엔티티는 비동기다 */
|
||||
applyRemote(row: RemoteRow, ctx: PushContext): boolean | Promise<boolean>
|
||||
/** 원격 행을 로컬에 반영. 반영했으면 true */
|
||||
applyRemote(row: RemoteRow): boolean
|
||||
/** 원격 삭제를 로컬에 반영. 지운 행이 있으면 true */
|
||||
deleteLocal(id: string): boolean
|
||||
}
|
||||
|
|
@ -212,9 +209,7 @@ const historyAdapter: SyncAdapter = {
|
|||
)
|
||||
return [...outcomes, ...missingAsDone(ids, found)]
|
||||
},
|
||||
async pushDeletes(ctx, ids) {
|
||||
// 지운 기록의 녹음 파일도 저장소에서 지운다(행은 SET NULL로 남아 고아가 된다).
|
||||
await purgeRemoteAudio(ctx, 'history_id', ids)
|
||||
pushDeletes(ctx, ids) {
|
||||
return deleteRemote(ctx, 'history', ids)
|
||||
},
|
||||
applyRemote(row) {
|
||||
|
|
@ -301,9 +296,11 @@ async function adoptRemoteDictionaryRow(
|
|||
const match = matches.find((m) => isUuid(m.id) && m.id !== localId)
|
||||
if (!match || !isUuid(match.id)) return error
|
||||
const remoteId = match.id
|
||||
db.delete(dictionary).where(eq(dictionary.id, localId)).run()
|
||||
db.transaction((tx) => {
|
||||
tx.delete(dictionary).where(eq(dictionary.id, localId)).run()
|
||||
})
|
||||
dropEntry('dictionary', localId)
|
||||
void dictionaryAdapter.applyRemote(match, ctx)
|
||||
dictionaryAdapter.applyRemote(match)
|
||||
const merged = db.select().from(dictionary).where(eq(dictionary.id, remoteId)).get()
|
||||
if (merged && local.usageCount > merged.usageCount) {
|
||||
db.update(dictionary)
|
||||
|
|
@ -443,8 +440,7 @@ const meetingsAdapter: SyncAdapter = {
|
|||
)
|
||||
return [...outcomes, ...missingAsDone(ids, found)]
|
||||
},
|
||||
async pushDeletes(ctx, ids) {
|
||||
await purgeRemoteAudio(ctx, 'meeting_id', ids)
|
||||
pushDeletes(ctx, ids) {
|
||||
return deleteRemote(ctx, 'meetings', ids)
|
||||
},
|
||||
applyRemote(row) {
|
||||
|
|
@ -845,95 +841,6 @@ const userTemplatesAdapter: SyncAdapter = {
|
|||
},
|
||||
}
|
||||
|
||||
// ── knowledge_documents ─────────────────────────────────
|
||||
// 원문 청크만 옮긴다. 임베딩은 기기마다 모델·차원이 달라(데스크톱 nomic 768 vs 서버 1536) 각자 만든다.
|
||||
|
||||
const KNOWLEDGE_TYPES = ['txt', 'md', 'pdf', 'docx'] as const
|
||||
const CHUNK_BATCH = 200
|
||||
|
||||
async function pushKnowledgeDocument(ctx: PushContext, id: string): Promise<SyncRemoteError | null> {
|
||||
const db = getDatabase()
|
||||
const doc = db.select().from(ragDocuments).where(eq(ragDocuments.id, id)).get()
|
||||
if (!doc) return null
|
||||
const chunks = getRAGService().getStoredChunks(id)
|
||||
if (chunks.length === 0) return null
|
||||
try {
|
||||
await ctx.remote.upsert('knowledge_documents', [
|
||||
{
|
||||
id: doc.id,
|
||||
user_id: ctx.userId,
|
||||
title: doc.fileName.slice(0, 300),
|
||||
file_name: doc.fileName,
|
||||
file_type: doc.fileType,
|
||||
chunk_count: chunks.length,
|
||||
indexed: false,
|
||||
indexed_at: null,
|
||||
created_at: iso(doc.addedAt),
|
||||
},
|
||||
])
|
||||
await ctx.remote.deleteChildren('knowledge_chunks', 'document_id', doc.id)
|
||||
for (let i = 0; i < chunks.length; i += CHUNK_BATCH) {
|
||||
await ctx.remote.insert(
|
||||
'knowledge_chunks',
|
||||
chunks.slice(i, i + CHUNK_BATCH).map((content, offset) => ({
|
||||
document_id: doc.id,
|
||||
chunk_index: i + offset,
|
||||
content,
|
||||
}))
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
return toSyncRemoteError(err)
|
||||
}
|
||||
// 모바일·웹 검색용 서버 임베딩. 공급자 키가 없거나 한도에 걸려도 원문은 이미 올라갔다 —
|
||||
// 모바일에서 "색인" 을 다시 누를 수 있으므로 여기서 실패로 되돌리지 않는다.
|
||||
try {
|
||||
await ctx.remote.invokeFunction('embed-chunks', { document_id: doc.id })
|
||||
} catch {
|
||||
// 의도적 무시(위 주석)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const knowledgeAdapter: SyncAdapter = {
|
||||
entity: 'knowledge_documents',
|
||||
pull: { columns: 'id,title,file_name,file_type,chunk_count,created_at,updated_at' },
|
||||
listLocalVersions() {
|
||||
return getDatabase()
|
||||
.select({ id: ragDocuments.id, addedAt: ragDocuments.addedAt })
|
||||
.from(ragDocuments)
|
||||
.all()
|
||||
.filter((r) => isUuid(r.id))
|
||||
.map((r) => ({ id: r.id, updatedAt: r.addedAt }))
|
||||
},
|
||||
async push(ctx, ids) {
|
||||
const outcomes: PushOutcome[] = []
|
||||
for (const id of ids) outcomes.push({ id, error: await pushKnowledgeDocument(ctx, id) })
|
||||
return outcomes
|
||||
},
|
||||
pushDeletes(ctx, ids) {
|
||||
return deleteRemote(ctx, 'knowledge_documents', ids)
|
||||
},
|
||||
async applyRemote(row, ctx) {
|
||||
const id = row.id
|
||||
if (!isUuid(id)) return false
|
||||
const exists = getDatabase().select({ id: ragDocuments.id }).from(ragDocuments).where(eq(ragDocuments.id, id)).get()
|
||||
if (exists) return false
|
||||
const chunkRows = await ctx.remote.selectChildren('knowledge_chunks', 'document_id', id, 'chunk_index,content', 'chunk_index')
|
||||
const chunks = chunkRows.map((c) => str(c.content)).filter((c): c is string => c !== null)
|
||||
return getRAGService().applyRemoteDocument({
|
||||
id,
|
||||
fileName: str(row.file_name) ?? str(row.title) ?? 'document',
|
||||
fileType: oneOf(row.file_type, KNOWLEDGE_TYPES) ?? 'txt',
|
||||
chunks,
|
||||
addedAt: ms(row.created_at, Date.now()),
|
||||
})
|
||||
},
|
||||
deleteLocal(id) {
|
||||
return getRAGService().removeRemote(id)
|
||||
},
|
||||
}
|
||||
|
||||
/** push 순서: 부모(이력·회의)가 자식(태그·메모·문서)보다 먼저. 삭제는 역순. */
|
||||
export const TABLE_ADAPTERS: readonly SyncAdapter[] = [
|
||||
historyAdapter,
|
||||
|
|
@ -943,7 +850,6 @@ export const TABLE_ADAPTERS: readonly SyncAdapter[] = [
|
|||
meetingDocumentsAdapter,
|
||||
customInstructionsAdapter,
|
||||
userTemplatesAdapter,
|
||||
knowledgeAdapter,
|
||||
]
|
||||
|
||||
export function adapterFor(entity: SyncEntity): SyncAdapter | null {
|
||||
|
|
|
|||
|
|
@ -11,12 +11,6 @@ export const SYNC_ENTITIES = [
|
|||
'memo_tags',
|
||||
'custom_instructions',
|
||||
'user_templates',
|
||||
'knowledge_documents',
|
||||
/** 단일 행(row_id 'self'): 언어·테마·자동 다듬기·활성 명령 */
|
||||
'user_settings',
|
||||
/** 녹음 파일 업로드(row_id = history id / meeting id) */
|
||||
'history_audio',
|
||||
'meeting_audio',
|
||||
] as const
|
||||
|
||||
export type SyncEntity = (typeof SYNC_ENTITIES)[number]
|
||||
|
|
@ -60,18 +54,9 @@ export interface RemotePageRequest {
|
|||
export interface SyncRemote {
|
||||
fetchPage(request: RemotePageRequest): Promise<RemoteRow[]>
|
||||
selectWhere(table: string, userId: string, filters: RemoteFilter[], columns?: string): Promise<RemoteRow[]>
|
||||
/** user_id 소유 검사가 없는 자식 테이블(knowledge_chunks) 조회 — RLS가 부모 소유로 거른다 */
|
||||
selectChildren(table: string, parentColumn: string, parentId: string, columns: string, orderBy: string): Promise<RemoteRow[]>
|
||||
upsert(table: string, rows: RemoteRow[], onConflict?: string): Promise<void>
|
||||
insert(table: string, rows: RemoteRow[]): Promise<void>
|
||||
/** user_id + match 조건에 맞는 행을 patch로 수정하고 수정된 행 수를 돌려준다(낙관적 동시성용) */
|
||||
updateMatching(table: string, userId: string, match: Record<string, string | number>, patch: RemoteRow): Promise<number>
|
||||
upsert(table: string, rows: RemoteRow[]): Promise<void>
|
||||
deleteByIds(table: string, userId: string, ids: string[]): Promise<void>
|
||||
deleteChildren(table: string, parentColumn: string, parentId: string): Promise<void>
|
||||
rpc(name: string, params: Record<string, unknown>): Promise<unknown>
|
||||
invokeFunction(name: string, body: Record<string, unknown>): Promise<unknown>
|
||||
uploadObject(bucket: string, key: string, bytes: Uint8Array, contentType: string): Promise<void>
|
||||
removeObjects(bucket: string, keys: string[]): Promise<void>
|
||||
}
|
||||
|
||||
export class SyncRemoteError extends Error {
|
||||
|
|
|
|||
|
|
@ -67,7 +67,6 @@ import type {
|
|||
HistoryDeleteParams,
|
||||
HistorySearchParams,
|
||||
HistorySetFavoriteParams,
|
||||
HistoryAudioSource,
|
||||
DictionaryQueryParams,
|
||||
DictionaryPage,
|
||||
DictionaryEntry,
|
||||
|
|
@ -412,8 +411,6 @@ const electronAPI = {
|
|||
deleteAll: () => invoke<void>(IPC_CHANNELS.HISTORY.DELETE_ALL),
|
||||
setFavorite: (params: HistorySetFavoriteParams) =>
|
||||
invoke<HistoryEntry>(IPC_CHANNELS.HISTORY.SET_FAVORITE, params),
|
||||
getAudio: (params: HistoryGetByIdParams) =>
|
||||
invoke<HistoryAudioSource | null>(IPC_CHANNELS.HISTORY.GET_AUDIO, params),
|
||||
search: (params: HistorySearchParams) =>
|
||||
invoke<HistoryPage>(IPC_CHANNELS.HISTORY.SEARCH, params),
|
||||
onAdded: (cb: (e: HistoryEntry) => void): Unsubscribe =>
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
import { useState, useEffect, useMemo, useRef } from 'react'
|
||||
import { ThemeProvider, CssBaseline, useMediaQuery } from '@mui/material'
|
||||
import { getTheme } from '@d3ro/ui/theme'
|
||||
import { I18nProvider, useI18n, type I18nStorage, type Locale } from '@d3ro/i18n'
|
||||
import { I18nProvider, type I18nStorage, type Locale } from '@d3ro/i18n'
|
||||
import { AppLayout } from './components/AppLayout'
|
||||
import { UpgradePromptModal } from './components/UpgradePromptModal'
|
||||
import { startSystemAudioCapture, stopSystemAudioCapture } from './utils/systemAudioCapture'
|
||||
|
|
@ -26,21 +26,6 @@ const electronI18nStorage: I18nStorage = {
|
|||
}
|
||||
}
|
||||
|
||||
/** 다른 기기(모바일)에서 바꾼 언어가 동기화로 들어오면 화면 언어도 바꾼다. */
|
||||
function SyncedLocale(): null {
|
||||
const { locale, setLocale } = useI18n()
|
||||
useEffect(
|
||||
() =>
|
||||
window.electronAPI.config.onChanged((e: ConfigChangedEvent) => {
|
||||
if (e.key === 'language' && typeof e.value === 'string' && e.value !== locale) {
|
||||
setLocale(e.value as Locale)
|
||||
}
|
||||
}),
|
||||
[locale, setLocale],
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
export function App(): React.ReactElement {
|
||||
const [themeMode, setThemeMode] = useState<ThemeMode>('auto')
|
||||
const prefersDark = useMediaQuery('(prefers-color-scheme: dark)')
|
||||
|
|
@ -91,7 +76,6 @@ export function App(): React.ReactElement {
|
|||
|
||||
return (
|
||||
<I18nProvider storage={electronI18nStorage}>
|
||||
<SyncedLocale />
|
||||
<ThemeProvider theme={theme}>
|
||||
<CssBaseline />
|
||||
<AppLayout />
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
// 로그인 상태 / 지금 동기화 / 마지막 동기화 / 올릴 변경·거부된 변경 건수
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Box, Button, Stack, Alert, CircularProgress, FormControlLabel, Switch } from '@mui/material'
|
||||
import { Box, Button, Stack, Alert, CircularProgress } from '@mui/material'
|
||||
import { Cloud, CloudCheck, Globe, GitBranch, RefreshCw } from 'lucide-react'
|
||||
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
|
||||
import { useI18n } from '@d3ro/i18n'
|
||||
|
|
@ -32,7 +32,6 @@ export function CloudSyncSection(): React.ReactElement {
|
|||
const [error, setError] = useState<string | null>(null)
|
||||
const [info, setInfo] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [audioSync, setAudioSync] = useState(true)
|
||||
|
||||
const refreshState = useCallback(async () => {
|
||||
const r = await window.electronAPI.cloudSync.getState()
|
||||
|
|
@ -42,9 +41,6 @@ export function CloudSyncSection(): React.ReactElement {
|
|||
// 초기 상태 로드 + 이벤트 구독
|
||||
useEffect(() => {
|
||||
void refreshState()
|
||||
void window.electronAPI.config.get({ key: 'cloudSyncAudio' }).then((r) => {
|
||||
if (r.success) setAudioSync(r.data !== false)
|
||||
})
|
||||
|
||||
const unsubAuth = window.electronAPI.cloudSync.onAuthChanged(() => {
|
||||
void refreshState()
|
||||
|
|
@ -64,11 +60,6 @@ export function CloudSyncSection(): React.ReactElement {
|
|||
}
|
||||
}, [refreshState])
|
||||
|
||||
function handleAudioSyncChange(enabled: boolean): void {
|
||||
setAudioSync(enabled)
|
||||
void window.electronAPI.config.set({ key: 'cloudSyncAudio', value: enabled })
|
||||
}
|
||||
|
||||
async function handleSignIn(provider: 'google' | 'github'): Promise<void> {
|
||||
setError(null)
|
||||
setBusy(true)
|
||||
|
|
@ -183,16 +174,6 @@ export function CloudSyncSection(): React.ReactElement {
|
|||
)}
|
||||
</Stack>
|
||||
|
||||
<Box>
|
||||
<FormControlLabel
|
||||
control={<Switch checked={audioSync} onChange={(e) => handleAudioSyncChange(e.target.checked)} />}
|
||||
label={t('cloudSync.audio')}
|
||||
/>
|
||||
<Box sx={{ color: d3roPalette.text.muted, fontSize: 12, lineHeight: 1.6, pl: 0.5 }}>
|
||||
{t('cloudSync.audioDesc')}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Stack direction="row" spacing={1}>
|
||||
<Button
|
||||
variant="contained"
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
// src/renderer/components/shared/HistoryEntryCard.tsx
|
||||
// High-End Agency Dictation History Card with Audio Telemetry & Instant Actions
|
||||
|
||||
import React, { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import React, { useState, useEffect, useCallback } from 'react'
|
||||
import { Box, IconButton, Tooltip, Chip, Collapse } from '@mui/material'
|
||||
import { Copy, Check, Trash2, Tag, X, ScrollText, ChevronDown, Sparkles, Volume2, Star, Play, Square } from 'lucide-react'
|
||||
import { Copy, Check, Trash2, Tag, X, ScrollText, ChevronDown, Sparkles, Volume2, Star } from 'lucide-react'
|
||||
import { MetalCard, Led, TactileBadge } from '@d3ro/ui/components/ds'
|
||||
import { d3roPalette, d3roFontSans, d3roFontMono, d3roTypo, d3roRadius, d3roShadow } from '@d3ro/ui/theme'
|
||||
import { useI18n } from '@d3ro/i18n'
|
||||
|
|
@ -40,56 +40,6 @@ export function HistoryEntryCard({
|
|||
const [summaryLoading, setSummaryLoading] = useState(false)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const hasSummary = !!entry.summaryText
|
||||
const [audioState, setAudioState] = useState<'idle' | 'loading' | 'playing' | 'unavailable'>('idle')
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
const objectUrlRef = useRef<string | null>(null)
|
||||
|
||||
const stopAudio = useCallback((next: 'idle' | 'unavailable' = 'idle') => {
|
||||
audioRef.current?.pause()
|
||||
audioRef.current = null
|
||||
if (objectUrlRef.current) {
|
||||
URL.revokeObjectURL(objectUrlRef.current)
|
||||
objectUrlRef.current = null
|
||||
}
|
||||
setAudioState(next)
|
||||
}, [])
|
||||
|
||||
useEffect(() => () => stopAudio(), [stopAudio])
|
||||
|
||||
// 이 기기 녹음은 파일 바이트로, 모바일·웹 녹음은 서명 URL로 재생한다.
|
||||
const handleToggleAudio = useCallback(
|
||||
async (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (audioState === 'playing') {
|
||||
stopAudio()
|
||||
return
|
||||
}
|
||||
setAudioState('loading')
|
||||
try {
|
||||
const result = await window.electronAPI.history.getAudio({ id: entry.id })
|
||||
if (!result.success || !result.data) {
|
||||
stopAudio('unavailable')
|
||||
return
|
||||
}
|
||||
let src: string
|
||||
if (result.data.kind === 'local') {
|
||||
src = URL.createObjectURL(new Blob([result.data.bytes.slice()], { type: result.data.mimeType }))
|
||||
objectUrlRef.current = src
|
||||
} else {
|
||||
src = result.data.url
|
||||
}
|
||||
const audio = new Audio(src)
|
||||
audioRef.current = audio
|
||||
audio.onended = () => stopAudio()
|
||||
audio.onerror = () => stopAudio('unavailable')
|
||||
await audio.play()
|
||||
setAudioState('playing')
|
||||
} catch {
|
||||
stopAudio('unavailable')
|
||||
}
|
||||
},
|
||||
[audioState, entry.id, stopAudio],
|
||||
)
|
||||
|
||||
const loadTags = useCallback(async () => {
|
||||
if (!showTags) return
|
||||
|
|
@ -213,39 +163,6 @@ export function HistoryEntryCard({
|
|||
|
||||
{/* Quick Action Buttons */}
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, flexShrink: 0 }}>
|
||||
{entry.duration > 0 && (
|
||||
<Tooltip
|
||||
title={
|
||||
audioState === 'playing'
|
||||
? t('history.stopAudio')
|
||||
: audioState === 'unavailable'
|
||||
? t('history.audioUnavailable')
|
||||
: t('history.playAudio')
|
||||
}
|
||||
>
|
||||
<span>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label={audioState === 'playing' ? t('history.stopAudio') : t('history.playAudio')}
|
||||
disabled={audioState === 'loading'}
|
||||
onClick={(e) => void handleToggleAudio(e)}
|
||||
sx={{
|
||||
p: 0.6,
|
||||
color:
|
||||
audioState === 'playing'
|
||||
? d3roPalette.accent.main
|
||||
: audioState === 'unavailable'
|
||||
? d3roPalette.tag.red
|
||||
: d3roPalette.text.inactive,
|
||||
bgcolor: audioState === 'playing' ? d3roPalette.accent.dim : 'transparent',
|
||||
'&:hover': { color: d3roPalette.text.primary, bgcolor: d3roPalette.glass.raised },
|
||||
}}
|
||||
>
|
||||
{audioState === 'playing' ? <Square size={13} /> : <Play size={14} />}
|
||||
</IconButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{onToggleFavorite && (
|
||||
<Tooltip title={entry.isFavorite ? t('history.unfavorite') : t('history.favorite')}>
|
||||
<IconButton
|
||||
|
|
|
|||
|
|
@ -17,9 +17,6 @@ export class FakeSyncRemote implements SyncRemote {
|
|||
private clock = Date.parse('2026-09-27T00:00:00.000Z')
|
||||
private tombstoneSeq = 0
|
||||
networkDown = false
|
||||
/** 업로드된 저장소 객체: `${bucket}/${key}` → 바이트 */
|
||||
readonly objects = new Map<string, Uint8Array>()
|
||||
readonly invoked: string[] = []
|
||||
/** 특정 행 upsert를 거부시키는 훅 (재시도 불가 오류 시뮬레이션) */
|
||||
rejectRow: ((table: string, row: RemoteRow) => SyncRemoteError | null) | null = null
|
||||
readonly calls: string[] = []
|
||||
|
|
@ -109,71 +106,7 @@ export class FakeSyncRemote implements SyncRemote {
|
|||
.map((r) => ({ ...r }))
|
||||
}
|
||||
|
||||
async selectChildren(
|
||||
table: string,
|
||||
parentColumn: string,
|
||||
parentId: string,
|
||||
_columns: string,
|
||||
orderBy: string
|
||||
): Promise<RemoteRow[]> {
|
||||
this.guard()
|
||||
return this.rows(table)
|
||||
.filter((r) => r[parentColumn] === parentId)
|
||||
.sort((a, b) => Number(a[orderBy]) - Number(b[orderBy]))
|
||||
.map((r) => ({ ...r }))
|
||||
}
|
||||
|
||||
async insert(table: string, rows: RemoteRow[]): Promise<void> {
|
||||
this.guard()
|
||||
this.calls.push(`insert:${table}:${rows.length}`)
|
||||
for (const row of rows) {
|
||||
if (table === 'user_settings' && this.rows(table).some((r) => r.user_id === row.user_id)) {
|
||||
throw new SyncRemoteError('duplicate key value', '23505', false)
|
||||
}
|
||||
const at = this.now()
|
||||
this.rows(table).push({ id: crypto.randomUUID(), revision: 1, created_at: at, updated_at: at, ...row })
|
||||
}
|
||||
}
|
||||
|
||||
async updateMatching(
|
||||
table: string,
|
||||
userId: string,
|
||||
match: Record<string, string | number>,
|
||||
patch: RemoteRow
|
||||
): Promise<number> {
|
||||
this.guard()
|
||||
this.calls.push(`update:${table}`)
|
||||
const rows = this.rows(table).filter(
|
||||
(r) => r.user_id === userId && Object.entries(match).every(([k, v]) => r[k] === v)
|
||||
)
|
||||
for (const row of rows) Object.assign(row, patch, { updated_at: this.now() })
|
||||
return rows.length
|
||||
}
|
||||
|
||||
async deleteChildren(table: string, parentColumn: string, parentId: string): Promise<void> {
|
||||
this.guard()
|
||||
const rows = this.rows(table)
|
||||
for (let i = rows.length - 1; i >= 0; i--) if (rows[i][parentColumn] === parentId) rows.splice(i, 1)
|
||||
}
|
||||
|
||||
async invokeFunction(name: string, body: Record<string, unknown>): Promise<unknown> {
|
||||
this.guard()
|
||||
this.invoked.push(`${name}:${String(body.document_id ?? '')}`)
|
||||
return { indexed: true }
|
||||
}
|
||||
|
||||
async uploadObject(bucket: string, key: string, bytes: Uint8Array): Promise<void> {
|
||||
this.guard()
|
||||
if (!key.startsWith(`${this.userId}/`)) throw new SyncRemoteError('row-level security', '42501', false)
|
||||
this.objects.set(`${bucket}/${key}`, bytes)
|
||||
}
|
||||
|
||||
async removeObjects(bucket: string, keys: string[]): Promise<void> {
|
||||
this.guard()
|
||||
for (const key of keys) this.objects.delete(`${bucket}/${key}`)
|
||||
}
|
||||
|
||||
async upsert(table: string, rows: RemoteRow[], onConflict = 'id'): Promise<void> {
|
||||
async upsert(table: string, rows: RemoteRow[]): Promise<void> {
|
||||
this.guard()
|
||||
this.calls.push(`upsert:${table}:${rows.length}`)
|
||||
// 배치는 원자적이다: 하나라도 거부되면 전체 실패
|
||||
|
|
@ -193,19 +126,15 @@ export class FakeSyncRemote implements SyncRemote {
|
|||
throw new SyncRemoteError('violates foreign key', '23503', true)
|
||||
}
|
||||
}
|
||||
const conflictColumns = onConflict.split(',')
|
||||
for (const row of rows) {
|
||||
const existing =
|
||||
onConflict === 'id'
|
||||
? this.find(table, String(row.id))
|
||||
: this.rows(table).find((r) => conflictColumns.every((c) => r[c] === row[c]))
|
||||
const existing = this.find(table, String(row.id))
|
||||
if (existing) {
|
||||
const changed = Object.keys(row).some((k) => k !== 'updated_at' && existing[k] !== row[k])
|
||||
Object.assign(existing, row, { updated_at: this.now() })
|
||||
if (table === 'history' && changed) existing.revision = Number(existing.revision ?? 1) + 1
|
||||
} else {
|
||||
const at = this.now()
|
||||
this.rows(table).push({ id: crypto.randomUUID(), revision: 1, created_at: at, ...row, updated_at: row.updated_at ?? at })
|
||||
this.rows(table).push({ revision: 1, created_at: at, ...row, updated_at: row.updated_at ?? at })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -239,10 +168,6 @@ export class FakeSyncRemote implements SyncRemote {
|
|||
if (table === 'history') {
|
||||
for (const t of this.rows('memo_tags').filter((r) => r.history_id === id)) this.removeRow('memo_tags', String(t.id))
|
||||
}
|
||||
if (table === 'knowledge_documents') {
|
||||
const chunks = this.rows('knowledge_chunks')
|
||||
for (let i = chunks.length - 1; i >= 0; i--) if (chunks[i].document_id === id) chunks.splice(i, 1)
|
||||
}
|
||||
}
|
||||
|
||||
async rpc(name: string, params: Record<string, unknown>): Promise<unknown> {
|
||||
|
|
@ -288,16 +213,6 @@ export class FakeSyncRemote implements SyncRemote {
|
|||
}
|
||||
return this.mobileInsert('user_templates', { id, revision: 1, ...fields })
|
||||
}
|
||||
if (name === 'set_active_custom_instruction') {
|
||||
const instructionId = params.instruction_id
|
||||
if (instructionId !== null && !this.find('custom_instructions', String(instructionId))) {
|
||||
throw new SyncRemoteError('instruction_not_found', 'P0002', true)
|
||||
}
|
||||
const row = this.rows('user_settings').find((r) => r.user_id === this.userId)
|
||||
if (row) Object.assign(row, { active_instruction_id: instructionId, revision: Number(row.revision) + 1, updated_at: this.now() })
|
||||
else this.mobileInsert('user_settings', { active_instruction_id: instructionId, revision: 1 })
|
||||
return row
|
||||
}
|
||||
if (name === 'sync_delete_user_template_v1') {
|
||||
const id = String(params.p_id)
|
||||
if (!this.find('user_templates', id)) return false
|
||||
|
|
|
|||
|
|
@ -8,18 +8,14 @@
|
|||
// vitest run tests/integration/cross-device-sync.supabase.test.ts
|
||||
// 환경변수가 없으면 건너뛴다(CI 기본).
|
||||
|
||||
import fs from 'fs'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
|
||||
import { nodeRealtimeTransport } from '../../src/main/services/sync/realtime-transport'
|
||||
import { createTestDb } from '../helpers/createTestDb'
|
||||
import { bindTestDatabase, unbindTestDatabase } from '../../src/main/db'
|
||||
import { dictionary, history, meetingMemos, meetingSessions, memoTags, ragChunks, ragDocuments } from '../../src/main/db/schema'
|
||||
import { configGet, configSet, initInMemoryConfig, resetInMemoryConfig } from '../../src/main/services/ConfigService'
|
||||
import { resetRAGServiceForTests } from '../../src/main/services/RAGService'
|
||||
import { dictionary, history, meetingMemos, meetingSessions, memoTags } from '../../src/main/db/schema'
|
||||
import { initInMemoryConfig, resetInMemoryConfig } from '../../src/main/services/ConfigService'
|
||||
import {
|
||||
getCustomInstructionService,
|
||||
resetCustomInstructionServiceForTests,
|
||||
|
|
@ -256,82 +252,6 @@ describe.skipIf(!enabled)('cross-device sync against local Supabase', () => {
|
|||
expect(seen).toContain('tombstone')
|
||||
}, 45_000)
|
||||
|
||||
it('지식 문서(원문 청크)·설정·녹음이 실제 RLS/저장소 정책을 통과해 오간다', async () => {
|
||||
const db = testDb.db
|
||||
resetRAGServiceForTests()
|
||||
// 로컬 임베딩 서버(Ollama)는 없다고 보고 원문 저장 경로만 확인한다(Supabase 호출은 통과시킨다).
|
||||
const realFetch = globalThis.fetch
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) =>
|
||||
String(input instanceof Request ? input.url : input).includes('11434')
|
||||
? Promise.reject(new TypeError('fetch failed'))
|
||||
: realFetch(input, init)
|
||||
)
|
||||
|
||||
// 데스크톱 지식 문서
|
||||
const docId = crypto.randomUUID()
|
||||
db.insert(ragDocuments).values({ id: docId, fileName: 'desk.md', filePath: '', fileType: 'md', chunkCount: 2, indexed: false, addedAt: Date.now() }).run()
|
||||
;['alpha chunk', 'beta chunk'].forEach((content, chunkIndex) =>
|
||||
db.insert(ragChunks).values({ id: crypto.randomUUID(), documentId: docId, content, embedding: '', chunkIndex }).run()
|
||||
)
|
||||
enqueueChange('knowledge_documents', docId, 'upsert')
|
||||
|
||||
// 모바일 지식 문서
|
||||
const phoneDoc = crypto.randomUUID()
|
||||
must(await mobile.from('knowledge_documents').insert({ id: phoneDoc, user_id: userId, title: 'Phone doc', file_name: 'phone.txt', file_type: 'txt', chunk_count: 1 }))
|
||||
must(await mobile.from('knowledge_chunks').insert({ document_id: phoneDoc, chunk_index: 0, content: 'from the phone' }))
|
||||
|
||||
// 녹음이 있는 데스크톱 기록
|
||||
const audioDir = fs.mkdtempSync(path.join(os.tmpdir(), 'd3ro-it-audio-'))
|
||||
const audioFile = path.join(audioDir, 'clip.wav')
|
||||
fs.writeFileSync(audioFile, Buffer.from('RIFF----WAVEfmt integration audio bytes'))
|
||||
const clipId = crypto.randomUUID()
|
||||
db.insert(history).values({ id: clipId, originalText: 'with audio', duration: 1, audioLocalPath: audioFile, createdAt: Date.now(), updatedAt: Date.now() }).run()
|
||||
enqueueChange('history', clipId, 'upsert')
|
||||
enqueueChange('history_audio', clipId, 'upsert')
|
||||
|
||||
// 설정: 데스크톱 변경 → 서버, 이후 모바일 변경 → 데스크톱
|
||||
configSet('theme', 'dark')
|
||||
enqueueChange('user_settings', 'self', 'upsert')
|
||||
|
||||
const pushed = await engine.flush()
|
||||
expect(pushed.errors).toEqual([])
|
||||
const remoteChunks = must(await mobile.from('knowledge_chunks').select('content').eq('document_id', docId).order('chunk_index'))
|
||||
expect(remoteChunks.map((c) => c.content)).toEqual(['alpha chunk', 'beta chunk'])
|
||||
const audio = must(await mobile.from('audio_files').select('storage_key,upload_status,mime_type').eq('history_id', clipId))
|
||||
expect(audio).toHaveLength(1)
|
||||
expect(audio[0].upload_status).toBe('uploaded')
|
||||
const signed = await mobile.storage.from('audio').createSignedUrl(String(audio[0].storage_key), 60)
|
||||
expect(signed.error).toBeNull()
|
||||
const settings = must(await mobile.from('user_settings').select('theme_mode,revision').eq('user_id', userId).single())
|
||||
expect(settings.theme_mode).toBe('dark')
|
||||
|
||||
must(
|
||||
await mobile
|
||||
.from('user_settings')
|
||||
.update({ locale: 'en', revision: Number(settings.revision) + 1 })
|
||||
.eq('user_id', userId)
|
||||
.eq('revision', settings.revision)
|
||||
)
|
||||
await engine.pull()
|
||||
expect(configGet('language')).toBe('en')
|
||||
const pulledChunks = db.select().from(ragChunks).where(eq(ragChunks.documentId, phoneDoc)).all()
|
||||
expect(pulledChunks.map((c) => c.content)).toEqual(['from the phone'])
|
||||
|
||||
// 모바일이 지식 문서를 지우면 데스크톱에서도 사라진다(삭제 기록)
|
||||
must(await mobile.from('knowledge_documents').delete().eq('id', phoneDoc))
|
||||
await engine.pull()
|
||||
expect(db.select().from(ragDocuments).where(eq(ragDocuments.id, phoneDoc)).all()).toEqual([])
|
||||
|
||||
// 데스크톱 기록 삭제 → 저장소 녹음도 정리
|
||||
db.delete(history).where(eq(history.id, clipId)).run()
|
||||
enqueueChange('history', clipId, 'delete')
|
||||
const deleted = await engine.flush()
|
||||
expect(deleted.errors).toEqual([])
|
||||
expect(must(await mobile.from('audio_files').select('id').eq('user_id', userId).eq('storage_key', String(audio[0].storage_key)))).toEqual([])
|
||||
fs.rmSync(audioDir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
}, 60_000)
|
||||
|
||||
it('데스크톱이 기기 목록에 나타나고, 모바일에서 해제하면 revoked가 된다', async () => {
|
||||
const info = { deviceName: 'IT-DESKTOP', appVersion: '9.9.9', osVersion: 'test' }
|
||||
const first = await checkInDesktopDevice(desktop, userId, 'signin', info, null)
|
||||
|
|
|
|||
|
|
@ -1,203 +0,0 @@
|
|||
// 동기화 확장 — 지식베이스(원문 청크), 모바일 user_settings, 녹음 파일 업로드.
|
||||
|
||||
import fs from 'fs'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { createTestDb } from '../../helpers/createTestDb'
|
||||
import { FakeSyncRemote } from '../../helpers/fakeSyncRemote'
|
||||
import { bindTestDatabase, unbindTestDatabase } from '../../../src/main/db'
|
||||
import { history, ragChunks, ragDocuments } from '../../../src/main/db/schema'
|
||||
import { configGet, configSet, initInMemoryConfig, resetInMemoryConfig } from '../../../src/main/services/ConfigService'
|
||||
import {
|
||||
getCustomInstructionService,
|
||||
resetCustomInstructionServiceForTests,
|
||||
} from '../../../src/main/services/CustomInstructionService'
|
||||
import { resetDictationTemplateServiceForTests } from '../../../src/main/services/DictationTemplateService'
|
||||
import { resetMeetingDocTemplateServiceForTests } from '../../../src/main/services/MeetingDocTemplateService'
|
||||
import { resetRAGServiceForTests } from '../../../src/main/services/RAGService'
|
||||
import { SyncEngine } from '../../../src/main/services/sync/SyncEngine'
|
||||
import { enqueueChange, outboxCounts, pendingOps } from '../../../src/main/services/sync/sync-outbox'
|
||||
import { remoteToLocalPatch, toRemoteSettings } from '../../../src/main/services/sync/settings-sync'
|
||||
|
||||
const USER = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
let testDb: ReturnType<typeof createTestDb>
|
||||
let remote: FakeSyncRemote
|
||||
let engine: SyncEngine
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
testDb = createTestDb()
|
||||
bindTestDatabase(testDb.db, USER)
|
||||
initInMemoryConfig()
|
||||
resetCustomInstructionServiceForTests()
|
||||
resetDictationTemplateServiceForTests()
|
||||
resetMeetingDocTemplateServiceForTests()
|
||||
resetRAGServiceForTests()
|
||||
getCustomInstructionService().initialize()
|
||||
// 로컬 임베딩 서버(Ollama)는 테스트에 없다 — 즉시 실패시켜 원문만 저장되는 경로를 탄다.
|
||||
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('fetch failed'))
|
||||
remote = new FakeSyncRemote(USER)
|
||||
engine = new SyncEngine({ remote, userId: USER })
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'd3ro-sync-audio-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
engine.dispose()
|
||||
unbindTestDatabase()
|
||||
resetInMemoryConfig()
|
||||
testDb.close()
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function insertLocalDocument(chunks: string[]): string {
|
||||
const id = crypto.randomUUID()
|
||||
testDb.db
|
||||
.insert(ragDocuments)
|
||||
.values({ id, fileName: 'notes.md', filePath: '', fileType: 'md', chunkCount: chunks.length, indexed: false, addedAt: Date.now() })
|
||||
.run()
|
||||
chunks.forEach((content, chunkIndex) => {
|
||||
testDb.db.insert(ragChunks).values({ id: crypto.randomUUID(), documentId: id, content, embedding: '', chunkIndex }).run()
|
||||
})
|
||||
return id
|
||||
}
|
||||
|
||||
describe('지식베이스', () => {
|
||||
it('데스크톱 문서를 원문 청크로 올리고 서버 임베딩을 요청한다', async () => {
|
||||
const id = insertLocalDocument(['first chunk text', 'second chunk text'])
|
||||
const result = await engine.runFullSync()
|
||||
expect(result.errors).toEqual([])
|
||||
expect(remote.find('knowledge_documents', id)?.chunk_count).toBe(2)
|
||||
expect(remote.rows('knowledge_chunks').filter((c) => c.document_id === id).map((c) => c.content)).toEqual([
|
||||
'first chunk text',
|
||||
'second chunk text',
|
||||
])
|
||||
expect(remote.invoked).toContain(`embed-chunks:${id}`)
|
||||
})
|
||||
|
||||
it('모바일 문서를 받아 원문을 저장하고, 모바일 삭제를 반영한다', async () => {
|
||||
const id = crypto.randomUUID()
|
||||
remote.mobileInsert('knowledge_documents', { id, title: 'Phone doc', file_name: 'phone.txt', file_type: 'txt', chunk_count: 2 })
|
||||
remote.rows('knowledge_chunks').push(
|
||||
{ id: crypto.randomUUID(), document_id: id, chunk_index: 1, content: 'second' },
|
||||
{ id: crypto.randomUUID(), document_id: id, chunk_index: 0, content: 'first' }
|
||||
)
|
||||
await engine.runFullSync()
|
||||
const doc = testDb.db.select().from(ragDocuments).where(eq(ragDocuments.id, id)).get()
|
||||
expect(doc?.fileName).toBe('phone.txt')
|
||||
expect(doc?.filePath).toBe('')
|
||||
const chunks = testDb.db.select().from(ragChunks).where(eq(ragChunks.documentId, id)).all()
|
||||
expect(chunks.sort((a, b) => a.chunkIndex - b.chunkIndex).map((c) => c.content)).toEqual(['first', 'second'])
|
||||
|
||||
remote.mobileDelete('knowledge_documents', id)
|
||||
await engine.pull()
|
||||
expect(testDb.db.select().from(ragDocuments).all()).toEqual([])
|
||||
expect(testDb.db.select().from(ragChunks).all()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('설정 (user_settings)', () => {
|
||||
it('서버에 행이 없으면 데스크톱 값을 올린다', async () => {
|
||||
configSet('language', 'en')
|
||||
configSet('theme', 'dark')
|
||||
configSet('defaultLLMAction', 'none')
|
||||
await engine.runFullSync()
|
||||
const row = remote.rows('user_settings')[0]
|
||||
expect(row).toMatchObject({ locale: 'en', theme_mode: 'dark', auto_polish_enabled: false })
|
||||
})
|
||||
|
||||
it('서버에 행이 있으면 모바일 값이 이기고, 반영이 다시 올라가지 않는다', async () => {
|
||||
configSet('language', 'en')
|
||||
configSet('theme', 'auto')
|
||||
configSet('defaultLLMAction', 'none')
|
||||
remote.mobileInsert('user_settings', { locale: 'ko', theme_mode: 'light', auto_polish_enabled: true, revision: 4, active_instruction_id: null })
|
||||
const result = await engine.runFullSync()
|
||||
expect(result.changed).toContain('user_settings')
|
||||
expect(configGet('language')).toBe('ko')
|
||||
expect(configGet('theme')).toBe('light')
|
||||
expect(configGet('defaultLLMAction')).toBe('refine')
|
||||
expect(pendingOps('user_settings').size).toBe(0)
|
||||
expect(remote.rows('user_settings')[0].revision).toBe(4)
|
||||
})
|
||||
|
||||
it('데스크톱 변경은 revision 조건부로 올리고, 같은 값이면 쓰지 않는다', async () => {
|
||||
remote.mobileInsert('user_settings', { locale: 'ko', theme_mode: 'system', auto_polish_enabled: true, revision: 2, active_instruction_id: null })
|
||||
await engine.runFullSync()
|
||||
configSet('theme', 'dark')
|
||||
enqueueChange('user_settings', 'self', 'upsert')
|
||||
await engine.flush()
|
||||
expect(remote.rows('user_settings')[0]).toMatchObject({ theme_mode: 'dark', revision: 3 })
|
||||
|
||||
enqueueChange('user_settings', 'self', 'upsert')
|
||||
await engine.flush()
|
||||
expect(remote.rows('user_settings')[0].revision).toBe(3)
|
||||
expect(outboxCounts().pending).toBe(0)
|
||||
})
|
||||
|
||||
it('양쪽에 있는 사용자 명령만 활성 명령으로 맞춘다', async () => {
|
||||
const command = getCustomInstructionService().create({ name: 'Calm', description: '', prompt: 'Make it calm' })
|
||||
await engine.runFullSync()
|
||||
const row = remote.rows('user_settings')[0]
|
||||
Object.assign(row, { active_instruction_id: command.id, revision: Number(row.revision) + 1 })
|
||||
await engine.pull()
|
||||
expect(configGet('activeInstructionId')).toBe(command.id)
|
||||
|
||||
// 데스크톱 프리셋이 켜져 있으면 모바일의 '없음'이 덮지 않는다
|
||||
const local = { language: 'ko', theme: 'auto' as const, defaultLLMAction: 'refine' as const, activeInstructionId: 'builtin-translate' }
|
||||
expect(remoteToLocalPatch({ active_instruction_id: null }, local, new Set([command.id]))).toEqual({})
|
||||
})
|
||||
|
||||
it('데스크톱 전용 테마·언어는 서버로 보내지 않는다', () => {
|
||||
expect(toRemoteSettings({ language: 'ja', theme: 'nord', defaultLLMAction: 'translate', activeInstructionId: '' })).toEqual({
|
||||
auto_polish_enabled: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('녹음 파일', () => {
|
||||
function insertHistoryWithAudio(): { id: string; file: string } {
|
||||
const id = crypto.randomUUID()
|
||||
const file = path.join(tmpDir, `${id}.wav`)
|
||||
fs.writeFileSync(file, Buffer.from('RIFF....WAVEfmt fake audio'))
|
||||
const now = Date.now()
|
||||
testDb.db.insert(history).values({ id, originalText: 'spoken', duration: 2, audioLocalPath: file, createdAt: now, updatedAt: now }).run()
|
||||
return { id, file }
|
||||
}
|
||||
|
||||
it('기록 녹음을 모바일과 같은 경로·행으로 올리고, 기록을 지우면 파일도 지운다', async () => {
|
||||
const { id } = insertHistoryWithAudio()
|
||||
const result = await engine.runFullSync()
|
||||
expect(result.errors).toEqual([])
|
||||
const key = `${USER}/desktop/history/${id}.wav`
|
||||
expect(remote.objects.has(`audio/${key}`)).toBe(true)
|
||||
expect(remote.rows('audio_files')[0]).toMatchObject({
|
||||
history_id: id,
|
||||
storage_key: key,
|
||||
mime_type: 'audio/wav',
|
||||
upload_status: 'uploaded',
|
||||
duration_ms: 2000,
|
||||
})
|
||||
|
||||
// 같은 파일은 다시 올리지 않는다
|
||||
enqueueChange('history_audio', id, 'upsert')
|
||||
await engine.flush()
|
||||
expect(remote.rows('audio_files')).toHaveLength(1)
|
||||
|
||||
testDb.db.delete(history).where(eq(history.id, id)).run()
|
||||
enqueueChange('history', id, 'delete')
|
||||
await engine.flush()
|
||||
expect(remote.objects.size).toBe(0)
|
||||
expect(remote.rows('audio_files')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('녹음 동기화를 끄면 올리지 않는다', async () => {
|
||||
configSet('cloudSyncAudio', false)
|
||||
insertHistoryWithAudio()
|
||||
await engine.runFullSync()
|
||||
expect(remote.objects.size).toBe(0)
|
||||
expect(outboxCounts().pending).toBe(0)
|
||||
})
|
||||
})
|
||||
|
|
@ -151,8 +151,8 @@ def versionSettingsValid = configuredVersionName != null &&
|
|||
configuredVersionName ==~ strictSemver &&
|
||||
configuredVersionCodeValue != null &&
|
||||
configuredVersionCodeValue <= 2100000000L
|
||||
def resolvedVersionName = versionSettingsValid ? configuredVersionName : "1.8.0"
|
||||
def resolvedVersionCode = versionSettingsValid ? configuredVersionCodeValue.toInteger() : 1080000
|
||||
def resolvedVersionName = versionSettingsValid ? configuredVersionName : "1.7.0"
|
||||
def resolvedVersionCode = versionSettingsValid ? configuredVersionCodeValue.toInteger() : 1070000
|
||||
|
||||
def requiredReleaseSettings = [
|
||||
D3RO_RELEASE_STORE_FILE: releaseStoreFilePath,
|
||||
|
|
|
|||
|
|
@ -257,7 +257,7 @@
|
|||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1080000;
|
||||
CURRENT_PROJECT_VERSION = 1070000;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = D3ROVoice/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
|
||||
|
|
@ -265,7 +265,7 @@
|
|||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.8.0;
|
||||
MARKETING_VERSION = 1.7.0;
|
||||
OTHER_LDFLAGS = (
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
|
|
@ -287,14 +287,14 @@
|
|||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1080000;
|
||||
CURRENT_PROJECT_VERSION = 1070000;
|
||||
INFOPLIST_FILE = D3ROVoice/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.8.0;
|
||||
MARKETING_VERSION = 1.7.0;
|
||||
OTHER_LDFLAGS = (
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
Knowledge documents and recordings from the desktop app now show up on your phone, and language, theme and auto-polish settings stay in step with the desktop.
|
||||
|
|
@ -1 +0,0 @@
|
|||
데스크톱 앱에서 추가한 지식 문서와 녹음을 휴대폰에서도 보고 들을 수 있습니다. 언어·테마·자동 다듬기 설정도 데스크톱과 함께 맞춰집니다.
|
||||
14
apps/mobile-rn/package-lock.json
generated
14
apps/mobile-rn/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "@d3ro/mobile-rn",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@d3ro/mobile-rn",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"dependencies": {
|
||||
"@d3ro/api-client": "file:../../packages/api-client",
|
||||
"@d3ro/core": "file:../../packages/core",
|
||||
|
|
@ -62,7 +62,7 @@
|
|||
},
|
||||
"../..": {
|
||||
"name": "d3ro-voice-monorepo",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"apps/desktop",
|
||||
|
|
@ -81,7 +81,7 @@
|
|||
},
|
||||
"../../packages/api-client": {
|
||||
"name": "@d3ro/api-client",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -98,7 +98,7 @@
|
|||
},
|
||||
"../../packages/core": {
|
||||
"name": "@d3ro/core",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"docx": "^9.6.1"
|
||||
|
|
@ -109,7 +109,7 @@
|
|||
},
|
||||
"../../packages/i18n": {
|
||||
"name": "@d3ro/i18n",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.0.0"
|
||||
|
|
@ -120,7 +120,7 @@
|
|||
},
|
||||
"../../packages/ui-native": {
|
||||
"name": "@d3ro/ui-native",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/react": "*"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/mobile-rn",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"android": "react-native run-android",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/web",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice 웹 앱 — Next.js 기반 SaaS 인터페이스",
|
||||
"scripts": {
|
||||
|
|
|
|||
|
|
@ -139,7 +139,7 @@ export function Sidebar(): React.ReactElement {
|
|||
</PhosphorText>
|
||||
</Box>
|
||||
<Box sx={{ fontSize: '10px', fontFamily: 'ui-monospace, monospace', color: d3roPalette.text.muted }}>
|
||||
v1.8.0
|
||||
v1.7.0
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,15 +1,15 @@
|
|||
{
|
||||
"version": "1.7.0",
|
||||
"version": "1.6.0",
|
||||
"description": "로컬 AI 음성 어시스턴트 (faster-whisper + Ollama, 100% 오프라인 지원)",
|
||||
"homepage": "https://d3ro.chanpaca.net",
|
||||
"license": "MIT",
|
||||
"architecture": {
|
||||
"64bit": {
|
||||
"url": [
|
||||
"https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/portable-1.7.0/D3RO-Voice-1.7.0-x64-portable.7z.001"
|
||||
"https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/portable-1.6.0/D3RO-Voice-1.6.0-x64-portable.7z.001"
|
||||
],
|
||||
"hash": [
|
||||
"4a1a958d2f52d72b5ba42b5128366d1d8bbeaebd23503d6af94b550d2c2907ad"
|
||||
"4cd454362ef85d69c52ce086df97fe673ba50e634d58f2be5e2ccd3d7c8c9830"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
|
@ -27,7 +27,7 @@
|
|||
"architecture": {
|
||||
"64bit": {
|
||||
"url": [
|
||||
"https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/portable-$version/D3RO-Voice-1.7.0-x64-portable.7z.001"
|
||||
"https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/portable-$version/D3RO-Voice-1.6.0-x64-portable.7z.001"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,7 @@
|
|||
|
||||
> Status: ACTIVE
|
||||
> Last full audit: 2026-09-13
|
||||
> Last update: 2026-09-27 — **v1.7.0 릴리스 + 기기 간 동기화 재작성 + 운영 DB 정렬.** 데스크톱↔모바일·웹 동기화를 outbox·서버시각 커서·삭제 기록(`sync_tombstones`)·실시간(`ws`) 엔진으로 다시 만들고, 이력·사전·회의·메모 태그·명령·템플릿·지식베이스·녹음·공통 설정·기기 등록까지 넓혔다(MEM-13, ACC-08/09, MEM-05). 운영 Supabase가 `0028`에 멈춰 있던 것을 발견해 `0029`–`0035`를 적용하고 함수 23개를 재배포했다(GAP-OPS-01 — 사용자가 자기 tier를 올릴 수 있던 권한 구멍 포함). 모바일 기기 목록·데이터 내보내기 결함도 고쳤다(GAP-SYNC-03/04). 무서명 로컬 게시 예외(GAP-REL-06) 유지.
|
||||
>
|
||||
> Previous update: 2026-09-24 — **v1.6.0 릴리스.** 버전 SSOT를 1.6.0(android/iOS 1060000)으로 올렸다. 다음 문장 제안을 1개씩 순차 생성해 최대 12개·3개씩 페이지로 보여 주고(Ctrl+Alt+↑↓ 이동, ←→ 페이지, Enter 수락, Esc 닫기; 기존 기본 단축키는 revision 5에서 이관), 오버레이를 재설계했다(`INPUT-06`/`INPUT-07`). 개인 문구 코퍼스는 터미널·에디터·코딩 에이전트와 비문장·플레이스홀더를 학습하지 않고 기존 데이터도 같은 규칙으로 정리한다(`INPUT-04`/`INPUT-05`). 제안 단축키가 받아쓰기를 켜던 버그, 구버전 사이드카가 `/uia/focus` 없이 남던 버그(런타임 최소 버전 1.5.0), Ollama 러너 콘솔 창, 사이드카 이중 기동을 고쳤다. 실시간 자막 창은 끌어서 옮길 수 있고 첫 자막 전까지 준비 안내를 보인다. 무서명 로컬 게시 예외(GAP-REL-06)를 유지한다.
|
||||
> Last update: 2026-09-24 — **v1.6.0 릴리스.** 버전 SSOT를 1.6.0(android/iOS 1060000)으로 올렸다. 다음 문장 제안을 1개씩 순차 생성해 최대 12개·3개씩 페이지로 보여 주고(Ctrl+Alt+↑↓ 이동, ←→ 페이지, Enter 수락, Esc 닫기; 기존 기본 단축키는 revision 5에서 이관), 오버레이를 재설계했다(`INPUT-06`/`INPUT-07`). 개인 문구 코퍼스는 터미널·에디터·코딩 에이전트와 비문장·플레이스홀더를 학습하지 않고 기존 데이터도 같은 규칙으로 정리한다(`INPUT-04`/`INPUT-05`). 제안 단축키가 받아쓰기를 켜던 버그, 구버전 사이드카가 `/uia/focus` 없이 남던 버그(런타임 최소 버전 1.5.0), Ollama 러너 콘솔 창, 사이드카 이중 기동을 고쳤다. 실시간 자막 창은 끌어서 옮길 수 있고 첫 자막 전까지 준비 안내를 보인다. 무서명 로컬 게시 예외(GAP-REL-06)를 유지한다.
|
||||
>
|
||||
> Previous update: 2026-09-22 — **Gemma/Ollama 폭주 방어 계약을 기록했다.** 19:14:12 부팅 워밍업이 `keep_alive: 30m`으로 `gemma4:e4b`를 19:44:12까지 VRAM 3,226,342,521 bytes / context 4096으로 강제 상주시킨 것이 관측됐으며, 같은 시점 Windows GPU Engine PID 표본에는 Ollama의 활성 compute가 없었다. 즉 당시 상태는 무한 추론이 아니라 강제 residency였다. 19:11:17~19:11:58의 자동 제안 연속 생성은 기존 900 ms·12/min·5 candidates·128 tokens·한 글자 재생성 정책이 허용한 burst였다. 현재 구현 계약은 부팅 warmup 제거, `keep_alive: 2m`, 제안 600 ms / 최소 5 s 간격 / 기본 6회·hard max 12회 per min / 3 candidates / 64 tokens / 12-char growth / 8 s timeout, 그리고 요청별 취소·상한·종료 정리다. 독립 표적 검증은 6 test files / 69 tests passed / 0 failed, 변경 코드·테스트 ESLint와 `git diff --check`도 exit 0이다. Raw Ollama에서는 cold bounded 요청이 client hard timeout 15.044 s에 취소된 뒤 `/api/ps`가 비었고 `/api/version`은 80 ms에 회복했다. 명시 warmup은 HTTP 200 / 16.639 s, 후속 warm 요청은 body `options.num_predict=1`, `keep_alive='2m'`로 553 ms HTTP 200 / `done:true` / `eval_count:1` / `done_reason:length`였고 `/api/ps` expiry는 약 119.9 s였다. **19:48:59 +09:00에는 새 generate/unload/kill/retry 없이 충분히 지난 뒤 한 번의 `/api/ps`가 HTTP 200 / 45.8 ms / `{models:[]}`였고 `/api/version`은 HTTP 200 / 7.3 ms / `0.32.13`이었다.** 이는 raw API 수준의 expiry 뒤 unload 확인일 뿐 앱 재시작·GUI·실제 타이핑 증거는 아니므로 상태는 `[~]`로 유지한다 (`11` GAP-LLM-04, GAP-INPUT-06).
|
||||
>
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ The existing `input-telemetry-handlers` and `suggestion-handlers` IPC extensions
|
|||
| `ConfigService` | electron-store `AppConfig` (`configGet/Set`, defaults) |
|
||||
| `LicenseService` | Freemium tiers, quotas (`daily_usage`), activation, upgrade prompts |
|
||||
| `CloudSyncService` | Supabase auth + lifecycle: per-user DB switching, local-mode import on first sign-in, Realtime (`ws` transport) + 5-min heartbeat, device check-in, debounced flush/pull triggers. The sync itself lives in `services/sync/` |
|
||||
| `services/sync/` | `SyncEngine` (backfill once per user DB → push outbox → pull by server-clock keyset cursor → tombstones → memo-tag reconcile), `sync-outbox` (`sync_outbox`/`sync_state` tables), `sync-adapters` (history, dictionary, meetings, meeting memos/documents, custom commands, templates), `memo-tag-sync`, `supabase-sync-remote`, `device-registration`, `realtime-transport`, `settings-sync` (mobile `user_settings` ↔ language/theme/defaultLLMAction/activeInstructionId), `audio-sync` (recording upload to the `audio` bucket, remote cleanup on delete), knowledge adapter (source-text chunks). Services record changes with `getCloudSyncService().pushOne/pushDelete(entity, id)`; pulled rows are applied without re-queuing |
|
||||
| `services/sync/` | `SyncEngine` (backfill once per user DB → push outbox → pull by server-clock keyset cursor → tombstones → memo-tag reconcile), `sync-outbox` (`sync_outbox`/`sync_state` tables), `sync-adapters` (history, dictionary, meetings, meeting memos/documents, custom commands, templates), `memo-tag-sync`, `supabase-sync-remote`, `device-registration`, `realtime-transport`. Services record changes with `getCloudSyncService().pushOne/pushDelete(entity, id)`; pulled rows are applied without re-queuing |
|
||||
| `CloudSTTService` | Thin cloud STT wrapper over `D3ROCloudDriver` |
|
||||
| `UpdateService` | electron-updater (canonical Forgejo feed, channels, mandatory/full-vs-delta policy, staged rollout, restart dialog) |
|
||||
| `AutoLaunchService` | OS login-item auto-start |
|
||||
|
|
@ -130,7 +130,7 @@ Registry: `src/main/ipc/index.ts` calls 31 `registerXHandlers()` in fixed order.
|
|||
| `context-handlers` | CONTEXT |
|
||||
| `dictionary-handlers` | DICTIONARY |
|
||||
| `file-transcription-handlers` | FILE_TRANSCRIPTION |
|
||||
| `history-handlers` | HISTORY (incl. `history:setFavorite`, `history:getAudio` → local bytes or signed URL) + `stats:getSummary` |
|
||||
| `history-handlers` | HISTORY (incl. `history:setFavorite`) + `stats:getSummary` |
|
||||
| `input-telemetry-handlers` | INPUT_TELEMETRY |
|
||||
| `instruction-handlers` | INSTRUCTION |
|
||||
| `keybinding-handlers` | KEYBINDING |
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
## 1. Supabase project (`server/supabase/`)
|
||||
|
||||
- `config.toml` — project_id `d3ro-voice`; local ports API 55321 / DB 55322 / Studio 55323 / Inbucket 55324; DB major v17; storage 50 MiB; auth `site_url` localhost:5173, redirects include `https://d3ro.chanpaca.net` and `d3ro-voice://auth-callback`; external providers Google/GitHub/Apple; per-function `verify_jwt` settings; analytics off.
|
||||
- `seed.sql`, `migrations/` (65; production at `20260927000035` — it lagged at `0028` until 2026-09-27, GAP-OPS-01), `functions/` (23, all redeployed 2026-09-27), `functions/_shared/`, `tests/`, `deno.json`.
|
||||
- `seed.sql`, `migrations/` (63), `functions/` (~27), `functions/_shared/`, `tests/`, `deno.json`.
|
||||
|
||||
> Note: root `supabase/` contains only empty scaffolding (`.branches/`, `snippets/`). The real project lives under `server/supabase/`.
|
||||
|
||||
|
|
@ -19,7 +19,7 @@
|
|||
| Core schema + RLS + auth triggers | initial tables, profiles, triggers |
|
||||
| Storage buckets | audio, meeting documents, exports |
|
||||
| Teams | team invites, membership, roles, `team_activities` feed (`20260913000033`) |
|
||||
| Cross-device sync | `20260927000035`: knowledge_documents tombstones/cursor/realtime + `pg_cron` job `prune-sync-tombstones` (daily 03:17 UTC). `20260927000034`: `sync_tombstones` (AFTER DELETE triggers on 8 synced tables, owner-read RLS, realtime, `prune_sync_tombstones_v1`), `history.revision` bump on content change, `meeting_memos.updated_at`, `(user_id, updated_at, id)` cursor indexes, client-keyed `sync_upsert/delete_user_template_v1`, realtime for `devices`/`memo_tags`/`custom_instructions`/`user_templates`, and `export_account_portability` projected back onto v1 archive keys |
|
||||
| Cross-device sync | `20260927000034`: `sync_tombstones` (AFTER DELETE triggers on 8 synced tables, owner-read RLS, realtime, `prune_sync_tombstones_v1`), `history.revision` bump on content change, `meeting_memos.updated_at`, `(user_id, updated_at, id)` cursor indexes, client-keyed `sync_upsert/delete_user_template_v1`, realtime for `devices`/`memo_tags`/`custom_instructions`/`user_templates`, and `export_account_portability` projected back onto v1 archive keys |
|
||||
| Knowledge / RAG | `knowledge_documents`, `knowledge_chunks`, pgvector |
|
||||
| Notifications / push | push tokens, durable outbox |
|
||||
| Billing | Payple, subscriptions, payment provider events/operations (`'stripe'` provider values kept only for historical rows) |
|
||||
|
|
|
|||
|
|
@ -58,15 +58,15 @@ Status quick-reference: `[x]` done+verified · `[~]` partial/unverified · `[ ]`
|
|||
| MEM-02 | History detail + edit | [x] | [x] | [x] | [x] | Mobile `HistoryDetailScreen` |
|
||||
| MEM-03 | History favorites | [~] | [x] | [x] | [x] | Desktop had **no** favorites until 2026-09-27 (the old `[x]` was wrong): `history.is_favorite` column, `HistoryService.setFavorite` + `history:setFavorite` IPC, star toggle in `HistoryEntryCard`; the value is the same Supabase `history.is_favorite` mobile filters on, so it syncs both ways (`apps/desktop/tests/main/sync/SyncEngine.test.ts` (20) + `apps/desktop/tests/integration/cross-device-sync.supabase.test.ts` (5, local Supabase stack)). `[~]` until a GUI run toggles it and mobile shows it |
|
||||
| MEM-04 | History export / share | [x] | [~] | [x] | [x] | Desktop export; web limited; mobile share sheet |
|
||||
| MEM-05 | History audio playback | [~] | [x] | [x] | [x] | Signed URLs on web/mobile. **Desktop had no playback at all** (the old `[x]` was wrong); since 2026-09-27 the history card plays this device's recording from the file (`history:getAudio` → bytes → Blob) and a phone/web recording through a 5-minute signed URL of its `audio_files` row. Desktop recordings upload to the same `audio` bucket contract (`{userId}/desktop/...`, `audio_files`, ≤50 MiB, Settings > Cloud toggle `cloudSyncAudio`) so the phone plays them too (`tests/main/sync/SyncExtensions.test.ts` (9) + integration case "지식 문서·설정·녹음" against the local Supabase stack). `[~]` until a GUI run plays both kinds |
|
||||
| MEM-05 | History audio playback | [x] | [x] | [x] | [x] | Signed URLs on web/mobile |
|
||||
| MEM-06 | Dictionary (custom vocabulary) | [x] | [x] | [x] | [x] | All surfaces CRUD; Desktop Red Team RT-02 & RT-18 fuzzed/verified |
|
||||
| MEM-07 | Dictionary import/export | [x] | [x] | [x] | [-] | Desktop `dictionary:import/export` JSON+CSV (file dialogs, `DictionaryService`); web `serializeDictionary`/`importDictionaryFile` + header buttons; mobile CSV/TXT export + CSV/JSON/TXT import via `data-portability` |
|
||||
| MEM-08 | Memos (tags over history) | [x] | [ ] | [x] | [x] | Desktop `MemoService`; mobile `MemosScreen`; web none. **Desktop tags sync with mobile since 2026-09-27**: pushed through the mobile RPCs (`mobile_add/remove_memo_tag_v1`) and reconciled by natural key `historyId` + normalized tag because the server owns tag ids and renames rows (`services/sync/memo-tag-sync.ts`). Tag normalisation (trim, collapse spaces, lower-case) is now identical on both sides |
|
||||
| MEM-09 | Knowledge base / RAG add+index | [x] | [x] | [x] | [x] | Desktop local RAG (DEF-008 infinite chunking loop resolved, RT-08 verified); web/mobile cloud RAG **Sync (2026-09-27):** desktop documents mirror `knowledge_documents` + `knowledge_chunks` as source text; each surface embeds with its own model (desktop nomic 768-d, server 1536-d), the server index is requested through `embed-chunks`. Documents synced from the phone are stored without a file and re-indexed from their stored chunks (`RAGService.applyRemoteDocument`). Chunk text is now kept even when local embedding fails |
|
||||
| MEM-09 | Knowledge base / RAG add+index | [x] | [x] | [x] | [x] | Desktop local RAG (DEF-008 infinite chunking loop resolved, RT-08 verified); web/mobile cloud RAG |
|
||||
| MEM-10 | Semantic search over knowledge | [x] | [x] | [x] | [x] | Web `KnowledgeSearch` calls `search-knowledge` (was mislabeled deferred); mobile + Edge `search-knowledge` |
|
||||
| MEM-11 | Knowledge file upload | [x] | [x] | [x] | [x] | Web `.txt`/`.md` picker + newline-aware chunking + `embed-chunks`; desktop txt/md/pdf/docx; mobile file picker **Sync (2026-09-27):** desktop documents mirror `knowledge_documents` + `knowledge_chunks` as source text; each surface embeds with its own model (desktop nomic 768-d, server 1536-d), the server index is requested through `embed-chunks`. Documents synced from the phone are stored without a file and re-indexed from their stored chunks (`RAGService.applyRemoteDocument`). Chunk text is now kept even when local embedding fails |
|
||||
| MEM-11 | Knowledge file upload | [x] | [x] | [x] | [x] | Web `.txt`/`.md` picker + newline-aware chunking + `embed-chunks`; desktop txt/md/pdf/docx; mobile file picker |
|
||||
| MEM-12 | Voice actions (OS automation) | [x] | [x] | [x] | [x] | Desktop `VoiceActionService`; web `ActionRunner` (simulated); mobile `ActionsScreen` |
|
||||
| MEM-13 | Cross-surface data sync | [~] | [x] | [x] | [x] | **Desktop rewritten 2026-09-27** (`services/sync/SyncEngine.ts`): persistent outbox (offline/restart safe), server-clock keyset cursors per user DB with pagination, pending local edits never overwritten by pull, deletions both ways through `sync_tombstones`, per-row failure isolation, Realtime that actually connects (`ws` transport). Covers history (+title/favorite), dictionary, meetings, meeting memos/documents, memo tags, custom commands, dictation + meeting-doc templates; plus device registration. Evidence: `apps/desktop/tests/main/sync/SyncEngine.test.ts` (20) + `apps/desktop/tests/integration/cross-device-sync.supabase.test.ts` (5, local Supabase stack). `[~]` until migration `20260927000034` is deployed to production and a desktop build is exercised against a phone (GAP-SYNC-05); knowledge/audio/settings still local (GAP-SYNC-06) **2026-09-27 second batch:** knowledge base, recordings (upload + remote playback) and the mobile `user_settings` fields that mean the same thing on both sides (ko/en locale, system/light/dark theme, auto-polish on/off, active user command) now sync too; remote setting changes reach the open window (`app:dataChanged`, `config:changed`). Production DB is at migration `0035` and all Edge Functions are redeployed from the repo |
|
||||
| MEM-13 | Cross-surface data sync | [~] | [x] | [x] | [x] | **Desktop rewritten 2026-09-27** (`services/sync/SyncEngine.ts`): persistent outbox (offline/restart safe), server-clock keyset cursors per user DB with pagination, pending local edits never overwritten by pull, deletions both ways through `sync_tombstones`, per-row failure isolation, Realtime that actually connects (`ws` transport). Covers history (+title/favorite), dictionary, meetings, meeting memos/documents, memo tags, custom commands, dictation + meeting-doc templates; plus device registration. Evidence: `apps/desktop/tests/main/sync/SyncEngine.test.ts` (20) + `apps/desktop/tests/integration/cross-device-sync.supabase.test.ts` (5, local Supabase stack). `[~]` until migration `20260927000034` is deployed to production and a desktop build is exercised against a phone (GAP-SYNC-05); knowledge/audio/settings still local (GAP-SYNC-06) |
|
||||
| MEM-14 | Memo tag search | [x] | [ ] | [x] | [x] | |
|
||||
|
||||
---
|
||||
|
|
|
|||
|
|
@ -96,11 +96,10 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res
|
|||
| GAP-SYNC-02 | Sync | **Desktop Realtime never connected.** Electron 33 main (Node 20.18) has no global `WebSocket`; supabase-js Realtime only ever logged `TIMED_OUT`/`CLOSED` (installed-app log 2026-09-16) and gave up after three retries. Also: filtered `postgres_changes` channels never deliver DELETE (Supabase limitation). | `CloudSyncService.ts`, `services/sync/realtime-transport.ts`, integration test "Realtime" case | `[x]` 2026-09-27: `ws` injected as the Realtime transport (`ws` now a declared desktop dependency, externalised in the main bundle); deletions arrive as `sync_tombstones` INSERT events; the heartbeat re-subscribes a channel that is not `joined`. Verified live against the local stack (INSERT/UPDATE + tombstone events received). |
|
||||
| GAP-SYNC-03 | Portability | Mobile/cloud data export failed for any account with meetings or generated documents: `export_account_portability` used `to_jsonb(row)` while the v1 archive contract (server restore + mobile `exactKeys`) is a frozen key set, and later migrations added columns. | `server/supabase/migrations/20260927000034_cross_device_sync_parity.sql` §7 | `[x]` 2026-09-27: export projects each dataset onto its v1 keys; integration test asserts the memo/meeting key sets. |
|
||||
| GAP-SYNC-04 | Mobile devices | Mobile `normalizeRegisteredDevice` rejected every platform except `android`/`ios`, so the first desktop/web device on an account would have made the whole Devices screen fail to load. | `apps/mobile-rn/src/features/devices/device-service.ts`, `screens/DevicesScreen.tsx` | `[x]` 2026-09-27: accepts the server platform list (`android/ios/web/windows/macos`), card shows the platform; `__tests__/devices.test.ts` 3/3, full mobile Jest 372/372. |
|
||||
| GAP-SYNC-05 | Sync | **Not yet in production.** Migration `20260927000034` is applied only to the local stack; the rewritten desktop sync ships with the next desktop release. Until the migration is deployed, desktop tombstone pulls and template RPCs fail against production (they are isolated per step, other entities keep syncing). | migration file, `apps/desktop/src/main/services/sync/` | `[~]` 2026-09-27: production `supabase db push` applied `0029`–`0035` (backup dump taken first; see GAP-OPS-01), all 23 Edge Functions redeployed, v1.7.0 published (runtime/portable first, then the updater feed) and installed on the owner PC. **Remaining:** the desktop on that PC is in local mode — one Google sign-in in Settings > Cloud, then edit/delete on the phone and confirm the desktop updates within seconds and appears under Devices. |
|
||||
| GAP-SYNC-06 | Sync | Still desktop-local (not mirrored): knowledge base (desktop local RAG embeddings vs cloud pgvector — different embedding spaces), audio (desktop WAV files vs mobile Storage uploads), `user_settings` (locale, auto-polish, active command), desktop preset-command prompt edits, meeting `transcripts` segments (desktop uses `raw_transcript`, which mobile also fills). | `docs/map/10-feature-catalog.md` MEM-09/MEM-05/SHELL rows | `[x]` 2026-09-27: knowledge docs sync as source text and are re-embedded per surface; recordings upload to the mobile storage contract (≤50 MiB per file, opt-out toggle) and remote recordings play through signed URLs; `user_settings` maps the shared fields. Deliberately not synced (see §7.x): meeting `transcripts` segments (mobile renders `raw_transcript`/`edited_transcript`, which the desktop fills) and desktop preset-command prompt edits (server presets are immutable by RLS). Evidence: `tests/main/sync/SyncExtensions.test.ts` (9) + integration case "지식 문서·설정·녹음" against the local Supabase stack. |
|
||||
| GAP-SYNC-07 | Sync | `sync_tombstones` grows without a schedule. `prune_sync_tombstones_v1(interval)` (service_role) exists; nothing calls it. | migration §1 | `[x]` 2026-09-27: migration `0035` enables `pg_cron` and schedules `prune-sync-tombstones` daily at 03:17 UTC (production `cron.job` active=true). A client whose cursor is older than 180 days must fall back to a full resync. |
|
||||
| GAP-SYNC-05 | Sync | **Not yet in production.** Migration `20260927000034` is applied only to the local stack; the rewritten desktop sync ships with the next desktop release. Until the migration is deployed, desktop tombstone pulls and template RPCs fail against production (they are isolated per step, other entities keep syncing). | migration file, `apps/desktop/src/main/services/sync/` | `[ ]` Deploy the migration (`supabase db push` against the production project) **before** publishing a desktop build that contains this engine; then run a GUI pass: sign in on desktop, edit/delete on the phone, confirm desktop updates within seconds and the phone lists the desktop under Devices. |
|
||||
| GAP-SYNC-06 | Sync | Still desktop-local (not mirrored): knowledge base (desktop local RAG embeddings vs cloud pgvector — different embedding spaces), audio (desktop WAV files vs mobile Storage uploads), `user_settings` (locale, auto-polish, active command), desktop preset-command prompt edits, meeting `transcripts` segments (desktop uses `raw_transcript`, which mobile also fills). | `docs/map/10-feature-catalog.md` MEM-09/MEM-05/SHELL rows | `[ ]` Decide per item: knowledge docs could sync as source text and be re-embedded per surface; audio needs a size/quota policy before upload. |
|
||||
| GAP-SYNC-07 | Sync | `sync_tombstones` grows without a schedule. `prune_sync_tombstones_v1(interval)` (service_role) exists; nothing calls it. | migration §1 | `[ ]` Call it from an existing cron (e.g. the Forgejo scheduled workflow) with the 180-day default. A client whose cursor is older than the retention must fall back to a full resync. |
|
||||
|
||||
| GAP-OPS-01 | Ops | **Production Supabase was five migrations behind** (`0029` content reporting, `0030` profile column ACL — users could raise their own `role`/`tier` through PostgREST, `0031` audit-log actor unlink, `0032` meeting-document reporting, `0033` team activity feed) and `content-report` was never deployed, while the map listed those features GREEN from local runs. Most functions still ran the 2026-08-21 build. | `server/supabase/migrations/`, Management API `schema_migrations`, `functions` list | `[x]` 2026-09-27: schema+data dump taken, `db push` applied `0029`–`0035`, all functions redeployed (unauthenticated calls return 401, i.e. live and gated); `authenticated` can no longer UPDATE `profiles.tier`; real-account export returns exactly the v1 keys. Next: add a CI check that compares `supabase migration list --linked` with the repo so production cannot silently lag again. |
|
||||
---
|
||||
|
||||
## 2. Mobile checklist roll-up (from `MOBILE_APP_COMPLETION_SSOT.md` §4)
|
||||
|
|
@ -218,10 +217,6 @@ Actionable checklist for the work started this session. Fields to fill are blank
|
|||
- **원격 삭제가 로컬 미전송 수정보다 우선한다.** 다른 기기에서 지운 행은 데스크톱에서 편집 중이었어도 지워진다.
|
||||
- **업그레이드 후 첫 동기화는 예전 삭제를 되살릴 수 있다.** 이 버전 이전에는 삭제 기록이 없었으므로, 데스크톱에만 남아 있던 행(모바일에서 지웠지만 데스크톱이 몰랐던 행)은 첫 대조에서 서버로 다시 올라간다. 데이터 유실보다 되살림을 택했다.
|
||||
- **데스크톱 사용 횟수(`dictionary.usage_count`)는 자주 바뀌어 매번 올리지 않는다.** 단어를 추가·수정할 때 함께 올라간다.
|
||||
- **회의 `transcripts` 세그먼트는 동기화하지 않는다.** 모바일은 회의 본문을 `raw_transcript`/`edited_transcript`로 그리고, 데스크톱은 이 두 컬럼을 채운다.
|
||||
- **데스크톱 프리셋 명령의 프롬프트 수정은 기기 로컬이다.** 서버 프리셋(`builtin_key`)은 RLS상 클라이언트가 고칠 수 없고 두 프리셋 목록도 다르다. 사용자가 만든 명령만 동기화한다.
|
||||
- **설정은 뜻이 같은 것만 맞춘다.** 언어는 모바일이 지원하는 ko/en, 테마는 시스템/라이트/다크만(데스크톱 전용 테마는 로컬), 자동 다듬기는 켬/끔, 활성 명령은 양쪽에 있는 사용자 명령일 때만. 서버에 설정 행이 이미 있으면 첫 동기화에서 서버 값이 이긴다.
|
||||
- **지식 문서는 원문만 옮긴다.** 기기마다 임베딩 모델·차원이 달라(데스크톱 768, 서버 1536) 벡터는 각자 만든다. 다른 기기에서 온 문서에는 원본 파일이 없다.
|
||||
|
||||
여기 있는 항목은 고쳐야 할 갭이 아니라 **대안을 검토한 뒤 의도적으로 유지하기로 한 절충**이다.
|
||||
§1 에 갭으로 재등록하지 마라.
|
||||
|
|
|
|||
|
|
@ -175,7 +175,7 @@
|
|||
- [ ] D-001 `user_settings`, `devices`, `audio_files`, `processing_jobs` 스키마·RLS·Realtime 확정
|
||||
- [ ] D-002 모바일 기기 등록, last seen, push token, 앱 버전 갱신
|
||||
- [~] D-003 연결 기기 목록·현재 기기 표시·원격 연결 해제 — 2026-09-27: 데스크톱도 `windows`/`macos` 기기로 등록되고 모바일 목록이 이를 파싱·표시(이전엔 비모바일 플랫폼 한 행이 화면 전체 로드를 실패시킴), 모바일 해제 시 데스크톱 로그아웃. 로컬 Supabase 통합 테스트 GREEN, 운영 배포·기기 실측 대기(`docs/map/11` GAP-SYNC-04/05)
|
||||
- [~] D-004 데스크톱/Web에서 생성한 history/meeting/document/dictionary/knowledge/team 데이터 조회 — 2026-09-27: 데스크톱 history(제목·즐겨찾기)·사전·회의·메모·문서·메모 태그·명령·템플릿이 서버로 올라가 모바일에서 조회됨(로컬 스택 통합 테스트). knowledge 원문·녹음(audio_files)·공통 설정도 2026-09-27 두 번째 묶음에서 동기화, 운영 반영 완료(0035)
|
||||
- [~] D-004 데스크톱/Web에서 생성한 history/meeting/document/dictionary/knowledge/team 데이터 조회 — 2026-09-27: 데스크톱 history(제목·즐겨찾기)·사전·회의·메모·문서·메모 태그·명령·템플릿이 서버로 올라가 모바일에서 조회됨(로컬 스택 통합 테스트). knowledge는 미동기화(GAP-SYNC-06)
|
||||
- [~] D-005 모바일 변경을 데스크톱/Web에 Realtime 또는 재조회로 반영 — 2026-09-27: 데스크톱 Realtime 복구(`ws` 전송) + 삭제 기록(`sync_tombstones`) + 5분 주기 재조회, 반영 즉시 화면 새로고침. 로컬 스택에서 생성·수정·삭제 수신 확인, 운영 배포 대기
|
||||
- [ ] D-006 최근 데이터 암호화 캐시와 로그인 사용자별 격리
|
||||
- [ ] D-007 오프라인 생성·편집 queue, 재시도 backoff, 앱 재시작 복구
|
||||
|
|
|
|||
20
package-lock.json
generated
20
package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "d3ro-voice-monorepo",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "d3ro-voice-monorepo",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"apps/desktop",
|
||||
|
|
@ -25,7 +25,7 @@
|
|||
},
|
||||
"apps/admin": {
|
||||
"name": "@d3ro/admin",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"dependencies": {
|
||||
"@d3ro/api-client": "*",
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -109,7 +109,7 @@
|
|||
},
|
||||
"apps/desktop": {
|
||||
"name": "@d3ro/desktop",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -161,7 +161,7 @@
|
|||
},
|
||||
"apps/web": {
|
||||
"name": "@d3ro/web",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"dependencies": {
|
||||
"@d3ro/api-client": "*",
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -17216,7 +17216,7 @@
|
|||
},
|
||||
"packages/api-client": {
|
||||
"name": "@d3ro/api-client",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -17233,7 +17233,7 @@
|
|||
},
|
||||
"packages/core": {
|
||||
"name": "@d3ro/core",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"docx": "^9.6.1"
|
||||
|
|
@ -17244,7 +17244,7 @@
|
|||
},
|
||||
"packages/i18n": {
|
||||
"name": "@d3ro/i18n",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.0.0"
|
||||
|
|
@ -17255,7 +17255,7 @@
|
|||
},
|
||||
"packages/ui": {
|
||||
"name": "@d3ro/ui",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@d3ro/core": "*"
|
||||
|
|
@ -17275,7 +17275,7 @@
|
|||
},
|
||||
"packages/ui-native": {
|
||||
"name": "@d3ro/ui-native",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/react": "*"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "d3ro-voice-monorepo",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice — 멀티플랫폼 AI 음성 어시스턴트 (Monorepo)",
|
||||
"author": "D3RO",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/api-client",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice API 클라이언트 — Supabase 래퍼 (web/desktop/mobile 공유)",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/core",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice 공유 비즈니스 로직 — 타입, 에러, IPC 채널, 상수, 유틸",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -146,8 +146,6 @@ export const IPC_CHANNELS = {
|
|||
DELETE: 'history:delete',
|
||||
DELETE_ALL: 'history:deleteAll',
|
||||
SET_FAVORITE: 'history:setFavorite',
|
||||
/** 녹음 재생 소스: 로컬 파일 바이트 또는 다른 기기 녹음의 서명 URL */
|
||||
GET_AUDIO: 'history:getAudio',
|
||||
SEARCH: 'history:search',
|
||||
EXPORT: 'history:export',
|
||||
// Main → Renderer events
|
||||
|
|
|
|||
|
|
@ -485,8 +485,6 @@ export interface AppConfig {
|
|||
* 원격 해제된 id는 재사용할 수 없어(서버 규칙) 재로그인 때 새로 발급한다.
|
||||
*/
|
||||
deviceInstallationId: string | null
|
||||
/** 로그인 시 녹음 파일도 클라우드에 올려 모바일·웹에서 재생 (파일당 50MiB 이하) */
|
||||
cloudSyncAudio: boolean
|
||||
/** 빅뱅 Phase 2: 첫 실행 온보딩 완료 여부 (로컬 모드 entry point) */
|
||||
onboardingCompleted: boolean
|
||||
/** Phase 6: Custom instructions (CustomInstructionService) */
|
||||
|
|
@ -662,11 +660,6 @@ export interface HistorySetFavoriteParams {
|
|||
isFavorite: boolean
|
||||
}
|
||||
|
||||
/** 녹음 재생 소스. 이 기기에서 녹음했으면 파일 바이트, 모바일·웹 녹음이면 5분짜리 서명 URL */
|
||||
export type HistoryAudioSource =
|
||||
| { kind: 'local'; bytes: Uint8Array; mimeType: string }
|
||||
| { kind: 'remote'; url: string }
|
||||
|
||||
export interface HistorySearchParams {
|
||||
query: string
|
||||
page: number
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/i18n",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice 공유 i18n — 12개 locale, 타입 안전 키, Context, 포맷 유틸",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "Schließe die Anmeldung im Browser ab.",
|
||||
"cloudSync.signedOut": "Abgemeldet. Die Einträge auf diesem Computer bleiben erhalten.",
|
||||
"cloudSync.done": "Synchronisierung abgeschlossen ({{count}} übernommen)",
|
||||
"cloudSync.doneWithErrors": "Synchronisierung abgeschlossen ({{count}} übernommen, {{errors}} fehlgeschlagen – nächster Lauf versucht es erneut)",
|
||||
"history.playAudio": "Aufnahme abspielen",
|
||||
"history.stopAudio": "Wiedergabe stoppen",
|
||||
"history.audioUnavailable": "Keine Aufnahme zum Abspielen (Aufnahmen anderer Geräte erst nach deren Synchronisierung)",
|
||||
"cloudSync.audio": "Aufnahmen ebenfalls synchronisieren",
|
||||
"cloudSync.audioDesc": "Lädt Aufnahmen hoch, damit Handy und Web sie abspielen können. Dateien über 50 MB bleiben auf diesem Computer."
|
||||
"cloudSync.doneWithErrors": "Synchronisierung abgeschlossen ({{count}} übernommen, {{errors}} fehlgeschlagen – nächster Lauf versucht es erneut)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1927,10 +1927,5 @@
|
|||
"mobile.devices.platform.ios": "iPhone / iPad",
|
||||
"mobile.devices.platform.web": "Web browser",
|
||||
"mobile.devices.platform.windows": "Windows desktop app",
|
||||
"mobile.devices.platform.macos": "macOS desktop app",
|
||||
"history.playAudio": "Play recording",
|
||||
"history.stopAudio": "Stop playback",
|
||||
"history.audioUnavailable": "No recording to play (recordings from another device play once that device has synced)",
|
||||
"cloudSync.audio": "Sync recordings too",
|
||||
"cloudSync.audioDesc": "Uploads recordings so the phone and web can play them. Files over 50 MB stay on this computer."
|
||||
"mobile.devices.platform.macos": "macOS desktop app"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "Termina de iniciar sesión en el navegador.",
|
||||
"cloudSync.signedOut": "Sesión cerrada. Los registros de este equipo se conservan.",
|
||||
"cloudSync.done": "Sincronización completa ({{count}} aplicados)",
|
||||
"cloudSync.doneWithErrors": "Sincronización completa ({{count}} aplicados, {{errors}} fallidos: se reintentan en la próxima)",
|
||||
"history.playAudio": "Reproducir grabación",
|
||||
"history.stopAudio": "Detener",
|
||||
"history.audioUnavailable": "No hay grabación para reproducir (las de otro dispositivo se reproducen cuando ese dispositivo sincroniza)",
|
||||
"cloudSync.audio": "Sincronizar también las grabaciones",
|
||||
"cloudSync.audioDesc": "Sube las grabaciones para reproducirlas en el móvil y la web. Los archivos de más de 50 MB se quedan en este equipo."
|
||||
"cloudSync.doneWithErrors": "Sincronización completa ({{count}} aplicados, {{errors}} fallidos: se reintentan en la próxima)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "Terminez la connexion dans votre navigateur.",
|
||||
"cloudSync.signedOut": "Déconnecté. Les enregistrements de cet ordinateur sont conservés.",
|
||||
"cloudSync.done": "Synchronisation terminée ({{count}} appliqués)",
|
||||
"cloudSync.doneWithErrors": "Synchronisation terminée ({{count}} appliqués, {{errors}} en échec — réessayés à la prochaine)",
|
||||
"history.playAudio": "Écouter l'enregistrement",
|
||||
"history.stopAudio": "Arrêter la lecture",
|
||||
"history.audioUnavailable": "Aucun enregistrement à lire (ceux d'un autre appareil sont disponibles après sa synchronisation)",
|
||||
"cloudSync.audio": "Synchroniser aussi les enregistrements",
|
||||
"cloudSync.audioDesc": "Envoie les enregistrements pour les écouter sur mobile et sur le web. Les fichiers de plus de 50 Mo restent sur cet ordinateur."
|
||||
"cloudSync.doneWithErrors": "Synchronisation terminée ({{count}} appliqués, {{errors}} en échec — réessayés à la prochaine)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "ブラウザでログインを完了してください。",
|
||||
"cloudSync.signedOut": "ログアウトしました。このコンピューターの記録はそのまま残ります。",
|
||||
"cloudSync.done": "同期完了({{count}} 件反映)",
|
||||
"cloudSync.doneWithErrors": "同期完了({{count}} 件反映、{{errors}} 件失敗 — 次回の同期で再試行)",
|
||||
"history.playAudio": "録音を再生",
|
||||
"history.stopAudio": "再生を停止",
|
||||
"history.audioUnavailable": "再生できる録音がありません(他の端末の録音は、その端末の同期後に再生できます)",
|
||||
"cloudSync.audio": "録音ファイルも同期",
|
||||
"cloudSync.audioDesc": "録音をクラウドにアップロードし、モバイルやウェブで再生できるようにします。50MBを超えるファイルはこのコンピューターにのみ保存されます。"
|
||||
"cloudSync.doneWithErrors": "同期完了({{count}} 件反映、{{errors}} 件失敗 — 次回の同期で再試行)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1934,10 +1934,5 @@
|
|||
"mobile.devices.platform.ios": "iPhone·iPad",
|
||||
"mobile.devices.platform.web": "웹 브라우저",
|
||||
"mobile.devices.platform.windows": "Windows 데스크톱 앱",
|
||||
"mobile.devices.platform.macos": "macOS 데스크톱 앱",
|
||||
"history.playAudio": "녹음 듣기",
|
||||
"history.stopAudio": "재생 멈춤",
|
||||
"history.audioUnavailable": "들을 수 있는 녹음이 없습니다 (다른 기기 녹음은 그 기기의 동기화가 끝나면 들을 수 있어요)",
|
||||
"cloudSync.audio": "녹음 파일도 동기화",
|
||||
"cloudSync.audioDesc": "녹음을 클라우드에 올려 모바일·웹에서 들을 수 있게 합니다. 50MB를 넘는 파일은 이 컴퓨터에만 둡니다."
|
||||
"mobile.devices.platform.macos": "macOS 데스크톱 앱"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "Conclua o login no navegador.",
|
||||
"cloudSync.signedOut": "Você saiu. Os registros deste computador continuam aqui.",
|
||||
"cloudSync.done": "Sincronização concluída ({{count}} aplicados)",
|
||||
"cloudSync.doneWithErrors": "Sincronização concluída ({{count}} aplicados, {{errors}} com falha — tentados de novo na próxima)",
|
||||
"history.playAudio": "Ouvir gravação",
|
||||
"history.stopAudio": "Parar",
|
||||
"history.audioUnavailable": "Nenhuma gravação para ouvir (as de outro dispositivo tocam depois que ele sincroniza)",
|
||||
"cloudSync.audio": "Sincronizar também as gravações",
|
||||
"cloudSync.audioDesc": "Envia as gravações para ouvir no celular e na web. Arquivos acima de 50 MB ficam neste computador."
|
||||
"cloudSync.doneWithErrors": "Sincronização concluída ({{count}} aplicados, {{errors}} com falha — tentados de novo na próxima)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "Завершите вход в браузере.",
|
||||
"cloudSync.signedOut": "Вы вышли. Записи на этом компьютере сохранены.",
|
||||
"cloudSync.done": "Синхронизация завершена (применено: {{count}})",
|
||||
"cloudSync.doneWithErrors": "Синхронизация завершена (применено: {{count}}, ошибок: {{errors}} — повтор при следующей синхронизации)",
|
||||
"history.playAudio": "Прослушать запись",
|
||||
"history.stopAudio": "Остановить",
|
||||
"history.audioUnavailable": "Нет записи для воспроизведения (записи с другого устройства доступны после его синхронизации)",
|
||||
"cloudSync.audio": "Синхронизировать и записи",
|
||||
"cloudSync.audioDesc": "Загружает записи, чтобы их можно было слушать на телефоне и в вебе. Файлы больше 50 МБ остаются на этом компьютере."
|
||||
"cloudSync.doneWithErrors": "Синхронизация завершена (применено: {{count}}, ошибок: {{errors}} — повтор при следующей синхронизации)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "โปรดเข้าสู่ระบบให้เสร็จในเบราว์เซอร์",
|
||||
"cloudSync.signedOut": "ออกจากระบบแล้ว ข้อมูลบนคอมพิวเตอร์นี้ยังอยู่ครบ",
|
||||
"cloudSync.done": "ซิงก์เสร็จแล้ว ({{count}} รายการ)",
|
||||
"cloudSync.doneWithErrors": "ซิงก์เสร็จแล้ว ({{count}} รายการ, ล้มเหลว {{errors}} — จะลองใหม่รอบหน้า)",
|
||||
"history.playAudio": "เล่นเสียงที่บันทึก",
|
||||
"history.stopAudio": "หยุดเล่น",
|
||||
"history.audioUnavailable": "ไม่มีเสียงให้เล่น (เสียงจากอุปกรณ์อื่นจะเล่นได้หลังอุปกรณ์นั้นซิงก์)",
|
||||
"cloudSync.audio": "ซิงก์ไฟล์เสียงด้วย",
|
||||
"cloudSync.audioDesc": "อัปโหลดไฟล์เสียงเพื่อเล่นบนมือถือและเว็บ ไฟล์ที่ใหญ่กว่า 50MB จะเก็บไว้ในเครื่องนี้เท่านั้น"
|
||||
"cloudSync.doneWithErrors": "ซิงก์เสร็จแล้ว ({{count}} รายการ, ล้มเหลว {{errors}} — จะลองใหม่รอบหน้า)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "Hãy hoàn tất đăng nhập trên trình duyệt.",
|
||||
"cloudSync.signedOut": "Đã đăng xuất. Dữ liệu trên máy này vẫn được giữ nguyên.",
|
||||
"cloudSync.done": "Đồng bộ xong (áp dụng {{count}})",
|
||||
"cloudSync.doneWithErrors": "Đồng bộ xong ({{count}} áp dụng, {{errors}} lỗi — sẽ thử lại lần sau)",
|
||||
"history.playAudio": "Phát bản ghi",
|
||||
"history.stopAudio": "Dừng phát",
|
||||
"history.audioUnavailable": "Không có bản ghi để phát (bản ghi từ thiết bị khác phát được sau khi thiết bị đó đồng bộ)",
|
||||
"cloudSync.audio": "Đồng bộ cả bản ghi âm",
|
||||
"cloudSync.audioDesc": "Tải bản ghi lên để nghe trên điện thoại và web. Tệp lớn hơn 50MB chỉ lưu trên máy này."
|
||||
"cloudSync.doneWithErrors": "Đồng bộ xong ({{count}} áp dụng, {{errors}} lỗi — sẽ thử lại lần sau)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "請在瀏覽器中完成登入。",
|
||||
"cloudSync.signedOut": "已登出。這台電腦上的紀錄會保留。",
|
||||
"cloudSync.done": "同步完成(已套用 {{count}} 項)",
|
||||
"cloudSync.doneWithErrors": "同步完成(已套用 {{count}} 項,{{errors}} 項失敗 — 下次同步時重試)",
|
||||
"history.playAudio": "播放錄音",
|
||||
"history.stopAudio": "停止播放",
|
||||
"history.audioUnavailable": "沒有可播放的錄音(其他裝置的錄音需在該裝置同步後才能播放)",
|
||||
"cloudSync.audio": "同時同步錄音",
|
||||
"cloudSync.audioDesc": "將錄音上傳到雲端,讓手機和網頁也能播放。超過 50MB 的檔案只保留在本機。"
|
||||
"cloudSync.doneWithErrors": "同步完成(已套用 {{count}} 項,{{errors}} 項失敗 — 下次同步時重試)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -541,10 +541,5 @@
|
|||
"cloudSync.browserPending": "请在浏览器中完成登录。",
|
||||
"cloudSync.signedOut": "已退出登录。本机上的记录会保留。",
|
||||
"cloudSync.done": "同步完成(已应用 {{count}} 项)",
|
||||
"cloudSync.doneWithErrors": "同步完成(已应用 {{count}} 项,{{errors}} 项失败 — 下次同步时重试)",
|
||||
"history.playAudio": "播放录音",
|
||||
"history.stopAudio": "停止播放",
|
||||
"history.audioUnavailable": "没有可播放的录音(其他设备的录音需在该设备同步后才能播放)",
|
||||
"cloudSync.audio": "同时同步录音",
|
||||
"cloudSync.audioDesc": "将录音上传到云端,以便在手机和网页上播放。超过 50MB 的文件只保留在本机。"
|
||||
"cloudSync.doneWithErrors": "同步完成(已应用 {{count}} 项,{{errors}} 项失败 — 下次同步时重试)"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/ui-native",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice React Native DS — MetalCard/PhosphorText/Led/WaveBars etc.",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/ui",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice 공유 UI — 디자인 시스템 컴포넌트 + 테마 토큰 + CSS 변수 맵",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"version": "1.8.0",
|
||||
"androidVersionCode": 1080000,
|
||||
"iosBuildNumber": 1080000,
|
||||
"version": "1.7.0",
|
||||
"androidVersionCode": 1070000,
|
||||
"iosBuildNumber": 1070000,
|
||||
"releaseDate": "2026-09-27",
|
||||
"desktopLicensePublicKeyId": "5c52b765135ee2531c681b53cd4dc0e96fff8737f496c0b04ba8334fc81a887f"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,55 +0,0 @@
|
|||
-- Knowledge base joins the cross-device mirror; tombstones get a retention job.
|
||||
--
|
||||
-- 1. knowledge_documents deletions leave a tombstone like the other synced
|
||||
-- tables, and a (user_id, updated_at, id) cursor index backs keyset pulls.
|
||||
-- Chunks are re-read with their document, so they need neither.
|
||||
-- 2. pg_cron prunes tombstones daily with the 180-day default of
|
||||
-- prune_sync_tombstones_v1 (a device offline longer than that resyncs fully).
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- 1) knowledge_documents ---------------------------------------------------------
|
||||
ALTER TABLE public.sync_tombstones DROP CONSTRAINT IF EXISTS sync_tombstones_table_name_check;
|
||||
ALTER TABLE public.sync_tombstones
|
||||
ADD CONSTRAINT sync_tombstones_table_name_check CHECK (table_name IN (
|
||||
'history',
|
||||
'dictionary',
|
||||
'meetings',
|
||||
'meeting_memos',
|
||||
'meeting_documents',
|
||||
'memo_tags',
|
||||
'custom_instructions',
|
||||
'user_templates',
|
||||
'knowledge_documents'
|
||||
));
|
||||
|
||||
DROP TRIGGER IF EXISTS record_sync_tombstone_v1 ON public.knowledge_documents;
|
||||
CREATE TRIGGER record_sync_tombstone_v1
|
||||
AFTER DELETE ON public.knowledge_documents
|
||||
FOR EACH ROW EXECUTE FUNCTION public.record_sync_tombstone_v1();
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_knowledge_documents_sync_cursor
|
||||
ON public.knowledge_documents(user_id, updated_at, id);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_publication_tables
|
||||
WHERE pubname = 'supabase_realtime' AND schemaname = 'public' AND tablename = 'knowledge_documents'
|
||||
) THEN
|
||||
ALTER PUBLICATION supabase_realtime ADD TABLE public.knowledge_documents;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- 2) Tombstone retention ---------------------------------------------------------
|
||||
-- Outside the transaction: extension creation and cron scheduling are
|
||||
-- idempotent, and cron.schedule with an existing job name replaces it.
|
||||
CREATE EXTENSION IF NOT EXISTS pg_cron WITH SCHEMA pg_catalog;
|
||||
|
||||
SELECT cron.schedule(
|
||||
'prune-sync-tombstones',
|
||||
'17 3 * * *',
|
||||
$$SELECT public.prune_sync_tombstones_v1()$$
|
||||
);
|
||||
4
site/package-lock.json
generated
4
site/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "d3ro-voice-site",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "d3ro-voice-site",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"dependencies": {
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "d3ro-voice-site",
|
||||
"private": true,
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --port 5199 --host",
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
// NAS 배포는 바이너리를 포함하지 않으므로 `/releases/...` 같은 로컬 경로는
|
||||
// 실제 배포 환경에서 404가 된다.
|
||||
|
||||
export const DESKTOP_VERSION = '1.8.0'
|
||||
export const DESKTOP_VERSION = '1.7.0'
|
||||
|
||||
/** 릴리스 게시일. `release/product-version.json`의 releaseDate와 같아야 한다. */
|
||||
export const DESKTOP_RELEASE_DATE = '2026-09-27'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue