fix(release): restore automatic updates by shipping the speech engine on demand
Some checks failed
deploy-site / deploy (push) Failing after 1m15s

Auto-update could not work at all: the installer was 189 MB because it carried
the local speech engine and ffmpeg, and the download feed rejects uploads over
about 100 MiB, so update metadata could never be published.

The installer now leaves those components out and the app fetches them the first
time they are needed, verifying every part and the joined archive before
installing. The installer is 90.6 MiB, the update feed is published again, and
updates stay small because the engine is not re-sent on every release.

The fetch is visible and recoverable: the download runs with progress, a failed
install cleans up after itself, and Settings > STT shows the runtime status with
a manual download action for when the automatic one cannot run.
This commit is contained in:
Yun Chan 2026-09-18 13:51:49 +09:00
parent 0411f389d9
commit 0fbbbc1756
42 changed files with 1137 additions and 123 deletions

View file

@ -25,12 +25,17 @@ import {
existsSync,
readFileSync,
readdirSync,
mkdirSync,
renameSync,
rmSync,
statSync,
writeFileSync,
} from 'node:fs'
import { createRequire } from 'node:module'
import { createGzip } from 'node:zlib'
import { pipeline } from 'node:stream/promises'
import { createReadStream, createWriteStream } from 'node:fs'
import * as tar from 'tar'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
@ -306,6 +311,90 @@ writeFileSync(
`${JSON.stringify(indexJson, null, 2)}\n`,
'utf8',
)
// ── 로컬 AI 런타임 번들 (설치본에 넣지 않고 처음 필요할 때 내려받는다) ──────
const RUNTIME_DIR = join(releaseDir, 'runtime')
rmSync(RUNTIME_DIR, { recursive: true, force: true })
mkdirSync(RUNTIME_DIR, { recursive: true })
/** 디렉터리를 tar.gz으로 묶어 90MiB 부품으로 나누고 인덱스 항목을 돌려준다 */
async function packRuntime(component, sourceDir, archiveBase) {
const archivePath = join(RUNTIME_DIR, `${archiveBase}.tar.gz`)
await pipeline(
tar.c({ cwd: sourceDir, portable: true, gzip: false }, ['.']),
createGzip({ level: 6 }),
createWriteStream(archivePath),
)
const archiveBytes = readFileSync(archivePath)
const sha256 = createHash('sha256').update(archiveBytes).digest('hex')
const partSize = 90 * 1024 * 1024
const parts = []
for (let offset = 0, index = 1; offset < archiveBytes.length; offset += partSize, index += 1) {
const slice = archiveBytes.subarray(offset, Math.min(offset + partSize, archiveBytes.length))
const name = `${archiveBase}.tar.gz.${String(index).padStart(3, '0')}`
if (slice.length > MAX_ZIP_PART_BYTES) {
throw new Error(`런타임 부품이 너무 큽니다: ${name}`)
}
writeFileSync(join(RUNTIME_DIR, name), slice)
parts.push({
name,
size: slice.length,
sha256: createHash('sha256').update(slice).digest('hex'),
})
}
return {
component,
archive: `${archiveBase}.tar.gz`,
sha256,
totalSize: archiveBytes.length,
parts,
}
}
const runtimeComponents = {}
const sidecarSource = join(desktopDir, 'sidecar-dist', 'sidecar')
// @ffmpeg-installer가 플랫폼별로 제공하는 실행 파일 경로를 그대로 사용한다
const ffmpegInstaller = (() => {
try {
return require('@ffmpeg-installer/ffmpeg')
} catch {
return null
}
})()
const ffmpegSource = ffmpegInstaller?.path ? dirname(ffmpegInstaller.path) : null
if (existsSync(sidecarSource)) {
console.log('[portable] 런타임 번들 생성: sidecar (faster-whisper 진)')
runtimeComponents.sidecar = await packRuntime('sidecar', sidecarSource, 'd3ro-runtime-sidecar')
} else {
console.error('[portable] 경고: sidecar-dist가 없어 런타임 번들을 만들 수 없습니다')
}
if (ffmpegSource && existsSync(ffmpegSource)) {
console.log('[portable] 런타임 번들 생성: ffmpeg')
runtimeComponents.ffmpeg = await packRuntime('ffmpeg', ffmpegSource, 'd3ro-runtime-ffmpeg')
} else {
console.error('[portable] 경고: @ffmpeg-installer가 없어 ffmpeg 런타임을 만들 수 없습니다')
}
const runtimeIndex = {
schemaVersion: 1,
version,
generatedAt: new Date().toISOString(),
components: Object.fromEntries(
Object.entries(runtimeComponents).map(([name, entry]) => [
name,
{
...entry,
parts: entry.parts.map((part) => ({
...part,
url: `${FEED}/runtime-${version}/${part.name}`,
})),
},
]),
),
}
writeFileSync(join(RUNTIME_DIR, 'runtime.json'), `${JSON.stringify(runtimeIndex, null, 2)}\n`, 'utf8')
console.log(
[
'[portable] 완료',
@ -316,6 +405,7 @@ console.log(
` zip : ${zipParts.length}개 부품 / 합계 ${(zipBytes.length / 1048576).toFixed(1)}MiB`,
` 인덱스 : ${join(releaseDir, 'portable.json')}`,
` scoop : ${join(root, 'bucket', 'd3ro-voice.json')}`,
` 런타임 : ${Object.keys(runtimeComponents).join(', ') || '(없음)'}${join(RUNTIME_DIR, 'runtime.json')}`,
` 게시 : node scripts/ci/publish-portable-release.mjs`,
].join('\n'),
)

View file

@ -93,6 +93,36 @@ payloads.push({
contentType: 'text/plain',
})
// ── 로컬 AI 런타임 번들 게시 (설치본에는 없고, 앱이 처음 필요할 때 내려받는다) ──
const runtimeDir = join(releaseDir, 'runtime')
const runtimePayloads = []
const runtimeIndexPath = join(runtimeDir, 'runtime.json')
if (existsSync(runtimeIndexPath)) {
const runtimeIndex = JSON.parse(readFileSync(runtimeIndexPath, 'utf8'))
for (const [component, entry] of Object.entries(runtimeIndex.components ?? {})) {
for (const part of entry.parts) {
const partPath = join(runtimeDir, part.name)
if (!existsSync(partPath)) {
console.error(`[portable] 런타임 부품이 없습니다: ${partPath}`)
process.exit(1)
}
const bytes = await readFile(partPath)
const sha = createHash('sha256').update(bytes).digest('hex')
if (sha !== part.sha256) {
console.error(`[portable] 런타임 부품 sha256 불일치: ${part.name}`)
process.exit(1)
}
runtimePayloads.push({ name: part.name, bytes, contentType: 'application/octet-stream' })
}
void component
}
runtimePayloads.push({
name: 'runtime.json',
bytes: Buffer.from(`${JSON.stringify(runtimeIndex, null, 2)}\n`, 'utf8'),
contentType: 'application/json',
})
}
const authorization = forgejoAuthorization()
const bases = [`${FEED}/portable-${version}`, `${FEED}/portable-latest`]
@ -142,6 +172,13 @@ async function upload(url, body, contentType) {
console.log(`[portable] uploaded ${url}`)
}
const runtimeBases = [`${FEED}/runtime-${version}`, `${FEED}/runtime-latest`]
for (const base of runtimeBases) {
for (const payload of runtimePayloads) {
await upload(`${base}/${encodeURIComponent(payload.name)}`, payload.bytes, payload.contentType)
}
}
for (const base of bases) {
for (const payload of payloads) {
await upload(`${base}/${encodeURIComponent(payload.name)}`, payload.bytes, payload.contentType)
@ -155,6 +192,9 @@ console.log(
` 볼륨 : ${index.volumeCount}개 / 합계 ${(index.totalSize / 1048576).toFixed(1)}MiB`,
` 인덱스 : ${FEED}/portable-latest/portable.json`,
` 스크립트: ${FEED}/portable-latest/install-d3ro-voice.ps1`,
runtimePayloads.length
? ` 런타임 : ${FEED}/runtime-latest/runtime.json (${runtimePayloads.length}개 파일)`
: ' 런타임 : (없음)',
'',
' 설치(Scoop, 권장):',
' scoop bucket add d3ro https://git.chanpaca.net/yunchan/d3ro-voice.git',

View file

@ -0,0 +1,213 @@
// 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'
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) {
console.log('[updater] electron-builder NSIS 빌드 ( 전용 — 런타임 제외)')
const result = spawnSync(
'npx',
[
'electron-builder',
'--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 (result.status !== 0) {
console.error(`[updater] 빌드 실패 (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')
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)
}
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`]
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()
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는 같은 경로에 다른 바이트가 있으면 409를 돌려준다.
// 메타데이터(latest.yml / update-policy.json)는 최신을 가리켜야 하므로 먼저 지운다.
// (설치본/블록맵은 파일명에 버전이 있어 충돌하지 않는다.)
const existing = await forgejoFetch(url, { headers: { Range: 'bytes=0-0' } }).catch(
() => null,
)
if (existing?.ok) {
const contentRange = existing.headers.get('content-range')
const remoteSize = contentRange ? Number(contentRange.split('/')[1]) : NaN
if (remoteSize === body.length) {
console.log(`[updater] 이미 동일한 파일이 있습니다(건너뜀): ${url}`)
continue
}
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'),
)