Capture still used the old snapshot code: a file copied in Explorer looked empty and was cleared, and Excel's own formats were dropped on restore. It now uses the shared clipboard snapshot policy and leaves the clipboard alone when it couldn't put everything back.
306 lines
11 KiB
TypeScript
306 lines
11 KiB
TypeScript
// src/main/services/ScreenContextService.ts
|
|
// 활성 윈도우 정보 + 선택된 텍스트를 캡처하여 LLM 프롬프트에 컨텍스트로 제공한다.
|
|
// Phase 10.2 스크린 컨텍스트. Speakly ContextService 참조.
|
|
// 활성 창 조회는 ForegroundWindowPort(foreground-window-port.ts)에 맡긴다 — 이 서비스는 컨텍스트
|
|
// 정책(무엇을 언제 캡처해 어떻게 프롬프트로 만드는가)만 소유한다.
|
|
|
|
import { getLogger } from './LoggerService'
|
|
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 { applyClipboardRestore, captureClipboard, planClipboardRestore, type ClipboardRestorePlan } from './text-insert/clipboard-snapshot'
|
|
import { electronClipboardPort } from './text-insert/electron-clipboard-port'
|
|
import {
|
|
createDefaultForegroundWindowPort,
|
|
isTerminalHost,
|
|
type ForegroundWindowPort,
|
|
} from './foreground-window-port'
|
|
|
|
const logger = getLogger('screen-context')
|
|
|
|
/**
|
|
* 선택 텍스트 캡처 전에 사용자가 수정자 키(Ctrl/Alt/Shift/Win)를 뗄 때까지 기다리는 최대 시간.
|
|
* 손을 떼지 않으면 캡처를 건너뛴다 — 수정자를 쥔 채 Ctrl+C 를 보내면 대상 앱엔 Ctrl+Alt+C 등이
|
|
* 들어가 복사가 되지 않고(AltGr 배열에선 문자가 입력되어 선택 영역을 덮어쓴다) 클립보드만 비워진다.
|
|
*/
|
|
const MODIFIER_RELEASE_TIMEOUT_MS = 800
|
|
|
|
// ============================================================
|
|
// nut-js 타입 (lazy import)
|
|
// ============================================================
|
|
|
|
type NutModule = typeof import('@nut-tree-fork/nut-js')
|
|
|
|
interface NutKeyboard {
|
|
pressKey: NutModule['keyboard']['pressKey']
|
|
releaseKey: NutModule['keyboard']['releaseKey']
|
|
Key: NutModule['Key']
|
|
}
|
|
|
|
export interface ScreenContextServiceDeps {
|
|
/** 포그라운드 창 조회 (기본: 플랫폼 어댑터) */
|
|
foreground?: ForegroundWindowPort
|
|
/** 복사 단축키 수정자 결정용 플랫폼 (기본: process.platform) */
|
|
platform?: NodeJS.Platform
|
|
}
|
|
|
|
// ============================================================
|
|
// 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 패턴).
|
|
*/
|
|
private async _ensureNut(): Promise<NutKeyboard> {
|
|
if (this._nutKeyboard) return this._nutKeyboard
|
|
|
|
if (!this._nutLoadPromise) {
|
|
this._nutLoadPromise = (async () => {
|
|
try {
|
|
const nut = await import('@nut-tree-fork/nut-js')
|
|
this._nutKeyboard = {
|
|
pressKey: nut.keyboard.pressKey.bind(nut.keyboard),
|
|
releaseKey: nut.keyboard.releaseKey.bind(nut.keyboard),
|
|
Key: nut.Key,
|
|
}
|
|
logger.info('nut-js loaded for screen context')
|
|
} catch (error) {
|
|
logger.error(
|
|
`Failed to load nut-js: ${error instanceof Error ? error.message : String(error)}`
|
|
)
|
|
throw new D3ROError(
|
|
ErrorCode.ContextCaptureFailed,
|
|
'nut-js 로드 실패. 스크린 컨텍스트를 사용할 수 없습니다.'
|
|
)
|
|
}
|
|
})()
|
|
}
|
|
|
|
await this._nutLoadPromise
|
|
if (!this._nutKeyboard) {
|
|
throw new D3ROError(ErrorCode.ContextCaptureFailed, 'nut-js not available')
|
|
}
|
|
return this._nutKeyboard
|
|
}
|
|
|
|
// ── 메인 API ──────────────────────────────────────────
|
|
|
|
/**
|
|
* 활성 윈도우 정보 + 선택된 텍스트를 캡처한다.
|
|
*
|
|
* @param captureSelectedText true이면 복사 단축키로 선택 텍스트 캡처 시도
|
|
*/
|
|
async captureContext(captureSelectedText = true): Promise<CaptureContextResult> {
|
|
const capturedAt = Date.now()
|
|
let appName: string | null = null
|
|
let windowTitle: string | null = null
|
|
let selectedText: string | null = null
|
|
let selectedTextAttempted = false
|
|
|
|
// 1. 활성 윈도우 정보 (ForegroundWindowPort)
|
|
try {
|
|
const appInfo = await this._foreground.current()
|
|
appName = appInfo.appName
|
|
windowTitle = appInfo.windowTitle
|
|
} catch (error) {
|
|
logger.warn(
|
|
`Failed to get active window info: ${error instanceof Error ? error.message : String(error)}`
|
|
)
|
|
// 활성 윈도우 감지 실패는 치명적이지 않으므로 계속 진행
|
|
}
|
|
|
|
// 2. 선택된 텍스트 캡처 (클립보드 방식)
|
|
if (captureSelectedText) {
|
|
selectedTextAttempted = true
|
|
try {
|
|
selectedText = await this._captureSelectionIn(appName)
|
|
} catch (error) {
|
|
logger.warn(
|
|
`Failed to capture selected text: ${error instanceof Error ? error.message : String(error)}`
|
|
)
|
|
// 선택 텍스트 캡처 실패도 치명적이지 않음
|
|
}
|
|
}
|
|
|
|
const context: ScreenContext = {
|
|
appName,
|
|
windowTitle,
|
|
selectedText,
|
|
capturedAt,
|
|
}
|
|
|
|
logger.info(
|
|
`Context captured: app=${appName ?? 'unknown'}, title=${windowTitle ? windowTitle.substring(0, 40) : 'unknown'}, selectedText=${selectedText ? `${selectedText.length} chars` : 'none'}`
|
|
)
|
|
|
|
return { context, selectedTextAttempted }
|
|
}
|
|
|
|
/**
|
|
* 선택된 텍스트만 캡처한다 (클립보드 방식).
|
|
* 수정자 키가 눌려 있으면 뗄 때까지 잠깐 기다리고, 그래도 쥐고 있으면 캡처하지 않고 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()
|
|
}
|
|
|
|
/**
|
|
* ScreenContext를 LLM 시스템 프롬프트 접두사로 변환한다.
|
|
* 빈 컨텍스트면 빈 문자열을 반환.
|
|
*/
|
|
buildContextPrompt(ctx: ScreenContext): string {
|
|
const parts: string[] = []
|
|
|
|
if (ctx.appName || ctx.windowTitle || ctx.selectedText) {
|
|
parts.push('[컨텍스트]')
|
|
|
|
if (ctx.appName) {
|
|
parts.push(`활성 앱: ${ctx.appName}`)
|
|
}
|
|
if (ctx.windowTitle) {
|
|
parts.push(`윈도우: ${ctx.windowTitle}`)
|
|
}
|
|
if (ctx.selectedText) {
|
|
parts.push(`선택된 텍스트:`)
|
|
parts.push(ctx.selectedText)
|
|
}
|
|
|
|
parts.push('') // 빈 줄로 구분
|
|
}
|
|
|
|
return parts.join('\n')
|
|
}
|
|
|
|
/**
|
|
* 스크린 컨텍스트 활성화 여부.
|
|
*/
|
|
isEnabled(): boolean {
|
|
return configGet('screenContextEnabled')
|
|
}
|
|
|
|
/**
|
|
* 스크린 컨텍스트 활성화/비활성화.
|
|
*/
|
|
setEnabled(enabled: boolean): void {
|
|
configSet('screenContextEnabled', enabled)
|
|
logger.info(`Screen context ${enabled ? 'enabled' : 'disabled'}`)
|
|
}
|
|
|
|
dispose(): void {
|
|
this._nutKeyboard = null
|
|
this._nutLoadPromise = null
|
|
logger.info('ScreenContextService disposed')
|
|
}
|
|
|
|
// ── 내부 구현 ─────────────────────────────────────────
|
|
|
|
/**
|
|
* 선택된 텍스트를 클립보드 방식으로 캡처한다.
|
|
* TextInsertService의 역방향: clipboard save → 복사 단축키 simulate → clipboard read → clipboard restore
|
|
*/
|
|
private async _captureSelectedText(): Promise<string | null> {
|
|
const nut = await this._ensureNut()
|
|
const port = electronClipboardPort
|
|
|
|
// 1. 기존 클립보드 저장 + 온전히 되돌릴 수 있는지 판정 (삽입과 같은 정책)
|
|
// 탐색기에서 복사한 파일·Excel 셀처럼 다 되돌릴 수 없으면 캡처를 건너뛴다 — 부가 문맥 하나 때문에
|
|
// 사용자가 복사해 둔 것을 지우면 안 된다(예전엔 파일 복사본이 '비어 있음'으로 보여 clear() 됐다).
|
|
const restore = planClipboardRestore(captureClipboard(port))
|
|
if (restore.kind === 'unrestorable' || (restore.kind === 'write' && restore.dropped.length > 0)) {
|
|
logger.info('선택 텍스트 캡처 건너뜀: 클립보드를 온전히 되돌릴 수 없다')
|
|
return null
|
|
}
|
|
|
|
try {
|
|
// 2. 클립보드 비우기 (이전 내용이 남아있으면 "선택 없음"을 감지할 수 없으므로)
|
|
port.clear()
|
|
|
|
// 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)
|
|
|
|
// 5. 클립보드에서 텍스트 읽기
|
|
const text = port.readText()
|
|
|
|
// 6. 클립보드 복원
|
|
this._restoreClipboard(restore)
|
|
|
|
// 빈 문자열이면 선택된 텍스트 없음
|
|
if (!text || text.trim().length === 0) {
|
|
return null
|
|
}
|
|
|
|
return text
|
|
} catch (error) {
|
|
// 실패 시에도 클립보드 복원
|
|
try {
|
|
this._restoreClipboard(restore)
|
|
} catch {
|
|
logger.warn('Failed to restore clipboard after selected text capture error')
|
|
}
|
|
|
|
throw new D3ROError(
|
|
ErrorCode.ContextSelectedTextFailed,
|
|
`선택 텍스트 캡처 실패: ${error instanceof Error ? error.message : String(error)}`
|
|
)
|
|
}
|
|
}
|
|
|
|
private _restoreClipboard(plan: ClipboardRestorePlan<Electron.NativeImage>): void {
|
|
applyClipboardRestore(electronClipboardPort, plan)
|
|
}
|
|
|
|
private _sleep(ms: number): Promise<void> {
|
|
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
}
|
|
}
|
|
|
|
// ── 싱글톤 ────────────────────────────────────────────
|
|
|
|
let instance: ScreenContextService | null = null
|
|
|
|
export function getScreenContextService(): ScreenContextService {
|
|
if (!instance) {
|
|
instance = new ScreenContextService()
|
|
}
|
|
return instance
|
|
}
|