feat(V2-1a): Monorepo 구조 전환 — apps/desktop으로 V1 이동

- npm workspaces 루트 (apps/*, packages/*) 세팅
- V1 전체를 apps/desktop/으로 git mv (src, resources, tests, sidecar,
  scripts, electron.vite.config.ts, electron-builder.yml, vitest.config.ts,
  tsconfig.node.json, tsconfig.web.json)
- apps/desktop/package.json 신규 (name=@d3ro/desktop)
- productName: 'd3ro-voice' 명시 — app.getName()을 고정하여 userData 경로
  %APPDATA%\d3ro-voice\ 그대로 유지 (기존 DB/설정 연속성 보장)
- 루트 package.json을 workspace 루트로 재구성, 공통 devDep만 유지
  (typescript, eslint, prettier)
- turbo.json, tsconfig.base.json 추가 (Turborepo 자체 설치는 별도 sub-phase)
- memory/project_status.md 생성 (규칙 13)

검증:
- npm run typecheck 통과
- npm run build 통과 (electron-vite main+preload+renderer)
- npm run dev 실제 실행 → DB/핫키/Ollama 자동 실행 모두 정상
This commit is contained in:
yunchan8804 2026-04-08 14:04:41 +09:00
parent 3a160b9032
commit 45a580878a
178 changed files with 214 additions and 0 deletions

View file

@ -0,0 +1,259 @@
// src/main/services/ChainService.ts
// Phase 10.4: Multi-LLM Chain 서비스.
// LLMChain을 electron-store에 저장하고, 체인을 순차 실행한다.
import { nanoid } from 'nanoid'
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 '@shared/ipc-channels'
import { D3ROError, ErrorCode } from '@shared/errors'
import type {
LLMChain,
ChainStep,
CreateChainParams,
UpdateChainParams,
ChainProgress,
ChainExecutionResult
} from '@shared/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: nanoid(),
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
}