Skip to content

Fix macOS off-main AppleScript, BLE continuation crash, memory delete pagination skip, task reorder flicker (bug sweep #5) - #9492

Merged
eulicesl merged 5 commits into
mainfrom
claude/macos-bug-fixes-testing-i8z7cm
Jul 11, 2026
Merged

eulicesl merged 5 commits into
mainfrom
claude/macos-bug-fixes-testing-i8z7cm

Conversation

@eulicesl

@eulicesl eulicesl commented Jul 11, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fifth batch of the macOS bug sweep, working through the previously-deferred findings. Four confirmed defects, each fixed at the failure boundary. The remaining deferrals are re-scoped into focused follow-ups (see below) because they need a local build or carry wide blast radius — not appropriate to land blind here (this environment has no Swift toolchain; macOS CI is the compile/test gate).

Fixes

1. NSAppleScript run off the main thread (AppState+Permissions.swift, ChatToolExecutor.swift)

triggerAutomationPermission, checkAutomationPermission, and ChatToolExecutor.triggerAutomationPermissionDirectly all built and executed NSAppleScript inside Task.detached on a background cooperative thread. NSAppleScript is main-thread-only; off-main execution is undefined behavior, and since these paths are exactly what raises the Automation (Apple Events) TCC prompt, it can make the prompt silently fail to appear. Each NSAppleScript build+executeAndReturnError now runs in await MainActor.run; the inter-script delays and the thread-safe AEDeterminePermissionToAutomateTarget queries stay off-main. The NSDictionary error stays local to each block so no non-Sendable value crosses back to the detached task.

2. Limitless storage-status continuation double-resume (LimitlessDeviceConnection.swift)

getStorageStatus stored its CheckedContinuation in an unsynchronized var on a non-actor class and resumed it from two parallel executors — the 3s timeout Task and the RX parser Task. Both could resume the same continuation (double-resume trap → crash), and an overlapping call leaked the first continuation (hang). Guarded storageState/storageStateCompletion with an NSLock using the same capture-under-lock / resume-outside single-winner pattern as BleTransport, plus a generation tag so a timeout only resolves its own pending call and a displaced continuation is resumed with nil instead of leaked.

3. Memory pagination skipped one item per delete (MemoriesPage.swift)

Deleting a memory soft-deleted it in SQLite immediately (excluded from getLocalMemories) and removed it from the visible arrays, but never adjusted the paging cursors, so the next loadMore() skipped the item that shifted into the old cursor slot — one memory silently vanished from pagination per delete. Now currentOffset is decremented in the optimistic block (SQLite soft-delete is immediate) and rawBackendOffset in performActualDelete after the backend DELETE succeeds (the backend still holds the row during the undo window, so decrementing earlier would re-fetch and duplicate it). Undo and delete-failure both call reloadForCurrentLayerFilter(), which recomputes currentOffset from offset 0, so the decrement unwinds safely.

4. Task reorder flicker from shared suppression flag (TasksPage.swift)

suppressDatabaseRequery is a single boolean set by a reorder but cleared by a different, later-running async sync's post-await defer. Two reorders within the debounce+network window collide: reorder #2 re-sets the flag, then reorder #1's earlier sync clears it while #2 is still pending, and the ensuing filtered SQLite requery overwrites the display with #1's stale order. Added a monotonic suppressRequeryGeneration bumped at each suppress site; the async sync clears only if its captured token still matches, so only the newest suppressor lifts suppression. A depth counter can't be used because scheduleSortOrderSync cancels intermediate sync tasks (unbalanced set/clear). The automation harness manages the flag directly and is unaffected.

Not a bug (verified, no change)

  • AppState+Transcription guard !isTranscribing / isTranscribing = true — investigated as a possible TOCTOU; it is safe. The function is @MainActor and synchronous with no await between the check and the set, so it's atomic. No fix.

Product invariants

  • INV-CHAT-1 — cited because the diff touches ChatToolExecutor.swift (a path glob). The change there is the off-main→main-thread move of the Automation-permission AppleScript trigger; it does not touch the chat write-path, kernel projection, floating viewport, or agent timeline identity, so no continuity-DoD guard-test change is required.

Deliberately deferred to focused follow-ups (not fixed here)

These are confirmed real, but each needs more than a blind edit in a no-toolchain environment:

  • TaskAgentManager activeSessions/pollingTasks data race — real (background polling Task reads the dictionaries off-main while main-actor Stop removes entries). The correct fix marks the class @MainActor and makes the five waitUntilExit subprocess helpers nonisolated/off-main — a whole-class isolation refactor that should be built and run locally (and exercised via agent-logic-harness.sh) before landing. Tracking separately.
  • PushToTalkManager text-based transcript dedup + ChatMessagesView prepend-anchor restore — both real and both INV-CHAT-1 chat-surface changes that warrant a maintainer continuity-gauntlet run, which needs a live named bundle unavailable here.
  • RewindDatabase stale-pool-after-recovery — real; 10 storage actors cache _dbQueue and only invalidate on sign-out, not on the corruption/maintenance recovery paths. The generation-revalidation fix touches ~11 files of DB access and deserves its own reviewable PR with a local run.

Verification

  • Static checkers pass at baseline: check_desktop_test_quality.py, check-sources-root-layout.py, check-async-after-ratchet.py, check-userdefaults-key-ratchet.py, desktop-flow-lint.py, check-e2e-flow-coverage.py --strict (all 5 changed Swift files covered; added AppState+Permissions.swift to screen-recording-permission.yaml).
  • Swift compile/test gates on macOS CI (desktop-swift-ci.yml); no Swift toolchain in this environment. Fixes are reasoning-verified against the production paths, and colors to the LED board #2/About Firebase #4 reuse patterns already proven in this codebase (BleTransport lock discipline; generation-token ownership). Client #1 and colors to the LED board #2 close crash/UB classes; Add printing BLE device address to serial monitor #3 is a two-site cursor adjustment matching the existing raw-vs-visible cursor semantics; About Firebase #4 mirrors the existing debounce/defer structure.

🤖 Generated with Claude Code


Generated by Claude Code

Review in cubic

claude added 5 commits July 11, 2026 18:26
NSAppleScript is main-thread-only, but triggerAutomationPermission,
checkAutomationPermission, and ChatToolExecutor.triggerAutomationPermissionDirectly
all built and executed it inside Task.detached on a background cooperative
thread. Off-main NSAppleScript execution is undefined behavior: intermittent
failures, spurious errors, and — since these paths are exactly what raises the
Automation (Apple Events) TCC prompt — the prompt can silently fail to appear.

Wrap each NSAppleScript build+executeAndReturnError in await MainActor.run,
keeping the inter-script delays and the thread-safe AEDeterminePermissionToAutomate
queries off-main. The NSDictionary error stays local to each MainActor.run block
so no non-Sendable value crosses back to the detached task.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
getStorageStatus stored its CheckedContinuation in an unsynchronized var on a
non-actor class and resumed it from two parallel executors — the 3s timeout Task
and the RX parser Task. With no lock, both could resume the SAME continuation
(double-resume traps → crash), and a second overlapping call leaked the first
continuation (hang).

Guard storageState / storageStateCompletion with an NSLock using the same
capture-under-lock / resume-outside pattern as BleTransport: exactly one context
captures the non-nil continuation and resumes it; every other sees nil and
no-ops. A generation tag ensures a timeout only resolves its own pending call,
and a displaced continuation from an overlapping call is resumed with nil
instead of leaked.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
Deleting a memory soft-deleted it in SQLite immediately (excluded from
getLocalMemories) and removed it from the visible arrays, but never adjusted
the pagination cursors. The next loadMore() then called getLocalMemories(
offset: currentOffset) against a result set that had shrunk by one, so the
item that shifted into the old cursor slot was skipped — one memory silently
vanished from pagination per delete (and the same on the API path once the
backend row was removed).

Decrement currentOffset in the optimistic block (the SQLite soft-delete is
immediate) and decrement rawBackendOffset in performActualDelete after the
backend DELETE succeeds (the backend still holds the row during the undo
window, so decrementing earlier would re-fetch and duplicate it). Undo and
delete-failure both call reloadForCurrentLayerFilter(), which recomputes
currentOffset from offset 0, so the visible-cursor decrement unwinds safely.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
suppressDatabaseRequery is a single shared boolean set by a reorder but cleared
by a different, later-running async sync in its post-await defer. Two reorders
within the 500ms debounce + network window collide: reorder #2 re-sets the flag,
then reorder #1's earlier sync completes and its defer clears the flag while #2
is still pending. recomputeAllCaches then runs a filtered SQLite requery that
overwrites the display with #1's stale sortOrders — the exact drag-order flicker
the flag exists to prevent.

Add a monotonic suppressRequeryGeneration bumped at each suppress site; the async
sync captures it and clears the flag only if it still matches, so only the newest
suppressor can lift suppression. A depth counter can't be used because
scheduleSortOrderSync cancels intermediate sync tasks, unbalancing set/clear.
The automation harness manages the flag directly and is unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
@eulicesl
eulicesl requested a review from Copilot July 11, 2026 18:53
@eulicesl
eulicesl marked this pull request as ready for review July 11, 2026 18:53
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR is the fifth macOS “bug sweep” batch, addressing several correctness/concurrency issues in the desktop app: ensuring AppleScript execution occurs on the main actor, hardening a BLE continuation against double-resume, fixing a pagination cursor bug on memory deletion, and eliminating task reorder flicker from a shared suppression flag.

Changes:

  • Run NSAppleScript build/execute on MainActor while keeping delays/background work off-main.
  • Make LimitlessDeviceConnection.getStorageStatus() continuation completion single-winner (lock + generation) to avoid double-resume crashes and leaked continuations.
  • Adjust MemoriesPage local + backend paging offsets after deletion to prevent skipping an item; add generation-based suppression ownership for task requery suppression.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
desktop/macos/e2e/flows/screen-recording-permission.yaml Adds coverage for AppState+Permissions.swift in the screen-recording permission flow.
desktop/macos/Desktop/Sources/Providers/ChatToolExecutor.swift Runs the automation-permission AppleScript on the main actor.
desktop/macos/Desktop/Sources/MainWindow/Pages/TasksPage.swift Adds generation-token ownership to prevent stale async clears of suppressDatabaseRequery.
desktop/macos/Desktop/Sources/MainWindow/Pages/MemoriesPage.swift Fixes pagination cursor drift after delete by decrementing offsets appropriately.
desktop/macos/Desktop/Sources/Bluetooth/Connections/LimitlessDeviceConnection.swift Synchronizes storage-status continuation resumption to prevent double-resume and hangs.
desktop/macos/Desktop/Sources/AppState/AppState+Permissions.swift Moves AppleScript trigger/check execution onto the main actor for reliable TCC prompting.
desktop/macos/changelog/unreleased/20260711-macos-bug-sweep-5.json Adds a macOS changelog fragment for this bug sweep batch.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 1253 to +1255
try await APIClient.shared.deleteMemory(id: memory.id)
AnalyticsManager.shared.memoryDeleted(conversationId: memory.id)
// The backend row is now gone, so the raw backend paging cursor is one

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks — flagging that this line is pre-existing (this PR only added the rawBackendOffset decrement right after it), and I'm intentionally leaving it out of scope here because the right fix is ambiguous:

  • The "Memory Deleted" event's property key is conversation_id, but it's not clear whether the intended value is the source conversation or the memory itself — the key looks copy-pasted from the sibling memoryShareButtonClicked(conversationId:), which has no callers to establish the convention. So memory.id may be the intended value under a misnamed key (memory_id), rather than a wrong value.
  • ServerMemory.conversationId is optional and nil for memories not linked to a conversation. The suggested "only emit when conversationId is present" would silently drop the deletion event for all unlinked memories, regressing the metric's coverage.

Since this is an analytics-semantics call I can't settle from the code, and it's unrelated to the pagination-cursor fix in this PR, I'd rather not guess at it here. Happy to file a separate issue to decide the correct key/value (and whether unlinked deletions should still be counted) if that's useful.


Generated by Claude Code

@eulicesl
eulicesl merged commit bbfb0cd into main Jul 11, 2026
23 of 26 checks passed
@eulicesl
eulicesl deleted the claude/macos-bug-fixes-testing-i8z7cm branch July 11, 2026 19:03
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.

3 participants