Skip to content

Doubao-powered voice input for Linux, Wayland and Omarchy

fix(macos): improve dictation, onboarding and preview signing (#87)

Leyangab9faf99771b
diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml
index db8f1a3..271227a 100644
--- a/.github/workflows/macos.yml
+++ b/.github/workflows/macos.yml
@@ -27,15 +27,61 @@ jobs:
run: bash macos/Tests/Settings/build-sidebar-focus.sh
- name: Build opt-in personal learning UI probe
run: bash macos/Tests/Settings/build-personal-ui.sh
- - name: Archive preview (development signing only)
+ - name: Explain preview availability
+ run: |
+ echo 'PR builds publish test probes only. Installable previews are Developer ID signed and notarized by the protected-main preview job. Missing signing credentials fail that job instead of producing an ad-hoc application.' >> "$GITHUB_STEP_SUMMARY"
+ - name: Archive opt-in test probes
run: |
- ditto -c -k --sequesterRsrc --keepParent "build/macos/$(uname -m)/Doubao Say.app" build/Doubao-Say-macos-preview.zip
ditto -c -k build/macos/tests/sidebar-focus-check build/Sidebar-Focus-Check.zip
ditto -c -k build/macos/tests/personal-ui-check build/Personal-Learning-Check.zip
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
- name: Doubao-Say-macos-development-preview
+ name: Doubao-Say-macos-test-probes
path: |
- build/Doubao-Say-macos-preview.zip
build/Sidebar-Focus-Check.zip
build/Personal-Learning-Check.zip
+
+ preview:
+ # Signing credentials never reach pull-request code or a dispatch on another branch.
+ if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
+ needs: build
+ runs-on: macos-latest
+ environment: macos-preview
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.12'
+ - name: Import preview signing credentials
+ env:
+ MACOS_CERTIFICATE_P12_BASE64: ${{ secrets.MACOS_CERTIFICATE_P12_BASE64 }}
+ MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
+ MACOS_NOTARY_KEY_P8_BASE64: ${{ secrets.MACOS_NOTARY_KEY_P8_BASE64 }}
+ MACOS_NOTARY_KEY_ID: ${{ secrets.MACOS_NOTARY_KEY_ID }}
+ MACOS_NOTARY_ISSUER_ID: ${{ secrets.MACOS_NOTARY_ISSUER_ID }}
+ MACOS_SIGNING_TEAM_ID: ${{ vars.MACOS_SIGNING_TEAM_ID }}
+ run: bash macos/Packaging/prepare-preview-signing.sh
+ - name: Build signed preview
+ run: bash macos/build.sh
+ - name: Notarize and package preview
+ run: |
+ python3 macos/package-dmg.py --identity "$DOUBAO_CODESIGN_IDENTITY" \
+ --key "$DOUBAO_NOTARY_KEY_PATH" --key-id "$DOUBAO_NOTARY_KEY_ID" \
+ --issuer "$DOUBAO_NOTARY_ISSUER_ID"
+ python3 macos/Packaging/preview-manifest.py
+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: Doubao-Say-macos-signed-preview
+ if-no-files-found: error
+ path: |
+ build/macos/*.dmg
+ build/macos/*.dmg.sha256
+ build/macos/preview-manifest.json
+ - name: Remove preview signing credentials
+ if: always()
+ run: |
+ security delete-keychain "$RUNNER_TEMP/doubao-preview-signing.keychain-db" 2>/dev/null || true
+ rm -f "$RUNNER_TEMP/doubao-preview-certificate.p12" "$RUNNER_TEMP/doubao-preview-notary.p8"
diff --git a/macos/Package.swift b/macos/Package.swift
index d38a473..eafa8f6 100644
--- a/macos/Package.swift
+++ b/macos/Package.swift
@@ -2,5 +2,5 @@
import PackageDescription
let package = Package(name: "DoubaoSayCore", platforms: [.macOS(.v13)], targets: [
.target(name: "DoubaoSayCore", path: "Sources", exclude: ["ApplicationPresence.swift", "APIASRClient.swift", "ASRParamsStore.swift", "AppState.swift", "AudioCaptureManager.swift", "AudioDevices.swift", "DoubaoASRClient.swift", "DoubaoSayApp.swift", "HotkeyManager.swift", "OverlayPanel.swift", "OverlayView.swift", "ListeningWaveform.swift", "PasteHelper.swift", "InputTargetCapture.swift", "SecretStore.swift", "SettingsWindow.swift", "SettingsModel.swift", "ChatGPTSettings.swift", "DropdownControl.swift", "PolishingSettingsView.swift", "StartupService.swift", "TranscriptionManager.swift", "UpdateInstaller.swift", "VibekeyReceiver.swift", "WebViewManager.swift", "WindowCapture.swift", "PersonalViews.swift", "SpeechEvaluationView.swift", "SpeechEvaluationModel.swift"], sources: ["InputLatency.swift", "SpeechEvaluation.swift", "VoiceMotion.swift", "HotkeyGesture.swift", "ASRResponse.swift", "FinalResultGate.swift", "ShortcutGesture.swift", "MacSettings.swift", "Strings.swift", "PolishDefaults.swift", "PolishClient.swift", "ChatGPTVault.swift", "ChatGPTProtocol.swift", "ChatGPTOAuth.swift", "ChatGPTCallback.swift", "ChatGPTService.swift", "ChatGPTResponses.swift", "PolishCoordinator.swift", "SeedProtocol.swift", "VibekeyProtocol.swift", "UpdateRelease.swift", "UpdateChecker.swift", "PersonalData.swift", "PersonalCorrections.swift"]),
- .testTarget(name: "DoubaoSayCoreTests", dependencies: ["DoubaoSayCore"], path: "Tests", exclude: ["Transport", "Live", "Network", "Settings", "Input"])
+ .testTarget(name: "DoubaoSayCoreTests", dependencies: ["DoubaoSayCore"], path: "Tests", exclude: ["Transport", "Live", "Network", "Settings", "Input", "Packaging"])
])
diff --git a/macos/Packaging/prepare-preview-signing.sh b/macos/Packaging/prepare-preview-signing.sh
new file mode 100644
index 0000000..f4268c9
--- /dev/null
+++ b/macos/Packaging/prepare-preview-signing.sh
@@ -0,0 +1,53 @@
+#!/bin/bash
+set -euo pipefail
+# This script runs only in the protected-main signing job, never in PR jobs.
+python3 - <<'PYTHON'
+import base64
+import os
+from pathlib import Path
+
+required = ["MACOS_CERTIFICATE_P12_BASE64", "MACOS_CERTIFICATE_PASSWORD",
+ "MACOS_NOTARY_KEY_P8_BASE64", "MACOS_NOTARY_KEY_ID",
+ "MACOS_NOTARY_ISSUER_ID", "MACOS_SIGNING_TEAM_ID"]
+missing = [name for name in required if not os.environ.get(name)]
+if missing:
+ raise SystemExit("Signed preview requires environment configuration: " + ", ".join(missing))
+for name in ["MACOS_NOTARY_KEY_ID", "MACOS_NOTARY_ISSUER_ID", "MACOS_SIGNING_TEAM_ID"]:
+ value = os.environ[name]
+ if not value.isascii() or not all(c.isalnum() or c == "-" for c in value):
+ raise SystemExit("Invalid signing metadata: " + name)
+for name, filename in [("MACOS_CERTIFICATE_P12_BASE64", "doubao-preview-certificate.p12"),
+ ("MACOS_NOTARY_KEY_P8_BASE64", "doubao-preview-notary.p8")]:
+ try:
+ data = base64.b64decode(os.environ[name], validate=True)
+ except ValueError:
+ raise SystemExit("Invalid base64 signing credential: " + name) from None
+ if not data:
+ raise SystemExit("Empty signing credential: " + name)
+ path = Path(os.environ["RUNNER_TEMP"]) / filename
+ with open(path, "wb", opener=lambda p, flags: os.open(p, flags, 0o600)) as stream:
+ os.chmod(path, 0o600)
+ stream.write(data)
+PYTHON
+keychain="$RUNNER_TEMP/doubao-preview-signing.keychain-db"
+password=$(python3 -c 'import secrets; print(secrets.token_hex(32))')
+security create-keychain -p "$password" "$keychain"
+security set-keychain-settings -lut 21600 "$keychain"
+security unlock-keychain -p "$password" "$keychain"
+security import "$RUNNER_TEMP/doubao-preview-certificate.p12" -k "$keychain" \
+ -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign >/dev/null
+security set-key-partition-list -S apple-tool:,apple: -s -k "$password" "$keychain" >/dev/null
+security list-keychains -d user -s "$keychain" "$HOME/Library/Keychains/login.keychain-db"
+identity=$(security find-identity -v -p codesigning "$keychain" | \
+ sed -n 's/.*) \([0-9A-F]\{40\}\) "Developer ID Application:.*$/\1/p')
+if [[ ! "$identity" =~ ^[0-9A-F]{40}$ ]]; then
+ echo 'Expected exactly one valid Developer ID Application identity in the preview keychain.' >&2
+ exit 1
+fi
+{
+ echo "DOUBAO_CODESIGN_IDENTITY=$identity"
+ echo "DOUBAO_NOTARY_KEY_PATH=$RUNNER_TEMP/doubao-preview-notary.p8"
+ echo "DOUBAO_NOTARY_KEY_ID=$MACOS_NOTARY_KEY_ID"
+ echo "DOUBAO_NOTARY_ISSUER_ID=$MACOS_NOTARY_ISSUER_ID"
+ echo "DOUBAO_EXPECTED_TEAM_ID=$MACOS_SIGNING_TEAM_ID"
+} >> "$GITHUB_ENV"
diff --git a/macos/Packaging/preview-manifest.py b/macos/Packaging/preview-manifest.py
new file mode 100644
index 0000000..556d88a
--- /dev/null
+++ b/macos/Packaging/preview-manifest.py
@@ -0,0 +1,28 @@
+"""Write public provenance for a successfully signed and notarized preview."""
+import hashlib
+import json
+import platform
+import plistlib
+from pathlib import Path
+import subprocess
+
+arch = platform.machine()
+app = Path(f"build/macos/{arch}/Doubao Say.app")
+info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
+subprocess.run(["codesign", "--verify", "--strict", str(app)], check=True)
+result = subprocess.run(["codesign", "-d", "-r-", str(app)], capture_output=True, text=True, check=True)
+requirement = next(line.removeprefix("designated => ") for line in
+ (result.stdout + result.stderr).splitlines() if line.startswith("designated => "))
+artifacts = list(Path("build/macos").glob("*.dmg"))
+if len(artifacts) != 1:
+ raise SystemExit("Expected exactly one notarized preview DMG")
+manifest = {
+ "commit": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
+ "version": info["CFBundleShortVersionString"],
+ "bundle_id": info["CFBundleIdentifier"],
+ "architecture": arch,
+ "designated_requirement": requirement,
+ "artifact": artifacts[0].name,
+ "sha256": hashlib.sha256(artifacts[0].read_bytes()).hexdigest(),
+}
+Path("build/macos/preview-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
diff --git a/macos/README.zh-CN.md b/macos/README.zh-CN.md
index 57860ea..28545b7 100644
--- a/macos/README.zh-CN.md
+++ b/macos/README.zh-CN.md
@@ -69,7 +69,7 @@ ChatGPT 凭据使用本应用独立的 macOS 钥匙串条目,不借用 Codex
隔离 UI 检查渲染真实设置窗口和非激活浮窗,逐页检查中英文,并由测试主进程捕获对应窗口;需要测试宿主已有屏幕录制权限。验证应用使用独立 Bundle ID,不读取真实登录会话。
-构建脚本默认使用开发签名;设置 `DOUBAO_CODESIGN_IDENTITY` 可使用 Developer ID 签名并启用强化运行时。`macos/package-dmg.py` 使用指定的公证配置生成带“应用程序”拖拽入口的签名、公证 DMG。真实麦克风、快捷键、不同应用的粘贴、登录项、AU05 硬件、全屏/多屏和 Intel 运行需分别实机验收;编译和合成检查不替代这些结果。详见 [验收清单](ACCEPTANCE.zh-CN.md)。
+本地构建需要固定的签名证书。运行 `security find-identity -v -p codesigning` 查看证书,再执行 `git config --local doubao.codesignIdentity '<证书 SHA-1>'` 保存到当前仓库的本机配置。后续构建自动复用该证书,避免临时签名随代码变化而使快捷键权限失效。也可通过 `DOUBAO_CODESIGN_IDENTITY` 指定证书;发行包使用 Developer ID 签名。首次从临时签名切换到证书签名时,可能需要重新授权一次。PR CI 的临时签名构建仅用于测试,不再提供应用安装包。主分支预览包与正式包使用同一发行团队的 Developer ID 证书,完成公证后才提供下载;凭据配置见 [更新与签名说明](../packaging/UPDATES.md#signed-mac-previews)。本机只有显式设置 `DOUBAO_CODESIGN_IDENTITY=-` 才生成临时预览包,不建议用于日常安装。`macos/package-dmg.py` 使用指定的公证配置生成带“应用程序”拖拽入口的签名、公证 DMG。真实麦克风、快捷键、不同应用的粘贴、登录项、AU05 硬件、全屏/多屏和 Intel 运行需分别实机验收;编译和合成检查不替代这些结果。详见 [验收清单](ACCEPTANCE.zh-CN.md)。
上游来源和许可见根目录 `NOTICE` 及本目录 `UPSTREAM-LICENSE`。
diff --git a/macos/Sources/DoubaoSayApp.swift b/macos/Sources/DoubaoSayApp.swift
index 3f0b29d..4d80f2d 100644
--- a/macos/Sources/DoubaoSayApp.swift
+++ b/macos/Sources/DoubaoSayApp.swift
@@ -376,6 +376,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
state.updateVersion = ProcessInfo.processInfo.environment["DOUBAO_SMOKE_UPDATE_VERSION"] ?? ""
settingsWindow.model.selectedTab = ProcessInfo.processInfo.environment["DOUBAO_SMOKE_TAB"] ?? "setup"
settingsWindow.model.draft.polishEnabled = true
+ if ProcessInfo.processInfo.environment["DOUBAO_SMOKE_ONBOARDING_SAVED"] == "1" {
+ settingsWindow.model.draft.onboardingComplete = true
+ precondition(!settingsWindow.model.showsSetupWizard,
+ "Saved onboarding must show completion without live microphone or voice checks")
+ }
settingsWindow.model.setupStep = min(max(Int(ProcessInfo.processInfo.environment["DOUBAO_SMOKE_SETUP_STEP"] ?? "0") ?? 0, 0), 3)
if ProcessInfo.processInfo.environment["DOUBAO_SMOKE_SIGNED_IN"] == "1" {
state.loginStatus = .loggedIn
diff --git a/macos/Sources/PolishCoordinator.swift b/macos/Sources/PolishCoordinator.swift
index 0f3c594..f818711 100644
--- a/macos/Sources/PolishCoordinator.swift
+++ b/macos/Sources/PolishCoordinator.swift
@@ -37,6 +37,15 @@ final class PolishCoordinator {
self.timer = timer
DispatchQueue.main.asyncAfter(deadline: .now() + 1.2, execute: timer)
}
+ /// Overlap polishing with ASR finalization; delivery still waits for final text.
+ func prepareFinal(text: String) {
+ guard !isFinal else { return }
+ let text = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ update(text: text, speaking: false)
+ timer?.cancel(); timer = nil
+ guard settings.polishEnabled, !key.isEmpty else { return }
+ startPreview()
+ }
private func startPreview() {
guard !isFinal, !currentText.isEmpty, snapshot != currentText else { return }
snapshot = currentText; cached = nil; cachedPolished = false
diff --git a/macos/Sources/SettingsModel.swift b/macos/Sources/SettingsModel.swift
index adb860f..d827ae7 100644
--- a/macos/Sources/SettingsModel.swift
+++ b/macos/Sources/SettingsModel.swift
@@ -23,6 +23,8 @@ final class SettingsModel: ObservableObject {
@Published var feedback = ""
@Published var selectedTab = "setup"
@Published var setupStep = 0
+ @Published private(set) var repeatingSetup = false
+ var showsSetupWizard: Bool { !draft.onboardingComplete || repeatingSetup }
@Published var shortcutAvailable = false
@Published var capturing = false { didSet { if !capturing { resumeAutosave() } } }
@Published var testing = false { didSet { if !testing { resumeAutosave() } } }
@@ -68,8 +70,12 @@ final class SettingsModel: ObservableObject {
private var currentDefaultMicrophoneID: String?
private var deviceMonitor: AudioDeviceMonitor?
init(state: AppState, microphoneInputs: @escaping () -> [AudioInputDevice] = AudioDevices.inputs,
- defaultMicrophoneID: @escaping () -> String? = AudioDevices.defaultInputUID) {
+ defaultMicrophoneID: @escaping () -> String? = AudioDevices.defaultInputUID,
+ initialSettings: MacSettings? = nil) {
self.state = state
+ let saved = initialSettings ?? SettingsStore.shared.value
+ suppressAutosave = true; draft = saved; suppressAutosave = false
+ selectedTab = saved.onboardingComplete ? "general" : "setup"
self.microphoneInputs = microphoneInputs; self.defaultMicrophoneID = defaultMicrophoneID
microphones = microphoneInputs(); currentDefaultMicrophoneID = defaultMicrophoneID()
deviceMonitor = AudioDeviceMonitor { [weak self] in self?.refreshMicrophones() }
@@ -192,6 +198,10 @@ final class SettingsModel: ObservableObject {
guard !setupBusy else { return }
setupStep = max(0, setupStep - 1); feedback = ""
}
+ func repeatSetup() {
+ guard !setupBusy, saveIfNeeded() else { return }
+ repeatingSetup = true; setupStep = 0; feedback = ""
+ }
func finishSetup() {
guard setupStep == 3, canAdvanceSetup, saveIfNeeded() else { return }
let saved = SettingsStore.shared.value
@@ -201,7 +211,7 @@ final class SettingsModel: ObservableObject {
return
}
var completed = draft; completed.onboardingComplete = true
- do { try apply?(completed, nil, nil); draft = completed; onFinishSetup?() }
+ do { try apply?(completed, nil, nil); draft = completed; repeatingSetup = false; onFinishSetup?() }
catch { feedback = L("Could not complete setup.", "无法完成使用准备。") }
}
func chooseShortcut(_ destination: String = "record") {
diff --git a/macos/Sources/SettingsWindow.swift b/macos/Sources/SettingsWindow.swift
index ee1ea2c..b54dce3 100644
--- a/macos/Sources/SettingsWindow.swift
+++ b/macos/Sources/SettingsWindow.swift
@@ -124,7 +124,23 @@ struct SettingsView: View {
}.formStyle(.grouped).padding(8)
}
private var setupTitles: [String] { [L("Recognition", "识别服务"), L("Microphone", "麦克风"), L("Shortcut", "快捷键"), L("Voice test", "语音试说")] }
- private var setup: some View {
+ @ViewBuilder private var setup: some View {
+ if model.showsSetupWizard {
+ setupWizard
+ } else {
+ VStack(alignment: .leading, spacing: 16) {
+ Label(L("Setup complete", "使用准备已完成"), systemImage: "checkmark.circle.fill")
+ .font(.headline).foregroundColor(.green)
+ Text(L("You have already completed setup. Your settings are kept when the app is restarted or updated.", "你已完成使用准备。重启或更新应用后,已有设置会保留。"))
+ Button(L("Open general settings", "打开通用设置")) { model.selectedTab = "general" }
+ .buttonStyle(.borderedProminent)
+ Button(L("Run setup again", "重新检查使用准备")) { model.repeatSetup() }
+ .disabled(model.setupBusy)
+ Spacer()
+ }.padding(24)
+ }
+ }
+ private var setupWizard: some View {
VStack(alignment: .leading, spacing: 16) {
HStack(spacing: 12) {
ForEach(0..<4) { index in
diff --git a/macos/Sources/TranscriptionManager.swift b/macos/Sources/TranscriptionManager.swift
index 1ddfbe3..2a162ec 100644
--- a/macos/Sources/TranscriptionManager.swift
+++ b/macos/Sources/TranscriptionManager.swift
@@ -103,7 +103,10 @@ final class TranscriptionManager {
self.state.transcriptionText = text
self.state.overlayStatus = ""
if self.state.isRecording { self.polisher.update(text: text, speaking: self.speaking) }
- else if self.state.recordingState == .stopping { self.armQuietCompletion(token: token) }
+ else if self.state.recordingState == .stopping {
+ self.polisher.prepareFinal(text: text)
+ self.armQuietCompletion(token: token)
+ }
}
}
transport.onAudioDrained = { [weak self] in
@@ -153,6 +156,7 @@ final class TranscriptionManager {
guard state.recordingState == .starting || state.recordingState == .recording else { return }
latency.stop(at: ProcessInfo.processInfo.systemUptime)
setState(.stopping); audio.stopCapture(); client?.finishSending()
+ polisher.prepareFinal(text: rawText)
// Bound slow handshakes without authorizing delivery of incomplete text.
scheduleTimeout(seconds: 8, token: session) { [weak self] in
guard let self = self else { return }
diff --git a/macos/Tests/Input/RetryCheck.swift b/macos/Tests/Input/RetryCheck.swift
index 24fcacf..24251ad 100644
--- a/macos/Tests/Input/RetryCheck.swift
+++ b/macos/Tests/Input/RetryCheck.swift
@@ -55,6 +55,7 @@ final class HotkeyManager {
var onPreview: ((String, Bool) -> Void)?; var onProgress: ((String) -> Void)?
func begin(settings: MacSettings, key: String) {}
func update(text: String, speaking: Bool) {}
+ func prepareFinal(text: String) {}
func useOriginal() {}
func cancel() {}
func finish(text: String, completion: @escaping (String, Bool) -> Void) { completion(text, false) }
diff --git a/macos/Tests/Network/PolishCheck.swift b/macos/Tests/Network/PolishCheck.swift
index 34ab640..58bebef 100644
--- a/macos/Tests/Network/PolishCheck.swift
+++ b/macos/Tests/Network/PolishCheck.swift
@@ -67,6 +67,32 @@ struct PolishCheck {
final = nil
coordinator.finish(text: "success", completion: { text, _ in final = text })
check(final == "周四上线。", "matching preview cache reused")
+ // A stop starts work immediately instead of waiting for the preview debounce.
+ // Simulate ASR's finalization window before allowing delivery.
+ coordinator.begin(settings: settings, key: "fake-polish-key")
+ var overlapReady = false
+ coordinator.onPreview = { _, busy in if !busy { overlapReady = true } }
+ coordinator.prepareFinal(text: " overlap ")
+ drain(until: { overlapReady }, seconds: 0.8)
+ check(overlapReady, "polishing completes during ASR finalization")
+ final = nil
+ coordinator.prepareFinal(text: "overlap")
+ coordinator.finish(text: "overlap", completion: { text, _ in final = text })
+ check(final == "周四上线。", "final text reuses overlapped result synchronously")
+
+ coordinator.begin(settings: settings, key: "fake-polish-key")
+ coordinator.prepareFinal(text: "slow")
+ coordinator.prepareFinal(text: "success")
+ final = nil
+ coordinator.finish(text: "success", completion: { text, _ in final = text })
+ drain(until: { final != nil })
+ check(final == "周四上线。", "trailing ASR correction invalidates early polishing")
+
+ coordinator.begin(settings: settings, key: "")
+ coordinator.prepareFinal(text: "no credentials")
+ final = nil
+ coordinator.finish(text: "no credentials", completion: { text, _ in final = text })
+ check(final == "no credentials", "early polishing requires credentials")
coordinator.cancel()
print(failed ? "FAIL: polish network lifecycle" : "PASS: streaming, malformed/incomplete responses, redirects, five-second deadline, skip, cancel, stale preview and cache")
exit(failed ? 1 : 0)
diff --git a/macos/Tests/Network/check.py b/macos/Tests/Network/check.py
index 5779896..370e8fd 100644
--- a/macos/Tests/Network/check.py
+++ b/macos/Tests/Network/check.py
@@ -42,6 +42,8 @@ class Handler(http.server.BaseHTTPRequestHandler):
else:
assert 'User-confirmed' not in prompt
requests.append(sample)
+ if sample == 'overlap':
+ time.sleep(0.3)
if sample == 'slow':
time.sleep(6)
if sample == 'error':
@@ -81,7 +83,8 @@ try:
result = subprocess.run([sys.argv[1], f'http://127.0.0.1:{server.server_port}/v1'], timeout=28)
if errors:
raise SystemExit('FAIL: fixture ' + repr(errors))
- assert requests.count('success') == 3, requests
+ assert requests.count('success') == 4, requests
+ assert requests.count('overlap') == 1, requests
raise SystemExit(result.returncode)
finally:
server.shutdown()
diff --git a/macos/Tests/Packaging/test_preview_signing.py b/macos/Tests/Packaging/test_preview_signing.py
new file mode 100644
index 0000000..6b32efd
--- /dev/null
+++ b/macos/Tests/Packaging/test_preview_signing.py
@@ -0,0 +1,115 @@
+"""Synthetic CI-signing checks; never access the real keychain or Apple services."""
+import base64
+import json
+import os
+from pathlib import Path
+import plistlib
+import runpy
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[2]
+SIGNING = ROOT / 'Packaging/prepare-preview-signing.sh'
+PACKAGE = ROOT / 'package-dmg.py'
+
+
+class PreviewSigningTests(unittest.TestCase):
+ def prepare(self, directory, identities, missing=None):
+ binary = directory / 'bin'
+ binary.mkdir()
+ security = binary / 'security'
+ security.write_text('''#!/usr/bin/env python3
+import os, sys
+from pathlib import Path
+with open(os.environ['CALLS'], 'a') as output: output.write(sys.argv[1] + '\\n')
+if sys.argv[1] == 'find-identity': print(os.environ['IDENTITIES'])
+''')
+ security.chmod(0o755)
+ env = {**os.environ, 'PATH': str(binary) + ':' + os.environ['PATH'],
+ 'RUNNER_TEMP': str(directory), 'GITHUB_ENV': str(directory / 'job.env'),
+ 'CALLS': str(directory / 'calls'), 'IDENTITIES': identities,
+ 'MACOS_CERTIFICATE_P12_BASE64': base64.b64encode(b'fake certificate').decode(),
+ 'MACOS_CERTIFICATE_PASSWORD': 'synthetic-password',
+ 'MACOS_NOTARY_KEY_P8_BASE64': base64.b64encode(b'fake notary key').decode(),
+ 'MACOS_NOTARY_KEY_ID': 'FAKEKEY123', 'MACOS_NOTARY_ISSUER_ID': 'fake-issuer',
+ 'MACOS_SIGNING_TEAM_ID': 'FAKETEAM12'}
+ if missing:
+ env.pop(missing)
+ return subprocess.run(['bash', str(SIGNING)], env=env, capture_output=True, text=True)
+
+ def test_missing_credentials_fail_before_keychain_access(self):
+ with tempfile.TemporaryDirectory() as folder:
+ directory = Path(folder)
+ result = self.prepare(directory, '', 'MACOS_NOTARY_KEY_P8_BASE64')
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn('MACOS_NOTARY_KEY_P8_BASE64', result.stderr)
+ self.assertFalse((directory / 'calls').exists())
+ self.assertFalse((directory / 'job.env').exists())
+
+ def test_only_one_valid_distribution_identity_is_accepted(self):
+ identity = 'A' * 40
+ for identities, accepted in [
+ (f'1) {identity} "Apple Development: Synthetic"', False),
+ (f'1) {identity} "Developer ID Application: Synthetic"', True),
+ (f'1) {identity} "Developer ID Application: First"\n'
+ f'2) {"B" * 40} "Developer ID Application: Second"', False),
+ ]:
+ with self.subTest(accepted=accepted), tempfile.TemporaryDirectory() as folder:
+ directory = Path(folder)
+ result = self.prepare(directory, identities)
+ self.assertEqual(result.returncode == 0, accepted, result.stderr)
+ self.assertEqual((directory / 'job.env').exists(), accepted)
+ if accepted:
+ output = (directory / 'job.env').read_text()
+ self.assertIn('DOUBAO_CODESIGN_IDENTITY=' + identity, output)
+ self.assertNotIn('synthetic-password', output + result.stdout + result.stderr)
+ self.assertNotIn('fake notary key', output + result.stdout + result.stderr)
+ for name in ['doubao-preview-certificate.p12', 'doubao-preview-notary.p8']:
+ self.assertEqual((directory / name).stat().st_mode & 0o777, 0o600)
+
+ def package_failure(self, team, notarization):
+ with tempfile.TemporaryDirectory() as folder:
+ directory = Path(folder)
+ info = directory / 'build/macos/arm64/Doubao Say.app/Contents/Info.plist'
+ info.parent.mkdir(parents=True)
+ info.write_bytes(plistlib.dumps({'CFBundleShortVersionString': '1.0.0'}))
+ calls = []
+
+ def run(argv, **kwargs):
+ calls.append(argv)
+ signature = 'Authority=Developer ID Application: Synthetic\nflags=runtime\nTeamIdentifier=' + team
+ return subprocess.CompletedProcess(argv, 0, stdout='', stderr=signature)
+
+ def output(argv, **kwargs):
+ calls.append(argv)
+ return json.dumps({'status': notarization})
+
+ previous = Path.cwd()
+ try:
+ os.chdir(directory)
+ with patch.dict(os.environ, {'DOUBAO_EXPECTED_TEAM_ID': 'FAKETEAM12'}), \
+ patch('sys.argv', [str(PACKAGE), '--identity', 'fake', '--arch', 'arm64',
+ '--key', 'fake.p8', '--key-id', 'fake', '--issuer', 'fake']), \
+ patch('subprocess.run', side_effect=run), \
+ patch('subprocess.check_output', side_effect=output):
+ with self.assertRaises(RuntimeError):
+ runpy.run_path(str(PACKAGE), run_name='__main__')
+ finally:
+ os.chdir(previous)
+ self.assertFalse(list(directory.rglob('*.dmg')))
+ return calls
+
+ def test_wrong_team_is_rejected_before_notarization(self):
+ calls = self.package_failure('OTHERTEAM1', 'Accepted')
+ self.assertFalse(any('notarytool' in call for call in calls))
+
+ def test_rejected_notarization_never_reaches_dmg_creation(self):
+ calls = self.package_failure('FAKETEAM12', 'Invalid')
+ self.assertTrue(any('notarytool' in call for call in calls))
+ self.assertFalse(any('hdiutil' in call for call in calls))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/macos/Tests/Settings/AutoSaveCheck.swift b/macos/Tests/Settings/AutoSaveCheck.swift
index e4e45e4..53249d3 100644
--- a/macos/Tests/Settings/AutoSaveCheck.swift
+++ b/macos/Tests/Settings/AutoSaveCheck.swift
@@ -71,6 +71,27 @@ struct AutoSaveCheck {
let defaults = UserDefaults(suiteName: suite)!
defer { defaults.removePersistentDomain(forName: suite) }
let store = SettingsStore(defaults: defaults)
+ // A replacement app loads the same persisted settings with fresh in-memory checks.
+ precondition(SettingsModel(state: AppState(), initialSettings: store.value).selectedTab == "setup")
+ var completed = store.value; completed.onboardingComplete = true
+ try! store.save(completed)
+ let restored = SettingsStore(defaults: defaults)
+ let upgradeState = AppState()
+ let upgraded = SettingsModel(state: upgradeState, initialSettings: restored.value)
+ precondition(upgraded.selectedTab == "general" && !upgraded.showsSetupWizard,
+ "Restarting or upgrading must not reopen completed onboarding")
+ precondition(!upgradeState.microphoneChecked && !upgradeState.voiceChecked,
+ "Saved onboarding must not fabricate live device checks")
+ upgraded.draft.microphoneID = "new-device"
+ precondition(!upgraded.showsSetupWizard && upgraded.draft.onboardingComplete,
+ "Device changes must not reset completed onboarding")
+ upgraded.repeatSetup()
+ precondition(upgraded.showsSetupWizard && upgraded.setupStep == 0 && upgraded.draft.onboardingComplete,
+ "Explicit rechecks must not erase saved completion")
+ let reopened = SettingsModel(state: AppState(), initialSettings: restored.value)
+ precondition(!reopened.showsSetupWizard, "Abandoning an optional recheck must not reset onboarding")
+ try! store.save(MacSettings())
+ print("PASS: persisted onboarding survives app replacement and fresh runtime checks; explicit rechecks stay optional")
deviceModel.apply = { settings, _, _ in try store.save(settings) }
precondition(deviceModel.selectMicrophone(builtIn.id) && store.value.microphoneID == builtIn.id)
precondition(deviceModel.selectMicrophone("") && store.value.microphoneID.isEmpty)
diff --git a/macos/build.sh b/macos/build.sh
index c7f9291..56aef95 100755
--- a/macos/build.sh
+++ b/macos/build.sh
@@ -4,6 +4,20 @@ cd "$(dirname "$0")/.."
if [[ "$(uname -s)" != Darwin ]]; then echo 'macOS with Xcode Command Line Tools is required.' >&2; exit 1; fi
arch="${DOUBAO_MAC_ARCH:-$(uname -m)}"
case "$arch" in arm64|x86_64) ;; *) echo 'Unsupported architecture' >&2; exit 1 ;; esac
+# Pin local development signing so rebuilding does not silently change TCC identity.
+identity="${DOUBAO_CODESIGN_IDENTITY:-$(git config --local --get doubao.codesignIdentity || true)}"
+if [[ -z "$identity" ]]; then
+ if [[ "${CI:-}" == true ]]; then
+ identity=-
+ else
+ echo 'Local builds require a stable signing identity. Set DOUBAO_CODESIGN_IDENTITY or git config --local doubao.codesignIdentity <certificate SHA-1>.' >&2
+ echo 'Use security find-identity -v -p codesigning to list certificates. For disposable previews only, explicitly set DOUBAO_CODESIGN_IDENTITY=-.' >&2
+ exit 1
+ fi
+fi
+if [[ "$identity" == - ]]; then
+ echo 'Warning: ad-hoc preview signing changes identity on rebuild; macOS permissions may need to be granted again.' >&2
+fi
bundle="build/macos/$arch/Doubao Say.app"
mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources"
xcrun swiftc -swift-version 5 -O -target "$arch-apple-macos13.0" \
@@ -30,8 +44,8 @@ info = dict(CFBundleIdentifier='md.lifeos.doubao-say.macos', CFBundleName='Douba
NSMicrophoneUsageDescription='Doubao Say uses your microphone to transcribe speech with Doubao.')
pathlib.Path(sys.argv[1], 'Contents/Info.plist').write_bytes(plistlib.dumps(info))
PY
-if [[ -n "${DOUBAO_CODESIGN_IDENTITY:-}" ]]; then
- codesign --force --sign "$DOUBAO_CODESIGN_IDENTITY" --timestamp --options runtime \
+if [[ "$identity" != - ]]; then
+ codesign --force --sign "$identity" --timestamp --options runtime \
--entitlements macos/Packaging/Entitlements.plist "$bundle"
else
codesign --force --sign - "$bundle"
diff --git a/macos/check.sh b/macos/check.sh
index 2921c85..161b67c 100755
--- a/macos/check.sh
+++ b/macos/check.sh
@@ -1,6 +1,7 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")/.."
+python3 macos/Tests/Packaging/test_preview_signing.py
swift test --package-path macos --jobs 2
mkdir -p build/macos/tests
chatgpt_core=(macos/Sources/ChatGPTVault.swift macos/Sources/ChatGPTProtocol.swift macos/Sources/ChatGPTOAuth.swift macos/Sources/ChatGPTCallback.swift macos/Sources/ChatGPTService.swift macos/Sources/ChatGPTResponses.swift)
diff --git a/macos/package-dmg.py b/macos/package-dmg.py
index 4d0e440..fd2be10 100644
--- a/macos/package-dmg.py
+++ b/macos/package-dmg.py
@@ -43,6 +43,9 @@ run('codesign', '--verify', '--strict', str(app))
signature = subprocess.run(['codesign', '-d', '--verbose=4', str(app)], capture_output=True, text=True, check=True).stderr
if 'Developer ID Application:' not in signature or 'runtime' not in signature:
raise RuntimeError('Build with DOUBAO_CODESIGN_IDENTITY and hardened runtime first')
+expected_team = os.environ.get('DOUBAO_EXPECTED_TEAM_ID')
+if expected_team and f'TeamIdentifier={expected_team}' not in signature.splitlines():
+ raise RuntimeError('Preview signing team does not match the configured release team')
archive = Path('build/macos/Doubao-Say-notarization.zip').resolve()
run('ditto', '-c', '-k', '--keepParent', str(app), str(archive))
# Apple accepts ZIP submissions; the ticket is stapled to the contained application.
@@ -60,7 +63,7 @@ if not shortcut.is_symlink():
os.symlink('/Applications', shortcut)
commit = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], text=True).strip()
dmg = Path(f'build/macos/Doubao-Say-{version}-macos-{args.arch}-{commit}.dmg').resolve()
-run(str(Path.home() / '.local/bin/dev-gate'), 'run', '--label', 'doubao-dmg-image', '--', 'hdiutil', 'create', '-volname', 'Doubao Say', '-srcfolder', str(stage), '-fs', 'HFS+', '-format', 'UDZO', '-ov', str(dmg))
+run('hdiutil', 'create', '-volname', 'Doubao Say', '-srcfolder', str(stage), '-fs', 'HFS+', '-format', 'UDZO', '-ov', str(dmg))
run('codesign', '--sign', args.identity, '--timestamp', str(dmg))
notarize(dmg)
run('spctl', '--assess', '--type', 'open', '--context', 'context:primary-signature', '--verbose=2', str(dmg))
diff --git a/macos/runtime-check.py b/macos/runtime-check.py
index 385c14f..df88002 100644
--- a/macos/runtime-check.py
+++ b/macos/runtime-check.py
@@ -20,6 +20,8 @@ for language in ['en', 'zh']:
cases = [('overlay', '--smoke-test', '')]
if '--launch-settings' in sys.argv[3:]:
cases = [(f'launch-{status}', '--settings-smoke-test', 'general') for status in ['available', 'latest']]
+ if '--saved-setup' in sys.argv[3:]:
+ cases = [('saved-setup', '--settings-smoke-test', 'setup')]
if '--setup-completion' in sys.argv[3:]:
cases = [(f'setup-{status}-{theme}', '--settings-smoke-test', 'setup')
for status in ['complete', 'pending'] for theme in ['light', 'dark']]
@@ -35,6 +37,8 @@ for language in ['en', 'zh']:
cases += [(f'settings-{tab}', '--settings-smoke-test', tab) for tab in ['setup', 'recognition', 'polishing', 'shortcuts', 'general', 'result']]
for label, argument, tab in cases:
env = dict(os.environ, DOUBAO_SMOKE_IMAGE=str(output / f'{label}-{language}.png'), DOUBAO_SMOKE_TAB=tab)
+ if label == 'saved-setup':
+ env['DOUBAO_SMOKE_ONBOARDING_SAVED'] = '1'
if label == 'input-failure':
env['DOUBAO_SMOKE_INPUT_FAILURE'] = '1'
if label == 'microphone-menu':
diff --git a/packaging/UPDATES.md b/packaging/UPDATES.md
index d69fc74..8ea8c1f 100644
--- a/packaging/UPDATES.md
+++ b/packaging/UPDATES.md
@@ -79,3 +79,59 @@ all eight Linux archives, official asset URLs and matching checksum entries. It
omits release body, uploader/account fields and credentials. Verify the public
`releases/latest/download/update.json` URL and both update-source paths. Older
clients that cannot reach the API need one manual DMG upgrade to get this fallback.
+
+## Local Mac development signing
+
+Pin a certificate for local builds so successive app replacements keep a stable
+code-signing identity for macOS permission checks:
+
+```sh
+security find-identity -v -p codesigning
+git config --local doubao.codesignIdentity '<certificate SHA-1>'
+bash macos/build.sh
+```
+
+The setting stays in this checkout's local Git configuration. An explicit
+`DOUBAO_CODESIGN_IDENTITY` overrides it. Local builds fail without a configured
+identity instead of silently falling back to ad-hoc signing. PR CI builds still
+use ad-hoc signing for tests and do not distribute an installable app; `DOUBAO_CODESIGN_IDENTITY=-` explicitly requests a disposable
+local preview. Changing from ad-hoc to certificate signing may require one more
+permission grant. Release DMGs still require Developer ID signing and notarization.
+
+## Signed Mac previews
+
+Installable previews use the same Developer ID signing team and bundle ID as the
+release DMGs. They are notarized and stapled before upload. The protected-main
+`preview` job in `.github/workflows/macos.yml` runs after the Mac checks on a main
+push or a manual run on main. Pull-request builds publish only opt-in test probes;
+they cannot access signing credentials or distribute an ad-hoc application ZIP.
+Dispatching the workflow on another branch does not start the signing job.
+
+Configure the `macos-preview` GitHub environment before merging this workflow.
+Restrict its deployment branches to protected branches and keep `main` protected.
+Set the environment variable `MACOS_SIGNING_TEAM_ID` to the existing release
+team. Add these environment secrets through GitHub Settings → Environments →
+macos-preview (never through source files, issue comments or chat):
+
+| Secret | Value |
+| --- | --- |
+| `MACOS_CERTIFICATE_P12_BASE64` | Single-line base64 of the release Developer ID Application certificate **and private key**, exported as PKCS#12 |
+| `MACOS_CERTIFICATE_PASSWORD` | Nonempty password protecting that PKCS#12 export |
+| `MACOS_NOTARY_KEY_P8_BASE64` | Single-line base64 of the App Store Connect API private key used for notarization |
+| `MACOS_NOTARY_KEY_ID` | That API key's key ID |
+| `MACOS_NOTARY_ISSUER_ID` | That API key's issuer ID |
+
+The job imports the certificate into a temporary keychain, permits `codesign`
+access, requires exactly one valid Developer ID Application identity and verifies
+that the app's team matches the configured release team. Missing credentials,
+a team mismatch or failed notarization fail the job; no unsigned fallback app is
+uploaded. An always-run cleanup step removes the temporary keychain and credential
+files. Only the DMG, checksum and public provenance manifest are uploaded.
+
+Download `Doubao-Say-macos-signed-preview` from the successful workflow run. The
+manifest records the exact source commit, architecture, bundle ID, signing
+requirement and artifact hash. Replacing an older ad-hoc or Apple Development
+build may require one final permission grant. Successive Developer ID previews
+and releases with compatible signing requirements should retain existing grants.
+Real permission retention across two distributed previews still needs acceptance
+on a Mac; synthetic signing tests do not establish that result.