diff --git a/apps/desktop/src/main/services/ScreenContextService.ts b/apps/desktop/src/main/services/ScreenContextService.ts index dab6093..6e2455f 100644 --- a/apps/desktop/src/main/services/ScreenContextService.ts +++ b/apps/desktop/src/main/services/ScreenContextService.ts @@ -4,12 +4,13 @@ // 활성 창 조회는 ForegroundWindowPort(foreground-window-port.ts)에 맡긴다 — 이 서비스는 컨텍스트 // 정책(무엇을 언제 캡처해 어떻게 프롬프트로 만드는가)만 소유한다. -import { clipboard } from 'electron' 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, @@ -44,18 +45,6 @@ export interface ScreenContextServiceDeps { platform?: NodeJS.Platform } -// ============================================================ -// 클립보드 스냅샷 (TextInsertService와 동일 패턴) -// ============================================================ - -interface ClipboardSnapshot { - text: string | null - html: string | null - image: Electron.NativeImage | null - rtf: string | null - hasContent: boolean -} - // ============================================================ // ScreenContextService // ============================================================ @@ -246,13 +235,20 @@ export class ScreenContextService { */ private async _captureSelectedText(): Promise { const nut = await this._ensureNut() + const port = electronClipboardPort - // 1. 기존 클립보드 저장 - const snapshot = this._saveClipboard() + // 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. 클립보드 비우기 (이전 내용이 남아있으면 "선택 없음"을 감지할 수 없으므로) - clipboard.clear() + port.clear() // 3. 복사 단축키 시뮬레이션 (macOS ⌘+C, 그 외 Ctrl+C) const modifier = this._platform === 'darwin' ? nut.Key.LeftSuper : nut.Key.LeftControl @@ -263,10 +259,10 @@ export class ScreenContextService { await this._sleep(150) // 5. 클립보드에서 텍스트 읽기 - const text = clipboard.readText() + const text = port.readText() // 6. 클립보드 복원 - this._restoreClipboard(snapshot) + this._restoreClipboard(restore) // 빈 문자열이면 선택된 텍스트 없음 if (!text || text.trim().length === 0) { @@ -277,7 +273,7 @@ export class ScreenContextService { } catch (error) { // 실패 시에도 클립보드 복원 try { - this._restoreClipboard(snapshot) + this._restoreClipboard(restore) } catch { logger.warn('Failed to restore clipboard after selected text capture error') } @@ -289,42 +285,8 @@ export class ScreenContextService { } } - /** - * 클립보드 저장 (TextInsertService와 동일 패턴). - */ - private _saveClipboard(): ClipboardSnapshot { - const text = clipboard.readText() || null - const html = clipboard.readHTML() || null - const rtf = clipboard.readRTF() || null - const image = clipboard.readImage() - const hasImage = image && !image.isEmpty() - - return { - text, - html, - image: hasImage ? image : null, - rtf, - hasContent: !!(text || html || rtf || hasImage), - } - } - - /** - * 클립보드 복원 — 저장해 둔 모든 형식(text/html/rtf/image)을 한 번에 되돌린다. - * 예전엔 첫 번째로 있는 형식 하나만 썼기 때문에 서식 있는 복사본이나 텍스트+이미지가 - * 캡처 한 번에 평문으로 바뀌었다. - */ - private _restoreClipboard(snapshot: ClipboardSnapshot): void { - if (!snapshot.hasContent) { - clipboard.clear() - return - } - - const data: Electron.Data = {} - if (snapshot.text) data.text = snapshot.text - if (snapshot.html) data.html = snapshot.html - if (snapshot.rtf) data.rtf = snapshot.rtf - if (snapshot.image) data.image = snapshot.image - clipboard.write(data) + private _restoreClipboard(plan: ClipboardRestorePlan): void { + applyClipboardRestore(electronClipboardPort, plan) } private _sleep(ms: number): Promise { diff --git a/apps/desktop/tests/main/services/screen-context-redteam-r1-3.test.ts b/apps/desktop/tests/main/services/screen-context-redteam-r1-3.test.ts index b019a96..214fc57 100644 --- a/apps/desktop/tests/main/services/screen-context-redteam-r1-3.test.ts +++ b/apps/desktop/tests/main/services/screen-context-redteam-r1-3.test.ts @@ -67,4 +67,15 @@ describe('ScreenContextService.captureSelectedText', () => { image, }) }) + + it('탐색기에서 복사한 파일처럼 되돌릴 수 없는 클립보드면 캡처를 건너뛰고 클립보드를 건드리지 않는다', async () => { + vi.mocked(clipboard.availableFormats).mockReturnValueOnce(['FileNameW']) + + const text = await getScreenContextService().captureSelectedText() + + expect(text).toBeNull() + expect(nut.pressKey).not.toHaveBeenCalled() + expect(clipboardClear).not.toHaveBeenCalled() + expect(clipboard.write).not.toHaveBeenCalled() + }) }) diff --git a/apps/desktop/tests/setup.ts b/apps/desktop/tests/setup.ts index 92536b1..bf197cc 100644 --- a/apps/desktop/tests/setup.ts +++ b/apps/desktop/tests/setup.ts @@ -65,6 +65,9 @@ vi.mock('electron', () => ({ readHTML: vi.fn(() => ''), readRTF: vi.fn(() => ''), readImage: vi.fn(() => ({ isEmpty: () => true, toPNG: () => Buffer.alloc(0) })), + availableFormats: vi.fn((): string[] => []), + readBuffer: vi.fn(() => Buffer.alloc(0)), + writeBuffer: vi.fn(), write: vi.fn(), }, shell: {