From 59cdddbecb5eb4224a292da67ef48aa9d26165bb Mon Sep 17 00:00:00 2001 From: Yun Chan Date: Fri, 20 Nov 2026 22:13:49 +0900 Subject: [PATCH 1/3] docs(release): record the 1.18.4 updater recovery --- docs/evidence/2026-11-17-backlog-operations.md | 4 ++++ docs/map/00-index.md | 2 +- docs/map/10-feature-catalog.md | 2 +- docs/map/11-gap-backlog.md | 4 ++-- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/evidence/2026-11-17-backlog-operations.md b/docs/evidence/2026-11-17-backlog-operations.md index c44a7dd4..145e8248 100644 --- a/docs/evidence/2026-11-17-backlog-operations.md +++ b/docs/evidence/2026-11-17-backlog-operations.md @@ -121,3 +121,7 @@ - 정상화된 트리의 full-only 크기 시험은 109.6초 만에 완료했지만 설치본은 `105,962,867 bytes`로 한도보다 `1,105,267 bytes` 컸다. ASAR 안 source map이 `15,231,119 bytes` 있어 production 패키지에서는 `!**/*.map`으로 제외한다. 실행 코드·리소스가 아니며 macOS에도 동일하게 적용할 수 있는 패키지 위생 수정이다. - source map 제거본의 ASAR은 `38,905,787 bytes`이며 최상위 `out`/`node_modules`/`package.json`만 있고 source map·release/src/tests·제외한 package는 0건이다. 패키징된 `win32-x64` SQLite 열기·질의와 `uiohook` 검사 GREEN이다. - full-only 설치본 시험은 106.6초 만에 `104,687,868 bytes`를 생성했다. 한도 `104,857,600 bytes`보다 `169,732 bytes` 작다. `.blockmap` 없이 `latest.yml`이 생성됐고, 실제 설치본·manifest와 레이아웃을 함께 smoke에 넣어 PE/SHA-512/feed/ASAR 계약 GREEN이다. self-test는 3 valid + 10 negative cases다. +- 정식 `1.18.4`(`f77c86d`) 설치본은 `104,691,365 bytes`로 빌드·native DB·smoke를 통과하고 `release-artifacts.json`에 full-only 해시가 기록됐다. canonical/mirror `main`과 annotated `v1.18.4`가 push됐다. +- 최초 게시는 `.env`의 Forgejo token이 실제 `/api/v1/user`에서도 HTTP 401이라 runtime feed gate에서 중단됐다. 공개 runtime은 무인증 HTTP 200이다. 기존 Git credential의 API 인증은 200이었고, 자격증명은 파일에 쓰거나 출력하지 않고 프로세스 메모리에서만 사용했다. checkpoint의 태그·SHA-256을 재검증하고 재빌드 없이 게시를 재개했다. +- 버전별 및 latest 설치본·서명 manifest·policy 업로드, 공개 signed-manifest 검증, Forgejo Release 3개 자산 첨부가 모두 성공했다. 공개 `latest/latest.yml`은 `1.18.4`, 설치본은 Range GET HTTP 206이다. Windows 차분 파일이 없으므로 policy `fullInstallVersionGap=0`도 게시됐다. +- 실행 중인 설치 앱은 여전히 1.17.1이며 새 버전의 업데이트 확인 로그는 아직 없다. 에이전트가 Electron을 실행하거나 종료하지 않았으므로 `설정 → 정보 → 업데이트`의 수동 확인과 제안/다운로드 화면은 사용자 검증으로 남는다. 다음 릴리스를 위해서는 만료된 `.env` token의 교체가 필요하다. diff --git a/docs/map/00-index.md b/docs/map/00-index.md index 204d626b..343be1b4 100644 --- a/docs/map/00-index.md +++ b/docs/map/00-index.md @@ -2,7 +2,7 @@ > Status: ACTIVE > Last full audit: 2026-09-13 -> Last update: 2026-11-20 — **데스크톱 자동 업데이트 미표시 원인 확인 및 `v1.18.4` 게시 복구.** 설치 앱과 공개 피드가 모두 `1.17.1`이며 업데이트 정책은 활성(kill switch=false, staging=100%)인 것을 실제 로그와 HTTP 응답으로 확인했다. 미게시 `1.18.1` 설치본은 115.2 MiB라 100 MiB 업로드 게이트에서 중단됐다. `1.18.4`는 중복 renderer 패키지와 미사용 SQLite 소스를 제외하고 최대 압축을 적용한다. 실제 공개 피드·설치 앱 제안 검증은 `11` GAP-REL-17에 기록한다. +> Last update: 2026-11-20 — **데스크톱 `v1.18.4` 자동 업데이트 피드 복구.** 기존 설치본은 정상 확인했으나 공개 피드가 `1.17.1`에 멈춰 있었다. 미게시 1.18.x의 크기 초과·과거 release 재귀 포함·만료된 Forgejo token을 해결하고 `1.18.4`(`f77c86d`)를 게시했다. Windows full-only 설치본 `104,691,365 bytes`, 공개 signed manifest와 Release 다운로드 HTTP 206을 확인했다. 실제 설치 앱의 제안 화면은 사용자 수동 확인으로 남는다(`11` GAP-REL-17). > > Previous update: 2026-11-14 — **전 표면 프로덕션 `v1.17.1` 배포 완결.** 데스크톱(`v1.17.1`, 커밋 `6c6875b`, 서명 매니페스트 `1.17.1/latest.yml`·`.sig` 및 `latest/latest.yml`, 런타임 `runtime-1.17.1`/`runtime-latest`, 포터블 `portable-1.17.1`/`portable-latest` 모두 Forgejo HTTP `200`, 태그 `v1.17.1` canonical/mirror 푸시; Human Release #339 ~91MB 바이너리 첨부만 Cloudflare HTTP 524/`ECONNRESET` `GAP-REL-16` 예외), Supabase 운영 DB(`db push --remote`, 전체 74개 마이그레이션 일치) 및 Edge Functions 24종(`--import-map deno.json --use-api`) 재배포, 랜딩 사이트(`site/` → Cloudflare Pages `d3ro`, `https://d3ro.chanpaca.net/release-identity.json` = `1.17.1`/`6c6875b` & `assetlinks.json` 검증 GREEN), Cloudflare Worker(`d3ro-voice-api` `--keep-vars`, Version ID `fe6d9532-0052-48f5-b62c-45c86f6aaaa5`), NAS Docker 스택(`d3ro_voice_api` `v1.17.1` `/health` `200`, `d3ro_voice_admin` `:3001`/`d3ro-admin.chanpaca.net/login` `200`, `d3ro_voice_web` `:3002/app/login`·`d3ro.chanpaca.net/app/login` `200`) 반영 완료. > diff --git a/docs/map/10-feature-catalog.md b/docs/map/10-feature-catalog.md index 680aeffb..6dad7ba4 100644 --- a/docs/map/10-feature-catalog.md +++ b/docs/map/10-feature-catalog.md @@ -234,7 +234,7 @@ end-to-end behaviour has **not been verified by typing in a real app** (`11` GAP | INFRA-12 | Cloudflare edge + tunnel | [x] | `server/cloudflare-worker`, Cloudflare Tunnel `kd-nas` | | INFRA-13 | Site deploy (Cloudflare Pages) | [x] | `.forgejo/workflows/deploy-site.yml`; the unused GitHub Pages workflow was removed in Wave 3 | | INFRA-17 | Test hygiene & TDD v2.0 gates | [x] | `scripts/ci/check-test-hygiene.mjs` (`test:hygiene`), `check-protected-tests.mjs` (`check:protected-tests`), `check-test-quality.mjs` (`test:quality`), `check-i18n-contract.mjs` (`check:i18n`), `check-ds-contract.mjs` (`check:ds-contract`), `run-affected-tests.mjs` (`test:affected`), `verify-desktop-installer-smoke.mjs` (`release:installer:smoke`), and `@d3ro/core/ports` (`Clock`/`Random` deterministic ports) — all equipped with `--self-test` and wired into `verify:all`, `.forgejo/workflows/ci.yml`, `release-desktop.mjs`, and `.forgejo/workflows/release.yml`. Applied policy: `docs/tdd-red/06-repo-application.md`, `07-revamp-plan.md`. | -| INFRA-15 | Update & release system | [~] | Canonical Forgejo feed + channels/policy (`release/update-policy.json`, `src/main/update-policy.ts`), canonical publisher `scripts/ci/publish-forgejo-release.mjs`; `npm run release:metadata:test`. 2026-11-20 설치본과 로그는 정상적으로 업데이트를 확인했으나 공개 피드가 1.17.1에 머물렀고 미게시 1.18.1·1.18.2의 115.2 MiB 설치본이 업로드 한도를 초과했다. 1.18.4는 Windows full-only 패키지(`fullInstallVersionGap=0`)와 재귀적인 과거 산출물 포함 차단으로 피드 한도를 맞춘다. 게시·실제 설치본 제안은 `11` GAP-REL-17에서 추적한다. | +| INFRA-15 | Update & release system | [~] | Canonical Forgejo feed + channels/policy, publisher `scripts/ci/publish-forgejo-release.mjs`; `npm run release:metadata:test`. 2026-11-20 `1.18.4`(`f77c86d`) Windows full-only 설치본 `104,691,365 bytes`를 게시하고 공개 피드·signed manifest·Release HTTP 206을 확인했다. 과거 release 재귀 포함과 source map·미사용 플랫폼 binary를 차단한다. 실제 1.17.1 설치본의 업데이트 제안·설치 GUI는 `11` GAP-REL-17의 남은 게이트다. | | INFRA-16 | Desktop STT engine packaging | [x] | `apps/desktop/scripts/setup-sidecar.mjs` + `build-sidecar.mjs`, `electron-builder.yml` `extraResources` (`sidecar-dist/sidecar` → `resources/sidecar`, `resources/ffmpeg`), and `scripts/ci/verify-sidecar-bundle.mjs` run in `package-windows`/`package-macos` before electron-builder. Verified on the real bundle: `sidecar.exe` + `_internal` including `faster_whisper/assets/silero_vad_v6.onnx`, plus a packaged-engine transcription round-trip on GPU. | | INFRA-17 | 서명 없는 배포 채널 (portable + Scoop) | [x] | `scripts/ci/build-portable.mjs` (95MiB 7z 분할 볼륨 + Scoop 매니페스트), `scripts/ci/publish-portable-release.mjs`, `scripts/local/install-d3ro-voice.ps1`, `bucket/` 버킷, `.forgejo/workflows/portable.yml`; 7z 분할 볼륨(Scoop, 162MiB) + zip 분할 부품(수동 설치, 243MiB, 7-Zip 불필요); updater feed와 분리. 2026-09-18 `portable-1.3.1` 게시 + 실제 설치 검증. | | INFRA-18 | 로컬 런타임 온디맨드 설치 | [x] | `RuntimeProvisioner`(부품 다운로드 + SHA-256 검증 + tar 해제, `%APPDATA%/d3ro-voice/runtime`), `POST runtime:ensure` / `runtime:progress` IPC, 설정 > STT 상태/내려받기 UI. 설치본에서 엔진/ffmpeg를 분리해 189MB → 90.6MiB, 업데이트 피드 게시 복구. 검증은 전부 디스크에 기록된 파일 기준이며(부품 크기·해시 → 결합본 크기·해시), 부품 다운로드는 최대 3회 재시도한다. 2026-09-18 실제 feed 통합 검증(엔진 94.4MiB/18초, ffmpeg 21.7MiB/5초). | diff --git a/docs/map/11-gap-backlog.md b/docs/map/11-gap-backlog.md index fd934c26..c5de5f21 100644 --- a/docs/map/11-gap-backlog.md +++ b/docs/map/11-gap-backlog.md @@ -71,8 +71,8 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res | GAP-MTG-02 | Meetings | Speaker diarization only partially done on desktop; absent web/mobile. | `apps/desktop/sidecar/main.py` (`POST /diarize`), `MeetingModeService.ts`, `packages/core/src/meeting-transcript.ts`, `apps/desktop/src/renderer/components/meeting/{TranscriptTab,EditableSegment}.tsx`, `apps/web/src/components/meetings/live-transcript-list.tsx`, `apps/mobile-rn/src/screens/MeetingDetailScreen.tsx` | `[~]` **2026-11-13 전 표면 구현·테스트 완료:** 사이드카 `POST /diarize`(`pyannote.audio` 설치 시 자동 사용 + 무의존 에너지 VAD 화자 교대 분할 폴백, Python 30/30 PASS)를 `LocalSTTService.sidecarBaseUrl`로 `MeetingModeService._diarizeTranscript`(LLM 추정 폴백 및 `stripInventedMarkers({ allowSpeakerMarkers })` 포함)에 연결하고, `@d3ro/core/meeting-transcript` 화자 목록/필터 유틸과 화자 배지·다중 화자 필터 칩을 데스크톱·웹·모바일 상세 화면 전부에 구현했다(코어 13/13, 데스크톱·웹·모바일 테스트 전수 PASS; 실음성 다중 화자 데스크톱 GUI 확인 전까지 `[~]`). | | GAP-MTG-03 | Meetings | Existing recordings could become plain transcription history, but not a meeting with linked audio and minutes. | desktop `MeetingModeService`, `meeting/imported-recording.ts`, `meeting-mode-handlers.ts`; mobile `MeetingsScreen` → `RecordScreen`; MTG-13 | `[~]` 2026-11-02: installed Windows 1.16.0 passed native picker→timestamped transcript→local summary/action item with a real WAV (`2026-11-02-verification.md`). Desktop GUI gate is complete; authenticated Android picker→upload→transcript→minutes on Fold6 remains. | | GAP-MTG-04 | Meetings | Learned typing vocabulary never reached meeting transcription: STT used a hardcoded Korean hint, refine had no glossary, refined lines stopped inside `CaptionService`, and the stored transcript was raw segments. | `packages/core/src/transcript-correction.ts`, `apps/desktop/src/main/services/TranscriptGlossaryService.ts`, `CaptionService.ts`, `meeting/MeetingRecordingSession.ts`, `MeetingModeService.ts`, `FileTranscriptionService.ts`, `VoiceModeService.ts`; MTG-14 | `[~]` 2026-11-05: one glossary SSOT wired into caption, meeting, file transcription and dictation; refined lines now propagate to the meeting transcript and renderer (`meetingMode:segmentUpdated`). **Direct measurement against the real local database** (`users/_local/d3ro.db`: 1,952 learned phrases / 2,522 typing samples / 3 meeting transcripts) exposed that the first cut also rewrote ordinary Korean (286 of 3,005 words: 하면→라면, 이제→이게, 매일→메일, 정보→정도), and v1.16.3 restricts deterministic correction to dictionary pronunciations plus typed Latin identifiers — re-measured **0 of 3,005**. Real-engine check with the local sidecar (`large-v3-turbo`): a Korean TTS fixture containing the user term transcribes as 하람로그에 with no hint and haramlog에 with the learned hint; a dictionary pronunciation entry maps 디에로 → D3RO. Hangul-layout artifacts (dkssudgktpdy) are excluded from the hint. Evidence: `packages/core/__tests__/transcript-correction.test.ts` 16/16, `apps/desktop/tests/main/services/transcript-glossary.test.ts` 10/10, core 589/589, desktop offline suite, workspace typecheck, touched-file ESLint, `test:hygiene`. **Remaining:** a live meeting with real names/jargon by voice, and a packaged-install check of the new IPC event. | -| GAP-REL-16 | Release | Forgejo release-page asset attachment for the ~91 MB installer times out through Cloudflare (HTTP 524), although the package registry upload and the signed manifest succeed. | `scripts/ci/publish-forgejo-release.mjs`, `scripts/ci/lib/immutable-package-guard.mjs` | `[~]` 2026-11-06: reproduced on v1.16.2, v1.16.3 and v1.16.4. **2026-11-14 (`v1.17.1`):** `v1.17.1` (`6c6875b`) also reproduced `write ECONNRESET` at Human Release #339 asset attachment due to Cloudflare ~91 MB proxy limit, while Forgejo generic registry (`1.17.1/latest.yml`, `.sig`, `latest/latest.yml`, `runtime-1.17.1`, `portable-1.17.1`) and public signed-manifest verification completed with HTTP `200`, so installed apps can auto-update cleanly. To retry only this step locally without Cloudflare proxy timeout or check detached tag: check out `v1.17.1` before `npm run release -- --resume`. | -| GAP-REL-17 | Release | 설치된 1.17.1은 자동 업데이트를 정상 확인하지만 공개 피드도 1.17.1이라 1.18.x 제안이 나오지 않았다. 미게시 1.18.1·1.18.2 설치본이 각각 120,821,996·120,821,907 bytes(115.2 MiB)라 100 MiB 업로드 게이트에서 중단됐고, 버전 태그와 원격 피드가 어긋났다. | `apps/desktop/electron-builder.yml`, `scripts/ci/{build-desktop-installer,release-desktop,publish-forgejo-release}.mjs`, `docs/evidence/2026-11-17-backlog-operations.md` | `[~]` 2026-11-20: 원인 재현. 실행 앱·피드·로그가 모두 `1.17.1`이며 kill switch=false, staging=100%다. full-only 시험 108,504,875 bytes도 초과했고 1.18.3은 과거 release를 ASAR에 재귀 포함해 실패했다. `1.18.4`는 `!release/**`·명시적 `out/**/*`, Windows nut-js·다른 플랫폼 SQLite·shared package 중복 제외로 레이아웃을 정상화한다. Windows는 `.blockmap` 대신 최대 압축 전체 설치본을 받는다(`fullInstallVersionGap=0`). 실제 빌드·smoke·서명 공개 피드와 설치본 제안까지 확인한다. | +| GAP-REL-16 | Release | Forgejo release-page asset attachment for the ~91 MB installer timed out through Cloudflare (HTTP 524), although package registry upload and signed manifest succeeded. | `scripts/ci/publish-forgejo-release.mjs`, `scripts/ci/lib/immutable-package-guard.mjs` | `[x]` 2026-11-20: `v1.18.4`(`f77c86d`)의 `104,691,365-byte` 설치본·`latest.yml`·`.sig` Release 첨부가 모두 성공하고 공개 Release 설치본 Range GET도 HTTP 206이다. 과거 1.16.2~1.17.1의 524/ECONNRESET 이력과 달리 현재 경로는 완료했다. 증거: `docs/evidence/2026-11-17-backlog-operations.md`. | +| GAP-REL-17 | Release | 설치된 1.17.1은 자동 업데이트를 정상 확인하지만 공개 피드도 1.17.1이라 1.18.x 제안이 나오지 않았다. 미게시 1.18.1·1.18.2 설치본이 각각 120,821,996·120,821,907 bytes(115.2 MiB)라 100 MiB 업로드 게이트에서 중단됐고, 버전 태그와 원격 피드가 어긋났다. | `apps/desktop/electron-builder.yml`, `scripts/ci/{build-desktop-installer,release-desktop,publish-forgejo-release}.mjs`, `docs/evidence/2026-11-17-backlog-operations.md` | `[~]` 2026-11-20: `1.18.4`(`f77c86d`)는 `!release/**`·명시적 `out/**/*`, source map·미사용 플랫폼 바이너리 제외로 `104,691,365 bytes`가 됐다. Windows는 `.blockmap` 대신 전체 설치본을 받는다(`fullInstallVersionGap=0`). 빌드·native DB·smoke(3 valid/10 negative)·공개 피드·signed manifest·Release 자산 모두 GREEN. `.env` Forgejo token 401은 남아 있고 이번 게시는 유효한 기존 Git credential을 프로세스 메모리에서만 사용했다. **남은 것:** 1.17.1 실제 앱의 설정→정보→업데이트 제안·다운로드·재시작 GUI 확인. | | GAP-INFRA-01 | Build | `apps/mobile-rn` is outside npm workspaces, so root `typecheck`/`test`/`lint` skip it. `typecheck:mobile`/`lint:mobile`/`test:mobile`/`verify:all` root scripts added 2026-09-13 (`package.json`), but membership/CI integration is still open. | `package.json`, `.forgejo/workflows/ci.yml`, `.gitlab-ci.yml` | `[x]` 2026-10-30: React Native Metro/Gradle 네이티브 오토링킹 격리를 위해 `apps/mobile-rn`은 독립 `node_modules`로 유지하고, 루트 `verify:all` 및 `.forgejo/workflows/ci.yml`·`.gitlab-ci.yml`의 `mobile-quality` 잡이 모바일 `lint`·`typecheck`·`test:ci`를 필수 게이트로 실행하도록 정본화했다. **2026-11-04:** root `test:mobile`도 watch-capable 기본 Jest가 아니라 mobile `test:ci`(`jest --runInBand`)를 호출하도록 고정했다. | | GAP-MOB-01 | Legacy | `apps/mobile` Expo skeleton duplicated auth/data code and got version-sync edits. | SSOT G-002 | `[x]` 2026-09-13: deleted `apps/mobile`, removed from `sync-version.mjs` and `package-lock.json`; `version:check` GREEN. | | GAP-INFRA-02 | CI | GitLab admin NAS deploy job is disabled; admin deploy is manual/GHCR. | `.gitlab-ci.yml`, `docs/deployment/nas-deploy-runbook.md` | `[x]` 2026-10-30: 임시 CI DinD 데몬만 바꾸던 구 잡 대신 `docker-compose.nas.yml` 기반의 정본 배포·헬스체크·롤백 절차를 `docs/deployment/nas-deploy-runbook.md`로 문서화하고 `.gitlab-ci.yml` 및 `02-infrastructure.md`에 연결했다. | From 25fd3ac004b8b5fa861203ebefa41528e481dd57 Mon Sep 17 00:00:00 2001 From: Yun Chan Date: Sat, 21 Nov 2026 10:15:49 +0900 Subject: [PATCH 2/3] fix(desktop): add precise local OCR reading --- CHANGELOG.md | 4 + apps/desktop/src/main/screen-ocr-wiring.ts | 4 + .../src/main/services/ScreenOcrService.ts | 54 +++++- .../services/screen-ocr/electron-adapters.ts | 2 + .../screen-ocr/ollama-precision-engine.ts | 165 ++++++++++++++++++ .../services/screen-ocr/precision-output.ts | 11 ++ .../src/renderer/popups/screen-ocr/index.html | 1 + .../src/renderer/popups/screen-ocr/script.js | 25 +++ .../services/ollama-precision-engine.test.ts | 113 ++++++++++++ .../main/services/screen-ocr-service.test.ts | 73 ++++++++ .../evidence/2026-11-17-backlog-operations.md | 44 +++++ docs/map/00-index.md | 4 +- docs/map/02-infrastructure.md | 3 +- docs/map/04-desktop-app.md | 4 +- docs/map/10-feature-catalog.md | 4 +- docs/map/11-gap-backlog.md | 4 +- packages/core/__tests__/screen-ocr.test.ts | 58 ++++++ packages/core/src/screen-ocr.ts | 20 ++- packages/i18n/src/locales/de.json | 4 + packages/i18n/src/locales/en.json | 4 + packages/i18n/src/locales/es.json | 4 + packages/i18n/src/locales/fr.json | 4 + packages/i18n/src/locales/ja.json | 4 + packages/i18n/src/locales/ko.json | 4 + packages/i18n/src/locales/pt.json | 4 + packages/i18n/src/locales/ru.json | 4 + packages/i18n/src/locales/th.json | 4 + packages/i18n/src/locales/vi.json | 4 + packages/i18n/src/locales/zh-TW.json | 4 + packages/i18n/src/locales/zh.json | 4 + 30 files changed, 626 insertions(+), 15 deletions(-) create mode 100644 apps/desktop/src/main/services/screen-ocr/ollama-precision-engine.ts create mode 100644 apps/desktop/src/main/services/screen-ocr/precision-output.ts create mode 100644 apps/desktop/tests/main/services/ollama-precision-engine.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bfd03ae..52e49ea4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Additional Whisper model management UI - Plugin system for custom pipelines +### Fixed +- Screen OCR reconstructs tightly spaced URL, email and punctuation tokens from their pixel positions instead of inserting a space between every recognized word. Ordinary word spacing is preserved; unrecognized glyphs are not guessed or rewritten. +- Add an on-demand precise-reading action to screen OCR. Only the selected crop goes to a loopback GLM-OCR model; the first action downloads about 2.7 GB, original text remains available, and failed, truncated, repeated or cancelled results never replace it. + ## [1.18.4] - 2026-11-20 diff --git a/apps/desktop/src/main/screen-ocr-wiring.ts b/apps/desktop/src/main/screen-ocr-wiring.ts index 4d76638d..a654e9be 100644 --- a/apps/desktop/src/main/screen-ocr-wiring.ts +++ b/apps/desktop/src/main/screen-ocr-wiring.ts @@ -21,6 +21,10 @@ const OVERLAY_STRING_KEYS = [ 'modeRect', 'copy', 'copyLine', + 'precision', + 'workingPrecision', + 'resultPrecision', + 'errorPrecision', 'copyImage', 'saveImage', 'savePdf', diff --git a/apps/desktop/src/main/services/ScreenOcrService.ts b/apps/desktop/src/main/services/ScreenOcrService.ts index e0ef3155..38b46a0d 100644 --- a/apps/desktop/src/main/services/ScreenOcrService.ts +++ b/apps/desktop/src/main/services/ScreenOcrService.ts @@ -8,7 +8,8 @@ // 창 · 파일 · 클립보드 · LLM · TTS 는 전부 포트로 받는다(Electron 어댑터는 screen-ocr/electron-adapters.ts). // // 사생활: 캡처한 그림은 인식에 쓰는 임시 파일 하나로만 디스크에 닿고, 인식이 끝나면 곧바로 지운다. -// 닫으면 메모리의 그림도 놓는다. 어디에도 보내지 않는다(번역·요약은 사용자가 고른 글자만 LLM 으로 간다). +// 닫으면 메모리의 그림도 놓는다. 정밀 읽기는 선택 영역의 그림만 루프백 GLM-OCR로 본다. +// 원격 Ollama는 차단한다. 어디에도 보내지 않는다(번역·요약은 사용자가 고른 글자만 LLM 으로 간다). import { EventEmitter } from 'events' import { randomUUID } from 'crypto' @@ -24,6 +25,8 @@ import { } from '@d3ro/core/screen-ocr' import { getLogger } from './LoggerService' import type { OcrEnginePort } from './screen-ocr/windows-ocr-engine' +import type { PrecisionOcrEnginePort } from './screen-ocr/ollama-precision-engine' +import { isPrecisionOutputWithinBounds, unwrapOcrCodeFence } from './screen-ocr/precision-output' const logger = getLogger('ScreenOcrService') @@ -70,6 +73,7 @@ export interface ScreenOcrFilesPort { export interface ScreenOcrDeps { capture: () => Promise engine: OcrEnginePort + precision: PrecisionOcrEnginePort overlay: ScreenOcrOverlayPort files: ScreenOcrFilesPort /** HTML 파일 → PDF */ @@ -130,6 +134,7 @@ export type ScreenOcrRequest = | { type: 'copy-image'; rect: OcrRect | null } | { type: 'save-image'; rect: OcrRect | null } | { type: 'save-pdf'; rect: OcrRect | null } + | { type: 'refine-text'; text: string; rect: OcrRect | null } | { type: 'translate'; text: string } | { type: 'summarize'; text: string } | { type: 'speak'; text: string } @@ -150,6 +155,7 @@ interface Session { abort: AbortController /** 인식을 다시 돌릴 때마다 올린다 — 늦게 끝난 옛 인식 결과를 버린다 */ recognitionRound: number + precisionPending: boolean /** 이 캡처에서 읽어 주기를 시작했는지 — 닫을 때 그 읽기만 멈춘다(다른 기능의 재생은 건드리지 않는다) */ spoke: boolean } @@ -230,6 +236,7 @@ export class ScreenOcrService extends EventEmitter { result: null, abort: new AbortController(), recognitionRound: 0, + precisionPending: false, spoke: false } this._session = session @@ -373,6 +380,8 @@ export class ScreenOcrService extends EventEmitter { } case 'save-pdf': return this._savePdf(session, request.rect) + case 'refine-text': + return this._refineText(session, request) case 'translate': { const text = this._requireText(request.text).slice(0, SCREEN_OCR_MAX_LLM_CHARS) const target = pickTranslationTarget( @@ -426,6 +435,48 @@ export class ScreenOcrService extends EventEmitter { } } + private async _refineText( + session: Session, + request: Extract + ): Promise<{ ok: true; text: string } | { ok: false; error: ScreenOcrErrorKind }> { + if (session.precisionPending) return { ok: false, error: 'invalid' } + const source = this._requireText(request.text) + const area = this._areaOf(session, request.rect) + const png = area ? session.shot.crop(area) : session.shot.png + session.precisionPending = true + let tempPath: string | null = null + try { + tempPath = await this._deps.files.writeTemp(`${session.id}-precision-${randomUUID()}.png`, png) + session.abort.signal.throwIfAborted() + const raw = (await this._deps.precision.recognize({ + imagePath: tempPath, + signal: session.abort.signal, + maxOutputTokens: Math.min(4096, Math.max(256, Math.ceil(source.length * 2))) + })).replace(/\r\n/gu, '\n').replace(/\n+$/u, '') + if (!isPrecisionOutputWithinBounds(raw, source)) { + throw new D3ROError(ErrorCode.ScreenOcrRecognitionFailed, 'Precision OCR returned an implausibly long result') + } + const text = unwrapOcrCodeFence(raw, source) + if (text.trim().length === 0) { + throw new D3ROError(ErrorCode.ScreenOcrRecognitionFailed, 'Precision OCR returned empty text') + } + return { ok: true, text } + } catch (error) { + if (error instanceof D3ROError) throw error + throw new D3ROError( + ErrorCode.ScreenOcrRecognitionFailed, + `Precision OCR failed: ${error instanceof Error ? error.message : String(error)}` + ) + } finally { + session.precisionPending = false + if (tempPath) { + await this._deps.files.remove(tempPath).catch((error: unknown) => { + logger.warn(`Precision OCR temp file cleanup failed: ${error instanceof Error ? error.message : String(error)}`) + }) + } + } + } + private async _savePdf( session: Session, rect: OcrRect | null @@ -507,6 +558,7 @@ export class ScreenOcrService extends EventEmitter { case 'search-web': return 'link' case 'set-language': + case 'refine-text': return 'recognition' default: return 'export' diff --git a/apps/desktop/src/main/services/screen-ocr/electron-adapters.ts b/apps/desktop/src/main/services/screen-ocr/electron-adapters.ts index 6d557235..f34c187b 100644 --- a/apps/desktop/src/main/services/screen-ocr/electron-adapters.ts +++ b/apps/desktop/src/main/services/screen-ocr/electron-adapters.ts @@ -28,6 +28,7 @@ import type { ScreenShot } from '../ScreenOcrService' import { createWindowsOcrEngine } from './windows-ocr-engine' +import { createOllamaPrecisionOcrEngine } from './ollama-precision-engine' const logger = getLogger('ScreenOcrAdapters') @@ -213,6 +214,7 @@ export function createScreenOcrDeps( return { capture: captureDisplayAtCursor, engine: createWindowsOcrEngine(), + precision: createOllamaPrecisionOcrEngine(), overlay, files: createFilesPort(dialogTitle, guard), renderPdf: renderHtmlFileToPdf, diff --git a/apps/desktop/src/main/services/screen-ocr/ollama-precision-engine.ts b/apps/desktop/src/main/services/screen-ocr/ollama-precision-engine.ts new file mode 100644 index 00000000..bd927fc9 --- /dev/null +++ b/apps/desktop/src/main/services/screen-ocr/ollama-precision-engine.ts @@ -0,0 +1,165 @@ +import { readFile } from 'fs/promises' +import { D3ROError, ErrorCode } from '@d3ro/core/errors' +import { getLocalLLMService } from '../LocalLLMService' +import { getOllamaServerUrl } from '../LocalLLMService' +import { getLogger } from '../LoggerService' +import { readNdjsonLines } from '../../utils/ndjson-reader' + +const MODEL = 'glm-ocr:latest' +const GENERATE_TIMEOUT_MS = 120_000 +const DOWNLOAD_TIMEOUT_MS = 15 * 60_000 +const MAX_OUTPUT_TOKENS = 4096 + +export interface PrecisionOcrRequest { + imagePath: string + signal?: AbortSignal + maxOutputTokens: number +} + +export interface PrecisionOcrEnginePort { + recognize(request: PrecisionOcrRequest): Promise +} + +interface Deps { + serverUrl?: string + model?: string + fetchFn?: typeof fetch + ensureRunning?: () => Promise + readImage?: (path: string) => Promise +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function loopbackOnly(url: string): boolean { + try { + return ['127.0.0.1', 'localhost', '::1', '[::1]'].includes(new URL(url).hostname) + } catch { + return false + } +} + +function timeoutSignal(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal { + return signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) +} + +export function createOllamaPrecisionOcrEngine(deps: Deps = {}): PrecisionOcrEnginePort { + const serverUrl = (deps.serverUrl ?? getOllamaServerUrl()).replace(/\/$/u, '') + const model = deps.model ?? MODEL + const fetchFn = deps.fetchFn ?? fetch + const ensureRunning = deps.ensureRunning ?? (() => getLocalLLMService().ensureRunning()) + const readImage = deps.readImage ?? readFile + const logger = getLogger('OllamaPrecisionOcr') + + const request = async (path: string, init: RequestInit, signal: AbortSignal): Promise => { + try { + return await fetchFn(`${serverUrl}${path}`, { ...init, signal }) + } catch (error) { + throw new D3ROError( + ErrorCode.ScreenOcrRecognitionFailed, + `Local precision OCR request failed: ${error instanceof Error ? error.message : String(error)}` + ) + } + } + + const hasModel = async (signal?: AbortSignal): Promise => { + const response = await request('/api/tags', { method: 'GET' }, timeoutSignal(signal, 10_000)) + if (!response.ok) return false + const body: unknown = await response.json() + if (!isRecord(body) || !Array.isArray(body.models)) return false + return body.models.some((entry) => isRecord(entry) && entry.name === model) + } + + const pullModel = async (signal?: AbortSignal): Promise => { + logger.info(`GLM-OCR 모델 다운로드 시작: ${model}`) + const response = await request( + '/api/pull', + { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ model, stream: true }) + }, + timeoutSignal(signal, DOWNLOAD_TIMEOUT_MS) + ) + if (!response.ok || !response.body) { + throw new D3ROError(ErrorCode.ScreenOcrUnavailable, `GLM-OCR download failed with HTTP ${response.status}`) + } + const reader = response.body.getReader() + const cancel = (): void => { + void reader.cancel().catch(() => undefined) + } + signal?.addEventListener('abort', cancel, { once: true }) + let succeeded = false + try { + for await (const line of readNdjsonLines(reader)) { + if (line.length > 64 * 1024) { + throw new D3ROError(ErrorCode.ScreenOcrRecognitionFailed, 'GLM-OCR download returned an oversized status line') + } + const chunk: unknown = JSON.parse(line) + if (!isRecord(chunk)) continue + if (typeof chunk.error === 'string') { + throw new D3ROError(ErrorCode.ScreenOcrUnavailable, `GLM-OCR download failed: ${chunk.error}`) + } + if (chunk.status === 'success') succeeded = true + } + } finally { + signal?.removeEventListener('abort', cancel) + reader.releaseLock() + } + if (!succeeded) { + throw new D3ROError(ErrorCode.ScreenOcrUnavailable, 'GLM-OCR download ended without success') + } + logger.info('GLM-OCR 모델 다운로드 완료') + } + + return { + async recognize({ imagePath, signal, maxOutputTokens }): Promise { + try { + if (!loopbackOnly(serverUrl)) { + throw new D3ROError( + ErrorCode.ScreenOcrUnavailable, + 'Precision OCR requires a loopback Ollama server so screenshots stay on this PC' + ) + } + await ensureRunning() + if (!(await hasModel(signal))) await pullModel(signal) + const image = await readImage(imagePath) + const numPredict = Math.min(MAX_OUTPUT_TOKENS, Math.max(256, Math.floor(maxOutputTokens))) + const response = await request( + '/api/generate', + { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + model, + prompt: 'Text Recognition:', + images: [image.toString('base64')], + stream: false, + keep_alive: '2m', + options: { temperature: 0, num_ctx: 8192, num_predict: numPredict } + }) + }, + timeoutSignal(signal, GENERATE_TIMEOUT_MS) + ) + if (!response.ok) { + throw new D3ROError(ErrorCode.ScreenOcrRecognitionFailed, `GLM-OCR returned HTTP ${response.status}`) + } + const body: unknown = await response.json() + if (!isRecord(body) || body.done !== true || body.done_reason !== 'stop' || typeof body.response !== 'string') { + throw new D3ROError(ErrorCode.ScreenOcrRecognitionFailed, 'GLM-OCR returned an incomplete or truncated result') + } + if (body.response.trim().length === 0) { + throw new D3ROError(ErrorCode.ScreenOcrRecognitionFailed, 'GLM-OCR returned empty text') + } + return body.response + } catch (error) { + if (error instanceof D3ROError) throw error + throw new D3ROError( + ErrorCode.ScreenOcrRecognitionFailed, + `Precision OCR failed: ${error instanceof Error ? error.message : String(error)}` + ) + } + } + } +} diff --git a/apps/desktop/src/main/services/screen-ocr/precision-output.ts b/apps/desktop/src/main/services/screen-ocr/precision-output.ts new file mode 100644 index 00000000..865794ed --- /dev/null +++ b/apps/desktop/src/main/services/screen-ocr/precision-output.ts @@ -0,0 +1,11 @@ +export function unwrapOcrCodeFence(raw: string, source: string): string { + const lines = raw.split('\n') + if (lines.length < 3 || source.includes('```')) return raw + if (!/^```[A-Za-z0-9_+.-]*$/u.test(lines[0].trim()) || lines[lines.length - 1].trim() !== '```') return raw + const body = lines.slice(1, -1).join('\n') + return body.includes('```') ? raw : body +} + +export function isPrecisionOutputWithinBounds(raw: string, source: string): boolean { + return Array.from(raw).length <= Math.max(4000, Array.from(source).length * 8) +} diff --git a/apps/desktop/src/renderer/popups/screen-ocr/index.html b/apps/desktop/src/renderer/popups/screen-ocr/index.html index 75cadfc8..7053c3ac 100644 --- a/apps/desktop/src/renderer/popups/screen-ocr/index.html +++ b/apps/desktop/src/renderer/popups/screen-ocr/index.html @@ -31,6 +31,7 @@