Repository navigation
fix(translation): fix 15 root causes of low translation efficiency and success rate - #82
Conversation
…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
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
| defer { | ||
| if currentGeneration == analysisGeneration { | ||
| isPerformingOCR = false | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
| while url.absoluteString.hasSuffix("/") { | ||
| url.deleteLastPathComponent() |
There was a problem hiding this comment.
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 👍 / 👎.
| let cleaned = self.sanitizeTranslation(translated: res.translatedText, source: res.sourceText) | ||
| if cleaned == res.sourceText, res.translatedText != res.sourceText { | ||
| hasFailedSlot = true | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
| } else if let first = settings.parallelEngines.first { | ||
| preferredEngine = first |
There was a problem hiding this comment.
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 👍 / 👎.
|
🔍 OpenCodeReview found 11 issue(s) in this PR.
📄
|
| ocrTask?.cancel() | ||
| translationTask?.cancel() | ||
| analysisGeneration &+= 1 | ||
| ocrResult = nil | ||
| bilingualSegments = [] |
There was a problem hiding this comment.
裁剪路径取消 ocrTask/translationTask 并递增 generation 后,被取消任务的 defer 因 generation 不匹配会跳过复位 isPerformingOCR/isTranslating,而此处也未显式复位这两个标志。结果:裁剪时若有 OCR/翻译在途,加载标志永久残留为 true,之后 performOCR()(guard !isPerformingOCR)与 performTranslation()(guard !isTranslating)都会被静默拦截。请在取消的同时复位这两个状态标志。
Suggestion:
| ocrTask?.cancel() | |
| translationTask?.cancel() | |
| analysisGeneration &+= 1 | |
| ocrResult = nil | |
| bilingualSegments = [] | |
| ocrTask?.cancel() | |
| translationTask?.cancel() | |
| analysisGeneration &+= 1 | |
| ocrResult = nil | |
| bilingualSegments = [] | |
| isPerformingOCR = false | |
| isTranslating = false |
| 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 |
There was a problem hiding this comment.
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:
| 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() |
| 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) | ||
| } |
There was a problem hiding this comment.
贴底回退分支将译文放在原文上方,但 estimatedStripHeight 是按单行估算的(fontSize * 1.6 + 4),而实际条带高度由 translationStrip 中按 maxWidth 换行后的测量结果决定,长译文换行成多行时实际高度可能显著大于估算值,导致译文条带与原文重叠。可考虑用真实测量高度(或在 translationStrip 中对越界条带做二次位置修正)而非仅用估算值决策。
Suggestion:
| 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 |
| } else if let first = config.languages.first { | ||
| langCode = first.cliValue | ||
| } else { | ||
| langCode = "ch" | ||
| } |
There was a problem hiding this comment.
Set 无固定顺序:当 config.languages 不含 .chinese 时,使用 Set.first 作为回退语言,Set 的 first 顺序在跨进程运行间不保证一致,相同配置可能在不同运行中选中不同语言,导致 OCR 结果不确定。建议配置为有序数组,或按 Language.allCases 的固定优先级选择。
Suggestion:
| } 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" | |
| } |
| // 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" |
There was a problem hiding this comment.
旧实现中自定义 baseURL 被视为完整请求 endpoint 直接使用;新实现会对所有不以 "/translate" 结尾的自定义 URL 强制追加 "/translate"。这会破坏既有用户配置:例如已配置第三方代理的完整转发地址(如 https://proxy.example.com/deepl,代理内部再路由到 DeepL /v2/translate)的存量用户,升级后请求会打到 .../deepl/translate 而失败。若需保留自动补全,建议仅对识别为 host/version 根(如以 /v2 或 /v2/ 结尾)的 URL 追加,或在配置界面提示该契约变更。
| let configuredFallback: TranslationEngineType? = { | ||
| guard fallbackEnabled else { return nil } | ||
| if parallelEngines.count > 1 { | ||
| return parallelEngines[1] | ||
| } | ||
| return nil | ||
| }() |
There was a problem hiding this comment.
当调用方传入的 preferredEngine 恰好等于 parallelEngines1时,这里会把配置的第二引擎作为 fallbackEngine 传入,随后 translateWithFallback 中新增的 guard actualFallback != primaryEngine 会直接抛出 allEnginesFailed——原本会回退到场景默认引擎或 apple/mtranServer 的恢复路径完全丢失,一次主引擎瞬时失败即导致整批翻译失败。建议在两者相同时返回 nil,让 translateWithFallback 走场景默认/内置回退逻辑。
Suggestion:
| 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 | |
| }() |
| if hasFailedSlot { | ||
| throw TranslationProviderError.translationFailed( | ||
| "\(provider.name) returned invalid or empty translations" | ||
| ) | ||
| } |
There was a problem hiding this comment.
新的批量翻译语义过于严格:只要批中任一条译文经 sanitizeTranslation 还原为原文(如 LLM 对某段输出为空或泄漏了 JSON 结构),整批立即抛错,丢弃其余 N-1 条已成功译文,并触发 translateWithFallback 用回退引擎重译整批(重复消耗配额并增加延迟)。另外 LLM 批量路径以 "\n---\n" 拆分输出(LLMTranslationProvider.swift:117),若任一段译文本身含有 '---'(如 Markdown 内容),拆分数量不匹配也会导致整批 throw。建议:数量不匹配时优先重试当前引擎;对单条 sanitize 失败的槽位保留原文作为该条结果而非整批失败,或至少缩小 throw 条件。
Suggestion:
| 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 | |
| ) | |
| } |
| return sanitized.map { result in | ||
| result ?? TranslationResult( | ||
| sourceText: "", | ||
| translatedText: "", | ||
| sourceLanguage: sourceLanguage ?? "auto", | ||
| targetLanguage: targetLanguage | ||
| ) | ||
| } |
There was a problem hiding this comment.
此处 map 的 result ?? ... 兜底分支实际不可达:hasFailedSlot 为 true 时已提前 throw,为 false 时 sanitized 中不含 nil。死代码会误导后续维护者以为此处仍可能有缺失槽位,建议移除兜底并直接返回非可选结果(或将 hasFailedSlot 检查与兜底逻辑二选一)。
Suggestion:
| return sanitized.map { result in | |
| result ?? TranslationResult( | |
| sourceText: "", | |
| translatedText: "", | |
| sourceLanguage: sourceLanguage ?? "auto", | |
| targetLanguage: targetLanguage | |
| ) | |
| } | |
| return sanitized.compactMap { $0 } |
| 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). |
There was a problem hiding this comment.
改为仅按文本+位置签名去重后,overrepresentedTexts 及其依赖的 textCounts/threshold 计算结果已不再影响输出,只用于日志。若保留幻觉抑制意图,这些变量成了死代码;若该行为已由调用方/上游变更取代(见 TranslationService 等改动),建议移除相关计算与 config 字段引用,避免误导后续维护者以为百分比阈值仍参与过滤。
Suggestion:
| 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
| - name: Notarize & Staple App | ||
| id: notarize | ||
| env: |
There was a problem hiding this comment.
| 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 |
| echo "Recreating DMG with stapled app..." | ||
| DMG_FILE="${{ env.PROJECT_NAME }}-${VERSION}.dmg" | ||
| ARM64_DMG_FILE="${{ env.PROJECT_NAME }}-${VERSION}-arm64.dmg" |
| xcrun stapler staple "$DMG_FILE" | ||
| cp "$DMG_FILE" "$ARM64_DMG_FILE" |
There was a problem hiding this comment.
DMG 公证提交了 zip 包但未像 App 那样对 DMG 做最终校验(仅 staple 成功即视为通过)。建议在 xcrun stapler staple "$DMG_FILE" 后追加 xcrun stapler validate "$DMG_FILE",以便及时发现公证日志中存在 warning 的问题(warning 状态下 staple 会失败但易被误解)。
Suggestion:
| 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" |
| rm -rf dmg_temp | ||
| rm -f "$ZIP_PATH" "$DMG_ZIP" | ||
|
|
||
| echo "notarized=true" >> $GITHUB_OUTPUT |
There was a problem hiding this comment.
公证成功后 DMG 被重建(Notarize & Staple App 步骤重新 hdiutil create),文件大小必然变化,但后续 appcast 使用的是 steps.create_dmg.outputs.dmg_size(即公证前旧 DMG 的大小),导致 enclosure length 与实际发布产物不一致;Sparkle 的 appcast 中 length 错误可能影响更新下载校验。应在公证步骤重建 DMG 后重新计算并输出 dmg_size,或让后续步骤读取 notarize 步骤输出的新尺寸。
Suggestion:
| 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 |
| 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) | ||
| } |
There was a problem hiding this comment.
estimatedStripHeight 按 fontSize*1.6+4 只估算单行条带,而实际条带高度来自 translationStrip 中换行后的 measured.height+4。当译文较长发生多行换行时,向上回退放置的 y 仍按单行高度计算,实际绘制的条带会向上超出画布顶部被裁剪,或覆盖上方相邻的原文文本。建议用实际测量高度决定放置方向(先测量再布局),或按预估行数估算高度。
Suggestion:
| 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) | |
| } |
| let translatedText = transResult.compactMap { $0["dst"] as? String } | ||
| .joined(separator: "\n") |
There was a problem hiding this comment.
compactMap 会静默丢弃缺少 "dst" 字段的 trans_result 条目:多行输入时 Baidu 按行返回数组,若某一行 dst 缺失或类型异常,返回的译文行数将少于输入行数,造成下游行级对齐错位且无任何错误提示。既然本改动已把数量匹配作为契约(TranslationService 中数量不符即抛错),这里至少应校验 compactMap 结果数量与 transResult 一致,否则直接抛 translationFailed。
Suggestion:
| 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") |
| let configuredFallback: TranslationEngineType? = { | ||
| guard fallbackEnabled else { return nil } | ||
| if parallelEngines.count > 1 { | ||
| return parallelEngines[1] | ||
| } | ||
| return nil | ||
| }() |
There was a problem hiding this comment.
当 fallbackEngine 取自 parallelEngines[1] 且恰好等于 primaryEngine(用户并行引擎列表中包含主引擎,配置无去重保证,场景绑定与 parallelEngines 相互独立,重复可达)时,下方 guard actualFallback != primaryEngine 会直接抛出 allEnginesFailed,跳过了 scene 绑定的 fallbackEngine 或 apple/mtranServer 默认回退。同理,若 parallelEngines[1] 在用户设置中被禁用,filterEnabledEngines 返回空也会直接失败,而旧逻辑会退回场景默认回退引擎。建议在选择 configuredFallback 时即排除 primaryEngine,或在 guard 失败时回退到 scene/默认回退引擎而非直接抛错。
Suggestion:
| 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 | |
| }() |
| let cleaned = self.sanitizeTranslation(translated: res.translatedText, source: res.sourceText) | ||
| if cleaned == res.sourceText, res.translatedText != res.sourceText { | ||
| hasFailedSlot = true | ||
| } |
There was a problem hiding this comment.
此处将「清洗后译文等于原文」一律视为翻译失败并抛错,但存在合法的假阳性场景:当译文本来就应该与原文相同(如专有名词、代码标识符、数字、单词 "OK" 等未被翻译的内容)时,sanitizeTranslation 会原样返回 translated,cleaned == res.sourceText 成立,导致整批请求被误判为失败并抛出 translationFailed。之前这段逻辑会正常返回结果,改动后会把可成功的翻译整体判为失败(在 primaryWithFallback 模式下还会触发不必要的 fallback 重试)。建议仅在译文为空或被 JSON 清洗回退时判失败,例如让 sanitizeTranslation 返回是否发生了回退的标记,而不是用文本相等来推断。
Suggestion:
| 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 | |
| } |
| 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). |
There was a problem hiding this comment.
去重逻辑改为仅基于 text+position 签名后,overrepresentedTexts 的计算结果不再参与任何过滤决策,成为死代码;连带 config.percentageMultiplier / minCountThreshold 配置也失去实际作用。建议删除该计算(或保留 logger 统计所需的阈值逻辑并注明仅用于诊断),避免误导后续维护者认为幻觉过滤仍在生效。
Suggestion:
| 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)
| - name: Notarize & Staple App | ||
| id: notarize |
There was a problem hiding this comment.
release.yml 的 build job 未设置 timeout-minutes。新增的公证步骤包含两次 notarytool submit(--timeout 30m),加上构建、签名、发布,最坏情况下 job 可运行极长时间且无兜底上限,异常挂起时会持续占用 runner 资源。建议为 job 声明 timeout-minutes: 60 左右的合理上限。
Suggestion:
| - name: Notarize & Staple App | |
| id: notarize | |
| jobs: | |
| build: | |
| runs-on: macos-15 | |
| timeout-minutes: 60 |
| echo "Warning: Notarization secrets not configured, skipping notarization" | ||
| echo "notarized=false" >> $GITHUB_OUTPUT | ||
| exit 0 |
There was a problem hiding this comment.
跳过公证的分支只输出 notarized=false 而未设置 dmg_size,依赖下游 steps.notarize.outputs.dmg_size || steps.create_dmg.outputs.dmg_size 的隐式回退;且 notarized 输出在后续任何步骤中均未被消费。建议跳过分支同样输出 dmg_size 保持输出自洽,或删除无人使用的 notarized 输出。
Suggestion:
| 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 |
| xcrun notarytool submit "$ZIP_PATH" \ | ||
| --apple-id "$APPLE_ID" \ | ||
| --password "$APPLE_APP_SPECIFIC_PASSWORD" \ | ||
| --team-id "$APPLE_TEAM_ID" \ | ||
| --wait \ | ||
| --timeout 30m |
There was a problem hiding this comment.
公证为可选能力(secrets 缺失或 ad-hoc 签名时可跳过),但 notarytool submit 失败(如 --timeout 30m 超时、Apple 服务临时不可用)会导致整个 release job 中止,已构建签名的产物无法发布。行为不一致:跳过是优雅降级,失败却是硬失败。建议对 notarytool submit 增加重试机制,或明确失败降级策略。
Suggestion:
| 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 |
| xcrun notarytool submit "$ZIP_PATH" \ | ||
| --apple-id "$APPLE_ID" \ | ||
| --password "$APPLE_APP_SPECIFIC_PASSWORD" \ | ||
| --team-id "$APPLE_TEAM_ID" \ | ||
| --wait \ | ||
| --timeout 30m |
There was a problem hiding this comment.
公证凭据通过命令行参数传递给 notarytool,可能通过进程列表或 verbose 日志暴露。建议预先使用 xcrun notarytool store-credentials 将凭据存入 keychain profile,之后提交时仅引用 profile 名称,凭据不再出现在命令行中。
Suggestion:
| 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 |
| 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" |
There was a problem hiding this comment.
此处重建 DMG 的逻辑(mkdir dmg_temp / cp app / ln Applications / hdiutil create / cp arm64 副本)与上方 create_dmg 步骤几乎完全重复。若日后 DMG 结构调整(如添加 LICENSE、更改布局),两处极易失同步导致公证版与未公证版 DMG 内容不一致。建议抽取为可复用的脚本或 composite action。
Suggestion:
| 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" |
| } else if let first = config.languages.first { | ||
| langCode = first.cliValue | ||
| } else { |
There was a problem hiding this comment.
config.languages 是 Set,Set.first 返回值在每次运行中不确定(Swift Set 无稳定顺序)。当用户选择多种语言(如 english + french)时,fast 模式会随机选择其中一个语言的模型,导致 OCR 行为不可复现。建议定义确定性的优先级顺序(如固定数组按优先级选取第一个匹配语言),或与旧行为一致在非中文时回退到 "en"。
Suggestion:
| } 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 { |
| let translatedText = transResult.compactMap { $0["dst"] as? String } | ||
| .joined(separator: "\n") |
There was a problem hiding this comment.
compactMap 静默丢弃 dst 缺失或非 String 的段落后再按 "\n" 拼接,会导致多行输入时译文行与源文本行错位(某段丢失后,后续行的译文对应到前一行的源文),且上游对返回文本不做行数校验,无法发现。建议任一段 dst 缺失时直接抛出 translationFailed,保持失败可检测。
Suggestion:
| 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") |
| // 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" |
There was a problem hiding this comment.
对自定义 baseURL 无条件追加 "/translate" 属于行为变更:旧实现将自定义 URL 原样使用,允许用户配置不带 /translate 后缀的自定义代理/网关端点。新逻辑会把诸如 ".../deepl-proxy/api" 改写为 ".../deepl-proxy/api/translate",破坏原本可用的自定义端点。建议仅对官方默认 URL(或明确以 /v2 结尾的 URL)做自动补全,或提供配置项明确禁用该补全。
Suggestion:
| // 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" |
| let allStructural = trimmed.allSatisfy { char in | ||
| char == "{" || char == "}" || char == "\"" || char == "'" || char == "`" || | ||
| char == "[" || char == "]" || char == ":" || char == "," || | ||
| char == "“" || char == "”" || char == "‘" || char == "’" || | ||
| char.isWhitespace || char.isNumber | ||
| } |
There was a problem hiding this comment.
isLikelyBrokenTranslation 将「仅由数字/标点/空白组成」的输出判定为失败,但这可能是合法译文:例如源文 "一百" → "100"、"一万" → "10,000"、日期/金额/编号等纯数字译文是常见且正确的翻译结果。此时 translatedText != sourceText 且命中 allStructural,整个批次会被误判为 translationFailed 而抛错(经 fallback 后可能整体失败)。建议从 allStructural 集合中移除 char.isNumber(或仅当输出为空/纯 JSON 结构时判失败),避免把合法译文当作损坏输出。
Suggestion:
| 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 | |
| } |
Summary
全面审查并修复翻译 pipeline 的效率和成功率问题,覆盖截图翻译、选区内翻译、选中文本、翻译并插入四条生产链路。
Changes Made
端点与配置(开箱即失败)
成功语义与回退
路由与分析
任务生命周期与安全
显示与解析
Testing