Repository navigation
Fix macOS off-main AppleScript, BLE continuation crash, memory delete pagination skip, task reorder flicker (bug sweep #5) - #9492
Conversation
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
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RAxLsaxtwVNDTWAZFfJp9q
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
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
NSAppleScriptbuild/execute onMainActorwhile keeping delays/background work off-main. - Make
LimitlessDeviceConnection.getStorageStatus()continuation completion single-winner (lock + generation) to avoid double-resume crashes and leaked continuations. - Adjust
MemoriesPagelocal + 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.
| 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 |
There was a problem hiding this comment.
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 isconversation_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 siblingmemoryShareButtonClicked(conversationId:), which has no callers to establish the convention. Somemory.idmay be the intended value under a misnamed key (memory_id), rather than a wrong value. ServerMemory.conversationIdis optional and nil for memories not linked to a conversation. The suggested "only emit whenconversationIdis 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
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, andChatToolExecutor.triggerAutomationPermissionDirectlyall built and executedNSAppleScriptinsideTask.detachedon a background cooperative thread.NSAppleScriptis 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. EachNSAppleScriptbuild+executeAndReturnErrornow runs inawait MainActor.run; the inter-script delays and the thread-safeAEDeterminePermissionToAutomateTargetqueries stay off-main. TheNSDictionaryerror 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)getStorageStatusstored itsCheckedContinuationin an unsynchronizedvaron a non-actor class and resumed it from two parallel executors — the 3s timeoutTaskand the RX parserTask. Both could resume the same continuation (double-resume trap → crash), and an overlapping call leaked the first continuation (hang). GuardedstorageState/storageStateCompletionwith anNSLockusing the same capture-under-lock / resume-outside single-winner pattern asBleTransport, plus a generation tag so a timeout only resolves its own pending call and a displaced continuation is resumed withnilinstead 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 nextloadMore()skipped the item that shifted into the old cursor slot — one memory silently vanished from pagination per delete. NowcurrentOffsetis decremented in the optimistic block (SQLite soft-delete is immediate) andrawBackendOffsetinperformActualDeleteafter 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 callreloadForCurrentLayerFilter(), which recomputescurrentOffsetfrom offset 0, so the decrement unwinds safely.4. Task reorder flicker from shared suppression flag (
TasksPage.swift)suppressDatabaseRequeryis a single boolean set by a reorder but cleared by a different, later-running async sync's post-awaitdefer. 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 monotonicsuppressRequeryGenerationbumped 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 becausescheduleSortOrderSynccancels intermediate sync tasks (unbalanced set/clear). The automation harness manages the flag directly and is unaffected.Not a bug (verified, no change)
guard !isTranscribing/isTranscribing = true— investigated as a possible TOCTOU; it is safe. The function is@MainActorand synchronous with noawaitbetween the check and the set, so it's atomic. No fix.Product invariants
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:
activeSessions/pollingTasksdata race — real (background pollingTaskreads the dictionaries off-main while main-actor Stop removes entries). The correct fix marks the class@MainActorand makes the fivewaitUntilExitsubprocess helpersnonisolated/off-main — a whole-class isolation refactor that should be built and run locally (and exercised viaagent-logic-harness.sh) before landing. Tracking separately._dbQueueand 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
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; addedAppState+Permissions.swifttoscreen-recording-permission.yaml).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