Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 81 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,86 @@ jobs:

rm -rf dmg_temp

- name: Notarize & Staple App
id: notarize
Comment on lines +241 to +242

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

env:
Comment on lines +241 to +243

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:

APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
APP_PATH="build/Build/Products/Release/${{ env.PROJECT_NAME }}.app"
VERSION=${{ steps.vars.outputs.version }}

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
Comment on lines +252 to +254

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

fi
Comment on lines +251 to +255

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' 之类的分支,未公证产物会被正常发布且无失败提示。若这是有意的降级行为,至少应在发布说明中标注;否则应让后续步骤感知该标记。


if codesign -dv "$APP_PATH" 2>&1 | grep -q "Signature=adhoc"; then
echo "Warning: App is ad-hoc signed, skipping notarization"
echo "notarized=false" >> $GITHUB_OUTPUT
exit 0
fi

echo "Creating ZIP for notarization submission..."
ZIP_PATH="$RUNNER_TEMP/${{ env.PROJECT_NAME }}-${VERSION}-notarize.zip"
ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"

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

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

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


echo "Stapling notarization ticket to app..."
xcrun stapler staple "$APP_PATH"

echo "Verifying notarization..."
xcrun stapler validate "$APP_PATH"
spctl --assess --type execute --verbose "$APP_PATH"

echo "Notarization complete."

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

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)传递复用。


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"
Comment on lines +288 to +295

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"


cp "$DMG_FILE" "$ARM64_DMG_FILE"

echo "Notarizing DMG..."
DMG_ZIP="$RUNNER_TEMP/${{ env.PROJECT_NAME }}-${VERSION}-dmg.zip"
ditto -c -k --keepParent "$DMG_FILE" "$DMG_ZIP"

xcrun notarytool submit "$DMG_ZIP" \
--apple-id "$APPLE_ID" \
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
--team-id "$APPLE_TEAM_ID" \
--wait \
--timeout 30m

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

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"


rm -rf dmg_temp
rm -f "$ZIP_PATH" "$DMG_ZIP"

# Update DMG size for appcast (may have changed after notarization)
NEW_DMG_SIZE=$(stat -f%z "$DMG_FILE")
echo "dmg_size=$NEW_DMG_SIZE" >> $GITHUB_OUTPUT
echo "notarized=true" >> $GITHUB_OUTPUT
Comment on lines +313 to +319

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


- name: Sign DMG for Sparkle
id: sign_dmg
run: |
Expand Down Expand Up @@ -301,7 +381,7 @@ jobs:
BUILD_NUM="${{ steps.build_number.outputs.build_num }}"
DMG_URL="https://github.com/${{ github.repository }}/releases/download/${{ steps.vars.outputs.tag_name }}/${{ env.PROJECT_NAME }}-${VERSION}.dmg"
PUBDATE="${{ steps.pubdate.outputs.date }}"
DMG_SIZE="${{ steps.create_dmg.outputs.dmg_size }}"
DMG_SIZE="${{ steps.notarize.outputs.dmg_size || steps.create_dmg.outputs.dmg_size }}"
SIGNATURE="${{ steps.sign_dmg.outputs.signature }}"

# Build enclosure tag with or without signature
Expand Down
9 changes: 7 additions & 2 deletions TransFrame/Features/Capture/CaptureSessionController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ final class CaptureSessionController: NSObject, SelectionOverlayDelegate {
private var currentMode: CaptureMode = .region
private var currentSnapshotSet: FrozenSnapshotSet?
private var beautifyConfig: BeautifyConfig?
private var isStartingCapture = false

private var localKeyMonitor: Any?
private var globalKeyMonitor: Any?
Expand All @@ -49,11 +50,12 @@ final class CaptureSessionController: NSObject, SelectionOverlayDelegate {

/// Triggers screen capture session with instant freeze.
func startCapture(mode: CaptureMode = .region) {
// Prevent launching another session if overlays are active
guard activeOverlays.isEmpty else {
// Prevent launching another session if overlays are active or starting
guard activeOverlays.isEmpty, !isStartingCapture else {
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 👍 / 👎.


self.currentMode = mode
let triggerTime = ContinuousClock.now
Expand Down Expand Up @@ -88,6 +90,7 @@ final class CaptureSessionController: NSObject, SelectionOverlayDelegate {
CaptureDocumentStore.shared.register(doc)
self.dispatchAction(.copy, for: doc)
self.onCaptureComplete?(doc)
self.isStartingCapture = false
return
}

Expand Down Expand Up @@ -122,9 +125,11 @@ final class CaptureSessionController: NSObject, SelectionOverlayDelegate {
// Record freeze visible time
self.currentSnapshotSet?.freezeVisibleAt = .now
self.logger.info("All frozen overlays presented successfully")
self.isStartingCapture = false

} catch {
self.logger.error("Failed to start capture session: \(error.localizedDescription)")
self.isStartingCapture = false
self.closeAllOverlays()
}
}
Expand Down
24 changes: 15 additions & 9 deletions TransFrame/Features/Capture/SelectionOverlayWindow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ final class SelectionOverlayView: NSView, SelectionToolbarDelegate, NSTextFieldD
/// In-flight drawer analysis; cancelled on rerun and when the drawer closes
/// so a dismissed overlay keeps no running network work writing into it.
private var inPlaceAnalysisTask: Task<Void, Never>?
private var inPlaceAnalysisGeneration: UInt64 = 0

/// Selection snapshot captured when a click starts outside the current
/// selection; tiny clicks (no drag) must restore it instead of re-picking.
Expand Down Expand Up @@ -1663,9 +1664,8 @@ final class SelectionOverlayView: NSView, SelectionToolbarDelegate, NSTextFieldD

/// Runs OCR or translation on the selection and shows results in the
/// embedded right-side drawer. The capture window stays open.
private func runInPlaceAnalysis(tab: InPlaceResultsModel.Tab, in selectionRect: CGRect) {
// Second click on the same tab closes the drawer (PRD toggle behaviour)
if resultsModel.isVisible, resultsModel.activeTab == tab, !resultsModel.isLoading {
private func runInPlaceAnalysis(tab: InPlaceResultsModel.Tab, in selectionRect: CGRect, forceRerun: Bool = false) {
if !forceRerun, resultsModel.isVisible, resultsModel.activeTab == tab, !resultsModel.isLoading {
hideResultsPanel()
return
}
Expand All @@ -1683,12 +1683,16 @@ final class SelectionOverlayView: NSView, SelectionToolbarDelegate, NSTextFieldD

// Cancel any in-flight run so a slow old result can't overwrite a new one
inPlaceAnalysisTask?.cancel()
inPlaceAnalysisGeneration &+= 1
let generation = inPlaceAnalysisGeneration
inPlaceAnalysisTask = Task { @MainActor [weak self] in
guard let self, !Task.isCancelled else { return }
defer {
self.resultsModel.isLoading = false
self.layoutResultsPanel(for: selectionRect)
self.needsDisplay = true
if self.inPlaceAnalysisGeneration == generation {
self.resultsModel.isLoading = false
self.layoutResultsPanel(for: selectionRect)
self.needsDisplay = true
}
}
do {
switch tab {
Expand All @@ -1712,12 +1716,11 @@ final class SelectionOverlayView: NSView, SelectionToolbarDelegate, NSTextFieldD
case .translate:
let pipeline = ImageTranslationPipeline()
let context = PipelineContext()
// Stage-split so failures are attributed correctly: the
// drawer reads VLM errors as recognition, not translation.
let analysis: ScreenAnalysisResult
do {
analysis = try await pipeline.analyze(image: cropped, context: context)
} catch {
guard self.inPlaceAnalysisGeneration == generation else { return }
self.resultsModel.statusMessage = String(
format: String(localized: "error.pipeline.ocrFailed"),
Self.pipelineErrorMessage(error)
Expand All @@ -1737,15 +1740,18 @@ final class SelectionOverlayView: NSView, SelectionToolbarDelegate, NSTextFieldD
context: context
)
if Task.isCancelled { return }
guard self.inPlaceAnalysisGeneration == generation else { return }
self.resultsModel.segments = segments
} catch {
guard self.inPlaceAnalysisGeneration == generation else { return }
self.resultsModel.statusMessage = String(
format: String(localized: "error.pipeline.translateFailed"),
Self.pipelineErrorMessage(error)
)
}
}
} catch {
guard self.inPlaceAnalysisGeneration == generation else { return }
let message = Self.pipelineErrorMessage(error)
self.resultsModel.statusMessage = message
}
Expand Down Expand Up @@ -1779,7 +1785,7 @@ final class SelectionOverlayView: NSView, SelectionToolbarDelegate, NSTextFieldD
if resultsPanelHost == nil {
resultsModel.onRerun = { [weak self] in
guard let self, case .selected(let rect) = self.state else { return }
self.runInPlaceAnalysis(tab: self.resultsModel.activeTab, in: rect)
self.runInPlaceAnalysis(tab: self.resultsModel.activeTab, in: rect, forceRerun: true)
}
resultsModel.onClose = { [weak self] in
self?.hideResultsPanel()
Expand Down
8 changes: 7 additions & 1 deletion TransFrame/Features/Preview/PreviewViewModel+Crop.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,14 @@ extension PreviewViewModel {
$0.offsetBy(dx: -originShift.x, dy: -originShift.y)
}

// Invalidate OCR cache for the previous crop area
// Invalidate OCR cache and translation results for the previous crop area
ocrTask?.cancel()
translationTask?.cancel()
analysisGeneration &+= 1
isPerformingOCR = false
isTranslating = false
ocrResult = nil
bilingualSegments = []
Comment on lines +71 to +77

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 +70 to +77

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
裁剪时取消任务并递增 analysisGeneration 后,被取消任务的 defer 会因代数不匹配跳过重置 isPerformingOCR/isTranslating,而本函数既不重置这两个标志也不重新触发 OCR。由于 performOCR 入口有 guard !isPerformingOCR else { return },若裁剪发生在 OCR/翻译进行中,标志将永久卡在 true,后续所有 OCR 请求被静默丢弃,UI 永久停留在"识别中/翻译中"状态且无恢复路径。建议在取消任务后直接重置这两个标志,或在 defer 中无条件重置(配合代数守卫仅丢弃结果写入)。

Suggestion:

Suggested change
// Invalidate OCR cache and translation results for the previous crop area
ocrTask?.cancel()
translationTask?.cancel()
analysisGeneration &+= 1
ocrResult = nil
bilingualSegments = []
// Invalidate OCR cache and translation results for the previous crop area
ocrTask?.cancel()
translationTask?.cancel()
analysisGeneration &+= 1
ocrResult = nil
bilingualSegments = []
isPerformingOCR = false
isTranslating = false


screenshot = Screenshot(
id: screenshot.id,
Expand Down
20 changes: 14 additions & 6 deletions TransFrame/Features/Preview/PreviewViewModel+OCR.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,22 @@ extension PreviewViewModel {
isPerformingOCR = true
ocrTranslationError = nil

Task {
await executeOCR()
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
Comment on lines +15 to +24

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

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

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 👍 / 👎.

}

// Recognize in the user's source language; auto (or an unsupported
// language) falls back to Vision's automatic language detection.
let languages = Set(
[AppSettings.shared.translationSourceLanguage]
.compactMap { OCREngine.RecognitionLanguage(translationLanguage: $0) }
Expand All @@ -32,11 +38,13 @@ extension PreviewViewModel {
image,
languages: languages
)
guard currentGeneration == analysisGeneration else { return }
ocrResult = result
if result.observations.isEmpty {
errorMessage = String(localized: "error.ocr.no.text")
}
} catch {
guard currentGeneration == analysisGeneration else { return }
let message = "\(String(localized: "error.ocr.failed")) \(error.localizedDescription)"
ocrTranslationError = message
errorMessage = message
Expand Down
20 changes: 15 additions & 5 deletions TransFrame/Features/Preview/PreviewViewModel+Translation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,32 @@ extension PreviewViewModel {
isTranslating = true
ocrTranslationError = nil

Task { @MainActor in
defer { isTranslating = false }
translationTask?.cancel()
analysisGeneration &+= 1
let generation = analysisGeneration
translationTask = Task { @MainActor in
defer {
if generation == self.analysisGeneration {
self.isTranslating = false
}
}

let pipeline = ImageTranslationPipeline()
let context = PipelineContext()

// Stage-split so failures are attributed correctly: analysis
// (VLM) errors read as recognition, not translation failures.
let analysis: ScreenAnalysisResult
do {
analysis = try await pipeline.analyze(image: image, context: context)
} catch {
guard generation == self.analysisGeneration else { return }
let message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
errorMessage = String(format: String(localized: "error.pipeline.ocrFailed"), message)
ocrTranslationError = errorMessage
clearError()
return
}

guard generation == self.analysisGeneration else { return }
let filtered = analysis.filteredForTranslation()
guard !filtered.segments.isEmpty else {
errorMessage = String(localized: "error.ocr.no.text")
Expand All @@ -48,12 +55,15 @@ extension PreviewViewModel {

let config = ImageTranslationPipelineConfig.fromAppSettings(scene: nil)
do {
bilingualSegments = try await pipeline.translate(
let segments = try await pipeline.translate(
analysisResult: filtered,
config: config,
context: context
)
guard generation == self.analysisGeneration else { return }
bilingualSegments = segments
} catch {
guard generation == self.analysisGeneration else { return }
let message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
errorMessage = String(format: String(localized: "error.pipeline.translateFailed"), message)
ocrTranslationError = errorMessage
Expand Down
8 changes: 8 additions & 0 deletions TransFrame/Features/Preview/PreviewViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ final class PreviewViewModel {
var bilingualSegments: [BilingualSegment] = []
var isTranslating: Bool = false

@ObservationIgnored
var ocrTask: Task<Void, Never>?
@ObservationIgnored
var translationTask: Task<Void, Never>?
var analysisGeneration: UInt64 = 0

// MARK: - Annotation Tools

@ObservationIgnored
Expand Down Expand Up @@ -264,6 +270,8 @@ final class PreviewViewModel {
func hide() {
guard isVisible else { return }
isVisible = false
ocrTask?.cancel()
translationTask?.cancel()
undoStack.removeAll()
redoStack.removeAll()
onDismiss?()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,16 @@ final class TextTranslationPopupController: NSObject {

extension TextTranslationPopupController: NSWindowDelegate {
nonisolated func windowWillClose(_ notification: Notification) {
guard let closedWindow = notification.object as? NSWindow else { return }
Task { @MainActor in
window = nil
onDismiss?()
popupDelegate?.textTranslationPopupDidDismiss()
// Only clear the reference if this is still the current window,
// preventing an old window's async close callback from clearing
// a newly-presented window's reference.
if window === closedWindow {
window = nil
onDismiss?()
popupDelegate?.textTranslationPopupDidDismiss()
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,16 @@ enum BilingualOverlayLayout {
/// TextSegment 使用左上角原点;译文从原文下边缘开始,按画布宽度换行。
static func translationAnchor(for boundingBox: CGRect, in displaySize: CGSize) -> Anchor {
let x = max(0, min(boundingBox.minX * displaySize.width, displaySize.width))
let y = boundingBox.maxY * displaySize.height + 1
let belowY = boundingBox.maxY * displaySize.height + 1
let stripWidth = min(max(boundingBox.width * displaySize.width, 60), max(0, displaySize.width - x))
let fontSize = min(max(boundingBox.height * displaySize.height * 0.85, 10), 16)
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)
}
Comment on lines +48 to +54

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 +48 to +54

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)
}

return Anchor(x: x, y: y, maxWidth: stripWidth, fontSize: fontSize)
}

Expand Down
Loading
Loading