feat(commands): multi-select ordered command pipeline with step reordering and single-pass composition (AI-05, AI-07)

This commit is contained in:
Yun Chan 2026-10-31 02:54:54 +09:00
parent f49acf0105
commit 10af20a0ad
157 changed files with 29455 additions and 913 deletions

View file

@ -1,11 +1,16 @@
import { describe, it, expect } from 'vitest'
import {
DEFAULT_INSTRUCTION_TARGET_LANGUAGE,
composeInstructionPipelinePrompt,
detectUserSlot,
fillInstructionPlaceholders,
findUnresolvedPlaceholders,
moveInstructionInPipeline,
parseActiveInstructionIds,
renderInstruction,
renderInstructionAsSingleMessage,
serializeActiveInstructionIds,
toggleInstructionInPipeline,
} from '../src/instruction-template'
describe('fillInstructionPlaceholders — 치환값은 문자 그대로 들어간다', () => {
@ -112,3 +117,36 @@ describe('renderInstructionAsSingleMessage', () => {
expect(renderInstructionAsSingleMessage('요약: {{text}}', { text: "a $' b" })).toBe("요약: a $' b")
})
})
describe('다단계 명령 파이프라인 (parseActiveInstructionIds / toggle / move / compose)', () => {
it('콤마 구분 문자열에서 선택 순서를 유지하고 공백·중복을 제거한다', () => {
expect(parseActiveInstructionIds(' builtin-clean-speech , builtin-formal , builtin-clean-speech ')).toEqual([
'builtin-clean-speech',
'builtin-formal',
])
expect(serializeActiveInstructionIds(['builtin-clean-speech', 'builtin-formal'])).toBe(
'builtin-clean-speech,builtin-formal',
)
})
it('토글 및 위·아래 순서 이동이 정확히 동작한다', () => {
const step1 = toggleInstructionInPipeline([], 'builtin-clean-speech')
expect(step1).toEqual(['builtin-clean-speech'])
const step2 = toggleInstructionInPipeline(step1, 'builtin-formal')
expect(step2).toEqual(['builtin-clean-speech', 'builtin-formal'])
const swapped = moveInstructionInPipeline(step2, 'builtin-formal', 'up')
expect(swapped).toEqual(['builtin-formal', 'builtin-clean-speech'])
const removed = toggleInstructionInPipeline(swapped, 'builtin-formal')
expect(removed).toEqual(['builtin-clean-speech'])
})
it('2개 이상 명령은 단계 번호와 후행 단계 우선 규칙이 포함된 단일 파이프라인 프롬프트로 합성한다', () => {
const composed = composeInstructionPipelinePrompt([
{ name: '구어·추임새·중복 정리', prompt: '추임새와 중복을 제거하세요.' },
{ name: '격식체 변환', prompt: '정중한 비즈니스 존댓말(-습니다/-합니다)로 변환하세요.' },
])
expect(composed).toContain('[1단계: 구어·추임새·중복 정리]')
expect(composed).toContain('[2단계: 격식체 변환]')
expect(composed).toContain('뒤쪽(마지막) 단계')
})
})

View file

@ -398,6 +398,16 @@ describe('낱자 잡음 (2026-10-17 실측 입력)', () => {
}
})
it('커서 끝에서 다음 한글 음절을 조합하기 시작한 초성(안ㄴ·안녕ㅎ·한ㄱ·글ㅈ)은 잡음이나 오타로 보지 않는다', () => {
for (const composing of ['안ㄴ', '안녕ㅎ', '한ㄱ', '글ㅈ', '오늘 회의 자ㄹ']) {
expect(detectJamoNoise(composing)).toEqual([])
expect(hasSuspiciousTypo(composing)).toBe(false)
}
// 반면 공백이나 문장부호로 어절이 끝났는데도 자음이 홀로 남았으면 잡음으로 지운다
expect(fixed('안ㄴ ')).toBe('안 ')
expect(fixed('한ㄱ ')).toBe('한 ')
})
it('모델 교정이 같은 단어의 낱자 지우기보다 앞선다', () => {
const text = '안ㄴ뇽하세여.?'
const model = validateModelCorrections(text, [{ from: '안ㄴ뇽하세여', to: '안녕하세요' }])

View file

@ -153,18 +153,12 @@ export function isWordBoundaryKey(keyClass: KeyStrokeClass): boolean {
/**
* 단어 수.
*
* 공백 분리 토큰 중 문자/숫자/CJK 를 포함한 것만 센다.
* (중국어처럼 공백이 없는 언어는 과소 집계된다 — 활동 통계 전용. 학습 필터는
* text-segmentation.ts 의 countLexicalWords 로 센다)
* 공백 분리 언어(한국어·라틴 문자 등)는 공백 분리 토큰 중 문자/숫자를 포함한 것만 세고,
* 띄어쓰기 없이 쓰는 문자 체계(중국어·일본어·태국어 등)는 `countLexicalWords`(Intl.Segmenter
* 또는 글자 수 어림)로 분할해 과소 집계를 방지한다.
*/
export function countWords(text: string): number {
if (!text) return 0
const tokens = text.split(/\s+/)
let count = 0
for (const token of tokens) {
if (/[\p{L}\p{N}]/u.test(token)) count += 1
}
return count
return countLexicalWords(text)
}
/** 문장 수 — 종결 부호 + 개행 기준. */

View file

@ -115,3 +115,101 @@ export function renderInstructionAsSingleMessage(
const { system, user } = renderInstruction(prompt, vars)
return system === undefined ? user : `${system}\n\n${user}`
}
// ============================================================
// 다단계 명령 파이프라인 (Multi-Instruction Pipeline) SSOT
// ============================================================
/**
* 저장된 `activeInstructionId` 문자열(단일 ID 또는 콤마 구분 복수 ID)이나 배열에서
* 선택 순서를 보존하고 중복·빈 값을 제거한 명령 ID 목록을 반환한다.
*/
export function parseActiveInstructionIds(raw: unknown): string[] {
const parts: string[] =
typeof raw === 'string'
? raw.split(',')
: Array.isArray(raw)
? raw.filter((v): v is string => typeof v === 'string')
: []
const seen = new Set<string>()
const result: string[] = []
for (const part of parts) {
const trimmed = part.trim()
if (trimmed.length > 0 && !seen.has(trimmed)) {
seen.add(trimmed)
result.push(trimmed)
}
}
return result
}
/**
* 순서가 있는 명령 ID 배열을 `AppConfig.activeInstructionId` 저장 형식(콤마 구분 문자열)으로 직렬화한다.
*/
export function serializeActiveInstructionIds(ids: readonly string[]): string {
return parseActiveInstructionIds(ids).join(',')
}
/**
* 파이프라인에서 특정 명령 ID를 토글(없으면 맨 뒤에 추가, 있으면 제거)한 새 배열을 반환한다.
*/
export function toggleInstructionInPipeline(
currentIds: readonly string[],
targetId: string,
): string[] {
const normalized = parseActiveInstructionIds(currentIds)
const trimmed = targetId.trim()
if (!trimmed) return normalized
const idx = normalized.indexOf(trimmed)
if (idx >= 0) {
return normalized.filter((id) => id !== trimmed)
}
return [...normalized, trimmed]
}
/**
* 파이프라인 안에서 특정 명령의 실행 순서를 위(`up`) 또는 아래(`down`)로 한 칸 이동한다.
*/
export function moveInstructionInPipeline(
currentIds: readonly string[],
targetId: string,
direction: 'up' | 'down',
): string[] {
const next = parseActiveInstructionIds(currentIds)
const idx = next.indexOf(targetId.trim())
if (idx === -1) return next
const swapIdx = direction === 'up' ? idx - 1 : idx + 1
if (swapIdx < 0 || swapIdx >= next.length) return next
const temp = next[idx]
next[idx] = next[swapIdx]
next[swapIdx] = temp
return next
}
/**
* 복수 명령(1단계 → 2단계 → …)을 단일 LLM 호출로 빠르게 처리하기 위한 파이프라인 프롬프트를 합성한다.
* - 0개면 빈 문자열, 1개면 해당 지시문 원문을 그대로 반환한다(하위 호환 100%).
* - 2개 이상이면 단계별 순서와 충돌 해결 규칙(어투·형식·언어 등 최종 표현은 뒤쪽 단계가 우선)을 명시해 합성한다.
*/
export function composeInstructionPipelinePrompt(
steps: ReadonlyArray<{ name: string; prompt: string }>,
): string {
if (steps.length === 0) return ''
if (steps.length === 1) return steps[0].prompt
const normalizedSteps = steps.map((step, index) => {
const cleanedPrompt = step.prompt
.replaceAll(INSTRUCTION_TEXT_PLACEHOLDER, '입력된 텍스트')
.replaceAll(INSTRUCTION_USER_PROMPT_PLACEHOLDER, '입력된 텍스트')
.trim()
return `[${index + 1}단계: ${step.name}]\n${cleanedPrompt}`
})
return [
'다음 파이프라인 단계들을 1단계부터 순서대로 모두 적용하여 입력된 텍스트를 처리하세요.',
'앞 단계의 처리 결과를 바탕으로 다음 단계를 이어서 적용하되, 어투(존댓말/반말/격식체)·출력 형식·번역 언어 등 최종 표현 방식이 단계 간에 충돌할 경우 반드시 **뒤쪽(마지막) 단계**의 지시를 최종 기준으로 우선 적용하세요.',
'각 단계의 중간 과정이나 단계 번호, 부연 설명은 절대 출력하지 말고 **최종 완료된 결과 텍스트만** 출력하세요.',
'',
...normalizedSteps,
].join('\n\n')
}

View file

@ -478,6 +478,8 @@ export interface AppConfig {
*/
conversationBackend: 'local' | 'realtime'
defaultLLMAction: LLMActionSelection
/** 번역 대상 언어 (예: 'English', 'Korean', 'Japanese'). 기본값 'English'. */
targetLanguage: string
/**
* 전체 키바인딩. 액션 id → 바인딩 목록(다중 바인딩).
* 구조·기본값·검증은 `packages/core/src/keybinding.ts` 가 정본이다.

View file

@ -1726,7 +1726,7 @@ export function detectHangulTypedLatin(
const [, korPrefix, jamoRest] = korPrefixAndJamoRest
if (Array.from(korPrefix).every((ch) => isCommonHangulSyllable(ch))) {
const restResolved =
LOOSE_JAMO_TWO_LETTER_ENGLISH[jamoRest] ?? detectHangulTypedLatin(jamoRest, options)
LOOSE_JAMO_TWO_LETTER_ENGLISH[jamoRest] ?? detectHangulTypedLatin(jamoRest, context, options)
if (restResolved) {
return `${korPrefix}${restResolved}`
}
@ -2286,7 +2286,12 @@ export function detectJamoNoise(prefix: string, options: { ignoredWords?: readon
if (!COMPAT_JAMO.test(char)) return true
const lone = !COMPAT_JAMO.test(chars[position - 1] ?? '') && !COMPAT_JAMO.test(chars[position + 1] ?? '')
if (!lone) return true
if (position === chars.length - 1 && EMOTIVE_JAMO.has(char)) return true
if (
position === chars.length - 1 &&
(EMOTIVE_JAMO.has(char) || (token.end === prefix.length && /^[\u3131-\u314e]$/u.test(char)))
) {
return true
}
changed = true
return false
})
@ -2305,6 +2310,16 @@ function isIntentionalJamoToken(word: string): boolean {
return false
}
/**
* 커서 끝에서 다음 한글 음절을 조합하기 위해 막 초성 자음 하나만 누른 중간 상태인가
* (예: "안ㄴ", "안녕ㅎ", "한ㄱ", "오늘 ㄴ"). 이 상태는 오타가 아니라 정상적인 한글 타이핑 과정이다.
*/
function isComposingTrailingConsonantAtEnd(region: string, token: WordToken): boolean {
if (token.end !== region.length) return false
if (LOOSE_JAMO_TWO_LETTER_ENGLISH[token.text]) return false
return /^[가-힣]*[\u3131-\u314e]$/u.test(token.text)
}
/**
* 모델에 오타 검사를 맡길 만큼 수상한 구간인가 — 낱자가 섞인 한글/한영 오타 단어, 드문 음절, 미등록 소문자 영단어.
*
@ -2312,9 +2327,16 @@ function isIntentionalJamoToken(word: string): boolean {
* 수상한 흔적이 있을 때만 즉시 묻는다.
*/
export function hasSuspiciousTypo(region: string): boolean {
if (detectJamoNoise(region).length > 0) return true
if (
detectJamoNoise(region).some(
(c) => c.to !== '' || /[ \t]$/u.test(c.from) || c.end < region.length
)
) {
return true
}
return tokenizeWords(region).some((token) => {
const word = token.text
if (isComposingTrailingConsonantAtEnd(region, token)) return false
if (/[ㄱ-ㆎ]/u.test(word) && !isIntentionalJamoToken(word)) return true
if (Array.from(word).some((char) => HANGUL_SYLLABLE.test(char) && !isCommonHangulSyllable(char))) {
return true

File diff suppressed because it is too large Load diff

View file

@ -9,13 +9,21 @@
"nav.meetings": "Meetings",
"nav.record": "Record",
"nav.chat": "Chat",
"nav.knowledge": "Knowledge",
"nav.actions": "Actions",
"nav.teams": "Teams",
"nav.billing": "Billing",
"nav.logout": "Logout",
"login.subtitle": "AI Voice Assistant",
"login.google": "Continue with Google",
"login.apple": "Continue with Apple",
"login.github": "Continue with GitHub",
"login.or": "or",
"login.email": "Email",
"login.password": "Password",
"login.signIn": "Sign in",
"login.noAccount": "Don't have an account?",
"login.signUp": "Sign up",
"login.terms": "By continuing, you agree to the Terms of Service and Privacy Policy.",
"dashboard.systemStatus": "System Status",
"dashboard.sessionsToday": "Today's Sessions",
@ -384,7 +392,6 @@
"conversation.realtime.badge": "LIVE",
"conversation.realtime.connecting": "Connecting",
"conversation.realtime.fallback": "Live connection failed — switched to local conversation.",
"nav.knowledge": "Knowledge",
"rag.title": "Knowledge Base",
"rag.addDocument": "Add Document",
"rag.documents": "Documents",
@ -1210,7 +1217,7 @@
"onboarding.title": "D3RO Voice Initial Setup",
"onboarding.subtitle": "Download the model required to use the voice assistant.",
"onboarding.llmModelMissing": "AI model ({{model}}) is not installed.",
"onboarding.llmModelSize": "Size: ~9.6GB — takes 10–30 min depending on network speed",
"onboarding.llmModelSize": "Size: ~4.0GB — takes 3–10 min depending on network speed",
"onboarding.download": "Start Download",
"onboarding.cancel": "Later",
"onboarding.close": "Close",
@ -2493,11 +2500,14 @@
"tools.loadMore": "Show more ({{shown}}/{{total}})",
"tools.commands.description": "Choose how AI polishes what you dictate.",
"tools.commands.add": "Add command",
"tools.commands.listTitle": "Command to use",
"tools.commands.listHint": "Your choice applies from the next dictation.",
"tools.commands.listTitle": "Command pipeline",
"tools.commands.listHint": "Check one or multiple commands in order to build a pipeline (e.g., Step 1 Clean Speech → Step 2 Formal Tone).",
"tools.commands.none": "No AI command",
"tools.commands.noneHint": "Inserts what you said as-is.",
"tools.commands.inUse": "In use",
"tools.commands.stepBadge": "Step {{step}}",
"tools.commands.moveUp": "Move {{name}} earlier",
"tools.commands.moveDown": "Move {{name}} later",
"tools.commands.empty": "No commands yet",
"tools.commands.emptyHint": "Select Add command to save a polishing style you use often.",
"tools.commands.loadFailed": "Couldn't load commands.",
@ -2511,6 +2521,7 @@
"tools.commands.pipeline.stepStt": "Speech becomes text, using dictionary words as recognition hints.",
"tools.commands.pipeline.stepRaw": "No AI post-processing.",
"tools.commands.pipeline.stepInstruction": "AI polishes it with '{{name}}'.",
"tools.commands.pipeline.stepPipelineItem": "AI Step {{step}} — applies '{{name}}'.",
"tools.commands.pipeline.stepMissing": "Set to use a command, but none is selected — pick one below.",
"tools.commands.pipeline.stepAction": "AI applies the default action ({{action}}). Change it in Settings > LLM.",
"tools.commands.pipeline.stepInsert": "The result goes into the window you were typing in.",
@ -2693,5 +2704,19 @@
"popup.suggestion.none": "No suggestions",
"keybinding.action.suggestionAcceptWord": "Accept one word of a suggestion",
"keybinding.action.suggestionAcceptWord.desc": "Inserts only the first word and keeps the rest on screen so you can keep going.",
"popup.suggestion.hintWord": "Word"
"popup.suggestion.hintWord": "Word",
"settings.targetLanguage": "Translation target language",
"settings.targetLanguage.desc": "Language used for translation post-processing and {{targetLanguage}} commands.",
"settings.targetLanguage.en": "English",
"settings.targetLanguage.ko": "Korean",
"settings.targetLanguage.ja": "Japanese",
"settings.targetLanguage.zhCN": "Chinese (Simplified)",
"settings.targetLanguage.zhTW": "Chinese (Traditional)",
"settings.targetLanguage.es": "Spanish",
"settings.targetLanguage.fr": "French",
"settings.targetLanguage.de": "German",
"settings.targetLanguage.pt": "Portuguese",
"settings.targetLanguage.vi": "Vietnamese",
"settings.targetLanguage.id": "Indonesian",
"settings.targetLanguage.ar": "Arabic"
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1217,7 +1217,7 @@
"onboarding.title": "D3RO Voice 초기 설정",
"onboarding.subtitle": "음성 어시스턴트 사용에 필요한 모델을 다운로드합니다.",
"onboarding.llmModelMissing": "AI 모델({{model}})이 설치되어 있지 않습니다.",
"onboarding.llmModelSize": "크기: 약 9.6GB — 네트워크 속도에 따라 10~30분 소요",
"onboarding.llmModelSize": "크기: 약 4.0GB — 네트워크 속도에 따라 3~10분 소요",
"onboarding.download": "다운로드 시작",
"onboarding.cancel": "나중에",
"onboarding.close": "닫기",
@ -2500,11 +2500,14 @@
"tools.loadMore": "더 보기 ({{shown}}/{{total}})",
"tools.commands.description": "받아쓴 문장을 AI가 어떻게 다듬을지 고릅니다.",
"tools.commands.add": "명령 추가",
"tools.commands.listTitle": "사용할 명령",
"tools.commands.listHint": "하나를 고르면 다음 받아쓰기부터 적용됩니다.",
"tools.commands.listTitle": "사용할 명령 파이프라인",
"tools.commands.listHint": "하나 또는 여러 개를 순서대로 체크해 파이프라인으로 묶을 수 있습니다 (예: 1단계 정리 → 2단계 격식체 변환).",
"tools.commands.none": "AI 명령 사용 안 함",
"tools.commands.noneHint": "받아쓴 문장을 그대로 넣습니다.",
"tools.commands.inUse": "사용 중",
"tools.commands.stepBadge": "{{step}}단계",
"tools.commands.moveUp": "{{name}} 순서 위로 이동",
"tools.commands.moveDown": "{{name}} 순서 아래로 이동",
"tools.commands.empty": "만든 명령이 없습니다",
"tools.commands.emptyHint": "명령 추가를 눌러 자주 쓰는 다듬기 방식을 저장하세요.",
"tools.commands.loadFailed": "명령 목록을 불러오지 못했습니다.",
@ -2518,6 +2521,7 @@
"tools.commands.pipeline.stepStt": "음성을 글로 옮깁니다. 사전 단어를 인식 힌트로 씁니다.",
"tools.commands.pipeline.stepRaw": "AI 후처리 없이 그대로 둡니다.",
"tools.commands.pipeline.stepInstruction": "AI가 '{{name}}' 명령으로 다듬습니다.",
"tools.commands.pipeline.stepPipelineItem": "AI {{step}}단계 — '{{name}}' 명령을 적용합니다.",
"tools.commands.pipeline.stepMissing": "명령을 쓰도록 설정됐지만 고른 명령이 없습니다 — 아래에서 하나를 고르세요.",
"tools.commands.pipeline.stepAction": "AI가 기본 후처리({{action}})를 적용합니다. 설정 > LLM에서 바꿀 수 있습니다.",
"tools.commands.pipeline.stepInsert": "결과를 지금 쓰던 창에 넣습니다.",
@ -2700,5 +2704,19 @@
"popup.suggestion.none": "제안 사항 없음",
"keybinding.action.suggestionAcceptWord": "제안 한 단어 받기",
"keybinding.action.suggestionAcceptWord.desc": "제안의 첫 단어만 넣고, 나머지는 창에 남겨 이어서 받을 수 있게 합니다.",
"popup.suggestion.hintWord": "단어"
"popup.suggestion.hintWord": "단어",
"settings.targetLanguage": "번역 대상 언어",
"settings.targetLanguage.desc": "번역 후처리와 {{targetLanguage}} 명령어에 쓸 언어입니다.",
"settings.targetLanguage.en": "영어 (English)",
"settings.targetLanguage.ko": "한국어 (Korean)",
"settings.targetLanguage.ja": "일본어 (Japanese)",
"settings.targetLanguage.zhCN": "중국어 간체 (Chinese Simplified)",
"settings.targetLanguage.zhTW": "중국어 번체 (Chinese Traditional)",
"settings.targetLanguage.es": "스페인어 (Spanish)",
"settings.targetLanguage.fr": "프랑스어 (French)",
"settings.targetLanguage.de": "독일어 (German)",
"settings.targetLanguage.pt": "포르투갈어 (Portuguese)",
"settings.targetLanguage.vi": "베트남어 (Vietnamese)",
"settings.targetLanguage.id": "인도네시아어 (Indonesian)",
"settings.targetLanguage.ar": "아랍어 (Arabic)"
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff