Compare commits
4 commits
d63854db67
...
f3018f38cb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3018f38cb | ||
|
|
14de596a15 | ||
|
|
fd9c97b7cc | ||
|
|
f5ae4c8c04 |
80 changed files with 2307 additions and 849 deletions
|
|
@ -1,15 +1,13 @@
|
|||
name: release
|
||||
|
||||
# Canonical tag-triggered desktop release built and published on Forgejo.
|
||||
# GitLab CI (.gitlab-ci.yml) is the legacy mirror builder; both converge on
|
||||
# publish-forgejo-release.mjs so the Forgejo feed is the single update source.
|
||||
# 태그(vX.Y.Z) 데스크톱 릴리스 — 로컬 `npm run release` 와 같은 스크립트를 쓰는 예비 경로.
|
||||
# 보통은 로컬 명령이 빌드·게시까지 끝낸 뒤 태그를 푸시하므로, 피드에 이미 그 버전이 있으면 건너뛴다.
|
||||
#
|
||||
# Required repository secrets:
|
||||
# Required repository secrets (npm run release:secrets 로 .env 에서 동기화):
|
||||
# FORGEJO_TOKEN — PAT with write:package + write:repository
|
||||
# WIN_CSC_LINK — base64 Authenticode PFX (public-trust)
|
||||
# WIN_CSC_KEY_PASSWORD — PFX password
|
||||
# WIN_CSC_EXPECTED_SIGNER_SUBJECT — exact certificate subject
|
||||
# Release fails closed when signing material is absent.
|
||||
# D3RO_UPDATE_SIGNING_KEY — latest.yml Ed25519 서명 키 (없으면 게시 실패)
|
||||
# Optional (Authenticode — 있으면 설치본에 서명, 없으면 무서명 + Ed25519 메타데이터 서명):
|
||||
# WIN_CSC_LINK, WIN_CSC_KEY_PASSWORD
|
||||
|
||||
on:
|
||||
push:
|
||||
|
|
@ -37,46 +35,30 @@ jobs:
|
|||
run: |
|
||||
node scripts/ci/sync-version.mjs --check --tag "$env:GITHUB_REF_NAME"
|
||||
|
||||
- name: 이미 게시됐는지 확인
|
||||
id: feed
|
||||
run: |
|
||||
$releaseVersion = node -p "require('./release/product-version.json').version"
|
||||
$url = "https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/$releaseVersion/latest.yml"
|
||||
try { Invoke-WebRequest -Uri $url -Method Get -UseBasicParsing | Out-Null; $published = 'true' } catch { $published = 'false' }
|
||||
"published=$published" >> $env:GITHUB_OUTPUT
|
||||
if ($published -eq 'true') { Write-Host "$releaseVersion 는 이미 피드에 있습니다 — 건너뜁니다." }
|
||||
|
||||
- name: 의존성 설치
|
||||
if: steps.feed.outputs.published != 'true'
|
||||
run: npm ci
|
||||
|
||||
- name: STT 사이드카 빌드 (로컬 전사 엔진)
|
||||
run: |
|
||||
# 로컬 전사는 faster-whisper 사이드카에 의존한다. 이 번들이 빠지면
|
||||
# 설치본에서 전사가 전혀 동작하지 않으므로 패키징 전에 반드시 빌드/검증한다.
|
||||
npm run sidecar:setup --workspace=@d3ro/desktop
|
||||
npm run sidecar:build --workspace=@d3ro/desktop
|
||||
node scripts/ci/verify-sidecar-bundle.mjs
|
||||
|
||||
- name: 데스크톱 빌드 (서명 필수)
|
||||
- name: 설치본 빌드
|
||||
if: steps.feed.outputs.published != 'true'
|
||||
env:
|
||||
WIN_CSC_LINK: "${{ secrets.WIN_CSC_LINK }}"
|
||||
WIN_CSC_KEY_PASSWORD: "${{ secrets.WIN_CSC_KEY_PASSWORD }}"
|
||||
WIN_CSC_EXPECTED_SIGNER_SUBJECT: "${{ secrets.WIN_CSC_EXPECTED_SIGNER_SUBJECT }}"
|
||||
run: |
|
||||
if (-not $env:WIN_CSC_LINK -or -not $env:WIN_CSC_KEY_PASSWORD) {
|
||||
throw "WIN_CSC_LINK / WIN_CSC_KEY_PASSWORD 가 없으면 stable 릴리스를 게시할 수 없습니다."
|
||||
}
|
||||
if ($env:WIN_CSC_EXPECTED_SIGNER_SUBJECT -match '(?i)Everything2EverythingDev') {
|
||||
throw "로컬 개발 인증서는 production 서명 identity가 아닙니다."
|
||||
}
|
||||
npm run build --workspace=@d3ro/desktop
|
||||
node scripts/ci/verify-desktop-renderer-bundles.mjs
|
||||
Push-Location apps/desktop
|
||||
npx electron-builder --win --x64 --config electron-builder.yml --publish never
|
||||
node scripts/ci/verify-native-abi.mjs
|
||||
Pop-Location
|
||||
run: node scripts/ci/build-desktop-installer.mjs
|
||||
|
||||
- name: Windows 산출물 검증
|
||||
env:
|
||||
WIN_CSC_EXPECTED_SIGNER_SUBJECT: "${{ secrets.WIN_CSC_EXPECTED_SIGNER_SUBJECT }}"
|
||||
run: |
|
||||
$releaseVersion = node -p "require('./release/product-version.json').version"
|
||||
& scripts/ci/verify-windows-release-artifact.ps1 -ExpectedVersion $releaseVersion -ExpectedSignerSubject $env:WIN_CSC_EXPECTED_SIGNER_SUBJECT -ReleaseDirectory "apps/desktop/release/$releaseVersion"
|
||||
|
||||
- name: Forgejo 릴리스 + feed 게시
|
||||
- name: Forgejo 피드 게시 (latest.yml Ed25519 서명 + 공개 URL 검증)
|
||||
if: steps.feed.outputs.published != 'true'
|
||||
env:
|
||||
FORGEJO_TOKEN: "${{ secrets.FORGEJO_TOKEN }}"
|
||||
D3RO_UPDATE_SIGNING_KEY: "${{ secrets.D3RO_UPDATE_SIGNING_KEY }}"
|
||||
FORGEJO_REPO: "${{ github.server_url }}/${{ github.repository }}"
|
||||
run: |
|
||||
node scripts/ci/publish-forgejo-release.mjs
|
||||
run: node scripts/ci/publish-forgejo-release.mjs
|
||||
|
|
|
|||
|
|
@ -495,9 +495,8 @@ publish-release:
|
|||
artifacts: false
|
||||
optional: true
|
||||
script:
|
||||
# canonical: Forgejo feed + release hub. legacy mirror: GitLab registry.
|
||||
# canonical: Forgejo feed + release hub (GitLab registry 미러는 2026-10 폐기).
|
||||
- node scripts/ci/publish-forgejo-release.mjs
|
||||
- node scripts/ci/publish-gitlab-release.mjs
|
||||
rules:
|
||||
- if: '$CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+.*$/'
|
||||
|
||||
|
|
|
|||
52
AGENTS.md
52
AGENTS.md
|
|
@ -116,12 +116,27 @@ Full procedure and templates: [`docs/map/12-update-protocol.md`](./docs/map/12-u
|
|||
|
||||
## 6. Update & release system
|
||||
|
||||
Desktop auto-update runs `electron-updater` against the **canonical Forgejo feed**
|
||||
Desktop auto-update runs `electron-updater` against the **Forgejo feed**
|
||||
`https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/latest`.
|
||||
The GitLab project 1172 registry is a **legacy mirror** for pre-Forgejo installs;
|
||||
runtime must never point at it. Full evaluation and 2026 methodology:
|
||||
The installer is unsigned (no Authenticode yet), so `latest.yml` is signed with an
|
||||
**Ed25519 key** and the app verifies the downloaded installer against it before
|
||||
installing (`apps/desktop/src/main/update-signature.ts`). The GitLab registry mirror
|
||||
was retired in 2026-10. Full evaluation:
|
||||
[`docs/deployment/update-system-assessment.md`](./docs/deployment/update-system-assessment.md).
|
||||
|
||||
**To ship a desktop release, run one command on `main` with a clean tree:**
|
||||
|
||||
```bash
|
||||
npm run release -- patch # fix → 1.9.0 → 1.9.1
|
||||
npm run release -- minor # feat → 1.9.0 → 1.10.0
|
||||
npm run release -- --resume # continue after a failed build/publish/push
|
||||
```
|
||||
|
||||
It bumps the version, drafts the CHANGELOG section if missing (write it by hand first
|
||||
for user-facing notes), runs the gates, commits + tags, builds, signs, publishes,
|
||||
re-verifies the public feed, then pushes. Existing installs pick it up on their next
|
||||
check (15 s after launch, then every 4 h).
|
||||
|
||||
These files move together and are enforced by `npm run release:metadata:test`:
|
||||
|
||||
| Concern | SSOT |
|
||||
|
|
@ -130,8 +145,10 @@ These files move together and are enforced by `npm run release:metadata:test`:
|
|||
| builder publish URL | `apps/desktop/electron-builder.yml` |
|
||||
| update policy (channels, min version, force, delta/full, rollout, kill switch) | `release/update-policy.json` |
|
||||
| policy runtime logic | `apps/desktop/src/main/update-policy.ts` |
|
||||
| canonical publisher | `scripts/ci/publish-forgejo-release.mjs` |
|
||||
| legacy mirror publisher | `scripts/ci/publish-gitlab-release.mjs` |
|
||||
| one-command release | `scripts/ci/release-desktop.mjs` (`npm run release`) |
|
||||
| installer build | `scripts/ci/build-desktop-installer.mjs` |
|
||||
| publisher (sign + upload + verify) | `scripts/ci/publish-forgejo-release.mjs` |
|
||||
| update signing key | `.env` `D3RO_UPDATE_SIGNING_KEY` (private) · `release/desktop-update-public.pem` == `update-signature.ts` |
|
||||
| version SSOT | `release/product-version.json` |
|
||||
|
||||
Rules:
|
||||
|
|
@ -139,8 +156,12 @@ Rules:
|
|||
- **Tag-only, immutable releases.** Publish runs only on annotated `vX.Y.Z` tags.
|
||||
Tags are never moved or deleted; a bad release is fixed forward with a higher
|
||||
patch. Same-version re-release is forbidden by SemVer.
|
||||
- **Feed contract.** `UPDATE_FEED_URL` == builder `publish.url` == canonical
|
||||
Forgejo URL. `LEGACY_UPDATE_FEED_URL` must stay the GitLab mirror.
|
||||
- **Feed contract.** `UPDATE_FEED_URL` == builder `publish.url` == Forgejo URL.
|
||||
The app verifies against the immutable `<version>/latest.yml` + `.sig`, never the
|
||||
mutable `latest` alias.
|
||||
- **Never rotate or lose the update signing key.** Installs that embed its public key
|
||||
reject releases signed by any other key; the only recovery is a manual reinstall.
|
||||
Back up `.env`.
|
||||
- **Version discipline.** SemVer: `feat`=MINOR, `fix`=PATCH, breaking=MAJOR. Run
|
||||
`npm run version:sync` when syncing surfaces; `npm run version:check` must be clean.
|
||||
- **Channels.** `latest` (stable), `beta`, `alpha`. Stable clients never receive a
|
||||
|
|
@ -150,15 +171,16 @@ Rules:
|
|||
full installer instead of a blockmap delta (`fullInstallOnMajorChange`,
|
||||
`fullInstallVersionGap`). `stagingPercentage` limits rollout; `killSwitch` stops
|
||||
update checks remotely.
|
||||
- **Secrets stay fail-closed.** Every publisher needs `FORGEJO_TOKEN`
|
||||
(`write:package` + `write:repository`). Desktop releases additionally require the
|
||||
`WIN_CSC_*` Authenticode material; missing signing data must fail the pipeline.
|
||||
- **Secrets stay fail-closed.** Publishing needs `FORGEJO_TOKEN`
|
||||
(`write:package` + `write:repository`) and `D3RO_UPDATE_SIGNING_KEY`; a missing or
|
||||
mismatched signing key fails before any upload. `WIN_CSC_*` Authenticode material is
|
||||
optional — when present electron-builder also signs the installer.
|
||||
- **CI is the backup path.** `.forgejo/workflows/release.yml` runs on the pushed tag
|
||||
with the same build/publish scripts and skips when the feed already has the version
|
||||
(the normal case after `npm run release`). Sync secrets with `npm run release:secrets`.
|
||||
|
||||
Commands: `npm run release:metadata`, `npm run release:metadata:test`,
|
||||
`npm run release:forgejo:check`, `npm run release:tag -- --dry-run` (then
|
||||
`npm run release:tag`, then `git push origin vX.Y.Z`). Use `--sign` when GPG is
|
||||
configured; tags are annotated and immutable. Locally, `npm run release:forgejo:local`
|
||||
loads `FORGEJO_TOKEN` from `.env` (gitignored); CI reads the secret from its store.
|
||||
Other commands: `npm run release -- minor --dry-run`, `npm run release:build`,
|
||||
`npm run release:metadata:test`, `npm run release:forgejo:check`.
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
35
CHANGELOG.md
35
CHANGELOG.md
|
|
@ -12,6 +12,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
- Additional Whisper model management UI
|
||||
- Plugin system for custom pipelines
|
||||
|
||||
## [1.10.0] - 2026-10-18
|
||||
|
||||
> Published from an annotated tag. Installer and update metadata are served by the
|
||||
> canonical Forgejo feed; no binaries are committed to this repository.
|
||||
|
||||
### Added
|
||||
- **Typo auto-correct and sentence prediction while you type.** D3RO suggests how your
|
||||
sentence continues based on the surrounding document or conversation. With
|
||||
suggestions on, typo fixes appear in the same popup and are applied only when you
|
||||
accept the suggestion.
|
||||
- **A redesigned app.** Home, records and meetings come first, and the whole interface
|
||||
uses a calmer, flatter look.
|
||||
- **Unified search** across your records, meetings and memos.
|
||||
- **Esc cancels dictation**, and the dictation popups now show what is really happening.
|
||||
- **Updates are verified before they install.** The update file is checked against a
|
||||
signature, so a tampered download is refused.
|
||||
|
||||
### Changed
|
||||
- Suggestions appear right after you pause instead of mid-typing, stay put while you
|
||||
pick one, and also work in terminals.
|
||||
- Pasting is faster: the 300 ms key delay is gone and every clipboard format is
|
||||
restored after a paste.
|
||||
- Local models are no longer pinned in memory, so the app uses less RAM when idle.
|
||||
|
||||
### Fixed
|
||||
- Speech recognition falls back to the CPU when the GPU runtime cannot be used.
|
||||
- File transcription no longer fails on clean installs because ffmpeg was missing.
|
||||
- Clicking the recording tip cancels the recording; the Sound switch applies at once.
|
||||
- Meeting transcript edits are kept, and the live recording view comes back after
|
||||
switching screens.
|
||||
- Clearing all history now asks for confirmation.
|
||||
- Keyboard shortcuts no longer steal key combinations from other apps on Windows.
|
||||
- Offline license keys survive restarts and cloud sign-out.
|
||||
- Many sync, quota, billing and security fixes from a third security review.
|
||||
|
||||
## [1.9.0] - 2026-09-27
|
||||
|
||||
> Published from an annotated tag. Installer and update metadata are served by the
|
||||
|
|
|
|||
13
CLAUDE.md
13
CLAUDE.md
|
|
@ -44,12 +44,13 @@ Phase 1~15.5 전체 완료 + 랜딩 페이지(site/).
|
|||
차단 이슈: @nut-tree-fork/nut-js 포크 사용
|
||||
|
||||
## 업데이트 / 릴리스
|
||||
자동 업데이트는 electron-updater + **canonical Forgejo feed**
|
||||
(`git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/latest`). GitLab project 1172은
|
||||
legacy mirror다. 채널·최소 지원 버전·강제 업데이트·증분/전체·staged rollout·킬 스위치는
|
||||
`release/update-policy.json`이 정본이다. 릴리스는 annotated `vX.Y.Z` 태그에서만 게시하며
|
||||
태그는 불변이다. 규칙은 `AGENTS.md` §6, 평가·방법론은
|
||||
`docs/deployment/update-system-assessment.md` 참조.
|
||||
자동 업데이트는 electron-updater + Forgejo feed
|
||||
(`git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/latest`). 설치본은 무서명이라
|
||||
latest.yml 을 Ed25519 로 서명하고 앱이 받은 설치 파일을 검증한다(`update-signature.ts`).
|
||||
**릴리스 = `npm run release -- patch|minor` 한 줄** (main, 깨끗한 트리, .env 의 FORGEJO_TOKEN ·
|
||||
D3RO_UPDATE_SIGNING_KEY). 실패하면 `npm run release -- --resume`. 채널·최소 지원 버전·
|
||||
강제 업데이트·rollout·킬 스위치는 `release/update-policy.json`이 정본. 태그는 불변.
|
||||
규칙은 `AGENTS.md` §6.
|
||||
|
||||
## 설계 문서 (구현 시 Read 도구로 참조)
|
||||
- docs/design/00-master-architecture.md — 시스템 아키텍처, 초기화/종료, 서비스 목록
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
"info": {
|
||||
"title": "D3RO-VOICE Admin API",
|
||||
"description": "Admin CRM Edge Functions for user management, subscription CRUD, payment history, and audit logs.",
|
||||
"version": "1.9.0"
|
||||
"version": "1.10.0"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/admin",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice Admin CRM — SaaS 관리 도구",
|
||||
"scripts": {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Version>1.9.0</Version>
|
||||
<Version>1.10.0</Version>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/desktop",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"productName": "d3ro-voice",
|
||||
"description": "로컬 AI 음성 어시스턴트 (Electron)",
|
||||
"main": "./out/main/index.js",
|
||||
|
|
@ -58,7 +58,7 @@
|
|||
"drizzle-orm": "^0.45.2",
|
||||
"electron-log": "^5.2.0",
|
||||
"electron-store": "^10.0.0",
|
||||
"electron-updater": "^6.3.9",
|
||||
"electron-updater": "^6.8.10",
|
||||
"koffi": "^3.3.1",
|
||||
"lucide-react": "^1.25.0",
|
||||
"overlayscrollbars": "^2.16.0",
|
||||
|
|
|
|||
|
|
@ -235,7 +235,14 @@ async function initInputIntelligence(): Promise<void> {
|
|||
typo.on('corrected', () => {
|
||||
if (suggestion.isPresentationActive) suggestion.dismiss('stale')
|
||||
})
|
||||
// 제안이 켜져 있으면 오타를 조용히 고치지 않고 제안 창에 "지운 글자 → 고친 글자" 로 함께 내놓는다
|
||||
// (수락할 때만 적용 — 2026-10-17 사용자 요청). 제안이 꺼져 있을 때만 위 자동 교정이 돈다.
|
||||
suggestion.setTypoProposer({ propose: (context, signal, options) => typo.propose(context, signal, options) })
|
||||
telemetry.on('typed-context', (context) => {
|
||||
if (suggestion.isEnabled()) {
|
||||
suggestion.handleTypingContext(context)
|
||||
return
|
||||
}
|
||||
const verdict = typo.handleTypingContext(context)
|
||||
if (verdict === 'pass') suggestion.handleTypingContext(context)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -58,7 +58,7 @@ export function registerSuggestionHandlers(): void {
|
|||
configSet('suggestionMinPrefixChars', clamp(params.minPrefixChars, 4, 40))
|
||||
}
|
||||
if (params.maxRequestsPerMinute !== undefined) {
|
||||
configSet('suggestionMaxRequestsPerMinute', clamp(params.maxRequestsPerMinute, 1, 12))
|
||||
configSet('suggestionMaxRequestsPerMinute', clamp(params.maxRequestsPerMinute, 1, 30))
|
||||
}
|
||||
if (params.dailyBudget !== undefined) {
|
||||
configSet('suggestionDailyBudget', clamp(params.dailyBudget, 1, 100000))
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ import { getLogger } from './LoggerService'
|
|||
const logger = getLogger('ConfigService')
|
||||
|
||||
/** 제안/텔레메트리 튜닝 기본값의 현재 개정판. 기본값을 바꾸면 올린다. */
|
||||
const SUGGESTION_TUNING_REVISION = 6
|
||||
const SUGGESTION_TUNING_REVISION = 7
|
||||
|
||||
const INITIAL_SUGGESTION_TUNING = {
|
||||
suggestionTriggerDelayMs: 300,
|
||||
|
|
@ -62,6 +62,12 @@ function migrateSuggestionTuning(activeStore: ElectronStore<AppConfig>): void {
|
|||
if (!Number.isFinite(delay) || delay < 500) activeStore.set('suggestionTriggerDelayMs', 600)
|
||||
}
|
||||
|
||||
// 분당 6회는 로컬 모델(첫 후보 0.8초)에 너무 빡빡했다 — 고르고 이어 친 뒤 멈추면 rate-limited 로 안 떴다.
|
||||
if (current < 7) {
|
||||
const perMinute = Number(raw.suggestionMaxRequestsPerMinute)
|
||||
if (!Number.isFinite(perMinute) || perMinute < 20) activeStore.set('suggestionMaxRequestsPerMinute', 20)
|
||||
}
|
||||
|
||||
activeStore.set('suggestionTuningRevision', SUGGESTION_TUNING_REVISION)
|
||||
logger.info(
|
||||
`Migrated suggestion tuning values to revision ${SUGGESTION_TUNING_REVISION}`
|
||||
|
|
@ -210,7 +216,7 @@ const CONFIG_DEFAULTS: AppConfig = {
|
|||
// 기본값 정본: packages/core/src/input-intelligence.ts SUGGESTION_DEFAULTS
|
||||
suggestionTriggerDelayMs: 600,
|
||||
suggestionMinPrefixChars: 8,
|
||||
suggestionMaxRequestsPerMinute: 6,
|
||||
suggestionMaxRequestsPerMinute: 20,
|
||||
suggestionDailyBudget: 500,
|
||||
suggestionOverlayInteractive: true,
|
||||
suggestionRequestTimeoutMs: 8000,
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import { sql, gte, eq, desc, inArray } from 'drizzle-orm'
|
|||
import {
|
||||
INPUT_TELEMETRY_DEFAULTS,
|
||||
SUGGESTION_CONTEXT_MAX_CHARS,
|
||||
COMPOSING_IDLE_MULTIPLIER,
|
||||
SUGGESTION_DEFAULTS,
|
||||
calculateFrictionInsight,
|
||||
classifyKeyStroke,
|
||||
|
|
@ -637,9 +638,11 @@ class InputTelemetryService extends EventEmitter {
|
|||
// 제안이 영원히 요청되지 않는다(실측: debounce 로그만 반복). 그래서
|
||||
// 트리거 지연을 넘긴 시점에 한 번 더 스냅샷을 돌려 게이트를 연다.
|
||||
if (this._settleTimer) clearTimeout(this._settleTimer)
|
||||
// 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔
|
||||
// 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측 2026-10-17: "빠릿하지 않다").
|
||||
const settleDelay = Math.max(
|
||||
INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 300,
|
||||
(configGet('suggestionTriggerDelayMs') || 1000) + 400
|
||||
INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 50,
|
||||
Math.ceil((configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) * COMPOSING_IDLE_MULTIPLIER) + 60
|
||||
)
|
||||
this._settleTimer = setTimeout(() => {
|
||||
this._settleTimer = null
|
||||
|
|
@ -738,8 +741,9 @@ class InputTelemetryService extends EventEmitter {
|
|||
context.editedSinceFocus = textForFocus !== this._textAtFocus || this._typedIntoFocus
|
||||
|
||||
// 보내면 비워지는 칸(채팅)의 직전 내용을 "이 창에서 조금 전에 쓴 글" 로 잠시 기억한다.
|
||||
// 비밀번호·편집 불가·조합 중 칸과 터미널(명령 기록)은 보지 않는다.
|
||||
if (snapshot.isEditable && !snapshot.isPassword && !snapshot.isComposing && !isTerminalApp(this._foreground.appName)) {
|
||||
// 비밀번호·편집 불가 칸과 터미널(명령 기록)은 보지 않는다. 조합 중인 칸도 본다 — 한글은 보내기 직전
|
||||
// 스냅샷이 거의 늘 조합 중이라, 빼면 보낸 글이 하나도 기억되지 않았다(실측 2026-10-17 에이전트 창 comp=true 연속).
|
||||
if (snapshot.isEditable && !snapshot.isPassword && !isTerminalApp(this._foreground.appName)) {
|
||||
this._recentWrites.observe(
|
||||
focusKey,
|
||||
snapshot.text,
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
|
||||
import { EventEmitter } from 'events'
|
||||
import {
|
||||
COMPOSING_IDLE_MULTIPLIER,
|
||||
SUGGESTION_DEFAULTS,
|
||||
SUGGESTION_MAX_OUTPUT_CHARS,
|
||||
buildLocalSuggestionCandidateEntries,
|
||||
|
|
@ -33,6 +34,7 @@ import {
|
|||
type AnchorKind,
|
||||
type PhysicalRect,
|
||||
type SuggestionCandidate,
|
||||
type SuggestionCorrection,
|
||||
type SuggestionPolicyInput,
|
||||
type SuggestionProvenance,
|
||||
type SuggestionSkipReason,
|
||||
|
|
@ -76,6 +78,31 @@ export interface SuggestionLearningPort {
|
|||
expectProgrammaticInsert(text: string): () => void
|
||||
/** 수락한 문장을 사용자 문체 표본으로 기록한다 (학습 동의 시에만 저장됨). */
|
||||
recordAccepted(text: string, meta: { appName: string | null; windowTitle: string | null }): void
|
||||
/** 곧 보낼 프로그램 키 수(교정 수락의 백스페이스 등) — 입력 통계에서 뺀다. */
|
||||
expectProgrammaticKeys?(count: number): void
|
||||
}
|
||||
|
||||
/**
|
||||
* 제안과 함께 내놓을 오타 교정을 만드는 포트 (TypoCorrectionService.propose — bootstrap 이 연결한다).
|
||||
* 커서 앞 원문 끝의 originalText 를 insertText 로 바꾸는 계획을 돌려준다.
|
||||
*/
|
||||
export interface SuggestionTypoProposer {
|
||||
propose(
|
||||
context: TypingContext,
|
||||
signal: AbortSignal,
|
||||
options?: { thorough?: boolean }
|
||||
): Promise<{ originalText: string; insertText: string; corrections: Array<{ start: number; end: number; to: string }> } | null>
|
||||
}
|
||||
|
||||
/** 교정을 적용한 문맥 — 모델에는 고친 글을 보여 주고, 세션 비교는 원문으로 한다. */
|
||||
function applyCorrectionToContext(context: TypingContext, correction: SuggestionCorrection): TypingContext {
|
||||
const replaceTail = (text: string): string =>
|
||||
text.endsWith(correction.from) ? text.slice(0, text.length - correction.from.length) + correction.to : text
|
||||
return {
|
||||
...context,
|
||||
prefix: replaceTail(context.prefix),
|
||||
documentBefore: context.documentBefore == null ? context.documentBefore : replaceTail(context.documentBefore)
|
||||
}
|
||||
}
|
||||
|
||||
/** 서비스 협력자 — 기본값은 getSuggestionService() 가 연결한다 (DIP). */
|
||||
|
|
@ -98,6 +125,7 @@ export function createDefaultSuggestionServiceDeps(): SuggestionServiceDeps {
|
|||
},
|
||||
learning: {
|
||||
expectProgrammaticInsert: (text) => getInputTelemetryService().expectProgrammaticInsert(text),
|
||||
expectProgrammaticKeys: (count) => getInputTelemetryService().expectProgrammaticKeys(count),
|
||||
recordAccepted: (text, meta) =>
|
||||
getInputTelemetryService().recordExternalText(text, { ...meta, source: 'suggestion' })
|
||||
}
|
||||
|
|
@ -205,6 +233,14 @@ interface ModelRequest {
|
|||
parse(raw: string): { candidate: SuggestionCandidate | null; rejected: string | null }
|
||||
/** 스트리밍 중간 표시용 텍스트 */
|
||||
partial(raw: string): string
|
||||
/**
|
||||
* 빈 출력일 때 다시 보낼 변형 — prefill 끝에 공백을 붙여 "다음 단어부터" 쓰게 한다.
|
||||
*
|
||||
* 실측(2026-10-17, gemma4:e4b): "…잠시 쉬면", "…창이 나왔다가" 처럼 공백 없이 문장 중간에서 끝난
|
||||
* prefill 은 모델이 곧바로 턴을 닫아 빈 출력이 됐다(첫 후보 18회 중 15회). 끝에 공백 하나를 붙이면
|
||||
* 4문장 모두 이어 썼다. 출력 앞에 공백을 되돌려 붙여 해석하므로 이음새는 '띄어 쓰기' 가 된다.
|
||||
*/
|
||||
spaced?: ModelRequest
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -281,6 +317,24 @@ export class SuggestionService extends EventEmitter {
|
|||
private _windowHandle: number | null = null
|
||||
/** 이 세션의 이력 행 id — 한 세션은 한 행이다(채우기 후보·수락은 이 행을 갱신한다). */
|
||||
private _sessionRecordId: string | null = null
|
||||
/** 이 세션 후보가 함께 적용하는 오타 교정 */
|
||||
private _correction: SuggestionCorrection | null = null
|
||||
/** 모델에 보여 준 (교정 적용) 문맥 — 채우기 루프가 같은 문맥으로 더 만든다 */
|
||||
private _promptContext: TypingContext | null = null
|
||||
private _typoProposer: SuggestionTypoProposer | null = null
|
||||
/** 이 세션 첫 후보가 "공백 붙인 prefill" 로 나왔다 — 채우기도 그 변형으로 보낸다 */
|
||||
private _spacedPreferred = false
|
||||
/**
|
||||
* 첫 후보를 못 만든 접두 — 같은 글로 멈춰 있는 동안 다시 생성하지 않는다. 실패할 때마다 다음 스냅샷이
|
||||
* 같은 글로 또 생성해 "생성 중" 창이 1초마다 떴다 꺼졌다(실측 2026-10-17).
|
||||
*/
|
||||
private _failedPrefix = ''
|
||||
/**
|
||||
* 손을 멈추자마자 먼저 띄운 "생성 중" 자리 — 생성은 아직 시작 전이다. 정책의 "표시 중"(already-visible)
|
||||
* 에는 넣지 않는다: 넣으면 정작 생성 시점에 이미 떠 있다고 보고 생성하지 않는다.
|
||||
*/
|
||||
private _pending = false
|
||||
private _pendingTimer: NodeJS.Timeout | null = null
|
||||
|
||||
/** 요청 예산 (간격 · 분/일 카운트 · 실패 쿨다운) */
|
||||
private readonly _budget: SuggestionBudget
|
||||
|
|
@ -389,7 +443,7 @@ export class SuggestionService extends EventEmitter {
|
|||
modelId: this.resolveModel(),
|
||||
modelAvailable: getLocalLLMService().isAvailable(),
|
||||
visible: this.isVisible,
|
||||
generating: this._generating,
|
||||
generating: this._generating || this._pending,
|
||||
warmingUp: this._warmingUp,
|
||||
partialText: this._partialText || null,
|
||||
candidates: [...this._candidates],
|
||||
|
|
@ -411,10 +465,16 @@ export class SuggestionService extends EventEmitter {
|
|||
telemetryEnabled: configGet('inputTelemetryEnabled') === true,
|
||||
overlayInteractive: configGet('suggestionOverlayInteractive') !== false,
|
||||
typoAutoCorrect: configGet('typoAutoCorrectEnabled') !== false,
|
||||
provenance: this._provenance
|
||||
provenance: this._provenance,
|
||||
correction: this._correction
|
||||
}
|
||||
}
|
||||
|
||||
/** 제안 창에 오타 교정을 함께 내놓을 포트를 연결한다 (bootstrap). null 이면 교정 없이 제안만 한다. */
|
||||
setTypoProposer(proposer: SuggestionTypoProposer | null): void {
|
||||
this._typoProposer = proposer
|
||||
}
|
||||
|
||||
/** 제안 전용 모델 (설정 없으면 기본 LLM 모델). */
|
||||
resolveModel(): string | null {
|
||||
const dedicated = configGet('suggestionModelId')
|
||||
|
|
@ -605,9 +665,76 @@ export class SuggestionService extends EventEmitter {
|
|||
// 서버가 없을 때 "준비 중" 은 실제 준비 작업(워밍업 루프)이 돌 때만 보여준다.
|
||||
modelStarting: this._warmUpPromise !== null
|
||||
})
|
||||
if (step.action === 'generate' && this._failedPrefix && step.prefix === this._failedPrefix) {
|
||||
// 방금 이 글로 첫 후보를 못 만들었다 — 더 치기 전까지 같은 생성을 되풀이하지 않는다(창 깜빡임 방지).
|
||||
this._lastSkipReason = 'unchanged'
|
||||
this._clearPending(true)
|
||||
return
|
||||
}
|
||||
this._updatePresence(step, context, now)
|
||||
this._executeStep(step, context, config, now)
|
||||
}
|
||||
|
||||
/**
|
||||
* 손을 멈춘 순간(presenceDelayMs) "생성 중" 자리를 먼저 띄운다 — 생성은 트리거 지연 뒤에 시작한다.
|
||||
* 곧 생성으로 이어질 때만 띄운다(예산·모델 온기·닫기 직후·실패한 같은 글 확인). 다시 치면 거둔다.
|
||||
*/
|
||||
private _updatePresence(step: SuggestionStep, context: TypingContext, now: number): void {
|
||||
if (step.action === 'generate') {
|
||||
this._clearPending(false)
|
||||
return
|
||||
}
|
||||
const waiting = step.action === 'settle' && (step.reason === 'debounce' || step.reason === 'composing')
|
||||
if (
|
||||
waiting &&
|
||||
context.idleMs >= SUGGESTION_DEFAULTS.presenceDelayMs &&
|
||||
!this.isPresentationActive &&
|
||||
this._willGenerateSoon(context, now)
|
||||
) {
|
||||
if (!this._pending) this._showPending(context)
|
||||
return
|
||||
}
|
||||
this._clearPending(true)
|
||||
}
|
||||
|
||||
private _willGenerateSoon(context: TypingContext, now: number): boolean {
|
||||
const model = this.resolveModel()
|
||||
if (!model || !this._warmth.isWarm(model, now) || this._budget.isCoolingDown(now)) return false
|
||||
if (now < this._userDismissedUntil) return false
|
||||
const prefix = normalizeRequestPrefix(context.prefix)
|
||||
if (prefix === this._failedPrefix || prefix === this._lastRequestedPrefix) return false
|
||||
const config = this.readPolicyConfig()
|
||||
const budget = this._budget.snapshot(now)
|
||||
// 생성은 조금 뒤(트리거 지연)에 시작한다 — 그때까지 흐를 시간을 쳐서 간격을 본다.
|
||||
const untilGenerate = Math.max(0, config.triggerDelayMs * COMPOSING_IDLE_MULTIPLIER - context.idleMs)
|
||||
return (
|
||||
budget.sinceLastRequestMs + untilGenerate >= SUGGESTION_DEFAULTS.minIntervalMs &&
|
||||
budget.requestsThisMinute < config.maxRequestsPerMinute &&
|
||||
budget.requestsToday < config.dailyBudget
|
||||
)
|
||||
}
|
||||
|
||||
private _showPending(context: TypingContext): void {
|
||||
this._pending = true
|
||||
this._anchor = context.anchor
|
||||
this._anchorKind = context.anchorKind
|
||||
this._appName = context.appName
|
||||
if (this._pendingTimer) clearTimeout(this._pendingTimer)
|
||||
this._pendingTimer = setTimeout(() => this._clearPending(true), SUGGESTION_DEFAULTS.presenceMaxMs)
|
||||
this._pendingTimer.unref?.()
|
||||
this.emit('updated', this.getState())
|
||||
}
|
||||
|
||||
private _clearPending(notify: boolean): void {
|
||||
if (this._pendingTimer) {
|
||||
clearTimeout(this._pendingTimer)
|
||||
this._pendingTimer = null
|
||||
}
|
||||
if (!this._pending) return
|
||||
this._pending = false
|
||||
if (notify && !this.isPresentationActive) this.emit('updated', this.getState())
|
||||
}
|
||||
|
||||
private _executeStep(step: SuggestionStep, context: TypingContext, config: PolicyConfig, now: number): void {
|
||||
switch (step.action) {
|
||||
case 'end-session':
|
||||
|
|
@ -877,9 +1004,9 @@ export class SuggestionService extends EventEmitter {
|
|||
* 미리 넣어 그 글자 바로 뒤부터 쓰게 한다. 모르는 모델이면 예전 지시형 프롬프트를 쓴다.
|
||||
* 두 경로 모두 같은 문맥(문서 첫머리·사실, 이 창의 앞 글, 개인 그래프)을 받는다.
|
||||
*
|
||||
* `preferInstruct`: 다음 문장 모드의 채우기 후보는 지시형을 섞는다. prefill 은 분포가 뾰족해
|
||||
* 온도를 올려도 첫 후보와 같은 문장이 반복됐고, 지시형은 "이미 제안한 문장" 목록을 따라 다른
|
||||
* 내용을 낸다(실측). 마저 쓰기 모드에서는 지시형이 새 문장을 시작해 버려 섞지 않는다.
|
||||
* 채우기 후보도 prefill 로만 만든다. 예전엔 다양성을 위해 다음 문장 모드에서 지시형을 섞었는데,
|
||||
* 지시형 gemma 는 사용자 글에 "대답" 했다(실측 2026-10-17 이력: "혹시 어떤 기능을 염두에 두고 계신지
|
||||
* 설명해 주실 수 있을까요?" — 사용자 신고 "내가 쓴 것에 대한 응답만 나온다"). 후보가 덜 다양한 편이 낫다.
|
||||
*/
|
||||
private _buildModelRequest(
|
||||
model: string,
|
||||
|
|
@ -887,7 +1014,7 @@ export class SuggestionService extends EventEmitter {
|
|||
context: TypingContext,
|
||||
memory: LocalMemoryContext,
|
||||
maxChars: number,
|
||||
options: { avoidCandidates?: readonly string[]; preferInstruct?: boolean } = {}
|
||||
options: { avoidCandidates?: readonly string[] } = {}
|
||||
): ModelRequest {
|
||||
const now = Date.now()
|
||||
const recentWrites = getInputTelemetryService()
|
||||
|
|
@ -919,8 +1046,7 @@ export class SuggestionService extends EventEmitter {
|
|||
assistantPrefix: prompt.assistantPrefix ?? ''
|
||||
})
|
||||
|
||||
const instruct = options.preferInstruct === true && prompt.writing.mode === 'next-sentence'
|
||||
if (rawPrompt !== null && !instruct) {
|
||||
if (rawPrompt !== null) {
|
||||
const written = splitSentences(context.documentBefore ?? prefix)
|
||||
const extract = (raw: string) =>
|
||||
extractContinuation(raw, {
|
||||
|
|
@ -931,10 +1057,35 @@ export class SuggestionService extends EventEmitter {
|
|||
allowEmoji: prompt.allowEmoji,
|
||||
maxChars
|
||||
})
|
||||
const parse = (raw: string): { candidate: SuggestionCandidate | null; rejected: string | null } => {
|
||||
const continuation = extract(raw)
|
||||
if (!continuation) return { candidate: null, rejected: 'empty' }
|
||||
// 원문·창 제목·앞 글·개인 힌트 어디에도 없는 날짜·이름·숫자 = 지어낸 사실. 수락하면 글에 박힌다.
|
||||
const unsupported = findUnsupportedFacts(continuation.text, prompt.factSource)
|
||||
if (unsupported.length > 0) return { candidate: null, rejected: `unsupported-facts:${unsupported.join('/')}` }
|
||||
return {
|
||||
candidate:
|
||||
continuation.joint === 'attach'
|
||||
? { text: continuation.text, rank: 0, joint: 'attach' }
|
||||
: { text: continuation.text, rank: 0 },
|
||||
rejected: null
|
||||
}
|
||||
}
|
||||
const stop = rawChatStopSequences(model)
|
||||
const endsWithSpace = /\s$/u.test(prompt.assistantPrefix ?? '')
|
||||
return {
|
||||
prompt: rawPrompt,
|
||||
raw: true,
|
||||
stop: rawChatStopSequences(model),
|
||||
stop,
|
||||
spaced: endsWithSpace
|
||||
? undefined
|
||||
: {
|
||||
prompt: `${rawPrompt} `,
|
||||
raw: true,
|
||||
stop,
|
||||
parse: (raw) => parse(` ${raw}`),
|
||||
partial: (raw) => extract(` ${raw}`)?.text ?? ''
|
||||
},
|
||||
parse: (raw) => {
|
||||
const continuation = extract(raw)
|
||||
if (!continuation) return { candidate: null, rejected: 'empty' }
|
||||
|
|
@ -1029,6 +1180,8 @@ export class SuggestionService extends EventEmitter {
|
|||
this._candidates = entries.map((entry, index) =>
|
||||
entry.attachToPrefix ? { text: entry.text, rank: index, joint: 'attach' } : { text: entry.text, rank: index }
|
||||
)
|
||||
this._correction = null
|
||||
this._promptContext = null
|
||||
this._activeIndex = 0
|
||||
this._anchor = context.anchor
|
||||
this._anchorKind = context.anchorKind
|
||||
|
|
@ -1118,6 +1271,8 @@ export class SuggestionService extends EventEmitter {
|
|||
// 후보가 오기 전에 빈 화면으로 기다리게 하지 않는다 — 즉시 자리를 잡고
|
||||
// "생성 중" 을 보여준 뒤 내용으로 채운다. 실측 5초 지연에서 특히 중요하다.
|
||||
this._candidates = []
|
||||
this._correction = null
|
||||
this._promptContext = null
|
||||
this._sessionRecordId = null
|
||||
this._activeIndex = 0
|
||||
this._anchor = context.anchor
|
||||
|
|
@ -1142,19 +1297,35 @@ export class SuggestionService extends EventEmitter {
|
|||
|
||||
// 개인 그래프 문맥: (1) 과거에 그 꼬리 뒤에 실제로 이어 쓴 문장,
|
||||
// (2) follows/용어공유 관계로 끌어온 관련 문장.
|
||||
const memory = this._collectMemoryHints(trimmedPrefix, context.appName)
|
||||
const continuationHints = memory.continuationHints
|
||||
// 세션의 첫 요청은 딱 1개만 청한다 — 한꺼번에 여러 개를 요청하면 느리다(사용자
|
||||
// 요청). 첫 후보를 보여준 뒤 나머지는 채우기 루프가 하나씩 순차로 더 만든다.
|
||||
const request = this._buildModelRequest(model, trimmedPrefix, context, memory, maxChars)
|
||||
let memory = this._collectMemoryHints(trimmedPrefix, context.appName)
|
||||
let spacedPreferred = false
|
||||
let correction: SuggestionCorrection | null = null
|
||||
let promptContext = context
|
||||
|
||||
let parsed: { candidate: SuggestionCandidate | null; rejected: string | null } = { candidate: null, rejected: 'empty' }
|
||||
try {
|
||||
// 오타가 있으면 고친 글로 이어 쓴다 — 낱자 잡음("안ㄴ뇽", "ㅇ다른")이 섞인 글을 그대로 주면 모델이
|
||||
// 그 잡음까지 되풀이했다(실측 이력: "아직 ㅇ" → "아직 ㅇ 기능도…"). 교정은 수락할 때만 적용한다.
|
||||
correction = await this._proposeCorrection(context, abort.signal)
|
||||
if (correction) {
|
||||
promptContext = applyCorrectionToContext(context, correction)
|
||||
memory = this._collectMemoryHints(normalizeSessionPrefix(promptContext.prefix), context.appName)
|
||||
}
|
||||
// 세션의 첫 요청은 딱 1개만 청한다 — 한꺼번에 여러 개를 요청하면 느리다(사용자
|
||||
// 요청). 첫 후보를 보여준 뒤 나머지는 채우기 루프가 하나씩 순차로 더 만든다.
|
||||
const request = this._buildModelRequest(
|
||||
model,
|
||||
normalizeSessionPrefix(promptContext.prefix),
|
||||
promptContext,
|
||||
memory,
|
||||
maxChars
|
||||
)
|
||||
this._partialText = ''
|
||||
// 지어낸 사실(원문에 없는 날짜·이름·숫자)로 버린 첫 후보는 같은 시간 제한 안에서 한 번 더 뽑는다.
|
||||
let active = request
|
||||
let temperature: number = SUGGESTION_DEFAULTS.temperature
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const temperature = attempt === 0 ? SUGGESTION_DEFAULTS.temperature : FILL_TEMPERATURE
|
||||
const raw = await this._streamModel(request, model, temperature, abort.signal, (partial) => {
|
||||
const raw = await this._streamModel(active, model, temperature, abort.signal, (partial) => {
|
||||
// 도착하는 대로 오버레이에 흘려보낸다 — 사용자는 "계속 생성되는" 것을 본다.
|
||||
// IPC 과다 방출을 막기 위해 120ms 간격으로만 보낸다.
|
||||
this._partialText = partial
|
||||
|
|
@ -1165,15 +1336,25 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
})
|
||||
if (abort.signal.aborted) break
|
||||
parsed = request.parse(raw)
|
||||
parsed = active.parse(raw)
|
||||
if (!parsed.candidate) {
|
||||
// 진단: 왜 비었는지 모양만 남긴다(글자 내용은 남기지 않는다) — 실측 2026-10-03 카톡 10회 모두 빈 후보.
|
||||
logger.debug(`제안 정제 실패: ${describeRawOutput(raw, request.raw)}`)
|
||||
logger.debug(`제안 정제 실패: ${describeRawOutput(raw, active.raw)}`)
|
||||
}
|
||||
if (parsed.candidate) break
|
||||
if (raw.trim().length === 0 && active.spaced) {
|
||||
// 모델이 곧바로 턴을 닫았다 — prefill 끝에 공백을 붙여 다음 단어부터 쓰게 한다(같은 온도).
|
||||
logger.debug('제안 빈 출력 — prefill 끝에 공백을 붙여 다시 뽑는다')
|
||||
active = active.spaced
|
||||
} else if (parsed.rejected?.startsWith('unsupported-facts')) {
|
||||
logger.info(`제안 후보 버림 (${parsed.rejected}) — 한 번 더 뽑는다`)
|
||||
temperature = FILL_TEMPERATURE
|
||||
} else {
|
||||
break
|
||||
}
|
||||
if (parsed.candidate || !parsed.rejected?.startsWith('unsupported-facts')) break
|
||||
logger.info(`제안 후보 버림 (${parsed.rejected}) — 한 번 더 뽑는다`)
|
||||
this._partialText = ''
|
||||
}
|
||||
spacedPreferred = active !== request
|
||||
} catch (error) {
|
||||
if (!abort.signal.aborted) {
|
||||
this._lastSkipReason = 'generation-failed'
|
||||
|
|
@ -1264,6 +1445,7 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
|
||||
const first = parsed.candidate
|
||||
this._failedPrefix = first ? '' : this._lastRequestedPrefix
|
||||
if (!first) {
|
||||
this._lastSkipReason = 'generation-failed'
|
||||
logger.info(`제안 후보가 비어 있음 (모델 출력 정제 후: ${parsed.rejected ?? 'empty'})`)
|
||||
|
|
@ -1290,6 +1472,9 @@ export class SuggestionService extends EventEmitter {
|
|||
this._budget.noteSuccess()
|
||||
this._partialText = ''
|
||||
this._candidates = [{ ...first, rank: 0 }]
|
||||
this._correction = correction
|
||||
this._promptContext = promptContext
|
||||
this._spacedPreferred = spacedPreferred
|
||||
this._activeIndex = 0
|
||||
this._anchor = context.anchor
|
||||
this._anchorKind = context.anchorKind
|
||||
|
|
@ -1301,7 +1486,7 @@ export class SuggestionService extends EventEmitter {
|
|||
this._lastSkipReason = null
|
||||
this._provenance = {
|
||||
mode: 'local-model',
|
||||
continuationCount: continuationHints.length,
|
||||
continuationCount: memory.continuationHints.length,
|
||||
relatedCount: memory.relatedHints.length + memory.followUpHints.length,
|
||||
phraseCount: memory.phraseHints.length,
|
||||
appPhraseCount: memory.appPhraseCount
|
||||
|
|
@ -1327,6 +1512,28 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/** 이 문맥에 함께 내놓을 오타 교정 — 포트가 없거나 실패하면 교정 없이 간다. */
|
||||
private async _proposeCorrection(
|
||||
context: TypingContext,
|
||||
signal: AbortSignal,
|
||||
thorough = false
|
||||
): Promise<SuggestionCorrection | null> {
|
||||
if (!this._typoProposer) return null
|
||||
try {
|
||||
const plan = await this._typoProposer.propose(context, signal, { thorough })
|
||||
if (!plan || !context.prefix.endsWith(plan.originalText)) return null
|
||||
const base = plan.corrections[0]?.start ?? 0
|
||||
return {
|
||||
from: plan.originalText,
|
||||
to: plan.insertText,
|
||||
edits: plan.corrections.map((edit) => ({ start: edit.start - base, end: edit.end - base, to: edit.to }))
|
||||
}
|
||||
} catch (error) {
|
||||
logger.debug(`제안용 오타 교정 실패 — 교정 없이 제안한다: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// ── 채우기 루프 (2번째 이후 후보, 최대 12개) ────────────
|
||||
|
||||
/**
|
||||
|
|
@ -1337,6 +1544,7 @@ export class SuggestionService extends EventEmitter {
|
|||
* 소비하지 않는다(설계). 시간 초과된 채우기 요청은 조용히 다음으로 넘어간다.
|
||||
*/
|
||||
private async _runFillLoop(token: number, context: TypingContext, maxChars: number): Promise<void> {
|
||||
await this._proposeLateCorrection(token, context)
|
||||
let consecutiveEmpty = 0
|
||||
while (
|
||||
token === this._generationToken &&
|
||||
|
|
@ -1354,6 +1562,28 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 첫 후보를 보여 준 뒤 모델 오타 검사를 한 번 더 한다 — 낱자 없는 오타("회으에서")는 첫 요청 전에
|
||||
* 묻지 않는다(멈출 때마다 0.5~1초 늦어진다). 찾으면 교정 줄을 붙이고, 남은 후보는 고친 글로 잇는다.
|
||||
*/
|
||||
private async _proposeLateCorrection(token: number, context: TypingContext): Promise<void> {
|
||||
if (this._correction || !this._typoProposer) return
|
||||
const abort = new AbortController()
|
||||
this._fillAbort = abort
|
||||
try {
|
||||
const late = await this._proposeCorrection(context, abort.signal, true)
|
||||
if (!late || token !== this._generationToken || abort.signal.aborted) return
|
||||
// 그사이 원문이 바뀌었으면(세션이 끝났으면 토큰이 달라진다) 붙이지 않는다.
|
||||
if (!this._lastContext || !this._lastContext.prefix.endsWith(late.from)) return
|
||||
this._correction = late
|
||||
this._promptContext = applyCorrectionToContext(context, late)
|
||||
this._armVisibleTtl()
|
||||
this.emit('updated', this.getState())
|
||||
} finally {
|
||||
if (this._fillAbort === abort) this._fillAbort = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 채우기 루프 한 스텝 — 후보 1개를 요청해 고유하면 덧붙인다. */
|
||||
private async _fillOne(token: number, context: TypingContext, maxChars: number): Promise<boolean> {
|
||||
const model = this.resolveModel()
|
||||
|
|
@ -1371,14 +1601,13 @@ export class SuggestionService extends EventEmitter {
|
|||
// 세션이 고정한 접두를 쓴다 — context.prefix 는 그사이 바뀌었을 수 있지만,
|
||||
// 바뀌었다면 이미 위(handleTypingContext)에서 세션이 dismiss 되어 토큰이
|
||||
// 달라져 있으므로 이 루프는 다음 체크에서 멈춘다.
|
||||
const prefix = this._generatedForPrefix
|
||||
// 교정이 있으면 모델에는 고친 글을 보여 준다 (첫 후보와 같은 문맥).
|
||||
const promptContext = this._promptContext ?? context
|
||||
const prefix = normalizeSessionPrefix(promptContext.prefix)
|
||||
const memory = this._collectMemoryHints(prefix, context.appName)
|
||||
const avoidCandidates = this._candidates.map((candidate) => candidate.text)
|
||||
// 홀수 번째 채우기는 (다음 문장 모드일 때) 지시형으로 — 후보 다양성.
|
||||
const request = this._buildModelRequest(model, prefix, context, memory, maxChars, {
|
||||
avoidCandidates,
|
||||
preferInstruct: this._candidates.length % 2 === 1
|
||||
})
|
||||
const built = this._buildModelRequest(model, prefix, promptContext, memory, maxChars, { avoidCandidates })
|
||||
const request = this._spacedPreferred && built.spaced ? built.spaced : built
|
||||
const raw = await this._streamModel(request, model, FILL_TEMPERATURE, abort.signal)
|
||||
if (abort.signal.aborted || token !== this._generationToken) return false
|
||||
|
||||
|
|
@ -1630,7 +1859,8 @@ export class SuggestionService extends EventEmitter {
|
|||
this._userDismissedUntil = Date.now() + SUGGESTION_DEFAULTS.userDismissQuietMs
|
||||
logger.info(`사용자가 제안을 닫음 — ${SUGGESTION_DEFAULTS.userDismissQuietMs}ms 동안 재표시하지 않는다`)
|
||||
}
|
||||
const wasVisible = this.isPresentationActive
|
||||
const wasVisible = this.isPresentationActive || this._pending
|
||||
this._clearPending(false)
|
||||
// 진행 중이던 생성을 무효화한다 (닫았는데 잠시 뒤 결과가 다시 뜨는 것을 막는다).
|
||||
this._generationToken += 1
|
||||
this._clearVisibleTtl()
|
||||
|
|
@ -1645,6 +1875,8 @@ export class SuggestionService extends EventEmitter {
|
|||
this._targetTotal = 0
|
||||
this._provenance = null
|
||||
this._sessionRecordId = null
|
||||
this._correction = null
|
||||
this._promptContext = null
|
||||
this._lastSkipReason = reason
|
||||
this._abort?.abort()
|
||||
this._abort = null
|
||||
|
|
@ -1685,7 +1917,16 @@ export class SuggestionService extends EventEmitter {
|
|||
}
|
||||
// 후보는 정제 과정에서 앞 공백을 잃는다 — 커서 앞 원문의 마지막 글자를 보고 구분 공백을
|
||||
// 붙인다(joinSuggestion). 세션을 닫기 전에(dismiss 가 세션 접두를 지운다) 계산한다.
|
||||
const text = joinSuggestion(this._acceptPrefix(), candidate.text, candidate.joint ?? 'separate')
|
||||
// 교정이 있으면 커서 앞 오타 구간을 지우고 고친 글 + 후보를 함께 넣는다. 그사이 원문 끝이 달라졌으면
|
||||
// (IME 마지막 글자 교체 등) 교정은 버리고 후보만 넣는다 — 엉뚱한 글자를 지우지 않는다.
|
||||
const acceptPrefix = this._acceptPrefix()
|
||||
const correction = this._correction && acceptPrefix.endsWith(this._correction.from) ? this._correction : null
|
||||
const basePrefix = correction
|
||||
? acceptPrefix.slice(0, acceptPrefix.length - correction.from.length) + correction.to
|
||||
: acceptPrefix
|
||||
const text = (correction?.to ?? '') + joinSuggestion(basePrefix, candidate.text, candidate.joint ?? 'separate')
|
||||
const deleteCount = correction?.from.length ?? 0
|
||||
const composing = this._lastContext?.isComposing === true
|
||||
const appName = this._appName
|
||||
const windowTitle = this._windowTitle
|
||||
const targetWindow = this._windowHandle
|
||||
|
|
@ -1720,11 +1961,18 @@ export class SuggestionService extends EventEmitter {
|
|||
// 삽입 직후의 텍스트 스냅샷 diff 가 이 텍스트를 "타이핑" 으로 다시 학습하지 않도록 알린다.
|
||||
const cancelExpectedInsert = this._learning.expectProgrammaticInsert(text)
|
||||
const method = configGet('insertMethod')
|
||||
const insertMethod = method === 'keyboard' ? 'keyboard' : 'clipboard'
|
||||
try {
|
||||
const result = await getTextInsertService().insertText(
|
||||
text,
|
||||
method === 'keyboard' ? 'keyboard' : 'clipboard'
|
||||
)
|
||||
if (deleteCount > 0) {
|
||||
// 확정용 Space(+1)·백스페이스·붙여넣기(Ctrl, V) 키는 사용자 입력 통계에서 뺀다.
|
||||
this._learning.expectProgrammaticKeys?.(deleteCount + (composing ? 2 : 0) + 2)
|
||||
}
|
||||
const result =
|
||||
deleteCount > 0
|
||||
? await getTextInsertService().replaceBeforeCaret(deleteCount, text, insertMethod, {
|
||||
commitComposition: composing
|
||||
})
|
||||
: await getTextInsertService().insertText(text, insertMethod)
|
||||
if (!result.success) {
|
||||
cancelExpectedInsert()
|
||||
logger.warn(`제안 삽입 실패 (method=${result.method}, len=${result.textLength})`)
|
||||
|
|
@ -1736,7 +1984,12 @@ export class SuggestionService extends EventEmitter {
|
|||
return { ok: false, reason: 'generation-failed' }
|
||||
}
|
||||
|
||||
logger.info(`제안 수락: ${text.length}자 삽입 (method=${method === 'keyboard' ? 'keyboard' : 'clipboard'}, app=${appName ?? '-'})`)
|
||||
logger.info(
|
||||
`제안 수락: ${text.length}자 삽입${deleteCount > 0 ? ` (오타 교정 포함, ${deleteCount}자 교체)` : ''} ` +
|
||||
`(method=${insertMethod}, app=${appName ?? '-'})`
|
||||
)
|
||||
// 수락 뒤 이어 쳐서 멈추면 바로 다음 제안이 떠야 한다 — 방금 세션의 요청 간격에 걸리지 않게 푼다.
|
||||
this._budget.relaxInterval(Date.now(), SUGGESTION_DEFAULTS.minIntervalMs)
|
||||
// 이력은 후보 원문으로 기록돼 있다 — 구분 공백이 붙은 삽입 문자열로는 찾지 못한다.
|
||||
// 세션 행을 알면 그 행을 수락으로 표시한다 — 텍스트로 찾으면 로컬 기억의 2번째 이후 후보는
|
||||
// 행이 없어 사라지거나 같은 문구의 옛 행(다른 앱·다른 날)이 수락으로 잡혔다.
|
||||
|
|
@ -1778,7 +2031,7 @@ export class SuggestionService extends EventEmitter {
|
|||
maxRequestsPerMinute:
|
||||
Math.min(
|
||||
configGet('suggestionMaxRequestsPerMinute') || SUGGESTION_DEFAULTS.maxRequestsPerMinute,
|
||||
12
|
||||
30
|
||||
),
|
||||
dailyBudget: configGet('suggestionDailyBudget') || SUGGESTION_DEFAULTS.dailyBudget,
|
||||
maxCandidates: SUGGESTION_DEFAULTS.maxCandidates,
|
||||
|
|
|
|||
|
|
@ -97,10 +97,22 @@ export class TextInsertService extends EventEmitter {
|
|||
* 커서를 옮기지 않고 백스페이스로만 지운다 — 앱마다 다른 단어 이동/선택 동작에 기대지 않는다.
|
||||
* 다른 삽입과 같은 직렬화 꼬리를 탄다(클립보드 save/restore 가 엇갈리지 않게).
|
||||
*/
|
||||
replaceBeforeCaret(deleteCount: number, text: string, method: InsertMethod = 'clipboard'): Promise<InsertResult> {
|
||||
replaceBeforeCaret(
|
||||
deleteCount: number,
|
||||
text: string,
|
||||
method: InsertMethod = 'clipboard',
|
||||
options: { commitComposition?: boolean } = {}
|
||||
): Promise<InsertResult> {
|
||||
const run = this._tail.then(async () => {
|
||||
try {
|
||||
await this._keyboard.backspace(deleteCount)
|
||||
let count = deleteCount
|
||||
// 커서 앞 글자가 IME 조합 중이면 먼저 확정한다 (Space → 남은 공백까지 지운다).
|
||||
if (options.commitComposition && this._keyboard.commitComposition) {
|
||||
await this._keyboard.commitComposition()
|
||||
await this._sleep(15)
|
||||
count += 1
|
||||
}
|
||||
await this._keyboard.backspace(count)
|
||||
} catch (error) {
|
||||
throw error instanceof D3ROError
|
||||
? error
|
||||
|
|
|
|||
|
|
@ -8,6 +8,10 @@
|
|||
// core validateModelCorrections 로 다시 거른 것만 교체.
|
||||
// 3) 교체는 "커서 앞 N 글자 백스페이스 → 고친 구간 붙여넣기" 한 번이다.
|
||||
//
|
||||
// 제안이 켜져 있으면 조용히 고치지 않는다 — propose() 가 교정을 만들어 제안 창에 "지운 글자 → 고친
|
||||
// 글자" 로 함께 보여 주고, 사용자가 수락할 때만 적용한다(2026-10-17 사용자 요청). 위 자동 교정은 제안이
|
||||
// 꺼져 있을 때만 쓴다(bootstrap 배선).
|
||||
//
|
||||
// 안전장치: 멈춤(유휴 600ms) 뒤에만, 스냅샷 뒤 사용자가 한 키라도 더 쳤으면 취소, 포그라운드 창이
|
||||
// 바뀌었으면 취소, 터미널·에디터·제외 앱·비밀번호·선택·조합 중에는 하지 않는다. 사용자가 교정을
|
||||
// 되돌리면 그 단어는 무시 목록에 올려 다시 고치지 않는다.
|
||||
|
|
@ -21,8 +25,11 @@ import {
|
|||
TYPO_MIN_IDLE_MS,
|
||||
TYPO_REVERT_WINDOW_MS,
|
||||
buildVocabulary,
|
||||
detectJamoNoise,
|
||||
detectTypoRevert,
|
||||
detectTypos,
|
||||
hasSuspiciousTypo,
|
||||
mergeTypoCorrections,
|
||||
parseModelTypoPairs,
|
||||
planTypoReplacement,
|
||||
tokenizeWords,
|
||||
|
|
@ -46,6 +53,8 @@ const MODEL_CHECK_TIMEOUT_MS = 2500
|
|||
const MODEL_CHECK_MAX_TOKENS = 48
|
||||
/** 개인 어휘 캐시 수명 */
|
||||
const VOCABULARY_TTL_MS = 60_000
|
||||
/** 제안용 모델 검사 응답 제한 — 제안 첫 후보가 그만큼 늦어진다. */
|
||||
const PROPOSAL_CHECK_TIMEOUT_MS = 1500
|
||||
/** 모델 검사 최소 구간 길이 (글자) */
|
||||
const MODEL_CHECK_MIN_CHARS = 6
|
||||
|
||||
|
|
@ -182,6 +191,69 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
return 'checking'
|
||||
}
|
||||
|
||||
/**
|
||||
* 제안 창에 함께 내놓을 교정을 만든다 — 적용하지 않는다.
|
||||
*
|
||||
* 결정적 규칙(한영 전환·늘 틀린 철자·개인 어휘·낱자 잡음)은 늘 보고, 모델은 구간이 수상할 때
|
||||
* (낱자가 섞인 한글 단어·드문 음절)만 묻는다 — 멈출 때마다 묻으면 제안이 그만큼 늦는다.
|
||||
* 사용자가 고르는 제안이라 자동 교정보다 넓게 본다: 학습 제외 앱(에이전트 창 등)도 보되,
|
||||
* 명령을 치는 터미널과 사용자 제외 앱은 뺀다.
|
||||
*
|
||||
* `thorough`: 수상한 흔적이 없어도 끝난 단어가 둘 이상이면 모델에 묻는다 — 첫 후보를 보여 준 뒤
|
||||
* 백그라운드에서 쓴다("회으에서", "괜찬으세요" 처럼 낱자 없는 오타는 수상함 판정에 걸리지 않는다).
|
||||
*/
|
||||
async propose(
|
||||
context: TypingContext,
|
||||
signal: AbortSignal,
|
||||
options: { thorough?: boolean } = {}
|
||||
): Promise<TypoReplacementPlan | null> {
|
||||
if (!this.isEnabled()) return null
|
||||
if (!context.available || !context.isEditable || context.isPassword || context.hasSelection) return null
|
||||
if (isTerminalApp(context.appName)) return null
|
||||
if (context.appName && isAppExcluded(context.appName, configGet('inputExcludedApps'))) return null
|
||||
|
||||
const prefix = context.prefix
|
||||
const region = prefix.slice(typoRegionStart(prefix))
|
||||
if (!region.trim()) return null
|
||||
|
||||
const ignoredWords = configGet('typoIgnoredWords') ?? []
|
||||
const vocabulary = this._loadVocabulary()
|
||||
const deterministic = mergeTypoCorrections(
|
||||
detectTypos(prefix, { includeTrailingToken: true, ignoredWords, vocabulary: vocabulary.latin }),
|
||||
detectJamoNoise(prefix, { ignoredWords })
|
||||
)
|
||||
|
||||
let fromModel: TypoCorrection[] = []
|
||||
const model = configGet('typoAutoCorrectUseModel') !== false ? this._deps.warmModel() : null
|
||||
const worthAsking = hasSuspiciousTypo(region) || (options.thorough === true && this._worthModelCheck(region))
|
||||
if (model && worthAsking) {
|
||||
const abort = new AbortController()
|
||||
const forward = (): void => abort.abort()
|
||||
signal.addEventListener('abort', forward, { once: true })
|
||||
const timer = setTimeout(() => abort.abort(), PROPOSAL_CHECK_TIMEOUT_MS)
|
||||
timer.unref?.()
|
||||
try {
|
||||
fromModel = await this._askModel(model, prefix, abort.signal, ignoredWords, vocabulary.known)
|
||||
} catch (error) {
|
||||
if (!abort.signal.aborted) {
|
||||
logger.debug(`제안용 오타 검사 실패: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
signal.removeEventListener('abort', forward)
|
||||
}
|
||||
}
|
||||
if (signal.aborted) return null
|
||||
|
||||
// 모델이 같은 단어를 더 잘 고쳤으면(안ㄴ뇽 → 안녕) 낱자 지우기(안뇽)보다 앞선다.
|
||||
const plan = planTypoReplacement(prefix, mergeTypoCorrections(fromModel, deterministic))
|
||||
if (plan) {
|
||||
const sources = [...new Set(plan.corrections.map((correction) => correction.source))].join(',')
|
||||
logger.info(`제안에 오타 교정 ${plan.corrections.length}건 포함 (${sources}, app=${context.appName ?? '-'})`)
|
||||
}
|
||||
return plan
|
||||
}
|
||||
|
||||
/** 설정에서 끌 때·종료할 때 */
|
||||
dispose(): void {
|
||||
this._cancelCheck()
|
||||
|
|
@ -242,26 +314,8 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
let corrected = false
|
||||
try {
|
||||
const prefix = context.prefix
|
||||
const region = prefix.slice(typoRegionStart(prefix))
|
||||
const writing = analyzeWritingContext(prefix.slice(0, typoRegionStart(prefix)))
|
||||
const { systemPrompt, text } = buildTypoCheckPrompt({
|
||||
sentence: region,
|
||||
previous: [writing.earlierText, writing.lastSentence, writing.currentSentence].filter(Boolean).join(' ')
|
||||
})
|
||||
let raw = ''
|
||||
for await (const chunk of this._deps.generate(text, {
|
||||
model,
|
||||
systemPrompt,
|
||||
maxTokens: MODEL_CHECK_MAX_TOKENS,
|
||||
signal: abort.signal
|
||||
})) {
|
||||
if (abort.signal.aborted) break
|
||||
raw += chunk
|
||||
if (raw.length > 400) break
|
||||
}
|
||||
const corrections = await this._askModel(model, prefix, abort.signal, ignoredWords, knownWords)
|
||||
if (abort.signal.aborted || this._check?.abort !== abort) return
|
||||
|
||||
const corrections = validateModelCorrections(prefix, parseModelTypoPairs(raw), { ignoredWords, knownWords })
|
||||
const plan = planTypoReplacement(prefix, corrections)
|
||||
if (!plan) return
|
||||
// 검사하는 사이 사용자가 더 쳤으면 접두가 달라져 위에서 취소됐다. 여기서 한 번 더 키를 본다.
|
||||
|
|
@ -281,6 +335,30 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/** 지금 문장의 오타를 모델에 묻고, core 규칙으로 다시 거른 교정만 돌려준다. */
|
||||
private async _askModel(
|
||||
model: string,
|
||||
prefix: string,
|
||||
signal: AbortSignal,
|
||||
ignoredWords: readonly string[],
|
||||
knownWords: ReadonlySet<string>
|
||||
): Promise<TypoCorrection[]> {
|
||||
const region = prefix.slice(typoRegionStart(prefix))
|
||||
const writing = analyzeWritingContext(prefix.slice(0, typoRegionStart(prefix)))
|
||||
const { systemPrompt, text } = buildTypoCheckPrompt({
|
||||
sentence: region,
|
||||
previous: [writing.earlierText, writing.lastSentence, writing.currentSentence].filter(Boolean).join(' ')
|
||||
})
|
||||
let raw = ''
|
||||
for await (const chunk of this._deps.generate(text, { model, systemPrompt, maxTokens: MODEL_CHECK_MAX_TOKENS, signal })) {
|
||||
if (signal.aborted) break
|
||||
raw += chunk
|
||||
if (raw.length > 400) break
|
||||
}
|
||||
if (signal.aborted) return []
|
||||
return validateModelCorrections(prefix, parseModelTypoPairs(raw), { ignoredWords, knownWords })
|
||||
}
|
||||
|
||||
private _cancelCheck(): void {
|
||||
if (!this._check) return
|
||||
this._check.abort.abort()
|
||||
|
|
|
|||
|
|
@ -16,6 +16,11 @@ export interface KeyboardPort {
|
|||
type(text: string): Promise<void>
|
||||
/** 커서 앞 글자를 count 번 지운다 (오타 교정) */
|
||||
backspace(count: number): Promise<void>
|
||||
/**
|
||||
* IME 가 조합 중인 글자를 확정시키고 공백 하나를 남긴다 (실제 Space 키) — 조합 중에 백스페이스를 보내면
|
||||
* 글자가 아니라 낱자가 지워져(여 → ㅇ) 지울 개수가 어긋난다. 호출자는 남은 공백까지 지운다 (선택).
|
||||
*/
|
||||
commitComposition?(): Promise<void>
|
||||
/** 네이티브 키 모듈을 미리 불러 둔다 — 첫 삽입이 로딩을 기다리지 않게 (선택) */
|
||||
preload?(): Promise<void>
|
||||
}
|
||||
|
|
@ -98,6 +103,11 @@ export class NutKeyboardPort implements KeyboardPort {
|
|||
await nut.native.type(text)
|
||||
}
|
||||
|
||||
async commitComposition(): Promise<void> {
|
||||
const nut = await this._ensureNut()
|
||||
await nut.native.click(nut.Key.Space)
|
||||
}
|
||||
|
||||
/** 백스페이스를 count 번 — 키마다 네이티브 keyTap 한 번이다. */
|
||||
async backspace(count: number): Promise<void> {
|
||||
if (count <= 0) return
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ import { app, dialog } from 'electron'
|
|||
import { getLogger } from './LoggerService'
|
||||
import { configGet } from './ConfigService'
|
||||
import { getMainWindow } from '../windows/WindowManager'
|
||||
import { UPDATE_FEED_URL, UPDATE_POLICY_URL } from '../update-feed'
|
||||
import { UPDATE_FEED_URL, UPDATE_POLICY_URL, versionedManifestUrl } from '../update-feed'
|
||||
import { verifyDownloadedUpdate } from '../update-signature'
|
||||
import { DEFAULT_UPDATE_POLICY, parseUpdatePolicy, type UpdatePolicy } from '../update-policy'
|
||||
import { PORTABLE_INSTALL_MARKER, detectInstallKind, type InstallProbe } from '../install-kind'
|
||||
import type {
|
||||
|
|
@ -24,6 +25,41 @@ const logger = getLogger('UpdateService')
|
|||
|
||||
/** 원격 정책 fetch 타임아웃 */
|
||||
const POLICY_FETCH_TIMEOUT_MS = 8_000
|
||||
/** 서명된 latest.yml fetch 타임아웃 */
|
||||
const MANIFEST_FETCH_TIMEOUT_MS = 15_000
|
||||
|
||||
async function fetchText(url: string): Promise<string> {
|
||||
const response = await fetch(url, { cache: 'no-store', signal: AbortSignal.timeout(MANIFEST_FETCH_TIMEOUT_MS) })
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status} ${url}`)
|
||||
return response.text()
|
||||
}
|
||||
|
||||
/**
|
||||
* NsisUpdater 는 받은 파일을 넘기기 전에 `verifySignature(path)` 를 부르고, 문자열을 돌려받으면
|
||||
* 파일을 지우고 ERR_UPDATER_INVALID_SIGNATURE 로 실패한다. 무서명 앱에선 이 단계가 아무것도 안 하므로
|
||||
* 우리 Ed25519 검증으로 바꿔 끼운다. 라이브러리가 이 지점을 없애면 업데이트를 받지 않는다(fail-closed).
|
||||
*/
|
||||
function installManifestVerifier(
|
||||
updater: import('electron-updater').AppUpdater,
|
||||
offeredVersion: () => string | null,
|
||||
): boolean {
|
||||
const target = updater as unknown as { verifySignature?: (path: string) => Promise<string | null> }
|
||||
if (typeof target.verifySignature !== 'function') return false
|
||||
target.verifySignature = async (installerPath: string): Promise<string | null> => {
|
||||
const version = offeredVersion()
|
||||
if (!version) return '받으려던 버전을 알 수 없음'
|
||||
const rejection = await verifyDownloadedUpdate({
|
||||
version,
|
||||
installerPath,
|
||||
fetchText,
|
||||
manifestUrl: versionedManifestUrl(version),
|
||||
})
|
||||
if (rejection) logger.error(`업데이트 v${version} 설치 거부 — ${rejection}`)
|
||||
else logger.info(`업데이트 v${version} 서명 확인 완료`)
|
||||
return rejection
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** 실행 중인 설치본의 형태를 파일 시스템에서 읽는다 (판단은 detectInstallKind). */
|
||||
function probeInstall(): InstallProbe {
|
||||
|
|
@ -74,6 +110,13 @@ export function createElectronUpdater(handlers: UpdaterEventHandlers): UpdaterPo
|
|||
return null
|
||||
}
|
||||
|
||||
let offeredVersion: string | null = null
|
||||
// macOS 는 Squirrel.Mac 이 앱 코드 서명을 직접 요구하므로 이 검증은 Windows(NSIS) 전용이다.
|
||||
if (process.platform === 'win32' && !installManifestVerifier(updater, () => offeredVersion)) {
|
||||
logger.error('electron-updater 에 설치 파일 검증 지점(verifySignature)이 없음 — 자동 업데이트 비활성')
|
||||
return null
|
||||
}
|
||||
|
||||
updater.setFeedURL({ provider: 'generic', url: UPDATE_FEED_URL })
|
||||
// 사용자 인가를 위해 자동 다운로드는 비활성화 (동의 시 downloadUpdate 호출)
|
||||
updater.autoDownload = false
|
||||
|
|
@ -87,7 +130,10 @@ export function createElectronUpdater(handlers: UpdaterEventHandlers): UpdaterPo
|
|||
}
|
||||
|
||||
updater.on('checking-for-update', () => handlers.onChecking())
|
||||
updater.on('update-available', (info) => handlers.onAvailable(info))
|
||||
updater.on('update-available', (info) => {
|
||||
offeredVersion = info.version
|
||||
handlers.onAvailable(info)
|
||||
})
|
||||
updater.on('update-not-available', (info) => handlers.onNotAvailable(info.version))
|
||||
updater.on('download-progress', (progress) =>
|
||||
handlers.onProgress({
|
||||
|
|
|
|||
|
|
@ -24,11 +24,13 @@ export const RUNTIME_FEED_URL = UPDATE_FEED_URL.replace(/\/latest$/, '/runtime-l
|
|||
/** 런타임 인덱스 파일명 (feed 루트) — RuntimeProvisioner 가 `${RUNTIME_FEED_URL}/${RUNTIME_INDEX_FILENAME}` 으로 읽는다 */
|
||||
export const RUNTIME_INDEX_FILENAME = 'runtime.json'
|
||||
|
||||
// GitLab Generic Registry legacy mirror. 2026-08 이전 설치본(0.2.1-alpha)은
|
||||
// 이 feed를 폴링하므로, 새 설치자가 Forgejo feed를 내장할 때까지 publisher가
|
||||
// 함께 게시한다. 마이그레이션 완료 후 제거 가능. 런타임은 참조하지 않는다.
|
||||
export const LEGACY_UPDATE_FEED_URL =
|
||||
'https://gitlab.twentyoz.kr:8443/api/v4/projects/1172/packages/generic/d3ro-voice/latest'
|
||||
/**
|
||||
* 버전별(불변) 경로의 latest.yml. 서명 검증은 `latest`(가변) 대신 이 경로를 본다 —
|
||||
* 받는 사이에 새 버전이 게시돼 latest.yml 이 바뀌어도 검증 대상이 흔들리지 않는다.
|
||||
*/
|
||||
export function versionedManifestUrl(version: string): string {
|
||||
return `${UPDATE_FEED_URL.replace(/\/latest$/, '')}/${encodeURIComponent(version)}/latest.yml`
|
||||
}
|
||||
|
||||
/** 업데이트 채널. `latest`=stable, `beta`, `alpha` 순으로 불안정. */
|
||||
export type UpdateChannel = 'latest' | 'beta' | 'alpha'
|
||||
|
|
|
|||
91
apps/desktop/src/main/update-signature.ts
Normal file
91
apps/desktop/src/main/update-signature.ts
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
// src/main/update-signature.ts
|
||||
// 받은 업데이트 설치 파일이 우리가 게시한 것인지 확인한다.
|
||||
//
|
||||
// 설치본에 Authenticode 서명이 없어 electron-updater 는 자체 서명 검증을 건너뛴다. 그러면 피드
|
||||
// (Forgejo 패키지)가 털렸을 때 아무 설치 파일이나 배포된다. 그래서 게시 스크립트가 latest.yml 을
|
||||
// 오프라인 Ed25519 키로 서명하고(latest.yml.sig), 앱은:
|
||||
// 1. 버전별(불변) 경로의 latest.yml + .sig 를 받아 내장 공개키로 서명을 확인하고
|
||||
// 2. 그 latest.yml 의 version · sha512 가 받은 설치 파일과 같은지 본다.
|
||||
// 하나라도 어긋나면 설치를 거부한다(fail-closed). 게시 쪽: scripts/ci/lib/update-manifest-signature.mjs
|
||||
|
||||
import { createHash, createPublicKey, verify } from 'node:crypto'
|
||||
import { createReadStream } from 'node:fs'
|
||||
|
||||
/** release/desktop-update-public.pem 사본 — verify-release-metadata 가 둘이 같은지 검사한다 */
|
||||
export const UPDATE_SIGNING_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEAlvJTkVr7CSi9ZbBL2JOub7Sw4CAc1WOJpLEjDs/V/8o=
|
||||
-----END PUBLIC KEY-----
|
||||
`
|
||||
|
||||
export const UPDATE_SIGNATURE_SUFFIX = '.sig'
|
||||
|
||||
const ED25519_SIGNATURE_BYTES = 64
|
||||
|
||||
export interface SignedManifestInput {
|
||||
manifest: string
|
||||
signature: string
|
||||
publicKeyPem?: string
|
||||
}
|
||||
|
||||
/** 서명이 맞으면 latest.yml 의 version/sha512 를, 아니면 null 을 돌려준다 */
|
||||
export function readSignedManifest({
|
||||
manifest,
|
||||
signature,
|
||||
publicKeyPem = UPDATE_SIGNING_PUBLIC_KEY,
|
||||
}: SignedManifestInput): { version: string; sha512: string } | null {
|
||||
const signatureBytes = Buffer.from(signature.trim(), 'base64')
|
||||
if (signatureBytes.length !== ED25519_SIGNATURE_BYTES) return null
|
||||
let valid = false
|
||||
try {
|
||||
valid = verify(null, Buffer.from(manifest, 'utf8'), createPublicKey(publicKeyPem), signatureBytes)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!valid) return null
|
||||
// 서명된 내용이라 신뢰할 수 있다 — 최상위 키만 읽으면 된다(files[] 아래 들여쓴 줄은 제외).
|
||||
const version = manifest.match(/^version:\s*['"]?([^'"\s]+)['"]?\s*$/m)?.[1]
|
||||
const sha512 = manifest.match(/^sha512:\s*['"]?([^'"\s]+)['"]?\s*$/m)?.[1]
|
||||
return version && sha512 ? { version, sha512 } : null
|
||||
}
|
||||
|
||||
export function sha512Base64OfFile(path: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = createHash('sha512')
|
||||
createReadStream(path)
|
||||
.on('data', (chunk) => hash.update(chunk))
|
||||
.on('end', () => resolve(hash.digest('base64')))
|
||||
.on('error', reject)
|
||||
})
|
||||
}
|
||||
|
||||
export interface VerifyDownloadInput {
|
||||
/** 사용자에게 제안했던(받으려던) 버전 */
|
||||
version: string
|
||||
installerPath: string
|
||||
fetchText(url: string): Promise<string>
|
||||
manifestUrl: string
|
||||
publicKeyPem?: string
|
||||
hashFile?: (path: string) => Promise<string>
|
||||
}
|
||||
|
||||
/** 통과하면 null, 거부하면 사유 문자열 (electron-updater verifySignature 계약과 같다) */
|
||||
export async function verifyDownloadedUpdate(input: VerifyDownloadInput): Promise<string | null> {
|
||||
let manifest: string
|
||||
let signature: string
|
||||
try {
|
||||
;[manifest, signature] = await Promise.all([
|
||||
input.fetchText(input.manifestUrl),
|
||||
input.fetchText(`${input.manifestUrl}${UPDATE_SIGNATURE_SUFFIX}`),
|
||||
])
|
||||
} catch (err) {
|
||||
return `서명된 업데이트 메타데이터를 받지 못함: ${err instanceof Error ? err.message : String(err)}`
|
||||
}
|
||||
const signed = readSignedManifest({ manifest, signature, publicKeyPem: input.publicKeyPem })
|
||||
if (!signed) return 'latest.yml 서명이 유효하지 않음'
|
||||
if (signed.version !== input.version) {
|
||||
return `서명된 버전(${signed.version})이 받은 버전(${input.version})과 다름`
|
||||
}
|
||||
const actual = await (input.hashFile ?? sha512Base64OfFile)(input.installerPath)
|
||||
if (actual !== signed.sha512) return '설치 파일 sha512 가 서명된 latest.yml 과 다름'
|
||||
return null
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@ import { app, BrowserWindow, screen, ipcMain, Menu, clipboard } from 'electron'
|
|||
import { join } from 'path'
|
||||
import { is } from '@electron-toolkit/utils'
|
||||
import { WINDOW_SIZE } from '@d3ro/core/constants'
|
||||
import type { AnchorKind, PhysicalRect } from '@d3ro/core/input-intelligence'
|
||||
import type { AnchorKind, PhysicalRect, SuggestionCorrection } from '@d3ro/core/input-intelligence'
|
||||
import {
|
||||
fitAnchoredPanel,
|
||||
placeAnchoredPanel,
|
||||
|
|
@ -108,6 +108,7 @@ function getPopupI18nStrings(): Record<string, string> {
|
|||
// 키 힌트 줄 (동작 낱말 — 실제 키는 사용자 바인딩에서 매번 계산해 붙인다)
|
||||
suggestionHintMoveLabel: t('popup.suggestion.hintMove'),
|
||||
suggestionHintAcceptLabel: t('popup.suggestion.hintAccept'),
|
||||
suggestionCorrectionLabel: t('popup.suggestion.correctionLabel'),
|
||||
suggestionHintCloseLabel: t('popup.suggestion.hintDismiss'),
|
||||
suggestionHintGeneratingMore: t('popup.suggestion.hintGeneratingMore'),
|
||||
}
|
||||
|
|
@ -845,6 +846,8 @@ interface SuggestionOverlayContent {
|
|||
/** 스트리밍 중 부분 텍스트 */
|
||||
partialText?: string | null
|
||||
provenance?: SuggestionOverlayProvenance | null
|
||||
/** 후보와 함께 적용되는 오타 교정 — 팝업이 "지운 글자 → 고친 글자" 줄을 그린다 */
|
||||
correction?: SuggestionCorrection | null
|
||||
}
|
||||
|
||||
/** 현재 세션의 배치(최대 높이 기준) — 내용이 바뀌면 이 자리에서 높이만 맞춘다. */
|
||||
|
|
@ -872,7 +875,8 @@ function fitSuggestionOverlay(win: BrowserWindow, content: SuggestionOverlayCont
|
|||
activeIndex: content.activeIndex,
|
||||
generating: content.generating === true,
|
||||
warmingUp: content.warmingUp === true,
|
||||
hasPartialText: !!content.partialText
|
||||
hasPartialText: !!content.partialText,
|
||||
hasCorrection: !!content.correction
|
||||
})
|
||||
)
|
||||
const previous = suggestionOverlayBounds
|
||||
|
|
@ -921,6 +925,7 @@ export function showSuggestionOverlay(
|
|||
partialText: payload.partialText ?? null,
|
||||
appName: payload.appName,
|
||||
provenance: payload.provenance ?? null,
|
||||
correction: payload.correction ?? null,
|
||||
_i18n: getPopupI18nStrings(),
|
||||
_keyHints: buildSuggestionKeyHints()
|
||||
}))
|
||||
|
|
|
|||
|
|
@ -18,14 +18,16 @@ const PANEL_PADDING = 6 // .suggestion-panel padding
|
|||
const STATUS_HEIGHT = 32 // .status height
|
||||
const ITEM_HEIGHT = 44 // .suggestion-item height
|
||||
const ITEM_GAP = 2 // .candidates gap
|
||||
/** .correction: height 26 + margin-bottom 2, 그리고 뒤 후보와의 .candidates gap 2 */
|
||||
const CORRECTION_HEIGHT = 26 + 2 + ITEM_GAP
|
||||
/** .footer: margin-top 6 + border-top 1 + padding-top 6 + 행 14 + gap 5 + 키 안내 16 + padding-bottom 2 */
|
||||
const FOOTER_HEIGHT = 6 + 1 + 6 + 14 + 5 + 16 + 2
|
||||
|
||||
const CHROME_HEIGHT = 2 * (ROOT_PADDING + PANEL_BORDER + PANEL_PADDING)
|
||||
|
||||
/** 한 페이지(3개) + 진행률/키 안내 — 가장 큰 패널이자 창 최대 높이 (= 208). */
|
||||
/** 교정 줄 + 한 페이지(3개) + 진행률/키 안내 — 가장 큰 패널이자 창 최대 높이 (= 238). */
|
||||
export const SUGGESTION_OVERLAY_MAX_HEIGHT =
|
||||
CHROME_HEIGHT + PAGE_SIZE * ITEM_HEIGHT + (PAGE_SIZE - 1) * ITEM_GAP + FOOTER_HEIGHT
|
||||
CHROME_HEIGHT + CORRECTION_HEIGHT + PAGE_SIZE * ITEM_HEIGHT + (PAGE_SIZE - 1) * ITEM_GAP + FOOTER_HEIGHT
|
||||
|
||||
export interface SuggestionPanelLayoutInput {
|
||||
candidateCount: number
|
||||
|
|
@ -34,6 +36,8 @@ export interface SuggestionPanelLayoutInput {
|
|||
warmingUp: boolean
|
||||
/** 스트리밍 중인 부분 텍스트가 있는가 */
|
||||
hasPartialText: boolean
|
||||
/** 오타 교정 줄이 보이는가 (후보가 있을 때만 그린다) */
|
||||
hasCorrection?: boolean
|
||||
}
|
||||
|
||||
/** 지금 그려지는 패널(+root 패딩) 높이 — script.js render() 와 같은 규칙으로 센다. */
|
||||
|
|
@ -55,6 +59,7 @@ export function suggestionPanelHeight(input: SuggestionPanelLayoutInput): number
|
|||
(busy ? STATUS_HEIGHT : 0) +
|
||||
items * ITEM_HEIGHT +
|
||||
Math.max(0, items - 1) * ITEM_GAP +
|
||||
(count > 0 && input.hasCorrection ? CORRECTION_HEIGHT : 0) +
|
||||
(count > 0 ? FOOTER_HEIGHT : 0)
|
||||
return Math.min(height, SUGGESTION_OVERLAY_MAX_HEIGHT)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ import {
|
|||
/** 오버레이 내용 — show 와 update 가 같이 쓴다 */
|
||||
export type SuggestionOverlayContentPayload = Pick<
|
||||
SuggestionState,
|
||||
'candidates' | 'activeIndex' | 'targetTotal' | 'generating' | 'warmingUp' | 'partialText' | 'provenance'
|
||||
'candidates' | 'activeIndex' | 'targetTotal' | 'generating' | 'warmingUp' | 'partialText' | 'provenance' | 'correction'
|
||||
>
|
||||
|
||||
/** 새로 띄울 때만 필요한 배치 정보를 더한 payload */
|
||||
|
|
@ -38,6 +38,7 @@ export function toSuggestionOverlayContent(state: SuggestionState): SuggestionOv
|
|||
warmingUp: state.warmingUp,
|
||||
partialText: state.partialText,
|
||||
provenance: state.provenance,
|
||||
correction: state.correction,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -35,6 +35,8 @@
|
|||
var provenance = null
|
||||
var i18nStrings = {}
|
||||
var keyHints = null
|
||||
/** 후보와 함께 적용되는 오타 교정 { from, to, edits:[{start,end,to}] } */
|
||||
var correction = null
|
||||
var generatingSince = 0
|
||||
var tickTimer = null
|
||||
|
||||
|
|
@ -70,6 +72,8 @@
|
|||
return
|
||||
}
|
||||
|
||||
if (correction) candidatesContainer.appendChild(buildCorrectionRow(correction))
|
||||
|
||||
var page = Math.floor(activeIndex / PAGE_SIZE)
|
||||
var pageStart = page * PAGE_SIZE
|
||||
var pageEnd = Math.min(pageStart + PAGE_SIZE, candidates.length)
|
||||
|
|
@ -105,9 +109,45 @@
|
|||
body.textContent = text
|
||||
item.appendChild(num)
|
||||
item.appendChild(body)
|
||||
// 교정이 있으면 후보 앞에 고친 글 끝부분을 강조해 붙인다 — "이렇게 고친 뒤 이어진다" 를 보여 준다.
|
||||
if (correction && tag === 'button') {
|
||||
var lead = document.createElement('span')
|
||||
lead.className = 'corrected'
|
||||
var tail = correction.to.replace(/\s+$/, '')
|
||||
lead.textContent = (tail.length > 18 ? '…' + tail.slice(-18) : tail) + ' '
|
||||
body.insertBefore(lead, body.firstChild)
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
/** "고침 | 지운 글자 → 고친 글자" 한 줄 — 바뀐 단어만 보여 준다. */
|
||||
function buildCorrectionRow(value) {
|
||||
var row = document.createElement('div')
|
||||
row.className = 'correction'
|
||||
var label = document.createElement('span')
|
||||
label.className = 'correction-label'
|
||||
label.textContent = i18nStrings.suggestionCorrectionLabel || ''
|
||||
row.appendChild(label)
|
||||
var diff = document.createElement('span')
|
||||
diff.className = 'correction-diff'
|
||||
var edits = value.edits && value.edits.length ? value.edits : [{ start: 0, end: value.from.length, to: value.to }]
|
||||
for (var i = 0; i < edits.length; i++) {
|
||||
if (i > 0) diff.appendChild(document.createTextNode(', '))
|
||||
var removed = document.createElement('del')
|
||||
removed.textContent = value.from.slice(edits[i].start, edits[i].end).trim() || '␣'
|
||||
var arrow = document.createElement('span')
|
||||
arrow.className = 'correction-arrow'
|
||||
arrow.textContent = '→'
|
||||
var added = document.createElement('ins')
|
||||
added.textContent = edits[i].to || '∅'
|
||||
diff.appendChild(removed)
|
||||
diff.appendChild(arrow)
|
||||
diff.appendChild(added)
|
||||
}
|
||||
row.appendChild(diff)
|
||||
return row
|
||||
}
|
||||
|
||||
function renderProgress() {
|
||||
if (!progressContainer) return
|
||||
progressContainer.textContent = ''
|
||||
|
|
@ -211,6 +251,7 @@
|
|||
if (payload.warmingUp !== undefined) warmingUp = payload.warmingUp === true
|
||||
if (payload.partialText !== undefined) partialText = payload.partialText || null
|
||||
if (payload.provenance !== undefined) provenance = payload.provenance || null
|
||||
if (payload.correction !== undefined) correction = payload.correction || null
|
||||
}
|
||||
|
||||
function startTick() {
|
||||
|
|
@ -254,6 +295,7 @@
|
|||
warmingUp = false
|
||||
partialText = null
|
||||
provenance = null
|
||||
correction = null
|
||||
candidates = []
|
||||
activeIndex = 0
|
||||
targetTotal = 0
|
||||
|
|
|
|||
|
|
@ -299,3 +299,55 @@ kbd {
|
|||
line-height: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ── 오타 교정 (후보와 함께 적용된다) — 지운 글자는 취소선, 고친 글자는 강조. 높이 26px 고정 ── */
|
||||
.correction {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 26px;
|
||||
margin-bottom: 2px;
|
||||
padding: 0 28px 0 8px;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
color: var(--d3-text-secondary);
|
||||
}
|
||||
|
||||
.correction-label {
|
||||
flex: 0 0 auto;
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
background: var(--d3-accent-dim);
|
||||
color: var(--d3-accent-main);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.correction-diff {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.correction del {
|
||||
color: var(--d3-status-danger);
|
||||
text-decoration: line-through;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.correction ins {
|
||||
color: var(--d3-accent-main);
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.correction-arrow {
|
||||
margin: 0 3px;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
/* 후보 앞에 붙는 고친 글 — 이 글자들로 바뀐 뒤 후보가 이어진다는 표시 */
|
||||
.suggestion-text .corrected {
|
||||
color: var(--d3-accent-main);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,13 +54,13 @@ describe('SUGGESTION.SET_CONFIG', () => {
|
|||
expect(configSet).not.toHaveBeenCalledWith('suggestionEnabled', true)
|
||||
})
|
||||
|
||||
it('분당 요청 상한을 12로 강제한다', async () => {
|
||||
it('분당 요청 상한을 30으로 강제한다', async () => {
|
||||
const handler = handlers.get(IPC_CHANNELS.SUGGESTION.SET_CONFIG)
|
||||
if (!handler) throw new Error('suggestion config handler was not registered')
|
||||
|
||||
await handler({}, { maxRequestsPerMinute: 99 })
|
||||
|
||||
expect(configSet).toHaveBeenCalledWith('suggestionMaxRequestsPerMinute', 12)
|
||||
expect(configSet).toHaveBeenCalledWith('suggestionMaxRequestsPerMinute', 30)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -48,9 +48,9 @@ describe('ConfigService suggestion tuning migration', () => {
|
|||
)
|
||||
await initConfigService()
|
||||
|
||||
expect(configGet('suggestionTuningRevision')).toBe(6)
|
||||
expect(configGet('suggestionTuningRevision')).toBe(7)
|
||||
expect(configGet('suggestionTriggerDelayMs')).toBe(600)
|
||||
expect(configGet('suggestionMaxRequestsPerMinute')).toBe(6)
|
||||
expect(configGet('suggestionMaxRequestsPerMinute')).toBe(20)
|
||||
expect(configGet('suggestionMinPrefixChars')).toBe(17)
|
||||
expect(configGet('suggestionDailyBudget')).toBe(777)
|
||||
expect(configGet('suggestionRequestTimeoutMs')).toBe(23000)
|
||||
|
|
@ -114,7 +114,7 @@ describe('ConfigService suggestion tuning migration', () => {
|
|||
// 옮기지 않는 액션은 그대로 남는다.
|
||||
expect(bindings['suggestion-next']).toEqual(OLD_NEXT)
|
||||
expect(bindings['suggestion-prev']).toEqual(OLD_PREV)
|
||||
expect(configGet('suggestionTuningRevision')).toBe(6)
|
||||
expect(configGet('suggestionTuningRevision')).toBe(7)
|
||||
|
||||
resetInMemoryConfig()
|
||||
})
|
||||
|
|
@ -176,7 +176,7 @@ describe('ConfigService suggestion tuning migration', () => {
|
|||
'../../../src/main/services/ConfigService'
|
||||
)
|
||||
await initConfigService()
|
||||
expect(configGet('suggestionTuningRevision')).toBe(6)
|
||||
expect(configGet('suggestionTuningRevision')).toBe(7)
|
||||
expect(configGet('suggestionTriggerDelayMs')).toBe(expected)
|
||||
resetInMemoryConfig()
|
||||
vi.doUnmock('electron-store')
|
||||
|
|
|
|||
|
|
@ -263,3 +263,59 @@ describe('TypoCorrectionService', () => {
|
|||
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('dkssudgktpdy'.length, '안녕하세요')
|
||||
})
|
||||
})
|
||||
|
||||
describe('TypoCorrectionService.propose — 제안 창에 함께 내놓을 교정 (적용하지 않음)', () => {
|
||||
beforeEach(() => {
|
||||
config.typoAutoCorrectEnabled = true
|
||||
config.typoAutoCorrectUseModel = true
|
||||
config.typoIgnoredWords = []
|
||||
config.inputExcludedApps = []
|
||||
})
|
||||
|
||||
it('수상한 구간이면 모델에 묻고, 고친 계획만 돌려준다 — 대상 앱에는 아무것도 보내지 않는다', async () => {
|
||||
const generate = vi.fn(async function* () {
|
||||
yield '안ㄴ뇽하세여 => 안녕하세요'
|
||||
})
|
||||
const fake = deps({ warmModel: () => 'gemma4:e4b', generate })
|
||||
const service = new TypoCorrectionService(fake.deps)
|
||||
|
||||
const plan = await service.propose(
|
||||
typingContext({ prefix: '안ㄴ뇽하세여.?', appName: 'Agent Switchboard.exe' }),
|
||||
new AbortController().signal
|
||||
)
|
||||
|
||||
expect(plan?.insertText).toBe('안녕하세요.?')
|
||||
expect(plan?.originalText).toBe('안ㄴ뇽하세여.?')
|
||||
expect(generate).toHaveBeenCalledTimes(1)
|
||||
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('수상하지 않으면 모델에 묻지 않는다 (제안이 늦어지지 않게)', async () => {
|
||||
const generate = vi.fn(async function* () {
|
||||
yield '없음'
|
||||
})
|
||||
const service = new TypoCorrectionService(deps({ warmModel: () => 'gemma4:e4b', generate }).deps)
|
||||
|
||||
const plan = await service.propose(typingContext({ prefix: '오늘 회의 자료 공유드립니다 ' }), new AbortController().signal)
|
||||
|
||||
expect(plan).toBeNull()
|
||||
expect(generate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('모델이 없어도 낱자 잡음은 결정적으로 지운다', async () => {
|
||||
const service = new TypoCorrectionService(deps().deps)
|
||||
const plan = await service.propose(typingContext({ prefix: '그ㅓ런건 전혀 ' }), new AbortController().signal)
|
||||
expect(plan?.insertText).toBe('그런건 전혀 ')
|
||||
})
|
||||
|
||||
it('터미널·제외 앱·꺼진 설정에서는 내놓지 않는다', async () => {
|
||||
const service = new TypoCorrectionService(deps().deps)
|
||||
const signal = new AbortController().signal
|
||||
expect(await service.propose(typingContext({ prefix: '그ㅓ런건 ', appName: 'WindowsTerminal.exe' }), signal)).toBeNull()
|
||||
config.inputExcludedApps = ['slack']
|
||||
expect(await service.propose(typingContext({ prefix: '그ㅓ런건 ' }), signal)).toBeNull()
|
||||
config.inputExcludedApps = []
|
||||
config.typoAutoCorrectEnabled = false
|
||||
expect(await service.propose(typingContext({ prefix: '그ㅓ런건 ' }), signal)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -581,8 +581,8 @@ describe('개인 문구', () => {
|
|||
describe('기본값 (실측 근거)', () => {
|
||||
it('자동 제안의 요청 상한은 보수적 기본 정책을 지킨다', () => {
|
||||
expect(SUGGESTION_DEFAULTS.triggerDelayMs).toBe(600)
|
||||
expect(SUGGESTION_DEFAULTS.minIntervalMs).toBe(5000)
|
||||
expect(SUGGESTION_DEFAULTS.maxRequestsPerMinute).toBe(6)
|
||||
expect(SUGGESTION_DEFAULTS.minIntervalMs).toBe(1200)
|
||||
expect(SUGGESTION_DEFAULTS.maxRequestsPerMinute).toBe(20)
|
||||
expect(SUGGESTION_DEFAULTS.dailyBudget).toBe(500)
|
||||
expect(SUGGESTION_DEFAULTS.maxCandidates).toBe(3)
|
||||
expect(SUGGESTION_DEFAULTS.maxOutputTokens).toBe(64)
|
||||
|
|
|
|||
216
apps/desktop/tests/main/services/suggestion-presence.test.ts
Normal file
216
apps/desktop/tests/main/services/suggestion-presence.test.ts
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
// 제안 창 반응성 — 빈 출력 재시도, 실패한 같은 글 재생성 방지, 멈추자마자 "생성 중" 자리 (2026-10-17)
|
||||
//
|
||||
// 실측: 문장 중간에서 공백 없이 끝난 prefill 은 gemma 가 곧바로 턴을 닫아 빈 출력이 됐고(18회 중 15회), 빈 출력마다
|
||||
// 창을 닫은 뒤 같은 글로 1초마다 다시 생성해 "떴다 꺼졌다" 를 반복했다.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const config = vi.hoisted(() => ({
|
||||
suggestionEnabled: true as boolean,
|
||||
suggestionModelId: 'gemma4:e4b' as string | null,
|
||||
llmModelId: 'gemma4:e4b' as string | null,
|
||||
inputExcludedApps: [] as string[],
|
||||
suggestionTriggerDelayMs: 600,
|
||||
suggestionMinPrefixChars: 4,
|
||||
suggestionMaxRequestsPerMinute: 20,
|
||||
suggestionDailyBudget: 500,
|
||||
suggestionRequestTimeoutMs: 8000,
|
||||
inputLearnTypedText: false,
|
||||
inputTelemetryEnabled: false,
|
||||
suggestionOverlayInteractive: true,
|
||||
insertMethod: 'clipboard'
|
||||
}))
|
||||
const harness = vi.hoisted(() => ({
|
||||
streamGenerate: vi.fn(),
|
||||
insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })),
|
||||
replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({
|
||||
success: true,
|
||||
method: 'clipboard',
|
||||
textLength: text.length
|
||||
}))
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/ConfigService', () => ({
|
||||
configGet: vi.fn((key: keyof typeof config) => config[key]),
|
||||
configSet: vi.fn()
|
||||
}))
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/LocalLLMService', () => ({
|
||||
getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/InputTelemetryService', () => ({
|
||||
getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/PersonalGraphService', () => ({
|
||||
getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/TextInsertService', () => ({
|
||||
getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/modifier-state', () => ({ waitForModifiersReleased: async () => true }))
|
||||
vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null }))
|
||||
vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() }))
|
||||
vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} }))
|
||||
|
||||
import {
|
||||
SuggestionService,
|
||||
type SuggestionServiceDeps
|
||||
} from '../../../src/main/services/SuggestionService'
|
||||
import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget'
|
||||
import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker'
|
||||
import type { TypingContext } from '../../../src/main/services/InputTelemetryService'
|
||||
|
||||
const PREFIX = '지금 테스트 해보는데 잠시 쉬면'
|
||||
|
||||
function typingContext(overrides: Partial<TypingContext> = {}): TypingContext {
|
||||
const prefix = overrides.prefix ?? PREFIX
|
||||
return {
|
||||
prefix,
|
||||
fullText: prefix,
|
||||
caretOffset: prefix.length,
|
||||
documentBefore: prefix,
|
||||
anchor: { x: 10, y: 10, width: 2, height: 16 },
|
||||
anchorKind: 'caret',
|
||||
isPassword: false,
|
||||
isEditable: true,
|
||||
isComposing: false,
|
||||
hasSelection: false,
|
||||
available: true,
|
||||
appName: 'notepad.exe',
|
||||
windowTitle: 'notes',
|
||||
windowHandle: null,
|
||||
idleMs: 2000,
|
||||
capturedAt: Date.now(),
|
||||
editedSinceFocus: true,
|
||||
typedRecently: true,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function deps(): SuggestionServiceDeps {
|
||||
const warmth = new ModelWarmTracker()
|
||||
warmth.noteWarm('gemma4:e4b', Date.now() + 600_000)
|
||||
return {
|
||||
repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) },
|
||||
budget: new SuggestionBudget(),
|
||||
warmth,
|
||||
foreground: { currentWindowHandle: () => null },
|
||||
learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: vi.fn() }
|
||||
}
|
||||
}
|
||||
|
||||
interface Internal {
|
||||
_generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise<void>
|
||||
_lastContext: TypingContext | null
|
||||
_lastRequestAt: number
|
||||
}
|
||||
|
||||
let services: SuggestionService[] = []
|
||||
function create(): SuggestionService {
|
||||
const service = new SuggestionService(deps())
|
||||
services.push(service)
|
||||
return service
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
harness.streamGenerate.mockReset()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const service of services) service.dispose()
|
||||
services = []
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('빈 출력 재시도', () => {
|
||||
it('모델이 곧바로 턴을 닫으면 prefill 끝에 공백을 붙여 한 번 더 뽑고, 띄어 쓴 후보로 쓴다', async () => {
|
||||
harness.streamGenerate.mockImplementation(async function* (prompt: string) {
|
||||
yield prompt.endsWith(' ') ? '렉 걸리는 느낌이 있어.' : ''
|
||||
})
|
||||
const service = create()
|
||||
;(service as unknown as Internal)._lastContext = typingContext()
|
||||
await (service as unknown as Internal)._generate(PREFIX, typingContext(), 3, 160)
|
||||
|
||||
const prompts = harness.streamGenerate.mock.calls.map(([prompt]) => String(prompt))
|
||||
expect(prompts[0].endsWith(PREFIX)).toBe(true)
|
||||
expect(prompts[1].endsWith(`${PREFIX} `)).toBe(true)
|
||||
expect(service.getState().candidates[0]).toEqual({ text: '렉 걸리는 느낌이 있어.', rank: 0 })
|
||||
// 채우기도 공백 붙인 변형으로 보낸다
|
||||
await vi.waitFor(() => expect(harness.streamGenerate.mock.calls.length).toBeGreaterThan(2))
|
||||
expect(String(harness.streamGenerate.mock.calls[2][0]).endsWith(`${PREFIX} `)).toBe(true)
|
||||
})
|
||||
|
||||
it('끝내 비면 창을 닫고, 같은 글로 멈춰 있는 동안 다시 생성하지 않는다 (더 치면 다시 한다)', async () => {
|
||||
harness.streamGenerate.mockImplementation(async function* () {
|
||||
yield ''
|
||||
})
|
||||
const service = create()
|
||||
const context = typingContext()
|
||||
service.handleTypingContext(context)
|
||||
await vi.waitFor(() => expect(harness.streamGenerate).toHaveBeenCalledTimes(2))
|
||||
await vi.waitFor(() => expect(service.getState().generating).toBe(false))
|
||||
|
||||
// 같은 글의 다음 스냅샷들 — 1.2초 간격이 지나도 다시 생성하지 않는다
|
||||
vi.useFakeTimers({ now: Date.now() + 5000 })
|
||||
service.handleTypingContext({ ...context, idleMs: 7000 })
|
||||
service.handleTypingContext({ ...context, idleMs: 8000 })
|
||||
expect(harness.streamGenerate).toHaveBeenCalledTimes(2)
|
||||
expect(service.getState().generating).toBe(false)
|
||||
vi.useRealTimers()
|
||||
|
||||
harness.streamGenerate.mockImplementation(async function* () {
|
||||
yield ' 다음 문장.'
|
||||
})
|
||||
// 실제로는 더 치는 데 시간이 걸린다 — 요청 간격(1.2초)이 지난 것으로 둔다
|
||||
;(service as unknown as Internal)._lastRequestAt = Date.now() - 5000
|
||||
const longer = `${PREFIX} 그리고`
|
||||
service.handleTypingContext(typingContext({ prefix: longer, documentBefore: longer, fullText: longer, caretOffset: longer.length }))
|
||||
await vi.waitFor(() => expect(service.getState().candidates.length).toBeGreaterThan(0))
|
||||
})
|
||||
})
|
||||
|
||||
describe('멈추자마자 "생성 중" 자리', () => {
|
||||
it('트리거 지연 전이라도 presenceDelayMs 가 지나면 생성 중으로 보이고, 생성은 아직 시작하지 않는다', () => {
|
||||
const service = create()
|
||||
const updates: boolean[] = []
|
||||
service.on('updated', (state) => updates.push(state.generating))
|
||||
|
||||
service.handleTypingContext(typingContext({ idleMs: 400 }))
|
||||
|
||||
expect(service.getState().generating).toBe(true)
|
||||
expect(service.getState().anchor).not.toBeNull()
|
||||
expect(harness.streamGenerate).not.toHaveBeenCalled()
|
||||
expect(updates).toEqual([true])
|
||||
// 정책상 "표시 중" 은 아니다 — 생성 시점에 already-visible 로 막히면 안 된다
|
||||
expect(service.isPresentationActive).toBe(false)
|
||||
})
|
||||
|
||||
it('다시 치기 시작하면 조용히 거두고, 트리거 지연이 지나면 생성으로 이어진다', async () => {
|
||||
harness.streamGenerate.mockImplementation(async function* () {
|
||||
yield ' 이어지는 문장.'
|
||||
})
|
||||
const service = create()
|
||||
service.handleTypingContext(typingContext({ idleMs: 400 }))
|
||||
expect(service.getState().generating).toBe(true)
|
||||
|
||||
const typed = `${PREFIX}고`
|
||||
service.handleTypingContext(typingContext({ prefix: typed, documentBefore: typed, fullText: typed, caretOffset: typed.length, idleMs: 80 }))
|
||||
expect(service.getState().generating).toBe(false)
|
||||
|
||||
service.handleTypingContext(typingContext({ prefix: typed, documentBefore: typed, fullText: typed, caretOffset: typed.length, idleMs: 400 }))
|
||||
expect(service.getState().generating).toBe(true)
|
||||
service.handleTypingContext(typingContext({ prefix: typed, documentBefore: typed, fullText: typed, caretOffset: typed.length, idleMs: 800 }))
|
||||
await vi.waitFor(() => expect(service.getState().candidates.length).toBeGreaterThan(0))
|
||||
})
|
||||
|
||||
it('생성으로 이어지지 않으면 presenceMaxMs 뒤 스스로 거둔다', () => {
|
||||
vi.useFakeTimers()
|
||||
const service = create()
|
||||
service.handleTypingContext(typingContext({ idleMs: 400 }))
|
||||
expect(service.getState().generating).toBe(true)
|
||||
vi.advanceTimersByTime(3100)
|
||||
expect(service.getState().generating).toBe(false)
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,242 @@
|
|||
// 제안 창에 오타 교정을 함께 내놓기 (2026-10-17 사용자 요청)
|
||||
//
|
||||
// "안ㄴ뇽하세여.?" 를 치고 멈추면 조용히 고치지 않고, 제안 창에 "지운 글자 → 고친 글자" 를 보여 주며
|
||||
// 모델에는 고친 글로 이어 쓰게 한다. 수락하면 오타 구간을 지우고 고친 글 + 후보를 한 번에 넣는다.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const config = vi.hoisted(() => ({
|
||||
suggestionEnabled: true as boolean,
|
||||
suggestionModelId: 'gemma4:e4b' as string | null,
|
||||
llmModelId: 'gemma4:e4b' as string | null,
|
||||
inputExcludedApps: [] as string[],
|
||||
suggestionTriggerDelayMs: 600,
|
||||
suggestionMinPrefixChars: 4,
|
||||
suggestionMaxRequestsPerMinute: 20,
|
||||
suggestionDailyBudget: 500,
|
||||
suggestionRequestTimeoutMs: 8000,
|
||||
inputLearnTypedText: false,
|
||||
inputTelemetryEnabled: false,
|
||||
suggestionOverlayInteractive: true,
|
||||
insertMethod: 'clipboard'
|
||||
}))
|
||||
const harness = vi.hoisted(() => ({
|
||||
streamGenerate: vi.fn(),
|
||||
insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })),
|
||||
replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({
|
||||
success: true,
|
||||
method: 'clipboard',
|
||||
textLength: text.length
|
||||
}))
|
||||
}))
|
||||
|
||||
vi.mock('../../../src/main/services/ConfigService', () => ({
|
||||
configGet: vi.fn((key: keyof typeof config) => config[key]),
|
||||
configSet: vi.fn()
|
||||
}))
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/LocalLLMService', () => ({
|
||||
getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/InputTelemetryService', () => ({
|
||||
getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/PersonalGraphService', () => ({
|
||||
getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/TextInsertService', () => ({
|
||||
getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/modifier-state', () => ({ waitForModifiersReleased: async () => true }))
|
||||
vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null }))
|
||||
vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() }))
|
||||
vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} }))
|
||||
|
||||
import {
|
||||
SuggestionService,
|
||||
type SuggestionServiceDeps,
|
||||
type SuggestionTypoProposer
|
||||
} from '../../../src/main/services/SuggestionService'
|
||||
import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget'
|
||||
import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker'
|
||||
import type { TypingContext } from '../../../src/main/services/InputTelemetryService'
|
||||
|
||||
const TYPO = '안ㄴ뇽하세여.?'
|
||||
|
||||
function typingContext(overrides: Partial<TypingContext> = {}): TypingContext {
|
||||
const prefix = overrides.prefix ?? TYPO
|
||||
return {
|
||||
prefix,
|
||||
fullText: prefix,
|
||||
caretOffset: prefix.length,
|
||||
documentBefore: prefix,
|
||||
anchor: null,
|
||||
anchorKind: null,
|
||||
isPassword: false,
|
||||
isEditable: true,
|
||||
isComposing: false,
|
||||
hasSelection: false,
|
||||
available: true,
|
||||
appName: 'Agent Switchboard.exe',
|
||||
windowTitle: 'Agent Switchboard',
|
||||
windowHandle: null,
|
||||
idleMs: 2000,
|
||||
capturedAt: Date.now(),
|
||||
editedSinceFocus: true,
|
||||
typedRecently: true,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
const proposer: SuggestionTypoProposer = {
|
||||
propose: vi.fn(async () => ({
|
||||
originalText: TYPO,
|
||||
insertText: '안녕하세요.?',
|
||||
corrections: [{ start: 0, end: 6, to: '안녕하세요' }]
|
||||
}))
|
||||
}
|
||||
|
||||
function deps(expectKeys = vi.fn()): SuggestionServiceDeps {
|
||||
const warmth = new ModelWarmTracker()
|
||||
warmth.noteWarm('gemma4:e4b', Date.now() + 600_000)
|
||||
return {
|
||||
repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) },
|
||||
budget: new SuggestionBudget(),
|
||||
warmth,
|
||||
foreground: { currentWindowHandle: () => null },
|
||||
learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: vi.fn(), expectProgrammaticKeys: expectKeys }
|
||||
}
|
||||
}
|
||||
|
||||
interface Internal {
|
||||
_generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise<void>
|
||||
_lastContext: TypingContext | null
|
||||
}
|
||||
|
||||
let services: SuggestionService[] = []
|
||||
|
||||
async function visible(context: TypingContext, expectKeys = vi.fn()): Promise<SuggestionService> {
|
||||
const service = new SuggestionService(deps(expectKeys))
|
||||
services.push(service)
|
||||
service.setTypoProposer(proposer)
|
||||
const internal = service as unknown as Internal
|
||||
internal._lastContext = context
|
||||
await internal._generate(context.prefix, context, 3, 160)
|
||||
return service
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
harness.streamGenerate.mockReset()
|
||||
harness.streamGenerate.mockImplementation(async function* () {
|
||||
yield ' 오늘 회의 자료 공유드립니다.'
|
||||
})
|
||||
harness.insertText.mockClear()
|
||||
harness.replaceBeforeCaret.mockClear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const service of services) service.dispose()
|
||||
services = []
|
||||
})
|
||||
|
||||
describe('제안 + 오타 교정', () => {
|
||||
it('모델에는 고친 글을 보여 주고, 세션 상태에 교정(지운 글자 → 고친 글자)을 싣는다', async () => {
|
||||
const service = await visible(typingContext())
|
||||
|
||||
const prompt = String(harness.streamGenerate.mock.calls[0][0])
|
||||
expect(prompt).toContain('안녕하세요.?')
|
||||
expect(prompt).not.toContain('안ㄴ뇽')
|
||||
const state = service.getState()
|
||||
expect(state.candidates[0]?.text).toBe('오늘 회의 자료 공유드립니다.')
|
||||
expect(state.correction).toEqual({ from: TYPO, to: '안녕하세요.?', edits: [{ start: 0, end: 6, to: '안녕하세요' }] })
|
||||
})
|
||||
|
||||
it('수락하면 오타 구간을 지우고 고친 글 + 후보를 한 번에 넣는다', async () => {
|
||||
const expectKeys = vi.fn()
|
||||
const service = await visible(typingContext(), expectKeys)
|
||||
|
||||
const result = await service.accept()
|
||||
|
||||
expect(result).toEqual({ ok: true })
|
||||
expect(harness.insertText).not.toHaveBeenCalled()
|
||||
expect(harness.replaceBeforeCaret).toHaveBeenCalledWith(TYPO.length, '안녕하세요.? 오늘 회의 자료 공유드립니다.', 'clipboard', {
|
||||
commitComposition: false
|
||||
})
|
||||
// 백스페이스 8 + Ctrl,V 2
|
||||
expect(expectKeys).toHaveBeenCalledWith(TYPO.length + 2)
|
||||
})
|
||||
|
||||
it('커서 앞 글자가 조합 중이면 먼저 확정하고 지운다', async () => {
|
||||
const context = typingContext({ isComposing: true })
|
||||
const service = await visible(context)
|
||||
|
||||
await service.accept()
|
||||
|
||||
expect(harness.replaceBeforeCaret).toHaveBeenCalledWith(TYPO.length, expect.any(String), 'clipboard', {
|
||||
commitComposition: true
|
||||
})
|
||||
})
|
||||
|
||||
it('수락 직전 원문 끝이 교정 원문과 다르면 교정은 버리고 후보만 넣는다', async () => {
|
||||
const service = await visible(typingContext())
|
||||
// 같은 세션으로 보이되(마지막 글자만 바뀜) 끝이 더 이상 교정 원문이 아니다.
|
||||
;(service as unknown as Internal)._lastContext = typingContext({ prefix: '안ㄴ뇽하세여.!' })
|
||||
|
||||
await service.accept()
|
||||
|
||||
expect(harness.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||
expect(harness.insertText).toHaveBeenCalledWith(' 오늘 회의 자료 공유드립니다.', 'clipboard')
|
||||
})
|
||||
|
||||
it('교정 포트가 없거나 교정이 없으면 예전처럼 후보만 넣는다', async () => {
|
||||
const service = new SuggestionService(deps())
|
||||
services.push(service)
|
||||
const context = typingContext({ prefix: '오늘 회의에서 논의한 내용을 정리해서', documentBefore: null })
|
||||
;(service as unknown as Internal)._lastContext = context
|
||||
await (service as unknown as Internal)._generate(context.prefix, context, 3, 160)
|
||||
|
||||
expect(service.getState().correction).toBeNull()
|
||||
await service.accept()
|
||||
expect(harness.insertText).toHaveBeenCalledTimes(1)
|
||||
expect(harness.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('낱자 없는 오타는 첫 후보를 늦추지 않고, 첫 후보 뒤 정밀 검사로 교정 줄을 붙인다', async () => {
|
||||
const PREFIX = '오늘 회으에서 나온 얘기를 정리하면 '
|
||||
const late: SuggestionTypoProposer = {
|
||||
propose: vi.fn(async (_context, _signal, options) =>
|
||||
options?.thorough
|
||||
? { originalText: '회으에서 나온 얘기를 정리하면 ', insertText: '회의에서 나온 얘기를 정리하면 ', corrections: [{ start: 3, end: 7, to: '회의에서' }] }
|
||||
: null
|
||||
)
|
||||
}
|
||||
const service = new SuggestionService(deps())
|
||||
services.push(service)
|
||||
service.setTypoProposer(late)
|
||||
const context = typingContext({ prefix: PREFIX, documentBefore: PREFIX })
|
||||
;(service as unknown as Internal)._lastContext = context
|
||||
await (service as unknown as Internal)._generate(PREFIX, context, 3, 160)
|
||||
|
||||
// 첫 요청 전 검사는 정밀 검사가 아니었다
|
||||
expect(late.propose).toHaveBeenNthCalledWith(1, expect.anything(), expect.anything(), { thorough: false })
|
||||
await vi.waitFor(() => expect(service.getState().correction?.to).toBe('회의에서 나온 얘기를 정리하면 '))
|
||||
expect(service.getState().correction?.edits).toEqual([{ start: 0, end: 4, to: '회의에서' }])
|
||||
})
|
||||
|
||||
it('채우기 후보도 prefill 로만 만든다 — 지시형(대답하는 말투)을 섞지 않는다', async () => {
|
||||
let call = 0
|
||||
harness.streamGenerate.mockImplementation(async function* () {
|
||||
call += 1
|
||||
yield ` ${'가나다라마바사'.charAt(call)}로 이어 쓴다.`
|
||||
})
|
||||
const service = await visible(typingContext())
|
||||
|
||||
await vi.waitFor(() => expect(service.getState().generating).toBe(false))
|
||||
expect(harness.streamGenerate.mock.calls.length).toBeGreaterThan(2)
|
||||
for (const [, options] of harness.streamGenerate.mock.calls) {
|
||||
expect(options).toEqual(expect.objectContaining({ raw: true }))
|
||||
}
|
||||
})
|
||||
})
|
||||
107
apps/desktop/tests/main/update-signature.test.ts
Normal file
107
apps/desktop/tests/main/update-signature.test.ts
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import { createHash, generateKeyPairSync, sign } from 'node:crypto'
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
UPDATE_SIGNING_PUBLIC_KEY,
|
||||
readSignedManifest,
|
||||
sha512Base64OfFile,
|
||||
verifyDownloadedUpdate,
|
||||
} from '../../src/main/update-signature'
|
||||
import { versionedManifestUrl } from '../../src/main/update-feed'
|
||||
|
||||
const { privateKey, publicKey } = generateKeyPairSync('ed25519')
|
||||
const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString()
|
||||
|
||||
function fixture(version = '1.10.0') {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'd3ro-update-sig-'))
|
||||
const installerPath = join(dir, 'setup.exe')
|
||||
writeFileSync(installerPath, `installer bytes ${version}`)
|
||||
const sha512 = createHash('sha512').update(readFileSync(installerPath)).digest('base64')
|
||||
const manifest = [
|
||||
`version: ${version}`,
|
||||
'files:',
|
||||
` - url: D3RO-Voice-Setup-${version}-x64.exe`,
|
||||
` sha512: ${sha512}`,
|
||||
' size: 22',
|
||||
`path: D3RO-Voice-Setup-${version}-x64.exe`,
|
||||
`sha512: ${sha512}`,
|
||||
"releaseDate: '2026-10-17T00:00:00.000Z'",
|
||||
'',
|
||||
].join('\n')
|
||||
const signature = sign(null, Buffer.from(manifest), privateKey).toString('base64')
|
||||
return { installerPath, manifest, signature, sha512 }
|
||||
}
|
||||
|
||||
function fetcher(files: Record<string, string>) {
|
||||
return async (url: string): Promise<string> => {
|
||||
const name = url.endsWith('.sig') ? 'sig' : 'manifest'
|
||||
const body = files[name]
|
||||
if (body === undefined) throw new Error(`HTTP 404 ${url}`)
|
||||
return body
|
||||
}
|
||||
}
|
||||
|
||||
describe('update-signature', () => {
|
||||
it('reads version and sha512 from a correctly signed manifest', () => {
|
||||
const { manifest, signature, sha512 } = fixture()
|
||||
expect(readSignedManifest({ manifest, signature, publicKeyPem })).toEqual({ version: '1.10.0', sha512 })
|
||||
})
|
||||
|
||||
it('rejects a tampered manifest, a foreign key, and a malformed signature', () => {
|
||||
const { manifest, signature } = fixture()
|
||||
expect(readSignedManifest({ manifest: manifest.replace('1.10.0', '9.9.9'), signature, publicKeyPem })).toBeNull()
|
||||
expect(readSignedManifest({ manifest, signature, publicKeyPem: UPDATE_SIGNING_PUBLIC_KEY })).toBeNull()
|
||||
expect(readSignedManifest({ manifest, signature: 'not-a-signature', publicKeyPem })).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts the downloaded installer only when manifest, version and hash all match', async () => {
|
||||
const { installerPath, manifest, signature } = fixture()
|
||||
const base = { version: '1.10.0', installerPath, manifestUrl: 'https://feed/1.10.0/latest.yml', publicKeyPem }
|
||||
await expect(verifyDownloadedUpdate({ ...base, fetchText: fetcher({ manifest, sig: signature }) })).resolves.toBeNull()
|
||||
|
||||
await expect(
|
||||
verifyDownloadedUpdate({ ...base, version: '1.11.0', fetchText: fetcher({ manifest, sig: signature }) }),
|
||||
).resolves.toMatch(/버전/)
|
||||
|
||||
writeFileSync(installerPath, 'swapped installer')
|
||||
await expect(verifyDownloadedUpdate({ ...base, fetchText: fetcher({ manifest, sig: signature }) })).resolves.toMatch(
|
||||
/sha512/,
|
||||
)
|
||||
})
|
||||
|
||||
it('fails closed when the signature file is missing', async () => {
|
||||
const { installerPath, manifest } = fixture()
|
||||
await expect(
|
||||
verifyDownloadedUpdate({
|
||||
version: '1.10.0',
|
||||
installerPath,
|
||||
manifestUrl: 'https://feed/1.10.0/latest.yml',
|
||||
publicKeyPem,
|
||||
fetchText: fetcher({ manifest }),
|
||||
}),
|
||||
).resolves.toMatch(/받지 못함/)
|
||||
})
|
||||
|
||||
it('hashes files as base64 sha512 like electron-builder', async () => {
|
||||
const { installerPath, sha512 } = fixture()
|
||||
await expect(sha512Base64OfFile(installerPath)).resolves.toBe(sha512)
|
||||
})
|
||||
|
||||
it('embeds the same public key as release/desktop-update-public.pem', () => {
|
||||
const pem = readFileSync(join(__dirname, '../../../../release/desktop-update-public.pem'), 'utf8')
|
||||
expect(UPDATE_SIGNING_PUBLIC_KEY.trim()).toBe(pem.trim())
|
||||
})
|
||||
|
||||
it('verifies against the immutable versioned path, not the mutable latest alias', () => {
|
||||
expect(versionedManifestUrl('1.10.0')).toBe(
|
||||
'https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/1.10.0/latest.yml',
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps the electron-updater hook this verifier replaces', async () => {
|
||||
const { NsisUpdater } = await import('electron-updater')
|
||||
expect(typeof (NsisUpdater.prototype as unknown as { verifySignature?: unknown }).verifySignature).toBe('function')
|
||||
})
|
||||
})
|
||||
|
|
@ -339,7 +339,7 @@ describe('suggestionPanelHeight — style.css 고정 치수와 같은 규칙', (
|
|||
'../../../src/main/windows/suggestion-overlay-geometry'
|
||||
)
|
||||
const base = { candidateCount: 0, activeIndex: 0, generating: false, warmingUp: false, hasPartialText: false }
|
||||
expect(SUGGESTION_OVERLAY_MAX_HEIGHT).toBe(208)
|
||||
expect(SUGGESTION_OVERLAY_MAX_HEIGHT).toBe(238)
|
||||
expect(suggestionPanelHeight({ ...base, warmingUp: true })).toBe(54)
|
||||
expect(suggestionPanelHeight({ ...base, generating: true })).toBe(54)
|
||||
expect(suggestionPanelHeight({ ...base, generating: true, hasPartialText: true })).toBe(98)
|
||||
|
|
@ -349,6 +349,9 @@ describe('suggestionPanelHeight — style.css 고정 치수와 같은 규칙', (
|
|||
// 두 번째 페이지에 후보 1개
|
||||
expect(suggestionPanelHeight({ ...base, candidateCount: 4, activeIndex: 3 })).toBe(116)
|
||||
expect(suggestionPanelHeight({ ...base, candidateCount: 12, activeIndex: 5 })).toBe(208)
|
||||
// 오타 교정 줄은 후보가 있을 때만 30px 를 더한다
|
||||
expect(suggestionPanelHeight({ ...base, candidateCount: 3, hasCorrection: true })).toBe(238)
|
||||
expect(suggestionPanelHeight({ ...base, generating: true, hasCorrection: true })).toBe(54)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -151,8 +151,8 @@ def versionSettingsValid = configuredVersionName != null &&
|
|||
configuredVersionName ==~ strictSemver &&
|
||||
configuredVersionCodeValue != null &&
|
||||
configuredVersionCodeValue <= 2100000000L
|
||||
def resolvedVersionName = versionSettingsValid ? configuredVersionName : "1.9.0"
|
||||
def resolvedVersionCode = versionSettingsValid ? configuredVersionCodeValue.toInteger() : 1090000
|
||||
def resolvedVersionName = versionSettingsValid ? configuredVersionName : "1.10.0"
|
||||
def resolvedVersionCode = versionSettingsValid ? configuredVersionCodeValue.toInteger() : 1100000
|
||||
|
||||
def requiredReleaseSettings = [
|
||||
D3RO_RELEASE_STORE_FILE: releaseStoreFilePath,
|
||||
|
|
|
|||
|
|
@ -257,7 +257,7 @@
|
|||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1090000;
|
||||
CURRENT_PROJECT_VERSION = 1100000;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = D3ROVoice/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
|
||||
|
|
@ -265,7 +265,7 @@
|
|||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.9.0;
|
||||
MARKETING_VERSION = 1.10.0;
|
||||
OTHER_LDFLAGS = (
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
|
|
@ -287,14 +287,14 @@
|
|||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CURRENT_PROJECT_VERSION = 1090000;
|
||||
CURRENT_PROJECT_VERSION = 1100000;
|
||||
INFOPLIST_FILE = D3ROVoice/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.9.0;
|
||||
MARKETING_VERSION = 1.10.0;
|
||||
OTHER_LDFLAGS = (
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
Stability and performance improvements.
|
||||
|
|
@ -0,0 +1 @@
|
|||
안정성과 성능을 개선했습니다.
|
||||
14
apps/mobile-rn/package-lock.json
generated
14
apps/mobile-rn/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "@d3ro/mobile-rn",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@d3ro/mobile-rn",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"dependencies": {
|
||||
"@d3ro/api-client": "file:../../packages/api-client",
|
||||
"@d3ro/core": "file:../../packages/core",
|
||||
|
|
@ -62,7 +62,7 @@
|
|||
},
|
||||
"../..": {
|
||||
"name": "d3ro-voice-monorepo",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"apps/desktop",
|
||||
|
|
@ -81,7 +81,7 @@
|
|||
},
|
||||
"../../packages/api-client": {
|
||||
"name": "@d3ro/api-client",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -98,7 +98,7 @@
|
|||
},
|
||||
"../../packages/core": {
|
||||
"name": "@d3ro/core",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"docx": "^9.6.1"
|
||||
|
|
@ -109,7 +109,7 @@
|
|||
},
|
||||
"../../packages/i18n": {
|
||||
"name": "@d3ro/i18n",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.0.0"
|
||||
|
|
@ -120,7 +120,7 @@
|
|||
},
|
||||
"../../packages/ui-native": {
|
||||
"name": "@d3ro/ui-native",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/react": "*"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/mobile-rn",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"android": "react-native run-android",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/web",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice 웹 앱 — Next.js 기반 SaaS 인터페이스",
|
||||
"scripts": {
|
||||
|
|
|
|||
|
|
@ -139,7 +139,7 @@ export function Sidebar(): React.ReactElement {
|
|||
</PhosphorText>
|
||||
</Box>
|
||||
<Box sx={{ fontSize: '10px', fontFamily: 'ui-monospace, monospace', color: d3roPalette.text.muted }}>
|
||||
v1.9.0
|
||||
v1.10.0
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# D3RO Voice 릴리스 가이드
|
||||
|
||||
기준일: 2026-09-18. 이 문서는 desktop GitLab 패키지·자동 업데이트와 mobile store release의 경계를 분리한다. 태그 생성이나 HTTP 200 하나만으로 배포 완료를 선언하지 않는다.
|
||||
기준일: 2026-10-17. 이 문서는 desktop 자동 업데이트(Forgejo feed)와 mobile store release의 경계를 분리한다. 태그 생성이나 HTTP 200 하나만으로 배포 완료를 선언하지 않는다.
|
||||
|
||||
## 현재 release identity
|
||||
|
||||
|
|
@ -12,38 +12,62 @@
|
|||
| Android upload key | alias `d3ro-upload-20260821`, cert SHA-256 `4F:AC:69:24:...:15:2B:54` | external PKCS12·user-only ACL·Credential Manager·private-key readback GREEN; CI secret·복구 백업·AAB signer 대조 대기 |
|
||||
| release evidence | Ed25519 public `release/mobile-release-evidence-public.pem`, keyId `2797d3e6...4a890b7f` | external private key ACL·roundtrip GREEN; CI private-key secret·복구 백업 대기 |
|
||||
| desktop offline license | Ed25519 public `apps/desktop/resources/license/production-public.pem`, keyId `5c52b765...81a887f` | 새 전용 keypair·external private ACL·roundtrip·desktop production build GREEN; admin `ADMIN_LICENSE_PRIVATE_KEY` secret 주입 대기 |
|
||||
| Windows Authenticode | external public-trust code-signing certificate | production PFX 없음. Forgejo 저장소 시크릿 4종(`WIN_CSC_LINK`/`WIN_CSC_KEY_PASSWORD`/`WIN_CSC_EXPECTED_SIGNER_SUBJECT`/`FORGEJO_TOKEN`)이 0건이라 릴리스 파이프라인이 fail-closed. `scripts/ci/set-forgejo-secrets.mjs --check`로 확인한다. GREEN 전까지 게시 금지 |
|
||||
| Windows Authenticode | external public-trust code-signing certificate | production PFX 없음(한국 개인은 Azure Artifact Signing 불가, 사업자면 가능). 2026-10-17부터 **선택 사항** — 없으면 무서명 설치본 + Ed25519 서명 `latest.yml` 로 게시하고 앱이 검증한다 |
|
||||
| 업데이트 서명 키 | Ed25519 public `release/desktop-update-public.pem` (== `apps/desktop/src/main/update-signature.ts`), private = `.env` `D3RO_UPDATE_SIGNING_KEY` | 2026-10-17 생성. **교체·분실 금지** — 이 공개키를 내장한 설치본은 다른 키로 서명된 릴리스를 거부한다. `.env` 백업 필수 |
|
||||
| Firebase | Console `u/0`, `u/1` 모두 D3RO project 없음 | 사용자 승인 후 project·Android app 생성 필요 |
|
||||
| AdMob | app `ca-app-pub-1039714767792854~6427959892`; banner `/9840591290`; rewarded `/2255790918` | SSOT 확정. `검토 필요`·`광고 게재 제한`·store 미연결·결제 프로필 미완료 |
|
||||
| updater feed (canonical) | `https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/latest` | Forgejo Generic Registry. GitLab project 1172은 legacy mirror |
|
||||
| updater feed (canonical) | `https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/latest` | Forgejo Generic Registry. GitLab 미러는 2026-10-17 폐기 |
|
||||
| release notes | `CHANGELOG.md` `## [1.5.0]` + Play changelog `1050000.txt` (ko/en) | 태그 전 확정·검증 필수 |
|
||||
| 직전 게시본 | Forgejo Generic Registry `1.6.0` (2026-09-24 게시, unsigned installer + runtime/portable) | `v1.2.0`·`v1.3.0` 파이프라인은 서명/사이드카 선행 조건에서 실패했고 `v1.4.0`은 게시되지 않았다. `1.3.2`·`1.3.7`·`1.5.0`·`1.6.0`은 무서명 로컬 게시 경로(GAP-REL-06)를 사용했다 |
|
||||
|
||||
live canonical feed(`git.chanpaca.net/.../d3ro-voice/latest`)의 `latest.yml`은 현재 `1.6.0`을 보고한다(2026-09-24 무서명 로컬 게시). `runtime-latest/runtime.json`과 `portable-latest/portable.json`도 `1.6.0`이다. 서명 인증서를 확보하면 이보다 높은 버전을 서명 게시해 대체한다.
|
||||
|
||||
## desktop 릴리스 파이프라인
|
||||
## desktop 릴리스 = 한 줄 명령 (2026-10-17~)
|
||||
|
||||
```text
|
||||
authoritative release commit
|
||||
→ version/check/test/build GREEN
|
||||
→ annotated tag v1.3.0
|
||||
→ package-windows (build-win-x64)
|
||||
→ package-macos (build-mac-arm64)
|
||||
→ publish-release (build-linux-x64)
|
||||
├─ publish-forgejo-release.mjs ← canonical
|
||||
│ ├─ Forgejo Generic Registry /d3ro-voice/1.3.0/ (버전별 보존)
|
||||
│ ├─ Forgejo Generic Registry /d3ro-voice/latest/ (updater feed + update-policy.json)
|
||||
│ └─ Forgejo Release + CHANGELOG notes + 자산 첨부
|
||||
└─ publish-gitlab-release.mjs ← legacy mirror (pre-Forgejo 설치본)
|
||||
├─ GitLab Generic Registry /d3ro-voice/1.3.0/
|
||||
├─ GitLab Generic Registry /d3ro-voice/latest/
|
||||
└─ GitLab Release
|
||||
```bash
|
||||
npm run release -- patch # fix 1.9.0 → 1.9.1
|
||||
npm run release -- minor # feat 1.9.0 → 1.10.0
|
||||
npm run release -- minor --dry-run # 할 일만 출력
|
||||
npm run release -- --resume # 빌드·게시·푸시 중 실패 후 이어 가기
|
||||
```
|
||||
|
||||
- Forgejo·GitHub Actions도 동일한 `publish-forgejo-release.mjs`로 수렴한다. 어느
|
||||
빌더가 성공해도 canonical feed는 하나다.
|
||||
- `publish-forgejo-release.mjs`는 설치 자산을 먼저, `latest.yml`을 마지막에
|
||||
게시하고, 공개 URL에서 재검증한 뒤 Release 자산을 첨부한다.
|
||||
전제: `main`, 깨끗한 작업 트리, 루트 `.env` 의 `FORGEJO_TOKEN` · `D3RO_UPDATE_SIGNING_KEY`.
|
||||
사용자에게 보일 변경점은 미리 `CHANGELOG.md` `## [x.y.z] - 날짜` 로 써 두는 게 좋다(없으면
|
||||
커밋 제목으로 초안을 만든다). 모바일 Play '새 기능' 문구 파일이 없으면 일반 문구로 채운다.
|
||||
|
||||
```text
|
||||
scripts/ci/release-desktop.mjs
|
||||
1. 점검 main · 깨끗한 트리 · 토큰 · 서명 키가 저장소 공개키와 짝 · 태그/피드 미사용
|
||||
2. 버전 product-version.json + sync-version --write + CHANGELOG + Play 문구
|
||||
3. 게이트 version:check · release:metadata · typecheck
|
||||
4. 커밋 chore(release): vX.Y.Z + annotated 태그 (로컬)
|
||||
5. 빌드 build-desktop-installer.mjs (electron-vite → unpacked → ABI 보정·검증 → app-update.yml → NSIS, 100MiB 한도)
|
||||
6. 게시 publish-forgejo-release.mjs
|
||||
├─ latest.yml → latest.yml.sig (Ed25519)
|
||||
├─ /d3ro-voice/<version>/ 불변, 다른 바이트면 중단
|
||||
├─ /d3ro-voice/latest/ 설치 자산 먼저, 메타데이터·정책 마지막
|
||||
├─ 공개 URL 의 <version>/latest.yml + .sig 를 다시 받아 서명·설치본 sha512 검증
|
||||
└─ Forgejo Release + CHANGELOG 노트
|
||||
7. 푸시 chanpaca main + 태그 (origin 미러는 실패해도 경고)
|
||||
```
|
||||
|
||||
- CI(`.forgejo/workflows/release.yml`)는 같은 빌드·게시 스크립트를 쓰는 **예비 경로**다. 태그가
|
||||
푸시되면 돌지만 피드에 이미 그 버전이 있으면(보통) 건너뛴다. 시크릿: `FORGEJO_TOKEN`,
|
||||
`D3RO_UPDATE_SIGNING_KEY`(필수), `WIN_CSC_*`(선택) — `npm run release:secrets` 로 `.env` 에서 동기화.
|
||||
- 런타임(사이드카/ffmpeg)을 바꿨으면 먼저 `npm run release:portable:build` → `npm run release:portable`.
|
||||
게시 스크립트는 `runtime-latest` 가 이 빌드의 최소 런타임을 만족하지 않으면 아무것도 올리지 않는다.
|
||||
|
||||
### 앱 쪽 검증 (무서명 설치본 보호)
|
||||
|
||||
electron-updater 는 Authenticode 서명이 없으면 자체 검증을 건너뛴다. 그래서
|
||||
`update-adapters.ts` 가 NsisUpdater 의 `verifySignature` 단계를 `verifyDownloadedUpdate`
|
||||
(`update-signature.ts`)로 바꿔 끼운다: 불변 경로 `<version>/latest.yml` + `.sig` 를 받아 내장
|
||||
공개키로 서명을 확인하고, 그 version·sha512 가 받은 설치 파일과 같아야 설치한다. 하나라도
|
||||
어긋나면 electron-updater 가 파일을 지우고 `ERR_UPDATER_INVALID_SIGNATURE` 로 실패한다.
|
||||
1.9.0 이하 설치본은 이 검증이 없지만 새 릴리스를 그대로 받는다(서명 파일이 추가될 뿐).
|
||||
|
||||
### 공통 규칙
|
||||
|
||||
- 설치 바이너리는 저장소에 커밋하지 않는다. 배포 정본은 Forgejo feed이며,
|
||||
`site/public/releases/*/`, `apps/web/public/releases/*/`는 `.gitignore`로
|
||||
막혀 있어 build graph 밖이고 배포 산출물에 포함되지 않는다(추적 상태로 남아
|
||||
|
|
@ -55,7 +79,7 @@ authoritative release commit
|
|||
- `scripts/ci/sync-version.mjs --check --tag v1.3.0`는 태그, `release/product-version.json`, package/lockfile, Android/iOS 버전 면의 일치를 fail-closed로 검증한다.
|
||||
- `scripts/ci/verify-release-metadata.mjs`는 배포 메타데이터와 CI/publisher 계약을 검증한다.
|
||||
- 같은 gate는 desktop license public key가 Ed25519이고 `release/product-version.json`의 `desktopLicensePublicKeyId`와 일치하는지 검증한다. `electron.vite.config.ts`는 이 파일을 직접 읽으므로 누락·손상된 키로는 build가 시작되지 않는다.
|
||||
- `scripts/ci/publish-forgejo-release.mjs`는 canonical이다. 버전별 패키지를 먼저 올리고, `latest`에서 설치 자산 참조를 검증한 뒤 `latest.yml`과 `update-policy.json`을 마지막에 게시하고 공개 URL에서 재검증한다. `scripts/ci/publish-gitlab-release.mjs`는 legacy mirror로 동일 자산을 GitLab에도 올린다.
|
||||
- `scripts/ci/publish-forgejo-release.mjs`가 유일한 게시 경로다. 버전별 패키지를 먼저 올리고, `latest`에서 설치 자산 참조를 검증한 뒤 `latest.yml`(+`.sig`)과 `update-policy.json`을 마지막에 게시하고 공개 URL에서 서명까지 재검증한다.
|
||||
- Windows installer와 `latest.yml`은 필수다. macOS 산출물이 없는 Windows-only release를 의도했다면 그 판단을 release record에 남긴다.
|
||||
- `package-windows`는 external public-trust code-signing PFX를 protected file variable `WIN_CSC_PFX_FILE`로, 암호와 exact certificate subject를 protected `WIN_CSC_KEY_PASSWORD`, `WIN_CSC_EXPECTED_SIGNER_SUBJECT`로 받아야 한다. GitHub Release도 `WIN_CSC_LINK`, `WIN_CSC_KEY_PASSWORD`, `WIN_CSC_EXPECTED_SIGNER_SUBJECT`가 모두 없으면 실패한다.
|
||||
- `scripts/ci/verify-windows-release-artifact.ps1`는 installer와 unpacked app의 Authenticode `Valid`, exact signer subject, non-self-signed code-signing EKU, PE version, `latest.yml` path/size/SHA-512를 검증한다. 로컬 self-signed `Everything2EverythingDev`는 production 신뢰 인증서가 아니며 gate에서 명시적으로 거부한다.
|
||||
|
|
@ -174,21 +198,11 @@ node --env-file-if-exists=.env scripts/ci/set-forgejo-secrets.mjs --write
|
|||
10. Forgejo Release note/asset, `latest.yml`, `update-policy.json`, installer hash를 외부 public URL에서 다시 검증한다.
|
||||
11. 이전 설치본에서 자동 업데이트 E2E를 실행하고 실행 중 버전·프로세스·사용자 데이터 보존, 그리고 **업데이트 후 로컬 받아쓰기 1회 성공**을 확인한다.
|
||||
|
||||
## 자동 업데이트 게시 (런타임 분리 전제)
|
||||
## 설치본 크기와 네이티브 ABI
|
||||
|
||||
설치본은 **90MiB대**를 유지해야 한다. 로컬 AI 런타임(사이드카 엔진/ffmpeg)을 설치본에 넣으면
|
||||
Cloudflare 업로드 한도(100MiB)를 넘어 `latest.yml`을 게시할 수 없다.
|
||||
Cloudflare 업로드 한도(100MiB)를 넘어 게시할 수 없다 — `build-desktop-installer.mjs` 가 넘으면 실패한다.
|
||||
|
||||
```bash
|
||||
npm run build --workspace=@d3ro/desktop # 렌더러/메인 번들
|
||||
npm run release:portable:build # 런타임 번들 생성(엔진/ffmpeg)
|
||||
npm run release:portable # portable + runtime 채널 게시
|
||||
npm run release:updater:check # 업데이터 게시 예정 확인
|
||||
npm run release:updater -- --ack-unsigned # (인증서 없을 때만) 무서명 게시
|
||||
```
|
||||
|
||||
- 서명 인증서가 있으면 `--ack-unsigned` 없이 게시한다(권장). 무서명 게시는 명시적 예외이며
|
||||
스크립트가 플래그 없이는 즉시 실패한다(GAP-REL-06에 기록).
|
||||
- **네이티브 ABI 게이트 필수**: 패키징 후 `node scripts/ci/verify-native-abi.mjs`로 확인한다.
|
||||
개발 PC에서 `npm install`을 돌리면 `better-sqlite3`가 Node ABI로 재빌드되어 설치본이
|
||||
시작조차 못 한다(실측: 1.3.2). 로컬에서 실행 중인 Electron이 모듈을 잠그면
|
||||
|
|
@ -262,8 +276,10 @@ Desktop release를 게시해도 Android production 출시가 자동으로 완료
|
|||
- `scripts/ci/create-release-tag.mjs` — 릴리스 태그 게이트 (annotated/서명, 불변)
|
||||
- `scripts/ci/verify-release-metadata.mjs` — release metadata 자가 검증
|
||||
- `scripts/ci/verify-windows-release-artifact.ps1` — Windows version·updater metadata·Authenticode gate
|
||||
- `scripts/ci/publish-gitlab-release.mjs` — legacy GitLab registry·Release mirror publisher
|
||||
- `apps/desktop/src/main/update-feed.ts` — runtime updater URL SSOT (canonical Forgejo + legacy mirror 상수)
|
||||
- `scripts/ci/release-desktop.mjs` — 한 줄 릴리스 명령 (`npm run release`)
|
||||
- `scripts/ci/build-desktop-installer.mjs` — 설치본 빌드 (로컬·CI 공용)
|
||||
- `scripts/ci/lib/update-manifest-signature.mjs` · `apps/desktop/src/main/update-signature.ts` — latest.yml Ed25519 서명·검증
|
||||
- `apps/desktop/src/main/update-feed.ts` — runtime updater URL SSOT
|
||||
- `release/update-policy.json` — 채널·최소 지원 버전·강제 업데이트·full/delta·staged rollout·킬 스위치 SSOT
|
||||
- `apps/desktop/src/main/update-policy.ts` — 정책 파싱·결정 순수 로직
|
||||
- `scripts/ci/publish-forgejo-release.mjs` — canonical Forgejo registry·Release·feed publisher
|
||||
|
|
|
|||
|
|
@ -185,7 +185,8 @@ end-to-end behaviour has **not been verified by typing in a real app** (`11` GAP
|
|||
| INPUT-18 | Shortcut Safety Audit | [~] | [-] | [-] | [-] | Settings UI applies core `auditKeyBindingMap` to surface invalid/conflict issues while hold/double-press exceptions remain unchanged. |
|
||||
| INPUT-19 | Typo auto-correct while typing | [~] | [-] | [-] | [-] | **2026-10-03.** `TypoCorrectionService` (main, singleton + EventEmitter) runs on each `typed-context` before `SuggestionService`. Only after a pause (`TYPO_MIN_IDLE_MS` 600 ms), only in the 120-char/last-line region before the caret, only in fields the user just edited (`editedSinceFocus` + `typedRecently`); never in password/selection/IME-composing/caret-unknown fields, terminals, code editors (`shouldLearnFromApp`) or user-excluded apps. Layer 1 (core `typo-correction.ts`, pure): 2-set Korean layout mistypes both ways (`dkssudgktpdy`→`안녕하세요`, `솓`→`the`; conversion must compose fully into KS X 1001 common syllables — `hangul-common-syllables.ts`), always-wrong spellings (됬→됐, ㄹ께→ㄹ게, 몇일→며칠, teh→the, dont→don't …), and 1-edit near-misses of the user's frequent English words. Layer 2: if the suggestion model is already warm, a 2.5 s / 48-token sentence check (`buildTypoCheckPrompt`, `틀린말 => 고친말`) whose output is re-validated by `validateModelCorrections` (whole-eojeol or stem match, jamo-level edit distance, no spacing/case/word swaps, no abbreviation expansion like 넘→너무, user's repeated words exempt). Apply = backspace N + paste the corrected span (`TextInsertService.replaceBeforeCaret`, serialized with other inserts); cancelled if any key arrived after the decision or the foreground window changed. Programmatic keys are excluded from input stats. Reverting a fix within 30 s puts the word in `typoIgnoredWords`. While the model check runs the suggestion is deferred (`settled`) so it is generated from the corrected text and the two requests never race on the same model. Toggle: Settings → Input (`typoAutoCorrectEnabled`, default on; `typoAutoCorrectUseModel`). Logs record counts/sources only, never the words. Evidence: core 478 tests, desktop `TypoCorrectionService.test.ts` 14; real `gemma4:e4b` probe ≈0.5–0.8 s per check, 0 false fixes on slang/proper-noun samples. Not yet verified by typing in a real external app (GAP-INPUT-08). |
|
||||
| INPUT-20 | Context-aware suggestion prompt & graph retrieval | [~] | [-] | [-] | [-] | **2026-10-03.** Prompt (`buildSuggestionPrompt`) now splits the prefix with core `writing-context.ts` into earlier text / last sentence / unfinished current sentence and states the mode (finish this sentence vs. write the next one), language and Korean register (formal/polite/casual); adds the text after the caret (no overlap) and fixes dropped characters that had leaked into the old prompt ("[지금까지 텍스트]", "사용자가 언어"). Graph (`PersonalGraphService.retrieveContext`): `followUps` = what the user actually wrote after the same (or near-identical) last sentence via `follows` edges; continuations fall back from 14- to 10- to 7-char word-boundary tails; related sentences ranked by IDF-weighted term overlap (`scoreRelatedNodes`) with same-app/recency boosts plus a one-hop `follows` expansion. Korean terms are stemmed (`stemTerm`: particles and common 하다 endings) so "회의에서"/"회의는" match; stored old terms are re-stemmed at query time. Phrase hints for the prompt keep only phrases sharing terms with the current text (or same app); unfiltered phrases remain for the no-model local-memory fallback. Evidence: `personal-graph-context.test.ts` (real SQLite) 5, `llm-prompts.test.ts` +5, core `writing-context.test.ts` 8; real `gemma4:e4b` probe keeps register and follows graph hints (~0.55 s). |
|
||||
| INPUT-21 | Prefill continuation + document/conversation context for suggestions | [~] | [-] | [-] | [-] | **2026-10-03.** For models whose chat template we know (gemma 4 `<\|turn>`, gemma 2/3 `<start_of_turn>`; core `chat-template.ts`), the suggestion request is sent `raw` with the user's own unfinished sentence (or last sentence) pre-filled into the model turn, so the model literally continues the text: mid-word joins (`회의실`+`에서`) and spacing come out exact (`extractContinuation` keeps joint `attach`/`separate`; trailing space is not pre-filled — it destabilised output — and an attach after a finished word is rejected). Ollama's chat-API prefill was measured and rejected (drops the leading space, closes the turn: `검토해 보시`→`부탁드립니다.`). Other models keep the instruction prompt. Context added to both paths: whole text before the caret (`TypingContext.documentBefore`, ≤6000 chars; null for document-like/terminal/password) → opening lines outside the 1,200-char window and a fact list (names+titles, attendee lines, dates, times, amounts, versions, acronyms, quoted terms — `analyzeDocumentContext`); **same-window messages the user just sent** (chat boxes empty on send — `RecentWritesBuffer`, memory only, 30 min, cleared when input observation stops, terminals excluded); search-box detection (keywords, not sentences); plain `-다` register split from casual `-어`; no emoji unless the user uses them. Output guards: first sentence/line only, stream cut as soon as it ends, restated-prefix stripping (also fixes the instruction path, where `CI는 통과했고…` was inserted after `CI는`), repeat-of-written-sentence drop, and **unsupported-fact rejection** (`findUnsupportedFacts`: dates/numbers/names+titles/lone Latin identifiers absent from document, window title, recent messages and personal hints) with one retry for the first candidate. Fill loop: temperature 1.0; in next-sentence mode every other fill uses the instruction prompt (prefill alone repeated the first candidate). Evidence: real `gemma4:e4b` probe `tests/integration/suggestion-quality.ollama.test.ts` (15 scenarios, opt-in `D3RO_SUGGESTION_PROBE=1`) — first-candidate warnings 0/15 vs 1/15 for the old path (old path invented a launch date instead of the 11월 15일 stated 1,200 chars earlier), mean ≈0.68 s both; core `suggestion-continuation.test.ts` 25, `llm-prompts.test.ts` +7. Not yet verified by typing in a real app (GAP-INPUT-09). |
|
||||
| INPUT-21 | Prefill continuation + document/conversation context for suggestions | [~] | [-] | [-] | [-] | **2026-10-03.** For models whose chat template we know (gemma 4 `<\|turn>`, gemma 2/3 `<start_of_turn>`; core `chat-template.ts`), the suggestion request is sent `raw` with the user's own unfinished sentence (or last sentence) pre-filled into the model turn, so the model literally continues the text: mid-word joins (`회의실`+`에서`) and spacing come out exact (`extractContinuation` keeps joint `attach`/`separate`; trailing space is not pre-filled — it destabilised output — and an attach after a finished word is rejected). Ollama's chat-API prefill was measured and rejected (drops the leading space, closes the turn: `검토해 보시`→`부탁드립니다.`). Other models keep the instruction prompt. Context added to both paths: whole text before the caret (`TypingContext.documentBefore`, ≤6000 chars; null for document-like/terminal/password) → opening lines outside the 1,200-char window and a fact list (names+titles, attendee lines, dates, times, amounts, versions, acronyms, quoted terms — `analyzeDocumentContext`); **same-window messages the user just sent** (chat boxes empty on send — `RecentWritesBuffer`, memory only, 30 min, cleared when input observation stops, terminals excluded); search-box detection (keywords, not sentences); plain `-다` register split from casual `-어`; no emoji unless the user uses them. Output guards: first sentence/line only, stream cut as soon as it ends, restated-prefix stripping (also fixes the instruction path, where `CI는 통과했고…` was inserted after `CI는`), repeat-of-written-sentence drop, and **unsupported-fact rejection** (`findUnsupportedFacts`: dates/numbers/names+titles/lone Latin identifiers absent from document, window title, recent messages and personal hints) with one retry for the first candidate. Fill loop: temperature 1.0, prefill only (the 2026-10-17 change removed the alternating instruction prompt — see INPUT-22). Evidence: real `gemma4:e4b` probe `tests/integration/suggestion-quality.ollama.test.ts` (15 scenarios, opt-in `D3RO_SUGGESTION_PROBE=1`) — first-candidate warnings 0/15 vs 1/15 for the old path (old path invented a launch date instead of the 11월 15일 stated 1,200 chars earlier), mean ≈0.68 s both; core `suggestion-continuation.test.ts` 25, `llm-prompts.test.ts` +7. Not yet verified by typing in a real app (GAP-INPUT-09). |
|
||||
| INPUT-22 | Typo fixes proposed inside the suggestion popup + snappier suggestions | [~] | [-] | [-] | [-] | **2026-10-17.** While suggestions are on, typos are no longer replaced silently: `TypoCorrectionService.propose()` builds a plan without applying it and `SuggestionService` shows it in the popup as a `오타 고침` row (`del` struck-through original → `ins` fix) with the corrected tail prefixed to every candidate; the model continues from the corrected text. Accept = backspace the typo span + paste fix + candidate in one `replaceBeforeCaret` (if the caret char is still IME-composing, a real Space commits it first and is deleted too); if the text before the caret no longer ends with the typo span, only the candidate is inserted. Silent auto-correct (INPUT-19) still runs when suggestions are off. New core rule `detectJamoNoise`: a lone stray jamo inside/before Hangul syllables (`그ㅓ런`, `ㅇ다른`, `가쓴ㄷ거`) or a lone jamo word mid-sentence is removed; `ㅋㅋ`/`ㅠㅠ`/trailing `ㅎ`/first-word `ㅇ` are kept. Model typo check runs before the first candidate only when `hasSuspiciousTypo` (stray jamo, rare syllable); otherwise once in the background after the first candidate (`thorough`, ≥2 words) and the row is attached late. Proposals also work in learning-excluded apps (agent windows) but not terminals/excluded apps. Responsiveness: `minIntervalMs` 5000→1200, per-minute cap 6→20 (config migration rev 7, IPC clamp 30), composing idle ×1.5→×1.2, settle snapshot fires right after the required idle (≈780 ms instead of 1 s), accept relaxes the interval so the next pause after Space suggests again, visible TTL 20→45 s. Fill loop no longer mixes instruction prompts (instruction-path gemma *answered* the user: "설명해 주실 수 있을까요?"). **Round 2 (same day, live test: "panel should appear the moment I pause; it still closes mid-generation / flashes"):** 15 of 18 first requests returned an empty model output — a prefill ending mid-sentence with no trailing space (`…잠시 쉬면`) makes gemma close its turn at once; each empty result closed the panel and the next snapshot regenerated the same text ~1 s later (flash loop). Fixes: empty raw output → one retry with a trailing space appended to the prefill (`ModelRequest.spaced`, output re-parsed with a leading space so the joint is separate; probe: 4/4 sentences continue; fills reuse the spaced variant); a prefix whose first request failed is not regenerated until the text changes (`_failedPrefix`); a lone trailing jamo is removed with the *following* space so the text still ends "word + space"; snapshot debounce 700→380 ms and a "생성 중" placeholder (`presenceDelayMs` 350, self-clears after `presenceMaxMs` 3 s or when typing resumes, only when a request will follow — warm model, budget, not dismissed, not a failed prefix) shown before generation starts; it is not counted as "visible" by the policy. Tests: `suggestion-presence.test.ts` 5. Recent same-window writes are observed even while IME-composing (Korean chat boxes are almost always composing, so sent messages were never remembered). Diagnosis (installed v1.9.0 log + history DB, 1,122 suggestions / 11 accepted): v1.9.0 predates INPUT-19/21 and cleared a visible popup once `typedRecently` expired 8 s after the last key — ≈ the time the 12-candidate fill takes ("closes by itself when all candidates are done"). Evidence: real `gemma4:e4b` — `안ㄴ뇽하세여.?`→`안녕하세요.?` (1.1 s), `회으에서`→`회의에서`, `괜찬으세요`→`괜찮으세요`, `ㅇ다른`/`그ㅓ런` (0.8 s); desktop `suggestion-typo-correction.test.ts` 7, `TypoCorrectionService.test.ts` +4, core `typo-correction.test.ts` +4; desktop 2556 pass (2 known caption-env failures). Real-app check pending (GAP-INPUT-10). |
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -45,11 +45,12 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res
|
|||
| GAP-UX-06 | Desktop | main 쪽 정리 필요: `STTManager.ts:53-129` 공급자 설명 한국어 하드코딩·마케팅 문구("100% 완전 오프라인", "Industry Benchmark") — 렌더러는 더 이상 쓰지 않는다 / audio TEST_DEVICE 가 deviceId 무시 / 사전 `incrementUsage` 호출처 없음(사용 횟수 항상 0) / 사전 발음 필드가 인식 힌트·치환에 쓰이지 않음 / 대화 세션 다시 듣기 IPC 없음 / preload `instruction.getAll` 이 `unknown[]` / 지식 추가 실패 판정이 문구 비교. | 각 파일 | `[ ]` 2026-09-28 (도구·설정 개편 에이전트 보고) |
|
||||
| GAP-UX-07 | Desktop | 2026-09-28 개편 문구는 ko·en 만 — 다른 8개 로케일은 en 폴백. 온보딩 Ollama 모델 크기 표기(`onboarding.llmModelSize` 9.6GB)와 안내 모달의 크기가 다르다. | `packages/i18n/src/locales/*` | `[ ]` 2026-09-28 |
|
||||
| GAP-TEAM-02 | Team | 브라우저에서 초대를 수락하는 경로가 없다. 웹 `accept-invite` 페이지는 발급 링크가 가리키지 않고 로그인 후 토큰을 읽는 곳이 없어 끊겨 있었으므로 삭제했다(사이트 `/accept-invite/`는 앱 딥링크만). | `site/public/accept-invite/`, `server/supabase/functions/team-accept` | `[ ]` 2026-09-26: 데스크톱 전용 사용자를 위한 웹 수락 흐름이 필요하면 `/app` 아래에 다시 설계. |
|
||||
| GAP-REL-10 | Release | `release-windows`(태그 파이프라인)는 서명 가드에 도달하기 **전에** sidecar 단계에서 죽는다. 이 러너 컨텍스트에서는 `sidecar:setup`이 Python 3.11+를 찾지 못한다(`Python 3.11+ 를 찾을 수 없습니다`) → `sidecar:build` → `verify-sidecar-bundle.mjs` 연쇄 실패(실측: run#65 `v1.3.7`, run#61 `v1.3.6`). 같은 러너의 portable 잡은 `py -3.11 → Python 3.11.9`를 찾아 사이드카 빌드에 성공하므로, 워크플로/컨테이너 간 PATH 차이다. | `.forgejo/workflows/release.yml`, `apps/desktop/scripts/setup-sidecar.mjs` | `[!]` 2026-09-19: 러너에 Python 3.11+(`py` 런처 포함)를 보장하거나 워크플로에 `actions/setup-python` 단계를 추가한다. 그 전까지 서명 게시는 불가능하다(GAP-REL-02와 별개 선행 차단). |
|
||||
| GAP-REL-10 | Release | `release-windows`(태그 파이프라인)는 서명 가드에 도달하기 **전에** sidecar 단계에서 죽는다. 이 러너 컨텍스트에서는 `sidecar:setup`이 Python 3.11+를 찾지 못한다(`Python 3.11+ 를 찾을 수 없습니다`) → `sidecar:build` → `verify-sidecar-bundle.mjs` 연쇄 실패(실측: run#65 `v1.3.7`, run#61 `v1.3.6`). 같은 러너의 portable 잡은 `py -3.11 → Python 3.11.9`를 찾아 사이드카 빌드에 성공하므로, 워크플로/컨테이너 간 PATH 차이다. | `.forgejo/workflows/release.yml`, `apps/desktop/scripts/setup-sidecar.mjs` | `[!]` 2026-09-19: 러너에 Python 3.11+(`py` 런처 포함)를 보장하거나 워크플로에 `actions/setup-python` 단계를 추가한다. 그 전까지 서명 게시는 불가능하다(GAP-REL-02와 별개 선행 차단). **2026-10-17 `[x]`**: 런타임이 설치본에서 분리돼 `release.yml` 은 더 이상 사이드카를 빌드하지 않는다(`build-desktop-installer.mjs`). |
|
||||
| GAP-REL-11 | Release | portable 워크플로의 마지막 `actions/upload-artifact@v4` 단계가 Forgejo 러너에서 `GHESNotSupportedError`로 실패한다(증거 보존만 실패, 게시는 성공). | `.forgejo/workflows/portable.yml` | `[x]` 2026-09-19: `v1.3.7` portable 게시는 run#64에서 성공(7z 단일 볼륨 83.7MB + zip 2부, `portable-latest/portable.json`이 1.3.7 보고). 남은 조치: upload-artifact 단계를 제거하거나 v3/다른 보존 방식으로 바꿔 워크플로를 GREEN으로 만든다. |
|
||||
| GAP-REL-12 | Release | Forgejo generic registry는 파일 단위 덮어쓰기를 거부(HTTP 409)하는데, portable 게시 스크립트의 "동일 파일 건너뛰기"가 1MiB 초과 파일을 **크기만** 비교했다. 그래서 새 runtime의 sidecar 볼륨 `.001`이 이전 볼륨과 정확히 같은 94,371,840 bytes였고, 내용이 다른데도 "동일"로 오판해 `runtime-latest`가 낡은 `.001` + 새 `.002`로 갈라졌다(다운로드 시 손상). | `scripts/ci/publish-portable-release.mjs` | `[x]` 2026-09-23: 파일 목록 API(`GET /api/v1/packages/{owner}/generic/{name}/{version}/files`)의 sha256으로 정확히 비교하고, 내용이 다른 파일이 하나라도 있으면 해당 별칭 버전 전체를 삭제 후 재업로드하도록 수정했다. 이미 발생한 `runtime-latest`는 버전을 지우고 재게시해 4개 파일 모두 로컬 해시와 일치함을 확인했다. |
|
||||
| GAP-REL-02 | Release | Windows stable publication needs an external public-trust Authenticode PFX, its password, the exact signer subject, and a Forgejo token, none of which live in the repository. | `.forgejo/workflows/release.yml`, `.gitlab-ci.yml`, `scripts/ci/set-forgejo-secrets.mjs`, `scripts/ci/verify-windows-release-artifact.ps1` | `[!]` 2026-09-18 measured: the Forgejo repo had **zero** Actions secrets; `FORGEJO_TOKEN` is registered now (2026-09-18) but `WIN_CSC_*` still have no values, so `v1.2.0` (run 49) and `v1.3.0` (run 51) both failed at the signing guard and **no updater-feed release has been published since `1.1.0`**. Inject the four secrets (`WIN_CSC_LINK`, `WIN_CSC_KEY_PASSWORD`, `WIN_CSC_EXPECTED_SIGNER_SUBJECT`, `FORGEJO_TOKEN`) with `npm run release:secrets` (check: `npm run release:secrets:check`), then re-run `release.yml` for the `v1.3.0` tag via `workflow_dispatch` (tags are immutable). **2026-09-19 정정**: CI 서명 게이트는 여전히 막혀 있지만, updater feed에는 `1.3.2`~`1.3.7`이 로컬 `release:updater` 경로로 게시되어 있다(GAP-REL-06). **2026-09-23 정정**: `1.4.0`은 게시되지 않았고(GAP-REL-06), `1.5.0`도 로컬 무서명 경로로 게시했다. CI 서명 게이트는 여전히 `WIN_CSC_*` 부재로 막혀 있다(GAP-REL-10의 Python 선행 문제와 별개). |
|
||||
| GAP-REL-06 | Release | 서명 인증서가 없어 stable(`latest`) 채널에 **무서명** 설치본을 게시했다. electron-updater는 `app-update.yml`에 `publisherName`이 없으면 서명 검증을 건너뛰므로 설치는 동작하지만, SmartScreen 평판은 버전마다 0부터 시작한다. | `scripts/ci/publish-updater-release.mjs`, `release/update-policy.json`, `.forgejo/workflows/release.yml` | `[!]` 2026-09-18: `1.3.2`를 `--ack-unsigned`(명시적 승인 플래그)로 게시. **2026-09-19: `1.3.7`도 같은 경로로 게시**(`npm run release:updater -- --ack-unsigned`, 설치본 90.6MiB, `latest.yml`=1.3.7, 설치본 sha512가 피드 메타데이터와 일치). 인증서 확보 시 더 높은 버전으로 서명 게시하여 대체하고, 이 예외를 제거한다. **2026-09-23: `1.5.0`도 같은 경로로 게시**(`npm run release:updater -- --build --ack-unsigned`, 설치본 91.2MiB, `latest.yml`=1.5.0, sha512 검증). |
|
||||
| GAP-REL-02 | Release | Windows stable publication needs an external public-trust Authenticode PFX, its password, the exact signer subject, and a Forgejo token, none of which live in the repository. | `.forgejo/workflows/release.yml`, `.gitlab-ci.yml`, `scripts/ci/set-forgejo-secrets.mjs`, `scripts/ci/verify-windows-release-artifact.ps1` | `[!]` 2026-09-18 measured: the Forgejo repo had **zero** Actions secrets; `FORGEJO_TOKEN` is registered now (2026-09-18) but `WIN_CSC_*` still have no values, so `v1.2.0` (run 49) and `v1.3.0` (run 51) both failed at the signing guard and **no updater-feed release has been published since `1.1.0`**. Inject the four secrets (`WIN_CSC_LINK`, `WIN_CSC_KEY_PASSWORD`, `WIN_CSC_EXPECTED_SIGNER_SUBJECT`, `FORGEJO_TOKEN`) with `npm run release:secrets` (check: `npm run release:secrets:check`), then re-run `release.yml` for the `v1.3.0` tag via `workflow_dispatch` (tags are immutable). **2026-09-19 정정**: CI 서명 게이트는 여전히 막혀 있지만, updater feed에는 `1.3.2`~`1.3.7`이 로컬 `release:updater` 경로로 게시되어 있다(GAP-REL-06). **2026-09-23 정정**: `1.4.0`은 게시되지 않았고(GAP-REL-06), `1.5.0`도 로컬 무서명 경로로 게시했다. CI 서명 게이트는 여전히 `WIN_CSC_*` 부재로 막혀 있다(GAP-REL-10의 Python 선행 문제와 별개). **2026-10-17 `[~]`**: Authenticode 는 더 이상 게시 차단 조건이 아니다 — 무서명 설치본은 Ed25519 서명 `latest.yml` 로 보호하고(GAP-REL-13), `release.yml` 은 `WIN_CSC_*` 가 있으면 서명만 추가한다. 남은 것은 SmartScreen 평판용 인증서(한국 개인은 Azure Artifact Signing 불가, 사업자 필요). |
|
||||
| GAP-REL-13 | Release | **9-27 v1.9.0 이후 3주간 업데이트 0건(커밋 83개 미배포).** 앱 업데이터는 정상(4시간마다 확인, 피드 200)이었지만 게시가 손으로 5~6단계라 아무도 돌리지 않으면 안 나갔고, CI 경로는 서명 가드로 늘 실패했다. 게시 스크립트도 4벌(forgejo·updater·portable·gitlab)로 겹쳐 있었다. | `scripts/ci/release-desktop.mjs`, `scripts/ci/build-desktop-installer.mjs`, `scripts/ci/publish-forgejo-release.mjs`, `scripts/ci/lib/update-manifest-signature.mjs`, `apps/desktop/src/main/update-signature.ts`, `apps/desktop/src/main/services/update-adapters.ts`, `.forgejo/workflows/release.yml` | `[~]` 2026-10-17: `npm run release -- patch|minor` 한 줄(점검→버전→게이트→커밋·태그→빌드→서명·게시→공개 URL 재검증→푸시, `--resume`). latest.yml Ed25519 서명 + 앱이 NsisUpdater `verifySignature` 단계에서 불변 `<version>/latest.yml`+`.sig` 로 설치본 sha512 검증(fail-closed). electron-updater 6.8.9→6.8.10(차분 다운로드 수정). `publish-updater-release.mjs`·`publish-gitlab-release.mjs`·`LEGACY_UPDATE_FEED_URL` 삭제. CI 는 같은 스크립트를 쓰는 예비 경로(피드에 있으면 건너뜀). 검증: 업데이트 테스트 95/95, release:metadata 음성 16, typecheck 0, 게시 --check 자산 4개, 서명 왕복. **남은 것**: 첫 실제 릴리스(1.10.0) 게시 + 1.9.0 설치본→1.10.0 자동 업데이트 E2E, Forgejo 시크릿 `D3RO_UPDATE_SIGNING_KEY` 동기화(`npm run release:secrets`). |
|
||||
| GAP-REL-06 | Release | 서명 인증서가 없어 stable(`latest`) 채널에 **무서명** 설치본을 게시했다. electron-updater는 `app-update.yml`에 `publisherName`이 없으면 서명 검증을 건너뛰므로 설치는 동작하지만, SmartScreen 평판은 버전마다 0부터 시작한다. | `scripts/ci/publish-forgejo-release.mjs`, `release/update-policy.json`, `.forgejo/workflows/release.yml` | `[~]` 2026-10-17: 무서명 게시가 정식 경로가 됐다 — `--ack-unsigned` 예외 대신 latest.yml Ed25519 서명 + 앱 검증(GAP-REL-13). SmartScreen 평판 문제만 남음. 이력: 2026-09-18: `1.3.2`를 `--ack-unsigned`(명시적 승인 플래그)로 게시. **2026-09-19: `1.3.7`도 같은 경로로 게시**(`npm run release:updater -- --ack-unsigned`, 설치본 90.6MiB, `latest.yml`=1.3.7, 설치본 sha512가 피드 메타데이터와 일치). 인증서 확보 시 더 높은 버전으로 서명 게시하여 대체하고, 이 예외를 제거한다. **2026-09-23: `1.5.0`도 같은 경로로 게시**(`npm run release:updater -- --build --ack-unsigned`, 설치본 91.2MiB, `latest.yml`=1.5.0, sha512 검증). |
|
||||
| GAP-REL-07 | Release | 패키징된 `better-sqlite3`가 호스트 Node ABI여서 `1.3.2` 설치본이 시작 즉시 죽었다(NODE_MODULE_VERSION 131 vs 130). 원인: 로컬 `npm install`이 네이티브 모듈을 Node용으로 재빌드했고 패키징이 재빌드를 건너었다. | `scripts/ci/verify-native-abi.mjs`, `scripts/ci/fix-native-abi.mjs`, `.gitlab-ci.yml`/`.forgejo`/`.github` 패키징 단계 | `[x]` 2026-09-18: 패키징 후 Electron ABI를 검증하고, 검증된 트리에서만 설치본을 생성(`--prepackaged`)한다. `1.3.3`은 설치본에서 추출한 바이너리로 재검증 GREEN. |
|
||||
| GAP-ADS-01 | Ads | 9 of 10 desktop ad adapters still extend `UnavailableAdAdapter` (`provider_not_integrated`). | `apps/desktop/src/main/services/ads/*` | `[~]` 2026-09-13: `DirectHouseSponsorAdapter` is now a real configurable REST adapter (bid/impression/click/reward via `endpointUrl`; fail-closed when unconfigured; 22 unit tests GREEN). Remaining 9 need official SDKs/authenticated endpoints. |
|
||||
| GAP-ADS-02 | Ads | Desktop mediation reward accounting is not wired to license quota (`claimReward` still returns no tokens). | `AdMediationEngine.ts`, `AppLayout.tsx` | Wire verified `reportRewardCompletion` to `LicenseService` quota after the direct sponsor endpoint exists. |
|
||||
|
|
@ -76,7 +77,7 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res
|
|||
| GAP-STT-04 | Local STT | Live partial transcript (`CAP-03`, `voice:partialTranscript`) was marked done but had **no producer**: the channel, popup UI, and preload existed, nothing ever emitted. | `apps/desktop/src/main/services/VoiceModeService.ts`, `LocalSTTService.transcribePartial`, `STTManager.transcribePartial` | `[x]` 2026-09-18: 1.5 s cadence over a 7.5 s trailing window, greedy decode, drained before the final transcription; never inserted. |
|
||||
| GAP-STT-05 | Local STT | The bundled sidecar lacked faster-whisper's Silero VAD data, so `vad_filter=true` transcription would have failed at runtime even with the engine bundled. | `apps/desktop/scripts/build-sidecar.mjs`, `scripts/ci/verify-sidecar-bundle.mjs` | `[x]` 2026-09-18: `--collect-all faster_whisper` plus a packaging-time presence check for `assets/silero_vad_v6.onnx`. |
|
||||
| GAP-REL-03 | Release | 서명이 없어 설치할 수 있는 경로가 없다(인증서 발급 전 공백). | `.forgejo/workflows/portable.yml`, `scripts/ci/build-portable.mjs`, `scripts/local/install-d3ro-voice.ps1`, `bucket/d3ro-voice.json` | `[x]` 2026-09-18: 서명 없는 portable 채널 구현 — 95MiB 7z 분할 볼륨(688MB → 162MiB) + Scoop 버킷 + 수동 설치 스크립트를 Forgejo에 게시. 실제 설치 스크립트 end-to-end 검증(볼륨 다운로드 → SHA-256 → 결합 → 해제 → 엔진 포함 확인). updater feed는 건드리지 않음. **2026-09-19: `1.3.7`이 CI portable run#64에서 `portable-latest`에 게시됨**(7z 단일 볼륨 83.7MB + zip 2부, `portable.json`=1.3.7) — 즉 portable 경로는 CI만으로 동작하고, 실패한 것은 마지막 증거 업로드 단계다(GAP-REL-11). |
|
||||
| GAP-REL-04 | Release | canonical feed는 Cloudflare 뒤에 있어 업로드 본문이 **100MiB**를 넘으면 HTTP 413으로 거부한다. | `scripts/ci/publish-updater-release.mjs`, `docs/deployment/unsigned-distribution.md` | `[~]` 2026-09-18: 설치본을 90.6MiB로 줄여 업데이트 피드 게시를 복구했다(GAP-STT-07). 휴대용/Scoop 채널은 여전히 95MiB 분할이 필요하다. |
|
||||
| GAP-REL-04 | Release | canonical feed는 Cloudflare 뒤에 있어 업로드 본문이 **100MiB**를 넘으면 HTTP 413으로 거부한다. | `scripts/ci/build-desktop-installer.mjs`, `docs/deployment/unsigned-distribution.md` | `[~]` 2026-09-18: 설치본을 90.6MiB로 줄여 업데이트 피드 게시를 복구했다(GAP-STT-07). 휴대용/Scoop 채널은 여전히 95MiB 분할이 필요하다. |
|
||||
| GAP-STT-07 | Local STT | 진(사이드카)을 앱 번들에 넣으면 설치본이 100MiB를 넘고 매 업데이트마다 162MiB를 다시 받는다. | `apps/desktop/src/main/services/RuntimeProvisioner.ts`, `apps/desktop/electron-builder.yml` | `[x]` 2026-09-18: 설치본에서 엔진/ffmpeg를 제거하고 처음 필요할 때 `runtime-latest`에서 내려받는다(부품별 + 결합본 SHA-256 검증). 설치본 189MB → 90.6MiB, 런타임 1회 116MiB(엔진 94.4 + ffmpeg 21.7). 실제 feed로 통합 검증 완료. |
|
||||
| GAP-STT-06 | Local STT | Decode settings were untuned: previous-text conditioning let repeated hallucinations compound, and no VAD parameters meant slow, uneven segments. | `apps/desktop/sidecar/main.py` | `[x]` 2026-09-18: `condition_on_previous_text=false`, bounded low-temperature fallback, `no_speech`/`compression_ratio`/`log_prob` thresholds, 300 ms silence trimming. Same transcript, ~5x faster on the reference machine (7.7 s audio: 1609 ms → 303 ms). |
|
||||
| GAP-KEY-01 | Key bindings | 키바인딩 전면 개편(CAP-16)이 실앱 구동으로 검증되지 않은 상태였다. uiohook 전역 후킹, 더블프레스 타이밍, 마우스 버튼 수신을 실행 중인 Electron 에서 확인한 적이 없었고, 증거가 계약 수준(`packages/core` 117개 통과, 키바인딩 파일 타입 에러 0건)뿐이었다. 에이전트는 데스크톱 GUI 를 띄울 수 없다(`AGENTS.md` §3). | `apps/desktop/src/main/services/KeyBindingService.ts`, `packages/core/__tests__/keybinding.test.ts`, `%APPDATA%/d3ro-voice/logs/main.log`, `%APPDATA%/d3ro-voice/d3ro-voice-config.json` | `[x]` 2026-09-21: 사용자가 Windows 에서 앱을 띄워 검증 완료. 로그(12:53–13:06)에 `Migrated 4 legacy shortcut(s) to keyBindings` → `Loaded 6 key binding(s) from config for 6 action(s)` → `uiohook started, global keyboard/mouse hook active` → `key-bindings initialized` → `Key binding events connected` 가 순서대로 남았고 부팅 에러 0건, STT 모델 로딩까지 정상. 키보드·마우스(MB4/MB5) 바인딩을 UI 로 실제 조작해 동작을 확인했고, 같은 세션의 `Loaded 7 key binding(s) … for 6 action(s)` 가 다중 바인딩이 실동작함을 보인다. 설정 파일 되읽기로 마이그레이션 결과를 확인 — 사용자 커스텀 값이 그대로 보존됐고(dictation `code:49,alt` / hands-free `code:49,alt+shift` / command `code:165,ctrl` / caption `code:49,ctrl+alt+shift`, 팝업 2종은 신규 기본값), 구 `*Shortcut` 4개와 `displayLabel` 은 모두 사라졌다. **남은 것**: `KeyBindingService` 자체의 유닛 테스트는 여전히 없다(실행 검증이 유닛 테스트를 대체하지 않는다). macOS/Linux 는 GAP-KEY-02 로 계속 열려 있다. |
|
||||
|
|
@ -104,6 +105,7 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res
|
|||
| GAP-INPUT-06 | Input intelligence | `[~]` **제안 폭주 상한 및 runtime 확인.** 이전 24.7 s / 4.9 s, boot warmup, `keep_alive: 30m`, 48/96/128 tokens 및 2/5 candidates 기록은 역사적 가설/완화 이력이며 현재 정책이 아니다. 현 정책은 600 ms debounce, 5 s minimum interval, 6 requests/min default (hard max 12), 3 candidates, 64 output tokens, 12-character growth, 8 s timeout, `keep_alive: 2m` 및 boot warmup 제거다. | `apps/desktop/src/main/services/SuggestionService.ts`, `packages/core/src/input-intelligence.ts`, `LocalLLMService.ts` | 표적 자동 검증은 6 files / 69 passed / 0 failed이며 raw Ollama의 15.044 s cold timeout cleanup, 약 119.9 s residency expiry, 그리고 19:48:59 +09:00에 새 generate/unload/kill/retry 없이 확인한 `/api/ps` HTTP 200 / 45.8 ms / `{models:[]}` (`/api/version` HTTP 200 / 7.3 ms / `0.32.13`)도 확인됐다. 전체 strict typecheck는 green이 아니며, 이 raw API unload 증거는 앱 재시작·GUI·실제 자동제안 타이핑 검증이 아니다. 그 경로에서 rate limit, 8 s abort, 3-candidate/64-token 상한을 확인한다. |
|
||||
| GAP-INPUT-08 | Input intelligence | `[~]` **오타 자동 교정(INPUT-19)·문맥 제안(INPUT-20) 실앱 확인 (2026-10-03).** 자동 테스트와 실제 `gemma4:e4b` 프롬프트 프로브는 통과했지만, 외부 앱에서 "백스페이스 N + 붙여넣기" 교체가 정확히 동작하는지는 GUI 로 확인하지 않았다. | `apps/desktop/src/main/services/{TypoCorrectionService,SuggestionService,PersonalGraphService,TextInsertService}.ts`, `packages/core/src/{typo-correction,writing-context,personal-graph}.ts` | `run-desktop.bat` 재시작 후 메모장·카톡·크롬 입력창에서: (1) `됬어요 ` 치고 멈추면 `됐어요 ` 로 바뀌는지, (2) 한글 문장 중 `dkssudgktpdy` 가 `안녕하세요` 로 바뀌는지, (3) 교체 도중 계속 치면 교체가 취소되고 글이 섞이지 않는지, (4) 고친 단어를 원래대로 되돌리면 다시 고치지 않는지, (5) 앱마다 백스페이스 한 번이 한 글자를 지우는지(리치 에디터·웹 에디터), (6) 교정 뒤 제안이 고친 문장 기준으로 뜨는지. 문제가 있는 앱은 제외 목록 또는 앱별 차단 규칙으로 다룬다. |
|
||||
| GAP-INPUT-09 | Input intelligence | `[~]` **prefill 이어 쓰기·문서/대화 문맥(INPUT-21) 실앱 확인 (2026-10-03).** 실제 `gemma4:e4b` 프로브 15개 시나리오와 단위 테스트는 통과했지만, (a) 외부 앱 UIA 가 커서 앞 문서 전체를 주는지(케어렛 미상 앱은 tail 폴백), (b) 채팅 앱이 보내기 뒤 입력칸을 실제로 비우는 스냅샷을 내는지(카톡은 UIA 텍스트 길이 0 인 경우가 있었다 — GAP-INPUT-01), (c) 단어 중간 수락(`attach`)이 실제 삽입에서 공백 없이 붙는지는 GUI 로 확인하지 않았다. 후보 다양성: 마저 쓰기 모드는 prefill 분포가 뾰족해 채우기 후보가 1~2개에서 멈출 때가 많다. | `apps/desktop/src/main/services/{SuggestionService,InputTelemetryService,LocalLLMService,llm-prompts}.ts`, `packages/core/src/{chat-template,recent-writes,suggestion-text,writing-context}.ts`, `apps/desktop/tests/integration/suggestion-quality.ollama.test.ts` | `run-desktop.bat` 재시작 후: (1) 긴 메모장 문서 끝에서 앞부분의 날짜·이름을 이어 받는지, (2) 슬랙/디스코드 같은 Chromium 채팅에서 메시지를 보낸 뒤 다음 메시지 제안이 앞 메시지를 이어 받는지(로그 `제안 판단 입력` + 프롬프트 길이), (3) `내일 3시에 회의실` 같은 단어 중간에서 수락하면 `회의실에서…` 로 붙는지, (4) 지어낸 사실로 후보를 버린 로그(`제안 후보 버림 (unsupported-facts…)`)가 과하게 잦지 않은지. 모델 교체 시 `D3RO_SUGGESTION_PROBE=1 D3RO_SUGGESTION_PROBE_MODEL=<태그>` 로 같은 프로브를 다시 돌린다. **2026-10-03 19:00 "제안 창이 잘 안 뜸" 로그 분석**: 보류 1위 WindowsTerminal(Claude Code) `caret-unknown` 721회 — 입력 상자 아래 상태줄 때문에 화면 전체 기준으로 매번 "문서 중간 편집" 판정 → `SuggestionService._terminalContext` 가 입력 줄 연속성(늘거나 줄면 커서=끝)으로 판단. 2위 Chrome `not-typing` 122회 — 타이핑 중 UIA 포커스가 입력칸↔legacy 요소를 오가며 기준선을 다시 잡음 → 같은 창·클릭 없이 치는 중의 깜빡임이면 편집한 칸 유지(`input-telemetry-focus-flicker.test.ts`). 모든 앱에서 caret 오프셋을 못 얻는 것(caret=-1)과 Kitedesk/Candy/Paca 의 legacy(읽기 불가)는 별도 과제. 19:10 재시작 뒤 6분간 첫 후보 10회 생성(터미널 caret-unknown 721→4). **수락 키 전달 문제**: uiohook 은 키를 엿듣기만 해서 Ctrl+Alt+Enter 가 Claude Code 에도 전달돼 개행이 들어갔다 → 제안 창이 떠 있는 동안만 제안 단축키를 globalShortcut(noop)으로 잡아 OS 가 삼키게 하고 창이 사라지면 해제(`KeyBindingService.setSuggestionCaptureActive`, `suggestionCaptureAccelerators`). 실앱에서 수락 시 개행이 더는 안 들어가는지, 창이 없을 때 다른 앱의 Ctrl+Alt+Enter/↑↓ 가 정상인지 확인 필요. |
|
||||
| GAP-INPUT-10 | Input intelligence | `[~]` **제안 창 오타 교정·반응성(INPUT-22) 실앱 확인 (2026-10-17).** 단위 테스트·실모델 프로브·팝업 렌더 스크린샷은 통과, HEAD 로컬 빌드를 띄워 둠(설치본 v1.9.0 종료). 실제 앱에서 교정 수락(백스페이스 N + 붙여넣기)과 조합 중 Space 확정이 정확히 동작하는지는 미확인. 사용자 입력에 섞여 들어간 홀로 남은 `ㅇ`(이력 DB 접두에 반복)의 출처 — 사용자가 친 것인지, 조합이 깨진 흔적인지 — 미확정. | `apps/desktop/src/main/services/{SuggestionService,TypoCorrectionService,TextInsertService,InputTelemetryService}.ts`, `apps/desktop/src/renderer/popups/suggestion-overlay/*`, `packages/core/src/typo-correction.ts` | 에이전트 창·카톡·크롬에서: (1) `안ㄴ뇽하세여.?` 치고 멈추면 `오타 고침` 줄과 함께 후보가 뜨는지, 수락하면 오타가 지워지고 `안녕하세요.? …` 로 바뀌는지, (2) 마지막 글자가 조합 중일 때 수락해도 글자가 남거나 더 지워지지 않는지, (3) 수락 → Space → 멈춤에서 다음 제안이 바로 뜨는지(`rate-limited` 로그 없어야 함), (4) 후보 12개가 다 차도 창이 저절로 닫히지 않는지(45초 TTL 전), (5) 낱자 없는 오타는 첫 후보 뒤 교정 줄이 늦게 붙는지. |
|
||||
|
||||
| GAP-SYNC-01 | Sync | Desktop↔mobile sync was one-way and lossy. (1) `pushAll` set the cursor to *now* before `pullAll` ran, so the first pull after sign-in fetched nothing — mobile-created data never reached the desktop except via Realtime while running (which never connected, GAP-SYNC-02). (2) `_inArray` used only the first meeting id, so memos/documents of every other meeting were never pushed. (3) No deletion propagation either way. (4) Pull had no `user_id` filter — team meetings of other users landed in the personal DB and a desktop re-push cleared `team_id`. (5) One global, local-clock cursor across accounts; no pagination (1,000-row cap). (6) Desktop writes did not move `history.revision`, so mobile's optimistic concurrency silently overwrote desktop edits. (7) One case-duplicate dictionary word failed the whole batch. (8) Memo tags, custom commands, templates, favorites and history titles were not synced at all; anonymous local-mode data was never uploaded after sign-in. | `apps/desktop/src/main/services/sync/*`, `CloudSyncService.ts`, `server/supabase/migrations/20260927000034_cross_device_sync_parity.sql` | `[x]` 2026-09-27: engine rewritten (outbox + per-user server-clock keyset cursors + tombstones + per-row isolation + dictionary adoption + natural-key memo tags + client-keyed template RPCs + local-mode import). Evidence: `apps/desktop/tests/main/sync/SyncEngine.test.ts` (20) + `apps/desktop/tests/integration/cross-device-sync.supabase.test.ts` (5, local Supabase stack); full desktop suite 1499/1500 (1 = known caption env timeout); SQL checks for revision bump, tombstones, account-delete cascade. |
|
||||
| GAP-SYNC-02 | Sync | **Desktop Realtime never connected.** Electron 33 main (Node 20.18) has no global `WebSocket`; supabase-js Realtime only ever logged `TIMED_OUT`/`CLOSED` (installed-app log 2026-09-16) and gave up after three retries. Also: filtered `postgres_changes` channels never deliver DELETE (Supabase limitation). | `CloudSyncService.ts`, `services/sync/realtime-transport.ts`, integration test "Realtime" case | `[x]` 2026-09-27: `ws` injected as the Realtime transport (`ws` now a declared desktop dependency, externalised in the main bundle); deletions arrive as `sync_tombstones` INSERT events; the heartbeat re-subscribes a channel that is not `joined`. Verified live against the local stack (INSERT/UPDATE + tombstone events received). |
|
||||
|
|
|
|||
28
package-lock.json
generated
28
package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "d3ro-voice-monorepo",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "d3ro-voice-monorepo",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"apps/desktop",
|
||||
|
|
@ -25,7 +25,7 @@
|
|||
},
|
||||
"apps/admin": {
|
||||
"name": "@d3ro/admin",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"dependencies": {
|
||||
"@d3ro/api-client": "*",
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -109,7 +109,7 @@
|
|||
},
|
||||
"apps/desktop": {
|
||||
"name": "@d3ro/desktop",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -127,7 +127,7 @@
|
|||
"drizzle-orm": "^0.45.2",
|
||||
"electron-log": "^5.2.0",
|
||||
"electron-store": "^10.0.0",
|
||||
"electron-updater": "^6.3.9",
|
||||
"electron-updater": "^6.8.10",
|
||||
"koffi": "^3.3.1",
|
||||
"lucide-react": "^1.25.0",
|
||||
"overlayscrollbars": "^2.16.0",
|
||||
|
|
@ -161,7 +161,7 @@
|
|||
},
|
||||
"apps/web": {
|
||||
"name": "@d3ro/web",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"dependencies": {
|
||||
"@d3ro/api-client": "*",
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -8553,9 +8553,9 @@
|
|||
"license": "ISC"
|
||||
},
|
||||
"node_modules/electron-updater": {
|
||||
"version": "6.8.9",
|
||||
"resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.9.tgz",
|
||||
"integrity": "sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig==",
|
||||
"version": "6.8.10",
|
||||
"resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.10.tgz",
|
||||
"integrity": "sha512-6ZSwTUoBNtI1f9Pp8y6zCigD8LKV18Rb1+1A7sZzvKvA17o2sqSqKmm0t6uvKeF+HZqA4vsmw4qq0JSS241USQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"builder-util-runtime": "9.7.0",
|
||||
|
|
@ -17216,7 +17216,7 @@
|
|||
},
|
||||
"packages/api-client": {
|
||||
"name": "@d3ro/api-client",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@d3ro/core": "*",
|
||||
|
|
@ -17233,7 +17233,7 @@
|
|||
},
|
||||
"packages/core": {
|
||||
"name": "@d3ro/core",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"docx": "^9.6.1"
|
||||
|
|
@ -17244,7 +17244,7 @@
|
|||
},
|
||||
"packages/i18n": {
|
||||
"name": "@d3ro/i18n",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.0.0"
|
||||
|
|
@ -17255,7 +17255,7 @@
|
|||
},
|
||||
"packages/ui": {
|
||||
"name": "@d3ro/ui",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@d3ro/core": "*"
|
||||
|
|
@ -17275,7 +17275,7 @@
|
|||
},
|
||||
"packages/ui-native": {
|
||||
"name": "@d3ro/ui-native",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/react": "*"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "d3ro-voice-monorepo",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice — 멀티플랫폼 AI 음성 어시스턴트 (Monorepo)",
|
||||
"author": "D3RO",
|
||||
|
|
@ -22,6 +22,8 @@
|
|||
"version:sync": "node scripts/ci/sync-version.mjs --write",
|
||||
"contract:check": "node scripts/ci/sync-core-contract.mjs --check",
|
||||
"contract:sync": "node scripts/ci/sync-core-contract.mjs --write",
|
||||
"release": "node --env-file-if-exists=.env scripts/ci/release-desktop.mjs",
|
||||
"release:build": "node scripts/ci/build-desktop-installer.mjs",
|
||||
"release:metadata": "node scripts/ci/verify-release-metadata.mjs",
|
||||
"release:metadata:test": "node scripts/ci/verify-release-metadata.mjs --self-test",
|
||||
"release:forgejo": "node scripts/ci/publish-forgejo-release.mjs",
|
||||
|
|
@ -54,9 +56,7 @@
|
|||
"typecheck:mobile": "npm --prefix apps/mobile-rn run typecheck",
|
||||
"lint:mobile": "npm --prefix apps/mobile-rn run lint",
|
||||
"test:mobile": "npm --prefix apps/mobile-rn test",
|
||||
"verify:all": "npm run typecheck && npm run typecheck:mobile && npm run lint && npm run lint:mobile && npm run test && npm run test:mobile && npm run check:design",
|
||||
"release:updater": "node --env-file-if-exists=.env scripts/ci/publish-updater-release.mjs",
|
||||
"release:updater:check": "node scripts/ci/publish-updater-release.mjs --check"
|
||||
"verify:all": "npm run typecheck && npm run typecheck:mobile && npm run lint && npm run lint:mobile && npm run test && npm run test:mobile && npm run check:design"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@typescript-eslint/eslint-plugin": "^8.0.0",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/api-client",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice API 클라이언트 — Supabase 래퍼 (web/desktop/mobile 공유)",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -5,16 +5,20 @@ import { describe, expect, it } from 'vitest'
|
|||
import {
|
||||
buildVocabulary,
|
||||
detectHangulTypedLatin,
|
||||
detectJamoNoise,
|
||||
detectLatinTypedHangul,
|
||||
detectTypoRevert,
|
||||
detectTypos,
|
||||
fixByVocabulary,
|
||||
fixKnownMisspelling,
|
||||
hasSuspiciousTypo,
|
||||
mergeTypoCorrections,
|
||||
hangulToLatin,
|
||||
isPlausibleTypoFix,
|
||||
latinToHangul,
|
||||
parseModelTypoPairs,
|
||||
planTypoReplacement,
|
||||
validateModelCorrections,
|
||||
typoRegionStart,
|
||||
validateModelCorrections
|
||||
} from '../src/typo-correction'
|
||||
|
|
@ -221,3 +225,33 @@ describe('되돌리기 감지', () => {
|
|||
expect(detectTypoRevert('그건 됐다 그리고', { from: '됬다', to: '됐다', tailLength: 4 })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('낱자 잡음 (2026-10-17 실측 입력)', () => {
|
||||
const fixed = (text: string): string | null => planTypoReplacement(text, detectJamoNoise(text))?.insertText ?? null
|
||||
|
||||
it('음절 사이·앞에 끼어든 낱자 하나를 지운다', () => {
|
||||
expect(fixed('그ㅓ런건 전혀')).toBe('그런건 전혀')
|
||||
expect(fixed('내 가쓴ㄷ거에 대한')).toBe('가쓴거에 대한')
|
||||
expect(fixed('파츠가 ㅇ다른 UI')).toBe('다른 UI')
|
||||
expect(fixed('안ㄴ뇽하세여.?')).toBe('안뇽하세여.?')
|
||||
})
|
||||
|
||||
it('문장 중간에 홀로 남은 낱자는 뒤 공백과 함께 지운다 — 끝의 낱자를 지워도 "아직 " 이 남는다', () => {
|
||||
expect(fixed('실망스럽고 ㅇ ㅇ이전 까지')).toBe('이전 까지')
|
||||
expect(fixed('아직 ㅇ')).toBe('')
|
||||
expect(planTypoReplacement('아직 ㅇ', detectJamoNoise('아직 ㅇ'))?.deleteCount).toBe(1)
|
||||
})
|
||||
|
||||
it('의도한 낱자(ㅋㅋ·ㅠㅠ·끝의 감정 낱자·첫머리 대답)는 두고, 수상하다고 보지도 않는다', () => {
|
||||
for (const text of ['ㅋㅋ 좋아', '좋아ㅋㅋ', '고마워ㅎ', '미안ㅠ', 'ㅇ 알겠어', 'ㅇㅋ 그럼']) {
|
||||
expect(detectJamoNoise(text)).toEqual([])
|
||||
expect(hasSuspiciousTypo(text)).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('모델 교정이 같은 단어의 낱자 지우기보다 앞선다', () => {
|
||||
const text = '안ㄴ뇽하세여.?'
|
||||
const model = validateModelCorrections(text, [{ from: '안ㄴ뇽하세여', to: '안녕하세요' }])
|
||||
expect(planTypoReplacement(text, mergeTypoCorrections(model, detectJamoNoise(text)))?.insertText).toBe('안녕하세요.?')
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/core",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice 공유 비즈니스 로직 — 타입, 에러, IPC 채널, 상수, 유틸",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -1212,6 +1212,18 @@ export interface SuggestionCandidate {
|
|||
joint?: SuggestionJoint
|
||||
}
|
||||
|
||||
/**
|
||||
* 제안과 함께 내놓는 오타 교정 — 커서 앞 원문 끝의 `from` 을 `to` 로 바꾼 뒤 후보를 잇는다.
|
||||
*
|
||||
* 조용히 고치지 않고 제안 창에 "지운 글자 → 고친 글자" 로 보여 주며, 수락할 때만 적용한다.
|
||||
* `edits` 는 `from` 안의 위치(표시용)다 — 바뀐 단어만 강조하고 나머지는 그대로 보인다.
|
||||
*/
|
||||
export interface SuggestionCorrection {
|
||||
from: string
|
||||
to: string
|
||||
edits: Array<{ start: number; end: number; to: string }>
|
||||
}
|
||||
|
||||
/** 현재 제안이 어느 로컬 근거에서 나왔는지 보여 주는 비식별 설명. */
|
||||
export interface SuggestionProvenance {
|
||||
mode: 'local-model' | 'local-memory'
|
||||
|
|
@ -1267,6 +1279,8 @@ export interface SuggestionState {
|
|||
typoAutoCorrect: boolean
|
||||
/** 후보를 만든 로컬 근거의 수량만 노출한다. */
|
||||
provenance: SuggestionProvenance | null
|
||||
/** 이 세션의 후보가 함께 적용하는 오타 교정 (없으면 null) */
|
||||
correction: SuggestionCorrection | null
|
||||
}
|
||||
|
||||
/** 제안 기본값 — 인라인 컴플리션 실측 중앙값 기준. */
|
||||
|
|
@ -1286,14 +1300,28 @@ export const SUGGESTION_DEFAULTS = {
|
|||
* 보수적이다.
|
||||
*/
|
||||
minPrefixChars: 8,
|
||||
minIntervalMs: 5000,
|
||||
/**
|
||||
* 요청 사이 최소 간격.
|
||||
*
|
||||
* 원래 5초였다 — 로컬 모델 첫 후보가 0.8초 안팎인데 5초·분당 6회에 막혀, 제안을 고르고 이어 친 뒤
|
||||
* 다시 멈추면 rate-limited 로 아무것도 안 떴다(실측 2026-10-17: "나올 때도 있고 안 나올 때도").
|
||||
* 치는 동안 진행 중 요청은 취소·환불되므로 간격은 짧아도 된다.
|
||||
*/
|
||||
minIntervalMs: 1200,
|
||||
/**
|
||||
* 손을 멈춘 뒤 "생성 중" 자리를 먼저 띄우는 시점 (ms). 생성은 triggerDelayMs(조합 중이면 배수) 뒤에
|
||||
* 시작하고, 그 전에 다시 치면 조용히 거둔다 — 반응은 빠르게, 모델 호출은 지금처럼 보수적으로.
|
||||
*/
|
||||
presenceDelayMs: 350,
|
||||
/** 먼저 띄운 자리가 생성으로 이어지지 않으면 이 시간 뒤 스스로 거둔다 (ms) */
|
||||
presenceMaxMs: 3000,
|
||||
/**
|
||||
* 멈춤 판단의 하한. 이보다 짧으면 글자 사이의 순간 멈춤에도 생성이 시작돼,
|
||||
* 치는 도중 창이 떴다 사라지기를 반복한다(실측 2026-09-27: 100ms 설정에서
|
||||
* 5~6초마다 생성→소멸 반복).
|
||||
*/
|
||||
minTriggerDelayMs: 500,
|
||||
maxRequestsPerMinute: 6,
|
||||
maxRequestsPerMinute: 20,
|
||||
dailyBudget: 500,
|
||||
/** 로컬 기억 경로(폴백)에서 한 번에 만드는 후보 수 — 채우기 루프가 없다. */
|
||||
maxCandidates: 3,
|
||||
|
|
@ -1320,7 +1348,7 @@ export const SUGGESTION_DEFAULTS = {
|
|||
* 오버레이는 "다음 문맥" 이 와야 지워지는데, 타이핑을 멈추면 문맥이 오지 않아
|
||||
* 창이 무한정 남는다(실측 신고: 아무것도 안 치는데 제안창이 떠 있음).
|
||||
*/
|
||||
visibleTtlMs: 20000,
|
||||
visibleTtlMs: 45000,
|
||||
/**
|
||||
* 요청 시작 후 이 시간이 지나면 결과를 폐기한다.
|
||||
*
|
||||
|
|
@ -1353,7 +1381,7 @@ export const SUGGESTION_DEFAULTS = {
|
|||
*
|
||||
* 조합 중에는 손을 멈춘 것으로 보이려면 기본 지연의 이 배수만큼 조용해야 한다.
|
||||
*/
|
||||
export const COMPOSING_IDLE_MULTIPLIER = 1.5
|
||||
export const COMPOSING_IDLE_MULTIPLIER = 1.2
|
||||
|
||||
/**
|
||||
* 접두가 이만큼 더 자라면 재생성한다.
|
||||
|
|
@ -1382,8 +1410,14 @@ export const INPUT_TELEMETRY_DEFAULTS = {
|
|||
activeWindowSampleMinIntervalMs: 1000,
|
||||
/** 마지막 입력 후 이 시간이 지나면 활성 시간 누적을 멈춘다 */
|
||||
activeIdleTimeoutMs: 60000,
|
||||
/** 텍스트 스냅샷(학습/컨텍스트) 디바운스 */
|
||||
textSnapshotDebounceMs: 700,
|
||||
/**
|
||||
* 텍스트 스냅샷(학습/컨텍스트) 디바운스.
|
||||
*
|
||||
* 700ms 였다 — 제안 창은 이 스냅샷이 와야 뜨므로, 잠깐 쉬어도 창이 늦게 떴다("UI 가 빠릿하게, 잠시
|
||||
* 쉬면 나와야" — 2026-10-17). 이 시점에 "생성 중" 자리를 먼저 띄우고(presenceDelayMs), 생성은
|
||||
* 트리거 지연 뒤에 시작한다.
|
||||
*/
|
||||
textSnapshotDebounceMs: 380,
|
||||
/** 백그라운드 샘플 주기 (ms) — 타이핑이 이어져도 관측을 멈추지 않는다 */
|
||||
sampleIntervalMs: 800,
|
||||
/** 마지막 입력이 이 시간 안에 있었으면 주기 샘플을 돌린다 (ms) */
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import { isCommonHangulSyllable } from './hangul-common-syllables'
|
|||
// 타입
|
||||
// ============================================================
|
||||
|
||||
export type TypoSource = 'layout' | 'dictionary' | 'vocabulary' | 'model'
|
||||
export type TypoSource = 'layout' | 'dictionary' | 'vocabulary' | 'model' | 'jamo'
|
||||
|
||||
/** 접두(커서 앞 텍스트) 안의 교정 하나. start/end 는 접두 문자열 오프셋(UTF-16)이다. */
|
||||
export interface TypoCorrection {
|
||||
|
|
@ -591,6 +591,87 @@ export function detectTypos(prefix: string, options: TypoDetectOptions = {}): Ty
|
|||
return out
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 자모 잡음 (낱자가 음절 사이에 끼어든 오타)
|
||||
// ============================================================
|
||||
|
||||
/** 호환 자모 (ㄱ–ㅣ) — 조합되지 못하고 남은 낱자 */
|
||||
const COMPAT_JAMO = /^[\u3131-\u3163]$/u
|
||||
/** 일부러 붙이는 감정 낱자 (고마워ㅎ, 좋아ㅋ, 미안ㅠ) — 낱자 하나여도 오타가 아니다 */
|
||||
const EMOTIVE_JAMO = new Set(['ㅋ', 'ㅎ', 'ㅠ', 'ㅜ'])
|
||||
|
||||
/**
|
||||
* 음절 사이·앞에 끼어든 낱자 하나를 지우는 교정을 찾는다.
|
||||
*
|
||||
* 실측(2026-10-17, 사용자 입력 원문): "안ㄴ뇽", "그ㅓ런", "가쓴ㄷ거", "ㅇ다른", "실망스럽고 ㅇ ㅇ이전".
|
||||
* 빠르게 치다 조합이 깨지면 낱자가 남는다. 낱자 둘 이상(ㅋㅋ, ㅠㅠ, ㅇㅋ)과 끝에 붙인 감정 낱자는
|
||||
* 의도한 표현이라 두고, 단어 하나가 통째로 낱자 하나인 것(문장 중간의 "ㅇ")은 앞 공백과 함께 지운다.
|
||||
* 결정적 규칙은 "지우기" 만 한다 — "안ㄴ뇽 → 안녕" 처럼 글자를 바꿔야 하는 것은 모델 검사 몫이다.
|
||||
*/
|
||||
export function detectJamoNoise(prefix: string, options: { ignoredWords?: readonly string[] } = {}): TypoCorrection[] {
|
||||
const regionStart = typoRegionStart(prefix)
|
||||
const tokens = tokenizeWords(prefix).filter((token) => token.start >= regionStart)
|
||||
const out: TypoCorrection[] = []
|
||||
tokens.forEach((token, index) => {
|
||||
if (isIgnored(token.text, options.ignoredWords)) return
|
||||
const chars = Array.from(token.text)
|
||||
if (chars.length === 1 && COMPAT_JAMO.test(chars[0])) {
|
||||
// 글 첫 단어인 "ㅇ"(응)·"ㄱ"(고) 는 대답이다 — 앞에 한글 단어가 있을 때만 잡음으로 본다.
|
||||
const previous = tokens[index - 1]
|
||||
if (!previous || !HANGUL_SYLLABLE.test(previous.text) || EMOTIVE_JAMO.has(chars[0])) return
|
||||
// 뒤 공백과 함께 지운다 — 앞 공백을 지우면 끝에 남은 낱자("있고 ㅇ")가 "있고" 가 되어, 모델이 끝난
|
||||
// 단어에 글자를 붙이려 하거나 곧바로 턴을 닫았다(실측 2026-10-17: 교정이 붙은 첫 후보 4번 모두 빈 출력).
|
||||
const end = /[ \t]/u.test(prefix[token.end] ?? '') ? token.end + 1 : token.end
|
||||
out.push({ start: token.start, end, from: prefix.slice(token.start, end), to: '', source: 'jamo' })
|
||||
return
|
||||
}
|
||||
if (!HANGUL_SYLLABLE.test(token.text)) return
|
||||
let changed = false
|
||||
const kept = chars.filter((char, position) => {
|
||||
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
|
||||
changed = true
|
||||
return false
|
||||
})
|
||||
if (!changed) return
|
||||
const to = kept.join('')
|
||||
if (!HANGUL_SYLLABLE.test(to)) return
|
||||
out.push({ start: token.start, end: token.end, from: token.text, to, source: 'jamo' })
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 모델에 오타 검사를 맡길 만큼 수상한 구간인가 — 낱자가 섞인 한글 단어, 드문 음절, 결정적 탐지 결과.
|
||||
*
|
||||
* 제안 창에 교정을 함께 내놓을 때 멈출 때마다 모델 검사(0.5초)를 하면 제안이 그만큼 늦는다.
|
||||
* 수상한 흔적이 있을 때만 묻는다.
|
||||
*/
|
||||
export function hasSuspiciousTypo(region: string): boolean {
|
||||
if (detectJamoNoise(region).length > 0) return true
|
||||
return tokenizeWords(region).some((token) =>
|
||||
Array.from(token.text).some((char) => HANGUL_SYLLABLE.test(char) && !isCommonHangulSyllable(char))
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 같은 구간에 대한 교정을 합친다 — 앞 목록이 우선이고, 겹치는 뒤 목록 항목은 버린다.
|
||||
* (모델이 "안ㄴ뇽 → 안녕" 을 냈으면 같은 단어의 "낱자 지우기" 는 쓰지 않는다)
|
||||
*/
|
||||
export function mergeTypoCorrections(
|
||||
primary: readonly TypoCorrection[],
|
||||
secondary: readonly TypoCorrection[]
|
||||
): TypoCorrection[] {
|
||||
const out = [...primary]
|
||||
for (const candidate of secondary) {
|
||||
if (out.some((existing) => candidate.start < existing.end && existing.start < candidate.end)) continue
|
||||
out.push(candidate)
|
||||
}
|
||||
return out.sort((a, b) => a.start - b.start)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 모델 교정 검증
|
||||
// ============================================================
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/i18n",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice 공유 i18n — 12개 locale, 타입 안전 키, Context, 포맷 유틸",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "Ausschlüsse gespeichert.",
|
||||
"input.feedback.cleared": "Erfasste Daten gelöscht.",
|
||||
"popup.suggestion.hintAccept": "Übernehmen",
|
||||
"popup.suggestion.correctionLabel": "Korrigiert",
|
||||
"popup.suggestion.hintNext": "Weiter",
|
||||
"popup.suggestion.hintDismiss": "Schließen",
|
||||
"popup.suggestion.hintMove": "Bewegen",
|
||||
|
|
|
|||
|
|
@ -1778,6 +1778,7 @@
|
|||
"input.feedback.excludedSaved": "Exclusions saved.",
|
||||
"input.feedback.cleared": "Collected data deleted.",
|
||||
"popup.suggestion.hintAccept": "Accept",
|
||||
"popup.suggestion.correctionLabel": "Fixed",
|
||||
"popup.suggestion.hintNext": "Next",
|
||||
"popup.suggestion.hintDismiss": "Dismiss",
|
||||
"popup.suggestion.hintMove": "Move",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "Exclusiones guardadas.",
|
||||
"input.feedback.cleared": "Datos recopilados eliminados.",
|
||||
"popup.suggestion.hintAccept": "Aceptar",
|
||||
"popup.suggestion.correctionLabel": "Corregido",
|
||||
"popup.suggestion.hintNext": "Siguiente",
|
||||
"popup.suggestion.hintDismiss": "Descartar",
|
||||
"popup.suggestion.hintMove": "Mover",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "Exclusions enregistrées.",
|
||||
"input.feedback.cleared": "Données collectées supprimées.",
|
||||
"popup.suggestion.hintAccept": "Accepter",
|
||||
"popup.suggestion.correctionLabel": "Corrigé",
|
||||
"popup.suggestion.hintNext": "Suivant",
|
||||
"popup.suggestion.hintDismiss": "Fermer",
|
||||
"popup.suggestion.hintMove": "Déplacer",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "除外リストを保存しました。",
|
||||
"input.feedback.cleared": "収集したデータを削除しました。",
|
||||
"popup.suggestion.hintAccept": "承認",
|
||||
"popup.suggestion.correctionLabel": "誤字修正",
|
||||
"popup.suggestion.hintNext": "次へ",
|
||||
"popup.suggestion.hintDismiss": "閉じる",
|
||||
"popup.suggestion.hintMove": "移動",
|
||||
|
|
|
|||
|
|
@ -1785,6 +1785,7 @@
|
|||
"input.feedback.excludedSaved": "제외 목록을 저장했습니다.",
|
||||
"input.feedback.cleared": "수집된 데이터를 삭제했습니다.",
|
||||
"popup.suggestion.hintAccept": "수락",
|
||||
"popup.suggestion.correctionLabel": "오타 고침",
|
||||
"popup.suggestion.hintNext": "다음",
|
||||
"popup.suggestion.hintDismiss": "닫기",
|
||||
"popup.suggestion.hintMove": "이동",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "Exclusões salvas.",
|
||||
"input.feedback.cleared": "Dados coletados excluídos.",
|
||||
"popup.suggestion.hintAccept": "Aceitar",
|
||||
"popup.suggestion.correctionLabel": "Corrigido",
|
||||
"popup.suggestion.hintNext": "Próxima",
|
||||
"popup.suggestion.hintDismiss": "Descartar",
|
||||
"popup.suggestion.hintMove": "Mover",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "Исключения сохранены.",
|
||||
"input.feedback.cleared": "Собранные данные удалены.",
|
||||
"popup.suggestion.hintAccept": "Принять",
|
||||
"popup.suggestion.correctionLabel": "Исправлено",
|
||||
"popup.suggestion.hintNext": "Далее",
|
||||
"popup.suggestion.hintDismiss": "Закрыть",
|
||||
"popup.suggestion.hintMove": "Перемещение",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "บันทึกรายการยกเว้นแล้ว",
|
||||
"input.feedback.cleared": "ลบข้อมูลที่เก็บไว้แล้ว",
|
||||
"popup.suggestion.hintAccept": "ยอมรับ",
|
||||
"popup.suggestion.correctionLabel": "แก้คำผิด",
|
||||
"popup.suggestion.hintNext": "ถัดไป",
|
||||
"popup.suggestion.hintDismiss": "ปิด",
|
||||
"popup.suggestion.hintMove": "ย้าย",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "Đã lưu danh sách loại trừ.",
|
||||
"input.feedback.cleared": "Đã xóa dữ liệu thu thập.",
|
||||
"popup.suggestion.hintAccept": "Chấp nhận",
|
||||
"popup.suggestion.correctionLabel": "Đã sửa",
|
||||
"popup.suggestion.hintNext": "Tiếp",
|
||||
"popup.suggestion.hintDismiss": "Đóng",
|
||||
"popup.suggestion.hintMove": "Di chuyển",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "已儲存排除清單。",
|
||||
"input.feedback.cleared": "已刪除收集的資料。",
|
||||
"popup.suggestion.hintAccept": "接受",
|
||||
"popup.suggestion.correctionLabel": "已更正",
|
||||
"popup.suggestion.hintNext": "下一個",
|
||||
"popup.suggestion.hintDismiss": "關閉",
|
||||
"popup.suggestion.hintMove": "移動",
|
||||
|
|
|
|||
|
|
@ -363,6 +363,7 @@
|
|||
"input.feedback.excludedSaved": "已保存排除列表。",
|
||||
"input.feedback.cleared": "已删除收集的数据。",
|
||||
"popup.suggestion.hintAccept": "接受",
|
||||
"popup.suggestion.correctionLabel": "已纠错",
|
||||
"popup.suggestion.hintNext": "下一个",
|
||||
"popup.suggestion.hintDismiss": "关闭",
|
||||
"popup.suggestion.hintMove": "移动",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/ui-native",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice React Native DS — MetalCard/PhosphorText/Led/WaveBars etc.",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@d3ro/ui",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"private": true,
|
||||
"description": "D3RO Voice 공유 UI — 디자인 시스템 컴포넌트 + 테마 토큰 + CSS 변수 맵",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"version": "1.9.0",
|
||||
"androidVersionCode": 1090000,
|
||||
"iosBuildNumber": 1090000,
|
||||
"releaseDate": "2026-09-27",
|
||||
"version": "1.10.0",
|
||||
"androidVersionCode": 1100000,
|
||||
"iosBuildNumber": 1100000,
|
||||
"releaseDate": "2026-10-18",
|
||||
"desktopLicensePublicKeyId": "5c52b765135ee2531c681b53cd4dc0e96fff8737f496c0b04ba8334fc81a887f"
|
||||
}
|
||||
|
|
|
|||
73
scripts/ci/build-desktop-installer.mjs
Normal file
73
scripts/ci/build-desktop-installer.mjs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
// scripts/ci/build-desktop-installer.mjs
|
||||
// 데스크톱 NSIS 설치본(+ blockmap + latest.yml)을 apps/desktop/release/<version>/ 에 만든다.
|
||||
// 로컬 릴리스(release-desktop.mjs)와 CI(release.yml)가 같은 빌드를 쓴다.
|
||||
//
|
||||
// 순서: electron-vite 빌드 → unpacked 트리 → 네이티브 ABI 보정·검증 → app-update.yml 보장
|
||||
// → --prepackaged 로 설치본 (재빌드 없이 검증된 트리 그대로 포장)
|
||||
//
|
||||
// 로컬 AI 런타임(사이드카/ffmpeg)은 설치본에 넣지 않는다 — Cloudflare 업로드 한도(100MiB) 때문.
|
||||
// 앱이 처음 필요할 때 runtime-latest 에서 받는다(RuntimeProvisioner, `npm run release:portable`).
|
||||
//
|
||||
// WIN_CSC_LINK 가 있으면 electron-builder 가 Authenticode 서명을 한다. 없으면 무서명 — 그 대신
|
||||
// 게시 단계가 latest.yml 을 Ed25519 로 서명하고 앱이 검증한다(update-manifest-signature.mjs).
|
||||
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
|
||||
const desktopDir = join(root, 'apps', 'desktop')
|
||||
/** Cloudflare 업로드 본문 한도 (실측: 110MiB → 413) */
|
||||
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024
|
||||
|
||||
const version = JSON.parse(readFileSync(join(root, 'release', 'product-version.json'), 'utf8')).version
|
||||
const releaseDir = join(desktopDir, 'release', version)
|
||||
const appDir = join(releaseDir, 'win-unpacked')
|
||||
const builderFlags = ['--config', 'electron-builder.yml', '--publish', 'never', '-c.win.forceCodeSigning=false', '-c.npmRebuild=false']
|
||||
|
||||
// 같은 버전을 다시 빌드할 때 이전 산출물(휴대용 zip 등)이 섞여 게시되지 않게 비운다.
|
||||
rmSync(releaseDir, { recursive: true, force: true })
|
||||
|
||||
run('npm', ['run', 'build', '--workspace=@d3ro/desktop'], root)
|
||||
run('npx', ['electron-builder', '--win', 'dir', '--x64', ...builderFlags], desktopDir)
|
||||
runNode('scripts/ci/fix-native-abi.mjs', ['--dir', appDir])
|
||||
runNode('scripts/ci/verify-native-abi.mjs', ['--dir', appDir])
|
||||
// app-update.yml 이 없으면 설치된 앱의 electron-updater 가 설정을 못 읽어 자동 업데이트가 죽는다.
|
||||
runNode('scripts/ci/write-app-update-yml.mjs', ['--dir', appDir])
|
||||
run('npx', ['electron-builder', '--prepackaged', appDir, '--win', 'nsis', '--x64', ...builderFlags], desktopDir)
|
||||
|
||||
const installer = readdirSync(releaseDir).find((name) => /-Setup-.*\.exe$/.test(name))
|
||||
if (!installer) fail(`설치본이 없습니다: ${releaseDir}`)
|
||||
for (const required of [`${installer}.blockmap`, 'latest.yml']) {
|
||||
if (!existsSync(join(releaseDir, required))) fail(`${required} 가 없습니다: ${releaseDir}`)
|
||||
}
|
||||
if (!existsSync(join(appDir, 'resources', 'app-update.yml'))) fail('app-update.yml 누락')
|
||||
if (!readFileSync(join(releaseDir, 'latest.yml'), 'utf8').includes(`version: ${version}`)) {
|
||||
fail('latest.yml 의 버전이 product-version.json 과 다릅니다.')
|
||||
}
|
||||
const size = statSync(join(releaseDir, installer)).size
|
||||
if (size > MAX_UPLOAD_BYTES) {
|
||||
fail(
|
||||
`설치본 ${(size / 1048576).toFixed(1)}MiB 가 업로드 한도 100MiB 를 넘습니다 — ` +
|
||||
'런타임(사이드카/ffmpeg)을 electron-builder.yml 의 extraResources/files 에 다시 넣지 않았는지 확인하세요.',
|
||||
)
|
||||
}
|
||||
process.stdout.write(`[build] ${installer} (${(size / 1048576).toFixed(1)}MiB) 준비 완료 — ${releaseDir}\n`)
|
||||
|
||||
function run(command, args, cwd) {
|
||||
process.stdout.write(`[build] $ ${command} ${args.join(' ')}\n`)
|
||||
const result = spawnSync(command, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' })
|
||||
if (result.status !== 0) fail(`${command} ${args[0]} 실패 (exit ${result.status ?? 'null'})`)
|
||||
}
|
||||
|
||||
function runNode(relativePath, args) {
|
||||
process.stdout.write(`[build] $ node ${relativePath} ${args.join(' ')}\n`)
|
||||
const result = spawnSync(process.execPath, [join(root, relativePath), ...args], { cwd: root, stdio: 'inherit' })
|
||||
if (result.status !== 0) fail(`${relativePath} 실패 (exit ${result.status ?? 'null'})`)
|
||||
}
|
||||
|
||||
function fail(message) {
|
||||
process.stderr.write(`[build] ${message}\n`)
|
||||
process.exit(1)
|
||||
}
|
||||
46
scripts/ci/create-update-signing-key.mjs
Normal file
46
scripts/ci/create-update-signing-key.mjs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
// scripts/ci/create-update-signing-key.mjs
|
||||
// 업데이트 메타데이터 서명용 Ed25519 키를 한 번 만든다.
|
||||
// - 비밀키 → 루트 .env 의 D3RO_UPDATE_SIGNING_KEY (이미 있으면 중단 — 키를 바꾸면 기존 앱이 새 릴리스를 거부한다)
|
||||
// - 공개키 → release/desktop-update-public.pem
|
||||
// 그 다음 공개키를 apps/desktop/src/main/update-signature.ts 의 UPDATE_SIGNING_PUBLIC_KEY 에 넣고,
|
||||
// `npm run release:secrets` 로 Forgejo 시크릿에 동기화한다.
|
||||
//
|
||||
// 키를 잃어버리면 이 공개키를 내장한 설치본은 새 릴리스를 더는 받지 못한다(수동 재설치 필요).
|
||||
// .env 백업이 유일한 복구 수단이다.
|
||||
|
||||
import { generateKeyPairSync } from 'node:crypto'
|
||||
import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { SIGNING_KEY_ENV, signManifest, verifyManifest } from './lib/update-manifest-signature.mjs'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
|
||||
const envPath = join(root, '.env')
|
||||
const publicPath = join(root, 'release', 'desktop-update-public.pem')
|
||||
|
||||
const envText = existsSync(envPath) ? readFileSync(envPath, 'utf8') : ''
|
||||
if (new RegExp(`^${SIGNING_KEY_ENV}=`, 'm').test(envText)) {
|
||||
process.stderr.write(`[update-key] .env 에 ${SIGNING_KEY_ENV} 가 이미 있습니다 — 덮어쓰지 않습니다.\n`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (existsSync(publicPath)) {
|
||||
process.stderr.write(`[update-key] ${publicPath} 가 이미 있습니다 — 덮어쓰지 않습니다.\n`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const { privateKey, publicKey } = generateKeyPairSync('ed25519')
|
||||
const publicPem = publicKey.export({ type: 'spki', format: 'pem' }).toString()
|
||||
const probe = 'version: 0.0.0\n'
|
||||
if (!verifyManifest(probe, signManifest(probe, privateKey), publicPem)) {
|
||||
process.stderr.write('[update-key] 생성한 키 자체 검사 실패\n')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const privateB64 = privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64')
|
||||
const separator = envText && !envText.endsWith('\n') ? '\n' : ''
|
||||
appendFileSync(
|
||||
envPath,
|
||||
`${separator}\n# 데스크톱 업데이트 메타데이터 서명 키 (Ed25519, 잃어버리면 기존 앱이 새 릴리스를 거부)\n${SIGNING_KEY_ENV}=${privateB64}\n`,
|
||||
)
|
||||
writeFileSync(publicPath, publicPem, { flag: 'wx' })
|
||||
process.stdout.write(`[update-key] 비밀키 → .env ${SIGNING_KEY_ENV}\n[update-key] 공개키 → ${publicPath}\n${publicPem}`)
|
||||
44
scripts/ci/lib/update-manifest-signature.mjs
Normal file
44
scripts/ci/lib/update-manifest-signature.mjs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// scripts/ci/lib/update-manifest-signature.mjs
|
||||
// 업데이트 메타데이터(latest.yml) Ed25519 서명 — 게시 스크립트와 사후 검증이 같이 쓴다.
|
||||
//
|
||||
// 설치본에 Authenticode 서명이 없으면 electron-updater 는 서명 검증을 건너뛴다. 그래서 피드가
|
||||
// 털리면 아무 설치 파일이나 배포될 수 있다. 대신 latest.yml 을 오프라인 키로 서명하고, 앱은 내장
|
||||
// 공개키로 서명을 확인한 뒤 받은 설치 파일의 sha512 를 그 latest.yml 과 대조한다
|
||||
// (apps/desktop/src/main/update-signature.ts).
|
||||
//
|
||||
// 비밀키: 환경변수 D3RO_UPDATE_SIGNING_KEY = PKCS8 DER 의 base64 한 줄 (.env 정본, Forgejo 시크릿 동기화).
|
||||
// 공개키: release/desktop-update-public.pem (앱 내장 사본과 verify-release-metadata 가 대조).
|
||||
|
||||
import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto'
|
||||
|
||||
export const SIGNING_KEY_ENV = 'D3RO_UPDATE_SIGNING_KEY'
|
||||
export const SIGNATURE_SUFFIX = '.sig'
|
||||
|
||||
export function loadSigningKey(env = process.env) {
|
||||
const raw = env[SIGNING_KEY_ENV]?.trim()
|
||||
if (!raw) {
|
||||
throw new Error(
|
||||
`${SIGNING_KEY_ENV} 가 없습니다 — 업데이트 메타데이터를 서명할 수 없습니다. ` +
|
||||
'루트 .env 에 있는지 확인하세요 (처음이면 node scripts/ci/create-update-signing-key.mjs).',
|
||||
)
|
||||
}
|
||||
const key = createPrivateKey({ key: Buffer.from(raw, 'base64'), format: 'der', type: 'pkcs8' })
|
||||
if (key.asymmetricKeyType !== 'ed25519') throw new Error(`${SIGNING_KEY_ENV} 는 Ed25519 키여야 합니다.`)
|
||||
return key
|
||||
}
|
||||
|
||||
/** latest.yml 바이트에 대한 서명(base64 한 줄) */
|
||||
export function signManifest(manifest, privateKey) {
|
||||
return `${sign(null, Buffer.from(manifest), privateKey).toString('base64')}\n`
|
||||
}
|
||||
|
||||
export function verifyManifest(manifest, signatureText, publicKeyPem) {
|
||||
const signature = Buffer.from(String(signatureText).trim(), 'base64')
|
||||
if (signature.length !== 64) return false
|
||||
return verify(null, Buffer.from(manifest), createPublicKey(publicKeyPem), signature)
|
||||
}
|
||||
|
||||
/** 비밀키에서 공개키 PEM — 게시 전에 저장소 공개키와 짝이 맞는지 확인할 때 쓴다 */
|
||||
export function publicPemOf(privateKey) {
|
||||
return createPublicKey(privateKey).export({ type: 'spki', format: 'pem' }).toString()
|
||||
}
|
||||
|
|
@ -7,6 +7,10 @@
|
|||
// - latest 경로: /api/packages/<owner>/generic/d3ro-voice/latest/<file> (electron-updater feed)
|
||||
// 2) release/update-policy.json을 latest feed에 게시 (원격 정책/킬 스위치)
|
||||
// 3) Forgejo Release 생성/갱신 + 설치 자산 첨부 (admin·site 다운로드 허브)
|
||||
// 4) 공개 URL 에서 서명된 latest.yml 을 다시 받아 서명·설치본 해시를 검증 (기존 앱이 받을 그대로)
|
||||
//
|
||||
// latest.yml 은 Ed25519 로 서명해 latest.yml.sig 를 함께 올린다 (D3RO_UPDATE_SIGNING_KEY 필수).
|
||||
// 무서명 설치본이라도 앱이 이 서명으로 설치 파일을 검증한다 — apps/desktop/src/main/update-signature.ts.
|
||||
//
|
||||
// 배포 순서 보장: 설치파일/blockmap을 먼저 올리고 update metadata(latest.yml)를
|
||||
// 마지막에 게시한다. 기존 설치본이 배포 도중 404를 받지 않는다.
|
||||
|
|
@ -19,7 +23,7 @@
|
|||
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream, readFileSync } from "node:fs";
|
||||
import { readFile, readdir, stat } from "node:fs/promises";
|
||||
import { readFile, readdir, stat, writeFile } from "node:fs/promises";
|
||||
import { basename, join } from "node:path";
|
||||
import process from "node:process";
|
||||
import { fileURLToPath, URL } from "node:url";
|
||||
|
|
@ -38,6 +42,13 @@ import {
|
|||
parseRuntimeMinVersions,
|
||||
} from "./lib/runtime-feed-gate.mjs";
|
||||
import { assertValidUpdatePolicy } from "./lib/update-policy-schema.mjs";
|
||||
import {
|
||||
SIGNATURE_SUFFIX,
|
||||
loadSigningKey,
|
||||
publicPemOf,
|
||||
signManifest,
|
||||
verifyManifest,
|
||||
} from "./lib/update-manifest-signature.mjs";
|
||||
|
||||
const { forgejoAuthorization } = credentialHelpers;
|
||||
|
||||
|
|
@ -81,7 +92,25 @@ assertValidUpdatePolicy(readFileSync(policyPath), "release/update-policy.json");
|
|||
const releaseDirectory = process.env.FORGEJO_RELEASE_DIR?.trim()
|
||||
? process.env.FORGEJO_RELEASE_DIR.trim()
|
||||
: fileURLToPath(new URL(`../../apps/desktop/release/${version}/`, import.meta.url));
|
||||
const ASSET_PATTERN = /(\.exe|\.dmg|\.zip|\.blockmap|^(latest|beta|alpha)(-mac|-linux)?\.yml)$/;
|
||||
// 같은 폴더에 휴대용 zip/7z·__uninstaller exe 가 섞일 수 있다 — 업데이트 자산만 고른다.
|
||||
const ASSET_PATTERN = /(-Setup-[^/]*\.exe(\.blockmap)?|\.dmg|-mac\.zip(\.blockmap)?|^(latest|beta|alpha)(-mac|-linux)?\.yml(\.sig)?)$/;
|
||||
|
||||
// latest.yml 서명 — 키가 저장소 공개키와 짝이 아니면 앱이 거부할 릴리스이므로 아무것도 올리지 않는다.
|
||||
const repoPublicKeyPem = readFileSync(
|
||||
fileURLToPath(new URL("../../release/desktop-update-public.pem", import.meta.url)),
|
||||
"utf8",
|
||||
);
|
||||
if (!dryRun || process.env.D3RO_UPDATE_SIGNING_KEY) {
|
||||
const signingKey = loadSigningKey();
|
||||
if (publicPemOf(signingKey).trim() !== repoPublicKeyPem.trim()) {
|
||||
throw new Error("D3RO_UPDATE_SIGNING_KEY 가 release/desktop-update-public.pem 과 짝이 아닙니다.");
|
||||
}
|
||||
for (const name of await readdir(releaseDirectory)) {
|
||||
if (!/^(latest|beta|alpha)(-mac|-linux)?\.yml$/.test(name)) continue;
|
||||
const manifest = await readFile(join(releaseDirectory, name));
|
||||
await writeFile(join(releaseDirectory, `${name}${SIGNATURE_SUFFIX}`), signManifest(manifest, signingKey));
|
||||
}
|
||||
}
|
||||
|
||||
const files = [];
|
||||
for (const name of await readdir(releaseDirectory)) {
|
||||
|
|
@ -96,6 +125,9 @@ if (!files.some((file) => file.name.endsWith(".exe"))) {
|
|||
if (!files.some((file) => file.name === "latest.yml")) {
|
||||
throw new Error(`latest.yml is missing for ${tag} — check electron-builder.yml publish config.`);
|
||||
}
|
||||
if (!dryRun && !files.some((file) => file.name === `latest.yml${SIGNATURE_SUFFIX}`)) {
|
||||
throw new Error(`latest.yml${SIGNATURE_SUFFIX} is missing for ${tag}.`);
|
||||
}
|
||||
if (!files.some((file) => file.name.endsWith(".dmg"))) {
|
||||
process.stdout.write(`WARNING: macOS artifacts missing for ${tag} — Windows-only release.\n`);
|
||||
}
|
||||
|
|
@ -195,7 +227,10 @@ if (latestFeed.update) {
|
|||
await verifyPublicFile(`${packageVersionedUrl}/latest.yml`);
|
||||
}
|
||||
|
||||
// 4) Forgejo Release 생성/갱신 + 자산 첨부
|
||||
// 4) 기존 앱이 받을 그대로 검증 — 공개(무인증) 버전별 경로의 latest.yml + 서명 + 설치본 해시
|
||||
await verifySignedPublicManifest();
|
||||
|
||||
// 5) Forgejo Release 생성/갱신 + 자산 첨부
|
||||
const description = await buildReleaseDescription();
|
||||
const releaseId = await upsertRelease(description);
|
||||
for (const file of sorted) {
|
||||
|
|
@ -236,7 +271,7 @@ function safeAssetName(name) {
|
|||
}
|
||||
|
||||
function isUpdateMetadata(name) {
|
||||
return /(?:\.blockmap$|^(?:latest|beta|alpha)(?:-mac|-linux)?\.yml$|^update-policy\.json$)/.test(name);
|
||||
return /(?:\.blockmap$|^(?:latest|beta|alpha)(?:-mac|-linux)?\.yml(?:\.sig)?$|^update-policy\.json$)/.test(name);
|
||||
}
|
||||
|
||||
function isYamlUpdateMetadata(name) {
|
||||
|
|
@ -333,6 +368,31 @@ async function verifyPublicFile(url) {
|
|||
if (!body.trim()) throw new Error(`Public updater file is empty: ${url}`);
|
||||
}
|
||||
|
||||
async function verifySignedPublicManifest() {
|
||||
const url = `${packageVersionedUrl}/latest.yml`;
|
||||
const [manifestResponse, signatureResponse] = await Promise.all([
|
||||
fetch(url, { cache: "no-store" }),
|
||||
fetch(`${url}${SIGNATURE_SUFFIX}`, { cache: "no-store" }),
|
||||
]);
|
||||
if (!manifestResponse.ok || !signatureResponse.ok) {
|
||||
throw new Error(
|
||||
`Public signed manifest unreachable: latest.yml HTTP ${manifestResponse.status}, .sig HTTP ${signatureResponse.status}`,
|
||||
);
|
||||
}
|
||||
const manifest = await manifestResponse.text();
|
||||
if (!verifyManifest(manifest, await signatureResponse.text(), repoPublicKeyPem)) {
|
||||
throw new Error(`Public ${url} signature does not verify with release/desktop-update-public.pem.`);
|
||||
}
|
||||
const signedSha512 = manifest.match(/^sha512:\s*(\S+)\s*$/m)?.[1];
|
||||
const installer = sorted.find((file) => /-Setup-.*\.exe$/.test(file.name));
|
||||
const localSha512 = createHash("sha512").update(await readFile(installer.path)).digest("base64");
|
||||
if (signedSha512 !== localSha512) {
|
||||
throw new Error(`Signed latest.yml sha512 does not match ${installer.name}.`);
|
||||
}
|
||||
process.stdout.write(` verified public signed manifest ${url}
|
||||
`);
|
||||
}
|
||||
|
||||
async function buildReleaseDescription() {
|
||||
const changelog = await readFile(
|
||||
fileURLToPath(new URL("../../CHANGELOG.md", import.meta.url)),
|
||||
|
|
|
|||
|
|
@ -1,259 +0,0 @@
|
|||
// scripts/ci/publish-gitlab-release.mjs
|
||||
// 태그 파이프라인의 release 스테이지에서 실행:
|
||||
// 1) package-windows / package-macos artifacts를 GitLab Generic Package Registry에 업로드
|
||||
// - 버전별 경로: packages/generic/d3ro-voice/<version>/<file>
|
||||
// - latest 경로: packages/generic/d3ro-voice/latest/<file> (electron-updater feed)
|
||||
// 2) GitLab Release 생성 + asset 링크 연결
|
||||
//
|
||||
// agent-switchboard-client의 publish-gitlab-release.mjs 패턴을 D3RO에 맞게 단순화.
|
||||
// (Ed25519 update-policy 서명 체계는 후속 단계 — 현재는 latest.yml 기반)
|
||||
//
|
||||
// 필요 env: CI_API_V4_URL, CI_PROJECT_ID, CI_JOB_TOKEN, CI_COMMIT_TAG
|
||||
|
||||
import { createReadStream, readFileSync } from "node:fs";
|
||||
import { readFile, readdir, stat } from "node:fs/promises";
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { basename, join } from "node:path";
|
||||
import process from "node:process";
|
||||
import { fileURLToPath, URL } from "node:url";
|
||||
|
||||
const apiUrl = required("CI_API_V4_URL").replace(/\/+$/, "");
|
||||
const projectId = required("CI_PROJECT_ID");
|
||||
const jobToken = required("CI_JOB_TOKEN");
|
||||
const tag = required("CI_COMMIT_TAG");
|
||||
const version = tag.replace(/^v/, "");
|
||||
const packageName = "d3ro-voice";
|
||||
|
||||
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version)) {
|
||||
throw new Error(`Unsupported release tag: ${tag}`);
|
||||
}
|
||||
|
||||
const productVersion = JSON.parse(
|
||||
await readFile(fileURLToPath(new URL("../../release/product-version.json", import.meta.url)), "utf8"),
|
||||
);
|
||||
if (tag !== `v${productVersion.version}` || !/^\d+\.\d+\.\d+$/.test(version)) {
|
||||
throw new Error(`Release tag ${tag} does not match stable product version v${productVersion.version}.`);
|
||||
}
|
||||
|
||||
// electron-builder output: apps/desktop/release/<version>/
|
||||
const releaseDirectory = fileURLToPath(new URL(`../../apps/desktop/release/${version}/`, import.meta.url));
|
||||
|
||||
// 업로드 대상 수집 — 설치파일 + 업데이터 메타데이터만 (unpacked 디렉토리 제외)
|
||||
const ASSET_PATTERN = /(\.exe|\.dmg|\.zip|\.blockmap|^(latest|alpha|beta)(-mac|-linux)?\.yml)$/;
|
||||
|
||||
const files = [];
|
||||
for (const name of await readdir(releaseDirectory)) {
|
||||
if (!ASSET_PATTERN.test(name)) continue;
|
||||
const path = join(releaseDirectory, name);
|
||||
if ((await stat(path)).isFile()) files.push({ name, path });
|
||||
}
|
||||
|
||||
if (files.length === 0) {
|
||||
throw new Error(`No release assets found in ${releaseDirectory}`);
|
||||
}
|
||||
|
||||
const hasWindows = files.some((file) => file.name.endsWith(".exe"));
|
||||
if (!hasWindows) {
|
||||
throw new Error(`Windows installer is missing for ${tag}.`);
|
||||
}
|
||||
// latest.yml은 자동 업데이트 feed의 핵심 — 없으면 electron-builder publish 설정 회귀
|
||||
if (!files.some((file) => file.name === "latest.yml")) {
|
||||
throw new Error(
|
||||
`latest.yml is missing for ${tag} — check electron-builder.yml publish config.`,
|
||||
);
|
||||
}
|
||||
const hasMac = files.some((file) => file.name.endsWith(".dmg"));
|
||||
if (!hasMac) {
|
||||
// mac runner 미등록/실패 시에도 Windows 단독 릴리스는 진행 (경고만)
|
||||
process.stdout.write(`WARNING: macOS artifacts missing for ${tag} — Windows-only release.\n`);
|
||||
}
|
||||
|
||||
const packageBaseUrl = `${apiUrl}/projects/${encodeURIComponent(projectId)}/packages/generic/${packageName}/${version}`;
|
||||
const latestPackageBaseUrl = `${apiUrl}/projects/${encodeURIComponent(projectId)}/packages/generic/${packageName}/latest`;
|
||||
|
||||
const links = [];
|
||||
const sortedFiles = files.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
// 1) 버전별 패키지 업로드
|
||||
for (const file of sortedFiles) {
|
||||
const registryName = safeAssetName(file.name);
|
||||
const uploadUrl = `${packageBaseUrl}/${encodeURIComponent(registryName)}`;
|
||||
await uploadFile(file, uploadUrl, "versioned package");
|
||||
links.push({
|
||||
name: file.name,
|
||||
url: uploadUrl,
|
||||
direct_asset_path: `/${registryName}`,
|
||||
link_type: isUpdateMetadata(file.name) ? "other" : "package",
|
||||
});
|
||||
}
|
||||
|
||||
// 2) latest 패키지 갱신. 설치파일과 blockmap을 먼저 올리고, update metadata를
|
||||
// 마지막에 게시한다. 기존 latest를 선삭제하지 않으므로 배포 중에도 이전
|
||||
// 설치본이 404를 받지 않는다. 중복 업로드가 금지된 인스턴스라면 metadata
|
||||
// 전환 전에 실패해 기존 feed가 그대로 보존된다.
|
||||
const latestFiles = [...sortedFiles].sort((a, b) => {
|
||||
const metadataOrder = Number(isUpdateMetadata(a.name)) - Number(isUpdateMetadata(b.name));
|
||||
return metadataOrder || a.name.localeCompare(b.name);
|
||||
});
|
||||
for (const file of latestFiles) {
|
||||
const registryName = safeAssetName(file.name);
|
||||
await uploadFile(file, `${latestPackageBaseUrl}/${encodeURIComponent(registryName)}`, "latest package");
|
||||
}
|
||||
|
||||
for (const file of latestFiles.filter((candidate) => isYamlUpdateMetadata(candidate.name))) {
|
||||
validateUpdateMetadataReferences(file, latestFiles);
|
||||
}
|
||||
for (const file of latestFiles.filter((candidate) => isUpdateMetadata(candidate.name))) {
|
||||
await verifyPublicLatestFile(file, latestPackageBaseUrl);
|
||||
}
|
||||
|
||||
// 3) GitLab Release 생성 또는 재시도 시 안전하게 갱신
|
||||
const description = await buildDescription();
|
||||
const releaseUrl = `${apiUrl}/projects/${encodeURIComponent(projectId)}/releases`;
|
||||
await upsertRelease(releaseUrl, description, links);
|
||||
|
||||
process.stdout.write(`Created ${tag} with ${links.length} release assets.\n`);
|
||||
|
||||
// ── 헬퍼 ────────────────────────────────────────────────────
|
||||
|
||||
function required(name) {
|
||||
const value = process.env[name]?.trim();
|
||||
if (!value) throw new Error(`${name} is required.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function safeAssetName(name) {
|
||||
return basename(name).replace(/[^A-Za-z0-9._-]+/g, "-");
|
||||
}
|
||||
|
||||
function isUpdateMetadata(name) {
|
||||
return /(?:\.blockmap$|^(?:latest|alpha|beta)(?:-mac|-linux)?\.yml$)/.test(name);
|
||||
}
|
||||
|
||||
function isYamlUpdateMetadata(name) {
|
||||
return /^(?:latest|alpha|beta)(?:-mac|-linux)?\.yml$/.test(name);
|
||||
}
|
||||
|
||||
async function buildDescription() {
|
||||
const changelog = await readFile(
|
||||
fileURLToPath(new URL("../../CHANGELOG.md", import.meta.url)),
|
||||
"utf8",
|
||||
);
|
||||
const section = extractChangelogSection(changelog, version);
|
||||
if (!section) throw new Error(`CHANGELOG.md is missing a ${version} release section.`);
|
||||
return section;
|
||||
}
|
||||
|
||||
function extractChangelogSection(changelog, targetVersion) {
|
||||
const lines = changelog.split("\n");
|
||||
// 버전 뒤 경계 필수 — "0.1.0"이 "0.1.0-alpha" 섹션에 오매칭되지 않게
|
||||
const escaped = targetVersion.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const headerPattern = new RegExp(`^##\\s+\\[?v?${escaped}(?:\\]|\\s|$)`);
|
||||
const start = lines.findIndex((line) => headerPattern.test(line));
|
||||
if (start === -1) return null;
|
||||
let end = lines.length;
|
||||
for (let i = start + 1; i < lines.length; i++) {
|
||||
if (/^##\s+/.test(lines[i])) {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return lines.slice(start, end).join("\n").trim();
|
||||
}
|
||||
|
||||
async function uploadFile(file, uploadUrl, target) {
|
||||
process.stdout.write(`Uploading ${file.name} to ${target}...\n`);
|
||||
const response = await globalThis.fetch(uploadUrl, {
|
||||
method: "PUT",
|
||||
headers: { "JOB-TOKEN": jobToken },
|
||||
body: createReadStream(file.path),
|
||||
duplex: "half",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`${target} upload failed for ${file.name}: HTTP ${response.status} ${await response.text()}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateUpdateMetadataReferences(metadataFile, uploadedFiles) {
|
||||
const text = readFileSyncUtf8(metadataFile.path);
|
||||
const uploadedNames = new Set(uploadedFiles.map((file) => safeAssetName(file.name)));
|
||||
const references = [...text.matchAll(/^\s*(?:-\s+url:|path:)\s*["']?([^"'\r\n]+?)["']?\s*$/gm)]
|
||||
.map((match) => basename(match[1].trim()));
|
||||
if (references.length === 0) {
|
||||
throw new Error(`${metadataFile.name} does not reference a release artifact.`);
|
||||
}
|
||||
for (const reference of references) {
|
||||
if (!uploadedNames.has(reference)) {
|
||||
throw new Error(`${metadataFile.name} references missing release artifact ${reference}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function readFileSyncUtf8(path) {
|
||||
return readFileSync(path, "utf8");
|
||||
}
|
||||
|
||||
async function verifyPublicLatestFile(file, packageBaseUrl) {
|
||||
const publicUrl = `${packageBaseUrl}/${encodeURIComponent(safeAssetName(file.name))}?release=${encodeURIComponent(tag)}`;
|
||||
const response = await globalThis.fetch(publicUrl, { cache: "no-store" });
|
||||
if (!response.ok) {
|
||||
throw new Error(`Public updater verification failed for ${file.name}: HTTP ${response.status}`);
|
||||
}
|
||||
const expected = await readFile(file.path);
|
||||
const actual = Buffer.from(await response.arrayBuffer());
|
||||
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
|
||||
throw new Error(`Public updater verification returned stale or altered ${file.name}.`);
|
||||
}
|
||||
process.stdout.write(`Verified public latest metadata ${file.name}.\n`);
|
||||
}
|
||||
|
||||
async function upsertRelease(releaseUrl, description, desiredLinks) {
|
||||
const headers = { "JOB-TOKEN": jobToken, "Content-Type": "application/json" };
|
||||
const existingUrl = `${releaseUrl}/${encodeURIComponent(tag)}`;
|
||||
const existingResponse = await globalThis.fetch(existingUrl, { headers });
|
||||
|
||||
if (existingResponse.status === 404) {
|
||||
const createResponse = await globalThis.fetch(releaseUrl, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
name: `D3RO Voice ${tag}`,
|
||||
tag_name: tag,
|
||||
description,
|
||||
assets: { links: desiredLinks },
|
||||
}),
|
||||
});
|
||||
if (!createResponse.ok) {
|
||||
throw new Error(`Release creation failed: HTTP ${createResponse.status} ${await createResponse.text()}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!existingResponse.ok) {
|
||||
throw new Error(`Release lookup failed: HTTP ${existingResponse.status} ${await existingResponse.text()}`);
|
||||
}
|
||||
|
||||
const existing = await existingResponse.json();
|
||||
const updateResponse = await globalThis.fetch(existingUrl, {
|
||||
method: "PUT",
|
||||
headers,
|
||||
body: JSON.stringify({ name: `D3RO Voice ${tag}`, description }),
|
||||
});
|
||||
if (!updateResponse.ok) {
|
||||
throw new Error(`Release update failed: HTTP ${updateResponse.status} ${await updateResponse.text()}`);
|
||||
}
|
||||
|
||||
const existingLinks = Array.isArray(existing?.assets?.links) ? existing.assets.links : [];
|
||||
for (const desired of desiredLinks) {
|
||||
const match = existingLinks.find((link) => link?.name === desired.name);
|
||||
const linksBase = `${existingUrl}/assets/links`;
|
||||
const response = await globalThis.fetch(match ? `${linksBase}/${encodeURIComponent(match.id)}` : linksBase, {
|
||||
method: match ? "PUT" : "POST",
|
||||
headers,
|
||||
body: JSON.stringify(desired),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Release link upsert failed for ${desired.name}: HTTP ${response.status} ${await response.text()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,316 +0,0 @@
|
|||
// scripts/ci/publish-updater-release.mjs
|
||||
// 자동 업데이트 채널(latest)에 디스크톱 설치본을 게시한다.
|
||||
//
|
||||
// 전제: 설치본이 Cloudflare 업로드 한도(100MiB) 아래여야 한다. 그래서 로컬 AI
|
||||
// 런타임(사이드카/ffmpeg)은 설치본에 넣지 않고, 앱이 처음 필요할 때
|
||||
// `runtime-latest`에서 내려받는다(RuntimeProvisioner, `npm run release:portable`가 게시).
|
||||
//
|
||||
// 정책 예외(명시):
|
||||
// - 이 채널은 일반적으로 Authenticode 서명을 요구한다. 서명 인증서가 준비되기 전까지
|
||||
// 업데이트를 전달할 수 없어, **무서명 빌드를 명시적 승인(--ack-unsigned)으로만** 게시한다.
|
||||
// - 검증되지 않은 서명을 조용히 게시하지 않는다: 승인 플래그가 없으면 즉시 실패한다.
|
||||
//
|
||||
// 사용:
|
||||
// npm run build --workspace=@d3ro/desktop
|
||||
// node scripts/ci/publish-updater-release.mjs --build --ack-unsigned
|
||||
// node scripts/ci/publish-updater-release.mjs --check # 게시 예정만 확인
|
||||
|
||||
import credentialHelpers from '../lib/credentials.cjs'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
RUNTIME_MIN_VERSION_SOURCE,
|
||||
WINDOWS_X64_TARGET,
|
||||
assertRuntimeFeedCompatible,
|
||||
parseRuntimeMinVersions,
|
||||
} from './lib/runtime-feed-gate.mjs'
|
||||
import { assertValidUpdatePolicy } from './lib/update-policy-schema.mjs'
|
||||
|
||||
const { forgejoAuthorization } = credentialHelpers
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
|
||||
const desktopDir = join(root, 'apps', 'desktop')
|
||||
const args = process.argv.slice(2)
|
||||
const check = args.includes('--check')
|
||||
const ackUnsigned = args.includes('--ack-unsigned')
|
||||
const build = args.includes('--build')
|
||||
|
||||
const FEED = 'https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice'
|
||||
/** Cloudflare 업로드 본문 한도 (실측: 110MiB → 413) */
|
||||
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024
|
||||
|
||||
const version = JSON.parse(
|
||||
readFileSync(join(root, 'release', 'product-version.json'), 'utf8'),
|
||||
).version
|
||||
const releaseDir = join(desktopDir, 'release', version)
|
||||
|
||||
if (build) {
|
||||
const appDir = join(releaseDir, 'win-unpacked')
|
||||
|
||||
// 1) 먼저 unpacked 트리빌드한다.
|
||||
console.log('[updater] electron-builder --dir (앱 전용 — 런타임 제외)')
|
||||
const result = spawnSync(
|
||||
'npx',
|
||||
[
|
||||
'electron-builder',
|
||||
'--win',
|
||||
'dir',
|
||||
'--x64',
|
||||
'--config',
|
||||
'electron-builder.yml',
|
||||
'--publish',
|
||||
'never',
|
||||
'-c.win.forceCodeSigning=false',
|
||||
'-c.npmRebuild=false',
|
||||
],
|
||||
{ cwd: desktopDir, stdio: 'inherit', shell: process.platform === 'win32' },
|
||||
)
|
||||
if (result.status !== 0) {
|
||||
console.error(`[updater] 빌드 실패 (exit ${result.status ?? 'null'})`)
|
||||
process.exit(result.status ?? 1)
|
||||
}
|
||||
|
||||
// 2) 네이티브 모듈 ABI 보장 + 검증 (호스트 Node ABI가 섞이면 이 시작조차 못 한다)
|
||||
runNodeScript('scripts/ci/fix-native-abi.mjs', ['--dir', appDir])
|
||||
runNodeScript('scripts/ci/verify-native-abi.mjs', ['--dir', appDir])
|
||||
|
||||
// electron-updater 설정 파일을 보장한다(없으면 자동 업데이트가 동작하지 않는다)
|
||||
runNodeScript('scripts/ci/write-app-update-yml.mjs', ['--dir', appDir])
|
||||
|
||||
// 3) 검증된 트리에서 설치본 생성 (--prepackaged = 재빌드 없이 그대로 패키징)
|
||||
console.log('[updater] electron-builder --prepackaged (NSIS x64)')
|
||||
const packageResult = spawnSync(
|
||||
'npx',
|
||||
[
|
||||
'electron-builder',
|
||||
'--prepackaged',
|
||||
appDir,
|
||||
'--win',
|
||||
'nsis',
|
||||
'--x64',
|
||||
'--config',
|
||||
'electron-builder.yml',
|
||||
'--publish',
|
||||
'never',
|
||||
'-c.win.forceCodeSigning=false',
|
||||
'-c.npmRebuild=false',
|
||||
],
|
||||
{ cwd: desktopDir, stdio: 'inherit', shell: process.platform === 'win32' },
|
||||
)
|
||||
if (packageResult.status !== 0) {
|
||||
console.error(`[updater] 설치본 생성 실패 (exit ${packageResult.status ?? 'null'})`)
|
||||
process.exit(packageResult.status ?? 1)
|
||||
}
|
||||
}
|
||||
|
||||
/** 이 스크립트와 같은 Node로 CI 스크립트를 실행한다 */
|
||||
function runNodeScript(relativePath, scriptArgs) {
|
||||
console.log(`[updater] $ node ${relativePath} ${scriptArgs.join(' ')}`)
|
||||
const result = spawnSync(process.execPath, [join(root, relativePath), ...scriptArgs], {
|
||||
cwd: root,
|
||||
stdio: 'inherit',
|
||||
})
|
||||
if (result.status !== 0) {
|
||||
console.error(`[updater] ${relativePath} 실패 (exit ${result.status ?? 'null'})`)
|
||||
process.exit(result.status ?? 1)
|
||||
}
|
||||
}
|
||||
|
||||
const metadataPath = join(releaseDir, 'latest.yml')
|
||||
if (!existsSync(metadataPath)) {
|
||||
console.error(
|
||||
`[updater] latest.yml이 없습니다: ${metadataPath}\n --build로 먼저 빌드하세요.`,
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const candidates = readdirSync(releaseDir).filter(
|
||||
(name) => /\.exe$/.test(name) && !/__uninstaller|apponly/i.test(name),
|
||||
)
|
||||
const installer = candidates.find((name) => name.includes('Setup')) ?? candidates[0]
|
||||
if (!installer) {
|
||||
console.error(`[updater] 설치본을 찾을 수 없습니다: ${releaseDir}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const installerPath = join(releaseDir, installer)
|
||||
const blockmapPath = `${installerPath}.blockmap`
|
||||
const policyPath = join(root, 'release', 'update-policy.json')
|
||||
|
||||
// 원격 정책은 오타 하나로 킬 스위치·staged rollout 이 조용히 꺼질 수 있다 — 올리기 전에 엄격히 검증한다.
|
||||
if (existsSync(policyPath)) {
|
||||
try {
|
||||
assertValidUpdatePolicy(readFileSync(policyPath), 'release/update-policy.json')
|
||||
} catch (error) {
|
||||
console.error(`[updater] ${error instanceof Error ? error.message : String(error)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
const payloads = [
|
||||
{ name: installer, path: installerPath, type: 'application/octet-stream' },
|
||||
{ name: `${installer}.blockmap`, path: blockmapPath, type: 'application/octet-stream' },
|
||||
{ name: 'latest.yml', path: metadataPath, type: 'text/yaml' },
|
||||
{ name: 'update-policy.json', path: policyPath, type: 'application/json' },
|
||||
].filter((payload) => existsSync(payload.path))
|
||||
|
||||
const installerSize = statSync(installerPath).size
|
||||
console.log(
|
||||
[
|
||||
`[updater] 버전 ${version}`,
|
||||
` 설치본 : ${installer} (${(installerSize / 1048576).toFixed(1)}MiB)`,
|
||||
` 한도 : ${(MAX_UPLOAD_BYTES / 1048576).toFixed(0)}MiB (Cloudflare 업로드 본문 한도)`,
|
||||
].join('\n'),
|
||||
)
|
||||
|
||||
if (installerSize > MAX_UPLOAD_BYTES) {
|
||||
console.error(
|
||||
[
|
||||
'[updater] 설치본이 업로드 한도를 넘습니다 — 게시할 수 없습니다.',
|
||||
' 런타임(사이드카/ffmpeg)을 설치본에 다시 넣지 않았는지 확인하세요:',
|
||||
' `apps/desktop/electron-builder.yml`의 extraResources / files / asarUnpack.',
|
||||
].join('\n'),
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// 설치본에 app-update.yml이 없으면 electron-updater가 설정을 읽지 못해 자동 업데이트가 죽는다.
|
||||
const packagedUpdateConfig = join(releaseDir, 'win-unpacked', 'resources', 'app-update.yml')
|
||||
if (!existsSync(packagedUpdateConfig)) {
|
||||
console.error('[updater] app-update.yml 누락 — write-app-update-yml.mjs를 먼저 실행하세요.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const metadata = readFileSync(metadataPath, 'utf8')
|
||||
if (!metadata.includes(`version: ${version}`)) {
|
||||
console.error('[updater] latest.yml의 버전이 product-version.json과 다릅니다.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const targets = [`${FEED}/${version}`, `${FEED}/latest`]
|
||||
|
||||
// 앱이 요구하는 런타임(RUNTIME_MIN_VERSION)을 runtime-latest 가 아직 제공하지 못하면, 이 설치본으로
|
||||
// 업데이트한 사용자는 로컬 STT 엔진을 쓸 수 없다. latest.yml 을 올리기 전에 fail-closed 로 확인한다.
|
||||
try {
|
||||
const runtime = await assertRuntimeFeedCompatible({
|
||||
url: `${FEED}/runtime-latest/runtime.json`,
|
||||
fetchImpl: (url, init) => fetch(url, init),
|
||||
minVersions: parseRuntimeMinVersions(readFileSync(join(root, RUNTIME_MIN_VERSION_SOURCE), 'utf8')),
|
||||
target: WINDOWS_X64_TARGET,
|
||||
})
|
||||
console.log(`[updater] runtime-latest ${runtime.version} 이 이 빌드의 최소 런타임 요구를 만족합니다.`)
|
||||
} catch (error) {
|
||||
console.error(`[updater] ${error instanceof Error ? error.message : String(error)}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (check) {
|
||||
console.log('[updater] (check) 게시 예정:')
|
||||
for (const target of targets) {
|
||||
for (const payload of payloads) {
|
||||
console.log(` PUT ${target}/${payload.name} (${statSync(payload.path).size} bytes)`)
|
||||
}
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (!ackUnsigned) {
|
||||
console.error(
|
||||
[
|
||||
'[updater] 무서명 빌드를 stable 채널에 게시하려면 명시적 승인이 필요합니다.',
|
||||
' 서명 인증서가 준비되면 이 플래그 없이 게시하세요(권장).',
|
||||
' 승인: --ack-unsigned',
|
||||
].join('\n'),
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const authorization = forgejoAuthorization()
|
||||
|
||||
/**
|
||||
* 원격 파일이 로컬 바이트와 같은지 판단한다.
|
||||
* Forgejo generic registry는 HEAD를 405로 거부하고 해시도 주지 않으므로,
|
||||
* Range GET으로 크기를 본 뒤 1MiB 이하는 실제 바이트까지 비교한다.
|
||||
* (크기만 비교하면 버전 문자열만 바뀐 latest.yml 같은 메타데이터를 놓친다 — 실측 사고.)
|
||||
*/
|
||||
async function remoteIsIdentical(url, body, fetchImpl) {
|
||||
const probe = await fetchImpl(url, { headers: { Range: 'bytes=0-0' } }).catch(() => null)
|
||||
if (!probe?.ok) return false
|
||||
const contentRange = probe.headers.get('content-range')
|
||||
const remoteSize = contentRange ? Number(contentRange.split('/')[1]) : NaN
|
||||
if (!Number.isFinite(remoteSize) || remoteSize !== body.length) return false
|
||||
if (body.length > 1024 * 1024) return true
|
||||
const full = await fetchImpl(url).catch(() => null)
|
||||
if (!full?.ok) return false
|
||||
const remoteBytes = Buffer.from(await full.arrayBuffer())
|
||||
return remoteBytes.length === body.length && remoteBytes.equals(body)
|
||||
}
|
||||
|
||||
async function forgejoFetch(url, init = {}) {
|
||||
return fetch(url, {
|
||||
...init,
|
||||
headers: { Authorization: authorization, ...(init.headers ?? {}) },
|
||||
})
|
||||
}
|
||||
|
||||
console.log(
|
||||
[
|
||||
'[updater] 경고: 무서명 설치본을 stable(latest) 채널에 게시합니다.',
|
||||
' - electron-updater는 app-update.yml에 publisherName이 없으면 서명 검증을 건너뛰므로',
|
||||
' 설치 자체는 정상 동작합니다.',
|
||||
' - 인증서가 준비되면 이 버전보다 높은 버전으로 서명 게시하여 대체하세요.',
|
||||
].join('\n'),
|
||||
)
|
||||
|
||||
for (const target of targets) {
|
||||
for (const payload of payloads) {
|
||||
const url = `${target}/${encodeURIComponent(payload.name)}`
|
||||
const body = await readFile(payload.path)
|
||||
|
||||
// Forgejo generic registry는 HEAD를 405로 거부하고 해시도 주지 않는다.
|
||||
// 크기만 비교하면 버전 문자열만 바뀐 latest.yml을 "동일"로 오판한다 — 내용까지 비교한다.
|
||||
if (await remoteIsIdentical(url, body, forgejoFetch)) {
|
||||
console.log(`[updater] 이미 동일한 파일이 있습니다(건너): ${url}`)
|
||||
continue
|
||||
}
|
||||
|
||||
// 메타데이터는 최신을 가리켜야 하므로 기존 파일을 지우고 쓴다(PUT은 409를 돌려준다).
|
||||
const existing = await forgejoFetch(url, { headers: { Range: 'bytes=0-0' } }).catch(() => null)
|
||||
if (existing?.ok) {
|
||||
await forgejoFetch(url, { method: 'DELETE' }).catch(() => null)
|
||||
}
|
||||
|
||||
const response = await forgejoFetch(url, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': payload.type },
|
||||
body,
|
||||
})
|
||||
if (!response.ok) {
|
||||
const hint =
|
||||
response.status === 409
|
||||
? ' (409: 같은 경로에 다른 내용이 이미 있음 — 게시된 버전을 덮어쓰지 않습니다)'
|
||||
: response.status === 413
|
||||
? ' (413: Cloudflare 업로드 한도 초과 — 런타임 분리 확인)'
|
||||
: ''
|
||||
console.error(
|
||||
`[updater] 업로드 실패 (HTTP ${response.status}): ${target}/${payload.name}${hint}`,
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`[updater] uploaded ${target}/${payload.name}`)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
[
|
||||
'',
|
||||
`[updater] 게시 완료: ${version}`,
|
||||
` 피드 : ${FEED}/latest`,
|
||||
` 메타 : ${FEED}/latest/latest.yml`,
|
||||
' 기존 설치본(canonical feed 사용)은 다음 업데이트 확인 때 이 버전을 받습니다.',
|
||||
' legacy GitLab mirror를 보는 1.0.x 이하 설치는 1회 수동 설치가 필요합니다.',
|
||||
].join('\n'),
|
||||
)
|
||||
283
scripts/ci/release-desktop.mjs
Normal file
283
scripts/ci/release-desktop.mjs
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
// scripts/ci/release-desktop.mjs
|
||||
// 데스크톱 릴리스 한 줄 명령 — 버전 올리기부터 기존 사용자 자동 업데이트까지.
|
||||
//
|
||||
// npm run release -- patch # 1.9.0 → 1.9.1 (fix)
|
||||
// npm run release -- minor # 1.9.0 → 1.10.0 (feat)
|
||||
// npm run release -- 2.0.0 # 직접 지정
|
||||
// npm run release -- minor --dry-run # 무엇을 할지만 출력
|
||||
// npm run release -- --resume # 빌드/게시/푸시 중 실패했을 때 같은 버전으로 이어서
|
||||
//
|
||||
// 단계 (실패하면 거기서 멈추고, --resume 으로 이어 간다):
|
||||
// 1. 점검 main 브랜치 · 깨끗한 작업 트리 · Forgejo 토큰 · 서명 키 짝 · 태그 미사용
|
||||
// 2. 버전 product-version.json + sync-version --write + CHANGELOG 섹션(없으면 커밋 제목으로 초안)
|
||||
// 3. 게이트 typecheck · version:check · release:metadata
|
||||
// 4. 커밋 + annotated 태그 (로컬만 — 게시가 끝나야 푸시한다)
|
||||
// 5. 빌드 build-desktop-installer.mjs
|
||||
// 6. 게시 publish-forgejo-release.mjs (latest.yml Ed25519 서명 · 불변 버전 경로 · latest 피드 · 공개 URL 재검증)
|
||||
// 7. 푸시 chanpaca main + 태그 (origin 미러는 실패해도 경고만)
|
||||
//
|
||||
// 태그는 불변이다. 게시된 버전에 문제가 있으면 더 높은 patch 로 다시 낸다.
|
||||
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { loadSigningKey, publicPemOf } from './lib/update-manifest-signature.mjs'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
|
||||
const args = process.argv.slice(2)
|
||||
const dryRun = args.includes('--dry-run')
|
||||
const resume = args.includes('--resume')
|
||||
const bumpArg = args.find((arg) => !arg.startsWith('--'))
|
||||
const CANONICAL_REMOTE = 'chanpaca'
|
||||
const MIRROR_REMOTES = ['origin']
|
||||
const FEED = 'https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice'
|
||||
|
||||
const versionPath = join(root, 'release', 'product-version.json')
|
||||
const changelogPath = join(root, 'CHANGELOG.md')
|
||||
|
||||
if (!resume && !bumpArg) {
|
||||
fail('사용법: npm run release -- <patch|minor|major|X.Y.Z> [--dry-run] 또는 npm run release -- --resume')
|
||||
}
|
||||
|
||||
// ── 1. 점검 ──
|
||||
step('점검')
|
||||
const branch = git(['rev-parse', '--abbrev-ref', 'HEAD'])
|
||||
if (branch !== 'main') fail(`main 브랜치에서만 릴리스합니다 (현재 ${branch}).`)
|
||||
if (!process.env.FORGEJO_TOKEN && !(process.env.FORGEJO_USERNAME && process.env.FORGEJO_PASSWORD)) {
|
||||
fail('FORGEJO_TOKEN 이 없습니다 — 루트 .env 를 확인하세요.')
|
||||
}
|
||||
const repoPublicKey = readFileSync(join(root, 'release', 'desktop-update-public.pem'), 'utf8')
|
||||
if (publicPemOf(loadSigningKey()).trim() !== repoPublicKey.trim()) {
|
||||
fail('D3RO_UPDATE_SIGNING_KEY 가 release/desktop-update-public.pem 과 짝이 아닙니다.')
|
||||
}
|
||||
const dirty = git(['status', '--porcelain'])
|
||||
if (dirty && !dryRun) fail(`작업 트리가 깨끗하지 않습니다 — 먼저 커밋하세요:\n${dirty}`)
|
||||
|
||||
const current = readJson(versionPath)
|
||||
let version = current.version
|
||||
|
||||
if (resume) {
|
||||
const tag = `v${version}`
|
||||
if (!git(['tag', '--list', tag])) fail(`${tag} 태그가 없습니다 — 이어 갈 릴리스가 없습니다.`)
|
||||
if (git(['rev-parse', `${tag}^{commit}`]) !== git(['rev-parse', 'HEAD'])) {
|
||||
fail(`HEAD 가 ${tag} 가 아닙니다 — 태그 이후 커밋이 있으면 새 버전으로 릴리스하세요.`)
|
||||
}
|
||||
info(`${tag} 이어서 진행 (빌드 → 게시 → 푸시)`)
|
||||
} else {
|
||||
version = nextVersion(current.version, bumpArg)
|
||||
const tag = `v${version}`
|
||||
if (git(['tag', '--list', tag])) fail(`${tag} 태그가 이미 있습니다. 실패한 릴리스를 이어 가려면 --resume.`)
|
||||
if (spawnGit(['ls-remote', '--exit-code', '--tags', CANONICAL_REMOTE, tag]).status === 0) {
|
||||
fail(`${CANONICAL_REMOTE} 에 ${tag} 가 이미 있습니다.`)
|
||||
}
|
||||
if (await feedHasVersion(version)) fail(`피드에 ${version} 가 이미 게시돼 있습니다.`)
|
||||
|
||||
// ── 2. 버전 ──
|
||||
step(`버전 ${current.version} → ${version}`)
|
||||
const changelog = readFileSync(changelogPath, 'utf8')
|
||||
const releaseDate = todayKst()
|
||||
const notes = changelog.includes(`## [${version}] - `) ? null : draftNotes(current.version)
|
||||
if (dryRun) {
|
||||
info(notes ? `CHANGELOG 초안:\n${notes}` : 'CHANGELOG 섹션 있음')
|
||||
info('단계: 커밋·태그 → 빌드 → 게시(서명) → 공개 URL 검증 → 푸시')
|
||||
info('dry-run — 아무것도 바꾸지 않았습니다.')
|
||||
process.exit(0)
|
||||
}
|
||||
writeFileSync(
|
||||
versionPath,
|
||||
`${JSON.stringify({ ...current, version, ...mobileBuildNumbers(version), releaseDate }, null, 2)}\n`,
|
||||
)
|
||||
if (notes) {
|
||||
insertChangelogSection(version, releaseDate, notes)
|
||||
} else {
|
||||
// 손으로 쓴 섹션의 날짜만 오늘로 맞춘다.
|
||||
writeFileSync(
|
||||
changelogPath,
|
||||
changelog.replace(new RegExp(`## \\[${escapeRegExp(version)}\\] - \\d{4}-\\d{2}-\\d{2}`), `## [${version}] - ${releaseDate}`),
|
||||
)
|
||||
}
|
||||
ensurePlayChangelogs(mobileBuildNumbers(version).androidVersionCode)
|
||||
runNode('scripts/ci/sync-version.mjs', ['--write'])
|
||||
|
||||
// ── 3. 게이트 ──
|
||||
step('게이트')
|
||||
runNpm(['run', 'version:check'])
|
||||
runNpm(['run', 'release:metadata'])
|
||||
runNpm(['run', 'typecheck'])
|
||||
// 여기까지 실패하면 버전 파일만 바뀐 상태다 — git checkout -- . 로 되돌리고 다시 실행.
|
||||
|
||||
// ── 4. 커밋 + 태그 ──
|
||||
step(`커밋 + 태그 ${tag}`)
|
||||
gitInherit(['add', '-u'])
|
||||
gitInherit(['commit', '-m', `chore(release): ${tag}`])
|
||||
runNode('scripts/ci/create-release-tag.mjs', [])
|
||||
}
|
||||
|
||||
const tag = `v${version}`
|
||||
|
||||
// 태그가 생긴 뒤의 실패는 --resume 으로 이어 간다.
|
||||
const resumeHint = '\n고친 뒤 이어 가기: npm run release -- --resume'
|
||||
|
||||
// 이미 게시가 끝난 버전을 다시 빌드하면 바이트가 달라 불변 경로와 충돌한다 — 푸시만 남은 경우다.
|
||||
if (resume && (await feedHasVersion(version))) {
|
||||
info(`피드에 ${version} 가 이미 있습니다 — 빌드·게시를 건너뜁니다.`)
|
||||
} else {
|
||||
// ── 5. 빌드 ──
|
||||
step('빌드')
|
||||
runNode('scripts/ci/build-desktop-installer.mjs', [], {}, resumeHint)
|
||||
|
||||
// ── 6. 게시 ──
|
||||
step('게시')
|
||||
runNode('scripts/ci/publish-forgejo-release.mjs', [], { FORGEJO_RELEASE_TAG: tag }, resumeHint)
|
||||
}
|
||||
|
||||
// ── 7. 푸시 ──
|
||||
step('푸시')
|
||||
// 게시는 끝났다 — 푸시 실패는 사용자 업데이트에 영향이 없고, 손으로 다시 밀면 된다.
|
||||
const pushed = spawnSync('git', ['push', CANONICAL_REMOTE, 'main', tag], { cwd: root, stdio: 'inherit' })
|
||||
if (pushed.status !== 0) warn(`${CANONICAL_REMOTE} 푸시 실패 — git push ${CANONICAL_REMOTE} main ${tag}`)
|
||||
for (const remote of MIRROR_REMOTES) {
|
||||
const result = spawnSync('git', ['push', remote, 'main', tag], { cwd: root, stdio: 'inherit' })
|
||||
if (result.status !== 0) warn(`${remote} 미러 푸시 실패 — 나중에 git push ${remote} main ${tag}`)
|
||||
}
|
||||
|
||||
step('완료')
|
||||
info(`${tag} 게시 완료. 기존 설치본은 다음 업데이트 확인(시작 15초 뒤, 이후 4시간마다)에 받습니다.`)
|
||||
info(`피드: ${FEED}/latest/latest.yml`)
|
||||
|
||||
// ── helpers ──
|
||||
|
||||
function nextVersion(from, bump) {
|
||||
const [major, minor, patch] = from.split('.').map(Number)
|
||||
if (bump === 'patch') return `${major}.${minor}.${patch + 1}`
|
||||
if (bump === 'minor') return `${major}.${minor + 1}.0`
|
||||
if (bump === 'major') return `${major + 1}.0.0`
|
||||
if (/^\d+\.\d+\.\d+$/.test(bump)) {
|
||||
const [a, b, c] = bump.split('.').map(Number)
|
||||
if (a * 1e8 + b * 1e4 + c <= major * 1e8 + minor * 1e4 + patch) fail(`${bump} 는 ${from} 보다 높아야 합니다.`)
|
||||
return bump
|
||||
}
|
||||
fail(`알 수 없는 버전 지정: ${bump} (patch|minor|major|X.Y.Z)`)
|
||||
}
|
||||
|
||||
/** 1.9.0 → 1090000 (기존 규칙: major*1e6 + minor*1e4 + patch*1e2) */
|
||||
function mobileBuildNumbers(next) {
|
||||
const [major, minor, patch] = next.split('.').map(Number)
|
||||
const code = major * 1_000_000 + minor * 10_000 + patch * 100
|
||||
return { androidVersionCode: code, iosBuildNumber: code }
|
||||
}
|
||||
|
||||
function draftNotes(previous) {
|
||||
const subjects = git(['log', '--no-merges', '--format=%s', `v${previous}..HEAD`]).split('\n').filter(Boolean)
|
||||
const groups = { Added: [], Fixed: [], Changed: [] }
|
||||
for (const subject of subjects) {
|
||||
const match = subject.match(/^(\w+)(?:\([^)]*\))?!?:\s*(.+)$/)
|
||||
const type = match?.[1]
|
||||
const text = match?.[2] ?? subject
|
||||
if (type === 'feat') groups.Added.push(text)
|
||||
else if (type === 'fix') groups.Fixed.push(text)
|
||||
else if (type === 'perf' || type === 'refactor') groups.Changed.push(text)
|
||||
}
|
||||
const body = Object.entries(groups)
|
||||
.filter(([, items]) => items.length > 0)
|
||||
.map(([heading, items]) => `### ${heading}\n${items.map((item) => `- ${item}`).join('\n')}`)
|
||||
.join('\n\n')
|
||||
return body || '### Changed\n- Maintenance release.'
|
||||
}
|
||||
|
||||
function insertChangelogSection(next, date, notes) {
|
||||
const text = readFileSync(changelogPath, 'utf8')
|
||||
const anchor = text.search(/\n## \[\d+\.\d+\.\d+\]/)
|
||||
const section =
|
||||
`\n## [${next}] - ${date}\n\n` +
|
||||
'> Published from an annotated tag. Installer and update metadata are served by the\n' +
|
||||
'> canonical Forgejo feed; no binaries are committed to this repository.\n\n' +
|
||||
`${notes}\n`
|
||||
writeFileSync(changelogPath, anchor === -1 ? `${text.trimEnd()}\n${section}` : `${text.slice(0, anchor)}\n${section}${text.slice(anchor)}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 모바일과 버전을 같이 쓰므로 release:metadata 가 새 versionCode 의 Play '새 기능' 문구를 요구한다.
|
||||
* 데스크톱만 내는 릴리스면 일반 문구로 채운다 — 모바일을 실제로 낼 때 고쳐 쓴다.
|
||||
*/
|
||||
function ensurePlayChangelogs(versionCode) {
|
||||
const texts = {
|
||||
'ko-KR': '안정성과 성능을 개선했습니다.',
|
||||
'en-US': 'Stability and performance improvements.',
|
||||
}
|
||||
for (const [locale, text] of Object.entries(texts)) {
|
||||
const path = join(root, 'apps', 'mobile-rn', 'metadata', 'android', locale, 'changelogs', `${versionCode}.txt`)
|
||||
if (!existsSync(path)) {
|
||||
writeFileSync(path, `${text}\n`)
|
||||
gitInherit(['add', path])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function feedHasVersion(next) {
|
||||
const response = await fetch(`${FEED}/${next}/latest.yml`, { cache: 'no-store' }).catch(() => null)
|
||||
return Boolean(response?.ok)
|
||||
}
|
||||
|
||||
function todayKst() {
|
||||
return new Date(Date.now() + 9 * 3600_000).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function escapeRegExp(value) {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
return JSON.parse(readFileSync(path, 'utf8'))
|
||||
}
|
||||
|
||||
function spawnGit(commandArgs) {
|
||||
return spawnSync('git', commandArgs, { cwd: root, encoding: 'utf8' })
|
||||
}
|
||||
|
||||
function git(commandArgs) {
|
||||
const result = spawnGit(commandArgs)
|
||||
if (result.status !== 0 && !(commandArgs[0] === 'tag' && commandArgs[1] === '--list')) {
|
||||
fail(`git ${commandArgs.join(' ')} 실패: ${result.stderr?.trim() || `exit ${result.status}`}`)
|
||||
}
|
||||
return (result.stdout ?? '').trim()
|
||||
}
|
||||
|
||||
function gitInherit(commandArgs) {
|
||||
const result = spawnSync('git', commandArgs, { cwd: root, stdio: 'inherit' })
|
||||
if (result.status !== 0) fail(`git ${commandArgs.join(' ')} 실패 (exit ${result.status ?? 'null'})`)
|
||||
}
|
||||
|
||||
function runNpm(commandArgs) {
|
||||
info(`$ npm ${commandArgs.join(' ')}`)
|
||||
const result = spawnSync('npm', commandArgs, { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' })
|
||||
if (result.status !== 0) fail(`npm ${commandArgs.join(' ')} 실패 (exit ${result.status ?? 'null'})`)
|
||||
}
|
||||
|
||||
function runNode(relativePath, scriptArgs, env = {}, hint = '') {
|
||||
info(`$ node ${relativePath} ${scriptArgs.join(' ')}`)
|
||||
const result = spawnSync(process.execPath, [join(root, relativePath), ...scriptArgs], {
|
||||
cwd: root,
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, ...env },
|
||||
})
|
||||
if (result.status !== 0) fail(`${relativePath} 실패 (exit ${result.status ?? 'null'})${hint}`)
|
||||
}
|
||||
|
||||
function step(name) {
|
||||
process.stdout.write(`\n[release] ── ${name} ──\n`)
|
||||
}
|
||||
|
||||
function info(message) {
|
||||
process.stdout.write(`[release] ${message}\n`)
|
||||
}
|
||||
|
||||
function warn(message) {
|
||||
process.stdout.write(`[release] 경고: ${message}\n`)
|
||||
}
|
||||
|
||||
function fail(message) {
|
||||
process.stderr.write(`[release] ${message}\n`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
|
@ -30,7 +30,7 @@ const SECRETS = [
|
|||
{ name: 'FORGEJO_TOKEN', envKey: 'FORGEJO_TOKEN', required: true, usedBy: 'release.yml, portable.yml' },
|
||||
{ name: 'WIN_CSC_LINK', envKey: 'WIN_CSC_LINK', required: false, usedBy: 'release.yml' },
|
||||
{ name: 'WIN_CSC_KEY_PASSWORD', envKey: 'WIN_CSC_KEY_PASSWORD', required: false, usedBy: 'release.yml' },
|
||||
{ name: 'WIN_CSC_EXPECTED_SIGNER_SUBJECT', envKey: 'WIN_CSC_EXPECTED_SIGNER_SUBJECT', required: false, usedBy: 'release.yml' },
|
||||
{ name: 'D3RO_UPDATE_SIGNING_KEY', envKey: 'D3RO_UPDATE_SIGNING_KEY', required: true, usedBy: 'release.yml' },
|
||||
]
|
||||
|
||||
const LOCAL_HOST = /^(https?:\/\/)?(localhost|127\.|0\.0\.0\.0|\[::1\]|host\.docker\.internal)/i
|
||||
|
|
|
|||
46
scripts/ci/setup-nas-cron-runner.sh
Normal file
46
scripts/ci/setup-nas-cron-runner.sh
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
#!/usr/bin/env bash
|
||||
# scripts/ci/setup-nas-cron-runner.sh
|
||||
# NAS 에 d3ro-voice 저장소 전용 Forgejo 러너(라벨 `nas`)를 띄운다.
|
||||
#
|
||||
# 왜: linux-builder 러너는 노트북 한 대뿐이라 노트북이 꺼지면 payple-renew 크론도
|
||||
# 멈춘다(GAP-CI-02). 상시 켜진 NAS 에서 크론을 돌린다. 기존 NAS 러너
|
||||
# (forgejo-runner, 다른 저장소 전용)는 건드리지 않는다.
|
||||
#
|
||||
# 사용 (루트에서): bash scripts/ci/setup-nas-cron-runner.sh
|
||||
# 필요: 루트 .env 의 FORGEJO_TOKEN, ssh 별칭 yunchan-nas.
|
||||
# 되돌리기: ssh yunchan-nas 'docker rm -f d3ro-nas-runner && rm -rf /volume1/docker/d3ro-nas-runner'
|
||||
# 후 Forgejo 저장소 설정 > Actions > Runners 에서 d3ro-nas 삭제.
|
||||
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
|
||||
token=$(grep '^FORGEJO_TOKEN=' .env | cut -d= -f2- | tr -d '"')
|
||||
[ -n "$token" ] || { echo "FORGEJO_TOKEN 이 .env 에 없습니다." >&2; exit 1; }
|
||||
|
||||
reg=$(curl -fsS -m 15 -H "Authorization: token $token" \
|
||||
"https://git.chanpaca.net/api/v1/repos/yunchan/d3ro-voice/actions/runners/registration-token" |
|
||||
node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>process.stdout.write(JSON.parse(s).token))')
|
||||
|
||||
# 등록 토큰은 명령줄에 남기지 않고 stdin 으로 넘긴다.
|
||||
printf '%s\n' "$reg" | ssh -o BatchMode=yes yunchan-nas '
|
||||
export PATH=$PATH:/usr/local/bin
|
||||
set -e
|
||||
read -r RT
|
||||
D=/volume1/docker/d3ro-nas-runner
|
||||
IMG=code.forgejo.org/forgejo/runner:6
|
||||
# 기존 forgejo-runner 와 같이 root 로 돈다. 기본 사용자(1000)는 Synology ACL 에 막혀 .runner 를 못 쓴다.
|
||||
if docker ps -a --format "{{.Names}}" | grep -qx d3ro-nas-runner; then
|
||||
echo "d3ro-nas-runner 가 이미 있습니다."; docker ps --filter name=d3ro-nas-runner; exit 0
|
||||
fi
|
||||
mkdir -p "$D"
|
||||
[ -f "$D/config.yml" ] || grep -v A_TEST_ENV /volume1/docker/forgejo-runner/config.yml > "$D/config.yml"
|
||||
[ -f "$D/.runner" ] || docker run --rm -u 0:0 -v "$D:/data" -w /data "$IMG" forgejo-runner register \
|
||||
--no-interactive --config /data/config.yml --instance http://192.168.0.39:3000 \
|
||||
--token "$RT" --name d3ro-nas --labels "nas:docker://node:22-bookworm"
|
||||
docker run -d --name d3ro-nas-runner --restart unless-stopped -u 0:0 \
|
||||
-v "$D:/data" -v /var/run/docker.sock:/var/run/docker.sock -w /data -e HOME=/data \
|
||||
"$IMG" forgejo-runner daemon --config /data/config.yml >/dev/null
|
||||
sleep 6
|
||||
docker ps --filter name=d3ro-nas-runner --format "{{.Names}} {{.Status}}"
|
||||
docker logs --tail 4 d3ro-nas-runner 2>&1
|
||||
'
|
||||
|
|
@ -7,9 +7,6 @@ const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
|
|||
// canonical updater feed: Forgejo Generic Package Registry
|
||||
const CANONICAL_UPDATE_FEED =
|
||||
'https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice/latest'
|
||||
// legacy mirror: GitLab Generic Registry (pre-Forgejo installs still poll this)
|
||||
const LEGACY_UPDATE_FEED =
|
||||
'https://gitlab.twentyoz.kr:8443/api/v4/projects/1172/packages/generic/d3ro-voice/latest'
|
||||
|
||||
function read(path) {
|
||||
return readFileSync(join(root, path), 'utf8')
|
||||
|
|
@ -31,7 +28,9 @@ function loadSurfaces(readSurface = read) {
|
|||
updatePolicySource: readSurface('apps/desktop/src/main/update-policy.ts'),
|
||||
updateService: readSurface('apps/desktop/src/main/services/UpdateService.ts'),
|
||||
updateAdapters: readSurface('apps/desktop/src/main/services/update-adapters.ts'),
|
||||
publisher: readSurface('scripts/ci/publish-gitlab-release.mjs'),
|
||||
updateSignature: readSurface('apps/desktop/src/main/update-signature.ts'),
|
||||
updatePublicKey: readSurface('release/desktop-update-public.pem'),
|
||||
releaseCommand: readSurface('scripts/ci/release-desktop.mjs'),
|
||||
forgejoPublisher: readSurface('scripts/ci/publish-forgejo-release.mjs'),
|
||||
gitlab: readSurface('.gitlab-ci.yml'),
|
||||
forgejoRelease: readSurface('.forgejo/workflows/release.yml'),
|
||||
|
|
@ -128,12 +127,35 @@ function validate(surfaces) {
|
|||
|
||||
// ── canonical feed contract: runtime == builder == Forgejo canonical ──
|
||||
const sourceFeed = surfaces.updateFeed.match(/UPDATE_FEED_URL\s*=\s*\n?\s*['"]([^'"]+)['"]/)?.[1]
|
||||
const legacyFeed = surfaces.updateFeed.match(/LEGACY_UPDATE_FEED_URL\s*=\s*\n?\s*['"]([^'"]+)['"]/)?.[1]
|
||||
const builderFeed = surfaces.builder.match(/publish:\s*[\s\S]*?\n\s+url:\s*["']([^"']+)["']/)?.[1]
|
||||
fail(sourceFeed === CANONICAL_UPDATE_FEED, 'desktop_runtime_update_feed_drift')
|
||||
fail(builderFeed === CANONICAL_UPDATE_FEED, 'desktop_builder_update_feed_drift')
|
||||
fail(!/\/releases\/\d+\.\d+\.\d+/.test(sourceFeed ?? ''), 'desktop_update_feed_version_pinned')
|
||||
fail(legacyFeed === LEGACY_UPDATE_FEED, 'desktop_legacy_mirror_feed_missing')
|
||||
fail(!surfaces.updateFeed.includes('gitlab'), 'desktop_legacy_gitlab_feed_reintroduced')
|
||||
|
||||
// ── 업데이트 메타데이터 Ed25519 서명: 앱 내장 공개키 == 저장소 공개키, 앱이 실제로 검증 ──
|
||||
const embeddedKey = surfaces.updateSignature.match(/UPDATE_SIGNING_PUBLIC_KEY = `([^`]+)`/)?.[1]?.trim()
|
||||
let updateKeyValid = false
|
||||
try {
|
||||
updateKeyValid = createPublicKey(surfaces.updatePublicKey).asymmetricKeyType === 'ed25519'
|
||||
} catch {
|
||||
updateKeyValid = false
|
||||
}
|
||||
fail(updateKeyValid, 'update_signing_public_key_invalid')
|
||||
fail(embeddedKey === surfaces.updatePublicKey.trim(), 'update_signing_public_key_drift')
|
||||
fail(surfaces.updateAdapters.includes('verifyDownloadedUpdate('), 'update_signature_verification_missing')
|
||||
fail(
|
||||
surfaces.forgejoPublisher.includes('signManifest(') && surfaces.forgejoPublisher.includes('verifySignedPublicManifest()'),
|
||||
'forgejo_publisher_manifest_signing_missing',
|
||||
)
|
||||
fail(surfaces.forgejoRelease.includes('D3RO_UPDATE_SIGNING_KEY'), 'forgejo_release_signing_key_missing')
|
||||
// 로컬 한 줄 명령과 CI 예비 경로가 같은 빌드·게시 스크립트를 써야 한다
|
||||
fail(
|
||||
surfaces.releaseCommand.includes('build-desktop-installer.mjs') &&
|
||||
surfaces.releaseCommand.includes('publish-forgejo-release.mjs') &&
|
||||
surfaces.forgejoRelease.includes('build-desktop-installer.mjs'),
|
||||
'release_paths_diverged',
|
||||
)
|
||||
|
||||
// ── update policy SSOT ──
|
||||
const policy = surfaces.updatePolicy
|
||||
|
|
@ -183,12 +205,6 @@ function validate(surfaces) {
|
|||
'update_service_differential_control_missing',
|
||||
)
|
||||
|
||||
// ── legacy GitLab publisher (mirror) ──
|
||||
fail(surfaces.publisher.includes('const latestFiles = [...sortedFiles].sort'), 'publisher_asset_first_order_missing')
|
||||
fail(!surfaces.publisher.includes('deletePackagesForVersion("latest")'), 'publisher_deletes_live_feed_first')
|
||||
fail(surfaces.publisher.includes('verifyPublicLatestFile'), 'publisher_public_metadata_verification_missing')
|
||||
fail(surfaces.publisher.includes('release/product-version.json'), 'publisher_product_version_gate_missing')
|
||||
|
||||
// ── canonical Forgejo publisher contract ──
|
||||
fail(!/1\.0\.0/.test(surfaces.forgejoPublisher), 'forgejo_publisher_hardcoded_version')
|
||||
fail(surfaces.forgejoPublisher.includes('release/product-version.json'), 'forgejo_publisher_version_gate_missing')
|
||||
|
|
@ -243,7 +259,6 @@ function validate(surfaces) {
|
|||
androidVersionCode: metadata.androidVersionCode,
|
||||
iosBuildNumber: metadata.iosBuildNumber,
|
||||
updateFeed: sourceFeed,
|
||||
legacyUpdateFeed: legacyFeed,
|
||||
updateChannel: policy.defaultChannel,
|
||||
minimumSupportedVersion: policy.minimumSupportedVersion,
|
||||
electronVersion: lockedElectron,
|
||||
|
|
@ -282,9 +297,16 @@ if (process.argv.includes('--self-test')) {
|
|||
expectRejected(
|
||||
surfaces,
|
||||
(candidate) => {
|
||||
candidate.updateFeed = candidate.updateFeed.replace(LEGACY_UPDATE_FEED, 'https://example.invalid/legacy')
|
||||
candidate.updatePublicKey = candidate.desktopLicensePublicKey
|
||||
},
|
||||
'desktop_legacy_mirror_feed_missing',
|
||||
'update_signing_public_key_drift',
|
||||
)
|
||||
expectRejected(
|
||||
surfaces,
|
||||
(candidate) => {
|
||||
candidate.updateAdapters = candidate.updateAdapters.replaceAll('verifyDownloadedUpdate(', 'skipVerification(')
|
||||
},
|
||||
'update_signature_verification_missing',
|
||||
)
|
||||
expectRejected(
|
||||
surfaces,
|
||||
|
|
@ -345,9 +367,9 @@ if (process.argv.includes('--self-test')) {
|
|||
expectRejected(
|
||||
surfaces,
|
||||
(candidate) => {
|
||||
candidate.publisher = candidate.publisher.replace('const latestFiles = [...sortedFiles].sort', 'const latestFiles = sortedFiles.sort')
|
||||
candidate.forgejoPublisher = candidate.forgejoPublisher.replaceAll('signManifest(', 'noSign(')
|
||||
},
|
||||
'publisher_asset_first_order_missing',
|
||||
'forgejo_publisher_manifest_signing_missing',
|
||||
)
|
||||
expectRejected(
|
||||
surfaces,
|
||||
|
|
@ -385,7 +407,7 @@ if (process.argv.includes('--self-test')) {
|
|||
if (!missingDesktopKeyRejected) {
|
||||
throw new Error('release_metadata_self_test_failed:desktop_license_public_key_missing')
|
||||
}
|
||||
result.negativeCases = 14
|
||||
result.negativeCases = 16
|
||||
}
|
||||
|
||||
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)
|
||||
|
|
|
|||
4
site/package-lock.json
generated
4
site/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "d3ro-voice-site",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "d3ro-voice-site",
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"dependencies": {
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "d3ro-voice-site",
|
||||
"private": true,
|
||||
"version": "1.9.0",
|
||||
"version": "1.10.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --port 5199 --host",
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@
|
|||
// NAS 배포는 바이너리를 포함하지 않으므로 `/releases/...` 같은 로컬 경로는
|
||||
// 실제 배포 환경에서 404가 된다.
|
||||
|
||||
export const DESKTOP_VERSION = '1.9.0'
|
||||
export const DESKTOP_VERSION = '1.10.0'
|
||||
|
||||
/** 릴리스 게시일. `release/product-version.json`의 releaseDate와 같아야 한다. */
|
||||
export const DESKTOP_RELEASE_DATE = '2026-09-27'
|
||||
export const DESKTOP_RELEASE_DATE = '2026-10-18'
|
||||
|
||||
const FORGEJO_ORIGIN = 'https://git.chanpaca.net'
|
||||
const FORGEJO_OWNER = 'yunchan'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue