Skip to content

fix(translation): fix 15 root causes of low translation efficiency and success rate - #82

Merged
hubo1989 merged 3 commits into
mainfrom
hubo/translate-improve
Oct 27, 2026
Merged

hubo1989 merged 3 commits into
mainfrom
hubo/translate-improve

Conversation

@hubo1989

Copy link
Copy Markdown
Owner

Summary

全面审查并修复翻译 pipeline 的效率和成功率问题,覆盖截图翻译、选区内翻译、选中文本、翻译并插入四条生产链路。

Changes Made

端点与配置(开箱即失败)

  • 修复 Claude 默认 URL 产生 /v1/v1/messages(现为 /v1/messages)
  • 修复 Gemini 兼容路径缺 /openai
  • 修复 Ollama 默认 URL 缺 /v1 前缀;同步连接测试路径
  • 修复 DeepL 默认 URL 缺 /translate 操作后缀

成功语义与回退

  • 空/条数不匹配/无效译文抛错触发回退,不再静默回填原文
  • primaryResult 回退到任意成功引擎
  • 取消错误原样传播,不触发 fallback
  • 尊重显式源语言;简繁转换不再被同语言旁路跳过
  • 主备模式使用 parallelEngines[1] 作为备用引擎

路由与分析

  • 截图翻译统一从 parallelEngines[0] 解析主引擎
  • 空 VLM 结果也触发 OCR 回退
  • 收紧提示词泄漏启发式;去重保留重复 UI 标签
  • Vision auto 模式启用 automaticallyDetectsLanguage
  • PaddleOCR 语言映射使用 cliValue

任务生命周期与安全

  • SelectionOverlayWindow/PreviewViewModel 任务代次跟踪
  • forceRerun 参数绕过 toggle 关闭
  • isStartingCapture 防重复捕获
  • 剪贴板恢复使用 defer
  • 裁剪/关闭取消任务并失效结果

显示与解析

  • 叠层底边译文改放原文上方
  • 百度响应 join 全部 trans_result 段
  • LLM 批量 prompt 提示保留分隔符

Testing

  • 全部翻译测试通过
  • 全部测试套件通过(TEST SUCCEEDED)
  • 构建通过

…d success rate

Endpoints & configuration:
- Fix Claude default URL producing /v1/v1/messages (now /v1/messages)
- Fix Gemini default URL missing /openai in compat path
- Fix Ollama default URL missing /v1 prefix; sync connection test path
- Fix DeepL default URL missing /translate operation suffix
- Add appendingAPISuffix helper to deduplicate version segments in URLs

Success semantics & fallback:
- Throw TranslationProviderError on empty/mismatched/invalid translations
  instead of silently returning source text as success
- primaryResult falls back to any successful engine when primary fails
- Propagate CancellationError; skip fallback after cancellation
- Respect explicit source language; don't rewrite zh-Hant→zh-Hans as bypass
- Use configured parallelEngines[1] as fallback engine in primaryWithFallback

Route & analysis:
- Resolve preferred engine from parallelEngines[0] consistently in
  ImageTranslationPipelineConfig (matches TextTranslationFlow)
- Trigger OCR fallback on empty VLM results, not just prompt leakage
- Tighten prompt-leakage heuristic; require multi-signal match
- Deduplicate by text+position signature only; preserve repeated UI labels
- Enable Vision automaticallyDetectsLanguage for auto mode
- Map PaddleOCR language codes via cliValue instead of binary ch/en

Task lifecycle & safety:
- Add generation tracking to SelectionOverlayWindow/PreviewViewModel tasks
- Add forceRerun parameter to bypass toggle-close on retry/language switch
- Add isStartingCapture guard to prevent duplicate capture sessions
- Use defer for clipboard restore in TextSelectionService
- Cancel tasks and invalidate results on crop/hide in PreviewViewModel
- Fix stale windowWillClose callback clearing new popup reference

Display & parsing:
- Place translation strip above source when it would clip at bottom edge
- Join all Baidu trans_result segments instead of taking only first
- Instruct LLM batch prompts to preserve '---' separators

Tests:
- Update testSanitizeTranslationCurlyBraces to verify error-on-invalid
- Add testEmptyTranslationTriggersError
- Add testExplicitSourceLanguageRespected for zh-Hant→zh-Hans conversion
- Replace NL-dependent testSelfLanguageTranslationBypass with explicit source
@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6e27f97e-578c-45c6-994a-4cd8501bd8e4
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T03:22:46.035225Z cecd8fd PR opened
🔒 Security Review ✅ Completed 2026-10-27T03:19:50.336911Z cecd8fd PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cecd8fd35e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

logger.warning("Capture session already in progress, ignoring trigger")
return
}
isStartingCapture = true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Clear the startup guard before the full-screen return

When a full-screen capture succeeds, execution returns at line 93 before isStartingCapture is reset at the end of the task. Because this controller is a singleton, every subsequent call to startCapture fails the new guard and all capture modes remain unavailable until the application restarts; reset the flag on every exit path, such as with a task-level defer.

Useful? React with 👍 / 👎.

Comment on lines +25 to +28
defer {
if currentGeneration == analysisGeneration {
isPerformingOCR = false
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear operation flags after generation invalidation

If translation starts while OCR is running, or a crop invalidates the analysis, the shared analysisGeneration changes before this task exits. This conditional defer then refuses to clear isPerformingOCR, so performOCR() continues returning at its guard and the OCR button remains disabled with a permanent spinner for the lifetime of the preview; the symmetric translation defer can leave isTranslating stuck in the same way. Generation checks should suppress stale result writes without preventing the cancelled operation's busy state from being cleared.

Useful? React with 👍 / 👎.

Comment on lines +534 to +535
while url.absoluteString.hasSuffix("/") {
url.deleteLastPathComponent()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid an infinite loop for trailing-slash base URLs

When a configured LLM base URL ends in /—for example http://localhost:11434/ or https://api.openai.com/v1/—repeatedly calling deleteLastPathComponent() eventually reaches the host root, whose absolute URL still ends in /; deleting its last component makes no further change, so this loop never terminates. Connection tests and translations using these common URL forms spin indefinitely and cannot reach the request code.

Useful? React with 👍 / 👎.

Comment on lines +515 to +518
let cleaned = self.sanitizeTranslation(translated: res.translatedText, source: res.sourceText)
if cleaned == res.sourceText, res.translatedText != res.sourceText {
hasFailedSlot = true
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Distinguish sanitizer failures from unchanged translations

The equality check treats every sanitizer result equal to the source as invalid whenever the provider's raw response differs. This rejects valid supported JSON-wrapped output when the correct translation is unchanged—for example source OpenAI with {"translation":"OpenAI"}—and consequently fails or retries the entire batch even though sanitizeTranslation successfully extracted a valid value. The sanitizer needs to report whether parsing actually failed rather than using source-text equality as the failure signal.

Useful? React with 👍 / 👎.

Comment on lines +23 to +24
} else if let first = settings.parallelEngines.first {
preferredEngine = first

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip disabled engines when resolving the image primary

In primary-with-fallback and quick-switch modes, this now selects parallelEngines.first without checking whether that engine is enabled. The settings UI allows an engine to be disabled without removing it from parallelEngines, and translateWithEngine does not inspect isEnabled, so screenshot and preview translations can continue sending requests to a deliberately disabled provider (and never fall back if its credentials remain valid). Resolve the first enabled engine, or prune disabled entries when configuration changes.

Useful? React with 👍 / 👎.

@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

🔍 OpenCodeReview found 11 issue(s) in this PR.

  • ✅ Successfully posted inline: 9 comment(s)
  • ❌ Failed to post inline: 2 comment(s)

maintainability · low

📄 TransFrame/Services/VLMTextDeduplicator.swift (L18-L22)

⚠️ GitHub could not post this as an inline comment: Lines 18-22 could not be resolved (outside PR diff hunks)

minCountThreshold 与 percentageMultiplier 在移除幻觉检测后已无任何引用,属于死代码;保留会暗示调用方这些配置仍影响行为。

💡 Suggested Change

Before:

        /// Minimum count threshold for detecting overrepresented texts (hallucinations)
        var minCountThreshold: Int

        /// Percentage of total segments to use as threshold (0.0-1.0)
        var percentageMultiplier: Double

After:

        /// Position rounding precision for signature matching
        var positionPrecision: Double

maintainability · low

📄 TransFrame/Services/VLMTextDeduplicator.swift (L34-L41)

⚠️ GitHub could not post this as an inline comment: Lines 34-41 could not be resolved (outside PR diff hunks)

改为仅基于签名去重后,Configuration 中的 minCountThreshold 与 percentageMultiplier 已完全不被使用,deduplicate 的 logger 闭包也永远不会被调用,但函数文档与类型文档仍声称会做幻觉检测。调用方(ClaudeVLMProvider/OpenAIVLMProvider)仍传入只记录"检测到过度重复文本"的日志闭包,永远不会触发,容易误导后续维护者以为幻觉过滤仍然生效。建议删除无用字段与 logger 参数,或修正文档说明幻觉检测已移除。

💡 Suggested Change

Before:

    /// Removes duplicate segments using a two-pass strategy:
    /// 1. First pass: detect overrepresented texts (hallucinations) and keep only first occurrence
    /// 2. Second pass: remove segments with identical text+position signatures
    /// - Parameters:
    ///   - segments: The segments to deduplicate
    ///   - config: Deduplication configuration
    ///   - logger: Optional logging closure for detected hallucinations
    /// - Returns: Deduplicated segments

After:

    /// Removes duplicate segments by text+position signature only.
    /// - Parameters:
    ///   - segments: The segments to deduplicate
    ///   - config: Deduplication configuration
    /// - Returns: Deduplicated segments

Comment on lines +71 to +75
ocrTask?.cancel()
translationTask?.cancel()
analysisGeneration &+= 1
ocrResult = nil
bilingualSegments = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
裁剪路径取消 ocrTask/translationTask 并递增 generation 后,被取消任务的 defer 因 generation 不匹配会跳过复位 isPerformingOCR/isTranslating,而此处也未显式复位这两个标志。结果:裁剪时若有 OCR/翻译在途,加载标志永久残留为 true,之后 performOCR()(guard !isPerformingOCR)与 performTranslation()(guard !isTranslating)都会被静默拦截。请在取消的同时复位这两个状态标志。

Suggestion:

Suggested change
ocrTask?.cancel()
translationTask?.cancel()
analysisGeneration &+= 1
ocrResult = nil
bilingualSegments = []
ocrTask?.cancel()
translationTask?.cancel()
analysisGeneration &+= 1
ocrResult = nil
bilingualSegments = []
isPerformingOCR = false
isTranslating = false

Comment on lines +15 to +24
ocrTask?.cancel()
analysisGeneration &+= 1
let generation = analysisGeneration
ocrTask = Task {
await executeOCR(generation: generation)
}
}

func executeOCR() async {
defer { isPerformingOCR = false }
func executeOCR(generation: UInt64? = nil) async {
let currentGeneration = generation ?? analysisGeneration

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
OCR 与翻译共用同一个 analysisGeneration 计数器,但二者是独立入口(ResultsPanel 的 rerun 按钮、translate tab 按钮等可分别触发)。在 OCR 进行中触发 performTranslation()(或反之)会使在途任务结果被 generation 校验静默丢弃,且其 defer 因 currentGeneration != analysisGeneration 跳过复位 isPerformingOCR——该标志将永久为 true,而 performOCR() 入口有 guard !isPerformingOCR else { return },之后 OCR 功能彻底失效,UI 永久停留在骨架屏加载态。建议为 OCR 与翻译使用各自独立的 generation 计数器(或独立任务引用 + 各自的 isLoading 由启动方管理)。

Suggestion:

Suggested change
ocrTask?.cancel()
analysisGeneration &+= 1
let generation = analysisGeneration
ocrTask = Task {
await executeOCR(generation: generation)
}
}
func executeOCR() async {
defer { isPerformingOCR = false }
func executeOCR(generation: UInt64? = nil) async {
let currentGeneration = generation ?? analysisGeneration
ocrTask?.cancel()
ocrGeneration &+= 1
let generation = ocrGeneration
ocrTask = Task {
await executeOCR(generation: generation)
}
}
func executeOCR(generation: UInt64? = nil) async {
let currentGeneration = generation ?? ocrGeneration


private var window: NSWindow?
private weak var popupDelegate: TextTranslationPopupDelegate?
private var presentationID = UUID()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
presentationID 在两处被赋值但全代码库中没有任何读取点,属于死状态。如果本意是用它做新旧窗口区分(类似 generation 方案),当前实现并未生效;否则建议移除,避免给后续维护者留下"已在使用"的误解。

Suggestion:

Suggested change
private var presentationID = UUID()
// 移除未使用的 presentationID,或在实际比较逻辑中使用它

Comment on lines +48 to +54
let estimatedStripHeight = fontSize * 1.6 + 4
let y: CGFloat
if belowY + estimatedStripHeight < displaySize.height {
y = belowY
} else {
y = max(0, boundingBox.minY * displaySize.height - estimatedStripHeight - 1)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
贴底回退分支将译文放在原文上方,但 estimatedStripHeight 是按单行估算的(fontSize * 1.6 + 4),而实际条带高度由 translationStrip 中按 maxWidth 换行后的测量结果决定,长译文换行成多行时实际高度可能显著大于估算值,导致译文条带与原文重叠。可考虑用真实测量高度(或在 translationStrip 中对越界条带做二次位置修正)而非仅用估算值决策。

Suggestion:

Suggested change
let estimatedStripHeight = fontSize * 1.6 + 4
let y: CGFloat
if belowY + estimatedStripHeight < displaySize.height {
y = belowY
} else {
y = max(0, boundingBox.minY * displaySize.height - estimatedStripHeight - 1)
}
// 估算单行高度作为贴底判断依据;多行换行时可能仍与原文轻微重叠,
// 如需精确可基于实际测量高度计算。
let estimatedStripHeight = fontSize * 1.6 + 4

Comment on lines +479 to +483
} else if let first = config.languages.first {
langCode = first.cliValue
} else {
langCode = "ch"
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
Set 无固定顺序:当 config.languages 不含 .chinese 时,使用 Set.first 作为回退语言,Set 的 first 顺序在跨进程运行间不保证一致,相同配置可能在不同运行中选中不同语言,导致 OCR 结果不确定。建议配置为有序数组,或按 Language.allCases 的固定优先级选择。

Suggestion:

Suggested change
} else if let first = config.languages.first {
langCode = first.cliValue
} else {
langCode = "ch"
}
} else if let first = PaddleOCREngine.Language.allCases.first(where: { config.languages.contains($0) }) {
langCode = first.cliValue
} else {
langCode = "ch"
}

Comment on lines +34 to +39
// If user supplied only the host/version root (e.g. .../v2), append /translate.
let trimmed = raw.hasSuffix("/") ? String(raw.dropLast()) : raw
if trimmed.hasSuffix("/translate") {
return trimmed
}
return trimmed + "/translate"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
旧实现中自定义 baseURL 被视为完整请求 endpoint 直接使用;新实现会对所有不以 "/translate" 结尾的自定义 URL 强制追加 "/translate"。这会破坏既有用户配置:例如已配置第三方代理的完整转发地址(如 https://proxy.example.com/deepl,代理内部再路由到 DeepL /v2/translate)的存量用户,升级后请求会打到 .../deepl/translate 而失败。若需保留自动补全,建议仅对识别为 host/version 根(如以 /v2 或 /v2/ 结尾)的 URL 追加,或在配置界面提示该契约变更。

Comment on lines +69 to +75
let configuredFallback: TranslationEngineType? = {
guard fallbackEnabled else { return nil }
if parallelEngines.count > 1 {
return parallelEngines[1]
}
return nil
}()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
当调用方传入的 preferredEngine 恰好等于 parallelEngines1时,这里会把配置的第二引擎作为 fallbackEngine 传入,随后 translateWithFallback 中新增的 guard actualFallback != primaryEngine 会直接抛出 allEnginesFailed——原本会回退到场景默认引擎或 apple/mtranServer 的恢复路径完全丢失,一次主引擎瞬时失败即导致整批翻译失败。建议在两者相同时返回 nil,让 translateWithFallback 走场景默认/内置回退逻辑。

Suggestion:

Suggested change
let configuredFallback: TranslationEngineType? = {
guard fallbackEnabled else { return nil }
if parallelEngines.count > 1 {
return parallelEngines[1]
}
return nil
}()
let configuredFallback: TranslationEngineType? = {
guard fallbackEnabled else { return nil }
if parallelEngines.count > 1, parallelEngines[1] != preferredEngine {
return parallelEngines[1]
}
return nil
}()

Comment on lines +527 to +531
if hasFailedSlot {
throw TranslationProviderError.translationFailed(
"\(provider.name) returned invalid or empty translations"
)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
新的批量翻译语义过于严格:只要批中任一条译文经 sanitizeTranslation 还原为原文(如 LLM 对某段输出为空或泄漏了 JSON 结构),整批立即抛错,丢弃其余 N-1 条已成功译文,并触发 translateWithFallback 用回退引擎重译整批(重复消耗配额并增加延迟)。另外 LLM 批量路径以 "\n---\n" 拆分输出(LLMTranslationProvider.swift:117),若任一段译文本身含有 '---'(如 Markdown 内容),拆分数量不匹配也会导致整批 throw。建议:数量不匹配时优先重试当前引擎;对单条 sanitize 失败的槽位保留原文作为该条结果而非整批失败,或至少缩小 throw 条件。

Suggestion:

Suggested change
if hasFailedSlot {
throw TranslationProviderError.translationFailed(
"\(provider.name) returned invalid or empty translations"
)
}
if hasFailedSlot {
logger.error("\(provider.name) returned invalid or empty translations for some segments")
}
return sanitized.map { result in
result ?? TranslationResult(
sourceText: "",
translatedText: "",
sourceLanguage: sourceLanguage ?? "auto",
targetLanguage: targetLanguage
)
}

Comment on lines +533 to +540
return sanitized.map { result in
result ?? TranslationResult(
sourceText: "",
translatedText: "",
sourceLanguage: sourceLanguage ?? "auto",
targetLanguage: targetLanguage
)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
此处 map 的 result ?? ... 兜底分支实际不可达:hasFailedSlot 为 true 时已提前 throw,为 false 时 sanitized 中不含 nil。死代码会误导后续维护者以为此处仍可能有缺失槽位,建议移除兜底并直接返回非可选结果(或将 hasFailedSlot 检查与兜底逻辑二选一)。

Suggestion:

Suggested change
return sanitized.map { result in
result ?? TranslationResult(
sourceText: "",
translatedText: "",
sourceLanguage: sourceLanguage ?? "auto",
targetLanguage: targetLanguage
)
}
return sanitized.compactMap { $0 }

Comment on lines +63 to +70
overrepresentedTexts.insert(text)
// Log only safe statistics: length, count, threshold
logger?(text.count, count, percentageThreshold)
}
}

// Second pass: deduplicate
var seenTexts = Set<String>() // For overrepresented texts, only keep first
var seenSignatures = Set<String>() // For normal texts, use position-based signature
// Deduplicate using text+position signature ONLY.
// Do NOT collapse same-text segments at different positions —
// those are legitimate repeated UI elements (buttons, table cells).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
改为仅按文本+位置签名去重后,overrepresentedTexts 及其依赖的 textCounts/threshold 计算结果已不再影响输出,只用于日志。若保留幻觉抑制意图,这些变量成了死代码;若该行为已由调用方/上游变更取代(见 TranslationService 等改动),建议移除相关计算与 config 字段引用,避免误导后续维护者以为百分比阈值仍参与过滤。

Suggestion:

Suggested change
overrepresentedTexts.insert(text)
// Log only safe statistics: length, count, threshold
logger?(text.count, count, percentageThreshold)
}
}
// Second pass: deduplicate
var seenTexts = Set<String>() // For overrepresented texts, only keep first
var seenSignatures = Set<String>() // For normal texts, use position-based signature
// Deduplicate using text+position signature ONLY.
// Do NOT collapse same-text segments at different positions —
// those are legitimate repeated UI elements (buttons, table cells).
for (text, count) in textCounts {
if count > percentageThreshold {
logger?(text.count, count, percentageThreshold)
}
}

- Add Notarize & Staple step between app signing and Sparkle DMG signing
- Submit .app ZIP to Apple notarytool, wait, and staple the ticket
- Recreate DMG with stapled app, then notarize and staple the DMG itself
- Verify with stapler validate and spctl --assess
- Gracefully skip if secrets missing or app is ad-hoc signed
Comment on lines +241 to +243
- name: Notarize & Staple App
id: notarize
env:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other · medium
本步骤包含两次 notarytool submit --wait --timeout 30m,最坏情况可运行约 1 小时以上,而该 job 未设置 timeout-minutes(全文件均未配置),公证服务延迟时会长时间占用 runner。建议为 job(或至少此步骤)设置合理的超时。

Suggestion:

Suggested change
- name: Notarize & Staple App
id: notarize
env:
- name: Notarize & Staple App
id: notarize
timeout-minutes: 90
env:

Comment on lines +251 to +255
if [ -z "$APPLE_ID" ] || [ -z "$APPLE_APP_SPECIFIC_PASSWORD" ] || [ -z "$APPLE_TEAM_ID" ]; then
echo "Warning: Notarization secrets not configured, skipping notarization"
echo "notarized=false" >> $GITHUB_OUTPUT
exit 0
fi

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
notarized 输出从未被下游步骤消费:当 secrets 缺失或为 ad-hoc 签名时本步骤静默跳过(notarized=false),但后续 "Sign DMG for Sparkle"、生成 appcast 和上传发布步骤均无 if: steps.notarize.outputs.notarized == 'true' 之类的分支,未公证产物会被正常发布且无失败提示。若这是有意的降级行为,至少应在发布说明中标注;否则应让后续步骤感知该标记。

Comment on lines +284 to +286
echo "Recreating DMG with stapled app..."
DMG_FILE="${{ env.PROJECT_NAME }}-${VERSION}.dmg"
ARM64_DMG_FILE="${{ env.PROJECT_NAME }}-${VERSION}-arm64.dmg"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
本步骤的 DMG 文件名(DMG_FILE / ARM64_DMG_FILE)与上游 create_dmg 步骤硬编码重复。若上游命名变更而此处遗漏同步,公证后的 DMG 将不会覆盖原产物,发布会退回未公证版本。建议将 DMG 文件名通过 create_dmg 的 outputs(如 dmg_file)传递复用。

Comment on lines +310 to +311
xcrun stapler staple "$DMG_FILE"
cp "$DMG_FILE" "$ARM64_DMG_FILE"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · low
DMG 公证提交了 zip 包但未像 App 那样对 DMG 做最终校验(仅 staple 成功即视为通过)。建议在 xcrun stapler staple "$DMG_FILE" 后追加 xcrun stapler validate "$DMG_FILE",以便及时发现公证日志中存在 warning 的问题(warning 状态下 staple 会失败但易被误解)。

Suggestion:

Suggested change
xcrun stapler staple "$DMG_FILE"
cp "$DMG_FILE" "$ARM64_DMG_FILE"
xcrun stapler staple "$DMG_FILE"
xcrun stapler validate "$DMG_FILE"
cp "$DMG_FILE" "$ARM64_DMG_FILE"

Comment on lines +313 to +316
rm -rf dmg_temp
rm -f "$ZIP_PATH" "$DMG_ZIP"

echo "notarized=true" >> $GITHUB_OUTPUT

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
公证成功后 DMG 被重建(Notarize & Staple App 步骤重新 hdiutil create),文件大小必然变化,但后续 appcast 使用的是 steps.create_dmg.outputs.dmg_size(即公证前旧 DMG 的大小),导致 enclosure length 与实际发布产物不一致;Sparkle 的 appcast 中 length 错误可能影响更新下载校验。应在公证步骤重建 DMG 后重新计算并输出 dmg_size,或让后续步骤读取 notarize 步骤输出的新尺寸。

Suggestion:

Suggested change
rm -rf dmg_temp
rm -f "$ZIP_PATH" "$DMG_ZIP"
echo "notarized=true" >> $GITHUB_OUTPUT
rm -rf dmg_temp
rm -f "$ZIP_PATH" "$DMG_ZIP"
# DMG was rebuilt after stapling; refresh size for the appcast enclosure
DMG_SIZE=$(stat -f%z "$DMG_FILE")
echo "dmg_size=$DMG_SIZE" >> $GITHUB_OUTPUT
echo "notarized=true" >> $GITHUB_OUTPUT

Comment on lines +48 to +54
let estimatedStripHeight = fontSize * 1.6 + 4
let y: CGFloat
if belowY + estimatedStripHeight < displaySize.height {
y = belowY
} else {
y = max(0, boundingBox.minY * displaySize.height - estimatedStripHeight - 1)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
estimatedStripHeight 按 fontSize*1.6+4 只估算单行条带,而实际条带高度来自 translationStrip 中换行后的 measured.height+4。当译文较长发生多行换行时,向上回退放置的 y 仍按单行高度计算,实际绘制的条带会向上超出画布顶部被裁剪,或覆盖上方相邻的原文文本。建议用实际测量高度决定放置方向(先测量再布局),或按预估行数估算高度。

Suggestion:

Suggested change
let estimatedStripHeight = fontSize * 1.6 + 4
let y: CGFloat
if belowY + estimatedStripHeight < displaySize.height {
y = belowY
} else {
y = max(0, boundingBox.minY * displaySize.height - estimatedStripHeight - 1)
}
// 用实际测量高度决定放置方向,避免多行译文向上溢出画布或遮挡上方原文
let measured = (text as NSString).boundingRect(
with: CGSize(width: max(stripWidth - 8, 1), height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: [.font: NSFont.systemFont(ofSize: fontSize, weight: .medium)]
).height + 4
let y: CGFloat
if belowY + measured < displaySize.height {
y = belowY
} else {
y = max(0, boundingBox.minY * displaySize.height - measured - 1)
}

Comment on lines +180 to +181
let translatedText = transResult.compactMap { $0["dst"] as? String }
.joined(separator: "\n")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
compactMap 会静默丢弃缺少 "dst" 字段的 trans_result 条目:多行输入时 Baidu 按行返回数组,若某一行 dst 缺失或类型异常,返回的译文行数将少于输入行数,造成下游行级对齐错位且无任何错误提示。既然本改动已把数量匹配作为契约(TranslationService 中数量不符即抛错),这里至少应校验 compactMap 结果数量与 transResult 一致,否则直接抛 translationFailed。

Suggestion:

Suggested change
let translatedText = transResult.compactMap { $0["dst"] as? String }
.joined(separator: "\n")
let dstLines = transResult.map { $0["dst"] as? String }
guard !dstLines.contains(nil) else {
throw TranslationProviderError.translationFailed("Baidu response has missing 'dst' entries")
}
let translatedText = dstLines.compactMap { $0 }.joined(separator: "\n")

Comment on lines +69 to +75
let configuredFallback: TranslationEngineType? = {
guard fallbackEnabled else { return nil }
if parallelEngines.count > 1 {
return parallelEngines[1]
}
return nil
}()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
当 fallbackEngine 取自 parallelEngines[1] 且恰好等于 primaryEngine(用户并行引擎列表中包含主引擎,配置无去重保证,场景绑定与 parallelEngines 相互独立,重复可达)时,下方 guard actualFallback != primaryEngine 会直接抛出 allEnginesFailed,跳过了 scene 绑定的 fallbackEngine 或 apple/mtranServer 默认回退。同理,若 parallelEngines[1] 在用户设置中被禁用,filterEnabledEngines 返回空也会直接失败,而旧逻辑会退回场景默认回退引擎。建议在选择 configuredFallback 时即排除 primaryEngine,或在 guard 失败时回退到 scene/默认回退引擎而非直接抛错。

Suggestion:

Suggested change
let configuredFallback: TranslationEngineType? = {
guard fallbackEnabled else { return nil }
if parallelEngines.count > 1 {
return parallelEngines[1]
}
return nil
}()
let configuredFallback: TranslationEngineType? = {
guard fallbackEnabled else { return nil }
if parallelEngines.count > 1, parallelEngines[1] != preferredEngine {
return parallelEngines[1]
}
return nil
}()

Comment on lines +515 to +518
let cleaned = self.sanitizeTranslation(translated: res.translatedText, source: res.sourceText)
if cleaned == res.sourceText, res.translatedText != res.sourceText {
hasFailedSlot = true
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
此处将「清洗后译文等于原文」一律视为翻译失败并抛错,但存在合法的假阳性场景:当译文本来就应该与原文相同(如专有名词、代码标识符、数字、单词 "OK" 等未被翻译的内容)时,sanitizeTranslation 会原样返回 translated,cleaned == res.sourceText 成立,导致整批请求被误判为失败并抛出 translationFailed。之前这段逻辑会正常返回结果,改动后会把可成功的翻译整体判为失败(在 primaryWithFallback 模式下还会触发不必要的 fallback 重试)。建议仅在译文为空或被 JSON 清洗回退时判失败,例如让 sanitizeTranslation 返回是否发生了回退的标记,而不是用文本相等来推断。

Suggestion:

Suggested change
let cleaned = self.sanitizeTranslation(translated: res.translatedText, source: res.sourceText)
if cleaned == res.sourceText, res.translatedText != res.sourceText {
hasFailedSlot = true
}
let (cleaned, wasReverted) = sanitizeTranslation(translated: res.translatedText, source: res.sourceText)
if wasReverted {
hasFailedSlot = true
}

Comment on lines +63 to +70
overrepresentedTexts.insert(text)
// Log only safe statistics: length, count, threshold
logger?(text.count, count, percentageThreshold)
}
}

// Second pass: deduplicate
var seenTexts = Set<String>() // For overrepresented texts, only keep first
var seenSignatures = Set<String>() // For normal texts, use position-based signature
// Deduplicate using text+position signature ONLY.
// Do NOT collapse same-text segments at different positions —
// those are legitimate repeated UI elements (buttons, table cells).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
去重逻辑改为仅基于 text+position 签名后,overrepresentedTexts 的计算结果不再参与任何过滤决策,成为死代码;连带 config.percentageMultiplier / minCountThreshold 配置也失去实际作用。建议删除该计算(或保留 logger 统计所需的阈值逻辑并注明仅用于诊断),避免误导后续维护者认为幻觉过滤仍在生效。

Suggestion:

Suggested change
overrepresentedTexts.insert(text)
// Log only safe statistics: length, count, threshold
logger?(text.count, count, percentageThreshold)
}
}
// Second pass: deduplicate
var seenTexts = Set<String>() // For overrepresented texts, only keep first
var seenSignatures = Set<String>() // For normal texts, use position-based signature
// Deduplicate using text+position signature ONLY.
// Do NOT collapse same-text segments at different positions —
// those are legitimate repeated UI elements (buttons, table cells).
for (text, count) in textCounts {
if count > percentageThreshold {
// Log only safe statistics: length, count, threshold
logger?(text.count, count, percentageThreshold)
}
}

- Reset isStartingCapture on full-screen early return (CaptureSessionController)
- Reset isPerformingOCR/isTranslating on crop invalidation (PreviewViewModel+Crop)
- Fix appendingAPISuffix infinite loop on trailing-slash URLs (LLMTranslationProvider)
- Distinguish valid unchanged translations from broken output (TranslationService)
- Update appcast DMG size after notarization rebuild (release.yml)
- Remove dead presentationID property (TextTranslationPopupWindow)
- Remove dead overrepresentedTexts computation (VLMTextDeduplicator)
Comment on lines +241 to +242
- name: Notarize & Staple App
id: notarize

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other · medium
release.yml 的 build job 未设置 timeout-minutes。新增的公证步骤包含两次 notarytool submit(--timeout 30m),加上构建、签名、发布,最坏情况下 job 可运行极长时间且无兜底上限,异常挂起时会持续占用 runner 资源。建议为 job 声明 timeout-minutes: 60 左右的合理上限。

Suggestion:

Suggested change
- name: Notarize & Staple App
id: notarize
jobs:
build:
runs-on: macos-15
timeout-minutes: 60

Comment on lines +252 to +254
echo "Warning: Notarization secrets not configured, skipping notarization"
echo "notarized=false" >> $GITHUB_OUTPUT
exit 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
跳过公证的分支只输出 notarized=false 而未设置 dmg_size,依赖下游 steps.notarize.outputs.dmg_size || steps.create_dmg.outputs.dmg_size 的隐式回退;且 notarized 输出在后续任何步骤中均未被消费。建议跳过分支同样输出 dmg_size 保持输出自洽,或删除无人使用的 notarized 输出。

Suggestion:

Suggested change
echo "Warning: Notarization secrets not configured, skipping notarization"
echo "notarized=false" >> $GITHUB_OUTPUT
exit 0
echo "Warning: Notarization secrets not configured, skipping notarization"
echo "notarized=false" >> $GITHUB_OUTPUT
echo "dmg_size=$(stat -f%z "${{ env.PROJECT_NAME }}-${VERSION}.dmg")" >> $GITHUB_OUTPUT
exit 0

Comment on lines +268 to +273
xcrun notarytool submit "$ZIP_PATH" \
--apple-id "$APPLE_ID" \
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
--team-id "$APPLE_TEAM_ID" \
--wait \
--timeout 30m

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · medium
公证为可选能力(secrets 缺失或 ad-hoc 签名时可跳过),但 notarytool submit 失败(如 --timeout 30m 超时、Apple 服务临时不可用)会导致整个 release job 中止,已构建签名的产物无法发布。行为不一致:跳过是优雅降级,失败却是硬失败。建议对 notarytool submit 增加重试机制,或明确失败降级策略。

Suggestion:

Suggested change
xcrun notarytool submit "$ZIP_PATH" \
--apple-id "$APPLE_ID" \
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
--team-id "$APPLE_TEAM_ID" \
--wait \
--timeout 30m
for i in 1 2 3; do
if xcrun notarytool submit "$ZIP_PATH" \
--keychain-profile "NOTARY_PROFILE" \
--wait --timeout 30m; then
break
fi
[ "$i" = "3" ] && exit 1
echo "Notarization attempt $i failed, retrying in 60s..."
sleep 60
done

Comment on lines +268 to +273
xcrun notarytool submit "$ZIP_PATH" \
--apple-id "$APPLE_ID" \
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
--team-id "$APPLE_TEAM_ID" \
--wait \
--timeout 30m

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security · low
公证凭据通过命令行参数传递给 notarytool,可能通过进程列表或 verbose 日志暴露。建议预先使用 xcrun notarytool store-credentials 将凭据存入 keychain profile,之后提交时仅引用 profile 名称,凭据不再出现在命令行中。

Suggestion:

Suggested change
xcrun notarytool submit "$ZIP_PATH" \
--apple-id "$APPLE_ID" \
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
--team-id "$APPLE_TEAM_ID" \
--wait \
--timeout 30m
xcrun notarytool store-credentials NOTARY_PROFILE \
--apple-id "$APPLE_ID" \
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
--team-id "$APPLE_TEAM_ID"
xcrun notarytool submit "$ZIP_PATH" \
--keychain-profile "NOTARY_PROFILE" \
--wait \
--timeout 30m

Comment on lines +288 to +295
mkdir -p dmg_temp
cp -R "$APP_PATH" dmg_temp/
ln -sf /Applications dmg_temp/Applications

hdiutil create -volname "${{ env.PROJECT_NAME }}" \
-srcfolder dmg_temp \
-ov -format UDZO \
"$DMG_FILE"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
此处重建 DMG 的逻辑(mkdir dmg_temp / cp app / ln Applications / hdiutil create / cp arm64 副本)与上方 create_dmg 步骤几乎完全重复。若日后 DMG 结构调整(如添加 LICENSE、更改布局),两处极易失同步导致公证版与未公证版 DMG 内容不一致。建议抽取为可复用的脚本或 composite action。

Suggestion:

Suggested change
mkdir -p dmg_temp
cp -R "$APP_PATH" dmg_temp/
ln -sf /Applications dmg_temp/Applications
hdiutil create -volname "${{ env.PROJECT_NAME }}" \
-srcfolder dmg_temp \
-ov -format UDZO \
"$DMG_FILE"
# Reuse the same DMG-building logic as the create_dmg step
# (extract to a shared script, e.g. .github/scripts/build_dmg.sh)
.github/scripts/build_dmg.sh "$APP_PATH" "$DMG_FILE" "$ARM64_DMG_FILE"

Comment on lines +479 to +481
} else if let first = config.languages.first {
langCode = first.cliValue
} else {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
config.languages 是 Set,Set.first 返回值在每次运行中不确定(Swift Set 无稳定顺序)。当用户选择多种语言(如 english + french)时,fast 模式会随机选择其中一个语言的模型,导致 OCR 行为不可复现。建议定义确定性的优先级顺序(如固定数组按优先级选取第一个匹配语言),或与旧行为一致在非中文时回退到 "en"。

Suggestion:

Suggested change
} else if let first = config.languages.first {
langCode = first.cliValue
} else {
} else if let first = [.english, .japanese, .korean, .french, .german]
.first(where: config.languages.contains) {
langCode = first.cliValue
} else {

Comment on lines +180 to +181
let translatedText = transResult.compactMap { $0["dst"] as? String }
.joined(separator: "\n")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
compactMap 静默丢弃 dst 缺失或非 String 的段落后再按 "\n" 拼接,会导致多行输入时译文行与源文本行错位(某段丢失后,后续行的译文对应到前一行的源文),且上游对返回文本不做行数校验,无法发现。建议任一段 dst 缺失时直接抛出 translationFailed,保持失败可检测。

Suggestion:

Suggested change
let translatedText = transResult.compactMap { $0["dst"] as? String }
.joined(separator: "\n")
let parts = transResult.map { $0["dst"] as? String }
guard parts.allSatisfy({ $0 != nil }) else {
throw TranslationProviderError.translationFailed("Baidu response missing dst for some segments")
}
let translatedText = parts.compactMap { $0 }.joined(separator: "\n")

Comment on lines +34 to +39
// If user supplied only the host/version root (e.g. .../v2), append /translate.
let trimmed = raw.hasSuffix("/") ? String(raw.dropLast()) : raw
if trimmed.hasSuffix("/translate") {
return trimmed
}
return trimmed + "/translate"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
对自定义 baseURL 无条件追加 "/translate" 属于行为变更:旧实现将自定义 URL 原样使用,允许用户配置不带 /translate 后缀的自定义代理/网关端点。新逻辑会把诸如 ".../deepl-proxy/api" 改写为 ".../deepl-proxy/api/translate",破坏原本可用的自定义端点。建议仅对官方默认 URL(或明确以 /v2 结尾的 URL)做自动补全,或提供配置项明确禁用该补全。

Suggestion:

Suggested change
// If user supplied only the host/version root (e.g. .../v2), append /translate.
let trimmed = raw.hasSuffix("/") ? String(raw.dropLast()) : raw
if trimmed.hasSuffix("/translate") {
return trimmed
}
return trimmed + "/translate"
// Only auto-complete /translate for URLs that look like the official API root
if customURL == nil { return "https://api.deepl.com/v2/translate" }
let trimmed = raw.hasSuffix("/") ? String(raw.dropLast()) : raw
return trimmed.hasSuffix("/translate") ? trimmed : trimmed + "/translate"

Comment on lines +612 to +617
let allStructural = trimmed.allSatisfy { char in
char == "{" || char == "}" || char == "\"" || char == "'" || char == "`" ||
char == "[" || char == "]" || char == ":" || char == "," ||
char == "“" || char == "”" || char == "‘" || char == "’" ||
char.isWhitespace || char.isNumber
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
isLikelyBrokenTranslation 将「仅由数字/标点/空白组成」的输出判定为失败,但这可能是合法译文:例如源文 "一百" → "100"、"一万" → "10,000"、日期/金额/编号等纯数字译文是常见且正确的翻译结果。此时 translatedText != sourceText 且命中 allStructural,整个批次会被误判为 translationFailed 而抛错(经 fallback 后可能整体失败)。建议从 allStructural 集合中移除 char.isNumber(或仅当输出为空/纯 JSON 结构时判失败),避免把合法译文当作损坏输出。

Suggestion:

Suggested change
let allStructural = trimmed.allSatisfy { char in
char == "{" || char == "}" || char == "\"" || char == "'" || char == "`" ||
char == "[" || char == "]" || char == ":" || char == "," ||
char == "“" || char == "”" || char == "‘" || char == "’" ||
char.isWhitespace || char.isNumber
}
let allStructural = trimmed.allSatisfy { char in
char == "{" || char == "}" || char == "\"" || char == "'" || char == "`" ||
char == "[" || char == "]" || char == ":" || char == "," ||
char == "“" || char == "”" || char == "‘" || char == "’" ||
char.isWhitespace
}

@hubo1989
hubo1989 merged commit 601398e into main Oct 27, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant