fix(voice): stop mic-test ref stealing, unblock action queue, keep tail audio, and move context/LLM routing behind ports and pure policies
This commit is contained in:
parent
2cd462333f
commit
2f94d24c99
13 changed files with 1672 additions and 353 deletions
|
|
@ -1,6 +1,8 @@
|
|||
// src/main/services/ScreenContextService.ts
|
||||
// 활성 윈도우 정보 + 선택된 텍스트를 캡처하여 LLM 프롬프트에 컨텍스트로 제공한다.
|
||||
// Phase 10.2 스크린 컨텍스트. Speakly ContextService 참조.
|
||||
// 활성 창 조회는 ForegroundWindowPort(foreground-window-port.ts)에 맡긴다 — 이 서비스는 컨텍스트
|
||||
// 정책(무엇을 언제 캡처해 어떻게 프롬프트로 만드는가)만 소유한다.
|
||||
|
||||
import { clipboard } from 'electron'
|
||||
import { getLogger } from './LoggerService'
|
||||
|
|
@ -8,6 +10,11 @@ import { configGet, configSet } from './ConfigService'
|
|||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
import type { ScreenContext, CaptureContextResult } from '@d3ro/core/types'
|
||||
import { waitForModifiersReleased } from './modifier-state'
|
||||
import {
|
||||
createDefaultForegroundWindowPort,
|
||||
isTerminalHost,
|
||||
type ForegroundWindowPort,
|
||||
} from './foreground-window-port'
|
||||
|
||||
const logger = getLogger('screen-context')
|
||||
|
||||
|
|
@ -30,6 +37,13 @@ interface NutKeyboard {
|
|||
Key: NutModule['Key']
|
||||
}
|
||||
|
||||
export interface ScreenContextServiceDeps {
|
||||
/** 포그라운드 창 조회 (기본: 플랫폼 어댑터) */
|
||||
foreground?: ForegroundWindowPort
|
||||
/** 복사 단축키 수정자 결정용 플랫폼 (기본: process.platform) */
|
||||
platform?: NodeJS.Platform
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 클립보드 스냅샷 (TextInsertService와 동일 패턴)
|
||||
// ============================================================
|
||||
|
|
@ -46,9 +60,16 @@ interface ClipboardSnapshot {
|
|||
// ScreenContextService
|
||||
// ============================================================
|
||||
|
||||
class ScreenContextService {
|
||||
export class ScreenContextService {
|
||||
private _nutKeyboard: NutKeyboard | null = null
|
||||
private _nutLoadPromise: Promise<void> | null = null
|
||||
private readonly _foreground: ForegroundWindowPort
|
||||
private readonly _platform: NodeJS.Platform
|
||||
|
||||
constructor(deps: ScreenContextServiceDeps = {}) {
|
||||
this._platform = deps.platform ?? process.platform
|
||||
this._foreground = deps.foreground ?? createDefaultForegroundWindowPort(this._platform)
|
||||
}
|
||||
|
||||
/**
|
||||
* nut-js lazy dynamic import (TextInsertService 패턴).
|
||||
|
|
@ -90,7 +111,7 @@ class ScreenContextService {
|
|||
/**
|
||||
* 활성 윈도우 정보 + 선택된 텍스트를 캡처한다.
|
||||
*
|
||||
* @param captureSelectedText true이면 Ctrl+C로 선택 텍스트 캡처 시도
|
||||
* @param captureSelectedText true이면 복사 단축키로 선택 텍스트 캡처 시도
|
||||
*/
|
||||
async captureContext(captureSelectedText = true): Promise<CaptureContextResult> {
|
||||
const capturedAt = Date.now()
|
||||
|
|
@ -99,9 +120,9 @@ class ScreenContextService {
|
|||
let selectedText: string | null = null
|
||||
let selectedTextAttempted = false
|
||||
|
||||
// 1. 활성 윈도우 정보 (PowerShell)
|
||||
// 1. 활성 윈도우 정보 (ForegroundWindowPort)
|
||||
try {
|
||||
const appInfo = await this._getActiveWindowInfo()
|
||||
const appInfo = await this._foreground.current()
|
||||
appName = appInfo.appName
|
||||
windowTitle = appInfo.windowTitle
|
||||
} catch (error) {
|
||||
|
|
@ -115,7 +136,7 @@ class ScreenContextService {
|
|||
if (captureSelectedText) {
|
||||
selectedTextAttempted = true
|
||||
try {
|
||||
selectedText = await this.captureSelectedText()
|
||||
selectedText = await this._captureSelectionIn(appName)
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
`Failed to capture selected text: ${error instanceof Error ? error.message : String(error)}`
|
||||
|
|
@ -142,13 +163,30 @@ class ScreenContextService {
|
|||
* 선택된 텍스트만 캡처한다 (클립보드 방식).
|
||||
* 수정자 키가 눌려 있으면 뗄 때까지 잠깐 기다리고, 그래도 쥐고 있으면 캡처하지 않고 null 을
|
||||
* 돌려준다(클립보드도 건드리지 않는다).
|
||||
* 포그라운드가 콘솔/터미널이면 복사 단축키를 보내지 않는다 — 선택이 없을 때 Ctrl+C 는
|
||||
* 실행 중 프로세스를 중단(SIGINT)하거나 입력 줄을 지운다.
|
||||
*/
|
||||
async captureSelectedText(): Promise<string | null> {
|
||||
let foregroundApp: string | null = null
|
||||
try {
|
||||
foregroundApp = (await this._foreground.current()).appName
|
||||
} catch {
|
||||
// 조회 실패 시엔 앱을 모른 채 진행한다
|
||||
}
|
||||
return this._captureSelectionIn(foregroundApp)
|
||||
}
|
||||
|
||||
/** 포그라운드 앱을 이미 알고 있을 때의 선택 텍스트 캡처 */
|
||||
private async _captureSelectionIn(foregroundApp: string | null): Promise<string | null> {
|
||||
const released = await waitForModifiersReleased(MODIFIER_RELEASE_TIMEOUT_MS)
|
||||
if (!released) {
|
||||
logger.info('Selected text capture skipped: modifier keys still held')
|
||||
return null
|
||||
}
|
||||
if (isTerminalHost(foregroundApp)) {
|
||||
logger.info(`Selected text capture skipped: terminal host (${foregroundApp ?? 'unknown'})`)
|
||||
return null
|
||||
}
|
||||
return this._captureSelectedText()
|
||||
}
|
||||
|
||||
|
|
@ -202,132 +240,9 @@ class ScreenContextService {
|
|||
|
||||
// ── 내부 구현 ─────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* 활성 윈도우의 프로세스명과 타이틀을 가져온다.
|
||||
* - Windows: PowerShell + user32.dll
|
||||
* - macOS: osascript (System Events)
|
||||
* - Linux: 미지원 (null 반환)
|
||||
*
|
||||
* 참고: macOS는 Accessibility 권한이 필요하다. 첫 호출 시 시스템이
|
||||
* 권한 요청 다이얼로그를 띄운다. 사용자가 거부하면 { null, null } 반환.
|
||||
*/
|
||||
private async _getActiveWindowInfo(): Promise<{
|
||||
appName: string | null
|
||||
windowTitle: string | null
|
||||
}> {
|
||||
if (process.platform === 'win32') {
|
||||
return this._getActiveWindowInfoWin32()
|
||||
}
|
||||
if (process.platform === 'darwin') {
|
||||
return this._getActiveWindowInfoDarwin()
|
||||
}
|
||||
return { appName: null, windowTitle: null }
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows: PowerShell + user32.dll로 활성 윈도우 조회.
|
||||
*/
|
||||
private async _getActiveWindowInfoWin32(): Promise<{
|
||||
appName: string | null
|
||||
windowTitle: string | null
|
||||
}> {
|
||||
const { execFile } = await import('child_process')
|
||||
const { promisify } = await import('util')
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const psScript = `
|
||||
Add-Type @"
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
public class Win32 {
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
|
||||
}
|
||||
"@
|
||||
$hwnd = [Win32]::GetForegroundWindow()
|
||||
$pid = 0
|
||||
[void][Win32]::GetWindowThreadProcessId($hwnd, [ref]$pid)
|
||||
$proc = Get-Process -Id $pid -ErrorAction SilentlyContinue
|
||||
$sb = New-Object System.Text.StringBuilder 512
|
||||
[void][Win32]::GetWindowText($hwnd, $sb, 512)
|
||||
$procName = if ($proc) { $proc.ProcessName } else { '' }
|
||||
$title = $sb.ToString()
|
||||
"$procName$([char]10)$title"
|
||||
`.trim()
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync('powershell.exe', [
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-ExecutionPolicy', 'Bypass',
|
||||
'-Command', psScript,
|
||||
], { timeout: 3000, windowsHide: true })
|
||||
|
||||
const lines = stdout.trim().split('\n')
|
||||
const appName = lines[0]?.trim() || null
|
||||
const windowTitle = lines[1]?.trim() || null
|
||||
|
||||
return { appName, windowTitle }
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
`PowerShell active window query failed: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
return { appName: null, windowTitle: null }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* macOS: osascript (AppleScript)로 frontmost process와 윈도우 타이틀 조회.
|
||||
* Accessibility 권한 필요.
|
||||
*/
|
||||
private async _getActiveWindowInfoDarwin(): Promise<{
|
||||
appName: string | null
|
||||
windowTitle: string | null
|
||||
}> {
|
||||
const { execFile } = await import('child_process')
|
||||
const { promisify } = await import('util')
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
// AppleScript: 프로세스명과 앞 윈도우 타이틀을 2줄로 반환.
|
||||
// 윈도우가 없는 앱도 있으므로 try-fallback.
|
||||
const script = `
|
||||
try
|
||||
tell application "System Events"
|
||||
set frontApp to first process whose frontmost is true
|
||||
set appName to name of frontApp
|
||||
try
|
||||
set winTitle to name of front window of frontApp
|
||||
on error
|
||||
set winTitle to ""
|
||||
end try
|
||||
return appName & linefeed & winTitle
|
||||
end tell
|
||||
on error errMsg
|
||||
return "" & linefeed & ""
|
||||
end try
|
||||
`.trim()
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync('/usr/bin/osascript', ['-e', script], {
|
||||
timeout: 3000
|
||||
})
|
||||
const lines = stdout.split('\n')
|
||||
const appName = lines[0]?.trim() || null
|
||||
const windowTitle = lines[1]?.trim() || null
|
||||
return { appName, windowTitle }
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
`osascript active window query failed: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
return { appName: null, windowTitle: null }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 선택된 텍스트를 클립보드 방식으로 캡처한다.
|
||||
* TextInsertService의 역방향: clipboard save → Ctrl+C simulate → clipboard read → clipboard restore
|
||||
* TextInsertService의 역방향: clipboard save → 복사 단축키 simulate → clipboard read → clipboard restore
|
||||
*/
|
||||
private async _captureSelectedText(): Promise<string | null> {
|
||||
const nut = await this._ensureNut()
|
||||
|
|
@ -339,9 +254,10 @@ end try
|
|||
// 2. 클립보드 비우기 (이전 내용이 남아있으면 "선택 없음"을 감지할 수 없으므로)
|
||||
clipboard.clear()
|
||||
|
||||
// 3. Ctrl+C 시뮬레이션
|
||||
await nut.pressKey(nut.Key.LeftControl, nut.Key.C)
|
||||
await nut.releaseKey(nut.Key.LeftControl, nut.Key.C)
|
||||
// 3. 복사 단축키 시뮬레이션 (macOS ⌘+C, 그 외 Ctrl+C)
|
||||
const modifier = this._platform === 'darwin' ? nut.Key.LeftSuper : nut.Key.LeftControl
|
||||
await nut.pressKey(modifier, nut.Key.C)
|
||||
await nut.releaseKey(modifier, nut.Key.C)
|
||||
|
||||
// 4. 클립보드에 텍스트가 복사될 때까지 대기
|
||||
await this._sleep(150)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue