d3ro-voice/apps/desktop/src/main/services/ChainService.ts
윤찬 e55687d298 fix(desktop+supabase): 로컬 ID UUID 통일 + Realtime publication (빅뱅 Phase 5 Part 2)
SaaS [9] — 실증 A/B/C/D 전부 통과, 로컬→클라우드 push 최초 성공(pushed=1).

## Bug 4: 로컬 nanoid PK vs Supabase UUID PK 불일치
- 증상: Push history failed: invalid input syntax for type uuid: "fvy6bIzr..."
- 원인: 로컬 drizzle schema는 text PK + nanoid() 생성, Supabase는 uuid PK.
  빅뱅 사이클 내내 push가 한 번도 성공한 적 없었음 (지난 pushed=0은 데이터 0건이라서).
- 픽스: 로컬을 UUID로 통일 (근본 해결, 땜질 금지).
  14개 서비스 20곳 nanoid() → crypto.randomUUID() 일괄 교체.
  nanoid 의존성 + electron.vite.config exclude 제거.
  drizzle schema는 text PK 그대로 유지 (SQLite는 UUID 문자열 저장 가능).

## Bug 5: supabase_realtime publication 누락
- 증상: 로그인 직후 Realtime 채널 상태: TIMED_OUT
- 원인: initial_schema.sql이 transcripts 테이블만 publication에 추가.
  데스크톱이 구독하는 meetings/history/dictionary는 누락 → postgres_changes 흐르지 않음.
- 픽스: 20260411000002_realtime_publication.sql 신규.
  pg_publication_tables 카탈로그 체크 + 조건부 ADD TABLE (meetings/meeting_memos/
  meeting_documents/history/dictionary 5개). supabase db push 적용.

## Bug 6: persistSession:false에서 realtime.setAuth 자동 전파 안 됨 (부분 픽스)
- 픽스: CloudSyncService.startRealtime()에 client.realtime.setAuth(access_token)
  명시 호출 (채널 구성 이전).
- ⚠️ Bug 5+6 적용 후에도 Realtime 여전히 TIMED_OUT. 후속 조사 필요.
  블로커 아님 — 주기 pull + Phase 3.3 auto push로 최종 일관성 유지.

## 실증 결과
- A 세션 자동 복원: Restored session for yunchan8804@gmail.com → DB 재오픈
- B push 경로: HistoryService created 56a767ac-... → Sync complete pushed=1 errors=0
- C 로그아웃 복귀: Realtime 종료 → users/_local/d3ro.db 복귀 → local mode
- D 재로그인 복원: 실증 A의 restore 경로와 동일, 같은 uuid DB 파일 보존
- E 웹 크로스 디바이스: Phase 3.3 이후로 지연 (Realtime 이슈 별건)

검증: desktop tsc --noEmit , dev 재기동 , push 최초 성공 
2026-04-11 18:46:22 +09:00

258 lines
7.4 KiB
TypeScript

// src/main/services/ChainService.ts
// Phase 10.4: Multi-LLM Chain 서비스.
// LLMChain을 electron-store에 저장하고, 체인을 순차 실행한다.
import { getLogger } from './LoggerService'
import { configGet } from './ConfigService'
import { getCustomInstructionService } from './CustomInstructionService'
import { getLocalLLMService } from './LocalLLMService'
import { getMainWindow } from '../windows/WindowManager'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import type {
LLMChain,
ChainStep,
CreateChainParams,
UpdateChainParams,
ChainProgress,
ChainExecutionResult
} from '@d3ro/core/types'
const logger = getLogger('chain-service')
// ============================================================
// 저장소 (electron-store, CustomInstructionService 패턴)
// ============================================================
let chains: LLMChain[] = []
let initialized = false
function loadChains(): LLMChain[] {
try {
const stored = configGet('llmChains' as never) as LLMChain[] | undefined
if (Array.isArray(stored) && stored.length > 0) {
return stored
}
} catch {
// 첫 실행 시 키가 없을 수 있음
}
return []
}
function saveChains(): void {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { configSet } = require('./ConfigService') as {
configSet: (key: never, value: never) => void
}
configSet('llmChains' as never, chains as never)
} catch (error) {
logger.warn(
`Failed to save chains: ${error instanceof Error ? error.message : String(error)}`
)
}
}
/** 메인 윈도우 렌더러에 IPC 이벤트 전송 */
function sendProgressToRenderer(progress: ChainProgress): void {
const win = getMainWindow()
if (win && !win.isDestroyed()) {
win.webContents.send(IPC_CHANNELS.CHAIN.PROGRESS, progress)
}
}
// ============================================================
// ChainService
// ============================================================
class ChainService {
private _cancelRequested = false
initialize(): void {
if (initialized) return
chains = loadChains()
initialized = true
logger.info(`ChainService initialized (${chains.length} chains)`)
}
getAll(): LLMChain[] {
return [...chains]
}
getById(id: string): LLMChain | null {
return chains.find((c) => c.id === id) ?? null
}
create(params: CreateChainParams): LLMChain {
const now = Date.now()
const chain: LLMChain = {
id: crypto.randomUUID(),
name: params.name,
steps: params.steps,
createdAt: now,
updatedAt: now
}
chains.push(chain)
saveChains()
logger.info(`Chain created: "${chain.name}" (${chain.steps.length} steps)`)
return chain
}
update(params: UpdateChainParams): LLMChain {
const index = chains.findIndex((c) => c.id === params.id)
if (index === -1) {
throw new D3ROError(ErrorCode.ChainNotFound, `Chain not found: ${params.id}`)
}
const existing = chains[index]
const updated: LLMChain = {
...existing,
name: params.name ?? existing.name,
steps: params.steps ?? existing.steps,
updatedAt: Date.now()
}
chains[index] = updated
saveChains()
logger.info(`Chain updated: "${updated.name}"`)
return updated
}
delete(id: string): void {
const index = chains.findIndex((c) => c.id === id)
if (index === -1) {
throw new D3ROError(ErrorCode.ChainNotFound, `Chain not found: ${id}`)
}
const removed = chains.splice(index, 1)[0]
saveChains()
logger.info(`Chain deleted: "${removed.name}"`)
}
/**
* 체인을 순차 실행한다.
* 각 단계마다 CustomInstruction의 프롬프트로 LLM을 호출하고,
* 이전 단계 결과를 다음 단계의 입력으로 전달한다.
*/
async execute(chainId: string, inputText: string): Promise<ChainExecutionResult> {
const chain = this.getById(chainId)
if (!chain) {
throw new D3ROError(ErrorCode.ChainNotFound, `Chain not found: ${chainId}`)
}
if (chain.steps.length === 0) {
throw new D3ROError(ErrorCode.ChainExecutionFailed, 'Chain has no steps')
}
this._cancelRequested = false
const startTime = Date.now()
const stepResults: Array<{ instructionId: string; output: string; durationMs: number }> = []
let previousOutput = inputText
const llm = getLocalLLMService()
const instructionService = getCustomInstructionService()
logger.info(
`Executing chain "${chain.name}" (${chain.steps.length} steps) with input length ${inputText.length}`
)
for (let i = 0; i < chain.steps.length; i++) {
// 취소 확인
if (this._cancelRequested) {
logger.info(`Chain execution cancelled at step ${i + 1}/${chain.steps.length}`)
throw new D3ROError(ErrorCode.ChainCancelled, 'Chain execution cancelled')
}
const step: ChainStep = chain.steps[i]
const instruction = instructionService.getById(step.instructionId)
if (!instruction) {
throw new D3ROError(
ErrorCode.ChainStepFailed,
`Instruction not found for step ${i + 1}: ${step.instructionId}`
)
}
// 입력 소스 결정
const stepInput = step.inputSource === 'original' ? inputText : previousOutput
// 진행 상황 전송
const progress: ChainProgress = {
chainId,
currentStep: i + 1,
totalSteps: chain.steps.length,
stepName: instruction.name,
intermediateText: previousOutput
}
sendProgressToRenderer(progress)
// LLM 호출
const stepStart = Date.now()
try {
const result = await llm.processText(stepInput, 'custom', undefined, instruction.prompt)
const stepDuration = Date.now() - stepStart
stepResults.push({
instructionId: step.instructionId,
output: result,
durationMs: stepDuration
})
previousOutput = result
logger.info(
`Chain step ${i + 1}/${chain.steps.length} ("${instruction.name}") completed in ${stepDuration}ms`
)
} catch (error) {
if (error instanceof D3ROError && error.code === ErrorCode.ChainCancelled) {
throw error
}
const msg =
error instanceof Error ? error.message : String(error)
throw new D3ROError(
ErrorCode.ChainStepFailed,
`Step ${i + 1} ("${instruction.name}") failed: ${msg}`
)
}
}
const totalDuration = Date.now() - startTime
logger.info(`Chain "${chain.name}" completed in ${totalDuration}ms`)
return {
chainId,
finalText: previousOutput,
steps: stepResults,
totalDurationMs: totalDuration
}
}
/**
* 진행 중인 체인 실행을 취소한다.
* 현재 단계가 완료된 후 다음 단계 시작 전에 중단된다.
*/
cancelExecution(): void {
this._cancelRequested = true
// LLM 생성도 취소
getLocalLLMService().cancelGeneration()
logger.info('Chain execution cancel requested')
}
dispose(): void {
this._cancelRequested = true
logger.info('ChainService disposed')
}
}
// ============================================================
// 싱글톤
// ============================================================
let instance: ChainService | null = null
export function getChainService(): ChainService {
if (!instance) {
instance = new ChainService()
}
return instance
}