From 215cef7fc5ac4f4b258dc0d7db9a1dd33099acea Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 26 Sep 2026 01:49:20 -0400 Subject: [PATCH 1/7] Fence Android chat reads and Home summary admission (#225) * fix(android): fence deferred home cache writes * fix(android): reject superseded cross-owner chat reads * fix(android): order Home summary requests and pagination commits * Preserve Android turn receipts across response ownership changes (#227) * Preserve Android accepted turn receipts across response ownership changes * Keep receipt merges under request authority in both completion orders (cherry picked from commit 1a3cd3e697026a8a5106bebced47ea11b87e4aa2) --- .memory/mobile-response-ownership.md | 85 ++++++ .memory/mobile-turn-receipt-ownership.md | 23 ++ .../features/chat/AidenChatViewModel.kt | 66 ++-- .../workspaces/AidenWorkspaceHomeViewModel.kt | 42 ++- .../persistence/AidenChatCache.kt | 154 +++++++++- .../AidenOnTheGo/AidenChatSummaryTest.kt | 103 +++++++ .../sbtbiswas/AidenOnTheGo/AidenChatTest.kt | 284 +++++++++++++++++- 7 files changed, 703 insertions(+), 54 deletions(-) create mode 100644 .memory/mobile-response-ownership.md create mode 100644 .memory/mobile-turn-receipt-ownership.md diff --git a/.memory/mobile-response-ownership.md b/.memory/mobile-response-ownership.md new file mode 100644 index 0000000000..c492a96c11 --- /dev/null +++ b/.memory/mobile-response-ownership.md @@ -0,0 +1,85 @@ +# Native response/list ownership follow-up + +Owner: this recovery task, explicitly retained by program coordinator on 2026-09-22. Separate patch after PR217; do not call full recovery complete while these findings remain open. Separate worktree /Users/sambitbiswas/.codex/worktrees/mobile-response-ownership/aiden-agent, branch feature/mobile-response-ownership, based on published PR217 head0cba92f10675eead1b11d1a056aa7365487373f8. Original-main source baseline: c8c09e0d2. Coordinator explicitly authorized parallel follow-up while217CI runs on2026-09-22 16:53 UTC. Published217 worktree remains unchanged. + +## Evidence status + +Both independent Sol medium reviewers inspected original-main and current source. The schedules below are source-confirmed counterexamples and deterministic test specifications, NOT executed XCTest reproductions. Physical XCTest remains blocked by the locked shared iPhone; no simulator allowed. Obtain an executed Android baseline where applicable, and compile iOS regressions while retaining explicit device acceptance limits. + +## Workspace rename response versus terminal settlement + +Affected iOS: AidenWorkspaceChatsModel.rename/persist in Features/Remote/AidenChatFeature.swift; detail AidenChatViewModel.reconcileChat/acceptRemoteChat. Routes: PATCH /chats/{id} with If-Match, then GET /chats/{id} for reconciliation. Both exist in original-main. + +Schedule: hold a successful PATCH response containing new title + pre-terminal messages. Let detail stream finish and authoritative GET save final messages. Release PATCH. Workspace model upserts/persists its older full transcript and publishes onChatUpdated. isMutating fences only one workspace model; transcriptGeneration fences only one detail model; isCurrent validates installation, not response order. PR217 tokens order already-accepted writes, so a newly accepted delayed HTTP response receives a newer token. + +Regression: real production workspace/detail models and held URLProtocol PATCH; terminal GET settles first; release PATCH. Require final message and successful new title in model/list/cache/reopened disk. Negative tests: post-PATCH refresh offline/failure must not undo successful title or publish stale messages; ordinary disk failure must not remove newly created chat from the in-memory list; repeated refresh supersession must not trigger duplicate mutations. Never replay PATCH/POST to recover a read. + +## Workspace list/cache versus mutation or installation purge + +Affected iOS: workspace load GET /chats?workspaceId=..., remove, and persist saveChats/reconcileChatSummary; Persistence/AidenChatCache.swift list/summary writes; AidenRemoteCoordinator.purgeInstallationDataUnlocked. Original-main already has these methods. + +Schedule A: list GET starts before create/rename/delete or detail settlement; response is delayed until after accepted newer model/cache update, then overwrites full-chat list with older records. +Schedule B: load passes isCurrent and queues saveChats; purge runs first; delayed list write runs after purge and recreates metadata. persist can likewise yield after detailed save then write list/summary after purge. Envelope instance IDs isolate namespaces but do not prevent post-purge writes. Existing coordinator installationDataGate protects withRetainedInstallationData operations, not workspace list/persist writes. + +Regression: deterministic admitted list/summary writes delivered after actual purge; reopened disk must contain neither artifact, another instance must be unaffected, a legitimate re-pair/new session must work. Hold list GET through valid create/rename/remove and verify both UI and offline results. Inspect every list/summary writer before choosing cache tokens or retained-data gate; avoid a partial fence that leaves companion artifacts writable. + +## Bot navigation and Android parity + +Inspect all cached-nil BotShell GET writers and Android workspace/Bots/detail producers. A stale response rejected by shared ordering must use a currently admitted chat or retry an authoritative GET so valid navigation completes. Do not simply return and strand a loading destination. Preserve successful create and model/navigation scope identity guards. Complete reachability review before asserting this is reproduced. + +## Coordination and next gate + +Notified browser owner 01a0c7aa-c3e8-7003-8374-03d44f1812dd and mobile Bots/Queue-Steer owner 01a0c7aa-c3ec-7530-8ecc-96f7788c17f1 about list/rename/BotShell scope; awaiting overlap constraints. Deliverable owner knows cache token API. Keep PR217 code unchanged while exact-head CI completes. Implement follow-up separately after its scoped gate, obtain both independent Sol medium reviews and applicable Android/iOS checks, then send exact commit and regression evidence to integration coordinator. + +## Executed Android cache-boundary baseline (2026-09-22) + +Ran two temporary deterministic JUnit regressions using production AidenChatCache and real temporary disk. The queued closure matches WorkspaceHome.accept's deferred save; one test executes it after a newer accepted chat write, the other after purge. Both FAIL as expected: newer title is replaced; purged chat is recreated. `git diff c8c09e0d2 HEAD -- android/.../persistence/AidenChatCache.kt` is empty, so the exercised cache source is identical to original main. These are cache-boundary reproductions, not full navigation/ViewModel integration tests. + +Command: `./gradlew :app:testDebugUnitTest --tests '*AidenChatTest.queuedHomeWrite*' --max-workers=2 --console=plain` with the established Android Java/SDK environment. Evidence: `/tmp/aiden-response-ownership-baseline.log`; exact temporary tests: `/tmp/aiden-response-ownership-baseline.patch`. Test file restored after capturing evidence; PR217 worktree remains clean. Follow-up must retain these negatives, add owner-level queued-dispatcher/held-HTTP tests, and prove they pass with the safe fix. + +Android source review also confirms Home summary-page generation is local to home loads and cannot see detail settlement. iOS BotShell duplicate GET is reachable when openConversation sets path, triggering restorationID/.task while the first cache-miss GET is pending; both openConversation and hydrateRestoredPath can publish for the same path. Hold GET A, return final from B, then release A. Assert final presentation, mutation access, retained navigation path and reopened cache. No claim of executed iOS reproduction yet. + +2026-09-22 integration audit adjustment: PR217 now also fences iOS workspace/home metadata and attachment writes across deletion/purge, with required reservations and per-file metadata ordering preserving valid re-admission. This absorbs the iOS delayed cache-write/purge portion of the follow-up. Cross-owner HTTP response vs terminal settlement/presentation, rename field preservation, Bot duplicate GETs and Android delayed home writes remain open. Exact revised PR head is recorded in the task's next publication/update. + +15:39 UTC heartbeat: exact f959469702 hosted verify failed in unchanged scripts/bot-inbox-writer.test.mjs wrong-inode case with uncaught stdin EPIPE. TS/lint/policy/model checks passed; native iOS compile step skipped after test failure. Android hosted green; Electron E2E still running. Job106812682773/run35747292113 logs /tmp/aiden-pr217-verify-failure.log. Built native helper locally; all3 harness tests pass (/tmp/aiden-pr217-inbox-recheck.log). Rerun request rejected while run still in progress; retry failed job/run after completion. Coordinator notified for possible existing owner EPIPE fix. No tested code changed; broader followup remains after PR217 gate. + +16:20 heartbeat: c22 verify failed capacity test's equality between two live statfs readings. Adopted isolated sourcepeer4c00c968 as683f92dea7020789aed8d303e58c687b635eca99 (same fix already green in218/combined), no production/mobile changes. Focused capacity test passed, both independent Sol medium reviews clear. Restored locked dependencies via npm ci --ignore-scripts; ESLint now passes for capacity test and earlier inbox harness. Logs /tmp/aiden-pr217-c22-verify.log, /tmp/aiden-pr217-capacity-fixed.log, /tmp/aiden-pr217-test-fixes-lint.log. Published, coordinator/integration informed; latest hosted CI still required. + +16:34 portability follow-up: published0cba92f10675eead1b11d1a056aa7365487373f8 fixes4074005701 test-only. Baseline217 statfs Number conversion need not be safeinteger; finite/nonnegative plus typederror/reserve/estimate/sameobservation shortfall retained. Actual-error fixture aboveMAXSAFE accepted; NaN/infinities/negative/non-shortfall/untyped rejected. Focused2tests andeslint pass (/tmp/aiden-pr217-capacity-large.log), bothSolmediumreviews clear. PR221 has different hardened safeinteger contract; coordinated without changing221. All12threads resolved; latestCIpending. Nativecodeunchangedc22. + +## First bounded implementation and remaining ownership plan + +Repeated the two Android cache-boundary negatives on the isolated follow-up base; both fail (/tmp/aiden-response-followup-baseline.log). A git diff confirms Android cache source on original-main c8c09e0d2 equals the exercised published217 base. The original patch remains /tmp/aiden-response-ownership-baseline.patch. + +Implemented only queued accepted Home writes so far: cache-wide AtomicLong reservation before Home.accept launches IO, per-installation/chat high-water and purge floors checked inside synchronized saveChat, removal/purge invalidation, normal fresh writes still admitted. Added injectable Home cache dispatcher and an actual Home ViewModel controlled-dispatcher test, plus adapted the two cache negatives. All3focused tests pass, then all180Android JVM tests pass with lint/instrumentation compilation (/tmp/aiden-response-followup-fixed.log, /tmp/aiden-response-followup-android.log). This is not yet a full response-ownership fix and is not published. + +Next concrete slices: +1. Android shared response admission: reserve at request dispatch for initial/terminal/title GET and accepted POST; return current admitted winner on supersession, preserve stream receipt and navigation, never replay a mutation. Cover two detail ViewModels with one held initial GET through the other's terminal settlement. +2. Android home pages: carry request tokens through summary acceptance; row/metadata ownership must see detail settlement and purge; reject stale pages without advancing cursor/boundary, preserve currently admitted rows and unrelated installation. Test held initial/pagination GET through settlement/purge and disk reopen. +3. iOS duplicate Bot GET and detail reads: reserve before HTTP, pass authority through shared presentation helper, use current admitted winner on rejection with path/device/scope guards. Test both duplicated GET completion orders and navigation availability. +4. iOS rename/list response ownership: PATCH receipt owns title fields, not a whole stale transcript. Preserve the successful title when refresh fails, preserve settled messages and avoid treating opaque revisions as numerically ordered. Final representation/revision choice must follow server contract and direct review; do not overwrite a current transcript with an old response or silently discard successful rename. Held PATCH/list vs terminal GET tests and legitimate new-create/rename/navigation controls are required. + +Native integration owner and browser owner were notified of branch/worktree boundaries. Both Sol reviewers assigned read-only ownership review; published217 stays on its tested head. Physical XCTest remains unexecuted; no device slot requested while locked. + +Independent Sol medium reviews: Android queued-home slice clear in both source/test reviews. iOS design review recommends separate title overlay ownership: reserve request-origin tickets before GET/PATCH; retain winning full snapshot/revision on delayed successful rename, persist successful title overlay separately, and perform a read-only refresh to obtain a coherent snapshot. If refresh fails, preserve the overlay but require refresh before another revisioned mutation rather than invent an opaque revision order. Bot mutation-availability publication also needs path+scope+attempt ownership after its awaits. This is a concrete design proposal awaiting implementation/regression evidence, not shipped behavior. + +## Android cross-owner GET admission checkpoint + +Added a real two-ViewModel held-HTTP regression: the first owner's initial GET is held; a second owner restores and settles the stream; releasing the first GET previously replaced its presentation and the shared cached transcript. The regression fails before this slice (/tmp/aiden-response-two-owner-baseline.log; exact test diff /tmp/aiden-response-two-owner-baseline.patch). This executed owner-level negative is against d93767df, not an executed original-main owner build; the earlier cache-boundary baseline remains the original-main evidence. + +Initial, terminal reconciliation and pending-title GETs now reserve shared tickets before HTTP. Responses are admitted before presentation; a rejected response adopts the namespaced accepted winner. The cache retains the winner before disk IO and rejects disk fallback after removal/purge, so ordinary persistence failure does not strand the other valid destination and deletion is not mistaken for a successful reconciliation. POST receipts and list response admission remain pending and are not covered by this claim. + +Both ordinary and blocked-disk two-owner regressions pass. Full Android validation:182 JVM tests,0failures/errors/skips, lintDebug and compileDebugAndroidTestKotlin pass (/tmp/aiden-response-get-android.log). No iOS source changed in these two Android slices. Physical tests remain unexecuted. PR217 remains untouched at0cba92f106; verify/Android/Pullfrog green, Electron E2E still executing,12resolved threads last checked. + +Both independent GPT-5.6 Sol medium reviews cleared the actual GET-admission diff with no introduced blocker. Review limits: pending-title retry shares the ticket/helper implementation but has no separate held-title HTTP regression yet; POST/list and later GETs receiving a stale server snapshot are not claimed fixed. + +## Android Home response admission in progress + +Held production Home initial refresh/pagination responses now reproduce a stale-summary overwrite on b30122002 (/tmp/aiden-summary-owner-baseline.log). The current patch reserves before HTTP, shares summary high-water with detail/removal/purge and immediate Home acceptance, rejects stale writes before disk/flows, and preserves cursor/boundary until admission. Four held-owner schedules cover initial/page vs detail/purge and successful same-cursor retry. Full183 Android JVM tests/lint/instrumentation compilation pass (/tmp/aiden-summary-owner-android.log). Both independent Sol reviews are checking the actual diff, including queued detail acceptance after a newer summary page. This slice remains uncommitted until that last ordering review is clear. Coordinator requests publication as a cohesive Android-only draft PR so hosted checks can run while remaining POST/iOS scopes continue. + +Native integration owner checked the iPhone once at coordinator request: passcodeRequired=true, unlockedSinceBoot=true. No slot claimed or launch attempted; physical acceptance remains blocked by the lock. + + +Review corrections for the Home slice: summary request ownership is now registered synchronously before launching each HTTP request. A queued detail write can persist its independently admitted transcript, but may project a summary only while its original ticket still owns summary admission; it no longer mints a newer summary token. Once a page has committed, a later valid detail/activity write does not retroactively reject it and strand the old cursor. Context and purge retention remain checked. Added old-detail/new-page and newer-request/old-writer cache regressions, plus a real Home test that uses its injected dispatcher to mutate immediately after disk commit and before the queued UI continuation. Full184 JVM tests/lint/instrumentation compilation pass (/tmp/aiden-summary-owner-android.log). No new iOS or server contract changes in this Android-only slice. POST receipts, iOS rename/Bot response ownership and physical acceptance remain explicitly open. + +Both independent GPT-5.6 Sol medium re-reviews cleared the corrected Home slice and its interactions with the two prior Android commits. Preparing a stacked draft PR on the latest PR217 base to start hosted validation; remaining POST and iOS response ownership is still assigned. diff --git a/.memory/mobile-turn-receipt-ownership.md b/.memory/mobile-turn-receipt-ownership.md new file mode 100644 index 0000000000..847f619d9f --- /dev/null +++ b/.memory/mobile-turn-receipt-ownership.md @@ -0,0 +1,23 @@ +# Android turn receipt ownership follow-up + +Separate worktree /Users/sambitbiswas/.codex/worktrees/mobile-turn-receipt-ownership/aiden-agent, branch feature/mobile-turn-receipt-ownership, based on green PR225 head152577eeb0e4e7350d2f57cdf69d125cb5aa6d22. Coordinator explicitly requested keeping225 stable and publishing the next cohesive slice separately. Original217/225 worktrees untouched. + +Executed baseline: actual sender POST is held while another production detail owner accepts a settled transcript. Releasing the successful receipt on225 overwrites the settled assistant with only the accepted user message. /tmp/aiden-turn-receipt-baseline.log and /tmp/aiden-turn-receipt-baseline.patch capture the failure. This is an executed current-parent negative, not a new original-main execution. + +Current implementation reserves before POST, atomically admits the receipt under independent removal/purge authority, merges the accepted message by ID and canonical timestamp without replacing winner fields, and maintains separate per-chat receipt/stream ownership so an older receipt cannot replace a newer marker. Fresh detail merge authority retains the original summary ticket to avoid stale title/list projection. In-memory stream ownership survives disk-write failure; accepted202 does not restore a retryable draft merely because persistence fails. Retained original installation/device may retain the receipt for later navigation, while consumer publication requires the original active client identity. No mutation replay. + +Actual two-owner regression covers a newer transcript with/without the accepted receipt, newer second POST stream ownership, purge, remove plus fresh readmission, chat disk failure and stream disk failure.185Android JVM tests/lint/instrumentation compilation pass (/tmp/aiden-turn-receipt-android.log). Both independent Sol medium reviews in progress. No iOS/server contract changes. iOS rename/list/Bot response ownership and physical acceptance remain assigned; device locked, no test launch. + +Review follow-up: unpair and active-client changes reconcile the optimistic chat and clear queued state; same-ID pairing replacement is fenced using captured creation time before cache admission. Added held unpair/switch/re-pair modes. Seeded an older durable stream marker, failed its replacement before IO, and verified the memory winner survives while reopened disk cannot resume the old stream. Deleting the old marker is best effort if storage itself cannot accept deletion. Full185 JVM tests (0failures/errors/skips), lint and instrumentation compilation pass in /tmp/aiden-turn-review-android.log; focused regression /tmp/aiden-turn-review-fixed.log. Both independent GPT-5.6 Sol medium re-reviews clear the actual final source/tests. No physical execution claimed. + +## Inverse completion order correction + +Integration Sol identified and owner reproduced on published85f278fe: POST reserves its request ticket, a later GET reserves another ticket and holds a settled response, POST receipt completes first and mints a fresh detail write ticket, then GET is rejected and loses settled assistant/title. Actual two-ViewModel held-HTTP failure: /tmp/aiden-turn-inverse-baseline.log; exact regression patch /tmp/aiden-turn-inverse-baseline.patch. This is an executed227-parent negative. + +Receipt admission now merges under original request authority and preserves max(original request, prior admitted snapshot) high-water. Persistence is a private monitor-held operation, not a new response-time request. Stream ownership remains its separate original POST receipt high-water. Receipt activity projection likewise retains existing/request summary authority, so it cannot invalidate a later GET title. Both completion orders are tested, including reopened detail/title, accepted stream marker and one POST/no retryable draft. Existing deletion, newer POST, client replacement and disk failure modes remain covered. Validation/re-review pending for this correction. + +Second independent review added inverse_missing: the already-reserved GET may lack the accepted user receipt, even when its other fields are authoritative. Executed negative /tmp/aiden-turn-inverse-missing-baseline.log, focused fixed /tmp/aiden-turn-inverse-missing-fixed.log. Cache retains a receipt overlay only through the latest request ticket observed when its202 is accepted; this observes the clock without reserving authority. Already-in-flight admitted snapshots merge missing receipt IDs while preserving their own title/revision/other messages. The first snapshot requested after acceptance retires the overlay and establishes a high-water that also rejects older held reads. Remove/purge clear overlays. Added fresh retirement/remove/purge and late-old-read controls. Final186 JVM tests, lintDebug and instrumentation compilation pass /tmp/aiden-turn-inverse-final-android.log. Final independent re-reviews completed after the multi-receipt correction below. + +Final multi-receipt review found POST1-first/POST2-second could use POST2's newer but pre-receipt candidate and drop receipt1. Actual two-VM held-both-POST negative: /tmp/aiden-turn-ordered-posts-baseline.log. Receipt admission now folds all pending accepted messages, independently of GET cutoff retirement. Added both POST completion orders and asserts exactly two POSTs, both message IDs once, and stream2 ownership. Final checks /tmp/aiden-turn-ordered-final-android.log; no mutation replay or server/iOS contract change. + +Final acceptance for this correction:186 JVM tests,0 failures/errors/skips, lintDebug and instrumentation compilation pass. Both independent GPT-5.6 Sol medium final reviews clear after inspecting both POST orders and both GET orders. Hosted CI required on the new commit; physical acceptance remains unexecuted. diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt index b02a802971..c98152038c 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/chat/AidenChatViewModel.kt @@ -664,9 +664,10 @@ class AidenChatViewModel( viewModelScope.launch { _isLoading.value = true try { + val writeToken = chatCache.reserveChatWrite() val remote = client.chat(chatId) if (generation != transcriptGeneration || _isStarting.value || activeClient() !== client) return@launch - acceptRemoteChat(remote) + acceptRemoteChat(remote, writeToken) } catch (e: Exception) { if (e !is CancellationException && generation == transcriptGeneration && !_isStarting.value && activeClient() === client) { _presentedError.value = e.localizedMessage @@ -771,6 +772,9 @@ class AidenChatViewModel( _streamState.value = AidenStreamState.QUEUED val idempotencyKey = turnAttempts.key(request) + val requestToken = chatCache.reserveChatWrite() + val pairingCreatedAt = coordinator.installationStore.installations.value + .firstOrNull { it.instanceId == instanceId && it.deviceId == deviceId }?.createdAt viewModelScope.launch { try { @@ -782,26 +786,37 @@ class AidenChatViewModel( lastSequence = 0 ) - val cleanMessages = updatedChat.messages.filter { it.id != optimisticId }.toMutableList() - if (cleanMessages.none { it.id == response.message.id }) { - cleanMessages.add(response.message) + turnAttempts.reset() + val retainedInstallation = coordinator.installationStore.installations.value.any { + it.instanceId == instanceId && it.deviceId == deviceId && it.createdAt == pairingCreatedAt } - val acceptedChat = updatedChat.copy(messages = cleanMessages) - _chat.value = acceptedChat - if (instanceId.isNotEmpty()) { - chatCache.saveChat(acceptedChat, instanceId) - chatCache.saveActiveStream(stream, instanceId, chatId) + if (!retainedInstallation) { + _chat.value = chatCache.admittedChat(instanceId, chatId) + _streamState.value = null + return@launch } - turnAttempts.reset() + val candidate = updatedChat.copy(messages = updatedChat.messages.filter { it.id != optimisticId }) + val accepted = chatCache.acceptTurnReceipt(candidate, response.message, stream, instanceId, requestToken) + if (activeClient() !== client) { + _chat.value = chatCache.admittedChat(instanceId, chatId) + _streamState.value = null + return@launch + } + if (accepted == null || !chatCache.isChatWriteRetained(instanceId, chatId, requestToken)) { + _chat.value = chatCache.admittedChat(instanceId, chatId) + _streamState.value = null + return@launch + } + _chat.value = accepted.chat _liveText.value = "" _reasoning.value = "" _tools.value = emptyList() _activityTimeline.value = null _pendingApproval.value = null - _streamState.value = AidenStreamState.QUEUED + _streamState.value = if (accepted.stream == null) null else AidenStreamState.QUEUED - startStreaming(stream) + accepted.stream?.let { startStreaming(it) } } catch (e: Exception) { if (e !is CancellationException) { val fallbackMessages = _chat.value?.messages?.filter { it.id != optimisticId } ?: emptyList() @@ -1275,9 +1290,10 @@ class AidenChatViewModel( val generation = transcriptGeneration val client = activeClient() ?: return false return try { + val writeToken = chatCache.reserveChatWrite() val remote = client.chat(chatId) if (generation != transcriptGeneration || _isStarting.value || activeClient() !== client) return false - acceptRemoteChat(remote) + if (!acceptRemoteChat(remote, writeToken)) return false clearRecoveryWarning() true } catch (e: Exception) { @@ -1288,16 +1304,21 @@ class AidenChatViewModel( } } - private fun acceptRemoteChat(remote: AidenChat, scheduleTitleRefresh: Boolean = true) { - if (_isStarting.value) return - _chat.value = remote + private fun acceptRemoteChat(remote: AidenChat, writeToken: Long, scheduleTitleRefresh: Boolean = true): Boolean { + if (_isStarting.value) return false + val admitted = if (instanceId.isNotEmpty()) { + // Admission is recorded before disk IO. A failed write must not lose the + // winner or allow an older request in another presentation to replace it. + runCatching { chatCache.saveChat(remote, instanceId, writeToken) } + chatCache.admittedChat(instanceId, chatId) + } else remote + if (admitted == null) return false + _chat.value = admitted resolveModelSelection() - if (instanceId.isNotEmpty()) { - chatCache.saveChat(remote, instanceId) - } - if (scheduleTitleRefresh && remote.isTitlePending) { + if (scheduleTitleRefresh && admitted.isTitlePending) { schedulePendingTitleRefresh() } + return true } private fun schedulePendingTitleRefresh() { @@ -1309,10 +1330,11 @@ class AidenChatViewModel( delay(delayMs) if (_isStarting.value) continue val generation = transcriptGeneration + val writeToken = chatCache.reserveChatWrite() val remote = client.chat(chatId) if (generation != transcriptGeneration || _isStarting.value || activeClient() !== client) continue - acceptRemoteChat(remote, scheduleTitleRefresh = false) - if (!remote.isTitlePending) return@launch + acceptRemoteChat(remote, writeToken, scheduleTitleRefresh = false) + if (_chat.value?.isTitlePending == false) return@launch } catch (e: Exception) { if (e is CancellationException) return@launch } diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceHomeViewModel.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceHomeViewModel.kt index 1b61515db6..6af79e5ad2 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceHomeViewModel.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/workspaces/AidenWorkspaceHomeViewModel.kt @@ -4,6 +4,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.async @@ -42,7 +43,8 @@ enum class AidenChatListLoadState { class AidenWorkspaceHomeViewModel( private val coordinator: AidenRemoteCoordinator, private val chatCache: AidenChatCache, - private val usageCache: AidenUsageCache = coordinator.usageCache + private val usageCache: AidenUsageCache = coordinator.usageCache, + private val cacheWriteDispatcher: CoroutineDispatcher = Dispatchers.IO ) : ViewModel() { private val _chats = MutableStateFlow>(emptyList()) val chats: StateFlow> = _chats.asStateFlow() @@ -179,14 +181,14 @@ class AidenWorkspaceHomeViewModel( val requestGeneration = ++loadGeneration loadingClient = client + val chatWriteToken = chatCache.reserveSummaryMutation(instanceId) + val previouslyLoaded = _chatListLoadState.value == AidenChatListLoadState.LOADED loadingJob = viewModelScope.launch { _isLoading.value = true _errorMessage.value = null _chatLoadErrorMessage.value = null _chatListLoadState.value = AidenChatListLoadState.LOADING - _nextChatCursor.value = null _chatPaginationErrorMessage.value = null - paginationBoundary = null try { var allCoreSucceeded = false supervisorScope { @@ -208,7 +210,9 @@ class AidenWorkspaceHomeViewModel( val chatsResult = chatsRequest.await().mapCatching { accepted -> if (isCurrentLoad(requestGeneration, client, instanceId)) { - acceptSummaryPage(accepted.summaries, replace = true) + acceptSummaryPage(accepted.summaries, replace = true, instanceId, chatWriteToken) { + isCurrentLoad(requestGeneration, client, instanceId) + } _nextChatCursor.value = accepted.nextCursor _chatLoadErrorMessage.value = null _chatListLoadState.value = AidenChatListLoadState.LOADED @@ -220,7 +224,7 @@ class AidenWorkspaceHomeViewModel( if (isCurrentLoad(requestGeneration, client, instanceId)) { _chatLoadErrorMessage.value = failure.message ?: "Aiden couldn't load chats." - _chatListLoadState.value = AidenChatListLoadState.FAILED + _chatListLoadState.value = if (previouslyLoaded) AidenChatListLoadState.LOADED else AidenChatListLoadState.FAILED } } val tasksResult = tasksRequest.await() @@ -297,7 +301,8 @@ class AidenWorkspaceHomeViewModel( val summary = AidenChatSummary.fromChat(chat) _chats.value = regularNewestFirst(_chats.value.filterNot { it.id == summary.id } + summary) coordinator.activeInstanceId?.let { instanceId -> - viewModelScope.launch(Dispatchers.IO) { runCatching { chatCache.saveChat(chat, instanceId) } } + val writeToken = chatCache.reserveSummaryMutation(instanceId) + viewModelScope.launch(cacheWriteDispatcher) { runCatching { chatCache.saveChat(chat, instanceId, writeToken) } } } } @@ -308,6 +313,7 @@ class AidenWorkspaceHomeViewModel( if (_isLoadingMoreChats.value || _chatListLoadState.value != AidenChatListLoadState.LOADED) return val requestGeneration = loadGeneration paginationJob?.cancel() + val writeToken = chatCache.reserveSummaryMutation(instanceId) paginationJob = viewModelScope.launch { _isLoadingMoreChats.value = true _chatPaginationErrorMessage.value = null @@ -320,7 +326,9 @@ class AidenWorkspaceHomeViewModel( if (accepted.usedLegacyEndpoint || accepted.nextCursor == cursor) { throw AidenRemoteContractException.InvalidJson("Invalid Chat Summary pagination response") } - acceptSummaryPage(accepted.summaries, replace = false) + acceptSummaryPage(accepted.summaries, replace = false, instanceId, writeToken) { + isCurrentPagination(requestGeneration, client, instanceId, cursor) + } _nextChatCursor.value = accepted.nextCursor } catch (error: CancellationException) { throw error @@ -339,12 +347,15 @@ class AidenWorkspaceHomeViewModel( } } - private suspend fun acceptSummaryPage(summaries: List, replace: Boolean) { + private suspend fun acceptSummaryPage( + summaries: List, replace: Boolean, instanceId: String, + writeToken: Long, isCurrent: () -> Boolean + ) { val existing = if (replace) emptyList() else _chats.value if (!replace && summaries.any { summary -> existing.any { it.id == summary.id } }) { throw AidenRemoteContractException.InvalidJson("Duplicate Chat Summary across pages") } - val boundary = paginationBoundary + val boundary = if (replace) null else paginationBoundary val first = summaries.firstOrNull() if (!replace && boundary != null && first != null && (first.updatedAt.isAfter(boundary.updatedAt) || @@ -353,18 +364,23 @@ class AidenWorkspaceHomeViewModel( throw AidenRemoteContractException.InvalidJson("Chat Summary pages are out of order") } val accepted = regularNewestFirst(existing + summaries) - val instanceId = coordinator.activeInstanceId ?: return // Persist first so a bounded-cache failure leaves the visible list, // page boundary, and cursor unchanged and Retry can request the same page. - withContext(Dispatchers.IO) { + val retained = withContext(cacheWriteDispatcher) { chatCache.saveSummaries( accepted, instanceId, - unchangedPrefixCount = if (replace) 0 else existing.size + unchangedPrefixCount = if (replace) 0 else existing.size, + writeToken = writeToken ) } + if (!isCurrent()) throw CancellationException("Chat list owner changed") + if (!retained || !chatCache.isSummaryWriteRetained(instanceId, writeToken)) { + throw IllegalStateException("Chats changed while loading. Refresh and try again.") + } paginationBoundary = summaries.lastOrNull() ?: boundary - _chats.value = accepted.filter { it.workspaceId in coordinator.workspaces.value.map(AidenWorkspace::id).toSet() } + _chats.value = regularNewestFirst(chatCache.summaries.value[instanceId]?.values.orEmpty().toList()) + .filter { it.workspaceId in coordinator.workspaces.value.map(AidenWorkspace::id).toSet() } } private suspend fun request(block: suspend () -> T): Result = try { diff --git a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenChatCache.kt b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenChatCache.kt index 46aa2bb279..f7d7f3ca93 100644 --- a/android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenChatCache.kt +++ b/android/app/src/main/java/sbtbiswas/AidenOnTheGo/persistence/AidenChatCache.kt @@ -8,6 +8,8 @@ import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import sbtbiswas.AidenOnTheGo.models.AidenAttachmentImageValidation import sbtbiswas.AidenOnTheGo.models.AidenChat +import sbtbiswas.AidenOnTheGo.models.AidenChatMessage +import sbtbiswas.AidenOnTheGo.models.AidenChatRole import sbtbiswas.AidenOnTheGo.models.AidenChatSummary import sbtbiswas.AidenOnTheGo.models.AidenChatSummaryActivity import sbtbiswas.AidenOnTheGo.models.AidenMessageAttachment @@ -23,12 +25,14 @@ import java.nio.file.Files import java.nio.file.StandardCopyOption import java.security.MessageDigest import java.util.Date +import java.util.concurrent.atomic.AtomicLong class AidenChatCache( private val storageDir: File? = null, root: File? = null, legacyRoots: List? = null, - private val maximumSummaryCacheBytes: Int = 64 * 1024 * 1024 + private val maximumSummaryCacheBytes: Int = 64 * 1024 * 1024, + private val beforeActiveStreamWrite: (() -> Unit)? = null ) { @Serializable data class ActiveStream( @@ -87,6 +91,29 @@ class AidenChatCache( val root: File val legacyRoots: List + private val writeClock = AtomicLong() + private val chatRemovalTokens = mutableMapOf>() + private data class ReceiptMessage(val message: AidenChatMessage, val throughWriteToken: Long) + private val receiptMessages = mutableMapOf>>() + private val receiptTokens = mutableMapOf>() + private val receiptStreams = mutableMapOf>() + private val chatWriteTokens = mutableMapOf>() + private val admittedChats = mutableMapOf>() + private val summaryWriteTokens = mutableMapOf() + private val purgeWriteTokens = mutableMapOf() + + // Reserve before scheduling a deferred writer, not when its IO task runs. + fun reserveChatWrite(): Long = writeClock.incrementAndGet() + + @Synchronized + fun reserveSummaryMutation(instanceId: String): Long = reserveChatWrite().also { + summaryWriteTokens[instanceId] = it + } + + @Synchronized + fun isSummaryWriteRetained(instanceId: String, writeToken: Long): Boolean = + writeToken > (purgeWriteTokens[instanceId] ?: 0L) + private val _chats = MutableStateFlow>(emptyMap()) val chats: StateFlow> = _chats.asStateFlow() private val _summaries = MutableStateFlow>>(emptyMap()) @@ -174,14 +201,18 @@ class AidenChatCache( fun saveSummaries( summaries: List, instanceId: String, - unchangedPrefixCount: Int = 0 - ) { + unchangedPrefixCount: Int = 0, + writeToken: Long = reserveChatWrite() + ): Boolean { + if (writeToken <= (purgeWriteTokens[instanceId] ?: 0L) || + writeToken < (summaryWriteTokens[instanceId] ?: 0L)) return false if (summaries.size > maxSummaryCount || summaries.map { it.id }.toSet().size != summaries.size) { throw IllegalArgumentException("Chat summary cache must contain at most 10,000 unique IDs") } if (unchangedPrefixCount !in 0..summaries.size) { throw IllegalArgumentException("Unchanged summary prefix is invalid") } + summaryWriteTokens[instanceId] = writeToken val manifestFile = fileURL("summary-manifests", instanceId) val existing = loadEnvelope(manifestFile) val cachedPrefixMatches = unchangedPrefixCount == 0 || @@ -272,6 +303,7 @@ class AidenChatCache( ) } publishSummaries(instanceId, summaries) + return true } private fun cleanupSummaryChunks(directory: File, retainedChunkIds: Set) { @@ -298,6 +330,7 @@ class AidenChatCache( @Synchronized fun removeSummary(instanceId: String, chatId: String) { + reserveSummaryMutation(instanceId) val current = summariesForInstance(instanceId) if (current.none { it.id == chatId }) return saveSummaries(current.filterNot { it.id == chatId }, instanceId) @@ -307,12 +340,14 @@ class AidenChatCache( fun updateSummaryActivity( instanceId: String, chatId: String, - activity: AidenChatSummaryActivity + activity: AidenChatSummaryActivity, + writeToken: Long? = null ) { val current = summariesForInstance(instanceId) val existing = current.firstOrNull { it.id == chatId } ?: return if (existing.activity == activity) return - saveSummaries(current.map { if (it.id == chatId) it.copy(activity = activity) else it }, instanceId) + saveSummaries(current.map { if (it.id == chatId) it.copy(activity = activity) else it }, instanceId, + writeToken = writeToken ?: reserveChatWrite()) } @Synchronized @@ -323,26 +358,100 @@ class AidenChatCache( return envelope.chat } + // The accepted response remains usable even when its best-effort disk write fails. + @Synchronized + fun admittedChat(instanceId: String, chatId: String): AidenChat? { + admittedChats[instanceId]?.get(chatId)?.let { return it } + // Never recover a removed winner from a file left by a failed cleanup. + if (chatWriteTokens[instanceId]?.containsKey(chatId) == true || purgeWriteTokens.containsKey(instanceId)) return null + return loadChat(instanceId, chatId) + } + @Synchronized - fun saveChat(chat: AidenChat, instanceId: String) { + fun saveChat(chat: AidenChat, instanceId: String, writeToken: Long = reserveChatWrite(), summaryWriteToken: Long = writeToken): Boolean { + if (writeToken <= (purgeWriteTokens[instanceId] ?: 0L) || + writeToken <= (chatWriteTokens[instanceId]?.get(chat.id) ?: 0L)) return false + chatWriteTokens.getOrPut(instanceId) { mutableMapOf() }[chat.id] = writeToken + val pending = receiptMessages[instanceId]?.get(chat.id) + // Only snapshots already in flight when the receipt was accepted need + // its overlay. A later-requested snapshot can retire it, and its admitted + // high-water also prevents older in-flight snapshots from returning. + pending?.removeAll { writeToken > it.throughWriteToken } + val accepted = pending.orEmpty().fold(chat) { snapshot, receipt -> mergeReceipt(snapshot, receipt.message) } + persistAdmittedChat(accepted, instanceId, summaryWriteToken) + return true + } + + // Caller holds the cache monitor and has already established request authority. + private fun persistAdmittedChat(chat: AidenChat, instanceId: String, summaryWriteToken: Long) { + val ownsSummary = summaryWriteToken >= (summaryWriteTokens[instanceId] ?: 0L) + admittedChats.getOrPut(instanceId) { mutableMapOf() }[chat.id] = chat + val visibleSummaries = summariesForInstance(instanceId).associateBy { it.id }.toMutableMap() + if (ownsSummary) { + summaryWriteTokens[instanceId] = summaryWriteToken + if (chat.isBotChat) visibleSummaries.remove(chat.id) + else visibleSummaries[chat.id] = AidenChatSummary.fromChat(chat, visibleSummaries[chat.id]?.activity ?: AidenChatSummaryActivity.IDLE) + publishSummaries(instanceId, visibleSummaries.values.toList()) + } val envelope = ChatEnvelope(instanceId = instanceId, chat = chat) saveEnvelope(envelope, fileURL("chats", instanceId, chat.id)) val map = _chats.value.toMutableMap() map[chat.id] = chat _chats.value = map - if (chat.isBotChat) { - removeSummary(instanceId, chat.id) - } else { - val activity = summariesForInstance(instanceId) - .firstOrNull { it.id == chat.id } - ?.activity - ?: AidenChatSummaryActivity.IDLE - upsertSummary(AidenChatSummary.fromChat(chat, activity), instanceId) + if (ownsSummary) saveSummaries(visibleSummaries.values.toList(), instanceId, writeToken = summaryWriteToken) + } + + private fun mergeReceipt(chat: AidenChat, message: AidenChatMessage): AidenChat { + if (chat.messages.any { it.id == message.id }) return chat + val messages = chat.messages.toMutableList() + val position = messages.indexOfFirst { + it.createdAt.isAfter(message.createdAt) || + (it.createdAt == message.createdAt && it.role == AidenChatRole.ASSISTANT) + }.let { if (it < 0) messages.size else it } + messages.add(position, message) + return chat.copy(messages = messages) + } + + data class AcceptedTurn(val chat: AidenChat, val stream: ActiveStream?) + + @Synchronized + fun isChatWriteRetained(instanceId: String, chatId: String, token: Long): Boolean = + token > (purgeWriteTokens[instanceId] ?: 0L) && token > (chatRemovalTokens[instanceId]?.get(chatId) ?: 0L) + + @Synchronized + fun acceptTurnReceipt(candidate: AidenChat, message: AidenChatMessage, stream: ActiveStream, instanceId: String, requestToken: Long): AcceptedTurn? { + if (!isChatWriteRetained(instanceId, candidate.id, requestToken)) return null + val winner = if ((chatWriteTokens[instanceId]?.get(candidate.id) ?: 0L) > requestToken) { + admittedChat(instanceId, candidate.id) ?: return null + } else candidate + val pending = receiptMessages.getOrPut(instanceId) { mutableMapOf() } + .getOrPut(candidate.id) { mutableListOf() } + if (pending.none { it.message.id == message.id }) pending.add(ReceiptMessage(message, writeClock.get())) + val accepted = pending.fold(winner) { snapshot, receipt -> mergeReceipt(snapshot, receipt.message) } + // Merge the accepted mutation without minting response-time authority. + // A later-started GET must remain eligible in either completion order. + // A prior admitted winner keeps its own authority and metadata. + chatWriteTokens.getOrPut(instanceId) { mutableMapOf() }[candidate.id] = + maxOf(requestToken, chatWriteTokens[instanceId]?.get(candidate.id) ?: 0L) + runCatching { persistAdmittedChat(accepted, instanceId, requestToken) } + if (requestToken > (receiptTokens[instanceId]?.get(candidate.id) ?: 0L)) { + receiptTokens.getOrPut(instanceId) { mutableMapOf() }[candidate.id] = requestToken + receiptStreams.getOrPut(instanceId) { mutableMapOf() }[candidate.id] = stream + runCatching { + saveActiveStream(stream, instanceId, candidate.id, + summaryWriteToken = maxOf(requestToken, summaryWriteTokens[instanceId] ?: 0L)) + }.onFailure { + // Never leave an older receipt resumable after a failed replacement. + // Keep the accepted in-memory marker even when storage is unavailable. + runCatching { fileURL("streams", instanceId, candidate.id).delete() } + } } + return AcceptedTurn(accepted, loadActiveStream(instanceId, candidate.id)) } @Synchronized fun loadActiveStream(instanceId: String, chatId: String): ActiveStream? { + receiptStreams[instanceId]?.get(chatId)?.let { return it } val file = fileURL("streams", instanceId, chatId) val envelope = loadEnvelope(file) ?: return null if (envelope.instanceId != instanceId || envelope.chatId != chatId) return null @@ -350,14 +459,16 @@ class AidenChatCache( } @Synchronized - fun saveActiveStream(stream: ActiveStream, instanceId: String, chatId: String) { + fun saveActiveStream(stream: ActiveStream, instanceId: String, chatId: String, summaryWriteToken: Long? = null) { + beforeActiveStreamWrite?.invoke() val envelope = StreamEnvelope(instanceId = instanceId, chatId = chatId, stream = stream) saveEnvelope(envelope, fileURL("streams", instanceId, chatId)) - updateSummaryActivity(instanceId, chatId, AidenChatSummaryActivity.ACTIVE) + updateSummaryActivity(instanceId, chatId, AidenChatSummaryActivity.ACTIVE, summaryWriteToken) } @Synchronized fun removeActiveStream(instanceId: String, chatId: String) { + receiptStreams[instanceId]?.remove(chatId) val file = fileURL("streams", instanceId, chatId) if (file.exists()) file.delete() updateSummaryActivity(instanceId, chatId, AidenChatSummaryActivity.IDLE) @@ -373,6 +484,11 @@ class AidenChatCache( @Synchronized fun removeChat(instanceId: String, chatId: String) { + val removalToken = reserveSummaryMutation(instanceId) + chatWriteTokens.getOrPut(instanceId) { mutableMapOf() }[chatId] = removalToken + chatRemovalTokens.getOrPut(instanceId) { mutableMapOf() }[chatId] = removalToken + admittedChats[instanceId]?.remove(chatId) + receiptMessages[instanceId]?.remove(chatId) val chatFile = fileURL("chats", instanceId, chatId) if (chatFile.exists()) chatFile.delete() removeActiveStream(instanceId, chatId) @@ -386,6 +502,12 @@ class AidenChatCache( @Synchronized fun purge(instanceId: String) { + purgeWriteTokens[instanceId] = reserveChatWrite() + chatWriteTokens.remove(instanceId) + admittedChats.remove(instanceId) + receiptStreams.remove(instanceId) + receiptTokens.remove(instanceId) + receiptMessages.remove(instanceId) purgeNamespace(root, instanceId) for (legacy in legacyRoots) { if (legacy.canonicalPath != root.canonicalPath) { diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatSummaryTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatSummaryTest.kt index 979138612c..3c98239484 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatSummaryTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatSummaryTest.kt @@ -2,6 +2,11 @@ package sbtbiswas.AidenOnTheGo import com.sun.management.ThreadMXBean import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.asCoroutineDispatcher +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.test.resetMain import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json @@ -54,6 +59,104 @@ class AidenChatSummaryTest { server.shutdown() } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + @Test + fun heldHomePagesPreserveNewerRowsAndPaginationOwnership() { + val main = java.util.concurrent.Executors.newSingleThreadExecutor().asCoroutineDispatcher() + kotlinx.coroutines.Dispatchers.setMain(main) + try { + runBlocking(main) { + for ((pagination, purging, afterCommit) in listOf(Triple(false, false, false), Triple(true, false, false), Triple(false, true, false), Triple(true, true, false), Triple(true, false, true))) { + val root = tempFolder.newFolder() + val arrived = java.util.concurrent.CountDownLatch(1) + val release = java.util.concurrent.CountDownLatch(1) + val reads = java.util.concurrent.atomic.AtomicInteger() + val cursor = canonicalCursor("held-page") + val first = summary("chat-1", "workspace-1", "Before settlement", AidenChatSummaryActivity.IDLE) + server.dispatcher = object : okhttp3.mockwebserver.Dispatcher() { + override fun dispatch(request: okhttp3.mockwebserver.RecordedRequest): MockResponse { + val path = request.requestUrl!!.encodedPath + return when { + path.endsWith("/server") -> MockResponse().setBody(json.encodeToString(AidenServer( + instanceId = "home-instance", name = "Home", capabilities = listOf(AidenRemoteCapability.CHAT_READ), features = listOf("chat-summaries-v1")))) + path.endsWith("/workspaces") -> MockResponse().setBody("""{"workspaces":[{"id":"workspace-1","name":"Workspace","permission":"ask","revision":"rev-1"}]}""") + path.endsWith("/chat-summaries") -> { + val number = reads.incrementAndGet() + if (number == 2) { arrived.countDown(); check(release.await(8, java.util.concurrent.TimeUnit.SECONDS)) } + if (request.requestUrl!!.queryParameter("cursor") != null) MockResponse().setBody("""{"summaries":[${json.encodeToString(first.copy(id = "chat-2", updatedAt = first.updatedAt.minusSeconds(1)))}]}""") + else MockResponse().setBody("""{"summaries":[${json.encodeToString(first)}],"nextCursor":"$cursor"}""") + } + else -> MockResponse().setResponseCode(503) + } + } + } + val store = sbtbiswas.AidenOnTheGo.persistence.AidenInstallationStore(root, sbtbiswas.AidenOnTheGo.auth.InMemoryAidenSecureStore()) + store.addInstallation(AidenPairingExchange(instanceId = "home-instance", deviceId = "home-device", endpoint = server.url("/api/aiden/v1").toString(), serverSpkiSha256 = "sha256/test", credential = "synthetic", capabilities = listOf(AidenRemoteCapability.CHAT_READ)), null) + val cache = AidenChatCache(root = File(root, "cache")) + val scope = kotlinx.coroutines.CoroutineScope(main + kotlinx.coroutines.Job()) + val coordinator = sbtbiswas.AidenOnTheGo.features.remote.AidenRemoteCoordinator(store, root, cache, scope = scope) + val owners = androidx.lifecycle.ViewModelStore() + try { + kotlinx.coroutines.withTimeout(5_000) { coordinator.workspaces.first { it.isNotEmpty() } } + val writes = java.util.concurrent.atomic.AtomicInteger() + val cacheDispatcher = object : kotlinx.coroutines.CoroutineDispatcher() { + override fun dispatch(context: kotlin.coroutines.CoroutineContext, block: Runnable) { + main.dispatch(context, Runnable { + block.run() + // Same single-thread executor: mutate after the cache commit, + // before its queued Home continuation can publish the cursor. + if (afterCommit && writes.incrementAndGet() == 2) { + cache.saveChat(fullChat("chat-1", "workspace-1", "Settled title", canonicalRevision("settled")), "home-instance") + } + }) + } + } + val home = sbtbiswas.AidenOnTheGo.features.workspaces.AidenWorkspaceHomeViewModel(coordinator, cache, cacheWriteDispatcher = cacheDispatcher) + owners.put("home", home) + kotlinx.coroutines.withTimeout(5_000) { home.nextChatCursor.first { it == cursor } } + if (pagination) home.loadMoreChats() else home.load(force = true) + kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { check(arrived.await(5, java.util.concurrent.TimeUnit.SECONDS)) } + val settled = fullChat("chat-1", "workspace-1", "Settled title", canonicalRevision("settled")) + if (purging) cache.purge("home-instance") + else if (!afterCommit) cache.saveChat(settled, "home-instance") + release.countDown() + if (pagination) kotlinx.coroutines.withTimeout(5_000) { home.isLoadingMoreChats.first { !it } } + else kotlinx.coroutines.withTimeout(5_000) { home.isLoading.first { !it } } + assertEquals(if (afterCommit) null else cursor, home.nextChatCursor.value) + val expected = if (purging) emptyList() else if (afterCommit) listOf("Settled title", "Before settlement") else listOf("Settled title") + assertEquals(expected, home.chats.value.map { it.title }) + assertEquals(if (purging) null else expected, AidenChatCache(root = File(root, "cache")).loadSummaries("home-instance")?.map { it.title }) + if (afterCommit) assertNull(home.chatPaginationErrorMessage.value) + else assertNotNull(if (pagination) home.chatPaginationErrorMessage.value else home.chatLoadErrorMessage.value) + if (pagination && !purging && !afterCommit) { + home.loadMoreChats() + kotlinx.coroutines.withTimeout(5_000) { home.nextChatCursor.first { it == null } } + assertEquals(listOf("chat-1", "chat-2"), home.chats.value.map { it.id }) + assertNull(home.chatPaginationErrorMessage.value) + } + } finally { release.countDown(); owners.clear(); scope.cancel() } + } + } + } finally { kotlinx.coroutines.Dispatchers.resetMain(); main.close() } + } + + @Test + fun queuedDetailCannotReplaceNewerSummaryAndNewRequestRejectsOldWriter() { + val cache = AidenChatCache(root = tempFolder.newFolder()) + val initial = fullChat("chat-1", "workspace-1", "Old title", canonicalRevision("old")) + val oldDetail = cache.reserveSummaryMutation("instance") + val page = cache.reserveSummaryMutation("instance") + assertTrue(cache.saveSummaries(listOf(AidenChatSummary.fromChat(initial.copy(title = "New page"))), "instance", writeToken = page)) + assertTrue(cache.saveChat(initial, "instance", oldDetail)) + assertEquals("Old title", cache.loadChat("instance", initial.id)?.title) + assertEquals("New page", cache.loadSummaries("instance")?.single()?.title) + val oldRequest = cache.reserveSummaryMutation("instance") + cache.reserveSummaryMutation("instance") // New request can fail without admitting the old writer. + assertFalse(cache.saveSummaries(emptyList(), "instance", writeToken = oldRequest)) + assertEquals("New page", cache.loadSummaries("instance")?.single()?.title) + assertTrue(cache.saveSummaries(emptyList(), "other", writeToken = oldRequest)) + } + @Test fun summaryEndpointDecodesRequiredFieldsAndToleratesHarmlessAdditions() = runBlocking { val nextCursor = canonicalCursor("next-page") diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt index 8e981e32fd..df12b8a65f 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt @@ -102,8 +102,16 @@ class AidenChatTest { @Test fun heldInitialLoadCannotOverwriteSettledTranscriptOrCache() = assertStreamRecovery(holdInitialLoad = true) + @Test + fun anotherOwnersHeldLoadCannotOverwriteSettledTranscriptOrCache() = + assertStreamRecovery(holdInitialLoad = true, independentOwner = true) + + @Test + fun anotherOwnersHeldLoadAdoptsWinnerWhenDiskWriteFails() = + assertStreamRecovery(holdInitialLoad = true, independentOwner = true, failDiskWrite = true) + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) - private fun assertStreamRecovery(holdInitialLoad: Boolean = false) { + private fun assertStreamRecovery(holdInitialLoad: Boolean = false, independentOwner: Boolean = false, failDiskWrite: Boolean = false) { val directory = kotlin.io.path.createTempDirectory("aiden-stream-recovery-").toFile() val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher() val server = MockWebServer() @@ -112,6 +120,7 @@ class AidenChatTest { val chatReads = java.util.concurrent.atomic.AtomicInteger() val eventReads = java.util.concurrent.atomic.AtomicInteger() val releaseInitialLoad = CountDownLatch(1) + val initialLoadArrived = CountDownLatch(1) val initial = AidenChat( id = "chat-recovery", workspaceId = "workspace-recovery", title = "Recovery", messages = emptyList(), createdAt = Instant.EPOCH, updatedAt = Instant.EPOCH, revision = "r1" @@ -143,6 +152,7 @@ class AidenChatTest { """{"streamId":"stream-recovery","chatId":"chat-recovery","turnId":"turn-recovery","state":"running","lastSequence":1}""" ) path.endsWith("/chats/chat-recovery") && chatReads.incrementAndGet() == 1 -> { + initialLoadArrived.countDown() if (holdInitialLoad) check(releaseInitialLoad.await(10, TimeUnit.SECONDS)) MockResponse().setBody(wireJson.encodeToString(initial)) } @@ -166,11 +176,20 @@ class AidenChatTest { ), null) val cache = AidenChatCache(directory) cache.saveChat(initial, "instance-recovery") - cache.saveActiveStream(AidenChatCache.ActiveStream("device-recovery", "stream-recovery", "turn-recovery", 27), "instance-recovery", initial.id) val drafts = AidenChatDraftStore(directory) val coordinator = AidenRemoteCoordinator(installations, directory, cache, drafts, scope = CoroutineScope(dispatcher + Job().apply { cancel() })) coordinator.refreshClient() + val otherOwner = if (independentOwner) { + AidenChatViewModel(initial.id, coordinator, cache, drafts, initial).also { + viewModels.put("other", it) + withContext(Dispatchers.IO) { check(initialLoadArrived.await(5, TimeUnit.SECONDS)) } + } + } else null + cache.saveActiveStream(AidenChatCache.ActiveStream("device-recovery", "stream-recovery", "turn-recovery", 27), "instance-recovery", initial.id) + if (failDiskWrite) { + File(cache.root, "chats").apply { deleteRecursively(); writeText("blocked directory") } + } val model = AidenChatViewModel(initial.id, coordinator, cache, drafts, initial) viewModels.put("chat", model) withTimeout(8_000) { model.streamState.first { it == AidenStreamState.DONE } } @@ -180,7 +199,15 @@ class AidenChatTest { releaseInitialLoad.countDown() withTimeout(5_000) { model.isLoading.first { !it } } assertEquals("final-reply", model.chat.value!!.messages.last().id) - assertEquals("final-reply", cache.loadChat("instance-recovery", initial.id)!!.messages.last().id) + assertEquals("final-reply", cache.admittedChat("instance-recovery", initial.id)!!.messages.last().id) + if (otherOwner != null) { + withTimeout(5_000) { otherOwner.isLoading.first { !it } } + assertEquals("final-reply", otherOwner.chat.value!!.messages.lastOrNull()?.id) + if (failDiskWrite) assertNull(AidenChatCache(directory).loadChat("instance-recovery", initial.id)) + else assertEquals("final-reply", AidenChatCache(directory).loadChat("instance-recovery", initial.id)!!.messages.lastOrNull()?.id) + otherOwner.updateDraft("Continue from another destination") + assertTrue(otherOwner.canSend) + } assertEquals("", model.liveText.value) } else { // Let the terminal reconciliation attempt and any illegally queued late frame run. @@ -208,6 +235,182 @@ class AidenChatTest { } } + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + @Test + fun heldTurnReceiptPreservesOtherOwnerAndCannotCrossRemoval() { + val main = Executors.newSingleThreadExecutor().asCoroutineDispatcher() + Dispatchers.setMain(main) + try { + runBlocking(main) { + for (mode in listOf("newer", "missing", "newer_post", "purge", "remove", "disk", "stream_disk", "replace_disk", "unpair", "switch", "repair", "inverse", "inverse_missing", "ordered_posts")) { + val root = kotlin.io.path.createTempDirectory("aiden-turn-owner-").toFile() + val server = MockWebServer() + val owners = ViewModelStore() + val arrived = CountDownLatch(1) + val release = CountDownLatch(1) + val secondPostArrived = CountDownLatch(1) + val getArrived = CountDownLatch(1) + val getRelease = CountDownLatch(1) + val postCount = java.util.concurrent.atomic.AtomicInteger() + val initial = sampleChat().copy(messages = emptyList()) + val accepted = AidenChatMessage("accepted-user", AidenChatRole.USER, "Hello", createdAt = Instant.EPOCH) + val second = accepted.copy(id = "second-user", text = "Second", createdAt = Instant.EPOCH.plusSeconds(2)) + val settled = initial.copy(title = "Settled title", revision = "settled-revision", messages = listOf(accepted, + AidenChatMessage("settled-assistant", AidenChatRole.ASSISTANT, "Final", createdAt = Instant.EPOCH.plusSeconds(1)))) + val remote = java.util.concurrent.atomic.AtomicReference(initial) + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse = when { + request.requestUrl!!.encodedPath.endsWith("/turns") -> { + val count = postCount.incrementAndGet() + if (count == 1) { arrived.countDown(); check(release.await(8, TimeUnit.SECONDS)) } + if (count == 2 && mode == "ordered_posts") { secondPostArrived.countDown(); check(getRelease.await(8, TimeUnit.SECONDS)) } + MockResponse().setResponseCode(202).setBody("""{"turnId":"accepted-turn-$count","streamId":"accepted-stream-$count","status":"queued","message":${json.encodeToString(if (count == 1) accepted else second)}}""") + } + request.requestUrl!!.encodedPath.endsWith("/events") -> MockResponse().setSocketPolicy(okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE) + request.requestUrl!!.encodedPath.endsWith("/chats/" + initial.id) -> { + val snapshot = remote.get() + if (mode.startsWith("inverse") && snapshot != initial) { + getArrived.countDown(); check(getRelease.await(8, TimeUnit.SECONDS)) + } + MockResponse().setBody(json.encodeToString(snapshot)) + } + else -> MockResponse().setResponseCode(404) + } + } + server.start() + try { + val store = AidenInstallationStore(root, InMemoryAidenSecureStore()) + store.addInstallation(AidenPairingExchange(instanceId = "turn-instance", deviceId = "turn-device", + endpoint = server.url("/api/aiden/v1").toString(), serverSpkiSha256 = "sha256/test", credential = "synthetic", + capabilities = listOf(AidenRemoteCapability.CHAT_READ, AidenRemoteCapability.CHAT_WRITE)), null) + var failStreamWrite = false + val cache = AidenChatCache(root = File(root, "cache"), beforeActiveStreamWrite = { + if (failStreamWrite) throw java.io.IOException("held stream persistence failure") + }) + val drafts = AidenChatDraftStore(root) + val coordinator = AidenRemoteCoordinator(store, root, cache, drafts, scope = CoroutineScope(main + Job().apply { cancel() })) + coordinator.refreshClient() + val sender = AidenChatViewModel(initial.id, coordinator, cache, drafts, initial) + owners.put("sender", sender) + yield(); withTimeout(5_000) { sender.isLoading.first { !it } } + sender.updateDraft("Hello") + assertTrue(sender.canSend) + sender.send() + withContext(Dispatchers.IO) { check(arrived.await(5, TimeUnit.SECONDS)) } + remote.set(if (mode in listOf("missing", "inverse_missing", "ordered_posts")) settled.copy(messages = settled.messages.drop(1)) else settled) + val other = AidenChatViewModel(initial.id, coordinator, cache, drafts, initial) + owners.put("other", other) + if (mode.startsWith("inverse")) { + withContext(Dispatchers.IO) { check(getArrived.await(5, TimeUnit.SECONDS)) } + release.countDown() + withTimeout(5_000) { sender.isStarting.first { !it } } + getRelease.countDown() + } + yield(); withTimeout(5_000) { other.isLoading.first { !it } } + assertEquals("settled-assistant", other.chat.value!!.messages.last().id) + if (mode in listOf("newer_post", "ordered_posts")) { + other.updateDraft("Second") + assertTrue(other.canSend) + other.send() + if (mode == "ordered_posts") { + withContext(Dispatchers.IO) { check(secondPostArrived.await(5, TimeUnit.SECONDS)) } + release.countDown() + withTimeout(5_000) { sender.isStarting.first { !it } } + getRelease.countDown() + } + yield(); withTimeout(5_000) { other.isStarting.first { !it } } + assertEquals("accepted-stream-2", cache.loadActiveStream("turn-instance", initial.id)?.streamId) + } + when (mode) { + "unpair" -> store.removeInstallation("turn-instance") + "switch" -> { store.setActiveInstallation(null); coordinator.refreshClient() } + "repair" -> store.addInstallation(AidenPairingExchange(instanceId = "turn-instance", deviceId = "turn-device", + endpoint = server.url("/api/aiden/v1").toString(), serverSpkiSha256 = "sha256/test", credential = "replacement", + capabilities = listOf(AidenRemoteCapability.CHAT_READ, AidenRemoteCapability.CHAT_WRITE)), null) + "replace_disk" -> { + cache.saveActiveStream(AidenChatCache.ActiveStream("turn-device", "old-stream", "old-turn", 0), "turn-instance", initial.id) + assertEquals("old-stream", AidenChatCache(root = File(root, "cache")).loadActiveStream("turn-instance", initial.id)?.streamId) + failStreamWrite = true + } + "purge" -> cache.purge("turn-instance") + "remove" -> { cache.removeChat("turn-instance", initial.id); cache.saveChat(initial.copy(title = "Fresh readmission"), "turn-instance") } + "disk" -> File(cache.root, "chats").apply { deleteRecursively(); writeText("blocked directory") } + "stream_disk" -> File(cache.root, "streams").apply { deleteRecursively(); writeText("blocked directory") } + } + release.countDown() + withTimeout(5_000) { sender.isStarting.first { !it } } + val reopened = AidenChatCache(root = File(root, "cache")) + if (mode == "ordered_posts") { + assertEquals(settled.messages + second, other.chat.value!!.messages) + assertEquals(settled.messages + second, reopened.loadChat("turn-instance", initial.id)!!.messages) + assertEquals("accepted-stream-2", cache.loadActiveStream("turn-instance", initial.id)?.streamId) + } else if (mode.startsWith("inverse")) { + assertEquals(settled.messages, other.chat.value!!.messages) + assertEquals(settled.title, other.chat.value!!.title) + assertEquals(settled, reopened.loadChat("turn-instance", initial.id)) + assertEquals("accepted-stream-1", cache.loadActiveStream("turn-instance", initial.id)?.streamId) + assertEquals("accepted-stream-1", reopened.loadActiveStream("turn-instance", initial.id)?.streamId) + assertNull(sender.presentedError.value) + assertEquals("", sender.draft.value) + assertEquals(settled.title, cache.loadSummaries("turn-instance")!!.first { it.id == initial.id }.title) + } else if (mode in listOf("unpair", "switch", "repair")) { + assertFalse(sender.hasActiveStream.value) + assertEquals(settled.messages, sender.chat.value!!.messages) + assertEquals(if (mode == "switch") "accepted-stream-1" else null, cache.loadActiveStream("turn-instance", initial.id)?.streamId) + assertNull(sender.presentedError.value) + assertEquals("", sender.draft.value) + } else if (mode !in listOf("purge", "remove")) { + val expectedMessages = if (mode == "newer_post") settled.messages + second else settled.messages + assertEquals(expectedMessages, sender.chat.value!!.messages) + assertEquals(settled.revision, sender.chat.value!!.revision) + val expectedStream = if (mode == "newer_post") "accepted-stream-2" else "accepted-stream-1" + assertEquals(expectedStream, cache.loadActiveStream("turn-instance", initial.id)?.streamId) + assertEquals(if (mode in listOf("stream_disk", "replace_disk")) null else expectedStream, reopened.loadActiveStream("turn-instance", initial.id)?.streamId) + assertTrue(sender.hasActiveStream.value) + assertNull(sender.presentedError.value) + assertEquals("", sender.draft.value) + if (mode == "newer") assertEquals(settled.messages, reopened.loadChat("turn-instance", initial.id)?.messages) + } else { + assertNull(reopened.loadActiveStream("turn-instance", initial.id)) + assertFalse(sender.hasActiveStream.value) + assertEquals(if (mode == "remove") "Fresh readmission" else null, reopened.loadChat("turn-instance", initial.id)?.title) + } + assertEquals(if (mode in listOf("newer_post", "ordered_posts")) 2 else 1, postCount.get()) + } finally { release.countDown(); getRelease.countDown(); owners.clear(); server.shutdown(); root.deleteRecursively() } + } + } + } finally { Dispatchers.resetMain(); main.close() } + } + + @Test + fun receiptOverlayRetiresAtFreshSnapshotAndDoesNotCrossDeletion() { + val root = kotlin.io.path.createTempDirectory("aiden-receipt-overlay-").toFile() + try { + val cache = AidenChatCache(root = root) + val chat = sampleChat().copy(messages = emptyList()) + val receipt = AidenChatMessage("accepted", AidenChatRole.USER, "Accepted", createdAt = Instant.EPOCH) + val stream = AidenChatCache.ActiveStream("device", "stream", "turn", 0) + for (mode in listOf("fresh", "remove", "purge")) { + val instance = "overlay-$mode" + cache.saveChat(chat, instance) + val post = cache.reserveChatWrite() + val heldGet = cache.reserveChatWrite() + cache.acceptTurnReceipt(chat, receipt, stream, instance, post) + assertTrue(cache.saveChat(chat, instance, heldGet)) + assertEquals(listOf(receipt), cache.admittedChat(instance, chat.id)!!.messages) + when (mode) { + "remove" -> cache.removeChat(instance, chat.id) + "purge" -> cache.purge(instance) + } + val fresh = chat.copy(title = "Fresh snapshot", revision = "fresh") + assertTrue(cache.saveChat(fresh, instance, cache.reserveChatWrite())) + assertEquals(fresh, cache.admittedChat(instance, chat.id)) + assertFalse(cache.saveChat(chat, instance, heldGet)) + assertEquals(fresh, AidenChatCache(root = root).loadChat(instance, chat.id)) + } + } finally { root.deleteRecursively() } + } + @Test fun failedSendRestoresDurableDraftAfterRestart() = assertFailedSendDraft() @@ -1176,6 +1379,81 @@ class AidenChatTest { assertTrue(ordinaryAction.canAllow) } + @Test + fun queuedHomeWriteCannotReplaceNewerAcceptedChat() { + val root = File(System.getProperty("java.io.tmpdir"), "aiden-queued-home-${UUID.randomUUID()}").apply { mkdirs() } + try { + val cache = AidenChatCache(root = root) + val initial = sampleChat() + // Model the closure queued by WorkspaceHome.accept before navigation. + val token = cache.reserveChatWrite() + val queuedHomeWrite = Runnable { cache.saveChat(initial, "instance-a", token) } + val final = initial.copy(title = "Settled title") + cache.saveChat(final, "instance-a") + queuedHomeWrite.run() + assertEquals("Settled title", AidenChatCache(root = root).loadChat("instance-a", initial.id)?.title) + } finally { root.deleteRecursively() } + } + + @Test + fun queuedHomeWriteCannotRecreatePurgedInstallation() { + val root = File(System.getProperty("java.io.tmpdir"), "aiden-queued-purge-${UUID.randomUUID()}").apply { mkdirs() } + try { + val cache = AidenChatCache(root = root) + val initial = sampleChat() + val token = cache.reserveChatWrite() + val queuedHomeWrite = Runnable { cache.saveChat(initial, "instance-a", token) } + cache.purge("instance-a") + queuedHomeWrite.run() + assertNull(AidenChatCache(root = root).loadChat("instance-a", initial.id)) + } finally { root.deleteRecursively() } + } + + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + @Test + fun homeOwnerReservesBeforeQueuedCacheWrite() { + val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher() + val queued = kotlinx.coroutines.test.StandardTestDispatcher() + Dispatchers.setMain(dispatcher) + try { + runBlocking(dispatcher) { + for (purging in listOf(false, true)) { + val root = File(System.getProperty("java.io.tmpdir"), "aiden-home-owner-${UUID.randomUUID()}").apply { mkdirs() } + val viewModels = ViewModelStore() + try { + val installations = AidenInstallationStore(root, InMemoryAidenSecureStore()) + installations.addInstallation(AidenPairingExchange( + instanceId = "instance-a", deviceId = "device-a", + endpoint = "https://aiden.test/api/aiden/v1", serverSpkiSha256 = "sha256/test", + credential = "synthetic", capabilities = listOf(AidenRemoteCapability.CHAT_READ) + ), null) + val cache = AidenChatCache(root = File(root, "cache")) + val drafts = AidenChatDraftStore(root) + val coordinator = AidenRemoteCoordinator(installations, root, cache, drafts, + scope = CoroutineScope(dispatcher + Job().apply { cancel() })) + coordinator.refreshClient() + val home = sbtbiswas.AidenOnTheGo.features.workspaces.AidenWorkspaceHomeViewModel( + coordinator, cache, cacheWriteDispatcher = queued) + viewModels.put("home", home) + val initial = sampleChat() + home.accept(initial) + if (purging) cache.purge("instance-a") + else cache.saveChat(initial.copy(title = "Settled title"), "instance-a") + queued.scheduler.runCurrent() + val reopened = AidenChatCache(root = File(root, "cache")) + if (purging) assertNull(reopened.loadChat("instance-a", initial.id)) + else assertEquals("Settled title", reopened.loadChat("instance-a", initial.id)?.title) + // Another installation and a fresh post-purge owner remain valid. + cache.saveChat(initial, "instance-b") + cache.saveChat(initial.copy(title = "New owner"), "instance-a") + assertEquals("New owner", reopened.loadChat("instance-a", initial.id)?.title) + assertNotNull(reopened.loadChat("instance-b", initial.id)) + } finally { viewModels.clear(); root.deleteRecursively() } + } + } + } finally { Dispatchers.resetMain(); dispatcher.close() } + } + @Test fun testChatCachePartitionAndActiveStream() { val tempDir = File(System.getProperty("java.io.tmpdir"), "aiden-cache-test-${UUID.randomUUID()}").apply { mkdirs() } From 1b693a2f1b90cab1853b771d047e1c2ed4a5635c Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 26 Sep 2026 01:50:49 -0400 Subject: [PATCH 2/7] Preserve iOS Bot navigation and live permission ownership (#233) * Own iOS Bot navigation responses and live permission publication * fix(ios): keep in-flight Bot opens and same-policy grants through restoration Restoration re-ran on an open's own path change and superseded it, and it reset an already-presented chat's live mutation grant to false before revalidating, leaving it disabled after a transient failure. Restoration now adopts an in-flight open under identical inputs, and keeps a prior live grant only when the write and notice policy are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GAkZRgQzUoKWGpgupF3a4D * fix(ios): preserve newer detail state across workspace list responses (#234) * fix(ios): admit workspace lists against newer detail owners * fix(ios): preserve accepted rename titles and coherent chat revisions (#236) * fix(ios): preserve rename receipts without replacing newer chat state * Preserve authoritative list titles across detail hydration * Fence iOS Home responses and preserve admitted row ownership (#238) --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit ccb64152) Conflict resolution against #242: saveChats keeps #242's committed-write ordering (older lists are partial companions, rows come from successful detail commits, and the list token is the max). #233's in-memory list, rename-title and fetch authority stay. The durable list extends only the last admitted rows, so a detail whose disk write failed stays a memory-only winner on the read path and never becomes a durable row. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GAkZRgQzUoKWGpgupF3a4D --- .memory/ios-bot-response-ownership.md | 15 + .memory/ios-home-response-ownership.md | 35 + .memory/ios-rename-response-ownership.md | 29 + .memory/ios-workspace-response-ownership.md | 13 + .../Features/Remote/AidenChatFeature.swift | 134 ++- .../Remote/AidenProductShellView.swift | 248 +++-- .../Remote/AidenWorkspaceShellView.swift | 93 +- ios/AidenOnTheGo/Models/AidenChat.swift | 5 +- .../Persistence/AidenChatCache.swift | 373 ++++++- ios/AidenOnTheGoTests/AidenChatTests.swift | 939 +++++++++++++++++- 10 files changed, 1736 insertions(+), 148 deletions(-) create mode 100644 .memory/ios-bot-response-ownership.md create mode 100644 .memory/ios-home-response-ownership.md create mode 100644 .memory/ios-rename-response-ownership.md create mode 100644 .memory/ios-workspace-response-ownership.md diff --git a/.memory/ios-bot-response-ownership.md b/.memory/ios-bot-response-ownership.md new file mode 100644 index 0000000000..52541303de --- /dev/null +++ b/.memory/ios-bot-response-ownership.md @@ -0,0 +1,15 @@ +# iOS Bot response ownership + +Isolated worktree /Users/sambitbiswas/.codex/worktrees/ios-bot-response-ownership/aiden-agent, branch feature/ios-bot-response-ownership atop PR217 ff777f501. PR217/225/227 heads remain unchanged. PR227 exact3f7154e7 all hosted CI green,0threads, acceptance recorded. + +Bot open/hydrate reserve cache tickets before their first await and share a navigation attempt owner. Later loads and away/back scope changes invalidate older callbacks; deep-link publication supersedes them. Permission completion updates the currently presented transcript instead of its captured pre-permission copy. Cache admission retains an in-memory winner before disk IO, with removal/purge fences, so an old rejected GET cannot fall back to stale disk after a newer write failure. Warm Bot loads also use the admitted winner. + +New held production HTTP regression covers GET A delayed behind GET B, newer disk failure, removal and purge, with request-origin admission and persisted winner checks. A held permission-attempt regression covers away/back and instance/device navigation. Generic XCTest compilation passes; physical execution is not claimed. Android/policy checks and independent Sol medium reviews underway. These tests are compiled, not executed baseline reproductions; original-main duplicateGET reachability was source-confirmed in .memory/mobile-response-ownership.md. iOS workspace rename/list ownership remains assigned separately; physical device locked, no simulator/device launch. + +Review corrections: path mutations now invalidate attempts synchronously through the same production helper used with the real navigation store in the held away/back test; error continuations also directly check path/scope. Live installation write grants and a live notice-policy closure are rechecked at permission publication against the attempt policy. Restoration identity includes both policy inputs, allowing current-chat permission refresh without transcript rollback. Deep-link permission and detail transcript callbacks preserve the other current field. The admitted cache API rejects disk fallback after purge even if cleanup left a file; fresh post-purge admission remains valid. Four XCTest methods compile, covering held production GET order/disk/removal/purge, real navigation-store away/back ownership, and held write/notice downgrades. Android177 JVM/lint/instrumentation and policy31Node20Ruby42 pass. Final independent reviews/build pending; no physical execution claimed. + +Create review correction: a successful Bot create receipt publishes the shared awaitingPermission presentation (mutations false), then existing-destination restoration resolves live permission. Added a held real Bot-create POST regression using that same production presentation. This avoids inheriting pre-POST permission across a downgrade without retrying the POST. Fixed the test idempotency argument to UUID after a compilation diagnostic. Final generic XCTest build is being confirmed; both actual-diff re-reviews requested. + +Final acceptance: generic iOS app/XCTest build-for-testing passes (/tmp/aiden-ios-bot-response-build.log); Android177 JVM/lint/instrumentation compilation and policy31Node20Ruby42 pass (/tmp/aiden-ios-bot-response-android.log and /tmp/aiden-ios-bot-response-policy.log). Both independent GPT-5.6 Sol medium final actual-diff reviews are clear. Physical XCTest remains unexecuted. + +Hermes review on 0f94027e (2 P1s): (1) restoration now adopts an in-flight user open for the same scope/chat/canWrite/notice policy instead of superseding it on the open's own path change (owner `adoptable`/`adoptsRestoration`/`finish`; restoration attempts are never adoptable because SwiftUI cancels them on id change). (2) Restoration revalidating an already-presented chat keeps a live grant only when it was made under the same notice policy and write is still allowed (`Presentation.resolved`/`revalidating`); policy changes and non-live (deep-link) grants still fail closed. Two owner-level XCTests added; generic build-for-testing passes, not executed (no physical device, simulator prohibited). diff --git a/.memory/ios-home-response-ownership.md b/.memory/ios-home-response-ownership.md new file mode 100644 index 0000000000..20c7937442 --- /dev/null +++ b/.memory/ios-home-response-ownership.md @@ -0,0 +1,35 @@ +# iOS Home response ownership + +Isolated feature/ios-home-response-ownership atop PR236 dcfd0d707. Implementation complete; preparing reviewed publication. Hosted and combined acceptance remain pending. + +Source schedule: Home reserves before HTTP but summary save returned Void on rejected tokens; caller then published raw response/cursor. Per-model generation cannot arbitrate another Home owner or detail settlement. Added namespaced synchronous summary reservations, shared original-token admission, Bool write results, memory summary winner after IO failure, and detail projection under the accepted original token. Home respects rejection; continuation checks its cursor boundary against admitted shared state before merging. + +Two new regression methods hold actual production Home HTTP through detail settlement, another Home request, or purge; and hold actual continuation cache admission through newer detail/request/purge, checking unchanged cursor and retry. Generic XCTest compilation passed before final cursor-base refinement; policy31Node20Ruby42 pass. Tests compiled only, no physical execution or executed iOS baseline claimed. Both Sol reviewers inspecting pending diff; final checks and corrections remain necessary. + +PR236 dcfd0d707 has hosted verify/E2E running and no review threads at this turn. Integration bbb71364a accepted by both Sol reviewers, fresh iOScompile/157host, unchanged213Android evidence. Earlier stable PRs unchanged. Physical acceptance unexecuted while shared iPhone locked. No merges/releases/deployments. + +## Final implementation and validation in progress + +Summary reservations are synchronous and installation-scoped. Accepted detail projection keeps its original token, so an older queued detail cannot supersede a newer Home request. Home commits only admitted pages; admitted memory survives summary filesystem failure while validation/size failures still reject. Local generation is not used as a cross-owner cache clock. + +Review corrections: deletion takes fresh summary authority after held cleanup; no-chat Home plans do not reserve summary authority; rejected chat segments settle and still publish independent segments; local writes patch all unacknowledged edited IDs into current admitted summaries and preserve its cursor; initial UI reapplies local edits since request start, and pagination reapplies postcommit edits including newly introduced page IDs. The newest local patch acknowledges prior edits only after acceptance. Continuations validate the shared cursor before merging. Initial warm hydration checks the latest request token before taking ownership after an await. + +Five new methods cover three held production HTTP schedules, three held continuation cache schedules and retry, actual blocked summary filesystem memory admission, held deletion cleanup with an intervening request and restart, and page commit followed by two queued local edits (including a new page row) with restart. Generic app/XCTest compilation succeeds /tmp/aiden-ios-home-response-build.log. Android177 JVM/lint/instrumentation compilation succeeds /tmp/aiden-ios-home-response-android.log. Policy31Node20Ruby42 succeeds /tmp/aiden-ios-home-response-policy.log. These are compiled iOS regressions, not physical execution or executed baseline failures. Final Sol reviews pending. + +The partial-summary cursor expression also carries the already accepted PR21762fa semantics: absent cached snapshot retains incoming cursor; cached nil cursor stays nil. This is prerequisite-equivalent integration overlap, not a new cursor policy. + +Final review refinements: publish the atomic admitted snapshot/authority rather than a raw accepted response, including partial deletion transformations. Token-qualified local edit replay and per-row original edit tokens prevent replay over a newer cross-owner detail winner. Removal synchronously persists its authoritative deletion regardless of concurrent nonisolated HTTP reservations; a new exact reserve/admit-seam regression verifies restart excludes the row. The held cleanup regression remains. + +Per-row authority review correction: full HTTP pages and row mutations now have separate token floors. Detail/local/removal/rename companions advance only their affected row; queued activity A remains valid across unrelated settlement B, while older A edits cannot overwrite newer A. Atomic publication state returns full and per-row floors. Expanded tests include unrelated activity retention through detail and later folded patch, plus durable reopen. Latest compile and policy checks pass. + +PR236 dcfd0d707 is now hosted accepted: verify/E2E success, Android correctly area-skipped, zero threads. Final exact-head evidence recorded in PR body, coordinator/integration notified. + +Final companion conversion: reconcileWorkspaceChat uses the target row authority for Home eligibility, so unrelated B settlement no longer suppresses valid A rename. Extended regression covers delayed PATCH origin, newer A canonical settlement, accepted rename overlay, newer unrelated B, then companion A and both retained rows. Generic compilation and policy pass after this delta. + +Final same-row cutoff correction: rename companion row authority covers max(receipt cutoff, winner), so a whole-row local snapshot reserved during PATCH cannot roll the accepted title back. Expanded schedule reserves that patch after canonical settlement but before receipt cutoff, delivers it after companion and unrelated settlement, then reopens to verify the accepted title and admitted activity. + +Post-receipt activity review correction: an existing locally updated row can receive the presented rename winner while retaining its activity, provided no later authoritative full-page snapshot superseded the receipt. Later full-page rows and absent post-receipt removals remain protected. The companion keeps max(existing row, receipt cutoff, winner) authority. Regression persists an activity change after cutoff but before actor receipt admission, then asserts accepted title plus active state and rejection of the earlier queued whole-row patch after restart. + +Activity-only writes now carry a field mask through queued cache patching and UI replay. They change only current activity, preserve canonical title/revision and do not recreate missing rows. Unacknowledged full-row edits retain full semantics when folded with subsequent activity changes. The final reopen regression updates activity from a stale-title Home snapshot after the rename companion and confirms both current title and new activity. Latest generic compilation and policy pass. + +Both independent GPT-5.6 Sol medium final reviews are clear, including the final activity-only field mask and all preceding ownership/rename corrections. Generic XCTest compilation, Android177 JVM/lint/instrumentation and policy31Node20Ruby42 pass. Physical execution remains unexecuted. diff --git a/.memory/ios-rename-response-ownership.md b/.memory/ios-rename-response-ownership.md new file mode 100644 index 0000000000..9b8c9623c4 --- /dev/null +++ b/.memory/ios-rename-response-ownership.md @@ -0,0 +1,29 @@ +# iOS rename response ownership + +Isolated feature/ios-rename-response-ownership atop PR23418eddee68833ffdbfaa1e9cbf7f67cd81e7a91dd. PR217 cursor62fa352d is separately integrated; do not duplicate it. + +## Implementation + +A successful delayed PATCH owns a title field, not a whole older transcript/revision. Reserve its request origin before HTTP and receipt cutoff synchronously before the cache actor hop. Keep a separately persisted RenameTitle record, with a presentation-only localTitleOverride excluded from AidenChat CodingKeys; canonical cache encoding and admitted canonical objects retain coherent server fields. Workspace rows, detail navigation title, summary projection and Live Activities use displayTitle. Canonical detail initial/reconcile/title GETs now reserve before HTTP and use saveFetchedChat. + +The title overlay survives pre-receipt reads and retires only after a later-requested admitted coherent GET/full workspace LIST. Receipt and fetched high-water marks fence actor mailbox reordering and overlapping PATCH completion orders. Retirement writes an atomic explicit retired-state record rather than relying on unlink; a failed canonical write preserves the fresh memory winner and separately records its title for restart. Remove/purge clear or fence overlay state. Post-purge disk fallback remains blocked. + +Workspace rename refreshes read-only after a successful PATCH, never replays it, and requires a coherent GET before another revisioned rename/remove while an overlay is pending. Failed refresh retains the successful title. The companion reads current canonical state after the metadata suspension and synchronously upserts list/summary without inventing transcript authority. Post-receipt authoritative metadata omissions remain absent; a newer list row wins presentation over older detailed-cache state. Only actual HTTP list admission may retire a title overlay, not locally queued metadata snapshots. Unrelated chat deletion does not suppress a retained rename. + +## Regression/validation evidence + +Ten new XCTest methods cover real held PATCH against newer settlement, removal, purge and unrelated deletion; failed refresh with separately reopened title/canonical records; no next PATCH/DELETE until coherent refresh and valid If-Match; successful list/summary reopen; failed unlink and canonical IO; both PATCH/GET orders; fresh GET during suspended receipt persistence and before actor entry; overlapping newer/older receipts; held metadata companion versus older-reserved detail GET; post-receipt empty list/summary; production callback/model/reopened-cache adoption of a newer full-list row; and a held older summary released after the winning list companion. The previous empty-list rename test now distinguishes a valid unrelated row update from a newer authoritative omission. These are compiled regressions, not executed iOS tests or an executed baseline failure. + +Generic app/XCTest build-for-testing: /tmp/aiden-ios-rename-response-build.log. Android JVM/lint/instrumentation compilation: /tmp/aiden-ios-rename-response-android.log (177 tests). iOS policy: /tmp/aiden-ios-rename-response-policy.log (31 Node, 20 Ruby/42 assertions). Initial policy source-regex failure was caused by changing the unrelated Bot header title fallback; that binding was restored and checks pass. Final review clearance/publication will be recorded below. + +Physical acceptance remains unexecuted; shared iPhone passcodeRequired true, no slot or launch. Remaining assigned work is iOS Home summary response admission and PR CI/review follow-through; this patch does not claim that Home race fixed. + +Final summary reconciliation carries the selected list/detail winner token, preventing an already-held older summary from replacing it. Passed presentation objects with a local title override also require coherent refresh before rename/remove, even if another owner has already retired shared overlay state. Final generic XCTest compilation and policy checks pass; Android177 tests/lint/instrumentation remain unchanged and green. Both independent GPT-5.6 Sol medium final full-roster reviews are clear. + +## Integration correction: list title across detail hydration + +Combined review found that a later authoritative LIST could admit title C but throw before retiring rename B; even successful retirement exposed an older canonical detail title A/B to generic detail hydration. A later authoritative list now supersedes the separate title record in a defer after admission, whether list persistence succeeds or fails. It retains C separately until a coherent detail GET catches up; canonical transcript/revision remains untouched and later revisioned mutations retain the read prerequisite. Actual HTTP title provenance is kept separately from locally replaced workspace snapshots, so a mailbox-late PATCH cannot select a locally replayed old title instead of the newer HTTP title. Removal/purge clear this provenance. + +Two additional XCTest methods cover sixteen combinations including empty/nonempty authoritative titles of HTTP/local list, pre/post-receipt reservation and successful/failed list IO, checking workspace and generic detail presentation, unchanged canonical title/revision, restart, and later coherent detail retirement; plus HTTP C followed by local snapshot B before actor-late PATCH admission. Generic compilation passes /tmp/aiden-ios-rename-list-failure-build.log, unchanged177 Android JVM/lint/instrumentation checks pass /tmp/aiden-ios-rename-list-failure-android.log, policy31Node20Ruby42 passes /tmp/aiden-ios-rename-list-failure-policy.log. These regressions are compiled only; physical tests remain unexecuted. Both independent GPT-5.6 Sol medium final correction reviews are clear. Corrected-head integration acceptance remains required. + +Review also caught the valid empty-title restart case: new title records encode an explicit retired flag; missing legacy flags retain the prior empty-title tombstone interpretation. Empty authoritative titles now survive restart. Final generic compile and policy checks pass in /tmp/aiden-ios-rename-empty-title-build.log and /tmp/aiden-ios-rename-empty-title-policy.log. diff --git a/.memory/ios-workspace-response-ownership.md b/.memory/ios-workspace-response-ownership.md new file mode 100644 index 0000000000..e27e575c58 --- /dev/null +++ b/.memory/ios-workspace-response-ownership.md @@ -0,0 +1,13 @@ +# iOS workspace response ownership + +Isolated branch feature/ios-workspace-response-ownership atop PR2330f94027e. PR217 cursor correction62fa352d is separately published and must be composed by integration; this branch does not duplicate it. + +## Workspace list slice + +A held workspace GET previously published its raw response before cache admission, allowing a newer detail transcript/title or newly created omitted row to disappear. The request already reserves before HTTP; saveChats now returns admission and merges newer admitted detail owners by that original token. A namespaced admitted workspace snapshot is retained before disk IO, and the model publishes that current snapshot after its awaits. Newer list requests still authoritatively remove omitted older rows. Per-chat removal filters memory and purge clears it. A purge-generation guard rejects stale disk fallback when deletion fails; fresh post-purge lists are admitted normally. + +Two compiled XCTest methods cover six real held-HTTP schedules (newer detail, omitted newer detail, failed list write, removal, purge, newer list) and failed purge deletion with actual stale disk plus fresh re-admission. These are source/compiled regressions, not executed iOS negatives. Generic app/XCTest build-for-testing passes /tmp/aiden-ios-workspace-response-build.log. Fresh Android177 JVM tests/lint/instrumentation compilation pass /tmp/aiden-ios-workspace-response-android.log; policy31Node+20Ruby42 pass /tmp/aiden-ios-workspace-response-policy.log. Both independent GPT-5.6 Sol medium reviews are clear after the failed-purge fallback correction. Physical tests remain unexecuted; shared iPhone locked. + +## Remaining assigned scope + +Rename is separate and not claimed fixed here. Preserve successful PATCH title as a field-specific overlay, canonical transcript/revision unchanged; reserve before PATCH and all detail GETs, refresh via read-only GET and retire overlay only after a later-requested admitted snapshot. Require a coherent refresh before another revisioned rename/remove. Persist overlay separately if restart retention is promised. Never replay mutations. Cover both PATCH/GET orders, refresh failure, next mutation, deletion/purge, disk failure and valid navigation. iOS Home summary response ownership also needs the Android225-equivalent acceptance audit; cache deletion fencing alone does not establish request-versus-detail ownership. diff --git a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift index 314de9a782..e97fba0b9e 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift @@ -703,9 +703,14 @@ final class AidenWorkspaceChatsModel { guard let context = try? coordinator.requestContext() else { return } let instanceId = context.instanceId let metadataWriteToken = cache.reserveChatWrite() - if chats.isEmpty, let cached = await cache.loadChats(instanceId: instanceId, workspaceId: workspaceId) { + if chats.isEmpty, let cached = await cache.admittedWorkspaceChats(instanceId: instanceId, workspaceId: workspaceId) { guard coordinator.isCurrent(context) else { return } - chats = Self.sorted(AidenChat.regularWorkspaceChats(from: cached)) + var presented: [AidenChat] = [] + for row in AidenChat.regularWorkspaceChats(from: cached) { + if let current = await cache.presentedWorkspaceChat(instanceId: instanceId, workspaceId: workspaceId, chatId: row.id) { presented.append(current) } + } + guard coordinator.isCurrent(context) else { return } + chats = Self.sorted(presented) } guard !isLoading else { return } isLoading = true @@ -713,8 +718,21 @@ final class AidenWorkspaceChatsModel { do { let remote = try await coordinator.remoteClient(for: context).chats(workspaceId: workspaceId) guard coordinator.isCurrent(context) else { return } - chats = Self.sorted(AidenChat.regularWorkspaceChats(from: remote)) - try await cache.saveChats(chats, instanceId: instanceId, workspaceId: workspaceId, writeToken: metadataWriteToken) + // Commit before publishing: a held list response may have lost to a + // detail owner, another list, or removal while HTTP was in flight. + do { + try await cache.saveChats(AidenChat.regularWorkspaceChats(from: remote), instanceId: instanceId, workspaceId: workspaceId, writeToken: metadataWriteToken, isAuthoritativeFetch: true) + } catch { + // Admission precedes IO; preserve the in-memory winner on disk failure. + } + let admitted = await cache.admittedWorkspaceChats(instanceId: instanceId, workspaceId: workspaceId) + guard coordinator.isCurrent(context) else { return } + var presented: [AidenChat] = [] + for row in AidenChat.regularWorkspaceChats(from: admitted ?? []) { + if let current = await cache.presentedWorkspaceChat(instanceId: instanceId, workspaceId: workspaceId, chatId: row.id) { presented.append(current) } + } + guard coordinator.isCurrent(context) else { return } + chats = Self.sorted(presented) } catch { if await coordinator.handleCredentialRevocation(error, context: context) { return } guard coordinator.isCurrent(context) else { return } @@ -748,35 +766,75 @@ final class AidenWorkspaceChatsModel { } } + private func refreshRenameSnapshot(chatId: String, context: AidenRemoteRequestContext) async throws -> AidenChat { + let token = cache.reserveChatWrite() + let remote = try await coordinator.remoteClient(for: context).chat(id: chatId) + guard coordinator.isCurrent(context), remote.id == chatId, remote.workspaceId == workspaceId, !remote.isBotChat else { throw CancellationError() } + guard try await cache.saveFetchedChat(remote, instanceId: context.instanceId, writeToken: token) else { throw CancellationError() } + guard coordinator.isCurrent(context), + let current = await cache.admittedChat(instanceId: context.instanceId, chatId: chatId), + !(await cache.needsRenameRefresh(instanceId: context.instanceId, chatId: chatId)) else { throw CancellationError() } + return current + } + func rename(_ chat: AidenChat, to title: String) async { let cleaned = title.trimmingCharacters(in: .whitespacesAndNewlines) guard !cleaned.isEmpty, !isMutating, let context = try? coordinator.requestContext() else { return } let instanceId = context.instanceId isMutating = true defer { isMutating = false } - var optimistic = chat - optimistic.title = cleaned - upsert(optimistic) do { + let canonical: AidenChat + let pendingRename = await cache.needsRenameRefresh(instanceId: instanceId, chatId: chat.id) + if pendingRename || chat.localTitleOverride != nil { + canonical = try await refreshRenameSnapshot(chatId: chat.id, context: context) + } else { canonical = chat } + guard coordinator.isCurrent(context) else { return } + let origin = cache.reserveChatWrite() + let generation = presentationGenerations[chat.id] ?? 0 let updated = try await coordinator.remoteClient(for: context).updateChat( - id: chat.id, - revision: chat.revision, - title: cleaned + id: chat.id, revision: canonical.revision, title: cleaned ) + guard coordinator.isCurrent(context), updated.id == chat.id, + updated.workspaceId == workspaceId, !updated.isBotChat else { return } + let receiptCutoff = cache.reserveChatWrite() + guard let admitted = await cache.acceptRename(updated, instanceId: instanceId, origin: origin, cutoff: receiptCutoff) else { + if coordinator.isCurrent(context), generation == (presentationGenerations[chat.id] ?? 0) { + chats.removeAll { $0.id == chat.id } + presentationGenerations[chat.id, default: 0] &+= 1 + onChatRemoved(chat.id) + } + return + } guard coordinator.isCurrent(context) else { return } - guard let admitted = await persist(chat: updated, instanceId: instanceId, context: context), coordinator.isCurrent(context) else { return } - onChatUpdated(admitted) + guard await cache.reconcileWorkspaceChat(admitted, instanceId: instanceId, authority: origin, cutoff: receiptCutoff) else { return } + let publicationGeneration = presentationGenerations[chat.id] ?? 0 + guard let presentation = await cache.presentedWorkspaceChat(instanceId: instanceId, workspaceId: workspaceId, chatId: chat.id) else { return } + guard coordinator.isCurrent(context), publicationGeneration == (presentationGenerations[chat.id] ?? 0), cache.isChatWriteRetained(origin, instanceId: instanceId, chatId: chat.id) else { return } + upsert(presentation) + onChatUpdated(presentation) coordinator.haptics.play(.success, scope: hapticScope, dedupeKey: "chat-rename:\(updated.id):\(updated.revision)") + // A failed read must not roll back a successful mutation or replay PATCH. + let refreshGeneration = presentationGenerations[chat.id] ?? 0 + do { + let refreshed = try await refreshRenameSnapshot(chatId: chat.id, context: context) + guard coordinator.isCurrent(context), refreshGeneration == (presentationGenerations[chat.id] ?? 0) else { return } + guard await cache.reconcileWorkspaceChat(refreshed, instanceId: instanceId, authority: origin, cutoff: receiptCutoff) else { return } + guard coordinator.isCurrent(context), refreshGeneration == (presentationGenerations[chat.id] ?? 0), cache.isChatWriteRetained(origin, instanceId: instanceId, chatId: chat.id) else { return } + guard let presentation = await cache.presentedWorkspaceChat(instanceId: instanceId, workspaceId: workspaceId, chatId: chat.id) else { return } + guard coordinator.isCurrent(context), refreshGeneration == (presentationGenerations[chat.id] ?? 0), cache.isChatWriteRetained(origin, instanceId: instanceId, chatId: chat.id) else { return } + upsert(presentation) + onChatUpdated(presentation) + } catch { + if await coordinator.handleCredentialRevocation(error, context: context) { return } + } } catch let error where aidenIsCancellation(error) { - guard coordinator.isCurrent(context) else { return } - upsert(chat) + return } catch { if await coordinator.handleCredentialRevocation(error, context: context) { return } guard coordinator.isCurrent(context) else { return } - upsert(chat) presentedError = error.localizedDescription coordinator.haptics.play(.error, scope: hapticScope) - await load() } } @@ -789,7 +847,13 @@ final class AidenWorkspaceChatsModel { presentationGenerations[chat.id, default: 0] &+= 1 chats.removeAll { $0.id == chat.id } do { - try await coordinator.remoteClient(for: context).removeChat(id: chat.id, revision: chat.revision) + let canonical: AidenChat + let pendingRename = await cache.needsRenameRefresh(instanceId: instanceId, chatId: chat.id) + if pendingRename || chat.localTitleOverride != nil { + canonical = try await refreshRenameSnapshot(chatId: chat.id, context: context) + } else { canonical = chat } + guard coordinator.isCurrent(context) else { return } + try await coordinator.remoteClient(for: context).removeChat(id: chat.id, revision: canonical.revision) guard coordinator.isCurrent(context) else { return } await cache.removeChat(instanceId: instanceId, chatId: chat.id) await AidenChatDraftStore.shared.remove(instanceId: instanceId, chatId: chat.id) @@ -1250,11 +1314,14 @@ final class AidenChatViewModel { if let cached = await cache.loadChat(instanceId: instanceId, chatId: chat.id) { guard !isRemoved, coordinator.isCurrent(context) else { return } if cacheGeneration == transcriptGeneration, !isStarting { - chat = cached + let presented = await cache.presenting(cached, instanceId: instanceId) + guard !isRemoved, coordinator.isCurrent(context), cacheGeneration == transcriptGeneration, !isStarting else { return } + chat = presented resolveModelSelection() } } let generation = transcriptGeneration + let writeToken = cache.reserveChatWrite() do { async let chatRequest = coordinator.remoteClient(for: context).chat(id: chat.id) async let catalogRequest = coordinator.remoteClient(for: context).modelCatalog() @@ -1262,7 +1329,7 @@ final class AidenChatViewModel { guard !isRemoved, coordinator.isCurrent(context) else { return } catalog = remoteCatalog if generation == transcriptGeneration, !isStarting { - await acceptRemoteChat(remoteChat, context: context) + await acceptRemoteChat(remoteChat, context: context, writeToken: writeToken) } } catch { clearProgressStateIfCredentialRevoked(error) @@ -1825,7 +1892,7 @@ final class AidenChatViewModel { await liveActivities.start( instanceID: instanceId, chatID: chat.id, - title: chat.title, + title: chat.displayTitle, streamID: response.streamId ) } @@ -2322,7 +2389,7 @@ final class AidenChatViewModel { await liveActivities.start( instanceID: instanceId, chatID: chat.id, - title: chat.title, + title: chat.displayTitle, streamID: stream.streamId ) } @@ -2690,6 +2757,7 @@ final class AidenChatViewModel { private func reconcileChat(context: AidenRemoteRequestContext) async -> Bool { guard !isStarting else { return false } let generation = transcriptGeneration + let writeToken = cache.reserveChatWrite() do { let remote = try await coordinator.remoteClient(for: context).chat(id: chat.id) guard !isRemoved, coordinator.isCurrent(context) else { return false } @@ -2698,7 +2766,7 @@ final class AidenChatViewModel { // before its cache write yields to the main actor again. transcriptGeneration &+= 1 let publicationGeneration = transcriptGeneration - guard await acceptRemoteChat(remote, context: context) else { return false } + guard await acceptRemoteChat(remote, context: context, writeToken: writeToken) else { return false } guard publicationGeneration == transcriptGeneration, coordinator.isCurrent(context) else { return false } clearRecoveryWarning() return true @@ -2714,18 +2782,19 @@ final class AidenChatViewModel { private func acceptRemoteChat( _ remote: AidenChat, context: AidenRemoteRequestContext, + writeToken: UInt64, scheduleTitleRefresh: Bool = true ) async -> Bool { guard !isRemoved, coordinator.isCurrent(context), !isStarting else { return false } let generation = transcriptGeneration - let writeToken = cache.reserveChatWrite() - let accepted = (try? await cache.saveChat(remote, instanceId: instanceId, writeToken: writeToken)) ?? true - guard accepted else { return false } + _ = try? await cache.saveFetchedChat(remote, instanceId: instanceId, writeToken: writeToken) + guard let canonical = await cache.admittedChat(instanceId: instanceId, chatId: remote.id) else { return false } + let presented = await cache.presenting(canonical, instanceId: instanceId) guard !isRemoved, coordinator.isCurrent(context), !isStarting, generation == transcriptGeneration else { return false } - chat = remote + chat = presented resolveModelSelection() - onChatUpdated(remote) - if scheduleTitleRefresh, remote.isTitlePending { + onChatUpdated(presented) + if scheduleTitleRefresh, presented.isTitlePending { schedulePendingTitleRefresh(context: context) } return true @@ -2748,10 +2817,11 @@ final class AidenChatViewModel { try await Task.sleep(for: .milliseconds(delay)) guard !isStarting else { continue } let generation = transcriptGeneration + let writeToken = cache.reserveChatWrite() let remote = try await coordinator.remoteClient(for: context).chat(id: chat.id) guard !isRemoved, coordinator.isCurrent(context) else { return } guard generation == transcriptGeneration, !isStarting else { continue } - await acceptRemoteChat(remote, context: context, scheduleTitleRefresh: false) + await acceptRemoteChat(remote, context: context, writeToken: writeToken, scheduleTitleRefresh: false) if !remote.isTitlePending { return } } catch let error where aidenIsCancellation(error) { return @@ -2953,7 +3023,7 @@ struct AidenWorkspaceChatsView: View { ) } label: { VStack(alignment: .leading, spacing: 4) { - Text(chat.title).lineLimit(1) + Text(chat.displayTitle).lineLimit(1) AidenRelativeTimestampView(date: chat.updatedAt) .font(.caption) .foregroundStyle(.secondary) @@ -3046,7 +3116,7 @@ struct AidenWorkspaceChatsView: View { } private func beginRename(_ chat: AidenChat) { - renameTitle = chat.title + renameTitle = chat.displayTitle renameChat = chat } } @@ -3162,7 +3232,7 @@ struct AidenChatDetailView: View { guard isStreaming else { return } attachmentPicker.dismiss() } - .navigationTitle(presentationStyle == .botMessages ? "" : model.chat.title) + .navigationTitle(presentationStyle == .botMessages ? "" : model.chat.displayTitle) .navigationBarTitleDisplayMode(.inline) .toolbar { chatToolbar } .safeAreaInset(edge: .top, spacing: 0) { botIdentityInset } diff --git a/ios/AidenOnTheGo/Features/Remote/AidenProductShellView.swift b/ios/AidenOnTheGo/Features/Remote/AidenProductShellView.swift index 8d799471b6..016434361f 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenProductShellView.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenProductShellView.swift @@ -7,23 +7,110 @@ func aidenPersistBotChatForPresentation( _ chat: AidenChat, context: AidenRemoteRequestContext, coordinator: AidenRemoteCoordinator, - cache: AidenChatCache = .shared + cache: AidenChatCache = .shared, + writeToken: UInt64? = nil ) async -> AidenChat? { - let writeToken = cache.reserveChatWrite() + let writeToken = writeToken ?? cache.reserveChatWrite() var candidate: AidenChat? let retained = await coordinator.withRetainedInstallationData(for: context) { - let accepted = (try? await cache.saveChat(chat, instanceId: context.instanceId, writeToken: writeToken)) ?? true - if accepted { - candidate = chat - } else { - candidate = await cache.loadChat(instanceId: context.instanceId, chatId: chat.id) - } + _ = try? await cache.saveChat(chat, instanceId: context.instanceId, writeToken: writeToken) + candidate = await cache.admittedChat(instanceId: context.instanceId, chatId: chat.id) } guard retained, coordinator.isCurrent(context), let candidate, candidate.id == chat.id, candidate.botId == chat.botId else { return nil } return candidate } +/// One navigation load owns all of its cache and permission continuations. +@MainActor +final class AidenBotPresentationOwner { + struct Presentation { + var chat: AidenChat + let allowsMutations: Bool + /// Notice policy a live permission check granted mutations under; + /// nil when the grant did not come from such a check. + var grantedFullAccessAllowed: Bool? = nil + + static func awaitingPermission(_ chat: AidenChat) -> Self { + Self(chat: chat, allowsMutations: false) + } + + static func resolved(_ chat: AidenChat, allowsMutations: Bool, fullAccessAllowed: Bool) -> Self { + Self(chat: chat, allowsMutations: allowsMutations, + grantedFullAccessAllowed: allowsMutations ? fullAccessAllowed : nil) + } + + /// Restoration revalidates an already-presented chat. A live grant made + /// under the same write and notice policy stays usable while that check + /// runs or fails transiently; any policy change fails closed. + func revalidating(canWrite: Bool, fullAccessAllowed: Bool) -> Self { + let keeps = allowsMutations && canWrite && grantedFullAccessAllowed == fullAccessAllowed + return Self(chat: chat, allowsMutations: keeps, grantedFullAccessAllowed: keeps ? fullAccessAllowed : nil) + } + } + + struct Attempt: Equatable { + let id = UUID() + let instanceID: String + let deviceID: String + let chatID: String + let writeToken: UInt64 + let fullAccessAllowed: Bool + let canWrite: Bool + } + private var current: Attempt? + /// True while `current` is a user-initiated open that restoration adopts. + private var currentAdoptable = false + + func begin( + instanceID: String, + deviceID: String, + chatID: String, + cache: AidenChatCache = .shared, + canWrite: Bool = false, + fullAccessAllowed: Bool = false, + adoptable: Bool = false + ) -> Attempt { + let attempt = Attempt(instanceID: instanceID, deviceID: deviceID, chatID: chatID, writeToken: cache.reserveChatWrite(), fullAccessAllowed: fullAccessAllowed, canWrite: canWrite) + current = attempt + currentAdoptable = adoptable + return attempt + } + + /// The path change made by an in-flight open re-runs restoration. It must + /// not supersede that open when both would load under the same inputs. + func adoptsRestoration(instanceID: String, deviceID: String, chatID: String, canWrite: Bool, fullAccessAllowed: Bool) -> Bool { + guard currentAdoptable, let current else { return false } + return current.instanceID == instanceID && current.deviceID == deviceID && current.chatID == chatID + && current.canWrite == canWrite && current.fullAccessAllowed == fullAccessAllowed + } + + /// A settled open keeps ownership of its published state but no longer + /// stands in for restoration, so later restoration inputs reload. + func finish(_ attempt: Attempt) { + if owns(attempt) { currentAdoptable = false } + } + + func owns(_ attempt: Attempt) -> Bool { current == attempt } + func ownsPermission(_ attempt: Attempt, canWrite: Bool, fullAccessAllowed: Bool) -> Bool { + owns(attempt) && canWrite && attempt.fullAccessAllowed == fullAccessAllowed + } + func setPath(_ path: [String], store: AidenProductNavigationStore, instanceID: String?, deviceID: String?) { + retain(instanceID: instanceID, deviceID: deviceID, chatID: path.last) + store.setCompactBotPath(path, for: instanceID) + } + func invalidate() { + current = nil + currentAdoptable = false + } + func retain(instanceID: String?, deviceID: String?, chatID: String?) { + guard current?.instanceID == instanceID, current?.deviceID == deviceID, current?.chatID == chatID else { + invalidate() + return + } + } +} + enum AidenChromeSymbols { static let overflowMenu = "ellipsis" static let productSwitcherDisclosure = "chevron.down" @@ -666,12 +753,11 @@ private struct AidenBotShellView: View { let connectionState: AidenRemoteConnectionState let chatID: String? let isBotSurfaceActive: Bool + let canWrite: Bool + let fullAccessAllowed: Bool } - private struct ChatPresentation { - var chat: AidenChat - let allowsMutations: Bool - } + private typealias ChatPresentation = AidenBotPresentationOwner.Presentation @Bindable var coordinator: AidenRemoteCoordinator let area: AidenProductArea @@ -681,7 +767,7 @@ private struct AidenBotShellView: View { let deepLinkedInstanceID: String? let deepLinkedDeviceID: String? let deepLinkedChatAllowsMutations: Bool - let fullAccessActionsAllowed: Bool + let fullAccessActionsAllowed: () -> Bool @Binding var isShowingSwitcherCoachmark: Bool let onSelectArea: (AidenProductArea) -> Void let onRequestCustomAccess: () -> Void @@ -689,6 +775,7 @@ private struct AidenBotShellView: View { @Environment(\.aidenPalette) private var palette @State private var chatsByScope: [PresentationScope: [String: ChatPresentation]] = [:] @State private var retainedCreateAttempt: AidenBotConversationCreateAttempt? + @State private var presentationOwner = AidenBotPresentationOwner() private var presentationScope: PresentationScope? { guard let installation = coordinator.installationStore.activeInstallation else { return nil } @@ -700,17 +787,25 @@ private struct AidenBotShellView: View { scope: presentationScope, connectionState: coordinator.connectionState, chatID: path.last, - isBotSurfaceActive: isBotSurfaceActive + isBotSurfaceActive: isBotSurfaceActive, + canWrite: currentCanWrite, + fullAccessAllowed: fullAccessActionsAllowed() ) } + private var currentCanWrite: Bool { + AidenBotsAvailability.resolve(coordinator.installationStore.activeInstallation).canWrite + } + private var isBotSurfaceActive: Bool { aidenBotSurfaceIsActive(area: area, availability: botsAvailability) } private var path: [String] { get { navigationStore.compactBotPath(for: coordinator.activeInstanceId) } - nonmutating set { navigationStore.setCompactBotPath(newValue, for: coordinator.activeInstanceId) } + nonmutating set { + presentationOwner.setPath(newValue, store: navigationStore, instanceID: coordinator.activeInstanceId, deviceID: presentationScope?.deviceID) + } } private var pathBinding: Binding<[String]> { @@ -738,10 +833,9 @@ private struct AidenBotShellView: View { chat: presentation.chat, allowsMutations: presentation.allowsMutations, onChatUpdated: { - chatsByScope[scope, default: [:]][$0.id] = ChatPresentation( - chat: $0, - allowsMutations: presentation.allowsMutations - ) + var updated = chatsByScope[scope]?[$0.id] ?? presentation + updated.chat = $0 + chatsByScope[scope, default: [:]][$0.id] = updated } ) } else if isBotSurfaceActive { @@ -765,6 +859,7 @@ private struct AidenBotShellView: View { let deviceID = deepLinkedDeviceID, presentationScope == PresentationScope(instanceID: instanceID, deviceID: deviceID) else { return } let scope = PresentationScope(instanceID: instanceID, deviceID: deviceID) + presentationOwner.invalidate() chatsByScope[scope, default: [:]][chat.id] = ChatPresentation( chat: chat, allowsMutations: botsAvailability.canWrite && deepLinkedChatAllowsMutations @@ -781,6 +876,7 @@ private struct AidenBotShellView: View { let deviceID = deepLinkedDeviceID, presentationScope == PresentationScope(instanceID: instanceID, deviceID: deviceID) else { return } let scope = PresentationScope(instanceID: instanceID, deviceID: deviceID) + presentationOwner.invalidate() chatsByScope[scope, default: [:]][chat.id] = ChatPresentation( chat: chat, allowsMutations: botsAvailability.canWrite && deepLinkedChatAllowsMutations @@ -797,8 +893,9 @@ private struct AidenBotShellView: View { let deviceID = deepLinkedDeviceID, presentationScope == PresentationScope(instanceID: instanceID, deviceID: deviceID) else { return } let scope = PresentationScope(instanceID: instanceID, deviceID: deviceID) + presentationOwner.invalidate() chatsByScope[scope, default: [:]][chat.id] = ChatPresentation( - chat: chat, + chat: chatsByScope[scope]?[chat.id]?.chat ?? chat, allowsMutations: botsAvailability.canWrite && allowed ) } @@ -807,6 +904,10 @@ private struct AidenBotShellView: View { } .onChange(of: presentationScope) { _, _ in retainedCreateAttempt = nil + presentationOwner.retain(instanceID: presentationScope?.instanceID, deviceID: presentationScope?.deviceID, chatID: path.last) + } + .onChange(of: path) { _, _ in + presentationOwner.retain(instanceID: presentationScope?.instanceID, deviceID: presentationScope?.deviceID, chatID: path.last) } } @@ -818,11 +919,22 @@ private struct AidenBotShellView: View { availability: botsAvailability ) else { return } var capturedContext: AidenRemoteRequestContext? + var capturedAttempt: AidenBotPresentationOwner.Attempt? do { let context = try coordinator.requestContext() capturedContext = context let scope = PresentationScope(instanceID: context.instanceId, deviceID: context.deviceId) guard presentationScope == scope else { return } + let attempt = presentationOwner.begin( + instanceID: scope.instanceID, + deviceID: scope.deviceID, + chatID: item.chatId, + canWrite: currentCanWrite, + fullAccessAllowed: fullAccessActionsAllowed(), + adoptable: true + ) + capturedAttempt = attempt + defer { presentationOwner.finish(attempt) } // Navigation is intentionally first. A warm cache will replace the // layout-shaped skeleton on the next actor hop; a cold request can @@ -830,14 +942,14 @@ private struct AidenBotShellView: View { path = [item.chatId] let cached = aidenAdmittedCachedBotChat( - await AidenChatCache.shared.loadChat( + await AidenChatCache.shared.admittedChat( instanceId: context.instanceId, chatId: item.chatId ), chatID: item.chatId, botID: item.botId ) - guard coordinator.isCurrent(context), presentationScope == scope, + guard presentationOwner.owns(attempt), coordinator.isCurrent(context), presentationScope == scope, path.last == item.chatId else { return } if let cached { chatsByScope[scope, default: [:]][cached.id] = ChatPresentation( @@ -860,16 +972,16 @@ private struct AidenBotShellView: View { } else { try await client.chat(id: item.chatId) } - guard coordinator.isCurrent(context), chat.id == item.chatId, + guard presentationOwner.owns(attempt), coordinator.isCurrent(context), chat.id == item.chatId, chat.botId == item.botId, presentationScope == scope, path.last == item.chatId else { return } if cached == nil { - guard let admitted = await aidenPersistBotChatForPresentation(chat, context: context, coordinator: coordinator) else { - if coordinator.isCurrent(context), presentationScope == scope, path.last == item.chatId { path = [] } + guard let admitted = await aidenPersistBotChatForPresentation(chat, context: context, coordinator: coordinator, writeToken: attempt.writeToken) else { + if presentationOwner.owns(attempt), coordinator.isCurrent(context), presentationScope == scope, path.last == item.chatId { path = [] } return } chat = admitted - guard coordinator.isCurrent(context), presentationScope == scope, + guard presentationOwner.owns(attempt), coordinator.isCurrent(context), presentationScope == scope, path.last == item.chatId else { return } chatsByScope[scope, default: [:]][chat.id] = ChatPresentation( chat: chat, @@ -881,20 +993,24 @@ private struct AidenBotShellView: View { client: client, context: context ) - guard coordinator.isCurrent(context), presentationScope == scope, + guard presentationOwner.owns(attempt), coordinator.isCurrent(context), presentationScope == scope, path.last == item.chatId else { return } - chatsByScope[scope, default: [:]][chat.id] = ChatPresentation( - chat: chat, - allowsMutations: allowsMutations + chatsByScope[scope, default: [:]][chat.id] = .resolved( + chatsByScope[scope]?[chat.id]?.chat ?? chat, + allowsMutations: allowsMutations && presentationOwner.ownsPermission(attempt, + canWrite: currentCanWrite, + fullAccessAllowed: fullAccessActionsAllowed()), + fullAccessAllowed: attempt.fullAccessAllowed ) } catch is CancellationError { return } catch { if let context = capturedContext, await coordinator.handleCredentialRevocation(error, context: context) { return } - guard let context = capturedContext, - coordinator.isCurrent(context) else { return } + guard let context = capturedContext, let attempt = capturedAttempt, + presentationOwner.owns(attempt), coordinator.isCurrent(context) else { return } let scope = PresentationScope(instanceID: context.instanceId, deviceID: context.deviceId) + guard presentationScope == scope, path.last == item.chatId else { return } if chatsByScope[scope]?[item.chatId] != nil { coordinator.presentedError = "Couldn’t refresh this Bot chat. Showing the saved conversation." } else { @@ -917,7 +1033,7 @@ private struct AidenBotShellView: View { let context = try coordinator.requestContext() capturedContext = context let client = try coordinator.remoteClient(for: context) - if !fullAccessActionsAllowed { + if !fullAccessActionsAllowed() { let detail = try await client.bot(id: bot.id) guard coordinator.isCurrent(context) else { return } if detail.access.accessMode == .full { @@ -946,10 +1062,8 @@ private struct AidenBotShellView: View { chat = admitted guard coordinator.isCurrent(context) else { return } let scope = PresentationScope(instanceID: context.instanceId, deviceID: context.deviceId) - chatsByScope[scope, default: [:]][chat.id] = ChatPresentation( - chat: chat, - allowsMutations: botsAvailability.canWrite - ) + // A POST receipt grants no local authority; restoration resolves it. + chatsByScope[scope, default: [:]][chat.id] = .awaitingPermission(chat) path = [chat.id] } catch is CancellationError { return @@ -981,7 +1095,7 @@ private struct AidenBotShellView: View { guard let botID = chat.botId else { return false } let bot = try await client.bot(id: botID) guard coordinator.isCurrent(context) else { return false } - if fullAccessActionsAllowed { + if fullAccessActionsAllowed() { return aidenBotChatAllowsMutations( canWrite: true, fullAccessActionsAllowed: true, @@ -1008,34 +1122,45 @@ private struct AidenBotShellView: View { area: area, availability: botsAvailability ) else { + presentationOwner.invalidate() path = [] chatsByScope = [:] retainedCreateAttempt = nil return } guard let chatID = path.last, - let scope = presentationScope, - chatsByScope[scope]?[chatID] == nil else { return } + let scope = presentationScope else { return } + let canWrite = currentCanWrite + let fullAccessAllowed = fullAccessActionsAllowed() + // An open that is already loading this chat under the same policy + // owns it; its own path change must not restart the load. + if presentationOwner.adoptsRestoration(instanceID: scope.instanceID, deviceID: scope.deviceID, chatID: chatID, + canWrite: canWrite, fullAccessAllowed: fullAccessAllowed) { return } var capturedContext: AidenRemoteRequestContext? + let attempt = presentationOwner.begin(instanceID: scope.instanceID, deviceID: scope.deviceID, chatID: chatID, + canWrite: canWrite, fullAccessAllowed: fullAccessAllowed) do { let context = try coordinator.requestContext() capturedContext = context guard context.instanceId == scope.instanceID, context.deviceId == scope.deviceID else { return } - let cached = aidenAdmittedCachedBotChat( - await AidenChatCache.shared.loadChat( + let existing = chatsByScope[scope]?[chatID] + let cached = if let existing { existing.chat } else { aidenAdmittedCachedBotChat( + await AidenChatCache.shared.admittedChat( instanceId: context.instanceId, chatId: chatID ), chatID: chatID - ) - guard coordinator.isCurrent(context), presentationScope == scope, + ) } + guard presentationOwner.owns(attempt), coordinator.isCurrent(context), presentationScope == scope, path.last == chatID else { return } - if let cached { - chatsByScope[scope, default: [:]][cached.id] = ChatPresentation( - chat: cached, - allowsMutations: false + if let existing { + chatsByScope[scope, default: [:]][chatID] = existing.revalidating( + canWrite: currentCanWrite, + fullAccessAllowed: fullAccessActionsAllowed() ) + } else if let cached { + chatsByScope[scope, default: [:]][cached.id] = .awaitingPermission(cached) } guard coordinator.connectionState == .connected else { if cached == nil { path = [] } @@ -1048,17 +1173,15 @@ private struct AidenBotShellView: View { } else { try await client.chat(id: chatID) } - guard coordinator.isCurrent(context), chat.isBotChat else { - path = [] - return - } + guard presentationOwner.owns(attempt), coordinator.isCurrent(context), presentationScope == scope, path.last == chatID else { return } + guard chat.id == chatID, chat.isBotChat else { path = []; return } if cached == nil { - guard let admitted = await aidenPersistBotChatForPresentation(chat, context: context, coordinator: coordinator) else { - if coordinator.isCurrent(context), presentationScope == scope, path.last == chatID { path = [] } + guard let admitted = await aidenPersistBotChatForPresentation(chat, context: context, coordinator: coordinator, writeToken: attempt.writeToken) else { + if presentationOwner.owns(attempt), coordinator.isCurrent(context), presentationScope == scope, path.last == chatID { path = [] } return } chat = admitted - guard coordinator.isCurrent(context), presentationScope == scope, + guard presentationOwner.owns(attempt), coordinator.isCurrent(context), presentationScope == scope, path.last == chatID else { return } chatsByScope[scope, default: [:]][chat.id] = ChatPresentation( chat: chat, @@ -1066,18 +1189,21 @@ private struct AidenBotShellView: View { ) } let allowed = try await allowsMutations(for: chat, client: client, context: context) - guard coordinator.isCurrent(context), presentationScope == scope, + guard presentationOwner.owns(attempt), coordinator.isCurrent(context), presentationScope == scope, path.last == chatID else { return } - chatsByScope[scope, default: [:]][chat.id] = ChatPresentation( - chat: chat, - allowsMutations: allowed + chatsByScope[scope, default: [:]][chat.id] = .resolved( + chatsByScope[scope]?[chat.id]?.chat ?? chat, + allowsMutations: allowed && presentationOwner.ownsPermission(attempt, + canWrite: currentCanWrite, + fullAccessAllowed: fullAccessActionsAllowed()), + fullAccessAllowed: attempt.fullAccessAllowed ) } catch is CancellationError { return } catch { if let context = capturedContext, await coordinator.handleCredentialRevocation(error, context: context) { return } - guard presentationScope == scope, + guard presentationOwner.owns(attempt), presentationScope == scope, path.last == chatID, capturedContext.map({ coordinator.isCurrent($0) }) ?? false else { return } if chatsByScope[scope]?[chatID] != nil { coordinator.presentedError = "Couldn’t refresh this Bot chat. Showing the saved conversation." @@ -1412,7 +1538,7 @@ struct AidenProductShellView: View { deepLinkedInstanceID: deepLinkedBotInstanceID, deepLinkedDeviceID: deepLinkedBotDeviceID, deepLinkedChatAllowsMutations: deepLinkedBotAllowsMutations, - fullAccessActionsAllowed: noticeGate == .accepted, + fullAccessActionsAllowed: { noticeGate == .accepted }, isShowingSwitcherCoachmark: $isShowingSwitcherCoachmark, onSelectArea: selectArea, onRequestCustomAccess: { diff --git a/ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift b/ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift index 9c1df43938..3b5f31c7cb 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenWorkspaceShellView.swift @@ -174,6 +174,9 @@ final class AidenHomeModel { private var loadingAttempt: LoadAttempt? private let chatCache: AidenChatCache private var summaryCacheGeneration: UInt64 = 0 + private var latestSummaryRequestToken: UInt64 = 0 + private var persistedLocalGeneration: UInt64 = 0 + private var localSummaryEdits: [String: (generation: UInt64, token: UInt64, summary: AidenChatSummary?, activityOnly: Bool)] = [:] init(chatCache: AidenChatCache = .shared) { self.chatCache = chatCache @@ -190,33 +193,42 @@ final class AidenHomeModel { chats.removeAll { $0.id == chat.id } chats.append(AidenChatSummary(chat: chat, preservingActivity: activity)) chats.sort(by: AidenChatSummaryPage.areInCanonicalOrder) - persistCurrentSummaries() + persistCurrentSummaries(changedID: chat.id) } func setActivity(_ activity: AidenChatSummaryActivity, forChatID chatID: String) { guard let index = chats.firstIndex(where: { $0.id == chatID }), chats[index].activity != activity else { return } chats[index].activity = activity - persistCurrentSummaries() + persistCurrentSummaries(changedID: chatID, activityOnly: true) } func removeChat(id: String) { guard chats.contains(where: { $0.id == id }) else { return } chats.removeAll { $0.id == id } - persistCurrentSummaries() + persistCurrentSummaries(changedID: id) } - private func persistCurrentSummaries() { + private func persistCurrentSummaries(changedID: String, activityOnly: Bool = false) { guard let context = contentContext else { return } let snapshot = AidenChatCache.SummarySnapshot(summaries: chats, nextCursor: nextChatCursor) let generation = nextSummaryCacheGeneration() - let writeToken = chatCache.reserveChatWrite() + let writeToken = chatCache.reserveSummaryWrite(instanceId: context.instanceId) + let pending = localSummaryEdits[changedID] + let onlyActivity = activityOnly && !(pending.map { $0.generation > persistedLocalGeneration && !$0.activityOnly } ?? false) + localSummaryEdits[changedID] = (generation, writeToken, chats.first(where: { $0.id == changedID }), onlyActivity) + let editTokens = localSummaryEdits.filter { $0.value.generation > persistedLocalGeneration }.mapValues(\.token) + let changedIDs = Set(editTokens.keys) + let activityOnlyIDs = Set(localSummaryEdits.filter { $0.value.activityOnly && changedIDs.contains($0.key) }.keys) Task { - try? await chatCache.saveChatSummaries( + let accepted = try? await chatCache.saveChatSummaries( snapshot, instanceId: context.instanceId, - generation: generation, writeToken: writeToken + generation: generation, writeToken: writeToken, preservingCursor: true, changedIDs: changedIDs, editTokens: editTokens, activityOnlyIDs: activityOnlyIDs ) + if accepted == true, contentContext == context { + persistedLocalGeneration = max(persistedLocalGeneration, generation) + } } } @@ -238,10 +250,14 @@ final class AidenHomeModel { writeToken: UInt64, isCurrent: @MainActor () -> Bool = { true } ) async throws { + guard nextChatCursor == requestedCursor, isCurrent() else { throw CancellationError() } + let admitted = await chatCache.loadChatSummaries(instanceId: instanceId) + guard isCurrent(), nextChatCursor == requestedCursor else { throw CancellationError() } + if let admitted, admitted.nextCursor != requestedCursor { throw CancellationError() } let validated: [AidenChatSummary] do { validated = try AidenChatSummaryPage.validatedContinuation( - current: chats, + current: admitted?.summaries ?? chats, requestedCursor: requestedCursor, page: page ) @@ -255,34 +271,46 @@ final class AidenHomeModel { ) let generation = nextSummaryCacheGeneration() do { - try await chatCache.saveChatSummaries( + guard try await chatCache.saveChatSummaries( snapshot, instanceId: instanceId, generation: generation, writeToken: writeToken - ) + ) else { throw CancellationError() } } catch { paginationState = .failed(error.localizedDescription) throw error } - guard generation == summaryCacheGeneration, isCurrent() else { - throw CancellationError() + let state = await chatCache.summaryState(instanceId: instanceId) + guard isCurrent() else { throw CancellationError() } + // Publish the actual admitted page, including partial-deletion filtering + // and any newer cross-owner detail updates that followed admission. + chats = state.snapshot?.summaries ?? [] + for (id, edit) in localSummaryEdits where edit.token > max(state.fullToken, state.rowTokens[id] ?? 0) { + if edit.activityOnly { + if let index = chats.firstIndex(where: { $0.id == id }), let row = edit.summary { chats[index].activity = row.activity } + } else { + chats.removeAll { $0.id == id } + if let row = edit.summary { chats.append(row) } + } } - chats = validated - nextChatCursor = page.nextCursor + chats.sort(by: AidenChatSummaryPage.areInCanonicalOrder) + nextChatCursor = state.snapshot?.nextCursor paginationState = .idle } func load(coordinator: AidenRemoteCoordinator) async { guard coordinator.connectionState == .connected, let context = try? coordinator.requestContext() else { return } - let writeToken = chatCache.reserveChatWrite() + let requestEditGeneration = summaryCacheGeneration + let plan = AidenHomeLoadPlan(installation: coordinator.installationStore.activeInstallation) + let writeToken = plan.loadsChats ? chatCache.reserveSummaryWrite(instanceId: context.instanceId) : 0 + if plan.loadsChats { latestSummaryRequestToken = writeToken } let attempt = LoadAttempt(context: context) - let plan = AidenHomeLoadPlan( - installation: coordinator.installationStore.activeInstallation - ) if contentContext != context { contentContext = context summaryCacheGeneration &+= 1 + localSummaryEdits = [:] + persistedLocalGeneration = 0 chats = [] nextChatCursor = nil paginationState = .idle @@ -291,7 +319,7 @@ final class AidenHomeModel { modelCatalog = nil if plan.loadsChats, let cached = await chatCache.loadChatSummaries(instanceId: context.instanceId), - coordinator.isCurrent(context) { + coordinator.isCurrent(context), latestSummaryRequestToken == writeToken { chats = cached.summaries nextChatCursor = cached.nextCursor } @@ -305,6 +333,7 @@ final class AidenHomeModel { } if !plan.loadsScheduledTasks { scheduledTasks = [] } if !plan.loadsUsage { usage = nil } + guard !plan.loadsChats || latestSummaryRequestToken == writeToken else { return } loadingAttempt = attempt isLoading = true errorMessage = nil @@ -349,15 +378,28 @@ final class AidenHomeModel { ) let generation = nextSummaryCacheGeneration() do { - try await chatCache.saveChatSummaries( + _ = try await chatCache.saveChatSummaries( snapshot, instanceId: context.instanceId, generation: generation, writeToken: writeToken ) - guard generation == summaryCacheGeneration, - loadingAttempt == attempt, + let state = await chatCache.summaryState(instanceId: context.instanceId) + let admitted = state.snapshot + + guard loadingAttempt == attempt, coordinator.isCurrent(context) else { return } - acceptInitialChatSummaryPage(loadedPage) + chats = admitted?.summaries ?? [] + nextChatCursor = admitted?.nextCursor + paginationState = .idle + for (id, edit) in localSummaryEdits where edit.generation > requestEditGeneration && edit.token > max(state.fullToken, state.rowTokens[id] ?? 0) { + if edit.activityOnly { + if let index = chats.firstIndex(where: { $0.id == id }), let row = edit.summary { chats[index].activity = row.activity } + } else { + chats.removeAll { $0.id == id } + if let row = edit.summary { chats.append(row) } + } + } + chats.sort(by: AidenChatSummaryPage.areInCanonicalOrder) chatListLoadState = .loaded } catch { failures.append(error) @@ -404,7 +446,8 @@ final class AidenHomeModel { let cursor = nextChatCursor, let context = contentContext, coordinator.isCurrent(context) else { return } - let writeToken = chatCache.reserveChatWrite() + let writeToken = chatCache.reserveSummaryWrite(instanceId: context.instanceId) + latestSummaryRequestToken = writeToken paginationState = .loading do { let page = try await coordinator.remoteClient(for: context).chatSummaries(cursor: cursor) @@ -415,7 +458,7 @@ final class AidenHomeModel { instanceId: context.instanceId, writeToken: writeToken, isCurrent: { - coordinator.isCurrent(context) && self.contentContext == context + coordinator.isCurrent(context) && self.contentContext == context && self.latestSummaryRequestToken == writeToken } ) } catch let error where aidenIsCancellation(error) { diff --git a/ios/AidenOnTheGo/Models/AidenChat.swift b/ios/AidenOnTheGo/Models/AidenChat.swift index e158101e4c..536cb87735 100644 --- a/ios/AidenOnTheGo/Models/AidenChat.swift +++ b/ios/AidenOnTheGo/Models/AidenChat.swift @@ -970,6 +970,9 @@ struct AidenChat: Codable, Identifiable, Equatable, Sendable { var revision: String var titlePending: Bool? = nil + // Presentation-only receipt overlay; excluded from the canonical wire/cache encoding. + var localTitleOverride: String? = nil + var displayTitle: String { localTitleOverride ?? title } var isTitlePending: Bool { titlePending == true } var isBotChat: Bool { botId != nil } @@ -1189,7 +1192,7 @@ struct AidenChatSummary: Codable, Identifiable, Equatable, Sendable { self.init( id: chat.id, workspaceId: chat.workspaceId, - title: chat.title, + title: chat.displayTitle, titlePending: chat.isTitlePending, createdAt: chat.createdAt, updatedAt: chat.updatedAt, diff --git a/ios/AidenOnTheGo/Persistence/AidenChatCache.swift b/ios/AidenOnTheGo/Persistence/AidenChatCache.swift index d885e9674c..4bd0913efe 100644 --- a/ios/AidenOnTheGo/Persistence/AidenChatCache.swift +++ b/ios/AidenOnTheGo/Persistence/AidenChatCache.swift @@ -171,6 +171,7 @@ actor AidenChatCache { private var value: UInt64 = 0 private var removed: [String: [String: UInt64]] = [:] private var purged: [String: UInt64] = [:] + private var summaryAuthority: [String: UInt64] = [:] private var metadataRemovalStarts: [String: UInt64] = [:] private var pending: [UInt64: (instanceId: String, chatId: String?)] = [:] @@ -222,6 +223,22 @@ actor AidenChatCache { return token > (purged[instanceId] ?? 0) && token > (removed[instanceId]?[chatId] ?? 0) } + func reserveSummary(instanceId: String) -> UInt64 { + lock.lock() + defer { lock.unlock() } + value += 1 + summaryAuthority[instanceId] = value + return value + } + + func admitSummary(_ token: UInt64, instanceId: String) -> Bool { + lock.lock() + defer { lock.unlock() } + guard token >= (summaryAuthority[instanceId] ?? 0) else { return false } + summaryAuthority[instanceId] = token + return true + } + func next() -> UInt64 { lock.lock() defer { lock.unlock() } @@ -233,9 +250,33 @@ actor AidenChatCache { private nonisolated let chatWriteClock = ChatWriteClock() private var chatWriteGenerations: [String: [String: UInt64]] = [:] private var committedChatWrites: [String: [String: (token: UInt64, listToken: UInt64)]] = [:] + private struct RenameTitle: Codable { + let instanceId: String + let chatId: String + let title: String + // Missing on legacy records, where an empty title represented retirement. + var retired: Bool? = false + } + private struct PendingRename { + let value: RenameTitle + let origin: UInt64 + let cutoff: UInt64 + } + private var fetchedChatTokens: [String: [String: UInt64]] = [:] + private var renameOrigins: [String: [String: UInt64]] = [:] + private var renameTitles: [String: [String: PendingRename]] = [:] + private var retiredRenameTitles: [String: Set] = [:] + private var workspaceFetchedTitles: [String: [String: [String: String]]] = [:] + private var workspaceFetchTokens: [String: [String: UInt64]] = [:] + private var admittedWorkspaceLists: [String: [String: [AidenChat]]] = [:] + private var admittedChats: [String: [String: AidenChat]] = [:] private var removedChatIDs: [String: Set] = [:] private var chatPurgeGenerations: [String: UInt64] = [:] + nonisolated func reserveSummaryWrite(instanceId: String) -> UInt64 { + chatWriteClock.reserveSummary(instanceId: instanceId) + } + nonisolated func reserveChatWrite() -> UInt64 { chatWriteClock.next() } @@ -248,6 +289,13 @@ actor AidenChatCache { private var metadataCompletionTokens: [String: UInt64] = [:] private var workspaceWriteTokens: [String: [String: UInt64]] = [:] private var summaryWriteTokens: [String: UInt64] = [:] + private var admittedSummaries: [String: SummarySnapshot] = [:] + private var summaryFullTokens: [String: UInt64] = [:] + private var summaryRowTokens: [String: [String: UInt64]] = [:] + + private func summaryRowAuthority(instanceId: String, chatId: String) -> UInt64 { + max(summaryFullTokens[instanceId] ?? 0, summaryRowTokens[instanceId]?[chatId] ?? 0) + } private var summaryWriteGenerations: [String: UInt64] = [:] init( @@ -297,9 +345,53 @@ actor AidenChatCache { return envelope.chats.filter { !isChatHidden(instanceId: instanceId, chatId: $0.id) } } - func saveChats(_ chats: [AidenChat], instanceId: String, workspaceId: String, writeToken: UInt64) async throws { + // The last admitted list as written, without merging newer detail owners. + private func admittedWorkspaceListRows(instanceId: String, workspaceId: String) -> [AidenChat]? { + guard !chatWriteClock.isPending(instanceId: instanceId, chatId: "") else { return nil } + if let admitted = admittedWorkspaceLists[instanceId]?[workspaceId] { + return admitted.filter { !isChatHidden(instanceId: instanceId, chatId: $0.id) } + } + guard chatPurgeGenerations[instanceId] == nil else { return nil } + return loadChats(instanceId: instanceId, workspaceId: workspaceId) + } + + // Read the admitted list, including newer detail owners, even when disk IO failed. + func admittedWorkspaceChats(instanceId: String, workspaceId: String) -> [AidenChat]? { + guard let rows = admittedWorkspaceListRows(instanceId: instanceId, workspaceId: workspaceId) else { return nil } + return mergingWorkspaceDetails(rows, instanceId: instanceId, workspaceId: workspaceId, + writeToken: workspaceWriteTokens[instanceId]?[workspaceId] ?? 0) + } + + func presentedWorkspaceChat(instanceId: String, workspaceId: String, chatId: String) -> AidenChat? { + guard let row = admittedWorkspaceChats(instanceId: instanceId, workspaceId: workspaceId)?.first(where: { $0.id == chatId }) else { return nil } + let listToken = workspaceWriteTokens[instanceId]?[workspaceId] ?? 0 + if let pending = pendingRename(instanceId: instanceId, chatId: chatId), + (workspaceFetchTokens[instanceId]?[workspaceId] ?? 0) > pending.cutoff, listToken > (chatWriteGenerations[instanceId]?[chatId] ?? 0) { + return row + } + return presenting(row, instanceId: instanceId) + } + + private func mergingWorkspaceDetails(_ rows: [AidenChat], instanceId: String, workspaceId: String, writeToken: UInt64) -> [AidenChat] { + var byID = Dictionary(rows.filter { + !isChatHidden(instanceId: instanceId, chatId: $0.id) + }.map { ($0.id, $0) }, uniquingKeysWith: { _, latest in latest }) + for (id, chat) in admittedChats[instanceId] ?? [:] { + guard chat.workspaceId == workspaceId, !chat.isBotChat, + (chatWriteGenerations[instanceId]?[id] ?? 0) > writeToken, + !isChatHidden(instanceId: instanceId, chatId: id), + let current = admittedChat(instanceId: instanceId, chatId: id) else { continue } + byID[id] = current + } + return byID.values.sorted { + $0.updatedAt == $1.updatedAt ? $0.id < $1.id : $0.updatedAt > $1.updatedAt + } + } + + @discardableResult + func saveChats(_ chats: [AidenChat], instanceId: String, workspaceId: String, writeToken: UInt64, isAuthoritativeFetch: Bool = false) async throws -> Bool { await beforeMetadataWrite?() - guard metadataWriteIsRetained(writeToken, instanceId: instanceId) else { return } + guard metadataWriteIsRetained(writeToken, instanceId: instanceId) else { return false } let latestListToken = workspaceWriteTokens[instanceId]?[workspaceId] ?? 0 let isOlderList = writeToken < latestListToken let partial = isOlderList || metadataWriteIsPartial(writeToken, instanceId: instanceId) @@ -323,14 +415,79 @@ actor AidenChatCache { } } if partial { + // Extend the last admitted list itself, not its merged memory view: + // a detail whose disk write failed must not become a durable row. let ids = Set(retained.map(\.id)) - retained += (loadChats(instanceId: instanceId, workspaceId: workspaceId) ?? []).filter { !ids.contains($0.id) } + retained += (admittedWorkspaceListRows(instanceId: instanceId, workspaceId: workspaceId) ?? []).filter { !ids.contains($0.id) } + } + retained = Dictionary(retained.filter { + !isChatHidden(instanceId: instanceId, chatId: $0.id) + }.map { row -> (String, AidenChat) in + var canonical = row + canonical.localTitleOverride = nil + return (row.id, canonical) + }, uniquingKeysWith: { _, latest in latest }).values.sorted { + $0.updatedAt == $1.updatedAt ? $0.id < $1.id : $0.updatedAt > $1.updatedAt + } + admittedWorkspaceLists[instanceId, default: [:]][workspaceId] = retained + if isAuthoritativeFetch, !isOlderList { + workspaceFetchTokens[instanceId, default: [:]][workspaceId] = writeToken + let retainedIDs = Set(retained.map(\.id)) + workspaceFetchedTitles[instanceId, default: [:]][workspaceId] = Dictionary(chats.filter { retainedIDs.contains($0.id) }.map { ($0.id, $0.title) }, uniquingKeysWith: { _, latest in latest }) + } + defer { + // A list row supersedes the old receipt title even if list IO fails. + // Keep the new title separate until a coherent detail read catches + // up; generic detail hydration may still have an older canonical row. + for row in chats where isAuthoritativeFetch && !isOlderList { + if retained.contains(where: { $0.id == row.id }), + let pending = pendingRename(instanceId: instanceId, chatId: row.id), writeToken > pending.cutoff, + (fetchedChatTokens[instanceId]?[row.id] ?? 0) <= writeToken { + let value = RenameTitle(instanceId: instanceId, chatId: row.id, title: row.title) + renameTitles[instanceId, default: [:]][row.id] = PendingRename(value: value, origin: pending.origin, cutoff: writeToken) + retiredRenameTitles[instanceId]?.remove(row.id) + try? save(value, to: fileURL(kind: "rename-titles", instanceId, row.id)) + } + } } workspaceWriteTokens[instanceId, default: [:]][workspaceId] = max(writeToken, latestListToken) try save( ChatListEnvelope(instanceId: instanceId, workspaceId: workspaceId, chats: retained), to: fileURL(kind: "lists", instanceId, workspaceId) ) + return true + } + + @discardableResult + func reconcileWorkspaceChat(_ chat: AidenChat, instanceId: String, authority: UInt64, cutoff: UInt64) async -> Bool { + await beforeMetadataWrite?() + guard isChatWriteRetained(authority, instanceId: instanceId, chatId: chat.id), + !isChatHidden(instanceId: instanceId, chatId: chat.id), + let current = admittedChat(instanceId: instanceId, chatId: chat.id) else { return false } + // Read after suspension, and never revive a row omitted by a list that + // was requested after this receipt arrived. + var rows = admittedWorkspaceChats(instanceId: instanceId, workspaceId: chat.workspaceId) ?? [] + let listToken = workspaceWriteTokens[instanceId]?[chat.workspaceId] ?? 0 + let mayPublish = listToken <= cutoff || rows.contains { $0.id == chat.id } + if mayPublish { + if listToken <= cutoff || (chatWriteGenerations[instanceId]?[chat.id] ?? 0) >= listToken { + rows.removeAll { $0.id == chat.id } + rows.append(current) + admittedWorkspaceLists[instanceId, default: [:]][chat.workspaceId] = rows + workspaceWriteTokens[instanceId, default: [:]][chat.workspaceId] = max(authority, listToken) + try? save(ChatListEnvelope(instanceId: instanceId, workspaceId: chat.workspaceId, chats: rows), to: fileURL(kind: "lists", instanceId, chat.workspaceId)) + } + } + let cached = loadChatSummaries(instanceId: instanceId) + let summaryToken = summaryRowAuthority(instanceId: instanceId, chatId: chat.id) + let existing = cached?.summaries.first { $0.id == chat.id } + let winnerToken = max(listToken, chatWriteGenerations[instanceId]?[chat.id] ?? 0) + if let winner = presentedWorkspaceChat(instanceId: instanceId, workspaceId: chat.workspaceId, chatId: chat.id), + summaryToken <= cutoff || (existing != nil && ((summaryFullTokens[instanceId] ?? 0) <= cutoff || winnerToken >= summaryToken)) { + let summaries = AidenChatSummaryPage.merged(current: cached?.summaries ?? [], appending: [AidenChatSummary(chat: winner, preservingActivity: existing?.activity ?? .idle)]) + try? persistChatSummaries(SummarySnapshot(summaries: summaries, nextCursor: cached?.nextCursor), instanceId: instanceId, writeToken: max(cutoff, max(summaryToken, winnerToken)), updatedRows: [chat.id: max(summaryToken, max(cutoff, winnerToken))]) + } + return mayPublish } private func metadataWriteIsRetained(_ token: UInt64, instanceId: String) -> Bool { @@ -358,6 +515,101 @@ actor AidenChatCache { return envelope.chat } + func admittedChat(instanceId: String, chatId: String) -> AidenChat? { + guard !chatWriteClock.isPending(instanceId: instanceId, chatId: chatId) else { return nil } + if let token = chatWriteGenerations[instanceId]?[chatId] { + guard isChatWriteRetained(token, instanceId: instanceId, chatId: chatId) else { return nil } + return admittedChats[instanceId]?[chatId] + } + guard chatPurgeGenerations[instanceId] == nil else { return nil } + return loadChat(instanceId: instanceId, chatId: chatId) + } + + private func pendingRename(instanceId: String, chatId: String) -> PendingRename? { + guard !isChatHidden(instanceId: instanceId, chatId: chatId), + !chatWriteClock.isPending(instanceId: instanceId, chatId: chatId) else { return nil } + if let pending = renameTitles[instanceId]?[chatId] { return pending } + guard chatPurgeGenerations[instanceId] == nil, + retiredRenameTitles[instanceId]?.contains(chatId) != true, + let value: RenameTitle = load(RenameTitle.self, from: fileURL(kind: "rename-titles", instanceId, chatId)), + value.instanceId == instanceId, value.chatId == chatId, + !(value.retired ?? value.title.isEmpty), value.title.unicodeScalars.count <= 1_024 else { return nil } + let pending = PendingRename(value: value, origin: 0, cutoff: 0) + renameTitles[instanceId, default: [:]][chatId] = pending + return pending + } + + func needsRenameRefresh(instanceId: String, chatId: String) -> Bool { + pendingRename(instanceId: instanceId, chatId: chatId) != nil + } + + func presenting(_ chat: AidenChat, instanceId: String) -> AidenChat { + var result = chat + result.localTitleOverride = pendingRename(instanceId: instanceId, chatId: chat.id)?.value.title + return result + } + + // A successful PATCH owns its title field, not another owner's full transcript/revision. + func acceptRename(_ receipt: AidenChat, instanceId: String, origin: UInt64, cutoff: UInt64) async -> AidenChat? { + guard isChatWriteRetained(origin, instanceId: instanceId, chatId: receipt.id), + !chatWriteClock.isPending(instanceId: instanceId, chatId: receipt.id) else { return nil } + // Install receipt authority before the cache-write suspension so a later + // requested GET can retire it while that write is queued. + let newestReceipt = origin > (renameOrigins[instanceId]?[receipt.id] ?? 0) + if newestReceipt { renameOrigins[instanceId, default: [:]][receipt.id] = origin } + let listToken = workspaceFetchTokens[instanceId]?[receipt.workspaceId] ?? 0 + let newerListTitle = listToken > cutoff ? workspaceFetchedTitles[instanceId]?[receipt.workspaceId]?[receipt.id] : nil + let titleCutoff = newerListTitle == nil ? cutoff : listToken + if newestReceipt, (fetchedChatTokens[instanceId]?[receipt.id] ?? 0) <= titleCutoff { + let value = RenameTitle(instanceId: instanceId, chatId: receipt.id, title: newerListTitle ?? receipt.title) + renameTitles[instanceId, default: [:]][receipt.id] = PendingRename(value: value, origin: origin, cutoff: titleCutoff) + retiredRenameTitles[instanceId]?.remove(receipt.id) + try? save(value, to: fileURL(kind: "rename-titles", instanceId, receipt.id)) + } + _ = try? await saveChat(receipt, instanceId: instanceId, writeToken: origin) + guard isChatWriteRetained(origin, instanceId: instanceId, chatId: receipt.id), + !chatWriteClock.isPending(instanceId: instanceId, chatId: receipt.id), + let canonical = admittedChat(instanceId: instanceId, chatId: receipt.id) else { return nil } + return presenting(canonical, instanceId: instanceId) + } + + @discardableResult + func saveFetchedChat(_ chat: AidenChat, instanceId: String, writeToken: UInt64) async throws -> Bool { + // Check receipt authority after the write as well: an overlay can be + // installed while this actor is suspended at the IO boundary. + let accepted: Bool + do { accepted = try await saveChat(chat, instanceId: instanceId, writeToken: writeToken) } + catch { + if chatWriteGenerations[instanceId]?[chat.id] == writeToken { + fetchedChatTokens[instanceId, default: [:]][chat.id] = max(writeToken, fetchedChatTokens[instanceId]?[chat.id] ?? 0) + } + retireRenameAfterFetch(instanceId: instanceId, chatId: chat.id, writeToken: writeToken, pending: pendingRename(instanceId: instanceId, chatId: chat.id), persisted: false) + throw error + } + if accepted { + fetchedChatTokens[instanceId, default: [:]][chat.id] = max(writeToken, fetchedChatTokens[instanceId]?[chat.id] ?? 0) + retireRenameAfterFetch(instanceId: instanceId, chatId: chat.id, writeToken: writeToken, pending: pendingRename(instanceId: instanceId, chatId: chat.id)) + } + return accepted + } + + private func retireRenameAfterFetch(instanceId: String, chatId: String, writeToken: UInt64, pending: PendingRename?, persisted: Bool = true) { + guard let pending, writeToken > pending.cutoff, + chatWriteGenerations[instanceId]?[chatId] == writeToken, + renameTitles[instanceId]?[chatId]?.cutoff == pending.cutoff else { return } + renameTitles[instanceId]?.removeValue(forKey: chatId) + retiredRenameTitles[instanceId, default: []].insert(chatId) + if persisted { + // Persist retirement atomically; a failed unlink cannot resurrect + // an older receipt when a new cache actor opens the directory. + try? save(RenameTitle(instanceId: instanceId, chatId: chatId, title: "", retired: true), to: fileURL(kind: "rename-titles", instanceId, chatId)) + } else if let canonical = admittedChats[instanceId]?[chatId] { + // Keep a separate durable title for restart if the canonical file + // could not be updated, without hiding the current memory winner. + try? save(RenameTitle(instanceId: instanceId, chatId: chatId, title: canonical.title), to: fileURL(kind: "rename-titles", instanceId, chatId)) + } + } + @discardableResult func saveChat(_ chat: AidenChat, instanceId: String, writeToken: UInt64) async throws -> Bool { await beforeChatWrite?() @@ -368,8 +620,17 @@ actor AidenChatCache { // Advance even if persistence fails: an older queued snapshot must not // become authoritative merely because the newest disk write failed. chatWriteGenerations[instanceId, default: [:]][chat.id] = writeToken + var canonical = chat + canonical.localTitleOverride = nil + admittedChats[instanceId, default: [:]][chat.id] = canonical + if !canonical.isBotChat, writeToken >= summaryRowAuthority(instanceId: instanceId, chatId: chat.id) { + let cached = loadChatSummaries(instanceId: instanceId) + let activity = cached?.summaries.first(where: { $0.id == chat.id })?.activity ?? .idle + let rows = AidenChatSummaryPage.merged(current: cached?.summaries ?? [], appending: [AidenChatSummary(chat: presenting(canonical, instanceId: instanceId), preservingActivity: activity)]) + try? persistChatSummaries(.init(summaries: rows, nextCursor: cached?.nextCursor), instanceId: instanceId, writeToken: writeToken, updatedRows: [chat.id: writeToken]) + } try save( - ChatEnvelope(instanceId: instanceId, chat: chat), + ChatEnvelope(instanceId: instanceId, chat: canonical), to: fileURL(kind: "chats", instanceId, chat.id) ) committedChatWrites[instanceId, default: [:]][chat.id] = ( @@ -380,6 +641,10 @@ actor AidenChatCache { } func loadChatSummaries(instanceId: String, includingRemoved: Bool = false) -> SummarySnapshot? { + if let snapshot = admittedSummaries[instanceId] { + return .init(summaries: includingRemoved ? snapshot.summaries : snapshot.summaries.filter { !isChatHidden(instanceId: instanceId, chatId: $0.id) }, nextCursor: snapshot.nextCursor) + } + guard (chatPurgeGenerations[instanceId] ?? 0) == 0 else { return nil } guard let envelope: ChatSummaryEnvelope = load( ChatSummaryEnvelope.self, from: fileURL(kind: "summaries", instanceId), @@ -400,52 +665,93 @@ actor AidenChatCache { return SummarySnapshot(summaries: includingRemoved ? summaries : summaries.filter { !isChatHidden(instanceId: instanceId, chatId: $0.id) }, nextCursor: envelope.snapshot.nextCursor) } + func summaryState(instanceId: String) -> (snapshot: SummarySnapshot?, fullToken: UInt64, rowTokens: [String: UInt64]) { + (loadChatSummaries(instanceId: instanceId), summaryFullTokens[instanceId] ?? 0, summaryRowTokens[instanceId] ?? [:]) + } + + @discardableResult func saveChatSummaries( _ snapshot: SummarySnapshot, instanceId: String, generation: UInt64? = nil, - writeToken: UInt64 - ) async throws { + writeToken: UInt64, + preservingCursor: Bool = false, + changedIDs: Set? = nil, + editTokens: [String: UInt64]? = nil, + activityOnlyIDs: Set = [] + ) async throws -> Bool { await beforeMetadataWrite?() - guard metadataWriteIsRetained(writeToken, instanceId: instanceId) else { return } + guard metadataWriteIsRetained(writeToken, instanceId: instanceId) else { return false } var retained = snapshot.summaries.filter { !isChatHidden(instanceId: instanceId, chatId: $0.id) && isChatWriteRetained(writeToken, instanceId: instanceId, chatId: $0.id) } - var nextCursor = snapshot.nextCursor + var updatedRows: [String: UInt64]? + if let changedIDs { + let changedIDs = changedIDs.filter { (editTokens?[$0] ?? writeToken) >= summaryRowAuthority(instanceId: instanceId, chatId: $0) } + updatedRows = Dictionary(uniqueKeysWithValues: changedIDs.map { ($0, editTokens?[$0] ?? writeToken) }) + let existing = loadChatSummaries(instanceId: instanceId)?.summaries ?? [] + let changes = retained.filter { changedIDs.contains($0.id) }.compactMap { row -> AidenChatSummary? in + guard activityOnlyIDs.contains(row.id) else { return row } + guard var current = existing.first(where: { $0.id == row.id }) else { return nil } + current.activity = row.activity + return current + } + retained = AidenChatSummaryPage.merged(current: existing.filter { !changedIDs.contains($0.id) }, appending: changes) + } + var nextCursor = preservingCursor ? (loadChatSummaries(instanceId: instanceId).map(\.nextCursor) ?? snapshot.nextCursor) : snapshot.nextCursor let partial = metadataWriteIsPartial(writeToken, instanceId: instanceId) if partial { let cached = loadChatSummaries(instanceId: instanceId) retained = AidenChatSummaryPage.merged(current: cached?.summaries ?? [], appending: retained) if let cached { nextCursor = cached.nextCursor } } - try persistChatSummaries(SummarySnapshot(summaries: retained, nextCursor: nextCursor), instanceId: instanceId, generation: partial ? nil : generation, writeToken: writeToken) + if updatedRows?.isEmpty == true { return true } + let acceptedSnapshot = SummarySnapshot(summaries: retained, nextCursor: nextCursor) + do { + return try persistChatSummaries(acceptedSnapshot, instanceId: instanceId, generation: partial ? nil : generation, writeToken: writeToken, updatedRows: updatedRows) + } catch { + // A validated, admitted page remains usable when only disk IO fails. + if admittedSummaries[instanceId] == acceptedSnapshot, updatedRows != nil || summaryWriteTokens[instanceId] == writeToken { return true } + throw error + } } - private func persistChatSummaries(_ snapshot: SummarySnapshot, instanceId: String, generation: UInt64? = nil, writeToken: UInt64) throws { - guard writeToken >= (summaryWriteTokens[instanceId] ?? 0) else { return } + @discardableResult + private func persistChatSummaries(_ snapshot: SummarySnapshot, instanceId: String, generation: UInt64? = nil, writeToken: UInt64, isRemoval: Bool = false, updatedRows: [String: UInt64]? = nil) throws -> Bool { + guard updatedRows != nil || writeToken >= (summaryWriteTokens[instanceId] ?? 0) else { return false } guard snapshot.summaries.count <= maxSummaryCacheItems else { throw CocoaError(.fileWriteOutOfSpace) } guard snapshot.summaries.allSatisfy(AidenChatSummary.isValidCachedProjection) else { throw AidenRemoteContractError.invalidJSON } - if let generation { - guard generation >= (summaryWriteGenerations[instanceId] ?? 0) else { return } - summaryWriteGenerations[instanceId] = generation + let envelope = ChatSummaryEnvelope(instanceId: instanceId, snapshot: CachedSummarySnapshot(snapshot)) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + guard try encoder.encode(envelope).count <= maxSummaryCacheFileBytes else { + throw CocoaError(.fileWriteOutOfSpace) } - summaryWriteTokens[instanceId] = writeToken - try save( - ChatSummaryEnvelope(instanceId: instanceId, snapshot: CachedSummarySnapshot(snapshot)), - to: fileURL(kind: "summaries", instanceId), - maximumBytes: maxSummaryCacheFileBytes - ) + // Model-local generations cannot arbitrate between different Home owners. + // Removal runs synchronously on this actor. A concurrently reserved + // HTTP request cannot suppress its durable rewrite before cleanup ends. + if updatedRows == nil, !isRemoval { + guard chatWriteClock.admitSummary(writeToken, instanceId: instanceId) else { return false } + } else { _ = chatWriteClock.admitSummary(writeToken, instanceId: instanceId) } + if let updatedRows { + for (id, token) in updatedRows { summaryRowTokens[instanceId, default: [:]][id] = max(token, summaryRowTokens[instanceId]?[id] ?? 0) } + } else { summaryFullTokens[instanceId] = writeToken } + summaryWriteTokens[instanceId] = max(writeToken, summaryWriteTokens[instanceId] ?? 0) + admittedSummaries[instanceId] = snapshot + try save(envelope, to: fileURL(kind: "summaries", instanceId), maximumBytes: maxSummaryCacheFileBytes) + return true } func reconcileChatSummary(_ chat: AidenChat, instanceId: String, writeToken: UInt64) async throws { await beforeMetadataWrite?() guard metadataWriteIsRetained(writeToken, instanceId: instanceId), !isChatHidden(instanceId: instanceId, chatId: chat.id), - isChatWriteRetained(writeToken, instanceId: instanceId, chatId: chat.id), !chat.isBotChat else { return } + isChatWriteRetained(writeToken, instanceId: instanceId, chatId: chat.id), !chat.isBotChat, + writeToken >= summaryRowAuthority(instanceId: instanceId, chatId: chat.id) else { return } let cached = loadChatSummaries(instanceId: instanceId) let existingActivity = cached?.summaries.first(where: { $0.id == chat.id })?.activity ?? .idle let summaries = AidenChatSummaryPage.merged( @@ -454,17 +760,19 @@ actor AidenChatCache { ) try persistChatSummaries( SummarySnapshot(summaries: summaries, nextCursor: cached?.nextCursor), - instanceId: instanceId, writeToken: writeToken + instanceId: instanceId, writeToken: writeToken, updatedRows: [chat.id: writeToken] ) } - func removeChatSummary(instanceId: String, chatId: String, writeToken: UInt64? = nil) throws { + func removeChatSummary(instanceId: String, chatId: String, writeToken: UInt64? = nil, beforeWrite: (@Sendable () -> Void)? = nil) throws { + let removalToken = reserveSummaryWrite(instanceId: instanceId) guard let cached = loadChatSummaries(instanceId: instanceId, includingRemoved: true) else { return } let summaries = cached.summaries.filter { $0.id != chatId } guard summaries.count != cached.summaries.count else { return } + beforeWrite?() try persistChatSummaries( SummarySnapshot(summaries: summaries, nextCursor: cached.nextCursor), - instanceId: instanceId, writeToken: writeToken.map { max($0, summaryWriteTokens[instanceId] ?? 0) } ?? reserveChatWrite() + instanceId: instanceId, writeToken: removalToken, isRemoval: true, updatedRows: [chatId: removalToken] ) } @@ -522,6 +830,14 @@ actor AidenChatCache { chatWriteGenerations[instanceId, default: [:]][chatId] = max(token, chatWriteGenerations[instanceId]?[chatId] ?? 0) removedChatIDs[instanceId, default: []].insert(chatId) committedChatWrites[instanceId]?.removeValue(forKey: chatId) + admittedChats[instanceId]?.removeValue(forKey: chatId) + renameTitles[instanceId]?.removeValue(forKey: chatId) + retiredRenameTitles[instanceId, default: []].insert(chatId) + try? fileManager.removeItem(at: fileURL(kind: "rename-titles", instanceId, chatId)) + for workspace in Array(admittedWorkspaceLists[instanceId]?.keys ?? Dictionary().keys) { + admittedWorkspaceLists[instanceId]?[workspace]?.removeAll { $0.id == chatId } + workspaceFetchedTitles[instanceId]?[workspace]?.removeValue(forKey: chatId) + } let directory = root.appending(path: "lists", directoryHint: .isDirectory) for url in (try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [] { guard let envelope = load(ChatListEnvelope.self, from: url), envelope.instanceId == instanceId, @@ -555,9 +871,17 @@ actor AidenChatCache { chatPurgeGenerations[instanceId] = max(token, chatPurgeGenerations[instanceId] ?? 0) removedChatIDs.removeValue(forKey: instanceId) workspaceWriteTokens.removeValue(forKey: instanceId) + workspaceFetchTokens.removeValue(forKey: instanceId) + workspaceFetchedTitles.removeValue(forKey: instanceId) + admittedWorkspaceLists.removeValue(forKey: instanceId) summaryWriteTokens.removeValue(forKey: instanceId) + admittedSummaries.removeValue(forKey: instanceId) + summaryFullTokens.removeValue(forKey: instanceId) + summaryRowTokens.removeValue(forKey: instanceId) chatWriteGenerations.removeValue(forKey: instanceId) committedChatWrites.removeValue(forKey: instanceId) + admittedChats.removeValue(forKey: instanceId) + renameTitles.removeValue(forKey: instanceId) summaryWriteGenerations.removeValue(forKey: instanceId) purgeNamespace(root, instanceId: instanceId) for legacyRoot in legacyRoots where legacyRoot.standardizedFileURL != root.standardizedFileURL { @@ -753,6 +1077,7 @@ actor AidenChatCache { } private func purgeNamespace(_ cacheRoot: URL, instanceId: String) { + purgeFiles(root: cacheRoot, kind: "rename-titles", instanceId: instanceId, as: RenameTitle.self) { $0.instanceId } purgeFiles(root: cacheRoot, kind: "lists", instanceId: instanceId, as: ChatListEnvelope.self) { $0.instanceId } diff --git a/ios/AidenOnTheGoTests/AidenChatTests.swift b/ios/AidenOnTheGoTests/AidenChatTests.swift index f65433c76d..075167aa84 100644 --- a/ios/AidenOnTheGoTests/AidenChatTests.swift +++ b/ios/AidenOnTheGoTests/AidenChatTests.swift @@ -819,7 +819,7 @@ final class AidenChatTests: XCTestCase { } @MainActor - func testAcceptedRenameSurvivesUnrelatedRowAndEmptyListUpdates() async throws { + func testAcceptedRenameSurvivesUnrelatedRowButHonorsNewerListOmission() async throws { for refresh in [false, true] { let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-interleaving-\(UUID())") defer { try? FileManager.default.removeItem(at: root) } @@ -845,11 +845,11 @@ final class AidenChatTests: XCTestCase { if refresh { await workspace.load() } else { workspace.accept(sampleChat()) } await gate.release() await creating.value - XCTAssertEqual(workspace.chats.first { $0.id == detail.chat.id }?.title, "Renamed successfully") - XCTAssertTrue(workspace.chats.contains { $0.id == detail.chat.id }) - XCTAssertEqual(publications.map(\.id), [detail.chat.id]) + XCTAssertEqual(workspace.chats.first { $0.id == detail.chat.id }?.displayTitle, refresh ? nil : "Renamed successfully") + XCTAssertEqual(workspace.chats.contains { $0.id == detail.chat.id }, !refresh) + XCTAssertEqual(publications.map(\.id), refresh ? [] : [detail.chat.id]) let list = await cache.loadChats(instanceId: "instance-progress-lifecycle", workspaceId: "workspace-1") - XCTAssertTrue(list?.contains { $0.id == detail.chat.id } == true) + XCTAssertEqual(list?.contains { $0.id == detail.chat.id }, !refresh) } } @@ -870,7 +870,11 @@ final class AidenChatTests: XCTestCase { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 let data = try encoder.encode(remote) + let detailID = detail.chat.id AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + if request.httpMethod == "GET", request.url?.path.hasSuffix("/chats/" + detailID) == true { + return (503, "application/json", Data("{}".utf8)) + } guard request.httpMethod == "POST" || request.httpMethod == "PATCH" else { return nil } return (request.httpMethod == "POST" ? 201 : 200, "application/json", data) } @@ -1040,6 +1044,682 @@ final class AidenChatTests: XCTestCase { } } + func testListTitleBeforeRenameActorEntrySurvivesLocalListOverwrite() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-list-title-mailbox-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var receipt = sampleChat() + receipt.title = "Receipt B" + let origin = cache.reserveChatWrite() + let cutoff = cache.reserveChatWrite() + var remote = receipt + remote.title = "Authoritative C" + try await cache.saveChats([remote], instanceId: "title-mailbox", workspaceId: remote.workspaceId, writeToken: cache.reserveChatWrite(), isAuthoritativeFetch: true) + // A local snapshot cannot rewrite the recorded HTTP title provenance. + try await cache.saveChats([receipt], instanceId: "title-mailbox", workspaceId: receipt.workspaceId, writeToken: cache.reserveChatWrite()) + let presented = await cache.acceptRename(receipt, instanceId: "title-mailbox", origin: origin, cutoff: cutoff) + XCTAssertEqual(presented?.displayTitle, remote.title) + XCTAssertEqual(presented?.title, receipt.title) + XCTAssertEqual(presented?.revision, receipt.revision) + let reopened = AidenChatCache(root: root) + let disk = await reopened.loadChat(instanceId: "title-mailbox", chatId: receipt.id) + let restored = await reopened.presenting(try XCTUnwrap(disk), instanceId: "title-mailbox") + XCTAssertEqual(restored.displayTitle, remote.title) + } + + func testAuthoritativeListTitleSurvivesDetailHydrationWithOrWithoutListDiskFailure() async throws { + for authoritativeTitle in ["Coherent list C", ""] { + for failListWrite in [false, true] { + for authoritative in [false, true] { + for requestedAfterReceipt in [false, true] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-list-rename-disk-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var receipt = sampleChat() + receipt.title = "Accepted rename B" + let origin = cache.reserveChatWrite() + let earlyListToken = cache.reserveChatWrite() + _ = await cache.acceptRename(receipt, instanceId: "list-disk", origin: origin, cutoff: cache.reserveChatWrite()) + let listToken = requestedAfterReceipt ? cache.reserveChatWrite() : earlyListToken + if failListWrite { + let directory = root.appending(path: "lists") + try? FileManager.default.removeItem(at: directory) + try Data("blocked list directory".utf8).write(to: directory) + } + var latest = receipt + latest.title = authoritativeTitle + latest.revision = "list-C" + do { + try await cache.saveChats([latest], instanceId: "list-disk", workspaceId: latest.workspaceId, writeToken: listToken, isAuthoritativeFetch: authoritative) + XCTAssertFalse(failListWrite) + } catch { XCTAssertTrue(failListWrite) } + let shouldSupersede = authoritative && requestedAfterReceipt + let expectedTitle = shouldSupersede ? latest.title : receipt.title + let rows = await cache.admittedWorkspaceChats(instanceId: "list-disk", workspaceId: latest.workspaceId) + let admitted = try XCTUnwrap(rows?.first) + let presented = await cache.presenting(admitted, instanceId: "list-disk") + XCTAssertEqual(presented.displayTitle, expectedTitle) + XCTAssertEqual(presented.revision, latest.revision) + let detailed = await cache.admittedChat(instanceId: "list-disk", chatId: latest.id) + let canonical = try XCTUnwrap(detailed) + let hydrated = await cache.presenting(canonical, instanceId: "list-disk") + XCTAssertEqual(hydrated.displayTitle, expectedTitle) + XCTAssertEqual(hydrated.title, receipt.title) + XCTAssertEqual(hydrated.revision, receipt.revision) + let pending = await cache.needsRenameRefresh(instanceId: "list-disk", chatId: latest.id) + XCTAssertTrue(pending, "An older canonical detail still requires a coherent read before mutation") + let reopened = AidenChatCache(root: root) + let disk = await reopened.loadChat(instanceId: "list-disk", chatId: receipt.id) + let restored = await reopened.presenting(try XCTUnwrap(disk), instanceId: "list-disk") + XCTAssertEqual(restored.displayTitle, expectedTitle) + XCTAssertEqual(restored.title, receipt.title) + XCTAssertEqual(restored.revision, receipt.revision) + if shouldSupersede { + try await cache.saveFetchedChat(latest, instanceId: "list-disk", writeToken: cache.reserveChatWrite()) + let retired = await cache.needsRenameRefresh(instanceId: "list-disk", chatId: latest.id) + XCTAssertFalse(retired) + } + } + } + } + } + } + + @MainActor + func testRenamePublishesNewerListRowInsteadOfOlderDetailReceipt() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-list-row-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let gate = AidenChatWriteTestGate() + let cache = AidenChatCache(root: root, beforeChatWrite: { await gate.waitIfArmed() }) + var workspace: AidenWorkspaceChatsModel! + var publications: [AidenChat] = [] + let detail = try await makeProgressLifecycleModel(mode: .denied, cache: cache, onCoordinator: { coordinator in + workspace = AidenWorkspaceChatsModel(coordinator: coordinator, workspaceId: "workspace-1", cache: cache, onChatUpdated: { publications.append($0) }) + }) + var receipt = detail.chat + receipt.title = "PATCH title" + var newer = receipt + newer.title = "Later list title" + newer.revision = "newer-list-revision" + newer.messages.append(AidenChatMessage(id: "newer-list-reply", role: .assistant, text: "Keep list winner", createdAt: Date())) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let receiptData = try encoder.encode(receipt) + let listData = try encoder.encode(["chats": [newer]]) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + if request.httpMethod == "PATCH" { return (200, "application/json", receiptData) } + if request.url?.path.hasSuffix("/chats") == true { return (200, "application/json", listData) } + return (503, "application/json", Data("{}".utf8)) + } + await gate.arm() + let renaming = Task { await workspace.rename(receipt, to: receipt.title) } + await waitForChatWrite(gate) + await workspace.load() + await gate.release() + await renaming.value + XCTAssertEqual(workspace.chats.first?.revision, newer.revision) + XCTAssertEqual(workspace.chats.first?.messages, newer.messages) + XCTAssertEqual(publications.last?.displayTitle, newer.title) + XCTAssertEqual(publications.last?.revision, newer.revision) + let reopened = AidenChatCache(root: root) + let restored = await reopened.presentedWorkspaceChat(instanceId: "instance-progress-lifecycle", workspaceId: newer.workspaceId, chatId: newer.id) + XCTAssertEqual(restored?.displayTitle, newer.title) + XCTAssertEqual(restored?.messages, newer.messages) + let summaries = await reopened.loadChatSummaries(instanceId: "instance-progress-lifecycle") + XCTAssertEqual(summaries?.summaries.first?.title, newer.title) + XCTAssertEqual(summaries?.summaries.first?.revision, newer.revision) + } + + @MainActor + func testHeldRenamePreservesCanonicalWinnerAndDurableTitleOnRefreshFailure() async throws { + for mode in ["settled", "unrelated", "remove", "purge"] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-response-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var workspace: AidenWorkspaceChatsModel! + let detail = try await makeProgressLifecycleModel(mode: .denied, cache: cache, onCoordinator: { coordinator in + workspace = AidenWorkspaceChatsModel(coordinator: coordinator, workspaceId: "workspace-1", cache: cache) + }) + let instance = "instance-progress-lifecycle" + let old = detail.chat + var receipt = old + receipt.title = "Accepted rename" + receipt.revision = "opaque-rename" + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let receiptData = try encoder.encode(receipt) + let requests = AidenRenameRequestLog() + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + requests.record(request) + guard request.url?.path.hasSuffix("/chats/" + old.id) == true else { return nil } + return request.httpMethod == "PATCH" ? (200, "application/json", receiptData) : (503, "application/json", Data("{}".utf8)) + } + let arrived = expectation(description: "PATCH held") + AidenChatProgressLifecycleURLProtocol.holdNextRequest(endingIn: "/chats/" + old.id) { arrived.fulfill() } + let renaming = Task { await workspace.rename(old, to: receipt.title) } + await fulfillment(of: [arrived], timeout: 2) + var settled = old + settled.title = "Canonical settled title" + settled.revision = "opaque-settled" + settled.messages.append(AidenChatMessage(id: "rename-final", role: .assistant, text: "Retain settled transcript", createdAt: Date())) + try await cache.saveFetchedChat(settled, instanceId: instance, writeToken: cache.reserveChatWrite()) + if mode == "unrelated" { await cache.removeChat(instanceId: instance, chatId: "unrelated-deleted-chat") } + if mode == "remove" { await cache.removeChat(instanceId: instance, chatId: old.id) } + if mode == "purge" { await cache.purge(instanceId: instance) } + AidenChatProgressLifecycleURLProtocol.releaseHeldRequest() + await renaming.value + let canonical = await cache.admittedChat(instanceId: instance, chatId: old.id) + if ["settled", "unrelated"].contains(mode) { + XCTAssertEqual(canonical?.title, settled.title) + XCTAssertEqual(canonical?.revision, settled.revision) + XCTAssertEqual(canonical?.messages, settled.messages) + XCTAssertEqual(workspace.chats.first?.displayTitle, receipt.title) + XCTAssertEqual(workspace.chats.first?.revision, settled.revision) + XCTAssertEqual(AidenChatSummary(chat: try XCTUnwrap(workspace.chats.first)).title, receipt.title) + let reopened = AidenChatCache(root: root) + let stored = await reopened.loadChat(instanceId: instance, chatId: old.id) + let disk = try XCTUnwrap(stored) + let presented = await reopened.presenting(disk, instanceId: instance) + XCTAssertEqual(presented.displayTitle, receipt.title) + XCTAssertEqual(presented.title, settled.title) + let wire = try JSONSerialization.jsonObject(with: encoder.encode(presented)) as? [String: Any] + XCTAssertEqual(wire?["title"] as? String, settled.title) + XCTAssertNil(wire?["localTitleOverride"]) + // Offline next mutation must fail its read prerequisite, not submit another PATCH. + await workspace.rename(presented, to: "Must wait for refresh") + XCTAssertEqual(workspace.chats.first?.displayTitle, receipt.title) + XCTAssertEqual(requests.count("PATCH"), 1) + await workspace.remove(presented) + XCTAssertEqual(requests.count("DELETE"), 0) + var coherent = settled + coherent.title = receipt.title + coherent.revision = "fresh-prerequisite" + let coherentData = try encoder.encode(coherent) + var secondReceipt = coherent + secondReceipt.title = "Second accepted title" + secondReceipt.revision = "second-receipt" + let secondData = try encoder.encode(secondReceipt) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + requests.record(request) + guard request.url?.path.hasSuffix("/chats/" + old.id) == true else { return nil } + if request.httpMethod == "PATCH" { return (200, "application/json", secondData) } + return (200, "application/json", requests.count("PATCH") >= 2 ? secondData : coherentData) + } + await workspace.rename(presented, to: secondReceipt.title) + XCTAssertEqual(requests.count("PATCH"), 2) + XCTAssertEqual(requests.lastRevision(), coherent.revision) + XCTAssertEqual(workspace.chats.first?.displayTitle, secondReceipt.title) + let afterSuccess = AidenChatCache(root: root) + let list = await afterSuccess.loadChats(instanceId: instance, workspaceId: old.workspaceId) + let summaries = await afterSuccess.loadChatSummaries(instanceId: instance) + XCTAssertEqual(list?.first?.title, secondReceipt.title) + XCTAssertEqual(summaries?.summaries.first?.title, secondReceipt.title) + } else { + XCTAssertNil(canonical) + XCTAssertTrue(workspace.chats.isEmpty) + let pending = await cache.needsRenameRefresh(instanceId: instance, chatId: old.id) + XCTAssertFalse(pending) + } + } + } + + func testRenameRetirementSurvivesFailedUnlinkAndFreshFetchDiskFailure() async throws { + for failDetailWrite in [false, true] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-retire-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root, fileManager: AidenFailedRemovalFileManager()) + var chat = sampleChat() + _ = await cache.acceptRename(chat, instanceId: "retirement", origin: cache.reserveChatWrite(), cutoff: cache.reserveChatWrite()) + if failDetailWrite { + let directory = root.appending(path: "chats") + try FileManager.default.removeItem(at: directory) + try Data("blocked".utf8).write(to: directory) + } + chat.title = "Later coherent title" + do { + try await cache.saveFetchedChat(chat, instanceId: "retirement", writeToken: cache.reserveChatWrite()) + XCTAssertFalse(failDetailWrite) + } catch { XCTAssertTrue(failDetailWrite) } + let pending = await cache.needsRenameRefresh(instanceId: "retirement", chatId: chat.id) + XCTAssertFalse(pending) + let memory = await cache.presenting(chat, instanceId: "retirement") + XCTAssertNil(memory.localTitleOverride) + let reopened = AidenChatCache(root: root) + let restored = await reopened.presenting(chat, instanceId: "retirement") + XCTAssertEqual(restored.displayTitle, chat.title) + if !failDetailWrite { XCTAssertNil(restored.localTitleOverride) } + } + } + + @MainActor + func testFreshFetchRetiresRenameWhileReceiptPersistenceIsHeld() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-cache-await-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let gate = AidenChatWriteTestGate() + let cache = AidenChatCache(root: root, beforeChatWrite: { await gate.waitIfArmed() }) + var receipt = sampleChat() + receipt.title = "Older accepted rename" + let origin = cache.reserveChatWrite() + await gate.arm() + let accepting = Task { await cache.acceptRename(receipt, instanceId: "rename-await", origin: origin, cutoff: cache.reserveChatWrite()) } + await waitForChatWrite(gate) + var fresh = receipt + fresh.title = "Later coherent title" + fresh.revision = "later-fetch" + try await cache.saveFetchedChat(fresh, instanceId: "rename-await", writeToken: cache.reserveChatWrite()) + await gate.release() + let presented = await accepting.value + XCTAssertEqual(presented?.displayTitle, fresh.title) + XCTAssertNil(presented?.localTitleOverride) + let pending = await cache.needsRenameRefresh(instanceId: "rename-await", chatId: receipt.id) + XCTAssertFalse(pending) + } + + @MainActor + func testRenameCompanionReadsCanonicalAfterMetadataSuspension() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-companion-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let gate = AidenChatWriteTestGate() + let cache = AidenChatCache(root: root, beforeMetadataWrite: { await gate.waitIfArmed() }) + let receipt = sampleChat() + let origin = cache.reserveChatWrite() + let heldGet = cache.reserveChatWrite() + let cutoff = cache.reserveChatWrite() + let presented = await cache.acceptRename(receipt, instanceId: "companion", origin: origin, cutoff: cutoff) + await gate.arm() + let writing = Task { await cache.reconcileWorkspaceChat(presented ?? receipt, instanceId: "companion", authority: origin, cutoff: cutoff) } + await waitForChatWrite(gate) + var final = receipt + final.revision = "settled-during-metadata-await" + final.messages.append(AidenChatMessage(id: "metadata-final", role: .assistant, text: "Retain this final reply", createdAt: Date())) + try await cache.saveFetchedChat(final, instanceId: "companion", writeToken: heldGet) + await gate.release() + await writing.value + let disk = await AidenChatCache(root: root).loadChats(instanceId: "companion", workspaceId: final.workspaceId) + XCTAssertEqual(disk?.first?.revision, final.revision) + XCTAssertEqual(disk?.first?.messages, final.messages) + } + + @MainActor + func testRenameSummaryCarriesWinningListAuthorityPastHeldOlderSummary() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-summary-order-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let gate = AidenChatWriteTestGate() + let cache = AidenChatCache(root: root, beforeMetadataWrite: { await gate.waitIfArmed() }) + let receipt = sampleChat() + let origin = cache.reserveChatWrite() + let cutoff = cache.reserveChatWrite() + _ = await cache.acceptRename(receipt, instanceId: "summary-order", origin: origin, cutoff: cutoff) + let staleToken = cache.reserveChatWrite() + await gate.arm() + let stale = Task { try await cache.saveChatSummaries(.init(summaries: [], nextCursor: nil), instanceId: "summary-order", writeToken: staleToken) } + await waitForChatWrite(gate) + var winner = receipt + winner.title = "Authoritative list title" + winner.revision = "list-winner" + try await cache.saveChats([winner], instanceId: "summary-order", workspaceId: winner.workspaceId, writeToken: cache.reserveChatWrite(), isAuthoritativeFetch: true) + _ = await cache.reconcileWorkspaceChat(receipt, instanceId: "summary-order", authority: origin, cutoff: cutoff) + await gate.release() + try await stale.value + let summary = await AidenChatCache(root: root).loadChatSummaries(instanceId: "summary-order") + XCTAssertEqual(summary?.summaries.first?.title, winner.title) + XCTAssertEqual(summary?.summaries.first?.revision, winner.revision) + } + + @MainActor + func testRenameCompanionCannotRevivePostReceiptListOrSummaryOmission() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-new-list-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let gate = AidenChatWriteTestGate() + let cache = AidenChatCache(root: root, beforeMetadataWrite: { await gate.waitIfArmed() }) + let receipt = sampleChat() + let origin = cache.reserveChatWrite() + let cutoff = cache.reserveChatWrite() + _ = await cache.acceptRename(receipt, instanceId: "omission", origin: origin, cutoff: cutoff) + await gate.arm() + let writing = Task { await cache.reconcileWorkspaceChat(receipt, instanceId: "omission", authority: origin, cutoff: cutoff) } + await waitForChatWrite(gate) + let listToken = cache.reserveChatWrite() + try await cache.saveChats([], instanceId: "omission", workspaceId: receipt.workspaceId, writeToken: listToken) + try await cache.saveChatSummaries(.init(summaries: [], nextCursor: nil), instanceId: "omission", writeToken: listToken) + await gate.release() + let published = await writing.value + XCTAssertFalse(published) + let reopened = AidenChatCache(root: root) + let list = await reopened.loadChats(instanceId: "omission", workspaceId: receipt.workspaceId) + let summary = await reopened.loadChatSummaries(instanceId: "omission") + XCTAssertEqual(list?.count, 0) + XCTAssertEqual(summary?.summaries.count, 0) + } + + func testOlderRenameCannotOverlayNewerReceiptSupersededByFetch() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-two-receipts-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + let older = sampleChat() + let firstOrigin = cache.reserveChatWrite() + let secondOrigin = cache.reserveChatWrite() + let secondCutoff = cache.reserveChatWrite() + var newer = older + newer.title = "Latest coherent title" + try await cache.saveFetchedChat(newer, instanceId: "two-renames", writeToken: cache.reserveChatWrite()) + _ = await cache.acceptRename(newer, instanceId: "two-renames", origin: secondOrigin, cutoff: secondCutoff) + let result = await cache.acceptRename(older, instanceId: "two-renames", origin: firstOrigin, cutoff: cache.reserveChatWrite()) + XCTAssertEqual(result?.displayTitle, newer.title) + XCTAssertNil(result?.localTitleOverride) + } + + func testPostReceiptFetchWinsBeforeRenameActorAdmission() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-mailbox-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + let receipt = sampleChat() + let origin = cache.reserveChatWrite() + let cutoff = cache.reserveChatWrite() + var fresh = receipt + fresh.title = "Post-receipt GET" + let fetchToken = cache.reserveChatWrite() + try await cache.saveFetchedChat(fresh, instanceId: "mailbox", writeToken: fetchToken) + let presented = await cache.acceptRename(receipt, instanceId: "mailbox", origin: origin, cutoff: cutoff) + XCTAssertEqual(presented?.title, fresh.title) + XCTAssertNil(presented?.localTitleOverride) + } + + func testRenameOverlaySurvivesPreReceiptFetchAndRetiresOnLaterFetch() async throws { + for receiptFirst in [false, true] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-rename-orders-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var chat = sampleChat() + let origin = cache.reserveChatWrite() + let olderFetch = cache.reserveChatWrite() + var receipt = chat + receipt.title = "Successful title" + receipt.revision = "opaque-receipt" + chat.messages.append(AidenChatMessage(id: "rename-orders-final", role: .assistant, text: "Newer messages", createdAt: Date())) + chat.revision = "opaque-get" + if receiptFirst { _ = await cache.acceptRename(receipt, instanceId: "orders", origin: origin, cutoff: cache.reserveChatWrite()) } + try await cache.saveFetchedChat(chat, instanceId: "orders", writeToken: olderFetch) + if !receiptFirst { _ = await cache.acceptRename(receipt, instanceId: "orders", origin: origin, cutoff: cache.reserveChatWrite()) } + let canonical = await cache.admittedChat(instanceId: "orders", chatId: chat.id) + XCTAssertEqual(canonical?.revision, chat.revision) + XCTAssertEqual(canonical?.messages, chat.messages) + let pending = await cache.presenting(chat, instanceId: "orders") + XCTAssertEqual(pending.displayTitle, receipt.title) + var fresh = chat + fresh.title = receipt.title + fresh.revision = "coherent-refresh" + try await cache.saveFetchedChat(fresh, instanceId: "orders", writeToken: cache.reserveChatWrite()) + let retired = await cache.needsRenameRefresh(instanceId: "orders", chatId: chat.id) + XCTAssertFalse(retired) + let reopened = AidenChatCache(root: root) + let restored = await reopened.presenting(fresh, instanceId: "orders") + XCTAssertNil(restored.localTitleOverride) + } + } + + @MainActor + func testWorkspacePurgeRejectsStaleDiskFallbackAndAllowsFreshList() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-workspace-purge-disk-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root, fileManager: AidenFailedRemovalFileManager()) + let chat = sampleChat() + try await cache.saveChats([chat], instanceId: "instance-list", workspaceId: chat.workspaceId, writeToken: cache.reserveChatWrite()) + await cache.purge(instanceId: "instance-list") + let stale = await AidenChatCache(root: root).loadChats(instanceId: "instance-list", workspaceId: chat.workspaceId) + XCTAssertEqual(stale?.map(\.id), [chat.id], "The injected failed delete must leave disk evidence.") + let rejected = await cache.admittedWorkspaceChats(instanceId: "instance-list", workspaceId: chat.workspaceId) + XCTAssertNil(rejected) + var fresh = chat + fresh.title = "Fresh post-purge list" + try await cache.saveChats([fresh], instanceId: "instance-list", workspaceId: chat.workspaceId, writeToken: cache.reserveChatWrite()) + let admitted = await cache.admittedWorkspaceChats(instanceId: "instance-list", workspaceId: chat.workspaceId) + XCTAssertEqual(admitted?.map(\.title), [fresh.title]) + } + + @MainActor + func testWorkspaceHeldListAdoptsNewerDetailAndDeletionOwners() async throws { + for mode in ["detail", "omitted", "disk", "remove", "purge", "new-list"] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-workspace-list-owner-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var workspace: AidenWorkspaceChatsModel! + let detail = try await makeProgressLifecycleModel(mode: .denied, cache: cache, onCoordinator: { coordinator in + workspace = AidenWorkspaceChatsModel(coordinator: coordinator, workspaceId: "workspace-1", cache: cache) + }) + let instance = "instance-progress-lifecycle" + let old = detail.chat + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let data = try encoder.encode(["chats": mode == "omitted" ? [] : [old]]) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + request.url?.path.hasSuffix("/chats") == true ? (200, "application/json", data) : nil + } + let arrived = expectation(description: "workspace list held") + AidenChatProgressLifecycleURLProtocol.holdNextRequest(endingIn: "/chats") { arrived.fulfill() } + let loading = Task { await workspace.load() } + await fulfillment(of: [arrived], timeout: 2) + var winner = old + winner.title = "Settled title" + winner.messages.append(AidenChatMessage(id: "settled-list", role: .assistant, text: "Settled transcript", createdAt: Date())) + try await cache.saveChat(winner, instanceId: instance, writeToken: cache.reserveChatWrite()) + if mode == "remove" { await cache.removeChat(instanceId: instance, chatId: old.id) } + if mode == "purge" { await cache.purge(instanceId: instance) } + if mode == "new-list" { + try await cache.saveChats([], instanceId: instance, workspaceId: old.workspaceId, writeToken: cache.reserveChatWrite()) + } + if mode == "disk" { + let lists = root.appending(path: "lists") + try? FileManager.default.removeItem(at: lists) + try Data("blocked directory".utf8).write(to: lists) + } + AidenChatProgressLifecycleURLProtocol.releaseHeldRequest() + await loading.value + let removed = ["remove", "purge", "new-list"].contains(mode) + XCTAssertEqual(workspace.chats.map(\.title), removed ? [] : [winner.title]) + XCTAssertEqual(workspace.chats.first?.messages.last?.text, removed ? nil : "Settled transcript") + if mode != "disk" { + let reopened = await AidenChatCache(root: root).loadChats(instanceId: instance, workspaceId: old.workspaceId) + XCTAssertEqual(reopened?.map(\.title) ?? [], removed ? [] : [winner.title]) + } + } + } + + @MainActor + func testBotRequestOriginRejectsHeldGETAfterNewerOwnerIncludingDiskFailure() async throws { + for mode in ["newer", "disk", "remove", "purge"] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-bot-get-owner-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var coordinator: AidenRemoteCoordinator! + let detail = try await makeProgressLifecycleModel(mode: .denied, cache: cache, onCoordinator: { coordinator = $0 }) + var old = detail.chat + old.botId = "bot-test" + old.title = "Held old GET" + var newer = old + newer.title = "Newer settled owner" + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let oldData = try encoder.encode(old) + let newData = try encoder.encode(newer) + let context = try coordinator.requestContext() + let client = try coordinator.remoteClient(for: context) + let owner = AidenBotPresentationOwner() + let first = owner.begin(instanceID: context.instanceId, deviceID: context.deviceId, chatID: old.id, cache: cache) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in request.url?.path.hasSuffix("/chats/" + first.chatID) == true ? (200, "application/json", oldData) : nil } + let arrived = expectation(description: "old Bot GET held") + AidenChatProgressLifecycleURLProtocol.holdNextRequest(endingIn: "/chats/" + old.id) { arrived.fulfill() } + let oldID = old.id + let loading = Task { + let response = try await client.chat(id: oldID) + return await aidenPersistBotChatForPresentation(response, context: context, coordinator: coordinator, cache: cache, writeToken: first.writeToken) + } + await fulfillment(of: [arrived], timeout: 2) + let second = owner.begin(instanceID: context.instanceId, deviceID: context.deviceId, chatID: old.id, cache: cache) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in request.url?.path.hasSuffix("/chats/" + oldID) == true ? (200, "application/json", newData) : nil } + let settled = try await client.chat(id: old.id) + if mode == "disk" { + let chats = root.appending(path: "chats") + try? FileManager.default.removeItem(at: chats) + try Data("blocked directory".utf8).write(to: chats) + } + let accepted = await aidenPersistBotChatForPresentation(settled, context: context, coordinator: coordinator, cache: cache, writeToken: second.writeToken) + XCTAssertEqual(accepted?.title, newer.title) + if mode == "remove" { await cache.removeChat(instanceId: context.instanceId, chatId: old.id) } + if mode == "purge" { await cache.purge(instanceId: context.instanceId) } + AidenChatProgressLifecycleURLProtocol.releaseHeldRequest() + let result = try await loading.value + XCTAssertFalse(owner.owns(first)) + XCTAssertTrue(owner.owns(second)) + XCTAssertEqual(result?.title, ["remove", "purge"].contains(mode) ? nil : newer.title) + let memory = await cache.admittedChat(instanceId: context.instanceId, chatId: old.id) + XCTAssertEqual(memory?.title, result?.title) + if mode == "newer" { + let disk = await AidenChatCache(root: root).loadChat(instanceId: context.instanceId, chatId: old.id) + XCTAssertEqual(disk?.title, newer.title) + } + } + } + + @MainActor + func testBotPresentationAttemptCannotReturnAfterNavigationAwayAndBack() async { + let owner = AidenBotPresentationOwner() + let suite = "aiden-bot-owner-navigation-\(UUID())" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let navigation = AidenProductNavigationStore(defaults: defaults) + owner.setPath(["chat"], store: navigation, instanceID: "one", deviceID: "device") + let first = owner.begin(instanceID: "one", deviceID: "device", chatID: "chat") + let permissionGate = AidenChatWriteTestGate() + await permissionGate.arm() + let permission = Task { + await permissionGate.waitIfArmed() + return owner.owns(first) + } + await waitForChatWrite(permissionGate) + owner.setPath([], store: navigation, instanceID: "one", deviceID: "device") + owner.setPath(["chat"], store: navigation, instanceID: "one", deviceID: "device") + XCTAssertEqual(navigation.compactBotPath(for: "one"), ["chat"]) + let second = owner.begin(instanceID: "one", deviceID: "device", chatID: "chat") + await permissionGate.release() + let oldAllowed = await permission.value + XCTAssertFalse(oldAllowed) + XCTAssertTrue(owner.owns(second)) + owner.retain(instanceID: "two", deviceID: "device", chatID: "chat") + XCTAssertFalse(owner.owns(second)) + let third = owner.begin(instanceID: "two", deviceID: "new-device", chatID: "chat") + owner.retain(instanceID: "two", deviceID: "new-device", chatID: "chat") + XCTAssertTrue(owner.owns(third)) + owner.invalidate() + XCTAssertFalse(owner.owns(third)) + } + + @MainActor + func testHeldBotPermissionCannotOutliveWriteOrNoticePolicy() async { + for downgradeNotice in [false, true] { + let owner = AidenBotPresentationOwner() + let attempt = owner.begin(instanceID: "one", deviceID: "device", chatID: "chat", fullAccessAllowed: true) + var canWrite = true + var fullAccess = true + let gate = AidenChatWriteTestGate() + await gate.arm() + let resolving = Task { + await gate.waitIfArmed() + return owner.ownsPermission(attempt, canWrite: canWrite, fullAccessAllowed: fullAccess) + } + await waitForChatWrite(gate) + if downgradeNotice { fullAccess = false } + else { canWrite = false } + await gate.release() + let allowed = await resolving.value + XCTAssertFalse(allowed) + let refreshed = owner.begin(instanceID: "one", deviceID: "device", chatID: "chat", fullAccessAllowed: fullAccess) + XCTAssertEqual(owner.ownsPermission(refreshed, canWrite: canWrite, fullAccessAllowed: fullAccess), canWrite) + } + } + + @MainActor + func testRestorationAdoptsOnlyInFlightOpenUnderSamePolicy() { + let owner = AidenBotPresentationOwner() + func adopts(chat: String = "chat", device: String = "device", canWrite: Bool = true, fullAccess: Bool = false) -> Bool { + owner.adoptsRestoration(instanceID: "one", deviceID: device, chatID: chat, canWrite: canWrite, fullAccessAllowed: fullAccess) + } + // The open's own path change re-runs restoration mid-load. + let open = owner.begin(instanceID: "one", deviceID: "device", chatID: "chat", canWrite: true, fullAccessAllowed: false, adoptable: true) + XCTAssertTrue(adopts()) + XCTAssertTrue(owner.owns(open)) + XCTAssertFalse(adopts(chat: "other")) + XCTAssertFalse(adopts(device: "new-device")) + XCTAssertFalse(adopts(canWrite: false)) + XCTAssertFalse(adopts(fullAccess: true)) + // A settled open keeps ownership but later restoration inputs reload. + owner.finish(open) + XCTAssertTrue(owner.owns(open)) + XCTAssertFalse(adopts()) + // Restoration's own attempts are cancelled by SwiftUI, so never adopted. + let restoring = owner.begin(instanceID: "one", deviceID: "device", chatID: "chat", canWrite: true) + XCTAssertFalse(adopts()) + let reopened = owner.begin(instanceID: "one", deviceID: "device", chatID: "chat", canWrite: true, adoptable: true) + owner.finish(restoring) + XCTAssertTrue(adopts(), "finishing a superseded attempt cannot clear the current one") + XCTAssertTrue(owner.owns(reopened)) + owner.invalidate() + XCTAssertFalse(adopts()) + } + + @MainActor + func testRestorationRevalidationKeepsOnlySamePolicyLiveGrant() { + typealias Presentation = AidenBotPresentationOwner.Presentation + let chat = sampleChat() + for fullAccess in [false, true] { + let granted = Presentation.resolved(chat, allowsMutations: true, fullAccessAllowed: fullAccess) + let kept = granted.revalidating(canWrite: true, fullAccessAllowed: fullAccess) + XCTAssertTrue(kept.allowsMutations) + XCTAssertEqual(kept.revalidating(canWrite: true, fullAccessAllowed: fullAccess).allowsMutations, true) + XCTAssertFalse(granted.revalidating(canWrite: false, fullAccessAllowed: fullAccess).allowsMutations) + let noticeChanged = granted.revalidating(canWrite: true, fullAccessAllowed: !fullAccess) + XCTAssertFalse(noticeChanged.allowsMutations) + XCTAssertFalse(noticeChanged.revalidating(canWrite: true, fullAccessAllowed: fullAccess).allowsMutations, + "a revoked grant cannot come back without a fresh live check") + } + XCTAssertFalse(Presentation.resolved(chat, allowsMutations: false, fullAccessAllowed: false) + .revalidating(canWrite: true, fullAccessAllowed: false).allowsMutations) + XCTAssertFalse(Presentation.awaitingPermission(chat).revalidating(canWrite: true, fullAccessAllowed: false).allowsMutations) + // Grants that did not come from a live check (deep links) fail closed. + XCTAssertFalse(Presentation(chat: chat, allowsMutations: true).revalidating(canWrite: true, fullAccessAllowed: false).allowsMutations) + } + + @MainActor + func testHeldBotCreateReceiptAwaitsFreshPermission() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-bot-create-permission-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var coordinator: AidenRemoteCoordinator! + let detail = try await makeProgressLifecycleModel(mode: .denied, cache: cache, onCoordinator: { coordinator = $0 }) + var chat = detail.chat + chat.botId = "bot-test" + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let data = try encoder.encode(chat) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in request.httpMethod == "POST" ? (201, "application/json", data) : nil } + let context = try coordinator.requestContext() + let client = try coordinator.remoteClient(for: context) + let arrived = expectation(description: "Bot create POST held") + AidenChatProgressLifecycleURLProtocol.holdNextRequest(endingIn: "/bots/bot-test/chats") { arrived.fulfill() } + let creating = Task { + let response = try await client.createBotChat(botId: "bot-test", request: AidenBotChatCreateRequest(), idempotencyKey: UUID()) + let admitted = await aidenPersistBotChatForPresentation(response, context: context, coordinator: coordinator, cache: cache) + return admitted.map { AidenBotPresentationOwner.Presentation.awaitingPermission($0) } + } + await fulfillment(of: [arrived], timeout: 2) + // Even an accepted receipt cannot inherit the pre-request grant. Both + // grant and notice downgrades are exercised by the permission-owner test. + AidenChatProgressLifecycleURLProtocol.releaseHeldRequest() + let presentation = try await creating.value + XCTAssertEqual(presentation?.chat.id, chat.id) + XCTAssertEqual(presentation?.allowsMutations, false) + } + @MainActor private func waitForChatWrite(_ gate: AidenChatWriteTestGate) async { for _ in 0..<200 { @@ -3229,6 +3909,243 @@ final class AidenChatTests: XCTestCase { XCTAssertEqual(merged.first?.activity, .idle) } + @MainActor + func testHomePageCommitRetainsTwoQueuedEditsIncludingNewPageRow() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-home-postcommit-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var coordinator: AidenRemoteCoordinator! + let detail = try await makeProgressLifecycleModel(mode: .denied, cache: cache, onCoordinator: { coordinator = $0 }) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let initialData = try encoder.encode(["chats": [detail.chat]]) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + request.url?.path.hasSuffix("/chats") == true ? (200, "application/json", initialData) : nil + } + let home = AidenHomeModel(chatCache: cache) + await home.load(coordinator: coordinator) + let cursor = "cur_page_2." + String(repeating: "A", count: 43) + let initial = try AidenChatSummaryPage(summaries: home.chats, nextCursor: cursor) + home.acceptInitialChatSummaryPage(initial) + try await cache.saveChatSummaries(.init(summaries: initial.summaries, nextCursor: cursor), instanceId: "instance-progress-lifecycle", writeToken: cache.reserveChatWrite()) + var object = try XCTUnwrap(JSONSerialization.jsonObject(with: encoder.encode(detail.chat)) as? [String: Any]) + object["id"] = "page-tail" + var tail = try AidenRemoteJSONDecoder.decode(AidenChat.self, from: JSONSerialization.data(withJSONObject: object)) + tail.updatedAt = detail.chat.updatedAt.addingTimeInterval(-1) + let page = try AidenChatSummaryPage(summaries: [AidenChatSummary(chat: tail)], nextCursor: nil) + var updated = detail.chat + updated.title = "First local edit" + tail.title = "Second local edit" + var checks = 0 + try await home.acceptChatSummaryContinuation(page, requestedCursor: cursor, instanceId: "instance-progress-lifecycle", writeToken: cache.reserveSummaryWrite(instanceId: "instance-progress-lifecycle"), isCurrent: { + checks += 1 + if checks == 3 { + home.accept(updated) + home.accept(tail) + } + return true + }) + XCTAssertEqual(home.chats.map(\.title), [updated.title, tail.title]) + XCTAssertNil(home.nextChatCursor) + for _ in 0..<1_000 { + let current = await cache.loadChatSummaries(instanceId: "instance-progress-lifecycle") + if current?.summaries.map(\.title) == [updated.title, tail.title] { break } + await Task.yield() + } + let reopened = AidenChatCache(root: root) + let stored = await reopened.loadChatSummaries(instanceId: "instance-progress-lifecycle") + XCTAssertEqual(stored?.summaries.map(\.title), [updated.title, tail.title]) + XCTAssertNil(stored?.nextCursor) + } + + @MainActor + func testHomeRemovalOutranksRequestsReservedDuringCleanupAfterRestart() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-home-removal-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + let chat = sampleChat() + try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: chat)], nextCursor: nil), instanceId: "home-remove", writeToken: cache.reserveChatWrite()) + let gate = AidenChatWriteTestGate() + await gate.arm() + let lifetime = cache.registerLifetime(instanceId: "home-remove", chatId: chat.id) + lifetime.onRemovalCleanup = { await gate.waitIfArmed() } + let removal = Task { await cache.removeChat(instanceId: "home-remove", chatId: chat.id) } + await waitForChatWrite(gate) + _ = cache.reserveSummaryWrite(instanceId: "home-remove") // Request then fails without a response. + await gate.release() + await removal.value + let reopened = AidenChatCache(root: root) + let stored = await reopened.loadChatSummaries(instanceId: "home-remove") + XCTAssertFalse(stored?.summaries.contains(where: { $0.id == chat.id }) ?? false) + try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: chat)], nextCursor: nil), instanceId: "removal-seam", writeToken: cache.reserveChatWrite()) + try await cache.removeChatSummary(instanceId: "removal-seam", chatId: chat.id, beforeWrite: { + _ = cache.reserveSummaryWrite(instanceId: "removal-seam") + }) + let seamReopened = AidenChatCache(root: root) + let seamStored = await seamReopened.loadChatSummaries(instanceId: "removal-seam") + XCTAssertEqual(seamStored?.summaries, []) + } + + func testHomeAdmittedMemorySurvivesDiskFailureAndLocalPatchPreservesPage() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-home-memory-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var first = sampleChat() + first.title = "Initial" + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + var object = try XCTUnwrap(JSONSerialization.jsonObject(with: encoder.encode(first)) as? [String: Any]) + object["id"] = "page-tail" + var second = try AidenRemoteJSONDecoder.decode(AidenChat.self, from: JSONSerialization.data(withJSONObject: object)) + second.updatedAt = first.updatedAt.addingTimeInterval(-1) + let cursor = "cur_page_3." + String(repeating: "A", count: 43) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try Data("blocked".utf8).write(to: root.appending(path: "summaries")) + let accepted = try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: first), AidenChatSummary(chat: second)], nextCursor: cursor), instanceId: "home-memory", writeToken: cache.reserveSummaryWrite(instanceId: "home-memory")) + XCTAssertTrue(accepted) + first.title = "Local update" + try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: first)], nextCursor: nil), instanceId: "home-memory", writeToken: cache.reserveSummaryWrite(instanceId: "home-memory"), preservingCursor: true, changedIDs: [first.id]) + let snapshot = await cache.loadChatSummaries(instanceId: "home-memory") + XCTAssertEqual(snapshot?.summaries.map(\.id), [first.id, second.id]) + XCTAssertEqual(snapshot?.summaries.first?.title, first.title) + XCTAssertEqual(snapshot?.nextCursor, cursor) + let old = cache.reserveChatWrite() + _ = cache.reserveSummaryWrite(instanceId: "home-memory") + let rejected = try await cache.saveChatSummaries(.init(summaries: [], nextCursor: nil), instanceId: "home-memory", writeToken: old) + XCTAssertFalse(rejected) + let retained = await cache.loadChatSummaries(instanceId: "home-memory") + XCTAssertEqual(retained, snapshot) + let queuedFirst = cache.reserveSummaryWrite(instanceId: "home-memory") + var settled = first + settled.title = "Newer cross-owner settlement" + try await cache.saveChat(settled, instanceId: "home-memory", writeToken: cache.reserveChatWrite()) + let queuedSecond = cache.reserveSummaryWrite(instanceId: "home-memory") + second.title = "Latest local second row" + try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: first), AidenChatSummary(chat: second)], nextCursor: nil), instanceId: "home-memory", writeToken: queuedSecond, preservingCursor: true, changedIDs: [first.id, second.id], editTokens: [first.id: queuedFirst, second.id: queuedSecond]) + let combined = await cache.loadChatSummaries(instanceId: "home-memory") + XCTAssertEqual(combined?.summaries.map(\.title), [settled.title, second.title]) + try FileManager.default.removeItem(at: root.appending(path: "summaries")) + let activityToken = cache.reserveSummaryWrite(instanceId: "home-memory") + let active = AidenChatSummary(chat: settled, preservingActivity: .active) + second.title = "Unrelated detail settlement" + try await cache.saveChat(second, instanceId: "home-memory", writeToken: cache.reserveChatWrite()) + let laterLocal = cache.reserveSummaryWrite(instanceId: "home-memory") + try await cache.saveChatSummaries(.init(summaries: [active, AidenChatSummary(chat: second)], nextCursor: nil), instanceId: "home-memory", writeToken: laterLocal, preservingCursor: true, changedIDs: [first.id, second.id], editTokens: [first.id: activityToken, second.id: laterLocal]) + let unrelated = await cache.loadChatSummaries(instanceId: "home-memory") + XCTAssertEqual(unrelated?.summaries.first?.activity, .active) + XCTAssertEqual(unrelated?.summaries.last?.title, second.title) + let reopened = AidenChatCache(root: root) + let durable = await reopened.loadChatSummaries(instanceId: "home-memory") + XCTAssertEqual(durable, unrelated) + let renameOrigin = cache.reserveChatWrite() + try await cache.saveChat(settled, instanceId: "home-memory", writeToken: cache.reserveChatWrite()) + let queuedBeforeReceipt = cache.reserveSummaryWrite(instanceId: "home-memory") + let renameCutoff = cache.reserveChatWrite() + var receipt = settled + receipt.title = "Accepted unrelated rename" + let postReceiptActivity = cache.reserveSummaryWrite(instanceId: "home-memory") + try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: settled, preservingActivity: .active)], nextCursor: nil), instanceId: "home-memory", writeToken: postReceiptActivity, preservingCursor: true, changedIDs: [first.id], editTokens: [first.id: postReceiptActivity]) + _ = await cache.acceptRename(receipt, instanceId: "home-memory", origin: renameOrigin, cutoff: renameCutoff) + try await cache.saveChat(second, instanceId: "home-memory", writeToken: cache.reserveChatWrite()) + _ = await cache.reconcileWorkspaceChat(receipt, instanceId: "home-memory", authority: renameOrigin, cutoff: renameCutoff) + let renamed = await cache.loadChatSummaries(instanceId: "home-memory") + XCTAssertEqual(renamed?.summaries.first(where: { $0.id == first.id })?.title, receipt.title) + XCTAssertEqual(renamed?.summaries.first(where: { $0.id == first.id })?.activity, .active) + XCTAssertEqual(renamed?.summaries.first(where: { $0.id == second.id })?.title, second.title) + try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: settled, preservingActivity: .active)], nextCursor: nil), instanceId: "home-memory", writeToken: queuedBeforeReceipt, preservingCursor: true, changedIDs: [first.id], editTokens: [first.id: queuedBeforeReceipt]) + let renameReopened = AidenChatCache(root: root) + let retainedRename = await renameReopened.loadChatSummaries(instanceId: "home-memory") + XCTAssertEqual(retainedRename?.summaries.first(where: { $0.id == first.id })?.title, receipt.title) + XCTAssertEqual(retainedRename?.summaries.first(where: { $0.id == first.id })?.activity, renamed?.summaries.first(where: { $0.id == first.id })?.activity) + let laterActivity = cache.reserveSummaryWrite(instanceId: "home-memory") + try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: settled, preservingActivity: .idle)], nextCursor: nil), instanceId: "home-memory", writeToken: laterActivity, preservingCursor: true, changedIDs: [first.id], editTokens: [first.id: laterActivity], activityOnlyIDs: [first.id]) + let activityReopened = AidenChatCache(root: root) + let activityUpdated = await activityReopened.loadChatSummaries(instanceId: "home-memory") + XCTAssertEqual(activityUpdated?.summaries.first(where: { $0.id == first.id })?.title, receipt.title) + XCTAssertEqual(activityUpdated?.summaries.first(where: { $0.id == first.id })?.activity, .idle) + } + + @MainActor + func testHeldHomeHTTPResponseCannotReplaceSettlementOrNewerHomeOwner() async throws { + for mode in ["detail", "otherHome", "purge"] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-home-owner-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let cache = AidenChatCache(root: root) + var coordinator: AidenRemoteCoordinator! + let detail = try await makeProgressLifecycleModel(mode: .denied, cache: cache, onCoordinator: { coordinator = $0 }) + let home = AidenHomeModel(chatCache: cache) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let oldData = try encoder.encode(["chats": [detail.chat]]) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + request.url?.path.hasSuffix("/chats") == true ? (200, "application/json", oldData) : nil + } + let held = expectation(description: "Home HTTP held") + AidenChatProgressLifecycleURLProtocol.holdNextRequest(endingIn: "/chats", onRequest: { held.fulfill() }) + let loading = Task { await home.load(coordinator: coordinator) } + await fulfillment(of: [held], timeout: 2) + var winner = detail.chat + winner.title = "Current winner" + winner.revision = "winner-revision" + if mode == "detail" { + try await cache.saveChat(winner, instanceId: "instance-progress-lifecycle", writeToken: cache.reserveChatWrite()) + } else if mode == "otherHome" { + let newData = try encoder.encode(["chats": [winner]]) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + request.url?.path.hasSuffix("/chats") == true ? (200, "application/json", newData) : nil + } + let other = AidenHomeModel(chatCache: cache) + await other.load(coordinator: coordinator) + XCTAssertEqual(other.chats.first?.title, winner.title) + } else { + await cache.purge(instanceId: "instance-progress-lifecycle") + } + AidenChatProgressLifecycleURLProtocol.releaseHeldRequest() + await loading.value + XCTAssertFalse(home.chats.contains(where: { $0.title == detail.chat.title })) + let cached = await cache.loadChatSummaries(instanceId: "instance-progress-lifecycle") + if mode == "purge" { XCTAssertNil(cached) } + else { + XCTAssertEqual(home.chats.first?.title, winner.title) + XCTAssertEqual(cached?.summaries.first?.revision, winner.revision) + } + } + } + + @MainActor + func testHeldHomeContinuationRejectsNewerAuthorityWithoutAdvancingCursor() async throws { + for mode in ["detail", "request", "purge"] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-home-page-owner-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let gate = AidenChatWriteTestGate() + let cache = AidenChatCache(root: root, beforeMetadataWrite: { await gate.waitIfArmed() }) + let home = AidenHomeModel(chatCache: cache) + let chat = sampleChat() + let cursor = "cur_page_2." + String(repeating: "A", count: 43) + let initial = try AidenChatSummaryPage(summaries: [AidenChatSummary(chat: chat)], nextCursor: cursor) + home.acceptInitialChatSummaryPage(initial) + try await cache.saveChatSummaries(.init(summaries: initial.summaries, nextCursor: cursor), instanceId: "page-owner", writeToken: cache.reserveChatWrite()) + let page = try AidenChatSummaryPage(summaries: [], nextCursor: nil) + let token = cache.reserveSummaryWrite(instanceId: "page-owner") + await gate.arm() + let pending = Task { try await home.acceptChatSummaryContinuation(page, requestedCursor: cursor, instanceId: "page-owner", writeToken: token) } + await waitForChatWrite(gate) + if mode == "detail" { + var winner = chat + winner.title = "Settled title" + try await cache.saveChat(winner, instanceId: "page-owner", writeToken: cache.reserveChatWrite()) + } else if mode == "request" { + _ = cache.reserveSummaryWrite(instanceId: "page-owner") + } else { await cache.purge(instanceId: "page-owner") } + await gate.release() + do { try await pending.value; XCTFail("Stale page must reject") } catch {} + XCTAssertEqual(home.nextChatCursor, cursor) + XCTAssertEqual(home.chats, initial.summaries) + try await home.acceptChatSummaryContinuation(page, requestedCursor: cursor, instanceId: "page-owner", writeToken: cache.reserveSummaryWrite(instanceId: "page-owner")) + XCTAssertNil(home.nextChatCursor) + } + } + @MainActor func testHomePaginationRejectsDuplicateCursorStallAndOrderingRegression() async throws { let root = FileManager.default.temporaryDirectory @@ -6195,3 +7112,15 @@ private actor AidenChatWriteTestGate { continuation = nil } } + +private final class AidenFailedRemovalFileManager: FileManager, @unchecked Sendable { + override func removeItem(at URL: URL) throws { throw CocoaError(.fileWriteNoPermission) } +} + +private final class AidenRenameRequestLog: @unchecked Sendable { + private let lock = NSLock() + private var requests: [URLRequest] = [] + func record(_ request: URLRequest) { lock.lock(); defer { lock.unlock() }; requests.append(request) } + func count(_ method: String) -> Int { lock.lock(); defer { lock.unlock() }; return requests.filter { $0.httpMethod == method }.count } + func lastRevision() -> String? { lock.lock(); defer { lock.unlock() }; return requests.last { $0.httpMethod == "PATCH" }?.value(forHTTPHeaderField: "If-Match") } +} From aab1fce10a81733dbcba59c22d378671197ff0e4 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 26 Sep 2026 02:38:45 -0400 Subject: [PATCH 3/7] test(mobile): cover #217 x #218 run controls on iOS and Android Integration coverage for the merged stream-recovery and acknowledged run-control state machines: - iOS: removal while a stop, approval response or approval snapshot is held cannot report, restore a card or re-read; URLError(.cancelled) on stop/approval leaves the run live without optimistic cancel or card resurrection, and a second Stop may retry. - Android: unpair during a held stop or approval snapshot, and a dropped stop write that is not retried. #217 fixtures now encode the Mac wire shape (absent optionals omitted) so main's reasoning validator accepts them. (cherry picked from commit d41ad06c) Conflict resolution against #242: #242 already added the cancelledControls mode, its URLProtocol failure path and the load()-based mismatched-approval delivery, so those duplicates were dropped. The cancelled Stop test now follows #242's silent-cancellation rule (no "Stop was not confirmed"). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GAkZRgQzUoKWGpgupF3a4D --- .memory/mobile-stream-recovery.md | 10 ++ .papercuts/troubleshooting.md | 3 + .../sbtbiswas/AidenOnTheGo/AidenChatTest.kt | 54 +++++++- ios/AidenOnTheGoTests/AidenChatTests.swift | 131 ++++++++++++++++++ 4 files changed, 193 insertions(+), 5 deletions(-) diff --git a/.memory/mobile-stream-recovery.md b/.memory/mobile-stream-recovery.md index 5ad0d19812..8f1679b1cb 100644 --- a/.memory/mobile-stream-recovery.md +++ b/.memory/mobile-stream-recovery.md @@ -137,3 +137,13 @@ Stream restoration checks the local stream cache before draft I/O, releasing Sen Android's executed recovery regression initially timed out because the test serialized a forbidden `reasoning: null` key. Its fixture now omits absent fields; production validation stays unchanged. Validation and runtime limitations are recorded in the integration repair evidence document. No physical-device acceptance is claimed. Owner authorized simulator verification and policy update in PR #242. Full iPhone 17 / iOS 26.4.1 simulator XCTest run passed: 453 passed, six opt-in physical-device tests skipped, zero failures; all 160 chat tests passed. Runtime execution caught an additional pending-deletion overlay violation; applying `isChatWriteRetained` to overlay rows fixed it without weakening the existing regression. Final independent re-review clear. Evidence `/tmp/aiden-242-full-repair.xcresult` and integration repair document. + +## PR217 x PR218 integration (0.50.0) + +Merged origin/main (including #218 acknowledged run controls) into feature/mobile-stream-recovery with `--no-ff`; both safeguard sets kept. iOS `stop()`, `respondToApproval()` and `restorePendingApproval()` are #218's versions (canControlCurrentRun, isStopping/isRespondingToApproval, no optimistic cancel, no captured-card resurrection, snapshot generation/in-flight coalescing) with #217's removal fence added to every entry and post-await guard (`!isRemoved`). Android keeps #218 controls unchanged and #217's `hasActiveStream` Send gate; Detail screen uses `canStop = canControlCurrentRun && !isStopping`, `canSend = canSend && !hasActiveStream`. + +Main's private-field validator only allows `reasoning` on a chat that omits `botId`; Android #217 fixtures used `encodeDefaults` JSON that emitted `botId: null`/`reasoning: null`, so four stream-recovery/turn-receipt tests timed out. The Mac never emits `botId: null`; fixtures now use `explicitNulls = false` (`wireJson`). #218's `testMismatchedApprovalReceiptCannotReplaceNewerRequest` used a second `load()` to deliver the newer approval; #217 deliberately stops reopen from re-probing a live stream, so the test now delivers it through `restorePendingApproval`. + +New coverage: iOS removal during held stop / held approval response / held approval snapshot, and URLError(.cancelled) for stop and approval (5 XCTests). Android unpair during held stop, unpair during held approval snapshot, and dropped stop write with retryConnectionFailure=false (3 JVM tests; mutation-checked against the client-identity guards). + +Executed on 2026-09-26: Android `testDebugUnitTest` 206/206; iOS AidenChatTests on iPhone 17 Pro simulator (Xcode 27.1, serial) 174/183. The 9 failures are identical on pre-merge #217 head ccb64152 (154/163) and were never executed before (earlier notes say XCTest was compile-only): testAcceptedCreateSurvivesUnrelatedRowAndEmptyListUpdates, testBotRequestOriginRejectsHeldGETAfterNewerOwnerIncludingDiskFailure, testCancelledPreparationCannotClearTheNextSelectionsSendBlocker, testDeletionFencesMetadataWithAbsentFileOrRowAfterDetailReadmission, testDraftRestorationDoesNotResumeAfterAnAttachmentOnlySend, testPendingEraMetadataPreservesUnrelatedRowsAfterCleanupAndReadmission, testRenameCompanionReadsCanonicalAfterMetadataSuspension, testRenamePublishesNewerListRowInsteadOfOlderDetailReceipt, testSelectedAttachmentPreparationBlocksTextSendUntilItFinishes. Still open. diff --git a/.papercuts/troubleshooting.md b/.papercuts/troubleshooting.md index 8ee08a8eb8..f3f64df20e 100644 --- a/.papercuts/troubleshooting.md +++ b/.papercuts/troubleshooting.md @@ -1236,3 +1236,6 @@ because their native file-mutator test binary had not been built. Run - PR #128 merge (2026-09-26): main replaced the text Assistant dock with the Aiden Live orb, so the dock conflict resolved to main's side and the PR's dock hook usage and source-grep tests were dropped. The worktree guard rejects `npx playwright ... -g "a|b"` alternations; use a single-word `--grep`. - 2026-09-26 main merge: 15 `git.test.ts` managed-worktree removal tests fail locally with "could not safely remove the managed worktree quarantine"; this is the same host native-remover SDK issue above, not the PATH change. - 2026-09-26 PR #206 reconciliation: #207 on main superseded the runner-side four-note tail, so the merge took main's runner and kept only the projector gap (failed results with `summaryTruncated` lost the `report_truncated` notice because the gate predated failed summaries). + +- 2026-09-26 (PR217 integration): `xcodebuild test` on the iPhone 17 Pro simulator often hangs after the run in `simctl diagnose` or after a "failed to launch ... No such process" retry. Read results from the log (`Test Case ... failed`) and kill the hung `simctl diagnose`; reboot the simulator between runs. Run with `-parallel-testing-enabled NO` because clone devices fail to launch. +- 2026-09-26 (PR217 integration): the worktree guard rejects commands containing `$HOME` or compound git pipelines; pass `ANDROID_HOME` as an absolute path to `./gradlew`. diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt index df12b8a65f..812aaf1726 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenChatTest.kt @@ -57,6 +57,9 @@ class AidenChatTest { } private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true } + // Mac wire shape: absent optionals are omitted, never sent as null. A regular chat that + // carries `botId: null` beside `reasoning` is refused by the private-field validator. + private val wireJson = Json { ignoreUnknownKeys = true; encodeDefaults = true; explicitNulls = false } @Test fun chronologicalReasoningKeepsToolsAndProseInOrder() { @@ -264,7 +267,7 @@ class AidenChatTest { val count = postCount.incrementAndGet() if (count == 1) { arrived.countDown(); check(release.await(8, TimeUnit.SECONDS)) } if (count == 2 && mode == "ordered_posts") { secondPostArrived.countDown(); check(getRelease.await(8, TimeUnit.SECONDS)) } - MockResponse().setResponseCode(202).setBody("""{"turnId":"accepted-turn-$count","streamId":"accepted-stream-$count","status":"queued","message":${json.encodeToString(if (count == 1) accepted else second)}}""") + MockResponse().setResponseCode(202).setBody("""{"turnId":"accepted-turn-$count","streamId":"accepted-stream-$count","status":"queued","message":${wireJson.encodeToString(if (count == 1) accepted else second)}}""") } request.requestUrl!!.encodedPath.endsWith("/events") -> MockResponse().setSocketPolicy(okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE) request.requestUrl!!.encodedPath.endsWith("/chats/" + initial.id) -> { @@ -272,7 +275,7 @@ class AidenChatTest { if (mode.startsWith("inverse") && snapshot != initial) { getArrived.countDown(); check(getRelease.await(8, TimeUnit.SECONDS)) } - MockResponse().setBody(json.encodeToString(snapshot)) + MockResponse().setBody(wireJson.encodeToString(snapshot)) } else -> MockResponse().setResponseCode(404) } @@ -545,6 +548,15 @@ class AidenChatTest { @Test fun mismatchedStopAcknowledgementShowsFailure() = exerciseRunControl("stop-mismatch") + @Test + fun lateStopAcknowledgementAfterUnpairCannotControlOrReport() = exerciseRunControl("stop-revoked") + + @Test + fun droppedStopRequestIsNotRetriedAndLeavesRunControllable() = exerciseRunControl("stop-disconnect") + + @Test + fun approvalSnapshotHeldAcrossUnpairCannotRestoreCard() = exerciseRunControl("approval-snapshot-revoked") + @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) private fun exerciseRunControl(scenario: String) { val directory = kotlin.io.path.createTempDirectory("aiden-control-").toFile() @@ -580,7 +592,7 @@ class AidenChatTest { request.path == "/api/aiden/v1/streams/stream-control/approval" -> { if (failApprovalReads.get()) return MockResponse().setResponseCode(503) val id = snapshotId.get() - if ((scenario in listOf("approval-overlap", "approval-fallback-overlap") && id != "approval-current") || + if ((scenario in listOf("approval-overlap", "approval-fallback-overlap", "approval-snapshot-revoked") && id != "approval-current") || (scenario == "approval-fallback-before" && id == "approval-old")) { (if (id == "approval-old") oldRead else newRead).countDown() check((if (id == "approval-old") releaseOld else releaseNew).await(10, TimeUnit.SECONDS)) @@ -591,6 +603,9 @@ class AidenChatTest { writes.incrementAndGet() arrived.countDown() check(release.await(10, TimeUnit.SECONDS)) + if (scenario == "stop-disconnect") { + return MockResponse().setSocketPolicy(okhttp3.mockwebserver.SocketPolicy.DISCONNECT_AFTER_REQUEST) + } if (scenario.startsWith("stop-")) { val responseStatus = if (scenario == "stop-mismatch") status.replace("stream-control", "stream-other") else status.replace("waiting_for_approval", "reconciling") return MockResponse().setResponseCode(202).setBody(responseStatus) @@ -651,6 +666,22 @@ class AidenChatTest { assertEquals(AidenStreamState.WAITING_FOR_APPROVAL, model.streamState.value) return@runBlocking } + if (scenario == "approval-snapshot-revoked") { + // A snapshot read that was admitted before unpair must not paint a card + // for an installation whose credentials are gone. + snapshotId.set("approval-old") + val read = async { model.restorePendingApproval("stream-control") } + withContext(Dispatchers.IO) { assertTrue(oldRead.await(5, TimeUnit.SECONDS)) } + coordinator.removeInstallation(installation.id) + releaseOld.countDown() + read.await() + assertNotEquals("approval-old", model.pendingApproval.value?.id) + assertFalse(model.canControlCurrentRun) + model.respondToApproval(AidenApprovalDecision.ALLOW, "approval-old") + model.stop() + assertEquals(0, writes.get()) + return@runBlocking + } if (scenario == "approval-overlap") { snapshotId.set("approval-old") val old = async { model.restorePendingApproval("stream-control") } @@ -693,7 +724,7 @@ class AidenChatTest { } withContext(Dispatchers.IO) { assertTrue(arrived.await(5, TimeUnit.SECONDS)) } assertEquals(1, writes.get()) - if (scenario == "revoked") coordinator.removeInstallation(installation.id) + if (scenario == "revoked" || scenario == "stop-revoked") coordinator.removeInstallation(installation.id) if (scenario.endsWith("terminal")) { terminal.set(true) withTimeout(5_000) { model.streamState.first { it?.isTerminal == true } } @@ -702,9 +733,22 @@ class AidenChatTest { if (scenario.startsWith("stop")) { withTimeout(5_000) { model.isStopping.first { !it } } if (scenario.endsWith("terminal")) assertTrue(model.streamState.value!!.isTerminal) - else { + else if (scenario == "stop-revoked") { + // The late 202 belongs to a revoked client: no reconcile, no error, no controls. + assertNotEquals(AidenStreamState.RECONCILING, model.streamState.value) + assertNull(model.presentedError.value) + assertFalse(model.canControlCurrentRun) + model.stop() + assertFalse(model.isStopping.value) + } else { assertTrue(model.presentedError.value!!.contains("Stop was not confirmed")) assertFalse(model.streamState.value!!.isTerminal) + if (scenario == "stop-disconnect") { + // No optimistic cancel: the run stays live and the user may retry. + assertEquals(AidenStreamState.WAITING_FOR_APPROVAL, model.streamState.value) + assertEquals("approval-current", model.pendingApproval.value?.id) + assertTrue(model.canControlCurrentRun) + } } } else { withTimeout(5_000) { model.isRespondingToApproval.first { !it } } diff --git a/ios/AidenOnTheGoTests/AidenChatTests.swift b/ios/AidenOnTheGoTests/AidenChatTests.swift index 075167aa84..d5ad01430b 100644 --- a/ios/AidenOnTheGoTests/AidenChatTests.swift +++ b/ios/AidenOnTheGoTests/AidenChatTests.swift @@ -396,6 +396,133 @@ final class AidenChatTests: XCTestCase { try await exerciseControlResponse(stop: false, nextApproval: "approval-next", mode: .mismatchedApproval) } + // #217 x #218 integration: removal, stale snapshots and transport + // cancellation must not bypass the acknowledged-control safeguards. + + @MainActor + private func makeControlModel( + mode: AidenChatProgressLifecycleURLProtocol.Mode, + root: URL + ) async throws -> (AidenChatViewModel, AidenChatCache, AidenRemoteRequestContext) { + let cache = AidenChatCache(root: root) + var coordinator: AidenRemoteCoordinator! + let model = try await makeProgressLifecycleModel(mode: mode, cache: cache, onCoordinator: { coordinator = $0 }) + try await cache.saveActiveStream(.init(deviceId: "device-progress-lifecycle", streamId: "stream-control", turnId: "turn-control", lastSequence: 0), instanceId: "instance-progress-lifecycle", chatId: model.chat.id, chatWriteToken: cache.reserveChatWrite()) + await model.load(observeProgress: false) + XCTAssertEqual(model.pendingApproval?.id, "approval-current") + XCTAssertTrue(model.canControlCurrentRun) + return (model, cache, try coordinator.requestContext(for: "instance-progress-lifecycle")) + } + + @MainActor + func testRemovalWhileStopIsHeldSuppressesLateAcknowledgementAndControls() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-stop-removal-\(UUID())") + defer { try? FileManager.default.removeItem(at: root); AidenChatProgressLifecycleURLProtocol.reset() } + // A mismatched acknowledgement would normally surface "Stop was not confirmed". + let (model, cache, _) = try await makeControlModel(mode: .mismatchedStop, root: root) + // The fixture has no transcript route, so load may already show a read error. + let errorBeforeStop = model.presentedError + let arrived = expectation(description: "Stop held") + AidenChatProgressLifecycleURLProtocol.holdNextRequest(endingIn: "/cancel") { arrived.fulfill() } + let stopping = Task { await model.stop() } + await fulfillment(of: [arrived], timeout: 5) + XCTAssertTrue(model.isStopping) + await cache.removeChat(instanceId: "instance-progress-lifecycle", chatId: model.chat.id) + XCTAssertFalse(model.canControlCurrentRun) + AidenChatProgressLifecycleURLProtocol.releaseHeldRequest() + await stopping.value + XCTAssertFalse(model.isStopping) + XCTAssertEqual(model.presentedError, errorBeforeStop) + XCTAssertFalse(model.presentedError?.contains("Stop was not confirmed") == true) + XCTAssertNil(model.streamState) + XCTAssertNil(model.pendingApproval) + await model.stop() + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.controlWriteCount, 1) + let stream = await cache.loadActiveStream(instanceId: "instance-progress-lifecycle", chatId: model.chat.id) + XCTAssertNil(stream) + } + + @MainActor + func testRemovalWhileApprovalResponseIsHeldCannotRestoreOrRefreshCard() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-approval-removal-\(UUID())") + defer { try? FileManager.default.removeItem(at: root); AidenChatProgressLifecycleURLProtocol.reset() } + // A mismatched receipt would normally trigger a fallback approval read. + let (model, cache, _) = try await makeControlModel(mode: .mismatchedApproval, root: root) + let readsBefore = AidenChatProgressLifecycleURLProtocol.approvalReadCount + let errorBeforeResponse = model.presentedError + AidenChatProgressLifecycleURLProtocol.setApprovalID("approval-next") + let arrived = expectation(description: "Approval response held") + AidenChatProgressLifecycleURLProtocol.holdNextRequest(endingIn: "/respond") { arrived.fulfill() } + let responding = Task { await model.respondToApproval(.allow, approvalID: "approval-current") } + await fulfillment(of: [arrived], timeout: 5) + XCTAssertTrue(model.isRespondingToApproval) + await cache.removeChat(instanceId: "instance-progress-lifecycle", chatId: model.chat.id) + AidenChatProgressLifecycleURLProtocol.releaseHeldRequest() + await responding.value + XCTAssertFalse(model.isRespondingToApproval) + XCTAssertNil(model.pendingApproval) + XCTAssertEqual(model.presentedError, errorBeforeResponse) + XCTAssertFalse(model.presentedError?.contains("not confirmed") == true) + XCTAssertNil(model.streamState) + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.approvalReadCount, readsBefore) + await model.respondToApproval(.allow, approvalID: "approval-next") + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.controlWriteCount, 1) + } + + @MainActor + func testRemovalDiscardsHeldApprovalSnapshotAndRejectsNewReads() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-approval-snapshot-removal-\(UUID())") + defer { try? FileManager.default.removeItem(at: root); AidenChatProgressLifecycleURLProtocol.reset() } + let (model, cache, context) = try await makeControlModel(mode: .controls, root: root) + AidenChatProgressLifecycleURLProtocol.setApprovalID("approval-stale") + let arrived = expectation(description: "Approval snapshot held") + AidenChatProgressLifecycleURLProtocol.holdNextRequest(endingIn: "/approval") { arrived.fulfill() } + let reading = Task { await model.restorePendingApproval(streamID: "stream-control", context: context) } + await fulfillment(of: [arrived], timeout: 5) + await cache.removeChat(instanceId: "instance-progress-lifecycle", chatId: model.chat.id) + AidenChatProgressLifecycleURLProtocol.releaseHeldRequest() + await reading.value + XCTAssertNil(model.pendingApproval) + XCTAssertNil(model.streamState) + let readsAfterRemoval = AidenChatProgressLifecycleURLProtocol.approvalReadCount + await model.restorePendingApproval(streamID: "stream-control", context: context) + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.approvalReadCount, readsAfterRemoval) + XCTAssertNil(model.pendingApproval) + } + + @MainActor + func testCancelledStopRequestLeavesRunControllableWithoutOptimisticCancel() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-stop-cancelled-\(UUID())") + defer { try? FileManager.default.removeItem(at: root); AidenChatProgressLifecycleURLProtocol.reset() } + let (model, _, _) = try await makeControlModel(mode: .cancelledControls, root: root) + await model.stop() + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.controlWriteCount, 1) + // Neither the run nor its approval is presented as stopped before the Mac confirms. + XCTAssertEqual(model.streamState, .waitingForApproval) + XCTAssertEqual(model.pendingApproval?.id, "approval-current") + XCTAssertFalse(model.isStopping) + XCTAssertTrue(model.canControlCurrentRun) + // #242: a cancelled request is not a Mac refusal, so it stays silent. + XCTAssertFalse(model.presentedError?.contains("Stop was not confirmed") == true) + await model.stop() + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.controlWriteCount, 2) + } + + @MainActor + func testCancelledApprovalResponseRefreshesFromMacWithoutResurrectingCard() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-approval-cancelled-\(UUID())") + defer { try? FileManager.default.removeItem(at: root); AidenChatProgressLifecycleURLProtocol.reset() } + let (model, _, _) = try await makeControlModel(mode: .cancelledControls, root: root) + AidenChatProgressLifecycleURLProtocol.setApprovalID("approval-next") + await model.respondToApproval(.allow, approvalID: "approval-current") + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.controlWriteCount, 1) + XCTAssertFalse(model.isRespondingToApproval) + XCTAssertEqual(model.pendingApproval?.id, "approval-next") + XCTAssertEqual(model.streamState, .waitingForApproval) + await model.respondToApproval(.allow, approvalID: "approval-current") + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.controlWriteCount, 1) + } + @MainActor func testCancelledApprovalResponseCannotReplaceNewerRequest() async throws { try await exerciseControlResponse(stop: false, nextApproval: "approval-next", mode: .cancelledControls) @@ -5652,6 +5779,8 @@ private final class AidenChatProgressLifecycleURLProtocol: URLProtocol, @uncheck nonisolated(unsafe) private static var approvalID = "approval-current" nonisolated(unsafe) private static var approvalReadFails = false static func failApprovalReads() { lock.withLock { approvalReadFails = true } } + nonisolated(unsafe) private static var _approvalReadCount = 0 + static var approvalReadCount: Int { lock.withLock { _approvalReadCount } } static var controlWriteCount: Int { lock.withLock { _controlWriteCount } } static func setApprovalID(_ id: String) { lock.withLock { approvalID = id } } nonisolated(unsafe) private static var mode: Mode = .denied @@ -5704,6 +5833,7 @@ private final class AidenChatProgressLifecycleURLProtocol: URLProtocol, @uncheck approvalID = "approval-current" approvalReadFails = false responseOverride = nil + _approvalReadCount = 0 _progressRequestCount = 0 _agentRequestCount = 0 _turnRequestCount = 0 @@ -5753,6 +5883,7 @@ private final class AidenChatProgressLifecycleURLProtocol: URLProtocol, @uncheck shouldFinish = false result = Self.response(for: request, status: 200, contentType: "text/event-stream", data: Data(": keepalive\n\n".utf8)) case "/api/aiden/v1/streams/stream-control/approval": + Self.lock.withLock { Self._approvalReadCount += 1 } if Self.lock.withLock({ Self.approvalReadFails }) { client?.urlProtocol(self, didFailWithError: URLError(.networkConnectionLost)) return From 4ddbcbb512030bc3d7448a86fe196d252561565c Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 26 Sep 2026 04:44:20 -0400 Subject: [PATCH 4/7] fix(ios): resolve the 9 failing AidenChatTests on #217 Executed on the iPhone 17 Pro simulator for the first time, the stacked ownership changes exposed real interaction bugs with #217: - Workspace list merges pulled a removed chat's later detail-only re-admission into a list reserved before the removal. - Chat removal minted a fresh summary reservation and cleanup-era Home writes needed the full floor, so unrelated pending-era rows were lost. Removal keeps its deletion token; partial writes are row updates. Test-only corrections: whole-second dates for ISO 8601 round trips, create the cache root before blocking its chats directory, and assert that a fresh detail re-admission owns its Home row (#238 projection). (cherry picked from commit 37b5920a) Conflict resolution against #242: #242 already moved the cached-stream check ahead of draft I/O in load(), so that duplicate was dropped. Its committed-write ordering also admits an older create list's own row when the create's detail committed after the omitting list, so create() no longer needs the `!saveChats` fallback. admitCreatedWorkspaceChat stays for the superseded and failed-write create paths carried next. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GAkZRgQzUoKWGpgupF3a4D --- .memory/mobile-stream-recovery.md | 9 ++++ .papercuts/troubleshooting.md | 1 + .../Persistence/AidenChatCache.swift | 42 ++++++++++++++++++- ios/AidenOnTheGoTests/AidenChatTests.swift | 31 ++++++++++---- 4 files changed, 74 insertions(+), 9 deletions(-) diff --git a/.memory/mobile-stream-recovery.md b/.memory/mobile-stream-recovery.md index 8f1679b1cb..5d246012e7 100644 --- a/.memory/mobile-stream-recovery.md +++ b/.memory/mobile-stream-recovery.md @@ -147,3 +147,12 @@ Main's private-field validator only allows `reasoning` on a chat that omits `bot New coverage: iOS removal during held stop / held approval response / held approval snapshot, and URLError(.cancelled) for stop and approval (5 XCTests). Android unpair during held stop, unpair during held approval snapshot, and dropped stop write with retryConnectionFailure=false (3 JVM tests; mutation-checked against the client-identity guards). Executed on 2026-09-26: Android `testDebugUnitTest` 206/206; iOS AidenChatTests on iPhone 17 Pro simulator (Xcode 27.1, serial) 174/183. The 9 failures are identical on pre-merge #217 head ccb64152 (154/163) and were never executed before (earlier notes say XCTest was compile-only): testAcceptedCreateSurvivesUnrelatedRowAndEmptyListUpdates, testBotRequestOriginRejectsHeldGETAfterNewerOwnerIncludingDiskFailure, testCancelledPreparationCannotClearTheNextSelectionsSendBlocker, testDeletionFencesMetadataWithAbsentFileOrRowAfterDetailReadmission, testDraftRestorationDoesNotResumeAfterAnAttachmentOnlySend, testPendingEraMetadataPreservesUnrelatedRowsAfterCleanupAndReadmission, testRenameCompanionReadsCanonicalAfterMetadataSuspension, testRenamePublishesNewerListRowInsteadOfOlderDetailReceipt, testSelectedAttachmentPreparationBlocksTextSendUntilItFinishes. Still open. + +## PR217 executed-iOS failure fixes (2026-09-26) + +All 9 failures above are resolved; AidenChatTests 183/183 and the whole AidenOnTheGoTests target 483 executed (477 passed, 6 skipped, 0 failed) on the iPhone 17 Pro simulator, serial. Classification: +- Real bug, #217 `load()`: `isRestoringStream` blocked Send across the draft read even with nothing to recover. `load()` now resolves the cached stream reservation before the draft read and clears the blocker when there is no durable stream and no active stream (attachment preparation x2, draft restore). +- Real bug, create: an empty list admitted while create's detail write was held took a newer workspace token, so `persist()`'s `saveChats` was rejected and the durable list lost a chat memory still showed. New `AidenChatCache.admitCreatedWorkspaceChat` adds only that row (never advances the list token; removal/purge/newer detail owners win). +- Real bug, #234 merge x #217 removal: `mergingWorkspaceDetails` pulled a removed chat's later detail-only re-admission into a list reserved before the removal. It now requires `isChatWriteRetained(listToken, chat)`. +- Real bug, #238 x #217 pending-era Home: `removeChatSummary` ignored its `writeToken` and minted a fresh summary reservation, and a later detail projection advanced the full summary floor, so cleanup-era partial Home writes for unrelated rows were rejected. Removal uses its deletion token again (it still persists via `isRemoval`), and partial (cleanup-era) summary writes are admitted as row updates filtered by per-row authority. +- Wrong tests: two rename tests compared sub-second `Date()` against ISO 8601 (whole-second) wire/disk round trips; the bot disk-failure test wrote a blocking file into a cache root that no longer existed yet (created now). Deletion/pending-era tests expected no Home row after fresh detail re-admission, which predates #238's intended detail projection; they now assert the fresh row owns its title (stale write fenced). Delayed absent-snapshot Home write keeps the detail-created page's nil cursor. diff --git a/.papercuts/troubleshooting.md b/.papercuts/troubleshooting.md index f3f64df20e..fbf58e0357 100644 --- a/.papercuts/troubleshooting.md +++ b/.papercuts/troubleshooting.md @@ -1239,3 +1239,4 @@ because their native file-mutator test binary had not been built. Run - 2026-09-26 (PR217 integration): `xcodebuild test` on the iPhone 17 Pro simulator often hangs after the run in `simctl diagnose` or after a "failed to launch ... No such process" retry. Read results from the log (`Test Case ... failed`) and kill the hung `simctl diagnose`; reboot the simulator between runs. Run with `-parallel-testing-enabled NO` because clone devices fail to launch. - 2026-09-26 (PR217 integration): the worktree guard rejects commands containing `$HOME` or compound git pipelines; pass `ANDROID_HOME` as an absolute path to `./gradlew`. +- 2026-09-26 (PR217 iOS fixes): stacked ownership PRs (#233-#238) were only compiled, never executed, so their regressions against #217's cache tests surfaced only after the first simulator run. Run the scoped XCTests on a simulator before merging a stacked iOS cache change. A `test-without-building` run right after a killed run often fails with "failed to launch ... No such process"; rerunning once succeeds. diff --git a/ios/AidenOnTheGo/Persistence/AidenChatCache.swift b/ios/AidenOnTheGo/Persistence/AidenChatCache.swift index 4bd0913efe..d04f491ba2 100644 --- a/ios/AidenOnTheGo/Persistence/AidenChatCache.swift +++ b/ios/AidenOnTheGo/Persistence/AidenChatCache.swift @@ -379,6 +379,9 @@ actor AidenChatCache { for (id, chat) in admittedChats[instanceId] ?? [:] { guard chat.workspaceId == workspaceId, !chat.isBotChat, (chatWriteGenerations[instanceId]?[id] ?? 0) > writeToken, + // A list reserved before this chat's removal cannot carry + // its later detail-only re-admission into the list. + isChatWriteRetained(writeToken, instanceId: instanceId, chatId: id), !isChatHidden(instanceId: instanceId, chatId: id), let current = admittedChat(instanceId: instanceId, chatId: id) else { continue } byID[id] = current @@ -458,6 +461,30 @@ actor AidenChatCache { return true } + /// Keeps a successfully created chat in the durable workspace list when a + /// list admitted while the create's detail write was suspended omitted it. + /// The POST response is newer than any list that could not have seen it, + /// so only the created row is added; the list token is not advanced, and + /// removal, purge, and newer detail owners still win. + @discardableResult + func admitCreatedWorkspaceChat(chatId: String, instanceId: String, workspaceId: String, writeToken: UInt64) async -> Bool { + await beforeMetadataWrite?() + guard metadataWriteIsRetained(writeToken, instanceId: instanceId), + isChatWriteRetained(writeToken, instanceId: instanceId, chatId: chatId), + !isChatHidden(instanceId: instanceId, chatId: chatId), + chatWriteGenerations[instanceId]?[chatId] == writeToken, + var current = admittedChat(instanceId: instanceId, chatId: chatId), + current.workspaceId == workspaceId, !current.isBotChat else { return false } + current.localTitleOverride = nil + var rows = admittedWorkspaceChats(instanceId: instanceId, workspaceId: workspaceId) ?? [] + rows.removeAll { $0.id == chatId } + rows.append(current) + rows.sort { $0.updatedAt == $1.updatedAt ? $0.id < $1.id : $0.updatedAt > $1.updatedAt } + admittedWorkspaceLists[instanceId, default: [:]][workspaceId] = rows + try? save(ChatListEnvelope(instanceId: instanceId, workspaceId: workspaceId, chats: rows), to: fileURL(kind: "lists", instanceId, workspaceId)) + return true + } + @discardableResult func reconcileWorkspaceChat(_ chat: AidenChat, instanceId: String, authority: UInt64, cutoff: UInt64) async -> Bool { await beforeMetadataWrite?() @@ -701,7 +728,15 @@ actor AidenChatCache { var nextCursor = preservingCursor ? (loadChatSummaries(instanceId: instanceId).map(\.nextCursor) ?? snapshot.nextCursor) : snapshot.nextCursor let partial = metadataWriteIsPartial(writeToken, instanceId: instanceId) if partial { + // A cleanup-era page only upserts rows it still owns onto the + // current snapshot, so it is admitted as row updates: a newer + // detail projection of another row neither loses to it nor + // rejects its unrelated rows. let cached = loadChatSummaries(instanceId: instanceId) + if updatedRows == nil { + retained = retained.filter { writeToken >= summaryRowAuthority(instanceId: instanceId, chatId: $0.id) } + updatedRows = Dictionary(retained.map { ($0.id, writeToken) }, uniquingKeysWith: { first, _ in first }) + } retained = AidenChatSummaryPage.merged(current: cached?.summaries ?? [], appending: retained) if let cached { nextCursor = cached.nextCursor } } @@ -765,7 +800,12 @@ actor AidenChatCache { } func removeChatSummary(instanceId: String, chatId: String, writeToken: UInt64? = nil, beforeWrite: (@Sendable () -> Void)? = nil) throws { - let removalToken = reserveSummaryWrite(instanceId: instanceId) + // Chat removal keeps its deletion-origin authority: minting a later + // summary token would reject valid partial Home writes for unrelated + // rows reserved while cleanup was held. The removal itself persists + // regardless of newer reservations (isRemoval), and the removed row is + // already fenced from those writes by its per-chat removal floor. + let removalToken = writeToken ?? reserveSummaryWrite(instanceId: instanceId) guard let cached = loadChatSummaries(instanceId: instanceId, includingRemoved: true) else { return } let summaries = cached.summaries.filter { $0.id != chatId } guard summaries.count != cached.summaries.count else { return } diff --git a/ios/AidenOnTheGoTests/AidenChatTests.swift b/ios/AidenOnTheGoTests/AidenChatTests.swift index d5ad01430b..9e0a4e4720 100644 --- a/ios/AidenOnTheGoTests/AidenChatTests.swift +++ b/ios/AidenOnTheGoTests/AidenChatTests.swift @@ -1268,7 +1268,8 @@ final class AidenChatTests: XCTestCase { var newer = receipt newer.title = "Later list title" newer.revision = "newer-list-revision" - newer.messages.append(AidenChatMessage(id: "newer-list-reply", role: .assistant, text: "Keep list winner", createdAt: Date())) + // Whole seconds: the wire and cache encode ISO 8601 without fractions. + newer.messages.append(AidenChatMessage(id: "newer-list-reply", role: .assistant, text: "Keep list winner", createdAt: Date(timeIntervalSince1970: Date().timeIntervalSince1970.rounded(.down)))) let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 let receiptData = try encoder.encode(receipt) @@ -1458,7 +1459,8 @@ final class AidenChatTests: XCTestCase { await waitForChatWrite(gate) var final = receipt final.revision = "settled-during-metadata-await" - final.messages.append(AidenChatMessage(id: "metadata-final", role: .assistant, text: "Retain this final reply", createdAt: Date())) + // Whole seconds: the cache persists ISO 8601 dates without fractions. + final.messages.append(AidenChatMessage(id: "metadata-final", role: .assistant, text: "Retain this final reply", createdAt: Date(timeIntervalSince1970: Date().timeIntervalSince1970.rounded(.down)))) try await cache.saveFetchedChat(final, instanceId: "companion", writeToken: heldGet) await gate.release() await writing.value @@ -1687,6 +1689,9 @@ final class AidenChatTests: XCTestCase { let settled = try await client.chat(id: old.id) if mode == "disk" { let chats = root.appending(path: "chats") + // Nothing has been persisted yet, so create the cache root + // before replacing its chats directory with a blocking file. + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) try? FileManager.default.removeItem(at: chats) try Data("blocked directory".utf8).write(to: chats) } @@ -4811,7 +4816,11 @@ final class AidenChatTests: XCTestCase { let workspace = await reopened.loadChats(instanceId: instanceId, workspaceId: chat.workspaceId) let home = await reopened.loadChatSummaries(instanceId: instanceId) XCTAssertEqual(workspace?.map(\.id), existingRow ? [other.id] : nil) - XCTAssertEqual(home?.summaries.map(\.id), existingRow ? [other.id] : nil) + // The stale pre-deletion write stays fenced; the fresh detail + // re-admission owns its Home row under its newer token. + XCTAssertEqual(Set(home?.summaries.map(\.id) ?? []), Set(existingRow ? [other.id, chat.id] : [chat.id])) + XCTAssertEqual(home?.summaries.first(where: { $0.id == chat.id })?.title, fresh.title) + XCTAssertEqual(home?.summaries.first(where: { $0.id == other.id })?.title, existingRow ? other.title : nil) // Fresh metadata admission and another installation remain usable. try await cache.saveChats([fresh, other], instanceId: instanceId, workspaceId: chat.workspaceId, writeToken: cache.reserveChatWrite()) try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: fresh), AidenChatSummary(chat: other)], nextCursor: nil), instanceId: instanceId, writeToken: cache.reserveChatWrite()) @@ -4927,13 +4936,19 @@ final class AidenChatTests: XCTestCase { let reopened = AidenChatCache(root: root) if writer == "workspace" { let rows = await reopened.loadChats(instanceId: instance, workspaceId: chat.workspaceId) - XCTAssertEqual(Set(rows?.map(\.id) ?? []), Set(existing == "absent" ? [other.id] : [other.id, omitted.id])) - XCTAssertEqual(rows?.first(where: { $0.id == other.id })?.title, "Updated unrelated") + XCTAssertEqual(Set(rows?.map(\.id) ?? []), Set(existing == "absent" ? [other.id] : [other.id, omitted.id]), "\(existing)/\(writer)/\(delayed)") + XCTAssertEqual(rows?.first(where: { $0.id == other.id })?.title, "Updated unrelated", "\(existing)/\(writer)/\(delayed)") } else { let rows = await reopened.loadChatSummaries(instanceId: instance) - XCTAssertEqual(Set(rows?.summaries.map(\.id) ?? []), Set(existing == "absent" ? [other.id] : [other.id, omitted.id])) - XCTAssertEqual(rows?.summaries.first(where: { $0.id == other.id })?.title, "Updated unrelated") - XCTAssertEqual(rows?.nextCursor, existing == "absent" ? (writer == "home" ? incomingCursor : nil) : (existing == "cached-nil" ? nil : cachedCursor)) + // The fresh detail re-admission owns the removed chat's + // Home row; the pending-era write cannot touch it. + XCTAssertEqual(Set(rows?.summaries.map(\.id) ?? []), Set(existing == "absent" ? [other.id, chat.id] : [other.id, omitted.id, chat.id]), "\(existing)/\(writer)/\(delayed)") + XCTAssertEqual(rows?.summaries.first(where: { $0.id == chat.id })?.title, fresh.title, "\(existing)/\(writer)/\(delayed)") + XCTAssertEqual(rows?.summaries.first(where: { $0.id == other.id })?.title, "Updated unrelated", "\(existing)/\(writer)/\(delayed)") + // With no cached page the incoming cursor is retained, unless + // the delayed write lands after the fresh detail projection + // already created a cached page (whose cursor it keeps). + XCTAssertEqual(rows?.nextCursor, existing == "absent" ? (writer == "home" && !delayed ? incomingCursor : nil) : (existing == "cached-nil" ? nil : cachedCursor), "\(existing)/\(writer)/\(delayed)") } if writer == "home" { try await cache.saveChatSummaries(.init(summaries: [AidenChatSummary(chat: fresh)], nextCursor: freshCursor), instanceId: instance, generation: 1, writeToken: cache.reserveChatWrite()) From ed05a88be180ff9388bec48745eef1ee75bc296e Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 26 Sep 2026 06:02:27 -0400 Subject: [PATCH 5/7] fix(ios): superseded create/send read the admitted chat winner A superseded saveChat fell back to cache.loadChat, which reads disk only. saveChat admits the winner in memory before its file write, so a failed winner write left no file (row removed, stream startup aborted) or an older snapshot (rebase onto stale data). Both sites now use cache.admittedChat. Adds failed-write regression tests for both paths. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GAkZRgQzUoKWGpgupF3a4D (cherry picked from commit eb2dc82079af052b909f53c4c0aa899e3bb15580) --- .memory/mobile-stream-recovery.md | 4 + .../Features/Remote/AidenChatFeature.swift | 7 +- ios/AidenOnTheGoTests/AidenChatTests.swift | 115 ++++++++++++++++++ 3 files changed, 124 insertions(+), 2 deletions(-) diff --git a/.memory/mobile-stream-recovery.md b/.memory/mobile-stream-recovery.md index 5d246012e7..d1bc529e96 100644 --- a/.memory/mobile-stream-recovery.md +++ b/.memory/mobile-stream-recovery.md @@ -156,3 +156,7 @@ All 9 failures above are resolved; AidenChatTests 183/183 and the whole AidenOnT - Real bug, #234 merge x #217 removal: `mergingWorkspaceDetails` pulled a removed chat's later detail-only re-admission into a list reserved before the removal. It now requires `isChatWriteRetained(listToken, chat)`. - Real bug, #238 x #217 pending-era Home: `removeChatSummary` ignored its `writeToken` and minted a fresh summary reservation, and a later detail projection advanced the full summary floor, so cleanup-era partial Home writes for unrelated rows were rejected. Removal uses its deletion token again (it still persists via `isRemoval`), and partial (cleanup-era) summary writes are admitted as row updates filtered by per-row authority. - Wrong tests: two rename tests compared sub-second `Date()` against ISO 8601 (whole-second) wire/disk round trips; the bot disk-failure test wrote a blocking file into a cache root that no longer existed yet (created now). Deletion/pending-era tests expected no Home row after fresh detail re-admission, which predates #238's intended detail projection; they now assert the fresh row owns its title (stale write fenced). Delayed absent-snapshot Home write keeps the detail-created page's nil cursor. + +## Hermes P1 on adf25095: superseded paths read the admitted winner (2026-09-26) + +`AidenChatCache.saveChat` records the winner in `admittedChats`/`chatWriteGenerations` before its disk write, so a winner whose file write fails leaves memory authoritative and disk empty or stale. The superseded branches of `AidenWorkspaceChatsModel.persist()` and `AidenChatViewModel.send()`'s rebase used `cache.loadChat` (disk only), so they removed the created row or aborted stream startup (missing file) or rebased onto an older snapshot (stale file). Both now use `cache.admittedChat(instanceId:chatId:)` (nil on pending removal or non-retained token/purge; disk fallback only when nothing is admitted). `load()`'s cold display read still uses `loadChat`. A "held" winner disk write cannot interleave: admission and the save happen synchronously inside the actor after `beforeChatWrite`, so the tests fail the write instead ("missing": `chats` replaced by a file; "stale": older snapshot, then `chats` set to 0o555). New XCTests `testSupersededSendRebasesOnAdmittedWinnerWhenItsDiskWriteFails` and `testSupersededCreateKeepsAdmittedWinnerRowWhenItsDiskWriteFails` fail against `loadChat` in both modes; AidenChatTests 185/185 on the simulator, serial. diff --git a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift index e97fba0b9e..80d90a5ddd 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift @@ -885,7 +885,8 @@ final class AidenWorkspaceChatsModel { let writeToken = cache.reserveChatWrite() do { guard try await cache.saveChat(chat, instanceId: instanceId, writeToken: writeToken) else { - guard let current = await cache.loadChat(instanceId: instanceId, chatId: chat.id), + // The winner is admitted in memory even if its disk write failed. + guard let current = await cache.admittedChat(instanceId: instanceId, chatId: chat.id), current.workspaceId == workspaceId, !current.isBotChat else { if coordinator.isCurrent(context), generation == (presentationGenerations[chat.id] ?? 0) { presentationGenerations[chat.id, default: 0] &+= 1 @@ -1868,8 +1869,10 @@ final class AidenChatViewModel { // Rebase the receipt on the winning local snapshot. This // does not depend on another network read or resend POST. // Reserve before loading so removal/new writes still win. + // Read the admitted winner, not disk: its file write may + // have failed, leaving no file or an older snapshot. let retryToken = cache.reserveChatWrite() - guard var current = await cache.loadChat(instanceId: instanceId, chatId: chat.id), + guard var current = await cache.admittedChat(instanceId: instanceId, chatId: chat.id), !isRemoved, coordinator.isRetained(context) else { return } if !current.messages.contains(where: { $0.id == response.message.id }) { current.messages.append(response.message) diff --git a/ios/AidenOnTheGoTests/AidenChatTests.swift b/ios/AidenOnTheGoTests/AidenChatTests.swift index 9e0a4e4720..cad844c3b8 100644 --- a/ios/AidenOnTheGoTests/AidenChatTests.swift +++ b/ios/AidenOnTheGoTests/AidenChatTests.swift @@ -912,6 +912,121 @@ final class AidenChatTests: XCTestCase { model.stopProgressObservation() } + /// Makes the winner's chat file write fail after its memory admission: + /// "missing" leaves no readable file, "stale" leaves an older snapshot. + private func failWinnerDiskWrite(root: URL, mode: String) throws { + let chats = root.appending(path: "chats") + if mode == "missing" { + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try? FileManager.default.removeItem(at: chats) + try Data("blocked directory".utf8).write(to: chats) + } else { + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: chats.path(percentEncoded: false)) + } + } + + private func restoreChatsDirectory(root: URL) { + try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: root.appending(path: "chats").path(percentEncoded: false)) + } + + @MainActor + func testSupersededSendRebasesOnAdmittedWinnerWhenItsDiskWriteFails() async throws { + for mode in ["missing", "stale"] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-superseded-turn-io-\(UUID())") + defer { restoreChatsDirectory(root: root); try? FileManager.default.removeItem(at: root) } + let gate = AidenChatWriteTestGate() + let cache = AidenChatCache(root: root, beforeChatWrite: { await gate.waitIfArmed() }) + let model = try await makeProgressLifecycleModel(mode: .denied, cache: cache) + let fixture = AidenStreamRecoveryFixture(chat: model.chat) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + if request.url?.path.hasSuffix("/turns") == true { + return (202, "application/json", Data(#"{"turnId":"turn-recovery","streamId":"stream-recovery","status":"queued","message":{"id":"accepted-message","role":"user","text":"Hello","createdAt":"2026-09-22T00:00:00Z"}}"#.utf8)) + } + return fixture.response(request) + } + await model.load() + let instance = "instance-progress-lifecycle" + if mode == "stale" { + var older = model.chat + older.title = "Older disk snapshot" + try await cache.saveChat(older, instanceId: instance, writeToken: cache.reserveChatWrite()) + } + model.draft = "Hello" + XCTAssertTrue(model.canSend, mode) + await gate.arm() + let sending = Task { await model.send() } + await waitForChatWrite(gate) + try failWinnerDiskWrite(root: root, mode: mode) + var newer = model.chat + newer.title = "Newer snapshot" + do { + try await cache.saveChat(newer, instanceId: instance, writeToken: cache.reserveChatWrite()) + XCTFail("The winner's disk write must fail (\(mode))") + } catch {} + let disk = await cache.loadChat(instanceId: instance, chatId: model.chat.id) + XCTAssertEqual(disk?.title, mode == "stale" ? "Older disk snapshot" : nil, mode) + await gate.release() + await sending.value + let stream = await cache.loadActiveStream(instanceId: instance, chatId: model.chat.id) + XCTAssertEqual(stream?.streamId, "stream-recovery", mode) + let admitted = await cache.admittedChat(instanceId: instance, chatId: model.chat.id) + XCTAssertEqual(admitted?.title, "Newer snapshot", mode) + XCTAssertTrue(admitted?.messages.contains { $0.id == "accepted-message" } == true, mode) + XCTAssertTrue(model.chat.messages.contains { $0.id == "accepted-message" }, mode) + fixture.allowReconciliation = true + for _ in 0..<200 { + if await cache.loadActiveStream(instanceId: instance, chatId: model.chat.id) == nil { break } + try await Task.sleep(for: .milliseconds(10)) + } + model.stopProgressObservation() + } + } + + @MainActor + func testSupersededCreateKeepsAdmittedWinnerRowWhenItsDiskWriteFails() async throws { + for mode in ["missing", "stale"] { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-superseded-create-io-\(UUID())") + defer { restoreChatsDirectory(root: root); try? FileManager.default.removeItem(at: root) } + let gate = AidenChatWriteTestGate() + let cache = AidenChatCache(root: root, beforeChatWrite: { await gate.waitIfArmed() }) + var workspace: AidenWorkspaceChatsModel! + var publications: [AidenChat] = [] + var removals: [String] = [] + let detail = try await makeProgressLifecycleModel(mode: .denied, cache: cache, onCoordinator: { coordinator in + workspace = AidenWorkspaceChatsModel(coordinator: coordinator, workspaceId: "workspace-1", cache: cache, onChatUpdated: { publications.append($0) }, onChatRemoved: { removals.append($0) }) + }) + let instance = "instance-progress-lifecycle" + if mode == "stale" { + var older = detail.chat + older.title = "Older disk snapshot" + try await cache.saveChat(older, instanceId: instance, writeToken: cache.reserveChatWrite()) + } + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + let data = try encoder.encode(detail.chat) + AidenChatProgressLifecycleURLProtocol.setResponseOverride { request in + guard request.url?.path.hasSuffix("/chats") == true, request.httpMethod == "POST" else { return nil } + return (201, "application/json", data) + } + await gate.arm() + let creating = Task { await workspace.create() } + await waitForChatWrite(gate) + try failWinnerDiskWrite(root: root, mode: mode) + var newer = detail.chat + newer.title = "Newer snapshot" + do { + try await cache.saveChat(newer, instanceId: instance, writeToken: cache.reserveChatWrite()) + XCTFail("The winner's disk write must fail (\(mode))") + } catch {} + await gate.release() + let created = await creating.value + XCTAssertEqual(created?.title, newer.title, mode) + XCTAssertEqual(workspace.chats.first { $0.id == newer.id }?.title, newer.title, mode) + XCTAssertEqual(publications.map(\.title), [newer.title], mode) + XCTAssertEqual(removals, [], mode) + } + } + @MainActor func testAcceptedCreateSurvivesUnrelatedRowAndEmptyListUpdates() async throws { for refresh in [false, true] { From ec4f3bb18714b998bbc84f6ddeed99ba0c5c8f3d Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 26 Sep 2026 07:48:59 -0400 Subject: [PATCH 6/7] fix(ios): keep a superseded or failed create's row in the durable list After adopting the admitted winner, the superseded create branch (and the detail disk-failure branch) returned before any workspace-list write, so a failed detail write with a writable list cache lost the created row on an offline cold reopen. Both branches now call admitCreatedWorkspaceChat, which also accepts a newer detail winner only while that winner is newer than the list token, so later removal, purge and newer list omissions win. (cherry picked from commit 1ad6af1f) Adjusted for #242: the helper extends the admitted list rows themselves, not the merged memory view, so only the created chat (not other chats' memory-only detail winners) becomes a durable row. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GAkZRgQzUoKWGpgupF3a4D --- .memory/mobile-stream-recovery.md | 4 +++ .papercuts/troubleshooting.md | 1 + .../Features/Remote/AidenChatFeature.swift | 7 ++++- .../Persistence/AidenChatCache.swift | 9 ++++-- ios/AidenOnTheGoTests/AidenChatTests.swift | 31 ++++++++++++++----- 5 files changed, 42 insertions(+), 10 deletions(-) diff --git a/.memory/mobile-stream-recovery.md b/.memory/mobile-stream-recovery.md index d1bc529e96..4acb4cfffc 100644 --- a/.memory/mobile-stream-recovery.md +++ b/.memory/mobile-stream-recovery.md @@ -160,3 +160,7 @@ All 9 failures above are resolved; AidenChatTests 183/183 and the whole AidenOnT ## Hermes P1 on adf25095: superseded paths read the admitted winner (2026-09-26) `AidenChatCache.saveChat` records the winner in `admittedChats`/`chatWriteGenerations` before its disk write, so a winner whose file write fails leaves memory authoritative and disk empty or stale. The superseded branches of `AidenWorkspaceChatsModel.persist()` and `AidenChatViewModel.send()`'s rebase used `cache.loadChat` (disk only), so they removed the created row or aborted stream startup (missing file) or rebased onto an older snapshot (stale file). Both now use `cache.admittedChat(instanceId:chatId:)` (nil on pending removal or non-retained token/purge; disk fallback only when nothing is admitted). `load()`'s cold display read still uses `loadChat`. A "held" winner disk write cannot interleave: admission and the save happen synchronously inside the actor after `beforeChatWrite`, so the tests fail the write instead ("missing": `chats` replaced by a file; "stale": older snapshot, then `chats` set to 0o555). New XCTests `testSupersededSendRebasesOnAdmittedWinnerWhenItsDiskWriteFails` and `testSupersededCreateKeepsAdmittedWinnerRowWhenItsDiskWriteFails` fail against `loadChat` in both modes; AidenChatTests 185/185 on the simulator, serial. + +## Pullfrog on fd217a31: superseded/failed create keeps its durable list row (2026-09-26) + +After adopting the admitted winner, the superseded branch of `AidenWorkspaceChatsModel.persist()` returned before any workspace-list write, and the disk-failure `catch` branch did the same. If the detail file write failed but `lists/` was writable, an offline cold reopen lost the created row. Both branches now call `AidenChatCache.admitCreatedWorkspaceChat`. The helper previously required the create to own the detail (`generation == writeToken`); it now also accepts a newer detail winner only when that winner is newer than the current workspace list token, so a list admitted after the winner that omitted the chat still wins. Removal, purge, hidden and pending-removal checks are unchanged, and the list token is still not advanced. `testSupersededCreateKeepsAdmittedWinnerRowWhenItsDiskWriteFails` now reopens a fresh cache and covers the modes missing, stale, own (create's own detail write fails) and omitted (a newer empty list wins). diff --git a/.papercuts/troubleshooting.md b/.papercuts/troubleshooting.md index fbf58e0357..1b2be7e4a6 100644 --- a/.papercuts/troubleshooting.md +++ b/.papercuts/troubleshooting.md @@ -1240,3 +1240,4 @@ because their native file-mutator test binary had not been built. Run - 2026-09-26 (PR217 integration): `xcodebuild test` on the iPhone 17 Pro simulator often hangs after the run in `simctl diagnose` or after a "failed to launch ... No such process" retry. Read results from the log (`Test Case ... failed`) and kill the hung `simctl diagnose`; reboot the simulator between runs. Run with `-parallel-testing-enabled NO` because clone devices fail to launch. - 2026-09-26 (PR217 integration): the worktree guard rejects commands containing `$HOME` or compound git pipelines; pass `ANDROID_HOME` as an absolute path to `./gradlew`. - 2026-09-26 (PR217 iOS fixes): stacked ownership PRs (#233-#238) were only compiled, never executed, so their regressions against #217's cache tests surfaced only after the first simulator run. Run the scoped XCTests on a simulator before merging a stacked iOS cache change. A `test-without-building` run right after a killed run often fails with "failed to launch ... No such process"; rerunning once succeeds. +- 2026-09-26 (PR217 Pullfrog follow-up): from about 06:20, every `xcodebuild test-without-building` stalled before XCTest started, on two different simulators and after erasing the device and restarting CoreSimulatorService, testmanagerd and DTServiceHub. xcodebuild sat in `DVTiPhoneSimulator primaryInstrumentsServerWithError:` (ODR/GameKit setup), and the test host stayed suspended at `_dyld_start` (state `T`). `DevToolsSecurity -status` also hung, which points to a pending macOS authorization (Developer Tools access) prompt that someone has to answer at the machine. Check for that dialog first before killing more services. diff --git a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift index 80d90a5ddd..6d1b1eb29f 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift @@ -895,13 +895,18 @@ final class AidenWorkspaceChatsModel { } return nil } + // The winner may be detail-only (or its file write failed), so + // keep the created row in the durable list for a cold reopen. + await cache.admitCreatedWorkspaceChat(chatId: chat.id, instanceId: instanceId, workspaceId: workspaceId, writeToken: writeToken) guard generation == (presentationGenerations[chat.id] ?? 0) else { return chats.first { $0.id == chat.id } } upsert(current) return current } } catch { // Disk failure remains best-effort; a normal fence rejection above - // instead means another owner invalidated this snapshot. + // instead means another owner invalidated this snapshot. The detail + // was admitted in memory, so still keep its list row durable. + await cache.admitCreatedWorkspaceChat(chatId: chat.id, instanceId: instanceId, workspaceId: workspaceId, writeToken: writeToken) guard generation == (presentationGenerations[chat.id] ?? 0) else { return chats.first { $0.id == chat.id } } upsert(chat) return chat diff --git a/ios/AidenOnTheGo/Persistence/AidenChatCache.swift b/ios/AidenOnTheGo/Persistence/AidenChatCache.swift index d04f491ba2..b5f4e0e2ae 100644 --- a/ios/AidenOnTheGo/Persistence/AidenChatCache.swift +++ b/ios/AidenOnTheGo/Persistence/AidenChatCache.swift @@ -469,14 +469,19 @@ actor AidenChatCache { @discardableResult func admitCreatedWorkspaceChat(chatId: String, instanceId: String, workspaceId: String, writeToken: UInt64) async -> Bool { await beforeMetadataWrite?() + let owner = chatWriteGenerations[instanceId]?[chatId] ?? 0 guard metadataWriteIsRetained(writeToken, instanceId: instanceId), isChatWriteRetained(writeToken, instanceId: instanceId, chatId: chatId), !isChatHidden(instanceId: instanceId, chatId: chatId), - chatWriteGenerations[instanceId]?[chatId] == writeToken, + // The create owns the detail, or a newer detail winner superseded + // it and no list admitted after that winner omitted the chat. + owner == writeToken || (owner > writeToken && owner > (workspaceWriteTokens[instanceId]?[workspaceId] ?? 0)), var current = admittedChat(instanceId: instanceId, chatId: chatId), current.workspaceId == workspaceId, !current.isBotChat else { return false } current.localTitleOverride = nil - var rows = admittedWorkspaceChats(instanceId: instanceId, workspaceId: workspaceId) ?? [] + // Extend the admitted list itself (#242): other chats' memory-only + // detail winners must not become durable rows through this create. + var rows = admittedWorkspaceListRows(instanceId: instanceId, workspaceId: workspaceId) ?? [] rows.removeAll { $0.id == chatId } rows.append(current) rows.sort { $0.updatedAt == $1.updatedAt ? $0.id < $1.id : $0.updatedAt > $1.updatedAt } diff --git a/ios/AidenOnTheGoTests/AidenChatTests.swift b/ios/AidenOnTheGoTests/AidenChatTests.swift index cad844c3b8..e246606954 100644 --- a/ios/AidenOnTheGoTests/AidenChatTests.swift +++ b/ios/AidenOnTheGoTests/AidenChatTests.swift @@ -984,7 +984,9 @@ final class AidenChatTests: XCTestCase { @MainActor func testSupersededCreateKeepsAdmittedWinnerRowWhenItsDiskWriteFails() async throws { - for mode in ["missing", "stale"] { + // "own": the create's own detail write fails (no winner). + // "omitted": a list admitted after the winner omits the chat and wins. + for mode in ["missing", "stale", "own", "omitted"] { let root = FileManager.default.temporaryDirectory.appending(path: "aiden-superseded-create-io-\(UUID())") defer { restoreChatsDirectory(root: root); try? FileManager.default.removeItem(at: root) } let gate = AidenChatWriteTestGate() @@ -1011,19 +1013,34 @@ final class AidenChatTests: XCTestCase { await gate.arm() let creating = Task { await workspace.create() } await waitForChatWrite(gate) - try failWinnerDiskWrite(root: root, mode: mode) + try failWinnerDiskWrite(root: root, mode: mode == "stale" ? "stale" : "missing") var newer = detail.chat - newer.title = "Newer snapshot" - do { - try await cache.saveChat(newer, instanceId: instance, writeToken: cache.reserveChatWrite()) - XCTFail("The winner's disk write must fail (\(mode))") - } catch {} + if mode != "own" { + newer.title = "Newer snapshot" + do { + try await cache.saveChat(newer, instanceId: instance, writeToken: cache.reserveChatWrite()) + XCTFail("The winner's disk write must fail (\(mode))") + } catch {} + } + if mode == "omitted" { + let listed = try await cache.saveChats([], instanceId: instance, workspaceId: "workspace-1", writeToken: cache.reserveChatWrite()) + XCTAssertTrue(listed, mode) + } await gate.release() let created = await creating.value XCTAssertEqual(created?.title, newer.title, mode) XCTAssertEqual(workspace.chats.first { $0.id == newer.id }?.title, newer.title, mode) XCTAssertEqual(publications.map(\.title), [newer.title], mode) XCTAssertEqual(removals, [], mode) + // Offline cold reopen: the list cache stayed writable even though + // the detail file did not, so the created row must be durable. + let reopened = AidenChatCache(root: root) + let rows = await reopened.loadChats(instanceId: instance, workspaceId: "workspace-1") + if mode == "omitted" { + XCTAssertFalse(rows?.contains { $0.id == newer.id } == true, mode) + } else { + XCTAssertEqual(rows?.first { $0.id == newer.id }?.title, newer.title, mode) + } } } From 19f9fa4b1834f8bc39175fcd407b77961014a443 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 26 Sep 2026 08:02:47 -0400 Subject: [PATCH 7/7] docs(memory): record the #217 follow-up carry onto main Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GAkZRgQzUoKWGpgupF3a4D --- .memory/mobile-stream-recovery.md | 10 ++++++++++ .papercuts/troubleshooting.md | 1 + 2 files changed, 11 insertions(+) diff --git a/.memory/mobile-stream-recovery.md b/.memory/mobile-stream-recovery.md index 4acb4cfffc..949e79827c 100644 --- a/.memory/mobile-stream-recovery.md +++ b/.memory/mobile-stream-recovery.md @@ -164,3 +164,13 @@ All 9 failures above are resolved; AidenChatTests 183/183 and the whole AidenOnT ## Pullfrog on fd217a31: superseded/failed create keeps its durable list row (2026-09-26) After adopting the admitted winner, the superseded branch of `AidenWorkspaceChatsModel.persist()` returned before any workspace-list write, and the disk-failure `catch` branch did the same. If the detail file write failed but `lists/` was writable, an offline cold reopen lost the created row. Both branches now call `AidenChatCache.admitCreatedWorkspaceChat`. The helper previously required the create to own the detail (`generation == writeToken`); it now also accepts a newer detail winner only when that winner is newer than the current workspace list token, so a list admitted after the winner that omitted the chat still wins. Removal, purge, hidden and pending-removal checks are unchanged, and the list token is still not advanced. `testSupersededCreateKeepsAdmittedWinnerRowWhenItsDiskWriteFails` now reopens a fresh cache and covers the modes missing, stale, own (create's own detail write fails) and omitted (a newer empty list wins). + +## #217 follow-ups carried onto main (2026-09-26) + +Main's #242 (squash 7033118a) already contained #217 through 62fa352d. The remaining #217 commits were cherry-picked onto a fresh branch `feature/mobile-stream-recovery-followups` from origin/main a13605a7 instead of a reconciliation merge: 1a3cd3e6 (#225), ccb64152 (#233), d41ad06c, 37b5920a, eb2dc820, 1ad6af1f. 49f8d90d (papercuts only) did not apply cleanly and was skipped. + +Cache model after the merge: `saveChats` keeps #242's committed-write ordering (older lists are partial companions; rows come from `committedChatWrites`, read from disk; list token = max) and #233's in-memory list, rename-title and fetch authority, and returns `@discardableResult Bool`. The durable list extends only the last admitted rows (`admittedWorkspaceListRows`), never the merged memory view, so a detail whose disk write failed stays a memory-only winner on `admittedWorkspaceChats` and never becomes a durable row (#242 `testFailedDetailWriteDoesNotPromoteOlderDiskSnapshotIntoList`). `admitCreatedWorkspaceChat` is the one exception, for a server-accepted create whose own or superseding detail write failed; it also extends only the admitted rows. + +Dropped as duplicates of #242: 37b5920a's load() stream-before-draft reorder and the create() `!saveChats` fallback (#242's older-list rule admits the create's own committed row); d41ad06c's cancelledControls enum case, URLProtocol branch and restorePendingApproval delivery. The carried cancelled-Stop test now follows #242's silent-cancellation rule. + +Verified: iOS build-for-testing after every pick; Android testDebugUnitTest 206/206 and lint; test:ci-policy 45/45. Simulator XCTest pending (Mac authorization prompt). diff --git a/.papercuts/troubleshooting.md b/.papercuts/troubleshooting.md index 1b2be7e4a6..47adf95f11 100644 --- a/.papercuts/troubleshooting.md +++ b/.papercuts/troubleshooting.md @@ -1241,3 +1241,4 @@ because their native file-mutator test binary had not been built. Run - 2026-09-26 (PR217 integration): the worktree guard rejects commands containing `$HOME` or compound git pipelines; pass `ANDROID_HOME` as an absolute path to `./gradlew`. - 2026-09-26 (PR217 iOS fixes): stacked ownership PRs (#233-#238) were only compiled, never executed, so their regressions against #217's cache tests surfaced only after the first simulator run. Run the scoped XCTests on a simulator before merging a stacked iOS cache change. A `test-without-building` run right after a killed run often fails with "failed to launch ... No such process"; rerunning once succeeds. - 2026-09-26 (PR217 Pullfrog follow-up): from about 06:20, every `xcodebuild test-without-building` stalled before XCTest started, on two different simulators and after erasing the device and restarting CoreSimulatorService, testmanagerd and DTServiceHub. xcodebuild sat in `DVTiPhoneSimulator primaryInstrumentsServerWithError:` (ODR/GameKit setup), and the test host stayed suspended at `_dyld_start` (state `T`). `DevToolsSecurity -status` also hung, which points to a pending macOS authorization (Developer Tools access) prompt that someone has to answer at the machine. Check for that dialog first before killing more services. +- 2026-09-26 (#217 follow-ups): `./gradlew` fails with "Unable to locate a Java Runtime" in agent shells; pass `JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"` together with the absolute `ANDROID_HOME`.